answer
stringlengths 17
10.2M
|
|---|
package se.toxbee.sleepfighter.model;
import java.util.Arrays;
import java.util.Map;
import org.joda.time.DateTime;
import org.joda.time.DateTimeConstants;
import org.joda.time.MutableDateTime;
import se.toxbee.sleepfighter.model.audio.AudioConfig;
import se.toxbee.sleepfighter.model.audio.AudioSource;
import se.toxbee.sleepfighter.model.audio.AudioSourceType;
import se.toxbee.sleepfighter.model.challenge.ChallengeConfigSet;
import se.toxbee.sleepfighter.utils.message.Message;
import se.toxbee.sleepfighter.utils.message.MessageBus;
import se.toxbee.sleepfighter.utils.message.MessageBusHolder;
import se.toxbee.sleepfighter.utils.model.IdProvider;
import se.toxbee.sleepfighter.utils.string.StringUtils;
import android.provider.Settings;
import com.google.common.base.Objects;
import com.google.common.base.Preconditions;
import com.google.common.collect.Maps;
import com.google.common.primitives.Booleans;
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;
/**
* Alarm models the alarm settings and business logic for an alarm.
*
* Actual model fields are described in {@link Field}
*
* @version 1.0
* @since Sep 16, 2013
*/
@DatabaseTable(tableName = "alarm")
public class Alarm implements IdProvider, MessageBusHolder {
/**
* Enumeration of fields in an Alarm.
*
* @author Centril<twingoow@gmail.com> / Mazdak Farrokhzad.
* @version 1.0
* @since Sep 19, 2013
*/
public static enum Field {
ID, NAME,
TIME, MODE, ACTIVATED, ENABLED_DAYS,
AUDIO_SOURCE, AUDIO_CONFIG, SPEECH, FLASH
}
/**
* All events fired by {@link Alarm} extends this interface.
*
* @author Centril<twingoow@gmail.com> / Mazdak Farrokhzad.
* @version 1.0
* @since Sep 19, 2013
*/
public static interface AlarmEvent extends Message {
/**
* Returns the alarm that triggered the event.
*
* @return the alarm.
*/
public Alarm getAlarm();
/**
* Returns the Field that was modified in the alarm.
*
* @return the modified field.
*/
public Field getModifiedField();
/**
* Returns the old value.
*
* @return the old value.
*/
public Object getOldValue();
}
/**
* Base implementation of AlarmEvent
*
* @author Centril<twingoow@gmail.com> / Mazdak Farrokhzad.
* @version 1.0
* @since Sep 19, 2013
*/
public static class BaseAlarmEvent implements AlarmEvent {
private Field field;
private Alarm alarm;
private Object oldValue;
private BaseAlarmEvent(Alarm alarm, Field field, Object oldValue ) {
this.alarm = alarm;
this.field = field;
this.oldValue = oldValue;
}
public Alarm getAlarm() {
return this.alarm;
}
public Field getModifiedField() {
return this.field;
}
@Override
public Object getOldValue() {
return this.oldValue;
}
}
/**
* ScheduleChangeEvent occurs when a scheduling related constraint is modified, these are:<br/>
* <ul>
* <li>{@link Field#TIME}</li>
* <li>{@link Field#ACTIVATED}</li>
* <li>{@link Field#ENABLED_DAYS}</li>
* </ul>
*
* @author Centril<twingoow@gmail.com> / Mazdak Farrokhzad.
* @version 1.0
* @since Sep 19, 2013
*/
public static class ScheduleChangeEvent extends BaseAlarmEvent {
private ScheduleChangeEvent(Alarm alarm, Field field, Object oldValue ) {
super(alarm, field, oldValue);
}
}
/**
* MetaChangeEvent occurs when a name related constraint is modified, these are:<br/>
* <ul>
* <li>{@link Field#NAME}</li>
* <li>{@link Field#ID}</li>
* </ul>
*
* @author Centril<twingoow@gmail.com> / Mazdak Farrokhzad.
* @version 1.0
* @since Sep 19, 2013
*/
public static class MetaChangeEvent extends BaseAlarmEvent {
private MetaChangeEvent(Alarm alarm, Field field, Object oldValue ) {
super(alarm, field, oldValue);
}
}
/**
* AudioChangeEvent occurs when a audio related constraint is modified, these are:<br/>
* <ul>
* <li>{@link Field#AUDIO_SOURCE}</li>
* <li>{@link Field#AUDIO_CONFIG}</li>
* </ul>
*
*
* @author Centril<twingoow@gmail.com> / Mazdak Farrokhzad.
* @version 1.0
* @since Sep 27, 2013
*/
public static class AudioChangeEvent extends BaseAlarmEvent {
private AudioChangeEvent(Alarm alarm, Field field, Object oldValue ) {
super(alarm, field, oldValue);
}
}
@DatabaseField(generatedId = true)
private int id = NOT_COMMITTED_ID;
/** IDs for non-committed Alarms. */
public static final int NOT_COMMITTED_ID = -1;
@DatabaseField
private boolean isActivated;
@DatabaseField
private String name = UNNAMED;
/** The value for unnamed strings is {@value #UNNAMED} */
public static final String UNNAMED = null;
@DatabaseField
private AlarmTime time;
@DatabaseField
private AlarmMode mode;
/** The weekdays that this alarm can ring. */
@DatabaseField(width = 7)
private boolean[] enabledDays = { true, true, true, true, true, true, true };
private static final int MAX_WEEK_LENGTH = DateTimeConstants.DAYS_PER_WEEK;
private static final int MAX_WEEK_INDEX = MAX_WEEK_LENGTH - 1;
@DatabaseField
private int unnamedPlacement;
@DatabaseField
private boolean isFlash = false;
// whether this alarm is the preset alarm(the default alarm)
@DatabaseField
private boolean isPresetAlarm = false;
@DatabaseField(foreign = true, canBeNull = true)
private AudioSource audioSource = new AudioSource(AudioSourceType.RINGTONE,
Settings.System.DEFAULT_ALARM_ALERT_URI.toString());
@DatabaseField(foreign = true, canBeNull = false)
private AudioConfig audioConfig = new AudioConfig( 100, true );
@DatabaseField(foreign = true, canBeNull = false)
private SnoozeConfig snoozeConfig = new SnoozeConfig( true, 9 );
// the time and weather will be read out when the alarm goes off.
@DatabaseField
private boolean isSpeech = false;
/** The value {@link #getNextMillis()} returns when Alarm can't happen. */
public static final Long NEXT_NON_REAL = null;
@DatabaseField(foreign = true, canBeNull = false)
private ChallengeConfigSet challenges = new ChallengeConfigSet( true );
private MessageBus<Message> bus;
/**
* Constructs an alarm to current time.
*/
public Alarm() {
this( new AlarmTime( new DateTime() ) );
}
/**
* Constructs an alarm for given time.
*
* @param time the time.
*/
public Alarm( AlarmTime time ) {
this.time = time;
}
/**
* Copy constructor
*
* @param rhs the alarm to copy from.
*/
public Alarm( Alarm rhs ) {
// Reset id.
this.setId( NOT_COMMITTED_ID );
// Copy data.
this.time = new AlarmTime( rhs.time );
this.isActivated = rhs.isActivated;
this.enabledDays = rhs.enabledDays.clone();
this.name = rhs.name;
this.mode = rhs.mode;
this.unnamedPlacement = 0;
// Copy dependencies.
this.bus = rhs.bus;
this.audioSource = new AudioSource( rhs.audioSource );
this.audioConfig = new AudioConfig( rhs.audioConfig );
this.snoozeConfig = new SnoozeConfig( rhs.snoozeConfig );
this.challenges = new ChallengeConfigSet( rhs.challenges );
this.isSpeech = rhs.isSpeech;
this.isFlash = rhs.isFlash;
}
/**
* Sets the message bus, if not set, no events will be received.
*
* @param bus the buss that receives events.
*/
public void setMessageBus( MessageBus<Message> bus ) {
this.bus = bus;
// Pass it on!
this.challenges.setMessageBus( bus );
this.audioConfig.setMessageBus(bus);
this.snoozeConfig.setMessageBus(bus);
}
/**
* Returns the message bus, or null if not set.
*
* @return the message bus.
*/
public MessageBus<Message> getMessageBus() {
return this.bus;
}
/**
* Returns the ID of the alarm.
*
* @return the ID of the alarm.
*/
public int getId() {
return this.id;
}
/**
* Sets the ID of the alarm.<br/>
* Should only be used for testing.
*
* @param id the ID of the alarm.
*/
public void setId( int id ) {
if ( this.id == id ) {
return;
}
int old = this.id;
this.id = id;
this.publish( new MetaChangeEvent( this, Field.ID, old ) );
}
/**
* Returns the name of the Alarm.
*
* @return the name of the Alarm.
*/
public String getName() {
return name;
}
/**
* Sets the name of the Alarm.
*
* @param name the name of the Alarm to set.
*/
public void setName( String name ) {
if (this.name != null && this.name.equals(name)) {
return;
}
if ( name == null ) {
if ( this.name == null ) {
return;
}
throw new IllegalArgumentException( "A named Alarm can not be unnamed." );
}
String old = this.name;
this.name = name;
this.unnamedPlacement = 0;
this.publish( new MetaChangeEvent( this, Field.NAME, old ) );
}
/**
* Returns the time of the alarm (not timestamp, see {@link #getNextMillis(long)} for that...).
*
* @return the time.
*/
public AlarmTime getTime() {
return this.time;
}
/**
* Sets the time to the given time.<br/>
* For performance, the passed value is not cloned.
*
* @param time the time to set alarm to.
*/
public synchronized void setTime( AlarmTime time ) {
if ( Objects.equal( this.time, time ) ) {
return;
}
AlarmTime old = this.time;
this.time = time;
this.publish( new ScheduleChangeEvent( this, Field.TIME, old ) );
}
/**
* Returns the weekdays days this alarm is enabled for.<br/>
* For performance, a direct reference is returned.
*
* @return the weekdays alarm is enabled for.
*/
public synchronized boolean[] getEnabledDays() {
return this.enabledDays.clone();
}
/**
* Sets the weekdays this alarm is enabled for.<br/>
* For performance, the passed value is not cloned.
*
* @param enabledDays the weekdays alarm should be enabled for.
*/
public synchronized void setEnabledDays( boolean[] enabledDays ) {
Preconditions.checkNotNull( enabledDays );
if ( enabledDays.length != MAX_WEEK_LENGTH ) {
throw new IllegalArgumentException( "A week has 7 days, but an array with: " + enabledDays.length + " was passed" );
}
boolean[] old = this.enabledDays;
this.enabledDays = enabledDays.clone();
this.publish( new ScheduleChangeEvent( this, Field.ENABLED_DAYS, old ) );
}
/**
* Returns when this alarm will ring.<br/>
* If {@link #canHappen()} returns false, -1 will be returned.
*
* @param now the current time in unix epoch timestamp.
* @return the time in unix epoch timestamp when alarm will next ring.
*/
public synchronized Long getNextMillis(long now) {
if ( !this.canHappen() ) {
return NEXT_NON_REAL;
}
MutableDateTime next = this.getTime().forNow( now );
// Check if alarm was earlier today. If so, move to next day
if ( next.isBefore( now ) ) {
next.addDays( 1 );
}
// Offset for weekdays
int offset = 0;
// First weekday to check (0-6), getDayOfWeek returns (1-7)
int weekday = next.getDayOfWeek() - 1;
// Find the weekday the alarm should run, should at most run seven times
for ( int i = 0; i < 7; ++i ) {
// Wrap to first weekday
if ( weekday > MAX_WEEK_INDEX ) {
weekday = 0;
}
if ( this.enabledDays[weekday] ) {
// We've found the closest day the alarm is enabled for
offset = i;
break;
}
++weekday;
++offset;
}
if ( offset > 0 ) {
next.addDays( offset );
}
return next.getMillis();
}
/**
* Returns true if the alarm can ring in the future,<br/>
* that is: if {@link #isActivated()} and some weekday is enabled.
*
* @return true if the alarm can ring in the future.
*/
public synchronized boolean canHappen() {
if ( !this.isActivated() ) {
return false;
}
return Booleans.contains( this.enabledDays, true );
}
/**
* Sets whether or not the alarm should be active.
*
* @param isActivated whether or not the alarm should be active.
*/
public void setActivated( boolean isActivated ) {
if ( this.isActivated == isActivated ) {
return;
}
boolean old = this.isActivated;
this.isActivated = isActivated;
this.publish( new ScheduleChangeEvent( this, Field.ACTIVATED, old ) );
}
/**
* Returns true if the alarm is active.
*
* @return true if the alarm is active.
*/
public boolean isActivated() {
return this.isActivated;
}
/**
* Returns true if the alarm is unnamed = ({@link #getName()} == {@link #UNNAMED}.
*
* @return true if the alarm is unnamed.
*/
public boolean isUnnamed() {
return this.name == UNNAMED;
}
/**
* Returns the unnamed placement.<br/>
* The unnamed placement is a number that is set for Alarms that honor {@link #isUnnamed()}.<br/>
* It is a leaping number that is set upon addition to {@link AlarmList#add(int, Alarm)}.
*
* Let us assume that we have 3 alarms which all start out as unnamed.
* Their placements will be 1,2,3,4.
*
* When the second alarm is removed, or renamed to "Holidays",
* the 3rd alarm will not change its placement to 2.
*
* If then a 4th alarm is added, it will usurp the place that the 2nd alarm had,
* and its unnamed placement will be 2.
*/
public int getUnnamedPlacement() {
return this.unnamedPlacement;
}
public void setUnnamedPlacement( int placement ) {
if ( !this.isUnnamed() ) {
throw new IllegalArgumentException("Can't set numeric placement when alarm is already named.");
}
this.unnamedPlacement = placement;
}
@Override
public String toString() {
final Map<String, String> prop = Maps.newHashMap();
prop.put( "id", Integer.toString( this.getId() ) );
prop.put( "name", this.getName() );
prop.put( "time", this.getTime().getTimeString( false ) );
prop.put( "weekdays", Arrays.toString( this.enabledDays ) );
prop.put( "activated", Boolean.toString( this.isActivated() ) );
prop.put( "repeating", Boolean.toString( this.isRepeating() ) );
prop.put( "audio_source", this.getAudioSource() == null ? null : this.getAudioSource().toString() );
prop.put( "audio_config", this.getAudioConfig().toString() );
return "Alarm[" + StringUtils.PROPERTY_MAP_JOINER.join( prop ) + "]";
}
/**
* <p><code>{@link Alarm#hashCode()} == {@link Alarm#getId()}</code></p>
* {@inheritDoc}
*/
@Override
public int hashCode() {
return this.id;
}
/**
* <p>Two alarms are considered equal iff <code>{@link Alarm#hashCode()} == {@link Alarm#getId()}</code></p>
* {@inheritDoc}
*/
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
Alarm rhs = (Alarm) obj;
return this.id == rhs.id;
}
/**
* Sets the mode of the alarm, this specifies how {@link #getTime()} is understood.
*
* @param mode the mode to set.
*/
public void setMode( AlarmMode mode ) {
if ( this.mode == mode ) {
return;
}
AlarmMode old = this.mode;
this.mode = mode;
this.publish( new ScheduleChangeEvent( this, Field.MODE, old ) );
}
/**
* Returns the mode of the alarm.
*
* @return the mode.
*/
public AlarmMode getMode() {
return this.mode;
}
/**
* Sets if the alarm is repeating or not.
*
* @param isRepeating true if it is repeating.
*/
public void setRepeat( boolean isRepeating ) {
AlarmMode mode = isRepeating ? AlarmMode.REPEATING : AlarmMode.NORMAL;
this.setMode( mode );
}
/**
* Sets if the alarm is counting down or not.
*
* @param isCountdown true if it is counting down.
*/
public void setCountdown( boolean isCountdown ) {
AlarmMode mode = isCountdown ? AlarmMode.COUNTDOWN : AlarmMode.NORMAL;
this.setMode( mode );
}
/**
* Returns whether or not this alarm is repeating or not.
*
* @return true if it is repeating.
*/
public boolean isRepeating() {
return this.mode == AlarmMode.REPEATING;
}
/**
* Returns whether or not this alarm is counting down or not.
*
* @return true if it is counting down.
*/
public boolean isCountdown() {
return this.mode == AlarmMode.COUNTDOWN;
}
/**
* Sets if the alarm is flashing or not.
*
* @param isFlash true if it is flashing.
*/
public void setFlash( boolean isFlash ) {
if ( this.isFlash == isFlash ) {
return;
}
boolean old = this.isFlash;
this.isFlash = isFlash;
this.publish( new BaseAlarmEvent( this, Field.FLASH, old ) );
}
/**
* Returns whether or not this alarm is flashing or not.
*
* @return true if it is flashing.
*/
public boolean isFlashEnabled() {
return this.isFlash;
}
/**
* Returns whether or not speech is enabled.<br/>
* If true, then the time and weather will be read out when the alarm goes off.
*
* @return true if enabled.
*/
public boolean isSpeech() {
return this.isSpeech;
}
/**
* Sets whether or not speech is enabled.
*
* @param isSpeech true if enabled.
*/
public void setSpeech( boolean isSpeech ) {
if ( this.isSpeech == isSpeech ) {
return;
}
boolean old = this.isSpeech;
this.isSpeech = isSpeech;
this.publish( new BaseAlarmEvent( this, Field.SPEECH, old ) );
}
/**
* Sets the audio source for this alarm.
*
* @param source the audio source to set.
*/
public void setAudioSource( AudioSource source ) {
if ( this.audioSource == source ) {
return;
}
AudioSource old = this.audioSource;
this.audioSource = source;
this.publish( new AudioChangeEvent( this, Field.AUDIO_SOURCE, old ) );
}
/**
* Returns the audio source of this Alarm.
*
* @return the audio source.
*/
public AudioSource getAudioSource() {
return this.audioSource;
}
/**
* Returns the audio configuration for this alarm.
*
* @return the audio configuration.
*/
public AudioConfig getAudioConfig() {
return this.audioConfig;
}
/**
* Returns the snooze configuration for the alarm.
*
* @return the snooze configuration
*/
public SnoozeConfig getSnoozeConfig() {
return this.snoozeConfig;
}
/**
* Returns the ChallengeConfigSet for this alarm.<br/>
* Modifications may be done directly to the returned set<br/>
* as it is a well isolated module/unit.
*
* @return the ChallengeConfigSet object.
*/
public ChallengeConfigSet getChallengeSet() {
return this.challenges;
}
/**
* <p><strong>NOTE:</strong> this method is only intended for persistence purposes.<br/>
* This method is motivated and needed due to OrmLite not supporting results from joins.<br/>
* This is also a better method than reflection which is particularly expensive on android.</p>
*
* <p>Sets the {@link AudioConfig}, bypassing any and all checks, and does not send any event to bus.</p>
*
* @param config the {@link AudioConfig} to set.
*/
public void setFetched( AudioConfig config ) {
this.audioConfig = config;
}
/**
* <p><strong>NOTE:</strong> this method is only intended for persistence purposes.<br/>
* This method is motivated and needed due to OrmLite not supporting results from joins.<br/>
* This is also a better method than reflection which is particularly expensive on android.</p>
*
* <p>Sets the {@link AudioSource}, bypassing any and all checks, and does not send any event to bus.</p>
*
* @param source the {@link AudioSource} to set.
*/
public void setFetched( AudioSource source ) {
this.audioSource = source;
}
/**
* <p><strong>NOTE:</strong> this method is only intended for persistence purposes.<br/>
* This method is motivated and needed due to OrmLite not supporting results from joins.<br/>
* This is also a better method than reflection which is particularly expensive on android.</p>
*
* <p>Sets the {@link SnoozeConfig}, bypassing any and all checks, and does not send any event to bus.</p>
*
* @param source the {@link SnoozeConfig} to set.
*/
public void setFetched(SnoozeConfig config) {
this.snoozeConfig = config;
}
/**
* <p><strong>NOTE:</strong> this method is only intended for persistence purposes and factorization.<br/>
* This method is motivated and needed due to OrmLite not supporting results from joins.<br/>
* This is also a better method than reflection which is particularly expensive on android.</p>
*
* <p>Sets the {@link ChallengeConfigSet}, bypassing any and all checks, and does not send any event to bus.</p>
*
* @param challenges the {@link ChallengeConfigSet} to set.
*/
public void setChallenges( ChallengeConfigSet challenges ) {
this.challenges = challenges;
this.challenges.setMessageBus( this.getMessageBus() );
}
/**
* Sets whether or not this is a preset alarm.
*
* @param isPresetAlarm true if it is a preset alarm, otherwise false.
*/
public void setIsPresetAlarm( boolean isPresetAlarm ) {
this.isPresetAlarm = isPresetAlarm;
}
/**
* Returns whether or not this is a preset alarm.
*
* @return true if it is a preset alarm, otherwise false.
*/
public boolean isPresetAlarm() {
return this.isPresetAlarm;
}
/**
* Publishes an event to event bus.
*
* @param event the event to publish.
*/
private void publish( AlarmEvent event ) {
if ( this.bus == null ) {
return;
}
this.bus.publish( event );
}
}
|
package com.dmdirc.util.io;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.verify;
@SuppressWarnings("resource")
@RunWith(MockitoJUnitRunner.class)
public class StreamUtilsTest {
@Rule public ExpectedException thrown = ExpectedException.none();
@Mock private Closeable closeable;
@Test
public void testCloseWithNullStream() {
// Shouldn't throw an exception
StreamUtils.close(null);
}
@Test
public void testReadStream() throws Exception {
final InputStream inputStream = getClass().getResource("test5.txt").openStream();
StreamUtils.readStream(inputStream);
inputStream.close();
thrown.expect(IOException.class);
thrown.expectMessage("Stream closed");
final int result = inputStream.read();
assertEquals(-1, result);
}
@Test
public void testCloseWithIoException() throws IOException {
doThrow(new IOException("Oops")).when(closeable).close();
StreamUtils.close(closeable);
verify(closeable).close();
}
@Test
public void testCloseNormally() throws IOException {
StreamUtils.close(closeable);
verify(closeable).close();
}
}
|
package org.nuxeo.ecm.platform.jbpm.core.filter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.jbpm.JbpmContext;
import org.jbpm.graph.def.ProcessDefinition;
import org.nuxeo.ecm.core.api.DocumentModel;
import org.nuxeo.ecm.core.api.NuxeoPrincipal;
import org.nuxeo.ecm.platform.jbpm.JbpmListFilter;
import org.nuxeo.ecm.platform.jbpm.JbpmService;
import org.nuxeo.runtime.api.Framework;
/**
* @author arussel
*
*/
public class ConfigurableTypeFilter implements JbpmListFilter {
private static final long serialVersionUID = 1L;
public ConfigurableTypeFilter() {
}
@SuppressWarnings("unchecked")
public <T> ArrayList<T> filter(JbpmContext jbpmContext,
DocumentModel document, ArrayList<T> list, NuxeoPrincipal principal) {
JbpmService jbpmService = null;
try {
jbpmService = Framework.getService(JbpmService.class);
} catch (Exception e) {
throw new IllegalStateException("Jbpm Service is not deployed.", e);
}
Map<String, List<String>> filters = jbpmService.getTypeFilterConfiguration();
ArrayList<ProcessDefinition> pds = new ArrayList<ProcessDefinition>();
for (T t : list) {
ProcessDefinition definition = (ProcessDefinition) t;
List<String> allowedTypes = filters.get(definition.getName());
if(allowedTypes == null) {
continue;
}
if(allowedTypes.contains(document.getType())) {
pds.add(definition);
}
}
return (ArrayList<T>) pds;
}
}
|
package hudson.model;
import com.gargoylesoftware.htmlunit.WebAssert;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import org.jvnet.hudson.test.HudsonTestCase;
import hudson.Extension;
import hudson.model.JobTest.JobPropertyImpl.DescriptorImpl;
/**
* @author Kohsuke Kawaguchi
*/
public class JobTest extends HudsonTestCase {
@SuppressWarnings("unchecked")
public void testJobPropertySummaryIsShownInMainPage() throws Exception {
JobPropertyDescriptor.all().add(new DescriptorImpl());
AbstractProject project = createFreeStyleProject();
project.addProperty(new JobPropertyImpl("NeedleInPage"));
HtmlPage page = new WebClient().getPage(project);
WebAssert.assertTextPresent(page, "NeedleInPage");
}
@SuppressWarnings("unchecked")
public static class JobPropertyImpl extends JobProperty {
private final String testString;
public JobPropertyImpl(String testString) {
this.testString = testString;
}
public String getTestString() {
return testString;
}
public static final class DescriptorImpl extends JobPropertyDescriptor {
public String getDisplayName() {
return "";
}
}
}
}
|
package org.apereo.cas.config;
import org.apereo.cas.authentication.surrogate.SurrogateAuthenticationService;
import org.apereo.cas.bucket4j.consumer.BucketConsumer;
import org.apereo.cas.bucket4j.consumer.DefaultBucketConsumer;
import org.apereo.cas.bucket4j.producer.BucketStore;
import org.apereo.cas.bucket4j.producer.InMemoryBucketStore;
import org.apereo.cas.configuration.CasConfigurationProperties;
import org.apereo.cas.configuration.features.CasFeatureModule;
import org.apereo.cas.mfa.simple.CasSimpleMultifactorTokenCommunicationStrategy;
import org.apereo.cas.mfa.simple.ticket.CasSimpleMultifactorAuthenticationTicket;
import org.apereo.cas.mfa.simple.ticket.CasSimpleMultifactorAuthenticationTicketExpirationPolicyBuilder;
import org.apereo.cas.mfa.simple.ticket.CasSimpleMultifactorAuthenticationTicketFactory;
import org.apereo.cas.mfa.simple.ticket.CasSimpleMultifactorAuthenticationTicketImpl;
import org.apereo.cas.mfa.simple.ticket.CasSimpleMultifactorAuthenticationUniqueTicketIdGenerator;
import org.apereo.cas.mfa.simple.ticket.DefaultCasSimpleMultifactorAuthenticationTicketFactory;
import org.apereo.cas.mfa.simple.validation.CasSimpleMultifactorAuthenticationService;
import org.apereo.cas.mfa.simple.web.flow.CasSimpleMultifactorSendTokenAction;
import org.apereo.cas.mfa.simple.web.flow.CasSimpleMultifactorTrustedDeviceWebflowConfigurer;
import org.apereo.cas.mfa.simple.web.flow.CasSimpleMultifactorWebflowConfigurer;
import org.apereo.cas.notifications.CommunicationsManager;
import org.apereo.cas.ticket.ExpirationPolicyBuilder;
import org.apereo.cas.ticket.TicketFactoryExecutionPlanConfigurer;
import org.apereo.cas.ticket.UniqueTicketIdGenerator;
import org.apereo.cas.ticket.serialization.TicketSerializationExecutionPlanConfigurer;
import org.apereo.cas.trusted.config.MultifactorAuthnTrustConfiguration;
import org.apereo.cas.util.serialization.AbstractJacksonBackedStringSerializer;
import org.apereo.cas.util.spring.beans.BeanCondition;
import org.apereo.cas.util.spring.beans.BeanSupplier;
import org.apereo.cas.util.spring.boot.ConditionalOnFeatureEnabled;
import org.apereo.cas.web.flow.CasWebflowConfigurer;
import org.apereo.cas.web.flow.CasWebflowConstants;
import org.apereo.cas.web.flow.CasWebflowExecutionPlanConfigurer;
import org.apereo.cas.web.flow.actions.WebflowActionBeanSupplier;
import org.apereo.cas.web.flow.configurer.AbstractCasWebflowConfigurer;
import org.apereo.cas.web.flow.util.MultifactorAuthenticationWebflowUtils;
import lombok.val;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.core.Ordered;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.webflow.config.FlowDefinitionRegistryBuilder;
import org.springframework.webflow.definition.registry.FlowDefinitionRegistry;
import org.springframework.webflow.engine.builder.FlowBuilder;
import org.springframework.webflow.engine.builder.support.FlowBuilderServices;
import org.springframework.webflow.execution.Action;
import java.io.Serial;
/**
* This is {@link CasSimpleMultifactorAuthenticationConfiguration}.
*
* @author Misagh Moayyed
* @since 6.0.0
*/
@EnableConfigurationProperties(CasConfigurationProperties.class)
@EnableScheduling
@ConditionalOnFeatureEnabled(feature = CasFeatureModule.FeatureCatalog.SimpleMFA)
@AutoConfiguration
public class CasSimpleMultifactorAuthenticationConfiguration {
private static final int WEBFLOW_CONFIGURER_ORDER = 100;
private static final BeanCondition CONDITION_BUCKET4J_ENABLED = BeanCondition.on("cas.authn.mfa.simple.bucket4j.enabled").isTrue();
@Configuration(value = "CasSimpleMultifactorAuthenticationActionConfiguration", proxyBeanMethods = false)
@EnableConfigurationProperties(CasConfigurationProperties.class)
public static class CasSimpleMultifactorAuthenticationActionConfiguration {
@ConditionalOnMissingBean(name = CasWebflowConstants.ACTION_ID_MFA_SIMPLE_SEND_TOKEN)
@Bean
@RefreshScope(proxyMode = ScopedProxyMode.DEFAULT)
public Action mfaSimpleMultifactorSendTokenAction(
final ConfigurableApplicationContext applicationContext,
@Qualifier(CasSimpleMultifactorAuthenticationService.BEAN_NAME)
final CasSimpleMultifactorAuthenticationService casSimpleMultifactorAuthenticationService,
@Qualifier("mfaSimpleMultifactorTokenCommunicationStrategy")
final CasSimpleMultifactorTokenCommunicationStrategy mfaSimpleMultifactorTokenCommunicationStrategy,
final CasConfigurationProperties casProperties,
@Qualifier(CommunicationsManager.BEAN_NAME)
final CommunicationsManager communicationsManager,
@Qualifier("mfaSimpleMultifactorBucketConsumer")
final BucketConsumer mfaSimpleMultifactorBucketConsumer) {
return WebflowActionBeanSupplier.builder()
.withApplicationContext(applicationContext)
.withProperties(casProperties)
.withAction(() -> {
val simple = casProperties.getAuthn().getMfa().getSimple();
return new CasSimpleMultifactorSendTokenAction(
communicationsManager, casSimpleMultifactorAuthenticationService, simple,
mfaSimpleMultifactorTokenCommunicationStrategy,
mfaSimpleMultifactorBucketConsumer);
})
.withId(CasWebflowConstants.ACTION_ID_MFA_SIMPLE_SEND_TOKEN)
.build()
.get();
}
@ConditionalOnMissingBean(name = "mfaSimpleMultifactorBucketConsumer")
@Bean
@RefreshScope(proxyMode = ScopedProxyMode.DEFAULT)
public BucketConsumer mfaSimpleMultifactorBucketConsumer(
final ConfigurableApplicationContext applicationContext,
@Qualifier("mfaSimpleMultifactorBucketStore")
final BucketStore mfaSimpleMultifactorBucketStore,
final CasConfigurationProperties casProperties) {
return BeanSupplier.of(BucketConsumer.class)
.when(CONDITION_BUCKET4J_ENABLED.given(applicationContext.getEnvironment()))
.supply(() -> {
val simple = casProperties.getAuthn().getMfa().getSimple();
return new DefaultBucketConsumer(mfaSimpleMultifactorBucketStore, simple.getBucket4j());
})
.otherwise(BucketConsumer::permitAll)
.get();
}
@ConditionalOnMissingBean(name = "mfaSimpleMultifactorBucketStore")
@Bean
@RefreshScope(proxyMode = ScopedProxyMode.DEFAULT)
public BucketStore mfaSimpleMultifactorBucketStore(
final ConfigurableApplicationContext applicationContext,
final CasConfigurationProperties casProperties) {
return BeanSupplier.of(BucketStore.class)
.when(CONDITION_BUCKET4J_ENABLED.given(applicationContext.getEnvironment()))
.supply(() -> {
val simple = casProperties.getAuthn().getMfa().getSimple();
return new InMemoryBucketStore(simple.getBucket4j());
})
.otherwiseProxy()
.get();
}
}
@Configuration(value = "CasSimpleMultifactorAuthenticationPlanConfiguration", proxyBeanMethods = false)
@EnableConfigurationProperties(CasConfigurationProperties.class)
public static class CasSimpleMultifactorAuthenticationPlanConfiguration {
@Bean
@RefreshScope(proxyMode = ScopedProxyMode.DEFAULT)
@ConditionalOnMissingBean(name = "mfaSimpleCasWebflowExecutionPlanConfigurer")
public CasWebflowExecutionPlanConfigurer mfaSimpleCasWebflowExecutionPlanConfigurer(
@Qualifier("mfaSimpleMultifactorWebflowConfigurer")
final CasWebflowConfigurer mfaSimpleMultifactorWebflowConfigurer) {
return plan -> plan.registerWebflowConfigurer(mfaSimpleMultifactorWebflowConfigurer);
}
}
@Configuration(value = "CasSimpleMultifactorAuthenticationBaseConfiguration", proxyBeanMethods = false)
@EnableConfigurationProperties(CasConfigurationProperties.class)
public static class CasSimpleMultifactorAuthenticationBaseConfiguration {
@ConditionalOnMissingBean(name = "mfaSimpleMultifactorWebflowConfigurer")
@Bean
@RefreshScope(proxyMode = ScopedProxyMode.DEFAULT)
public CasWebflowConfigurer mfaSimpleMultifactorWebflowConfigurer(
@Qualifier("mfaSimpleAuthenticatorFlowRegistry")
final FlowDefinitionRegistry mfaSimpleAuthenticatorFlowRegistry,
@Qualifier(CasWebflowConstants.BEAN_NAME_LOGIN_FLOW_DEFINITION_REGISTRY)
final FlowDefinitionRegistry loginFlowRegistry,
@Qualifier(CasWebflowConstants.BEAN_NAME_FLOW_BUILDER_SERVICES)
final FlowBuilderServices flowBuilderServices,
final CasConfigurationProperties casProperties,
final ConfigurableApplicationContext applicationContext) {
val cfg = new CasSimpleMultifactorWebflowConfigurer(flowBuilderServices,
loginFlowRegistry,
mfaSimpleAuthenticatorFlowRegistry, applicationContext, casProperties,
MultifactorAuthenticationWebflowUtils.getMultifactorAuthenticationWebflowCustomizers(applicationContext));
cfg.setOrder(WEBFLOW_CONFIGURER_ORDER);
return cfg;
}
}
@Configuration(value = "CasSimpleMultifactorAuthenticationWebflowConfiguration", proxyBeanMethods = false)
@EnableConfigurationProperties(CasConfigurationProperties.class)
public static class CasSimpleMultifactorAuthenticationWebflowConfiguration {
@Bean
@RefreshScope(proxyMode = ScopedProxyMode.DEFAULT)
@ConditionalOnMissingBean(name = "mfaSimpleAuthenticatorFlowRegistry")
public FlowDefinitionRegistry mfaSimpleAuthenticatorFlowRegistry(
@Qualifier(CasWebflowConstants.BEAN_NAME_FLOW_BUILDER)
final FlowBuilder flowBuilder,
@Qualifier(CasWebflowConstants.BEAN_NAME_FLOW_BUILDER_SERVICES)
final FlowBuilderServices flowBuilderServices,
final ConfigurableApplicationContext applicationContext) {
val builder = new FlowDefinitionRegistryBuilder(applicationContext, flowBuilderServices);
builder.addFlowBuilder(flowBuilder, CasSimpleMultifactorWebflowConfigurer.MFA_SIMPLE_FLOW_ID);
return builder.build();
}
@ConditionalOnMissingBean(name = "mfaSimpleMultifactorTokenCommunicationStrategy")
@Bean
@RefreshScope(proxyMode = ScopedProxyMode.DEFAULT)
public CasSimpleMultifactorTokenCommunicationStrategy mfaSimpleMultifactorTokenCommunicationStrategy() {
return CasSimpleMultifactorTokenCommunicationStrategy.all();
}
}
@Configuration(value = "CasSimpleMultifactorAuthenticationTicketConfiguration", proxyBeanMethods = false)
@EnableConfigurationProperties(CasConfigurationProperties.class)
public static class CasSimpleMultifactorAuthenticationTicketConfiguration {
@ConditionalOnMissingBean(name = "casSimpleMultifactorAuthenticationTicketExpirationPolicy")
@Bean
@RefreshScope(proxyMode = ScopedProxyMode.DEFAULT)
public ExpirationPolicyBuilder casSimpleMultifactorAuthenticationTicketExpirationPolicy(final CasConfigurationProperties casProperties) {
return new CasSimpleMultifactorAuthenticationTicketExpirationPolicyBuilder(casProperties);
}
@ConditionalOnMissingBean(name = "casSimpleMultifactorAuthenticationUniqueTicketIdGenerator")
@Bean
@RefreshScope(proxyMode = ScopedProxyMode.DEFAULT)
public UniqueTicketIdGenerator casSimpleMultifactorAuthenticationUniqueTicketIdGenerator(final CasConfigurationProperties casProperties) {
val simple = casProperties.getAuthn().getMfa().getSimple().getToken().getCore();
return new CasSimpleMultifactorAuthenticationUniqueTicketIdGenerator(simple.getTokenLength());
}
}
@Configuration(value = "CasSimpleMultifactorAuthenticationTicketFactoryConfiguration", proxyBeanMethods = false)
@EnableConfigurationProperties(CasConfigurationProperties.class)
public static class CasSimpleMultifactorAuthenticationTicketFactoryConfiguration {
@ConditionalOnMissingBean(name = "casSimpleMultifactorAuthenticationTicketFactory")
@Bean
@RefreshScope(proxyMode = ScopedProxyMode.DEFAULT)
public CasSimpleMultifactorAuthenticationTicketFactory casSimpleMultifactorAuthenticationTicketFactory(
@Qualifier("casSimpleMultifactorAuthenticationUniqueTicketIdGenerator")
final UniqueTicketIdGenerator casSimpleMultifactorAuthenticationUniqueTicketIdGenerator,
@Qualifier("casSimpleMultifactorAuthenticationTicketExpirationPolicy")
final ExpirationPolicyBuilder casSimpleMultifactorAuthenticationTicketExpirationPolicy) {
return new DefaultCasSimpleMultifactorAuthenticationTicketFactory(
casSimpleMultifactorAuthenticationTicketExpirationPolicy,
casSimpleMultifactorAuthenticationUniqueTicketIdGenerator);
}
}
@Configuration(value = "CasSimpleMultifactorAuthenticationTicketSerializationConfiguration", proxyBeanMethods = false)
@EnableConfigurationProperties(CasConfigurationProperties.class)
public static class CasSimpleMultifactorAuthenticationTicketSerializationConfiguration {
@Bean
@RefreshScope(proxyMode = ScopedProxyMode.DEFAULT)
public TicketSerializationExecutionPlanConfigurer casSimpleMultifactorAuthenticationTicketSerializationExecutionPlanConfigurer() {
return plan -> {
plan.registerTicketSerializer(new CasSimpleMultifactorAuthenticationTicketStringSerializer());
plan.registerTicketSerializer(CasSimpleMultifactorAuthenticationTicket.class.getName(),
new CasSimpleMultifactorAuthenticationTicketStringSerializer());
};
}
private static class CasSimpleMultifactorAuthenticationTicketStringSerializer
extends AbstractJacksonBackedStringSerializer<CasSimpleMultifactorAuthenticationTicketImpl> {
@Serial
private static final long serialVersionUID = -2198623586274810263L;
@Override
public Class<CasSimpleMultifactorAuthenticationTicketImpl> getTypeToSerialize() {
return CasSimpleMultifactorAuthenticationTicketImpl.class;
}
}
}
@Configuration(value = "CasSimpleMultifactorAuthenticationTicketFactoryPlanConfiguration", proxyBeanMethods = false)
@EnableConfigurationProperties(CasConfigurationProperties.class)
public static class CasSimpleMultifactorAuthenticationTicketFactoryPlanConfiguration {
@ConditionalOnMissingBean(name = "casSimpleMultifactorAuthenticationTicketFactoryConfigurer")
@Bean
@RefreshScope(proxyMode = ScopedProxyMode.DEFAULT)
public TicketFactoryExecutionPlanConfigurer casSimpleMultifactorAuthenticationTicketFactoryConfigurer(
@Qualifier("casSimpleMultifactorAuthenticationTicketFactory")
final CasSimpleMultifactorAuthenticationTicketFactory casSimpleMultifactorAuthenticationTicketFactory) {
return () -> casSimpleMultifactorAuthenticationTicketFactory;
}
}
@ConditionalOnClass(MultifactorAuthnTrustConfiguration.class)
@Configuration(value = "CasSimpleMultifactorTrustConfiguration", proxyBeanMethods = false)
@DependsOn("casSimpleMultifactorAuthenticationTicketFactoryConfigurer")
public static class CasSimpleMultifactorTrustConfiguration {
@ConditionalOnMissingBean(name = "mfaSimpleMultifactorTrustWebflowConfigurer")
@Bean
@RefreshScope(proxyMode = ScopedProxyMode.DEFAULT)
public CasWebflowConfigurer mfaSimpleMultifactorTrustWebflowConfigurer(
@Qualifier("mfaSimpleAuthenticatorFlowRegistry")
final FlowDefinitionRegistry mfaSimpleAuthenticatorFlowRegistry,
@Qualifier(CasWebflowConstants.BEAN_NAME_LOGIN_FLOW_DEFINITION_REGISTRY)
final FlowDefinitionRegistry loginFlowDefinitionRegistry,
@Qualifier(CasWebflowConstants.BEAN_NAME_FLOW_BUILDER_SERVICES)
final FlowBuilderServices flowBuilderServices,
final CasConfigurationProperties casProperties,
final ConfigurableApplicationContext applicationContext) {
val cfg = new CasSimpleMultifactorTrustedDeviceWebflowConfigurer(flowBuilderServices,
loginFlowDefinitionRegistry,
mfaSimpleAuthenticatorFlowRegistry,
applicationContext, casProperties,
MultifactorAuthenticationWebflowUtils.getMultifactorAuthenticationWebflowCustomizers(applicationContext));
cfg.setOrder(WEBFLOW_CONFIGURER_ORDER + 1);
return cfg;
}
@ConditionalOnMissingBean(name = "casSimpleMultifactorTrustWebflowExecutionPlanConfigurer")
@Bean
@RefreshScope(proxyMode = ScopedProxyMode.DEFAULT)
public CasWebflowExecutionPlanConfigurer casSimpleMultifactorTrustWebflowExecutionPlanConfigurer(
@Qualifier("mfaSimpleMultifactorTrustWebflowConfigurer")
final CasWebflowConfigurer mfaSimpleMultifactorTrustWebflowConfigurer) {
return plan -> plan.registerWebflowConfigurer(mfaSimpleMultifactorTrustWebflowConfigurer);
}
}
@Configuration(value = "CasSimpleMultifactorSurrogateAuthenticationWebflowPlanConfiguration", proxyBeanMethods = false)
@EnableConfigurationProperties(CasConfigurationProperties.class)
@ConditionalOnClass(SurrogateAuthenticationService.class)
public static class CasSimpleMultifactorSurrogateAuthenticationWebflowPlanConfiguration {
@Bean
@ConditionalOnFeatureEnabled(feature = CasFeatureModule.FeatureCatalog.SurrogateAuthentication)
@RefreshScope(proxyMode = ScopedProxyMode.DEFAULT)
@ConditionalOnMissingBean(name = "surrogateCasSimpleMultifactorAuthenticationWebflowConfigurer")
public CasWebflowConfigurer surrogateCasSimpleMultifactorAuthenticationWebflowConfigurer(
@Qualifier(CasWebflowConstants.BEAN_NAME_FLOW_BUILDER_SERVICES)
final FlowBuilderServices flowBuilderServices,
@Qualifier(CasWebflowConstants.BEAN_NAME_LOGIN_FLOW_DEFINITION_REGISTRY)
final FlowDefinitionRegistry loginFlowDefinitionRegistry,
final CasConfigurationProperties casProperties,
final ConfigurableApplicationContext applicationContext) {
return new SurrogateWebflowConfigurer(flowBuilderServices,
loginFlowDefinitionRegistry, applicationContext, casProperties);
}
@Bean
@ConditionalOnMissingBean(name = "surrogateCasSimpleMultifactorAuthenticationWebflowExecutionPlanConfigurer")
@RefreshScope(proxyMode = ScopedProxyMode.DEFAULT)
public CasWebflowExecutionPlanConfigurer surrogateCasSimpleMultifactorAuthenticationWebflowExecutionPlanConfigurer(
@Qualifier("surrogateCasSimpleMultifactorAuthenticationWebflowConfigurer")
final CasWebflowConfigurer surrogateWebflowConfigurer) {
return plan -> plan.registerWebflowConfigurer(surrogateWebflowConfigurer);
}
private static class SurrogateWebflowConfigurer extends AbstractCasWebflowConfigurer {
SurrogateWebflowConfigurer(
final FlowBuilderServices flowBuilderServices,
final FlowDefinitionRegistry mainFlowDefinitionRegistry,
final ConfigurableApplicationContext applicationContext,
final CasConfigurationProperties casProperties) {
super(flowBuilderServices, mainFlowDefinitionRegistry, applicationContext, casProperties);
setOrder(Ordered.LOWEST_PRECEDENCE);
}
@Override
protected void doInitialize() {
val mfaState = getState(getLoginFlow(), CasSimpleMultifactorWebflowConfigurer.MFA_SIMPLE_FLOW_ID);
createTransitionForState(mfaState, CasWebflowConstants.TRANSITION_ID_SUCCESS,
CasWebflowConstants.STATE_ID_LOAD_SURROGATES_ACTION, true);
}
}
}
}
|
package org.eclipse.birt.report.item.crosstab.core.re;
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.eclipse.birt.core.data.ExpressionUtil;
import org.eclipse.birt.core.exception.BirtException;
import org.eclipse.birt.data.engine.api.IDataQueryDefinition;
import org.eclipse.birt.report.engine.extension.ReportItemQueryBase;
import org.eclipse.birt.report.item.crosstab.core.CrosstabException;
import org.eclipse.birt.report.item.crosstab.core.ICrosstabConstants;
import org.eclipse.birt.report.item.crosstab.core.de.CrosstabCellHandle;
import org.eclipse.birt.report.item.crosstab.core.de.CrosstabReportItemHandle;
import org.eclipse.birt.report.item.crosstab.core.de.DimensionViewHandle;
import org.eclipse.birt.report.item.crosstab.core.de.LevelViewHandle;
import org.eclipse.birt.report.item.crosstab.core.de.MeasureViewHandle;
import org.eclipse.birt.report.item.crosstab.core.i18n.Messages;
import org.eclipse.birt.report.model.api.DataItemHandle;
import org.eclipse.birt.report.model.api.ExtendedItemHandle;
import org.eclipse.birt.report.model.api.PropertyHandle;
import org.eclipse.birt.report.model.api.ReportElementHandle;
import org.eclipse.birt.report.model.api.StructureFactory;
import org.eclipse.birt.report.model.api.StyleHandle;
import org.eclipse.birt.report.model.api.activity.SemanticException;
import org.eclipse.birt.report.model.api.elements.DesignChoiceConstants;
import org.eclipse.birt.report.model.api.elements.structures.MapRule;
import org.eclipse.birt.report.model.api.extension.ExtendedElementException;
/**
* CrosstabReportItemQuery
*/
public class CrosstabReportItemQuery extends ReportItemQueryBase implements
ICrosstabConstants
{
private static Logger logger = Logger.getLogger( CrosstabReportItemQuery.class.getName( ) );
private CrosstabReportItemHandle crosstabItem;
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.extension.ReportItemQueryBase#setModelObject(org.eclipse.birt.report.model.api.ExtendedItemHandle)
*/
public void setModelObject( ExtendedItemHandle modelHandle )
{
super.setModelObject( modelHandle );
try
{
crosstabItem = (CrosstabReportItemHandle) modelHandle.getReportItem( );
}
catch ( ExtendedElementException e )
{
logger.log( Level.SEVERE,
Messages.getString( "CrosstabReportItemQuery.error.crosstab.loading" ) ); //$NON-NLS-1$
crosstabItem = null;
}
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.extension.ReportItemQueryBase#createReportQueries(org.eclipse.birt.data.engine.api.IDataQueryDefinition)
*/
public IDataQueryDefinition[] createReportQueries(
IDataQueryDefinition parent ) throws BirtException
{
if ( crosstabItem == null )
{
throw new CrosstabException( modelHandle == null ? null
: modelHandle.getElement( ),
Messages.getString( "CrosstabReportItemQuery.error.query.building" ) ); //$NON-NLS-1$
}
IDataQueryDefinition cubeQuery = CrosstabQueryHelper.buildQuery( crosstabItem,
parent );
String emptyValue = crosstabItem.getEmptyCellValue( );
// build child element query
if ( context != null )
{
// process measure
for ( int i = 0; i < crosstabItem.getMeasureCount( ); i++ )
{
// TODO check visibility?
MeasureViewHandle mv = crosstabItem.getMeasure( i );
processChildQuery( cubeQuery, mv.getCell( ), emptyValue );
processChildQuery( cubeQuery, mv.getHeader( ), emptyValue );
for ( int j = 0; j < mv.getAggregationCount( ); j++ )
{
processChildQuery( cubeQuery,
mv.getAggregationCell( j ),
emptyValue );
}
}
// process row edge
if ( crosstabItem.getDimensionCount( ROW_AXIS_TYPE ) > 0 )
{
// TODO check visibility?
for ( int i = 0; i < crosstabItem.getDimensionCount( ROW_AXIS_TYPE ); i++ )
{
DimensionViewHandle dv = crosstabItem.getDimension( ROW_AXIS_TYPE,
i );
for ( int j = 0; j < dv.getLevelCount( ); j++ )
{
LevelViewHandle lv = dv.getLevel( j );
processChildQuery( cubeQuery, lv.getCell( ), emptyValue );
processChildQuery( cubeQuery,
lv.getAggregationHeader( ),
emptyValue );
}
}
}
// process column edge
if ( crosstabItem.getDimensionCount( COLUMN_AXIS_TYPE ) > 0 )
{
// TODO check visibility?
for ( int i = 0; i < crosstabItem.getDimensionCount( COLUMN_AXIS_TYPE ); i++ )
{
DimensionViewHandle dv = crosstabItem.getDimension( COLUMN_AXIS_TYPE,
i );
for ( int j = 0; j < dv.getLevelCount( ); j++ )
{
LevelViewHandle lv = dv.getLevel( j );
processChildQuery( cubeQuery, lv.getCell( ), emptyValue );
processChildQuery( cubeQuery,
lv.getAggregationHeader( ),
emptyValue );
}
}
}
// process grandtotal header
processChildQuery( cubeQuery,
crosstabItem.getGrandTotal( ROW_AXIS_TYPE ),
emptyValue );
processChildQuery( cubeQuery,
crosstabItem.getGrandTotal( COLUMN_AXIS_TYPE ),
emptyValue );
}
return new IDataQueryDefinition[]{
cubeQuery
};
}
private void processChildQuery( IDataQueryDefinition parent,
CrosstabCellHandle cell, String emptyVlaue )
{
if ( cell != null )
{
for ( Iterator itr = cell.getContents( ).iterator( ); itr.hasNext( ); )
{
ReportElementHandle handle = (ReportElementHandle) itr.next( );
// handle empty value mapping
if ( emptyVlaue != null && handle instanceof DataItemHandle )
{
DataItemHandle dataHandle = (DataItemHandle) handle;
MapRule rule = StructureFactory.createMapRule( );
rule.setTestExpression( ExpressionUtil.createJSDataExpression( dataHandle.getResultSetColumn( ) ) );
rule.setOperator( DesignChoiceConstants.MAP_OPERATOR_NULL );
rule.setDisplay( emptyVlaue );
PropertyHandle mapHandle = dataHandle.getPropertyHandle( StyleHandle.MAP_RULES_PROP );
try
{
mapHandle.addItem( rule );
}
catch ( SemanticException e )
{
logger.log( Level.SEVERE,
Messages.getString( "CrosstabReportItemQuery.error.register.empty.cell.value" ), //$NON-NLS-1$
e );
}
}
context.createQuery( parent, handle );
}
}
}
}
|
package com.eatthepath.jeospatial;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import com.eatthepath.jeospatial.example.ZipCode;
import com.eatthepath.jvptree.DistanceComparator;
/**
* A crude test app that loads a bunch of zip codes, builds a vp-tree and
* performs some searches. The point here is to use a dataset that's larger
* than would be practical to use during normal unit tests.
*
* @author <a href="mailto:jon.chambers@gmail.com">Jon Chambers</a>
*/
public class LoadTestApp {
public static void main(String[] args) throws IOException {
final HaversineDistanceFunction distanceFunction = new HaversineDistanceFunction();
long start = System.currentTimeMillis();
final List<ZipCode> zipCodes = ZipCode.loadAllFromCsvFile(new File("data/zips.csv"));
long end = System.currentTimeMillis();
System.out.format("Loaded %d zip codes in %d milliseconds.%n", zipCodes.size(), end - start);
// Now put all of those zip codes into a vp-tree
start = System.currentTimeMillis();
final VPTreeGeospatialPointIndex<ZipCode> zipCodeTree =
new VPTreeGeospatialPointIndex<ZipCode>(zipCodes);
end = System.currentTimeMillis();
System.out.format("Built vp-tree from zip code list in %d milliseconds.%n", end - start);
// Now let's compare search performance! We'll start by picking a query
// point which, for lack of a better idea, will be where I live.
ZipCode davisSquare = null;
for (final ZipCode z : zipCodes) {
if (z.getCode() == 2144) {
davisSquare = z;
break;
}
}
// Dumb nearest neighbor search method: sort the entire list of zip codes!
start = System.currentTimeMillis();
java.util.Collections.sort(zipCodes, new DistanceComparator<ZipCode>(davisSquare, distanceFunction));
end = System.currentTimeMillis();
System.out.format("Sorted list of zip codes by distance from Ana's Tacqueria in %d milliseconds.%n", end - start);
System.out.println("Ten closest zip codes by list sort approach:");
for(int i = 0; i < 10; i++) {
final ZipCode z = zipCodes.get(i);
System.out.format("\t%.1f meters - %s%n", distanceFunction.getDistance(davisSquare, z), z);
}
// Now let's do OVER NINE THOUSAND searches using the vp-tree. We
// pre-generate random test points to remove random number generation
// from the time measurement.
final ZipCode[] testPoints = new ZipCode[10000];
final Random r = new Random();
for(int i = 0; i < testPoints.length; i++) {
double longitude = -70d - (r.nextDouble() * 50d);
double latitude = 28d + (r.nextDouble() * 14d);
testPoints[i] = new ZipCode(0, "Test", "Test", latitude, longitude);
}
start = System.currentTimeMillis();
for (final ZipCode p : testPoints) {
zipCodeTree.getNearestNeighbors(p, 10);
}
end = System.currentTimeMillis();
System.out.format("Performed %d vp-tree searches in %d milliseconds.%n", testPoints.length, end - start);
System.out.println("Ten closest zip codes by vp-tree search approach:");
for(final ZipCode z : zipCodeTree.getNearestNeighbors(davisSquare, 10)) {
System.out.format("\t%.1f meters - %s%n", distanceFunction.getDistance(davisSquare, z), z);
}
// Let's see how performance compares with a thread-safe locking tree.
/* LockingVPTree<ZipCode> lockingZipCodeTree = new LockingVPTree<ZipCode>(zipCodes, 20);
start = System.currentTimeMillis();
for(SimpleGeospatialPoint p : testPoints) {
lockingZipCodeTree.getNearestNeighbors(p, 10);
}
end = System.currentTimeMillis();
System.out.format("Performed %d locking vp-tree searches in %d milliseconds.%n", testPoints.length, end - start); */
// Just to be difficult, let's remove all of the zip codes from states
// in the northeast and try the search again.
ArrayList<String> statesToClobber = new ArrayList<String>();
statesToClobber.add("MA");
statesToClobber.add("ME");
statesToClobber.add("NH");
statesToClobber.add("VT");
statesToClobber.add("RI");
statesToClobber.add("NY");
statesToClobber.add("CT");
ArrayList<ZipCode> zipCodesToRemove = new ArrayList<ZipCode>();
for(ZipCode z : zipCodes) {
if(statesToClobber.contains(z.getState())) {
zipCodesToRemove.add(z);
}
}
start = System.currentTimeMillis();
zipCodeTree.removeAll(zipCodesToRemove);
end = System.currentTimeMillis();
System.out.format("Removed %d zip codes in %d milliseconds.%n", zipCodesToRemove.size(), end - start);
List<ZipCode> closestAfterRemoval = zipCodeTree.getNearestNeighbors(davisSquare, 10);
System.out.println("Ten closest zip codes after removal of points in the northeast:");
for(ZipCode z : closestAfterRemoval) {
System.out.format("\t%.1f meters - %s%n", distanceFunction.getDistance(davisSquare, z), z);
}
}
}
|
package org.voltdb;
import junit.framework.TestCase;
import org.voltdb.VoltDB.Configuration;
import org.voltdb.client.Client;
import org.voltdb.client.ClientFactory;
import org.voltdb.compiler.VoltProjectBuilder;
import org.voltdb.utils.MiscUtils;
public class TestAdHocQueries extends TestCase {
public void testSimple() throws Exception {
String simpleSchema =
"create table BLAH (" +
"IVAL bigint default 0 not null, " +
"TVAL timestamp default null," +
"DVAL decimal default null," +
"PRIMARY KEY(IVAL));";
VoltProjectBuilder builder = new VoltProjectBuilder();
builder.addLiteralSchema(simpleSchema);
builder.addPartitionInfo("BLAH", "IVAL");
builder.addStmtProcedure("Insert", "insert into blah values (?, ?, ?);", null);
builder.addStmtProcedure("InsertWithDate", "INSERT INTO BLAH VALUES (974599638818488300, '2011-06-24 10:30:26.002', 5);");
boolean success = builder.compile(Configuration.getPathToCatalogForTest("adhoc.jar"), 2, 1, 0);
assertTrue(success);
MiscUtils.copyFile(builder.getPathToDeployment(), Configuration.getPathToCatalogForTest("adhoc.xml"));
VoltDB.Configuration config = new VoltDB.Configuration();
config.m_pathToCatalog = Configuration.getPathToCatalogForTest("adhoc.jar");
config.m_pathToDeployment = Configuration.getPathToCatalogForTest("adhoc.xml");
ServerThread localServer = new ServerThread(config);
localServer.start();
localServer.waitForInitialization();
// do the test
Client client = ClientFactory.createClient();
client.createConnection("localhost");
VoltTable modCount = client.callProcedure("@AdHoc", "INSERT INTO BLAH VALUES (1, 1, 1);").getResults()[0];
assertTrue(modCount.getRowCount() == 1);
assertTrue(modCount.asScalarLong() == 1);
VoltTable result = client.callProcedure("@AdHoc", "SELECT * FROM BLAH;").getResults()[0];
assertTrue(result.getRowCount() == 1);
System.out.println(result.toString());
// test single-partition stuff
result = client.callProcedure("@AdHoc", "SELECT * FROM BLAH;", 0).getResults()[0];
assertTrue(result.getRowCount() == 0);
System.out.println(result.toString());
result = client.callProcedure("@AdHoc", "SELECT * FROM BLAH;", 1).getResults()[0];
assertTrue(result.getRowCount() == 1);
System.out.println(result.toString());
try {
client.callProcedure("@AdHoc", "INSERT INTO BLAH VALUES (0, 0, 0);", 1);
fail("Badly partitioned insert failed to throw expected exception");
}
catch (Exception e) {}
try {
client.callProcedure("@AdHoc", "SLEECT * FROOM NEEEW_OOORDERERER;");
fail("Bad SQL failed to throw expected exception");
}
catch (Exception e) {}
// try a huge bigint literal
modCount = client.callProcedure("@AdHoc", "INSERT INTO BLAH VALUES (974599638818488300, '2011-06-24 10:30:26', 5);").getResults()[0];
modCount = client.callProcedure("@AdHoc", "INSERT INTO BLAH VALUES (974599638818488301, '2011-06-24 10:30:28', 5);").getResults()[0];
assertTrue(modCount.getRowCount() == 1);
assertTrue(modCount.asScalarLong() == 1);
result = client.callProcedure("@AdHoc", "SELECT * FROM BLAH WHERE IVAL = 974599638818488300;").getResults()[0];
assertTrue(result.getRowCount() == 1);
System.out.println(result.toString());
result = client.callProcedure("@AdHoc", "SELECT * FROM BLAH WHERE TVAL = '2011-06-24 10:30:26';").getResults()[0];
assertTrue(result.getRowCount() == 1);
System.out.println(result.toString());
result = client.callProcedure("@AdHoc", "SELECT * FROM BLAH WHERE TVAL > '2011-06-24 10:30:25';").getResults()[0];
assertEquals(2, result.getRowCount());
System.out.println(result.toString());
result = client.callProcedure("@AdHoc", "SELECT * FROM BLAH WHERE TVAL < '2011-06-24 10:30:27';").getResults()[0];
System.out.println(result.toString());
// We inserted a 1,1,1 row way earlier
assertEquals(2, result.getRowCount());
// try a decimal calculation (ENG-1093)
modCount = client.callProcedure("@AdHoc", "INSERT INTO BLAH VALUES (2, '2011-06-24 10:30:26', 1.12345*1);").getResults()[0];
assertTrue(modCount.getRowCount() == 1);
assertTrue(modCount.asScalarLong() == 1);
result = client.callProcedure("@AdHoc", "SELECT * FROM BLAH WHERE IVAL = 2;").getResults()[0];
assertTrue(result.getRowCount() == 1);
System.out.println(result.toString());
localServer.shutdown();
localServer.join();
}
}
|
package org.voltdb;
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 java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.zookeeper_voltpatches.CreateMode;
import org.apache.zookeeper_voltpatches.WatchedEvent;
import org.apache.zookeeper_voltpatches.Watcher;
import org.apache.zookeeper_voltpatches.ZooDefs.Ids;
import org.apache.zookeeper_voltpatches.ZooKeeper;
import org.json_voltpatches.JSONException;
import org.json_voltpatches.JSONObject;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import org.voltcore.logging.VoltLogger;
import org.voltcore.network.WriteStream;
import org.voltcore.utils.CoreUtils;
import org.voltcore.utils.InstanceId;
import org.voltcore.zk.ZKTestBase;
import org.voltdb.RestoreAgent.SnapshotInfo;
import org.voltdb.VoltDB.START_ACTION;
import org.voltdb.VoltTable.ColumnInfo;
import org.voltdb.VoltZK.MailboxType;
import org.voltdb.catalog.Catalog;
import org.voltdb.client.Client;
import org.voltdb.client.ClientConfig;
import org.voltdb.client.ClientFactory;
import org.voltdb.client.ClientResponse;
import org.voltdb.client.ProcCallException;
import org.voltdb.compiler.ClusterConfig;
import org.voltdb.compiler.VoltProjectBuilder;
import org.voltdb.dtxn.SiteTracker;
import org.voltdb.dtxn.TransactionInitiator;
import org.voltdb.utils.CatalogUtil;
import org.voltdb.utils.VoltFile;
@RunWith(Parameterized.class)
public class TestRestoreAgent extends ZKTestBase implements RestoreAgent.Callback {
private final static VoltLogger LOG = new VoltLogger("HOST");
static final int TEST_SERVER_BASE_PORT = 30210;
static final int TEST_ZK_BASE_PORT = 21820;
static int uid = 0;
@Parameters
public static Collection<Object[]> startActions() {
return Arrays.asList(new Object[][] {{START_ACTION.CREATE},
{START_ACTION.START},
{START_ACTION.RECOVER}});
}
/**
* The start action to use for some of the tests
*/
protected final START_ACTION action;
public TestRestoreAgent(START_ACTION action) {
this.action = action;
}
class MockSnapshotMonitor extends SnapshotCompletionMonitor {
@Override
public void init(final ZooKeeper zk) {
try {
Watcher watcher = new Watcher() {
@Override
public void process(WatchedEvent event) {
try {
List<String> children = zk.getChildren(VoltZK.root, this);
for (String s : children) {
if (s.equals("request_truncation_snapshot")) {
snapshotted = true;
LinkedList<SnapshotCompletionInterest> interests =
new LinkedList<SnapshotCompletionInterest>(m_interests);
for (SnapshotCompletionInterest i : interests) {
i.snapshotCompleted( "", 0, new long[0], true, "");
}
break;
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
zk.getChildren(VoltZK.root, watcher);
} catch (Exception e) {
e.printStackTrace();
}
}
}
List<File> paths = new ArrayList<File>();
private SnapshotCompletionMonitor snapshotMonitor = null;
boolean snapshotted = false;
HashMap<Integer, SiteTracker> siteTrackers = null;
CatalogContext context;
File catalogJarFile;
String deploymentPath;
private final AtomicInteger m_count = new AtomicInteger();
volatile int m_hostCount = 0;
volatile boolean m_done = false;
final Set<String> m_unexpectedSPIs = new HashSet<String>();
protected Long snapshotTxnId = null;
/**
* A mock initiator that checks if the we have all the initiations we
* expect.
*/
class MockInitiator extends TransactionInitiator {
private final Map<String, Long> procCounts = new HashMap<String, Long>();
private final Map<String, ParameterSet> procParams = new HashMap<String, ParameterSet>();
public MockInitiator(Set<String> procNames) {
if (procNames != null) {
for (String proc : procNames) {
procCounts.put(proc, 0l);
procParams.put(proc, null);
}
}
}
public Map<String, Long> getProcCounts() {
return procCounts;
}
public Map<String, ParameterSet> getProcParams() {
return procParams;
}
@Override
public boolean createTransaction(long connectionId,
String connectionHostname,
boolean adminConnection,
StoredProcedureInvocation invocation,
boolean isReadOnly,
boolean isSinglePartition,
boolean isEverySite,
int[] partitions,
int numPartitions,
Object clientData,
int messageSize,
long now,
boolean allowMismatchedResults) {
createTransaction(connectionId, connectionHostname, adminConnection,
0, 0, invocation, isReadOnly, isSinglePartition,
isEverySite, partitions, numPartitions,
clientData, messageSize, now, allowMismatchedResults);
return true;
}
@Override
public boolean createTransaction(long connectionId,
String connectionHostname,
boolean adminConnection,
long txnId,
long timestamp,
StoredProcedureInvocation invocation,
boolean isReadOnly,
boolean isSinglePartition,
boolean isEverySite,
int[] partitions,
int numPartitions,
Object clientData,
int messageSize,
long now,
boolean allowMismatchedResults) {
String procName = invocation.procName;
if (!procCounts.containsKey(procName)) {
m_unexpectedSPIs.add(procName);
} else {
procCounts.put(procName, procCounts.get(procName) + 1);
procParams.put(procName, invocation.getParams());
}
// Fake success
ColumnInfo[] columns = new ColumnInfo[] {new ColumnInfo("RESULT", VoltType.STRING)};
VoltTable result = new VoltTable(columns);
result.addRow("SUCCESS");
VoltTable[] results = new VoltTable[] {result};
ClientResponseImpl response = new ClientResponseImpl(ClientResponse.SUCCESS,
results, null);
ByteBuffer buf = ByteBuffer.allocate(response.getSerializedSize() + 4);
buf.putInt(buf.capacity() - 4);
response.flattenToBuffer(buf);
buf.flip();
((WriteStream) clientData).enqueue(buf);
return true;
}
@Override
public long tick() {
throw new UnsupportedOperationException();
}
@Override
public long getMostRecentTxnId() {
throw new UnsupportedOperationException();
}
@Override
public void notifyExecutionSiteRejoin(ArrayList<Long> executorSiteIds) {
throw new UnsupportedOperationException();
}
@Override
public Map<Long, long[]> getOutstandingTxnStats() {
throw new UnsupportedOperationException();
}
@Override
protected void increaseBackpressure(int messageSize) {
throw new UnsupportedOperationException();
}
@Override
protected void reduceBackpressure(int messageSize) {
throw new UnsupportedOperationException();
}
@Override
public void setSendHeartbeats(boolean val) {
}
@Override
public void sendHeartbeat(long txnId) {
}
@Override
public boolean isOnBackPressure() {
return false;
}
@Override
public void removeConnectionStats(long connectionId) {
}
@Override
public void sendSentinel(long txnId, int partitionId) {}
@Override
public void sendEOLMessage(int partitionId) {}
}
void buildCatalog(int hostCount, int sitesPerHost, int kfactor, String voltroot,
boolean excludeProcs, boolean rebuildAll)
throws Exception {
/*
* This suite is intended only to test RestoreAgentWithout command logging.
* They fail with the pro build and command logging enabled because they are
* testing for community before. TestRestoreAgentWithReplay tests with CL enabled.
* We do want to check that the community edition doesn't barf if command logging is
* accidentally request, and we want to run these tests with the pro build as well
* so we switch CL enabled on whether this is a pro build.
*/
buildCatalog(hostCount, sitesPerHost, kfactor, voltroot, isEnterprise() ? false : true,
excludeProcs, rebuildAll);
}
/**
* Build a new catalog context.
*
* @param hostCount
* @param sitesPerHost
* @param kfactor
* @param voltroot
* @param excludeProcs used to create a different catalog to check CRC match
* @param rebuildAll TODO
* @throws IOException
*/
void buildCatalog(int hostCount, int sitesPerHost, int kfactor, String voltroot,
boolean commandLog, boolean excludeProcs, boolean rebuildAll)
throws Exception {
VoltProjectBuilder builder = new VoltProjectBuilder();
String schema = "create table A (i integer not null, s varchar(30), sh smallint, l bigint, primary key (i));";
builder.addLiteralSchema(schema);
builder.addPartitionInfo("A", "i");
builder.addStmtProcedure("hello", "select * from A where i = ? and s = ?", "A.i: 0");
builder.addStmtProcedure("world", "select * from A where i = ? and sh = ? and s = ?", "A.i: 0");
if (!excludeProcs)
{
builder.addStmtProcedure("bid", "select * from A where i = ? and sh = ? and s = ?", "A.i: 0");
builder.addStmtProcedure("sum", "select * from A where i = ? and sh = ? and s = ?", "A.i: 0");
builder.addStmtProcedure("calc", "select * from A where i = ? and sh = ? and s = ?", "A.i: 0");
builder.addStmtProcedure("HowWillAppleNameItsVaccuumCleaner", "select * from A where l = ? and sh = ? and s = ?");
builder.addStmtProcedure("Dedupe", "select * from A where l = ? and sh = ?");
builder.addStmtProcedure("Cill", "select * from A where l = ? and s = ?");
}
builder.configureLogging(voltroot, voltroot, false, commandLog, 200, 20000, 300);
File cat = File.createTempFile("temp-restore", "catalog");
cat.deleteOnExit();
assertTrue(builder.compile(cat.getAbsolutePath(), sitesPerHost,
hostCount, kfactor, voltroot));
deploymentPath = builder.getPathToDeployment();
File cat_to_use = cat;
if (rebuildAll)
{
catalogJarFile = cat;
}
else
{
cat_to_use = catalogJarFile;
}
byte[] bytes = CatalogUtil.toBytes(cat_to_use);
String serializedCat = CatalogUtil.loadCatalogFromJar(bytes, null);
assertNotNull(serializedCat);
Catalog catalog = new Catalog();
catalog.execute(serializedCat);
ClusterConfig config = new ClusterConfig(hostCount, sitesPerHost, kfactor);
List<Integer> hostIds = new ArrayList<Integer>(hostCount);
for (int ii = 0; ii < hostCount; ii++) hostIds.add(ii);
JSONObject topology = config.getTopology(hostIds);
long crc = CatalogUtil.compileDeploymentAndGetCRC(catalog, deploymentPath,
true);
context = new CatalogContext(0, 0, catalog, bytes, crc, 0, 0);
siteTrackers = new HashMap<Integer, SiteTracker>();
// create MailboxNodeContexts for all hosts (we only need getAllHosts(), I think)
for (int i = 0; i < hostCount; i++)
{
ArrayList<MailboxNodeContent> hosts = new ArrayList<MailboxNodeContent>();
for (int j = 0; j < hostCount; j++)
{
List<Integer> localPartitions = ClusterConfig.partitionsForHost(topology, j);
for (int zz = 0; zz < localPartitions.size(); zz++) {
MailboxNodeContent mnc =
new MailboxNodeContent(CoreUtils.getHSIdFromHostAndSite(j, zz), localPartitions.get(zz));
hosts.add(mnc);
}
}
HashMap<MailboxType, List<MailboxNodeContent>> blah =
new HashMap<MailboxType, List<MailboxNodeContent>>();
blah.put(MailboxType.ExecutionSite, hosts);
siteTrackers.put(i, new SiteTracker(i, blah));
}
}
/**
* Take a snapshot
* @throws IOException
*/
void snapshot(String nonce) throws Exception {
String path = context.cluster.getVoltroot() + File.separator + "snapshots";
ClientConfig clientConfig = new ClientConfig();
Client client = ClientFactory.createClient(clientConfig);
ClientResponse response = null;
try {
client.createConnection("localhost");
try {
response = client.callProcedure("@SnapshotSave",
path,
nonce,
1);
} catch (ProcCallException e) {
fail(e.getMessage());
}
} finally {
client.close();
}
assertEquals(ClientResponse.SUCCESS, response.getStatus());
assertEquals(1, response.getResults().length);
assertTrue(response.getResults()[0].advanceRow());
assertEquals("SUCCESS", response.getResults()[0].getString("RESULT"));
}
/**
* Generate a new voltroot with the given suffix. Will be automatically
* cleaned after the test.
*
* @param suffix
* @return The new voltroot
* @throws IOException
*/
String newVoltRoot(String suffix) throws IOException {
if (suffix == null) {
suffix = "";
}
File path = File.createTempFile("temp", "restore-test-" + suffix);
path.delete();
path = new VoltFile(path.getAbsolutePath());
assertTrue(path.mkdir());
paths.add(path);
return path.getAbsolutePath();
}
@Before
public void setUp() throws Exception {
m_count.set(0);
m_done = false;
snapshotted = false;
m_unexpectedSPIs.clear();
setUpZK(1);
getClient(0).create("/db", null, Ids.OPEN_ACL_UNSAFE,
CreateMode.PERSISTENT);
snapshotMonitor = new MockSnapshotMonitor();
snapshotMonitor.init(getClient(0));
}
@After
public void tearDown() throws Exception {
tearDownZK();
if (snapshotMonitor != null) {
snapshotMonitor.shutdown();
}
String msg = "";
for (String name : m_unexpectedSPIs) {
msg += name + ", ";
}
assertTrue(msg, m_unexpectedSPIs.isEmpty());
for (File p : paths) {
VoltFile.recursivelyDelete(p);
}
}
/**
* Check if nothing is recovered if the action is create
* @param initiator
*/
protected void createCheck(MockInitiator initiator) {
assertEquals(Long.MIN_VALUE, snapshotTxnId.longValue());
assertFalse(snapshotted);
if (!initiator.getProcCounts().isEmpty()) {
for (long count : initiator.getProcCounts().values()) {
assertEquals(0, count);
}
}
}
private boolean isEnterprise() {
return VoltDB.instance().getConfig().m_isEnterprise;
}
protected RestoreAgent getRestoreAgent(MockInitiator initiator, int hostId) throws Exception {
String snapshotPath = null;
if (context.cluster.getDatabases().get("database").getSnapshotschedule().get("default") != null) {
snapshotPath = context.cluster.getDatabases().get("database").getSnapshotschedule().get("default").getPath();
}
SiteTracker st = siteTrackers.get(hostId);
int[] allPartitions = st.getAllPartitions();
org.voltdb.catalog.CommandLog cl = context.cluster.getLogconfig().get("log");
Set<Integer> all_hosts = new HashSet<Integer>();
for (int host = 0; host < m_hostCount; host++)
{
all_hosts.add(host);
}
RestoreAgent restoreAgent = new RestoreAgent(getClient(0),
snapshotMonitor, this,
hostId, this.action,
cl.getEnabled(),
cl.getLogpath(),
cl.getInternalsnapshotpath(),
snapshotPath,
allPartitions,
all_hosts);
restoreAgent.setCatalogContext(context);
restoreAgent.setSiteTracker(siteTrackers.get(hostId));
assert(initiator != null);
restoreAgent.setInitiator(initiator);
return restoreAgent;
}
@Test
public void testSingleHostEmptyRestore() throws Exception {
m_hostCount = 1;
buildCatalog(m_hostCount, 8, 0, newVoltRoot(null), false, true);
MockInitiator initiator = new MockInitiator(null);
RestoreAgent restoreAgent = getRestoreAgent(initiator, 0);
restoreAgent.createZKDirectory(VoltZK.restore);
restoreAgent.createZKDirectory(VoltZK.restore_barrier);
restoreAgent.createZKDirectory(VoltZK.restore_barrier + "2");
restoreAgent.enterRestore();
assertNull(restoreAgent.generatePlans());
}
@Test
public void testMultipleHostEmptyRestore() throws Exception {
m_hostCount = 3;
buildCatalog(m_hostCount, 8, 0, newVoltRoot(null), false, true);
MockInitiator initiator = new MockInitiator(null);
List<RestoreAgent> agents = new ArrayList<RestoreAgent>();
for (int i = 0; i < m_hostCount; i++) {
agents.add(getRestoreAgent(initiator, i));
}
ExecutorService ex = Executors.newFixedThreadPool(3);
final AtomicInteger failure = new AtomicInteger();
for (final RestoreAgent agent : agents) {
ex.submit(new Runnable() {
@Override
public void run() {
agent.createZKDirectory(VoltZK.restore);
agent.createZKDirectory(VoltZK.restore_barrier);
agent.createZKDirectory(VoltZK.restore_barrier + "2");
agent.enterRestore();
try {
if (agent.generatePlans() != null) {
failure.incrementAndGet();
}
} catch (Exception e) {
failure.incrementAndGet();
}
}
});
}
ex.shutdown();
assertTrue(ex.awaitTermination(10, TimeUnit.SECONDS));
assertEquals(0, failure.get());
}
@Test
public void testMultipleHostAgreementFailure() throws Exception {
// Don't run this test if we are in recovery mode
if (action == START_ACTION.RECOVER) {
return;
}
m_hostCount = 3;
buildCatalog(m_hostCount, 8, 0, newVoltRoot(null), false, true);
MockInitiator initiator = new MockInitiator(null);
List<RestoreAgent> agents = new ArrayList<RestoreAgent>();
for (int i = 0; i < m_hostCount - 1; i++) {
agents.add(getRestoreAgent(initiator, i));
}
for (RestoreAgent agent : agents) {
agent.restore();
}
int count = 0;
while (!m_done && count++ < 10) {
try {
Thread.sleep(200);
} catch (InterruptedException e) {}
}
if (m_done) {
fail();
}
// Start the last restore agent, should be able to reach agreement now
RestoreAgent agent = getRestoreAgent(initiator, m_hostCount - 1);
agent.restore();
count = 0;
while (!m_done && count++ < 10) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {}
}
if (!m_done) {
fail();
}
assertFalse(snapshotted);
assertEquals(Long.MIN_VALUE, snapshotTxnId.longValue());
}
@Test
public void testSingleHostSnapshotRestoreNewestSnapshot() throws Exception {
m_hostCount = 1;
buildCatalog(m_hostCount, 8, 0, newVoltRoot(null), false, true);
ServerThread server = new ServerThread(catalogJarFile.getAbsolutePath(),
deploymentPath,
TEST_SERVER_BASE_PORT + 2,
TEST_SERVER_BASE_PORT + 1,
TEST_ZK_BASE_PORT,
BackendTarget.NATIVE_EE_JNI);
server.start();
server.waitForInitialization();
snapshot("bonjour");
// Now take a couple more for good measure
snapshot("sacrebleu");
snapshot("oolalacestcher");
server.shutdown();
// Now get a newer instance ID
server = new ServerThread(catalogJarFile.getAbsolutePath(),
deploymentPath,
TEST_SERVER_BASE_PORT + 2,
TEST_SERVER_BASE_PORT + 1,
TEST_ZK_BASE_PORT,
BackendTarget.NATIVE_EE_JNI);
server.start();
server.waitForInitialization();
snapshot("hello");
// Now take a couple more for good measure
snapshot("goodday");
snapshot("isaidgooddaysir");
server.shutdown();
HashSet<String> procs = new HashSet<String>();
procs.add("@SnapshotRestore");
MockInitiator initiator = new MockInitiator(procs);
RestoreAgent restoreAgent = getRestoreAgent(initiator, 0);
restoreAgent.restore();
while (!m_done) {
try {
Thread.sleep(200);
} catch (InterruptedException e) {}
}
if (action != START_ACTION.CREATE) {
Long count = initiator.getProcCounts().get("@SnapshotRestore");
assertEquals(new Long(1), count);
assertEquals(Long.MIN_VALUE, snapshotTxnId.longValue());
// We'd better have restored the newest snapshot
assertEquals("isaidgooddaysir", (String)(initiator.getProcParams().get("@SnapshotRestore").toArray()[1]));
} else {
createCheck(initiator);
}
}
@Test
public void testSingleHostSnapshotRestore() throws Exception {
m_hostCount = 1;
buildCatalog(m_hostCount, 8, 0, newVoltRoot(null), false, true);
ServerThread server = new ServerThread(catalogJarFile.getAbsolutePath(),
deploymentPath,
TEST_SERVER_BASE_PORT + 2,
TEST_SERVER_BASE_PORT + 1,
TEST_ZK_BASE_PORT,
BackendTarget.NATIVE_EE_JNI);
server.start();
server.waitForInitialization();
snapshot("hello");
server.shutdown();
HashSet<String> procs = new HashSet<String>();
procs.add("@SnapshotRestore");
MockInitiator initiator = new MockInitiator(procs);
RestoreAgent restoreAgent = getRestoreAgent(initiator, 0);
restoreAgent.restore();
while (!m_done) {
try {
Thread.sleep(200);
} catch (InterruptedException e) {}
}
if (action != START_ACTION.CREATE) {
Long count = initiator.getProcCounts().get("@SnapshotRestore");
assertEquals(new Long(1), count);
assertEquals(Long.MIN_VALUE, snapshotTxnId.longValue());
assertEquals("hello", (String)(initiator.getProcParams().get("@SnapshotRestore").toArray()[1]));
} else {
createCheck(initiator);
}
}
@Test
public void testSingleHostSnapshotRestoreCatalogChange() throws Exception {
m_hostCount = 1;
String voltroot = newVoltRoot(null);
buildCatalog(m_hostCount, 8, 0, voltroot, false, true);
ServerThread server = new ServerThread(catalogJarFile.getAbsolutePath(),
deploymentPath,
TEST_SERVER_BASE_PORT + 2,
TEST_SERVER_BASE_PORT,
TEST_ZK_BASE_PORT,
BackendTarget.NATIVE_EE_JNI);
server.start();
server.waitForInitialization();
snapshot("hello");
server.shutdown();
buildCatalog(m_hostCount, 8, 0, voltroot, true, true);
HashSet<String> procs = new HashSet<String>();
procs.add("@SnapshotRestore");
MockInitiator initiator = new MockInitiator(procs);
RestoreAgent restoreAgent = getRestoreAgent(initiator, 0);
restoreAgent.restore();
while (!m_done) {
try {
Thread.sleep(200);
} catch (InterruptedException e) {}
}
if (action != START_ACTION.CREATE) {
Long count = initiator.getProcCounts().get("@SnapshotRestore");
assertEquals(new Long(1), count);
assertEquals(Long.MIN_VALUE, snapshotTxnId.longValue());
} else {
createCheck(initiator);
}
}
@Test
public void testMultiHostSnapshotRestore() throws Exception {
m_hostCount = 1;
String voltroot = newVoltRoot(null);
buildCatalog(m_hostCount, 8, 0, voltroot, false, true);
ServerThread server = new ServerThread(catalogJarFile.getAbsolutePath(),
deploymentPath,
TEST_SERVER_BASE_PORT + 2,
TEST_SERVER_BASE_PORT,
TEST_ZK_BASE_PORT,
BackendTarget.NATIVE_EE_JNI);
server.start();
server.waitForInitialization();
snapshot("hello");
server.shutdown();
m_hostCount = 3;
buildCatalog(m_hostCount, 8, 1, voltroot, false, true);
HashSet<String> procs = new HashSet<String>();
procs.add("@SnapshotRestore");
MockInitiator initiator = new MockInitiator(procs);
List<RestoreAgent> agents = new ArrayList<RestoreAgent>();
for (int i = 0; i < m_hostCount; i++) {
agents.add(getRestoreAgent(initiator, i));
}
for (RestoreAgent agent : agents) {
agent.restore();
}
while (!m_done) {
try {
Thread.sleep(200);
} catch (InterruptedException e) {}
}
if (action != START_ACTION.CREATE) {
Long count = initiator.getProcCounts().get("@SnapshotRestore");
assertEquals(new Long(1), count);
assertEquals(Long.MIN_VALUE, snapshotTxnId.longValue());
} else {
createCheck(initiator);
}
}
@Test
public void testConsistentRestorePlan() {
List<SnapshotInfo> infos = new ArrayList<SnapshotInfo>();
InstanceId id = new InstanceId(0, 0);
SnapshotInfo info1 = new SnapshotInfo(0, "blah", "nonce", 3, 0, 0, id);
SnapshotInfo info2 = new SnapshotInfo(0, "blah", "nonce", 3, 0, 1, id);
infos.add(info1);
infos.add(info2);
SnapshotInfo pickedInfo = RestoreAgent.consolidateSnapshotInfos(infos);
assertNotNull(pickedInfo);
assertEquals(0, pickedInfo.hostId);
// Inverse the order we add infos
infos.clear();
infos.add(info2);
infos.add(info1);
pickedInfo = RestoreAgent.consolidateSnapshotInfos(infos);
assertNotNull(pickedInfo);
assertEquals(0, pickedInfo.hostId);
}
@Override
public void onRestoreCompletion(long txnId, long perPartitionTxnIds[]) {
if (snapshotTxnId != null) {
assertEquals(snapshotTxnId.longValue(), txnId);
}
snapshotTxnId = txnId;
if (m_count.incrementAndGet() == m_hostCount) {
m_done = true;
}
}
void addSnapshotInfo(Map<Long, Set<SnapshotInfo>> frags,
long txnid, long crc)
{
Set<SnapshotInfo> si = null;
if (frags.containsKey(txnid))
{
si = frags.get(txnid);
}
else
{
si = new HashSet<SnapshotInfo>();
frags.put(txnid, si);
}
InstanceId id = new InstanceId(0, 0);
si.add(new SnapshotInfo(txnid, "dummy", "dummy", 1, crc, -1, id));
}
@Test
public void testSnapshotInfoRoundTrip() throws JSONException
{
InstanceId id = new InstanceId(1234, 4321);
RestoreAgent.SnapshotInfo dut = new RestoreAgent.SnapshotInfo(1234L, "dummy", "stupid", 11, 4321L, 13, id);
dut.partitionToTxnId.put(1, 7000L);
dut.partitionToTxnId.put(7, 1000L);
byte[] serial = dut.toJSONObject().toString().getBytes(VoltDB.UTF8ENCODING);
SnapshotInfo rt = new SnapshotInfo(new JSONObject(new String(serial, VoltDB.UTF8ENCODING)));
System.out.println("Got: " + rt.toJSONObject().toString());
assertEquals(dut.partitionToTxnId.get(1), rt.partitionToTxnId.get(1));
assertEquals(id, rt.instanceId);
}
}
|
package net.ssehub.easy.reasoning.core.capabilities;
import org.junit.Test;
import org.junit.Assert;
import net.ssehub.easy.reasoning.core.reasoner.AbstractTest;
import net.ssehub.easy.reasoning.core.reasoner.ITestDescriptor;
import net.ssehub.easy.varModel.confModel.AssignmentState;
import net.ssehub.easy.varModel.confModel.Configuration;
import net.ssehub.easy.varModel.confModel.IDecisionVariable;
import net.ssehub.easy.varModel.model.AbstractVariable;
import net.ssehub.easy.varModel.model.ModelQuery;
import net.ssehub.easy.varModel.model.ModelQueryException;
import net.ssehub.easy.varModel.model.values.ContainerValue;
import net.ssehub.easy.varModel.model.values.Value;
/**
* Collection constraints tests.
*
* @author Sizonenko
* @author El-Sharkawy
*/
public class CollectionConstraintsTests extends AbstractTest {
/**
* Creating a test instance.
*
* @param descriptor the test descriptor
*/
protected CollectionConstraintsTests(ITestDescriptor descriptor) {
super(descriptor, "collectionConstraints");
}
/**
* Tests constraints in set.
*/
@Test
public void constraintSetDefaultTest() {
reasoningTest("constraintSetDefault.ivml", 1);
}
/**
* Tests constraints in set of set.
*/
@Test
public void constraintSetSetDefaultTest() {
reasoningTest("constraintSetSetDefault.ivml", 1);
}
/**
* Tests containers with derived types on compounds and constraints.
*/
@Test
public void constraintSetDerivedCompoundTest() {
reasoningTest("constraintSetDerivedCompound.ivml", 2);
}
/**
* Tests containers of containers with derived types on compounds and constraints.
*/
@Test
public void constraintSetSetDerivedCompoundTest() {
reasoningTest("constraintSetSetDerivedCompound.ivml", 2);
}
/**
* Tests constraints in set.
*/
@Test
public void constraintSetAssignedTest() {
reasoningTest("constraintSetAssigned.ivml", 1);
}
/**
* Tests constraints in set.
*/
@Test
public void constraintSetDefaultInCompoundTest() {
reasoningTest("constraintSetDefaultInCompound.ivml", 1);
}
/**
* Tests constraints in set.
*/
@Test
public void constraintSetInCompoundDefaultTest() {
reasoningTest("constraintSetInCompoundDefault.ivml", 1);
}
/**
* Tests constraints in set.
*/
@Test
public void constraintSetInCompoundAssignedTest() {
reasoningTest("constraintSetInCompoundAssigned.ivml", 1);
}
/**
* Tests constraints in set.
*/
@Test
public void constraintSetInNestedCompoundDefaultTest() {
reasoningTest("constraintSetInNestedCompoundDefault.ivml", 1);
}
/**
* Tests constraints in set.
*/
@Test
public void qmTest() {
reasoningTest("QM.ivml", 1);
}
/**
* Tests constraints in set.
*/
@Test
public void setDerivedSetTest() {
reasoningTest("setDerivedSet.ivml", 3);
}
/**
* Collection annotation test.
*/
@Test
public void containerAnnotationTest() {
reasoningTest("ContainerAnnotationTest.ivml", 10);
}
/**
* Tests for derived and referenced collections.
*/
@Test
public void referenceDerivedCollectionTest() {
reasoningTest("ReferenceDerivedCollectionTest.ivml", 5);
}
/**
* String collections test (#72).
*/
@Test
public void stringCollection1Test() {
reasoningTest("StringTest1.ivml", 1);
}
/**
* String collections test (#72).
*/
@Test
public void stringCollection2Test() {
reasoningTest("StringTest2.ivml", 0);
}
/**
* String collections test (#72).
*
* @throws ModelQueryException shall not occur
*/
@Test
public void stringCollection3Test() throws ModelQueryException {
Configuration cfg = reasoningTest("StringTest3.ivml", 0);
AbstractVariable orgVarsDecl = ModelQuery.findVariable(cfg.getProject(), "orgVars", null);
Assert.assertNotNull(orgVarsDecl);
IDecisionVariable orgVars = cfg.getDecision(orgVarsDecl);
Assert.assertNotNull(orgVars);
assertContained(orgVars.getState(), AssignmentState.ASSIGNED, AssignmentState.DERIVED);
Value val = orgVars.getValue();
Assert.assertTrue(val instanceof ContainerValue);
ContainerValue cVal = (ContainerValue) val;
Assert.assertTrue(cVal.getElementSize() > 0);
}
/**
* String collections test (#74).
*
* @throws ModelQueryException shall not occur
*/
@Test
public void stringCollection4Test() throws ModelQueryException {
Configuration cfg = reasoningTest("StringTest4.ivml", 0);
AbstractVariable orgVarsDecl = ModelQuery.findVariable(cfg.getProject(), "set2", null);
Assert.assertNotNull(orgVarsDecl);
IDecisionVariable orgVars = cfg.getDecision(orgVarsDecl);
Assert.assertNotNull(orgVars);
assertContained(orgVars.getState(), AssignmentState.DEFAULT);
Value val = orgVars.getValue();
Assert.assertTrue(val instanceof ContainerValue);
ContainerValue cVal = (ContainerValue) val;
Assert.assertTrue(cVal.getElementSize() > 0);
}
}
|
package org.commcare.resources;
import org.commcare.resources.model.InstallCancelledException;
import org.commcare.resources.model.ProcessCancelled;
import org.commcare.resources.model.Resource;
import org.commcare.resources.model.ResourceLocation;
import org.commcare.resources.model.ResourceTable;
import org.commcare.resources.model.TableStateListener;
import org.commcare.resources.model.UnresolvedResourceException;
import org.commcare.suite.model.Profile;
import org.commcare.util.CommCarePlatform;
import org.javarosa.core.services.Logger;
import org.javarosa.core.services.storage.StorageFullException;
import org.javarosa.xml.util.UnfullfilledRequirementsException;
import java.util.Vector;
public class ResourceManager {
protected final CommCarePlatform platform;
protected final ResourceTable masterTable;
protected final ResourceTable upgradeTable;
protected final ResourceTable tempTable;
public ResourceManager(CommCarePlatform platform,
ResourceTable masterTable,
ResourceTable upgradeTable,
ResourceTable tempTable) {
this.platform = platform;
this.masterTable = masterTable;
this.upgradeTable = upgradeTable;
this.tempTable = tempTable;
}
public void setUpgradeListeners(TableStateListener tableListener,
ProcessCancelled cancelListener) {
masterTable.setStateListener(tableListener);
upgradeTable.setStateListener(tableListener);
upgradeTable.setProcessListener(cancelListener);
}
/**
* Installs resources described by profile reference into the provided
* resource table. If the resource table is ready or already has a profile,
* don't do anything.
*
* @param profileReference URL to profile file
* @param global Add profile ref to this table and install its
* resources
* @param forceInstall Should installation be performed regardless of
* version numbers?
*/
public static void init(CommCarePlatform platform, String profileReference,
ResourceTable global, boolean forceInstall)
throws UnfullfilledRequirementsException,
UnresolvedResourceException,
InstallCancelledException {
try {
if (!global.isReady()) {
global.prepareResources(null, platform);
}
// First, see if the appropriate profile exists
Resource profile =
global.getResourceWithId(CommCarePlatform.APP_PROFILE_RESOURCE_ID);
if (profile == null) {
// grab the local profile and parse it
Vector<ResourceLocation> locations = new Vector<ResourceLocation>();
locations.addElement(new ResourceLocation(Resource.RESOURCE_AUTHORITY_LOCAL, profileReference));
// We need a way to identify this version...
Resource r = new Resource(Resource.RESOURCE_VERSION_UNKNOWN,
CommCarePlatform.APP_PROFILE_RESOURCE_ID,
locations, "Application Descriptor");
global.addResource(r, global.getInstallers().getProfileInstaller(forceInstall), "");
global.prepareResources(null, platform);
}
} catch (StorageFullException e) {
e.printStackTrace();
}
}
public void stageUpgradeTable(boolean clearProgress)
throws UnfullfilledRequirementsException,
StorageFullException,
UnresolvedResourceException, InstallCancelledException {
Profile current = platform.getCurrentProfile();
String profileRef = current.getAuthReference();
stageUpgradeTable(profileRef, clearProgress);
}
/**
* @param clearProgress Clear the 'incoming' table of any partial update
* info.
*/
public void stageUpgradeTable(String profileRef, boolean clearProgress)
throws UnfullfilledRequirementsException,
StorageFullException,
UnresolvedResourceException, InstallCancelledException {
ensureValidState();
if (clearProgress) {
upgradeTable.clear();
}
loadProfile(upgradeTable, profileRef);
}
public void prepareUpgradeResources()
throws UnfullfilledRequirementsException,
UnresolvedResourceException, IllegalArgumentException,
InstallCancelledException {
ensureValidState();
// TODO: Figure out more cleanly what the acceptable states are here
int upgradeTableState = upgradeTable.getTableReadiness();
if (upgradeTableState == ResourceTable.RESOURCE_TABLE_UNCOMMITED ||
upgradeTableState == ResourceTable.RESOURCE_TABLE_UNSTAGED ||
upgradeTableState == ResourceTable.RESOURCE_TABLE_EMPTY) {
throw new IllegalArgumentException("Upgrade table is not in an appropriate state");
}
// Wipe out any existing records in the tempTable table. If there's
// _anything_ in there and the app isn't in the install state, that's a
// signal to recover.
tempTable.destroy();
// Fetch and prepare all resources (Likely exit point here if a
// resource can't be found)
upgradeTable.prepareResources(masterTable, this.platform);
}
public void upgrade() throws UnresolvedResourceException, IllegalArgumentException {
boolean upgradeSuccess = false;
try {
Logger.log("Resource", "Upgrade table fetched, beginning upgrade");
//Try to stage the upgrade table to replace the incoming table
if (!masterTable.upgradeTable(upgradeTable)) {
throw new RuntimeException("global table failed to upgrade!");
} else if (upgradeTable.getTableReadiness() != ResourceTable.RESOURCE_TABLE_INSTALLED) {
throw new RuntimeException("not all incoming resources were installed!!");
} else {
//otherwise keep going
Logger.log("Resource", "Global table unstaged, upgrade table ready");
}
// Now we basically want to replace the global resource table with
// the upgrade table
// ok, so temporary should now be fully installed. make a copy of
// our table just in case.
Logger.log("Resource", "Copying global resources to recovery area");
try {
masterTable.copyToTable(tempTable);
} catch (RuntimeException e) {
// The _only_ time the recovery table should have data is if we
// were in the middle of an install. Since global hasn't been
// modified if there is a problem here we want to wipe out the
// recovery stub
//TODO: If this fails? Oof.
tempTable.destroy();
throw e;
}
Logger.log("Resource", "Wiping global");
//now clear the global table to make room (but not the data, just the records)
masterTable.destroy();
Logger.log("Resource", "Moving update resources");
//Now copy the upgrade table to take its place
upgradeTable.copyToTable(masterTable);
//Success! The global table should be ready to go now.
upgradeSuccess = true;
Logger.log("Resource", "Upgrade Succesful!");
//Now we need to do cleanup. Wipe out the upgrade table and finalize
//removing the original resources which are no longer needed.
//Wipe the incoming (we need to do nothing with its resources)
Logger.log("Resource", "Wiping redundant update table");
upgradeTable.destroy();
//Uninstall old resources
Logger.log("Resource", "Clearing out old resources");
tempTable.flagForDeletions(masterTable);
tempTable.completeUninstall();
//good to go.
} finally {
if (!upgradeSuccess) {
repair();
}
// TODO PLM: how necessary is this?
platform.clearAppState();
//Is it really possible to verify that we've un-registered everything here? Locale files are
//registered elsewhere, and we can't guarantee we're the only thing in there, so we can't
//straight up clear it...
platform.initialize(masterTable);
}
}
/**
* This method is responsible for recovering the state of the application
* to installed after anything happens during an upgrade. After it is
* finished, the global resource table should be valid.
*
* NOTE: this does not currently repair resources which have been
* corrupted, merely returns all of the tables to the appropriate states
*/
private void repair() {
// First we need to figure out what state we're in currently. There are
// a few possibilities
// TODO: Handle: Upgrade complete (upgrade table empty, all resources
// pushed to global), recovery table not empty
// First possibility is needing to restore from the recovery table.
if (!tempTable.isEmpty()) {
// If the recovery table isn't empty, we're likely restoring from
// there. We need to check first whether the global table has the
// same profile, or the recovery table simply doesn't have one in
// which case the recovery table didn't get copied correctly.
if (tempTable.getResourceWithId(CommCarePlatform.APP_PROFILE_RESOURCE_ID) == null ||
(masterTable.getResourceWithId(CommCarePlatform.APP_PROFILE_RESOURCE_ID).getVersion() == tempTable.getResourceWithId(CommCarePlatform.APP_PROFILE_RESOURCE_ID).getVersion())) {
Logger.log("resource", "Invalid recovery table detected. Wiping recovery table");
// This means the recovery table should be empty. Invalid copy.
tempTable.destroy();
} else {
// We need to recover the global resources from the recovery
// table.
Logger.log("resource", "Recovering global resources from recovery table");
masterTable.destroy();
tempTable.copyToTable(masterTable);
Logger.log("resource", "Global resources recovered. Wiping recovery table");
tempTable.destroy();
}
}
// Global and incoming are now in the right places. Ensure we have no
// uncommitted resources.
if (masterTable.getTableReadiness() == ResourceTable.RESOURCE_TABLE_UNCOMMITED) {
masterTable.rollbackCommits();
}
if (upgradeTable.getTableReadiness() == ResourceTable.RESOURCE_TABLE_UNCOMMITED) {
upgradeTable.rollbackCommits();
}
// If the global table needed to be recovered from the recovery table,
// it has. There are now two states: Either the global table is fully
// installed (no conflicts with the upgrade table) or it has unstaged
// resources to restage
if (masterTable.getTableReadiness() == ResourceTable.RESOURCE_TABLE_INSTALLED) {
Logger.log("resource", "Global table in fully installed mode. Repair complete");
} else if (masterTable.getTableReadiness() == ResourceTable.RESOURCE_TABLE_UNSTAGED) {
Logger.log("resource", "Global table needs to restage some resources");
masterTable.repairTable(upgradeTable);
}
}
public static Vector<Resource> getResourceListFromProfile(ResourceTable master) {
Vector<Resource> unresolved = new Vector<Resource>();
Vector<Resource> resolved = new Vector<Resource>();
Resource r = master.getResourceWithId(CommCarePlatform.APP_PROFILE_RESOURCE_ID);
if (r == null) {
return resolved;
}
unresolved.addElement(r);
while (unresolved.size() > 0) {
Resource current = unresolved.firstElement();
unresolved.removeElement(current);
resolved.addElement(current);
Vector<Resource> children = master.getResourcesForParent(current.getRecordGuid());
for (Resource child : children) {
unresolved.addElement(child);
}
}
return resolved;
}
protected void loadProfile(ResourceTable incoming,
String profileRef)
throws UnfullfilledRequirementsException,
UnresolvedResourceException,
InstallCancelledException {
Vector<ResourceLocation> locations = new Vector<ResourceLocation>();
locations.addElement(new ResourceLocation(Resource.RESOURCE_AUTHORITY_REMOTE, profileRef));
Resource r = new Resource(Resource.RESOURCE_VERSION_UNKNOWN,
CommCarePlatform.APP_PROFILE_RESOURCE_ID, locations,
"Application Descriptor");
incoming.addResource(r,
incoming.getInstallers().getProfileInstaller(false),
null);
incoming.prepareResourcesUpTo(masterTable,
this.platform,
CommCarePlatform.APP_PROFILE_RESOURCE_ID);
}
/**
* @return Is the table non-empty, marked for upgrade, with all ready resources?
*/
public static boolean isTableStagedForUpgrade(ResourceTable table) {
return (table.getTableReadiness() == ResourceTable.RESOURCE_TABLE_UPGRADE &&
table.isReady() &&
!table.isEmpty());
}
public boolean isUpgradeTableStaged() {
return isTableStagedForUpgrade(upgradeTable);
}
protected void ensureValidState() {
if (masterTable.getTableReadiness() != ResourceTable.RESOURCE_TABLE_INSTALLED) {
repair();
if (masterTable.getTableReadiness() != ResourceTable.RESOURCE_TABLE_INSTALLED) {
throw new IllegalArgumentException("Global resource table was not ready for upgrading");
}
}
}
public boolean updateIsntNewer(Resource currentProfile) {
Resource newProfile =
upgradeTable.getResourceWithId(CommCarePlatform.APP_PROFILE_RESOURCE_ID);
return newProfile != null && !newProfile.isNewer(currentProfile);
}
public Resource getMasterProfile() {
return masterTable.getResourceWithId(CommCarePlatform.APP_PROFILE_RESOURCE_ID);
}
}
|
package org.openhab.binding.ecobee.internal.handler;
import static org.openhab.binding.ecobee.internal.EcobeeBindingConstants.*;
import java.lang.reflect.Field;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import javax.measure.Unit;
import org.apache.commons.lang.WordUtils;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
import org.openhab.binding.ecobee.internal.action.EcobeeActions;
import org.openhab.binding.ecobee.internal.api.EcobeeApi;
import org.openhab.binding.ecobee.internal.config.EcobeeThermostatConfiguration;
import org.openhab.binding.ecobee.internal.dto.SelectionDTO;
import org.openhab.binding.ecobee.internal.dto.thermostat.AlertDTO;
import org.openhab.binding.ecobee.internal.dto.thermostat.ClimateDTO;
import org.openhab.binding.ecobee.internal.dto.thermostat.EventDTO;
import org.openhab.binding.ecobee.internal.dto.thermostat.HouseDetailsDTO;
import org.openhab.binding.ecobee.internal.dto.thermostat.LocationDTO;
import org.openhab.binding.ecobee.internal.dto.thermostat.ManagementDTO;
import org.openhab.binding.ecobee.internal.dto.thermostat.ProgramDTO;
import org.openhab.binding.ecobee.internal.dto.thermostat.RemoteSensorDTO;
import org.openhab.binding.ecobee.internal.dto.thermostat.RuntimeDTO;
import org.openhab.binding.ecobee.internal.dto.thermostat.SettingsDTO;
import org.openhab.binding.ecobee.internal.dto.thermostat.TechnicianDTO;
import org.openhab.binding.ecobee.internal.dto.thermostat.ThermostatDTO;
import org.openhab.binding.ecobee.internal.dto.thermostat.ThermostatUpdateRequestDTO;
import org.openhab.binding.ecobee.internal.dto.thermostat.VersionDTO;
import org.openhab.binding.ecobee.internal.dto.thermostat.WeatherDTO;
import org.openhab.binding.ecobee.internal.dto.thermostat.WeatherForecastDTO;
import org.openhab.binding.ecobee.internal.function.AbstractFunction;
import org.openhab.binding.ecobee.internal.function.FunctionRequest;
import org.openhab.core.i18n.TimeZoneProvider;
import org.openhab.core.library.types.DecimalType;
import org.openhab.core.library.types.OnOffType;
import org.openhab.core.library.types.QuantityType;
import org.openhab.core.library.types.StringType;
import org.openhab.core.library.unit.ImperialUnits;
import org.openhab.core.library.unit.SIUnits;
import org.openhab.core.library.unit.Units;
import org.openhab.core.thing.Bridge;
import org.openhab.core.thing.Channel;
import org.openhab.core.thing.ChannelUID;
import org.openhab.core.thing.Thing;
import org.openhab.core.thing.ThingStatus;
import org.openhab.core.thing.ThingStatusDetail;
import org.openhab.core.thing.ThingStatusInfo;
import org.openhab.core.thing.binding.BaseBridgeHandler;
import org.openhab.core.thing.binding.ThingHandler;
import org.openhab.core.thing.binding.ThingHandlerService;
import org.openhab.core.thing.type.ChannelType;
import org.openhab.core.thing.type.ChannelTypeRegistry;
import org.openhab.core.thing.type.ChannelTypeUID;
import org.openhab.core.types.Command;
import org.openhab.core.types.RefreshType;
import org.openhab.core.types.State;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* The {@link EcobeeThermostatBridgeHandler} is the handler for an Ecobee thermostat.
*
* @author Mark Hilbush - Initial contribution
*/
@NonNullByDefault
public class EcobeeThermostatBridgeHandler extends BaseBridgeHandler {
private final Logger logger = LoggerFactory.getLogger(EcobeeThermostatBridgeHandler.class);
private TimeZoneProvider timeZoneProvider;
private ChannelTypeRegistry channelTypeRegistry;
private @NonNullByDefault({}) String thermostatId;
private final Map<String, EcobeeSensorThingHandler> sensorHandlers = new ConcurrentHashMap<>();
private @Nullable ThermostatDTO savedThermostat;
private @Nullable List<RemoteSensorDTO> savedSensors;
private List<String> validClimateRefs = new CopyOnWriteArrayList<>();
private Map<String, State> stateCache = new ConcurrentHashMap<>();
private Map<ChannelUID, Boolean> channelReadOnlyMap = new HashMap<>();
private Map<Integer, String> symbolMap = new HashMap<>();
private Map<Integer, String> skyMap = new HashMap<>();
public EcobeeThermostatBridgeHandler(Bridge bridge, TimeZoneProvider timeZoneProvider,
ChannelTypeRegistry channelTypeRegistry) {
super(bridge);
this.timeZoneProvider = timeZoneProvider;
this.channelTypeRegistry = channelTypeRegistry;
}
@Override
public void initialize() {
thermostatId = getConfigAs(EcobeeThermostatConfiguration.class).thermostatId;
logger.debug("ThermostatBridge: Initializing thermostat '{}'", thermostatId);
initializeWeatherMaps();
initializeReadOnlyChannels();
clearSavedState();
updateStatus(EcobeeUtils.isBridgeOnline(getBridge()) ? ThingStatus.ONLINE : ThingStatus.OFFLINE);
}
@Override
public void dispose() {
logger.debug("ThermostatBridge: Disposing thermostat '{}'", thermostatId);
}
@Override
public void childHandlerInitialized(ThingHandler sensorHandler, Thing sensorThing) {
String sensorId = (String) sensorThing.getConfiguration().get(CONFIG_SENSOR_ID);
sensorHandlers.put(sensorId, (EcobeeSensorThingHandler) sensorHandler);
logger.debug("ThermostatBridge: Saving sensor handler for {} with id {}", sensorThing.getUID(), sensorId);
}
@Override
public void childHandlerDisposed(ThingHandler sensorHandler, Thing sensorThing) {
String sensorId = (String) sensorThing.getConfiguration().get(CONFIG_SENSOR_ID);
sensorHandlers.remove(sensorId);
logger.debug("ThermostatBridge: Removing sensor handler for {} with id {}", sensorThing.getUID(), sensorId);
}
@Override
public void bridgeStatusChanged(ThingStatusInfo bridgeStatusInfo) {
if (bridgeStatusInfo.getStatus() == ThingStatus.ONLINE) {
updateStatus(ThingStatus.ONLINE);
} else {
updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.BRIDGE_OFFLINE);
}
}
@SuppressWarnings("null")
@Override
public void handleCommand(ChannelUID channelUID, Command command) {
if (command instanceof RefreshType) {
State state = stateCache.get(channelUID.getId());
if (state != null) {
updateState(channelUID.getId(), state);
}
return;
}
if (isChannelReadOnly(channelUID)) {
logger.debug("Can't apply command '{}' to '{}' because channel is readonly", command, channelUID.getId());
return;
}
scheduler.execute(() -> {
handleThermostatCommand(channelUID, command);
});
}
/**
* Called by the AccountBridgeHandler to create a Selection that
* includes only the Ecobee objects for which there's at least one
* item linked to one of that object's channels.
*
* @return Selection
*/
public SelectionDTO getSelection() {
final SelectionDTO selection = new SelectionDTO();
for (String group : CHANNEL_GROUPS) {
for (Channel channel : thing.getChannelsOfGroup(group)) {
if (isLinked(channel.getUID())) {
try {
Field field = selection.getClass().getField("include" + WordUtils.capitalize(group));
logger.trace("ThermostatBridge: Thermostat thing '{}' including object '{}' in selection",
thing.getUID(), field.getName());
field.set(selection, Boolean.TRUE);
break;
} catch (IllegalArgumentException | IllegalAccessException | NoSuchFieldException
| SecurityException e) {
logger.debug("ThermostatBridge: Exception setting selection for group '{}'", group, e);
}
}
}
}
return selection;
}
public List<RemoteSensorDTO> getSensors() {
List<RemoteSensorDTO> localSavedSensors = savedSensors;
return localSavedSensors == null ? EMPTY_SENSORS : localSavedSensors;
}
public @Nullable String getAlerts() {
ThermostatDTO thermostat = savedThermostat;
if (thermostat != null && thermostat.alerts != null) {
return EcobeeApi.getGson().toJson(thermostat.alerts);
}
return null;
}
public @Nullable String getEvents() {
ThermostatDTO thermostat = savedThermostat;
if (thermostat != null && thermostat.events != null) {
return EcobeeApi.getGson().toJson(thermostat.events);
}
return null;
}
public @Nullable String getClimates() {
ThermostatDTO thermostat = savedThermostat;
if (thermostat != null && thermostat.program != null && thermostat.program.climates != null) {
return EcobeeApi.getGson().toJson(thermostat.program.climates);
}
return null;
}
public boolean isValidClimateRef(String climateRef) {
return validClimateRefs.contains(climateRef);
}
public String getThermostatId() {
return thermostatId;
}
/*
* Called by EcobeeActions to perform a thermostat function
*/
public boolean actionPerformFunction(AbstractFunction function) {
logger.debug("ThermostatBridge: Perform function '{}' on thermostat {}", function.type, thermostatId);
SelectionDTO selection = new SelectionDTO();
selection.setThermostats(Collections.singleton(thermostatId));
FunctionRequest request = new FunctionRequest(selection);
request.functions = Collections.singletonList(function);
EcobeeAccountBridgeHandler handler = getBridgeHandler();
if (handler != null) {
return handler.performThermostatFunction(request);
}
return false;
}
@Override
public Collection<Class<? extends ThingHandlerService>> getServices() {
return Collections.singletonList(EcobeeActions.class);
}
public void updateChannels(ThermostatDTO thermostat) {
logger.debug("ThermostatBridge: Updating channels for thermostat id {}", thermostat.identifier);
savedThermostat = thermostat;
updateAlert(thermostat.alerts);
updateHouseDetails(thermostat.houseDetails);
updateInfo(thermostat);
updateEquipmentStatus(thermostat);
updateLocation(thermostat.location);
updateManagement(thermostat.management);
updateProgram(thermostat.program);
updateEvent(thermostat.events);
updateRemoteSensors(thermostat.remoteSensors);
updateRuntime(thermostat.runtime);
updateSettings(thermostat.settings);
updateTechnician(thermostat.technician);
updateVersion(thermostat.version);
updateWeather(thermostat.weather);
savedSensors = thermostat.remoteSensors;
}
private void handleThermostatCommand(ChannelUID channelUID, Command command) {
logger.debug("Got command '{}' for channel '{}' of thing '{}'", command, channelUID, getThing().getUID());
String channelId = channelUID.getIdWithoutGroup();
String groupId = channelUID.getGroupId();
if (groupId == null) {
logger.info("Can't handle command because channel's groupId is null");
return;
}
ThermostatDTO thermostat = new ThermostatDTO();
Field field;
try {
switch (groupId) {
case CHGRP_INFO:
field = thermostat.getClass().getField(channelId);
setField(field, thermostat, command);
break;
case CHGRP_SETTINGS:
SettingsDTO settings = new SettingsDTO();
field = settings.getClass().getField(channelId);
setField(field, settings, command);
thermostat.settings = settings;
break;
case CHGRP_LOCATION:
LocationDTO location = new LocationDTO();
field = location.getClass().getField(channelId);
setField(field, location, command);
thermostat.location = location;
break;
case CHGRP_HOUSE_DETAILS:
HouseDetailsDTO houseDetails = new HouseDetailsDTO();
field = houseDetails.getClass().getField(channelId);
setField(field, houseDetails, command);
thermostat.houseDetails = houseDetails;
break;
default:
// All other groups contain only read-only fields
return;
}
performThermostatUpdate(thermostat);
} catch (NoSuchFieldException | SecurityException e) {
logger.info("Unable to get field for '{}.{}'", groupId, channelId);
}
}
private void setField(Field field, Object object, Command command) {
logger.info("Setting field '{}.{}' to value '{}'", object.getClass().getSimpleName().toLowerCase(),
field.getName(), command);
Class<?> fieldClass = field.getType();
try {
boolean success = false;
if (String.class.isAssignableFrom(fieldClass)) {
if (command instanceof StringType) {
logger.debug("Set field of type String to value of StringType");
field.set(object, command.toString());
success = true;
}
} else if (Integer.class.isAssignableFrom(fieldClass)) {
if (command instanceof DecimalType) {
logger.debug("Set field of type Integer to value of DecimalType");
field.set(object, Integer.valueOf(((DecimalType) command).intValue()));
success = true;
} else if (command instanceof QuantityType) {
Unit<?> unit = ((QuantityType<?>) command).getUnit();
logger.debug("Set field of type Integer to value of QuantityType with unit {}", unit);
if (unit.equals(ImperialUnits.FAHRENHEIT) || unit.equals(SIUnits.CELSIUS)) {
QuantityType<?> quantity = ((QuantityType<?>) command).toUnit(ImperialUnits.FAHRENHEIT);
if (quantity != null) {
field.set(object, quantity.intValue() * 10);
success = true;
}
}
}
} else if (Boolean.class.isAssignableFrom(fieldClass)) {
if (command instanceof OnOffType) {
logger.debug("Set field of type Boolean to value of OnOffType");
field.set(object, command == OnOffType.ON);
success = true;
}
}
if (!success) {
logger.info("Don't know how to convert command of type '{}' to {}.{}",
command.getClass().getSimpleName(), object.getClass().getSimpleName(), field.getName());
}
} catch (IllegalArgumentException | IllegalAccessException e) {
logger.info("Unable to set field '{}.{}' to value '{}'", object.getClass().getSimpleName(), field.getName(),
command, e);
}
}
private void updateInfo(ThermostatDTO thermostat) {
final String grp = CHGRP_INFO + "
updateChannel(grp + CH_IDENTIFIER, EcobeeUtils.undefOrString(thermostat.identifier));
updateChannel(grp + CH_NAME, EcobeeUtils.undefOrString(thermostat.name));
updateChannel(grp + CH_THERMOSTAT_REV, EcobeeUtils.undefOrString(thermostat.thermostatRev));
updateChannel(grp + CH_IS_REGISTERED, EcobeeUtils.undefOrOnOff(thermostat.isRegistered));
updateChannel(grp + CH_MODEL_NUMBER, EcobeeUtils.undefOrString(thermostat.modelNumber));
updateChannel(grp + CH_BRAND, EcobeeUtils.undefOrString(thermostat.brand));
updateChannel(grp + CH_FEATURES, EcobeeUtils.undefOrString(thermostat.features));
updateChannel(grp + CH_LAST_MODIFIED, EcobeeUtils.undefOrDate(thermostat.lastModified, timeZoneProvider));
updateChannel(grp + CH_THERMOSTAT_TIME, EcobeeUtils.undefOrDate(thermostat.thermostatTime, timeZoneProvider));
}
private void updateEquipmentStatus(ThermostatDTO thermostat) {
final String grp = CHGRP_EQUIPMENT_STATUS + "
updateChannel(grp + CH_EQUIPMENT_STATUS, EcobeeUtils.undefOrString(thermostat.equipmentStatus));
}
private void updateRuntime(@Nullable RuntimeDTO runtime) {
if (runtime == null) {
return;
}
final String grp = CHGRP_RUNTIME + "
updateChannel(grp + CH_RUNTIME_REV, EcobeeUtils.undefOrString(runtime.runtimeRev));
updateChannel(grp + CH_CONNECTED, EcobeeUtils.undefOrOnOff(runtime.connected));
updateChannel(grp + CH_FIRST_CONNECTED, EcobeeUtils.undefOrDate(runtime.firstConnected, timeZoneProvider));
updateChannel(grp + CH_CONNECT_DATE_TIME, EcobeeUtils.undefOrDate(runtime.connectDateTime, timeZoneProvider));
updateChannel(grp + CH_DISCONNECT_DATE_TIME,
EcobeeUtils.undefOrDate(runtime.disconnectDateTime, timeZoneProvider));
updateChannel(grp + CH_RT_LAST_MODIFIED, EcobeeUtils.undefOrDate(runtime.lastModified, timeZoneProvider));
updateChannel(grp + CH_RT_LAST_STATUS_MODIFIED,
EcobeeUtils.undefOrDate(runtime.lastStatusModified, timeZoneProvider));
updateChannel(grp + CH_RUNTIME_DATE, EcobeeUtils.undefOrString(runtime.runtimeDate));
updateChannel(grp + CH_RUNTIME_INTERVAL, EcobeeUtils.undefOrDecimal(runtime.runtimeInterval));
updateChannel(grp + CH_ACTUAL_TEMPERATURE, EcobeeUtils.undefOrTemperature(runtime.actualTemperature));
updateChannel(grp + CH_ACTUAL_HUMIDITY, EcobeeUtils.undefOrQuantity(runtime.actualHumidity, Units.PERCENT));
updateChannel(grp + CH_RAW_TEMPERATURE, EcobeeUtils.undefOrTemperature(runtime.rawTemperature));
updateChannel(grp + CH_SHOW_ICON_MODE, EcobeeUtils.undefOrDecimal(runtime.showIconMode));
updateChannel(grp + CH_DESIRED_HEAT, EcobeeUtils.undefOrTemperature(runtime.desiredHeat));
updateChannel(grp + CH_DESIRED_COOL, EcobeeUtils.undefOrTemperature(runtime.desiredCool));
updateChannel(grp + CH_DESIRED_HUMIDITY, EcobeeUtils.undefOrQuantity(runtime.desiredHumidity, Units.PERCENT));
updateChannel(grp + CH_DESIRED_DEHUMIDITY,
EcobeeUtils.undefOrQuantity(runtime.desiredDehumidity, Units.PERCENT));
updateChannel(grp + CH_DESIRED_FAN_MODE, EcobeeUtils.undefOrString(runtime.desiredFanMode));
if (runtime.desiredHeatRange != null && runtime.desiredHeatRange.size() == 2) {
updateChannel(grp + CH_DESIRED_HEAT_RANGE_LOW,
EcobeeUtils.undefOrTemperature(runtime.desiredHeatRange.get(0)));
updateChannel(grp + CH_DESIRED_HEAT_RANGE_HIGH,
EcobeeUtils.undefOrTemperature(runtime.desiredHeatRange.get(1)));
}
if (runtime.desiredCoolRange != null && runtime.desiredCoolRange.size() == 2) {
updateChannel(grp + CH_DESIRED_COOL_RANGE_LOW,
EcobeeUtils.undefOrTemperature(runtime.desiredCoolRange.get(0)));
updateChannel(grp + CH_DESIRED_COOL_RANGE_HIGH,
EcobeeUtils.undefOrTemperature(runtime.desiredCoolRange.get(1)));
}
}
private void updateSettings(@Nullable SettingsDTO settings) {
if (settings == null) {
return;
}
final String grp = CHGRP_SETTINGS + "
updateChannel(grp + CH_HVAC_MODE, EcobeeUtils.undefOrString(settings.hvacMode));
updateChannel(grp + CH_LAST_SERVICE_DATE, EcobeeUtils.undefOrString(settings.lastServiceDate));
updateChannel(grp + CH_SERVICE_REMIND_ME, EcobeeUtils.undefOrOnOff(settings.serviceRemindMe));
updateChannel(grp + CH_MONTHS_BETWEEN_SERVICE, EcobeeUtils.undefOrDecimal(settings.monthsBetweenService));
updateChannel(grp + CH_REMIND_ME_DATE, EcobeeUtils.undefOrString(settings.remindMeDate));
updateChannel(grp + CH_VENT, EcobeeUtils.undefOrString(settings.vent));
updateChannel(grp + CH_VENTILATOR_MIN_ON_TIME, EcobeeUtils.undefOrDecimal(settings.ventilatorMinOnTime));
updateChannel(grp + CH_SERVICE_REMIND_TECHNICIAN, EcobeeUtils.undefOrOnOff(settings.serviceRemindTechnician));
updateChannel(grp + CH_EI_LOCATION, EcobeeUtils.undefOrString(settings.eiLocation));
updateChannel(grp + CH_COLD_TEMP_ALERT, EcobeeUtils.undefOrTemperature(settings.coldTempAlert));
updateChannel(grp + CH_COLD_TEMP_ALERT_ENABLED, EcobeeUtils.undefOrOnOff(settings.coldTempAlertEnabled));
updateChannel(grp + CH_HOT_TEMP_ALERT, EcobeeUtils.undefOrTemperature(settings.hotTempAlert));
updateChannel(grp + CH_HOT_TEMP_ALERT_ENABLED, EcobeeUtils.undefOrOnOff(settings.hotTempAlertEnabled));
updateChannel(grp + CH_COOL_STAGES, EcobeeUtils.undefOrDecimal(settings.coolStages));
updateChannel(grp + CH_HEAT_STAGES, EcobeeUtils.undefOrDecimal(settings.heatStages));
updateChannel(grp + CH_MAX_SET_BACK, EcobeeUtils.undefOrDecimal(settings.maxSetBack));
updateChannel(grp + CH_MAX_SET_FORWARD, EcobeeUtils.undefOrDecimal(settings.maxSetForward));
updateChannel(grp + CH_QUICK_SAVE_SET_BACK, EcobeeUtils.undefOrDecimal(settings.quickSaveSetBack));
updateChannel(grp + CH_QUICK_SAVE_SET_FORWARD, EcobeeUtils.undefOrDecimal(settings.quickSaveSetForward));
updateChannel(grp + CH_HAS_HEAT_PUMP, EcobeeUtils.undefOrOnOff(settings.hasHeatPump));
updateChannel(grp + CH_HAS_FORCED_AIR, EcobeeUtils.undefOrOnOff(settings.hasForcedAir));
updateChannel(grp + CH_HAS_BOILER, EcobeeUtils.undefOrOnOff(settings.hasBoiler));
updateChannel(grp + CH_HAS_HUMIDIFIER, EcobeeUtils.undefOrOnOff(settings.hasHumidifier));
updateChannel(grp + CH_HAS_ERV, EcobeeUtils.undefOrOnOff(settings.hasErv));
updateChannel(grp + CH_HAS_HRV, EcobeeUtils.undefOrOnOff(settings.hasHrv));
updateChannel(grp + CH_CONDENSATION_AVOID, EcobeeUtils.undefOrOnOff(settings.condensationAvoid));
updateChannel(grp + CH_USE_CELSIUS, EcobeeUtils.undefOrOnOff(settings.useCelsius));
updateChannel(grp + CH_USE_TIME_FORMAT_12, EcobeeUtils.undefOrOnOff(settings.useTimeFormat12));
updateChannel(grp + CH_LOCALE, EcobeeUtils.undefOrString(settings.locale));
updateChannel(grp + CH_HUMIDITY, EcobeeUtils.undefOrString(settings.humidity));
updateChannel(grp + CH_HUMIDIFIER_MODE, EcobeeUtils.undefOrString(settings.humidifierMode));
updateChannel(grp + CH_BACKLIGHT_ON_INTENSITY, EcobeeUtils.undefOrDecimal(settings.backlightOnIntensity));
updateChannel(grp + CH_BACKLIGHT_SLEEP_INTENSITY, EcobeeUtils.undefOrDecimal(settings.backlightSleepIntensity));
updateChannel(grp + CH_BACKLIGHT_OFF_TIME, EcobeeUtils.undefOrDecimal(settings.backlightOffTime));
updateChannel(grp + CH_SOUND_TICK_VOLUME, EcobeeUtils.undefOrDecimal(settings.soundTickVolume));
updateChannel(grp + CH_SOUND_ALERT_VOLUME, EcobeeUtils.undefOrDecimal(settings.soundAlertVolume));
updateChannel(grp + CH_COMPRESSOR_PROTECTION_MIN_TIME,
EcobeeUtils.undefOrDecimal(settings.compressorProtectionMinTime));
updateChannel(grp + CH_COMPRESSOR_PROTECTION_MIN_TEMP,
EcobeeUtils.undefOrTemperature(settings.compressorProtectionMinTemp));
updateChannel(grp + CH_STAGE1_HEATING_DIFFERENTIAL_TEMP,
EcobeeUtils.undefOrDecimal(settings.stage1HeatingDifferentialTemp));
updateChannel(grp + CH_STAGE1_COOLING_DIFFERENTIAL_TEMP,
EcobeeUtils.undefOrDecimal(settings.stage1CoolingDifferentialTemp));
updateChannel(grp + CH_STAGE1_HEATING_DISSIPATION_TIME,
EcobeeUtils.undefOrDecimal(settings.stage1HeatingDissipationTime));
updateChannel(grp + CH_STAGE1_COOLING_DISSIPATION_TIME,
EcobeeUtils.undefOrDecimal(settings.stage1CoolingDissipationTime));
updateChannel(grp + CH_HEAT_PUMP_REVERSAL_ON_COOL, EcobeeUtils.undefOrOnOff(settings.heatPumpReversalOnCool));
updateChannel(grp + CH_FAN_CONTROLLER_REQUIRED, EcobeeUtils.undefOrOnOff(settings.fanControlRequired));
updateChannel(grp + CH_FAN_MIN_ON_TIME, EcobeeUtils.undefOrDecimal(settings.fanMinOnTime));
updateChannel(grp + CH_HEAT_COOL_MIN_DELTA, EcobeeUtils.undefOrDecimal(settings.heatCoolMinDelta));
updateChannel(grp + CH_TEMP_CORRECTION, EcobeeUtils.undefOrDecimal(settings.tempCorrection));
updateChannel(grp + CH_HOLD_ACTION, EcobeeUtils.undefOrString(settings.holdAction));
updateChannel(grp + CH_HEAT_PUMP_GROUND_WATER, EcobeeUtils.undefOrOnOff(settings.heatPumpGroundWater));
updateChannel(grp + CH_HAS_ELECTRIC, EcobeeUtils.undefOrOnOff(settings.hasElectric));
updateChannel(grp + CH_HAS_DEHUMIDIFIER, EcobeeUtils.undefOrOnOff(settings.hasDehumidifier));
updateChannel(grp + CH_DEHUMIDIFIER_MODE, EcobeeUtils.undefOrString(settings.dehumidifierMode));
updateChannel(grp + CH_DEHUMIDIFIER_LEVEL, EcobeeUtils.undefOrDecimal(settings.dehumidifierLevel));
updateChannel(grp + CH_DEHUMIDIFY_WITH_AC, EcobeeUtils.undefOrOnOff(settings.dehumidifyWithAC));
updateChannel(grp + CH_DEHUMIDIFY_OVERCOOL_OFFSET,
EcobeeUtils.undefOrDecimal(settings.dehumidifyOvercoolOffset));
updateChannel(grp + CH_AUTO_HEAT_COOL_FEATURE_ENABLED,
EcobeeUtils.undefOrOnOff(settings.autoHeatCoolFeatureEnabled));
updateChannel(grp + CH_WIFI_OFFLINE_ALERT, EcobeeUtils.undefOrOnOff(settings.wifiOfflineAlert));
updateChannel(grp + CH_HEAT_MIN_TEMP, EcobeeUtils.undefOrTemperature(settings.heatMinTemp));
updateChannel(grp + CH_HEAT_MAX_TEMP, EcobeeUtils.undefOrTemperature(settings.heatMaxTemp));
updateChannel(grp + CH_COOL_MIN_TEMP, EcobeeUtils.undefOrTemperature(settings.coolMinTemp));
updateChannel(grp + CH_COOL_MAX_TEMP, EcobeeUtils.undefOrTemperature(settings.coolMaxTemp));
updateChannel(grp + CH_HEAT_RANGE_HIGH, EcobeeUtils.undefOrTemperature(settings.heatRangeHigh));
updateChannel(grp + CH_HEAT_RANGE_LOW, EcobeeUtils.undefOrTemperature(settings.heatRangeLow));
updateChannel(grp + CH_COOL_RANGE_HIGH, EcobeeUtils.undefOrTemperature(settings.coolRangeHigh));
updateChannel(grp + CH_COOL_RANGE_LOW, EcobeeUtils.undefOrTemperature(settings.coolRangeLow));
updateChannel(grp + CH_USER_ACCESS_CODE, EcobeeUtils.undefOrString(settings.userAccessCode));
updateChannel(grp + CH_USER_ACCESS_SETTING, EcobeeUtils.undefOrDecimal(settings.userAccessSetting));
updateChannel(grp + CH_AUX_RUNTIME_ALERT, EcobeeUtils.undefOrDecimal(settings.auxRuntimeAlert));
updateChannel(grp + CH_AUX_OUTDOOR_TEMP_ALERT, EcobeeUtils.undefOrTemperature(settings.auxOutdoorTempAlert));
updateChannel(grp + CH_AUX_MAX_OUTDOOR_TEMP, EcobeeUtils.undefOrTemperature(settings.auxMaxOutdoorTemp));
updateChannel(grp + CH_AUX_RUNTIME_ALERT_NOTIFY, EcobeeUtils.undefOrOnOff(settings.auxRuntimeAlertNotify));
updateChannel(grp + CH_AUX_OUTDOOR_TEMP_ALERT_NOTIFY,
EcobeeUtils.undefOrOnOff(settings.auxOutdoorTempAlertNotify));
updateChannel(grp + CH_AUX_RUNTIME_ALERT_NOTIFY_TECHNICIAN,
EcobeeUtils.undefOrOnOff(settings.auxRuntimeAlertNotifyTechnician));
updateChannel(grp + CH_AUX_OUTDOOR_TEMP_ALERT_NOTIFY_TECHNICIAN,
EcobeeUtils.undefOrOnOff(settings.auxOutdoorTempAlertNotifyTechnician));
updateChannel(grp + CH_DISABLE_PREHEATING, EcobeeUtils.undefOrOnOff(settings.disablePreHeating));
updateChannel(grp + CH_DISABLE_PRECOOLING, EcobeeUtils.undefOrOnOff(settings.disablePreCooling));
updateChannel(grp + CH_INSTALLER_CODE_REQUIRED, EcobeeUtils.undefOrOnOff(settings.installerCodeRequired));
updateChannel(grp + CH_DR_ACCEPT, EcobeeUtils.undefOrString(settings.drAccept));
updateChannel(grp + CH_IS_RENTAL_PROPERTY, EcobeeUtils.undefOrOnOff(settings.isRentalProperty));
updateChannel(grp + CH_USE_ZONE_CONTROLLER, EcobeeUtils.undefOrOnOff(settings.useZoneController));
updateChannel(grp + CH_RANDOM_START_DELAY_COOL, EcobeeUtils.undefOrDecimal(settings.randomStartDelayCool));
updateChannel(grp + CH_RANDOM_START_DELAY_HEAT, EcobeeUtils.undefOrDecimal(settings.randomStartDelayHeat));
updateChannel(grp + CH_HUMIDITY_HIGH_ALERT,
EcobeeUtils.undefOrQuantity(settings.humidityHighAlert, Units.PERCENT));
updateChannel(grp + CH_HUMIDITY_LOW_ALERT,
EcobeeUtils.undefOrQuantity(settings.humidityLowAlert, Units.PERCENT));
updateChannel(grp + CH_DISABLE_HEAT_PUMP_ALERTS, EcobeeUtils.undefOrOnOff(settings.disableHeatPumpAlerts));
updateChannel(grp + CH_DISABLE_ALERTS_ON_IDT, EcobeeUtils.undefOrOnOff(settings.disableAlertsOnIdt));
updateChannel(grp + CH_HUMIDITY_ALERT_NOTIFY, EcobeeUtils.undefOrOnOff(settings.humidityAlertNotify));
updateChannel(grp + CH_HUMIDITY_ALERT_NOTIFY_TECHNICIAN,
EcobeeUtils.undefOrOnOff(settings.humidityAlertNotifyTechnician));
updateChannel(grp + CH_TEMP_ALERT_NOTIFY, EcobeeUtils.undefOrOnOff(settings.tempAlertNotify));
updateChannel(grp + CH_TEMP_ALERT_NOTIFY_TECHNICIAN,
EcobeeUtils.undefOrOnOff(settings.tempAlertNotifyTechnician));
updateChannel(grp + CH_MONTHLY_ELECTRICITY_BILL_LIMIT,
EcobeeUtils.undefOrDecimal(settings.monthlyElectricityBillLimit));
updateChannel(grp + CH_ENABLE_ELECTRICITY_BILL_ALERT,
EcobeeUtils.undefOrOnOff(settings.enableElectricityBillAlert));
updateChannel(grp + CH_ENABLE_PROJECTED_ELECTRICITY_BILL_ALERT,
EcobeeUtils.undefOrOnOff(settings.enableProjectedElectricityBillAlert));
updateChannel(grp + CH_ELECTRICITY_BILLING_DAY_OF_MONTH,
EcobeeUtils.undefOrDecimal(settings.electricityBillingDayOfMonth));
updateChannel(grp + CH_ELECTRICITY_BILL_CYCLE_MONTHS,
EcobeeUtils.undefOrDecimal(settings.electricityBillCycleMonths));
updateChannel(grp + CH_ELECTRICITY_BILL_START_MONTH,
EcobeeUtils.undefOrDecimal(settings.electricityBillStartMonth));
updateChannel(grp + CH_VENTILATOR_MIN_ON_TIME_HOME,
EcobeeUtils.undefOrDecimal(settings.ventilatorMinOnTimeHome));
updateChannel(grp + CH_VENTILATOR_MIN_ON_TIME_AWAY,
EcobeeUtils.undefOrDecimal(settings.ventilatorMinOnTimeAway));
updateChannel(grp + CH_BACKLIGHT_OFF_DURING_SLEEP, EcobeeUtils.undefOrOnOff(settings.backlightOffDuringSleep));
updateChannel(grp + CH_AUTO_AWAY, EcobeeUtils.undefOrOnOff(settings.autoAway));
updateChannel(grp + CH_SMART_CIRCULATION, EcobeeUtils.undefOrOnOff(settings.smartCirculation));
updateChannel(grp + CH_FOLLOW_ME_COMFORT, EcobeeUtils.undefOrOnOff(settings.followMeComfort));
updateChannel(grp + CH_VENTILATOR_TYPE, EcobeeUtils.undefOrString(settings.ventilatorType));
updateChannel(grp + CH_IS_VENTILATOR_TIMER_ON, EcobeeUtils.undefOrOnOff(settings.isVentilatorTimerOn));
updateChannel(grp + CH_VENTILATOR_OFF_DATE_TIME, EcobeeUtils.undefOrString(settings.ventilatorOffDateTime));
updateChannel(grp + CH_HAS_UV_FILTER, EcobeeUtils.undefOrOnOff(settings.hasUVFilter));
updateChannel(grp + CH_COOLING_LOCKOUT, EcobeeUtils.undefOrOnOff(settings.coolingLockout));
updateChannel(grp + CH_VENTILATOR_FREE_COOLING, EcobeeUtils.undefOrOnOff(settings.ventilatorFreeCooling));
updateChannel(grp + CH_DEHUMIDIFY_WHEN_HEATING, EcobeeUtils.undefOrOnOff(settings.dehumidifyWhenHeating));
updateChannel(grp + CH_VENTILATOR_DEHUMIDIFY, EcobeeUtils.undefOrOnOff(settings.ventilatorDehumidify));
updateChannel(grp + CH_GROUP_REF, EcobeeUtils.undefOrString(settings.groupRef));
updateChannel(grp + CH_GROUP_NAME, EcobeeUtils.undefOrString(settings.groupName));
updateChannel(grp + CH_GROUP_SETTING, EcobeeUtils.undefOrDecimal(settings.groupSetting));
}
private void updateProgram(@Nullable ProgramDTO program) {
if (program == null) {
return;
}
final String grp = CHGRP_PROGRAM + "
updateChannel(grp + CH_PROGRAM_CURRENT_CLIMATE_REF, EcobeeUtils.undefOrString(program.currentClimateRef));
if (program.climates != null) {
saveValidClimateRefs(program.climates);
}
}
private void saveValidClimateRefs(List<ClimateDTO> climates) {
validClimateRefs.clear();
for (ClimateDTO climate : climates) {
validClimateRefs.add(climate.climateRef);
}
}
private void updateAlert(@Nullable List<AlertDTO> alerts) {
AlertDTO firstAlert;
if (alerts == null || alerts.isEmpty()) {
firstAlert = EMPTY_ALERT;
} else {
firstAlert = alerts.get(0);
}
final String grp = CHGRP_ALERT + "
updateChannel(grp + CH_ALERT_ACKNOWLEDGE_REF, EcobeeUtils.undefOrString(firstAlert.acknowledgeRef));
updateChannel(grp + CH_ALERT_DATE, EcobeeUtils.undefOrString(firstAlert.date));
updateChannel(grp + CH_ALERT_TIME, EcobeeUtils.undefOrString(firstAlert.time));
updateChannel(grp + CH_ALERT_SEVERITY, EcobeeUtils.undefOrString(firstAlert.severity));
updateChannel(grp + CH_ALERT_TEXT, EcobeeUtils.undefOrString(firstAlert.text));
updateChannel(grp + CH_ALERT_ALERT_NUMBER, EcobeeUtils.undefOrDecimal(firstAlert.alertNumber));
updateChannel(grp + CH_ALERT_ALERT_TYPE, EcobeeUtils.undefOrString(firstAlert.alertType));
updateChannel(grp + CH_ALERT_IS_OPERATOR_ALERT, EcobeeUtils.undefOrOnOff(firstAlert.isOperatorAlert));
updateChannel(grp + CH_ALERT_REMINDER, EcobeeUtils.undefOrString(firstAlert.reminder));
updateChannel(grp + CH_ALERT_SHOW_IDT, EcobeeUtils.undefOrOnOff(firstAlert.showIdt));
updateChannel(grp + CH_ALERT_SHOW_WEB, EcobeeUtils.undefOrOnOff(firstAlert.showWeb));
updateChannel(grp + CH_ALERT_SEND_EMAIL, EcobeeUtils.undefOrOnOff(firstAlert.sendEmail));
updateChannel(grp + CH_ALERT_ACKNOWLEDGEMENT, EcobeeUtils.undefOrString(firstAlert.acknowledgement));
updateChannel(grp + CH_ALERT_REMIND_ME_LATER, EcobeeUtils.undefOrOnOff(firstAlert.remindMeLater));
updateChannel(grp + CH_ALERT_THERMOSTAT_IDENTIFIER, EcobeeUtils.undefOrString(firstAlert.thermostatIdentifier));
updateChannel(grp + CH_ALERT_NOTIFICATION_TYPE, EcobeeUtils.undefOrString(firstAlert.notificationType));
}
private void updateEvent(@Nullable List<EventDTO> events) {
EventDTO runningEvent = EMPTY_EVENT;
if (events != null && !events.isEmpty()) {
for (EventDTO event : events) {
if (event.running) {
runningEvent = event;
break;
}
}
}
final String grp = CHGRP_EVENT + "
updateChannel(grp + CH_EVENT_NAME, EcobeeUtils.undefOrString(runningEvent.name));
updateChannel(grp + CH_EVENT_TYPE, EcobeeUtils.undefOrString(runningEvent.type));
updateChannel(grp + CH_EVENT_RUNNING, EcobeeUtils.undefOrOnOff(runningEvent.running));
updateChannel(grp + CH_EVENT_START_DATE, EcobeeUtils.undefOrString(runningEvent.startDate));
updateChannel(grp + CH_EVENT_START_TIME, EcobeeUtils.undefOrString(runningEvent.startTime));
updateChannel(grp + CH_EVENT_END_DATE, EcobeeUtils.undefOrString(runningEvent.endDate));
updateChannel(grp + CH_EVENT_END_TIME, EcobeeUtils.undefOrString(runningEvent.endTime));
updateChannel(grp + CH_EVENT_IS_OCCUPIED, EcobeeUtils.undefOrOnOff(runningEvent.isOccupied));
updateChannel(grp + CH_EVENT_IS_COOL_OFF, EcobeeUtils.undefOrOnOff(runningEvent.isCoolOff));
updateChannel(grp + CH_EVENT_IS_HEAT_OFF, EcobeeUtils.undefOrOnOff(runningEvent.isHeatOff));
updateChannel(grp + CH_EVENT_COOL_HOLD_TEMP, EcobeeUtils.undefOrTemperature(runningEvent.coolHoldTemp));
updateChannel(grp + CH_EVENT_HEAT_HOLD_TEMP, EcobeeUtils.undefOrTemperature(runningEvent.heatHoldTemp));
updateChannel(grp + CH_EVENT_FAN, EcobeeUtils.undefOrString(runningEvent.fan));
updateChannel(grp + CH_EVENT_VENT, EcobeeUtils.undefOrString(runningEvent.vent));
updateChannel(grp + CH_EVENT_VENTILATOR_MIN_ON_TIME,
EcobeeUtils.undefOrDecimal(runningEvent.ventilatorMinOnTime));
updateChannel(grp + CH_EVENT_IS_OPTIONAL, EcobeeUtils.undefOrOnOff(runningEvent.isOptional));
updateChannel(grp + CH_EVENT_IS_TEMPERATURE_RELATIVE,
EcobeeUtils.undefOrOnOff(runningEvent.isTemperatureRelative));
updateChannel(grp + CH_EVENT_COOL_RELATIVE_TEMP, EcobeeUtils.undefOrDecimal(runningEvent.coolRelativeTemp));
updateChannel(grp + CH_EVENT_HEAT_RELATIVE_TEMP, EcobeeUtils.undefOrDecimal(runningEvent.heatRelativeTemp));
updateChannel(grp + CH_EVENT_IS_TEMPERATURE_ABSOLUTE,
EcobeeUtils.undefOrOnOff(runningEvent.isTemperatureAbsolute));
updateChannel(grp + CH_EVENT_DUTY_CYCLE_PERCENTAGE,
EcobeeUtils.undefOrDecimal(runningEvent.dutyCyclePercentage));
updateChannel(grp + CH_EVENT_FAN_MIN_ON_TIME, EcobeeUtils.undefOrDecimal(runningEvent.fanMinOnTime));
updateChannel(grp + CH_EVENT_OCCUPIED_SENSOR_ACTIVE,
EcobeeUtils.undefOrOnOff(runningEvent.occupiedSensorActive));
updateChannel(grp + CH_EVENT_UNOCCUPIED_SENSOR_ACTIVE,
EcobeeUtils.undefOrOnOff(runningEvent.unoccupiedSensorActive));
updateChannel(grp + CH_EVENT_DR_RAMP_UP_TEMP, EcobeeUtils.undefOrDecimal(runningEvent.drRampUpTemp));
updateChannel(grp + CH_EVENT_DR_RAMP_UP_TIME, EcobeeUtils.undefOrDecimal(runningEvent.drRampUpTime));
updateChannel(grp + CH_EVENT_LINK_REF, EcobeeUtils.undefOrString(runningEvent.linkRef));
updateChannel(grp + CH_EVENT_HOLD_CLIMATE_REF, EcobeeUtils.undefOrString(runningEvent.holdClimateRef));
}
private void updateWeather(@Nullable WeatherDTO weather) {
if (weather == null || weather.forecasts == null) {
return;
}
final String weatherGrp = CHGRP_WEATHER + "
updateChannel(weatherGrp + CH_WEATHER_TIMESTAMP, EcobeeUtils.undefOrDate(weather.timestamp, timeZoneProvider));
updateChannel(weatherGrp + CH_WEATHER_WEATHER_STATION, EcobeeUtils.undefOrString(weather.weatherStation));
for (int index = 0; index < weather.forecasts.size(); index++) {
final String grp = CHGRP_FORECAST + String.format("%d", index) + "
WeatherForecastDTO forecast = weather.forecasts.get(index);
if (forecast != null) {
updateChannel(grp + CH_FORECAST_WEATHER_SYMBOL, EcobeeUtils.undefOrDecimal(forecast.weatherSymbol));
updateChannel(grp + CH_FORECAST_WEATHER_SYMBOL_TEXT,
EcobeeUtils.undefOrString(symbolMap.get(forecast.weatherSymbol)));
updateChannel(grp + CH_FORECAST_DATE_TIME,
EcobeeUtils.undefOrDate(forecast.dateTime, timeZoneProvider));
updateChannel(grp + CH_FORECAST_CONDITION, EcobeeUtils.undefOrString(forecast.condition));
updateChannel(grp + CH_FORECAST_TEMPERATURE, EcobeeUtils.undefOrTemperature(forecast.temperature));
updateChannel(grp + CH_FORECAST_PRESSURE,
EcobeeUtils.undefOrQuantity(forecast.pressure, Units.MILLIBAR));
updateChannel(grp + CH_FORECAST_RELATIVE_HUMIDITY,
EcobeeUtils.undefOrQuantity(forecast.relativeHumidity, Units.PERCENT));
updateChannel(grp + CH_FORECAST_DEWPOINT, EcobeeUtils.undefOrTemperature(forecast.dewpoint));
updateChannel(grp + CH_FORECAST_VISIBILITY,
EcobeeUtils.undefOrQuantity(forecast.visibility, SIUnits.METRE));
updateChannel(grp + CH_FORECAST_WIND_SPEED,
EcobeeUtils.undefOrQuantity(forecast.windSpeed, ImperialUnits.MILES_PER_HOUR));
updateChannel(grp + CH_FORECAST_WIND_GUST,
EcobeeUtils.undefOrQuantity(forecast.windGust, ImperialUnits.MILES_PER_HOUR));
updateChannel(grp + CH_FORECAST_WIND_DIRECTION, EcobeeUtils.undefOrString(forecast.windDirection));
updateChannel(grp + CH_FORECAST_WIND_BEARING,
EcobeeUtils.undefOrQuantity(forecast.windBearing, Units.DEGREE_ANGLE));
updateChannel(grp + CH_FORECAST_POP, EcobeeUtils.undefOrQuantity(forecast.pop, Units.PERCENT));
updateChannel(grp + CH_FORECAST_TEMP_HIGH, EcobeeUtils.undefOrTemperature(forecast.tempHigh));
updateChannel(grp + CH_FORECAST_TEMP_LOW, EcobeeUtils.undefOrTemperature(forecast.tempLow));
updateChannel(grp + CH_FORECAST_SKY, EcobeeUtils.undefOrDecimal(forecast.sky));
updateChannel(grp + CH_FORECAST_SKY_TEXT, EcobeeUtils.undefOrString(skyMap.get(forecast.sky)));
}
}
}
private void updateVersion(@Nullable VersionDTO version) {
if (version == null) {
return;
}
final String grp = CHGRP_VERSION + "
updateChannel(grp + CH_THERMOSTAT_FIRMWARE_VERSION,
EcobeeUtils.undefOrString(version.thermostatFirmwareVersion));
}
private void updateLocation(@Nullable LocationDTO loc) {
LocationDTO location = EMPTY_LOCATION;
if (loc != null) {
location = loc;
}
final String grp = CHGRP_LOCATION + "
updateChannel(grp + CH_TIME_ZONE_OFFSET_MINUTES, EcobeeUtils.undefOrDecimal(location.timeZoneOffsetMinutes));
updateChannel(grp + CH_TIME_ZONE, EcobeeUtils.undefOrString(location.timeZone));
updateChannel(grp + CH_IS_DAYLIGHT_SAVING, EcobeeUtils.undefOrOnOff(location.isDaylightSaving));
updateChannel(grp + CH_STREET_ADDRESS, EcobeeUtils.undefOrString(location.streetAddress));
updateChannel(grp + CH_CITY, EcobeeUtils.undefOrString(location.city));
updateChannel(grp + CH_PROVINCE_STATE, EcobeeUtils.undefOrString(location.provinceState));
updateChannel(grp + CH_COUNTRY, EcobeeUtils.undefOrString(location.country));
updateChannel(grp + CH_POSTAL_CODE, EcobeeUtils.undefOrString(location.postalCode));
updateChannel(grp + CH_PHONE_NUMBER, EcobeeUtils.undefOrString(location.phoneNumber));
updateChannel(grp + CH_MAP_COORDINATES, EcobeeUtils.undefOrPoint(location.mapCoordinates));
}
private void updateHouseDetails(@Nullable HouseDetailsDTO hd) {
HouseDetailsDTO houseDetails = EMPTY_HOUSEDETAILS;
if (hd != null) {
houseDetails = hd;
}
final String grp = CHGRP_HOUSE_DETAILS + "
updateChannel(grp + CH_HOUSEDETAILS_STYLE, EcobeeUtils.undefOrString(houseDetails.style));
updateChannel(grp + CH_HOUSEDETAILS_SIZE, EcobeeUtils.undefOrDecimal(houseDetails.size));
updateChannel(grp + CH_HOUSEDETAILS_NUMBER_OF_FLOORS, EcobeeUtils.undefOrDecimal(houseDetails.numberOfFloors));
updateChannel(grp + CH_HOUSEDETAILS_NUMBER_OF_ROOMS, EcobeeUtils.undefOrDecimal(houseDetails.numberOfRooms));
updateChannel(grp + CH_HOUSEDETAILS_NUMBER_OF_OCCUPANTS,
EcobeeUtils.undefOrDecimal(houseDetails.numberOfOccupants));
updateChannel(grp + CH_HOUSEDETAILS_AGE, EcobeeUtils.undefOrDecimal(houseDetails.age));
updateChannel(grp + CH_HOUSEDETAILS_WINDOW_EFFICIENCY,
EcobeeUtils.undefOrDecimal(houseDetails.windowEfficiency));
}
private void updateManagement(@Nullable ManagementDTO mgmt) {
ManagementDTO management = EMPTY_MANAGEMENT;
if (mgmt != null) {
management = mgmt;
}
final String grp = CHGRP_MANAGEMENT + "
updateChannel(grp + CH_MANAGEMENT_ADMIN_CONTACT, EcobeeUtils.undefOrString(management.administrativeContact));
updateChannel(grp + CH_MANAGEMENT_BILLING_CONTACT, EcobeeUtils.undefOrString(management.billingContact));
updateChannel(grp + CH_MANAGEMENT_NAME, EcobeeUtils.undefOrString(management.name));
updateChannel(grp + CH_MANAGEMENT_PHONE, EcobeeUtils.undefOrString(management.phone));
updateChannel(grp + CH_MANAGEMENT_EMAIL, EcobeeUtils.undefOrString(management.email));
updateChannel(grp + CH_MANAGEMENT_WEB, EcobeeUtils.undefOrString(management.web));
updateChannel(grp + CH_MANAGEMENT_SHOW_ALERT_IDT, EcobeeUtils.undefOrOnOff(management.showAlertIdt));
updateChannel(grp + CH_MANAGEMENT_SHOW_ALERT_WEB, EcobeeUtils.undefOrOnOff(management.showAlertWeb));
}
private void updateTechnician(@Nullable TechnicianDTO tech) {
TechnicianDTO technician = EMPTY_TECHNICIAN;
if (tech != null) {
technician = tech;
}
final String grp = CHGRP_TECHNICIAN + "
updateChannel(grp + CH_TECHNICIAN_CONTRACTOR_REF, EcobeeUtils.undefOrString(technician.contractorRef));
updateChannel(grp + CH_TECHNICIAN_NAME, EcobeeUtils.undefOrString(technician.name));
updateChannel(grp + CH_TECHNICIAN_PHONE, EcobeeUtils.undefOrString(technician.phone));
updateChannel(grp + CH_TECHNICIAN_STREET_ADDRESS, EcobeeUtils.undefOrString(technician.streetAddress));
updateChannel(grp + CH_TECHNICIAN_CITY, EcobeeUtils.undefOrString(technician.city));
updateChannel(grp + CH_TECHNICIAN_PROVINCE_STATE, EcobeeUtils.undefOrString(technician.provinceState));
updateChannel(grp + CH_TECHNICIAN_COUNTRY, EcobeeUtils.undefOrString(technician.country));
updateChannel(grp + CH_TECHNICIAN_POSTAL_CODE, EcobeeUtils.undefOrString(technician.postalCode));
updateChannel(grp + CH_TECHNICIAN_EMAIL, EcobeeUtils.undefOrString(technician.email));
updateChannel(grp + CH_TECHNICIAN_WEB, EcobeeUtils.undefOrString(technician.web));
}
private void updateChannel(String channelId, State state) {
updateState(channelId, state);
stateCache.put(channelId, state);
}
@SuppressWarnings("null")
private void updateRemoteSensors(@Nullable List<RemoteSensorDTO> remoteSensors) {
if (remoteSensors == null) {
return;
}
logger.debug("ThermostatBridge: Thermostat '{}' has {} remote sensors", thermostatId, remoteSensors.size());
for (RemoteSensorDTO sensor : remoteSensors) {
EcobeeSensorThingHandler handler = sensorHandlers.get(sensor.id);
if (handler != null) {
logger.debug("ThermostatBridge: Sending data to sensor handler '{}({})' of type '{}'", sensor.id,
sensor.name, sensor.type);
handler.updateChannels(sensor);
}
}
}
private void performThermostatUpdate(ThermostatDTO thermostat) {
SelectionDTO selection = new SelectionDTO();
selection.setThermostats(Collections.singleton(thermostatId));
ThermostatUpdateRequestDTO request = new ThermostatUpdateRequestDTO(selection);
request.thermostat = thermostat;
EcobeeAccountBridgeHandler handler = getBridgeHandler();
if (handler != null) {
handler.performThermostatUpdate(request);
}
}
private @Nullable EcobeeAccountBridgeHandler getBridgeHandler() {
EcobeeAccountBridgeHandler handler = null;
Bridge bridge = getBridge();
if (bridge != null) {
handler = (EcobeeAccountBridgeHandler) bridge.getHandler();
}
return handler;
}
@SuppressWarnings("null")
private boolean isChannelReadOnly(ChannelUID channelUID) {
Boolean isReadOnly = channelReadOnlyMap.get(channelUID);
return isReadOnly != null ? isReadOnly : true;
}
private void clearSavedState() {
savedThermostat = null;
savedSensors = null;
stateCache.clear();
}
private void initializeReadOnlyChannels() {
channelReadOnlyMap.clear();
for (Channel channel : thing.getChannels()) {
ChannelTypeUID channelTypeUID = channel.getChannelTypeUID();
if (channelTypeUID != null) {
ChannelType channelType = channelTypeRegistry.getChannelType(channelTypeUID, null);
if (channelType != null) {
channelReadOnlyMap.putIfAbsent(channel.getUID(), channelType.getState().isReadOnly());
}
}
}
}
private void initializeWeatherMaps() {
initializeSymbolMap();
initializeSkyMap();
}
private void initializeSymbolMap() {
symbolMap.clear();
symbolMap.put(-2, "NO SYMBOL");
symbolMap.put(0, "SUNNY");
symbolMap.put(1, "FEW CLOUDS");
symbolMap.put(2, "PARTLY CLOUDY");
symbolMap.put(3, "MOSTLY CLOUDY");
symbolMap.put(4, "OVERCAST");
symbolMap.put(5, "DRIZZLE");
symbolMap.put(6, "RAIN");
symbolMap.put(7, "FREEZING RAIN");
symbolMap.put(8, "SHOWERS");
symbolMap.put(9, "HAIL");
symbolMap.put(10, "SNOW");
symbolMap.put(11, "FLURRIES");
symbolMap.put(12, "FREEZING SNOW");
symbolMap.put(13, "BLIZZARD");
symbolMap.put(14, "PELLETS");
symbolMap.put(15, "THUNDERSTORM");
symbolMap.put(16, "WINDY");
symbolMap.put(17, "TORNADO");
symbolMap.put(18, "FOG");
symbolMap.put(19, "HAZE");
symbolMap.put(20, "SMOKE");
symbolMap.put(21, "DUST");
}
private void initializeSkyMap() {
skyMap.clear();
skyMap.put(1, "SUNNY");
skyMap.put(2, "CLEAR");
skyMap.put(3, "MOSTLY SUNNY");
skyMap.put(4, "MOSTLY CLEAR");
skyMap.put(5, "HAZY SUNSHINE");
skyMap.put(6, "HAZE");
skyMap.put(7, "PASSING CLOUDS");
skyMap.put(8, "MORE SUN THAN CLOUDS");
skyMap.put(9, "SCATTERED CLOUDS");
skyMap.put(10, "PARTLY CLOUDY");
skyMap.put(11, "A MIXTURE OF SUN AND CLOUDS");
skyMap.put(12, "HIGH LEVEL CLOUDS");
skyMap.put(13, "MORE CLOUDS THAN SUN");
skyMap.put(14, "PARTLY SUNNY");
skyMap.put(15, "BROKEN CLOUDS");
skyMap.put(16, "MOSTLY CLOUDY");
skyMap.put(17, "CLOUDY");
skyMap.put(18, "OVERCAST");
skyMap.put(19, "LOW CLOUDS");
skyMap.put(20, "LIGHT FOG");
skyMap.put(21, "FOG");
skyMap.put(22, "DENSE FOG");
skyMap.put(23, "ICE FOG");
skyMap.put(24, "SANDSTORM");
skyMap.put(25, "DUSTSTORM");
skyMap.put(26, "INCREASING CLOUDINESS");
skyMap.put(27, "DECREASING CLOUDINESS");
skyMap.put(28, "CLEARING SKIES");
skyMap.put(29, "BREAKS OF SUN LATE");
skyMap.put(30, "EARLY FOG FOLLOWED BY SUNNY SKIES");
skyMap.put(31, "AFTERNOON CLOUDS");
skyMap.put(32, "MORNING CLOUDS");
skyMap.put(33, "SMOKE");
skyMap.put(34, "LOW LEVEL HAZE");
}
}
|
package org.opendaylight.yangtools.sal.binding.generator.util;
import static com.google.common.base.Preconditions.checkNotNull;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.locks.Lock;
import com.google.common.base.Joiner;
import com.google.common.base.Optional;
public final class ClassLoaderUtils {
private ClassLoaderUtils() {
throw new UnsupportedOperationException("Utility class");
}
public static <V> V withClassLoader(final ClassLoader cls, final Callable<V> function) throws Exception {
checkNotNull(cls, "Classloader should not be null");
checkNotNull(function, "Function should not be null");
final ClassLoader oldCls = Thread.currentThread().getContextClassLoader();
try {
Thread.currentThread().setContextClassLoader(cls);
return function.call();
} finally {
Thread.currentThread().setContextClassLoader(oldCls);
}
}
public static <V> V withClassLoaderAndLock(final ClassLoader cls, final Lock lock, final Callable<V> function) throws Exception {
checkNotNull(lock, "Lock should not be null");
lock.lock();
try {
return withClassLoader(cls, function);
} finally {
lock.unlock();
}
}
/**
* @deprecated Use one of the other utility methods.
*/
@Deprecated
public static <V> V withClassLoaderAndLock(final ClassLoader cls, final Optional<Lock> lock, final Callable<V> function) throws Exception {
if (lock.isPresent()) {
return withClassLoaderAndLock(cls, lock.get(), function);
} else {
return withClassLoader(cls, function);
}
}
public static Object construct(final Constructor<? extends Object> constructor, final List<Object> objects)
throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
Object[] initargs = objects.toArray(new Object[] {});
return constructor.newInstance(initargs);
}
public static Class<?> loadClass(final ClassLoader cls, final String name) throws ClassNotFoundException {
if ("byte[]".equals(name)) {
return byte[].class;
} else if("char[]".equals(name)) {
return char[].class;
}
try {
return cls.loadClass(name);
} catch (ClassNotFoundException e) {
String[] components = name.split("\\.");
String potentialOuter;
int length = components.length;
if (length > 2 && (potentialOuter = components[length - 2]) != null && Character.isUpperCase(potentialOuter.charAt(0))) {
String outerName = Joiner.on(".").join(Arrays.asList(components).subList(0, length - 1));
String innerName = outerName + "$" + components[length-1];
return cls.loadClass(innerName);
} else {
throw e;
}
}
}
public static Class<?> loadClassWithTCCL(final String name) throws ClassNotFoundException {
return loadClass(Thread.currentThread().getContextClassLoader(), name);
}
public static Class<?> tryToLoadClassWithTCCL(final String fullyQualifiedName) {
try {
return loadClassWithTCCL(fullyQualifiedName);
} catch (ClassNotFoundException e) {
return null;
}
}
}
|
package fr.inria.jessy.benchmark.tpcc;
import fr.inria.jessy.Jessy;
import fr.inria.jessy.benchmark.tpcc.entities.*;
import fr.inria.jessy.transaction.*;
import java.util.*;
/**
* @author Wang Haiyun & ZHAO Guang
*
*/
public class InsertData extends Transaction {
/*tpcc section 4.3*/
public InsertData(Jessy jessy) throws Exception{
super(jessy);
}
@Override
public ExecutionHistory execute() {
try {
int i, j, k, l;
Random rand = new Random(System.currentTimeMillis());
String[] lastnames = {"BAR", "OUGHT", "ABLE", "PRI", "PRES", "ESE", "ANTI", "CALLY", "ATION", "EING"};
int[] randCustomerId = new int[3000]; // random permutation, used while creating Order table
for(i=0; i<3000; i++){
randCustomerId[i] = i;
}
for(i=0; i<3000; i++){
randCustomerId[i] = randCustomerId[rand.nextInt(3000)];
}
String lastname;
Warehouse wh;
Stock st;
District dis;
Customer cus;
Item it;
History hi;
Order or;
Order_line ol;
New_order no;
NURand nu;
/*for i warehouses*/
for(i=0; i<1; i++){
wh = new Warehouse("W_"+i);
wh.setW_ID(Integer.toString(i));
wh.setW_NAME(NString.generate(6, 10));
wh.setW_STREET_1(NString.generate(10, 20));
wh.setW_STREET_2(NString.generate(10, 20));
wh.setW_CITY(NString.generate(10, 20));
wh.setW_STATE(NString.generateFix(2));
wh.setW_ZIP(Integer.toString(rand.nextInt(9999 - 1) + 1)+"11111");
wh.setW_TAX(rand.nextFloat()*0.200);
wh.setW_YTD(300000.00);
create(wh);
/*each warehouse has 100,000 rows in the STOCK table*/
for(j=0; j<100000; j++){
st = new Stock("S_W_"+wh.getW_ID()+"S_I_"+j);
st.setS_I_ID(Integer.toString(j));
st.setS_W_ID(wh.getW_ID());
st.setS_QUANTITY(rand.nextInt(100-10)+10); //[10..100]
st.setS_DIST_01(NString.generateFix(24));
st.setS_DIST_02(NString.generateFix(24));
st.setS_DIST_03(NString.generateFix(24));
st.setS_DIST_04(NString.generateFix(24));
st.setS_DIST_05(NString.generateFix(24));
st.setS_DIST_06(NString.generateFix(24));
st.setS_DIST_07(NString.generateFix(24));
st.setS_DIST_08(NString.generateFix(24));
st.setS_DIST_09(NString.generateFix(24));
st.setS_DIST_10(NString.generateFix(24));
st.setS_YTD(0);
st.setS_ORDER_CNT(0);
st.setS_REMOTE_CNT(0);
if(rand.nextInt(10) == 0){ //10% chance putting "ORIGINAL" in S_DATA
st.setS_DATA(NString.original(26, 50));
}
else st.setS_DATA(NString.generate(26, 50));
create(st);
}
/*each warehouse has 10 district*/
for(j=0; i<10; i++){
dis = new District("D_W_"+i+"_D_"+j);
dis.setD_ID(Integer.toString(j));
dis.setD_W_ID(wh.getW_ID());
dis.setD_NAME(NString.generate(6, 10));
dis.setD_STREET_1(NString.generate(10, 20));
dis.setD_STREET_2(NString.generate(10, 20));
dis.setD_CITY(NString.generate(10, 20));
dis.setD_STATE(NString.generateFix(2));
dis.setD_ZIP(Integer.toString(rand.nextInt(10000))+"11111"); /*[0....9999]+111111*/
dis.setD_TAX(rand.nextFloat()*0.2000);
dis.setD_YTD(300000.00);
dis.setD_NEXT_O(3001);
create(dis);
/*each district has 3k customer*/
for(k=0; k<3000; k++){
cus=new Customer("C_W_"+i+"_C_D_"+j+"_C_"+k);
cus.setC_ID(Integer.toString(k));
cus.setC_D_ID(dis.getD_ID());
cus.setC_W_ID(wh.getW_ID());
if(k<1000){//first 1000 customers
lastname = "";
for(l=0; l<3; l++){
lastname = lastname+lastnames[rand.nextInt(10)];
}
cus.setC_LAST(lastname);
}
else{
nu = new NURand(255, 0, 999);
cus.setC_LAST(Integer.toString(nu.calculate()));
}
cus.setC_MIDDLE("OE");
cus.setC_FIRST(NString.generate(8, 16));
cus.setC_STREET_1(NString.generate(10, 20));
cus.setC_STREET_2(NString.generate(10, 20));
cus.setC_CITY(NString.generate(10, 20));
cus.setC_STATE(NString.generateFix(2));
cus.setC_ZIP(Integer.toString(rand.nextInt(10000))+"11111"); /*[0....9999]+111111*/
cus.setC_PHONE(NString.generateFix(16));
cus.setC_SINCE(new Date());
if(rand.nextInt(10) == 0){
/* 10% chance */
cus.setC_Credit("BC");
}
else cus.setC_Credit("GC");
cus.setC_CREDIT_LIM(50000.00);
cus.setC_DISCOUNT(rand.nextFloat()*0.5000);
cus.setC_BALANCE(-10.00);
cus.setC_YTD_PAYMENT(10.00);
cus.setC_PAYMENT_CNT(1);
cus.setC_DELIVERY_CNT(0);
cus.setC_DATA(NString.generate(300, 500));
create(cus);
//each customer has 1 history
hi = new History("H_C_W_"+wh.getW_ID()+"_H_C_D_"+dis.getD_ID()+"_H_C_"+cus.getC_ID());
hi.setH_C_W_ID(wh.getW_ID());
hi.setH_C_D_ID(dis.getD_ID());
hi.setH_C_ID(cus.getC_ID());
hi.setH_DATE(new Date());
hi.setH_AMOUNT(10.00);
hi.setH_DATA(NString.generate(12, 24));
create(hi);
}
/*each district has 3000 order*/
for(k=0; k< 3000; k++){
or = new Order("O_W_"+wh.getW_ID()+"_O_D_"+dis.getD_ID()+"_O_"+k);
or.setO_C_ID(Integer.toString(randCustomerId[k]));
or.setO_W_ID(wh.getW_ID());
or.setO_D_ID(dis.getD_ID());
or.setO_ENTRY_D(new Date());
if(k<2101)
or.setO_CARRIER_ID(Integer.toString(rand.nextInt(10)+1));
else or.setO_CARRIER_ID(null);
or.setO_OL_CNT(rand.nextInt(15-5)+5); //[5 .. 15]
or.setO_ALL_LOCAL(1);
create(or);
/*each order has o_ol_cnt order_lines*/
for(l=0; l< or.getO_OL_CNT(); l++){
ol = new Order_line("OL_W_"+wh.getW_ID()+"_OL_D_"+dis.getD_ID()+"_OL_O_"+or.getO_ID()+"_OL_"+l);
ol.setOL_W_ID(wh.getW_ID());
ol.setOL_D_ID(dis.getD_ID());
ol.setOL_O_ID(or.getO_ID());
ol.setOL_NUMBER(Integer.toString(l));
ol.setOL_I_ID(Integer.toString(rand.nextInt(100000)+1)); //[1..100000]
ol.setOL_SUPPLY_W_ID(wh.getW_ID());
if(l < 2101){
ol.setOL_DELIVERY_D(or.getO_ENTRY_D());
ol.setOL_AMOUNT(0.00);
}
else{
ol.setOL_DELIVERY_D(null);
ol.setOL_AMOUNT(rand.nextFloat()*9999.99); //[0.01 .. 9999.99]
}
ol.setOL_QUANTITY(5);
ol.setOL_DIST_INFO(NString.generateFix(24));
create(ol);
}
}
/*each district has 900 new_order*/
for(k=0; k< 900; k++){
no = new New_order("NO_W_"+wh.getW_ID()+"_NO_D_"+dis.getD_ID()+"_NO_O_"+2101+k);
no.setNO_W_ID(wh.getW_ID());
no.setNO_D_ID(dis.getD_ID());
no.setNO_O_ID(2101+k);
create(no);
}
}
}
/*for whole system, we have 100k different types of item*/
for(i=0; i<100000; i++){
it = new Item("I_"+i);
it.setI_ID(Integer.toString(i));
it.setI_IM_ID(Integer.toString(rand.nextInt(10000)+1)); //[1..10000]
it.setI_NAME(NString.generate(14, 24));
it.setI_PRICE(rand.nextFloat()*100.00);//[1.00 .. 100.00]
if(rand.nextInt(10) == 0){ //10% chance putting "ORIGINAL" in I_DATA
it.setI_DATA(NString.original(26, 50));
}
else it.setI_DATA(NString.generate(26, 50));
create(it);
}
return commitTransaction();
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
}
|
package org.hisp.dhis.android.testapp.fileresource;
import android.content.Context;
import androidx.test.InstrumentationRegistry;
import org.apache.commons.io.FileUtils;
import org.hisp.dhis.android.core.common.BaseIdentifiableObject;
import org.hisp.dhis.android.core.common.State;
import org.hisp.dhis.android.core.data.fileresource.RandomGeneratedInputStream;
import org.hisp.dhis.android.core.fileresource.FileResource;
import org.hisp.dhis.android.core.fileresource.FileResourceTableInfo;
import org.hisp.dhis.android.core.fileresource.internal.FileResourceUtil;
import org.hisp.dhis.android.core.maintenance.D2Error;
import org.hisp.dhis.android.core.utils.integration.mock.BaseMockIntegrationTestFullDispatcher;
import org.hisp.dhis.android.core.utils.runner.D2JunitRunner;
import org.hisp.dhis.android.core.wipe.internal.TableWiper;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.util.Date;
import java.util.List;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
@RunWith(D2JunitRunner.class)
public class FileResourceCollectionRepositoryMockIntegrationShould extends BaseMockIntegrationTestFullDispatcher {
@Test
public void find_all() throws D2Error, IOException {
cleanFileResources();
d2.fileResourceModule().fileResources.blockingAdd(getFile());
List<FileResource> fileResources =
d2.fileResourceModule().fileResources
.blockingGet();
assertThat(fileResources.size(), is(1));
}
@Test
public void filter_by_uid() throws D2Error, IOException {
cleanFileResources();
String fileUid = d2.fileResourceModule().fileResources.blockingAdd(getFile());
List<FileResource> fileResources =
d2.fileResourceModule().fileResources
.byUid().eq(fileUid)
.blockingGet();
assertThat(fileResources.size(), is(1));
}
@Test
public void filter_by_name() throws D2Error, IOException {
cleanFileResources();
String fileUid = d2.fileResourceModule().fileResources.blockingAdd(getFile());
List<FileResource> fileResources =
d2.fileResourceModule().fileResources
.byName().eq(fileUid+ ".png")
.blockingGet();
assertThat(fileResources.size(), is(1));
}
@Test
public void filter_by_last_updated() throws D2Error, IOException, ParseException {
cleanFileResources();
String BEFORE_DATE = "2007-12-24T12:24:25.203";
Date created = BaseIdentifiableObject.DATE_FORMAT.parse(BEFORE_DATE);
d2.fileResourceModule().fileResources.blockingAdd(getFile());
List<FileResource> fileResources =
d2.fileResourceModule().fileResources
.byLastUpdated().after(created)
.blockingGet();
assertThat(fileResources.size(), is(1));
}
@Test
public void filter_by_content_type() throws D2Error, IOException {
cleanFileResources();
d2.fileResourceModule().fileResources.blockingAdd(getFile());
List<FileResource> fileResources =
d2.fileResourceModule().fileResources
.byContentType().eq("image/png")
.blockingGet();
assertThat(fileResources.size(), is(1));
}
@Test
public void filter_by_path() throws D2Error, IOException {
cleanFileResources();
d2.fileResourceModule().fileResources.blockingAdd(getFile());
List<FileResource> fileResources =
d2.fileResourceModule().fileResources
.byPath().like("%files/sdk_resources%")
.blockingGet();
assertThat(fileResources.size(), is(1));
}
@Test
public void filter_by_state() throws D2Error, IOException {
cleanFileResources();
d2.fileResourceModule().fileResources.blockingAdd(getFile());
List<FileResource> fileResources =
d2.fileResourceModule().fileResources
.byState().eq(State.TO_POST)
.blockingGet();
assertThat(fileResources.size(), is(1));
}
@Test
public void filter_by_content_length() throws D2Error, IOException {
cleanFileResources();
d2.fileResourceModule().fileResources.blockingAdd(getFile());
List<FileResource> fileResources =
d2.fileResourceModule().fileResources
.byContentLength().eq(1024L)
.blockingGet();
assertThat(fileResources.size(), is(1));
}
@Test
public void add_fileResources_to_the_repository() throws D2Error, IOException {
cleanFileResources();
List<FileResource> fileResources1 = d2.fileResourceModule().fileResources.blockingGet();
assertThat(fileResources1.size(), is(0));
File file = getFile();
assertThat(file.exists(), is(true));
String fileResourceUid = d2.fileResourceModule().fileResources.blockingAdd(file);
List<FileResource> fileResources2 = d2.fileResourceModule().fileResources.blockingGet();
assertThat(fileResources2.size(), is(1));
FileResource fileResource = d2.fileResourceModule().fileResources.uid(fileResourceUid).blockingGet();
assertThat(fileResource.uid(), is(fileResourceUid));
File savedFile = new File(fileResource.path(), fileResource.uid() + ".png");
assertThat(savedFile.exists(), is(true));
}
private File getFile() {
InputStream inputStream = new RandomGeneratedInputStream(1024);
Context context = InstrumentationRegistry.getTargetContext().getApplicationContext();
File destinationFile = new File(FileResourceUtil.getFileResourceDirectory(context), "file1.png");
return FileResourceUtil.writeInputStream(inputStream, destinationFile, 1024);
}
private void cleanFileResources() throws IOException {
Context context = InstrumentationRegistry.getTargetContext().getApplicationContext();
FileUtils.cleanDirectory(FileResourceUtil.getFileResourceDirectory(context));
new TableWiper(databaseAdapter).wipeTable(FileResourceTableInfo.TABLE_INFO);
}
}
|
package net.safedata.spring.data.jdbc.config;
import net.safedata.spring.data.jdbc.domain.entity.AbstractEntity;
import net.safedata.spring.data.jdbc.domain.entity.Product;
import net.safedata.spring.data.jdbc.domain.entity.Section;
import net.safedata.spring.data.jdbc.domain.repository.ProductRepository;
import net.safedata.spring.data.jdbc.domain.repository.SectionRepository;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jdbc.repository.config.AbstractJdbcConfiguration;
import org.springframework.data.jdbc.repository.config.EnableJdbcRepositories;
import org.springframework.data.relational.core.mapping.event.BeforeSaveEvent;
import java.util.concurrent.atomic.AtomicInteger;
@Configuration
@EnableJdbcRepositories(basePackages = "net.safedata.spring.data.jdbc.domain.repository")
public class PersistenceConfig extends AbstractJdbcConfiguration {
private static final AtomicInteger PK_GENERATOR = new AtomicInteger(0);
@Bean
public ApplicationListener<BeforeSaveEvent> idSetting() {
return event -> {
final AbstractEntity abstractEntity = (AbstractEntity) event.getEntity();
abstractEntity.setId(PK_GENERATOR.incrementAndGet());
};
}
@Bean
public ApplicationRunner applicationRunner(final ProductRepository productRepository,
final SectionRepository sectionRepository) {
return args -> {
final Section savedSection = sectionRepository.save(new Section("Electronics"));
System.out.println("The saved section is '" + savedSection + "'");
sectionRepository.findById(savedSection.getId())
.ifPresent(System.out::println);
System.out.println();
final Product tablet = new Product("Tablet", 200d);
final Product savedTablet = productRepository.save(tablet);
System.out.println("The saved product is '" + savedTablet + "'");
productRepository.findById(tablet.getId())
.ifPresent(System.out::println);
};
}
}
|
package org.deegree.securityproxy.wms.authorization;
import static org.deegree.securityproxy.wms.request.WmsRequestParser.GETCAPABILITIES;
import static org.deegree.securityproxy.wms.request.WmsRequestParser.GETFEATUREINFO;
import static org.deegree.securityproxy.wms.request.WmsRequestParser.GETMAP;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import org.deegree.securityproxy.authentication.ows.domain.LimitedOwsServiceVersion;
import org.deegree.securityproxy.authentication.ows.raster.RasterPermission;
import org.deegree.securityproxy.authorization.RequestAuthorizationManager;
import org.deegree.securityproxy.authorization.logging.AuthorizationReport;
import org.deegree.securityproxy.request.OwsRequest;
import org.deegree.securityproxy.request.OwsServiceVersion;
import org.deegree.securityproxy.wms.request.WmsRequest;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
public class WmsRequestAuthorizationManager implements RequestAuthorizationManager {
public static final boolean AUTHORIZED = true;
private static final String NOT_AUTHENTICATED_ERROR_MSG = "Error while retrieving authentication! "
+ "User could not be authenticated.";
private static final String ACCESS_GRANTED_MSG = "Access granted.";
private static final String UNKNOWN_ERROR_MSG = "Unknown error. See application log for details.";
private static final String GETFEATUREINFO_UNAUTHORIZED_MSG = "User not permitted to perform operation "
+ "GetFeatureInfo with the given parameters";
public static final String GETMAP_UNAUTHORIZED_MSG = "User not permitted to perform operation GetMap "
+ "with the given parameters";
public static final String GETCAPABILITIES_UNAUTHORIZED_MSG = "User not permitted to perform operation "
+ "GetCapabilities with the given parameters";
@Override
public AuthorizationReport decide( Authentication authentication, OwsRequest request ) {
if ( !checkAuthentication( authentication ) ) {
return new AuthorizationReport( NOT_AUTHENTICATED_ERROR_MSG );
}
Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
WmsRequest wmsRequest = (WmsRequest) request;
if ( isGetMapRequest( wmsRequest ) ) {
return authorizeGetMap( wmsRequest, authorities );
} else if ( isGetFeatureInfoRequest( wmsRequest ) ) {
return authorizeGetFeatureInfo( wmsRequest, authorities );
} else if ( isGetCapabilitiesRequest( wmsRequest ) ) {
return authorizeGetCapabilities( wmsRequest, authorities );
}
return new AuthorizationReport( UNKNOWN_ERROR_MSG );
}
private boolean checkAuthentication( Authentication authentication ) {
return !( authentication instanceof AnonymousAuthenticationToken );
}
@Override
public boolean supports( Class<?> clazz ) {
return WmsRequest.class.equals( clazz );
}
private AuthorizationReport authorizeGetFeatureInfo( WmsRequest wmsRequest,
Collection<? extends GrantedAuthority> authorities ) {
List<String> grantedLayers = new ArrayList<String>();
String internalServiceUrl = null;
Map<String, String[]> additionalKeyValuePairs = null;
for ( GrantedAuthority authority : authorities ) {
if ( authority instanceof RasterPermission ) {
RasterPermission wmsPermission = (RasterPermission) authority;
if ( areOwsParamsAuthorized( wmsRequest, wmsPermission ) ) {
grantedLayers.add( wmsPermission.getLayerName() );
// If there are data inconsistencies and a service-name is mapped to different internal-urls, the
internalServiceUrl = wmsPermission.getInternalServiceUrl();
additionalKeyValuePairs = wmsPermission.getAdditionalKeyValuePairs();
}
}
}
for ( String layerName : wmsRequest.getLayerNames() ) {
if ( !grantedLayers.contains( layerName ) )
return new AuthorizationReport( GETFEATUREINFO_UNAUTHORIZED_MSG );
}
return new AuthorizationReport( ACCESS_GRANTED_MSG, AUTHORIZED, internalServiceUrl, additionalKeyValuePairs );
}
private AuthorizationReport authorizeGetMap( WmsRequest wmsRequest,
Collection<? extends GrantedAuthority> authorities ) {
for ( GrantedAuthority authority : authorities ) {
if ( authority instanceof RasterPermission ) {
RasterPermission wmsPermission = (RasterPermission) authority;
if ( isFirstLayerNameAuthorized( wmsRequest, wmsPermission )
&& areOwsParamsAuthorized( wmsRequest, wmsPermission ) ) {
return createAuthorizedReport( wmsPermission );
}
}
}
return new AuthorizationReport( GETMAP_UNAUTHORIZED_MSG );
}
private AuthorizationReport authorizeGetCapabilities( WmsRequest wmsRequest,
Collection<? extends GrantedAuthority> authorities ) {
for ( GrantedAuthority authority : authorities ) {
if ( authority instanceof RasterPermission ) {
RasterPermission wmsPermission = (RasterPermission) authority;
if ( areOwsParamsAuthorized( wmsRequest, wmsPermission ) ) {
return createAuthorizedReport( wmsPermission );
}
}
}
return new AuthorizationReport( GETCAPABILITIES_UNAUTHORIZED_MSG );
}
private AuthorizationReport createAuthorizedReport( RasterPermission wmsPermission ) {
String internalServiceUrl = wmsPermission.getInternalServiceUrl();
Map<String, String[]> additionalKVPs = wmsPermission.getAdditionalKeyValuePairs();
return new AuthorizationReport( ACCESS_GRANTED_MSG, AUTHORIZED, internalServiceUrl, additionalKVPs );
}
private boolean areOwsParamsAuthorized( WmsRequest wmsRequest, RasterPermission wmsPermission ) {
return isOperationTypeAuthorized( wmsRequest, wmsPermission )
&& isServiceVersionAuthorized( wmsRequest, wmsPermission )
&& isServiceNameAuthorized( wmsRequest, wmsPermission );
}
private boolean isGetFeatureInfoRequest( WmsRequest wmsRequest ) {
return GETFEATUREINFO.equals( wmsRequest.getOperationType() );
}
private boolean isGetMapRequest( WmsRequest wmsRequest ) {
return GETMAP.equals( wmsRequest.getOperationType() );
}
private boolean isGetCapabilitiesRequest( WmsRequest wmsRequest ) {
return GETCAPABILITIES.equals( wmsRequest.getOperationType() );
}
private boolean isOperationTypeAuthorized( WmsRequest wmsRequest, RasterPermission wmsPermission ) {
return wmsRequest.getOperationType() != null
&& wmsRequest.getOperationType().equalsIgnoreCase( wmsPermission.getOperationType() );
}
private boolean isServiceVersionAuthorized( WmsRequest wmsRequest, RasterPermission wmsPermission ) {
OwsServiceVersion requestedServiceVersion = wmsRequest.getServiceVersion();
if ( requestedServiceVersion == null )
return false;
LimitedOwsServiceVersion serviceVersionLimit = wmsPermission.getServiceVersion();
return serviceVersionLimit.contains( requestedServiceVersion );
}
private boolean isFirstLayerNameAuthorized( WmsRequest wmsRequest, RasterPermission wmsPermission ) {
if ( !wmsRequest.getLayerNames().isEmpty() ) {
String firstLayer = wmsRequest.getLayerNames().get( 0 );
return firstLayer.equals( wmsPermission.getLayerName() );
}
return false;
}
private boolean isServiceNameAuthorized( WmsRequest wmsRequest, RasterPermission wmsPermission ) {
return wmsRequest.getServiceName() != null
&& wmsRequest.getServiceName().equals( wmsPermission.getServiceName() );
}
}
|
package org.eclipse.birt.report.engine.emitter.html;
import org.eclipse.birt.report.engine.content.ICellContent;
import org.eclipse.birt.report.engine.content.IColumn;
import org.eclipse.birt.report.engine.content.IContainerContent;
import org.eclipse.birt.report.engine.content.IForeignContent;
import org.eclipse.birt.report.engine.content.IImageContent;
import org.eclipse.birt.report.engine.content.IRowContent;
import org.eclipse.birt.report.engine.content.IStyle;
import org.eclipse.birt.report.engine.content.ITableContent;
import org.eclipse.birt.report.engine.content.ITextContent;
import org.eclipse.birt.report.engine.emitter.HTMLTags;
import org.eclipse.birt.report.engine.emitter.HTMLWriter;
import org.eclipse.birt.report.engine.emitter.html.util.HTMLEmitterUtil;
import org.eclipse.birt.report.engine.ir.DimensionType;
import org.w3c.dom.css.CSSValue;
public class HTMLPerformanceOptimize extends HTMLEmitter
{
public HTMLPerformanceOptimize( HTMLReportEmitter reportEmitter,
HTMLWriter writer, boolean fixedReport, boolean enableInlineStyle,
int browserVersion )
{
super( reportEmitter,
writer,
fixedReport,
enableInlineStyle,
browserVersion );
}
/**
* Build the report default style
*/
public void buildDefaultStyle( StringBuffer styleBuffer, IStyle style )
{
if ( style == null || style.isEmpty( ) )
{
return;
}
AttributeBuilder.buildFont( styleBuffer, style );
AttributeBuilder.buildText( styleBuffer, style );
AttributeBuilder.buildVisual( styleBuffer, style );
AttributeBuilder.buildTextDecoration( styleBuffer, style );
// bidi_hcg start
// Build direction.
AttributeBuilder.buildBidiDirection( styleBuffer, style );
// bidi_hcg end
// Build the textAlign
String value = style.getTextAlign( );
if ( null != value )
{
styleBuffer.append( " text-align:" );
styleBuffer.append( value );
styleBuffer.append( ";" );
}
}
/**
* Build attribute class
*/
public void buildStyle( StringBuffer styleBuffer, IStyle style )
{
if ( style == null || style.isEmpty( ) )
{
return;
}
AttributeBuilder.buildFont( styleBuffer, style );
AttributeBuilder.buildBox( styleBuffer, style );
AttributeBuilder.buildBackground( styleBuffer, style, reportEmitter );
AttributeBuilder.buildText( styleBuffer, style );
AttributeBuilder.buildVisual( styleBuffer, style );
AttributeBuilder.buildTextDecoration( styleBuffer, style );
AttributeBuilder.buildSize( styleBuffer, style );
}
/**
* Build the style of the page head and page footer
*/
public void buildPageBandStyle( StringBuffer styleBuffer,
IStyle style )
{
if ( style == null || style.isEmpty( ) )
{
return;
}
AttributeBuilder.buildFont( styleBuffer, style );
AttributeBuilder.buildText( styleBuffer, style );
AttributeBuilder.buildVisual( styleBuffer, style );
AttributeBuilder.buildTextDecoration( styleBuffer, style );
// Build the vertical-align
String value = style.getVerticalAlign( );
if ( null != value )
{
styleBuffer.append( " vertical-align:" );
styleBuffer.append( value );
styleBuffer.append( ";" );
}
// Build the textAlign
value = style.getTextAlign( );
if ( null != value )
{
styleBuffer.append( " text-align:" );
styleBuffer.append( value );
styleBuffer.append( ";" );
}
}
/**
* Build the style of table content
*/
public void buildTableStyle( ITableContent table, StringBuffer styleBuffer )
{
addDefaultTableStyles( styleBuffer );
// The method getStyle( ) will nevel return a null value;
IStyle style = table.getStyle( );
boolean isInline = false;
// output the display
CSSValue display = style.getProperty( IStyle.STYLE_DISPLAY );
if ( IStyle.NONE_VALUE == display )
{
styleBuffer.append( " display: none;" );
}
else if ( IStyle.INLINE_VALUE == display
|| IStyle.INLINE_BLOCK_VALUE == display )
{
isInline = true;
// implement the inline table for old version browser
if ( !reportEmitter.browserSupportsInlineBlock )
{
styleBuffer.append( " display:table !important; display:inline;" );
}
else
{
styleBuffer.append( " display:inline-block; zoom:1; *+display:inline;" );
}
}
// height
DimensionType height = table.getHeight( );
if ( null != height )
{
buildSize( styleBuffer, HTMLTags.ATTR_HEIGHT, height );
}
// width
boolean widthOutputFlag = false;
DimensionType width = table.getWidth( );
if ( null != width )
{
buildSize( styleBuffer, HTMLTags.ATTR_WIDTH, width );
widthOutputFlag = true;
}
else
{
// Shrink table will not output the 100% as the default width in
// HTML.
// This is different with the PDF. PDF will use the 100% as the
// default width for a shrink table.
// If the table's columns all have a absolute width, we should not
// output the 100% as the default width.
if ( !"true".equalsIgnoreCase( style.getCanShrink( ) ) )
{
boolean absoluteWidth = true;
for ( int i = 0; i < table.getColumnCount( ); i++ )
{
IColumn column = table.getColumn( i );
DimensionType columnWidth = column.getWidth( );
if ( columnWidth == null )
{
absoluteWidth = false;
break;
}
else
{
if ( "%".endsWith( columnWidth.getUnits( ) ) )
{
absoluteWidth = false;
break;
}
}
}
if ( !absoluteWidth )
{
styleBuffer.append( " width: 100%;" );
widthOutputFlag = true;
}
}
}
// implement table-layout
if ( fixedReport )
{
// shrink table will not output table-layout;
if ( !"true".equalsIgnoreCase( style.getCanShrink( ) ) )
{
if ( !widthOutputFlag )
{
// In Firefox, if a table hasn't a width, the
// " table-layout:fixed;"
if ( isInline )
{
styleBuffer.append( " width: auto;" );
}
else
{
styleBuffer.append( " width: 1px;" );
}
}
CSSValue overflowValue = style.getProperty(IStyle.STYLE_OVERFLOW);
if(overflowValue == null )
{
//only inline table support it in Chrome and IE
if ( isInline )
{
styleBuffer.append( " overflow:hidden;" );
}
}
else
{
styleBuffer.append(" overflow:").append(overflowValue.getCssText()).append(";");
}
// build the table-layout
styleBuffer.append( " table-layout:fixed;" );
}
}
// Build the textAlign
String value = style.getTextAlign( );
if ( null != value )
{
if ( isInline )
{
styleBuffer.append( " text-align:" );
styleBuffer.append( "-moz-" );
styleBuffer.append( value );
styleBuffer.append( " !important;" );
}
styleBuffer.append( "text-align:" );
styleBuffer.append( value );
styleBuffer.append( ";" );
}
// Table doesn't support vertical-align.
style = getElementStyle( table );
if ( style == null )
{
return;
}
AttributeBuilder.buildFont( styleBuffer, style );
AttributeBuilder.buildBox( styleBuffer, style );
AttributeBuilder.buildBackground( styleBuffer, style, reportEmitter );
AttributeBuilder.buildText( styleBuffer, style );
AttributeBuilder.buildVisual( styleBuffer, style );
AttributeBuilder.buildTextDecoration( styleBuffer, style );
}
/**
* Build the style of column
*/
public void buildColumnStyle( IColumn column, StringBuffer styleBuffer )
{
buildSize( styleBuffer, HTMLTags.ATTR_WIDTH, column.getWidth( ) );
// The method getStyle( ) will nevel return a null value;
IStyle style = column.getStyle( );
// output the none value of the display
CSSValue display = style.getProperty( IStyle.STYLE_DISPLAY );
if ( IStyle.NONE_VALUE == display )
{
styleBuffer.append( " display:none;" );
}
// Build the vertical-align
// In performance optimize model the vertical-align can't be setted to
// the column. Because we output the vertical-align directly here, and
// it will cause the conflict with the BIRT, CSS, IE, Firefox. The user
// should set the vertical-align to the row or cells in this model.
String value = style.getVerticalAlign( );
if ( null != value )
{
styleBuffer.append( " vertical-align:" );
styleBuffer.append( value );
styleBuffer.append( ";" );
}
style = column.getInlineStyle( );
if ( style == null || style.isEmpty( ) )
{
return;
}
AttributeBuilder.buildFont( styleBuffer, style );
AttributeBuilder.buildBox( styleBuffer, style );
AttributeBuilder.buildBackground( styleBuffer, style, reportEmitter );
AttributeBuilder.buildText( styleBuffer, style );
AttributeBuilder.buildVisual( styleBuffer, style );
AttributeBuilder.buildTextDecoration( styleBuffer, style );
}
/**
* Handles the alignment property of the column content.
*/
public void handleColumnAlign( IColumn column )
{
// Column doesn't support text-align in BIRT.
}
/**
* Build the style of row content.
*/
public void buildRowStyle( IRowContent row, StringBuffer styleBuffer )
{
buildSize( styleBuffer, HTMLTags.ATTR_HEIGHT, row.getHeight( ) ); //$NON-NLS-1$
// The method getStyle( ) will nevel return a null value;
IStyle style = row.getStyle( );
// output the none value of the display
CSSValue display = style.getProperty( IStyle.STYLE_DISPLAY );
if ( IStyle.NONE_VALUE == display )
{
styleBuffer.append( " display: none;" );
}
style = getElementStyle( row );
if ( style == null )
{
return;
}
AttributeBuilder.buildFont( styleBuffer, style );
AttributeBuilder.buildBox( styleBuffer, style );
AttributeBuilder.buildBackground( styleBuffer, style, reportEmitter );
AttributeBuilder.buildText( styleBuffer, style );
AttributeBuilder.buildVisual( styleBuffer, style );
AttributeBuilder.buildTextDecoration( styleBuffer, style );
}
/**
* Handles the Text-Align property of the row content.
*/
public void handleRowAlign( IRowContent row )
{
// The method getStyle( ) will nevel return a null value;
IStyle style = row.getStyle( );
// Build the Vertical-Align property of the row content
CSSValue vAlign = style.getProperty( IStyle.STYLE_VERTICAL_ALIGN );
if ( null == vAlign || IStyle.BASELINE_VALUE == vAlign )
{
// The default vertical-align value of cell is top. And the cell can
// inherit the valign from parent row.
vAlign = IStyle.TOP_VALUE;
}
writer.attribute( HTMLTags.ATTR_VALIGN, vAlign.getCssText( ) );
// Build the Text-Align property.
CSSValue hAlign = style.getProperty( IStyle.STYLE_TEXT_ALIGN );
if ( null != hAlign )
{
writer.attribute( HTMLTags.ATTR_ALIGN, hAlign.getCssText( ) );
}
}
/**
* Build the style of cell content.
*/
public void buildCellStyle( ICellContent cell, StringBuffer styleBuffer,
boolean isHead, boolean fixedCellHeight )
{
// The method getStyle( ) will never return a null value;
IStyle style = cell.getStyle( );
if ( style == null )
{
return;
}
// implement the cell's clip.
if ( fixedReport && !fixedCellHeight )
{
HTMLEmitterUtil.buildOverflowStyle( styleBuffer, style, true );
}
// output the none value of the display
CSSValue display = style.getProperty( IStyle.STYLE_DISPLAY );
if ( IStyle.NONE_VALUE == display )
{
styleBuffer.append( " display: none !important; display: block;" );
}
style = getElementStyle( cell );
if ( style == null )
{
if ( fixedCellHeight )
{
// Fixed cell height requires the padding must be 0px.
styleBuffer.append( " padding: 0px;" );
}
return;
}
AttributeBuilder.buildFont( styleBuffer, style );
AttributeBuilder.buildMargins( styleBuffer, style );
if ( fixedCellHeight )
{
// Fixed cell height requires the padding must be 0px.
styleBuffer.append( " padding: 0px;" );
}
else
{
AttributeBuilder.buildPaddings( styleBuffer, style );
}
AttributeBuilder.buildBorders( styleBuffer, style );
AttributeBuilder.buildBackground( styleBuffer, style, reportEmitter );
AttributeBuilder.buildText( styleBuffer, style );
AttributeBuilder.buildVisual( styleBuffer, style );
AttributeBuilder.buildTextDecoration( styleBuffer, style );
}
/**
* Handles the vertical align property of the element content.
*/
public void handleCellVAlign( ICellContent cell )
{
// The method getStyle( ) will never return a null value;
IStyle style = cell.getStyle( );
// Build the Vertical-Align property of the row content
CSSValue vAlign = style.getProperty( IStyle.STYLE_VERTICAL_ALIGN );
if ( IStyle.BASELINE_VALUE == vAlign )
{
vAlign = IStyle.TOP_VALUE;
}
if ( null != vAlign )
{
// The default vertical-align value has already been outputted on
// the parent row.
writer.attribute( HTMLTags.ATTR_VALIGN, vAlign.getCssText( ) );
}
}
/**
* Build the style of contianer content.
*/
public void buildContainerStyle( IContainerContent container,
StringBuffer styleBuffer )
{
int display = ( (Integer) containerDisplayStack.peek( ) ).intValue( );
// shrink
handleShrink( display,
container.getStyle( ),
container.getHeight( ),
container.getWidth( ),
styleBuffer );
if ( ( display & HTMLEmitterUtil.DISPLAY_NONE ) > 0 )
{
styleBuffer.append( "display: none;" ); //$NON-NLS-1$
}
else if ( ( ( display & HTMLEmitterUtil.DISPLAY_INLINE ) > 0 )
|| ( ( display & HTMLEmitterUtil.DISPLAY_INLINE_BLOCK ) > 0 ) )
{
styleBuffer.append( "display:inline-block; zoom:1; *+display:inline;" ); //$NON-NLS-1$
}
IStyle style = getElementStyle( container );
if ( style == null )
{
return;
}
AttributeBuilder.buildFont( styleBuffer, style );
AttributeBuilder.buildBox( styleBuffer, style );
AttributeBuilder.buildBackground( styleBuffer, style, reportEmitter );
AttributeBuilder.buildText( styleBuffer, style );
AttributeBuilder.buildVisual( styleBuffer, style );
AttributeBuilder.buildTextDecoration( styleBuffer, style );
}
/**
* Handles the alignment property of the container content.
*/
public void handleContainerAlign( IContainerContent container )
{
// The method getStyle( ) will nevel return a null value;
IStyle style = container.getStyle( );
// Container doesn't support vertical-align.
// Build the Text-Align property.
CSSValue hAlign = style.getProperty( IStyle.STYLE_TEXT_ALIGN );
if ( null != hAlign )
{
writer.attribute( HTMLTags.ATTR_ALIGN, hAlign.getCssText( ) );
}
}
/**
* Build the style of text content.
*/
public void buildTextStyle( ITextContent text, StringBuffer styleBuffer,
int display )
{
IStyle style = text.getStyle( );
// check 'can-shrink' property
handleTextShrink( display,
style,
text.getHeight( ),
text.getWidth( ),
styleBuffer );
setDisplayProperty( display,
HTMLEmitterUtil.DISPLAY_INLINE_BLOCK,
styleBuffer );
// bidi_hcg start
// Build direction.
AttributeBuilder.buildBidiDirection( styleBuffer, text
.getComputedStyle( ) );
// bidi_hcg end
// build the text-align
String textAlign = style.getTextAlign( );
if ( textAlign != null )
{
styleBuffer.append( " text-align:" );
styleBuffer.append( textAlign );
styleBuffer.append( ";" );
}
style = getElementStyle( text );
if ( style == null )
{
return;
}
AttributeBuilder.buildFont( styleBuffer, style );
AttributeBuilder.buildBox( styleBuffer, style );
AttributeBuilder.buildBackground( styleBuffer, style, reportEmitter );
AttributeBuilder.buildText( styleBuffer, style );
AttributeBuilder.buildVisual( styleBuffer, style );
AttributeBuilder.buildTextDecoration( styleBuffer, style );
}
/**
* Build the style of foreign content.
*/
public void buildForeignStyle( IForeignContent foreign,
StringBuffer styleBuffer, int display )
{
IStyle style = foreign.getStyle( );
// check 'can-shrink' property
handleShrink( display,
style,
foreign.getHeight( ),
foreign.getWidth( ),
styleBuffer );
setDisplayProperty( display,
HTMLEmitterUtil.DISPLAY_INLINE_BLOCK,
styleBuffer );
// bidi_hcg start
// Build direction.
AttributeBuilder.buildBidiDirection( styleBuffer, foreign.getComputedStyle( ) );
// bidi_hcg end
// build the text-align
String textAlign = style.getTextAlign( );
if ( textAlign != null )
{
styleBuffer.append( " text-align:" );
styleBuffer.append( textAlign );
styleBuffer.append( ";" );
}
style = getElementStyle( foreign );
if ( style == null )
{
return;
}
AttributeBuilder.buildFont( styleBuffer, style );
AttributeBuilder.buildBox( styleBuffer, style );
AttributeBuilder.buildBackground( styleBuffer, style, reportEmitter );
AttributeBuilder.buildText( styleBuffer, style );
AttributeBuilder.buildVisual( styleBuffer, style );
AttributeBuilder.buildTextDecoration( styleBuffer, style );
}
/**
* Build the style of image content.
*/
public void buildImageStyle( IImageContent image, StringBuffer styleBuffer,
int display )
{
// image size
buildSize( styleBuffer, HTMLTags.ATTR_WIDTH, image.getWidth( ) ); //$NON-NLS-1$
buildSize( styleBuffer, HTMLTags.ATTR_HEIGHT, image.getHeight( ) ); //$NON-NLS-1$
// build the value of display
// An image is indeed inline by default, and align itself on the text
// baseline with room for descenders. That caused the gap and extra height,
// and the gap/height will change with font-resizing. Set "display:block" to
// get rid of space at the top and bottom.
setDisplayProperty( display, HTMLEmitterUtil.DISPLAY_BLOCK, styleBuffer );
IStyle style = image.getStyle( );
String verticalAlign = style.getVerticalAlign( );
if ( verticalAlign != null )
{
styleBuffer.append( " vertical-align:" );
styleBuffer.append( verticalAlign );
styleBuffer.append( ";" );
}
style = getElementStyle( image );
if ( style == null )
{
return;
}
AttributeBuilder.buildFont( styleBuffer, style );
AttributeBuilder.buildBox( styleBuffer, style );
AttributeBuilder.buildBackground( styleBuffer, style, reportEmitter );
AttributeBuilder.buildText( styleBuffer, style );
AttributeBuilder.buildVisual( styleBuffer, style );
AttributeBuilder.buildTextDecoration( styleBuffer, style );
// Image doesn't text-align.
// Text-align has been build in the style class. But the text-align
// doesn't work with the image.
}
}
|
package org.opennms.features.vaadin.nodemaps.internal.gwt.client;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import org.discotools.gwt.leaflet.client.popup.Popup;
import org.discotools.gwt.leaflet.client.popup.PopupImpl;
import org.discotools.gwt.leaflet.client.popup.PopupOptions;
import com.vaadin.terminal.gwt.client.VConsole;
final class NodeMarkerClusterCallback implements MarkerClusterEventCallback {
NodeMarkerClusterCallback() {
}
@Override
public final void run(final MarkerClusterEvent event) {
final StringBuilder sb = new StringBuilder();
final MarkerCluster cluster = event.getMarkerCluster();
@SuppressWarnings("unchecked")
final List<NodeMarker> markers = (List<NodeMarker>)cluster.getAllChildMarkers();
VConsole.log("Clicked, processing " + markers.size() + " markers.");
Collections.sort(markers, new Comparator<NodeMarker>() {
final static int BEFORE = -1;
final static int EQUAL = 0;
final static int AFTER = 1;
@Override
public int compare(final NodeMarker left, final NodeMarker right) {
if (left == right) return EQUAL;
if (left.getSeverity() != right.getSeverity()) {
return left.getSeverity() > right.getSeverity()? BEFORE : AFTER;
}
if (left.getNodeLabel() != right.getNodeLabel()) {
return left.getNodeLabel() == null? AFTER : left.getNodeLabel().toLowerCase().compareTo(right.getNodeLabel() == null? BEFORE : right.getNodeLabel().toLowerCase());
}
return left.getNodeId().compareTo(right.getNodeId());
}
});
if (markers.size() == 1) {
final NodeMarker marker = markers.get(0);
sb.append(getPopupTextForMarker(marker));
} else {
final StringBuilder nodeBuilder = new StringBuilder();
int unacked = 0;
for (final NodeMarker marker : markers) {
unacked += marker.getUnackedCount();
nodeBuilder.append("<li>");
nodeBuilder.append(marker.getNodeLabel()).append(" ");
nodeBuilder.append("(").append(marker.getIpAddress()).append(")").append(": ");
nodeBuilder.append(marker.getSeverityLabel());
nodeBuilder.append("</li>");
}
sb.append("<h2># of nodes: ").append(markers.size()).append(" ");
sb.append("(").append(unacked).append(" Unacknowledged Alarms)");
sb.append("</h2>");
sb.append("<ul>").append(nodeBuilder).append("</ul>");
}
final PopupOptions options = new PopupOptions();
options.setMaxWidth(500);
options.setProperty("maxHeight", 250);
final Popup popup = new Popup(options);
popup.setContent(sb.toString());
popup.setLatLng(cluster.getLatLng());
VConsole.log("html = " + sb.toString());
PopupImpl.openOn(popup.getJSObject(), cluster.getGroup().getMapObject());
}
public static String getPopupTextForMarker(final NodeMarker marker) {
// TODO: THIS IS AWFUL
final StringBuilder sb = new StringBuilder();
sb.append("<h2><a href=\"/opennms/element/node.jsp?node=" + marker.getNodeId() + "\" target=\"_blank\">Node ").append(marker.getNodeLabel()).append("</a></h2>");
sb.append("<p>");
sb.append("Node ID: ").append(marker.getNodeId()).append("<br/>");
sb.append("Foreign Source: ").append(marker.getForeignSource()).append("<br/>");
sb.append("Foreign ID: ").append(marker.getForeignId()).append("<br/>");
sb.append("IP Address: ").append(marker.getIpAddress()).append("<br/>");
sb.append("Severity: ").append(marker.getSeverityLabel());
sb.append("</p>");
return sb.toString();
}
}
|
package javaslang.collection;
import javaslang.*;
import javaslang.collection.CharSeqModule.Combinations;
import javaslang.control.Option;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.*;
import java.util.HashSet;
import java.util.function.*;
import java.util.regex.PatternSyntaxException;
import java.util.stream.Collector;
/**
* The CharSeq (read: character sequence) collection essentially is a rich String wrapper having all operations
* we know from the functional Javaslang collections.
*
* @author Ruslan Sennov, Daniel Dietrich
* @since 2.0.0
*/
public final class CharSeq implements Kind1<CharSeq, Character>, CharSequence, IndexedSeq<Character>, Serializable {
private static final long serialVersionUID = 1L;
private static final CharSeq EMPTY = new CharSeq("");
private final String back;
private CharSeq(String javaString) {
this.back = javaString;
}
public static CharSeq empty() {
return EMPTY;
}
/**
* Returns a {@link java.util.stream.Collector} which may be used in conjunction with
* {@link java.util.stream.Stream#collect(java.util.stream.Collector)} to obtain a {@link CharSeq}.
*
* @return A {@code CharSeq} Collector.
*/
public static Collector<Character, ArrayList<Character>, CharSeq> collector() {
final Supplier<ArrayList<Character>> supplier = ArrayList::new;
final BiConsumer<ArrayList<Character>, Character> accumulator = ArrayList::add;
final BinaryOperator<ArrayList<Character>> combiner = (left, right) -> {
left.addAll(right);
return left;
};
final Function<ArrayList<Character>, CharSeq> finisher = CharSeq::ofAll;
return Collector.of(supplier, accumulator, combiner, finisher);
}
/**
* Creates a String of {@code CharSequence}.
*
* @param sequence {@code CharSequence} instance.
* @return A new {@code javaslang.String}
*/
// DEV-NOTE: Needs to be 'of' instead of 'ofAll' because 'ofAll(CharSeq)' is ambiguous.
public static CharSeq of(CharSequence sequence) {
Objects.requireNonNull(sequence, "sequence is null");
if (sequence instanceof CharSeq) {
return (CharSeq) sequence;
} else {
return sequence.length() == 0 ? empty() : new CharSeq(sequence.toString());
}
}
/**
* Returns a singleton {@code CharSeq}, i.e. a {@code CharSeq} of one character.
*
* @param character A character.
* @return A new {@code CharSeq} instance containing the given element
*/
public static CharSeq of(char character) {
return new CharSeq(new String(new char[] { character }));
}
/**
* Creates a String of the given characters.
*
* @param characters Zero or more characters.
* @return A string containing the given characters in the same order.
* @throws NullPointerException if {@code elements} is null
*/
public static CharSeq of(char... characters) {
Objects.requireNonNull(characters, "characters is null");
if (characters.length == 0) {
return empty();
} else {
final char[] chrs = new char[characters.length];
System.arraycopy(characters, 0, chrs, 0, characters.length);
return new CharSeq(new String(chrs));
}
}
/**
* Creates a String of the given elements.
*
* The resulting string has the same iteration order as the given iterable of elements
* if the iteration order of the elements is stable.
*
* @param elements An Iterable of elements.
* @return A string containing the given elements in the same order.
* @throws NullPointerException if {@code elements} is null
*/
public static CharSeq ofAll(Iterable<? extends Character> elements) {
Objects.requireNonNull(elements, "elements is null");
final StringBuilder sb = new StringBuilder();
for (Character character : elements) {
sb.append(character);
}
return sb.length() == 0 ? EMPTY : of(sb.toString());
}
/**
* Returns a CharSeq containing {@code n} values of a given Function {@code f}
* over a range of integer values from 0 to {@code n - 1}.
*
* @param n The number of elements in the CharSeq
* @param f The Function computing element values
* @return A CharSeq consisting of elements {@code f(0),f(1), ..., f(n - 1)}
* @throws NullPointerException if {@code f} is null
*/
public static CharSeq tabulate(int n, Function<? super Integer, ? extends Character> f) {
Objects.requireNonNull(f, "f is null");
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++) {
sb.append(f.apply(i));
}
return of(sb);
}
/**
* Returns a CharSeq containing {@code n} values supplied by a given Supplier {@code s}.
*
* @param n The number of elements in the CharSeq
* @param s The Supplier computing element values
* @return A CharSeq of size {@code n}, where each element contains the result supplied by {@code s}.
* @throws NullPointerException if {@code s} is null
*/
public static CharSeq fill(int n, Supplier<? extends Character> s) {
return tabulate(n, anything -> s.get());
}
/**
* Creates a CharSeq starting from character {@code from}, extending to character {@code toExclusive - 1}.
* <p>
* Examples:
* <pre>
* <code>
* CharSeq.range('a', 'c') // = "ab"
* CharSeq.range('c', 'a') // = ""
* </code>
* </pre>
*
* @param from the first character
* @param toExclusive the successor of the last character
* @return a range of characters as specified or the empty range if {@code from >= toExclusive}
*/
public static CharSeq range(char from, char toExclusive) {
return new CharSeq(Iterator.range(from, toExclusive).mkString());
}
public static CharSeq rangeBy(char from, char toExclusive, int step) {
return new CharSeq(Iterator.rangeBy(from, toExclusive, step).mkString());
}
/**
* Creates a CharSeq starting from character {@code from}, extending to character {@code toInclusive}.
* <p>
* Examples:
* <pre>
* <code>
* CharSeq.rangeClosed('a', 'c') // = "abc"
* CharSeq.rangeClosed('c', 'a') // = ""
* </code>
* </pre>
*
* @param from the first character
* @param toInclusive the last character
* @return a range of characters as specified or the empty range if {@code from > toInclusive}
*/
public static CharSeq rangeClosed(char from, char toInclusive) {
return new CharSeq(Iterator.rangeClosed(from, toInclusive).mkString());
}
public static CharSeq rangeClosedBy(char from, char toInclusive, int step) {
return new CharSeq(Iterator.rangeClosedBy(from, toInclusive, step).mkString());
}
private Tuple2<CharSeq, CharSeq> splitByBuilder(StringBuilder sb) {
if (sb.length() == 0) {
return Tuple.of(EMPTY, this);
} else if (sb.length() == length()) {
return Tuple.of(this, EMPTY);
} else {
return Tuple.of(of(sb.toString()), of(back.substring(sb.length())));
}
}
/**
* Repeats a character {@code times} times.
*
* @param character A character
* @param times Repetition count
* @return A CharSeq representing {@code character * times}
*/
public static CharSeq repeat(char character, int times) {
final int length = Math.max(times, 0);
final char[] characters = new char[length];
Arrays.fill(characters, character);
return new CharSeq(String.valueOf(characters));
}
/**
* Repeats this CharSeq {@code times} times.
* <p>
* Example: {@code CharSeq.of("ja").repeat(13) = "jajajajajajajajajajajajaja"}
*
* @param times Repetition count
* @return A CharSeq representing {@code this * times}
*/
public CharSeq repeat(int times) {
final StringBuilder builder = new StringBuilder();
for (int i = 0; i < times; i++) {
builder.append(back);
}
return new CharSeq(builder.toString());
}
// IndexedSeq
@Override
public CharSeq append(Character element) {
return of(back + element);
}
@Override
public CharSeq appendAll(Iterable<? extends Character> elements) {
Objects.requireNonNull(elements, "elements is null");
final StringBuilder sb = new StringBuilder(back);
for (char element : elements) {
sb.append(element);
}
return of(sb.toString());
}
@Override
public IndexedSeq<CharSeq> combinations() {
return Vector.rangeClosed(0, length()).map(this::combinations).flatMap(Function.identity());
}
@Override
public IndexedSeq<CharSeq> combinations(int k) {
return Combinations.apply(this, Math.max(k, 0));
}
@Override
public Iterator<CharSeq> crossProduct(int power) {
return Collections.crossProduct(CharSeq.empty(), this, power);
}
@Override
public CharSeq distinct() {
return distinctBy(Function.identity());
}
@Override
public CharSeq distinctBy(Comparator<? super Character> comparator) {
Objects.requireNonNull(comparator, "comparator is null");
final java.util.Set<Character> seen = new java.util.TreeSet<>(comparator);
return filter(seen::add);
}
@Override
public <U> CharSeq distinctBy(Function<? super Character, ? extends U> keyExtractor) {
Objects.requireNonNull(keyExtractor, "keyExtractor is null");
final java.util.Set<U> seen = new java.util.HashSet<>();
return filter(t -> seen.add(keyExtractor.apply(t)));
}
@Override
public CharSeq drop(long n) {
if (n <= 0) {
return this;
} else if (n >= length()) {
return EMPTY;
} else {
return of(back.substring((int) n));
}
}
@Override
public CharSeq dropRight(long n) {
if (n <= 0) {
return this;
} else if (n >= length()) {
return EMPTY;
} else {
return of(back.substring(0, length() - (int) n));
}
}
@Override
public CharSeq dropUntil(Predicate<? super Character> predicate) {
Objects.requireNonNull(predicate, "predicate is null");
return dropWhile(predicate.negate());
}
@Override
public CharSeq dropWhile(Predicate<? super Character> predicate) {
Objects.requireNonNull(predicate, "predicate is null");
int index = 0;
while (index < length() && predicate.test(charAt(index))) {
index++;
}
return index < length() ? (index == 0 ? this : of(back.substring(index))) : empty();
}
@Override
public CharSeq filter(Predicate<? super Character> predicate) {
Objects.requireNonNull(predicate, "predicate is null");
final StringBuilder sb = new StringBuilder();
for (int i = 0; i < back.length(); i++) {
final char ch = back.charAt(i);
if (predicate.test(ch)) {
sb.append(ch);
}
}
return sb.length() == 0 ? EMPTY : sb.length() == length() ? this : of(sb.toString());
}
@Override
public <U> IndexedSeq<U> flatMap(Function<? super Character, ? extends Iterable<? extends U>> mapper) {
Objects.requireNonNull(mapper, "mapper is null");
if (isEmpty()) {
return Vector.empty();
} else {
IndexedSeq<U> result = Vector.empty();
for (int i = 0; i < length(); i++) {
for (U u : mapper.apply(get(i))) {
result = result.append(u);
}
}
return result;
}
}
public CharSeq flatMapChars(CharFunction<? extends CharSequence> mapper) {
Objects.requireNonNull(mapper, "mapper is null");
if (isEmpty()) {
return this;
} else {
final StringBuilder builder = new StringBuilder();
back.chars().forEach(c -> builder.append(mapper.apply((char) c)));
return new CharSeq(builder.toString());
}
}
@Override
public <C> Map<C, CharSeq> groupBy(Function<? super Character, ? extends C> classifier) {
Objects.requireNonNull(classifier, "classifier is null");
return iterator().groupBy(classifier).map((c, it) -> Tuple.of(c, CharSeq.ofAll(it)));
}
@Override
public Iterator<CharSeq> grouped(long size) {
return sliding(size, size);
}
@Override
public boolean hasDefiniteSize() {
return true;
}
@Override
public CharSeq init() {
if (isEmpty()) {
throw new UnsupportedOperationException("init of empty string");
} else {
return of(back.substring(0, length() - 1));
}
}
@Override
public Option<CharSeq> initOption() {
if (isEmpty()) {
return Option.none();
} else {
return Option.some(init());
}
}
@Override
public CharSeq insert(int index, Character element) {
if (index < 0) {
throw new IndexOutOfBoundsException("insert(" + index + ", e)");
}
if (index > length()) {
throw new IndexOutOfBoundsException("insert(" + index + ", e) on String of length " + length());
}
return of(new StringBuilder(back).insert(index, element).toString());
}
@Override
public CharSeq insertAll(int index, Iterable<? extends Character> elements) {
Objects.requireNonNull(elements, "elements is null");
if (index < 0) {
throw new IndexOutOfBoundsException("insertAll(" + index + ", elements)");
}
if (index > length()) {
throw new IndexOutOfBoundsException("insertAll(" + index + ", elements) on String of length " + length());
}
final String javaString = back;
final StringBuilder sb = new StringBuilder(javaString.substring(0, index));
for (Character element : elements) {
sb.append(element);
}
sb.append(javaString.substring(index));
return of(sb.toString());
}
@Override
public Iterator<Character> iterator() {
return new AbstractIterator<Character>() {
private int index = 0;
@Override
public boolean hasNext() {
return index < back.length();
}
@Override
public Character getNext() {
return back.charAt(index++);
}
};
}
@Override
public CharSeq intersperse(Character element) {
final StringBuilder sb = new StringBuilder();
for (int i = 0; i < length(); i++) {
if (i > 0) {
sb.append(element);
}
sb.append(get(i));
}
return sb.length() == 0 ? EMPTY : of(sb.toString());
}
@Override
public <U> IndexedSeq<U> map(Function<? super Character, ? extends U> mapper) {
Objects.requireNonNull(mapper, "mapper is null");
IndexedSeq<U> result = Vector.empty();
for (int i = 0; i < length(); i++) {
result = result.append(mapper.apply(get(i)));
}
return result;
}
@Override
public CharSeq padTo(int length, Character element) {
if (length <= back.length()) {
return this;
}
final StringBuilder sb = new StringBuilder(back).append(padding(element, length - back.length()));
return new CharSeq(sb.toString());
}
@Override
public CharSeq leftPadTo(int length, Character element) {
if (length <= back.length()) {
return this;
}
final StringBuilder sb = new StringBuilder(padding(element, length - back.length())).append(back);
return new CharSeq(sb.toString());
}
private static StringBuilder padding(Character element, int limit) {
final StringBuilder padding = new StringBuilder();
for (int i = 0; i < limit; i++) {
padding.append(element);
}
return padding;
}
@Override
public CharSeq patch(int from, Iterable<? extends Character> that, int replaced) {
from = from < 0 ? 0 : from > length() ? length() : from;
replaced = replaced < 0 ? 0 : replaced;
final StringBuilder sb = new StringBuilder(back.substring(0, from));
for (Character character : that) {
sb.append(character);
}
from += replaced;
if (from < length()) {
sb.append(back.substring(from));
}
return sb.length() == 0 ? EMPTY : new CharSeq(sb.toString());
}
public CharSeq mapChars(CharUnaryOperator mapper) {
Objects.requireNonNull(mapper, "mapper is null");
if (isEmpty()) {
return this;
} else {
final char[] chars = back.toCharArray();
for (int i = 0; i < chars.length; i++) {
chars[i] = mapper.apply(chars[i]);
}
return CharSeq.of(chars);
}
}
@Override
public Tuple2<CharSeq, CharSeq> partition(Predicate<? super Character> predicate) {
Objects.requireNonNull(predicate, "predicate is null");
if (isEmpty()) {
return Tuple.of(EMPTY, EMPTY);
}
final StringBuilder left = new StringBuilder();
final StringBuilder right = new StringBuilder();
for (int i = 0; i < length(); i++) {
Character t = get(i);
(predicate.test(t) ? left : right).append(t);
}
if (left.length() == 0) {
return Tuple.of(EMPTY, of(right.toString()));
} else if (right.length() == 0) {
return Tuple.of(of(left.toString()), EMPTY);
} else {
return Tuple.of(of(left.toString()), of(right.toString()));
}
}
@Override
public CharSeq peek(Consumer<? super Character> action) {
Objects.requireNonNull(action, "action is null");
if (!isEmpty()) {
action.accept(back.charAt(0));
}
return this;
}
@Override
public IndexedSeq<CharSeq> permutations() {
if (isEmpty()) {
return Vector.empty();
} else {
if (length() == 1) {
return Vector.of(this);
} else {
IndexedSeq<CharSeq> result = Vector.empty();
for (Character t : distinct()) {
for (CharSeq ts : remove(t).permutations()) {
result = result.append(CharSeq.of(t).appendAll(ts));
}
}
return result;
}
}
}
@Override
public CharSeq prepend(Character element) {
return of(element + back);
}
@Override
public CharSeq prependAll(Iterable<? extends Character> elements) {
Objects.requireNonNull(elements, "elements is null");
final StringBuilder sb = new StringBuilder();
for (Character element : elements) {
sb.append(element);
}
sb.append(back);
return sb.length() == 0 ? EMPTY : of(sb.toString());
}
@Override
public CharSeq remove(Character element) {
final StringBuilder sb = new StringBuilder();
boolean found = false;
for (int i = 0; i < length(); i++) {
char c = get(i);
if (!found && c == element) {
found = true;
} else {
sb.append(c);
}
}
return sb.length() == 0 ? EMPTY : sb.length() == length() ? this : of(sb.toString());
}
@Override
public CharSeq removeFirst(Predicate<Character> predicate) {
Objects.requireNonNull(predicate, "predicate is null");
final StringBuilder sb = new StringBuilder();
boolean found = false;
for (int i = 0; i < back.length(); i++) {
final char ch = back.charAt(i);
if (predicate.test(ch)) {
if (found) {
sb.append(ch);
}
found = true;
} else {
sb.append(ch);
}
}
return found ? (sb.length() == 0 ? EMPTY : of(sb.toString())) : this;
}
@Override
public CharSeq removeLast(Predicate<Character> predicate) {
Objects.requireNonNull(predicate, "predicate is null");
for (int i = length() - 1; i >= 0; i
if (predicate.test(back.charAt(i))) {
return removeAt(i);
}
}
return this;
}
@Override
public CharSeq removeAt(int index) {
final String removed = back.substring(0, index) + back.substring(index + 1);
return removed.isEmpty() ? EMPTY : of(removed);
}
@Override
public CharSeq removeAll(Character element) {
final StringBuilder sb = new StringBuilder();
for (int i = 0; i < length(); i++) {
final char c = back.charAt(i);
if (c != element) {
sb.append(c);
}
}
return sb.length() == 0 ? EMPTY : sb.length() == length() ? this : of(sb.toString());
}
@Override
public CharSeq removeAll(Iterable<? extends Character> elements) {
Objects.requireNonNull(elements, "elements is null");
final java.util.Set<Character> distinct = new HashSet<>();
for (Character element : elements) {
distinct.add(element);
}
final StringBuilder sb = new StringBuilder();
for (int i = 0; i < length(); i++) {
final char c = back.charAt(i);
if (!distinct.contains(c)) {
sb.append(c);
}
}
return sb.length() == 0 ? EMPTY : sb.length() == length() ? this : of(sb.toString());
}
@Override
public CharSeq replace(Character currentElement, Character newElement) {
final StringBuilder sb = new StringBuilder();
boolean found = false;
for (int i = 0; i < length(); i++) {
final char c = back.charAt(i);
if (c == currentElement && !found) {
sb.append(newElement);
found = true;
} else {
sb.append(c);
}
}
return found ? of(sb.toString()) : this;
}
@Override
public CharSeq replaceAll(Character currentElement, Character newElement) {
final StringBuilder sb = new StringBuilder();
boolean found = false;
for (int i = 0; i < length(); i++) {
final char c = back.charAt(i);
if (c == currentElement) {
sb.append(newElement);
found = true;
} else {
sb.append(c);
}
}
return found ? of(sb.toString()) : this;
}
@Override
public CharSeq retainAll(Iterable<? extends Character> elements) {
Objects.requireNonNull(elements, "elements is null");
final java.util.Set<Character> kept = new HashSet<>();
for (Character element : elements) {
kept.add(element);
}
final StringBuilder sb = new StringBuilder();
for (int i = 0; i < length(); i++) {
final char c = back.charAt(i);
if (kept.contains(c)) {
sb.append(c);
}
}
return sb.length() == 0 ? EMPTY : of(sb.toString());
}
@Override
public CharSeq reverse() {
return of(new StringBuilder(back).reverse().toString());
}
@Override
public IndexedSeq<Character> scan(Character zero, BiFunction<? super Character, ? super Character, ? extends Character> operation) {
return scanLeft(zero, operation);
}
@Override
public <U> IndexedSeq<U> scanLeft(U zero, BiFunction<? super U, ? super Character, ? extends U> operation) {
Objects.requireNonNull(operation, "operation is null");
return Collections.scanLeft(this, zero, operation, Vector.empty(), Vector::append, Function.identity());
}
@Override
public <U> IndexedSeq<U> scanRight(U zero, BiFunction<? super Character, ? super U, ? extends U> operation) {
Objects.requireNonNull(operation, "operation is null");
return Collections.scanRight(this, zero, operation, Vector.empty(), Vector::prepend, Function.identity());
}
@Override
public CharSeq slice(long beginIndex, long endIndex) {
final long from = beginIndex < 0 ? 0 : beginIndex;
final long to = endIndex > length() ? length() : endIndex;
if (from >= to) {
return EMPTY;
}
if (from <= 0 && to >= length()) {
return this;
}
return CharSeq.of(back.substring((int) from, (int) to));
}
@Override
public Iterator<CharSeq> sliding(long size) {
return sliding(size, 1);
}
@Override
public Iterator<CharSeq> sliding(long size, long step) {
return iterator().sliding(size, step).map(CharSeq::ofAll);
}
@Override
public CharSeq sorted() {
return isEmpty() ? this : toJavaStream().sorted().collect(CharSeq.collector());
}
@Override
public CharSeq sorted(Comparator<? super Character> comparator) {
Objects.requireNonNull(comparator, "comparator is null");
return isEmpty() ? this : toJavaStream().sorted(comparator).collect(CharSeq.collector());
}
@Override
public <U extends Comparable<? super U>> CharSeq sortBy(Function<? super Character, ? extends U> mapper) {
return sortBy(U::compareTo, mapper);
}
@Override
public <U> CharSeq sortBy(Comparator<? super U> comparator, Function<? super Character, ? extends U> mapper) {
final Function<? super Character, ? extends U> domain = Function1.of(mapper::apply).memoized();
return toJavaStream()
.sorted((e1, e2) -> comparator.compare(domain.apply(e1), domain.apply(e2)))
.collect(collector());
}
@Override
public Tuple2<CharSeq, CharSeq> span(Predicate<? super Character> predicate) {
Objects.requireNonNull(predicate, "predicate is null");
final StringBuilder sb = new StringBuilder();
for (int i = 0; i < length(); i++) {
final char c = back.charAt(i);
if (predicate.test(c)) {
sb.append(c);
} else {
break;
}
}
return splitByBuilder(sb);
}
@Override
public Spliterator<Character> spliterator() {
return Spliterators.spliterator(iterator(), length(), Spliterator.ORDERED | Spliterator.IMMUTABLE);
}
@Override
public CharSeq subSequence(int beginIndex) {
if (beginIndex < 0 || beginIndex > length()) {
throw new IndexOutOfBoundsException("begin index " + beginIndex + " < 0");
}
if (beginIndex == 0) {
return this;
} else if (beginIndex == length()) {
return EMPTY;
} else {
return CharSeq.of(back.substring(beginIndex));
}
}
@Override
public CharSeq tail() {
if (isEmpty()) {
throw new UnsupportedOperationException("tail of empty string");
} else {
return CharSeq.of(back.substring(1));
}
}
@Override
public Option<CharSeq> tailOption() {
if (isEmpty()) {
return Option.none();
} else {
return Option.some(CharSeq.of(back.substring(1)));
}
}
@Override
public CharSeq take(long n) {
if (n <= 0) {
return EMPTY;
} else if (n >= length()) {
return this;
} else {
return CharSeq.of(back.substring(0, (int) n));
}
}
@Override
public CharSeq takeRight(long n) {
if (n <= 0) {
return EMPTY;
} else if (n >= length()) {
return this;
} else {
return CharSeq.of(back.substring(length() - (int) n));
}
}
@Override
public CharSeq takeUntil(Predicate<? super Character> predicate) {
Objects.requireNonNull(predicate, "predicate is null");
return takeWhile(predicate.negate());
}
@Override
public CharSeq takeWhile(Predicate<? super Character> predicate) {
Objects.requireNonNull(predicate, "predicate is null");
final StringBuilder sb = new StringBuilder();
for (int i = 0; i < length(); i++) {
char c = back.charAt(i);
if (!predicate.test(c)) {
break;
}
sb.append(c);
}
return sb.length() == length() ? this : sb.length() == 0 ? EMPTY : of(sb.toString());
}
/**
* Transforms this {@code CharSeq}.
*
* @param f A transformation
* @param <U> Type of transformation result
* @return An instance of type {@code U}
* @throws NullPointerException if {@code f} is null
*/
public <U> U transform(Function<? super CharSeq, ? extends U> f) {
Objects.requireNonNull(f, "f is null");
return f.apply(this);
}
@Override
public <U> IndexedSeq<U> unit(Iterable<? extends U> iterable) {
return Vector.ofAll(iterable);
}
@Override
public <T1, T2> Tuple2<IndexedSeq<T1>, IndexedSeq<T2>> unzip(
Function<? super Character, Tuple2<? extends T1, ? extends T2>> unzipper) {
Objects.requireNonNull(unzipper, "unzipper is null");
IndexedSeq<T1> xs = Vector.empty();
IndexedSeq<T2> ys = Vector.empty();
for (int i = 0; i < length(); i++) {
final Tuple2<? extends T1, ? extends T2> t = unzipper.apply(back.charAt(i));
xs = xs.append(t._1);
ys = ys.append(t._2);
}
return Tuple.of(xs, ys);
}
@Override
public <T1, T2, T3> Tuple3<IndexedSeq<T1>, IndexedSeq<T2>, IndexedSeq<T3>> unzip3(
Function<? super Character, Tuple3<? extends T1, ? extends T2, ? extends T3>> unzipper) {
Objects.requireNonNull(unzipper, "unzipper is null");
IndexedSeq<T1> xs = Vector.empty();
IndexedSeq<T2> ys = Vector.empty();
IndexedSeq<T3> zs = Vector.empty();
for (int i = 0; i < length(); i++) {
final Tuple3<? extends T1, ? extends T2, ? extends T3> t = unzipper.apply(back.charAt(i));
xs = xs.append(t._1);
ys = ys.append(t._2);
zs = zs.append(t._3);
}
return Tuple.of(xs, ys, zs);
}
@Override
public CharSeq update(int index, Character element) {
if (index < 0) {
throw new IndexOutOfBoundsException("update(" + index + ")");
}
if (index >= length()) {
throw new IndexOutOfBoundsException("update(" + index + ")");
}
return of(back.substring(0, index) + element + back.substring(index + 1));
}
@Override
public <U> IndexedSeq<Tuple2<Character, U>> zip(Iterable<? extends U> that) {
Objects.requireNonNull(that, "that is null");
IndexedSeq<Tuple2<Character, U>> result = Vector.empty();
Iterator<Character> list1 = iterator();
java.util.Iterator<? extends U> list2 = that.iterator();
while (list1.hasNext() && list2.hasNext()) {
result = result.append(Tuple.of(list1.next(), list2.next()));
}
return result;
}
@Override
public <U> IndexedSeq<Tuple2<Character, U>> zipAll(Iterable<? extends U> that, Character thisElem, U thatElem) {
Objects.requireNonNull(that, "that is null");
IndexedSeq<Tuple2<Character, U>> result = Vector.empty();
Iterator<Character> list1 = iterator();
java.util.Iterator<? extends U> list2 = that.iterator();
while (list1.hasNext() || list2.hasNext()) {
final Character elem1 = list1.hasNext() ? list1.next() : thisElem;
final U elem2 = list2.hasNext() ? list2.next() : thatElem;
result = result.append(Tuple.of(elem1, elem2));
}
return result;
}
@Override
public IndexedSeq<Tuple2<Character, Long>> zipWithIndex() {
IndexedSeq<Tuple2<Character, Long>> result = Vector.empty();
for (int i = 0; i < length(); i++) {
result = result.append(Tuple.of(get(i), (long) i));
}
return result;
}
@Override
public Character get(int index) {
return back.charAt(index);
}
@Override
public int indexOf(Character element, int from) {
return back.indexOf(element, from);
}
@Override
public int lastIndexOf(Character element, int end) {
return back.lastIndexOf(element, end);
}
@Override
public Tuple2<CharSeq, CharSeq> splitAt(long n) {
if (n <= 0) {
return Tuple.of(EMPTY, this);
} else if (n >= length()) {
return Tuple.of(this, EMPTY);
} else {
return Tuple.of(of(back.substring(0, (int) n)), of(back.substring((int) n)));
}
}
@Override
public Tuple2<CharSeq, CharSeq> splitAt(Predicate<? super Character> predicate) {
Objects.requireNonNull(predicate, "predicate is null");
if (isEmpty()) {
return Tuple.of(EMPTY, EMPTY);
}
final StringBuilder left = new StringBuilder();
for (int i = 0; i < length(); i++) {
Character t = get(i);
if (!predicate.test(t)) {
left.append(t);
} else {
break;
}
}
return splitByBuilder(left);
}
@Override
public Tuple2<CharSeq, CharSeq> splitAtInclusive(Predicate<? super Character> predicate) {
Objects.requireNonNull(predicate, "predicate is null");
if (isEmpty()) {
return Tuple.of(EMPTY, EMPTY);
}
final StringBuilder left = new StringBuilder();
for (int i = 0; i < length(); i++) {
Character t = get(i);
left.append(t);
if (predicate.test(t)) {
break;
}
}
return splitByBuilder(left);
}
@Override
public boolean startsWith(Iterable<? extends Character> that, int offset) {
return startsWith(CharSeq.ofAll(that), offset);
}
@Override
public Character head() {
if (isEmpty()) {
throw new NoSuchElementException("head of empty string");
} else {
return back.charAt(0);
}
}
@Override
public Option<Character> headOption() {
if (isEmpty()) {
return Option.none();
} else {
return Option.some(back.charAt(0));
}
}
@Override
public boolean isEmpty() {
return back.isEmpty();
}
@Override
public boolean isTraversableAgain() {
return true;
}
private Object readResolve() {
return isEmpty() ? EMPTY : this;
}
@Override
public boolean equals(Object o) {
if (o == this) {
return true;
} else if (o instanceof CharSeq) {
return ((CharSeq) o).back.equals(back);
} else {
return false;
}
}
@Override
public int hashCode() {
return back.hashCode();
}
// java.lang.CharSequence
/**
* Returns the {@code char} value at the
* specified index. An index ranges from {@code 0} to
* {@code length() - 1}. The first {@code char} value of the sequence
* is at index {@code 0}, the next at index {@code 1},
* and so on, as for array indexing.
*
* <p>If the {@code char} value specified by the index is a
* <a href="Character.html#unicode">surrogate</a>, the surrogate
* value is returned.
*
* @param index the index of the {@code char} value.
* @return the {@code char} value at the specified index of this string.
* The first {@code char} value is at index {@code 0}.
* @throws IndexOutOfBoundsException if the {@code index}
* argument is negative or not less than the length of this
* string.
*/
@Override
public char charAt(int index) {
return back.charAt(index);
}
/**
* Returns the length of this string.
* The length is equal to the number of <a href="Character.html#unicode">Unicode
* code units</a> in the string.
*
* @return the length of the sequence of characters represented by this
* object.
*/
@Override
public int length() {
return back.length();
}
// String
/**
* Returns the character (Unicode code point) at the specified
* index. The index refers to {@code char} values
* (Unicode code units) and ranges from {@code 0} to
* {@link #length()}{@code - 1}.
*
* <p> If the {@code char} value specified at the given index
* is in the high-surrogate range, the following index is less
* than the length of this {@code CharSeq}, and the
* {@code char} value at the following index is in the
* low-surrogate range, then the supplementary code point
* corresponding to this surrogate pair is returned. Otherwise,
* the {@code char} value at the given index is returned.
*
* @param index the index to the {@code char} values
* @return the code point value of the character at the
* {@code index}
* @throws IndexOutOfBoundsException if the {@code index}
* argument is negative or not less than the length of this
* string.
*/
public int codePointAt(int index) {
return back.codePointAt(index);
}
/**
* Returns the character (Unicode code point) before the specified
* index. The index refers to {@code char} values
* (Unicode code units) and ranges from {@code 1} to {@link
* CharSequence#length() length}.
*
* <p> If the {@code char} value at {@code (index - 1)}
* is in the low-surrogate range, {@code (index - 2)} is not
* negative, and the {@code char} value at {@code (index -
* 2)} is in the high-surrogate range, then the
* supplementary code point value of the surrogate pair is
* returned. If the {@code char} value at {@code index -
* 1} is an unpaired low-surrogate or a high-surrogate, the
* surrogate value is returned.
*
* @param index the index following the code point that should be returned
* @return the Unicode code point value before the given index.
* @throws IndexOutOfBoundsException if the {@code index}
* argument is less than 1 or greater than the length
* of this string.
*/
public int codePointBefore(int index) {
return back.codePointBefore(index);
}
/**
* Returns the number of Unicode code points in the specified text
* range of this {@code CharSeq}. The text range begins at the
* specified {@code beginIndex} and extends to the
* {@code char} at index {@code endIndex - 1}. Thus the
* length (in {@code char}s) of the text range is
* {@code endIndex-beginIndex}. Unpaired surrogates within
* the text range count as one code point each.
*
* @param beginIndex the index to the first {@code char} of
* the text range.
* @param endIndex the index after the last {@code char} of
* the text range.
* @return the number of Unicode code points in the specified text
* range
* @throws IndexOutOfBoundsException if the
* {@code beginIndex} is negative, or {@code endIndex}
* is larger than the length of this {@code CharSeq}, or
* {@code beginIndex} is larger than {@code endIndex}.
*/
public int codePointCount(int beginIndex, int endIndex) {
return back.codePointCount(beginIndex, endIndex);
}
/**
* Returns the index within this {@code CharSeq} that is
* offset from the given {@code index} by
* {@code codePointOffset} code points. Unpaired surrogates
* within the text range given by {@code index} and
* {@code codePointOffset} count as one code point each.
*
* @param index the index to be offset
* @param codePointOffset the offset in code points
* @return the index within this {@code CharSeq}
* @throws IndexOutOfBoundsException if {@code index}
* is negative or larger then the length of this
* {@code CharSeq}, or if {@code codePointOffset} is positive
* and the substring starting with {@code index} has fewer
* than {@code codePointOffset} code points,
* or if {@code codePointOffset} is negative and the substring
* before {@code index} has fewer than the absolute value
* of {@code codePointOffset} code points.
*/
public int offsetByCodePoints(int index, int codePointOffset) {
return back.offsetByCodePoints(index, codePointOffset);
}
/**
* Copies characters from this string into the destination character
* array.
* <p>
* The first character to be copied is at index {@code srcBegin};
* the last character to be copied is at index {@code srcEnd-1}
* (thus the total number of characters to be copied is
* {@code srcEnd-srcBegin}). The characters are copied into the
* subarray of {@code dst} starting at index {@code dstBegin}
* and ending at index:
* <blockquote><pre>
* dstbegin + (srcEnd-srcBegin) - 1
* </pre></blockquote>
*
* @param srcBegin index of the first character in the string
* to copy.
* @param srcEnd index after the last character in the string
* to copy.
* @param dst the destination array.
* @param dstBegin the start offset in the destination array.
* @throws IndexOutOfBoundsException If any of the following
* is true:
* <ul><li>{@code srcBegin} is negative.
* <li>{@code srcBegin} is greater than {@code srcEnd}
* <li>{@code srcEnd} is greater than the length of this
* string
* <li>{@code dstBegin} is negative
* <li>{@code dstBegin+(srcEnd-srcBegin)} is larger than
* {@code dst.length}</ul>
*/
public void getChars(int srcBegin, int srcEnd, char dst[], int dstBegin) {
back.getChars(srcBegin, srcEnd, dst, dstBegin);
}
/**
* Encodes this {@code CharSeq} into a sequence of bytes using the named
* charset, storing the result into a new byte array.
*
* <p> The behavior of this method when this string cannot be encoded in
* the given charset is unspecified. The {@link
* java.nio.charset.CharsetEncoder} class should be used when more control
* over the encoding process is required.
*
* @param charsetName The name of a supported {@linkplain java.nio.charset.Charset
* charset}
* @return The resultant byte array
* @throws UnsupportedEncodingException If the named charset is not supported
*/
public byte[] getBytes(String charsetName) throws UnsupportedEncodingException {
return back.getBytes(charsetName);
}
/**
* Encodes this {@code CharSeq} into a sequence of bytes using the given
* {@linkplain java.nio.charset.Charset charset}, storing the result into a
* new byte array.
*
* <p> This method always replaces malformed-input and unmappable-character
* sequences with this charset's default replacement byte array. The
* {@link java.nio.charset.CharsetEncoder} class should be used when more
* control over the encoding process is required.
*
* @param charset The {@linkplain java.nio.charset.Charset} to be used to encode
* the {@code CharSeq}
* @return The resultant byte array
*/
public byte[] getBytes(Charset charset) {
return back.getBytes(charset);
}
/**
* Encodes this {@code CharSeq} into a sequence of bytes using the
* platform's default charset, storing the result into a new byte array.
*
* <p> The behavior of this method when this string cannot be encoded in
* the default charset is unspecified. The {@link
* java.nio.charset.CharsetEncoder} class should be used when more control
* over the encoding process is required.
*
* @return The resultant byte array
*/
public byte[] getBytes() {
return back.getBytes();
}
/**
* Compares this string to the specified {@code StringBuffer}. The result
* is {@code true} if and only if this {@code CharSeq} represents the same
* sequence of characters as the specified {@code StringBuffer}. This method
* synchronizes on the {@code StringBuffer}.
*
* @param sb The {@code StringBuffer} to compare this {@code CharSeq} against
* @return {@code true} if this {@code CharSeq} represents the same
* sequence of characters as the specified {@code StringBuffer},
* {@code false} otherwise
*/
public boolean contentEquals(StringBuffer sb) {
return back.contentEquals(sb);
}
/**
* Compares this string to the specified {@code CharSequence}. The
* result is {@code true} if and only if this {@code CharSeq} represents the
* same sequence of char values as the specified sequence. Note that if the
* {@code CharSequence} is a {@code StringBuffer} then the method
* synchronizes on it.
*
* @param cs The sequence to compare this {@code CharSeq} against
* @return {@code true} if this {@code CharSeq} represents the same
* sequence of char values as the specified sequence, {@code
* false} otherwise
*/
public boolean contentEquals(CharSequence cs) {
return back.contentEquals(cs);
}
/**
* Compares this {@code CharSeq} to another {@code CharSeq}, ignoring case
* considerations. Two strings are considered equal ignoring case if they
* are of the same length and corresponding characters in the two strings
* are equal ignoring case.
*
* <p> Two characters {@code c1} and {@code c2} are considered the same
* ignoring case if at least one of the following is true:
* <ul>
* <li> The two characters are the same (as compared by the
* {@code ==} operator)
* <li> Applying the method {@link
* java.lang.Character#toUpperCase(char)} to each character
* produces the same result
* <li> Applying the method {@link
* java.lang.Character#toLowerCase(char)} to each character
* produces the same result
* </ul>
*
* @param anotherString The {@code CharSeq} to compare this {@code CharSeq} against
* @return {@code true} if the argument is not {@code null} and it
* represents an equivalent {@code CharSeq} ignoring case; {@code
* false} otherwise
* @see #equals(Object)
*/
public boolean equalsIgnoreCase(CharSeq anotherString) {
return back.equalsIgnoreCase(anotherString.back);
}
/**
* Compares two strings lexicographically.
* The comparison is based on the Unicode value of each character in
* the strings. The character sequence represented by this
* {@code CharSeq} object is compared lexicographically to the
* character sequence represented by the argument string. The result is
* a negative integer if this {@code CharSeq} object
* lexicographically precedes the argument string. The result is a
* positive integer if this {@code CharSeq} object lexicographically
* follows the argument string. The result is zero if the strings
* are equal; {@code compareTo} returns {@code 0} exactly when
* the {@link #equals(Object)} method would return {@code true}.
* <p>
* This is the definition of lexicographic ordering. If two strings are
* different, then either they have different characters at some index
* that is a valid index for both strings, or their lengths are different,
* or both. If they have different characters at one or more index
* positions, let <i>k</i> be the smallest such index; then the string
* whose character at position <i>k</i> has the smaller value, as
* determined by using the < operator, lexicographically precedes the
* other string. In this case, {@code compareTo} returns the
* difference of the two character values at position {@code k} in
* the two string -- that is, the value:
* <blockquote><pre>
* this.charAt(k)-anotherString.charAt(k)
* </pre></blockquote>
* If there is no index position at which they differ, then the shorter
* string lexicographically precedes the longer string. In this case,
* {@code compareTo} returns the difference of the lengths of the
* strings -- that is, the value:
* <blockquote><pre>
* this.length()-anotherString.length()
* </pre></blockquote>
*
* @param anotherString the {@code CharSeq} to be compared.
* @return the value {@code 0} if the argument string is equal to
* this string; a value less than {@code 0} if this string
* is lexicographically less than the string argument; and a
* value greater than {@code 0} if this string is
* lexicographically greater than the string argument.
*/
public int compareTo(CharSeq anotherString) {
return back.compareTo(anotherString.back);
}
/**
* Compares two strings lexicographically, ignoring case
* differences. This method returns an integer whose sign is that of
* calling {@code compareTo} with normalized versions of the strings
* where case differences have been eliminated by calling
* {@code Character.toLowerCase(Character.toUpperCase(character))} on
* each character.
* <p>
* Note that this method does <em>not</em> take locale into account,
* and will result in an unsatisfactory ordering for certain locales.
* The java.text package provides <em>collators</em> to allow
* locale-sensitive ordering.
*
* @param str the {@code CharSeq} to be compared.
* @return a negative integer, zero, or a positive integer as the
* specified String is greater than, equal to, or less
* than this String, ignoring case considerations.
*/
public int compareToIgnoreCase(CharSeq str) {
return back.compareToIgnoreCase(str.back);
}
/**
* Tests if two string regions are equal.
* <p>
* A substring of this {@code CharSeq} object is compared to a substring
* of the argument other. The result is true if these substrings
* represent identical character sequences. The substring of this
* {@code CharSeq} object to be compared begins at index {@code toffset}
* and has length {@code len}. The substring of other to be compared
* begins at index {@code ooffset} and has length {@code len}. The
* result is {@code false} if and only if at least one of the following
* is true:
* <ul><li>{@code toffset} is negative.
* <li>{@code ooffset} is negative.
* <li>{@code toffset+len} is greater than the length of this
* {@code CharSeq} object.
* <li>{@code ooffset+len} is greater than the length of the other
* argument.
* <li>There is some nonnegative integer <i>k</i> less than {@code len}
* such that:
* {@code this.charAt(toffset + }<i>k</i>{@code ) != other.charAt(ooffset + }
* <i>k</i>{@code )}
* </ul>
*
* @param toffset the starting offset of the subregion in this string.
* @param other the string argument.
* @param ooffset the starting offset of the subregion in the string
* argument.
* @param len the number of characters to compare.
* @return {@code true} if the specified subregion of this string
* exactly matches the specified subregion of the string argument;
* {@code false} otherwise.
*/
public boolean regionMatches(int toffset, CharSeq other, int ooffset, int len) {
return back.regionMatches(toffset, other.back, ooffset, len);
}
/**
* Tests if two string regions are equal.
* <p>
* A substring of this {@code CharSeq} object is compared to a substring
* of the argument {@code other}. The result is {@code true} if these
* substrings represent character sequences that are the same, ignoring
* case if and only if {@code ignoreCase} is true. The substring of
* this {@code CharSeq} object to be compared begins at index
* {@code toffset} and has length {@code len}. The substring of
* {@code other} to be compared begins at index {@code ooffset} and
* has length {@code len}. The result is {@code false} if and only if
* at least one of the following is true:
* <ul><li>{@code toffset} is negative.
* <li>{@code ooffset} is negative.
* <li>{@code toffset+len} is greater than the length of this
* {@code CharSeq} object.
* <li>{@code ooffset+len} is greater than the length of the other
* argument.
* <li>{@code ignoreCase} is {@code false} and there is some nonnegative
* integer <i>k</i> less than {@code len} such that:
* <blockquote><pre>
* this.charAt(toffset+k) != other.charAt(ooffset+k)
* </pre></blockquote>
* <li>{@code ignoreCase} is {@code true} and there is some nonnegative
* integer <i>k</i> less than {@code len} such that:
* <blockquote><pre>
* Character.toLowerCase(this.charAt(toffset+k)) !=
* Character.toLowerCase(other.charAt(ooffset+k))
* </pre></blockquote>
* and:
* <blockquote><pre>
* Character.toUpperCase(this.charAt(toffset+k)) !=
* Character.toUpperCase(other.charAt(ooffset+k))
* </pre></blockquote>
* </ul>
*
* @param ignoreCase if {@code true}, ignore case when comparing
* characters.
* @param toffset the starting offset of the subregion in this
* string.
* @param other the string argument.
* @param ooffset the starting offset of the subregion in the string
* argument.
* @param len the number of characters to compare.
* @return {@code true} if the specified subregion of this string
* matches the specified subregion of the string argument;
* {@code false} otherwise. Whether the matching is exact
* or case insensitive depends on the {@code ignoreCase}
* argument.
*/
public boolean regionMatches(boolean ignoreCase, int toffset, CharSeq other, int ooffset, int len) {
return back.regionMatches(ignoreCase, toffset, other.back, ooffset, len);
}
@Override
public CharSeq subSequence(int beginIndex, int endIndex) {
if (beginIndex < 0) {
throw new IndexOutOfBoundsException("begin index " + beginIndex + " < 0");
}
if (endIndex > length()) {
throw new IndexOutOfBoundsException("endIndex " + endIndex + " > length " + length());
}
int subLen = endIndex - beginIndex;
if (subLen < 0) {
throw new IndexOutOfBoundsException("beginIndex " + beginIndex + " > endIndex " + endIndex);
}
if (beginIndex == 0 && endIndex == length()) {
return this;
} else {
return CharSeq.of(back.subSequence(beginIndex, endIndex));
}
}
/**
* Tests if the substring of this string beginning at the
* specified index starts with the specified prefix.
*
* @param prefix the prefix.
* @param toffset where to begin looking in this string.
* @return {@code true} if the character sequence represented by the
* argument is a prefix of the substring of this object starting
* at index {@code toffset}; {@code false} otherwise.
* The result is {@code false} if {@code toffset} is
* negative or greater than the length of this
* {@code CharSeq} object; otherwise the result is the same
* as the result of the expression
* <pre>
* this.substring(toffset).startsWith(prefix)
* </pre>
*/
public boolean startsWith(CharSeq prefix, int toffset) {
return back.startsWith(prefix.back, toffset);
}
/**
* Tests if this string starts with the specified prefix.
*
* @param prefix the prefix.
* @return {@code true} if the character sequence represented by the
* argument is a prefix of the character sequence represented by
* this string; {@code false} otherwise.
* Note also that {@code true} will be returned if the
* argument is an empty string or is equal to this
* {@code CharSeq} object as determined by the
* {@link #equals(Object)} method.
*/
public boolean startsWith(CharSeq prefix) {
return back.startsWith(prefix.back);
}
/**
* Tests if this string ends with the specified suffix.
*
* @param suffix the suffix.
* @return {@code true} if the character sequence represented by the
* argument is a suffix of the character sequence represented by
* this object; {@code false} otherwise. Note that the
* result will be {@code true} if the argument is the
* empty string or is equal to this {@code CharSeq} object
* as determined by the {@link #equals(Object)} method.
*/
public boolean endsWith(CharSeq suffix) {
return back.endsWith(suffix.back);
}
/**
* Returns the index within this string of the first occurrence of
* the specified character. If a character with value
* {@code ch} occurs in the character sequence represented by
* this {@code CharSeq} object, then the index (in Unicode
* code units) of the first such occurrence is returned. For
* values of {@code ch} in the range from 0 to 0xFFFF
* (inclusive), this is the smallest value <i>k</i> such that:
* <blockquote><pre>
* this.charAt(<i>k</i>) == ch
* </pre></blockquote>
* is true. For other values of {@code ch}, it is the
* smallest value <i>k</i> such that:
* <blockquote><pre>
* this.codePointAt(<i>k</i>) == ch
* </pre></blockquote>
* is true. In either case, if no such character occurs in this
* string, then {@code -1} is returned.
*
* @param ch a character (Unicode code point).
* @return the index of the first occurrence of the character in the
* character sequence represented by this object, or
* {@code -1} if the character does not occur.
*/
public int indexOf(int ch) {
return back.indexOf(ch);
}
/**
* Returns the index within this string of the first occurrence of the
* specified character, starting the search at the specified index.
* <p>
* If a character with value {@code ch} occurs in the
* character sequence represented by this {@code CharSeq}
* object at an index no smaller than {@code fromIndex}, then
* the index of the first such occurrence is returned. For values
* of {@code ch} in the range from 0 to 0xFFFF (inclusive),
* this is the smallest value <i>k</i> such that:
* <blockquote><pre>
* (this.charAt(<i>k</i>) == ch) {@code &&} (<i>k</i> >= fromIndex)
* </pre></blockquote>
* is true. For other values of {@code ch}, it is the
* smallest value <i>k</i> such that:
* <blockquote><pre>
* (this.codePointAt(<i>k</i>) == ch) {@code &&} (<i>k</i> >= fromIndex)
* </pre></blockquote>
* is true. In either case, if no such character occurs in this
* string at or after position {@code fromIndex}, then
* {@code -1} is returned.
*
* <p>
* There is no restriction on the value of {@code fromIndex}. If it
* is negative, it has the same effect as if it were zero: this entire
* string may be searched. If it is greater than the length of this
* string, it has the same effect as if it were equal to the length of
* this string: {@code -1} is returned.
*
* <p>All indices are specified in {@code char} values
* (Unicode code units).
*
* @param ch a character (Unicode code point).
* @param fromIndex the index to start the search from.
* @return the index of the first occurrence of the character in the
* character sequence represented by this object that is greater
* than or equal to {@code fromIndex}, or {@code -1}
* if the character does not occur.
*/
public int indexOf(int ch, int fromIndex) {
return back.indexOf(ch, fromIndex);
}
/**
* Returns the index within this string of the last occurrence of
* the specified character. For values of {@code ch} in the
* range from 0 to 0xFFFF (inclusive), the index (in Unicode code
* units) returned is the largest value <i>k</i> such that:
* <blockquote><pre>
* this.charAt(<i>k</i>) == ch
* </pre></blockquote>
* is true. For other values of {@code ch}, it is the
* largest value <i>k</i> such that:
* <blockquote><pre>
* this.codePointAt(<i>k</i>) == ch
* </pre></blockquote>
* is true. In either case, if no such character occurs in this
* string, then {@code -1} is returned. The
* {@code CharSeq} is searched backwards starting at the last
* character.
*
* @param ch a character (Unicode code point).
* @return the index of the last occurrence of the character in the
* character sequence represented by this object, or
* {@code -1} if the character does not occur.
*/
public int lastIndexOf(int ch) {
return back.lastIndexOf(ch);
}
/**
* Returns the index within this string of the last occurrence of
* the specified character, searching backward starting at the
* specified index. For values of {@code ch} in the range
* from 0 to 0xFFFF (inclusive), the index returned is the largest
* value <i>k</i> such that:
* <blockquote><pre>
* (this.charAt(<i>k</i>) == ch) {@code &&} (<i>k</i> <= fromIndex)
* </pre></blockquote>
* is true. For other values of {@code ch}, it is the
* largest value <i>k</i> such that:
* <blockquote><pre>
* (this.codePointAt(<i>k</i>) == ch) {@code &&} (<i>k</i> <= fromIndex)
* </pre></blockquote>
* is true. In either case, if no such character occurs in this
* string at or before position {@code fromIndex}, then
* {@code -1} is returned.
*
* <p>All indices are specified in {@code char} values
* (Unicode code units).
*
* @param ch a character (Unicode code point).
* @param fromIndex the index to start the search from. There is no
* restriction on the value of {@code fromIndex}. If it is
* greater than or equal to the length of this string, it has
* the same effect as if it were equal to one less than the
* length of this string: this entire string may be searched.
* If it is negative, it has the same effect as if it were -1:
* -1 is returned.
* @return the index of the last occurrence of the character in the
* character sequence represented by this object that is less
* than or equal to {@code fromIndex}, or {@code -1}
* if the character does not occur before that point.
*/
public int lastIndexOf(int ch, int fromIndex) {
return back.lastIndexOf(ch, fromIndex);
}
/**
* Returns the index within this string of the first occurrence of the
* specified substring.
*
* <p>The returned index is the smallest value <i>k</i> for which:
* <blockquote><pre>
* this.startsWith(str, <i>k</i>)
* </pre></blockquote>
* If no such value of <i>k</i> exists, then {@code -1} is returned.
*
* @param str the substring to search for.
* @return the index of the first occurrence of the specified substring,
* or {@code -1} if there is no such occurrence.
*/
public int indexOf(CharSeq str) {
return back.indexOf(str.back);
}
/**
* Returns the index within this string of the first occurrence of the
* specified substring, starting at the specified index.
*
* <p>The returned index is the smallest value <i>k</i> for which:
* <blockquote><pre>
* <i>k</i> >= fromIndex {@code &&} this.startsWith(str, <i>k</i>)
* </pre></blockquote>
* If no such value of <i>k</i> exists, then {@code -1} is returned.
*
* @param str the substring to search for.
* @param fromIndex the index from which to start the search.
* @return the index of the first occurrence of the specified substring,
* starting at the specified index,
* or {@code -1} if there is no such occurrence.
*/
public int indexOf(CharSeq str, int fromIndex) {
return back.indexOf(str.back, fromIndex);
}
/**
* Returns the index within this string of the last occurrence of the
* specified substring. The last occurrence of the empty string ""
* is considered to occur at the index value {@code this.length()}.
*
* <p>The returned index is the largest value <i>k</i> for which:
* <blockquote><pre>
* this.startsWith(str, <i>k</i>)
* </pre></blockquote>
* If no such value of <i>k</i> exists, then {@code -1} is returned.
*
* @param str the substring to search for.
* @return the index of the last occurrence of the specified substring,
* or {@code -1} if there is no such occurrence.
*/
public int lastIndexOf(CharSeq str) {
return back.lastIndexOf(str.back);
}
/**
* Returns the index within this string of the last occurrence of the
* specified substring, searching backward starting at the specified index.
*
* <p>The returned index is the largest value <i>k</i> for which:
* <blockquote><pre>
* <i>k</i> {@code <=} fromIndex {@code &&} this.startsWith(str, <i>k</i>)
* </pre></blockquote>
* If no such value of <i>k</i> exists, then {@code -1} is returned.
*
* @param str the substring to search for.
* @param fromIndex the index to start the search from.
* @return the index of the last occurrence of the specified substring,
* searching backward from the specified index,
* or {@code -1} if there is no such occurrence.
*/
public int lastIndexOf(CharSeq str, int fromIndex) {
return back.lastIndexOf(str.back, fromIndex);
}
/**
* Returns a string that is a substring of this string. The
* substring begins with the character at the specified index and
* extends to the end of this string. <p>
* Examples:
* <blockquote><pre>
* "unhappy".substring(2) returns "happy"
* "Harbison".substring(3) returns "bison"
* "emptiness".substring(9) returns "" (an empty string)
* </pre></blockquote>
*
* @param beginIndex the beginning index, inclusive.
* @return the specified substring.
* @throws IndexOutOfBoundsException if
* {@code beginIndex} is negative or larger than the
* length of this {@code CharSeq} object.
*/
public CharSeq substring(int beginIndex) {
return CharSeq.of(back.substring(beginIndex));
}
/**
* Returns a string that is a substring of this string. The
* substring begins at the specified {@code beginIndex} and
* extends to the character at index {@code endIndex - 1}.
* Thus the length of the substring is {@code endIndex-beginIndex}.
* <p>
* Examples:
* <blockquote><pre>
* "hamburger".substring(4, 8) returns "urge"
* "smiles".substring(1, 5) returns "mile"
* </pre></blockquote>
*
* @param beginIndex the beginning index, inclusive.
* @param endIndex the ending index, exclusive.
* @return the specified substring.
* @throws IndexOutOfBoundsException if the
* {@code beginIndex} is negative, or
* {@code endIndex} is larger than the length of
* this {@code CharSeq} object, or
* {@code beginIndex} is larger than
* {@code endIndex}.
*/
public CharSeq substring(int beginIndex, int endIndex) {
return CharSeq.of(back.substring(beginIndex, endIndex));
}
@Override
public String stringPrefix() {
return "CharSeq";
}
/**
* Returns a string containing the characters in this sequence in the same
* order as this sequence. The length of the string will be the length of
* this sequence.
*
* @return a string consisting of exactly this sequence of characters
*/
@Override
public String toString() {
return back;
}
/**
* Concatenates the specified string to the end of this string.
* <p>
* If the length of the argument string is {@code 0}, then this
* {@code CharSeq} object is returned. Otherwise, a
* {@code CharSeq} object is returned that represents a character
* sequence that is the concatenation of the character sequence
* represented by this {@code CharSeq} object and the character
* sequence represented by the argument string.<p>
* Examples:
* <blockquote><pre>
* "cares".concat("s") returns "caress"
* "to".concat("get").concat("her") returns "together"
* </pre></blockquote>
*
* @param str the {@code CharSeq} that is concatenated to the end
* of this {@code CharSeq}.
* @return a string that represents the concatenation of this object's
* characters followed by the string argument's characters.
*/
public CharSeq concat(CharSeq str) {
return CharSeq.of(back.concat(str.back));
}
/**
* Tells whether or not this string matches the given <a
* href="../util/regex/Pattern.html#sum">regular expression</a>.
*
* <p> An invocation of this method of the form
* <i>str</i>{@code .matches(}<i>regex</i>{@code )} yields exactly the
* same result as the expression
*
* <blockquote>
* {@link java.util.regex.Pattern}.{@link java.util.regex.Pattern#matches(String, CharSequence)
* matches(<i>regex</i>, <i>str</i>)}
* </blockquote>
*
* @param regex the regular expression to which this string is to be matched
* @return {@code true} if, and only if, this string matches the
* given regular expression
* @throws PatternSyntaxException if the regular expression's syntax is invalid
* @see java.util.regex.Pattern
*/
public boolean matches(String regex) {
return back.matches(regex);
}
/**
* Returns true if and only if this string contains the specified
* sequence of char values.
*
* @param s the sequence to search for
* @return true if this string contains {@code s}, false otherwise
*/
public boolean contains(CharSequence s) {
return back.contains(s);
}
/**
* Replaces the first substring of this string that matches the given <a
* href="../util/regex/Pattern.html#sum">regular expression</a> with the
* given replacement.
*
* <p> An invocation of this method of the form
* <i>str</i>{@code .replaceFirst(}<i>regex</i>{@code ,} <i>repl</i>{@code )}
* yields exactly the same result as the expression
*
* <blockquote>
* <code>
* {@link java.util.regex.Pattern}.{@link
* java.util.regex.Pattern#compile compile}(<i>regex</i>).{@link
* java.util.regex.Pattern#matcher(java.lang.CharSequence) matcher}(<i>str</i>).{@link
* java.util.regex.Matcher#replaceFirst replaceFirst}(<i>repl</i>)
* </code>
* </blockquote>
*
* <p>
* Note that backslashes ({@code \}) and dollar signs ({@code $}) in the
* replacement string may cause the results to be different than if it were
* being treated as a literal replacement string; see
* {@link java.util.regex.Matcher#replaceFirst}.
* Use {@link java.util.regex.Matcher#quoteReplacement} to suppress the special
* meaning of these characters, if desired.
*
* @param regex the regular expression to which this string is to be matched
* @param replacement the string to be substituted for the first match
* @return The resulting {@code CharSeq}
* @throws PatternSyntaxException if the regular expression's syntax is invalid
* @see java.util.regex.Pattern
*/
public CharSeq replaceFirst(String regex, String replacement) {
return CharSeq.of(back.replaceFirst(regex, replacement));
}
/**
* Replaces each substring of this string that matches the given <a
* href="../util/regex/Pattern.html#sum">regular expression</a> with the
* given replacement.
*
* <p> An invocation of this method of the form
* <i>str</i>{@code .replaceAll(}<i>regex</i>{@code ,} <i>repl</i>{@code )}
* yields exactly the same result as the expression
*
* <blockquote>
* <code>
* {@link java.util.regex.Pattern}.{@link
* java.util.regex.Pattern#compile compile}(<i>regex</i>).{@link
* java.util.regex.Pattern#matcher(java.lang.CharSequence) matcher}(<i>str</i>).{@link
* java.util.regex.Matcher#replaceAll replaceAll}(<i>repl</i>)
* </code>
* </blockquote>
*
* <p>
* Note that backslashes ({@code \}) and dollar signs ({@code $}) in the
* replacement string may cause the results to be different than if it were
* being treated as a literal replacement string; see
* {@link java.util.regex.Matcher#replaceAll Matcher.replaceAll}.
* Use {@link java.util.regex.Matcher#quoteReplacement} to suppress the special
* meaning of these characters, if desired.
*
* @param regex the regular expression to which this string is to be matched
* @param replacement the string to be substituted for each match
* @return The resulting {@code CharSeq}
* @throws PatternSyntaxException if the regular expression's syntax is invalid
* @see java.util.regex.Pattern
*/
public CharSeq replaceAll(String regex, String replacement) {
return CharSeq.of(back.replaceAll(regex, replacement));
}
/**
* Replaces each substring of this string that matches the literal target
* sequence with the specified literal replacement sequence. The
* replacement proceeds from the beginning of the string to the end, for
* example, replacing "aa" with "b" in the string "aaa" will result in
* "ba" rather than "ab".
*
* @param target The sequence of char values to be replaced
* @param replacement The replacement sequence of char values
* @return The resulting string
*/
public CharSeq replace(CharSequence target, CharSequence replacement) {
return CharSeq.of(back.replace(target, replacement));
}
/**
* Splits this string around matches of the given
* <a href="../util/regex/Pattern.html#sum">regular expression</a>.
*
* <p> The array returned by this method contains each substring of this
* string that is terminated by another substring that matches the given
* expression or is terminated by the end of the string. The substrings in
* the array are in the order in which they occur in this string. If the
* expression does not match any part of the input then the resulting array
* has just one element, namely this string.
*
* <p> When there is a positive-width match at the beginning of this
* string then an empty leading substring is included at the beginning
* of the resulting array. A zero-width match at the beginning however
* never produces such empty leading substring.
*
* <p> The {@code limit} parameter controls the number of times the
* pattern is applied and therefore affects the length of the resulting
* array. If the limit <i>n</i> is greater than zero then the pattern
* will be applied at most <i>n</i> - 1 times, the array's
* length will be no greater than <i>n</i>, and the array's last entry
* will contain all input beyond the last matched delimiter. If <i>n</i>
* is non-positive then the pattern will be applied as many times as
* possible and the array can have any length. If <i>n</i> is zero then
* the pattern will be applied as many times as possible, the array can
* have any length, and trailing empty strings will be discarded.
*
* <p> The string {@code "boo:and:foo"}, for example, yields the
* following results with these parameters:
*
* <blockquote><table cellpadding=1 cellspacing=0 summary="Split example showing regex, limit, and result">
* <tr>
* <th>Regex</th>
* <th>Limit</th>
* <th>Result</th>
* </tr>
* <tr><td align=center>:</td>
* <td align=center>2</td>
* <td>{@code { "boo", "and:foo" }}</td></tr>
* <tr><td align=center>:</td>
* <td align=center>5</td>
* <td>{@code { "boo", "and", "foo" }}</td></tr>
* <tr><td align=center>:</td>
* <td align=center>-2</td>
* <td>{@code { "boo", "and", "foo" }}</td></tr>
* <tr><td align=center>o</td>
* <td align=center>5</td>
* <td>{@code { "b", "", ":and:f", "", "" }}</td></tr>
* <tr><td align=center>o</td>
* <td align=center>-2</td>
* <td>{@code { "b", "", ":and:f", "", "" }}</td></tr>
* <tr><td align=center>o</td>
* <td align=center>0</td>
* <td>{@code { "b", "", ":and:f" }}</td></tr>
* </table></blockquote>
*
* <p> An invocation of this method of the form
* <i>str.</i>{@code split(}<i>regex</i>{@code ,} <i>n</i>{@code )}
* yields the same result as the expression
*
* <blockquote>
* <code>
* {@link java.util.regex.Pattern}.{@link
* java.util.regex.Pattern#compile compile}(<i>regex</i>).{@link
* java.util.regex.Pattern#split(java.lang.CharSequence, int) split}(<i>str</i>, <i>n</i>)
* </code>
* </blockquote>
*
* @param regex the delimiting regular expression
* @param limit the result threshold, as described above
* @return the array of strings computed by splitting this string
* around matches of the given regular expression
* @throws PatternSyntaxException if the regular expression's syntax is invalid
* @see java.util.regex.Pattern
*/
public CharSeq[] split(String regex, int limit) {
final String[] javaStrings = back.split(regex, limit);
final CharSeq[] strings = new CharSeq[javaStrings.length];
for (int i = 0; i < strings.length; i++) {
strings[i] = of(javaStrings[i]);
}
return strings;
}
/**
* Splits this string around matches of the given <a
* href="../util/regex/Pattern.html#sum">regular expression</a>.
*
* <p> This method works as if by invoking the two-argument {@link
* #split(String, int) split} method with the given expression and a limit
* argument of zero. Trailing empty strings are therefore not included in
* the resulting array.
*
* <p> The string {@code "boo:and:foo"}, for example, yields the following
* results with these expressions:
*
* <blockquote><table cellpadding=1 cellspacing=0 summary="Split examples showing regex and result">
* <tr>
* <th>Regex</th>
* <th>Result</th>
* </tr>
* <tr><td align=center>:</td>
* <td>{@code { "boo", "and", "foo" }}</td></tr>
* <tr><td align=center>o</td>
* <td>{@code { "b", "", ":and:f" }}</td></tr>
* </table></blockquote>
*
* @param regex the delimiting regular expression
* @return the array of strings computed by splitting this string
* around matches of the given regular expression
* @throws PatternSyntaxException if the regular expression's syntax is invalid
* @see java.util.regex.Pattern
*/
public CharSeq[] split(String regex) {
return split(regex, 0);
}
/**
* Converts all of the characters in this {@code CharSeq} to lower
* case using the rules of the given {@code Locale}. Case mapping is based
* on the Unicode Standard version specified by the {@link java.lang.Character Character}
* class. Since case mappings are not always 1:1 char mappings, the resulting
* {@code CharSeq} may be a different length than the original {@code CharSeq}.
* <p>
* Examples of lowercase mappings are in the following table:
* <table border="1" summary="Lowercase mapping examples showing language code of locale, upper case, lower case, and description">
* <tr>
* <th>Language Code of Locale</th>
* <th>Upper Case</th>
* <th>Lower Case</th>
* <th>Description</th>
* </tr>
* <tr>
* <td>tr (Turkish)</td>
* <td>\u0130</td>
* <td>\u0069</td>
* <td>capital letter I with dot above -> small letter i</td>
* </tr>
* <tr>
* <td>tr (Turkish)</td>
* <td>\u0049</td>
* <td>\u0131</td>
* <td>capital letter I -> small letter dotless i </td>
* </tr>
* <tr>
* <td>(all)</td>
* <td>French Fries</td>
* <td>french fries</td>
* <td>lowercased all chars in String</td>
* </tr>
* <tr>
* <td>(all)</td>
* <td><img src="doc-files/capiota.gif" alt="capiota"><img src="doc-files/capchi.gif" alt="capchi">
* <img src="doc-files/captheta.gif" alt="captheta"><img src="doc-files/capupsil.gif" alt="capupsil">
* <img src="doc-files/capsigma.gif" alt="capsigma"></td>
* <td><img src="doc-files/iota.gif" alt="iota"><img src="doc-files/chi.gif" alt="chi">
* <img src="doc-files/theta.gif" alt="theta"><img src="doc-files/upsilon.gif" alt="upsilon">
* <img src="doc-files/sigma1.gif" alt="sigma"></td>
* <td>lowercased all chars in String</td>
* </tr>
* </table>
*
* @param locale use the case transformation rules for this locale
* @return the {@code CharSeq}, converted to lowercase.
* @see String#toLowerCase()
* @see String#toUpperCase()
* @see String#toUpperCase(Locale)
*/
public CharSeq toLowerCase(Locale locale) {
return CharSeq.of(back.toLowerCase(locale));
}
/**
* Converts all of the characters in this {@code CharSeq} to lower
* case using the rules of the default locale. This is equivalent to calling
* {@code toLowerCase(Locale.getDefault())}.
* <p>
* <b>Note:</b> This method is locale sensitive, and may produce unexpected
* results if used for strings that are intended to be interpreted locale
* independently.
* Examples are programming language identifiers, protocol keys, and HTML
* tags.
* For instance, {@code "TITLE".toLowerCase()} in a Turkish locale
* returns {@code "t\u005Cu0131tle"}, where '\u005Cu0131' is the
* LATIN SMALL LETTER DOTLESS I character.
* To obtain correct results for locale insensitive strings, use
* {@code toLowerCase(Locale.ROOT)}.
* <p>
*
* @return the {@code CharSeq}, converted to lowercase.
* @see String#toLowerCase(Locale)
*/
public CharSeq toLowerCase() {
return CharSeq.of(back.toLowerCase(Locale.getDefault()));
}
/**
* Converts all of the characters in this {@code CharSeq} to upper
* case using the rules of the given {@code Locale}. Case mapping is based
* on the Unicode Standard version specified by the {@link java.lang.Character Character}
* class. Since case mappings are not always 1:1 char mappings, the resulting
* {@code CharSeq} may be a different length than the original {@code CharSeq}.
* <p>
* Examples of locale-sensitive and 1:M case mappings are in the following table.
*
* <table border="1" summary="Examples of locale-sensitive and 1:M case mappings. Shows Language code of locale, lower case, upper case, and description.">
* <tr>
* <th>Language Code of Locale</th>
* <th>Lower Case</th>
* <th>Upper Case</th>
* <th>Description</th>
* </tr>
* <tr>
* <td>tr (Turkish)</td>
* <td>\u0069</td>
* <td>\u0130</td>
* <td>small letter i -> capital letter I with dot above</td>
* </tr>
* <tr>
* <td>tr (Turkish)</td>
* <td>\u0131</td>
* <td>\u0049</td>
* <td>small letter dotless i -> capital letter I</td>
* </tr>
* <tr>
* <td>(all)</td>
* <td>\u00df</td>
* <td>\u0053 \u0053</td>
* <td>small letter sharp s -> two letters: SS</td>
* </tr>
* <tr>
* <td>(all)</td>
* <td>Fahrvergnügen</td>
* <td>FAHRVERGNÜGEN</td>
* <td></td>
* </tr>
* </table>
*
* @param locale use the case transformation rules for this locale
* @return the {@code CharSeq}, converted to uppercase.
* @see String#toUpperCase()
* @see String#toLowerCase()
* @see String#toLowerCase(Locale)
*/
public CharSeq toUpperCase(Locale locale) {
return CharSeq.of(back.toUpperCase(locale));
}
/**
* Converts all of the characters in this {@code CharSeq} to upper
* case using the rules of the default locale. This method is equivalent to
* {@code toUpperCase(Locale.getDefault())}.
* <p>
* <b>Note:</b> This method is locale sensitive, and may produce unexpected
* results if used for strings that are intended to be interpreted locale
* independently.
* Examples are programming language identifiers, protocol keys, and HTML
* tags.
* For instance, {@code "title".toUpperCase()} in a Turkish locale
* returns {@code "T\u005Cu0130TLE"}, where '\u005Cu0130' is the
* LATIN CAPITAL LETTER I WITH DOT ABOVE character.
* To obtain correct results for locale insensitive strings, use
* {@code toUpperCase(Locale.ROOT)}.
* <p>
*
* @return the {@code CharSeq}, converted to uppercase.
* @see String#toUpperCase(Locale)
*/
public CharSeq toUpperCase() {
return CharSeq.of(back.toUpperCase(Locale.getDefault()));
}
/**
* Returns a string whose value is this string, with any leading and trailing
* whitespace removed.
* <p>
* If this {@code CharSeq} object represents an empty character
* sequence, or the first and last characters of character sequence
* represented by this {@code CharSeq} object both have codes
* greater than {@code '\u005Cu0020'} (the space character), then a
* reference to this {@code CharSeq} object is returned.
* <p>
* Otherwise, if there is no character with a code greater than
* {@code '\u005Cu0020'} in the string, then a
* {@code CharSeq} object representing an empty string is
* returned.
* <p>
* Otherwise, let <i>k</i> be the index of the first character in the
* string whose code is greater than {@code '\u005Cu0020'}, and let
* <i>m</i> be the index of the last character in the string whose code
* is greater than {@code '\u005Cu0020'}. A {@code CharSeq}
* object is returned, representing the substring of this string that
* begins with the character at index <i>k</i> and ends with the
* character at index <i>m</i>-that is, the result of
* {@code this.substring(k, m + 1)}.
* <p>
* This method may be used to trim whitespace (as defined above) from
* the beginning and end of a string.
*
* @return A string whose value is this string, with any leading and trailing white
* space removed, or this string if it has no leading or
* trailing white space.
*/
public CharSeq trim() {
return of(back.trim());
}
/**
* Converts this string to a new character array.
*
* @return a newly allocated character array whose length is the length
* of this string and whose contents are initialized to contain
* the character sequence represented by this string.
*/
public char[] toCharArray() {
return back.toCharArray();
}
@FunctionalInterface
interface CharUnaryOperator {
char apply(char c);
}
@FunctionalInterface
interface CharFunction<R> {
R apply(char c);
}
}
interface CharSeqModule {
interface Combinations {
static IndexedSeq<CharSeq> apply(CharSeq elements, int k) {
if (k == 0) {
return Vector.of(CharSeq.empty());
} else {
return elements.zipWithIndex().flatMap(
t -> apply(elements.drop(t._2 + 1), (k - 1)).map((CharSeq c) -> c.prepend(t._1))
);
}
}
}
}
|
package com.github.kostyasha.github.integration.branch.events.impl;
import com.github.kostyasha.github.integration.branch.GitHubBranch;
import com.github.kostyasha.github.integration.branch.GitHubBranchCause;
import com.github.kostyasha.github.integration.branch.GitHubBranchRepository;
import com.github.kostyasha.github.integration.branch.GitHubBranchTrigger;
import com.github.kostyasha.github.integration.branch.events.GitHubBranchEvent;
import com.github.kostyasha.github.integration.branch.events.GitHubBranchEventDescriptor;
import com.github.kostyasha.github.integration.branch.events.impl.commitchecks.GitHubBranchCommitCheck;
import com.github.kostyasha.github.integration.branch.events.impl.commitchecks.GitHubBranchCommitCheckDescriptor;
import hudson.Extension;
import hudson.model.TaskListener;
import net.sf.json.JSONObject;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.NoExternalUse;
import org.kohsuke.github.GHBranch;
import org.kohsuke.github.GHCommit;
import org.kohsuke.github.GHCompare;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.StaplerRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;
import java.io.IOException;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;
import static org.jenkinsci.plugins.github.pullrequest.utils.ObjectsUtil.isNull;
/**
* This branch event acts as a wrapper around checks that can be performed against commit data that requires an additional round trip to
* GitHub to retrieve.
* <p>
* Commit data is retrieved and then passed to each implementing instance of <code>GitHubBranchCommitCheck</code> to determine information
* about the commit should trigger a build.
* </p>
*
* @author Kanstantsin Shautsou
* @author Jae Gangemi
*/
public class GitHubBranchCommitEvent extends GitHubBranchEvent {
private static final String DISPLAY_NAME = "Commit Checks";
private static final Logger LOG = LoggerFactory.getLogger(GitHubBranchCommitEvent.class);
private List<GitHubBranchCommitCheck> checks = new ArrayList<>();
/**
* For groovy UI
*/
@Restricted(value = NoExternalUse.class)
public GitHubBranchCommitEvent() {
}
@DataBoundConstructor
public GitHubBranchCommitEvent(List<GitHubBranchCommitCheck> checks) {
this.checks = checks;
}
@Override
public GitHubBranchCause check(GitHubBranchTrigger trigger, GHBranch remoteBranch, @CheckForNull GitHubBranch localBranch,
GitHubBranchRepository localRepo, TaskListener listener)
throws IOException {
final PrintStream logger = listener.getLogger();
Function<GitHubBranchCommitCheck, GitHubBranchCause> function;
if (localBranch == null) {
GHCommit commit = getLastCommit(remoteBranch);
function = event -> event.check(remoteBranch, localRepo, commit);
} else {
GHCompare.Commit[] commits = getComparedCommits(localBranch, remoteBranch);
function = event -> event.check(remoteBranch, localRepo, commits);
}
return check(remoteBranch, function, logger);
}
// visible for testing to avoid complex mocking
GHCompare.Commit[] getComparedCommits(GitHubBranch localBranch, GHBranch remoteBranch) throws IOException {
String previous = localBranch.getCommitSha();
String current = remoteBranch.getSHA1();
LOG.debug("Comparing previous hash [{}] with current hash [{}]", previous, current);
return remoteBranch.getOwner()
.getCompare(previous, current)
.getCommits();
}
// visible for testing to avoid complex mocking
GHCommit getLastCommit(GHBranch remoteBranch) throws IOException {
return remoteBranch.getOwner().getCommit(remoteBranch.getSHA1());
}
@Nonnull
public List<GitHubBranchCommitCheck> getChecks() {
if (isNull(checks)) {
checks = new ArrayList<>();
}
return checks;
}
public void setChecks(List<GitHubBranchCommitCheck> checks) {
this.checks = checks;
}
private GitHubBranchCause check(GHBranch remoteBranch, Function<GitHubBranchCommitCheck, GitHubBranchCause> function,
PrintStream logger) {
List<GitHubBranchCause> causes = checks.stream()
.map(function::apply)
.filter(Objects::nonNull)
.collect(Collectors.toList());
String name = remoteBranch.getName();
if (causes.isEmpty()) {
LOG.debug("Commits for branch [{}] had no effect, not triggering run.", name);
return null;
}
GitHubBranchCause cause = causes.get(0);
LOG.info("Building branch [{}] skipped due to commit check: {}", name, cause.getReason());
logger.printf("Building branch [%s] skipped due to commit check: %s", name, cause.getReason());
return cause;
}
@Extension
public static class DescriptorImpl extends GitHubBranchEventDescriptor {
@Override
public boolean configure(StaplerRequest req, JSONObject formData) throws FormException {
req.bindJSON(this, formData);
save();
return super.configure(req, formData);
}
@Override
public final String getDisplayName() {
return DISPLAY_NAME;
}
public List<GitHubBranchCommitCheckDescriptor> getEventDescriptors() {
return GitHubBranchCommitCheckDescriptor.all();
}
}
}
|
package org.eclipse.persistence.testing.tests.jpa.jpaadvancedproperties;
import java.util.ArrayList;
import java.util.Vector;
import javax.persistence.EntityManager;
import junit.extensions.TestSetup;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.eclipse.persistence.expressions.Expression;
import org.eclipse.persistence.expressions.ExpressionBuilder;
import org.eclipse.persistence.internal.jpa.EJBQueryImpl;
import org.eclipse.persistence.queries.ReadAllQuery;
import org.eclipse.persistence.sessions.DatabaseSession;
import org.eclipse.persistence.sessions.UnitOfWork;
import org.eclipse.persistence.testing.framework.junit.JUnitTestCase;
import org.eclipse.persistence.sessions.*;
import org.eclipse.persistence.testing.models.jpa.jpaadvancedproperties.Customer;
import org.eclipse.persistence.testing.models.jpa.jpaadvancedproperties.ModelExamples;
import org.eclipse.persistence.testing.models.jpa.jpaadvancedproperties.JPAPropertiesRelationshipTableManager;
/**
* JUnit test case(s) for the TopLink JPAAdvPropertiesJUnitTestCase.
*/
public class JPAAdvPropertiesJUnitTestCase extends JUnitTestCase {
private static String persistenceUnitName = "JPAADVProperties";
public JPAAdvPropertiesJUnitTestCase() {
super();
}
public JPAAdvPropertiesJUnitTestCase(String name) {
super(name);
}
public static Test suite() {
TestSuite suite = new TestSuite("JPA Advanced Properties Model");
suite.addTest(new JPAAdvPropertiesJUnitTestCase("testSessionXMLProperty"));
suite.addTest(new JPAAdvPropertiesJUnitTestCase("testSessionEventListenerProperty"));
suite.addTest(new JPAAdvPropertiesJUnitTestCase("testExceptionHandlerProperty"));
suite.addTest(new JPAAdvPropertiesJUnitTestCase("testNativeSQLProperty"));
suite.addTest(new JPAAdvPropertiesJUnitTestCase("testCacheStatementsAndItsSizeProperty"));
suite.addTest(new JPAAdvPropertiesJUnitTestCase("testBatchwritingProperty"));
suite.addTest(new JPAAdvPropertiesJUnitTestCase("testCopyDescriptorNamedQueryToSessionProperty"));
suite.addTest(new JPAAdvPropertiesJUnitTestCase("testLoggingTyperProperty"));
suite.addTest(new JPAAdvPropertiesJUnitTestCase("testProfilerTyperProperty"));
return new TestSetup(suite) {
protected void setUp(){
DatabaseSession session = JUnitTestCase.getServerSession(persistenceUnitName);
JPAPropertiesRelationshipTableManager tm = new JPAPropertiesRelationshipTableManager();
tm.replaceTables(session);
}
protected void tearDown() {
clearCache();
}
};
}
public void testSessionEventListenerProperty() {
EntityManager em = createEntityManager(persistenceUnitName);
org.eclipse.persistence.sessions.server.ServerSession session = ((org.eclipse.persistence.jpa.JpaEntityManager)em.getDelegate()).getServerSession();
try {
//Create new customer
em.getTransaction().begin();
Customer customer = ModelExamples.customerExample1();
em.persist(customer);
Integer customerId = customer.getCustomerId();
em.getTransaction().commit();
//Purge it
em.getTransaction().begin();
em.remove(em.find(org.eclipse.persistence.testing.models.jpa.jpaadvancedproperties.Customer.class, customerId));
em.getTransaction().commit();
Vector listeners = session.getEventManager().getListeners();
boolean doseCustomizedSessionEventListenerExists=false;
for (int i =0;i<listeners.size();i++){
Object aListener = listeners.get(i);
if(aListener instanceof CustomizedSessionEventListener){
doseCustomizedSessionEventListenerExists=true;
CustomizedSessionEventListener requiredListener = ((CustomizedSessionEventListener)aListener);
if (!requiredListener.preCommitTransaction) {
assertTrue(" The preCommitTransaction event did not fire", true);
}
if (!requiredListener.postCommitTransaction) {
assertTrue("The postCommitTransaction event did not fire", true);
}
if (!requiredListener.preBeginTransaction) {
assertTrue("The preBeginTransaction event did not fire", true);
}
if (!requiredListener.postBeginTransaction) {
assertTrue("The postBeginTransaction event did not fire", true);
}
if (!requiredListener.postLogin) {
assertTrue("The postlogin event did not fire", true);
}
if (!requiredListener.preLogin) {
assertTrue("The preLogin event did not fire", true);
}
}
}
if(!doseCustomizedSessionEventListenerExists){
assertTrue("The session event listener specified by the property eclipselink.session-event-listener in persistence.xml not be processed properly.", true);
}
} catch (RuntimeException e) {
if (em.getTransaction().isActive()){
em.getTransaction().rollback();
}
throw e;
}finally{
em.close();
}
}
public void testExceptionHandlerProperty() {
EntityManager em = createEntityManager(persistenceUnitName);
org.eclipse.persistence.sessions.server.ServerSession session = ((org.eclipse.persistence.jpa.JpaEntityManager)em.getDelegate()).getServerSession();
Expression exp = new ExpressionBuilder().get("name1").equal("George W.");
try {
Object result = session.readObject(Customer.class, exp);
if(!((String)result).equals("return from CustomizedExceptionHandler")){
assertTrue("The exception handler specified by the property eclipselink.exception-handler in persistence.xml not be processed.", true);
}
} finally {
em.close();
}
}
public void testNativeSQLProperty() {
EntityManager em = createEntityManager(persistenceUnitName);
org.eclipse.persistence.sessions.server.ServerSession session = ((org.eclipse.persistence.jpa.JpaEntityManager)em.getDelegate()).getServerSession();
if(!session.getProject().getLogin().shouldUseNativeSQL()){
assertTrue("The native sql flag specified as true by the property eclipselink.jdbc.native-sql in persistence.xml, it however read as false.", true);
}
em.close();
}
public void testBatchwritingProperty(){
EntityManager em = createEntityManager(persistenceUnitName);
org.eclipse.persistence.sessions.server.ServerSession session = ((org.eclipse.persistence.jpa.JpaEntityManager)em.getDelegate()).getServerSession();
if(!(session.getPlatform().usesBatchWriting() &&
!session.getPlatform().usesJDBCBatchWriting() &&
!session.getPlatform().usesNativeBatchWriting())){
assertTrue("The BatcheWriting setting set to BUFFERED by the property eclipselink.jdbc.batch-writing in persistence.xml, JDBC batch writing or natvie batch writing however may be wrong.", true);
}
em.close();
}
public void testCopyDescriptorNamedQueryToSessionProperty(){
EntityManager em = createEntityManager(persistenceUnitName);
org.eclipse.persistence.sessions.server.ServerSession session = ((org.eclipse.persistence.jpa.JpaEntityManager)em.getDelegate()).getServerSession();
org.eclipse.persistence.queries.DatabaseQuery query = session.getQuery("customerReadByName");
if(query == null){
assertTrue("The copy descriptor named query is enable by the property eclipselink.session.include.descriptor.queries in persistence.xml, one descriptor named query has not been copied to the session", true);
}
em.close();
}
public void testCacheStatementsAndItsSizeProperty() {
EntityManager em = createEntityManager(persistenceUnitName);
org.eclipse.persistence.sessions.server.ServerSession session = ((org.eclipse.persistence.jpa.JpaEntityManager)em.getDelegate()).getServerSession();
if(session.getConnectionPools().size()>0){//And if connection pooling is configured,
if(!session.getProject().getLogin().shouldCacheAllStatements()){
assertTrue("Caching all statements flag set equals to true by property eclipselink.jdbc.cache-statements in persistence.xml, it however read as false.", true);
}
}
if(!(session.getProject().getLogin().getStatementCacheSize()==100)){
assertTrue("Statiment cache size set to 100 by property eclipselink.jdbc.cache-statements in persistence.xml, it however read as wrong size.", true);
}
em.close();
}
public void testLoggingTyperProperty(){
EntityManager em = createEntityManager(persistenceUnitName);
org.eclipse.persistence.sessions.server.ServerSession session = ((org.eclipse.persistence.jpa.JpaEntityManager)em.getDelegate()).getServerSession();
if(!(session.getSessionLog() instanceof org.eclipse.persistence.logging.JavaLog)){
assertTrue("Logging type set to JavaLog, it however has been detected as different type logger.", true);
}
em.close();
}
public void testProfilerTyperProperty(){
EntityManager em = createEntityManager(persistenceUnitName);
org.eclipse.persistence.sessions.server.ServerSession session = ((org.eclipse.persistence.jpa.JpaEntityManager)em.getDelegate()).getServerSession();
if(!(session.getSessionLog() instanceof org.eclipse.persistence.tools.profiler.PerformanceProfiler)){
assertTrue("Profiler type set to PerformanceProfiler, it however has been detected as different type Profiler.", true);
}
em.close();
em = createEntityManager("JPAADVProperties2");
session = ((org.eclipse.persistence.jpa.JpaEntityManager)em.getDelegate()).getServerSession();
if(!(session.getProfiler() instanceof org.eclipse.persistence.tools.profiler.QueryMonitor)){
assertTrue("Profiler type set to QueryMonitor, it however has been detected as different type profiler.", true);
}
em.close();
em = createEntityManager("JPAADVProperties3");
session = ((org.eclipse.persistence.jpa.JpaEntityManager)em.getDelegate()).getServerSession();
if((session.getSessionLog() !=null)){
assertTrue("no profiler has been set,it however has been detected.", true);
}
em.close();
}
public void testSessionXMLProperty() {
Integer customerId;
EntityManager em = createEntityManager(persistenceUnitName);
//Create customer
em.getTransaction().begin();
try {
Customer customer = ModelExamples.customerExample1();
ArrayList orders = new ArrayList();
orders.add(ModelExamples.orderExample1());
orders.add(ModelExamples.orderExample2());
orders.add(ModelExamples.orderExample3());
customer.setOrders(orders);
em.persist(customer);
customerId = customer.getCustomerId();
em.getTransaction().commit();
} catch (RuntimeException e) {
if (em.getTransaction().isActive()){
em.getTransaction().rollback();
}
em.close();
throw e;
}
//Find customer
em.getTransaction().begin();
Customer cm1 = em.find(org.eclipse.persistence.testing.models.jpa.jpaadvancedproperties.Customer.class, customerId);
if(cm1==null){
assertTrue("Error finding customer ", true);
}
ArrayList orders = (ArrayList)cm1.getOrders();
if(orders == null || orders.size()!=3){
assertTrue("Error finding order pertaining to the customer ", true);
}
//Query the customer
Customer cm2 = null;
try {
EJBQueryImpl query = (EJBQueryImpl) createEntityManager(persistenceUnitName).createNamedQuery("customerReadByName");
query.setParameter("name", "George W.");
cm2 = (Customer) query.getSingleResult();
}catch (RuntimeException e) {
if (em.getTransaction().isActive()){
em.getTransaction().rollback();
}
em.close();
throw e;
}
assertTrue("Error executing named query 'customerReadByName'", cm2 != null);
//Update customer
String originalName = null;
try {
Customer cm = em.find(org.eclipse.persistence.testing.models.jpa.jpaadvancedproperties.Customer.class, customerId);
originalName=cm.getName();
cm.setName(originalName+"-modified");
em.merge(cm);
em.getTransaction().commit();
} catch (RuntimeException e) {
if (em.getTransaction().isActive()){
em.getTransaction().rollback();
}
em.close();
throw e;
}
clearCache();
Customer cm3 = em.find(org.eclipse.persistence.testing.models.jpa.jpaadvancedproperties.Customer.class, customerId);
assertTrue("Error updating Customer", cm3.getName().equals(originalName+"-modified"));
//Delete customer
em.getTransaction().begin();
try {
em.remove(em.find(org.eclipse.persistence.testing.models.jpa.jpaadvancedproperties.Customer.class, customerId));
em.getTransaction().commit();
} catch (RuntimeException e) {
if (em.getTransaction().isActive()){
em.getTransaction().rollback();
}
em.close();
throw e;
}
assertTrue("Error deleting Customer", em.find(org.eclipse.persistence.testing.models.jpa.jpaadvancedproperties.Customer.class, customerId) == null);
}
}
|
package org.opendaylight.ovsdb.openstack.netvirt.sfc.standalone.openflow13;
import com.google.common.collect.Lists;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import org.opendaylight.controller.md.sal.binding.api.DataBroker;
import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
import org.opendaylight.ovsdb.openstack.netvirt.api.Southbound;
import org.opendaylight.ovsdb.openstack.netvirt.sfc.NshUtils;
import org.opendaylight.ovsdb.utils.mdsal.openflow.ActionUtils;
import org.opendaylight.ovsdb.utils.mdsal.openflow.FlowUtils;
import org.opendaylight.ovsdb.utils.mdsal.openflow.InstructionUtils;
import org.opendaylight.ovsdb.utils.mdsal.openflow.MatchUtils;
import org.opendaylight.ovsdb.utils.mdsal.utils.MdsalUtils;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev150317.access.lists.acl.access.list.entries.ace.Matches;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev150317.access.lists.acl.access.list.entries.ace.matches.ace.type.AceEth;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev150317.access.lists.acl.access.list.entries.ace.matches.ace.type.AceIp;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev150317.access.lists.acl.access.list.entries.ace.matches.ace.type.ace.ip.ace.ip.version.AceIpv4;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev100924.MacAddress;
import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.list.Action;
import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.list.ActionBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.list.ActionKey;
import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowId;
import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.FlowBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.FlowKey;
import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.flow.InstructionsBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.flow.MatchBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.instruction.ApplyActionsCase;
import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.instruction.ApplyActionsCaseBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.instruction.apply.actions._case.ApplyActionsBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.list.Instruction;
import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.list.InstructionBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.list.InstructionKey;
import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowjava.nx.match.rev140421.NxmNxReg;
import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowjava.nx.match.rev140421.NxmNxReg0;
import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.action.rev140714.dst.choice.grouping.dst.choice.DstNxRegCaseBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class SfcClassifier {
private static final Logger LOG = LoggerFactory.getLogger(SfcClassifier.class);
private DataBroker dataBroker;
private Southbound southbound;
private MdsalUtils mdsalUtils;
public final static long REG_VALUE_FROM_LOCAL = 0x1L;
public final static long REG_VALUE_FROM_REMOTE = 0x2L;
public static final Class<? extends NxmNxReg> REG_FIELD = NxmNxReg0.class;
private static final String OPENFLOW = "openflow:";
public SfcClassifier(DataBroker dataBroker, Southbound southbound, MdsalUtils mdsalUtils) {
this.dataBroker = dataBroker;
this.southbound = southbound;
this.mdsalUtils = mdsalUtils;
}
/*
* (TABLE:50) EGRESS VM TRAFFIC TOWARDS TEP with NSH header
* MATCH: Match fields passed through ACL entry
* INSTRUCTION: SET TUNNELID AND GOTO TABLE TUNNEL TABLE (N)
* TABLE=0,IN_PORT=2,DL_SRC=00:00:00:00:00:01 \
* ACTIONS=SET_FIELD:5->TUN_ID,GOTO_TABLE=1"
*/
public void programSfcClassiferFlows(Long dpidLong, short writeTable, String ruleName, Matches match,
NshUtils nshHeader, long tunnelOfPort, boolean write) {
NodeBuilder nodeBuilder = FlowUtils.createNodeBuilder(dpidLong);
FlowBuilder flowBuilder = new FlowBuilder();
String flowName = "sfcClass_" + ruleName + "_" + nshHeader.getNshNsp();
FlowUtils.initFlowBuilder(flowBuilder, flowName, writeTable);
MatchBuilder matchBuilder = buildMatch(match);
flowBuilder.setMatch(matchBuilder.build());
if (write) {
List<Action> actionList = getNshAction(nshHeader);
ActionBuilder ab = new ActionBuilder();
ab.setAction(ActionUtils.outputAction(FlowUtils.getNodeConnectorId(dpidLong, tunnelOfPort)));
ab.setOrder(actionList.size());
ab.setKey(new ActionKey(actionList.size()));
actionList.add(ab.build());
ApplyActionsBuilder aab = new ApplyActionsBuilder();
aab.setAction(actionList);
InstructionBuilder ib = new InstructionBuilder();
ib.setInstruction(new ApplyActionsCaseBuilder().setApplyActions(aab.build()).build());
ib.setOrder(0);
ib.setKey(new InstructionKey(0));
List<Instruction> instructions = Lists.newArrayList();
instructions.add(ib.build());
InstructionsBuilder isb = new InstructionsBuilder();
isb.setInstruction(instructions);
flowBuilder.setInstructions(isb.build());
writeFlow(flowBuilder, nodeBuilder);
} else {
removeFlow(flowBuilder, nodeBuilder);
}
}
public void programEgressSfcClassiferFlows(Long dpidLong, short writeTable, String ruleName,
Matches match, NshUtils nshHeader,
long tunnelOfPort, long outOfPort, boolean write) {
NodeBuilder nodeBuilder = FlowUtils.createNodeBuilder(dpidLong);
FlowBuilder flowBuilder = new FlowBuilder();
String flowName = "egressSfcClass_" + ruleName + "_" + nshHeader.getNshNsp() + "_" + nshHeader.getNshNsi();
FlowUtils.initFlowBuilder(flowBuilder, flowName, writeTable);
MatchBuilder matchBuilder = new MatchBuilder();
flowBuilder.setMatch(MatchUtils.createInPortMatch(matchBuilder, dpidLong, tunnelOfPort).build());
flowBuilder.setMatch(
MatchUtils.createTunnelIDMatch(matchBuilder, BigInteger.valueOf(nshHeader.getNshMetaC2())).build());
flowBuilder.setMatch(MatchUtils.addNxNspMatch(matchBuilder, nshHeader.getNshNsp()).build());
flowBuilder.setMatch(MatchUtils.addNxNsiMatch(matchBuilder, nshHeader.getNshNsi()).build());
if (write) {
List<Action> actionList = new ArrayList<>();
ActionBuilder ab = new ActionBuilder();
ab.setAction(ActionUtils.nxLoadRegAction(new DstNxRegCaseBuilder().setNxReg(REG_FIELD).build(),
BigInteger.valueOf(REG_VALUE_FROM_REMOTE)));
ab.setOrder(0);
ab.setKey(new ActionKey(0));
actionList.add(ab.build());
ab.setAction(ActionUtils.outputAction(FlowUtils.getNodeConnectorId(dpidLong, outOfPort)));
ab.setOrder(1);
ab.setKey(new ActionKey(1));
actionList.add(ab.build());
ApplyActionsBuilder aab = new ApplyActionsBuilder();
aab.setAction(actionList);
InstructionBuilder ib = new InstructionBuilder();
ib.setInstruction(new ApplyActionsCaseBuilder().setApplyActions(aab.build()).build());
ib.setOrder(0);
ib.setKey(new InstructionKey(0));
List<Instruction> instructions = new ArrayList<>();
instructions.add(ib.build());
InstructionsBuilder isb = new InstructionsBuilder();
isb.setInstruction(instructions);
flowBuilder.setInstructions(isb.build());
writeFlow(flowBuilder, nodeBuilder);
} else {
removeFlow(flowBuilder, nodeBuilder);
}
}
private List<Action> getNshAction(NshUtils header) {
// Build the Actions to Add the NSH Header
org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.Action nshC1Load =
ActionUtils.nxLoadNshc1RegAction(header.getNshMetaC1());
org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.Action nshC2Load =
ActionUtils.nxLoadNshc2RegAction(header.getNshMetaC2());
org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.Action nspLoad =
ActionUtils.nxSetNspAction(header.getNshNsp());
org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.Action nsiLoad =
ActionUtils.nxSetNsiAction(header.getNshNsi());
org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.Action loadChainTunVnid =
ActionUtils.nxLoadTunIdAction(BigInteger.valueOf(header.getNshNsp()), false);
org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.Action loadChainTunDest =
ActionUtils.nxLoadTunIPv4Action(header.getNshTunIpDst().getValue(), false);
int count = 0;
List<Action> actionList = Lists.newArrayList();
actionList.add(new ActionBuilder().setOrder(count++).setAction(nshC1Load).build());
actionList.add(new ActionBuilder().setOrder(count++).setAction(nshC2Load).build());
actionList.add(new ActionBuilder().setOrder(count++).setAction(nspLoad).build());
actionList.add(new ActionBuilder().setOrder(count++).setAction(nsiLoad).build());
actionList.add(new ActionBuilder().setOrder(count++).setAction(loadChainTunDest).build());
actionList.add(new ActionBuilder().setOrder(count++).setAction(loadChainTunVnid).build());
return actionList;
}
public void programLocalInPort(Long dpidLong, String segmentationId, Long inPort,
short writeTable, short goToTableId, Matches match, boolean write) {
NodeBuilder nodeBuilder = FlowUtils.createNodeBuilder(dpidLong);
FlowBuilder flowBuilder = new FlowBuilder();
String flowName = "sfcIngress_" + segmentationId + "_" + inPort;
FlowUtils.initFlowBuilder(flowBuilder, flowName, writeTable);
MatchBuilder matchBuilder = buildMatch(match);
flowBuilder.setMatch(matchBuilder.build());
flowBuilder.setMatch(MatchUtils.createInPortMatch(matchBuilder, dpidLong, inPort).build());
if (write) {
InstructionBuilder ib = new InstructionBuilder();
InstructionsBuilder isb = new InstructionsBuilder();
List<Instruction> instructions = Lists.newArrayList();
InstructionUtils.createSetTunnelIdInstructions(ib, new BigInteger(segmentationId));
ApplyActionsCase aac = (ApplyActionsCase) ib.getInstruction();
List<Action> actionList = aac.getApplyActions().getAction();
// TODO: Mark the packets as sfc classified?
ActionBuilder ab = new ActionBuilder();
ab.setAction(ActionUtils.nxLoadRegAction(new DstNxRegCaseBuilder().setNxReg(REG_FIELD).build(),
BigInteger.valueOf(REG_VALUE_FROM_LOCAL)));
ab.setOrder(1);
ab.setKey(new ActionKey(1));
actionList.add(ab.build());
ib.setOrder(0);
ib.setKey(new InstructionKey(0));
instructions.add(ib.build());
// Next service GOTO Instructions Need to be appended to the List
ib = InstructionUtils.createGotoTableInstructions(new InstructionBuilder(), goToTableId);
ib.setOrder(1);
ib.setKey(new InstructionKey(1));
instructions.add(ib.build());
isb.setInstruction(instructions);
flowBuilder.setInstructions(isb.build());
writeFlow(flowBuilder, nodeBuilder);
} else {
removeFlow(flowBuilder, nodeBuilder);
}
}
public MatchBuilder buildMatch(Matches matches) {
MatchBuilder matchBuilder = new MatchBuilder();
if (matches.getAceType() instanceof AceIp) {
AceIp aceIp = (AceIp)matches.getAceType();
if (aceIp.getAceIpVersion() instanceof AceIpv4) {
//AceIpv4 aceIpv4 = (AceIpv4) aceIp.getAceIpVersion();
//MatchUtils.createSrcL3IPv4Match(matchBuilder, aceIpv4.getSourceIpv4Network());
//MatchUtils.createDstL3IPv4Match(matchBuilder, aceIpv4.getDestinationIpv4Network());
MatchUtils.createIpProtocolMatch(matchBuilder, aceIp.getProtocol());
MatchUtils.addLayer4Match(matchBuilder, aceIp.getProtocol().intValue(), 0,
aceIp.getDestinationPortRange().getLowerPort().getValue().intValue());
}
} else if (matches.getAceType() instanceof AceEth) {
AceEth aceEth = (AceEth) matches.getAceType();
MatchUtils.createEthSrcMatch(matchBuilder, new MacAddress(aceEth.getSourceMacAddress().getValue()));
MatchUtils.createDestEthMatch(matchBuilder, new MacAddress(aceEth.getDestinationMacAddress().getValue()),
new MacAddress(aceEth.getDestinationMacAddressMask().getValue()));
}
LOG.info("buildMatch: {}", matchBuilder.build());
return matchBuilder;
}
protected void writeFlow(FlowBuilder flowBuilder, NodeBuilder nodeBuilder) {
LOG.debug("writeFlow: flowBuilder: {}, nodeBuilder: {}", flowBuilder.build(), nodeBuilder.build());
mdsalUtils.merge(LogicalDatastoreType.CONFIGURATION, FlowUtils.createNodePath(nodeBuilder),
nodeBuilder.build());
mdsalUtils.put(LogicalDatastoreType.CONFIGURATION, FlowUtils.createFlowPath(flowBuilder, nodeBuilder),
flowBuilder.build());
}
protected void removeFlow(FlowBuilder flowBuilder, NodeBuilder nodeBuilder) {
mdsalUtils.delete(LogicalDatastoreType.CONFIGURATION, FlowUtils.createFlowPath(flowBuilder, nodeBuilder));
}
}
|
package org.springsource.ide.eclipse.gradle.core.classpathcontainer;
import java.util.Collection;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.SubProgressMonitor;
import org.eclipse.core.runtime.jobs.Job;
import org.springsource.ide.eclipse.gradle.core.GradleCore;
import org.springsource.ide.eclipse.gradle.core.GradleProject;
import org.springsource.ide.eclipse.gradle.core.util.ExceptionUtil;
import org.springsource.ide.eclipse.gradle.core.util.GradleRunnable;
import org.springsource.ide.eclipse.gradle.core.util.JobUtil;
/**
* Manages a Job that refreshes classpath containers for all projects in
* workspace, ensuring that models needed for proper Jar remapping are
* present in the model cache before actually requesting classpath
* container updates.
* <p>
* This refresh is like a 'second' tier update that gets scheduled by a
* first tier update. First tier updates will populate containers with
* dependencies but only do jar remmaping if the publications models
* are already present in the cache. Since creating these models
* can be very slow (if large numbers of them are involved) the first tier
* refresh does not wait for these models. Instead, first tier refresh
* will take notice when these models are missing and proceed to populate
* the classpath. It will then request this second tier refresh to be
* scheduled.
* <p>
* This refresh is also triggered directly from a project open/close
* listener to perform 'quick' recomputation of classpath with updated
* remappings, but without refreshing model caches.
*
* @author Kris De Volder
*/
public class JarRemapRefresher {
public static final boolean DEBUG = (""+Platform.getLocation()).contains("kdvolder");
private static final void debug(String msg) {
if (DEBUG) {
System.out.println("JarRemapRefresher: "+msg);
}
}
private static JarRemapRefresher instance;
/**
* This class is a singleton. Don't call this, rather use
*/
private JarRemapRefresher() {
}
private Job qrJob = null;
public static void request() {
instance().handleRequest();
}
/**
* Refresh classpath entries in all containers in the workspace quickly (i.e. without invalidating
* the cached gradle models and rebuilding them). This is useful when the entries need to be
* recomputed because a project was opened / closed and so jar -> gradle or
*/
private synchronized void handleRequest() {
debug("handleRequest called");
Collection<GradleProject> projects = GradleCore.getGradleProjects();
if (!projects.isEmpty()) {
if (qrJob==null) {
qrJob = new GradleRunnable("Remap Gradle Dependencies") {
@Override
public void doit(IProgressMonitor mon) throws Exception {
//Important: must re-fetch current list of projects each time job runs.
final Collection<GradleProject> projects = GradleCore.getGradleProjects();
debug("Job started");
mon.beginTask("Remap Gradle Dependencies", 2*projects.size()+1);
mon.subTask("Computing project publications");
//Force publications models into the model cache, if we are going
//to need them.
if (GradleCore.getInstance().getPreferences().getRemapJarsToGradleProjects()) {
for (GradleProject p : projects) {
try {
p.getPublications(new SubProgressMonitor(mon, 1));
} catch (Throwable e) {
if (ExceptionUtil.isUnknownModelException(e)) {
//ignore
} else {
GradleCore.log(e);
}
}
}
}
mon.subTask("Updating classpaths");
JobUtil.withRule(JobUtil.buildRule(), mon, 1, new GradleRunnable("Refresh Gradle Classpath Containers") {
public void doit(IProgressMonitor mon) throws Exception {
for (GradleProject p : projects) {
GradleClassPathContainer classpath = p.getClassPathcontainer();
if (classpath!=null) {
mon.subTask("Refresh "+p.getName());
classpath.clearPersistedEntries();
classpath.notifyJDT();
}
mon.worked(1);
}
}
});
}
}.asJob();
}
qrJob.schedule(100); //Slight delay for 'bursty' sets of change events.
}
}
private synchronized static JarRemapRefresher instance() {
if (instance==null) {
instance = new JarRemapRefresher();
}
return instance;
}
}
|
package com.joestelmach.natty;
import java.text.DateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import junit.framework.Assert;
import org.junit.Test;
public class TestFrenchDateParser extends AbstractDateParserTest {
@Test
public void testExplicitDateTime() {
validateDate("12/02/2010", 2, 12, 2010);
validateDate("22-8-1988", 8, 22, 1988);
validateDate("21 mai 2001", 5, 21, 2001);
validateDate("le 11 novembre 2022", 11, 11, 2022);
validateDate("le treize juin 2010", 6, 13, 2010);
// validateDate("le dernier mardi de janvier", 1, 17, 2012);
validateDateTime("le 8 octobre 1987 à 15:31", 10, 8, 1987, 15, 31, 0);
validateDateTime("le 15 avril à 15 heures 30 minutes 45 secondes", 4, 15, 2012, 15, 30, 45);
List<Date> dates;
DateGroup dateGroup;
dateGroup = _parser.parse("le 30 janvier 2012 et le 3 février 2012").get(0);
Assert.assertFalse(dateGroup.isInterval());
dates = dateGroup.getDates();
Assert.assertEquals(2, dates.size());
validateDate(dates.get(0), 1, 30, 2012);
validateDate(dates.get(1), 2, 3, 2012);
dateGroup = _parser.parse("le 16 février ou 2 jours après").get(0);
Assert.assertFalse(dateGroup.isInterval());
dates = dateGroup.getDates();
Assert.assertEquals(2, dates.size());
validateDate(dates.get(0), 2, 16, 2012);
validateDate(dates.get(1), 2, 18, 2012);
dateGroup = _parser.parse("13/08/2007 ou 18/08/2008").get(0);
Assert.assertFalse(dateGroup.isInterval());
dates = dateGroup.getDates();
Assert.assertEquals(2, dates.size());
validateDate(dates.get(0), 8, 13, 2007);
validateDate(dates.get(1), 8, 18, 2008);
}
@Test
public void testRelativeDateTime() throws Exception {
Date reference = DateFormat.getDateTimeInstance(DateFormat.SHORT,
DateFormat.SHORT, Locale.FRENCH).parse("31/01/2012 17:00");
CalendarSource.setBaseDate(reference);
validateDateTime("aujourd'hui à 19:30:20", 1, 31, 2012, 19, 30, 20);
validateDateTime("jeudi après-midi", 2, 2, 2012, 12, 0, 0);
validateDateTime("douze ans plus tôt a 12:20", 1, 31, 2000, 12, 20, 0);
validateDateTime("10 heures avant", 1, 31, 2012, 7, 0, 0);
validateDateTime("demain matin", 2, 1, 2012, 8, 0, 0);
validateDateTime("après-demain soir", 2, 2, 2012, 19, 0, 0);
validateDateTime("dans 8 heures", 2, 1, 2012, 1, 0, 0);
validateDateTime("hier à 20 heures", 1, 30, 2012, 20, 0, 0);
validateDateTime("avant-hier dans la nuit", 1, 29, 2012, 20, 0, 0);
validateDate("dans vingt-deux jours", 2, 22, 2012);
validateDate("dans 15 jours", 2, 15, 2012);
validateDate("dans trois semaines", 2, 21, 2012);
validateDate("dans 5 ans", 1, 31, 2017);
validateDate("il y a dix huit jours", 1, 13, 2012);
validateDate("il y a 9 jours", 1, 22, 2012);
validateDate("il y a huit semaines", 12, 6, 2011);
validateDate("il y a 2 ans", 1, 31, 2010);
validateDate("ce jeudi", 2, 2, 2012);
validateDate("le 28 du mois dernier", 12, 28, 2011);
validateDate("jeudi de la semaine passée", 1, 26, 2012);
validateDate("mercredi passé", 1, 25, 2012);
List<Date> dates;
DateGroup dateGroup;
dateGroup = _parser.parse("demain et après-demain").get(0);
Assert.assertFalse(dateGroup.isInterval());
dates = dateGroup.getDates();
Assert.assertEquals(2, dates.size());
validateDate(dates.get(0), 2, 1, 2012);
validateDate(dates.get(1), 2, 2, 2012);
}
@Test
public void testSpelledDate() {
validateDate("le premier janvier 2011", 1, 1, 2011);
validateDate("deux janvier 2011", 1, 2, 2011);
validateDate("le trois janvier 2011", 1, 3, 2011);
validateDate("quatre janvier 2011", 1, 4, 2011);
validateDate("le cinq janvier 2011", 1, 5, 2011);
validateDate("six janvier 2011", 1, 6, 2011);
validateDate("le sept janvier 2011", 1, 7, 2011);
validateDate("huit janvier 2011", 1, 8, 2011);
validateDate("le neuf janvier 2011", 1, 9, 2011);
validateDate("dix mars 2011", 3, 10, 2011);
validateDate("le onze mars 2011", 3, 11, 2011);
validateDate("douze mars 2011", 3, 12, 2011);
validateDate("le treize mars 2011", 3, 13, 2011);
validateDate("quatorze mars 2011", 3, 14, 2011);
validateDate("le quinze mars 2011", 3, 15, 2011);
validateDate("seize mars 2011", 3, 16, 2011);
validateDate("le dix-sept mars 2011", 3, 17, 2011);
validateDate("dix huit mars 2011", 3, 18, 2011);
validateDate("le dix-neuf mars 2011", 3, 19, 2011);
validateDate("vingt octobre 2011", 10, 20, 2011);
validateDate("le vingt et un octobre 2011", 10, 21, 2011);
validateDate("vingt-deux octobre 2011", 10, 22, 2011);
validateDate("le vingt-trois octobre 2011", 10, 23, 2011);
validateDate("vingt quatre octobre 2011", 10, 24, 2011);
validateDate("le vingt-cinq octobre 2011", 10, 25, 2011);
validateDate("vingt-six octobre 2011", 10, 26, 2011);
validateDate("le vingt-sept octobre 2011", 10, 27, 2011);
validateDate("vingt huit octobre 2011", 10, 28, 2011);
validateDate("le vingt neuf octobre 2011", 10, 29, 2011);
validateDate("trente décembre 2011", 12, 30, 2011);
validateDate("le trente-et-un décembre 2011", 12, 31, 2011);
}
@Test
public void testIntervals() throws Exception {
Date reference = DateFormat.getDateTimeInstance(DateFormat.SHORT,
DateFormat.SHORT, Locale.FRENCH).parse("31/01/2012 17:00");
CalendarSource.setBaseDate(reference);
List<Date> dates;
DateGroup dateGroup;
// intervalles 'du ... au ...'
dateGroup = _parser.parse("du 23 janvier au 12 février 2013").get(0);
Assert.assertTrue(dateGroup.isInterval());
dates = dateGroup.getDates();
Assert.assertEquals(2, dates.size());
validateDate(dates.get(0), 1, 23, 2012);
validateDate(dates.get(1), 2, 12, 2013);
dateGroup = _parser.parse("du 10 janvier au 15 juin").get(0);
Assert.assertTrue(dateGroup.isInterval());
dates = dateGroup.getDates();
Assert.assertEquals(2, dates.size());
validateDate(dates.get(0), 1, 10, 2012);
validateDate(dates.get(1), 6, 15, 2012);
dateGroup = _parser.parse("du 11 juin 2010 au 13 août 2013").get(0);
Assert.assertTrue(dateGroup.isInterval());
dates = dateGroup.getDates();
Assert.assertEquals(2, dates.size());
validateDate(dates.get(0), 6, 11, 2010);
validateDate(dates.get(1), 8, 13, 2013);
dateGroup = _parser.parse("du 13 au 15 mai 2015").get(0);
Assert.assertTrue(dateGroup.isInterval());
dates = dateGroup.getDates();
Assert.assertEquals(2, dates.size());
validateDate(dates.get(0), 5, 13, 2015);
validateDate(dates.get(1), 5, 15, 2015);
dateGroup = _parser.parse("du 1 au 6 novembre").get(0);
Assert.assertTrue(dateGroup.isInterval());
dates = dateGroup.getDates();
Assert.assertEquals(2, dates.size());
validateDate(dates.get(0), 11, 1, 2012);
validateDate(dates.get(1), 11, 6, 2012);
// intervalles '... - ...'
dateGroup = _parser.parse("25 mai - 13 juillet").get(0);
Assert.assertTrue(dateGroup.isInterval());
dates = dateGroup.getDates();
Assert.assertEquals(2, dates.size());
validateDate(dates.get(0), 5, 25, 2012);
validateDate(dates.get(1), 7, 13, 2012);
dateGroup = _parser.parse("31/03/2032 - 1/05/2033").get(0);
Assert.assertTrue(dateGroup.isInterval());
dates = dateGroup.getDates();
Assert.assertEquals(2, dates.size());
validateDate(dates.get(0), 3, 31, 2032);
validateDate(dates.get(1), 5, 1, 2033);
dateGroup = _parser.parse("aujourd'hui - dans 3 semaines").get(0);
Assert.assertTrue(dateGroup.isInterval());
dates = dateGroup.getDates();
Assert.assertEquals(2, dates.size());
validateDate(dates.get(0), 1, 31, 2012);
validateDate(dates.get(1), 2, 21, 2012);
dateGroup = _parser.parse("pendant trois semaines").get(0);
Assert.assertTrue(dateGroup.isInterval());
dates = dateGroup.getDates();
Assert.assertEquals(2, dates.size());
validateDate(dates.get(0), 1, 31, 2012);
validateDate(dates.get(1), 2, 21, 2012);
dateGroup = _parser.parse("pendant 2 heures").get(0);
Assert.assertTrue(dateGroup.isInterval());
dates = dateGroup.getDates();
Assert.assertEquals(2, dates.size());
validateDateTime(dates.get(0), 1, 31, 2012, 17, 0, 0);
validateDateTime(dates.get(1), 1, 31, 2012, 19, 0, 0);
// dateGroup = _parser.parse("cette semaine").get(0);
// Assert.assertTrue(dateGroup.isInterval());
// dates = dateGroup.getDates();
// Assert.assertEquals(2, dates.size());
// validateDateTime(dates.get(0), 1, 30, 2012, 17, 0, 0);
// validateDateTime(dates.get(1), 2, 5, 2012, 17, 0, 0);
dateGroup = _parser.parse("ce mois").get(0);
Assert.assertTrue(dateGroup.isInterval());
dates = dateGroup.getDates();
Assert.assertEquals(2, dates.size());
validateDateTime(dates.get(0), 1, 1, 2012, 17, 0, 0);
validateDateTime(dates.get(1), 1, 31, 2012, 17, 0, 0);
dateGroup = _parser.parse("cette année").get(0);
Assert.assertTrue(dateGroup.isInterval());
dates = dateGroup.getDates();
Assert.assertEquals(2, dates.size());
validateDateTime(dates.get(0), 1, 1, 2012, 17, 0, 0);
validateDateTime(dates.get(1), 12, 31, 2012, 17, 0, 0);
// dateGroup = _parser.parse("ce weekend").get(0);
// Assert.assertTrue(dateGroup.isInterval());
// dates = dateGroup.getDates();
// Assert.assertEquals(2, dates.size());
// validateDateTime(dates.get(0), 2, 4, 2012, 17, 0, 0);
// validateDateTime(dates.get(1), 2, 5, 2012, 17, 0, 0);
// suffix 'suivant', 'prochain'
dateGroup = _parser.parse("la semaine suivante").get(0);
Assert.assertTrue(dateGroup.isInterval());
dates = dateGroup.getDates();
Assert.assertEquals(2, dates.size());
validateDateTime(dates.get(0), 2, 6, 2012, 17, 0, 0);
validateDateTime(dates.get(1), 2, 12, 2012, 17, 0, 0);
dateGroup = _parser.parse("le mois prochain").get(0);
Assert.assertTrue(dateGroup.isInterval());
dates = dateGroup.getDates();
Assert.assertEquals(2, dates.size());
validateDateTime(dates.get(0), 2, 1, 2012, 17, 0, 0);
validateDateTime(dates.get(1), 2, 29, 2012, 17, 0, 0);
dateGroup = _parser.parse("l'année prochaine").get(0);
Assert.assertTrue(dateGroup.isInterval());
dates = dateGroup.getDates();
Assert.assertEquals(2, dates.size());
validateDateTime(dates.get(0), 1, 1, 2013, 17, 0, 0);
validateDateTime(dates.get(1), 12, 31, 2013, 17, 0, 0);
dateGroup = _parser.parse("le week-end prochain").get(0);
Assert.assertTrue(dateGroup.isInterval());
dates = dateGroup.getDates();
Assert.assertEquals(2, dates.size());
validateDateTime(dates.get(0), 2, 11, 2012, 17, 0, 0);
validateDateTime(dates.get(1), 2, 12, 2012, 17, 0, 0);
dateGroup = _parser.parse("la semaine passée").get(0);
Assert.assertTrue(dateGroup.isInterval());
dates = dateGroup.getDates();
Assert.assertEquals(2, dates.size());
validateDateTime(dates.get(0), 1, 23, 2012, 17, 0, 0);
validateDateTime(dates.get(1), 1, 29, 2012, 17, 0, 0);
dateGroup = _parser.parse("l'année passée").get(0);
Assert.assertTrue(dateGroup.isInterval());
dates = dateGroup.getDates();
Assert.assertEquals(2, dates.size());
validateDateTime(dates.get(0), 1, 1, 2011, 17, 0, 0);
validateDateTime(dates.get(1), 12, 31, 2011, 17, 0, 0);
dateGroup = _parser.parse("mois passé").get(0);
Assert.assertTrue(dateGroup.isInterval());
dates = dateGroup.getDates();
Assert.assertEquals(2, dates.size());
validateDateTime(dates.get(0), 12, 1, 2011, 17, 0, 0);
validateDateTime(dates.get(1), 12, 31, 2011, 17, 0, 0);
dateGroup = _parser.parse("week-end passé").get(0);
Assert.assertTrue(dateGroup.isInterval());
dates = dateGroup.getDates();
Assert.assertEquals(2, dates.size());
validateDateTime(dates.get(0), 1, 28, 2012, 17, 0, 0);
validateDateTime(dates.get(1), 1, 29, 2012, 17, 0, 0);
}
@Test
public void testRelativeMonthIntervals() throws Exception {
Date reference = DateFormat.getDateTimeInstance(DateFormat.SHORT,
DateFormat.SHORT, Locale.FRENCH).parse("24/05/2012 12:00");
CalendarSource.setBaseDate(reference);
List<Date> dates;
DateGroup dateGroup;
dateGroup = _parser.parse("janvier prochain").get(0);
Assert.assertTrue(dateGroup.isInterval());
dates = dateGroup.getDates();
Assert.assertEquals(2, dates.size());
validateDateTime(dates.get(0), 1, 1, 2013, 12, 0, 0);
validateDateTime(dates.get(1), 1, 31, 2013, 12, 0, 0);
dateGroup = _parser.parse("février prochain").get(0);
Assert.assertTrue(dateGroup.isInterval());
dates = dateGroup.getDates();
Assert.assertEquals(2, dates.size());
validateDateTime(dates.get(0), 2, 1, 2013, 12, 0, 0);
validateDateTime(dates.get(1), 2, 28, 2013, 12, 0, 0);
dateGroup = _parser.parse("avril prochain").get(0);
Assert.assertTrue(dateGroup.isInterval());
dates = dateGroup.getDates();
Assert.assertEquals(2, dates.size());
validateDateTime(dates.get(0), 4, 1, 2013, 12, 0, 0);
validateDateTime(dates.get(1), 4, 30, 2013, 12, 0, 0);
dateGroup = _parser.parse("mai prochain").get(0);
Assert.assertTrue(dateGroup.isInterval());
dates = dateGroup.getDates();
Assert.assertEquals(2, dates.size());
validateDateTime(dates.get(0), 5, 1, 2013, 12, 0, 0);
validateDateTime(dates.get(1), 5, 31, 2013, 12, 0, 0);
dateGroup = _parser.parse("juin prochain").get(0);
Assert.assertTrue(dateGroup.isInterval());
dates = dateGroup.getDates();
Assert.assertEquals(2, dates.size());
validateDateTime(dates.get(0), 6, 1, 2012, 12, 0, 0);
validateDateTime(dates.get(1), 6, 30, 2012, 12, 0, 0);
dateGroup = _parser.parse("décembre prochain").get(0);
Assert.assertTrue(dateGroup.isInterval());
dates = dateGroup.getDates();
Assert.assertEquals(2, dates.size());
validateDateTime(dates.get(0), 12, 1, 2012, 12, 0, 0);
validateDateTime(dates.get(1), 12, 31, 2012, 12, 0, 0);
}
@Test
public void testExplicitMonthIntervals() throws Exception {
Date reference = DateFormat.getDateTimeInstance(DateFormat.SHORT,
DateFormat.SHORT, Locale.FRENCH).parse("08/02/2012 12:00");
CalendarSource.setBaseDate(reference);
List<Date> dates;
DateGroup dateGroup;
dateGroup = _parser.parse("juin 1998").get(0);
Assert.assertTrue(dateGroup.isInterval());
dates = dateGroup.getDates();
Assert.assertEquals(2, dates.size());
validateDateTime(dates.get(0), 6, 1, 1998, 12, 0, 0);
validateDateTime(dates.get(1), 6, 30, 1998, 12, 0, 0);
dateGroup = _parser.parse("janvier 2011").get(0);
Assert.assertTrue(dateGroup.isInterval());
dates = dateGroup.getDates();
Assert.assertEquals(2, dates.size());
validateDateTime(dates.get(0), 1, 1, 2011, 12, 0, 0);
validateDateTime(dates.get(1), 1, 31, 2011, 12, 0, 0);
dateGroup = _parser.parse("février 2013").get(0);
Assert.assertTrue(dateGroup.isInterval());
dates = dateGroup.getDates();
Assert.assertEquals(2, dates.size());
validateDateTime(dates.get(0), 2, 1, 2013, 12, 0, 0);
validateDateTime(dates.get(1), 2, 28, 2013, 12, 0, 0);
}
}
|
package com.opengamma.analytics.financial.model.volatility.smile.fitting.demo;
import java.util.Arrays;
import java.util.BitSet;
import java.util.List;
import org.apache.commons.lang.ArrayUtils;
import org.testng.annotations.Test;
import com.opengamma.analytics.financial.model.option.pricing.analytic.formula.EuropeanVanillaOption;
import com.opengamma.analytics.financial.model.volatility.smile.fitting.HestonModelFitter;
import com.opengamma.analytics.financial.model.volatility.smile.fitting.MixedLogNormalModelFitter;
import com.opengamma.analytics.financial.model.volatility.smile.fitting.SABRModelFitter;
import com.opengamma.analytics.financial.model.volatility.smile.fitting.SVIModelFitter;
import com.opengamma.analytics.financial.model.volatility.smile.fitting.SmileModelFitter;
import com.opengamma.analytics.financial.model.volatility.smile.fitting.interpolation.BenaimDodgsonKainthExtrapolationFunctionProvider;
import com.opengamma.analytics.financial.model.volatility.smile.fitting.interpolation.GeneralSmileInterpolator;
import com.opengamma.analytics.financial.model.volatility.smile.fitting.interpolation.ShiftedLogNormalTailExtrapolation;
import com.opengamma.analytics.financial.model.volatility.smile.fitting.interpolation.ShiftedLogNormalTailExtrapolationFitter;
import com.opengamma.analytics.financial.model.volatility.smile.fitting.interpolation.SmileInterpolatorSABR;
import com.opengamma.analytics.financial.model.volatility.smile.fitting.interpolation.SmileInterpolatorSpline;
import com.opengamma.analytics.financial.model.volatility.smile.function.HestonVolatilityFunction;
import com.opengamma.analytics.financial.model.volatility.smile.function.MixedLogNormalVolatilityFunction;
import com.opengamma.analytics.financial.model.volatility.smile.function.SABRFormulaData;
import com.opengamma.analytics.financial.model.volatility.smile.function.SABRHaganVolatilityFunction;
import com.opengamma.analytics.financial.model.volatility.smile.function.SVIVolatilityFunction;
import com.opengamma.analytics.financial.model.volatility.smile.function.SmileModelData;
import com.opengamma.analytics.financial.model.volatility.smile.function.VolatilityFunctionProvider;
import com.opengamma.analytics.math.differentiation.ScalarFirstOrderDifferentiator;
import com.opengamma.analytics.math.function.Function1D;
import com.opengamma.analytics.math.interpolation.BasisFunctionGenerator;
import com.opengamma.analytics.math.interpolation.BasisFunctionKnots;
import com.opengamma.analytics.math.matrix.DoubleMatrix1D;
import com.opengamma.analytics.math.statistics.leastsquare.GeneralizedLeastSquare;
import com.opengamma.analytics.math.statistics.leastsquare.GeneralizedLeastSquareResults;
import com.opengamma.analytics.math.statistics.leastsquare.LeastSquareResultsWithTransform;
/**
* The purpose of this class is to demonstrate the various methods in analytics for fitting/interpolating volatility
* smiles, and extrapolating out to low and high strikes beyond the data range.
* <p>
* The market data is Dec-2014 options on the S&P 500 index. The trade date is 20-Oct-2014 09:40 and the expiry is 19-Dec-2014 21:15
* (nominal expiry is 20-Dec-2014, which is a Saturday)
*/
public class SmileFittingDemo {
private static final double FORWARD = 1879.52;
@SuppressWarnings("unused")
private static final double RATE = 0.00231;
private static final double EXPIRY = 60.49514 / 365.;
private static final double[] STRIKES = new double[] {1700, 1750, 1800, 1850, 1900, 1950, 2000, 2050, 2150, 2250 };
private static final double[] IMPLIED_VOLS = new double[] {0.25907, 0.23819, 0.21715, 0.19517, 0.17684, 0.15383, 0.13577, 0.12505, 0.1564, 0.17344 };
private static VolatilityFunctionProvider<SABRFormulaData> SABR = new SABRHaganVolatilityFunction();
private static double[] ERRORS;
// These control how often the smile is sampled and the range used
private static final int NUM_SAMPLES = 101;
private static final double LOWER_STRIKE = 1500.0;
private static final double UPPER_STRIKE = 2500.0;
// For least squares fit use an error of 10bps - this only affects the reported chi-square
static {
int n = IMPLIED_VOLS.length;
ERRORS = new double[n];
Arrays.fill(ERRORS, 1e-3); // 10bps
}
// Global fitters: These fit a smile model to market data in a least squares sense. Extrapolation just involves
// using the calibrated parameters with the model for strikes outside the fitted range.
/**
* Fit the SABR model to market implied volatilities. The parameter beta is fixed at 1, so a three parameter fit is
* made.
*/
@Test(description = "Demo")
public void globalSabrFitDemo() {
// SABR starting parameters
BitSet fixed = new BitSet();
fixed.set(1);
double atmVol = 0.18;
double beta = 1.0;
double rho = -0.9;
double nu = 1.8;
double alpha = atmVol * Math.pow(FORWARD, 1 - beta);
DoubleMatrix1D start = new DoubleMatrix1D(alpha, beta, rho, nu);
SmileModelFitter<SABRFormulaData> sabrFitter = new SABRModelFitter(FORWARD, STRIKES, EXPIRY, IMPLIED_VOLS, ERRORS, SABR);
Function1D<Double, Double> smile = fitSmile(sabrFitter, start, fixed);
printSmile(smile);
}
/**
* Fit the SVI model to market implied volatilities
* <p>
* The model has 5 parameters $a,b,\rho,\nu$ and $m$, and the variance is given by $\sigma^2 = a+b(\rho d + \sqrt{d^2+\nu^2})$ where $d= \ln\left(\frac{k}{f}\right)-m$ With $m=0$, the ATMF vol is
* given by $\sigma = \sqrt{a+b\nu}$
* <p>
* Note: the solution is sensitive to the starting position (many 'sensible' starting points give a local minimum)
*/
@Test(description = "Demo")
public void globalSVIFitDemo() {
SVIVolatilityFunction model = new SVIVolatilityFunction();
SVIModelFitter fitter = new SVIModelFitter(FORWARD, STRIKES, EXPIRY, IMPLIED_VOLS, ERRORS, model);
DoubleMatrix1D start = new DoubleMatrix1D(0.015, 0.1, -0.3, 0.3, 0.0);
BitSet fixed = new BitSet();
Function1D<Double, Double> smile = fitSmile(fitter, start, fixed);
printSmile(smile);
}
/**
* Fit the Heston model market implied volatilities.
* <p>
* Parameters of the Heston model are:
* <ul>
* <li>kappa mean-reverting speed
* <li>theta mean-reverting level
* <li>vol0 starting value of volatility
* <li>omega volatility-of-volatility
* <li>rho correlation between the spot process and the volatility process
* </ul>
* <p>
* Note: the solution is sensitive to the starting position (many 'sensible' starting points give a local minimum)
*/
@Test(description = "Demo")
public void globalHestonFitDemo() {
HestonVolatilityFunction model = new HestonVolatilityFunction();
HestonModelFitter fitter = new HestonModelFitter(FORWARD, STRIKES, EXPIRY, IMPLIED_VOLS, ERRORS, model);
DoubleMatrix1D start = new DoubleMatrix1D(0.1, 0.02, 0.02, 0.4, -0.5);
BitSet fixed = new BitSet();
Function1D<Double, Double> smile = fitSmile(fitter, start, fixed);
printSmile(smile);
}
/**
* Fit a mixed log-normal model to market implied volatilities. This example uses 2 normals which are
* allowed to have different means, so there are 4 (2*3-2) degrees of freedom. In principle 3 normals (7=3*3-2 DoF)
* will give a better fit, but the plethora of local minima massively hampers this.
*/
@Test(description = "Demo")
void mixedLogNormalFitDemo() {
int nNorms = 2;
boolean useShiftedMeans = true;
MixedLogNormalVolatilityFunction model = MixedLogNormalVolatilityFunction.getInstance();
MixedLogNormalModelFitter fitter = new MixedLogNormalModelFitter(FORWARD, STRIKES, EXPIRY, IMPLIED_VOLS, ERRORS, model, nNorms, useShiftedMeans);
DoubleMatrix1D start = new DoubleMatrix1D(0.1, 0.2, 1.5, 1.5);
BitSet fixed = new BitSet();
Function1D<Double, Double> smile = fitSmile(fitter, start, fixed);
printSmile(smile);
}
// SABR Global fitters: These fit SABR to market data in a least squares sense. Extrapolation is with
// shifted log-normal and Benaim-Dodgson-Kainth
/**
* Fit the SABR model to market implied volatilities. The parameter beta is fixed at 1, so a three parameter fit is
* made. This differs from the example above in that outside the range of market strikes a shifted log-normal is
* use to extrapolate the smile.
*/
@Test(description = "Demo")
public void globalSabrFitWithExtrapolationDemo() {
BitSet fixed = new BitSet();
fixed.set(1);
double atmVol = 0.18;
double beta = 1.0;
double rho = -0.9;
double nu = 1.8;
double alpha = atmVol * Math.pow(FORWARD, 1 - beta);
DoubleMatrix1D start = new DoubleMatrix1D(alpha, beta, rho, nu);
SmileModelFitter<SABRFormulaData> sabrFitter = new SABRModelFitter(FORWARD, STRIKES, EXPIRY, IMPLIED_VOLS, ERRORS, SABR);
Function1D<Double, Double> smile = fitSmile(sabrFitter, start, fixed, STRIKES[0], STRIKES[STRIKES.length - 1]);
printSmile(smile);
}
/**
* Again fit global SABR, but now use Benaim-Dodgson-Kainth extrapolation
* <p>
* Note: currently our Benaim-Dodgson-Kainth implementation is hard coded to SABR so cannot be used with other smile models
*/
@Test(description = "Demo")
public void globalSabrFitWithBDKExtrapolationDemo() {
BitSet fixed = new BitSet();
fixed.set(1);
double atmVol = 0.18;
double beta = 1.0;
double rho = -0.9;
double nu = 1.8;
double alpha = atmVol * Math.pow(FORWARD, 1 - beta);
double muLow = 1.0;
double muHigh = 1.0;
DoubleMatrix1D start = new DoubleMatrix1D(alpha, beta, rho, nu);
SABRModelFitter sabrFitter = new SABRModelFitter(FORWARD, STRIKES, EXPIRY, IMPLIED_VOLS, ERRORS, SABR);
Function1D<Double, Double> smile = fitSmile(sabrFitter, start, fixed, STRIKES[0], STRIKES[STRIKES.length - 1], muLow, muHigh);
printSmile(smile);
}
// Local fitters: These can be classed as smile interpolators, in that they fit all the market points. Extrapolation
// is either native or using shifted log-normal or Benaim-Dodgson-Kainth
/**
* The SABR interpolator fits the SABR model (with a fixed Beta) to consecutive triplets of implied vols with
* smooth pasting in between. Extrapolation used the SABR fits for the end points.
*/
@Test(description = "Demo")
void sabrInterpolationTest() {
GeneralSmileInterpolator sabr_interpolator = new SmileInterpolatorSABR();
Function1D<Double, Double> smile = sabr_interpolator.getVolatilityFunction(FORWARD, STRIKES, EXPIRY, IMPLIED_VOLS);
printSmile(smile);
}
/**
* Spline interpolator fits a spline (the default is double-quadratic) through the market implied volatilities and
* uses shifted log-normal to handle the extrapolation.
*/
@Test
void splineInterpolatorTest() {
GeneralSmileInterpolator spline = new SmileInterpolatorSpline();
Function1D<Double, Double> smile = spline.getVolatilityFunction(FORWARD, STRIKES, EXPIRY, IMPLIED_VOLS);
printSmile(smile);
}
/**
* Fit the market variances (volatility squared) using a non-parametric curve. The parameter, lambda, controls the
* smoothness of the curve (penalty on the curvature), so for high values the curve will be smooth, but not match the
* market values. The extrapolated values will be linear in variance.
*/
@Test
void pSplineTest() {
int nKnots = 20; // 20 internal knots to represent the variance curve
int degree = 3; // Curve made from third order polynomial pieces
int penaltyOrder = 2; // Penalty on curvature
GeneralizedLeastSquare gls = new GeneralizedLeastSquare();
BasisFunctionGenerator gen = new BasisFunctionGenerator();
BasisFunctionKnots knots = BasisFunctionKnots.fromUniform(LOWER_STRIKE, UPPER_STRIKE, nKnots, degree);
List<Function1D<Double, Double>> set = gen.generateSet(knots);
int n = IMPLIED_VOLS.length;
double[] var = new double[n];
for (int i = 0; i < n; i++) {
var[i] = IMPLIED_VOLS[i] * IMPLIED_VOLS[i];
}
double log10Lambda = 6;
double lambda = Math.pow(10.0, log10Lambda);
GeneralizedLeastSquareResults<Double> res = gls.solve(ArrayUtils.toObject(STRIKES), var, ERRORS, set, lambda, penaltyOrder);
final Function1D<Double, Double> varFunc = res.getFunction();
Function1D<Double, Double> smile = new Function1D<Double, Double>() {
@Override
public Double evaluate(Double k) {
return Math.sqrt(varFunc.evaluate(k));
}
};
printSmile(smile);
}
// Helper methods. If 'smile' fitting is brought under a common API, these could form part of that design
/**
* Extrapolate a volatility smile to low and high strikes by fitting (separately) a shifted-log-normal model at
* the low and high strike cutoffs
* @param forward the forward
* @param expiry the expiry
* @param volSmileFunc a function describing the smile (Black vol as a function of strike)
* @param lowerStrike the lower strike
* @param upperStrike the upper strike
* @return a volatility smile (Black vol as a function of strike) that is valid for strikes from zero to infinity
*/
private Function1D<Double, Double> fitShiftedLogNormalTails(final double forward, final double expiry, final Function1D<Double, Double> volSmileFunc, final double lowerStrike,
final double upperStrike) {
ScalarFirstOrderDifferentiator diff = new ScalarFirstOrderDifferentiator();
Function1D<Double, Double> dVolDkFunc = diff.differentiate(volSmileFunc);
return fitShiftedLogNormalTails(forward, expiry, volSmileFunc, dVolDkFunc, lowerStrike, upperStrike);
}
/**
* Extrapolate a volatility smile to low and high strikes by fitting (separately) a shifted-log-normal model at
* the low and high strike cutoffs.
* @param forward the forward
* @param expiry the expiry
* @param volSmileFunc a function describing the smile (Black vol as a function of strike)
* @param dVolDkFunc the gradient of the smile as a function of strike
* @param lowerStrike the lower strike
* @param upperStrike the upper strike
* @return a volatility smile (Black vol as a function of strike) that is valid for strikes from zero to infinity
*/
private Function1D<Double, Double> fitShiftedLogNormalTails(final double forward, final double expiry, final Function1D<Double, Double> volSmileFunc, final Function1D<Double, Double> dVolDkFunc,
final double lowerStrike, final double upperStrike) {
ShiftedLogNormalTailExtrapolationFitter tailFitter = new ShiftedLogNormalTailExtrapolationFitter();
double vol = volSmileFunc.evaluate(lowerStrike);
double volGrad = dVolDkFunc.evaluate(lowerStrike);
final double[] lowerParms = tailFitter.fitVolatilityAndGrad(forward, lowerStrike, vol, volGrad, expiry);
vol = volSmileFunc.evaluate(upperStrike);
volGrad = dVolDkFunc.evaluate(upperStrike);
final double[] upperParms = tailFitter.fitVolatilityAndGrad(forward, upperStrike, vol, volGrad, expiry);
return new Function1D<Double, Double>() {
@Override
public Double evaluate(Double k) {
if (k >= lowerStrike && k <= upperStrike) {
return volSmileFunc.evaluate(k);
}
if (k < lowerStrike) {
return ShiftedLogNormalTailExtrapolation.impliedVolatility(forward, k, expiry, lowerParms[0], lowerParms[1]);
}
return ShiftedLogNormalTailExtrapolation.impliedVolatility(forward, k, expiry, upperParms[0], upperParms[1]);
}
};
}
/**
* gets a smile function (Black vol as a function of strike) from a VolatilityFunctionProvider and SmileModelData
* @param fwd the forward
* @param expiry the expiry
* @param data parameters of the smile model (e.g. for SABR these would be alpha, beta, rho and nu)
* @param volModel the volatility model
* @return the smile function
*/
private Function1D<Double, Double> toSmileFunction(final double fwd, final double expiry, final SmileModelData data, final VolatilityFunctionProvider<? extends SmileModelData> volModel) {
return new Function1D<Double, Double>() {
@Override
public Double evaluate(Double k) {
boolean isCall = k >= fwd;
EuropeanVanillaOption option = new EuropeanVanillaOption(k, expiry, isCall);
@SuppressWarnings("unchecked")
Function1D<SmileModelData, Double> func = (Function1D<SmileModelData, Double>) volModel.getVolatilityFunction(option, fwd);
return func.evaluate(data);
}
};
}
/**
* Fit a smile model to the data set and return the smile
* @param fitter the smile fitter
* @param start this initial starting point of the model parameters
* @param fixed map of any fixed parameters
* @return the smile function
*/
private Function1D<Double, Double> fitSmile(SmileModelFitter<? extends SmileModelData> fitter, DoubleMatrix1D start, BitSet fixed) {
LeastSquareResultsWithTransform res = fitter.solve(start, fixed);
System.out.println("chi-Square: " + res.getChiSq());
VolatilityFunctionProvider<?> model = fitter.getModel();
SmileModelData data = fitter.toSmileModelData(res.getModelParameters());
return toSmileFunction(FORWARD, EXPIRY, data, model);
}
/**
* Fit a smile model to the data set and return the smile. Outside the given range use shifted log-normal extrapolation
* @param fitter the smile fitter
* @param start this initial starting point of the model parameters
* @param fixed map of any fixed parameters
* @param lowerStrike start of the left extrapolation
* @param upperStrike start of the right extrapolation
* @return the smile function
*/
private Function1D<Double, Double> fitSmile(SmileModelFitter<? extends SmileModelData> fitter, DoubleMatrix1D start, BitSet fixed, double lowerStrike, double upperStrike) {
LeastSquareResultsWithTransform res = fitter.solve(start, fixed);
System.out.println("chi-Square: " + res.getChiSq());
VolatilityFunctionProvider<?> model = fitter.getModel();
SmileModelData data = fitter.toSmileModelData(res.getModelParameters());
Function1D<Double, Double> smile = toSmileFunction(FORWARD, EXPIRY, data, model);
return fitShiftedLogNormalTails(FORWARD, EXPIRY, smile, lowerStrike, upperStrike);
}
/**
* Fit a smile model to the data set and return the smile. Outside the given range use Benaim-Dodgson-Kainth extrapolation
* @param fitter the smile fitter
* @param start this initial starting point of the model parameters
* @param fixed map of any fixed parameters
* @param lowerStrike start of the left extrapolation
* @param upperStrike start of the right extrapolation
* @param lowerMu the left tail control parameter
* @param upperMu the right tail control parameter
* @return the smile function
*/
private Function1D<Double, Double> fitSmile(SABRModelFitter fitter, DoubleMatrix1D start, BitSet fixed, final double lowerStrike, final double upperStrike, double lowerMu, double upperMu) {
LeastSquareResultsWithTransform res = fitter.solve(start, fixed);
System.out.println("chi-Square: " + res.getChiSq());
VolatilityFunctionProvider<SABRFormulaData> model = fitter.getModel();
SABRFormulaData data = fitter.toSmileModelData(res.getModelParameters());
final Function1D<Double, Double> smile = toSmileFunction(FORWARD, EXPIRY, data, model);
BenaimDodgsonKainthExtrapolationFunctionProvider tailPro = new BenaimDodgsonKainthExtrapolationFunctionProvider(lowerMu, upperMu);
final Function1D<Double, Double> extrapFunc = tailPro.getExtrapolationFunction(data, data, model, FORWARD, EXPIRY, lowerStrike, upperStrike);
return new Function1D<Double, Double>() {
@Override
public Double evaluate(Double k) {
if (k < lowerStrike || k > upperStrike) {
return extrapFunc.evaluate(k);
}
return smile.evaluate(k);
}
};
}
/**
* Print the smile. The number of sample and range is controlled by static variables
* @param smile the smile function
*/
private void printSmile(Function1D<Double, Double> smile) {
System.out.println("Strike\tImplied Volatility");
double range = (UPPER_STRIKE - LOWER_STRIKE) / (NUM_SAMPLES - 1.0);
for (int i = 0; i < NUM_SAMPLES; i++) {
double k = LOWER_STRIKE + i * range;
double vol = smile.evaluate(k);
System.out.println(k + "\t" + vol);
}
}
}
|
package com.ctrip.xpipe.redis.console.healthcheck.factory;
import com.ctrip.xpipe.api.endpoint.Endpoint;
import com.ctrip.xpipe.api.proxy.ProxyEnabled;
import com.ctrip.xpipe.concurrent.DefaultExecutorFactory;
import com.ctrip.xpipe.endpoint.HostPort;
import com.ctrip.xpipe.lifecycle.LifecycleHelper;
import com.ctrip.xpipe.redis.console.config.ConsoleConfig;
import com.ctrip.xpipe.redis.console.health.RedisSessionManager;
import com.ctrip.xpipe.redis.console.healthcheck.HealthCheckActionListener;
import com.ctrip.xpipe.redis.console.healthcheck.RedisHealthCheckInstance;
import com.ctrip.xpipe.redis.console.healthcheck.RedisInstanceInfo;
import com.ctrip.xpipe.redis.console.healthcheck.config.DefaultHealthCheckConfig;
import com.ctrip.xpipe.redis.console.healthcheck.config.HealthCheckConfig;
import com.ctrip.xpipe.redis.console.healthcheck.config.ProxyEnabledHealthCheckConfig;
import com.ctrip.xpipe.redis.console.healthcheck.delay.DelayAction;
import com.ctrip.xpipe.redis.console.healthcheck.impl.DefaultRedisHealthCheckInstance;
import com.ctrip.xpipe.redis.console.healthcheck.ping.PingAction;
import com.ctrip.xpipe.redis.console.healthcheck.ping.PingService;
import com.ctrip.xpipe.redis.core.entity.RedisMeta;
import com.ctrip.xpipe.utils.OsUtils;
import com.ctrip.xpipe.utils.XpipeThreadFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
/**
* @author chen.zhu
* <p>
* Aug 27, 2018
*/
@Component
public class DefaultRedisHealthCheckInstanceFactory implements RedisHealthCheckInstanceFactory {
private static final Logger logger = LoggerFactory.getLogger(DefaultRedisHealthCheckInstanceFactory.class);
@Autowired
private ConsoleConfig consoleConfig;
@Autowired
private HealthCheckEndpointFactory endpointFactory;
@Autowired
private RedisSessionManager redisSessionManager;
private ScheduledExecutorService scheduled;
private ExecutorService executors;
@Autowired
private PingService pingService;
@Autowired
private List<HealthCheckActionListener> listeners;
private DefaultHealthCheckConfig defaultHealthCheckConfig;
private ProxyEnabledHealthCheckConfig proxyEnabledHealthCheckConfig;
@PostConstruct
public void init() {
defaultHealthCheckConfig = new DefaultHealthCheckConfig(consoleConfig);
proxyEnabledHealthCheckConfig = new ProxyEnabledHealthCheckConfig(consoleConfig);
executors = DefaultExecutorFactory.createAllowCoreTimeoutAbortPolicy("RedisHealthCheckInstance-").createExecutorService();
scheduled = Executors.newScheduledThreadPool(Math.min(OsUtils.getCpuCount(), 4), XpipeThreadFactory.create("RedisHealthCheckInstance-Scheduled-"));
}
@Override
public RedisHealthCheckInstance create(RedisMeta redisMeta) {
RedisHealthCheckInstance instance = new DefaultRedisHealthCheckInstance();
RedisInstanceInfo info = createRedisInstanceInfo(redisMeta);
Endpoint endpoint = endpointFactory.getOrCreateEndpoint(redisMeta);
HealthCheckConfig config = isEndpointProxyEnabled(endpoint) ? proxyEnabledHealthCheckConfig : defaultHealthCheckConfig;
((DefaultRedisHealthCheckInstance) instance).setEndpoint(endpoint)
.setHealthCheckConfig(config)
.setRedisInstanceInfo(info)
.setSession(redisSessionManager.findOrCreateSession(endpoint));
initActions(instance);
try {
LifecycleHelper.initializeIfPossible(instance);
} catch (Exception e) {
logger.error("[create]", e);
}
return instance;
}
private RedisInstanceInfo createRedisInstanceInfo(RedisMeta redisMeta) {
RedisInstanceInfo info = new DefaultRedisInstanceInfo(
redisMeta.parent().parent().parent().getId(),
redisMeta.parent().parent().getId(),
redisMeta.parent().getId(),
new HostPort(redisMeta.getIp(), redisMeta.getPort()));
info.isMaster(redisMeta.isMaster());
return info;
}
private boolean isEndpointProxyEnabled(Endpoint endpoint) {
return endpoint instanceof ProxyEnabled;
}
private void initActions(RedisHealthCheckInstance instance) {
new PingAction(scheduled, instance, executors).addListeners(listeners);
new DelayAction(scheduled, instance, executors, pingService).addListeners(listeners);
}
}
|
package org.carlspring.strongbox.users.service.impl;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import javax.inject.Inject;
import javax.inject.Qualifier;
import org.apache.commons.lang3.StringUtils;
import org.carlspring.strongbox.data.CacheName;
import org.carlspring.strongbox.data.service.CommonCrudService;
import org.carlspring.strongbox.domain.UserEntry;
import org.carlspring.strongbox.users.domain.UserData;
import org.carlspring.strongbox.users.domain.Users;
import org.carlspring.strongbox.users.dto.User;
import org.carlspring.strongbox.users.security.SecurityTokenProvider;
import org.carlspring.strongbox.users.service.UserEntryService;
import org.carlspring.strongbox.users.service.impl.OrientDbUserService.OrientDb;
import org.carlspring.strongbox.users.userdetails.StrongboxUserDetails;
import org.jose4j.lang.JoseException;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import com.orientechnologies.orient.core.record.impl.ODocument;
import com.orientechnologies.orient.core.sql.OCommandSQL;
import com.orientechnologies.orient.core.sql.query.OSQLSynchQuery;
/**
* @author sbespalov
*/
@Component
@OrientDb
public class OrientDbUserService extends CommonCrudService<UserEntry> implements UserEntryService
{
@Inject
private SecurityTokenProvider tokenProvider;
@Override
@CacheEvict(cacheNames = CacheName.User.AUTHENTICATIONS, key = "
public void deleteByUsername(String username)
{
Map<String, String> params = new HashMap<>();
params.put("username", username);
String sQuery = String.format("delete from %s where username = :username", UserEntry.class.getSimpleName());
OCommandSQL oQuery = new OCommandSQL(sQuery);
getDelegate().command(oQuery).execute(params);
}
@Override
public UserEntry findByUsername(String username)
{
Map<String, String> params = new HashMap<>();
params.put("username", username);
String sQuery = buildQuery(params);
OSQLSynchQuery<ODocument> oQuery = new OSQLSynchQuery<>(sQuery);
oQuery.setLimit(1);
List<UserEntry> resultList = getDelegate().command(oQuery).execute(params);
return resultList.stream().findFirst().orElse(null);
}
@Override
public String generateSecurityToken(String username)
throws JoseException
{
final User user = findByUsername(username);
if (StringUtils.isEmpty(user.getSecurityTokenKey()))
{
return null;
}
final Map<String, String> claimMap = new HashMap<>();
claimMap.put(UserData.SECURITY_TOKEN_KEY, user.getSecurityTokenKey());
return tokenProvider.getToken(username, claimMap, null, null);
}
@Override
@CacheEvict(cacheNames = CacheName.User.AUTHENTICATIONS, key = "#p0.username")
public void updateAccountDetailsByUsername(User userToUpdate)
{
UserEntry user = findByUsername(userToUpdate.getUsername());
if (user == null)
{
throw new UsernameNotFoundException(userToUpdate.getUsername());
}
if (!StringUtils.isBlank(userToUpdate.getPassword()))
{
user.setPassword(userToUpdate.getPassword());
}
if (StringUtils.isNotBlank(userToUpdate.getSecurityTokenKey()))
{
user.setSecurityTokenKey(userToUpdate.getSecurityTokenKey());
}
save(user);
}
@Override
public Users getUsers()
{
Optional<List<UserEntry>> allUsers = findAll();
if (allUsers.isPresent())
{
return new Users(allUsers.get().stream().map(u -> detach(u)).collect(Collectors.toSet()));
}
return null;
}
@Override
public void revokeEveryone(String roleToRevoke)
{
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
@CacheEvict(cacheNames = CacheName.User.AUTHENTICATIONS, key = "#p0.username")
public User save(User user)
{
UserEntry userEntry = Optional.ofNullable(findByUsername(user.getUsername())).orElseGet(() -> new UserEntry());
if (!StringUtils.isBlank(user.getPassword()))
{
userEntry.setPassword(user.getPassword());
}
userEntry.setUsername(user.getUsername());
userEntry.setEnabled(user.isEnabled());
userEntry.setRoles(user.getRoles());
userEntry.setSecurityTokenKey(user.getSecurityTokenKey());
userEntry.setLastUpdate(new Date());
return save(userEntry);
}
@Override
@CacheEvict(cacheNames = CacheName.User.AUTHENTICATIONS, key = "#p0.username")
public <S extends UserEntry> S save(S entity)
{
if (StringUtils.isNotBlank(entity.getSourceId()))
{
throw new IllegalStateException("Can't modify external users.");
}
return super.save(entity);
}
@Override
@CacheEvict(cacheNames = CacheName.User.AUTHENTICATIONS, key = "#p1.username")
public User cacheExternalUserDetails(String sourceId,
UserDetails springUser)
{
User user = springUser instanceof StrongboxUserDetails ? ((StrongboxUserDetails) springUser).getUser()
: new UserData(springUser);
UserEntry userEntry = Optional.ofNullable((UserEntry) findByUsername(user.getUsername()))
.map(u -> {
getDelegate().detachAll(u);
return u;
})
.filter(u -> u.getSourceId().equals(sourceId))
.orElseGet(() -> new UserEntry());
if (!StringUtils.isBlank(user.getPassword()))
{
userEntry.setPassword(user.getPassword());
}
userEntry.setUsername(user.getUsername());
userEntry.setEnabled(user.isEnabled());
userEntry.setRoles(user.getRoles());
userEntry.setSecurityTokenKey(user.getSecurityTokenKey());
userEntry.setLastUpdate(new Date());
userEntry.setSourceId(sourceId);
return super.save(userEntry);
}
@Override
public Class<UserEntry> getEntityClass()
{
return UserEntry.class;
}
@Documented
@Retention(RUNTIME)
@Qualifier
public @interface OrientDb
{
}
}
|
package org.meshwork.app.zeroconf.l3.node;
import org.meshwork.core.AbstractMessage;
import org.meshwork.core.AbstractMessageTransport;
import org.meshwork.core.MessageData;
import org.meshwork.core.TransportTimeoutException;
import org.meshwork.core.zeroconf.l3.*;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
public class MessageDispatcherImpl implements MessageDispatcher {
public static final int MAX_READ_MSG_COUNT_PER_CALL = 100;
protected AbstractMessageTransport transport;
protected PrintWriter writer;
protected MessageAdapter adapter;
protected ZeroConfiguration config;
protected boolean running;
protected SimpleDateFormat dateFormatter;
protected byte seq;
protected int consoleReadTimeout;
protected MZCIDRes lastMZCIDRes;
protected MZCNwkIDRes lastMZCNwkIDRes;
public MessageDispatcherImpl(MessageAdapter adapter, AbstractMessageTransport transport,
ZeroConfiguration config, PrintWriter writer) {
this.adapter = adapter;
this.transport = transport;
this.config = config;
this.writer = writer;
consoleReadTimeout = config.getConsoleReadTimeout();
dateFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
}
protected byte nextSeq() {
return ++seq;
}
@Override
public void run() {
synchronized (this) {
running = true;
this.notifyAll();
}
AbstractMessage message = null;
if (running) {
try {
writer.print("\n
writer.println(dateFormatter.format(new Date(System.currentTimeMillis())));
doMZCInit();
doMZCID();
doMZCNwkID();
if ( config.readonly ) {
writer.println("[MessageDispatcher] Read-only mode. Will NOT configure the device!");
} else {
doMZCCfgNwk();
doMZCNwkID();//read after write
doMZCCfgRep();//TODO add an ID message to read current rep config
}
doMZCDeinit();
writer.println("[MessageDispatcher] Device configured!");
writer.print("\n
writer.println();
if ( lastMZCIDRes != null ) {
lastMZCIDRes.toString(writer, "\t\t", null, null);
writer.println();
}
if ( lastMZCNwkIDRes != null ) {
lastMZCNwkIDRes.toString(writer, "\t\t", null, null);
writer.println();
}
writer.print("\n
} catch (Throwable t) {
writer.println("[MessageDispatcher] Error: " + t.getMessage());
t.printStackTrace(writer);
writer.flush();
// readMessagesAndDiscardAll();
// t.printStackTrace(writer);
}
}
writer.println("[MessageDispatcher] Run complete.");
}
@Override
public void init() throws Exception {
readMessagesAndDiscardAll();
}
@Override
public void deinit() throws Exception {
running = false;
lastMZCIDRes = null;
lastMZCNwkIDRes = null;
}
protected void doMZCInit() throws Exception {
MZCInit msg = new MZCInit(nextSeq());
AbstractMessage result = sendMessageAndReceive(msg);
writer.print("[doMZCInit] Response: ");
result.toString(writer, "\t\t", null, null);
if ( result == null || !(result instanceof MOK) )
throw new Exception("Error sending MZCInit");
}
protected void doMZCDeinit() throws Exception {
MZCDeinit msg = new MZCDeinit(nextSeq());
AbstractMessage result = sendMessageAndReceive(msg);
writer.print("[MZCDeinit] Response: ");
if ( result != null )
result.toString(writer, "\t\t", null, null);
if ( result == null || !(result instanceof MOK) )
throw new Exception("Error sending MZCDeinit");
}
protected void doMZCID() throws Exception {
MZCID msg = new MZCID(nextSeq());
AbstractMessage result = sendMessageAndReceive(msg);
writer.print("[doMZCID] Response: ");
if ( result != null ) {
result.toString(writer, "\t\t", null, null);
lastMZCIDRes = (MZCIDRes) result;
}
if ( result == null || !(result instanceof MZCIDRes) )
throw new Exception("Error sending MZCID");
}
protected void doMZCNwkID() throws Exception {
MZCNwkID msg = new MZCNwkID(nextSeq());
AbstractMessage result = sendMessageAndReceive(msg);
writer.print("[doMZCNwkID] Response: ");
if ( result != null ) {
result.toString(writer, "\t\t", null, null);
lastMZCNwkIDRes = (MZCNwkIDRes) result;
}
if ( result == null || !(result instanceof MZCNwkIDRes) )
throw new Exception("Error sending MZCNwkID");
}
protected void doMZCCfgNwk() throws Exception {
MZCCfgNwk msg = new MZCCfgNwk(nextSeq());
msg.channel = config.getChannel();
msg.nodeid = config.getNodeid();
msg.nwkid = config.getNwkid();
String k = config.getNwkkey();
msg.keylen = (byte) (k == null ? 0 : k.length());
msg.key = msg.keylen == 0 ? null : k.getBytes();
writer.print("[doMZCCfgNwk] Configuring network: ");
msg.toString(writer, "\t\t", null, null);
AbstractMessage result = sendMessageAndReceive(msg);
writer.print("[doMZCCfgNwk] Response: ");
if ( result != null )
result.toString(writer, "\t\t", null, null);
if ( result == null || !(result instanceof MOK) )
throw new Exception("Error sending MZCCfgNwk");
}
protected void doMZCCfgRep() throws Exception {
MZCCfgRep msg = new MZCCfgRep(nextSeq());
msg.reportNodeid = config.getReportNodeid();
msg.reportFlags = config.getReportFlags();
writer.print("[doMZCCfgNwk] Configuring reporting: ");
msg.toString(writer, "\t\t", null, null);
AbstractMessage result = sendMessageAndReceive(msg);
writer.print("[doMZCCfgRep] Response: ");
if ( result != null )
result.toString(writer, "\t\t", null, null);
if ( result == null || !(result instanceof MOK) )
throw new Exception("Error sending MZCCfgRep");
}
protected void readMessagesAndDiscardAll() {
boolean hasMessages = true;
int count = 0;//prevent endless loop for some unknown reason
while ( hasMessages && count < MAX_READ_MSG_COUNT_PER_CALL) {
try {
count ++;
transport.readMessage(10);//low timeout to catch only the buffered messages;
} catch (TransportTimeoutException e) {
hasMessages = false;
} catch (Exception e) {
}
}
}
protected void sendMessage(AbstractMessage msg) throws Exception {
writer.println("[sendMessage] Msg: "+msg);
msg.toString(writer, "\t\t", null, null);
writer.println();
writer.flush();
MessageData data = new MessageData();
msg.serialize(data);
transport.sendMessage(data);
writer.println("[sendMessage][DONE] Msg: " + msg);
}
protected AbstractMessage sendMessageAndReceive(AbstractMessage msg) throws Exception {
writer.println();
writer.println("[sendMessageAndReceive] Entered");
readMessagesAndDiscardAll();
sendMessage(msg);
writer.println("[sendMessageAndReceive] Receiving with timeout: " + consoleReadTimeout);
MessageData data = readMessageUntil(consoleReadTimeout, msg.seq);
writer.print("[sendMessageAndReceive] Received Data: ");
if ( data != null )
data.toString(writer, "\t\t", null, null);
else
writer.print("<Null or timeout>");
writer.println();
writer.flush();
AbstractMessage result = data == null ? null : adapter.deserialize(data);
writer.print("[sendMessageAndReceive] Received Message: ");
if ( result != null )
result.toString(writer, "\t\t", null, null);
else
writer.println("<Null or timeout>");
writer.println();
writer.println("[sendMessageAndReceive] Exited");
writer.println();
writer.flush();
return result;
}
protected MessageData readMessageUntil(int readTimeout, byte seq) {
MessageData result = null, temp = null;
long start = System.currentTimeMillis();
int count = 0;//prevent endless loop for some unknown reason... oh, sanity
while (count < MAX_READ_MSG_COUNT_PER_CALL) {
try {
count++;
temp = transport.readMessage(readTimeout);
boolean breakout = false;
if (temp != null) {//shouldn't happen?
if (temp.seq == seq) {
result = temp;
breakout = true;
} else {
AbstractMessage message = adapter.deserialize(temp);
writer.println("<Unexpected message> " + message);
if (message != null)
message.toString(writer, null, null, null);
writer.println();
writer.flush();
}
if ( breakout )
break;
}
} catch (TransportTimeoutException e) {
writer.println("*** Transport timeout error: "+e.getMessage());
writer.flush();
} catch (Exception e) {
writer.println("*** Read error: "+e.getMessage());
e.printStackTrace(writer);
writer.flush();
}
//invoked here to ensure at least one read in case readTimeout is really low or zero
if (System.currentTimeMillis() - start >= readTimeout)
break;
}
return result;
}
}
|
package edu.ucdenver.ccp.nlp.ext.uima.annotators.entitydetection;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import org.apache.log4j.Logger;
import org.apache.uima.UimaContext;
import org.apache.uima.analysis_engine.AnalysisEngine;
import org.apache.uima.analysis_engine.AnalysisEngineDescription;
import org.apache.uima.resource.ResourceInitializationException;
import org.apache.uima.resource.metadata.TypeSystemDescription;
import org.uimafit.descriptor.ConfigurationParameter;
import org.uimafit.factory.AnalysisEngineFactory;
import org.uimafit.factory.ConfigurationParameterFactory;
import edu.ucdenver.ccp.common.file.FileUtil;
import edu.ucdenver.ccp.nlp.core.exception.InitializationException;
import edu.ucdenver.ccp.nlp.core.interfaces.ITagger;
import edu.ucdenver.ccp.nlp.wrapper.abner.Abner_Util;
public class ABNER_AE extends EntityTagger_AE {
static Logger logger = Logger.getLogger(ABNER_AE.class);
// public final static String MODEL_FILE_KEY = "AbnerModelFile";
/**
* ExternalResources such as MODEL_FILE_KEY can only be defined once and thus conflict if there
* are more than one ABNER instances in a pipeline set up with different models - this may only
* be a problem when initializing from AnalysisEngineDescriptors in an Aggregate.
*/
// @ExternalResource(key = MODEL_FILE_KEY)
// DataResource modelFileDR;
/**
* Parameter name used in the UIMA descriptor file for the token attribute extractor
* implementation to use
*/
public static final String PARAM_MODEL_FILE = ConfigurationParameterFactory.createConfigurationParameterName(
ABNER_AE.class, "modelFile");
/**
* The name of the TokenAttributeExtractor implementation to use
*/
@ConfigurationParameter(mandatory = true, description = "path to the model file to load")
private File modelFile;
public void initialize(UimaContext context) throws ResourceInitializationException {
super.initialize(context);
entityTagger = new Abner_Util();
// /*
// * Get the model file as defined by the Resource section of the descriptor for this
// Analysis
// * Engine
// */
// String abnerModelFile = modelFileDR.getUri().getPath();
/* initialize the tagging system */
try {
String[] args = { modelFile.getAbsolutePath() };
entityTagger.initialize(ITagger.ENTITY_TAGGER, args);
} catch (InitializationException e) {
throw new ResourceInitializationException(e);
}
}
public static AnalysisEngineDescription createAnalysisEngineDescription_BioCreative(TypeSystemDescription tsd)
throws ResourceInitializationException {
InputStream modelStream = ABNER_AE.class.getResourceAsStream("/abner/models/biocreative.crf");
try {
File modelFile = File.createTempFile("biocreative", "crf");
FileUtil.copy(modelStream, modelFile);
return createAnalysisEngineDescription(tsd, modelFile);
} catch (IOException e) {
throw new ResourceInitializationException(e);
}
}
public static AnalysisEngineDescription createAnalysisEngineDescription_NLPBA(TypeSystemDescription tsd)
throws ResourceInitializationException {
InputStream modelStream = ABNER_AE.class.getResourceAsStream("/abner/models/nlpba.crf");
try {
File modelFile = File.createTempFile("nlpba", "crf");
FileUtil.copy(modelStream, modelFile);
return createAnalysisEngineDescription(tsd, modelFile);
} catch (IOException e) {
throw new ResourceInitializationException(e);
}
}
public static AnalysisEngine createAnalysisEngine_BioCreative(TypeSystemDescription tsd)
throws ResourceInitializationException {
return AnalysisEngineFactory.createPrimitive(createAnalysisEngineDescription_BioCreative(tsd));
}
public static AnalysisEngine createAnalysisEngine_NLPBA(TypeSystemDescription tsd)
throws ResourceInitializationException {
return AnalysisEngineFactory.createPrimitive(createAnalysisEngineDescription_NLPBA(tsd));
}
public static AnalysisEngineDescription createAnalysisEngineDescription(TypeSystemDescription tsd, File modelFile)
throws ResourceInitializationException {
AnalysisEngineDescription aed = AnalysisEngineFactory.createPrimitiveDescription(ABNER_AE.class, tsd,
PARAM_MODEL_FILE, modelFile.getAbsolutePath());
// try {
// ExternalResourceFactory.bindResource(aed, MODEL_FILE_KEY, path);
// } catch (InvalidXMLException x) {
// throw new ResourceInitializationException(x);
return aed;
}
}
|
package org.opendaylight.yangtools.maven.sal.api.gen.plugin;
import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.maven.plugin.logging.Log;
import org.apache.maven.project.MavenProject;
import org.opendaylight.yangtools.binding.generator.util.BindingGeneratorUtil;
import org.opendaylight.yangtools.sal.binding.generator.api.BindingGenerator;
import org.opendaylight.yangtools.sal.binding.generator.impl.BindingGeneratorImpl;
import org.opendaylight.yangtools.sal.binding.model.api.Type;
import org.opendaylight.yangtools.sal.java.api.generator.GeneratorJavaFile;
import org.opendaylight.yangtools.sal.java.api.generator.YangModuleInfoTemplate;
import org.opendaylight.yangtools.yang.model.api.Module;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
import org.opendaylight.yangtools.yang2sources.spi.BuildContextAware;
import org.opendaylight.yangtools.yang2sources.spi.CodeGenerator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonatype.plexus.build.incremental.BuildContext;
import com.google.common.base.Preconditions;
public final class CodeGeneratorImpl implements CodeGenerator, BuildContextAware {
private static final String FS = File.separator;
private BuildContext buildContext;
private File projectBaseDir;
private Map<String, String> additionalConfig;
private static final Logger logger = LoggerFactory.getLogger(CodeGeneratorImpl.class);
private MavenProject mavenProject;
@Override
public Collection<File> generateSources(final SchemaContext context, final File outputDir,
final Set<Module> yangModules) throws IOException {
final File outputBaseDir;
outputBaseDir = outputDir == null ? getDefaultOutputBaseDir() : outputDir;
final BindingGenerator bindingGenerator = new BindingGeneratorImpl();
final List<Type> types = bindingGenerator.generateTypes(context, yangModules);
final GeneratorJavaFile generator = new GeneratorJavaFile(buildContext, new HashSet<>(types));
File persistentSourcesDir = null;
if (additionalConfig != null) {
String persistenSourcesPath = additionalConfig.get("persistentSourcesDir");
if (persistenSourcesPath != null) {
persistentSourcesDir = new File(persistenSourcesPath);
}
}
if (persistentSourcesDir == null) {
persistentSourcesDir = new File(projectBaseDir, "src" + FS + "main" + FS + "java");
}
List<File> result = generator.generateToFile(outputBaseDir, persistentSourcesDir);
for (Module module : yangModules) {
// TODO: add YangModuleInfo class
result.add(generateYangModuleInfo(outputBaseDir, module, context));
}
return result;
}
public static final String DEFAULT_OUTPUT_BASE_DIR_PATH = "target" + File.separator + "generated-sources"
+ File.separator + "maven-sal-api-gen";
private File getDefaultOutputBaseDir() {
File outputBaseDir;
outputBaseDir = new File(DEFAULT_OUTPUT_BASE_DIR_PATH);
setOutputBaseDirAsSourceFolder(outputBaseDir, mavenProject);
logger.debug("Adding " + outputBaseDir.getPath() + " as compile source root");
return outputBaseDir;
}
private static void setOutputBaseDirAsSourceFolder(File outputBaseDir, MavenProject mavenProject) {
Preconditions.checkNotNull(mavenProject, "Maven project needs to be set in this phase");
mavenProject.addCompileSourceRoot(outputBaseDir.getPath());
}
@Override
public void setLog(Log log) {}
@Override
public void setAdditionalConfig(Map<String, String> additionalConfiguration) {
this.additionalConfig = additionalConfiguration;
}
@Override
public void setResourceBaseDir(File resourceBaseDir) {
// no resource processing necessary
}
@Override
public void setMavenProject(MavenProject project) {
this.mavenProject = project;
this.projectBaseDir = project.getBasedir();
}
@Override
public void setBuildContext(BuildContext buildContext) {
this.buildContext = Preconditions.checkNotNull(buildContext);
}
private File generateYangModuleInfo(File outputBaseDir, Module module, SchemaContext ctx) {
final YangModuleInfoTemplate template = new YangModuleInfoTemplate(module, ctx);
String generatedCode = template.generate();
if (generatedCode.isEmpty()) {
throw new IllegalStateException("Generated code should not be empty!");
}
final File packageDir = GeneratorJavaFile.packageToDirectory(outputBaseDir, BindingGeneratorUtil.moduleNamespaceToPackageName(module));
final File file = new File(packageDir, "$YangModuleInfoImpl.java");
try (final OutputStream stream = buildContext.newFileOutputStream(file)) {
try (final Writer fw = new OutputStreamWriter(stream)) {
try (final BufferedWriter bw = new BufferedWriter(fw)) {
bw.write(generatedCode);
}
} catch (Exception e) {
// TODO handle exception
}
} catch (Exception e) {
// TODO handle exception
}
return file;
}
}
|
package edu.cuny.citytech.foreachlooptolambda.ui.visitors;
import java.util.HashSet;
import java.util.Stack;
import org.eclipse.jdt.core.dom.ASTVisitor;
import org.eclipse.jdt.core.dom.IMethodBinding;
import org.eclipse.jdt.core.dom.ITypeBinding;
import org.eclipse.jdt.core.dom.Statement;
import org.eclipse.jdt.core.dom.ThrowStatement;
public class ThrownExceptionFinderVisitor extends ASTVisitor {
}
|
package org.ovirt.engine.ui.uicommonweb.models.datacenters;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import org.ovirt.engine.core.common.action.AddSANStorageDomainParameters;
import org.ovirt.engine.core.common.action.AttachStorageDomainToPoolParameters;
import org.ovirt.engine.core.common.action.ChangeVDSClusterParameters;
import org.ovirt.engine.core.common.action.ManagementNetworkOnClusterOperationParameters;
import org.ovirt.engine.core.common.action.StorageDomainManagementParameter;
import org.ovirt.engine.core.common.action.StorageServerConnectionParametersBase;
import org.ovirt.engine.core.common.action.VdcActionParametersBase;
import org.ovirt.engine.core.common.action.VdcActionType;
import org.ovirt.engine.core.common.action.VdcReturnValueBase;
import org.ovirt.engine.core.common.action.VdsActionParameters;
import org.ovirt.engine.core.common.action.hostdeploy.AddVdsActionParameters;
import org.ovirt.engine.core.common.action.hostdeploy.ApproveVdsParameters;
import org.ovirt.engine.core.common.businessentities.Cluster;
import org.ovirt.engine.core.common.businessentities.StorageDomain;
import org.ovirt.engine.core.common.businessentities.StorageDomainSharedStatus;
import org.ovirt.engine.core.common.businessentities.StorageDomainStatic;
import org.ovirt.engine.core.common.businessentities.StorageDomainType;
import org.ovirt.engine.core.common.businessentities.StorageFormatType;
import org.ovirt.engine.core.common.businessentities.StoragePool;
import org.ovirt.engine.core.common.businessentities.StoragePoolStatus;
import org.ovirt.engine.core.common.businessentities.StorageServerConnections;
import org.ovirt.engine.core.common.businessentities.VDS;
import org.ovirt.engine.core.common.businessentities.VDSStatus;
import org.ovirt.engine.core.common.businessentities.VdsProtocol;
import org.ovirt.engine.core.common.businessentities.storage.LUNs;
import org.ovirt.engine.core.common.businessentities.storage.LunStatus;
import org.ovirt.engine.core.common.businessentities.storage.StorageType;
import org.ovirt.engine.core.common.interfaces.SearchType;
import org.ovirt.engine.core.common.queries.ConfigurationValues;
import org.ovirt.engine.core.common.queries.GetDeviceListQueryParameters;
import org.ovirt.engine.core.common.queries.SearchParameters;
import org.ovirt.engine.core.common.queries.VdcQueryReturnValue;
import org.ovirt.engine.core.common.queries.VdcQueryType;
import org.ovirt.engine.core.common.scheduling.ClusterPolicy;
import org.ovirt.engine.core.compat.Guid;
import org.ovirt.engine.core.compat.Version;
import org.ovirt.engine.ui.frontend.AsyncQuery;
import org.ovirt.engine.ui.frontend.Frontend;
import org.ovirt.engine.ui.frontend.INewAsyncCallback;
import org.ovirt.engine.ui.uicommonweb.Linq;
import org.ovirt.engine.ui.uicommonweb.UICommand;
import org.ovirt.engine.ui.uicommonweb.dataprovider.AsyncDataProvider;
import org.ovirt.engine.ui.uicommonweb.help.HelpTag;
import org.ovirt.engine.ui.uicommonweb.models.ConfirmationModel;
import org.ovirt.engine.ui.uicommonweb.models.EntityModel;
import org.ovirt.engine.ui.uicommonweb.models.GuideModel;
import org.ovirt.engine.ui.uicommonweb.models.ListModel;
import org.ovirt.engine.ui.uicommonweb.models.Model;
import org.ovirt.engine.ui.uicommonweb.models.clusters.ClusterModel;
import org.ovirt.engine.ui.uicommonweb.models.hosts.HostModel;
import org.ovirt.engine.ui.uicommonweb.models.hosts.MoveHost;
import org.ovirt.engine.ui.uicommonweb.models.hosts.MoveHostData;
import org.ovirt.engine.ui.uicommonweb.models.hosts.NewHostModel;
import org.ovirt.engine.ui.uicommonweb.models.storage.IStorageModel;
import org.ovirt.engine.ui.uicommonweb.models.storage.LocalStorageModel;
import org.ovirt.engine.ui.uicommonweb.models.storage.LunModel;
import org.ovirt.engine.ui.uicommonweb.models.storage.NewEditStorageModelBehavior;
import org.ovirt.engine.ui.uicommonweb.models.storage.NfsStorageModel;
import org.ovirt.engine.ui.uicommonweb.models.storage.SanStorageModel;
import org.ovirt.engine.ui.uicommonweb.models.storage.StorageModel;
import org.ovirt.engine.ui.uicommonweb.models.vms.key_value.KeyValueModel;
import org.ovirt.engine.ui.uicommonweb.validation.IValidation;
import org.ovirt.engine.ui.uicommonweb.validation.NotEmptyValidation;
import org.ovirt.engine.ui.uicommonweb.validation.RegexValidation;
import org.ovirt.engine.ui.uicompat.ConstantsManager;
import org.ovirt.engine.ui.uicompat.Event;
import org.ovirt.engine.ui.uicompat.EventArgs;
import org.ovirt.engine.ui.uicompat.FrontendActionAsyncResult;
import org.ovirt.engine.ui.uicompat.FrontendMultipleActionAsyncResult;
import org.ovirt.engine.ui.uicompat.IEventListener;
import org.ovirt.engine.ui.uicompat.IFrontendActionAsyncCallback;
import org.ovirt.engine.ui.uicompat.IFrontendMultipleActionAsyncCallback;
import org.ovirt.engine.ui.uicompat.ITaskTarget;
import org.ovirt.engine.ui.uicompat.Task;
import org.ovirt.engine.ui.uicompat.TaskContext;
import com.google.gwt.user.client.Timer;
public class DataCenterGuideModel extends GuideModel implements ITaskTarget {
public final String DataCenterConfigureClustersAction = ConstantsManager.getInstance()
.getConstants()
.dataCenterConfigureClustersAction();
public final String DataCenterAddAnotherClusterAction = ConstantsManager.getInstance()
.getConstants()
.dataCenterAddAnotherClusterAction();
public final String DataCenterConfigureHostsAction = ConstantsManager.getInstance()
.getConstants()
.dataCenterConfigureHostsAction();
public final String DataCenterAddAnotherHostAction = ConstantsManager.getInstance()
.getConstants()
.dataCenterAddAnotherHostAction();
public final String DataCenterSelectHostsAction = ConstantsManager.getInstance()
.getConstants()
.dataCenterSelectHostsAction();
public final String DataCenterConfigureStorageAction = ConstantsManager.getInstance()
.getConstants()
.dataCenterConfigureStorageAction();
public final String DataCenterAddMoreStorageAction = ConstantsManager.getInstance()
.getConstants()
.dataCenterAddMoreStorageAction();
public final String DataCenterAttachStorageAction = ConstantsManager.getInstance()
.getConstants()
.dataCenterAttachStorageAction();
public final String DataCenterAttachMoreStorageAction = ConstantsManager.getInstance()
.getConstants()
.dataCenterAttachMoreStorageAction();
public final String DataCenterConfigureISOLibraryAction = ConstantsManager.getInstance()
.getConstants()
.dataCenterConfigureISOLibraryAction();
public final String DataCenterAttachISOLibraryAction = ConstantsManager.getInstance()
.getConstants()
.dataCenterAttachISOLibraryAction();
public final String NoUpHostReason = ConstantsManager.getInstance().getConstants().noUpHostReason();
public final String NoDataDomainAttachedReason = ConstantsManager.getInstance()
.getConstants()
.noDataDomainAttachedReason();
private StorageDomainStatic storageDomain;
private TaskContext context;
private IStorageModel storageModel;
private Guid storageId;
private StorageServerConnections connection;
private Guid hostId = Guid.Empty;
private String path;
private boolean removeConnection;
private ArrayList<Cluster> clusters;
private ArrayList<StorageDomain> allStorageDomains;
private ArrayList<StorageDomain> attachedStorageDomains;
private ArrayList<StorageDomain> isoStorageDomains;
private List<VDS> allHosts;
private VDS localStorageHost;
private boolean noLocalStorageHost;
public DataCenterGuideModel() {
}
@Override
public StoragePool getEntity() {
return (StoragePool) super.getEntity();
}
public void setEntity(StoragePool value) {
super.setEntity(value);
}
@Override
protected void onEntityChanged() {
super.onEntityChanged();
updateOptions();
}
private void updateOptionsNonLocalFSData() {
AsyncDataProvider.getInstance().getClusterList(new AsyncQuery(this,
new INewAsyncCallback() {
@Override
public void onSuccess(Object target, Object returnValue) {
DataCenterGuideModel dataCenterGuideModel = (DataCenterGuideModel) target;
dataCenterGuideModel.clusters = (ArrayList<Cluster>) returnValue;
dataCenterGuideModel.updateOptionsNonLocalFS();
}
}), getEntity().getId());
AsyncDataProvider.getInstance().getStorageDomainList(new AsyncQuery(this,
new INewAsyncCallback() {
@Override
public void onSuccess(Object target, Object returnValue) {
DataCenterGuideModel dataCenterGuideModel = (DataCenterGuideModel) target;
dataCenterGuideModel.allStorageDomains = (ArrayList<StorageDomain>) returnValue;
dataCenterGuideModel.updateOptionsNonLocalFS();
}
}));
AsyncDataProvider.getInstance().getStorageDomainList(new AsyncQuery(this,
new INewAsyncCallback() {
@Override
public void onSuccess(Object target, Object returnValue) {
DataCenterGuideModel dataCenterGuideModel = (DataCenterGuideModel) target;
dataCenterGuideModel.attachedStorageDomains = (ArrayList<StorageDomain>) returnValue;
dataCenterGuideModel.updateOptionsNonLocalFS();
}
}), getEntity().getId());
AsyncDataProvider.getInstance().getISOStorageDomainList(new AsyncQuery(this,
new INewAsyncCallback() {
@Override
public void onSuccess(Object target, Object returnValue) {
DataCenterGuideModel dataCenterGuideModel = (DataCenterGuideModel) target;
dataCenterGuideModel.isoStorageDomains = (ArrayList<StorageDomain>) returnValue;
dataCenterGuideModel.updateOptionsNonLocalFS();
}
}));
AsyncDataProvider.getInstance().getHostList(new AsyncQuery(this,
new INewAsyncCallback() {
@Override
public void onSuccess(Object target, Object returnValue) {
DataCenterGuideModel dataCenterGuideModel = (DataCenterGuideModel) target;
dataCenterGuideModel.allHosts = (ArrayList<VDS>) returnValue;
dataCenterGuideModel.updateOptionsNonLocalFS();
}
}));
}
private void updateOptionsLocalFSData() {
AsyncDataProvider.getInstance().getClusterList(new AsyncQuery(this,
new INewAsyncCallback() {
@Override
public void onSuccess(Object target, Object returnValue) {
DataCenterGuideModel dataCenterGuideModel = (DataCenterGuideModel) target;
dataCenterGuideModel.clusters = (ArrayList<Cluster>) returnValue;
dataCenterGuideModel.updateOptionsLocalFS();
}
}), getEntity().getId());
Frontend.getInstance().runQuery(VdcQueryType.Search, new SearchParameters("Hosts: datacenter!= " + getEntity().getName() //$NON-NLS-1$
+ " status=maintenance or status=pendingapproval ", SearchType.VDS), new AsyncQuery(this, //$NON-NLS-1$
new INewAsyncCallback() {
@Override
public void onSuccess(Object target, Object returnValue) {
DataCenterGuideModel dataCenterGuideModel = (DataCenterGuideModel) target;
List<VDS> hosts =
((VdcQueryReturnValue) returnValue).getReturnValue();
if (hosts == null) {
hosts = new ArrayList<>();
}
dataCenterGuideModel.allHosts = hosts;
AsyncDataProvider.getInstance().getLocalStorageHost(new AsyncQuery(dataCenterGuideModel,
new INewAsyncCallback() {
@Override
public void onSuccess(Object target, Object returnValue) {
DataCenterGuideModel dataCenterGuideModel = (DataCenterGuideModel) target;
if (returnValue != null) {
dataCenterGuideModel.localStorageHost = (VDS) returnValue;
} else {
noLocalStorageHost = true;
}
dataCenterGuideModel.updateOptionsLocalFS();
}
}), dataCenterGuideModel.getEntity().getName());
}
}));
}
private void updateOptionsNonLocalFS() {
if (clusters == null || allStorageDomains == null || attachedStorageDomains == null
|| isoStorageDomains == null || allHosts == null) {
return;
}
updateAddClusterAvailability();
ArrayList<VDS> hosts = new ArrayList<>();
ArrayList<VDS> availableHosts = new ArrayList<>();
ArrayList<VDS> upHosts = new ArrayList<>();
for (VDS vds : allHosts) {
if (Linq.isClusterItemExistInList(clusters, vds.getClusterId())) {
hosts.add(vds);
}
if ((vds.getStatus() == VDSStatus.Maintenance || vds.getStatus() == VDSStatus.PendingApproval)
&& doesHostSupportAnyCluster(clusters, vds)) {
availableHosts.add(vds);
}
if (vds.getStatus() == VDSStatus.Up && Linq.isClusterItemExistInList(clusters, vds.getClusterId())) {
upHosts.add(vds);
}
}
updateAddAndSelectHostAvailability(hosts, availableHosts);
List<StorageDomain> unattachedStorages = getUnattachedStorages();
List<StorageDomain> attachedDataStorages = new ArrayList<>();
List<StorageDomain> attachedIsoStorages = new ArrayList<>();
for (StorageDomain sd : attachedStorageDomains) {
if (sd.getStorageDomainType().isDataDomain()) {
attachedDataStorages.add(sd);
}
else if (sd.getStorageDomainType() == StorageDomainType.ISO) {
attachedIsoStorages.add(sd);
}
}
updateAddAndAttachDataDomainAvailability(upHosts, unattachedStorages, attachedDataStorages);
updateAddAndAttachIsoDomainAvailability(upHosts, attachedDataStorages, attachedIsoStorages);
stopProgress();
}
private void updateAddAndSelectHostAvailability(ArrayList<VDS> hosts, ArrayList<VDS> availableHosts) {
UICommand addHostAction = new UICommand("AddHost", this); //$NON-NLS-1$
addHostAction.setIsExecutionAllowed(clusters.size() > 0);
if (hosts.isEmpty()) {
addHostAction.setTitle(DataCenterConfigureHostsAction);
getCompulsoryActions().add(addHostAction);
} else {
addHostAction.setTitle(DataCenterAddAnotherHostAction);
getOptionalActions().add(addHostAction);
}
// Select host action.
UICommand selectHostAction = new UICommand("SelectHost", this); //$NON-NLS-1$
// If now compatible hosts are found - disable the select host button
selectHostAction.setIsChangeable(availableHosts.size() > 0);
selectHostAction.setIsExecutionAllowed(availableHosts.size() > 0);
if (clusters.size() > 0) {
if (hosts.isEmpty()) {
selectHostAction.setTitle(DataCenterSelectHostsAction);
getCompulsoryActions().add(selectHostAction);
}
else {
selectHostAction.setTitle(DataCenterSelectHostsAction);
getOptionalActions().add(selectHostAction);
}
}
}
private List<StorageDomain> getUnattachedStorages() {
List<StorageDomain> unattachedStorage = new ArrayList<>();
for (StorageDomain item : allStorageDomains) {
if (item.getStorageDomainType() == StorageDomainType.Data
&& item.getStorageDomainSharedStatus() == StorageDomainSharedStatus.Unattached) {
if (getEntity().getStoragePoolFormatType() == null ||
getEntity().getStoragePoolFormatType() == item.getStorageStaticData().getStorageFormat()) {
unattachedStorage.add(item);
}
}
}
return unattachedStorage;
}
private void updateAddClusterAvailability() {
// Add cluster action.
UICommand addClusterAction = new UICommand("AddCluster", this); //$NON-NLS-1$
if (clusters.isEmpty()) {
addClusterAction.setTitle(DataCenterConfigureClustersAction);
getCompulsoryActions().add(addClusterAction);
}
else {
addClusterAction.setTitle(DataCenterAddAnotherClusterAction);
getOptionalActions().add(addClusterAction);
}
}
// Attach ISO storage action.
// Allow to attach ISO domain only when there are Data storages attached
// and there ISO storages to attach and there are no ISO storages actually
// attached.
private void updateAddAndAttachIsoDomainAvailability(List<VDS> upHosts, List<StorageDomain> attachedDataStorages, List<StorageDomain> attachedIsoStorages) {
boolean attachOrAddIsoAvailable = attachedIsoStorages.isEmpty();
boolean masterStorageExistsAndRunning = Linq.isAnyStorageDomainIsMasterAndActive(attachedDataStorages);
boolean addIsoAllowed =
attachedDataStorages.size() > 0 && masterStorageExistsAndRunning
&& attachedIsoStorages.isEmpty() && upHosts.size() > 0;
if (attachOrAddIsoAvailable) {
UICommand addIsoStorageAction = new UICommand("AddIsoStorage", this); //$NON-NLS-1$
addIsoStorageAction.setTitle(DataCenterConfigureISOLibraryAction);
getOptionalActions().add(addIsoStorageAction);
UICommand attachIsoStorageAction = new UICommand("AttachIsoStorage", this); //$NON-NLS-1$
attachIsoStorageAction.setTitle(DataCenterAttachISOLibraryAction);
getOptionalActions().add(attachIsoStorageAction);
if (!masterStorageExistsAndRunning) {
addIsoStorageAction.getExecuteProhibitionReasons().add(NoDataDomainAttachedReason);
attachIsoStorageAction.getExecuteProhibitionReasons().add(NoDataDomainAttachedReason);
}
if (upHosts.isEmpty()) {
addIsoStorageAction.getExecuteProhibitionReasons().add(NoUpHostReason);
attachIsoStorageAction.getExecuteProhibitionReasons().add(NoUpHostReason);
}
addIsoStorageAction.setIsExecutionAllowed(addIsoAllowed);
attachIsoStorageAction.setIsExecutionAllowed(addIsoAllowed && isoStorageDomains.size() > 0);
}
}
private void updateAddAndAttachDataDomainAvailability(List<VDS> upHosts, List<StorageDomain> unattachedStorage, List<StorageDomain> attachedDataStorages) {
UICommand addDataStorageAction = new UICommand("AddDataStorage", this); //$NON-NLS-1$
addDataStorageAction.getExecuteProhibitionReasons().add(NoUpHostReason);
addDataStorageAction.setIsExecutionAllowed(upHosts.size() > 0);
if (unattachedStorage.isEmpty() && attachedDataStorages.isEmpty()) {
addDataStorageAction.setTitle(DataCenterConfigureStorageAction);
getCompulsoryActions().add(addDataStorageAction);
}
else {
addDataStorageAction.setTitle(DataCenterAddMoreStorageAction);
getOptionalActions().add(addDataStorageAction);
}
// Attach data storage action.
UICommand attachDataStorageAction = new UICommand("AttachDataStorage", this); //$NON-NLS-1$
if (upHosts.isEmpty()) {
attachDataStorageAction.getExecuteProhibitionReasons().add(NoUpHostReason);
}
attachDataStorageAction.setIsExecutionAllowed(unattachedStorage.size() > 0 && upHosts.size() > 0);
if (attachedDataStorages.isEmpty()) {
attachDataStorageAction.setTitle(DataCenterAttachStorageAction);
getCompulsoryActions().add(attachDataStorageAction);
}
else {
attachDataStorageAction.setTitle(DataCenterAttachMoreStorageAction);
getOptionalActions().add(attachDataStorageAction);
}
}
private boolean doesHostSupportAnyCluster(List<Cluster> clusterList, VDS host){
for (Cluster cluster : clusterList){
if (host.getSupportedClusterVersionsSet().contains(cluster.getCompatibilityVersion())){
return true;
}
}
return false;
}
private void updateOptionsLocalFS() {
if (clusters == null || allHosts == null || (localStorageHost == null && !noLocalStorageHost)) {
return;
}
UICommand addClusterAction = new UICommand("AddCluster", this); //$NON-NLS-1$
if (clusters.isEmpty()) {
addClusterAction.setTitle(DataCenterConfigureClustersAction);
getCompulsoryActions().add(addClusterAction);
}
else {
UICommand addHostAction = new UICommand("AddHost", this); //$NON-NLS-1$
addHostAction.setTitle(DataCenterConfigureHostsAction);
UICommand selectHost = new UICommand("SelectHost", this); //$NON-NLS-1$
selectHost.setTitle(DataCenterSelectHostsAction);
boolean hasMaintenance3_0Host = false;
Version version3_0 = new Version(3, 0);
for (VDS vds : allHosts) {
String[] hostVersions = vds.getSupportedClusterLevels().split("[,]", -1); //$NON-NLS-1$
for (String hostVersion : hostVersions) {
if (version3_0.compareTo(new Version(hostVersion)) <= 0) {
hasMaintenance3_0Host = true;
break;
}
}
if (hasMaintenance3_0Host) {
break;
}
}
if (localStorageHost != null) {
String hasHostReason =
ConstantsManager.getInstance().getConstants().localDataCenterAlreadyContainsAHostDcGuide();
addHostAction.getExecuteProhibitionReasons().add(hasHostReason);
addHostAction.setIsExecutionAllowed(false);
selectHost.getExecuteProhibitionReasons().add(hasHostReason);
selectHost.setIsExecutionAllowed(false);
if (localStorageHost.getStatus() == VDSStatus.Up) {
UICommand addLocalStorageAction = new UICommand("AddLocalStorage", this); //$NON-NLS-1$
addLocalStorageAction.setTitle(ConstantsManager.getInstance().getConstants().addLocalStorageTitle());
getOptionalActions().add(addLocalStorageAction);
}
getNote().setIsAvailable(true);
getNote().setEntity(ConstantsManager.getInstance().getConstants().attachLocalStorageDomainToFullyConfigure());
}
else if (getEntity().getStatus() != StoragePoolStatus.Uninitialized) {
String dataCenterInitializeReason =
ConstantsManager.getInstance().getConstants().dataCenterWasAlreadyInitializedDcGuide();
addHostAction.getExecuteProhibitionReasons().add(dataCenterInitializeReason);
addHostAction.setIsExecutionAllowed(false);
selectHost.getExecuteProhibitionReasons().add(dataCenterInitializeReason);
selectHost.setIsExecutionAllowed(false);
}
if (hasMaintenance3_0Host) {
getOptionalActions().add(selectHost);
}
getCompulsoryActions().add(addHostAction);
}
stopProgress();
}
private void updateOptions() {
getCompulsoryActions().clear();
getOptionalActions().clear();
if (getEntity() != null) {
startProgress();
if (!getEntity().isLocal()) {
updateOptionsNonLocalFSData();
}
else {
updateOptionsLocalFSData();
}
}
}
private void resetData() {
storageDomain = null;
storageModel = null;
storageId = null;
connection = null;
removeConnection = false;
path = null;
hostId = Guid.Empty;
clusters = null;
allStorageDomains = null;
attachedStorageDomains = null;
isoStorageDomains = null;
allHosts = null;
localStorageHost = null;
noLocalStorageHost = false;
}
private void addLocalStorage() {
StorageModel model = new StorageModel(new NewEditStorageModelBehavior());
setWindow(model);
model.setTitle(ConstantsManager.getInstance().getConstants().newLocalDomainTitle());
model.setHelpTag(HelpTag.new_local_domain);
model.setHashName("new_local_domain"); //$NON-NLS-1$
LocalStorageModel localStorageModel = new LocalStorageModel();
localStorageModel.setRole(StorageDomainType.Data);
ArrayList<IStorageModel> list = new ArrayList<>();
list.add(localStorageModel);
model.setStorageModels(list);
model.setCurrentStorageItem(list.get(0));
AsyncDataProvider.getInstance().getLocalStorageHost(new AsyncQuery(new Object[] { this, model },
new INewAsyncCallback() {
@Override
public void onSuccess(Object target, Object returnValue) {
Object[] array = (Object[]) target;
DataCenterGuideModel listModel = (DataCenterGuideModel) array[0];
StorageModel model = (StorageModel) array[1];
VDS localHost = (VDS) returnValue;
model.getHost()
.setItems(new ArrayList<>(Arrays.asList(new VDS[]{localHost})));
model.getHost().setSelectedItem(localHost);
model.getDataCenter().setItems(Collections.singletonList(getEntity()), getEntity());
UICommand tempVar = UICommand.createDefaultOkUiCommand("OnAddStorage", listModel); //$NON-NLS-1$
model.getCommands().add(tempVar);
UICommand tempVar2 = UICommand.createCancelUiCommand("Cancel", listModel); //$NON-NLS-1$
model.getCommands().add(tempVar2);
}
}),
getEntity().getName());
}
public void addIsoStorage() {
addStorageInternal(ConstantsManager.getInstance().getConstants().newISOLibraryTitle(), StorageDomainType.ISO);
}
public void addDataStorage() {
addStorageInternal(ConstantsManager.getInstance().getConstants().newStorageTitle(), StorageDomainType.Data);
}
private void addStorageInternal(String title, StorageDomainType type) {
StorageModel model = new StorageModel(new NewEditStorageModelBehavior());
setWindow(model);
model.setTitle(title);
model.setHelpTag(HelpTag.new_domain);
model.setHashName("new_domain"); //$NON-NLS-1$
ArrayList<StoragePool> dataCenters = new ArrayList<>();
dataCenters.add(getEntity());
model.getDataCenter().setItems(dataCenters, getEntity());
model.getDataCenter().setIsChangeable(false);
List<IStorageModel> items = null;
if (type == StorageDomainType.Data) {
items = AsyncDataProvider.getInstance().getDataStorageModels();
}
else if (type == StorageDomainType.ISO) {
items = AsyncDataProvider.getInstance().getIsoStorageModels();
}
model.setStorageModels(items);
model.initialize();
UICommand tempVar6 = UICommand.createDefaultOkUiCommand("OnAddStorage", this); //$NON-NLS-1$
model.getCommands().add(tempVar6);
UICommand tempVar7 = UICommand.createCancelUiCommand("Cancel", this); //$NON-NLS-1$
model.getCommands().add(tempVar7);
}
public void onAddStorage() {
StorageModel model = (StorageModel) getWindow();
String storageName = model.getName().getEntity();
AsyncDataProvider.getInstance().isStorageDomainNameUnique(new AsyncQuery(this,
new INewAsyncCallback() {
@Override
public void onSuccess(Object target, Object returnValue) {
DataCenterGuideModel dataCenterGuideModel = (DataCenterGuideModel) target;
StorageModel storageModel = (StorageModel) dataCenterGuideModel.getWindow();
String name = storageModel.getName().getEntity();
String tempVar = storageModel.getOriginalName();
String originalName = (tempVar != null) ? tempVar : ""; //$NON-NLS-1$
boolean isNameUnique = (Boolean) returnValue;
if (!isNameUnique && name.compareToIgnoreCase(originalName) != 0) {
storageModel.getName()
.getInvalidityReasons()
.add(ConstantsManager.getInstance().getConstants().nameMustBeUniqueInvalidReason());
storageModel.getName().setIsValid(false);
}
AsyncDataProvider.getInstance().getStorageDomainMaxNameLength(new AsyncQuery(dataCenterGuideModel,
new INewAsyncCallback() {
@Override
public void onSuccess(Object target1, Object returnValue1) {
DataCenterGuideModel dataCenterGuideModel1 = (DataCenterGuideModel) target1;
StorageModel storageModel1 = (StorageModel) dataCenterGuideModel1.getWindow();
int nameMaxLength = (Integer) returnValue1;
RegexValidation tempVar2 = new RegexValidation();
tempVar2.setExpression("^[A-Za-z0-9_-]{1," + nameMaxLength + "}$"); //$NON-NLS-1$ //$NON-NLS-2$
tempVar2.setMessage(ConstantsManager.getInstance().getMessages()
.nameCanContainOnlyMsg(nameMaxLength));
storageModel1.getName().validateEntity(new IValidation[] {
new NotEmptyValidation(), tempVar2});
dataCenterGuideModel1.postOnAddStorage();
}
}));
}
}),
storageName);
}
public void postOnAddStorage() {
StorageModel model = (StorageModel) getWindow();
if (!model.validate()) {
return;
}
// Save changes.
if (model.getCurrentStorageItem() instanceof NfsStorageModel) {
saveNfsStorage();
}
else if (model.getCurrentStorageItem() instanceof LocalStorageModel) {
saveLocalStorage();
}
else {
saveSanStorage();
}
}
private void saveLocalStorage() {
if (getWindow().getProgress() != null) {
return;
}
getWindow().startProgress();
Task.create(this, new ArrayList<>(Arrays.asList(new Object[]{"SaveLocal"}))).run(); //$NON-NLS-1$
}
private void saveLocalStorage(TaskContext context) {
this.context = context;
StorageModel model = (StorageModel) getWindow();
VDS host = model.getHost().getSelectedItem();
boolean isNew = model.getStorage() == null;
storageModel = model.getCurrentStorageItem();
LocalStorageModel localModel = (LocalStorageModel) storageModel;
path = localModel.getPath().getEntity();
storageDomain = new StorageDomainStatic();
storageDomain.setStorageType(isNew ? storageModel.getType() : storageDomain.getStorageType());
storageDomain.setStorageDomainType(isNew ? storageModel.getRole() : storageDomain.getStorageDomainType());
storageDomain.setStorageName(model.getName().getEntity());
AsyncDataProvider.getInstance().getStorageDomainsByConnection(new AsyncQuery(this,
new INewAsyncCallback() {
@Override
public void onSuccess(Object target, Object returnValue) {
DataCenterGuideModel dataCenterGuideModel = (DataCenterGuideModel) target;
ArrayList<StorageDomain> storages =
(ArrayList<StorageDomain>) returnValue;
if (storages != null && storages.size() > 0) {
String storageName = storages.get(0).getStorageName();
onFinish(dataCenterGuideModel.context,
false,
dataCenterGuideModel.storageModel,
ConstantsManager.getInstance()
.getMessages()
.createOperationFailedDcGuideMsg(storageName));
}
else {
dataCenterGuideModel.saveNewLocalStorage();
}
}
}),
host.getStoragePoolId(),
path);
}
public void saveNewLocalStorage() {
StorageModel model = (StorageModel) getWindow();
LocalStorageModel localModel = (LocalStorageModel) model.getCurrentStorageItem();
VDS host = model.getHost().getSelectedItem();
hostId = host.getId();
// Create storage connection.
StorageServerConnections tempVar = new StorageServerConnections();
tempVar.setConnection(path);
tempVar.setStorageType(localModel.getType());
connection = tempVar;
ArrayList<VdcActionType> actionTypes = new ArrayList<>();
ArrayList<VdcActionParametersBase> parameters = new ArrayList<>();
actionTypes.add(VdcActionType.AddStorageServerConnection);
actionTypes.add(VdcActionType.AddLocalStorageDomain);
parameters.add(new StorageServerConnectionParametersBase(connection, host.getId()));
StorageDomainManagementParameter tempVar2 = new StorageDomainManagementParameter(storageDomain);
tempVar2.setVdsId(host.getId());
parameters.add(tempVar2);
IFrontendActionAsyncCallback callback1 = new IFrontendActionAsyncCallback() {
@Override
public void executed(FrontendActionAsyncResult result) {
DataCenterGuideModel dataCenterGuideModel = (DataCenterGuideModel) result.getState();
dataCenterGuideModel.removeConnection = true;
VdcReturnValueBase vdcReturnValueBase = result.getReturnValue();
dataCenterGuideModel.storageDomain.setStorage((String) vdcReturnValueBase.getActionReturnValue());
}
};
IFrontendActionAsyncCallback callback2 = new IFrontendActionAsyncCallback() {
@Override
public void executed(FrontendActionAsyncResult result) {
DataCenterGuideModel dataCenterGuideModel = (DataCenterGuideModel) result.getState();
dataCenterGuideModel.removeConnection = false;
dataCenterGuideModel.onFinish(dataCenterGuideModel.context, true, dataCenterGuideModel.storageModel);
}
};
IFrontendActionAsyncCallback failureCallback = new IFrontendActionAsyncCallback() {
@Override
public void executed(FrontendActionAsyncResult result) {
DataCenterGuideModel dataCenterGuideModel = (DataCenterGuideModel) result.getState();
if (dataCenterGuideModel.removeConnection) {
dataCenterGuideModel.cleanConnection(dataCenterGuideModel.connection, dataCenterGuideModel.hostId);
dataCenterGuideModel.removeConnection = false;
}
dataCenterGuideModel.onFinish(dataCenterGuideModel.context, false, dataCenterGuideModel.storageModel);
}
};
Frontend.getInstance().runMultipleActions(actionTypes,
parameters,
new ArrayList<>(Arrays.asList(new IFrontendActionAsyncCallback[]{callback1, callback2})),
failureCallback,
this);
}
private void cleanConnection(StorageServerConnections connection, Guid hostId) {
Frontend.getInstance().runAction(VdcActionType.DisconnectStorageServerConnection,
new StorageServerConnectionParametersBase(connection, hostId),
null,
this);
}
public void onFinish(TaskContext context, boolean isSucceeded, IStorageModel model) {
onFinish(context, isSucceeded, model, null);
}
public void onFinish(TaskContext context, boolean isSucceeded, IStorageModel model, String message) {
context.invokeUIThread(this,
new ArrayList<>(Arrays.asList(new Object[]{"Finish", isSucceeded, model, message}))); //$NON-NLS-1$
}
private void saveNfsStorage() {
if (getWindow().getProgress() != null) {
return;
}
getWindow().startProgress();
Task.create(this, new ArrayList<>(Arrays.asList(new Object[]{"SaveNfs"}))).run(); //$NON-NLS-1$
}
private void saveNfsStorage(TaskContext context) {
this.context = context;
StorageModel model = (StorageModel) getWindow();
boolean isNew = model.getStorage() == null;
storageModel = model.getCurrentStorageItem();
NfsStorageModel nfsModel = (NfsStorageModel) storageModel;
path = nfsModel.getPath().getEntity();
storageDomain = new StorageDomainStatic();
storageDomain.setStorageType(isNew ? storageModel.getType() : storageDomain.getStorageType());
storageDomain.setStorageDomainType(isNew ? storageModel.getRole() : storageDomain.getStorageDomainType());
storageDomain.setStorageName(model.getName().getEntity());
storageDomain.setStorageFormat(model.getFormat().getSelectedItem());
AsyncDataProvider.getInstance().getStorageDomainsByConnection(new AsyncQuery(this,
new INewAsyncCallback() {
@Override
public void onSuccess(Object target, Object returnValue) {
DataCenterGuideModel dataCenterGuideModel = (DataCenterGuideModel) target;
ArrayList<StorageDomain> storages =
(ArrayList<StorageDomain>) returnValue;
if (storages != null && storages.size() > 0) {
String storageName = storages.get(0).getStorageName();
onFinish(dataCenterGuideModel.context,
false,
dataCenterGuideModel.storageModel,
ConstantsManager.getInstance()
.getMessages()
.createOperationFailedDcGuideMsg(storageName));
}
else {
dataCenterGuideModel.saveNewNfsStorage();
}
}
}),
null,
path);
}
public void saveNewNfsStorage() {
StorageModel model = (StorageModel) getWindow();
NfsStorageModel nfsModel = (NfsStorageModel) model.getCurrentStorageItem();
VDS host = model.getHost().getSelectedItem();
hostId = host.getId();
// Create storage connection.
StorageServerConnections tempVar = new StorageServerConnections();
tempVar.setConnection(path);
tempVar.setStorageType(nfsModel.getType());
connection = tempVar;
ArrayList<VdcActionType> actionTypes = new ArrayList<>();
ArrayList<VdcActionParametersBase> parameters = new ArrayList<>();
actionTypes.add(VdcActionType.AddStorageServerConnection);
actionTypes.add(VdcActionType.AddNFSStorageDomain);
actionTypes.add(VdcActionType.DisconnectStorageServerConnection);
parameters.add(new StorageServerConnectionParametersBase(connection, host.getId()));
StorageDomainManagementParameter tempVar2 = new StorageDomainManagementParameter(storageDomain);
tempVar2.setVdsId(host.getId());
parameters.add(tempVar2);
parameters.add(new StorageServerConnectionParametersBase(connection, host.getId()));
IFrontendActionAsyncCallback callback1 = new IFrontendActionAsyncCallback() {
@Override
public void executed(FrontendActionAsyncResult result) {
DataCenterGuideModel dataCenterGuideModel = (DataCenterGuideModel) result.getState();
VdcReturnValueBase vdcReturnValueBase = result.getReturnValue();
dataCenterGuideModel.storageDomain.setStorage((String) vdcReturnValueBase.getActionReturnValue());
}
};
IFrontendActionAsyncCallback callback2 = new IFrontendActionAsyncCallback() {
@Override
public void executed(FrontendActionAsyncResult result) {
DataCenterGuideModel dataCenterGuideModel = (DataCenterGuideModel) result.getState();
VdcReturnValueBase vdcReturnValueBase = result.getReturnValue();
dataCenterGuideModel.storageId = vdcReturnValueBase.getActionReturnValue();
}
};
IFrontendActionAsyncCallback callback3 = new IFrontendActionAsyncCallback() {
@Override
public void executed(FrontendActionAsyncResult result) {
DataCenterGuideModel dataCenterGuideModel = (DataCenterGuideModel) result.getState();
StorageModel storageModel = (StorageModel) dataCenterGuideModel.getWindow();
// Attach storage to data center as neccessary.
StoragePool dataCenter = storageModel.getDataCenter().getSelectedItem();
if (!dataCenter.getId().equals(StorageModel.UnassignedDataCenterId)) {
dataCenterGuideModel.attachStorageToDataCenter(dataCenterGuideModel.storageId,
dataCenter.getId());
}
dataCenterGuideModel.onFinish(dataCenterGuideModel.context, true, dataCenterGuideModel.storageModel);
}
};
IFrontendActionAsyncCallback failureCallback = new IFrontendActionAsyncCallback() {
@Override
public void executed(FrontendActionAsyncResult result) {
DataCenterGuideModel dataCenterGuideModel = (DataCenterGuideModel) result.getState();
dataCenterGuideModel.cleanConnection(dataCenterGuideModel.connection, dataCenterGuideModel.hostId);
dataCenterGuideModel.onFinish(dataCenterGuideModel.context, false, dataCenterGuideModel.storageModel);
}
};
Frontend.getInstance().runMultipleActions(actionTypes,
parameters,
new ArrayList<>(Arrays.asList(new IFrontendActionAsyncCallback[]{callback1, callback2, callback3})),
failureCallback,
this);
}
private void saveSanStorage() {
if (getWindow().getProgress() != null) {
return;
}
getWindow().startProgress();
Task.create(this, new ArrayList<>(Arrays.asList(new Object[]{"SaveSan"}))).run(); //$NON-NLS-1$
}
private void saveSanStorage(TaskContext context) {
this.context = context;
StorageModel model = (StorageModel) getWindow();
SanStorageModel sanModel = (SanStorageModel) model.getCurrentStorageItem();
storageDomain = new StorageDomainStatic();
storageDomain.setStorageType(sanModel.getType());
storageDomain.setStorageDomainType(sanModel.getRole());
storageDomain.setStorageFormat(sanModel.getContainer().getFormat().getSelectedItem());
storageDomain.setStorageName(model.getName().getEntity());
AsyncDataProvider.getInstance().getStorageDomainsByConnection(new AsyncQuery(this,
new INewAsyncCallback() {
@Override
public void onSuccess(Object target, Object returnValue) {
DataCenterGuideModel dataCenterGuideModel = (DataCenterGuideModel) target;
ArrayList<StorageDomain> storages =
(ArrayList<StorageDomain>) returnValue;
if (storages != null && storages.size() > 0) {
String storageName = storages.get(0).getStorageName();
onFinish(dataCenterGuideModel.context,
false,
dataCenterGuideModel.storageModel,
ConstantsManager.getInstance()
.getMessages()
.createOperationFailedDcGuideMsg(storageName));
}
else {
dataCenterGuideModel.saveNewSanStorage();
}
dataCenterGuideModel.getWindow().stopProgress();
}
}),
null,
path);
}
public void saveNewSanStorage() {
StorageModel storageModel = (StorageModel) getWindow();
final SanStorageModel sanStorageModel = (SanStorageModel) storageModel.getCurrentStorageItem();
Map<LunStatus, List<LUNs>> lunsMapByStatus = sanStorageModel.getLunsMapByStatus(sanStorageModel.getAddedLuns());
// The status will be either all Unknown (for DC above 3.5) or either Free/Used
// Once we stop supporting 3.5 and below , we will won't need the getLunsMapByStatus method
if (!lunsMapByStatus.get(LunStatus.Unknown).isEmpty()) {
Guid hostId = sanStorageModel.getContainer().getHost().getSelectedItem().getId();
Model target = getWidgetModel() != null ? getWidgetModel() : sanStorageModel.getContainer();
List<String> unkownStatusLuns = new ArrayList<>();
for (LUNs lun : lunsMapByStatus.get(LunStatus.Unknown)) {
unkownStatusLuns.add(lun.getLUNId());
}
Frontend.getInstance()
.runQuery(VdcQueryType.GetDeviceList,
new GetDeviceListQueryParameters(hostId,
sanStorageModel.getType(),
true,
unkownStatusLuns),
new AsyncQuery(target, new INewAsyncCallback() {
@Override
public void onSuccess(Object target, Object returnValue) {
VdcQueryReturnValue response = (VdcQueryReturnValue) returnValue;
if (response.getSucceeded()) {
List<LUNs> checkedLuns = (ArrayList<LUNs>) response.getReturnValue();
postGetLunsMessages(sanStorageModel.getUsedLunsMessages(checkedLuns));
} else {
sanStorageModel.setGetLUNsFailure(
ConstantsManager.getInstance()
.getConstants()
.couldNotRetrieveLUNsLunsFailure());
}
}
}, true));
} else {
postGetLunsMessages(sanStorageModel.getUsedLunsMessages(lunsMapByStatus.get(LunStatus.Used)));
}
}
private void postGetLunsMessages(ArrayList<String> usedLunsMessages) {
if (usedLunsMessages.isEmpty()) {
onSaveSanStorage();
}
else {
forceCreationWarning(usedLunsMessages);
}
}
private void onSaveSanStorage() {
ConfirmationModel confirmationModel = (ConfirmationModel) getConfirmWindow();
if (confirmationModel != null && !confirmationModel.validate()) {
return;
}
cancelConfirm();
getWindow().startProgress();
StorageModel model = (StorageModel) getWindow();
SanStorageModel sanModel = (SanStorageModel) model.getCurrentStorageItem();
VDS host = model.getHost().getSelectedItem();
boolean force = sanModel.isForce();
ArrayList<String> lunIds = new ArrayList<>();
for (LunModel lun : sanModel.getAddedLuns()) {
lunIds.add(lun.getLunId());
}
AddSANStorageDomainParameters params = new AddSANStorageDomainParameters(storageDomain);
params.setVdsId(host.getId());
params.setLunIds(lunIds);
params.setForce(force);
Frontend.getInstance().runAction(VdcActionType.AddSANStorageDomain, params,
new IFrontendActionAsyncCallback() {
@Override
public void executed(FrontendActionAsyncResult result) {
DataCenterGuideModel dataCenterGuideModel = (DataCenterGuideModel) result.getState();
StorageModel storageModel = (StorageModel) dataCenterGuideModel.getWindow();
StoragePool dataCenter = storageModel.getDataCenter().getSelectedItem();
if (!dataCenter.getId().equals(StorageModel.UnassignedDataCenterId)) {
VdcReturnValueBase returnValue = result.getReturnValue();
Guid storageId = returnValue.getActionReturnValue();
dataCenterGuideModel.attachStorageToDataCenter(storageId, dataCenter.getId());
}
dataCenterGuideModel.onFinish(dataCenterGuideModel.context,
true,
dataCenterGuideModel.storageModel);
}
}, this);
}
private void forceCreationWarning(ArrayList<String> usedLunsMessages) {
StorageModel storageModel = (StorageModel) getWindow();
SanStorageModel sanStorageModel = (SanStorageModel) storageModel.getCurrentStorageItem();
sanStorageModel.setForce(true);
ConfirmationModel model = new ConfirmationModel();
setConfirmWindow(model);
model.setTitle(ConstantsManager.getInstance().getConstants().forceStorageDomainCreation());
model.setMessage(ConstantsManager.getInstance().getConstants().lunsAlreadyInUse());
model.setHelpTag(HelpTag.force_storage_domain_creation);
model.setHashName("force_storage_domain_creation"); //$NON-NLS-1$
model.setItems(usedLunsMessages);
UICommand onSaveSanStorageCommand = UICommand.createDefaultOkUiCommand("OnSaveSanStorage", this); //$NON-NLS-1$
model.getCommands().add(onSaveSanStorageCommand);
UICommand cancelConfirmCommand = UICommand.createCancelUiCommand("CancelConfirm", this); //$NON-NLS-1$
model.getCommands().add(cancelConfirmCommand);
}
private void attachStorageInternal(List<StorageDomain> storages, String title) {
ListModel model = new ListModel();
model.setTitle(title);
setWindow(model);
ArrayList<EntityModel> items = new ArrayList<>();
for (StorageDomain sd : storages) {
EntityModel tempVar = new EntityModel();
tempVar.setEntity(sd);
items.add(tempVar);
}
model.setItems(items);
UICommand tempVar2 = UICommand.createDefaultOkUiCommand("OnAttachStorage", this); //$NON-NLS-1$
model.getCommands().add(tempVar2);
UICommand tempVar3 = UICommand.createCancelUiCommand("Cancel", this); //$NON-NLS-1$
model.getCommands().add(tempVar3);
}
private void attachStorageToDataCenter(Guid storageId, Guid dataCenterId) {
Frontend.getInstance().runAction(VdcActionType.AttachStorageDomainToPool, new AttachStorageDomainToPoolParameters(storageId,
dataCenterId),
null,
this);
}
public void onAttachStorage() {
ListModel model = (ListModel) getWindow();
ArrayList<StorageDomain> items = new ArrayList<>();
for (EntityModel a : Linq.<EntityModel> cast(model.getItems())) {
if (a.getIsSelected()) {
items.add((StorageDomain) a.getEntity());
}
}
if (items.size() > 0) {
for (StorageDomain sd : items) {
attachStorageToDataCenter(sd.getId(), getEntity().getId());
}
}
cancel();
postAction();
}
public void attachIsoStorage() {
AsyncDataProvider.getInstance().getStorageDomainList(new AsyncQuery(this,
new INewAsyncCallback() {
@Override
public void onSuccess(Object target, Object returnValue) {
DataCenterGuideModel dataCenterGuideModel = (DataCenterGuideModel) target;
ArrayList<StorageDomain> attachedStorage =
new ArrayList<>();
AsyncDataProvider.getInstance().getISOStorageDomainList(new AsyncQuery(new Object[] {dataCenterGuideModel,
attachedStorage},
new INewAsyncCallback() {
@Override
public void onSuccess(Object target, Object returnValue) {
Object[] array = (Object[]) target;
DataCenterGuideModel dataCenterGuideModel = (DataCenterGuideModel) array[0];
ArrayList<StorageDomain> attachedStorage =
(ArrayList<StorageDomain>) array[1];
ArrayList<StorageDomain> isoStorageDomains =
(ArrayList<StorageDomain>) returnValue;
ArrayList<StorageDomain> sdl =
new ArrayList<>();
for (StorageDomain a : isoStorageDomains) {
boolean isContains = false;
for (StorageDomain b : attachedStorage) {
if (b.getId().equals(a.getId())) {
isContains = true;
break;
}
}
if (!isContains) {
sdl.add(a);
}
}
dataCenterGuideModel.attachStorageInternal(sdl, ConstantsManager.getInstance()
.getConstants()
.attachISOLibraryTitle());
}
}));
}
}),
getEntity().getId());
}
public void attachDataStorage() {
AsyncDataProvider.getInstance().getStorageDomainList(new AsyncQuery(this,
new INewAsyncCallback() {
@Override
public void onSuccess(Object target, Object returnValue) {
DataCenterGuideModel dataCenterGuideModel = (DataCenterGuideModel) target;
ArrayList<StorageDomain> storageDomains =
(ArrayList<StorageDomain>) returnValue;
ArrayList<StorageDomain> unattachedStorage =
new ArrayList<>();
boolean addToList;
Version version3_0 = new Version(3, 0);
for (StorageDomain item : storageDomains) {
addToList = false;
if (item.getStorageDomainType() == StorageDomainType.Data
&& (item.getStorageType() == StorageType.LOCALFS) == dataCenterGuideModel.getEntity()
.isLocal()
&& item.getStorageDomainSharedStatus() == StorageDomainSharedStatus.Unattached) {
if (getEntity().getStoragePoolFormatType() == null) {
// compat logic: in case its not v1 and the version is less than 3.0 continue.
if (item.getStorageStaticData().getStorageFormat() != StorageFormatType.V1
&& dataCenterGuideModel.getEntity()
.getCompatibilityVersion()
.compareTo(version3_0) < 0) {
continue;
}
addToList = true;
} else if (getEntity().getStoragePoolFormatType() == item.getStorageStaticData()
.getStorageFormat()) {
addToList = true;
}
}
if (addToList) {
unattachedStorage.add(item);
}
}
dataCenterGuideModel.attachStorageInternal(unattachedStorage, ConstantsManager.getInstance()
.getConstants()
.attachStorageTitle());
}
}));
}
public void addCluster() {
ClusterModel model = new ClusterModel();
model.init(false);
setWindow(model);
model.setTitle(ConstantsManager.getInstance().getConstants().newClusterTitle());
model.setHelpTag(HelpTag.new_cluster);
model.setHashName("new_cluster"); //$NON-NLS-1$
model.setIsNew(true);
ArrayList<StoragePool> dataCenters = new ArrayList<>();
dataCenters.add(getEntity());
model.getDataCenter().setItems(dataCenters, getEntity());
model.getDataCenter().setIsChangeable(false);
UICommand tempVar = UICommand.createDefaultOkUiCommand("OnAddCluster", this); //$NON-NLS-1$
model.getCommands().add(tempVar);
UICommand tempVar2 = UICommand.createCancelUiCommand("Cancel", this); //$NON-NLS-1$
model.getCommands().add(tempVar2);
}
public void onAddCluster() {
ClusterModel model = (ClusterModel) getWindow();
Cluster cluster = new Cluster();
if (model.getProgress() != null) {
return;
}
if (!model.validate(model.getEnableOvirtService().getEntity())) { // CPU is mandatory only if the
// cluster is virt enabled
return;
}
// Save changes.
Version version = model.getVersion().getSelectedItem();
cluster.setName(model.getName().getEntity());
cluster.setDescription(model.getDescription().getEntity());
cluster.setComment(model.getComment().getEntity());
cluster.setStoragePoolId(model.getDataCenter().getSelectedItem().getId());
if (model.getCPU().getSelectedItem() != null) {
cluster.setCpuName(model.getCPU().getSelectedItem().getCpuName());
}
cluster.setMaxVdsMemoryOverCommit(model.getMemoryOverCommit());
cluster.setTransparentHugepages(version.compareTo(new Version("3.0")) >= 0); //$NON-NLS-1$
cluster.setCompatibilityVersion(version);
cluster.setMigrateOnError(model.getMigrateOnErrorOption());
cluster.setVirtService(model.getEnableOvirtService().getEntity());
cluster.setGlusterService(model.getEnableGlusterService().getEntity());
cluster.setOptionalReasonRequired(model.getEnableOptionalReason().getEntity());
cluster.setMaintenanceReasonRequired(model.getEnableHostMaintenanceReason().getEntity());
if (model.getClusterPolicy().getSelectedItem() != null) {
ClusterPolicy selectedPolicy = model.getClusterPolicy().getSelectedItem();
cluster.setClusterPolicyId(selectedPolicy.getId());
cluster.setClusterPolicyProperties(KeyValueModel.convertProperties(model.getCustomPropertySheet()
.serialize()));
}
model.startProgress();
Frontend.getInstance().runAction(VdcActionType.AddCluster, new ManagementNetworkOnClusterOperationParameters(cluster),
new IFrontendActionAsyncCallback() {
@Override
public void executed(FrontendActionAsyncResult result) {
DataCenterGuideModel localModel = (DataCenterGuideModel) result.getState();
localModel.postOnAddCluster(result.getReturnValue());
}
}, this);
}
public void postOnAddCluster(VdcReturnValueBase returnValue) {
ClusterModel model = (ClusterModel) getWindow();
model.stopProgress();
if (returnValue != null && returnValue.getSucceeded()) {
cancel();
postAction();
}
}
public void selectHost() {
MoveHost model = new MoveHost();
model.setTitle(ConstantsManager.getInstance().getConstants().selectHostTitle());
model.setHelpTag(HelpTag.select_host);
model.setHashName("select_host"); //$NON-NLS-1$
// In case of local storage, do not show the cluster selection in host select menu as there can be only one cluster in that case
//also only one host is allowed in the cluster so we should disable multi selection
boolean isMultiHostDC = getEntity().isLocal();
if (isMultiHostDC) {
model.getCluster().setIsAvailable(false);
model.setMultiSelection(false);
}
setWindow(model);
AsyncDataProvider.getInstance().getClusterList(new AsyncQuery(new Object[] { this, model },
new INewAsyncCallback() {
@Override
public void onSuccess(Object target, Object returnValue) {
Object[] array = (Object[]) target;
DataCenterGuideModel dataCenterGuideModel = (DataCenterGuideModel) array[0];
MoveHost moveHostModel = (MoveHost) array[1];
ArrayList<Cluster> clusters = (ArrayList<Cluster>) returnValue;
moveHostModel.getCluster().setItems(clusters);
moveHostModel.getCluster().setSelectedItem(Linq.firstOrNull(clusters));
UICommand tempVar = UICommand.createDefaultOkUiCommand("OnSelectHost", dataCenterGuideModel); //$NON-NLS-1$
moveHostModel.getCommands().add(tempVar);
UICommand tempVar2 = UICommand.createCancelUiCommand("Cancel", dataCenterGuideModel); //$NON-NLS-1$
moveHostModel.getCommands().add(tempVar2);
}
}), getEntity().getId());
}
public void onSelectHost() {
MoveHost model = (MoveHost) getWindow();
if (model.getProgress() != null) {
return;
}
if (!model.validate()) {
return;
}
model.setSelectedHosts(new ArrayList<MoveHostData>());
for (EntityModel a : Linq.<EntityModel> cast(model.getItems())) {
if (a.getIsSelected()) {
model.getSelectedHosts().add((MoveHostData) a);
}
}
Cluster cluster = model.getCluster().getSelectedItem();
final List<VdcActionParametersBase> parameterList = new ArrayList<>();
for (MoveHostData hostData : model.getSelectedHosts()) {
VDS host = hostData.getEntity();
// Try to change host's cluster as neccessary.
if (host.getClusterId() != null && !host.getClusterId().equals(cluster.getId())) {
parameterList.add(new ChangeVDSClusterParameters(cluster.getId(), host.getId()));
}
}
model.startProgress();
Frontend.getInstance().runMultipleAction(VdcActionType.ChangeVDSCluster, parameterList,
new IFrontendMultipleActionAsyncCallback() {
@Override
public void executed(FrontendMultipleActionAsyncResult result) {
final DataCenterGuideModel dataCenterGuideModel = (DataCenterGuideModel) result.getState();
List<MoveHostData> hosts =
((MoveHost) dataCenterGuideModel.getWindow()).getSelectedHosts();
List<VdcReturnValueBase> retVals = result.getReturnValue();
final List<VdcActionParametersBase> activateVdsParameterList = new ArrayList<>();
if (retVals != null && hosts.size() == retVals.size()) {
int i = 0;
for (MoveHostData selectedHostData : hosts) {
VDS selectedHost = selectedHostData.getEntity();
if (selectedHost.getStatus() == VDSStatus.PendingApproval && retVals.get(i) != null
&& retVals.get(i).getSucceeded()) {
Frontend.getInstance().runAction(VdcActionType.ApproveVds,
new ApproveVdsParameters(selectedHost.getId()),
null,
this);
} else if (selectedHostData.getActivateHost()) {
activateVdsParameterList.add(new VdsActionParameters(selectedHostData.getEntity().getId()));
}
i++;
}
}
if (activateVdsParameterList.isEmpty()) {
dataCenterGuideModel.getWindow().stopProgress();
dataCenterGuideModel.cancel();
dataCenterGuideModel.postAction();
} else {
final String searchString = getVdsSearchString((MoveHost) dataCenterGuideModel.getWindow());
Timer timer = new Timer() {
public void run() {
checkVdsClusterChangeSucceeded(dataCenterGuideModel, searchString, parameterList, activateVdsParameterList);
}
};
timer.schedule(2000);
}
}
},
this);
}
public void addHost() {
final HostModel model = new NewHostModel();
setWindow(model);
model.setTitle(ConstantsManager.getInstance().getConstants().newHostTitle());
model.setHelpTag(HelpTag.new_host_guide_me);
model.setHashName("new_host_guide_me"); //$NON-NLS-1$
model.getPort().setEntity(54321);
model.getOverrideIpTables().setEntity(true);
model.setSpmPriorityValue(null);
model.getDataCenter().setItems(Collections.singletonList(getEntity()), getEntity());
model.getDataCenter().setIsChangeable(false);
model.getCluster().getSelectedItemChangedEvent().addListener(new IEventListener() {
@Override
public void eventRaised(Event ev, Object sender, EventArgs args) {
ListModel<Cluster> clusterModel = model.getCluster();
if (clusterModel.getSelectedItem() != null) {
Cluster cluster = clusterModel.getSelectedItem();
if (clusterModel.getSelectedItem() != null) {
if (Version.v3_6.compareTo(cluster.getCompatibilityVersion()) <= 0) {
model.getProtocol().setIsAvailable(false);
} else {
model.getProtocol().setIsAvailable(true);
}
}
Boolean jsonSupported =
(Boolean) AsyncDataProvider.getInstance().getConfigValuePreConverted(ConfigurationValues.JsonProtocolSupported,
cluster.getCompatibilityVersion().toString());
if (jsonSupported) {
model.getProtocol().setEntity(true);
} else {
model.getProtocol().setEntity(false);
model.getProtocol().setIsChangeable(false);
}
}
}
});
UICommand tempVar = UICommand.createDefaultOkUiCommand("OnConfirmPMHost", this); //$NON-NLS-1$
tempVar.setTitle(ConstantsManager.getInstance().getConstants().ok());
tempVar.setIsDefault(true);
model.getCommands().add(tempVar);
UICommand tempVar2 = UICommand.createCancelUiCommand("Cancel", this); //$NON-NLS-1$
model.getCommands().add(tempVar2);
}
public void onConfirmPMHost() {
HostModel model = (HostModel) getWindow();
if (!model.validate()) {
return;
}
if (!model.getIsPm().getEntity()) {
ConfirmationModel confirmModel = new ConfirmationModel();
setConfirmWindow(confirmModel);
confirmModel.setTitle(ConstantsManager.getInstance().getConstants().powerManagementConfigurationTitle());
confirmModel.setHelpTag(HelpTag.power_management_configuration);
confirmModel.setHashName("power_management_configuration"); //$NON-NLS-1$
confirmModel.setMessage(ConstantsManager.getInstance().getConstants().youHavntConfigPmMsg());
UICommand tempVar = UICommand.createDefaultOkUiCommand("OnAddHost", this); //$NON-NLS-1$
confirmModel.getCommands().add(tempVar);
UICommand tempVar2 = UICommand.createCancelUiCommand("CancelConfirmWithFocus", this); //$NON-NLS-1$
confirmModel.getCommands().add(tempVar2);
}
else {
onAddHost();
}
}
public void onAddHost() {
cancelConfirm();
HostModel model = (HostModel) getWindow();
if (model.getProgress() != null) {
return;
}
// Save changes.
VDS host = new VDS();
host.setVdsName(model.getName().getEntity());
host.setHostName(model.getHost().getEntity());
host.setPort(model.getPort().getEntity());
host.setProtocol(VdsProtocol.fromValue(model.getProtocol().getEntity() ? VdsProtocol.STOMP.toString() : VdsProtocol.XML.toString()));
host.setSshPort(model.getAuthSshPort().getEntity());
host.setSshUsername(model.getUserName().getEntity());
host.setSshKeyFingerprint(model.getFetchSshFingerprint().getEntity());
host.setClusterId(model.getCluster().getSelectedItem().getId());
host.setVdsSpmPriority(model.getSpmPriorityValue());
// Save other PM parameters.
host.setPmEnabled(model.getIsPm().getEntity());
host.setDisablePowerManagementPolicy(model.getDisableAutomaticPowerManagement().getEntity());
host.setPmKdumpDetection(model.getPmKdumpDetection().getEntity());
AddVdsActionParameters addVdsParams = new AddVdsActionParameters();
addVdsParams.setVdsId(host.getId());
addVdsParams.setvds(host);
if (model.getUserPassword().getEntity() != null) {
addVdsParams.setPassword(model.getUserPassword().getEntity());
}
addVdsParams.setOverrideFirewall(model.getOverrideIpTables().getEntity());
addVdsParams.setFenceAgents(model.getFenceAgentListModel().getFenceAgents());
model.startProgress();
Frontend.getInstance().runAction(VdcActionType.AddVds, addVdsParams,
new IFrontendActionAsyncCallback() {
@Override
public void executed(FrontendActionAsyncResult result) {
DataCenterGuideModel localModel = (DataCenterGuideModel) result.getState();
localModel.postOnAddHost(result.getReturnValue());
}
}, this);
}
public void postOnAddHost(VdcReturnValueBase returnValue) {
HostModel model = (HostModel) getWindow();
model.stopProgress();
if (returnValue != null && returnValue.getSucceeded()) {
cancel();
postAction();
}
}
@Override
protected void postAction() {
resetData();
updateOptions();
}
@Override
protected void cancel() {
resetData();
setWindow(null);
}
public void cancelConfirm() {
setConfirmWindow(null);
}
public void cancelConfirmWithFocus() {
setConfirmWindow(null);
HostModel hostModel = (HostModel) getWindow();
hostModel.setIsPowerManagementTabSelected(true);
}
@Override
public void executeCommand(UICommand command) {
super.executeCommand(command);
if ("AddCluster".equals(command.getName())) { //$NON-NLS-1$
addCluster();
}
if ("AddHost".equals(command.getName())) { //$NON-NLS-1$
addHost();
}
if ("SelectHost".equals(command.getName())) { //$NON-NLS-1$
selectHost();
}
if ("AddDataStorage".equals(command.getName())) { //$NON-NLS-1$
addDataStorage();
}
if ("AttachDataStorage".equals(command.getName())) { //$NON-NLS-1$
attachDataStorage();
}
if ("AddIsoStorage".equals(command.getName())) { //$NON-NLS-1$
addIsoStorage();
}
if ("AttachIsoStorage".equals(command.getName())) { //$NON-NLS-1$
attachIsoStorage();
}
if ("OnAddCluster".equals(command.getName())) { //$NON-NLS-1$
onAddCluster();
}
if ("OnSelectHost".equals(command.getName())) { //$NON-NLS-1$
onSelectHost();
}
if ("OnAddHost".equals(command.getName())) { //$NON-NLS-1$
onAddHost();
}
if ("OnAddStorage".equals(command.getName())) { //$NON-NLS-1$
onAddStorage();
}
if ("OnSaveSanStorage".equals(command.getName())) { //$NON-NLS-1$
onSaveSanStorage();
}
if ("OnAttachStorage".equals(command.getName())) { //$NON-NLS-1$
onAttachStorage();
}
if ("AddLocalStorage".equals(command.getName())) { //$NON-NLS-1$
addLocalStorage();
}
if ("OnConfirmPMHost".equals(command.getName())) { //$NON-NLS-1$
onConfirmPMHost();
}
if ("CancelConfirm".equals(command.getName())) { //$NON-NLS-1$
cancelConfirm();
}
if ("CancelConfirmWithFocus".equals(command.getName())) { //$NON-NLS-1$
cancelConfirmWithFocus();
}
if ("Cancel".equals(command.getName())) { //$NON-NLS-1$
cancel();
}
}
@Override
public void run(TaskContext context) {
ArrayList<Object> data = (ArrayList<Object>) context.getState();
String key = (String) data.get(0);
if ("SaveNfs".equals(key)) { //$NON-NLS-1$
saveNfsStorage(context);
}
else if ("SaveLocal".equals(key)) { //$NON-NLS-1$
saveLocalStorage(context);
}
else if ("SaveSan".equals(key)) { //$NON-NLS-1$
saveSanStorage(context);
}
else if ("Finish".equals(key)) { //$NON-NLS-1$
getWindow().stopProgress();
if ((Boolean) data.get(1)) {
cancel();
postAction();
}
else {
((Model) data.get(2)).setMessage((String) data.get(3));
}
}
}
}
|
package org.innovateuk.ifs.assessment.controller;
import org.innovateuk.ifs.assessment.resource.AssessorCompetitionSummaryResource;
import org.innovateuk.ifs.assessment.transactional.AssessorCompetitionSummaryService;
import org.innovateuk.ifs.commons.rest.RestResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* Exposes endpoints for retrieving assessor summaries for competitions.
*/
@RestController
@RequestMapping("/assessor/{assessorId}/competition/{competitionId}")
public class AssessorCompetitionSummaryController {
@Autowired
private AssessorCompetitionSummaryService assessorCompetitionSummaryService;
@GetMapping("/summary")
public RestResult<AssessorCompetitionSummaryResource> getAssessorSummary(@PathVariable("assessorId") long assessorId,
@PathVariable("competitionId") long competitionId) {
return assessorCompetitionSummaryService.getAssessorSummary(assessorId, competitionId).toGetResponse();
}
}
|
package org.innovateuk.ifs.competitionsetup.transactional;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.innovateuk.ifs.commons.service.ServiceResult;
import org.innovateuk.ifs.competition.domain.Competition;
import org.innovateuk.ifs.competition.domain.GrantTermsAndConditions;
import org.innovateuk.ifs.competition.domain.InnovationLead;
import org.innovateuk.ifs.competition.mapper.CompetitionMapper;
import org.innovateuk.ifs.competition.mapper.GrantTermsAndConditionsMapper;
import org.innovateuk.ifs.competition.repository.*;
import org.innovateuk.ifs.competition.resource.CompetitionResource;
import org.innovateuk.ifs.competition.resource.CompetitionSetupSection;
import org.innovateuk.ifs.competition.resource.CompetitionSetupSubsection;
import org.innovateuk.ifs.competition.transactional.CompetitionFunderService;
import org.innovateuk.ifs.competitionsetup.domain.CompetitionDocument;
import org.innovateuk.ifs.file.controller.FileControllerUtils;
import org.innovateuk.ifs.file.domain.FileEntry;
import org.innovateuk.ifs.file.domain.FileType;
import org.innovateuk.ifs.file.mapper.FileEntryMapper;
import org.innovateuk.ifs.file.repository.FileTypeRepository;
import org.innovateuk.ifs.file.resource.FileEntryResource;
import org.innovateuk.ifs.file.service.FilesizeAndTypeFileValidator;
import org.innovateuk.ifs.file.transactional.FileEntryService;
import org.innovateuk.ifs.file.transactional.FileService;
import org.innovateuk.ifs.publiccontent.repository.PublicContentRepository;
import org.innovateuk.ifs.publiccontent.transactional.PublicContentService;
import org.innovateuk.ifs.setup.repository.SetupStatusRepository;
import org.innovateuk.ifs.setup.resource.SetupStatusResource;
import org.innovateuk.ifs.setup.transactional.SetupStatusService;
import org.innovateuk.ifs.transactional.BaseTransactionalService;
import org.innovateuk.ifs.user.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;
import static java.util.Collections.singletonList;
import static org.innovateuk.ifs.commons.error.CommonErrors.notFoundError;
import static org.innovateuk.ifs.commons.service.ServiceResult.aggregate;
import static org.innovateuk.ifs.commons.service.ServiceResult.serviceSuccess;
import static org.innovateuk.ifs.competition.resource.CompetitionDocumentResource.COLLABORATION_AGREEMENT_TITLE;
import static org.innovateuk.ifs.util.CollectionFunctions.combineLists;
import static org.innovateuk.ifs.util.CollectionFunctions.simpleMap;
import static org.innovateuk.ifs.util.EntityLookupCallbacks.find;
import static org.springframework.util.ReflectionUtils.*;
/**
* Service for operations around the usage and processing of Competitions
*/
@Service
public class CompetitionSetupServiceImpl extends BaseTransactionalService implements CompetitionSetupService {
private static final Log LOG = LogFactory.getLog(CompetitionSetupServiceImpl.class);
@Autowired
private CompetitionMapper competitionMapper;
@Autowired
private CompetitionTypeRepository competitionTypeRepository;
@Autowired
private InnovationLeadRepository innovationLeadRepository;
@Autowired
private StakeholderRepository stakeholderRepository;
@Autowired
private CompetitionFunderService competitionFunderService;
@Autowired
private PublicContentService publicContentService;
@Autowired
private CompetitionSetupTemplateService competitionSetupTemplateService;
@Autowired
private SetupStatusService setupStatusService;
@Autowired
private SetupStatusRepository setupStatusRepository;
@Autowired
private GrantTermsAndConditionsRepository grantTermsAndConditionsRepository;
@Autowired
private GrantTermsAndConditionsMapper termsAndConditionsMapper;
@Autowired
private PublicContentRepository publicContentRepository;
@Autowired
private MilestoneRepository milestoneRepository;
@Value("${ifs.data.service.file.storage.competition.terms.max.filesize.bytes}")
private Long maxFileSize;
@Value("${ifs.data.service.file.storage.competition.terms.valid.media.types}")
private List<String> validMediaTypes;
@Autowired
private FileService fileService;
@Autowired
private FileEntryService fileEntryService;
@Autowired
@Qualifier("mediaTypeStringsFileValidator")
private FilesizeAndTypeFileValidator<List<String>> fileValidator;
@Autowired
private FileTypeRepository fileTypeRepository;
@Autowired
private FileEntryMapper fileEntryMapper;
private FileControllerUtils fileControllerUtils = new FileControllerUtils();
public static final BigDecimal DEFAULT_ASSESSOR_PAY = new BigDecimal(100);
@Override
@Transactional
public ServiceResult<String> generateCompetitionCode(Long id, ZonedDateTime dateTime) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("YYMM");
Competition competition = competitionRepository.findById(id).get();
String datePart = formatter.format(dateTime);
List<Competition> openingSameMonth = competitionRepository.findByCodeLike("%" + datePart + "%");
String unusedCode = "";
if (StringUtils.hasText(competition.getCode())) {
return serviceSuccess(competition.getCode());
} else if (openingSameMonth.isEmpty()) {
unusedCode = datePart + "-1";
} else {
List<String> codes = openingSameMonth.stream().map(Competition::getCode).sorted().peek(c -> LOG.info("Codes : " + c)).collect(Collectors.toList());
for (int i = 1; i < 10000; i++) {
unusedCode = datePart + "-" + i;
if (!codes.contains(unusedCode)) {
break;
}
}
}
competition.setCode(unusedCode);
competitionRepository.save(competition);
return serviceSuccess(unusedCode);
}
@Override
@Transactional
public ServiceResult<CompetitionResource> save(Long id, CompetitionResource competitionResource) {
Competition existingCompetition = competitionRepository.findById(competitionResource.getId()).orElse(null);
Competition competition = competitionMapper.mapToDomain(competitionResource);
competition = setCompetitionAuditableFields(competition, existingCompetition);
saveFunders(competitionResource);
competition = competitionRepository.save(competition);
return serviceSuccess(competitionMapper.mapToResource(competition));
}
private void saveFunders(CompetitionResource competitionResource) {
competitionFunderService.reinsertFunders(competitionResource);
}
@Override
@Transactional
public ServiceResult<Void> updateCompetitionInitialDetails(final Long competitionId, final CompetitionResource
competitionResource, final Long existingInnovationLeadId) {
return deleteExistingInnovationLead(competitionId, existingInnovationLeadId)
.andOnSuccess(() -> save(competitionId, competitionResource))
.andOnSuccess(this::saveInnovationLead);
}
private ServiceResult<Void> deleteExistingInnovationLead(Long competitionId, Long existingInnovationLeadId) {
if (existingInnovationLeadId != null) {
innovationLeadRepository.deleteInnovationLead(competitionId, existingInnovationLeadId);
}
return serviceSuccess();
}
private ServiceResult<Void> saveInnovationLead(CompetitionResource competitionResource) {
if (competitionResource.getLeadTechnologist() != null) {
Competition competition = competitionMapper.mapToDomain(competitionResource);
if (!doesInnovationLeadAlreadyExist(competition)) {
User innovationLead = competition.getLeadTechnologist();
innovationLeadRepository.save(new InnovationLead(competition, innovationLead));
}
}
return serviceSuccess();
}
private boolean doesInnovationLeadAlreadyExist(Competition competition) {
return innovationLeadRepository.existsInnovationLead(competition.getId(), competition.getLeadTechnologist().getId());
}
@Override
@Transactional
public ServiceResult<CompetitionResource> create() {
Competition competition = new Competition();
competition.setSetupComplete(false);
return persistNewCompetition(competition);
}
@Override
@Transactional
public ServiceResult<CompetitionResource> createNonIfs() {
Competition competition = new Competition();
competition.setNonIfs(true);
return persistNewCompetition(competition);
}
@Override
public ServiceResult<Map<CompetitionSetupSection, Optional<Boolean>>> getSectionStatuses(Long competitionId) {
List<SetupStatusResource> setupStatuses = setupStatusService
.findByTargetClassNameAndTargetId(Competition.class.getName(), competitionId).getSuccess();
return serviceSuccess(Arrays.stream(CompetitionSetupSection.values())
.collect(Collectors.toMap(section -> section, section -> findStatus(setupStatuses, section.getClass().getName(), section.getId()))));
}
@Override
public ServiceResult<Map<CompetitionSetupSubsection, Optional<Boolean>>> getSubsectionStatuses(Long competitionId) {
List<SetupStatusResource> setupStatuses = setupStatusService
.findByTargetClassNameAndTargetId(Competition.class.getName(), competitionId).getSuccess();
return serviceSuccess(Arrays.stream(CompetitionSetupSubsection.values())
.collect(Collectors.toMap(subsection -> subsection, subsection -> findStatus(setupStatuses, subsection.getClass().getName(), subsection.getId()))));
}
private Optional<Boolean> findStatus(List<SetupStatusResource> setupStatuses, String className, Long classPk) {
return setupStatuses.stream()
.filter(setupStatusResource ->
setupStatusResource.getClassName().equals(className) &&
setupStatusResource.getClassPk().equals(classPk))
.map(SetupStatusResource::getCompleted)
.findAny();
}
@Override
@Transactional
public ServiceResult<SetupStatusResource> markSectionComplete(Long competitionId, CompetitionSetupSection section) {
SetupStatusResource setupStatus = findOrCreateSetupStatusResource(competitionId, section.getClass().getName(), section.getId(), Optional.empty());
setupStatus.setCompleted(true);
return setupStatusService.saveSetupStatus(setupStatus);
}
@Override
@Transactional
public ServiceResult<List<SetupStatusResource>> markSectionIncomplete(long competitionId, CompetitionSetupSection section) {
List<CompetitionSetupSection> allSectionsToMarkIncomplete = getAllSectionsToMarkIncomplete(section);
List<ServiceResult<SetupStatusResource>> markIncompleteResults = simpleMap(allSectionsToMarkIncomplete,
sectionToMarkIncomplete -> setSectionIncompleteAndUpdate(competitionId, sectionToMarkIncomplete));
return aggregate(markIncompleteResults);
}
/**
* When marking a section as incomplete, mark any next sections as incomplete also as they will need revisiting
* based on changes to this section.
*/
private List<CompetitionSetupSection> getAllSectionsToMarkIncomplete(CompetitionSetupSection section) {
return combineLists(section, section.getAllNextSections());
}
private ServiceResult<SetupStatusResource> setSectionIncompleteAndUpdate(Long competitionId, CompetitionSetupSection section) {
SetupStatusResource setupStatus = findOrCreateSetupStatusResource(competitionId, section.getClass().getName(), section.getId(), Optional.empty());
setupStatus.setCompleted(false);
return setupStatusService.saveSetupStatus(setupStatus);
}
@Override
@Transactional
public ServiceResult<SetupStatusResource> markSubsectionComplete(Long competitionId, CompetitionSetupSection parentSection, CompetitionSetupSubsection subsection) {
SetupStatusResource setupStatus = findOrCreateSetupStatusResource(competitionId, subsection.getClass().getName(), subsection.getId(), Optional.of(parentSection));
setupStatus.setCompleted(true);
return setupStatusService.saveSetupStatus(setupStatus);
}
@Override
@Transactional
public ServiceResult<SetupStatusResource> markSubsectionIncomplete(Long competitionId, CompetitionSetupSection parentSection, CompetitionSetupSubsection subsection) {
SetupStatusResource setupStatus = findOrCreateSetupStatusResource(competitionId, subsection.getClass().getName(), subsection.getId(), Optional.of(parentSection));
setupStatus.setCompleted(false);
return setupStatusService.saveSetupStatus(setupStatus);
}
private SetupStatusResource findOrCreateSetupStatusResource(Long competitionId, String sectionClassName, Long sectionId, Optional<CompetitionSetupSection> parentSection) {
Optional<SetupStatusResource> setupStatusOpt = setupStatusService.findSetupStatusAndTarget(sectionClassName, sectionId, Competition.class.getName(), competitionId)
.getOptionalSuccessObject();
return setupStatusOpt.orElseGet(() -> createNewSetupStatus(competitionId, sectionClassName, sectionId, parentSection));
}
private SetupStatusResource createNewSetupStatus(Long competitionId, String sectionClassName, Long sectionId, Optional<CompetitionSetupSection> parentSectionOpt) {
SetupStatusResource newSetupStatusResource = new SetupStatusResource(sectionClassName, sectionId, Competition.class.getName(), competitionId);
parentSectionOpt.ifPresent(parentSection -> {
Optional<SetupStatusResource> parentSetupStatusOpt =
setupStatusService.findSetupStatusAndTarget(parentSection.getClass().getName(), parentSection.getId(), Competition.class.getName(), competitionId)
.getOptionalSuccessObject();
long parentStatus = parentSetupStatusOpt.orElseGet(() ->
markSectionIncomplete(competitionId, parentSection).getSuccess().get(0)).getId();
newSetupStatusResource.setParentId(
parentStatus
);
});
return newSetupStatusResource;
}
@Override
@Transactional
public ServiceResult<Void> returnToSetup(Long competitionId) {
Competition competition = competitionRepository.findById(competitionId).get();
competition.setSetupComplete(false);
return serviceSuccess();
}
@Override
@Transactional
public ServiceResult<Void> markAsSetup(Long competitionId) {
Competition competition = competitionRepository.findById(competitionId).get();
competition.setSetupComplete(true);
return serviceSuccess();
}
@Override
@Transactional
public ServiceResult<Void> copyFromCompetitionTypeTemplate(Long competitionId, Long competitionTypeId) {
return competitionSetupTemplateService.initializeCompetitionByCompetitionTemplate(competitionId, competitionTypeId)
.andOnSuccessReturnVoid();
}
@Override
@Transactional
public ServiceResult<Void> deleteCompetition(long competitionId) {
return getCompetition(competitionId).andOnSuccess(competition ->
deletePublicContentForCompetition(competition).andOnSuccess(() -> {
deleteFormValidatorsForCompetitionQuestions(competition);
deleteMilestonesForCompetition(competition);
deleteInnovationLead(competition);
deleteAllStakeholders(competition);
deleteSetupStatus(competition);
competitionRepository.delete(competition);
return serviceSuccess();
}));
}
@Override
@Transactional
public ServiceResult<FileEntryResource> uploadCompetitionTerms(String contentType, String contentLength, String originalFilename, long competitionId, HttpServletRequest request) {
return findCompetition(competitionId)
.andOnSuccess(competition -> fileControllerUtils.handleFileUpload(contentType, contentLength, originalFilename, fileValidator, validMediaTypes, maxFileSize, request,
(fileAttributes, inputStreamSupplier) -> fileService.createFile(fileAttributes.toFileEntryResource(), inputStreamSupplier)
.andOnSuccessReturn(created -> {
competition.setCompetitionTerms(created.getValue());
return fileEntryMapper.mapToResource(created.getValue());
})
)
.toServiceResult()
);
}
@Override
@Transactional
public ServiceResult<Void> deleteCompetitionTerms(long competitionId) {
return findCompetition(competitionId)
.andOnSuccess(competition -> find(competition.getCompetitionTerms(), notFoundError(FileEntry.class))
.andOnSuccess(competitionTerms -> fileService.deleteFileIgnoreNotFound(competitionTerms.getId()))
.andOnSuccessReturnVoid(() -> competition.setCompetitionTerms(null)));
}
private ServiceResult<Competition> findCompetition(long competitionId) {
return find(competitionRepository.findById(competitionId), notFoundError(Competition.class, competitionId));
}
private void deleteSetupStatus(Competition competition) {
setupStatusRepository.deleteByTargetClassNameAndTargetId(Competition.class.getName(), competition.getId());
}
private void deleteMilestonesForCompetition(Competition competition) {
competition.getMilestones().clear();
milestoneRepository.deleteByCompetitionId(competition.getId());
}
private void deleteInnovationLead(Competition competition) {
innovationLeadRepository.deleteAllInnovationLeads(competition.getId());
}
private void deleteAllStakeholders(Competition competition) {
stakeholderRepository.deleteAllStakeholders(competition.getId());
}
private ServiceResult<Void> deletePublicContentForCompetition(Competition competition) {
return find(publicContentRepository.findByCompetitionId(competition.getId()), notFoundError(Competition.class,
competition.getId())).andOnSuccess(publicContent -> {
publicContentRepository.delete(publicContent);
return serviceSuccess();
});
}
private void deleteFormValidatorsForCompetitionQuestions(Competition competition) {
competition.getSections().forEach(section ->
section.getQuestions().forEach(question ->
question.getFormInputs().forEach(formInput ->
formInput.getFormValidators().clear())));
competitionRepository.save(competition);
}
private ServiceResult<CompetitionResource> persistNewCompetition(Competition competition) {
GrantTermsAndConditions defaultTermsAndConditions = grantTermsAndConditionsRepository.findOneByTemplate
(GrantTermsAndConditionsRepository.DEFAULT_TEMPLATE_NAME);
competition.setTermsAndConditions(defaultTermsAndConditions);
competition.setCompetitionDocuments(createDefaultProjectDocuments(competition));
Competition savedCompetition = competitionRepository.save(competition);
return publicContentService.initialiseByCompetitionId(savedCompetition.getId())
.andOnSuccessReturn(() -> competitionMapper.mapToResource(savedCompetition));
}
private List<CompetitionDocument> createDefaultProjectDocuments(Competition competition) {
FileType pdfFileType = fileTypeRepository.findByName("PDF");
List<CompetitionDocument> defaultCompetitionDocuments = new ArrayList<>();
defaultCompetitionDocuments.add(createCollaborationAgreement(competition, singletonList(pdfFileType)));
defaultCompetitionDocuments.add(createExploitationPlan(competition, singletonList(pdfFileType)));
return defaultCompetitionDocuments;
}
private CompetitionDocument createCollaborationAgreement(Competition competition, List<FileType> fileTypes) {
return new CompetitionDocument(competition, COLLABORATION_AGREEMENT_TITLE, "<p>The collaboration agreement covers how the consortium will work together on the project and exploit its results. It must be signed by all partners.</p>\n" +
"\n" +
"<p>Please allow enough time to complete this document before your project start date.</p>\n" +
"\n" +
"<p>Guidance on completing a collaboration agreement can be found on the <a target=\"_blank\" href=\"http:
"\n" +
"<p>Your collaboration agreement must be:</p>\n" +
"<ul class=\"list-bullet\"><li>in portable document format (PDF)</li>\n" +
"<li>legible at 100% magnification</li>\n" +
"<li>less than 10MB in file size</li></ul>",
false, true, fileTypes);
}
private CompetitionDocument createExploitationPlan(Competition competition, List<FileType> fileTypes) {
return new CompetitionDocument(competition, "Exploitation plan", "<p>This is a confirmation of your overall plan, setting out the business case for your project. This plan will change during the lifetime of the project.</p>\n" +
"\n" +
"<p>It should also describe partner activities that will exploit the results of the project so that:</p>\n" +
"<ul class=\"list-bullet\"><li>changes in the commercial environment can be monitored and accounted for</li>\n" +
"<li>adequate resources are committed to exploitation</li>\n" +
"<li>exploitation can be monitored by the stakeholders</li></ul>\n" +
"\n" +
"<p>You can download an <a href=\"/files/exploitation_plan.doc\" class=\"govuk-link\">exploitation plan template</a>.</p>\n" +
"\n" +
"<p>The uploaded exploitation plan must be:</p>\n" +
"<ul class=\"list-bullet\"><li>in portable document format (PDF)</li>\n" +
"<li>legible at 100% magnification</li>\n" +
"<li>less than 10MB in file size</li></ul>",
false, true, fileTypes);
}
private Competition setCompetitionAuditableFields(Competition competition, Competition existingCompetition) {
Field createdBy = findField(Competition.class, "createdBy");
Field createdOn = findField(Competition.class, "createdOn");
makeAccessible(createdBy);
makeAccessible(createdOn);
setField(createdBy, competition, existingCompetition.getCreatedBy());
setField(createdOn, competition, existingCompetition.getCreatedOn());
return competition;
}
}
|
package org.eclipse.che.workspace.infrastructure.kubernetes.namespace.pvc;
import static java.util.Collections.singletonMap;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.eclipse.che.workspace.infrastructure.kubernetes.namespace.KubernetesObjectUtil.newVolume;
import static org.eclipse.che.workspace.infrastructure.kubernetes.namespace.KubernetesObjectUtil.newVolumeMount;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Predicate;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import io.fabric8.kubernetes.api.model.Container;
import io.fabric8.kubernetes.api.model.ContainerBuilder;
import io.fabric8.kubernetes.api.model.Pod;
import io.fabric8.kubernetes.api.model.PodBuilder;
import io.fabric8.kubernetes.api.model.PodStatus;
import io.fabric8.kubernetes.api.model.Quantity;
import java.util.Arrays;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Stream;
import javax.annotation.PreDestroy;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import org.eclipse.che.api.workspace.server.spi.InfrastructureException;
import org.eclipse.che.commons.lang.concurrent.LoggingUncaughtExceptionHandler;
import org.eclipse.che.commons.lang.concurrent.ThreadLocalPropagateContext;
import org.eclipse.che.workspace.infrastructure.kubernetes.namespace.KubernetesDeployments;
import org.eclipse.che.workspace.infrastructure.kubernetes.namespace.KubernetesNamespaceFactory;
import org.eclipse.che.workspace.infrastructure.kubernetes.provision.SecurityContextProvisioner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Helps to execute commands needed for workspace PVC preparation and cleanup.
*
* <p>Creates a short-lived Pod based on CentOS image which mounts a specified PVC and executes a
* command (either {@code mkdir -p <path>} or {@code rm -rf <path>}). Reports back whether the pod
* succeeded or failed. Supports multiple paths for one command.
*
* <p>Note that the commands execution is needed only for {@link CommonPVCStrategy}.
*
* @author amisevsk
* @author Anton Korneta
*/
@Singleton
public class PVCSubPathHelper {
private static final Logger LOG = LoggerFactory.getLogger(PVCSubPathHelper.class);
private static final JobFinishedPredicate POD_PREDICATE = new JobFinishedPredicate();
static final int COUNT_THREADS = 4;
static final int WAIT_POD_TIMEOUT_MIN = 5;
static final String[] RM_COMMAND_BASE = new String[] {"rm", "-rf"};
static final String[] MKDIR_COMMAND_BASE = new String[] {"mkdir", "-p"};
static final String IMAGE_PULL_POLICY = "IfNotPresent";
static final String POD_RESTART_POLICY = "Never";
static final String POD_PHASE_SUCCEEDED = "Succeeded";
static final String POD_PHASE_FAILED = "Failed";
static final String JOB_MOUNT_PATH = "/tmp/job_mount";
private final String pvcName;
private final String jobImage;
private final String jobMemoryLimit;
private final KubernetesNamespaceFactory factory;
private final ExecutorService executor;
private final SecurityContextProvisioner securityContextProvisioner;
@Inject
PVCSubPathHelper(
@Named("che.infra.kubernetes.pvc.name") String pvcName,
@Named("che.infra.kubernetes.pvc.jobs.memorylimit") String jobMemoryLimit,
@Named("che.infra.kubernetes.pvc.jobs.image") String jobImage,
KubernetesNamespaceFactory factory,
SecurityContextProvisioner securityContextProvisioner) {
this.pvcName = pvcName;
this.jobMemoryLimit = jobMemoryLimit;
this.jobImage = jobImage;
this.factory = factory;
this.securityContextProvisioner = securityContextProvisioner;
this.executor =
Executors.newFixedThreadPool(
COUNT_THREADS,
new ThreadFactoryBuilder()
.setNameFormat("PVCSubPathHelper-ThreadPool-%d")
.setUncaughtExceptionHandler(LoggingUncaughtExceptionHandler.getInstance())
.setDaemon(false)
.build());
}
/**
* Performs create workspace directories job by given paths and waits until it finished.
*
* @param workspaceId workspace identifier
* @param dirs workspace directories to create
*/
void createDirs(String workspaceId, String... dirs) {
execute(workspaceId, MKDIR_COMMAND_BASE, dirs);
}
/**
* Asynchronously starts a job for removing workspace directories by given paths.
*
* @param workspaceId workspace identifier
* @param dirs workspace directories to remove
*/
CompletableFuture<Void> removeDirsAsync(String workspaceId, String... dirs) {
return CompletableFuture.runAsync(
ThreadLocalPropagateContext.wrap(() -> execute(workspaceId, RM_COMMAND_BASE, dirs)),
executor);
}
/**
* Executes the job with the specified arguments.
*
* @param commandBase the command base to execute
* @param arguments the list of arguments for the specified job
*/
@VisibleForTesting
void execute(String workspaceId, String[] commandBase, String... arguments) {
final String jobName = commandBase[0];
final String podName = jobName + '-' + workspaceId;
final String[] command = buildCommand(commandBase, arguments);
final Pod pod = newPod(podName, command);
securityContextProvisioner.provision(pod);
KubernetesDeployments deployments = null;
try {
deployments = factory.create(workspaceId).deployments();
deployments.create(pod);
final Pod finished = deployments.wait(podName, WAIT_POD_TIMEOUT_MIN, POD_PREDICATE::apply);
PodStatus finishedStatus = finished.getStatus();
if (POD_PHASE_FAILED.equals(finishedStatus.getPhase())) {
LOG.error(
"Job command '{}' execution is failed. Status '{}'.",
Arrays.toString(command),
finishedStatus);
}
} catch (InfrastructureException ex) {
LOG.error(
"Unable to perform '{}' command for the workspace '{}' cause: '{}'",
Arrays.toString(command),
workspaceId,
ex.getMessage());
} finally {
if (deployments != null) {
try {
deployments.delete(podName);
} catch (InfrastructureException ignored) {
}
}
}
}
/**
* Builds the command by given base and paths.
*
* <p>Command is consists of base(e.g. rm -rf) and list of directories which are modified with
* mount path.
*
* @param base command base
* @param dirs the paths which are used as arguments for the command base
* @return complete command with given arguments
*/
@VisibleForTesting
String[] buildCommand(String[] base, String... dirs) {
return Stream.concat(
Arrays.stream(base),
Arrays.stream(dirs)
.map(dir -> JOB_MOUNT_PATH + (dir.startsWith("/") ? dir : '/' + dir)))
.toArray(String[]::new);
}
@PreDestroy
void shutdown() {
if (!executor.isShutdown()) {
executor.shutdown();
try {
if (!executor.awaitTermination(30, SECONDS)) {
executor.shutdownNow();
if (!executor.awaitTermination(60, SECONDS))
LOG.error("Couldn't shutdown PVCSubPathHelper thread pool");
}
} catch (InterruptedException ignored) {
executor.shutdownNow();
Thread.currentThread().interrupt();
}
LOG.info("PVCSubPathHelper thread pool is terminated");
}
}
/** Returns new instance of {@link Pod} with given name and command. */
private Pod newPod(String podName, String[] command) {
final Container container =
new ContainerBuilder()
.withName(podName)
.withImage(jobImage)
.withImagePullPolicy(IMAGE_PULL_POLICY)
.withCommand(command)
.withVolumeMounts(newVolumeMount(pvcName, JOB_MOUNT_PATH, null))
.withNewResources()
.withLimits(singletonMap("memory", new Quantity(jobMemoryLimit)))
.endResources()
.build();
return new PodBuilder()
.withNewMetadata()
.withName(podName)
.endMetadata()
.withNewSpec()
.withContainers(container)
.withVolumes(newVolume(pvcName, pvcName))
.withRestartPolicy(POD_RESTART_POLICY)
.endSpec()
.build();
}
/** Checks whether pod is Failed or Successfully finished command execution */
static class JobFinishedPredicate implements Predicate<Pod> {
@Override
public boolean apply(Pod pod) {
if (pod.getStatus() == null) {
return false;
}
switch (pod.getStatus().getPhase()) {
case POD_PHASE_FAILED:
// fall through
case POD_PHASE_SUCCEEDED:
// job is finished.
return true;
default:
// job is not finished.
return false;
}
}
}
}
|
package org.safehaus.subutai.core.agent.impl;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Queue;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.safehaus.subutai.common.enums.RequestType;
import org.safehaus.subutai.common.protocol.Agent;
import org.safehaus.subutai.common.protocol.Request;
import org.safehaus.subutai.common.protocol.Response;
import org.safehaus.subutai.common.protocol.ResponseListener;
import org.safehaus.subutai.common.settings.Common;
import org.safehaus.subutai.common.util.CollectionUtil;
import org.safehaus.subutai.common.util.UUIDUtil;
import org.safehaus.subutai.core.agent.api.AgentListener;
import org.safehaus.subutai.core.agent.api.AgentManager;
import org.safehaus.subutai.core.communication.api.CommunicationManager;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
/**
* Implementation of Agent Manager Interface
*/
public class AgentManagerImpl implements ResponseListener, AgentManager {
private static final Logger LOG = Logger.getLogger( AgentManagerImpl.class.getName() );
/**
* list of agent listeners
*/
private final Queue<AgentListener> listeners = new ConcurrentLinkedQueue<>();
/**
* reference to communication manager
*/
private final CommunicationManager communicationService;
/**
* executor for notifying agent listeners
*/
private ExecutorService exec;
/**
* cache of currently connected agents with expiry ttl. Agents will expire unless they send heartbeat message
* regularly
*/
private Cache<UUID, Agent> agents;
private volatile boolean notifyAgentListeners = true;
public AgentManagerImpl( final CommunicationManager communicationService )
{
Preconditions.checkNotNull( communicationService, "Communication Manager is null" );
this.communicationService = communicationService;
}
public Collection<AgentListener> getListeners()
{
return Collections.unmodifiableCollection( listeners );
}
/**
* Returns all agents currently connected to the mgmt server.
*
* @return set of all agents connected to the mgmt server.
*/
public Set<Agent> getAgents()
{
return new HashSet( agents.asMap().values() );
}
/**
* Returns all physical agents currently connected to the mgmt server.
*
* @return set of all physical agents currently connected to the mgmt server.
*/
public Set<Agent> getPhysicalAgents()
{
Set<Agent> physicalAgents = new HashSet<>();
for ( Agent agent : agents.asMap().values() )
{
if ( !agent.isLXC() )
{
physicalAgents.add( agent );
}
}
return physicalAgents;
}
/**
* Returns all lxc agents currently connected to the mgmt server.
*
* @return set of all lxc agents currently connected to the mgmt server.
*/
public Set<Agent> getLxcAgents()
{
Set<Agent> lxcAgents = new HashSet<>();
for ( Agent agent : agents.asMap().values() )
{
if ( agent.isLXC() )
{
lxcAgents.add( agent );
}
}
return lxcAgents;
}
/**
* Returns agent by its node's hostname or null if agent is not connected
*
* @param hostname - hostname of agent's node
*
* @return agent
*/
public Agent getAgentByHostname( String hostname )
{
if ( !Strings.isNullOrEmpty( hostname ) )
{
for ( Agent agent : agents.asMap().values() )
{
if ( hostname.equalsIgnoreCase( agent.getHostname() ) )
{
return agent;
}
}
}
return null;
}
/**
* Returns agent by its UUID or null if agent is not connected
*
* @param uuid - UUID of agent
*
* @return agent
*/
public Agent getAgentByUUID( UUID uuid )
{
return agents.getIfPresent( uuid );
}
/**
* Returns agent by its physical parent node's hostname or null if agent is not connected
*
* @param parentHostname - hostname of agent's node physical parent node
*
* @return agent
*/
public Set<Agent> getLxcAgentsByParentHostname( String parentHostname )
{
Set<Agent> lxcAgents = new HashSet<>();
if ( !Strings.isNullOrEmpty( parentHostname ) )
{
for ( Agent agent : agents.asMap().values() )
{
if ( parentHostname.equalsIgnoreCase( agent.getParentHostName() ) )
{
lxcAgents.add( agent );
}
}
}
return lxcAgents;
}
/**
* Adds listener which wants to be notified when agents connect/disconnect
*
* @param listener - listener to add
*/
@Override
public void addListener( AgentListener listener )
{
try
{
if ( !listeners.contains( listener ) )
{
listeners.add( listener );
}
}
catch ( Exception ex )
{
LOG.log( Level.SEVERE, "Error in addListener", ex );
}
}
/**
* Removes listener
*
* @param listener - - listener to remove
*/
@Override
public void removeListener( AgentListener listener )
{
try
{
listeners.remove( listener );
}
catch ( Exception ex )
{
LOG.log( Level.SEVERE, "Error in removeListener", ex );
}
}
@Override
public Set<Agent> getAgentsByHostnames( final Set<String> hostnames )
{
Set<Agent> agentSet = new HashSet<>();
if ( !CollectionUtil.isCollectionEmpty( hostnames ) )
{
for ( Agent agent : agents.asMap().values() )
{
if ( hostnames.contains( agent.getHostname() ) )
{
agentSet.add( agent );
}
}
}
return agentSet;
}
@Override
public Set<Agent> getAgentsByEnvironmentId( final UUID environmentId )
{
Set<Agent> agentSet = new HashSet<>();
if ( environmentId != null )
{
for ( Agent agent : agents.asMap().values() )
{
if ( agent.getEnvironmentId() != null && environmentId.compareTo( agent.getEnvironmentId() ) == 0 )
{
agentSet.add( agent );
}
}
}
return agentSet;
}
@Override
public Agent waitForRegistration( final String hostname, final long timeInMillis )
{
LOG.info( String.format("=====> Waiting in thread %s", Thread.currentThread()) );
Agent result = getAgentByHostname( hostname );
long threshold = System.currentTimeMillis() + timeInMillis;
while ( result == null && System.currentTimeMillis() < threshold )
{
try
{
Thread.sleep( 2000 );
result = getAgentByHostname( hostname );
}
catch ( InterruptedException ignore )
{
}
}
return result;
}
/**
* Initialized agent manager
*/
public void init()
{
try
{
Preconditions.checkNotNull( communicationService, "Communication service is null" );
agents = CacheBuilder.newBuilder().
expireAfterWrite( Common.AGENT_FRESHNESS_MIN, TimeUnit.MINUTES ).
build();
communicationService.addListener( this );
exec = Executors.newSingleThreadExecutor();
exec.execute( new Runnable() {
public void run()
{
long lastNotify = System.currentTimeMillis();
while ( !Thread.interrupted() )
{
try
{
if ( notifyAgentListeners || System.currentTimeMillis() - lastNotify
> Common.AGENT_FRESHNESS_MIN * 60 * 1000 / 2 )
{
lastNotify = System.currentTimeMillis();
notifyAgentListeners = false;
Set<Agent> freshAgents = new HashSet( agents.asMap().values() );
for ( Iterator<AgentListener> it = listeners.iterator(); it.hasNext(); )
{
AgentListener listener = it.next();
try
{
listener.onAgent( freshAgents );
}
catch ( Exception e )
{
it.remove();
LOG.log( Level.SEVERE,
"Error notifying agent listeners, removing faulting listener", e );
}
}
}
Thread.sleep( 1000 );
}
catch ( InterruptedException ex )
{
break;
}
}
}
} );
}
catch ( Exception ex )
{
LOG.log( Level.SEVERE, "Error in init", ex );
}
}
/**
* Disposes agent manager
*/
public void destroy()
{
try
{
agents.invalidateAll();
exec.shutdownNow();
communicationService.removeListener( this );
}
catch ( Exception ex )
{
LOG.log( Level.SEVERE, "Error in destroy", ex );
}
}
/**
* Communication manager event when response from agent arrives
*/
public void onResponse( Response response )
{
if ( response != null && response.getType() != null )
{
switch ( response.getType() )
{
case REGISTRATION_REQUEST:
{
addAgent( response );
break;
}
case HEARTBEAT_RESPONSE:
{
addAgent( response );
break;
}
case AGENT_DISCONNECT:
{
removeAgent( response );
break;
}
default:
{
break;
}
}
}
}
/**
* Adds agent to the cache of connected agents
*/
private void addAgent( Response response )
{
try
{
if ( response != null && response.getUuid() != null )
{
Agent checkAgent = agents.getIfPresent( response.getUuid() );
if ( checkAgent != null )
{
//update timestamp of agent here & return
agents.put( response.getUuid(), checkAgent );
return;
}
//create agent from response
Agent agent = new Agent( response.getUuid(),
Strings.isNullOrEmpty( response.getHostname() ) ? response.getUuid().toString() :
response.getHostname(), response.getParentHostName(), response.getMacAddress(),
response.getIps(), !Strings.isNullOrEmpty( response.getParentHostName() ),
response.getTransportId(), UUIDUtil.generateMACBasedUUID(), response.getEnvironmentId() );
//send registration acknowledgement to agent
sendAck( agent.getUuid() );
//put agent to cache
agents.put( response.getUuid(), agent );
//notify listeners
notifyAgentListeners = true;
}
}
catch ( Exception e )
{
LOG.log( Level.SEVERE, "Error in addAgent", e );
}
}
/**
* Sends ack to agent when it is registered with the management server
*/
private void sendAck( UUID agentUUID )
{
Request ack =
new Request( "AGENT-MANAGER", RequestType.REGISTRATION_REQUEST_DONE, agentUUID, UUID.randomUUID(), null,
null, null, null, null, null, null, null, null, null, null, null );
communicationService.sendRequest( ack );
}
/**
* Removes agent from the cache of connected agents
*/
private void removeAgent( Response response )
{
try
{
if ( response != null && response.getTransportId() != null )
{
for ( Agent agent : agents.asMap().values() )
{
if ( agent.getTransportId().startsWith( response.getTransportId() ) )
{
agents.invalidate( agent.getUuid() );
notifyAgentListeners = true;
return;
}
}
}
}
catch ( Exception e )
{
LOG.log( Level.SEVERE, "Error in removeAgent", e );
}
}
}
|
package org.safehaus.kiskis.mgmt.ui.hive.query.components;
import com.vaadin.data.util.BeanItemContainer;
import com.vaadin.ui.ListSelect;
import com.vaadin.ui.Select;
import org.safehaus.kiskis.mgmt.api.hive.query.Config;
import org.safehaus.kiskis.mgmt.ui.hive.query.HiveQueryUI;
import java.util.List;
public class QueryList extends ListSelect {
public static final int ROW_SIZE = 10;
public QueryList() {
//setFilteringMode(AbstractSelect.Filtering.FILTERINGMODE_CONTAINS);
setNullSelectionAllowed(false);
setImmediate(true);
setRows(QueryList.ROW_SIZE);
refreshDataSource(null);
}
public void refreshDataSource(String filter) {
List<Config> list = HiveQueryUI.getManager().load();
BeanItemContainer<Config> beans =
new BeanItemContainer<Config>(Config.class);
for (Config item : list) {
if (filter == null) {
beans.addBean(item);
} else if (item.getName().contains(filter) || item.getDescription().contains(filter)) {
beans.addBean(item);
}
}
setContainerDataSource(beans);
setItemCaptionMode(Select.ITEM_CAPTION_MODE_PROPERTY);
setItemCaptionPropertyId("name");
}
}
|
package org.geotools.geometry.jts.spatialschema.geometry.geometry;
// J2SE direct dependencies
import org.opengis.referencing.crs.CoordinateReferenceSystem;
/**
* The {@code GeometryFactoryImpl} class/interface...
*
* @author SYS Technologies
* @author crossley
* @version $Revision $
*/
public class GeometryFactoryImpl extends JTSGeometryFactory {
public GeometryFactoryImpl(CoordinateReferenceSystem crs) {
super(crs);
}
}
|
package org.openwms.core.domain.system.usermanagement;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.PostLoad;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Transient;
import javax.persistence.Version;
import org.openwms.core.domain.AbstractEntity;
import org.openwms.core.domain.DomainObject;
import org.openwms.core.exception.InvalidPasswordException;
import org.openwms.core.util.validation.AssertUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* An User represents a human user of the system. Typically an User is assigned
* to one or more <code>Role</code>s to define security constraints. Users can
* have their own configuration settings in form of <code>UserPreference</code>s
* and certain user details, encapsulated in an <code>UserDetails</code> object
* that tend to be extended by projects.
*
* @GlossaryTerm
* @author <a href="mailto:scherrer@openwms.org">Heiko Scherrer</a>
* @version $Revision$
* @since 0.1
* @see org.openwms.core.domain.system.usermanagement.UserDetails
* @see org.openwms.core.domain.system.usermanagement.UserPreference
* @see org.openwms.core.domain.system.usermanagement.UserPassword
* @see org.openwms.core.domain.system.usermanagement.Role
*/
@Entity
@Table(name = "COR_USER")
@NamedQueries({
@NamedQuery(name = User.NQ_FIND_ALL, query = "select u from User u left join fetch u.roles left join fetch u.preferences"),
@NamedQuery(name = User.NQ_FIND_ALL_ORDERED, query = "select u from User u left join fetch u.roles left join fetch u.preferences order by u.username"),
@NamedQuery(name = User.NQ_FIND_BY_USERNAME, query = "select u from User u left join fetch u.roles left join fetch u.preferences where u.username = ?1"),
@NamedQuery(name = User.NQ_FIND_BY_USERNAME_PASSWORD, query = "select u from User u left join fetch u.roles left join fetch u.preferences where u.username = :username and u.savedPassword = :password") })
public class User extends AbstractEntity implements DomainObject<Long> {
private static final long serialVersionUID = -1116645053773805413L;
private static final Logger LOGGER = LoggerFactory.getLogger(User.class);
/**
* Unique technical key.
*/
@Id
@Column(name = "C_ID")
@GeneratedValue
private Long id;
/**
* Unique identifier of this <code>User</code> (not nullable).
*/
@Column(name = "C_USERNAME", unique = true, nullable = false)
private String username;
/**
* <code>true</code> if the <code>User</code> is authenticated by an
* external system, otherwise <code>false</code>.
*/
@Column(name = "C_EXTERN")
private boolean extern = false;
/**
* Date of the last password change.
*/
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "C_LAST_PASSWORD_CHANGE")
private Date lastPasswordChange;
@Column(name = "C_LOCKED")
private boolean locked = false;
/**
* The <code>User</code>'s password.
*/
@Transient
private String password;
/**
* The <code>User</code>'s password.
*/
@Column(name = "C_PASSWORD")
private String savedPassword;
/**
* <code>true</code> if the <code>User</code> is enabled. This field can be
* managed by the UI application to lock an User manually.
*/
@Column(name = "C_ENABLED")
private boolean enabled = true;
/**
* Date when the account expires. After account expiration, the
* <code>User</code> cannot login anymore.
*/
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "C_EXPIRATION_DATE")
private Date expirationDate;
/**
* The <code>User</code>s fullname. Doesn't have to be unique.
*/
@Column(name = "C_FULLNAME")
private String fullname;
/**
* Version field.
*/
@Version
@Column(name = "C_VERSION")
private long version;
/**
* More detail information of the <code>User</code>.
*/
@Embedded
private UserDetails userDetails = new UserDetails();
/**
* List of {@link Role}s assigned to the <code>User</code>. In a JPA context
* eager loaded.
*
* @see javax.persistence.FetchType#EAGER
*/
@ManyToMany(mappedBy = "users", cascade = { CascadeType.MERGE, CascadeType.REFRESH })
private List<Role> roles = new ArrayList<Role>();
/**
* Password history of the <code>User</code>.
*/
@OneToMany(cascade = { CascadeType.MERGE, CascadeType.REMOVE, CascadeType.REFRESH })
@JoinTable(name = "COR_USER_PASSWORD_JOIN", joinColumns = @JoinColumn(name = "USER_ID"), inverseJoinColumns = @JoinColumn(name = "PASSWORD_ID"))
private List<UserPassword> passwords = new ArrayList<UserPassword>();
/**
* The {@link UserPreference}s of the <code>User</code>. In a JPA context
* eager loaded.
*
* @see javax.persistence.FetchType
*/
@OneToMany(cascade = { CascadeType.MERGE, CascadeType.REMOVE, CascadeType.REFRESH })
@JoinColumn(name = "C_OWNER", referencedColumnName = "C_USERNAME")
private Set<UserPreference> preferences = new HashSet<UserPreference>();
/**
* Query to find all <code>User</code>s. Name is {@value} .
*/
public static final String NQ_FIND_ALL = "User.findAll";
/**
* Query to find all <code>User</code>s sorted by userName. Name is {@value}
* .
*/
public static final String NQ_FIND_ALL_ORDERED = "User.findAllOrdered";
/**
* Query to find <strong>one</strong> <code>User</code> by his userName. <li>
* Query parameter index <strong>1</strong> : The userName of the
* <code>User</code> to search for.</li><br />
* Name is {@value} .
*/
public static final String NQ_FIND_BY_USERNAME = "User.findByUsername";
/**
* Query to find <strong>one</strong> <code>User</code> by his userName and
* password. <li>Query parameter name <strong>username</strong> : The
* userName of the <code>User</code> to search for.</li> <li>Query parameter
* name <strong>password</strong> : The current password of the
* <code>User</code> to search for.</li><br />
* Name is {@value} .
*/
public static final String NQ_FIND_BY_USERNAME_PASSWORD = "User.findByUsernameAndPassword";
/**
* The number of passwords to be stored in the password history. When an
* <code>User</code> changes the password, the old password is stored in a
* Collection. Default: {@value} .
*/
public static final short NUMBER_STORED_PASSWORDS = 3;
/**
* Accessed by persistence provider.
*/
protected User() {
super();
loadLazy();
}
public User(String username) {
super();
AssertUtils.isNotEmpty(username, "Not allowed to create an User with an empty username");
this.username = username;
loadLazy();
}
protected User(String username, String password) {
super();
AssertUtils.isNotEmpty(username, "Not allowed to create an User with an empty username");
AssertUtils.isNotEmpty(password, "Not allowed to create an User with an empty password");
this.username = username;
this.password = password;
}
/**
* {@inheritDoc}
*/
@Override
public Long getId() {
return id;
}
/**
* {@inheritDoc}
*/
@Override
public boolean isNew() {
return id == null;
}
private void loadLazy() {
password = savedPassword;
}
/**
* After load, the saved password is copied to the transient one. The
* transient one can be overridden by the application to force a password
* change.
*/
@PostLoad
public void postLoad() {
loadLazy();
}
/**
* Return the unique username of the <code>User</code>.
*
* @return The current username
*/
public String getUsername() {
return username;
}
/**
* Change the username of the <code>User</code>.
*
* @param username
* The new username to set
*/
protected void setUsername(String username) {
this.username = username;
}
/**
* Is the <code>User</code> authenticated by an external system?
*
* @return <code>true</code> if so, otherwise <code>false</code>
*/
public boolean isExternalUser() {
return extern;
}
/**
* Change the authentication method of the <code>User</code>.
*
* @param externalUser
* <code>true</code> if the <code>User</code> was authenticated
* by an external system, otherwise <code>false</code>.
*/
public void setExternalUser(boolean externalUser) {
extern = externalUser;
}
/**
* Return the date when the password has changed recently.
*
* @return The date when the password has changed recently
*/
public Date getLastPasswordChange() {
return lastPasswordChange == null ? null : new Date(lastPasswordChange.getTime());
}
/**
* Check if the <code>User</code> is locked.
*
* @return <code>true</code> if locked, otherwise <code>false</code>
*/
public boolean isLocked() {
return locked;
}
/**
* Lock the <code>User</code>.
*
* @param locked
* <code>true</code> to lock the <code>User</code>,
* <code>false</code> to unlock
*/
public void setLocked(boolean locked) {
this.locked = locked;
}
/**
* Returns the current password of the <code>User</code>.
*
* @return The current password as String
*/
public String getPassword() {
return password;
}
/**
* Set the password that shall be stored as new password. Note, that this
* password is not directly saved.
*
* @param password
* The password to change to
*/
public void setPassword(String password) {
this.password = password;
}
/**
* Checks if the new password is a valid and change the password of this
* <code>User</code>.
*
* @param password
* The new password of this <code>User</code>
* @throws InvalidPasswordException
* in case changing the password is not allowed or the new
* password is not valid
*/
public void changePassword(String password) throws InvalidPasswordException {
// FIXME [scherrer] : Setting the same password should fail
if (savedPassword != null && savedPassword.equals(password)) {
LOGGER.debug("Trying to set the new password equals to the current password");
return;
}
if (isPasswordValid(password)) {
storeOldPassword(this.password);
savedPassword = password;
this.password = password;
lastPasswordChange = new Date();
} else {
throw new InvalidPasswordException("Password is not confirm with the defined rules");
}
}
/**
* Checks whether the password is going to be changed from the application
* side.
*
* @return <code>true</code> when the <code>password</code> is different to
* the saved one, otherwise <code>false</code>
*/
public boolean hasPasswordChanged() {
return (savedPassword.equals(password));
}
/**
* Check whether the new password is in the history of former passwords.
*
* @param pwd
* The password to verify
* @return <code>true</code> if the password is valid, otherwise
* <code>false</code>
*/
protected boolean isPasswordValid(String pwd) {
if (passwords.contains(new UserPassword(this, pwd))) {
return false;
}
return true;
}
private void storeOldPassword(String oldPassword) {
if (oldPassword == null || oldPassword.isEmpty()) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("If the old password is null, do not store it in history");
}
return;
}
passwords.add(new UserPassword(this, oldPassword));
if (passwords.size() > NUMBER_STORED_PASSWORDS) {
Collections.sort(passwords, new Comparator<UserPassword>() {
@Override
public int compare(UserPassword o1, UserPassword o2) {
return o2.getPasswordChanged().compareTo(o1.getPasswordChanged());
}
});
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Remove the old password from the history: " + passwords.get(passwords.size() - 1));
}
UserPassword pw = passwords.get(passwords.size() - 1);
pw.setUser(null);
passwords.remove(pw);
}
}
/**
* Determines whether the <code>User</code> is enabled or not.
*
* @return <code>true</code> if the <code>User</code> is enabled, otherwise
* <code>false</code>
*/
public boolean isEnabled() {
return enabled;
}
/**
* Enable or disable the <code>User</code>.
*
* @param enabled
* <code>true</code> when enabled, otherwise <code>false</code>
*/
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
/**
* Return the date when the account expires.
*
* @return The expiration date
*/
public Date getExpirationDate() {
return new Date(expirationDate.getTime());
}
/**
* Change the date when the account expires.
*
* @param expDate
* The new expiration date to set
*/
public void setExpirationDate(Date expDate) {
expirationDate = new Date(expDate.getTime());
}
/**
* Returns a list of granted {@link Role}s.
*
* @return The list of granted {@link Role}s
*/
public List<Role> getRoles() {
return roles;
}
/**
* Flatten {@link Role}s and {@link Grant}s and return an unmodifiable list
* of all {@link Grant}s assigned to this <code>User</code>.
*
* @return A list of all {@link Grant}s
*/
public List<SecurityObject> getGrants() {
List<SecurityObject> grants = new ArrayList<SecurityObject>();
for (Role role : getRoles()) {
grants.addAll(role.getGrants());
}
return Collections.unmodifiableList(grants);
}
/**
* Add a new {@link Role} to the list of {@link Role}s.
*
* @param role
* The new {@link Role} to add
* @return see {@link java.util.Collection#add(Object)}
*/
public boolean addRole(Role role) {
return roles.add(role);
}
/**
* Set the {@link Role}s of this <code>User</code>. Existing {@link Role}s
* will be overridden.
*
* @param roles
* The new list of {@link Role}s
*/
public void setRoles(List<Role> roles) {
roles = roles;
}
/**
* Return the fullname of the <code>User</code>.
*
* @return The current fullname
*/
public String getFullname() {
return fullname;
}
/**
* Change the fullname of the <code>User</code>.
*
* @param fullname
* The new fullname to set
*/
public void setFullname(String fullname) {
this.fullname = fullname;
}
/**
* Return a list of recently used passwords.
*
* @return A list of recently used passwords
*/
public List<UserPassword> getPasswords() {
return passwords;
}
/**
* Return the details of the <code>User</code>.
*
* @return The userDetails
*/
public UserDetails getUserDetails() {
return userDetails;
}
/**
* Assign some details to the <code>User</code>.
*
* @param userDetails
* The userDetails to set
*/
public void setUserDetails(UserDetails userDetails) {
this.userDetails = userDetails;
}
/**
* Get all {@link UserPreference}s of this <code>User</code>.
*
* @return A set of all {@link UserPreference}s
*/
public Set<UserPreference> getPreferences() {
return preferences;
}
/**
* Set all {@link UserPreference}s of the <code>User</code>. Already
* existing {@link UserPreference}s will be overridden.
*
* @param preferences
* A set of {@link UserPreference}s to set
*/
public void setPreferences(Set<UserPreference> preferences) {
this.preferences = preferences;
}
/**
* {@inheritDoc}
*/
@Override
public long getVersion() {
return version;
}
/**
* {@inheritDoc}
*
* Does not call the superclass. Uses the username for calculation.
*
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((username == null) ? 0 : username.hashCode());
return result;
}
/**
* {@inheritDoc}
*
* Uses the username for comparison.
*
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof User)) {
return false;
}
User other = (User) obj;
if (username == null) {
if (other.username != null) {
return false;
}
} else if (!username.equals(other.username)) {
return false;
}
return true;
}
}
|
package org.silverpeas.components.projectmanager.servlets;
import org.silverpeas.components.projectmanager.control.ProjectManagerSessionController;
import org.silverpeas.components.projectmanager.model.TaskDetail;
import org.silverpeas.core.util.Charsets;
import org.silverpeas.core.util.DateUtil;
import org.silverpeas.core.util.JSONCodec;
import org.silverpeas.core.util.JSONCodec.JSONArray;
import org.silverpeas.core.util.MimeTypes;
import org.silverpeas.core.util.StringUtil;
import org.silverpeas.core.util.WebEncodeHelper;
import org.silverpeas.core.util.logging.SilverLogger;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.Writer;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.function.UnaryOperator;
public class AjaxProjectManagerServlet extends HttpServlet {
private static final long serialVersionUID = 798968548064856822L;
private static final String ACTION_LOAD_TASK = "loadTask";
private static final String ACTION_COLLAPSE_TASK = "collapseTask";
private static final String REQUEST_PARAM_TASKID = "TaskId";
private static final String REQUEST_PARAM_BEGINDATE = "BeginDate";
@Override
public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException {
doPost(req, res);
}
@Override
public void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException {
HttpSession session = req.getSession(true);
String componentId = req.getParameter("ComponentId");
// Retrieve action parameter
String action = req.getParameter("Action");
ProjectManagerSessionController projectManagerSC = (ProjectManagerSessionController) session
.getAttribute("Silverpeas_projectManager_" + componentId);
if (projectManagerSC == null) {
return;
}
String output = "";
if ("ProcessUserOccupation".equals(action)) {
String taskId = req.getParameter(REQUEST_PARAM_TASKID);
String userId = req.getParameter("UserId");
String userCharge = req.getParameter("UserCharge");
String sBeginDate = req.getParameter(REQUEST_PARAM_BEGINDATE);
String sEndDate = req.getParameter("EndDate");
Date beginDate = parseDate(sBeginDate, projectManagerSC);
Date endDate = parseDate(sEndDate, projectManagerSC);
int occupation = 0;
if (StringUtil.isDefined(taskId)) {
occupation = projectManagerSC.checkOccupation(taskId, userId, beginDate, endDate);
} else {
occupation = projectManagerSC.checkOccupation(userId, beginDate, endDate);
}
occupation += Integer.parseInt(userCharge);
output = formatOccupation(occupation);
} else if ("ProcessEndDate".equals(action)) {
String taskId = req.getParameter(REQUEST_PARAM_TASKID);
String charge = req.getParameter("Charge");
String sBeginDate = req.getParameter(REQUEST_PARAM_BEGINDATE);
Date beginDate = parseDate(sBeginDate, projectManagerSC);
if (beginDate == null) {
beginDate = new Date();
}
Date endDate;
if (StringUtil.isDefined(taskId)) {
endDate = projectManagerSC.processEndDate(taskId, charge, beginDate);
} else {
endDate = projectManagerSC.processEndDate(charge, beginDate, componentId);
}
output = WebEncodeHelper.escapeXml(projectManagerSC.date2UIDate(endDate));
} else if (ACTION_LOAD_TASK.equals(action)) {
String taskId = req.getParameter(REQUEST_PARAM_TASKID);
List<TaskDetail> tasks = projectManagerSC.getTasks(taskId);
output = JSONCodec.encodeObject(jsonResult -> {
jsonResult.put("success", true);
jsonResult.put("componentId", projectManagerSC.getComponentId());
jsonResult.putJSONArray("tasks", getJSONTasks(tasks));
return jsonResult;
});
} else if (ACTION_COLLAPSE_TASK.equals(action)) {
String taskId = req.getParameter(REQUEST_PARAM_TASKID);
output = JSONCodec.encodeObject(jsonResult -> {
jsonResult.put("success", true);
jsonResult.put("componentId", projectManagerSC.getComponentId());
List<Integer> listTaskIds = new ArrayList<>();
jsonResult.putJSONArray("tasks", convertCollapsedTaskIdsIntoJSON(
getCollapsedTaskIds(projectManagerSC, taskId, listTaskIds)));
return jsonResult;
});
}
res.setContentType(MimeTypes.XML_MIME_TYPE);
res.setHeader("charset", Charsets.UTF_8.name());
Writer writer = res.getWriter();
writer.write(output);
}
private UnaryOperator<JSONArray> convertCollapsedTaskIdsIntoJSON(
List<Integer> taskIds) {
return (jsonTaskIds -> {
for (Integer taskId : taskIds) {
jsonTaskIds.addJSONObject(jsonTask -> jsonTask.put("id", taskId));
}
return jsonTaskIds;
});
}
/**
* Recursive method which build the list of tasks id that are child of the task identifier given
* in parameter
* @param projectManagerSC the project manager session controller
* @param taskId the current task identifier we need to have task childs
* @param taskIds the list of ids to build
*/
private List<Integer> getCollapsedTaskIds(ProjectManagerSessionController projectManagerSC,
String taskId, List<Integer> taskIds) {
List<TaskDetail> tasks = projectManagerSC.getTasks(taskId);
for (TaskDetail curTask : tasks) {
taskIds.add(curTask.getId());
if (curTask.getEstDecomposee() == 1) {
this.getCollapsedTaskIds(projectManagerSC, Integer.toString(curTask.getId()), taskIds);
}
}
return taskIds;
}
/**
* @param tasks the list of tasks to convert into JSON
* @return JSONArray of list of tasks
*/
private UnaryOperator<JSONArray> getJSONTasks(List<TaskDetail> tasks) {
return (jsonTasks -> {
for (TaskDetail curTask : tasks) {
jsonTasks.addJSONObject(jsonTask -> {
jsonTask.put("id", curTask.getId());
jsonTask.put("status", curTask.getStatut());
// level is not used : need to use another element
jsonTask.put("level", curTask.getLevel());
jsonTask.put("containsSubTask", curTask.getEstDecomposee());
jsonTask.put("name", curTask.getNom());
jsonTask.put("manager", curTask.getResponsableFullName());
jsonTask.put("startDate", DateUtil.formatDate(curTask.getDateDebut(), "yyyyMMdd"));
jsonTask.put("endDate", DateUtil.formatDate(curTask.getDateFin(), "yyyyMMdd"));
float conso = curTask.getConsomme();
if (conso != 0) {
jsonTask.put("percentage", (conso / (conso + curTask.getRaf())) * 100);
} else {
jsonTask.put("percentage", conso);
}
return jsonTask;
});
}
return jsonTasks;
});
}
private Date parseDate(String date, ProjectManagerSessionController projectManagerSC) {
try {
return projectManagerSC.uiDate2Date(date);
} catch (ParseException ignored) {
SilverLogger.getLogger(this).debug("Error when parsing date "+date);
}
return null;
}
private String formatOccupation(int occupation) {
String font = "<font color=\"green\">";
if (occupation > 100) {
font = "<font color=\"red\">";
}
return font + occupation + " %</font>";
}
}
|
package io.narayana.lra.client;
import io.narayana.lra.Current;
import io.narayana.lra.LRAConstants;
import io.narayana.lra.LRAData;
import io.narayana.lra.logging.LRALogger;
import org.eclipse.microprofile.lra.annotation.AfterLRA;
import org.eclipse.microprofile.lra.annotation.Compensate;
import org.eclipse.microprofile.lra.annotation.Complete;
import org.eclipse.microprofile.lra.annotation.Forget;
import org.eclipse.microprofile.lra.annotation.LRAStatus;
import org.eclipse.microprofile.lra.annotation.Status;
import org.eclipse.microprofile.lra.annotation.ws.rs.Leave;
import javax.enterprise.context.RequestScoped;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.NotFoundException;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.container.Suspended;
import javax.ws.rs.core.GenericType;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.Link;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.core.UriBuilder;
import java.io.Closeable;
import java.io.UnsupportedEncodingException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.time.temporal.ChronoUnit;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import static io.narayana.lra.LRAConstants.AFTER;
import static io.narayana.lra.LRAConstants.CLIENT_ID_PARAM_NAME;
import static io.narayana.lra.LRAConstants.COMPENSATE;
import static io.narayana.lra.LRAConstants.COMPLETE;
import static io.narayana.lra.LRAConstants.FORGET;
import static io.narayana.lra.LRAConstants.LEAVE;
import static io.narayana.lra.LRAConstants.NARAYANA_LRA_API_VERSION_HEADER_NAME;
import static io.narayana.lra.LRAConstants.PARENT_LRA_PARAM_NAME;
import static io.narayana.lra.LRAConstants.STATUS;
import static io.narayana.lra.LRAConstants.TIMELIMIT_PARAM_NAME;
import static javax.ws.rs.core.Response.Status.OK;
import static javax.ws.rs.core.Response.Status.BAD_REQUEST;
import static javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR;
import static javax.ws.rs.core.Response.Status.NOT_ACCEPTABLE;
import static javax.ws.rs.core.Response.Status.PRECONDITION_FAILED;
import static javax.ws.rs.core.Response.Status.GONE;
import static javax.ws.rs.core.Response.Status.NOT_FOUND;
import static javax.ws.rs.core.Response.Status.NO_CONTENT;
import static org.eclipse.microprofile.lra.annotation.ws.rs.LRA.LRA_HTTP_RECOVERY_HEADER;
import static io.narayana.lra.LRAConstants.RECOVERY_COORDINATOR_PATH_NAME;
import static io.narayana.lra.LRAConstants.COORDINATOR_PATH_NAME;
/**
* WARNING: NarayanaLRAClient is an internal utility class and is subject to change
* (however it will be made available with improved guarantees in a subsequent release).
*
* A utility class for controlling the lifecycle of Long Running Actions (LRAs) but the preferred mechanism is to use
* the annotation in the {@link org.eclipse.microprofile.lra.annotation} package
*/
@Deprecated
@RequestScoped
public class NarayanaLRAClient implements Closeable {
/**
* Key for looking up the config property that specifies which is the URL
* to connect to the Narayana LRA coordinator
*/
public static final String LRA_COORDINATOR_URL_KEY = "lra.coordinator.url";
// LRA Coordinator API
private static final String START_PATH = "/start";
private static final String LEAVE_PATH = "/%s/remove";
private static final String STATUS_PATH = "/%s/status";
private static final String CLOSE_PATH = "/%s/close";
private static final String CANCEL_PATH = "/%s/cancel";
private static final String LINK_TEXT = "Link";
/**
* constrain how long client operations take before giving up
*
* WARNING: NarayanaLRAClient is an internal utility class and is subject to change
* (but it will be made available with improved guarantees in a subsequent release).
*/
private static final long CLIENT_TIMEOUT = Long.getLong("lra.internal.client.timeout", 10);
private static final long START_TIMEOUT = Long.getLong("lra.internal.client.timeout.start", CLIENT_TIMEOUT);
private static final long JOIN_TIMEOUT = Long.getLong("lra.internal.client.timeout.join", CLIENT_TIMEOUT);
private static final long END_TIMEOUT = Long.getLong("lra.internal.client.end.timeout", CLIENT_TIMEOUT);
private static final long LEAVE_TIMEOUT = Long.getLong("lra.internal.client.leave.timeout", CLIENT_TIMEOUT);
private static final long QUERY_TIMEOUT = Long.getLong("lra.internal.client.query.timeout", CLIENT_TIMEOUT);
private URI coordinatorUrl;
public NarayanaLRAClient() {
this(System.getProperty(NarayanaLRAClient.LRA_COORDINATOR_URL_KEY,
"http://localhost:8080/" + COORDINATOR_PATH_NAME));
}
/**
* Creating LRA client where expecting LRA coordinator being available through
* protocol <i>protocol</i> at <i>host</i>:<i>port</i>/<i>coordinatorPath</i>.
*
* @param protocol protocol used to contact the LRA coordinator
* @param host hostname where the LRA coordinator will be contacted
* @param port port where the LRA coordinator will be contacted
* @param coordinatorPath path where the LRA coordinator will be contacted
*/
public NarayanaLRAClient(String protocol, String host, int port, String coordinatorPath) {
coordinatorUrl = UriBuilder.fromPath(coordinatorPath).scheme(protocol).host(host).port(port).build();
}
/**
* Creating LRA client where expecting LRA coordinator being available
* at the provided uri.
* The LRA recovery coordinator will be searched at the sub-path {@value LRAConstants#RECOVERY_COORDINATOR_PATH_NAME}.
*
* @param coordinatorUrl uri of the LRA coordinator
*/
public NarayanaLRAClient(URI coordinatorUrl) {
this.coordinatorUrl = coordinatorUrl;
}
public NarayanaLRAClient(String coordinatorUrl) {
try {
this.coordinatorUrl = new URI(coordinatorUrl);
} catch (URISyntaxException use) {
throw new IllegalStateException("Cannot convert the provided coordinator url String "
+ coordinatorUrl + " to URL format", use);
}
}
/**
* Method changes the client's notion about the place where the LRA coordinator can be contacted.
* It takes the provided URI and tries to derive the URL path of the coordinator responsible
* for the LRA id. The URL is then used as endpoint for later use of this LRA Narayana client instance.
*
* @param lraId LRA id consisting of the coordinator URL and the LRA uid
*/
public void setCurrentLRA(URI lraId) {
try {
this.coordinatorUrl = LRAConstants.getLRACoordinatorUrl(lraId);
} catch (IllegalStateException e) {
String logMsg = LRALogger.i18nLogger.error_invalidLraIdFormatToConvertToCoordinatorUrl(lraId.toASCIIString(), e);
LRALogger.logger.error(logMsg);
throwGenericLRAException(lraId, BAD_REQUEST.getStatusCode(), logMsg, null);
}
}
public List<LRAData> getAllLRAs() {
Client client = null;
try {
client = getClient();
Response response = client.target(coordinatorUrl)
.request()
.header(NARAYANA_LRA_API_VERSION_HEADER_NAME, LRAConstants.CURRENT_API_VERSION_STRING)
.async()
.get()
.get(QUERY_TIMEOUT, TimeUnit.SECONDS);
if (response.getStatus() != OK.getStatusCode()) {
LRALogger.logger.debugf("Error getting all LRAs from the coordinator, response status: %d", response.getStatus());
throw new WebApplicationException(response);
}
return response.readEntity(new GenericType<List<LRAData>>() {});
} catch (InterruptedException | ExecutionException | TimeoutException e) {
throw new WebApplicationException("getAllLRAs client request timed out, try again later",
Response.Status.SERVICE_UNAVAILABLE.getStatusCode());
} finally {
if (client != null) {
client.close();
}
}
}
/**
* Starting LRA. You provide client id determining the LRA being started.
*
* @param clientID client id determining the LRA
* @return LRA id as URL
* @throws WebApplicationException thrown when start of the LRA failed
*/
public URI startLRA(String clientID) throws WebApplicationException {
return startLRA(clientID, 0L);
}
/**
* Starting LRA. You provide client id that joins the LRA context
* and is passed when working with the LRA.
*
* @param clientID client id determining the LRA
* @param timeout timeout value in seconds, when timeout-ed the LRA will be compensated
* @return LRA id as URL
* @throws WebApplicationException thrown when start of the LRA failed
*/
private URI startLRA(String clientID, Long timeout) throws WebApplicationException {
return startLRA(clientID, timeout, ChronoUnit.SECONDS);
}
/**
* Starting LRA. You provide client id that joins the LRA context
* and is passed when working with the LRA.
*
* @param clientID client id determining the LRA
* @param timeout timeout value, when timeout-ed the LRA will be compensated
* @param unit timeout unit, when null seconds are used
* @return LRA id as URL
* @throws WebApplicationException thrown when start of the LRA failed
*/
private URI startLRA(String clientID, Long timeout, ChronoUnit unit) throws WebApplicationException {
return startLRA(getCurrent(), clientID, timeout, unit);
}
public URI startLRA(URI parentLRA, String clientID, Long timeout, ChronoUnit unit) throws WebApplicationException {
return startLRA(parentLRA, clientID, timeout, unit, true);
}
/**
* Starting LRA. You provide client id that joins the LRA context
* and is passed when working with the LRA.
*
* @param parentLRA when the newly started LRA should be nested with this LRA parent, when null the newly started LRA is top-level
* @param clientID client id determining the LRA
* @param timeout timeout value, when timeout-ed the LRA will be compensated
* @param unit timeout unit, when null seconds are used
* @return LRA id as URL
* @throws WebApplicationException thrown when start of the LRA failed
*/
public URI startLRA(URI parentLRA, String clientID, Long timeout, ChronoUnit unit, boolean verbose) throws WebApplicationException {
Client client = null;
Response response = null;
URI lra;
if (clientID == null) {
clientID = "";
}
if (timeout == null) {
timeout = 0L;
} else if (timeout < 0) {
throwGenericLRAException(parentLRA, BAD_REQUEST.getStatusCode(),
"Invalid timeout value: " + timeout, null);
return null;
}
if (unit == null) {
unit = ChronoUnit.SECONDS;
}
lraTracef("startLRA for client %s with parent %s", clientID, parentLRA);
try {
String encodedParentLRA = parentLRA == null ? "" : URLEncoder.encode(parentLRA.toString(), StandardCharsets.UTF_8.name());
client = getClient();
response = client.target(coordinatorUrl)
.path(START_PATH)
.queryParam(CLIENT_ID_PARAM_NAME, clientID)
.queryParam(TIMELIMIT_PARAM_NAME, Duration.of(timeout, unit).toMillis())
.queryParam(PARENT_LRA_PARAM_NAME, encodedParentLRA)
.request()
.header(NARAYANA_LRA_API_VERSION_HEADER_NAME, LRAConstants.CURRENT_API_VERSION_STRING)
.async()
.post(null)
.get(START_TIMEOUT, TimeUnit.SECONDS);
// validate the HTTP status code says an LRA resource was created
if (isUnexpectedResponseStatus(response, Response.Status.CREATED)) {
String responseEntity = response.hasEntity() ? response.readEntity(String.class) : "";
String logMsg = LRALogger.i18nLogger.error_lraCreationUnexpectedStatus(response.getStatus(), responseEntity);
if (verbose) {
LRALogger.logger.error(logMsg);
}
throwGenericLRAException(null, response.getStatus(), // TODO the catch (Exception) block already catches this one
logMsg, null);
return null;
}
lra = URI.create(response.getHeaderString(HttpHeaders.LOCATION));
lraTrace(lra, "startLRA returned");
Current.push(lra);
return lra;
} catch (UnsupportedEncodingException uee) {
String logMsg = LRALogger.i18nLogger.error_invalidFormatToEncodeParentUri(parentLRA, uee);
if (verbose) {
LRALogger.logger.error(logMsg);
}
throwGenericLRAException(null, INTERNAL_SERVER_ERROR.getStatusCode(),
logMsg, uee);
return null;
} catch (InterruptedException | ExecutionException | TimeoutException e) {
LRALogger.i18nLogger.warn_startLRAFailed(e.getMessage(), e);
throw new WebApplicationException("start LRA client request failed, try again later", e,
Response.Status.SERVICE_UNAVAILABLE.getStatusCode());
} finally {
if (client != null) {
client.close();
}
}
}
public void cancelLRA(URI lraId) throws WebApplicationException {
endLRA(lraId, false);
}
public void closeLRA(URI lraId) throws WebApplicationException {
endLRA(lraId, true);
}
/**
* Joining the LRA with identity of `lraId` as participant defined by URIs for complete, compensate, forget, leave,
* after and status.
*
* @param lraId the URI of the LRA to join
* @param timeLimit how long the participant is prepared to wait for LRA completion
* @param compensateUri URI for compensation notifications
* @param completeUri URI for completion notifications
* @param forgetUri URI for forget callback
* @param leaveUri URI for leave requests
* @param statusUri URI for reporting the status of the participant
* @param compensatorData data provided during compensation
* @return a recovery URL for this enlistment
* @throws WebApplicationException if the LRA coordinator failed to enlist the participant
*/
public URI joinLRA(URI lraId, Long timeLimit,
URI compensateUri, URI completeUri, URI forgetUri, URI leaveUri, URI afterUri, URI statusUri,
String compensatorData) throws WebApplicationException {
return enlistCompensator(lraId, timeLimit, "",
compensateUri, completeUri,
forgetUri, leaveUri, afterUri, statusUri,
compensatorData);
}
/**
* Joining the LRA with identity of `lraId` as participant defined by a participant URI.
*
* @param lraId the URI of the LRA to join
* @param timeLimit how long the participant is prepared to wait for LRA completion
* @param participantUri URI of participant for enlistment
* @param compensatorData data provided during compensation
* @return a recovery URL for this enlistment
* @throws WebApplicationException if the LRA coordinator failed to enlist the participant
*/
public URI joinLRA(URI lraId, Long timeLimit,
URI participantUri, String compensatorData) throws WebApplicationException {
validateURI(participantUri, false, "Invalid participant URL: %s");
StringBuilder linkHeaderValue
= makeLink(new StringBuilder(), null, "participant", participantUri.toASCIIString());
return enlistCompensator(lraId, timeLimit, linkHeaderValue.toString(), compensatorData);
}
public void leaveLRA(URI lraId, String body) throws WebApplicationException {
Client client = null;
Response response;
try {
client = getClient();
response = client.target(coordinatorUrl)
.path(String.format(LEAVE_PATH, LRAConstants.getLRAUid(lraId)))
.request()
.header(NARAYANA_LRA_API_VERSION_HEADER_NAME, LRAConstants.CURRENT_API_VERSION_STRING)
.async()
.put(body == null ? Entity.text("") : Entity.text(body))
.get(LEAVE_TIMEOUT, TimeUnit.SECONDS);
if (OK.getStatusCode() != response.getStatus()) {
String logMsg = LRALogger.i18nLogger.error_lraLeaveUnexpectedStatus(lraId, response.getStatus(),
response.hasEntity() ? response.readEntity(String.class) : "");
LRALogger.logger.error(logMsg);
throwGenericLRAException(null, response.getStatus(), logMsg, null);
}
} catch (InterruptedException | ExecutionException | TimeoutException e) {
throw new WebApplicationException("leave LRA client request timed out, try again later",
Response.Status.SERVICE_UNAVAILABLE.getStatusCode());
} finally {
if (client != null) {
client.close();
}
}
}
/**
* For particular compensator class it returns termination uris based on the provided base uri.
* You get map of string and URI.
*
* @param compensatorClass compensator class to examine
* @param uriInfo the uri that triggered this join request.
* @return map of URI
*/
public static Map<String, String> getTerminationUris(Class<?> compensatorClass, UriInfo uriInfo, Long timeout) {
Map<String, String> paths = new HashMap<>();
final boolean[] asyncTermination = {false};
URI baseUri = uriInfo.getBaseUri();
/*
* Calculate which path to prepend to the LRA participant methods. If there is more than one matching URI
* then the second matched URI comes from either the class level Path annotation or from a sub-resource locator.
* In both cases the second matched URI can be used as a prefix for the LRA participant URIs:
*/
List<String> matchedURIs = uriInfo.getMatchedURIs();
int matchedURI = (matchedURIs.size() > 1 ? 1 : 0);
final String uriPrefix = baseUri + matchedURIs.get(matchedURI);
String timeoutValue = timeout != null ? Long.toString(timeout) : "0";
Arrays.stream(compensatorClass.getMethods()).forEach(method -> {
Path pathAnnotation = method.getAnnotation(Path.class);
if (pathAnnotation != null) {
if (checkMethod(paths, method, COMPENSATE, pathAnnotation,
method.getAnnotation(Compensate.class), uriPrefix) != 0) {
paths.put(TIMELIMIT_PARAM_NAME, timeoutValue);
if (isAsyncCompletion(method)) {
asyncTermination[0] = true;
}
}
if (checkMethod(paths, method, COMPLETE, pathAnnotation,
method.getAnnotation(Complete.class), uriPrefix) != 0) {
paths.put(TIMELIMIT_PARAM_NAME, timeoutValue);
if (isAsyncCompletion(method)) {
asyncTermination[0] = true;
}
}
checkMethod(paths, method, STATUS, pathAnnotation,
method.getAnnotation(Status.class), uriPrefix);
checkMethod(paths, method, FORGET, pathAnnotation,
method.getAnnotation(Forget.class), uriPrefix);
checkMethod(paths, method, LEAVE, pathAnnotation, method.getAnnotation(Leave.class), uriPrefix);
checkMethod(paths, method, AFTER, pathAnnotation, method.getAnnotation(AfterLRA.class), uriPrefix);
}
});
if (asyncTermination[0] && !paths.containsKey(STATUS) && !paths.containsKey(FORGET)) {
String logMsg = LRALogger.i18nLogger.error_asyncTerminationBeanMissStatusAndForget(compensatorClass);
LRALogger.logger.warn(logMsg);
throw new WebApplicationException(
Response.status(BAD_REQUEST)
.entity(logMsg)
.build());
}
StringBuilder linkHeaderValue = new StringBuilder();
if (paths.size() != 0) {
paths.forEach((k, v) -> makeLink(linkHeaderValue, null, k, v));
paths.put(LINK_TEXT, linkHeaderValue.toString());
}
return paths;
}
/**
* Providing information if method is defined to be completed asynchronously.
* This means that {@link Suspended} annotation is available amongst the method parameters
* while the method is annotated with {@link Complete} or {@link Compensate}.
*
* @param method method to be checked for async completion
* @return true if method is to complete asynchronously, false if synchronously
*/
public static boolean isAsyncCompletion(Method method) {
if (method.isAnnotationPresent(Complete.class) || method.isAnnotationPresent(Compensate.class)) {
for (Annotation[] ann : method.getParameterAnnotations()) {
for (Annotation an : ann) {
if (Suspended.class.isAssignableFrom(an.annotationType())) {
LRALogger.logger.warn("JAX-RS @Suspended annotation is untested");
return true;
}
}
}
}
return false;
}
private static int checkMethod(Map<String, String> paths,
Method method, String rel,
Path pathAnnotation,
Annotation annotationClass,
String uriPrefix) {
/*
* If the annotationClass is null the requested participant annotation is not present,
* but we also need to check for conformance with the interoperability spec,
* ie look for paths of the form:
* `<participant URL>/compensate`
* `<participant URL>/complete`
* etc
*/
if (annotationClass == null) {
// TODO support standard compenators with: && !pathAnnotation.value().endsWith(rel)) {
// ie ones that do not use the @Compensate annotation
return 0;
}
// search for a matching JAX-RS method
for (Annotation annotation : method.getDeclaredAnnotations()) {
String name = annotation.annotationType().getName();
if (name.equals(GET.class.getName()) ||
name.equals(PUT.class.getName()) ||
name.equals(POST.class.getName()) ||
name.equals(DELETE.class.getName())) {
String pathValue = pathAnnotation.value();
pathValue = pathValue.startsWith("/") ? pathValue : "/" + pathValue;
String url = String.format("%s%s?%s=%s", uriPrefix, pathValue, LRAConstants.HTTP_METHOD_NAME, name);
paths.put(rel, url);
break;
}
}
return 1;
}
public LRAStatus getStatus(URI uri) throws WebApplicationException {
Client client = null;
Response response;
URL lraId;
try {
lraId = uri.toURL();
} catch (MalformedURLException mue) {
throwGenericLRAException(null,
Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(),
"Could not convert LRA to a URL : " + mue.getClass().getName() + ":" + mue.getMessage(), mue);
return null;
}
try {
client = getClient();
response = client.target(coordinatorUrl)
.path(String.format(STATUS_PATH, LRAConstants.getLRAUid(uri)))
.request()
.header(NARAYANA_LRA_API_VERSION_HEADER_NAME, LRAConstants.CURRENT_API_VERSION_STRING)
.async()
.get()
.get(QUERY_TIMEOUT, TimeUnit.SECONDS);
if (response.getStatus() == NOT_FOUND.getStatusCode()) {
String responseEntity = response.hasEntity() ? response.readEntity(String.class) : "";
String errorMsg = "The requested LRA it '" + lraId + "' was not found and the status can't be obtained, "
+ "response content: " + responseEntity;
throw new NotFoundException(errorMsg, Response.status(NOT_FOUND).entity(errorMsg).build());
}
if (response.getStatus() == NO_CONTENT.getStatusCode()) {
return LRAStatus.Active;
}
if (response.getStatus() != OK.getStatusCode()) {
String logMsg = LRALogger.i18nLogger.error_invalidStatusCode(coordinatorUrl, response.getStatus(), lraId);
LRALogger.logger.error(logMsg);
throwGenericLRAException(uri, response.getStatus(),
logMsg, null);
}
if (!response.hasEntity()) {
String logMsg = LRALogger.i18nLogger.error_noContentOnGetStatus(coordinatorUrl, lraId);
LRALogger.logger.error(logMsg);
throwGenericLRAException(uri, Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(),
logMsg, null);
}
// convert the returned String into a status
try {
return fromString(response.readEntity(String.class));
} catch (IllegalArgumentException iae) {
String logMsg = LRALogger.i18nLogger.error_invalidArgumentOnStatusFromCoordinator(coordinatorUrl, lraId, iae);
LRALogger.logger.error(logMsg);
throwGenericLRAException(uri,Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(),
logMsg, iae);
}
} catch (InterruptedException | ExecutionException | TimeoutException e) {
throw new WebApplicationException("get LRA status client request timed out, try again later",
Response.Status.SERVICE_UNAVAILABLE.getStatusCode());
} finally {
if (client != null) {
client.close();
}
}
return null;
}
private static LRAStatus fromString(String status) {
if (status == null) {
throw new IllegalArgumentException("The status parameter is null");
}
return LRAStatus.valueOf(status);
}
private static StringBuilder makeLink(StringBuilder b, String uriPrefix, String key, String value) {
if (value == null) {
return b;
}
String terminationUri = uriPrefix == null ? value : String.format("%s%s", uriPrefix, value);
Link link = Link.fromUri(terminationUri).title(key + " URI").rel(key).type(MediaType.TEXT_PLAIN).build();
if (b.length() != 0) {
b.append(',');
}
return b.append(link);
}
private URI enlistCompensator(URI lraUri, Long timelimit, String uriPrefix,
URI compensateUri, URI completeUri,
URI forgetUri, URI leaveUri, URI afterUri, URI statusUri,
String compensatorData) {
validateURI(completeUri, true, "Invalid complete URL: %s");
validateURI(compensateUri, true, "Invalid compensate URL: %s");
validateURI(leaveUri, true, "Invalid status URL: %s");
validateURI(afterUri, true, "Invalid after URL: %s");
validateURI(forgetUri, true, "Invalid forgetUri URL: %s");
validateURI(statusUri, true, "Invalid status URL: %s");
Map<String, URI> terminateURIs = new HashMap<>();
terminateURIs.put(COMPENSATE, compensateUri);
terminateURIs.put(COMPLETE, completeUri);
terminateURIs.put(LEAVE, leaveUri);
terminateURIs.put(AFTER, afterUri);
terminateURIs.put(STATUS, statusUri);
terminateURIs.put(FORGET, forgetUri);
// register with the coordinator
// put the lra id in an http header
StringBuilder linkHeaderValue = new StringBuilder();
terminateURIs.forEach((k, v) -> makeLink(linkHeaderValue, uriPrefix, k, v == null ? null : v.toASCIIString()));
return enlistCompensator(lraUri, timelimit, linkHeaderValue.toString(), compensatorData);
}
private URI enlistCompensator(URI uri, Long timelimit, String linkHeader, String compensatorData) {
// register with the coordinator
// put the lra id in an http header
Client client = null;
Response response = null;
URL lraId = null;
try {
lraId = uri.toURL();
} catch (MalformedURLException mue) {
throwGenericLRAException(null, Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(),
"Could not convert LRA to a URL : " + mue.getClass().getName() + ":" + mue.getMessage(), mue);
}
if (timelimit == null || timelimit < 0) {
timelimit = 0L;
}
try {
client = getClient();
try {
response = client.target(coordinatorUrl)
.path(LRAConstants.getLRAUid(uri))
.queryParam(TIMELIMIT_PARAM_NAME, timelimit)
.request()
.header(NARAYANA_LRA_API_VERSION_HEADER_NAME, LRAConstants.CURRENT_API_VERSION_STRING)
.header("Link", linkHeader)
.async()
.put(Entity.text(compensatorData == null ? linkHeader : compensatorData))
.get(JOIN_TIMEOUT, TimeUnit.SECONDS);
String responseEntity = response.hasEntity() ? response.readEntity(String.class) : "";
if (response.getStatus() == Response.Status.PRECONDITION_FAILED.getStatusCode()) {
String logMsg = LRALogger.i18nLogger.error_tooLateToJoin(lraId, responseEntity);
LRALogger.logger.error(logMsg);
throw new WebApplicationException(logMsg,
Response.status(PRECONDITION_FAILED).entity(logMsg).build());
} else if (response.getStatus() == NOT_FOUND.getStatusCode()) {
String logMsg = LRALogger.i18nLogger.info_failedToEnlistingLRANotFound(
lraId, coordinatorUrl, NOT_FOUND.getStatusCode(), NOT_FOUND.getReasonPhrase(), GONE.getStatusCode(), GONE.getReasonPhrase());
LRALogger.logger.info(logMsg);
throw new WebApplicationException(logMsg);
} else if (response.getStatus() != OK.getStatusCode()) {
String logMsg = LRALogger.i18nLogger.error_failedToEnlist(lraId, coordinatorUrl, response.getStatus());
LRALogger.logger.error(logMsg);
throwGenericLRAException(uri, response.getStatus(), logMsg, null);
}
String recoveryUrl = null;
try {
recoveryUrl = response.getHeaderString(LRA_HTTP_RECOVERY_HEADER);
return new URI(recoveryUrl);
} catch (URISyntaxException e) {
LRALogger.logger.infof(e,"join %s returned an invalid recovery URI '%s': %s", lraId, recoveryUrl, responseEntity);
throwGenericLRAException(null, Response.Status.SERVICE_UNAVAILABLE.getStatusCode(),
"join " + lraId + " returned an invalid recovery URI '" + recoveryUrl + "' : " + responseEntity, e);
return null;
}
} catch (WebApplicationException webApplicationException) {
throw new WebApplicationException(uri.toASCIIString(), GONE); // not sure why we think it's gone TODO
} catch (InterruptedException | ExecutionException | TimeoutException e) {
throw new WebApplicationException("join LRA client request timed out, try again later",
Response.Status.SERVICE_UNAVAILABLE.getStatusCode());
}
} finally {
if (client != null) {
client.close();
}
}
}
private void endLRA(URI lra, boolean confirm) throws WebApplicationException {
Client client = null;
Response response = null;
lraTracef(lra, "%s LRA", confirm ? "close" : "compensate");
try {
client = getClient();
String lraUid = LRAConstants.getLRAUid(lra);
try {
response = client.target(coordinatorUrl)
.path(confirm ? String.format(CLOSE_PATH, lraUid) : String.format(CANCEL_PATH, lraUid))
.request()
.header(NARAYANA_LRA_API_VERSION_HEADER_NAME, LRAConstants.CURRENT_API_VERSION_STRING)
.async()
.put(Entity.text(""))
.get(END_TIMEOUT, TimeUnit.SECONDS);
} catch (InterruptedException | ExecutionException | TimeoutException e) {
throw new WebApplicationException("end LRA client request timed out, try again later",
Response.Status.SERVICE_UNAVAILABLE.getStatusCode());
}
if (isUnexpectedResponseStatus(response, OK, Response.Status.ACCEPTED, NOT_FOUND)) {
String warnMsg = LRALogger.i18nLogger.error_lraTerminationUnexpectedStatus(response.getStatus(),
response.hasEntity() ? response.readEntity(String.class) : "");
LRALogger.logger.warn(warnMsg);
throwGenericLRAException(lra, INTERNAL_SERVER_ERROR.getStatusCode(), warnMsg, null);
}
if (response.getStatus() == NOT_FOUND.getStatusCode()) {
String errorMsg = LRALogger.i18nLogger.get_couldNotCompleteCompensateOnReturnedStatus(
confirm ? "close" : "compensate", lra, coordinatorUrl, NOT_FOUND.getReasonPhrase());
LRALogger.logger.info(errorMsg);
throw new NotFoundException(errorMsg,
Response.status(NOT_FOUND).entity(lra.toASCIIString()).build());
}
} finally {
Current.pop(lra);
if (client != null) {
client.close();
}
}
}
private void validateURI(URI uri, boolean nullAllowed, String message) {
if (uri == null) {
if (!nullAllowed) {
throwGenericLRAException(null, NOT_ACCEPTABLE.getStatusCode(),
String.format(message, "null value"), null);
}
} else {
try {
// the passed in URI should be a valid URL - verify that that is the case
uri.toURL();
} catch (MalformedURLException mue) {
throwGenericLRAException(null, NOT_ACCEPTABLE.getStatusCode(),
String.format(message, mue.getClass().getName() + ":" + mue.getMessage()) + " uri=" + uri, mue);
}
}
}
private boolean isUnexpectedResponseStatus(Response response, Response.Status... expected) {
for (Response.Status anExpected : expected) {
if (response.getStatus() == anExpected.getStatusCode()) {
return false;
}
}
return true;
}
public String getCoordinatorUrl() {
return coordinatorUrl.toString();
}
public String getRecoveryUrl() {
return getCoordinatorUrl() + "/" + RECOVERY_COORDINATOR_PATH_NAME;
}
public URI getCurrent() {
return Current.peek();
}
private void lraTracef(String reasonFormat, Object... parameters) {
if (LRALogger.logger.isTraceEnabled()) {
LRALogger.logger.tracef(reasonFormat, parameters);
}
}
private void lraTrace(URI lra, String reason) {
if (LRALogger.logger.isTraceEnabled()) {
lraTracef(lra, reason, (Object[]) null);
}
}
private void lraTracef(URI lra, String reasonFormat, Object... parameters) {
if (LRALogger.logger.isTraceEnabled()) {
lraTracef(reasonFormat + ", lra id: %s", parameters, lra);
}
}
public void close() {
}
private void throwGenericLRAException(URI lraId, int statusCode, String message, Throwable cause) throws WebApplicationException {
String errorMsg = String.format("%s: %s", lraId, message);
throw new WebApplicationException(errorMsg, cause, Response.status(statusCode).entity(errorMsg).build());
}
private Client getClient() {
return ClientBuilder.newClient();
}
}
|
// -*- mode:java; encoding:utf-8 -*-
// vim:set fileencoding=utf-8:
// @homepage@
package example;
import java.awt.*;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import javax.swing.*;
public final class MainPanel extends JPanel {
private static final int MW = 300;
private static final int MH = 200;
private final JCheckBox checkbox = new JCheckBox("Fixed aspect ratio, Minimum size: " + MW + "*" + MH);
private MainPanel() {
super(new BorderLayout());
EventQueue.invokeLater(() -> {
Container c = getTopLevelAncestor();
if (c instanceof JFrame) {
JFrame frame = (JFrame) c;
frame.setMinimumSize(new Dimension(MW, MH)); // JDK 1.6.0
frame.addComponentListener(new ComponentAdapter() {
@Override public void componentResized(ComponentEvent e) {
initFrameSize(frame);
}
});
}
});
checkbox.addActionListener(e -> {
Container c = getTopLevelAncestor();
if (c instanceof JFrame) {
initFrameSize((JFrame) c);
}
});
// checkbox.setSelected(true);
JLabel label = new JLabel();
label.addComponentListener(new ComponentAdapter() {
@Override public void componentResized(ComponentEvent e) {
JLabel l = (JLabel) e.getComponent();
Container c = getTopLevelAncestor();
if (c instanceof JFrame) {
l.setText(c.getSize().toString());
}
}
});
Toolkit.getDefaultToolkit().setDynamicLayout(false);
JCheckBox check = new JCheckBox("Toolkit.getDefaultToolkit().setDynamicLayout: ");
check.addActionListener(e ->
Toolkit.getDefaultToolkit().setDynamicLayout(((JCheckBox) e.getSource()).isSelected()));
JPanel p = new JPanel(new GridLayout(2, 1));
p.add(checkbox);
p.add(check);
add(p, BorderLayout.NORTH);
add(label);
setPreferredSize(new Dimension(320, 240));
}
protected void initFrameSize(JFrame frame) {
if (!checkbox.isSelected()) {
return;
}
int fw = frame.getSize().width;
int fh = MH * fw / MW;
frame.setSize(Math.max(MW, fw), Math.max(MH, fh));
}
public static void main(String[] args) {
EventQueue.invokeLater(MainPanel::createAndShowGui);
}
private static void createAndShowGui() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
Toolkit.getDefaultToolkit().beep();
}
JFrame frame = new JFrame("@title@");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.getContentPane().add(new MainPanel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
|
package org.openhab.domain.rule;
import org.openhab.domain.IOpenHABWidgetControl;
import org.openhab.domain.user.AccessModifier;
import org.openhab.domain.util.StringHandler;
import org.openhab.domain.wear.IWearCommandHost;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
public class Rule implements OnOperandValueChangedListener {
public final static String ARG_RULE_ID = "Rule ID";
private String mName;
protected RuleOperation mRuleOperation;
protected Map<String, RuleOperation> mRuleOperationDataSourceIdMap;
protected List<RuleAction> mActions;//OpenHABNFCActionList, Intent writeTagIntent
protected boolean mEnabled;
protected AccessModifier mAccessModifier;
protected UUID mRuleId;
private final IOpenHABWidgetControl mOpenHABWidgetControl;
private final IWearCommandHost mWearCommandHost;
public Rule(IOpenHABWidgetControl widgetControl, IWearCommandHost wearCommandHost) {
this("New Rule", widgetControl, wearCommandHost);
}
public Rule(String name, IOpenHABWidgetControl widgetControl, IWearCommandHost wearCommandHost) {
mOpenHABWidgetControl = widgetControl;
mWearCommandHost = wearCommandHost;
setRuleId(UUID.randomUUID());
setName(name);
mActions = new ArrayList<RuleAction>();
mRuleOperationDataSourceIdMap = new HashMap<String, RuleOperation>();
}
public RuleOperation getRuleOperation() {
return mRuleOperation;
}
public void setRuleOperation(RuleOperation ruleOperation) {
mRuleOperation = ruleOperation;
if(mRuleOperation != null) {
((IRuleOperationOperand) mRuleOperation).setOnOperandValueChangedListener(this);
getRuleOperation().runCalculation();
}
}
public String getName() {
return mName;
}
public void setName(String name) {
mName = name;
if(mRuleOperation != null)
mRuleOperation.setName(name);
}
@Override
public String toString() {
if(mRuleOperation == null)
return "<Missing operation>";//TODO - TA: Language independent
StringBuilder result = new StringBuilder();
if(!mRuleOperation.isValid())
result.append("<Invalid operation> ");//TODO - TA: Language independent
else
result.append("[" + mRuleOperation.getFormattedString() + "] ");
if(!StringHandler.isNullOrEmpty(getName())) {
result.append(getName());
} else {
result.append(mRuleOperation.toString());
}
return result.toString();
}
public void setEnabled(boolean value) {
mEnabled = value;
}
public boolean isEnabled() {
return mEnabled;
}
@Override
public void onOperandValueChanged(IEntityDataType operand) {
if(!mEnabled)
return;
for(RuleAction action : mActions) {
if((action.getActionType() == RuleActionType.COMMAND && StringHandler.isNullOrEmpty(action.mTargetOpenHABItemName)) || StringHandler.isNullOrEmpty(action.getCommand()))
continue;
if(action.getActionType() == RuleActionType.COMMAND)
mOpenHABWidgetControl.sendItemCommand(action.getTargetOpenHABItemName(), action.getCommand());
else
mWearCommandHost.startSession("Rule Action", action.getTextValue());
}
}
public void addAction(RuleAction action) {
mActions.add(action);
if(getRuleOperation() != null)
getRuleOperation().runCalculation();
}
public List<RuleAction> getActions() {
return mActions;
}
public AccessModifier getAccess() {
return mAccessModifier;
}
public void setAccess(AccessModifier access) {
mAccessModifier = access;
}
public UUID getRuleId() {
return mRuleId;
}
public void setRuleId(UUID ruleId) {
mRuleId = ruleId;
}
}
|
package ghcvm.runtime.closure;
public class StgIndStatic extends StgClosure {
StgClosure indirectee;
public StgIndStatic(StgClosure indirectee) {
this.indirectee = indirectee;
}
@Override
public void enter(StgContext context) {
indirectee.enter(context);
}
}
|
package org.yakindu.sct.model.sexec.interpreter.test;
import static org.junit.Assert.*;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.impl.EcoreFactoryImpl;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.yakindu.sct.model.sexec.interpreter.stext.CoreFunction;
/**
*
* @author florian antony
*
*/
public class CoreFunctionTest {
private static CoreFunction cFunction;
private static double delta;
private static EObject obj1;
private static EObject obj2;
@BeforeClass
public static void beforeClass() throws Exception {
cFunction = new CoreFunction();
delta = 0.001;
}
@Before
public void setUp() throws Exception {
cFunction = new CoreFunction();
obj1 = EcoreFactoryImpl.eINSTANCE.createEObject();
obj2 = obj1;
}
@After
public void tearDown() throws Exception {
cFunction = null;
}
@Test
public void testPlusIntegerInteger() {
int expected = 10;
int actual = cFunction.plus(5, 5);
assertEquals("testPlusIntegerInteger faild", expected, actual);
}
@Test
public void testPlusFloatFloat() {
float expected = 10.6F;
float actual = cFunction.plus(5.3F, 5.3F);
assertEquals("testFloatFloat faild", expected, actual, delta);
}
@Test
public void testPlusDoubleDouble() {
double expected = 10.6;
double actual = cFunction.plus(5.3, 5.3);
assertEquals("testPlusDoubleDouble faild", expected, actual, delta);
}
@Test
public void testPlusLongLong() {
long expected = 10;
long actual = cFunction.plus(5L, 5L);
assertEquals("testPlusLongLong faild", expected, actual);
}
@Test
public void testPlusIntegerFloat() {
float expected = 10.3F;
float actual = cFunction.plus(5, 5.3F);
assertEquals("testPlusIntegerFloat faild", expected, actual, delta);
}
@Test
public void testPlusIntegerDouble() {
double expected = 10.3;
double actual = cFunction.plus(5, 5.3);
assertEquals("testPlusIntegerDouble faild", expected, actual, delta);
}
@Test
public void testPlusIntegerLong() {
long expected = 10;
long actual = cFunction.plus(5, 5L);
assertEquals("testPlusIntegerLong faild", expected, actual);
}
@Test
public void testPlusFloatInteger() {
float expected = 10.3F;
float actual = cFunction.plus(5.3F, 5);
assertEquals("testPlusFloatInteger faild", expected, actual, delta);
}
@Test
public void testPlusFloatDouble() {
double expected = 10.6;
double actual = cFunction.plus(5.3F, 5.3);
assertEquals("testPlusFloatDouble faild", expected, actual, delta);
}
@Test
public void testPlusDoubleInteger() {
double expected = 10.6;
double actual = cFunction.plus(5.6, 5);
assertEquals("testPlusDoubleInteger faild", expected, actual, delta);
}
@Test
public void testPlusDoubleFloat() {
double expected = 10.6;
double actual = cFunction.plus(5.3F, 5.3);
assertEquals("testPlusDoubleFloat faild", expected, actual, delta);
}
@Test
public void testPlusDoubleLong() {
double expected = 10.3;
double actual = cFunction.plus(5.3, 5L);
assertEquals("testPlusDoublelong faild", expected, actual, delta);
}
@Test
public void testPlusLongInteger() {
long expected = 10;
long actual = cFunction.plus(5L, 5);
assertEquals("testPlusLongInteger faild", expected, actual);
}
@Test
public void testPositiveInteger() {
int expected = 10;
int actual = cFunction.positive(10);
assertEquals("testPositiveInteger faild", expected, actual);
}
@Test
public void testPositiveFloat() {
float expected = 10.3F;
float actual = cFunction.positive(10.3F);
assertEquals("testPositiveFloat faild", expected, actual, delta);
}
@Test
public void testPositiveLong() {
long expected = 10;
long actual = cFunction.positive(10);
assertEquals("testPositiveLong faild", expected, actual);
}
@Test
public void testPositiveDouble() {
double expected = 10.3;
double actual = cFunction.positive(10.3);
assertEquals("testPositiveDouble faild", expected, actual, delta);
}
@Test
public void testPositiveBoolean() {
boolean expected = true;
boolean actual = cFunction.positive(true);
assertEquals("testPositiveBoolean faild", expected, actual);
}
@Test
public void testPositiveString() {
String expected = "positive";
String actual = cFunction.positive("positive");
assertEquals("testPositiveString faild", expected, actual);
}
@Test
public void testNegativeInteger() {
int expected = -10;
int actual = cFunction.negative(10);
assertEquals("testNegativeInteger faild", expected, actual);
}
@Test
public void testNegativeFloat() {
float expected = -10.3F;
float actual = cFunction.negative(10.3F);
assertEquals("testPositiveFloat faild", expected, actual, delta);
}
@Test
public void testNegativeDouble() {
double expected = -10.3;
double actual = cFunction.negative(10.3);
assertEquals("testPositiveDouble faild", expected, actual, delta);
}
@Test
public void testNegativeLong() {
long expected = 10L;
long actual = cFunction.negative(-10L);
assertEquals("testPositiveLong faild", expected, actual);
}
@Test
public void testMinusIntegerInteger() {
int expected = 5;
int actual = cFunction.minus(10, 5);
assertEquals("testMinusIntegerInteger faild", expected, actual);
}
@Test
public void testMinusFloatFloat() {
float expected = 5.3F;
float actual = cFunction.minus(10.3F, 5.0F);
assertEquals("testMinusFloatFloat faild", expected, actual, delta);
}
@Test
public void testMinusDoubleDouble() {
double expected = 5.3;
double actual = cFunction.minus(10.6, 5.3);
assertEquals("testMinusDoubleDouble faild", expected, actual, delta);
}
@Test
public void testMinusLongLong() {
long expected = 5L;
long actual = cFunction.minus(10L, 5L);
assertEquals("testMinusLongLong faild", expected, actual, delta);
}
@Test
public void testMinusIntegerFloat() {
float expected = 4.7F;
float actual = cFunction.minus(10, 5.3F);
assertEquals("testMinusIntegerFloat faild", expected, actual, delta);
}
@Test
public void testMinusIntegerDouble() {
double expected = 4.7;
double actual = cFunction.minus(10, 5.3F);
assertEquals("testMinusFloatDouble faild", expected, actual, delta);
}
@Test
public void testMinusIntegerLong() {
long expected = 5L;
long actual = cFunction.minus(10, 5L);
assertEquals("testMinusIntegerLong faild", expected, actual, delta);
}
@Test
public void testMinusFloatInteger() {
float expected = 5.3F;
float actual = cFunction.minus(10.3F, 5);
assertEquals("testMinusFloatInteger faild", expected, actual, delta);
}
@Test
public void testMinusFloatDouble() {
double expected = 5.0;
double actual = cFunction.minus(10.3, 5.3F);
assertEquals("testMinusFloatDouble faild", expected, actual, delta);
}
@Test
public void testMinusDoubleInteger() {
double expected = 5.3;
double actual = cFunction.minus(10.3, 5);
assertEquals("testMinusDoubleInteger faild", expected, actual, delta);
}
@Test
public void testMinusDoubleFloat() {
double expected = 5.0;
double actual = cFunction.minus(10.3, 5.3F);
assertEquals("testMinusDoubleFloat faild", expected, actual, delta);
}
@Test
public void testMinusDoubleLong() {
double expected = 5.3;
double actual = cFunction.minus(10.3, 5L);
assertEquals("testMinusDoubleLong faild", expected, actual, delta);
}
@Test
public void testMinusLongInteger() {
long expected = 5L;
long actual = cFunction.minus(10L, 5);
assertEquals("testMinusLongInteger faild", expected, actual);
}
@Test
public void testMulIntegerInteger() {
int expected = 25;
int actual = cFunction.mul(5, 5);
assertEquals("testMulIntegerInteger faild", expected, actual);
}
@Test
public void testMulFloatFloat() {
float expected = 25.0F;
float actual = cFunction.mul(5.0F, 5.0F);
assertEquals("testMulFloatFloat faild", expected, actual, delta);
}
@Test
public void testMulDoubleDouble() {
double expected = 25.0;
double actual = cFunction.mul(5.0, 5.0);
assertEquals("testMulDoubleDouble faild", expected, actual, delta);
}
@Test
public void testMulLongLong() {
long expected = 25L;
long actual = cFunction.mul(5L, 5L);
assertEquals("testMulLongLong faild", expected, actual);
}
@Test
public void testMulIntegerFloat() {
float expected = 25.0F;
float actual = cFunction.mul(5, 5.0F);
assertEquals("testMulIntegerFloat faild", expected, actual, delta);
}
@Test
public void testMulIntegerDouble() {
double expected = 25.0;
double actual = cFunction.mul(5, 5.0F);
assertEquals("testMulIntegerDouble faild", expected, actual, delta);
}
@Test
public void testMulIntegerLong() {
long expected = 25L;
long actual = cFunction.mul(5, 5L);
assertEquals("testMulIntegerLong faild", expected, actual);
}
@Test
public void testMulFloatInteger() {
float expected = 25.0F;
float actual = cFunction.mul(5.0F, 5);
assertEquals("testMulFlatInteger faild", expected, actual, delta);
}
@Test
public void testMulFloatDouble() {
double expected = 25.0;
double actual = cFunction.mul(5.0F, 5.0);
assertEquals("testMulFloatDouble faild", expected, actual, delta);
}
@Test
public void testMulDoubleInteger() {
double expected = 25.0;
double actual = cFunction.mul(5.0, 5);
assertEquals("testMulDoubleInteger faild", expected, actual, delta);
}
@Test
public void testMulDoubleFloat() {
double expected = 25.0;
double actual = cFunction.mul(5.0, 5.0F);
assertEquals("testMulDoubleDouble faild", expected, actual, delta);
}
@Test
public void testMulDoubleLong() {
double expected = 25.0;
double actual = cFunction.mul(5.0, 5L);
assertEquals("testMuldoubleLong faild", expected, actual, delta);
}
@Test
public void testMulLongInteger() {
long expected = 25L;
long actual = cFunction.mul(5L, 5);
assertEquals("testMulLongInteger faild", expected, actual);
}
@Test
public void testDivIntegerInteger() {
int expected = 5;
int actual = cFunction.div(25, 5);
assertEquals("testDivIntegerInteger faild", expected, actual);
}
@Test
public void testDivFloatFloat() {
float expected = 5.0F;
float actual = cFunction.div(25.0F, 5.0F);
assertEquals("testDivFloatFloat faild", expected, actual, delta);
}
@Test
public void testDivDoubleDouble() {
double expected = 5.0;
double actual = cFunction.div(25.0, 5.0);
assertEquals("testDivDoubleDouble faild", expected, actual, delta);
}
@Test
public void testDivLongLong() {
long expected = 5L;
long actual = cFunction.div(25L, 5L);
assertEquals("testDivLongLong faild", expected, actual);
}
@Test
public void testDivIntegerFloat() {
float expected = 5.0F;
float actual = cFunction.div(25, 5.0F);
assertEquals("testDivIntegerFloat faild", expected, actual, delta);
}
@Test
public void testDivIntegerDouble() {
double expected = 5.0;
double actual = cFunction.div(25, 5.0F);
assertEquals("testDivFloatDouble faild", expected, actual, delta);
}
@Test
public void testDivIntegerLong() {
long expected = 5L;
long actual = cFunction.div(25, 5L);
assertEquals("testDivIntegerLong faild", expected, actual);
}
@Test
public void testDivFloatInteger() {
float expected = 5.0F;
float actual = cFunction.div(25.0F, 5);
assertEquals("testDivFloatInteger faild", expected, actual, delta);
}
@Test
public void testDivFloatDouble() {
double expected = 5.0;
double actual = cFunction.div(25.0F, 5.0);
assertEquals("testDivFloatDouble faild", expected, actual, delta);
}
@Test
public void testDivDoubleInteger() {
double expected = 5.0;
double actual = cFunction.div(25.0, 5);
assertEquals("testDivDoubleInteger faild", expected, actual, delta);
}
@Test
public void testDivDoubleFloat() {
double expected = 5.0;
double actual = cFunction.div(25.0, 5.0F);
assertEquals("testDivDoublFloat faild", expected, actual, delta);
}
@Test
public void testDivDoubleLong() {
double expected = 5.0;
double actual = cFunction.div(25.0, 5L);
assertEquals("testDivDoubleLong faild", expected, actual, delta);
}
@Test
public void testDivLongInteger() {
long expected = 5L;
long actual = cFunction.div(25L, 5);
assertEquals("testDivLongInteger faild", expected, actual, delta);
}
@Test
public void testModIntegerInteger() {
int expected = 0;
int actual = cFunction.mod(5, 5);
assertEquals("testModIntegerInteger faild", expected, actual);
}
@Test
public void testModFloatFloat() {
float expected = 0.0F;
float actual = cFunction.mod(5.0F, 5.0F);
assertEquals("testModFloatFloat faild", expected, actual, delta);
}
@Test
public void testModDoubleDouble() {
double expected = 0.0;
double actual = cFunction.mod(5.0, 5.0);
assertEquals("testModDoubleDouble faild", expected, actual, delta);
}
@Test
public void testModLongLong() {
long expected = 0L;
long actual = cFunction.mod(5L, 5L);
assertEquals("testModLongLong faild", expected, actual);
}
@Test
public void testModIntegerFloat() {
float expected = 0.0F;
float actual = cFunction.mod(5, 5.0F);
assertEquals("testModIntegerFloat faild", expected, actual, delta);
}
@Test
public void testModIntegerDouble() {
double expected = 0.0;
double actual = cFunction.mod(5, 5.0);
assertEquals("testModIntegerDouble faild", expected, actual, delta);
}
@Test
public void testModIntegerLong() {
long expected = 0L;
long actual = cFunction.mod(5, 5L);
assertEquals("testModIntegerLong faild", expected, actual);
}
@Test
public void testModFloatInteger() {
float expected = 0.0F;
float actual = cFunction.mod(5.0F, 5);
assertEquals("testModDFloatInteger faild", expected, actual, delta);
}
@Test
public void testModFloatDouble() {
double expected = 0.0;
double actual = cFunction.mod(5.0F, 5.0);
assertEquals("testModFloatDouble faild", expected, actual, delta);
}
@Test
public void testModDoubleInteger() {
double expected = 0.0;
double actual = cFunction.mod(5.0, 5);
assertEquals("testModDoubleInteger faild", expected, actual, delta);
}
@Test
public void testModDoubleFloat() {
double expected = 0.0;
double actual = cFunction.mod(5.0, 5.0);
assertEquals("testModDoubleDouble faild", expected, actual, delta);
}
@Test
public void testModDoubleLong() {
double expected = 0.0;
double actual = cFunction.mod(5.0, 5L);
assertEquals("testModDoubleLong faild", expected, actual, delta);
}
@Test
public void testModLongInteger() {
long expected = 0L;
double actual = cFunction.mod(5L, 5);
assertEquals("testModLongInteger faild", expected, actual, delta);
}
@Test
public void testLeft() {
int expected = 20;
int actual = cFunction.left(10, 1);
assertEquals("testLeftIntegerInteger faild", expected, actual);
}
@Test
public void testRight() {
int expected = 5;
int actual = cFunction.right(10, 1);
assertEquals("testRightIntegerInteger faild", expected, actual);
}
@Test
public void testBitwiseAnd() {
int expected = 0;
int actual = cFunction.bitwiseAnd(5, 2);
assertEquals("testBitwiseANDntegerInteger faild", expected, actual);
}
@Test
public void testBitwiseOr() {
int expected = 7;
int actual = cFunction.bitwiseOr(5, 2);
assertEquals("testBitwiseORntegerInteger faild", expected, actual);
}
@Test
public void testBitwiseXorIntegerInteger() {
int expected = 6;
int actual = cFunction.bitwiseXor(5, 3);
assertEquals("testBitwiseXORIntegerInteger faild", expected, actual);
}
@Test
public void testBitwiseXorLongLong() {
long expected = 6L;
long actual = cFunction.bitwiseXor(5L, 3L);
assertEquals("testBitwiseXORLongLong faild", expected, actual);
}
@Test
public void testEqualsBooleanBoolean() {
boolean expected = false;
boolean actual = cFunction.equals(true, false);
assertEquals("testEqualsBooleanBoolean faild", expected, actual);
}
@Test
public void testEqualsEObjectEObject() {
boolean expected = true;
boolean actual = cFunction.equals(obj1, obj2);
assertEquals("testEqualsEObjectEObject faild", expected, actual);
}
@Test
public void testEqualsStringString() {
boolean expected = true;
String test = "test";
boolean actual = cFunction.equals(test, "test");
assertEquals("testEqualsStringString faild", expected, actual);
}
@Test
public void testEqualsIntegerInteger() {
boolean expected = true;
boolean actual = cFunction.equals(1, 1);
assertEquals("testEqualsIntegerInteger faild", expected, actual);
}
@Test
public void testEqualsFloatFloat() {
boolean expected = true;
boolean actual = cFunction.equals(1.5F, 1.5F);
assertEquals("testEqualsloatFloat faild", expected, actual);
}
@Test
public void testEqualsDoubleDouble() {
boolean expected = true;
boolean actual = cFunction.equals(1.5, 1.5);
assertEquals("testEqualsDoubleDouble faild", expected, actual);
}
@Test
public void testEqualsLongLong() {
boolean expected = true;
boolean actual = cFunction.equals(10L, 10L);
assertEquals("testEqualsLongLong faild", expected, actual);
}
@Test
public void testEqualsIntegerFloat() {
boolean expected = true;
boolean actual = cFunction.equals(1, 1.0F);
assertEquals("testEqualsIntegerFloat faild", expected, actual);
}
@Test
public void testEqualsIntegerDouble() {
boolean expected = true;
boolean actual = cFunction.equals(1, 1.0);
assertEquals("testEqualsIntegerDouble faild", expected, actual);
}
@Test
public void testEqualsIntegerLong() {
boolean expected = true;
boolean actual = cFunction.equals(1, 1L);
assertEquals("testEqualsIntegerLong faild", expected, actual);
}
@Test
public void testEqualsFloatInteger() {
boolean expected = true;
boolean actual = cFunction.equals(1.0F, 1);
assertEquals("testEqualsFloatInteger faild", expected, actual);
}
@Test
public void testEqualsFloatDouble() {
assertTrue( cFunction.equals(1.0F, 1.0));
assertTrue( cFunction.equals(1.5F, 1.5));
assertFalse( cFunction.equals(1.3F, 1.3));
}
@Test
public void testEqualsDoubleInteger() {
boolean expected = true;
boolean actual = cFunction.equals(1.0, 1);
assertEquals("testEqualsDoubleInteger faild", expected, actual);
}
@Test
public void testEqualsDoubleFloat() {
boolean expected = true;
boolean actual = cFunction.equals(1.5, 1.5F);
assertEquals("testEqualsDoubleFloat faild", expected, actual);
}
@Test
public void testEqualsDoubleLong() {
boolean expected = true;
boolean actual = cFunction.equals(1.0, 1L);
assertEquals("testEqualsDoubleLong faild", expected, actual);
}
@Test
public void testEqualsLongInteger() {
boolean expected = true;
boolean actual = cFunction.equals(1L, 1);
assertEquals("testEqualsLongInteger faild", expected, actual);
}
@Test
public void testNotEqualsEObjectEObject() {
boolean expected = false;
boolean actual = cFunction.notEquals(obj1, EcoreFactoryImpl.eINSTANCE.createEObject());
assertEquals(expected, actual);
}
@Test
public void testNotEqualsBooleanBoolean() {
boolean expected = true;
boolean actual = cFunction.notEquals(true, false);
assertEquals("testNotEqualsBooleanBoolean faild", expected, actual);
}
@Test
public void testNotEqualsStringString() {
boolean expected = true;
boolean actual = cFunction.notEquals("Hans", "Wurst");
assertEquals("testNotEqualsStringString faild", expected, actual);
}
@Test
public void testNotEqualsIntegerInteger() {
boolean expected = true;
boolean actual = cFunction.notEquals(1, 2);
assertEquals("testNotEqualsIntegerInteger faild", expected, actual);
}
@Test
public void testNotEqualsFloatFloat() {
boolean expected = true;
boolean actual = cFunction.notEquals(1.2F, 1.3F);
assertEquals("testNotEqualsFloatFloat faild", expected, actual);
}
@Test
public void testNotEqualsDoubleDouble() {
boolean expected = true;
boolean actual = cFunction.notEquals(1.2, 1.3);
assertEquals("testNotEqualsDoubleDouble faild", expected, actual);
}
@Test
public void testNotEqualsLongLong() {
boolean expected = true;
boolean actual = cFunction.notEquals(1L, 2L);
assertEquals("testNotEqualsLongLong faild", expected, actual);
}
@Test
public void testNotEqualsIntegerFloat() {
boolean expected = true;
boolean actual = cFunction.notEquals(1, 1.1F);
assertEquals("testNotEqualsIntegerFloat faild", expected, actual);
}
@Test
public void testNotEqualsIntegerDouble() {
boolean expected = true;
boolean actual = cFunction.notEquals(1, 1.1);
assertEquals("testNotEqualsIntegerDouble faild", expected, actual);
}
@Test
public void testNotEqualsIntegerLong() {
boolean expected = true;
boolean actual = cFunction.notEquals(1, 2L);
assertEquals("testNotEqualsIntegerLong faild", expected, actual);
}
@Test
public void testNotEqualsFloatInteger() {
boolean expected = true;
boolean actual = cFunction.notEquals(1.1F, 1);
assertEquals("testNotEqualsFloatInteger faild", expected, actual);
}
@Test
public void testNotEqualsFloatDouble() {
boolean expected = true;
boolean actual = cFunction.notEquals(1.01F, 1.02);
assertEquals("testNotEqualsFloatDouble faild", expected, actual);
}
@Test
public void testNotEqualsDoubleInteger() {
boolean expected = true;
boolean actual = cFunction.notEquals(1.01, 1);
assertEquals("testNotEqualsDoubleinteger faild", expected, actual);
}
@Test
public void testNotEqualsDoubleFloat() {
boolean expected = true;
boolean actual = cFunction.notEquals(1.01, 1.02F);
assertEquals("testNotEqualsDoubleFloat faild", expected, actual);
}
@Test
public void testNotEqualsDoubleLong() {
boolean expected = true;
boolean actual = cFunction.notEquals(1.01, 1L);
assertEquals("testNotEqualsDoubleLong faild", expected, actual);
}
@Test
public void testNotEqualsLongInteger() {
boolean expected = true;
boolean actual = cFunction.notEquals(1L, 2);
assertEquals("testNotEqualsLongInteger faild", expected, actual);
}
@Test
public void testGreaterEqualIntegerInteger() {
boolean expected = true;
boolean actual = cFunction.greaterEqual(1, 1);
assertEquals(expected, actual);
expected = true;
actual = cFunction.greaterEqual(2, 1);
assertEquals(expected, actual);
expected = false;
actual = cFunction.greaterEqual(1, 2);
assertEquals(expected, actual);
}
@Test
public void testGreaterEqualFloatFloat() {
boolean expected = true;
boolean actual = cFunction.greaterEqual(1.0F, 1.0F);
assertEquals(expected, actual);
expected = true;
actual = cFunction.greaterEqual(1.1F, 1F);
assertEquals(expected, actual);
expected = false;
actual = cFunction.greaterEqual(1F, 1.1F);
assertEquals(expected, actual);
}
@Test
public void testGreaterEqualDoubleDouble() {
boolean expected = true;
boolean actual = cFunction.greaterEqual(1.0, 1.0);
assertEquals(expected, actual);
expected = true;
actual = cFunction.greaterEqual(1.1, 1);
assertEquals(expected, actual);
expected = false;
actual = cFunction.greaterEqual(1, 1.1);
assertEquals(expected, actual);
}
@Test
public void testGreaterEqualLongLong() {
boolean expected = true;
boolean actual = cFunction.greaterEqual(1L, 1L);
assertEquals(expected, actual);
expected = true;
actual = cFunction.greaterEqual(2L, 1L);
assertEquals(expected, actual);
expected = false;
actual = cFunction.greaterEqual(1L, 2L);
assertEquals(expected, actual);
}
@Test
public void testGreaterEqualIntegerFloat() {
boolean expected = true;
boolean actual = cFunction.greaterEqual(1, 1.0F);
assertEquals(expected, actual);
expected = true;
actual = cFunction.greaterEqual(2, 1.0F);
assertEquals(expected, actual);
expected = false;
actual = cFunction.greaterEqual(1, 1.1F);
assertEquals(expected, actual);
}
@Test
public void testGreaterEqualIntegerDouble() {
boolean expected = true;
boolean actual = cFunction.greaterEqual(1, 1.0);
assertEquals(expected, actual);
expected = true;
actual = cFunction.greaterEqual(2, 1.0);
assertEquals(expected, actual);
expected = false;
actual = cFunction.greaterEqual(1, 1.1);
assertEquals(expected, actual);
}
@Test
public void testGreaterEqualIntegerLong() {
boolean expected = true;
boolean actual = cFunction.greaterEqual(1, 1L);
assertEquals(expected, actual);
expected = true;
actual = cFunction.greaterEqual(2, 1L);
assertEquals(expected, actual);
expected = false;
actual = cFunction.greaterEqual(1, 2L);
assertEquals(expected, actual);
}
@Test
public void testGreaterEqualFloatInteger() {
boolean expected = true;
boolean actual = cFunction.greaterEqual(1.0F, 1);
assertEquals(expected, actual);
expected = true;
actual = cFunction.greaterEqual(2.0F, 1);
assertEquals(expected, actual);
expected = false;
actual = cFunction.greaterEqual(1.0F, 2);
assertEquals(expected, actual);
}
@Test
public void testGreaterEqualFloatDouble() {
boolean expected = true;
boolean actual = cFunction.greaterEqual(1.0, 1.0F);
assertEquals(expected, actual);
expected = true;
actual = cFunction.greaterEqual(2.0, 1.0F);
assertEquals(expected, actual);
expected = false;
actual = cFunction.greaterEqual(1.0, 1.1F);
assertEquals(expected, actual);
}
@Test
public void testGreaterEqualDoubleInteger() {
boolean expected = true;
boolean actual = cFunction.greaterEqual(1.0, 1);
assertEquals(expected, actual);
expected = true;
actual = cFunction.greaterEqual(1.1, 1);
assertEquals(expected, actual);
expected = false;
actual = cFunction.greaterEqual(1, 1.2);
assertEquals(expected, actual);
}
@Test
public void testGreaterEqualDoubleFloat() {
boolean expected = true;
boolean actual = cFunction.greaterEqual(1.0, 1.0F);
assertEquals(expected, actual);
expected = true;
actual = cFunction.greaterEqual(2.0, 1.0F);
assertEquals(expected, actual);
expected = false;
actual = cFunction.greaterEqual(1.0, 1.1F);
assertEquals(expected, actual);
}
@Test
public void testGreaterEqualDoubleLong() {
boolean expected = true;
boolean actual = cFunction.greaterEqual(1.0, 1L);
assertEquals(expected, actual);
expected = true;
actual = cFunction.greaterEqual(1.1, 1L);
assertEquals(expected, actual);
expected = false;
actual = cFunction.greaterEqual(0.9, 1L);
assertEquals(expected, actual);
}
@Test
public void testGreaterEqualLongInteger() {
boolean expected = true;
boolean actual = cFunction.greaterEqual(1L, 1);
assertEquals(expected, actual);
expected = true;
actual = cFunction.greaterEqual(2L, 1);
assertEquals(expected, actual);
expected = false;
actual = cFunction.greaterEqual(1L, 2);
assertEquals(expected, actual);
}
@Test
public void testSmallerEqualIntegerInteger() {
boolean expected = true;
boolean actual = cFunction.smallerEqual(1, 1);
assertEquals(expected, actual);
expected = true;
actual = cFunction.smallerEqual(1, 2);
assertEquals(expected, actual);
expected = false;
actual = cFunction.smallerEqual(2, 1);
assertEquals(expected, actual);
}
@Test
public void testSmallerEqualFloatFloat() {
boolean expected = true;
boolean actual = cFunction.smallerEqual(1.0F, 1.0F);
assertEquals(expected, actual);
expected = true;
actual = cFunction.smallerEqual(1.0F, 1.1F);
assertEquals(expected, actual);
expected = false;
actual = cFunction.smallerEqual(1.1F, 1.0F);
assertEquals(expected, actual);
}
@Test
public void testSmallerEqualDoubleDouble() {
boolean expected = true;
boolean actual = cFunction.smallerEqual(1.1, 1.1);
assertEquals(expected, actual);
expected = true;
actual = cFunction.smallerEqual(1.1, 1.2);
assertEquals(expected, actual);
expected = false;
actual = cFunction.smallerEqual(1.2, 1.1);
assertEquals(expected, actual);
}
@Test
public void testSmallerEqualLongLong() {
boolean expected = true;
boolean actual = cFunction.smallerEqual(1L, 1L);
assertEquals(expected, actual);
expected = true;
actual = cFunction.smallerEqual(1L, 2L);
assertEquals(expected, actual);
expected = false;
actual = cFunction.smallerEqual(2L, 1L);
assertEquals(expected, actual);
}
@Test
public void testSmallerEqualIntegerFloat() {
boolean expected = true;
boolean actual = cFunction.smallerEqual(1, 1.0F);
assertEquals(expected, actual);
expected = true;
actual = cFunction.smallerEqual(1, 1.2F);
assertEquals(expected, actual);
expected = false;
actual = cFunction.smallerEqual(1, 0.9F);
assertEquals(expected, actual);
}
@Test
public void testSmallerEqualIntegerDouble() {
boolean expected = true;
boolean actual = cFunction.smallerEqual(1, 1.1);
assertEquals(expected, actual);
expected = true;
actual = cFunction.smallerEqual(1, 1.2);
assertEquals(expected, actual);
expected = false;
actual = cFunction.smallerEqual(2, 1.9);
assertEquals(expected, actual);
}
@Test
public void testSmallerEqualIntegerLong() {
boolean expected = true;
boolean actual = cFunction.smallerEqual(1, 1L);
assertEquals(expected, actual);
expected = true;
actual = cFunction.smallerEqual(1, 2L);
assertEquals(expected, actual);
expected = false;
actual = cFunction.smallerEqual(2, 1L);
assertEquals(expected, actual);
}
@Test
public void testSmallerEqualFloatInteger() {
boolean expected = true;
boolean actual = cFunction.smallerEqual(1.0F, 1);
assertEquals(expected, actual);
expected = true;
actual = cFunction.smallerEqual(1.0F, 1);
assertEquals(expected, actual);
expected = false;
actual = cFunction.smallerEqual(1.2F, 1);
assertEquals(expected, actual);
}
@Test
public void testSmallerEqualFloatDouble() {
assertTrue( cFunction.smallerEqual(1.0F, 1.0));
assertTrue( cFunction.smallerEqual(1.5F, 1.5));
assertTrue( cFunction.smallerEqual(1.1F, 1.2));
assertFalse( cFunction.smallerEqual(1.2F, 1.2));
assertFalse( cFunction.smallerEqual(1.2F, 1.1));
}
@Test
public void testSmallerEqualDoubleInteger() {
boolean expected = true;
boolean actual = cFunction.smallerEqual(1.0, 1);
assertEquals(expected, actual);
expected = true;
actual = cFunction.smallerEqual(0.9, 1);
assertEquals(expected, actual);
expected = false;
actual = cFunction.smallerEqual(1.1, 1);
assertEquals(expected, actual);
}
@Test
public void testSmallerEqualDoubleFloat() {
boolean expected = true;
boolean actual = cFunction.smallerEqual(1.1, 1.1);
assertEquals(expected, actual);
expected = true;
actual = cFunction.smallerEqual(1.1, 1.2);
assertEquals(expected, actual);
expected = false;
actual = cFunction.smallerEqual(1.2, 1.1);
assertEquals(expected, actual);
}
@Test
public void testSmallerEqualDoubleLong() {
boolean expected = true;
boolean actual = cFunction.smallerEqual(1.0, 1L);
assertEquals(expected, actual);
expected = true;
actual = cFunction.smallerEqual(0.9, 1L);
assertEquals(expected, actual);
expected = false;
actual = cFunction.smallerEqual(1.1, 1L);
assertEquals(expected, actual);
}
@Test
public void testSmallerEqualLongInteger() {
boolean expected = true;
boolean actual = cFunction.smallerEqual(1L, 1);
assertEquals(expected, actual);
expected = true;
actual = cFunction.smallerEqual(1L, 2);
assertEquals(expected, actual);
expected = false;
actual = cFunction.smallerEqual(2L, 1);
assertEquals(expected, actual);
}
@Test
public void testGreaterIntegerInteger() {
boolean expected = false;
boolean actual = cFunction.greater(1, 1);
assertEquals(expected, actual);
expected = true;
actual = cFunction.greater(2, 1);
assertEquals(expected, actual);
expected = false;
actual = cFunction.greater(1, 2);
assertEquals(expected, actual);
}
@Test
public void testGreaterFloatFloat() {
boolean expected = false;
boolean actual = cFunction.greater(1.0F, 1.0F);
assertEquals(expected, actual);
expected = true;
actual = cFunction.greater(1.1F, 1.0F);
assertEquals(expected, actual);
expected = false;
actual = cFunction.greater(1.0F, 1.1F);
assertEquals(expected, actual);
}
@Test
public void testGreaterDoubleDouble() {
boolean expected = false;
boolean actual = cFunction.greater(1.0, 1.0);
assertEquals(expected, actual);
expected = true;
actual = cFunction.greater(1.1, 1.0);
assertEquals(expected, actual);
expected = false;
actual = cFunction.greater(1.0, 1.1);
assertEquals(expected, actual);
}
@Test
public void testGreaterLongLong() {
boolean expected = false;
boolean actual = cFunction.greater(1L, 1L);
assertEquals(expected, actual);
expected = true;
actual = cFunction.greater(2L, 1L);
assertEquals(expected, actual);
expected = false;
actual = cFunction.greater(1L, 2L);
assertEquals(expected, actual);
}
@Test
public void testGreaterIntegerFloat() {
boolean expected = false;
boolean actual = cFunction.greater(1, 1.0F);
assertEquals(expected, actual);
expected = true;
actual = cFunction.greater(1, 0.9F);
assertEquals(expected, actual);
expected = false;
actual = cFunction.greater(1, 1.1F);
assertEquals(expected, actual);
}
@Test
public void testGreaterIntegerDouble() {
boolean expected = false;
boolean actual = cFunction.greater(1, 1.0);
assertEquals(expected, actual);
expected = true;
actual = cFunction.greater(1, 0.9);
assertEquals(expected, actual);
expected = false;
actual = cFunction.greater(1, 1.1);
assertEquals(expected, actual);
}
@Test
public void testGreaterIntegerLong() {
boolean expected = false;
boolean actual = cFunction.greater(1, 1L);
assertEquals(expected, actual);
expected = true;
actual = cFunction.greater(2, 1L);
assertEquals(expected, actual);
expected = false;
actual = cFunction.greater(1L, 2L);
assertEquals(expected, actual);
}
@Test
public void testGreaterFloatInteger() {
boolean expected = false;
boolean actual = cFunction.greater(1.0F, 1);
assertEquals(expected, actual);
expected = true;
actual = cFunction.greater(1.1F, 1);
assertEquals(expected, actual);
expected = false;
actual = cFunction.greater(0.9F, 1);
assertEquals(expected, actual);
}
@Test
public void testGreaterFloatDouble() {
assertFalse(cFunction.greater(1.0F, 1.0));
assertTrue( cFunction.greater(1.1F, 1.0));
assertFalse(cFunction.greater(1.0F, 1.1));
}
@Test
public void testGreaterDoubleInteger() {
boolean expected = false;
boolean actual = cFunction.greater(1.0, 1);
assertEquals(expected, actual);
expected = true;
actual = cFunction.greater(1.1, 1);
assertEquals(expected, actual);
expected = false;
actual = cFunction.greater(0.9, 1);
assertEquals(expected, actual);
}
@Test
public void testGreaterDoubleFloat() {
boolean expected = false;
boolean actual = cFunction.greater(1.0, 1.0F);
assertEquals(expected, actual);
expected = true;
actual = cFunction.greater(1.1, 1.0F);
assertEquals(expected, actual);
expected = false;
actual = cFunction.greater(0.9, 1.0F);
assertEquals(expected, actual);
}
@Test
public void testGreaterDoubleLong() {
boolean expected = false;
boolean actual = cFunction.greater(1.0, 1L);
assertEquals(expected, actual);
expected = true;
actual = cFunction.greater(1.1, 1L);
assertEquals(expected, actual);
expected = false;
actual = cFunction.greater(0.9, 1L);
assertEquals(expected, actual);
}
@Test
public void testGreaterLongInteger() {
boolean expected = false;
boolean actual = cFunction.greater(1L, 1);
assertEquals(expected, actual);
expected = true;
actual = cFunction.greater(2L, 1);
assertEquals(expected, actual);
expected = false;
actual = cFunction.greater(0L, 1);
assertEquals(expected, actual);
}
@Test
public void testSmallerIntegerInteger() {
boolean expected = false;
boolean actual = cFunction.smaller(1, 1);
assertEquals(expected, actual);
expected = true;
actual = cFunction.smaller(1, 2);
assertEquals(expected, actual);
expected = false;
actual = cFunction.smaller(1, 0);
assertEquals(expected, actual);
}
@Test
public void testSmallerFloatFloat() {
boolean expected = false;
boolean actual = cFunction.smaller(1.0F, 1.0F);
assertEquals(expected, actual);
expected = true;
actual = cFunction.smaller(1.0F, 1.1F);
assertEquals(expected, actual);
expected = false;
actual = cFunction.smaller(1.0F, 0.9F);
assertEquals(expected, actual);
}
@Test
public void testSmallerDoubleDouble() {
boolean expected = false;
boolean actual = cFunction.smaller(1.0, 1.0);
assertEquals(expected, actual);
expected = true;
actual = cFunction.smaller(1.0, 1.1);
assertEquals(expected, actual);
expected = false;
actual = cFunction.smaller(1.0, 0.9);
assertEquals(expected, actual);
}
@Test
public void testSmallerLongLong() {
boolean expected = false;
boolean actual = cFunction.smaller(1L, 1L);
assertEquals(expected, actual);
expected = true;
actual = cFunction.smaller(0L, 1L);
assertEquals(expected, actual);
expected = false;
actual = cFunction.smaller(1L, 0L);
assertEquals(expected, actual);
}
@Test
public void testSmallerIntegerFloat() {
boolean expected = false;
boolean actual = cFunction.smaller(1, 1.0F);
assertEquals(expected, actual);
expected = true;
actual = cFunction.smaller(1, 1.1F);
assertEquals(expected, actual);
expected = false;
actual = cFunction.smaller(1, 0.9F);
assertEquals(expected, actual);
}
@Test
public void testSmallerIntegerDouble() {
boolean expected = false;
boolean actual = cFunction.smaller(1, 1.0);
assertEquals(expected, actual);
expected = true;
actual = cFunction.smaller(1, 1.1);
assertEquals(expected, actual);
expected = false;
actual = cFunction.smaller(1, 0.9);
assertEquals(expected, actual);
}
@Test
public void testSmallerIntegerLong() {
boolean expected = false;
boolean actual = cFunction.smaller(1, 1L);
assertEquals(expected, actual);
expected = true;
actual = cFunction.smaller(1, 2L);
assertEquals(expected, actual);
expected = false;
actual = cFunction.smaller(1, 0L);
assertEquals(expected, actual);
}
@Test
public void testSmallerFloatInteger() {
boolean expected = false;
boolean actual = cFunction.smaller(1.0F, 1);
assertEquals(expected, actual);
expected = true;
actual = cFunction.smaller(0.9F, 1);
assertEquals(expected, actual);
expected = false;
actual = cFunction.smaller(1.1F, 1);
assertEquals(expected, actual);
}
@Test
public void testSmallerFloatDouble() {
boolean expected = false;
boolean actual = cFunction.smaller(1.0F, 1.0);
assertEquals(expected, actual);
expected = true;
actual = cFunction.smaller(0.9F, 1.0);
assertEquals(expected, actual);
expected = false;
actual = cFunction.smaller(1.1F, 1.0);
assertEquals(expected, actual);
}
@Test
public void testSmallerDoubleInteger() {
boolean expected = false;
boolean actual = cFunction.smaller(1.0, 1);
assertEquals(expected, actual);
expected = true;
actual = cFunction.smaller(0.9, 1);
assertEquals(expected, actual);
expected = false;
actual = cFunction.smaller(1.1, 1);
assertEquals(expected, actual);
}
@Test
public void testSmallerDoubleFloat() {
boolean expected = false;
boolean actual = cFunction.smaller(1.0, 1.0F);
assertEquals(expected, actual);
expected = true;
actual = cFunction.smaller(0.9, 1.0F);
assertEquals(expected, actual);
expected = false;
actual = cFunction.smaller(1.1, 1.0F);
assertEquals(expected, actual);
}
@Test
public void testSmallerDoubleLong() {
boolean expected = false;
boolean actual = cFunction.smaller(1.0, 1L);
assertEquals(expected, actual);
expected = true;
actual = cFunction.smaller(0.9, 1L);
assertEquals(expected, actual);
expected = false;
actual = cFunction.smaller(1.1, 1L);
assertEquals(expected, actual);
}
@Test
public void testSmallerLongInteger() {
boolean expected = false;
boolean actual = cFunction.smaller(1L, 1);
assertEquals(expected, actual);
expected = true;
actual = cFunction.smaller(0L, 1L);
assertEquals(expected, actual);
expected = false;
actual = cFunction.smaller(1L, 0L);
assertEquals(expected, actual);
}
@Test
public void testNot() {
boolean expected = false;
boolean actual = cFunction.not(true);
assertEquals(expected, actual);
expected = true;
actual = cFunction.not(false);
}
@Test
public void testComplement() {
int expected = -3;
int actual = cFunction.complement(2);
assertEquals(expected, actual);
}
}
|
package natlab.toolkits.path;
import java.util.*;
import natlab.NatlabPreferences;
import natlab.toolkits.filehandling.genericFile.*;
/**
* This class represents an ordered set of directories that act as a Path in matlab
* where files (*.m, *.mex, *.p) exist.
* Does not model main, or builtins, or context.
* Uses the Directory Cache to get quick access to directories.
*
* TODO - this treats directories in a case sensitive way - is that bad?
* TODO - this might be a bad name for the class
* TODO - one should probably add constructors that allow different sets of
* file extensions, like .p files
* TODO - one should review the order in which files with different extensions are found
* TODO - we need to deal with packages properly, probably
*
* @author ant6n
*
*/
public class MatlabPath extends AbstractPathEnvironment {
ArrayList<CachedDirectory> directories = new ArrayList<CachedDirectory>();
private boolean persistent;
/**
* the file extensions for matlab code files
* - they are in the order of preference
*/
private String[] codeFileExtensions = new String[]{"m"};
/**
* creates a path environment from the ';'-separated String of directories
* if the persistent flag is set, the directories will be cached persistently
* (i.e. they will be more quickly available during the next VM session)
*/
public MatlabPath(String path,boolean persistent){
super(null);
this.persistent = persistent;
if (path == null || path.length() == 0){
return;
}
//put all directories in
for (String s : path.split(";")){
GenericFile file = GenericFile.create(s);
DirectoryCache.put(file,persistent);
directories.add(DirectoryCache.get(file));
}
}
/**
* creates a path environment from the ';'-separated String of directories
* this will not be cached persistently
* @return
*/
public MatlabPath(String path){
this(path,false);
}
/**
* creates a path from a single directory - can be used to do lookups
* in current or private directories
* this will not be cached persistently
* @return
*/
public MatlabPath(GenericFile aPath){
super(null);
GenericFile file = aPath;
DirectoryCache.put(file,persistent);
directories.add(DirectoryCache.get(file));
}
/**
* factory method that returns a path object represented the matlab path stored in
* the natlab preferences
*/
public static MatlabPath getMatlabPath(){
return new MatlabPath(NatlabPreferences.getMatlabPath(),true);
}
/**
* factory method that returns a path object represented the natlab path stored in
* the natlab preferences
*/
public static MatlabPath getNatlabPath(){
return new MatlabPath(NatlabPreferences.getNatlabPath(),true);
}
/**
* returns the set of directories that are overloaded for the given class name
* i.e. the the directories whose parents are in the path, and whose name
* is @ + className
* The directories are returned as non-persistent cached directories
*/
public Collection<CachedDirectory> getAllOverloadedDirs(String className){
ArrayList<CachedDirectory> odirs = new ArrayList<CachedDirectory>();
for (CachedDirectory dir : directories){
for (String s : dir.getChildDirNames()){
if (s.equals("@"+className)){
GenericFile childDir = dir.getChild(s);
DirectoryCache.put(childDir,false);
odirs.add(DirectoryCache.get(childDir));
}
}
}
return odirs;
}
@Override
public FunctionReference getMain() {
return null;
}
@Override
public FunctionReference resolve(String name, GenericFile context) {
return resolveInDirs(name,directories);
}
@Override
public FunctionReference resolve(String name, String className, GenericFile context) {
return resolveInDirs(name,getAllOverloadedDirs(className));
}
public FunctionReference resolveInDirs(String name, Collection<CachedDirectory> dirs){
//System.err.println(name+" "+dirs);
boolean b = true;
if (dirs == null) return null;
for (String ext: codeFileExtensions){
Iterator<CachedDirectory> i = dirs.iterator();
for (CachedDirectory dir : dirs){
if (dir.exists()){
if (dir.getChildFileNames().contains(name+"."+ext)){
return new FunctionReference(dir.getChild(name+"."+ext));
}
}
}
}
return null;
}
@Override
public Map<String, FunctionReference> resolveAll(String name, GenericFile context) {
// TODO Auto-generated method stub
return null;
}
@Override
public Map<String, FunctionReference> getAllOverloaded(String className, GenericFile cotntext) {
Collection<CachedDirectory> oDirs = getAllOverloadedDirs(className);
Collection<GenericFile> list = new ArrayList<GenericFile>();
Map<String, FunctionReference> map = new HashMap<String,FunctionReference>();
for (String ext : codeFileExtensions){
for (CachedDirectory dir : oDirs){
for (String filename : dir.getChildFileNames()){
if (filename.endsWith(ext)){
String name = filename.substring(0,filename.length()-ext.length()-1);
if (!map.containsKey(name)){
map.put(name, new FunctionReference(dir.getChild(filename)));
}
}
}
}
}
return map;
}
}
|
/*
Problem 336. Palindrome Pairs
Given a list of unique words, find all pairs of distinct indices (i, j) in the given list, so that
the concatenation of the two words, i.e. words[i] + words[j] is a palindrome.
Example 1:
Given words = ["bat", "tab", "cat"]
Return [[0, 1], [1, 0]]
The palindromes are ["battab", "tabbat"]
Example 2:
Given words = ["abcd", "dcba", "lls", "s", "sssll"]
Return [[0, 1], [1, 0], [3, 2], [2, 4]]
The palindromes are ["dcbaabcd", "abcddcba", "slls", "llssssll"]
*/
/*
EXPLANATION
We intialize a hashmap and put all input words in it with value to be the corresponding index
We iterate through the words in the input array of strings.
For each word, we iterate through it and in each iteration, we divide the left and righ sides
into 2 subtrings, s1 (prefix, 1st part of the word) and s2 (the rest of the word).
Case 1: s1 is a palindrome
In this case, we reverse s2 (we called the reversed string s2Rev) and check to see if hmap contains s2Rev.
If so, this means appending s2Rev to the beginning of the current word (i.e. s2Rev + word = s2Rev + s1 + s2)
would form a palindrome.
Example, if word = "abacdef" (j will go from 0 to 7 included)
At j = 3, we have s1 = "aba", s2 = "cdef". Then s1 is a palindrome and s2Rev = "fedc".
If s2Rev is in the hash, then s2Rev + word = s2Rev + s1 + s2 = "fedcabacdef" is a palindrome.
Therefore, we add [index-of-s2Rev, index-of-word] to the result
Case 2: s2 is a palindrome.
We reverse s1 (s1Rev) and check to see if hmap contains s1Rev. If so, this means appending s1Rev
to the end of word (i.e word + s1Rev = s1 + s2 + s1Rev) would form a palindrome.
Example, if word = "abcdc" (j will go from 0 to 5 included)
At j = 2, we get s1 = "ab", s2 = "cdc". Then s2 is a palindrome and s1Rev = "ba".
If s1Rev is in the hash, then word + s1Rev = s1 + s2 + s1Rev = "abcdcba" is a palindrome.
Therefore, we add [index-of-word, index-of-s1Rev] to the result
We return the result at the end
*/
public class PalindromePairs {
}
|
// This file is part of Serleena.
// Nicola Mometto, Filippo Sestini, Tobia Tesan, Sebastiano Valle.
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// all copies or substantial portions of the Software.
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// 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 com.kyloth.serleena.sensors;
import android.app.PendingIntent;
import java.util.HashMap;
import java.util.Map;
/**
* Rappresenta i wakeup pianificati utilizzando WakeupManager.
*
* @author Filippo Sestini <sestini.filippo@gmail.com>
* @version 1.0.0
*/
class WakeupSchedule {
Map<String, IWakeupObserver> uuidMap;
Map<IWakeupObserver, PendingIntent> obsMap;
Map<PendingIntent, String> intentMap;
Map<IWakeupObserver, Boolean> onetimeMap;
public WakeupSchedule() {
uuidMap = new HashMap<String, IWakeupObserver>();
obsMap = new HashMap<IWakeupObserver, PendingIntent>();
intentMap = new HashMap<PendingIntent, String>();
onetimeMap = new HashMap<IWakeupObserver, Boolean>();
}
public PendingIntent getIntent(IWakeupObserver observer) {
return obsMap.get(observer);
}
public IWakeupObserver getObserver(String uuid) {
return uuidMap.get(uuid);
}
public void add(String uuid, IWakeupObserver observer,
PendingIntent alarmIntent, boolean oneTimeOnly) {
uuidMap.put(uuid, observer);
obsMap.put(observer, alarmIntent);
intentMap.put(alarmIntent, uuid);
onetimeMap.put(observer, oneTimeOnly);
}
public void remove(IWakeupObserver observer) {
uuidMap.remove(intentMap.remove(obsMap.remove(observer)));
onetimeMap.remove(observer);
}
public boolean isOneTimeOnly(IWakeupObserver observer) {
return onetimeMap.get(observer);
}
public boolean containsObserver(IWakeupObserver observer) {
return onetimeMap.containsKey(observer);
}
}
|
package com.orientechnologies.orient.server;
import com.orientechnologies.common.log.OLogManager;
import com.orientechnologies.orient.client.remote.message.*;
import com.orientechnologies.orient.core.config.OStorageConfiguration;
import com.orientechnologies.orient.core.db.ODatabaseDocumentInternal;
import com.orientechnologies.orient.core.db.OMetadataUpdateListener;
import com.orientechnologies.orient.core.index.OIndexManagerAbstract;
import com.orientechnologies.orient.core.index.OIndexManagerShared;
import com.orientechnologies.orient.core.metadata.schema.OSchemaShared;
import com.orientechnologies.orient.server.network.protocol.binary.ONetworkProtocolBinary;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.*;
import java.util.concurrent.*;
public class OPushManager implements OMetadataUpdateListener {
protected final Set<WeakReference<ONetworkProtocolBinary>> distributedConfigPush = new HashSet<>();
protected final OPushEventType storageConfigurations = new OPushEventType();
protected final OPushEventType schema = new OPushEventType();
protected final OPushEventType indexManager = new OPushEventType();
protected final OPushEventType functions = new OPushEventType();
protected final OPushEventType sequences = new OPushEventType();
private Set<String> registerDatabase = new HashSet<>();
private final ExecutorService executor;
public OPushManager() {
executor = new ThreadPoolExecutor(0, 5, 1, TimeUnit.MINUTES, new SynchronousQueue<Runnable>(), new PushThreadFactory());
}
public synchronized void pushDistributedConfig(String database, List<String> hosts) {
Iterator<WeakReference<ONetworkProtocolBinary>> iter = distributedConfigPush.iterator();
while (iter.hasNext()) {
WeakReference<ONetworkProtocolBinary> ref = iter.next();
ONetworkProtocolBinary protocolBinary = ref.get();
if (protocolBinary != null) {
//TODO Filter by database, push just list of active server for a specific database
OPushDistributedConfigurationRequest request = new OPushDistributedConfigurationRequest(hosts);
try {
OBinaryPushResponse response = protocolBinary.push(request);
} catch (IOException e) {
iter.remove();
}
} else {
iter.remove();
}
}
}
public synchronized void subscribeDistributeConfig(ONetworkProtocolBinary channel) {
distributedConfigPush.add(new WeakReference<ONetworkProtocolBinary>(channel));
}
public synchronized void cleanPushSockets() {
Iterator<WeakReference<ONetworkProtocolBinary>> iter = distributedConfigPush.iterator();
while (iter.hasNext()) {
if (iter.next().get() == null) {
iter.remove();
}
}
storageConfigurations.cleanListeners();
schema.cleanListeners();
indexManager.cleanListeners();
functions.cleanListeners();
sequences.cleanListeners();
}
private void cleanListeners(Map<String, Set<WeakReference<ONetworkProtocolBinary>>> toClean) {
for (Set<WeakReference<ONetworkProtocolBinary>> value : toClean.values()) {
Iterator<WeakReference<ONetworkProtocolBinary>> iter = value.iterator();
while (iter.hasNext()) {
if (iter.next().get() == null) {
iter.remove();
}
}
}
}
public void shutdown() {
executor.shutdownNow();
}
private void genericSubscribe(OPushEventType context, ODatabaseDocumentInternal database, ONetworkProtocolBinary protocol) {
if (!registerDatabase.contains(database.getName())) {
database.getSharedContext().registerListener(this);
registerDatabase.add(database.getName());
}
context.subscribe(database.getName(), protocol);
}
public synchronized void subscribeStorageConfiguration(ODatabaseDocumentInternal database, ONetworkProtocolBinary protocol) {
genericSubscribe(storageConfigurations, database, protocol);
}
public synchronized void subscribeSchema(ODatabaseDocumentInternal database, ONetworkProtocolBinary protocol) {
genericSubscribe(schema, database, protocol);
}
public synchronized void subscribeIndexManager(ODatabaseDocumentInternal database, ONetworkProtocolBinary protocol) {
genericSubscribe(indexManager, database, protocol);
}
public synchronized void subscribeFunctions(ODatabaseDocumentInternal database, ONetworkProtocolBinary protocol) {
genericSubscribe(functions, database, protocol);
}
public synchronized void subscribeSequences(ODatabaseDocumentInternal database, ONetworkProtocolBinary protocol) {
genericSubscribe(sequences, database, protocol);
}
@Override
public void onSchemaUpdate(String database, OSchemaShared schema) {
OPushSchemaRequest request = new OPushSchemaRequest(schema.toNetworkStream());
this.schema.send(database, request, this);
}
@Override
public void onIndexManagerUpdate(String database, OIndexManagerAbstract indexManager) {
OPushIndexManagerRequest request = new OPushIndexManagerRequest(((OIndexManagerShared) indexManager).toNetworkStream());
this.indexManager.send(database, request, this);
}
@Override
public void onFunctionLibraryUpdate(String database) {
OPushFunctionsRequest request = new OPushFunctionsRequest();
this.functions.send(database, request, this);
}
@Override
public void onSequenceLibraryUpdate(String database) {
OPushSequencesRequest request = new OPushSequencesRequest();
this.sequences.send(database, request, this);
}
@Override
public void onStorageConfigurationUpdate(String database, OStorageConfiguration update) {
OPushStorageConfigurationRequest request = new OPushStorageConfigurationRequest(update);
storageConfigurations.send(database, request, this);
}
public void genericNotify(Map<String, Set<WeakReference<ONetworkProtocolBinary>>> context, String database, OPushEventType pack) {
try {
executor.submit(() -> {
Set<WeakReference<ONetworkProtocolBinary>> clients = null;
synchronized (OPushManager.this) {
Set<WeakReference<ONetworkProtocolBinary>> cl = context.get(database);
if (cl != null) {
clients = new HashSet<>(cl);
}
}
if (clients != null) {
Iterator<WeakReference<ONetworkProtocolBinary>> iter = clients.iterator();
while (iter.hasNext()) {
WeakReference<ONetworkProtocolBinary> ref = iter.next();
ONetworkProtocolBinary protocolBinary = ref.get();
if (protocolBinary != null) {
try {
OBinaryPushRequest<?> request = pack.getRequest(database);
if (request != null) {
OBinaryPushResponse response = protocolBinary.push(request);
}
} catch (IOException e) {
synchronized (OPushManager.this) {
context.get(database).remove(ref);
}
}
} else {
synchronized (OPushManager.this) {
context.get(database).remove(ref);
}
}
}
}
});
} catch (RejectedExecutionException e) {
OLogManager.instance().info(this, "Cannot send push request to client for database '%s'", database);
}
}
private static class PushThreadFactory implements ThreadFactory {
@Override
public Thread newThread(Runnable r) {
Thread th = new Thread(r);
th.setName("Push Requests");
return th;
}
}
}
|
package org.wso2.identity.integration.test.scim2;
import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPatch;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Factory;
import org.testng.annotations.Test;
import org.wso2.carbon.automation.engine.context.AutomationContext;
import org.wso2.carbon.automation.engine.context.TestUserMode;
import org.wso2.carbon.integration.common.utils.LoginLogoutClient;
import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
import org.wso2.identity.integration.common.clients.claim.metadata.mgt.ClaimMetadataManagementServiceClient;
import org.wso2.identity.integration.common.utils.ISIntegrationTest;
import java.io.IOException;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertTrue;
import static org.wso2.identity.integration.test.scim2.SCIM2BaseTestCase.EMAILS_ATTRIBUTE;
import static org.wso2.identity.integration.test.scim2.SCIM2BaseTestCase.EMAIL_TYPE_HOME_ATTRIBUTE;
import static org.wso2.identity.integration.test.scim2.SCIM2BaseTestCase.EMAIL_TYPE_WORK_ATTRIBUTE;
import static org.wso2.identity.integration.test.scim2.SCIM2BaseTestCase.ERROR_SCHEMA;
import static org.wso2.identity.integration.test.scim2.SCIM2BaseTestCase.FAMILY_NAME_ATTRIBUTE;
import static org.wso2.identity.integration.test.scim2.SCIM2BaseTestCase.GIVEN_NAME_ATTRIBUTE;
import static org.wso2.identity.integration.test.scim2.SCIM2BaseTestCase.ID_ATTRIBUTE;
import static org.wso2.identity.integration.test.scim2.SCIM2BaseTestCase.LIST_SCHEMA;
import static org.wso2.identity.integration.test.scim2.SCIM2BaseTestCase.NAME_ATTRIBUTE;
import static org.wso2.identity.integration.test.scim2.SCIM2BaseTestCase.PASSWORD_ATTRIBUTE;
import static org.wso2.identity.integration.test.scim2.SCIM2BaseTestCase.RESOURCE_TYPE_SCHEMA;
import static org.wso2.identity.integration.test.scim2.SCIM2BaseTestCase.ROLE_ATTRIBUTE;
import static org.wso2.identity.integration.test.scim2.SCIM2BaseTestCase.SCHEMAS_ATTRIBUTE;
import static org.wso2.identity.integration.test.scim2.SCIM2BaseTestCase.SCIM2_USERS_ENDPOINT;
import static org.wso2.identity.integration.test.scim2.SCIM2BaseTestCase.SCIM_RESOURCE_TYPES_ENDPOINT;
import static org.wso2.identity.integration.test.scim2.SCIM2BaseTestCase.SERVER_URL;
import static org.wso2.identity.integration.test.scim2.SCIM2BaseTestCase.TYPE_PARAM;
import static org.wso2.identity.integration.test.scim2.SCIM2BaseTestCase.USER_NAME_ATTRIBUTE;
import static org.wso2.identity.integration.test.scim2.SCIM2BaseTestCase.VALUE_PARAM;
public class SCIM2UserTestCase extends ISIntegrationTest {
private static final String FAMILY_NAME_CLAIM_VALUE = "scim";
private static final String GIVEN_NAME_CLAIM_VALUE = "user";
private static final String EMAIL_TYPE_WORK_CLAIM_VALUE = "scim2user@wso2.com";
private static final String EMAIL_TYPE_HOME_CLAIM_VALUE = "scim2user@gmail.com";
public static final String USERNAME = "scim2user";
public static final String PASSWORD = "testPassword";
private ClaimMetadataManagementServiceClient claimMetadataManagementServiceClient = null;
private String backendURL;
private String sessionCookie;
private TestUserMode testUserMode;
private CloseableHttpClient client;
private static final String EQUAL = "+Eq+";
private static final String STARTWITH = "+Sw+";
private static final String ENDWITH = "+Ew+";
private static final String CONTAINS = "+Co+";
@BeforeClass(alwaysRun = true)
public void testInit() throws Exception {
super.init();
client = HttpClients.createDefault();
}
private String userId;
private String adminUsername;
private String adminPassword;
private String tenant;
@Factory(dataProvider = "SCIM2UserConfigProvider")
public SCIM2UserTestCase(TestUserMode userMode) throws Exception {
AutomationContext context = new AutomationContext("IDENTITY", userMode);
this.adminUsername = context.getContextTenant().getTenantAdmin().getUserName();
this.adminPassword = context.getContextTenant().getTenantAdmin().getPassword();
this.tenant = context.getContextTenant().getDomain();
testUserMode = userMode;
}
@DataProvider(name = "SCIM2UserConfigProvider")
public static Object[][] sCIM2UserConfigProvider() {
return new Object[][]{
{TestUserMode.SUPER_TENANT_ADMIN},
{TestUserMode.TENANT_ADMIN}
};
}
@Test
public void testCreateUser() throws Exception {
HttpPost request = new HttpPost(getPath());
request.addHeader(HttpHeaders.AUTHORIZATION, getAuthzHeader());
request.addHeader(HttpHeaders.CONTENT_TYPE, "application/json");
JSONObject rootObject = new JSONObject();
JSONArray schemas = new JSONArray();
rootObject.put(SCHEMAS_ATTRIBUTE, schemas);
JSONObject names = new JSONObject();
names.put(FAMILY_NAME_ATTRIBUTE, FAMILY_NAME_CLAIM_VALUE);
names.put(GIVEN_NAME_ATTRIBUTE, GIVEN_NAME_CLAIM_VALUE);
rootObject.put(NAME_ATTRIBUTE, names);
rootObject.put(USER_NAME_ATTRIBUTE, USERNAME);
JSONObject emailWork = new JSONObject();
emailWork.put(TYPE_PARAM, EMAIL_TYPE_WORK_ATTRIBUTE);
emailWork.put(VALUE_PARAM, EMAIL_TYPE_WORK_CLAIM_VALUE);
JSONObject emailHome = new JSONObject();
emailHome.put(TYPE_PARAM, EMAIL_TYPE_HOME_ATTRIBUTE);
emailHome.put(VALUE_PARAM, EMAIL_TYPE_HOME_CLAIM_VALUE);
JSONArray emails = new JSONArray();
emails.add(emailWork);
emails.add(emailHome);
rootObject.put(EMAILS_ATTRIBUTE, emails);
rootObject.put(PASSWORD_ATTRIBUTE, PASSWORD);
StringEntity entity = new StringEntity(rootObject.toString());
request.setEntity(entity);
HttpResponse response = client.execute(request);
assertEquals(response.getStatusLine().getStatusCode(), 201, "User " +
"has not been created successfully");
Object responseObj = JSONValue.parse(EntityUtils.toString(response.getEntity()));
EntityUtils.consume(response.getEntity());
String usernameFromResponse = ((JSONObject) responseObj).get(USER_NAME_ATTRIBUTE).toString();
assertEquals(usernameFromResponse, USERNAME);
userId = ((JSONObject) responseObj).get(ID_ATTRIBUTE).toString();
assertNotNull(userId);
String name = ((JSONObject) responseObj).get(NAME_ATTRIBUTE).toString();
assertNotNull(name);
String role = ((JSONObject) responseObj).get(ROLE_ATTRIBUTE).toString();
assertNotNull(role);
}
@Test
public void testAddUserFailure() throws Exception {
HttpPost request = new HttpPost(getPath());
request.addHeader(HttpHeaders.AUTHORIZATION, getAuthzHeader());
request.addHeader(HttpHeaders.CONTENT_TYPE, "application/json");
JSONObject rootObject = new JSONObject();
JSONArray schemas = new JSONArray();
rootObject.put(SCHEMAS_ATTRIBUTE, schemas);
JSONObject names = new JSONObject();
rootObject.put(NAME_ATTRIBUTE, names);
rootObject.put(USER_NAME_ATTRIBUTE, "passwordIncompatibleUser");
rootObject.put(PASSWORD_ATTRIBUTE, "a");
StringEntity entity = new StringEntity(rootObject.toString());
request.setEntity(entity);
HttpResponse response = client.execute(request);
Object responseObj = JSONValue.parse(EntityUtils.toString(response.getEntity()));
EntityUtils.consume(response.getEntity());
JSONArray schemasArray = (JSONArray)((JSONObject) responseObj).get("schemas");
Assert.assertNotNull(schemasArray);
Assert.assertEquals(schemasArray.size(), 1);
Assert.assertEquals(schemasArray.get(0).toString(), ERROR_SCHEMA);
}
@Test(dependsOnMethods = "testCreateUser")
public void testGetUser() throws Exception {
String userResourcePath = getPath() + "/" + userId;
HttpGet request = new HttpGet(userResourcePath);
request.addHeader(HttpHeaders.AUTHORIZATION, getAuthzHeader());
request.addHeader(HttpHeaders.CONTENT_TYPE, "application/json");
HttpResponse response = client.execute(request);
assertEquals(response.getStatusLine().getStatusCode(), 200, "User " +
"has not been retrieved successfully");
Object responseObj = JSONValue.parse(EntityUtils.toString(response.getEntity()));
EntityUtils.consume(response.getEntity());
String usernameFromResponse = ((JSONObject) responseObj).get(USER_NAME_ATTRIBUTE).toString();
assertEquals(usernameFromResponse, USERNAME);
userId = ((JSONObject) responseObj).get(ID_ATTRIBUTE).toString();
assertNotNull(userId);
}
@Test(dependsOnMethods = "testGetUser")
public void testFilterUser() throws Exception {
validateFilteredUser(USER_NAME_ATTRIBUTE, EQUAL, USERNAME);
validateFilteredUser(USER_NAME_ATTRIBUTE, CONTAINS, USERNAME.substring(2, 4));
validateFilteredUser(USER_NAME_ATTRIBUTE, STARTWITH, USERNAME.substring(0, 3));
validateFilteredUser(USER_NAME_ATTRIBUTE, ENDWITH, USERNAME.substring(4, USERNAME.length()));
}
private void validateFilteredUser(String attributeName, String operator, String attributeValue) throws IOException {
String userResourcePath = getPath() + "?filter=" + attributeName + operator + attributeValue;
HttpGet request = new HttpGet(userResourcePath);
request.addHeader(HttpHeaders.AUTHORIZATION, getAuthzHeader());
request.addHeader(HttpHeaders.CONTENT_TYPE, "application/json");
request.addHeader(HttpHeaders.ACCEPT, "application/scim+json");
HttpResponse response = client.execute(request);
assertEquals(response.getStatusLine().getStatusCode(), 200, "User " +
"has not been retrieved successfully");
Object responseObj = JSONValue.parse(EntityUtils.toString(response.getEntity()));
EntityUtils.consume(response.getEntity());
String usernameFromResponse = ((JSONObject) ((JSONArray) ((JSONObject) responseObj).get("Resources")).get(0))
.get(attributeName).toString();
assertEquals(usernameFromResponse, USERNAME);
String userId = ((JSONObject) ((JSONArray) ((JSONObject) responseObj).get("Resources")).get(0)).get
(ID_ATTRIBUTE).toString();
assertEquals(userId, this.userId);
}
@Test(dependsOnMethods = "testFilterUser")
public void testDeleteUser() throws Exception {
String userResourcePath = getPath() + "/" + userId;
HttpDelete request = new HttpDelete(userResourcePath);
request.addHeader(HttpHeaders.AUTHORIZATION, getAuthzHeader());
request.addHeader(HttpHeaders.CONTENT_TYPE, "application/json");
HttpResponse response = client.execute(request);
assertEquals(response.getStatusLine().getStatusCode(), 204, "User " +
"has not been retrieved successfully");
EntityUtils.consume(response.getEntity());
userResourcePath = getPath() + "/" + userId;
HttpGet getRequest = new HttpGet(userResourcePath);
getRequest.addHeader(HttpHeaders.AUTHORIZATION, getAuthzHeader());
getRequest.addHeader(HttpHeaders.CONTENT_TYPE, "application/json");
response = client.execute(request);
assertEquals(response.getStatusLine().getStatusCode(), 404, "User " +
"has not been deleted successfully");
EntityUtils.consume(response.getEntity());
}
@Test
public void testGetResourceTypes() throws Exception {
String resourcePathEndpoint = SERVER_URL + SCIM_RESOURCE_TYPES_ENDPOINT;
HttpGet request = new HttpGet(resourcePathEndpoint);
request.addHeader(HttpHeaders.CONTENT_TYPE, "application/json");
HttpResponse response = client.execute(request);
assertEquals(response.getStatusLine().getStatusCode(), 200, "Error while executing GET to resourceTypes " +
"Endpoint");
Object responseObj = JSONValue.parse(EntityUtils.toString(response.getEntity()));
EntityUtils.consume(response.getEntity());
JSONObject resourceResponse = ((JSONObject) responseObj);
Long totalResults = (Long) resourceResponse.get("totalResults");
Assert.assertEquals("2", Long.toString(totalResults));
JSONArray rootSchemas = (JSONArray) resourceResponse.get("schemas");
Assert.assertEquals(rootSchemas.get(0).toString(), LIST_SCHEMA);
JSONArray resourcesArray = (JSONArray) resourceResponse.get("Resources");
Assert.assertEquals(resourcesArray.size(), 2);
JSONObject resource = (JSONObject) resourcesArray.get(0);
JSONArray resourceSchemas = (JSONArray) resource.get("schemas");
Assert.assertEquals(resourceSchemas.size(), 1);
Assert.assertEquals(resourceSchemas.get(0).toString(), RESOURCE_TYPE_SCHEMA);
}
@Test
public void testUpdateUserWhenExternalClaimDeleted() throws Exception {
AutomationContext context = new AutomationContext("IDENTITY", testUserMode);
backendURL = context.getContextUrls().getBackEndUrl();
loginLogoutClient = new LoginLogoutClient(context);
sessionCookie = loginLogoutClient.login();
HttpPost postRequest = new HttpPost(getPath());
postRequest.addHeader(HttpHeaders.AUTHORIZATION, getAuthzHeader());
postRequest.addHeader(HttpHeaders.CONTENT_TYPE, "application/json");
JSONObject rootObject = new JSONObject();
JSONArray schemas = new JSONArray();
rootObject.put(SCHEMAS_ATTRIBUTE, schemas);
JSONObject names = new JSONObject();
names.put(FAMILY_NAME_ATTRIBUTE, "udaranga");
names.put(GIVEN_NAME_ATTRIBUTE, "buddhima");
rootObject.put(NAME_ATTRIBUTE, names);
rootObject.put(USER_NAME_ATTRIBUTE, "wso2is");
JSONObject emailWork = new JSONObject();
emailWork.put(TYPE_PARAM, EMAIL_TYPE_WORK_ATTRIBUTE);
emailWork.put(VALUE_PARAM, EMAIL_TYPE_WORK_CLAIM_VALUE);
JSONObject emailHome = new JSONObject();
emailHome.put(TYPE_PARAM, EMAIL_TYPE_HOME_ATTRIBUTE);
emailHome.put(VALUE_PARAM, EMAIL_TYPE_HOME_CLAIM_VALUE);
JSONArray emails = new JSONArray();
emails.add(emailWork);
emails.add(emailHome);
rootObject.put(EMAILS_ATTRIBUTE, emails);
rootObject.put(PASSWORD_ATTRIBUTE, PASSWORD);
StringEntity entity = new StringEntity(rootObject.toString());
postRequest.setEntity(entity);
HttpResponse postResponse = client.execute(postRequest);
assertEquals(postResponse.getStatusLine().getStatusCode(), 201,
"User " + "has not been created in patch process successfully");
Object responseObj = JSONValue.parse(EntityUtils.toString(postResponse.getEntity()));
EntityUtils.consume(postResponse.getEntity());
userId = ((JSONObject) responseObj).get(ID_ATTRIBUTE).toString();
assertNotNull(userId);
String userResourcePath = getPath() + "/" + userId;
claimMetadataManagementServiceClient = new ClaimMetadataManagementServiceClient(backendURL, sessionCookie);
claimMetadataManagementServiceClient.removeExternalClaim("urn:ietf:params:scim:schemas:core:2.0:User",
"urn:ietf:params:scim:schemas:core:2.0:User:name.honorificSuffix");
HttpPatch request = new HttpPatch(userResourcePath);
StringEntity params = new StringEntity("{\"schemas\":[\"urn:ietf:params:scim:api:messages:2.0:PatchOp\"],"
+ "\"Operations\":[{\"op\":\"replace\",\"path\":\"name\",\"value\":{\"givenName\":\"mahela\","
+ "\"familyName\":\"jayaxxxx\"}}]}");
request.setEntity(params);
request.addHeader(HttpHeaders.AUTHORIZATION, getAuthzHeader());
request.addHeader(HttpHeaders.CONTENT_TYPE, "application/json");
HttpResponse response = client.execute(request);
assertEquals(response.getStatusLine().getStatusCode(), 200, "User " + "has not been updated successfully");
Object responseObjAfterPatch = JSONValue.parse(EntityUtils.toString(response.getEntity()));
EntityUtils.consume(response.getEntity());
String updatedGivenName = ((JSONObject) responseObjAfterPatch).get(NAME_ATTRIBUTE).toString();
assertTrue(updatedGivenName.contains("mahela"));
}
private String getPath() {
if (tenant.equals(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)) {
return SERVER_URL + SCIM2_USERS_ENDPOINT;
} else {
return SERVER_URL + "/t/" + tenant + SCIM2_USERS_ENDPOINT;
}
}
private String getAuthzHeader() {
return "Basic " + Base64.encodeBase64String((adminUsername + ":" + adminPassword).getBytes()).trim();
}
}
|
package io.spine.server.entity.storage;
import com.google.common.annotations.VisibleForTesting;
import io.spine.annotation.Internal;
import io.spine.server.entity.Entity;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;
import static com.google.common.base.Preconditions.checkNotNull;
import static io.spine.server.entity.storage.Columns.obtainColumns;
import static io.spine.validate.Validate.checkNotEmptyOrBlank;
import static java.lang.String.format;
import static java.util.Collections.synchronizedMap;
/**
* A class designated to store cached {@linkplain EntityColumn entity column metadata} for a single
* {@link Entity} class.
*
* <p>The cache remains empty on creation. The {@linkplain EntityColumn column metadata} is retrieved
* on the first access to the {@linkplain EntityColumnCache cache} instance and then is stored
* to the {@link Map}.
*
* <p>This class relies on the {@link Columns} utility methods to perform operations
* on {@linkplain EntityColumn entity columns}.
*
* <p>The order in which {@link EntityColumn entity columns} are stored, is retained for
* the access operations.
*
* @author Dmytro Kuzmin
* @see EntityColumn
* @see Columns
*/
@Internal
public class EntityColumnCache {
private final Class<? extends Entity> entityClass;
private boolean columnsCached = false;
/**
* A one to one container of the {@link EntityColumn} name and its data.
*
* <p>The data is stored this way for convenient querying of the specific columns.
*
* <p>This contained is mutable and thread safe.
*/
private final Map<String, EntityColumn> entityColumnData = synchronizedMap(
new LinkedHashMap<String, EntityColumn>());
@VisibleForTesting
private EntityColumnCache() {
this.entityClass = null;
}
private EntityColumnCache(Class<? extends Entity> entityClass) {
checkNotNull(entityClass);
this.entityClass = entityClass;
}
@VisibleForTesting
static EntityColumnCache getEmptyInstance() {
return new EntityColumnCache();
}
/**
* Creates an instance of {@link EntityColumnCache} for the given {@link Entity} class.
*
* <p>The {@linkplain EntityColumn column metadata} will not be retrieved and stored on creation.
* Instead the {@linkplain EntityColumnCache instance }will wait for the first access to it
* to cache {@linkplain EntityColumn entity columns}.
*
* @param entityClass the class for which {@linkplain EntityColumn entity columns} should
* be obtained and cached
* @return new {@link EntityColumnCache} instance
*/
public static EntityColumnCache initializeFor(Class<? extends Entity> entityClass) {
checkNotNull(entityClass);
return new EntityColumnCache(entityClass);
}
public EntityColumn findColumn(String columnName) {
checkNotEmptyOrBlank(columnName, "entity column name");
ensureColumnsCached();
final EntityColumn entityColumn = entityColumnData.get(columnName);
if (entityColumn == null) {
throw new IllegalArgumentException(
format("Could not find an EntityColumn description for %s.%s.",
entityClass.getCanonicalName(),
columnName));
}
return entityColumn;
}
/**
* Retrieves all {@linkplain EntityColumn entity columns} for the {@link Entity} class managed
* by this {@linkplain EntityColumnCache cache}.
*
* <p>If the {@linkplain EntityColumn column metadata} is not yet obtained and cached, this method
* will {@linkplain EntityColumnCache#ensureColumnsCached() retrieve and cache it}.
*
* @return {@linkplain EntityColumn entity column} {@link Collection} for the managed
* {@link Entity} class
*/
public Collection<EntityColumn> getAllColumns() {
ensureColumnsCached();
return entityColumnData.values();
}
/**
* {@linkplain Columns#obtainColumns(Class) Obtains} and caches {@link EntityColumn} data if it is not
* yet cached.
*
* <p>If the data is already retrieved and cached, this method does nothing.
*/
public void ensureColumnsCached() {
if (!columnsCached) {
obtainAndCacheColumns();
columnsCached = true;
}
}
/**
* Checks if the current {@link EntityColumnCache} instance has already retrieved and cached
* {@linkplain EntityColumn column metadata}.
*
* @return {@code true} if columns are cached and {@code false} otherwise
*/
@VisibleForTesting
boolean isEmpty() {
return !columnsCached && entityColumnData.isEmpty();
}
private void obtainAndCacheColumns() {
final Collection<EntityColumn> columns = obtainColumns(entityClass);
cacheEntityColumns(columns);
}
/**
* Stores {@linkplain EntityColumn entity columns} from the {@link Iterable} to the inner
* {@link EntityColumnCache#entityColumnData cache}.
*
* @param columns {@linkplain EntityColumn columns} to store
*/
private void cacheEntityColumns(Iterable<EntityColumn> columns) {
for (EntityColumn column : columns) {
entityColumnData.put(column.getName(), column);
}
}
}
|
package io.spine.server.storage.memory;
import com.google.common.collect.ImmutableMap;
import com.google.protobuf.Timestamp;
import javax.annotation.Nullable;
import java.util.Objects;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static io.spine.client.ColumnFilter.Operator;
import static io.spine.time.Timestamps2.isLaterThan;
import static io.spine.util.Exceptions.newIllegalArgumentException;
import static java.lang.String.format;
/**
* A boolean non-typed comparison operation on two given instances.
*
* @author Dmytro Dashenkov
* @see io.spine.client.CompositeColumnFilter.CompositeOperator for the comparison strategies
*/
enum OperatorEvaluator {
EQUAL {
@Override
public boolean eval(@Nullable Object left, @Nullable Object right) {
return Objects.equals(left, right);
}
},
GREATER_THAN {
@SuppressWarnings("ChainOfInstanceofChecks") // Generic but limited operand types
@Override
public boolean eval(@Nullable Object left, @Nullable Object right) {
if (left == null || right == null) {
return false;
}
if (left.getClass() != right.getClass()) {
throw new IllegalArgumentException(
format(
"Cannot compare an instance of %s to an instance of %s.",
left.getClass(),
right.getClass())
);
}
if (left instanceof Timestamp) {
final Timestamp tsLeft = (Timestamp) left;
final Timestamp tsRight = (Timestamp) right;
return isLaterThan(tsLeft, tsRight);
}
if (left instanceof Comparable<?>) {
final Comparable cmpLeft = (Comparable<?>) left;
final Comparable cmpRight = (Comparable<?>) right;
@SuppressWarnings("unchecked") // Type is unknown but checked at runtime
final int comparisonResult = cmpLeft.compareTo(cmpRight);
return comparisonResult > 0;
}
throw newIllegalArgumentException("Operation \'%s\' is not supported for type %s.",
this,
left.getClass().getCanonicalName());
}
},
LESS_THAN {
@Override
public boolean eval(@Nullable Object left, @Nullable Object right) {
return GREATER_THAN.eval(right, left);
}
},
GREATER_OR_EQUAL {
@Override
public boolean eval(@Nullable Object left, @Nullable Object right) {
return GREATER_THAN.eval(left, right)
|| EQUAL.eval(left, right);
}
},
LESS_OR_EQUAL {
@Override
public boolean eval(@Nullable Object left, @Nullable Object right) {
return LESS_THAN.eval(left, right)
|| EQUAL.eval(left, right);
}
};
private static final ImmutableMap<Operator, OperatorEvaluator> EVALUATORS =
ImmutableMap.<Operator, OperatorEvaluator>builder()
.put(Operator.EQUAL, EQUAL)
.put(Operator.GREATER_THAN, GREATER_THAN)
.put(Operator.LESS_THAN, LESS_THAN)
.put(Operator.GREATER_OR_EQUAL, GREATER_OR_EQUAL)
.put(Operator.LESS_OR_EQUAL, LESS_OR_EQUAL)
.build();
/**
* Evaluates the given expression.
*
* <p>For example, if operands where {@code 42} and {@code 9} (exactly in that order) and
* the operator was {@link Operator#GREATER_THAN GREATER_THAN}, then this function could be
* expressed as {@code 42 > 8}. The function returns the {@code boolean} result of
* the evaluation.
*
* @param left the left operand
* @param operator the comparison operator
* @param right the right operand
* @param <T> the type of the compared values
* @return {@code true} if the operands match the operator, {@code false} otherwise
* @throws UnsupportedOperationException if the operation is
* <a href="supported_types">not supported</a> for
* the given data types
*/
static <T> boolean eval(@Nullable T left, Operator operator, @Nullable T right)
throws UnsupportedOperationException {
checkNotNull(operator);
final OperatorEvaluator evaluator = EVALUATORS.get(operator);
checkArgument(evaluator != null, operator);
final boolean result = evaluator.eval(left, right);
return result;
}
/**
* Evaluates the expression of joining the given operands with a certain operator.
*
* @see OperatorEvaluator#eval for the detailed behaiour
* description
* @return {@code true} if the expression evaluates into {@code true}, {@code false} otherwise
*/
abstract boolean eval(@Nullable Object left, @Nullable Object right);
}
|
package org.opendaylight.controller.cluster.datastore;
import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.actor.Address;
import akka.cluster.Cluster;
import akka.cluster.ClusterEvent;
import com.google.common.base.Preconditions;
public class ClusterWrapperImpl implements ClusterWrapper {
private final Cluster cluster;
private final String currentMemberName;
private final Address selfAddress;
public ClusterWrapperImpl(ActorSystem actorSystem){
Preconditions.checkNotNull(actorSystem, "actorSystem should not be null");
cluster = Cluster.get(actorSystem);
Preconditions.checkState(cluster.getSelfRoles().size() > 0,
"No akka roles were specified\n" +
"One way to specify the member name is to pass a property on the command line like so\n" +
" -Dakka.cluster.roles.0=member-3\n" +
"member-3 here would be the name of the member"
);
currentMemberName = cluster.getSelfRoles().iterator().next();
selfAddress = cluster.selfAddress();
}
public void subscribeToMemberEvents(ActorRef actorRef){
Preconditions.checkNotNull(actorRef, "actorRef should not be null");
cluster.subscribe(actorRef, ClusterEvent.initialStateAsEvents(),
ClusterEvent.MemberEvent.class,
ClusterEvent.UnreachableMember.class);
}
public String getCurrentMemberName() {
return currentMemberName;
}
public Address getSelfAddress() {
return selfAddress;
}
}
|
package com.gdxjam.screens;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.ImageButton;
import com.badlogic.gdx.scenes.scene2d.ui.ImageTextButton.ImageTextButtonStyle;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.badlogic.gdx.scenes.scene2d.ui.Label.LabelStyle;
import com.badlogic.gdx.scenes.scene2d.ui.ScrollPane.ScrollPaneStyle;
import com.badlogic.gdx.scenes.scene2d.ui.SelectBox;
import com.badlogic.gdx.scenes.scene2d.ui.SelectBox.SelectBoxStyle;
import com.badlogic.gdx.scenes.scene2d.ui.Table;
import com.badlogic.gdx.scenes.scene2d.ui.TextButton;
import com.badlogic.gdx.scenes.scene2d.ui.TextButton.TextButtonStyle;
import com.badlogic.gdx.scenes.scene2d.utils.Align;
import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener;
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener;
import com.badlogic.gdx.scenes.scene2d.utils.NinePatchDrawable;
import com.badlogic.gdx.scenes.scene2d.utils.TextureRegionDrawable;
import com.gdxjam.Assets;
import com.gdxjam.GameManager;
import com.gdxjam.components.FactionComponent.Faction;
import com.gdxjam.utils.Constants;
import com.gdxjam.utils.Constants.WorldSize;
public class NewGameScreen extends AbstractScreen {
Stage stage;
Table table;
Label description;
Faction selected;
WorldSize size;
@Override
public void show() {
selected = Faction.FACTION0;
size = WorldSize.MEDIUM;
stage = new Stage();
table = new Table();
table.setFillParent(true);
table.defaults().pad(10);
LabelStyle labelStyle = new LabelStyle(Assets.fonts.font, new Color(1,
1, 1, 1));
Label label = new Label("Choose Your Faction", labelStyle);
label.setFontScale(2);
label.setAlignment(Align.top);
ImageButton faction0 = newImageButton(Assets.spacecraft.ships.get(0));
faction0.addListener(new ClickListener() {
@Override
public void clicked(InputEvent event, float x, float y) {
super.clicked(event, x, y);
showFaction(Faction.FACTION0);
}
});
ImageButton faction1 = newImageButton(Assets.spacecraft.ships.get(1));
faction1.addListener(new ClickListener() {
@Override
public void clicked(InputEvent event, float x, float y) {
super.clicked(event, x, y);
showFaction(Faction.FACTION1);
}
});
ImageButton faction2 = newImageButton(Assets.spacecraft.ships.get(2));
faction2.addListener(new ClickListener() {
@Override
public void clicked(InputEvent event, float x, float y) {
super.clicked(event, x, y);
showFaction(Faction.FACTION2);
}
});
description = new Label("DERP DERP DERP", labelStyle);
description.setAlignment(Align.center);
NinePatchDrawable draw = new NinePatchDrawable(Assets.hotkey.button);
TextButtonStyle textStyle = new ImageTextButtonStyle();
textStyle.up = draw;
textStyle.down = draw.tint(Color.DARK_GRAY);
textStyle.checked = draw;
textStyle.font = Assets.fonts.font;
final SelectBox<String> worldSize = new SelectBox<String>(Assets.skin);
worldSize.addListener(new ChangeListener() {
@Override
public void changed(ChangeEvent event, Actor actor) {
System.out.println(worldSize.getSelected());
if (worldSize.getSelected().equalsIgnoreCase("small")) {
Constants.worldSize = WorldSize.SMALL;
} else if (worldSize.getSelected().equalsIgnoreCase("medium")) {
Constants.worldSize = WorldSize.MEDIUM;
} else if (worldSize.getSelected().equalsIgnoreCase("large")) {
Constants.worldSize = WorldSize.LARGE;
}
}
});
worldSize.setItems("Small", "Medium", "Large");
TextButton start = new TextButton("Start", textStyle);
start.addListener(new ClickListener() {
@Override
public void clicked(InputEvent event, float x, float y) {
// TODO Auto-generated method stub
super.clicked(event, x, y);
start(selected);
}
});
TextButton back = new TextButton("Back", textStyle);
back.addListener(new ClickListener() {
@Override
public void clicked(InputEvent event, float x, float y) {
// TODO Auto-generated method stub
super.clicked(event, x, y);
GameManager.setScreen(new MainMenuScreen());
}
});
table.align(Align.top).add(label).colspan(3);
table.row();
table.add(faction0);
table.add(faction1);
table.add(faction2);
table.row();
table.add(description).colspan(3);
table.row();
table.add(worldSize).fill(0.8f, 1f);
table.add(start);
table.add(back);
stage.addActor(table);
Gdx.input.setInputProcessor(stage);
}
public void showFaction(Faction faction) {
switch (faction) {
default:
case FACTION0:
description.setText(Constants.FACTION0_DESC);
selected = Faction.FACTION0;
break;
case FACTION1:
description.setText(Constants.FACTION1_DESC);
selected = Faction.FACTION1;
break;
case FACTION2:
description.setText(Constants.FACTION2_DESC);
selected = Faction.FACTION2;
break;
}
}
public ImageButton newImageButton(TextureRegion region) {
TextureRegionDrawable drawable = new TextureRegionDrawable(region);
return new ImageButton(drawable);
}
public void start(Faction faction) {
Constants.playerFaction = faction;
GameManager.setScreen(new GameScreen());
}
@Override
public void resize(int width, int height) {
stage.getViewport().update(width, height);
}
@Override
public void render(float delta) {
super.render(delta);
stage.act();
stage.draw();
}
@Override
public void pause() {
}
@Override
public void resume() {
}
@Override
public void hide() {
}
@Override
public void dispose() {
stage.dispose();
}
}
|
package by.kraskovski.pms.controller;
import by.kraskovski.pms.domain.Product;
import by.kraskovski.pms.service.ProductService;
import org.apache.commons.lang3.RandomUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import static by.kraskovski.pms.domain.enums.AuthorityEnum.ROLE_ADMIN;
import static by.kraskovski.pms.utils.TestUtils.prepareProduct;
import static org.apache.commons.lang3.RandomStringUtils.random;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
import static org.springframework.http.MediaType.APPLICATION_JSON_UTF8;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
public class ProductControllerIT extends ControllerConfig {
private static final String BASE_PRODUCTS_URL = "/product";
@Autowired
private ProductService productService;
@Before
public void before() {
setup(ROLE_ADMIN);
}
@After
public void after() {
cleanup();
productService.deleteAll();
}
@Test
public void createProductTest() throws Exception {
final Product product = prepareProduct();
mvc.perform(post(BASE_PRODUCTS_URL)
.contentType(APPLICATION_JSON_UTF8)
.header(authHeaderName, token)
.content(objectMapper.writeValueAsString(product)))
.andExpect(status().isCreated())
.andExpect(content().contentType(APPLICATION_JSON_UTF8))
.andExpect(jsonPath("$.id", notNullValue()))
.andExpect(jsonPath("$.name", is(product.getName())))
.andExpect(jsonPath("$.type", is(product.getType())))
.andExpect(jsonPath("$.image", is(product.getImage())));
}
@Test
public void findProductByIdTest() throws Exception {
final Product product = prepareProduct();
productService.create(product);
mvc.perform(get(BASE_PRODUCTS_URL + "/" + product.getId())
.header(authHeaderName, token))
.andExpect(status().isOk())
.andExpect(content().contentType(APPLICATION_JSON_UTF8))
.andExpect(jsonPath("$.id", is(product.getId())))
.andExpect(jsonPath("$.name", is(product.getName())))
.andExpect(jsonPath("$.type", is(product.getType())))
.andExpect(jsonPath("$.image", is(product.getImage())));
}
@Test
public void findProductByNameTest() throws Exception {
final Product product = prepareProduct();
productService.create(product);
mvc.perform(get(BASE_PRODUCTS_URL + "/name/" + product.getName())
.header(authHeaderName, token))
.andExpect(status().isOk())
.andExpect(content().contentType(APPLICATION_JSON_UTF8))
.andExpect(jsonPath("$[0].id", is(product.getId())))
.andExpect(jsonPath("$[0].name", is(product.getName())))
.andExpect(jsonPath("$[0].type", is(product.getType())))
.andExpect(jsonPath("$[0].image", is(product.getImage())));
}
@Test
public void findProductByTypeTest() throws Exception {
final Product product = prepareProduct();
productService.create(product);
mvc.perform(get(BASE_PRODUCTS_URL + "/type/" + product.getType())
.header(authHeaderName, token))
.andExpect(status().isOk())
.andExpect(content().contentType(APPLICATION_JSON_UTF8))
.andExpect(jsonPath("$[0].id", is(product.getId())))
.andExpect(jsonPath("$[0].name", is(product.getName())))
.andExpect(jsonPath("$[0].type", is(product.getType())))
.andExpect(jsonPath("$[0].image", is(product.getImage())));
}
@Test
public void updateProductTest() throws Exception {
final Product product = prepareProduct();
productService.create(product);
product.setName(random(20));
product.setImage(random(20));
product.setType(random(20));
product.setCost(RandomUtils.nextDouble());
product.setDetails(random(50));
product.setManufactureDate(null);
mvc.perform(put(BASE_PRODUCTS_URL)
.header(authHeaderName, token)
.contentType(APPLICATION_JSON_UTF8)
.content(objectMapper.writeValueAsString(product)))
.andExpect(status().isOk())
.andExpect(content().contentType(APPLICATION_JSON_UTF8))
.andExpect(jsonPath("$.id", is(product.getId())))
.andExpect(jsonPath("$.name", is(product.getName())))
.andExpect(jsonPath("$.type", is(product.getType())))
.andExpect(jsonPath("$.image", is(product.getImage())));
}
@Test
public void deleteProductTest() throws Exception {
final Product product = prepareProduct();
productService.create(product);
mvc.perform(delete(BASE_PRODUCTS_URL + "/" + product.getId())
.header(authHeaderName, token))
.andExpect(status().isNoContent());
}
}
|
package com.opengamma.analytics.math.interpolation;
import java.util.Arrays;
import com.google.common.primitives.Doubles;
import com.opengamma.analytics.math.function.PiecewisePolynomialWithSensitivityFunction1D;
import com.opengamma.analytics.math.matrix.DoubleMatrix1D;
import com.opengamma.analytics.math.matrix.DoubleMatrix2D;
import com.opengamma.util.ArgumentChecker;
import com.opengamma.util.ParallelArrayBinarySort;
/**
* Filter for local monotonicity of cubic spline interpolation based on
* R. L. Dougherty, A. Edelman, and J. M. Hyman, "Nonnegativity-, Monotonicity-, or Convexity-Preserving Cubic and Quintic Hermite Interpolation"
* Mathematics Of Computation, v. 52, n. 186, April 1989, pp. 471-494.
*
* First, interpolant is computed by another cubic interpolation method. Then the first derivatives are modified such that local monotonicity conditions are satisfied.
*/
public class MonotonicityPreservingCubicSplineInterpolator extends PiecewisePolynomialInterpolator {
private final HermiteCoefficientsProvider _solver = new HermiteCoefficientsProvider();
private final PiecewisePolynomialWithSensitivityFunction1D _function = new PiecewisePolynomialWithSensitivityFunction1D();
private PiecewisePolynomialInterpolator _method;
private static final double EPS = 1.e-7;
private static final double SMALL = 1.e-14;
/**
* Primary interpolation method should be passed
* @param method PiecewisePolynomialInterpolator
*/
public MonotonicityPreservingCubicSplineInterpolator(final PiecewisePolynomialInterpolator method) {
_method = method;
}
@Override
public PiecewisePolynomialResult interpolate(final double[] xValues, final double[] yValues) {
ArgumentChecker.notNull(xValues, "xValues");
ArgumentChecker.notNull(yValues, "yValues");
ArgumentChecker.isTrue(xValues.length == yValues.length | xValues.length + 2 == yValues.length, "(xValues length = yValues length) or (xValues length + 2 = yValues length)");
ArgumentChecker.isTrue(xValues.length > 2, "Data points should be more than 2");
final int nDataPts = xValues.length;
final int yValuesLen = yValues.length;
for (int i = 0; i < nDataPts; ++i) {
ArgumentChecker.isFalse(Double.isNaN(xValues[i]), "xValues containing NaN");
ArgumentChecker.isFalse(Double.isInfinite(xValues[i]), "xValues containing Infinity");
}
for (int i = 0; i < yValuesLen; ++i) {
ArgumentChecker.isFalse(Double.isNaN(yValues[i]), "yValues containing NaN");
ArgumentChecker.isFalse(Double.isInfinite(yValues[i]), "yValues containing Infinity");
}
double[] xValuesSrt = Arrays.copyOf(xValues, nDataPts);
double[] yValuesSrt = new double[nDataPts];
if (nDataPts == yValuesLen) {
yValuesSrt = Arrays.copyOf(yValues, nDataPts);
} else {
yValuesSrt = Arrays.copyOfRange(yValues, 1, nDataPts + 1);
}
ParallelArrayBinarySort.parallelBinarySort(xValuesSrt, yValuesSrt);
for (int i = 1; i < nDataPts; ++i) {
ArgumentChecker.isFalse(xValuesSrt[i - 1] == xValuesSrt[i], "xValues should be distinct");
}
final double[] intervals = _solver.intervalsCalculator(xValuesSrt);
final double[] slopes = _solver.slopesCalculator(yValuesSrt, intervals);
final PiecewisePolynomialResult result = _method.interpolate(xValues, yValues);
ArgumentChecker.isTrue(result.getOrder() == 4, "Primary interpolant is not cubic");
final double[] initialFirst = _function.differentiate(result, xValuesSrt).getData()[0];
final double[] first = firstDerivativeCalculator(intervals, slopes, initialFirst);
final double[][] coefs = _solver.solve(yValuesSrt, intervals, slopes, first);
for (int i = 0; i < nDataPts - 1; ++i) {
for (int j = 0; j < 4; ++j) {
ArgumentChecker.isFalse(Double.isNaN(coefs[i][j]), "Too large input");
ArgumentChecker.isFalse(Double.isInfinite(coefs[i][j]), "Too large input");
}
}
return new PiecewisePolynomialResult(new DoubleMatrix1D(xValuesSrt), new DoubleMatrix2D(coefs), 4, 1);
}
@Override
public PiecewisePolynomialResult interpolate(final double[] xValues, final double[][] yValuesMatrix) {
ArgumentChecker.notNull(xValues, "xValues");
ArgumentChecker.notNull(yValuesMatrix, "yValuesMatrix");
ArgumentChecker.isTrue(xValues.length == yValuesMatrix[0].length | xValues.length + 2 == yValuesMatrix[0].length,
"(xValues length = yValuesMatrix's row vector length) or (xValues length + 2 = yValuesMatrix's row vector length)");
ArgumentChecker.isTrue(xValues.length > 2, "Data points should be more than 2");
final int nDataPts = xValues.length;
final int yValuesLen = yValuesMatrix[0].length;
final int dim = yValuesMatrix.length;
for (int i = 0; i < nDataPts; ++i) {
ArgumentChecker.isFalse(Double.isNaN(xValues[i]), "xValues containing NaN");
ArgumentChecker.isFalse(Double.isInfinite(xValues[i]), "xValues containing Infinity");
}
for (int i = 0; i < yValuesLen; ++i) {
for (int j = 0; j < dim; ++j) {
ArgumentChecker.isFalse(Double.isNaN(yValuesMatrix[j][i]), "yValuesMatrix containing NaN");
ArgumentChecker.isFalse(Double.isInfinite(yValuesMatrix[j][i]), "yValuesMatrix containing Infinity");
}
}
for (int i = 0; i < nDataPts; ++i) {
for (int j = i + 1; j < nDataPts; ++j) {
ArgumentChecker.isFalse(xValues[i] == xValues[j], "xValues should be distinct");
}
}
double[] xValuesSrt = new double[nDataPts];
DoubleMatrix2D[] coefMatrix = new DoubleMatrix2D[dim];
for (int i = 0; i < dim; ++i) {
xValuesSrt = Arrays.copyOf(xValues, nDataPts);
double[] yValuesSrt = new double[nDataPts];
if (nDataPts == yValuesLen) {
yValuesSrt = Arrays.copyOf(yValuesMatrix[i], nDataPts);
} else {
yValuesSrt = Arrays.copyOfRange(yValuesMatrix[i], 1, nDataPts + 1);
}
ParallelArrayBinarySort.parallelBinarySort(xValuesSrt, yValuesSrt);
final double[] intervals = _solver.intervalsCalculator(xValuesSrt);
final double[] slopes = _solver.slopesCalculator(yValuesSrt, intervals);
final PiecewisePolynomialResult result = _method.interpolate(xValues, yValuesMatrix[i]);
ArgumentChecker.isTrue(result.getOrder() == 4, "Primary interpolant is not cubic");
final double[] initialFirst = _function.differentiate(result, xValuesSrt).getData()[0];
final double[] first = firstDerivativeCalculator(intervals, slopes, initialFirst);
coefMatrix[i] = new DoubleMatrix2D(_solver.solve(yValuesSrt, intervals, slopes, first));
}
final int nIntervals = coefMatrix[0].getNumberOfRows();
final int nCoefs = coefMatrix[0].getNumberOfColumns();
double[][] resMatrix = new double[dim * nIntervals][nCoefs];
for (int i = 0; i < nIntervals; ++i) {
for (int j = 0; j < dim; ++j) {
resMatrix[dim * i + j] = coefMatrix[j].getRowVector(i).getData();
}
}
for (int i = 0; i < (nIntervals * dim); ++i) {
for (int j = 0; j < nCoefs; ++j) {
ArgumentChecker.isFalse(Double.isNaN(resMatrix[i][j]), "Too large input");
ArgumentChecker.isFalse(Double.isInfinite(resMatrix[i][j]), "Too large input");
}
}
return new PiecewisePolynomialResult(new DoubleMatrix1D(xValuesSrt), new DoubleMatrix2D(resMatrix), nCoefs, dim);
}
@Override
public PiecewisePolynomialResultsWithSensitivity interpolateWithSensitivity(final double[] xValues, final double[] yValues) {
ArgumentChecker.notNull(xValues, "xValues");
ArgumentChecker.notNull(yValues, "yValues");
ArgumentChecker.isTrue(xValues.length == yValues.length | xValues.length + 2 == yValues.length, "(xValues length = yValues length) or (xValues length + 2 = yValues length)");
ArgumentChecker.isTrue(xValues.length > 2, "Data points should be more than 2");
final int nDataPts = xValues.length;
final int yValuesLen = yValues.length;
for (int i = 0; i < nDataPts; ++i) {
ArgumentChecker.isFalse(Double.isNaN(xValues[i]), "xValues containing NaN");
ArgumentChecker.isFalse(Double.isInfinite(xValues[i]), "xValues containing Infinity");
}
for (int i = 0; i < yValuesLen; ++i) {
ArgumentChecker.isFalse(Double.isNaN(yValues[i]), "yValues containing NaN");
ArgumentChecker.isFalse(Double.isInfinite(yValues[i]), "yValues containing Infinity");
}
double[] yValuesSrt = new double[nDataPts];
if (nDataPts == yValuesLen) {
yValuesSrt = Arrays.copyOf(yValues, nDataPts);
} else {
yValuesSrt = Arrays.copyOfRange(yValues, 1, nDataPts + 1);
}
for (int i = 1; i < nDataPts; ++i) {
ArgumentChecker.isFalse(xValues[i - 1] == xValues[i], "xValues should be distinct");
}
final double[] intervals = _solver.intervalsCalculator(xValues);
final double[] slopes = _solver.slopesCalculator(yValuesSrt, intervals);
final DoubleMatrix2D[] slopesSensitivityWithAbs = slopesSensitivityWithAbsCalculator(intervals, slopes);
final double[][] slopesSensitivity = slopesSensitivityWithAbs[0].getData();
final double[][] slopesAbsSensitivity = slopesSensitivityWithAbs[1].getData();
DoubleMatrix1D[] firstWithSensitivity = new DoubleMatrix1D[nDataPts + 1];
/*
* Mode sensitivity is not computed analytically for |s_i| = |s_{i+1}| or s_{i-1}*h_{i} + s_{i}*h_{i-1} = 0.
* Centered finite difference approximation is used in such cases
*/
final boolean sym = checkSymm(slopes);
if (sym == true) {
final PiecewisePolynomialResult result = _method.interpolate(xValues, yValues);
ArgumentChecker.isTrue(result.getOrder() == 4, "Primary interpolant is not cubic");
final double[] initialFirst = _function.differentiate(result, xValues).getData()[0];
firstWithSensitivity[0] = new DoubleMatrix1D(firstDerivativeCalculator(intervals, slopes, initialFirst));
int nExtra = nDataPts == yValuesLen ? 0 : 1;
final double[] yValuesUp = Arrays.copyOf(yValues, nDataPts + 2 * nExtra);
final double[] yValuesDw = Arrays.copyOf(yValues, nDataPts + 2 * nExtra);
final double[][] tmp = new double[nDataPts][nDataPts];
for (int i = nExtra; i < nDataPts + nExtra; ++i) {
final double den = Math.abs(yValues[i]) < SMALL ? EPS : yValues[i] * EPS;
yValuesUp[i] = Math.abs(yValues[i]) < SMALL ? EPS : yValues[i] * (1. + EPS);
yValuesDw[i] = Math.abs(yValues[i]) < SMALL ? -EPS : yValues[i] * (1. - EPS);
final double[] yValuesSrtUp = Arrays.copyOfRange(yValuesUp, nExtra, nDataPts + nExtra);
final double[] yValuesSrtDw = Arrays.copyOfRange(yValuesDw, nExtra, nDataPts + nExtra);
final double[] slopesUp = _solver.slopesCalculator(yValuesSrtUp, intervals);
final double[] slopesDw = _solver.slopesCalculator(yValuesSrtDw, intervals);
final double[] initialFirstUp = _function.differentiate(_method.interpolate(xValues, yValuesUp), xValues).getData()[0];
final double[] initialFirstDw = _function.differentiate(_method.interpolate(xValues, yValuesDw), xValues).getData()[0];
final double[] firstUp = firstDerivativeCalculator(intervals, slopesUp, initialFirstUp);
final double[] firstDw = firstDerivativeCalculator(intervals, slopesDw, initialFirstDw);
for (int j = 0; j < nDataPts; ++j) {
tmp[j][i - nExtra] = 0.5 * (firstUp[j] - firstDw[j]) / den;
}
yValuesUp[i] = yValues[i];
yValuesDw[i] = yValues[i];
}
for (int i = 0; i < nDataPts; ++i) {
firstWithSensitivity[i + 1] = new DoubleMatrix1D(tmp[i]);
}
} else {
final PiecewisePolynomialResultsWithSensitivity resultWithSensitivity = _method.interpolateWithSensitivity(xValues, yValues);
ArgumentChecker.isTrue(resultWithSensitivity.getOrder() == 4, "Primary interpolant is not cubic");
final double[] initialFirst = _function.differentiate(resultWithSensitivity, xValues).getData()[0];
final DoubleMatrix1D[] initialFirstSense = _function.differentiateNodeSensitivity(resultWithSensitivity, xValues);
firstWithSensitivity = firstDerivativeWithSensitivityCalculator(intervals, slopes, slopesSensitivity, slopesAbsSensitivity, initialFirst, initialFirstSense);
}
final DoubleMatrix2D[] resMatrix = _solver.solveWithSensitivity(yValuesSrt, intervals, slopes, slopesSensitivity, firstWithSensitivity);
for (int k = 0; k < nDataPts; k++) {
DoubleMatrix2D m = resMatrix[k];
final int rows = m.getNumberOfRows();
final int cols = m.getNumberOfColumns();
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
ArgumentChecker.isTrue(Doubles.isFinite(m.getEntry(i, j)), "Matrix contains a NaN or infinite");
}
}
}
final DoubleMatrix2D coefMatrix = resMatrix[0];
final DoubleMatrix2D[] coefSenseMatrix = new DoubleMatrix2D[nDataPts - 1];
System.arraycopy(resMatrix, 1, coefSenseMatrix, 0, nDataPts - 1);
final int nCoefs = coefMatrix.getNumberOfColumns();
return new PiecewisePolynomialResultsWithSensitivity(new DoubleMatrix1D(xValues), coefMatrix, nCoefs, 1, coefSenseMatrix);
}
@Override
public PiecewisePolynomialInterpolator getPrimaryMethod() {
return _method;
}
/**
* First derivatives are modified such that cubic interpolant has the same sign as linear interpolator
* @param yValues
* @param intervals
* @param slopes
* @param initialFirst
* @return first derivative
*/
private double[] firstDerivativeCalculator(final double[] intervals, final double[] slopes, final double[] initialFirst) {
final int nDataPts = intervals.length + 1;
double[] res = new double[nDataPts];
final double[][] pSlopes = parabolaSlopesCalculator(intervals, slopes);
for (int i = 1; i < nDataPts - 1; ++i) {
double refValue = 3. * Math.min(Math.abs(slopes[i - 1]), Math.min(Math.abs(slopes[i]), Math.abs(pSlopes[i - 1][1])));
if (i > 1) {
final double sig1 = Math.signum(pSlopes[i - 1][1]);
final double sig2 = Math.signum(pSlopes[i - 1][0]);
final double sig3 = Math.signum(slopes[i - 1] - slopes[i - 2]);
final double sig4 = Math.signum(slopes[i] - slopes[i - 1]);
if (Math.abs(sig1 - sig2) <= 1. && Math.abs(sig1 - sig3) <= 1. && Math.abs(sig1 - sig4) <= 1. && Math.abs(sig2 - sig3) <= 1. && Math.abs(sig2 - sig4) <= 1. && Math.abs(sig3 - sig4) <= 1.) {
refValue = 3. * Math.max(refValue, 1.5 * Math.min(Math.abs(pSlopes[i - 1][0]), Math.abs(pSlopes[i - 1][1])));
}
}
if (i < nDataPts - 2) {
final double sig1 = Math.signum(-pSlopes[i - 1][1]);
final double sig2 = Math.signum(-pSlopes[i - 1][2]);
final double sig3 = Math.signum(slopes[i + 1] - slopes[i]);
final double sig4 = Math.signum(slopes[i] - slopes[i - 1]);
if (Math.abs(sig1 - sig2) <= 1. && Math.abs(sig1 - sig3) <= 1. && Math.abs(sig1 - sig4) <= 1. && Math.abs(sig2 - sig3) <= 1. && Math.abs(sig2 - sig4) <= 1. && Math.abs(sig3 - sig4) <= 1.) {
refValue = 3. * Math.max(refValue, 1.5 * Math.min(Math.abs(pSlopes[i - 1][2]), Math.abs(pSlopes[i - 1][1])));
}
}
res[i] = Math.signum(initialFirst[i]) != Math.signum(pSlopes[i - 1][1]) ? 0. : Math.signum(initialFirst[i]) * Math.min(Math.abs(initialFirst[i]), refValue);
}
res[0] = Math.signum(initialFirst[0]) != Math.signum(slopes[0]) ? 0. : Math.signum(initialFirst[0]) * Math.min(Math.abs(initialFirst[0]), 3. * Math.abs(slopes[0]));
res[nDataPts - 1] = Math.signum(initialFirst[nDataPts - 1]) != Math.signum(slopes[nDataPts - 2]) ? 0. : Math.signum(initialFirst[nDataPts - 1])
* Math.min(Math.abs(initialFirst[nDataPts - 1]), 3. * Math.abs(slopes[nDataPts - 2]));
return res;
}
private DoubleMatrix1D[] firstDerivativeWithSensitivityCalculator(final double[] intervals, final double[] slopes, final double[][] slopesSensitivity,
final double[][] slopesAbsSensitivity, final double[] initialFirst, final DoubleMatrix1D[] initialFirstSense) {
final int nDataPts = intervals.length + 1;
final DoubleMatrix1D[] res = new DoubleMatrix1D[nDataPts + 1];
final double[] first = new double[nDataPts];
final double[][] pSlopes = parabolaSlopesCalculator(intervals, slopes);
final DoubleMatrix2D[] pSlopesAbsSensitivity = parabolaSlopesAbstSensitivityCalculator(intervals, slopesSensitivity, pSlopes);
for (int i = 1; i < nDataPts - 1; ++i) {
final double[] tmpSense = new double[nDataPts];
final double sigInitialFirst = Math.signum(initialFirst[i]);
if (sigInitialFirst * Math.signum(pSlopes[i - 1][1]) < 0.) {
first[i] = 0.;
Arrays.fill(tmpSense, 0.);
} else {
double[] refValueWithSense = factoredMinWithSensitivityFinder(Math.abs(slopes[i - 1]), slopesAbsSensitivity[i - 1], Math.abs(slopes[i]), slopesAbsSensitivity[i], Math.abs(pSlopes[i - 1][1]),
pSlopesAbsSensitivity[1].getData()[i - 1]);
final double[] refSense = new double[nDataPts];
System.arraycopy(refValueWithSense, 1, refSense, 0, nDataPts);
if (i > 1) {
final double sig1 = Math.signum(pSlopes[i - 1][1]);
final double sig2 = Math.signum(pSlopes[i - 1][0]);
final double sig3 = Math.signum(slopes[i - 1] - slopes[i - 2]);
final double sig4 = Math.signum(slopes[i] - slopes[i - 1]);
if (Math.abs(sig1 - sig2) <= 1. && Math.abs(sig1 - sig3) <= 1. && Math.abs(sig1 - sig4) <= 1. && Math.abs(sig2 - sig3) <= 1. && Math.abs(sig2 - sig4) <= 1. && Math.abs(sig3 - sig4) <= 1.) {
refValueWithSense = modifyRefValueWithSensitivity(refValueWithSense[0], refSense, Math.abs(pSlopes[i - 1][0]), pSlopesAbsSensitivity[0].getData()[i - 2], Math.abs(pSlopes[i - 1][1]),
pSlopesAbsSensitivity[1].getData()[i - 1]);
}
}
if (i < nDataPts - 2) {
final double sig1 = Math.signum(-pSlopes[i - 1][1]);
final double sig2 = Math.signum(-pSlopes[i - 1][2]);
final double sig3 = Math.signum(slopes[i + 1] - slopes[i]);
final double sig4 = Math.signum(slopes[i] - slopes[i - 1]);
if (Math.abs(sig1 - sig2) <= 1. && Math.abs(sig1 - sig3) <= 1. && Math.abs(sig1 - sig4) <= 1. && Math.abs(sig2 - sig3) <= 1. && Math.abs(sig2 - sig4) <= 1. && Math.abs(sig3 - sig4) <= 1.) {
refValueWithSense = modifyRefValueWithSensitivity(refValueWithSense[0], refSense, Math.abs(pSlopes[i - 1][2]), pSlopesAbsSensitivity[2].getData()[i - 1], Math.abs(pSlopes[i - 1][1]),
pSlopesAbsSensitivity[1].getData()[i - 1]);
}
}
final double absFirst = Math.abs(initialFirst[i]);
if (absFirst == refValueWithSense[0]) {
first[i] = initialFirst[i];
for (int k = 0; k < nDataPts; ++k) {
tmpSense[k] = 0.5 * (initialFirstSense[i].getData()[k] + sigInitialFirst * refValueWithSense[k + 1]);
}
} else {
if (absFirst < refValueWithSense[0]) {
first[i] = initialFirst[i];
System.arraycopy(initialFirstSense[i].getData(), 0, tmpSense, 0, nDataPts);
} else {
first[i] = sigInitialFirst * refValueWithSense[0];
for (int k = 0; k < nDataPts; ++k) {
tmpSense[k] = sigInitialFirst * refValueWithSense[k + 1];
}
}
}
}
res[i + 1] = new DoubleMatrix1D(tmpSense);
}
final double[] tmpSenseIni = new double[nDataPts];
final double sigFirstIni = Math.signum(initialFirst[0]);
if (sigFirstIni * Math.signum(slopes[0]) < 0.) {
first[0] = 0.;
Arrays.fill(tmpSenseIni, 0.);
} else {
if (Math.abs(initialFirst[0]) > SMALL && Math.abs(slopes[0]) < SMALL) {
first[0] = 0.;
Arrays.fill(tmpSenseIni, 0.);
tmpSenseIni[0] = -1.5 / intervals[0];
tmpSenseIni[1] = 1.5 / intervals[0];
} else {
final double absFirst = Math.abs(initialFirst[0]);
final double modSlope = 3. * Math.abs(slopes[0]);
if (absFirst == modSlope) {
first[0] = initialFirst[0];
for (int k = 0; k < nDataPts; ++k) {
tmpSenseIni[k] = 0.5 * (initialFirstSense[0].getData()[k] + 3. * sigFirstIni * slopesAbsSensitivity[0][k]);
}
} else {
if (absFirst < modSlope) {
first[0] = initialFirst[0];
final double factor = Math.abs(initialFirst[0]) < SMALL ? 0.5 : 1.;
for (int k = 0; k < nDataPts; ++k) {
tmpSenseIni[k] = factor * initialFirstSense[0].getData()[k];
}
} else {
first[0] = sigFirstIni * modSlope;
for (int k = 0; k < nDataPts; ++k) {
tmpSenseIni[k] = 3. * sigFirstIni * slopesAbsSensitivity[0][k];
}
}
}
}
}
res[1] = new DoubleMatrix1D(tmpSenseIni);
final double[] tmpSenseFin = new double[nDataPts];
final double sigFirstFin = Math.signum(initialFirst[nDataPts - 1]);
if (sigFirstFin * Math.signum(slopes[nDataPts - 2]) < 0.) {
first[nDataPts - 1] = 0.;
Arrays.fill(tmpSenseFin, 0.);
} else {
if (Math.abs(initialFirst[nDataPts - 1]) > SMALL && Math.abs(slopes[nDataPts - 2]) < SMALL) {
first[nDataPts - 1] = 0.;
Arrays.fill(tmpSenseFin, 0.);
tmpSenseFin[nDataPts - 2] = -1.5 / intervals[nDataPts - 2];
tmpSenseFin[nDataPts - 1] = 1.5 / intervals[nDataPts - 2];
} else {
final double absFirst = Math.abs(initialFirst[nDataPts - 1]);
final double modSlope = 3. * Math.abs(slopes[nDataPts - 2]);
if (absFirst == modSlope) {
first[nDataPts - 1] = initialFirst[nDataPts - 1];
for (int k = 0; k < nDataPts; ++k) {
tmpSenseFin[k] = 0.5 * (initialFirstSense[nDataPts - 1].getData()[k] + 3. * sigFirstFin * slopesAbsSensitivity[nDataPts - 2][k]);
}
} else {
if (absFirst < modSlope) {
first[nDataPts - 1] = initialFirst[nDataPts - 1];
final double factor = Math.abs(initialFirst[nDataPts - 1]) < SMALL ? 0.5 : 1.;
for (int k = 0; k < nDataPts; ++k) {
tmpSenseFin[k] = factor * initialFirstSense[nDataPts - 1].getData()[k];
}
} else {
first[nDataPts - 1] = sigFirstFin * modSlope;
for (int k = 0; k < nDataPts; ++k) {
tmpSenseFin[k] = 3. * sigFirstFin * slopesAbsSensitivity[nDataPts - 2][k];
}
}
}
}
}
res[nDataPts] = new DoubleMatrix1D(tmpSenseFin);
res[0] = new DoubleMatrix1D(first);
return res;
}
/**
* @param intervals
* @param slopes
* @return Parabola slopes, each row vactor is (p^{-1}, p^{0}, p^{1}) for xValues_1,...,xValues_{nDataPts-2}
*/
private double[][] parabolaSlopesCalculator(final double[] intervals, final double[] slopes) {
final int nData = intervals.length + 1;
double[][] res = new double[nData - 2][3];
res[0][0] = Double.POSITIVE_INFINITY;
res[0][1] = (slopes[0] * intervals[1] + slopes[1] * intervals[0]) / (intervals[0] + intervals[1]);
res[0][2] = (slopes[1] * (2. * intervals[1] + intervals[2]) - slopes[2] * intervals[1]) / (intervals[1] + intervals[2]);
for (int i = 1; i < nData - 3; ++i) {
res[i][0] = (slopes[i] * (2. * intervals[i] + intervals[i - 1]) - slopes[i - 1] * intervals[i]) / (intervals[i - 1] + intervals[i]);
res[i][1] = (slopes[i] * intervals[i + 1] + slopes[i + 1] * intervals[i]) / (intervals[i] + intervals[i + 1]);
res[i][2] = (slopes[i + 1] * (2. * intervals[i + 1] + intervals[i + 2]) - slopes[i + 2] * intervals[i + 1]) / (intervals[i + 1] + intervals[i + 2]);
}
res[nData - 3][0] = (slopes[nData - 3] * (2. * intervals[nData - 3] + intervals[nData - 4]) - slopes[nData - 4] * intervals[nData - 3]) / (intervals[nData - 4] + intervals[nData - 3]);
res[nData - 3][1] = (slopes[nData - 3] * intervals[nData - 2] + slopes[nData - 2] * intervals[nData - 3]) / (intervals[nData - 3] + intervals[nData - 2]);
res[nData - 3][2] = Double.POSITIVE_INFINITY;
return res;
}
private DoubleMatrix2D[] parabolaSlopesAbstSensitivityCalculator(final double[] intervals, final double[][] slopeSensitivity, final double[][] parabolaSlopes) {
final DoubleMatrix2D[] res = new DoubleMatrix2D[3];
final int nData = intervals.length + 1;
final double[][] left = new double[nData - 3][nData];
final double[][] center = new double[nData - 2][nData];
final double[][] right = new double[nData - 3][nData];
for (int i = 0; i < nData - 3; ++i) {
final double sigLeft = Math.signum(parabolaSlopes[i + 1][0]);
final double sigCenter = Math.signum(parabolaSlopes[i][1]);
final double sigRight = Math.signum(parabolaSlopes[i][2]);
if (sigLeft == 0.) {
Arrays.fill(left[i], 0.);
}
if (sigCenter == 0.) {
Arrays.fill(center[i], 0.);
}
if (sigRight == 0.) {
Arrays.fill(right[i], 0.);
}
for (int k = 0; k < nData; ++k) {
left[i][k] = sigLeft * (slopeSensitivity[i + 1][k] * (2. * intervals[i + 1] + intervals[i]) - slopeSensitivity[i][k] * intervals[i + 1]) /
(intervals[i] + intervals[i + 1]);
center[i][k] = sigCenter * (slopeSensitivity[i][k] * intervals[i + 1] + slopeSensitivity[i + 1][k] * intervals[i]) / (intervals[i] + intervals[i + 1]);
right[i][k] = sigRight * (slopeSensitivity[i + 1][k] * (2. * intervals[i + 1] + intervals[i + 2]) - slopeSensitivity[i + 2][k] * intervals[i + 1]) /
(intervals[i + 1] + intervals[i + 2]);
}
}
final double sigCenterFin = Math.signum(parabolaSlopes[nData - 3][1]);
if (sigCenterFin == 0.) {
Arrays.fill(center[nData - 3], 0.);
}
for (int k = 0; k < nData; ++k) {
center[nData - 3][k] = sigCenterFin * (slopeSensitivity[nData - 3][k] * intervals[nData - 2] + slopeSensitivity[nData - 2][k] * intervals[nData - 3]) /
(intervals[nData - 3] + intervals[nData - 2]);
}
res[0] = new DoubleMatrix2D(left);
res[1] = new DoubleMatrix2D(center);
res[2] = new DoubleMatrix2D(right);
return res;
}
private DoubleMatrix2D[] slopesSensitivityWithAbsCalculator(final double[] intervals, final double[] slopes) {
final int nDataPts = intervals.length + 1;
final DoubleMatrix2D[] res = new DoubleMatrix2D[2];
final double[][] slopesSensitivity = new double[nDataPts - 1][nDataPts];
final double[][] absSlopesSensitivity = new double[nDataPts - 1][nDataPts];
for (int i = 0; i < nDataPts - 1; ++i) {
final double sign = Math.signum(slopes[i]);
Arrays.fill(slopesSensitivity[i], 0.);
Arrays.fill(absSlopesSensitivity[i], 0.);
slopesSensitivity[i][i] = -1. / intervals[i];
slopesSensitivity[i][i + 1] = 1. / intervals[i];
if (sign > 0.) {
absSlopesSensitivity[i][i] = slopesSensitivity[i][i];
absSlopesSensitivity[i][i + 1] = slopesSensitivity[i][i + 1];
}
if (sign < 0.) {
absSlopesSensitivity[i][i] = -slopesSensitivity[i][i];
absSlopesSensitivity[i][i + 1] = -slopesSensitivity[i][i + 1];
}
}
res[0] = new DoubleMatrix2D(slopesSensitivity);
res[1] = new DoubleMatrix2D(absSlopesSensitivity);
return res;
}
private double[] factoredMinWithSensitivityFinder(final double val1, final double[] val1Sensitivity, final double val2, final double[] val2Sensitivity, final double val3,
final double[] val3Sensitivity) {
final int nData = val1Sensitivity.length;
final double[] res = new double[nData + 1];
double tmpRef = 0.;
final double[] tmpSensitivity = new double[nData];
if (val1 < val2) {
tmpRef = val1;
for (int i = 0; i < nData; ++i) {
tmpSensitivity[i] = val1Sensitivity[i];
}
} else {
tmpRef = val2;
for (int i = 0; i < nData; ++i) {
tmpSensitivity[i] = val2Sensitivity[i];
}
}
if (val3 == tmpRef) {
res[0] = 3. * val3;
for (int i = 0; i < nData; ++i) {
res[i + 1] = 1.5 * (val3Sensitivity[i] + tmpSensitivity[i]);
}
} else {
if (val3 < tmpRef) {
res[0] = 3. * val3;
for (int i = 0; i < nData; ++i) {
res[i + 1] = 3. * val3Sensitivity[i];
}
} else {
res[0] = 3. * tmpRef;
for (int i = 0; i < nData; ++i) {
res[i + 1] = 3. * tmpSensitivity[i];
}
}
}
return res;
}
private double[] modifyRefValueWithSensitivity(final double refVal, final double[] refValSensitivity, final double val1, final double[] val1Sensitivity, final double val2,
final double[] val2Sensitivity) {
final int nData = refValSensitivity.length;
final double absVal1 = Math.abs(val1);
final double absVal2 = Math.abs(val2);
final double[] res = new double[nData + 1];
double tmpRef = 0.;
final double[] tmpSensitivity = new double[nData];
if (absVal1 == absVal2) {
tmpRef = 1.5 * absVal1;
for (int i = 0; i < nData; ++i) {
tmpSensitivity[i] = 0.75 * (val1Sensitivity[i] + val2Sensitivity[i]);
}
} else {
if (absVal1 < absVal2) {
tmpRef = 1.5 * absVal1;
for (int i = 0; i < nData; ++i) {
tmpSensitivity[i] = 1.5 * (val1Sensitivity[i]);
}
} else {
tmpRef = 1.5 * absVal2;
for (int i = 0; i < nData; ++i) {
tmpSensitivity[i] = 1.5 * (val2Sensitivity[i]);
}
}
}
if (refVal == tmpRef) {
res[0] = 3. * refVal;
for (int i = 0; i < nData; ++i) {
res[i + 1] = 1.5 * (refValSensitivity[i] + tmpSensitivity[i]);
}
} else {
if (refVal > tmpRef) {
res[0] = 3. * refVal;
for (int i = 0; i < nData; ++i) {
res[i + 1] = 3. * refValSensitivity[i];
}
} else {
res[0] = 3. * tmpRef;
for (int i = 0; i < nData; ++i) {
res[i + 1] = 3. * tmpSensitivity[i];
}
}
}
return res;
}
private boolean checkSymm(final double[] slopes) {
final int nDataM2 = slopes.length - 1;
for (int i = 0; i < nDataM2; ++i) {
if (Math.abs(slopes[i]) == Math.abs(slopes[i + 1])) {
return true;
}
}
return false;
}
}
|
package org.zanata.rest.service;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import org.apache.commons.lang.StringUtils;
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.AutoCreate;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.annotations.intercept.BypassInterceptors;
import org.jboss.seam.log.Log;
import org.jboss.seam.log.Logging;
import org.zanata.common.ContentState;
import org.zanata.common.ResourceType;
import org.zanata.model.HDocument;
import org.zanata.model.HLocale;
import org.zanata.model.HPerson;
import org.zanata.model.HSimpleComment;
import org.zanata.model.HTextFlow;
import org.zanata.model.HTextFlowTarget;
import org.zanata.model.HasSimpleComment;
import org.zanata.model.po.HPoHeader;
import org.zanata.model.po.HPoTargetHeader;
import org.zanata.model.po.HPotEntryData;
import org.zanata.rest.dto.Person;
import org.zanata.rest.dto.extensions.comment.SimpleComment;
import org.zanata.rest.dto.extensions.gettext.AbstractResourceMetaExtension;
import org.zanata.rest.dto.extensions.gettext.HeaderEntry;
import org.zanata.rest.dto.extensions.gettext.PoHeader;
import org.zanata.rest.dto.extensions.gettext.PoTargetHeader;
import org.zanata.rest.dto.extensions.gettext.PotEntryHeader;
import org.zanata.rest.dto.extensions.gettext.TextFlowExtension;
import org.zanata.rest.dto.extensions.gettext.TextFlowTargetExtension;
import org.zanata.rest.dto.extensions.gettext.TranslationsResourceExtension;
import org.zanata.rest.dto.resource.AbstractResourceMeta;
import org.zanata.rest.dto.resource.ExtensionSet;
import org.zanata.rest.dto.resource.Resource;
import org.zanata.rest.dto.resource.TextFlow;
import org.zanata.rest.dto.resource.TextFlowTarget;
import org.zanata.rest.dto.resource.TranslationsResource;
import org.zanata.util.StringUtil;
@Name("resourceUtils")
@Scope(ScopeType.STATELESS)
@AutoCreate
@BypassInterceptors
public class ResourceUtils
{
/**
* Newline character used for multi-line comments
*/
private static final char NEWLINE = '\n';
private static final String ZANATA_TAG = "#zanata";
private static final String PO_DATE_FORMAT = "yyyy-MM-dd hh:mmZ";
private static final Log log = Logging.getLog(ResourceUtils.class);
/**
* Merges the list of TextFlows into the target HDocument, adding and obsoleting TextFlows as necessary.
* @param from
* @param to
* @return
*/
boolean transferFromTextFlows(List<TextFlow> from, HDocument to, Set<String> enabledExtensions, int nextDocRev)
{
boolean changed = false;
to.getTextFlows().clear();
Set<String> incomingIds = new HashSet<String>();
Set<String> previousIds = new HashSet<String>(to.getAllTextFlows().keySet());
for (TextFlow tf : from)
{
if (!incomingIds.add(tf.getId()))
{
Response response = Response.status(Status.BAD_REQUEST).entity("encountered TextFlow with duplicate ID " + tf.getId()).build();
throw new WebApplicationException(response);
}
HTextFlow textFlow;
if (previousIds.contains(tf.getId()))
{
previousIds.remove(tf.getId());
textFlow = to.getAllTextFlows().get(tf.getId());
textFlow.setObsolete(false);
// avoid changing revision when resurrecting an unchanged TF
if (transferFromTextFlow(tf, textFlow, enabledExtensions))
{// content has changed
textFlow.setRevision(nextDocRev);
changed = true;
for (HTextFlowTarget targ : textFlow.getTargets().values())
{
// if (targ.getState() != ContentState.New)
if (targ.getState() == ContentState.Approved)
{
targ.setState(ContentState.NeedReview);
targ.setVersionNum(targ.getVersionNum() + 1);
}
}
log.debug("TextFlow with id {0} has changed", tf.getId());
}
}
else
{
textFlow = new HTextFlow();
textFlow.setDocument(to);
textFlow.setResId(tf.getId());
textFlow.setRevision(nextDocRev);
transferFromTextFlow(tf, textFlow, enabledExtensions);
changed = true;
log.debug("TextFlow with id {0} is new", tf.getId());
}
to.getTextFlows().add(textFlow);
to.getAllTextFlows().put(textFlow.getResId(), textFlow);
}
// set remaining textflows to obsolete.
for (String id : previousIds)
{
HTextFlow textFlow = to.getAllTextFlows().get(id);
if (!textFlow.isObsolete())
{
changed = true;
log.debug("TextFlow with id {0} is now obsolete", id);
textFlow.setRevision(to.getRevision());
textFlow.setObsolete(true);
}
}
if (changed)
to.setRevision(nextDocRev);
return changed;
}
/**
* Merges from the DTO Resource into HDocument, adding and obsoleting textflows, including metadata and the specified extensions
* @param from
* @param to
* @param enabledExtensions
* @return
*/
public boolean transferFromResource(Resource from, HDocument to, Set<String> enabledExtensions, HLocale locale, int nextDocRev)
{
boolean changed = false;
changed |= transferFromResourceMetadata(from, to, enabledExtensions, locale, nextDocRev);
changed |= transferFromTextFlows(from.getTextFlows(), to, enabledExtensions, nextDocRev);
return changed;
}
/**
* Transfers metadata and the specified extensions from DTO AbstractResourceMeta into HDocument
* @param from
* @param to
* @param enabledExtensions
* @return
*/
public boolean transferFromResourceMetadata(AbstractResourceMeta from, HDocument to, Set<String> enabledExtensions, HLocale locale, int nextDocRev)
{
boolean changed = false;
// name
if (!equals(from.getName(), to.getDocId()))
{
to.setFullPath(from.getName());
changed = true;
}
// locale
if (!equals(from.getLang(), to.getLocale().getLocaleId()))
{
log.debug("locale:" + from.getLang());
to.setLocale(locale);
changed = true;
}
// contentType
if (!equals(from.getContentType(), to.getContentType()))
{
to.setContentType(from.getContentType());
changed = true;
}
// handle extensions
changed |= transferFromResourceExtensions(from.getExtensions(true), to, enabledExtensions);
if (changed)
to.setRevision(nextDocRev);
return changed;
}
/**
* Transfers from DTO TextFlowTarget into HTextFlowTarget
* @param from
* @param to
* @return
* @todo merge with {@link #transferFromTextFlowTargetExtensions}
*/
public boolean transferFromTextFlowTarget(TextFlowTarget from, HTextFlowTarget to)
{
boolean changed = false;
if (!equals(from.getContent(), to.getContent()))
{
to.setContent(from.getContent());
changed = true;
}
if (!equals(from.getState(), to.getState()))
{
to.setState(from.getState());
changed = true;
}
if (changed)
{
to.setVersionNum(to.getVersionNum() + 1);
}
return changed;
}
/**
* Transfers the specified extensions from DTO AbstractResourceMeta into HDocument
* @param from
* @param to
* @param enabledExtensions
* @return
* @see #transferFromResource
*/
private boolean transferFromResourceExtensions(ExtensionSet<AbstractResourceMetaExtension> from, HDocument to, Set<String> enabledExtensions)
{
boolean changed = false;
if (enabledExtensions.contains(PoHeader.ID))
{
PoHeader poHeaderExt = from.findByType(PoHeader.class);
if (poHeaderExt != null)
{
HPoHeader poHeader = to.getPoHeader();
if (poHeader == null)
{
log.debug("create a new HPoHeader");
poHeader = new HPoHeader();
}
changed |= transferFromPoHeader(poHeaderExt, poHeader);
if (to.getPoHeader() == null && changed)
{
to.setPoHeader(poHeader);
}
}
}
return changed;
}
/**
* Transfers enabled extensions from TranslationsResource into HDocument for a single locale
* @param from
* @param to
* @param enabledExtensions
* @param locale
* @param mergeType
* @return
* @see #transferToTranslationsResourceExtensions
*/
public boolean transferFromTranslationsResourceExtensions(ExtensionSet<TranslationsResourceExtension> from, HDocument to, Set<String> enabledExtensions, HLocale locale, MergeType mergeType)
{
boolean changed = false;
if (enabledExtensions.contains(PoTargetHeader.ID))
{
PoTargetHeader fromTargetHeader = from.findByType(PoTargetHeader.class);
if (fromTargetHeader != null)
{
log.debug("found PO header for locale: {0}", locale);
HPoTargetHeader toTargetHeader = to.getPoTargetHeaders().get(locale);
if (toTargetHeader == null)
{
changed = true;
toTargetHeader = new HPoTargetHeader();
toTargetHeader.setTargetLanguage(locale);
toTargetHeader.setDocument(to);
transferFromPoTargetHeader(fromTargetHeader, toTargetHeader, MergeType.IMPORT); // return value not needed
to.getPoTargetHeaders().put(locale, toTargetHeader);
}
else
{
changed |= transferFromPoTargetHeader(fromTargetHeader, toTargetHeader, mergeType);
}
}
else
{
changed |= to.getPoTargetHeaders().remove(locale) != null;
}
}
return changed;
}
/**
* Transfers enabled extensions from DTO TextFlowTarget to HTextFlowTarget
* @param extensions
* @param hTarget
* @param enabledExtensions
* @return
* @todo merge with {@link #transferFromTextFlowTarget}
*/
public boolean transferFromTextFlowTargetExtensions(ExtensionSet<TextFlowTargetExtension> extensions, HTextFlowTarget hTarget, Set<String> enabledExtensions)
{
boolean changed = false;
if (enabledExtensions.contains(SimpleComment.ID))
{
SimpleComment comment = extensions.findByType(SimpleComment.class);
if (comment != null)
{
changed |= transferFromComment(comment, hTarget);
}
}
return changed;
}
/**
* Transfers from DTO SimpleComment to a Hibernate object's "comment" property
* @param from
* @param to
* @return
*/
private boolean transferFromComment(SimpleComment from, HasSimpleComment to)
{
HSimpleComment hComment = to.getComment();
if (hComment == null)
{
hComment = new HSimpleComment();
}
if (!equals(from.getValue(), hComment.getComment()))
{
hComment.setComment(from.getValue());
to.setComment(hComment);
return true;
}
return false;
}
private boolean transferFromTextFlowExtensions(ExtensionSet<TextFlowExtension> from, HTextFlow to, Set<String> enabledExtensions)
{
boolean changed = false;
if (enabledExtensions.contains(PotEntryHeader.ID))
{
PotEntryHeader entryHeader = from.findByType(PotEntryHeader.class);
if (entryHeader != null)
{
HPotEntryData hEntryHeader = to.getPotEntryData();
if (hEntryHeader == null)
{
changed = true;
hEntryHeader = new HPotEntryData();
to.setPotEntryData(hEntryHeader);
log.debug("set potentryheader");
}
changed |= transferFromPotEntryHeader(entryHeader, hEntryHeader);
}
}
if (enabledExtensions.contains(SimpleComment.ID))
{
SimpleComment comment = from.findByType(SimpleComment.class);
if (comment != null)
{
HSimpleComment hComment = to.getComment();
if (hComment == null)
{
hComment = new HSimpleComment();
}
if (!equals(comment.getValue(), hComment.getComment()))
{
changed = true;
hComment.setComment(comment.getValue());
to.setComment(hComment);
log.debug("set comment:{0}", comment.getValue());
}
}
}
return changed;
}
/**
* @see #transferToPotEntryHeader(HPotEntryData, PotEntryHeader)
* @param from
* @param to
* @return
*/
private boolean transferFromPotEntryHeader(PotEntryHeader from, HPotEntryData to)
{
boolean changed = false;
if (!equals(from.getContext(), to.getContext()))
{
changed = true;
to.setContext(from.getContext());
}
String flags = StringUtil.concat(from.getFlags(), ',');
if (!equals(flags, to.getFlags()))
{
changed = true;
to.setFlags(flags);
}
String refs = StringUtil.concat(from.getReferences(), ',');
if (!equals(refs, to.getReferences()))
{
changed = true;
to.setReferences(refs);
}
return changed;
}
/**
*
* @param from
* @param to
* @param mergeType
* @return
* @see #transferFromTranslationsResourceExtensions
* @see #transferToPoTargetHeader
*/
private boolean transferFromPoTargetHeader(PoTargetHeader from, HPoTargetHeader to, MergeType mergeType)
{
boolean changed = pushPoTargetComment(from, to, mergeType);
// TODO we should probably block PoHeader/POT-specific entries
// ie POT-Creation-Date, Project-Id-Version, Report-Msgid-Bugs-To
String entries = PoUtility.listToHeader(from.getEntries());
if (!equals(entries, to.getEntries()))
{
to.setEntries(entries);
changed = true;
}
return changed;
}
/**
*
* @param fromHeader
* @param toHeader
* @param mergeType
* @return
* @see #pullPoTargetComment
*/
protected boolean pushPoTargetComment(PoTargetHeader fromHeader, HPoTargetHeader toHeader, MergeType mergeType)
{
boolean changed = false;
HSimpleComment hComment = toHeader.getComment();
if (hComment == null)
{
hComment = new HSimpleComment();
}
String fromComment = fromHeader.getComment();
String toComment = hComment.getComment();
if (!equals(fromComment, toComment))
{
// skip #zanata lines
List<String> fromLines = splitLines(fromComment, ZANATA_TAG);
StringBuilder sb = new StringBuilder(fromComment.length());
switch (mergeType)
{
case IMPORT:
for (String line : fromLines)
{
if (sb.length() != 0)
sb.append(NEWLINE);
sb.append(line);
changed = true;
}
break;
default: // AUTO or anything else will merge comments
// to merge, we just append new lines, skip old lines
List<String> toLines = Collections.emptyList();
if (toComment != null)
{
sb.append(toComment);
toLines = splitLines(toComment, null);
}
for (String line : fromLines)
{
if (!toLines.contains(line))
{
if (sb.length() != 0)
sb.append(NEWLINE);
sb.append(line);
changed = true;
}
}
break;
}
if (changed)
{
hComment.setComment(sb.toString());
toHeader.setComment(hComment);
}
}
return changed;
}
/**
* splits s into lines, skipping any which contain tagToSkip
* @param s
* @param tagToSkip
* @return
*/
static List<String> splitLines(String s, String tagToSkip)
{
if (s.isEmpty())
return Collections.emptyList();
try
{
List<String> lineList = new ArrayList<String>(s.length() / 40);
BufferedReader reader = new BufferedReader(new StringReader(s));
String line;
while ((line = reader.readLine()) != null)
{
if (tagToSkip == null || !line.contains(tagToSkip))
{
lineList.add(line);
}
}
return lineList;
}
catch (IOException e)
{
throw new RuntimeException(e);
}
}
private boolean transferFromPoHeader(PoHeader from, HPoHeader to)
{
boolean changed = false;
HSimpleComment comment = to.getComment();
if (comment == null)
{
comment = new HSimpleComment();
}
if (!equals(from.getComment(), comment.getComment()))
{
changed = true;
comment.setComment(from.getComment());
to.setComment(comment);
}
String entries = PoUtility.listToHeader(from.getEntries());
if (!equals(entries, to.getEntries()))
{
to.setEntries(entries);
changed = true;
}
return changed;
}
public static <T> boolean equals(T a, T b)
{
if (a == null && b == null)
{
return true;
}
if (a == null || b == null)
{
return false;
}
return a.equals(b);
}
private boolean transferFromTextFlow(TextFlow from, HTextFlow to, Set<String> enabledExtensions)
{
boolean changed = false;
if (!equals(from.getContent(), to.getContent()))
{
to.setContent(from.getContent());
changed = true;
}
// TODO from.getLang()
transferFromTextFlowExtensions(from.getExtensions(true), to, enabledExtensions);
return changed;
}
public void transferToResource(HDocument from, Resource to)
{
transferToAbstractResourceMeta(from, to);
}
private void transferToPoHeader(HPoHeader from, PoHeader to)
{
if (from.getComment() != null)
{
to.setComment(from.getComment().getComment());
}
to.getEntries().addAll(PoUtility.headerToList(from.getEntries()));
}
/**
*
* @param from
* @param to
* @see #transferToTranslationsResourceExtensions
* @see #transferFromPoTargetHeader
*/
private void transferToPoTargetHeader(HPoTargetHeader from, PoTargetHeader to, List<HTextFlowTarget> hTargets)
{
pullPoTargetComment(from, to, hTargets);
to.getEntries().addAll(this.headerToList(from.getEntries(), hTargets));
}
/**
* Transforms a set of header entries from a String to a list of POJOs.
*
* @param entries The header entries' string.
* @param hTargets The Text Flow Targets that the header applies to.
*/
private List<HeaderEntry> headerToList( final String entries, final List<HTextFlowTarget> hTargets )
{
List<HeaderEntry> convertedEntries = PoUtility.headerToList( entries );
// Custom tweaks to the converted entries
for( HeaderEntry entry : convertedEntries )
{
if( entry.getKey().equalsIgnoreCase("Last-Translator") )
{
entry.setValue( this.getLastTranslator(hTargets) );
}
else if( entry.getKey().equalsIgnoreCase("PO-Revision-Date") )
{
entry.setValue( this.getLastModifiedDate(hTargets) );
}
}
return convertedEntries;
}
/**
* Gets the last translator for a set of Text Flow targets.
*
* @param translations The text flow targets.
* @return A string with the value of the last translator for the given set of
* translations.
*/
private String getLastTranslator( final List<HTextFlowTarget> translations )
{
Date lastUpdate = new Date(Long.MIN_VALUE);
String lastTranslator = "";
for( HTextFlowTarget trans : translations )
{
if( trans.getLastChanged().after( lastUpdate ) )
{
HPerson lastModifiedBy = trans.getLastModifiedBy();
if( lastModifiedBy != null )
{
lastTranslator = lastModifiedBy.getName() + " <" + lastModifiedBy.getEmail() + ">";
}
}
}
return lastTranslator;
}
/**
* Gets the last date of modification for a set of Text Flow targets.
*
* @param translations The text flow targets.
* @return A string with the value of the Last modified date for the given set of
* translations.
*/
private String getLastModifiedDate( final List<HTextFlowTarget> translations )
{
Date lastUpdate = null;
for( HTextFlowTarget trans : translations )
{
if( lastUpdate == null || trans.getLastChanged().after( lastUpdate ) )
{
lastUpdate = trans.getLastChanged();
}
}
if( lastUpdate == null )
{
return null;
}
else
{
SimpleDateFormat dateFormat = new SimpleDateFormat( PO_DATE_FORMAT );
return dateFormat.format( lastUpdate );
}
}
/**
*
* @param fromHeader
* @param toHeader
* @see #pushPoTargetComment
*/
protected void pullPoTargetComment(HPoTargetHeader fromHeader, PoTargetHeader toHeader, List<HTextFlowTarget> hTargets)
{
StringBuilder sb = new StringBuilder();
HSimpleComment comment = fromHeader.getComment();
if (comment != null)
{
sb.append(comment.getComment());
}
// generate #zanata credit comments
// order by year, then alphabetically
Set<TranslatorCredit> zanataCredits = new TreeSet<TranslatorCredit>();
for(HTextFlowTarget tft : hTargets)
{
HPerson person = tft.getLastModifiedBy();
if (person != null)
{
Calendar lastChanged = Calendar.getInstance();
lastChanged.setTime(tft.getLastChanged());
int year = lastChanged.get(Calendar.YEAR);
TranslatorCredit credit = new TranslatorCredit();
credit.setEmail(person.getEmail());
credit.setName(person.getName());
credit.setYear(year);
zanataCredits.add(credit);
}
}
for(TranslatorCredit credit : zanataCredits)
{
if (sb.length() != 0)
sb.append(NEWLINE);
sb.append(credit);
sb.append(' ');
sb.append(ZANATA_TAG);
}
toHeader.setComment(sb.toString());
}
public void transferToTextFlow(HTextFlow from, TextFlow to)
{
to.setContent(from.getContent());
to.setRevision(from.getRevision());
// TODO HTextFlow should have a lang
// to.setLang(from.get)
}
public void transferToAbstractResourceMeta(HDocument from, AbstractResourceMeta to)
{
to.setContentType(from.getContentType());
to.setLang(from.getLocale().getLocaleId());
to.setName(from.getDocId());
// TODO ADD support within the hibernate model for multiple resource types
to.setType(ResourceType.FILE);
to.setRevision(from.getRevision());
}
public void transferToResourceExtensions(HDocument from, ExtensionSet<AbstractResourceMetaExtension> to, Set<String> enabledExtensions)
{
if (enabledExtensions.contains(PoHeader.ID))
{
PoHeader poHeaderExt = new PoHeader();
if (from.getPoHeader() != null)
{
transferToPoHeader(from.getPoHeader(), poHeaderExt);
to.add(poHeaderExt);
}
}
}
/**
*
* @param from
* @param to
* @param enabledExtensions
* @param locale
* @see #transferFromTranslationsResourceExtensions
*/
public void transferToTranslationsResourceExtensions(HDocument from, ExtensionSet<TranslationsResourceExtension> to, Set<String> enabledExtensions, HLocale locale, List<HTextFlowTarget> hTargets)
{
if (enabledExtensions.contains(PoTargetHeader.ID))
{
log.debug("PoTargetHeader requested");
PoTargetHeader poTargetHeader = new PoTargetHeader();
HPoTargetHeader fromHeader = from.getPoTargetHeaders().get(locale);
if (fromHeader != null)
{
log.debug("PoTargetHeader found");
transferToPoTargetHeader(fromHeader, poTargetHeader, hTargets);
to.add(poTargetHeader);
}
}
}
public void transferToTextFlowExtensions(HTextFlow from, ExtensionSet<TextFlowExtension> to, Set<String> enabledExtensions)
{
if (enabledExtensions.contains(PotEntryHeader.ID) && from.getPotEntryData() != null)
{
PotEntryHeader header = new PotEntryHeader();
transferToPotEntryHeader(from.getPotEntryData(), header);
log.debug("set header:{0}", from.getPotEntryData());
to.add(header);
}
if (enabledExtensions.contains(SimpleComment.ID) && from.getComment() != null)
{
SimpleComment comment = new SimpleComment(from.getComment().getComment());
log.debug("set comment:{0}", from.getComment().getComment());
to.add(comment);
}
}
/**
* @see #transferFromPotEntryHeader(PotEntryHeader, HPotEntryData)
* @param from
* @param to
*/
private void transferToPotEntryHeader(HPotEntryData from, PotEntryHeader to)
{
to.setContext(from.getContext());
List<String> flags = new ArrayList<String>(0);
if( from.getFlags() != null && !from.getFlags().trim().isEmpty() )
{
flags = StringUtil.split(from.getFlags(), ",");
}
to.getFlags().addAll(flags);
List<String> refs = new ArrayList<String>(0);
if( from.getReferences() != null && !from.getReferences().trim().isEmpty() )
{
StringUtil.split(from.getReferences(), ",");
}
to.getReferences().addAll(refs);
}
/**
*
* @param from
* @param to
* @param enabledExtensions
* @todo merge with {@link #transferToTextFlowTarget}
*/
public void transferToTextFlowTargetExtensions(HTextFlowTarget from, ExtensionSet<TextFlowTargetExtension> to, Set<String> enabledExtensions)
{
if (enabledExtensions.contains(SimpleComment.ID) && from.getComment() != null)
{
SimpleComment comment = new SimpleComment(from.getComment().getComment());
to.add(comment);
}
}
public String encodeDocId(String id)
{
String other = StringUtils.replace(id, "/", ",");
try
{
other = URLEncoder.encode(other, "UTF-8");
return StringUtils.replace(other, "%2C", ",");
}
catch (UnsupportedEncodingException e)
{
throw new RuntimeException(e);
}
}
public String decodeDocId(String id)
{
try
{
String other = URLDecoder.decode(id, "UTF-8");
return StringUtils.replace(other, ",", "/");
}
catch (UnsupportedEncodingException e)
{
throw new RuntimeException(e);
}
}
/**
*
* @param from
* @param to
* @todo merge with {@link #transferToTextFlowTargetExtensions}
*/
public void transferToTextFlowTarget(HTextFlowTarget from, TextFlowTarget to)
{
to.setContent(from.getContent());
to.setState(from.getState());
to.setRevision(from.getVersionNum());
to.setTextFlowRevision(from.getTextFlowRevision());
HPerson translator = from.getLastModifiedBy();
if (translator != null)
{
to.setTranslator(new Person(translator.getEmail(), translator.getName()));
}
}
public Resource buildResource( HDocument document )
{
Set<String> extensions = new HashSet<String>();
extensions.add("gettext");
extensions.add("comment");
Resource entity = new Resource(document.getDocId());
this.transferToResource(document, entity);
// handle extensions
this.transferToResourceExtensions(document, entity.getExtensions(true), extensions);
for (HTextFlow htf : document.getTextFlows())
{
TextFlow tf = new TextFlow(htf.getResId(), document.getLocale().getLocaleId());
this.transferToTextFlowExtensions(htf, tf.getExtensions(true), extensions);
this.transferToTextFlow(htf, tf);
entity.getTextFlows().add(tf);
}
return entity;
}
public void transferToTranslationsResource(TranslationsResource transRes, HDocument document,
HLocale locale, Set<String> enabledExtensions, List<HTextFlowTarget> hTargets)
{
this.transferToTranslationsResourceExtensions(document, transRes.getExtensions(true), enabledExtensions, locale, hTargets);
for (HTextFlowTarget hTarget : hTargets)
{
TextFlowTarget target = new TextFlowTarget();
target.setResId(hTarget.getTextFlow().getResId());
this.transferToTextFlowTarget(hTarget, target);
this.transferToTextFlowTargetExtensions(hTarget, target.getExtensions(true), enabledExtensions);
transRes.getTextFlowTargets().add(target);
}
}
}
|
package hudson;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.inject.AbstractModule;
import com.google.inject.Binding;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Key;
import com.google.inject.Module;
import com.google.inject.Provider;
import com.google.inject.Scope;
import com.google.inject.Scopes;
import com.google.inject.matcher.Matchers;
import com.google.inject.name.Names;
import com.google.inject.spi.ProvisionListener;
import hudson.init.InitMilestone;
import hudson.model.Descriptor;
import hudson.model.Hudson;
import jenkins.ExtensionComponentSet;
import jenkins.ExtensionFilter;
import jenkins.ExtensionRefreshException;
import jenkins.ProxyInjector;
import jenkins.model.Jenkins;
import net.java.sezpoz.Index;
import net.java.sezpoz.IndexItem;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.NoExternalUse;
import org.springframework.util.ClassUtils;
import javax.annotation.PostConstruct;
import java.lang.annotation.Annotation;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Discovers the implementations of an extension point.
*
* <p>
* This extension point allows you to write your implementations of {@link ExtensionPoint}s
* in arbitrary DI containers, and have Hudson discover them.
*
* <p>
* {@link ExtensionFinder} itself is an extension point, but to avoid infinite recursion,
* Jenkins discovers {@link ExtensionFinder}s through {@link Sezpoz} and that alone.
*
* @author Kohsuke Kawaguchi
* @since 1.286
* @see ExtensionFilter
*/
public abstract class ExtensionFinder implements ExtensionPoint {
/**
* @deprecated as of 1.356
* Use and implement {@link #find(Class,Hudson)} that allows us to put some metadata.
*/
@Restricted(NoExternalUse.class)
@Deprecated
public <T> Collection<T> findExtensions(Class<T> type, Hudson hudson) {
return Collections.emptyList();
}
/**
* Returns true if this extension finder supports the {@link #refresh()} operation.
*/
public boolean isRefreshable() {
try {
return getClass().getMethod("refresh").getDeclaringClass()!=ExtensionFinder.class;
} catch (NoSuchMethodException e) {
return false;
}
}
/**
* Rebuilds the internal index, if any, so that future {@link #find(Class, Hudson)} calls
* will discover components newly added to {@link PluginManager#uberClassLoader}.
*
* <p>
* The point of the refresh operation is not to disrupt instances of already loaded {@link ExtensionComponent}s,
* and only instantiate those that are new. Otherwise this will break the singleton semantics of various
* objects, such as {@link Descriptor}s.
*
* <p>
* The behaviour is undefined if {@link #isRefreshable()} is returning false.
*
* @since 1.442
* @see #isRefreshable()
* @return never null
*/
public abstract ExtensionComponentSet refresh() throws ExtensionRefreshException;
/**
* Discover extensions of the given type.
*
* <p>
* This method is called only once per the given type after all the plugins are loaded,
* so implementations need not worry about caching.
*
* <p>
* This method should return all the known components at the time of the call, including
* those that are discovered later via {@link #refresh()}, even though those components
* are separately returned in {@link ExtensionComponentSet}.
*
* @param <T>
* The type of the extension points. This is not bound to {@link ExtensionPoint} because
* of {@link Descriptor}, which by itself doesn't implement {@link ExtensionPoint} for
* a historical reason.
* @param jenkins
* Jenkins whose behalf this extension finder is performing lookup.
* @return
* Can be empty but never null.
* @since 1.356
* Older implementations provide {@link #findExtensions(Class,Hudson)}
*/
public abstract <T> Collection<ExtensionComponent<T>> find(Class<T> type, Hudson jenkins);
@Deprecated
public <T> Collection<ExtensionComponent<T>> _find(Class<T> type, Hudson hudson) {
return find(type, hudson);
}
public void scout(Class extensionType, Hudson hudson) {
}
@Extension
public static final class DefaultGuiceExtensionAnnotation extends GuiceExtensionAnnotation<Extension> {
public DefaultGuiceExtensionAnnotation() {
super(Extension.class);
}
@Override
protected boolean isOptional(Extension annotation) {
return annotation.optional();
}
@Override
protected double getOrdinal(Extension annotation) {
return annotation.ordinal();
}
@Override
protected boolean isActive(AnnotatedElement e) {
return true;
}
}
/**
* Captures information about the annotation that we use to mark Guice-instantiated components.
*/
public static abstract class GuiceExtensionAnnotation<T extends Annotation> {
public final Class<T> annotationType;
protected GuiceExtensionAnnotation(Class<T> annotationType) {
this.annotationType = annotationType;
}
protected abstract double getOrdinal(T annotation);
/**
* Hook to enable subtypes to control which ones to pick up and which ones to ignore.
*/
protected abstract boolean isActive(AnnotatedElement e);
protected abstract boolean isOptional(T annotation);
}
/**
* Discovers components via sezpoz but instantiates them by using Guice.
*/
@Extension
public static class GuiceFinder extends ExtensionFinder {
/**
* Injector that we find components from.
* <p>
* To support refresh when Guice doesn't let us alter the bindings, we'll create
* a child container to house newly discovered components. This field points to the
* youngest such container.
*/
private volatile Injector container;
/**
* Sezpoz index we are currently using in {@link #container} (and its ancestors.)
* Needed to compute delta.
*/
private List<IndexItem<?,Object>> sezpozIndex;
private final Map<Key,Annotation> annotations = new HashMap<>();
private final Sezpoz moduleFinder = new Sezpoz();
/**
* Map from {@link GuiceExtensionAnnotation#annotationType} to {@link GuiceExtensionAnnotation}
*/
private Map<Class<? extends Annotation>,GuiceExtensionAnnotation<?>> extensionAnnotations = Maps.newHashMap();
public GuiceFinder() {
refreshExtensionAnnotations();
SezpozModule extensions = new SezpozModule(loadSezpozIndices(Jenkins.get().getPluginManager().uberClassLoader));
List<Module> modules = new ArrayList<>();
modules.add(new AbstractModule() {
@Override
protected void configure() {
Jenkins j = Jenkins.get();
bind(Jenkins.class).toInstance(j);
bind(PluginManager.class).toInstance(j.getPluginManager());
}
});
modules.add(extensions);
for (ExtensionComponent<Module> ec : moduleFinder.find(Module.class, Hudson.getInstance())) {
modules.add(ec.getInstance());
}
try {
container = Guice.createInjector(modules);
sezpozIndex = extensions.getLoadedIndex();
} catch (Throwable e) {
LOGGER.log(Level.SEVERE, "Failed to create Guice container from all the plugins",e);
// failing to load all bindings are disastrous, so recover by creating minimum that works
// by just including the core
container = Guice.createInjector(new SezpozModule(loadSezpozIndices(Jenkins.class.getClassLoader())));
}
// expose Injector via lookup mechanism for interop with non-Guice clients
Jenkins.get().lookup.set(Injector.class,new ProxyInjector() {
protected Injector resolve() {
return getContainer();
}
});
}
private void refreshExtensionAnnotations() {
for (ExtensionComponent<GuiceExtensionAnnotation> ec : moduleFinder.find(GuiceExtensionAnnotation.class, Hudson.getInstance())) {
GuiceExtensionAnnotation gea = ec.getInstance();
extensionAnnotations.put(gea.annotationType,gea);
}
}
private ImmutableList<IndexItem<?, Object>> loadSezpozIndices(ClassLoader classLoader) {
List<IndexItem<?,Object>> indices = Lists.newArrayList();
for (GuiceExtensionAnnotation<?> gea : extensionAnnotations.values()) {
Iterables.addAll(indices, Index.load(gea.annotationType, Object.class, classLoader));
}
return ImmutableList.copyOf(indices);
}
public Injector getContainer() {
return container;
}
/**
* The basic idea is:
*
* <ul>
* <li>List up delta as a series of modules
* <li>
* </ul>
*/
@Override
public synchronized ExtensionComponentSet refresh() throws ExtensionRefreshException {
refreshExtensionAnnotations();
// figure out newly discovered sezpoz components
List<IndexItem<?, Object>> delta = Lists.newArrayList();
for (Class<? extends Annotation> annotationType : extensionAnnotations.keySet()) {
delta.addAll(Sezpoz.listDelta(annotationType,sezpozIndex));
}
SezpozModule deltaExtensions = new SezpozModule(delta);
List<Module> modules = new ArrayList<>();
modules.add(deltaExtensions);
for (ExtensionComponent<Module> ec : moduleFinder.refresh().find(Module.class)) {
modules.add(ec.getInstance());
}
try {
final Injector child = container.createChildInjector(modules);
container = child;
List<IndexItem<?, Object>> l = Lists.newArrayList(sezpozIndex);
l.addAll(deltaExtensions.getLoadedIndex());
sezpozIndex = l;
return new ExtensionComponentSet() {
@Override
public <T> Collection<ExtensionComponent<T>> find(Class<T> type) {
List<ExtensionComponent<T>> result = new ArrayList<>();
_find(type, result, child);
return result;
}
};
} catch (Throwable e) {
LOGGER.log(Level.SEVERE, "Failed to create Guice container from newly added plugins",e);
throw new ExtensionRefreshException(e);
}
}
private Object instantiate(IndexItem<?,Object> item) {
try {
return item.instance();
} catch (LinkageError | Exception e) {
// sometimes the instantiation fails in an indirect classloading failure,
// which results in a LinkageError
LOGGER.log(isOptional(item.annotation()) ? Level.FINE : Level.WARNING,
"Failed to load "+item.className(), e);
}
return null;
}
private boolean isOptional(Annotation annotation) {
GuiceExtensionAnnotation gea = extensionAnnotations.get(annotation.annotationType());
return gea.isOptional(annotation);
}
private boolean isActive(Annotation annotation, AnnotatedElement e) {
GuiceExtensionAnnotation gea = extensionAnnotations.get(annotation.annotationType());
return gea.isActive(e);
}
public <U> Collection<ExtensionComponent<U>> find(Class<U> type, Hudson jenkins) {
// the find method contract requires us to traverse all known components
List<ExtensionComponent<U>> result = new ArrayList<>();
for (Injector i=container; i!=null; i=i.getParent()) {
_find(type, result, i);
}
return result;
}
private <U> void _find(Class<U> type, List<ExtensionComponent<U>> result, Injector container) {
for (Entry<Key<?>, Binding<?>> e : container.getBindings().entrySet()) {
if (type.isAssignableFrom(e.getKey().getTypeLiteral().getRawType())) {
Annotation a = annotations.get(e.getKey());
Object o = e.getValue().getProvider().get();
if (o!=null) {
GuiceExtensionAnnotation gea = a!=null ? extensionAnnotations.get(a.annotationType()) : null;
result.add(new ExtensionComponent<>(type.cast(o), gea != null ? gea.getOrdinal(a) : 0));
}
}
}
}
/**
* TODO: need to learn more about concurrent access to {@link Injector} and how it interacts
* with classloading.
*/
@Override
public void scout(Class extensionType, Hudson hudson) {
}
/**
* {@link Scope} that allows a failure to create a component,
* and change the value to null.
*
* <p>
* This is necessary as a failure to load one plugin shouldn't fail the startup of the entire Jenkins.
* Instead, we should just drop the failing plugins.
*/
public static final Scope FAULT_TOLERANT_SCOPE = new FaultTolerantScope(true);
private static final Scope QUIET_FAULT_TOLERANT_SCOPE = new FaultTolerantScope(false);
private static final class FaultTolerantScope implements Scope {
private final boolean verbose;
FaultTolerantScope(boolean verbose) {
this.verbose = verbose;
}
public <T> Provider<T> scope(final Key<T> key, final Provider<T> unscoped) {
final Provider<T> base = Scopes.SINGLETON.scope(key,unscoped);
return new Provider<T>() {
public T get() {
try {
return base.get();
} catch (Exception | LinkageError e) {
error(key, e);
return null;
}
}
void error(Key<T> key, Throwable x) {
if (verbose) {
LOGGER.log(Level.WARNING, "Failed to instantiate " + key + "; skipping this component", x);
} else {
LOGGER.log(Level.INFO, "Failed to instantiate optional component {0}; skipping", key.getTypeLiteral());
LOGGER.log(Level.FINE, key.toString(), x);
}
}
};
}
}
private static final Logger LOGGER = Logger.getLogger(GuiceFinder.class.getName());
/**
* {@link Module} that finds components via sezpoz index.
* Instead of using SezPoz to instantiate, we'll instantiate them by using Guice,
* so that we can take advantage of dependency injection.
*/
private class SezpozModule extends AbstractModule implements ProvisionListener {
private final List<IndexItem<?,Object>> index;
private final List<IndexItem<?,Object>> loadedIndex;
public SezpozModule(List<IndexItem<?,Object>> index) {
this.index = index;
this.loadedIndex = new ArrayList<>();
}
/**
* Guice performs various reflection operations on the class to figure out the dependency graph,
* and that process can cause additional classloading problems, which will fail the injector creation,
* which in turn has disastrous effect on the startup.
*
* <p>
* Ultimately I'd like to isolate problems to plugins and selectively disable them, allowing
* Jenkins to start with plugins that work, but I haven't figured out how.
*
* So this is an attempt to detect subset of problems eagerly, by invoking various reflection
* operations and try to find non-existent classes early.
*/
private void resolve(Class c) {
try {
c.getGenericSuperclass();
c.getGenericInterfaces();
ClassLoader ecl = c.getClassLoader();
Method m = ClassLoader.class.getDeclaredMethod("resolveClass", Class.class);
m.setAccessible(true);
m.invoke(ecl, c);
c.getConstructors();
c.getMethods();
for (Field f : c.getFields()) {
if (f.getAnnotation(javax.inject.Inject.class) != null || f.getAnnotation(com.google.inject.Inject.class) != null) {
resolve(f.getType());
}
}
LOGGER.log(Level.FINER, "{0} looks OK", c);
while (c != Object.class) {
c.getGenericSuperclass();
c = c.getSuperclass();
}
} catch (Exception x) {
throw (LinkageError)new LinkageError("Failed to resolve "+c).initCause(x);
}
}
@SuppressWarnings({"unchecked", "ChainOfInstanceofChecks"})
@Override
protected void configure() {
bindListener(Matchers.any(), this);
for (final IndexItem<?,Object> item : index) {
boolean optional = isOptional(item.annotation());
try {
AnnotatedElement e = item.element();
Annotation a = item.annotation();
if (!isActive(a,e)) continue;
Scope scope = optional ? QUIET_FAULT_TOLERANT_SCOPE : FAULT_TOLERANT_SCOPE;
if (e instanceof Class) {
Key key = Key.get((Class)e);
resolve((Class)e);
annotations.put(key,a);
bind(key).in(scope);
} else {
Class extType;
if (e instanceof Field) {
extType = ((Field)e).getType();
} else
if (e instanceof Method) {
extType = ((Method)e).getReturnType();
} else {
throw new AssertionError();
}
resolve(extType);
// make unique key, because Guice wants that.
Key key = Key.get(extType, Names.named(item.className() + "." + item.memberName()));
annotations.put(key,a);
bind(key).toProvider(new Provider() {
public Object get() {
return instantiate(item);
}
}).in(scope);
}
loadedIndex.add(item);
} catch (Exception|LinkageError e) {
// sometimes the instantiation fails in an indirect classloading failure,
// which results in a LinkageError
LOGGER.log(optional ? Level.FINE : Level.WARNING,
"Failed to load "+item.className(), e);
}
}
}
public List<IndexItem<?, Object>> getLoadedIndex() {
return Collections.unmodifiableList(loadedIndex);
}
@Override
public <T> void onProvision(ProvisionInvocation<T> provision) {
final T instance = provision.provision();
if (instance == null) return;
List<Method> methods = new LinkedList<>();
Class c = instance.getClass();
// find PostConstruct methods in class hierarchy, the one from parent class being first in list
// so that we invoke them before derived class one. This isn't specified in JSR-250 but implemented
// this way in Spring and what most developers would expect to happen.
final Set<Class> interfaces = ClassUtils.getAllInterfacesAsSet(instance);
while (c != Object.class) {
Arrays.stream(c.getDeclaredMethods())
.map(m -> getMethodAndInterfaceDeclarations(m, interfaces))
.flatMap(Collection::stream)
.filter(m -> m.getAnnotation(PostConstruct.class) != null)
.findFirst()
.ifPresent(method -> methods.add(0, method));
c = c.getSuperclass();
}
for (Method postConstruct : methods) {
try {
postConstruct.setAccessible(true);
postConstruct.invoke(instance);
} catch (final Exception e) {
throw new RuntimeException(String.format("@PostConstruct %s", postConstruct), e);
}
}
}
}
}
/**
* Returns initial {@link Method} as well as all matching ones found in interfaces.
* This allows to introspect metadata for a method which is both declared in parent class and in implemented
* interface(s). <code>interfaces</code> typically is obtained by {@link ClassUtils#getAllInterfacesAsSet}
*/
Collection<Method> getMethodAndInterfaceDeclarations(Method method, Collection<Class> interfaces) {
final List<Method> methods = new ArrayList<>();
methods.add(method);
// we search for matching method by iteration and comparison vs getMethod to avoid repeated NoSuchMethodException
// being thrown, while interface typically only define a few set of methods to check.
interfaces.stream()
.map(Class::getMethods)
.flatMap(Arrays::stream)
.filter(m -> m.getName().equals(method.getName()) && Arrays.equals(m.getParameterTypes(), method.getParameterTypes()))
.findFirst()
.ifPresent(methods::add);
return methods;
}
/**
* The bootstrap implementation that looks for the {@link Extension} marker.
*
* <p>
* Uses Sezpoz as the underlying mechanism.
*/
public static final class Sezpoz extends ExtensionFinder {
private volatile List<IndexItem<Extension,Object>> indices;
/**
* Loads indices (ideally once but as few times as possible), then reuse them later.
* {@link ExtensionList#ensureLoaded()} guarantees that this method won't be called until
* {@link InitMilestone#PLUGINS_PREPARED} is attained, so this method is guaranteed to
* see all the classes and indices.
*/
private List<IndexItem<Extension,Object>> getIndices() {
// this method cannot be synchronized because of a dead lock possibility in the following order of events:
// 1. thread X can start listing indices, locking this object 'SZ'
// 2. thread Y starts loading a class, locking a classloader 'CL'
// 3. thread X needs to load a class, now blocked on CL
// 4. thread Y decides to load extensions, now blocked on SZ.
// 5. dead lock
if (indices==null) {
ClassLoader cl = Jenkins.get().getPluginManager().uberClassLoader;
indices = ImmutableList.copyOf(Index.load(Extension.class, Object.class, cl));
}
return indices;
}
/**
* {@inheritDoc}
*
* <p>
* SezPoz implements value-equality of {@link IndexItem}, so
*/
@Override
public synchronized ExtensionComponentSet refresh() {
final List<IndexItem<Extension,Object>> old = indices;
if (old==null) return ExtensionComponentSet.EMPTY; // we haven't loaded anything
final List<IndexItem<Extension, Object>> delta = listDelta(Extension.class,old);
List<IndexItem<Extension,Object>> r = Lists.newArrayList(old);
r.addAll(delta);
indices = ImmutableList.copyOf(r);
return new ExtensionComponentSet() {
@Override
public <T> Collection<ExtensionComponent<T>> find(Class<T> type) {
return _find(type,delta);
}
};
}
static <T extends Annotation> List<IndexItem<T,Object>> listDelta(Class<T> annotationType, List<? extends IndexItem<?,Object>> old) {
// list up newly discovered components
final List<IndexItem<T,Object>> delta = Lists.newArrayList();
ClassLoader cl = Jenkins.get().getPluginManager().uberClassLoader;
for (IndexItem<T,Object> ii : Index.load(annotationType, Object.class, cl)) {
if (!old.contains(ii)) {
delta.add(ii);
}
}
return delta;
}
public <T> Collection<ExtensionComponent<T>> find(Class<T> type, Hudson jenkins) {
return _find(type,getIndices());
}
/**
* Finds all the matching {@link IndexItem}s that match the given type and instantiate them.
*/
private <T> Collection<ExtensionComponent<T>> _find(Class<T> type, List<IndexItem<Extension,Object>> indices) {
List<ExtensionComponent<T>> result = new ArrayList<>();
for (IndexItem<Extension,Object> item : indices) {
try {
Class<?> extType = getClassFromIndex(item);
if(type.isAssignableFrom(extType)) {
Object instance = item.instance();
if(instance!=null)
result.add(new ExtensionComponent<>(type.cast(instance),item.annotation()));
}
} catch (LinkageError|Exception e) {
// sometimes the instantiation fails in an indirect classloading failure,
// which results in a LinkageError
LOGGER.log(logLevel(item), "Failed to load "+item.className(), e);
}
}
return result;
}
@Override
public void scout(Class extensionType, Hudson hudson) {
for (IndexItem<Extension,Object> item : getIndices()) {
try {
// we might end up having multiple threads concurrently calling into element(),
// can block while other threads wait for the entry into the element call().
// looking at the sezpoz code, it should be safe to do so
Class<?> extType = getClassFromIndex(item);
// according to JDK-4993813 this is the only way to force class initialization
Class.forName(extType.getName(),true,extType.getClassLoader());
} catch (Exception | LinkageError e) {
LOGGER.log(logLevel(item), "Failed to scout "+item.className(), e);
}
}
}
private Level logLevel(IndexItem<Extension, Object> item) {
return item.annotation().optional() ? Level.FINE : Level.WARNING;
}
}
private static Class<?> getClassFromIndex(IndexItem<Extension, Object> item) throws InstantiationException {
AnnotatedElement e = item.element();
Class<?> extType;
if (e instanceof Class) {
extType = (Class) e;
} else if (e instanceof Field) {
extType = ((Field) e).getType();
} else if (e instanceof Method) {
extType = ((Method) e).getReturnType();
} else {
throw new AssertionError();
}
return extType;
}
private static final Logger LOGGER = Logger.getLogger(ExtensionFinder.class.getName());
}
|
package hudson.matrix;
import com.thoughtworks.xstream.alias.CannotResolveClassException;
import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.converters.reflection.SerializableConverter;
import com.thoughtworks.xstream.converters.reflection.ReflectionProvider;
import com.thoughtworks.xstream.converters.collections.AbstractCollectionConverter;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import com.thoughtworks.xstream.mapper.Mapper;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import hudson.util.RobustCollectionConverter;
/**
* List of {@link Axis}.
*
* @author Kohsuke Kawaguchi
*/
public class AxisList extends ArrayList<Axis> {
public AxisList() {
}
public AxisList(Collection<Axis> c) {
super(c);
}
public Axis find(String name) {
for (Axis a : this) {
if(a.name.equals(name))
return a;
}
return null;
}
public boolean add(Axis axis) {
return axis!=null && super.add(axis);
}
/**
* List up all the possible combinations of this list.
*/
public Iterable<Combination> list() {
final int[] base = new int[size()];
int b = 1;
for( int i=size()-1; i>=0; i
base[i] = b;
b *= get(i).size();
}
final int total = b; // number of total combinations
return new Iterable<Combination>() {
public Iterator<Combination> iterator() {
return new Iterator<Combination>() {
private int counter = 0;
public boolean hasNext() {
return counter<total;
}
public Combination next() {
String[] data = new String[size()];
int x = counter++;
for( int i=0; i<data.length; i++) {
data[i] = get(i).value(x/base[i]);
x %= base[i];
}
assert x==0;
return new Combination(AxisList.this,data);
}
public void remove() {
throw new UnsupportedOperationException();
}
};
}
};
}
/**
* {@link Converter} implementation for XStream.
*/
public static final class ConverterImpl extends RobustCollectionConverter {
public ConverterImpl(Mapper mapper, ReflectionProvider reflectionProvider) {
super(mapper,reflectionProvider);
}
public boolean canConvert(Class type) {
return type==AxisList.class;
}
@Override
protected Object createCollection(Class type) {
return new AxisList();
}
}
}
|
package gov.nih.nci.evs.browser.utils;
import java.io.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Vector;
import java.util.Arrays;
import javax.faces.model.SelectItem;
import org.LexGrid.LexBIG.DataModel.Collections.ResolvedConceptReferenceList;
import org.LexGrid.LexBIG.DataModel.Collections.SortOptionList;
import org.LexGrid.LexBIG.DataModel.Core.CodingSchemeSummary;
import org.LexGrid.LexBIG.DataModel.Core.CodingSchemeVersionOrTag;
import org.LexGrid.LexBIG.DataModel.Core.ResolvedConceptReference;
import org.LexGrid.LexBIG.Exceptions.LBException;
import org.LexGrid.LexBIG.History.HistoryService;
import org.LexGrid.LexBIG.LexBIGService.CodedNodeSet;
import org.LexGrid.LexBIG.LexBIGService.LexBIGService;
import org.LexGrid.LexBIG.Utility.Constructors;
import org.LexGrid.concepts.Concept;
import org.LexGrid.LexBIG.DataModel.Collections.CodingSchemeRenderingList;
import org.LexGrid.LexBIG.DataModel.InterfaceElements.CodingSchemeRendering;
import org.LexGrid.LexBIG.DataModel.Collections.LocalNameList;
import org.LexGrid.LexBIG.Utility.Iterators.ResolvedConceptReferencesIterator;
import org.LexGrid.LexBIG.DataModel.Collections.ConceptReferenceList;
import org.LexGrid.LexBIG.DataModel.Core.ConceptReference;
import org.LexGrid.LexBIG.LexBIGService.CodedNodeGraph;
import org.LexGrid.LexBIG.DataModel.Collections.NameAndValueList;
import org.LexGrid.LexBIG.DataModel.Core.NameAndValue;
import org.LexGrid.LexBIG.DataModel.Collections.AssociationList;
import org.LexGrid.LexBIG.DataModel.Core.AssociatedConcept;
import org.LexGrid.LexBIG.DataModel.Core.Association;
import org.LexGrid.LexBIG.DataModel.Collections.AssociatedConceptList;
import org.LexGrid.codingSchemes.CodingScheme;
import org.LexGrid.concepts.Presentation;
import org.LexGrid.LexBIG.Utility.ConvenienceMethods;
import org.LexGrid.commonTypes.EntityDescription;
import org.LexGrid.commonTypes.Property;
import org.LexGrid.relations.Relations;
import org.LexGrid.versions.SystemRelease;
import org.LexGrid.commonTypes.PropertyQualifier;
import org.LexGrid.commonTypes.Source;
import org.LexGrid.naming.SupportedSource;
import org.LexGrid.naming.SupportedPropertyQualifier;
import org.LexGrid.LexBIG.DataModel.Core.types.CodingSchemeVersionStatus;
import org.LexGrid.naming.SupportedAssociation;
import org.LexGrid.naming.SupportedProperty;
import org.LexGrid.naming.SupportedRepresentationalForm;
import org.LexGrid.LexBIG.Extensions.Generic.LexBIGServiceConvenienceMethods;
import org.LexGrid.naming.Mappings;
import org.LexGrid.naming.SupportedHierarchy;
import org.LexGrid.LexBIG.DataModel.InterfaceElements.RenderingDetail;
import org.LexGrid.LexBIG.DataModel.Collections.CodingSchemeTagList;
import gov.nih.nci.evs.browser.properties.NCItBrowserProperties;
import static gov.nih.nci.evs.browser.common.Constants.*;
import org.LexGrid.naming.SupportedNamespace;
import org.LexGrid.LexBIG.Exceptions.LBInvocationException;
import org.LexGrid.concepts.Entity;
import org.LexGrid.LexBIG.LexBIGService.CodedNodeSet.PropertyType;
/**
* @author EVS Team
* @version 1.0
*
* Modification history Initial implementation kim.ong@ngc.com
*
*/
public class DataUtils {
LocalNameList noopList_ = Constructors.createLocalNameList("_noop_");
int maxReturn = 5000;
Connection con;
Statement stmt;
ResultSet rs;
private static List _ontologies = null;
private static org.LexGrid.LexBIG.LexBIGService.LexBIGService lbSvc = null;
public org.LexGrid.LexBIG.Utility.ConvenienceMethods lbConvMethods = null;
public CodingSchemeRenderingList csrl = null;
//private static HashMap codingSchemeMap = null;
private static HashSet codingSchemeHashSet = null;
private static HashMap csnv2codingSchemeNameMap = null;
private static HashMap csnv2VersionMap = null;
// For customized query use
public static int ALL = 0;
public static int PREFERRED_ONLY = 1;
public static int NON_PREFERRED_ONLY = 2;
static int RESOLVE_SOURCE = 1;
static int RESOLVE_TARGET = -1;
static int RESTRICT_SOURCE = -1;
static int RESTRICT_TARGET = 1;
public static final int SEARCH_NAME_CODE = 1;
public static final int SEARCH_DEFINITION = 2;
public static final int SEARCH_PROPERTY_VALUE = 3;
public static final int SEARCH_ROLE_VALUE = 6;
public static final int SEARCH_ASSOCIATION_VALUE = 7;
static final List<String> STOP_WORDS = Arrays.asList(new String[] { "a",
"an", "and", "by", "for", "of", "on", "in", "nos", "the", "to",
"with" });
public static String TYPE_ROLE = "type_role";
public static String TYPE_ASSOCIATION = "type_association";
public static String TYPE_SUPERCONCEPT = "type_superconcept";
public static String TYPE_SUBCONCEPT = "type_subconcept";
public String NCICBContactURL = null;
public String terminologySubsetDownloadURL = null;
public String term_suggestion_application_url = null;
public String NCITBuildInfo = null;
public String NCImURL = null;
public static HashMap namespace2CodingScheme = null;
public static String TYPE_INVERSE_ROLE = "type_inverse_role";
public static String TYPE_INVERSE_ASSOCIATION = "type_inverse_association";
public static HashMap formalName2LocalNameHashMap = null;
public static HashMap localName2FormalNameHashMap = null;
public DataUtils() {
// setCodingSchemeMap();
}
public static List getOntologyList() {
if (_ontologies == null)
setCodingSchemeMap();
return _ontologies;
}
private static boolean isCodingSchemeSupported(String codingSchemeName) {
if (codingSchemeHashSet == null) setCodingSchemeMap();
return codingSchemeHashSet.contains(codingSchemeName);
}
private static void setCodingSchemeMap()
{
codingSchemeHashSet = new HashSet();
_ontologies = new ArrayList();
//codingSchemeMap = new HashMap();
csnv2codingSchemeNameMap = new HashMap();
csnv2VersionMap = new HashMap();
formalName2LocalNameHashMap = new HashMap();
localName2FormalNameHashMap = new HashMap();
Vector nv_vec = new Vector();
boolean includeInactive = false;
try {
LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
CodingSchemeRenderingList csrl = null;
try {
csrl = lbSvc.getSupportedCodingSchemes();
} catch (LBInvocationException ex) {
ex.printStackTrace();
System.out.println("lbSvc.getSupportedCodingSchemes() FAILED..." + ex.getCause() );
return;
}
CodingSchemeRendering[] csrs = csrl.getCodingSchemeRendering();
for (int i=0; i<csrs.length; i++)
{
int j = i+1;
CodingSchemeRendering csr = csrs[i];
CodingSchemeSummary css = csr.getCodingSchemeSummary();
String formalname = css.getFormalName();
if (!codingSchemeHashSet.contains(formalname)) {
codingSchemeHashSet.add(formalname);
}
String representsVersion = css.getRepresentsVersion();
System.out.println("(" + j + ") " + formalname + " version: " + representsVersion);
String locallname = css.getLocalName();
formalName2LocalNameHashMap.put(formalname, locallname);
formalName2LocalNameHashMap.put(locallname, locallname);
localName2FormalNameHashMap.put(formalname, formalname);
localName2FormalNameHashMap.put(locallname, formalname);
Boolean isActive = null;
if (csr == null) {
System.out.println("\tcsr == null???");
} else if (csr.getRenderingDetail() == null) {
System.out.println("\tcsr.getRenderingDetail() == null");
} else if (csr.getRenderingDetail().getVersionStatus() == null) {
System.out.println("\tcsr.getRenderingDetail().getVersionStatus() == null");
} else {
isActive = csr.getRenderingDetail().getVersionStatus().equals(CodingSchemeVersionStatus.ACTIVE);
}
System.out.println("\n\tActive? " + isActive);
if ((includeInactive && isActive == null) || (isActive != null && isActive.equals(Boolean.TRUE))
|| (includeInactive && (isActive != null && isActive.equals(Boolean.FALSE))))
{
String value = formalname + " (version: " + representsVersion + ")";
nv_vec.add(value);
csnv2codingSchemeNameMap.put(value, formalname);
csnv2VersionMap.put(value, representsVersion);
}
}
} catch (Exception e) {
//e.printStackTrace();
//return null;
}
if (nv_vec.size() > 0) {
nv_vec = SortUtils.quickSort(nv_vec);
for (int k=0; k<nv_vec.size(); k++) {
String value = (String) nv_vec.elementAt(k);
_ontologies.add(new SelectItem(value, value));
}
}
}
public static String getLocalName(String key) {
if (formalName2LocalNameHashMap == null) {
setCodingSchemeMap();
}
return (String) formalName2LocalNameHashMap.get(key);
}
public static Vector<String> getSupportedAssociationNames(String key) {
if (csnv2codingSchemeNameMap == null) {
setCodingSchemeMap();
return getSupportedAssociationNames(key);
}
String codingSchemeName = (String) csnv2codingSchemeNameMap.get(key);
if (codingSchemeName == null)
return null;
String version = (String) csnv2VersionMap.get(key);
if (version == null)
return null;
return getSupportedAssociationNames(codingSchemeName, version);
}
public static Vector<String> getSupportedAssociationNames(
String codingSchemeName, String version) {
CodingSchemeVersionOrTag vt = new CodingSchemeVersionOrTag();
if (version != null) {
vt.setVersion(version);
}
CodingScheme scheme = null;
try {
// RemoteServerUtil rsu = new RemoteServerUtil();
// EVSApplicationService lbSvc = rsu.createLexBIGService();
LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
scheme = lbSvc.resolveCodingScheme(codingSchemeName, vt);
if (scheme == null) {
System.out.println("scheme is NULL");
return null;
}
Vector<String> v = new Vector<String>();
SupportedAssociation[] assos = scheme.getMappings()
.getSupportedAssociation();
for (int i = 0; i < assos.length; i++) {
SupportedAssociation sa = (SupportedAssociation) assos[i];
v.add(sa.getLocalId());
}
return v;
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
public static Vector<String> getPropertyNameListData(String key) {
if (csnv2codingSchemeNameMap == null) {
setCodingSchemeMap();
}
String codingSchemeName = (String) csnv2codingSchemeNameMap.get(key);
if (codingSchemeName == null) {
return null;
}
String version = (String) csnv2VersionMap.get(key);
if (version == null) {
return null;
}
return getPropertyNameListData(codingSchemeName, version);
}
public static Vector<String> getPropertyNameListData(
String codingSchemeName, String version) {
CodingSchemeVersionOrTag vt = new CodingSchemeVersionOrTag();
if (version != null) {
vt.setVersion(version);
}
CodingScheme scheme = null;
try {
// RemoteServerUtil rsu = new RemoteServerUtil();
// EVSApplicationService lbSvc = rsu.createLexBIGService();
LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
scheme = lbSvc.resolveCodingScheme(codingSchemeName, vt);
if (scheme == null)
return null;
Vector<String> propertyNameListData = new Vector<String>();
SupportedProperty[] properties = scheme.getMappings()
.getSupportedProperty();
for (int i = 0; i < properties.length; i++) {
SupportedProperty property = properties[i];
propertyNameListData.add(property.getLocalId());
}
return propertyNameListData;
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
public static Vector<String> getRepresentationalFormListData(String key) {
String codingSchemeName = (String) csnv2codingSchemeNameMap.get(key);
if (codingSchemeName == null)
return null;
String version = (String) csnv2VersionMap.get(key);
if (version == null)
return null;
return getRepresentationalFormListData(codingSchemeName, version);
}
public static Vector<String> getRepresentationalFormListData(
String codingSchemeName, String version) {
CodingSchemeVersionOrTag vt = new CodingSchemeVersionOrTag();
if (version != null) {
vt.setVersion(version);
}
CodingScheme scheme = null;
try {
// RemoteServerUtil rsu = new RemoteServerUtil();
// EVSApplicationService lbSvc = rsu.createLexBIGService();
LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
scheme = lbSvc.resolveCodingScheme(codingSchemeName, vt);
if (scheme == null)
return null;
Vector<String> propertyNameListData = new Vector<String>();
SupportedRepresentationalForm[] forms = scheme.getMappings()
.getSupportedRepresentationalForm();
if (forms != null) {
for (int i = 0; i < forms.length; i++) {
SupportedRepresentationalForm form = forms[i];
propertyNameListData.add(form.getLocalId());
}
}
return propertyNameListData;
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
public static Vector<String> getPropertyQualifierListData(String key) {
String codingSchemeName = (String) csnv2codingSchemeNameMap.get(key);
if (codingSchemeName == null)
return null;
String version = (String) csnv2VersionMap.get(key);
if (version == null)
return null;
return getPropertyQualifierListData(codingSchemeName, version);
}
public static Vector<String> getPropertyQualifierListData(
String codingSchemeName, String version) {
CodingSchemeVersionOrTag vt = new CodingSchemeVersionOrTag();
if (version != null) {
vt.setVersion(version);
}
CodingScheme scheme = null;
try {
// RemoteServerUtil rsu = new RemoteServerUtil();
// EVSApplicationService lbSvc = rsu.createLexBIGService();
LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
scheme = lbSvc.resolveCodingScheme(codingSchemeName, vt);
if (scheme == null)
return null;
Vector<String> propertyQualifierListData = new Vector<String>();
SupportedPropertyQualifier[] qualifiers = scheme.getMappings()
.getSupportedPropertyQualifier();
for (int i = 0; i < qualifiers.length; i++) {
SupportedPropertyQualifier qualifier = qualifiers[i];
propertyQualifierListData.add(qualifier.getLocalId());
}
return propertyQualifierListData;
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
public static Vector<String> getSourceListData(String key) {
if (csnv2codingSchemeNameMap == null) {
setCodingSchemeMap();
return getSourceListData(key);
}
String codingSchemeName = (String) csnv2codingSchemeNameMap.get(key);
if (codingSchemeName == null)
return null;
String version = (String) csnv2VersionMap.get(key);
if (version == null)
return null;
return getSourceListData(codingSchemeName, version);
}
public static Vector<String> getSourceListData(String codingSchemeName,
String version) {
CodingSchemeVersionOrTag vt = new CodingSchemeVersionOrTag();
if (version != null) {
vt.setVersion(version);
}
CodingScheme scheme = null;
try {
// RemoteServerUtil rsu = new RemoteServerUtil();
// EVSApplicationService lbSvc = rsu.createLexBIGService();
LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
scheme = lbSvc.resolveCodingScheme(codingSchemeName, vt);
if (scheme == null)
return null;
Vector<String> sourceListData = new Vector<String>();
// Insert your code here
SupportedSource[] sources = scheme.getMappings()
.getSupportedSource();
for (int i = 0; i < sources.length; i++) {
SupportedSource source = sources[i];
sourceListData.add(source.getLocalId());
}
return sourceListData;
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
public static String int2String(Integer int_obj) {
if (int_obj == null) {
return null;
}
String retstr = Integer.toString(int_obj);
return retstr;
}
public static Concept getConceptByCode(String codingSchemeName,
String vers, String ltag, String code) {
try {
if (code.indexOf("@") != -1) return null; // anonymous class
String formalname = (String) localName2FormalNameHashMap.get(codingSchemeName);
LexBIGService lbSvc = new RemoteServerUtil().createLexBIGService();
if (lbSvc == null) {
System.out.println("lbSvc == null???");
return null;
}
CodingSchemeVersionOrTag versionOrTag = new CodingSchemeVersionOrTag();
if (vers != null) versionOrTag.setVersion(vers);
ConceptReferenceList crefs = createConceptReferenceList(
new String[] { code }, codingSchemeName);
CodedNodeSet cns = null;
try {
try {
cns = lbSvc.getCodingSchemeConcepts(codingSchemeName,
versionOrTag);
} catch (Exception e) {
cns = lbSvc.getCodingSchemeConcepts(formalname,
versionOrTag);
}
if (cns == null) {
System.out.println("getConceptByCode getCodingSchemeConcepts returns null??? " + codingSchemeName);
return null;
}
cns = cns.restrictToCodes(crefs);
//ResolvedConceptReferenceList matches = cns.resolveToList(null, null, null, 1);
ResolvedConceptReferenceList matches = null;
try {
matches = cns.resolveToList(null, null, null, 1);
} catch (Exception e) {
System.out.println("cns.resolveToList failed???");
}
if (matches == null) {
System.out.println("Concep not found.");
return null;
}
int count = matches.getResolvedConceptReferenceCount();
// Analyze the result ...
if (count == 0)
return null;
if (count > 0) {
try {
ResolvedConceptReference ref = (ResolvedConceptReference) matches
.enumerateResolvedConceptReference()
.nextElement();
Concept entry = ref.getReferencedEntry();
return entry;
} catch (Exception ex1) {
System.out.println("Exception entry == null");
return null;
}
}
} catch (Exception e1) {
e1.printStackTrace();
return null;
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
return null;
}
public static NameAndValueList createNameAndValueList(String[] names,
String[] values) {
NameAndValueList nvList = new NameAndValueList();
for (int i = 0; i < names.length; i++) {
NameAndValue nv = new NameAndValue();
nv.setName(names[i]);
if (values != null) {
nv.setContent(values[i]);
}
nvList.addNameAndValue(nv);
}
return nvList;
}
public ResolvedConceptReferenceList getNext(
ResolvedConceptReferencesIterator iterator) {
return iterator.getNext();
}
public Vector getParentCodes(String scheme, String version, String code) {
Vector hierarchicalAssoName_vec = getHierarchyAssociationId(scheme,
version);
if (hierarchicalAssoName_vec == null
|| hierarchicalAssoName_vec.size() == 0) {
return null;
}
String hierarchicalAssoName = (String) hierarchicalAssoName_vec
.elementAt(0);
// KLO, 01/23/2009
// Vector<Concept> superconcept_vec = util.getAssociationSources(scheme,
// version, code, hierarchicalAssoName);
Vector superconcept_vec = getAssociationSourceCodes(scheme, version,
code, hierarchicalAssoName);
if (superconcept_vec == null)
return null;
// SortUtils.quickSort(superconcept_vec, SortUtils.SORT_BY_CODE);
return superconcept_vec;
}
public Vector getAssociationSourceCodes(String scheme, String version,
String code, String assocName) {
CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag();
if (version != null)
csvt.setVersion(version);
ResolvedConceptReferenceList matches = null;
Vector v = new Vector();
try {
// EVSApplicationService lbSvc = new
// RemoteServerUtil().createLexBIGService();
LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
CodedNodeGraph cng = lbSvc.getNodeGraph(scheme, csvt, null);
NameAndValueList nameAndValueList = createNameAndValueList(
new String[] { assocName }, null);
NameAndValueList nameAndValueList_qualifier = null;
cng = cng.restrictToAssociations(nameAndValueList,
nameAndValueList_qualifier);
matches = cng.resolveAsList(ConvenienceMethods
.createConceptReference(code, scheme), false, true, 1, 1,
new LocalNameList(), null, null, maxReturn);
if (matches.getResolvedConceptReferenceCount() > 0) {
Enumeration<ResolvedConceptReference> refEnum = matches
.enumerateResolvedConceptReference();
while (refEnum.hasMoreElements()) {
ResolvedConceptReference ref = refEnum.nextElement();
AssociationList targetof = ref.getTargetOf();
Association[] associations = targetof.getAssociation();
for (int i = 0; i < associations.length; i++) {
Association assoc = associations[i];
// KLO
assoc = processForAnonomousNodes(assoc);
AssociatedConcept[] acl = assoc.getAssociatedConcepts()
.getAssociatedConcept();
for (int j = 0; j < acl.length; j++) {
AssociatedConcept ac = acl[j];
v.add(ac.getReferencedEntry().getEntityCode());
}
}
}
SortUtils.quickSort(v);
}
} catch (Exception ex) {
ex.printStackTrace();
}
return v;
}
public static ConceptReferenceList createConceptReferenceList(
String[] codes, String codingSchemeName) {
if (codes == null) {
return null;
}
ConceptReferenceList list = new ConceptReferenceList();
for (int i = 0; i < codes.length; i++) {
ConceptReference cr = new ConceptReference();
cr.setCodingSchemeName(codingSchemeName);
cr.setConceptCode(codes[i]);
list.addConceptReference(cr);
}
return list;
}
public Vector getSubconceptCodes(String scheme, String version, String code) { // throws
// LBException{
Vector v = new Vector();
try {
// EVSApplicationService lbSvc = new
// RemoteServerUtil().createLexBIGService();
LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
LexBIGServiceConvenienceMethods lbscm = (LexBIGServiceConvenienceMethods) lbSvc
.getGenericExtension("LexBIGServiceConvenienceMethods");
lbscm.setLexBIGService(lbSvc);
CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag();
csvt.setVersion(version);
String desc = null;
try {
desc = lbscm.createCodeNodeSet(new String[] { code }, scheme,
csvt).resolveToList(null, null, null, 1)
.getResolvedConceptReference(0).getEntityDescription()
.getContent();
} catch (Exception e) {
desc = "<not found>";
}
// Iterate through all hierarchies and levels ...
String[] hierarchyIDs = lbscm.getHierarchyIDs(scheme, csvt);
for (int k = 0; k < hierarchyIDs.length; k++) {
String hierarchyID = hierarchyIDs[k];
AssociationList associations = null;
associations = null;
try {
associations = lbscm.getHierarchyLevelNext(scheme, csvt,
hierarchyID, code, false, null);
} catch (Exception e) {
System.out.println("getSubconceptCodes - Exception lbscm.getHierarchyLevelNext ");
return v;
}
for (int i = 0; i < associations.getAssociationCount(); i++) {
Association assoc = associations.getAssociation(i);
AssociatedConceptList concepts = assoc
.getAssociatedConcepts();
for (int j = 0; j < concepts.getAssociatedConceptCount(); j++) {
AssociatedConcept concept = concepts
.getAssociatedConcept(j);
String nextCode = concept.getConceptCode();
v.add(nextCode);
}
}
}
} catch (Exception ex) {
// ex.printStackTrace();
}
return v;
}
public Vector getSuperconceptCodes(String scheme, String version,
String code) { // throws LBException{
long ms = System.currentTimeMillis();
Vector v = new Vector();
try {
// EVSApplicationService lbSvc = new
// RemoteServerUtil().createLexBIGService();
LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
LexBIGServiceConvenienceMethods lbscm = (LexBIGServiceConvenienceMethods) lbSvc
.getGenericExtension("LexBIGServiceConvenienceMethods");
lbscm.setLexBIGService(lbSvc);
CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag();
csvt.setVersion(version);
String desc = null;
try {
desc = lbscm.createCodeNodeSet(new String[] { code }, scheme,
csvt).resolveToList(null, null, null, 1)
.getResolvedConceptReference(0).getEntityDescription()
.getContent();
} catch (Exception e) {
desc = "<not found>";
}
// Iterate through all hierarchies and levels ...
String[] hierarchyIDs = lbscm.getHierarchyIDs(scheme, csvt);
for (int k = 0; k < hierarchyIDs.length; k++) {
String hierarchyID = hierarchyIDs[k];
AssociationList associations = lbscm.getHierarchyLevelPrev(
scheme, csvt, hierarchyID, code, false, null);
for (int i = 0; i < associations.getAssociationCount(); i++) {
Association assoc = associations.getAssociation(i);
AssociatedConceptList concepts = assoc
.getAssociatedConcepts();
for (int j = 0; j < concepts.getAssociatedConceptCount(); j++) {
AssociatedConcept concept = concepts
.getAssociatedConcept(j);
String nextCode = concept.getConceptCode();
v.add(nextCode);
}
}
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
System.out.println("Run time (ms): "
+ (System.currentTimeMillis() - ms));
}
return v;
}
public Vector getHierarchyAssociationId(String scheme, String version) {
Vector association_vec = new Vector();
try {
// EVSApplicationService lbSvc = new
// RemoteServerUtil().createLexBIGService();
LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
// Will handle secured ontologies later.
CodingSchemeVersionOrTag versionOrTag = new CodingSchemeVersionOrTag();
versionOrTag.setVersion(version);
CodingScheme cs = lbSvc.resolveCodingScheme(scheme, versionOrTag);
Mappings mappings = cs.getMappings();
SupportedHierarchy[] hierarchies = mappings.getSupportedHierarchy();
java.lang.String[] ids = hierarchies[0].getAssociationNames();
for (int i = 0; i < ids.length; i++) {
if (!association_vec.contains(ids[i])) {
association_vec.add(ids[i]);
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
return association_vec;
}
public static String getVersion() {
return getVersion(CODING_SCHEME_NAME);
}
public static String getVersion(String coding_scheme_name) {
String info = getReleaseDate(coding_scheme_name);
String version = getVocabularyVersionByTag(coding_scheme_name,
"PRODUCTION");
if (version == null)
version = getVocabularyVersionByTag(coding_scheme_name, null);
if (version != null && version.length() > 0)
info += " (" + version + ")";
return info;
}
public static String getReleaseDate() {
return getReleaseDate(CODING_SCHEME_NAME);
}
public static String getReleaseDate(String coding_scheme_name) {
try {
LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
DateFormat formatter = new SimpleDateFormat("MMMM d, yyyy");
HistoryService hs = null;
try {
hs = lbSvc.getHistoryService(coding_scheme_name);
} catch (Exception ex) {
System.out.println("WARNING: HistoryService is not available for " + coding_scheme_name);
}
if (hs != null) {
SystemRelease release = hs.getLatestBaseline();
Date date = release.getReleaseDate();
return formatter.format(date);
}
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
/*
public static String getVocabularyVersionByTag(String codingSchemeName,
String ltag) {
if (codingSchemeName == null)
return null;
try {
LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
CodingSchemeRenderingList lcsrl = lbSvc.getSupportedCodingSchemes();
CodingSchemeRendering[] csra = lcsrl.getCodingSchemeRendering();
for (int i = 0; i < csra.length; i++) {
CodingSchemeRendering csr = csra[i];
CodingSchemeSummary css = csr.getCodingSchemeSummary();
if (css.getFormalName().compareTo(codingSchemeName) == 0
|| css.getLocalName().compareTo(codingSchemeName) == 0) {
if (ltag == null) return css.getRepresentsVersion();
RenderingDetail rd = csr.getRenderingDetail();
CodingSchemeTagList cstl = rd.getVersionTags();
java.lang.String[] tags = cstl.getTag();
for (int j = 0; j < tags.length; j++) {
String version_tag = (String) tags[j];
if (version_tag.compareToIgnoreCase(ltag) == 0) {
return css.getRepresentsVersion();
}
}
}
}
} catch (Exception e) {
System.out.println("Version corresponding to tag " + ltag
+ " is not found " + " in " + codingSchemeName);
//e.printStackTrace();
}
return null;
}
*/
public static String getVocabularyVersionByTag(String codingSchemeName, String ltag)
{
if (codingSchemeName == null) return null;
String version = null;
int knt = 0;
try {
LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
CodingSchemeRenderingList lcsrl = lbSvc.getSupportedCodingSchemes();
CodingSchemeRendering[] csra = lcsrl.getCodingSchemeRendering();
for (int i=0; i<csra.length; i++)
{
CodingSchemeRendering csr = csra[i];
CodingSchemeSummary css = csr.getCodingSchemeSummary();
if (css.getFormalName().compareTo(codingSchemeName) == 0 || css.getLocalName().compareTo(codingSchemeName) == 0)
{
version = css.getRepresentsVersion();
knt++;
if (ltag == null) return version;
RenderingDetail rd = csr.getRenderingDetail();
CodingSchemeTagList cstl = rd.getVersionTags();
java.lang.String[] tags = cstl.getTag();
//KLO, 102409
if (tags == null) return version;
if (tags != null && tags.length > 0) {
for (int j=0; j<tags.length; j++)
{
String version_tag = (String) tags[j];
if (version_tag.compareToIgnoreCase(ltag) == 0)
{
return version;
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("Version corresponding to tag " + ltag + " is not found " + " in " + codingSchemeName);
if (ltag != null && ltag.compareToIgnoreCase("PRODUCTION") == 0 & knt == 1) {
System.out.println("\tUse " + version + " as default.");
return version;
}
return null;
}
public static Vector<String> getVersionListData(String codingSchemeName) {
Vector<String> v = new Vector();
try {
// RemoteServerUtil rsu = new RemoteServerUtil();
// EVSApplicationService lbSvc = rsu.createLexBIGService();
LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
CodingSchemeRenderingList csrl = lbSvc.getSupportedCodingSchemes();
if (csrl == null)
System.out.println("csrl is NULL");
CodingSchemeRendering[] csrs = csrl.getCodingSchemeRendering();
for (int i = 0; i < csrs.length; i++) {
CodingSchemeRendering csr = csrs[i];
Boolean isActive = csr.getRenderingDetail().getVersionStatus()
.equals(CodingSchemeVersionStatus.ACTIVE);
//if (isActive != null && isActive.equals(Boolean.TRUE)) {
CodingSchemeSummary css = csr.getCodingSchemeSummary();
String formalname = css.getFormalName();
if (formalname.compareTo(codingSchemeName) == 0) {
String representsVersion = css.getRepresentsVersion();
v.add(representsVersion);
}
}
} catch (Exception ex) {
}
return v;
}
public static String getFileName(String pathname) {
File file = new File(pathname);
String filename = file.getName();
return filename;
}
protected static Association processForAnonomousNodes(Association assoc) {
// clone Association except associatedConcepts
Association temp = new Association();
temp.setAssociatedData(assoc.getAssociatedData());
temp.setAssociationName(assoc.getAssociationName());
temp.setAssociationReference(assoc.getAssociationReference());
temp.setDirectionalName(assoc.getDirectionalName());
temp.setAssociatedConcepts(new AssociatedConceptList());
for (int i = 0; i < assoc.getAssociatedConcepts()
.getAssociatedConceptCount(); i++) {
// Conditionals to deal with anonymous nodes and UMLS top nodes
// The first three allow UMLS traversal to top node.
// The last two are specific to owl anonymous nodes which can act
// like false
// top nodes.
if (assoc.getAssociatedConcepts().getAssociatedConcept(i)
.getReferencedEntry() != null
&& assoc.getAssociatedConcepts().getAssociatedConcept(i)
.getReferencedEntry().getIsAnonymous() != null
&& assoc.getAssociatedConcepts().getAssociatedConcept(i)
.getReferencedEntry().getIsAnonymous() != false
&& !assoc.getAssociatedConcepts().getAssociatedConcept(i)
.getConceptCode().equals("@")
&& !assoc.getAssociatedConcepts().getAssociatedConcept(i)
.getConceptCode().equals("@@")) {
// do nothing
} else {
temp.getAssociatedConcepts().addAssociatedConcept(
assoc.getAssociatedConcepts().getAssociatedConcept(i));
}
}
return temp;
}
public static LocalNameList vector2LocalNameList(Vector<String> v) {
if (v == null)
return null;
LocalNameList list = new LocalNameList();
for (int i = 0; i < v.size(); i++) {
String vEntry = (String) v.elementAt(i);
list.addEntry(vEntry);
}
return list;
}
protected static NameAndValueList createNameAndValueList(Vector names,
Vector values) {
if (names == null)
return null;
NameAndValueList nvList = new NameAndValueList();
for (int i = 0; i < names.size(); i++) {
String name = (String) names.elementAt(i);
String value = (String) values.elementAt(i);
NameAndValue nv = new NameAndValue();
nv.setName(name);
if (value != null) {
nv.setContent(value);
}
nvList.addNameAndValue(nv);
}
return nvList;
}
protected static CodingScheme getCodingScheme(String codingScheme,
CodingSchemeVersionOrTag versionOrTag) throws LBException {
CodingScheme cs = null;
try {
LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
cs = lbSvc.resolveCodingScheme(codingScheme, versionOrTag);
} catch (Exception ex) {
ex.printStackTrace();
}
return cs;
}
public static Vector<SupportedProperty> getSupportedProperties(
CodingScheme cs) {
if (cs == null)
return null;
Vector<SupportedProperty> v = new Vector<SupportedProperty>();
SupportedProperty[] properties = cs.getMappings()
.getSupportedProperty();
for (int i = 0; i < properties.length; i++) {
SupportedProperty sp = (SupportedProperty) properties[i];
v.add(sp);
}
return v;
}
public static Vector<String> getSupportedPropertyNames(CodingScheme cs) {
Vector w = getSupportedProperties(cs);
if (w == null)
return null;
Vector<String> v = new Vector<String>();
for (int i = 0; i < w.size(); i++) {
SupportedProperty sp = (SupportedProperty) w.elementAt(i);
v.add(sp.getLocalId());
}
return v;
}
public static Vector<String> getSupportedPropertyNames(String codingScheme,
String version) {
CodingSchemeVersionOrTag versionOrTag = new CodingSchemeVersionOrTag();
if (version != null)
versionOrTag.setVersion(version);
try {
CodingScheme cs = getCodingScheme(codingScheme, versionOrTag);
return getSupportedPropertyNames(cs);
} catch (Exception ex) {
}
return null;
}
public static Vector getPropertyNamesByType(Concept concept,
String property_type) {
Vector v = new Vector();
org.LexGrid.commonTypes.Property[] properties = null;
if (property_type.compareToIgnoreCase("GENERIC") == 0) {
properties = concept.getProperty();
} else if (property_type.compareToIgnoreCase("PRESENTATION") == 0) {
properties = concept.getPresentation();
//} else if (property_type.compareToIgnoreCase("INSTRUCTION") == 0) {
// properties = concept.getInstruction();
} else if (property_type.compareToIgnoreCase("COMMENT") == 0) {
properties = concept.getComment();
} else if (property_type.compareToIgnoreCase("DEFINITION") == 0) {
properties = concept.getDefinition();
}
if (properties == null || properties.length == 0)
return v;
for (int i = 0; i < properties.length; i++) {
Property p = (Property) properties[i];
// v.add(p.getText().getContent());
v.add(p.getPropertyName());
}
return v;
}
public static Vector getPropertyValues(Concept concept,
String property_type, String property_name) {
Vector v = new Vector();
org.LexGrid.commonTypes.Property[] properties = null;
if (property_type.compareToIgnoreCase("GENERIC") == 0) {
properties = concept.getProperty();
} else if (property_type.compareToIgnoreCase("PRESENTATION") == 0) {
properties = concept.getPresentation();
//} else if (property_type.compareToIgnoreCase("INSTRUCTION") == 0) {
// properties = concept.getInstruction();
} else if (property_type.compareToIgnoreCase("COMMENT") == 0) {
properties = concept.getComment();
} else if (property_type.compareToIgnoreCase("DEFINITION") == 0) {
properties = concept.getDefinition();
} else {
System.out.println("WARNING: property_type not found
+ property_type);
}
if (properties == null || properties.length == 0)
return v;
for (int i = 0; i < properties.length; i++) {
Property p = (Property) properties[i];
if (property_name.compareTo(p.getPropertyName()) == 0) {
String t = p.getValue().getContent();
//System.out.println("property_name: " + property_name);
//System.out.println("property_value p.getValue().getContent(): " + t);
Source[] sources = p.getSource();
if (sources != null && sources.length > 0) {
Source src = sources[0];
t = t + "|" + src.getContent();
//System.out.println("src.getContent(): " + src.getContent());
}
//System.out.println("getPropertyValues return : " + t);
v.add(t);
}
}
return v;
}
public List getSupportedRoleNames(LexBIGService lbSvc, String scheme,
String version) {
CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag();
if (version != null)
csvt.setVersion(version);
List list = new ArrayList();
try {
CodingScheme cs = lbSvc.resolveCodingScheme(scheme, csvt);
Relations[] relations = cs.getRelations();
for (int i = 0; i < relations.length; i++) {
Relations relation = relations[i];
if (relation.getContainerName().compareToIgnoreCase("roles") == 0) {
org.LexGrid.relations.Association[] asso_array = relation
.getAssociation();
for (int j = 0; j < asso_array.length; j++) {
org.LexGrid.relations.Association association = (org.LexGrid.relations.Association) asso_array[j];
//list.add(association.getAssociationName());
//KLO, 092209
list.add(association.getForwardName());
}
}
}
} catch (Exception ex) {
}
return list;
}
public static void sortArray(ArrayList list) {
String tmp;
if (list.size() <= 1)
return;
for (int i = 0; i < list.size(); i++) {
String s1 = (String) list.get(i);
for (int j = i + 1; j < list.size(); j++) {
String s2 = (String) list.get(j);
if (s1.compareToIgnoreCase(s2) > 0) {
tmp = s1;
list.set(i, s2);
list.set(j, tmp);
}
}
}
}
public static void sortArray(String[] strArray) {
String tmp;
if (strArray.length <= 1)
return;
for (int i = 0; i < strArray.length; i++) {
for (int j = i + 1; j < strArray.length; j++) {
if (strArray[i].compareToIgnoreCase(strArray[j]) > 0) {
tmp = strArray[i];
strArray[i] = strArray[j];
strArray[j] = tmp;
}
}
}
}
public String[] getSortedKeys(HashMap map) {
if (map == null)
return null;
Set keyset = map.keySet();
String[] names = new String[keyset.size()];
Iterator it = keyset.iterator();
int i = 0;
while (it.hasNext()) {
String s = (String) it.next();
names[i] = s;
i++;
}
sortArray(names);
return names;
}
public String getPreferredName(Concept c) {
Presentation[] presentations = c.getPresentation();
for (int i = 0; i < presentations.length; i++) {
Presentation p = presentations[i];
if (p.getPropertyName().compareTo("Preferred_Name") == 0) {
return p.getValue().getContent();
}
}
return null;
}
public LexBIGServiceConvenienceMethods createLexBIGServiceConvenienceMethods(LexBIGService lbSvc) {
LexBIGServiceConvenienceMethods lbscm = null;
try {
lbscm = (LexBIGServiceConvenienceMethods) lbSvc
.getGenericExtension("LexBIGServiceConvenienceMethods");
lbscm.setLexBIGService(lbSvc);
} catch (Exception ex) {
ex.printStackTrace();
}
return lbscm;
}
public HashMap getRelationshipHashMap(String scheme, String version,
String code) {
// EVSApplicationService lbSvc = new
// RemoteServerUtil().createLexBIGService();
LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
LexBIGServiceConvenienceMethods lbscm = createLexBIGServiceConvenienceMethods(lbSvc);
CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag();
if (version != null)
csvt.setVersion(version);
// Perform the query ...
ResolvedConceptReferenceList matches = null;
List list = getSupportedRoleNames(lbSvc, scheme, version);
ArrayList roleList = new ArrayList();
ArrayList associationList = new ArrayList();
ArrayList inverse_roleList = new ArrayList();
ArrayList inverse_associationList = new ArrayList();
ArrayList superconceptList = new ArrayList();
ArrayList subconceptList = new ArrayList();
HashMap map = new HashMap();
String[] associationsToNavigate = TreeUtils.getAssociationsToNavigate(scheme, version);
Vector w = new Vector();
if (associationsToNavigate != null) {
for (int k=0; k<associationsToNavigate.length; k++) {
w.add(associationsToNavigate[k]);
}
}
HashMap hmap_super = TreeUtils.getSuperconcepts(scheme, version, code);
if (hmap_super != null) {
TreeItem ti = (TreeItem) hmap_super.get(code);
for (String association : ti.assocToChildMap.keySet()) {
List<TreeItem> children = ti.assocToChildMap.get(association);
for (TreeItem childItem : children) {
superconceptList.add(childItem.text + "|" + childItem.code);
}
}
}
Collections.sort(superconceptList);
map.put(TYPE_SUPERCONCEPT, superconceptList);
HashMap hmap_sub = TreeUtils.getSubconcepts(scheme, version, code);
if (hmap_sub != null) {
TreeItem ti = (TreeItem) hmap_sub.get(code);
for (String association : ti.assocToChildMap.keySet()) {
List<TreeItem> children = ti.assocToChildMap.get(association);
for (TreeItem childItem : children) {
subconceptList.add(childItem.text + "|" + childItem.code);
}
}
}
Collections.sort(subconceptList);
map.put(TYPE_SUBCONCEPT, subconceptList);
try {
CodedNodeGraph cng = lbSvc.getNodeGraph(scheme, csvt, null);
matches = null;
try {
//KLO testing
CodedNodeSet.PropertyType[] propertyTypes = new CodedNodeSet.PropertyType[1];
propertyTypes[0] = PropertyType.PRESENTATION;
int resolveCodedEntryDepth = 0;
//matches = cng.resolveAsList(Constructors.createConceptReference(code, scheme), true, true, resolveCodedEntryDepth, 1, null, propertyTypes, null, -1);
//ResolvedConceptReferenceList resolveAsList(ConceptReference graphFocus, boolean resolveForward, boolean resolveBackward,
//int resolveCodedEntryDepth, int resolveAssociationDepth, LocalNameList propertyNames, CodedNodeSet.PropertyType[] propertyTypes, SortOptionList sortOptions, LocalNameList filterOptions, int maxToReturn, boolean keepLastAssociationLevelUnresolved)
matches = cng.resolveAsList(ConvenienceMethods
.createConceptReference(code, scheme),
//true, true, 1, 1, noopList_, null, null, null, -1, false);
//true, true, 1, 1, noopList_, propertyTypes, null, null, -1, false);
true, true, 0, 1, null, propertyTypes, null, null, -1, false);
} catch (Exception e) {
System.out.println("ERROR: DataUtils getRelationshipHashMap cng.resolveAsList throws exceptions." + code);
}
if (matches != null && matches.getResolvedConceptReferenceCount() > 0) {
Enumeration<ResolvedConceptReference> refEnum = matches
.enumerateResolvedConceptReference();
while (refEnum.hasMoreElements()) {
ResolvedConceptReference ref = refEnum.nextElement();
AssociationList sourceof = ref.getSourceOf();
if (sourceof != null) {
Association[] associations = sourceof.getAssociation();
if (associations != null) {
for (int i = 0; i < associations.length; i++) {
Association assoc = associations[i];
String associationName = lbscm.getAssociationNameFromAssociationCode(scheme, csvt, assoc.getAssociationName());
boolean isRole = false;
if (list.contains(associationName)) {
isRole = true;
}
AssociatedConcept[] acl = assoc.getAssociatedConcepts()
.getAssociatedConcept();
for (int j = 0; j < acl.length; j++) {
AssociatedConcept ac = acl[j];
EntityDescription ed = ac.getEntityDescription();
String name = "No Description";
if (ed != null)
name = ed.getContent();
String pt = name;
if (associationName.compareToIgnoreCase("equivalentClass") != 0 &&
ac.getConceptCode().indexOf("@") == -1) {
if (!w.contains(associationName)) {
String s = associationName + "|" + pt + "|"
+ ac.getConceptCode();
if (isRole) {
//if (associationName.compareToIgnoreCase("hasSubtype") != 0) {
// System.out.println("Adding role: " +
roleList.add(s);
} else {
// System.out.println("Adding association: "
associationList.add(s);
}
}
}
}
}
}
}
//inverse roles and associations
AssociationList targetof = ref.getTargetOf();
if (targetof != null) {
Association[] inv_associations = targetof.getAssociation();
if (inv_associations != null) {
for (int i = 0; i < inv_associations.length; i++) {
Association assoc = inv_associations[i];
//String associationName = assoc.getAssociationName();
String associationName = lbscm.getAssociationNameFromAssociationCode(scheme, csvt, assoc.getAssociationName());
boolean isRole = false;
if (list.contains(associationName)) {
isRole = true;
}
AssociatedConcept[] acl = assoc.getAssociatedConcepts()
.getAssociatedConcept();
for (int j = 0; j < acl.length; j++) {
AssociatedConcept ac = acl[j];
EntityDescription ed = ac.getEntityDescription();
String name = "No Description";
if (ed != null)
name = ed.getContent();
String pt = name;
//if (associationName.compareToIgnoreCase("equivalentClass") != 0) {
if (associationName.compareToIgnoreCase("equivalentClass") != 0 &&
ac.getConceptCode().indexOf("@") == -1) {
if (!w.contains(associationName)) {
String s = associationName + "|" + pt + "|"
+ ac.getConceptCode();
if (isRole) {
inverse_roleList.add(s);
} else {
inverse_associationList.add(s);
}
}
}
}
}
}
}
}
}
if (roleList.size() > 0) {
Collections.sort(roleList);
}
if (associationList.size() > 0) {
Collections.sort(associationList);
}
map.put(TYPE_ROLE, roleList);
map.put(TYPE_ASSOCIATION, associationList);
if (inverse_roleList.size() > 0) {
Collections.sort(inverse_roleList);
}
if (inverse_associationList.size() > 0) {
Collections.sort(inverse_associationList);
}
map.put(TYPE_INVERSE_ROLE, inverse_roleList);
map.put(TYPE_INVERSE_ASSOCIATION, inverse_associationList);
} catch (Exception ex) {
ex.printStackTrace();
}
return map;
}
public Vector getSuperconcepts(String scheme, String version, String code) {
// String assocName = "hasSubtype";
String hierarchicalAssoName = "hasSubtype";
Vector hierarchicalAssoName_vec = getHierarchyAssociationId(scheme,
version);
if (hierarchicalAssoName_vec != null
&& hierarchicalAssoName_vec.size() > 0) {
hierarchicalAssoName = (String) hierarchicalAssoName_vec
.elementAt(0);
}
return getAssociationSources(scheme, version, code,
hierarchicalAssoName);
}
public Vector getAssociationSources(String scheme, String version,
String code, String assocName) {
CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag();
if (version != null)
csvt.setVersion(version);
ResolvedConceptReferenceList matches = null;
Vector v = new Vector();
try {
// EVSApplicationService lbSvc = new
// RemoteServerUtil().createLexBIGService();
LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
CodedNodeGraph cng = lbSvc.getNodeGraph(scheme, csvt, null);
NameAndValueList nameAndValueList = createNameAndValueList(
new String[] { assocName }, null);
NameAndValueList nameAndValueList_qualifier = null;
cng = cng.restrictToAssociations(nameAndValueList,
nameAndValueList_qualifier);
ConceptReference graphFocus = ConvenienceMethods
.createConceptReference(code, scheme);
boolean resolveForward = false;
boolean resolveBackward = true;
int resolveAssociationDepth = 1;
int maxToReturn = 1000;
ResolvedConceptReferencesIterator iterator = codedNodeGraph2CodedNodeSetIterator(
cng, graphFocus, resolveForward, resolveBackward,
resolveAssociationDepth, maxToReturn);
v = resolveIterator(iterator, maxToReturn, code);
} catch (Exception ex) {
ex.printStackTrace();
}
return v;
}
public Vector getSubconcepts(String scheme, String version, String code) {
// String assocName = "hasSubtype";
String hierarchicalAssoName = "hasSubtype";
Vector hierarchicalAssoName_vec = getHierarchyAssociationId(scheme,
version);
if (hierarchicalAssoName_vec != null
&& hierarchicalAssoName_vec.size() > 0) {
hierarchicalAssoName = (String) hierarchicalAssoName_vec
.elementAt(0);
}
return getAssociationTargets(scheme, version, code,
hierarchicalAssoName);
}
public Vector getAssociationTargets(String scheme, String version,
String code, String assocName) {
CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag();
if (version != null)
csvt.setVersion(version);
ResolvedConceptReferenceList matches = null;
Vector v = new Vector();
try {
// EVSApplicationService lbSvc = new
// RemoteServerUtil().createLexBIGService();
LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
CodedNodeGraph cng = lbSvc.getNodeGraph(scheme, csvt, null);
NameAndValueList nameAndValueList = createNameAndValueList(
new String[] { assocName }, null);
NameAndValueList nameAndValueList_qualifier = null;
cng = cng.restrictToAssociations(nameAndValueList,
nameAndValueList_qualifier);
ConceptReference graphFocus = ConvenienceMethods
.createConceptReference(code, scheme);
boolean resolveForward = true;
boolean resolveBackward = false;
int resolveAssociationDepth = 1;
int maxToReturn = 1000;
ResolvedConceptReferencesIterator iterator = codedNodeGraph2CodedNodeSetIterator(
cng, graphFocus, resolveForward, resolveBackward,
resolveAssociationDepth, maxToReturn);
v = resolveIterator(iterator, maxToReturn, code);
} catch (Exception ex) {
ex.printStackTrace();
}
return v;
}
public ResolvedConceptReferencesIterator codedNodeGraph2CodedNodeSetIterator(
CodedNodeGraph cng, ConceptReference graphFocus,
boolean resolveForward, boolean resolveBackward,
int resolveAssociationDepth, int maxToReturn) {
CodedNodeSet cns = null;
try {
cns = cng.toNodeList(graphFocus, resolveForward, resolveBackward,
resolveAssociationDepth, maxToReturn);
if (cns == null) {
System.out.println("cng.toNodeList returns null???");
return null;
}
SortOptionList sortCriteria = null;
// Constructors.createSortOptionList(new String[]{"matchToQuery",
// "code"});
LocalNameList propertyNames = null;
CodedNodeSet.PropertyType[] propertyTypes = null;
ResolvedConceptReferencesIterator iterator = null;
try {
iterator = cns.resolve(sortCriteria, propertyNames,
propertyTypes);
} catch (Exception e) {
e.printStackTrace();
}
if (iterator == null) {
System.out.println("cns.resolve returns null???");
}
return iterator;
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
public Vector resolveIterator(ResolvedConceptReferencesIterator iterator,
int maxToReturn) {
return resolveIterator(iterator, maxToReturn, null);
}
public Vector resolveIterator(ResolvedConceptReferencesIterator iterator,
int maxToReturn, String code) {
Vector v = new Vector();
if (iterator == null) {
System.out.println("No match.");
return v;
}
try {
int iteration = 0;
while (iterator.hasNext()) {
iteration++;
iterator = iterator.scroll(maxToReturn);
ResolvedConceptReferenceList rcrl = iterator.getNext();
ResolvedConceptReference[] rcra = rcrl
.getResolvedConceptReference();
for (int i = 0; i < rcra.length; i++) {
ResolvedConceptReference rcr = rcra[i];
org.LexGrid.concepts.Concept ce = rcr.getReferencedEntry();
// System.out.println("Iteration " + iteration + " " +
// ce.getEntityCode() + " " +
// ce.getEntityDescription().getContent());
if (code == null) {
v.add(ce);
} else {
if (ce.getEntityCode().compareTo(code) != 0)
v.add(ce);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return v;
}
public static Vector<String> parseData(String line) {
String tab = "|";
return parseData(line, tab);
}
public static Vector<String> parseData(String line, String tab) {
Vector data_vec = new Vector();
StringTokenizer st = new StringTokenizer(line, tab);
while (st.hasMoreTokens()) {
String value = st.nextToken();
if (value.compareTo("null") == 0)
value = " ";
data_vec.add(value);
}
return data_vec;
}
public static String getHyperlink(String url, String codingScheme,
String code) {
codingScheme = codingScheme.replace(" ", "%20");
String link = url + "/ConceptReport.jsp?dictionary=" + codingScheme
+ "&code=" + code;
return link;
}
public List getHierarchyRoots(String scheme, String version,
String hierarchyID) throws LBException {
CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag();
if (version != null)
csvt.setVersion(version);
return getHierarchyRoots(scheme, csvt, hierarchyID);
}
public List getHierarchyRoots(String scheme, CodingSchemeVersionOrTag csvt,
String hierarchyID) throws LBException {
int maxDepth = 1;
LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
LexBIGServiceConvenienceMethods lbscm = (LexBIGServiceConvenienceMethods) lbSvc
.getGenericExtension("LexBIGServiceConvenienceMethods");
lbscm.setLexBIGService(lbSvc);
ResolvedConceptReferenceList roots = lbscm.getHierarchyRoots(scheme,
csvt, hierarchyID);
for (int i = 0; i < roots.getResolvedConceptReferenceCount(); i++) {
ResolvedConceptReference rcr = roots.getResolvedConceptReference(i);
if (rcr.getEntityDescription() == null) {
String name = TreeUtils.getCodeDescription(lbSvc, scheme, csvt, rcr.getConceptCode());
if (name == null) name = rcr.getConceptCode();//HL7
EntityDescription e = new EntityDescription();
e.setContent(name);
rcr.setEntityDescription(e);
} else if (rcr.getEntityDescription().getContent() == null) {
String name = TreeUtils.getCodeDescription(lbSvc, scheme, csvt, rcr.getConceptCode());
if (name == null) name = rcr.getConceptCode();//HL7
EntityDescription e = new EntityDescription();
e.setContent(name);
rcr.setEntityDescription(e);
}
}
List list = ResolvedConceptReferenceList2List(roots);
SortUtils.quickSort(list);
return list;
}
public List ResolvedConceptReferenceList2List(
ResolvedConceptReferenceList rcrl) {
ArrayList list = new ArrayList();
for (int i = 0; i < rcrl.getResolvedConceptReferenceCount(); i++) {
ResolvedConceptReference rcr = rcrl.getResolvedConceptReference(i);
list.add(rcr);
}
return list;
}
/*
* protected List getAncestors( String scheme, CodingSchemeVersionOrTag
* csvt, String hierarchyID, String code, int maxDistance) throws
* LBException { LexBIGService lbSvc =
* RemoteServerUtil.createLexBIGService(); LexBIGServiceConvenienceMethods
* lbscm = (LexBIGServiceConvenienceMethods)
* lbSvc.getGenericExtension("LexBIGServiceConvenienceMethods");
* lbscm.setLexBIGService(lbSvc);
*
* ArrayList list = new ArrayList(); int currentDistance = 0; try {
* addAncestorsToList(lbscm, scheme, csvt, hierarchyID, code, maxDistance,
* currentDistance, list); } catch (Exception ex) { ex.printStackTrace(); }
* return list; }
*
*
* protected void addAncestorsToList( LexBIGServiceConvenienceMethods lbscm,
* String scheme, CodingSchemeVersionOrTag csvt, String hierarchyID, String
* code, int maxDistance, int currentDistance, List list) throws LBException {
* if (maxDistance < 0 || currentDistance < maxDistance) { AssociationList
* associations = lbscm.getHierarchyLevelNext(scheme, csvt, hierarchyID,
* code, false, null); for (int i = 0; i <
* associations.getAssociationCount(); i++) { Association assoc =
* associations.getAssociation(i); AssociatedConceptList concepts =
* assoc.getAssociatedConcepts();
*
* if (concepts.getAssociatedConceptCount() == 0) { Concept c =
* getConceptByCode(scheme, null, null, code); org.LexGrid.concepts.Concept
* ce = new org.LexGrid.concepts.Concept(); ce.setId(c.getEntityCode());
* //ce.setEntityDescription(c.getEntityDescription().getContent());
* ce.setEntityDescription(c.getEntityDescription()); list.add(ce); }
*
* for (int j = 0; j < concepts.getAssociatedConceptCount(); j++) {
* AssociatedConcept concept = concepts.getAssociatedConcept(j); String
* nextCode = concept.getConceptCode(); String nextDesc =
* concept.getEntityDescription().getContent();
*
* if (currentDistance == maxDistance) { org.LexGrid.concepts.Concept ce =
* new org.LexGrid.concepts.Concept(); ce.setId(nextCode); EntityDescription
* ed = new EntityDescription(); ed.setContent(nextDesc);
* ce.setEntityDescription(ed); list.add(ce); } addAncestorsToList(lbscm,
* scheme, csvt, hierarchyID, nextCode, maxDistance, currentDistance + 1,
* list); } } } }
*/
public static Vector getSynonyms(String scheme, String version, String tag,
String code) {
Vector v = new Vector();
Concept concept = getConceptByCode(scheme, version, tag, code);
// KLO, 091009
//getSynonyms(concept);
return getSynonyms(scheme, concept);
}
public static Vector getSynonyms(Concept concept) {
if (concept == null)
return null;
Vector v = new Vector();
Presentation[] properties = concept.getPresentation();
int n = 0;
for (int i = 0; i < properties.length; i++) {
Presentation p = properties[i];
//if (p.getPropertyName().compareTo("FULL_SYN") == 0) {
String term_name = p.getValue().getContent();
String term_type = "null";
String term_source = "null";
String term_source_code = "null";
PropertyQualifier[] qualifiers = p.getPropertyQualifier();
if (qualifiers != null) {
for (int j = 0; j < qualifiers.length; j++) {
PropertyQualifier q = qualifiers[j];
String qualifier_name = q.getPropertyQualifierName();
String qualifier_value = q.getValue().getContent();
if (qualifier_name.compareTo("source-code") == 0) {
term_source_code = qualifier_value;
break;
}
}
}
term_type = p.getRepresentationalForm();
Source[] sources = p.getSource();
if (sources != null && sources.length > 0) {
Source src = sources[0];
term_source = src.getContent();
}
v.add(term_name + "|" + term_type + "|" + term_source + "|"
+ term_source_code);
}
SortUtils.quickSort(v);
return v;
}
public static Vector getSynonyms(String scheme, Concept concept) {
if (concept == null)
return null;
Vector v = new Vector();
Presentation[] properties = concept.getPresentation();
int n = 0;
boolean inclusion = true;
for (int i = 0; i < properties.length; i++) {
Presentation p = properties[i];
// for NCI Thesaurus or Pre-NCI Thesaurus, show FULL_SYNs only
if (scheme != null && scheme.indexOf(CODING_SCHEME_NAME) != -1) {
inclusion = false;
if (p.getPropertyName().compareTo("FULL_SYN") == 0) {
inclusion = true;
}
}
if (inclusion) {
String term_name = p.getValue().getContent();
String term_type = "null";
String term_source = "null";
String term_source_code = "null";
PropertyQualifier[] qualifiers = p.getPropertyQualifier();
if (qualifiers != null) {
for (int j = 0; j < qualifiers.length; j++) {
PropertyQualifier q = qualifiers[j];
String qualifier_name = q.getPropertyQualifierName();
String qualifier_value = q.getValue().getContent();
if (qualifier_name.compareTo("source-code") == 0) {
term_source_code = qualifier_value;
break;
}
}
}
term_type = p.getRepresentationalForm();
Source[] sources = p.getSource();
if (sources != null && sources.length > 0) {
Source src = sources[0];
term_source = src.getContent();
}
v.add(term_name + "|" + term_type + "|" + term_source + "|"
+ term_source_code);
}
}
SortUtils.quickSort(v);
return v;
}
public String getNCICBContactURL() {
if (NCICBContactURL != null) {
return NCICBContactURL;
}
String default_url = "ncicb@pop.nci.nih.gov";
NCItBrowserProperties properties = null;
try {
properties = NCItBrowserProperties.getInstance();
NCICBContactURL = properties
.getProperty(NCItBrowserProperties.NCICB_CONTACT_URL);
if (NCICBContactURL == null) {
NCICBContactURL = default_url;
}
} catch (Exception ex) {
}
//System.out.println("getNCICBContactURL returns " + NCICBContactURL);
return NCICBContactURL;
}
public String getTerminologySubsetDownloadURL() {
NCItBrowserProperties properties = null;
try {
properties = NCItBrowserProperties.getInstance();
terminologySubsetDownloadURL = properties
.getProperty(NCItBrowserProperties.TERMINOLOGY_SUBSET_DOWNLOAD_URL);
} catch (Exception ex) {
}
return terminologySubsetDownloadURL;
}
public String getNCITBuildInfo() {
if (NCITBuildInfo != null) {
return NCITBuildInfo;
}
String default_info = "N/A";
NCItBrowserProperties properties = null;
try {
properties = NCItBrowserProperties.getInstance();
NCITBuildInfo = properties
.getProperty(NCItBrowserProperties.NCIT_BUILD_INFO);
if (NCITBuildInfo == null) {
NCITBuildInfo = default_info;
}
} catch (Exception ex) {
ex.printStackTrace();
}
//System.out.println("getNCITBuildInfo returns " + NCITBuildInfo);
return NCITBuildInfo;
}
public String getNCImURL() {
if (NCImURL != null) {
return NCImURL;
}
String default_info = "N/A";
NCItBrowserProperties properties = null;
try {
properties = NCItBrowserProperties.getInstance();
NCImURL = properties
.getProperty(NCItBrowserProperties.NCIM_URL);
if (NCImURL == null) {
NCImURL = default_info;
}
} catch (Exception ex) {
}
return NCImURL;
}
public String getTermSuggestionURL() {
NCItBrowserProperties properties = null;
try {
properties = NCItBrowserProperties.getInstance();
term_suggestion_application_url = properties
.getProperty(NCItBrowserProperties.TERM_SUGGESTION_APPLICATION_URL);
} catch (Exception ex) {
}
return term_suggestion_application_url;
}
public static String getTermSuggestionURL(String codingSchemeName, String version) {
String propertyName = "term_suggestion_application_url";
String term_suggestion_application_url = "";
String urn = null;
if (version == null) {
version = getVocabularyVersionByTag(codingSchemeName, "PRODUCTION");
if (version == null) version = getVocabularyVersionByTag(codingSchemeName, null);
}
Vector v = MetadataUtils.getMetadataValues(codingSchemeName, version, urn, propertyName);
if (v != null && v.size() > 0) return (String) v.elementAt(0);
return term_suggestion_application_url;
}
public static CodingScheme resolveCodingScheme(LexBIGService lbSvc, String formalname, CodingSchemeVersionOrTag versionOrTag) {
try {
CodingScheme cs = lbSvc.resolveCodingScheme(formalname, versionOrTag);
return cs;
} catch (Exception ex) {
System.out.println("(*) Unable to resolveCodingScheme " + formalname);
System.out.println("(*) \tMay require security token. " );
}
return null;
}
public static HashMap getNamespaceId2CodingSchemeFormalNameMapping()
{
if (namespace2CodingScheme != null) {
return namespace2CodingScheme;
}
HashMap hmap = new HashMap();
LexBIGService lbSvc = new RemoteServerUtil().createLexBIGService();
if (lbSvc == null)
{
System.out.println("ERROR: setCodingSchemeMap RemoteServerUtil().createLexBIGService() returns null." );
return null;
}
CodingSchemeRenderingList csrl = null;
CodingSchemeRendering[] csrs = null;
try {
csrl = lbSvc.getSupportedCodingSchemes();
csrs = csrl.getCodingSchemeRendering();
} catch (LBInvocationException ex) {
System.out.println("lbSvc.getSupportedCodingSchemes() FAILED..." + ex.getCause() );
return null;
}
for (int i=0; i<csrs.length; i++)
{
CodingSchemeRendering csr = csrs[i];
if (csr != null && csr.getRenderingDetail() != null) {
Boolean isActive = null;
if (csr == null) {
System.out.println("\tcsr == null???");
} else if (csr.getRenderingDetail() == null) {
System.out.println("\tcsr.getRenderingDetail() == null");
} else if (csr.getRenderingDetail().getVersionStatus() == null) {
System.out.println("\tcsr.getRenderingDetail().getVersionStatus() == null");
} else {
isActive = csr.getRenderingDetail().getVersionStatus().equals(CodingSchemeVersionStatus.ACTIVE);
}
//System.out.println("\nActive? " + isActive);
//if (isActive != null && isActive.equals(Boolean.TRUE))
{
CodingSchemeSummary css = csr.getCodingSchemeSummary();
String formalname = css.getFormalName();
java.lang.String version = css.getRepresentsVersion();
CodingSchemeVersionOrTag versionOrTag = new CodingSchemeVersionOrTag();
if (version != null) versionOrTag.setVersion(version);
CodingScheme cs = null;
cs = resolveCodingScheme(lbSvc, formalname, versionOrTag);
if (cs != null) {
Mappings mapping = cs.getMappings();
if (mapping != null) {
SupportedNamespace[] namespaces = mapping.getSupportedNamespace();
if (namespaces != null) {
for (int j=0; j<namespaces.length; j++) {
SupportedNamespace ns = namespaces[j];
if (ns != null) {
java.lang.String ns_name = ns.getEquivalentCodingScheme();
java.lang.String ns_id = ns.getContent() ;
//System.out.println("\tns_name: " + ns_name + " ns_id:" + ns_id);
if (ns_id != null && ns_id.compareTo("") != 0) {
hmap.put(ns_id, formalname);
}
}
}
}
}
} else {
System.out.println("??? Unable to resolveCodingScheme " + formalname);
}
}
}
}
namespace2CodingScheme = hmap;
return hmap;
}
public static String getCodingSchemeName(String key) {
return key2CodingSchemeName(key);
}
public static String getCodingSchemeVersion(String key) {
return key2CodingSchemeVersion(key);
}
public static String key2CodingSchemeName(String key) {
if (key == null) {
return null;
}
if (csnv2codingSchemeNameMap == null) {
System.out.println("setCodingSchemeMap");
setCodingSchemeMap();
}
if (key.indexOf("%20") != -1) {
key.replaceAll("%20", " ");
}
if (csnv2codingSchemeNameMap == null) {
System.out.println("csnv2codingSchemeNameMap == NULL???");
return key;
}
String value = (String) csnv2codingSchemeNameMap.get(key);
if (value == null) {
//System.out.println("key2CodingSchemeName returns " + key);
return key;
}
return value;
}
public static String key2CodingSchemeVersion(String key) {
if (key == null) {
return null;
}
if (csnv2VersionMap == null) setCodingSchemeMap();
if (key.indexOf("%20") != -1) {
key.replaceAll("%20", " ");
}
if (csnv2VersionMap == null) {
System.out.println("csnv2VersionMap == NULL???");
return key;
}
String value = (String) csnv2VersionMap.get(key);
return value;
}
public static String replaceAll(String s, String t1, String t2) {
s = s.replaceAll(t1, t2);
return s;
}
public static String getDownloadLink(String url) {
String t = "<a href=\"" + url + "\" target=\"_blank\" alt=\"Download Site\">" + url + "</a>";
return t;
}
public static String getVisitedConceptLink(String scheme, Vector concept_vec) {
StringBuffer strbuf = new StringBuffer();
String line = "<A href=\"#\" onmouseover=\"Tip('";
strbuf.append(line);
strbuf.append("<ul>");
scheme = (String) formalName2LocalNameHashMap.get(scheme);
for (int i=0; i<concept_vec.size(); i++) {
int j = concept_vec.size()-i-1;
Concept c = (Concept) concept_vec.elementAt(j);
strbuf.append("<li>");
line =
"<a href=\\'/ncitbrowser/ConceptReport.jsp?dictionary="
+ scheme
+ "&code="
+ c.getEntityCode()
+ "\\'>"
+ c.getEntityDescription().getContent()
+ "</a><br>";
strbuf.append(line);
strbuf.append("</li>");
}
strbuf.append("</ul>");
line = "',";
strbuf.append(line);
line = "WIDTH, 300, TITLE, 'Visited Concepts', SHADOW, true, FADEIN, 300, FADEOUT, 300, STICKY, 1, CLOSEBTN, true, CLICKCLOSE, true)\"";
strbuf.append(line);
line = " onmouseout=UnTip() ";
strbuf.append(line);
line = ">Visited Concepts</A>";
strbuf.append(line);
return strbuf.toString();
}
public static String getVisitedConceptLink(Vector concept_vec) {
StringBuffer strbuf = new StringBuffer();
String line = "<A href=\"#\" onmouseover=\"Tip('";
strbuf.append(line);
strbuf.append("<ul>");
for (int i=0; i<concept_vec.size(); i++) {
int j = concept_vec.size()-i-1;
String concept_data = (String) concept_vec.elementAt(j);
Vector w = parseData(concept_data);
String scheme = (String) w.elementAt(0);
scheme = (String) formalName2LocalNameHashMap.get(scheme);
String code = (String) w.elementAt(1);
String name = (String) w.elementAt(2);
strbuf.append("<li>");
line =
//"<a href=\\'<%= request.getContextPath() %>/ConceptReport.jsp?dictionary="
"<a href=\\'/ncitbrowser/ConceptReport.jsp?dictionary="
+ scheme
+ "&code="
+ code
+ "\\'>"
+ name + " (" + scheme + ")"
+ "</a><br>";
strbuf.append(line);
strbuf.append("</li>");
}
strbuf.append("</ul>");
line = "',";
strbuf.append(line);
line = "WIDTH, 300, TITLE, 'Visited Concepts', SHADOW, true, FADEIN, 300, FADEOUT, 300, STICKY, 1, CLOSEBTN, true, CLICKCLOSE, true)\"";
strbuf.append(line);
line = " onmouseout=UnTip() ";
strbuf.append(line);
line = ">Visited Concepts</A>";
strbuf.append(line);
return strbuf.toString();
}
public void dumpRelationshipHashMap(HashMap hmap) {
ArrayList superconcepts = (ArrayList) hmap.get(DataUtils.TYPE_SUPERCONCEPT);
ArrayList subconcepts = (ArrayList) hmap.get(DataUtils.TYPE_SUBCONCEPT);
ArrayList roles = (ArrayList) hmap.get(DataUtils.TYPE_ROLE);
ArrayList associations = (ArrayList) hmap.get(DataUtils.TYPE_ASSOCIATION);
ArrayList inverse_roles = (ArrayList) hmap.get(DataUtils.TYPE_INVERSE_ROLE);
ArrayList inverse_associations = (ArrayList) hmap.get(DataUtils.TYPE_INVERSE_ASSOCIATION);
ArrayList concepts = null;
concepts = superconcepts;
String label = "\nParent Concepts:";
if (concepts == null || concepts.size() <= 0)
{
System.out.println(label + "(none)");
} else if (concepts != null && concepts.size() == 1) {
String s = (String) concepts.get(0);
Vector ret_vec = DataUtils.parseData(s, "|");
String cName = (String) ret_vec.elementAt(0);
String cCode = (String) ret_vec.elementAt(1);
System.out.println(label + " " + cName + "(" + cCode + ")");
} else if (concepts != null) {
System.out.println(label);
for (int i=0; i<concepts.size(); i++) {
String s = (String) concepts.get(i);
Vector ret_vec = DataUtils.parseData(s, "|");
String cName = (String) ret_vec.elementAt(0);
String cCode = (String) ret_vec.elementAt(1);
System.out.println("\t" + " " + cName + "(" + cCode + ")");
}
}
concepts = subconcepts;
label = "\nChild Concepts:";
if (concepts == null || concepts.size() <= 0)
{
System.out.println(label + "(none)");
} else if (concepts != null && concepts.size() == 1) {
String s = (String) concepts.get(0);
Vector ret_vec = DataUtils.parseData(s, "|");
String cName = (String) ret_vec.elementAt(0);
String cCode = (String) ret_vec.elementAt(1);
System.out.println(label + " " + cName + "(" + cCode + ")");
} else if (concepts != null) {
System.out.println(label);
for (int i=0; i<concepts.size(); i++) {
String s = (String) concepts.get(i);
Vector ret_vec = DataUtils.parseData(s, "|");
String cName = (String) ret_vec.elementAt(0);
String cCode = (String) ret_vec.elementAt(1);
System.out.println("\t" + " " + cName + "(" + cCode + ")");
}
}
concepts = roles;
label = "\nRoles:";
if (concepts == null || concepts.size() <= 0)
{
System.out.println(label + "(none)");
} else if (concepts != null && concepts.size() == 1) {
String s = (String) concepts.get(0);
Vector ret_vec = DataUtils.parseData(s, "|");
String cName = (String) ret_vec.elementAt(0);
String cCode = (String) ret_vec.elementAt(1);
System.out.println(label + " " + cName + "(" + cCode + ")");
} else if (concepts != null) {
System.out.println(label);
for (int i=0; i<concepts.size(); i++) {
String s = (String) concepts.get(i);
Vector ret_vec = DataUtils.parseData(s, "|");
String cName = (String) ret_vec.elementAt(0);
String cCode = (String) ret_vec.elementAt(1);
System.out.println("\t" + " " + cName + "(" + cCode + ")");
}
}
concepts = associations;
label = "\nAssociations:";
if (concepts == null || concepts.size() <= 0)
{
System.out.println(label + "(none)");
} else if (concepts != null && concepts.size() == 1) {
String s = (String) concepts.get(0);
Vector ret_vec = DataUtils.parseData(s, "|");
String cName = (String) ret_vec.elementAt(0);
String cCode = (String) ret_vec.elementAt(1);
System.out.println(label + " " + cName + "(" + cCode + ")");
} else if (concepts != null) {
System.out.println(label);
for (int i=0; i<concepts.size(); i++) {
String s = (String) concepts.get(i);
Vector ret_vec = DataUtils.parseData(s, "|");
String cName = (String) ret_vec.elementAt(0);
String cCode = (String) ret_vec.elementAt(1);
System.out.println("\t" + " " + cName + "(" + cCode + ")");
}
}
concepts = inverse_roles;
label = "\nInverse Roles:";
if (concepts == null || concepts.size() <= 0)
{
System.out.println(label + "(none)");
} else if (concepts != null && concepts.size() == 1) {
String s = (String) concepts.get(0);
Vector ret_vec = DataUtils.parseData(s, "|");
String cName = (String) ret_vec.elementAt(0);
String cCode = (String) ret_vec.elementAt(1);
System.out.println(label + " " + cName + "(" + cCode + ")");
} else if (concepts != null) {
System.out.println(label);
for (int i=0; i<concepts.size(); i++) {
String s = (String) concepts.get(i);
Vector ret_vec = DataUtils.parseData(s, "|");
String cName = (String) ret_vec.elementAt(0);
String cCode = (String) ret_vec.elementAt(1);
System.out.println("\t" + " " + cName + "(" + cCode + ")");
}
}
concepts = inverse_associations;
label = "\nInverse Associations:";
if (concepts == null || concepts.size() <= 0)
{
System.out.println(label + "(none)");
} else if (concepts != null && concepts.size() == 1) {
String s = (String) concepts.get(0);
Vector ret_vec = DataUtils.parseData(s, "|");
String cName = (String) ret_vec.elementAt(0);
String cCode = (String) ret_vec.elementAt(1);
System.out.println(label + " " + cName + "(" + cCode + ")");
} else if (concepts != null) {
System.out.println(label);
for (int i=0; i<concepts.size(); i++) {
String s = (String) concepts.get(i);
Vector ret_vec = DataUtils.parseData(s, "|");
String cName = (String) ret_vec.elementAt(0);
String cCode = (String) ret_vec.elementAt(1);
System.out.println("\t" + " " + cName + "(" + cCode + ")");
}
}
}
public static Vector getStatusByConceptCodes(String scheme, String version, String ltag, Vector codes) {
Vector w = new Vector();
long ms = System.currentTimeMillis();
for (int i=0; i<codes.size(); i++) {
String code = (String) codes.elementAt(i);
Concept c = getConceptByCode(scheme, version, ltag, code);
if (c != null) {
w.add(c.getStatus());
} else {
System.out.println("WARNING: getStatusByConceptCode returns null on " + scheme + " code: " + code );
w.add(null);
}
}
System.out.println("getStatusByConceptCodes Run time (ms): "
+ (System.currentTimeMillis() - ms) + " number of concepts: " + codes.size());
return w;
}
public static void main(String[] args) {
String scheme = "NCI Thesaurus";
String version = null;
//Breast Carcinoma (Code C4872)
String code = "C4872";
DataUtils test = new DataUtils();
HashMap hmap = test.getRelationshipHashMap(scheme, version, code);
test.dumpRelationshipHashMap(hmap);
}
}
|
package org.jfree.chart.renderer.category;
import java.awt.AlphaComposite;
import java.awt.Composite;
import java.awt.Font;
import java.awt.GradientPaint;
import java.awt.Graphics2D;
import java.awt.Paint;
import java.awt.Shape;
import java.awt.Stroke;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Line2D;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.jfree.chart.LegendItem;
import org.jfree.chart.LegendItemCollection;
import org.jfree.chart.annotations.CategoryAnnotation;
import org.jfree.chart.axis.CategoryAxis;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.entity.CategoryItemEntity;
import org.jfree.chart.entity.EntityCollection;
import org.jfree.chart.event.RendererChangeEvent;
import org.jfree.chart.labels.CategoryItemLabelGenerator;
import org.jfree.chart.labels.CategorySeriesLabelGenerator;
import org.jfree.chart.labels.CategoryToolTipGenerator;
import org.jfree.chart.labels.ItemLabelPosition;
import org.jfree.chart.labels.StandardCategorySeriesLabelGenerator;
import org.jfree.chart.plot.CategoryCrosshairState;
import org.jfree.chart.plot.CategoryMarker;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.DrawingSupplier;
import org.jfree.chart.plot.IntervalMarker;
import org.jfree.chart.plot.Marker;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.PlotRenderingInfo;
import org.jfree.chart.plot.ValueMarker;
import org.jfree.chart.renderer.AbstractRenderer;
import org.jfree.chart.text.TextUtilities;
import org.jfree.chart.urls.CategoryURLGenerator;
import org.jfree.chart.util.GradientPaintTransformer;
import org.jfree.chart.util.Layer;
import org.jfree.chart.util.LengthAdjustmentType;
import org.jfree.chart.util.ObjectList;
import org.jfree.chart.util.ObjectUtilities;
import org.jfree.chart.util.PublicCloneable;
import org.jfree.chart.util.RectangleAnchor;
import org.jfree.chart.util.RectangleEdge;
import org.jfree.chart.util.RectangleInsets;
import org.jfree.data.Range;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.general.DatasetUtilities;
/**
* An abstract base class that you can use to implement a new
* {@link CategoryItemRenderer}. When you create a new
* {@link CategoryItemRenderer} you are not required to extend this class,
* but it makes the job easier.
*/
public abstract class AbstractCategoryItemRenderer extends AbstractRenderer
implements CategoryItemRenderer, Cloneable, PublicCloneable,
Serializable {
/** For serialization. */
private static final long serialVersionUID = 1247553218442497391L;
/** The plot that the renderer is assigned to. */
private CategoryPlot plot;
/** A list of item label generators (one per series). */
private ObjectList itemLabelGeneratorList;
/** The base item label generator. */
private CategoryItemLabelGenerator baseItemLabelGenerator;
/** A list of tool tip generators (one per series). */
private ObjectList toolTipGeneratorList;
/** The base tool tip generator. */
private CategoryToolTipGenerator baseToolTipGenerator;
/** A list of label generators (one per series). */
private ObjectList urlGeneratorList;
/** The base label generator. */
private CategoryURLGenerator baseURLGenerator;
/** The legend item label generator. */
private CategorySeriesLabelGenerator legendItemLabelGenerator;
/** The legend item tool tip generator. */
private CategorySeriesLabelGenerator legendItemToolTipGenerator;
/** The legend item URL generator. */
private CategorySeriesLabelGenerator legendItemURLGenerator;
/**
* Annotations to be drawn in the background layer ('underneath' the data
* items).
*
* @since 1.2.0
*/
private List backgroundAnnotations;
/**
* Annotations to be drawn in the foreground layer ('on top' of the data
* items).
*
* @since 1.2.0
*/
private List foregroundAnnotations;
/** The number of rows in the dataset (temporary record). */
private transient int rowCount;
/** The number of columns in the dataset (temporary record). */
private transient int columnCount;
/**
* Creates a new renderer with no tool tip generator and no URL generator.
* The defaults (no tool tip or URL generators) have been chosen to
* minimise the processing required to generate a default chart. If you
* require tool tips or URLs, then you can easily add the required
* generators.
*/
protected AbstractCategoryItemRenderer() {
this.itemLabelGeneratorList = new ObjectList();
this.toolTipGeneratorList = new ObjectList();
this.urlGeneratorList = new ObjectList();
this.legendItemLabelGenerator
= new StandardCategorySeriesLabelGenerator();
this.backgroundAnnotations = new ArrayList();
this.foregroundAnnotations = new ArrayList();
}
/**
* Returns the number of passes through the dataset required by the
* renderer. This method returns <code>1</code>, subclasses should
* override if they need more passes.
*
* @return The pass count.
*/
public int getPassCount() {
return 1;
}
/**
* Returns the plot that the renderer has been assigned to (where
* <code>null</code> indicates that the renderer is not currently assigned
* to a plot).
*
* @return The plot (possibly <code>null</code>).
*
* @see #setPlot(CategoryPlot)
*/
public CategoryPlot getPlot() {
return this.plot;
}
/**
* Sets the plot that the renderer has been assigned to. This method is
* usually called by the {@link CategoryPlot}, in normal usage you
* shouldn't need to call this method directly.
*
* @param plot the plot (<code>null</code> not permitted).
*
* @see #getPlot()
*/
public void setPlot(CategoryPlot plot) {
if (plot == null) {
throw new IllegalArgumentException("Null 'plot' argument.");
}
this.plot = plot;
}
// ITEM LABEL GENERATOR
/**
* Returns the item label generator for a data item. This implementation
* returns the series item label generator if one is defined, otherwise
* it returns the default item label generator (which may be
* <code>null</code>).
*
* @param row the row index (zero based).
* @param column the column index (zero based).
*
* @return The generator (possibly <code>null</code>).
*/
public CategoryItemLabelGenerator getItemLabelGenerator(int row,
int column) {
CategoryItemLabelGenerator generator = (CategoryItemLabelGenerator)
this.itemLabelGeneratorList.get(row);
if (generator == null) {
generator = this.baseItemLabelGenerator;
}
return generator;
}
/**
* Returns the item label generator for a series.
*
* @param series the series index (zero based).
*
* @return The generator (possibly <code>null</code>).
*
* @see #setSeriesItemLabelGenerator(int, CategoryItemLabelGenerator)
*/
public CategoryItemLabelGenerator getSeriesItemLabelGenerator(int series) {
return (CategoryItemLabelGenerator) this.itemLabelGeneratorList.get(
series);
}
/**
* Sets the item label generator for a series and sends a
* {@link RendererChangeEvent} to all registered listeners.
*
* @param series the series index (zero based).
* @param generator the generator (<code>null</code> permitted).
*
* @see #getSeriesItemLabelGenerator(int)
*/
public void setSeriesItemLabelGenerator(int series,
CategoryItemLabelGenerator generator) {
setSeriesItemLabelGenerator(series, generator, true);
}
/**
* Sets the item label generator for a series and, if requested, sends a
* {@link RendererChangeEvent} to all registered listeners.
*
* @param series the series index (zero based).
* @param generator the generator (<code>null</code> permitted).
* @param notify notify listeners?
*
* @since 1.2.0
*
* @see #getSeriesItemLabelGenerator(int)
*/
public void setSeriesItemLabelGenerator(int series,
CategoryItemLabelGenerator generator, boolean notify) {
this.itemLabelGeneratorList.set(series, generator);
if (notify) {
notifyListeners(new RendererChangeEvent(this));
}
}
/**
* Returns the base item label generator.
*
* @return The generator (possibly <code>null</code>).
*
* @see #setBaseItemLabelGenerator(CategoryItemLabelGenerator)
*/
public CategoryItemLabelGenerator getBaseItemLabelGenerator() {
return this.baseItemLabelGenerator;
}
/**
* Sets the base item label generator and sends a
* {@link RendererChangeEvent} to all registered listeners.
*
* @param generator the generator (<code>null</code> permitted).
*
* @see #getBaseItemLabelGenerator()
*/
public void setBaseItemLabelGenerator(
CategoryItemLabelGenerator generator) {
setBaseItemLabelGenerator(generator, true);
}
/**
* Sets the base item label generator and, if requested, sends a
* {@link RendererChangeEvent} to all registered listeners.
*
* @param generator the generator (<code>null</code> permitted).
* @param notify notify listeners?
*
* @since 1.2.0
*
* @see #getBaseItemLabelGenerator()
*/
public void setBaseItemLabelGenerator(
CategoryItemLabelGenerator generator, boolean notify) {
this.baseItemLabelGenerator = generator;
if (notify) {
notifyListeners(new RendererChangeEvent(this));
}
}
// TOOL TIP GENERATOR
/**
* Returns the tool tip generator that should be used for the specified
* item. This method looks up the generator using the "three-layer"
* approach outlined in the general description of this interface. You
* can override this method if you want to return a different generator per
* item.
*
* @param row the row index (zero-based).
* @param column the column index (zero-based).
*
* @return The generator (possibly <code>null</code>).
*/
public CategoryToolTipGenerator getToolTipGenerator(int row, int column) {
CategoryToolTipGenerator result = null;
result = getSeriesToolTipGenerator(row);
if (result == null) {
result = this.baseToolTipGenerator;
}
return result;
}
/**
* Returns the tool tip generator for the specified series (a "layer 1"
* generator).
*
* @param series the series index (zero-based).
*
* @return The tool tip generator (possibly <code>null</code>).
*
* @see #setSeriesToolTipGenerator(int, CategoryToolTipGenerator)
*/
public CategoryToolTipGenerator getSeriesToolTipGenerator(int series) {
return (CategoryToolTipGenerator) this.toolTipGeneratorList.get(series);
}
/**
* Sets the tool tip generator for a series and sends a
* {@link RendererChangeEvent} to all registered listeners.
*
* @param series the series index (zero-based).
* @param generator the generator (<code>null</code> permitted).
*
* @see #getSeriesToolTipGenerator(int)
*/
public void setSeriesToolTipGenerator(int series,
CategoryToolTipGenerator generator) {
setSeriesToolTipGenerator(series, generator, true);
}
/**
* Sets the tool tip generator for a series and sends a
* {@link org.jfree.chart.event.RendererChangeEvent} to all registered
* listeners.
*
* @param series the series index (zero-based).
* @param generator the generator (<code>null</code> permitted).
* @param notify notify listeners?
*
* @since 1.2.0
*
* @see #getSeriesToolTipGenerator(int)
*/
public void setSeriesToolTipGenerator(int series,
CategoryToolTipGenerator generator, boolean notify) {
this.toolTipGeneratorList.set(series, generator);
if (notify) {
notifyListeners(new RendererChangeEvent(this));
}
}
/**
* Returns the base tool tip generator (the "layer 2" generator).
*
* @return The tool tip generator (possibly <code>null</code>).
*
* @see #setBaseToolTipGenerator(CategoryToolTipGenerator)
*/
public CategoryToolTipGenerator getBaseToolTipGenerator() {
return this.baseToolTipGenerator;
}
/**
* Sets the base tool tip generator and sends a {@link RendererChangeEvent}
* to all registered listeners.
*
* @param generator the generator (<code>null</code> permitted).
*
* @see #getBaseToolTipGenerator()
*/
public void setBaseToolTipGenerator(CategoryToolTipGenerator generator) {
setBaseToolTipGenerator(generator, true);
}
/**
* Sets the base tool tip generator and sends a {@link RendererChangeEvent}
* to all registered listeners.
*
* @param generator the generator (<code>null</code> permitted).
* @param notify notify listeners?
*
* @since 1.2.0
*
* @see #getBaseToolTipGenerator()
*/
public void setBaseToolTipGenerator(CategoryToolTipGenerator generator,
boolean notify) {
this.baseToolTipGenerator = generator;
if (notify) {
notifyListeners(new RendererChangeEvent(this));
}
}
// URL GENERATOR
/**
* Returns the URL generator for a data item.
*
* @param row the row index (zero based).
* @param column the column index (zero based).
*
* @return The URL generator.
*/
public CategoryURLGenerator getURLGenerator(int row, int column) {
CategoryURLGenerator generator
= (CategoryURLGenerator) this.urlGeneratorList.get(row);
if (generator == null) {
generator = this.baseURLGenerator;
}
return generator;
}
/**
* Returns the URL generator for a series.
*
* @param series the series index (zero based).
*
* @return The URL generator for the series.
*
* @see #setSeriesURLGenerator(int, CategoryURLGenerator)
*/
public CategoryURLGenerator getSeriesURLGenerator(int series) {
return (CategoryURLGenerator) this.urlGeneratorList.get(series);
}
/**
* Sets the URL generator for a series and sends a
* {@link RendererChangeEvent} to all registered listeners.
*
* @param series the series index (zero based).
* @param generator the generator.
*
* @see #getSeriesURLGenerator(int)
*/
public void setSeriesURLGenerator(int series,
CategoryURLGenerator generator) {
setSeriesURLGenerator(series, generator, true);
}
/**
* Sets the URL generator for a series and, if requested, sends a
* {@link RendererChangeEvent} to all registered listeners.
*
* @param series the series index (zero based).
* @param generator the generator (<code>null</code> permitted).
* @param notify notify listeners?
*
* @since 1.2.0
*
* @see #getSeriesURLGenerator(int)
*/
public void setSeriesURLGenerator(int series,
CategoryURLGenerator generator, boolean notify) {
this.urlGeneratorList.set(series, generator);
if (notify) {
notifyListeners(new RendererChangeEvent(this));
}
}
/**
* Returns the base item URL generator.
*
* @return The item URL generator.
*
* @see #setBaseURLGenerator(CategoryURLGenerator)
*/
public CategoryURLGenerator getBaseURLGenerator() {
return this.baseURLGenerator;
}
/**
* Sets the base item URL generator.
*
* @param generator the item URL generator.
*
* @see #getBaseURLGenerator()
*/
public void setBaseURLGenerator(CategoryURLGenerator generator) {
setBaseURLGenerator(generator, true);
}
/**
* Sets the base item URL generator.
*
* @param generator the item URL generator (<code>null</code> permitted).
* @param notify notify listeners?
*
* @see #getBaseURLGenerator()
*
* @since 1.2.0
*/
public void setBaseURLGenerator(CategoryURLGenerator generator,
boolean notify) {
this.baseURLGenerator = generator;
if (notify) {
notifyListeners(new RendererChangeEvent(this));
}
}
// ANNOTATIONS
/**
* Adds an annotation and sends a {@link RendererChangeEvent} to all
* registered listeners. The annotation is added to the foreground
* layer.
*
* @param annotation the annotation (<code>null</code> not permitted).
*
* @since 1.2.0
*/
public void addAnnotation(CategoryAnnotation annotation) {
// defer argument checking
addAnnotation(annotation, Layer.FOREGROUND);
}
/**
* Adds an annotation to the specified layer.
*
* @param annotation the annotation (<code>null</code> not permitted).
* @param layer the layer (<code>null</code> not permitted).
*
* @since 1.2.0
*/
public void addAnnotation(CategoryAnnotation annotation, Layer layer) {
if (annotation == null) {
throw new IllegalArgumentException("Null 'annotation' argument.");
}
if (layer.equals(Layer.FOREGROUND)) {
this.foregroundAnnotations.add(annotation);
notifyListeners(new RendererChangeEvent(this));
}
else if (layer.equals(Layer.BACKGROUND)) {
this.backgroundAnnotations.add(annotation);
notifyListeners(new RendererChangeEvent(this));
}
else {
// should never get here
throw new RuntimeException("Unknown layer.");
}
}
/**
* Removes the specified annotation and sends a {@link RendererChangeEvent}
* to all registered listeners.
*
* @param annotation the annotation to remove (<code>null</code> not
* permitted).
*
* @return A boolean to indicate whether or not the annotation was
* successfully removed.
*
* @since 1.2.0
*/
public boolean removeAnnotation(CategoryAnnotation annotation) {
boolean removed = this.foregroundAnnotations.remove(annotation);
removed = removed & this.backgroundAnnotations.remove(annotation);
notifyListeners(new RendererChangeEvent(this));
return removed;
}
/**
* Removes all annotations and sends a {@link RendererChangeEvent}
* to all registered listeners.
*
* @since 1.2.0
*/
public void removeAnnotations() {
this.foregroundAnnotations.clear();
this.backgroundAnnotations.clear();
notifyListeners(new RendererChangeEvent(this));
}
/**
* Returns the number of rows in the dataset. This value is updated in the
* {@link AbstractCategoryItemRenderer#initialise} method.
*
* @return The row count.
*/
public int getRowCount() {
return this.rowCount;
}
/**
* Returns the number of columns in the dataset. This value is updated in
* the {@link AbstractCategoryItemRenderer#initialise} method.
*
* @return The column count.
*/
public int getColumnCount() {
return this.columnCount;
}
protected CategoryItemRendererState createState(PlotRenderingInfo info) {
return new CategoryItemRendererState(info);
}
/**
* Initialises the renderer and returns a state object that will be used
* for the remainder of the drawing process for a single chart. The state
* object allows for the fact that the renderer may be used simultaneously
* by multiple threads (each thread will work with a separate state object).
*
* @param g2 the graphics device.
* @param dataArea the data area.
* @param plot the plot.
* @param rendererIndex the renderer index.
* @param info an object for returning information about the structure of
* the plot (<code>null</code> permitted).
*
* @return The renderer state.
*/
public CategoryItemRendererState initialise(Graphics2D g2,
Rectangle2D dataArea,
CategoryPlot plot,
int rendererIndex,
PlotRenderingInfo info) {
setPlot(plot);
CategoryDataset data = plot.getDataset(rendererIndex);
if (data != null) {
this.rowCount = data.getRowCount();
this.columnCount = data.getColumnCount();
}
else {
this.rowCount = 0;
this.columnCount = 0;
}
CategoryItemRendererState state = createState(info);
int[] visibleSeriesTemp = new int[this.rowCount];
int visibleSeriesCount = 0;
for (int row = 0; row < this.rowCount; row++) {
if (isSeriesVisible(row)) {
visibleSeriesTemp[visibleSeriesCount] = row;
visibleSeriesCount++;
}
}
int[] visibleSeries = new int[visibleSeriesCount];
System.arraycopy(visibleSeriesTemp, 0, visibleSeries, 0,
visibleSeriesCount);
state.setVisibleSeriesArray(visibleSeries);
return state;
}
/**
* Returns the range of values the renderer requires to display all the
* items from the specified dataset.
*
* @param dataset the dataset (<code>null</code> permitted).
*
* @return The range (or <code>null</code> if the dataset is
* <code>null</code> or empty).
*/
public Range findRangeBounds(CategoryDataset dataset) {
return findRangeBounds(dataset, false);
}
/**
* Returns the range of values the renderer requires to display all the
* items from the specified dataset.
*
* @param dataset the dataset (<code>null</code> permitted).
* @param includeInterval include the y-interval if the dataset has one.
*
* @return The range (<code>null</code> if the dataset is <code>null</code>
* or empty).
*
* @since 1.0.13
*/
protected Range findRangeBounds(CategoryDataset dataset,
boolean includeInterval) {
if (dataset == null) {
return null;
}
if (getDataBoundsIncludesVisibleSeriesOnly()) {
List visibleSeriesKeys = new ArrayList();
int seriesCount = dataset.getRowCount();
for (int s = 0; s < seriesCount; s++) {
if (isSeriesVisible(s)) {
visibleSeriesKeys.add(dataset.getRowKey(s));
}
}
return DatasetUtilities.findRangeBounds(dataset,
visibleSeriesKeys, includeInterval);
}
else {
return DatasetUtilities.findRangeBounds(dataset, includeInterval);
}
}
/**
* Returns the Java2D coordinate for the middle of the specified data item.
*
* @param rowKey the row key.
* @param columnKey the column key.
* @param dataset the dataset.
* @param axis the axis.
* @param area the data area.
* @param edge the edge along which the axis lies.
*
* @return The Java2D coordinate for the middle of the item.
*
* @since 1.0.11
*/
public double getItemMiddle(Comparable rowKey, Comparable columnKey,
CategoryDataset dataset, CategoryAxis axis, Rectangle2D area,
RectangleEdge edge) {
return axis.getCategoryMiddle(columnKey, dataset.getColumnKeys(), area,
edge);
}
/**
* Draws a background for the data area. The default implementation just
* gets the plot to draw the background, but some renderers will override
* this behaviour.
*
* @param g2 the graphics device.
* @param plot the plot.
* @param dataArea the data area.
*/
public void drawBackground(Graphics2D g2,
CategoryPlot plot,
Rectangle2D dataArea) {
plot.drawBackground(g2, dataArea);
}
/**
* Draws an outline for the data area. The default implementation just
* gets the plot to draw the outline, but some renderers will override this
* behaviour.
*
* @param g2 the graphics device.
* @param plot the plot.
* @param dataArea the data area.
*/
public void drawOutline(Graphics2D g2,
CategoryPlot plot,
Rectangle2D dataArea) {
plot.drawOutline(g2, dataArea);
}
/**
* Draws a grid line against the domain axis.
* <P>
* Note that this default implementation assumes that the horizontal axis
* is the domain axis. If this is not the case, you will need to override
* this method.
*
* @param g2 the graphics device.
* @param plot the plot.
* @param dataArea the area for plotting data (not yet adjusted for any
* 3D effect).
* @param value the Java2D value at which the grid line should be drawn.
* @param paint the paint (<code>null</code> not permitted).
* @param stroke the stroke (<code>null</code> not permitted).
*
* @see #drawRangeGridline(Graphics2D, CategoryPlot, ValueAxis,
* Rectangle2D, double)
*
* @since 1.2.0
*/
public void drawDomainLine(Graphics2D g2, CategoryPlot plot,
Rectangle2D dataArea, double value, Paint paint, Stroke stroke) {
if (paint == null) {
throw new IllegalArgumentException("Null 'paint' argument.");
}
if (stroke == null) {
throw new IllegalArgumentException("Null 'stroke' argument.");
}
Line2D line = null;
PlotOrientation orientation = plot.getOrientation();
if (orientation == PlotOrientation.HORIZONTAL) {
line = new Line2D.Double(dataArea.getMinX(), value,
dataArea.getMaxX(), value);
}
else if (orientation == PlotOrientation.VERTICAL) {
line = new Line2D.Double(value, dataArea.getMinY(), value,
dataArea.getMaxY());
}
g2.setPaint(paint);
g2.setStroke(stroke);
g2.draw(line);
}
/**
* Draws a line perpendicular to the range axis.
*
* @param g2 the graphics device.
* @param plot the plot.
* @param axis the value axis.
* @param dataArea the area for plotting data (not yet adjusted for any 3D
* effect).
* @param value the value at which the grid line should be drawn.
* @param paint the paint (<code>null</code> not permitted).
* @param stroke the stroke (<code>null</code> not permitted).
*
* @see #drawRangeGridline
*
* @since 1.0.13
*/
public void drawRangeLine(Graphics2D g2, CategoryPlot plot, ValueAxis axis,
Rectangle2D dataArea, double value, Paint paint, Stroke stroke) {
Range range = axis.getRange();
if (!range.contains(value)) {
return;
}
PlotOrientation orientation = plot.getOrientation();
Line2D line = null;
double v = axis.valueToJava2D(value, dataArea, plot.getRangeAxisEdge());
if (orientation == PlotOrientation.HORIZONTAL) {
line = new Line2D.Double(v, dataArea.getMinY(), v,
dataArea.getMaxY());
}
else if (orientation == PlotOrientation.VERTICAL) {
line = new Line2D.Double(dataArea.getMinX(), v,
dataArea.getMaxX(), v);
}
g2.setPaint(paint);
g2.setStroke(stroke);
g2.draw(line);
}
/**
* Draws a marker for the domain axis.
*
* @param g2 the graphics device (not <code>null</code>).
* @param plot the plot (not <code>null</code>).
* @param axis the range axis (not <code>null</code>).
* @param marker the marker to be drawn (not <code>null</code>).
* @param dataArea the area inside the axes (not <code>null</code>).
*
* @see #drawRangeMarker(Graphics2D, CategoryPlot, ValueAxis, Marker,
* Rectangle2D)
*/
public void drawDomainMarker(Graphics2D g2,
CategoryPlot plot,
CategoryAxis axis,
CategoryMarker marker,
Rectangle2D dataArea) {
Comparable category = marker.getKey();
CategoryDataset dataset = plot.getDataset(plot.getIndexOf(this));
int columnIndex = dataset.getColumnIndex(category);
if (columnIndex < 0) {
return;
}
final Composite savedComposite = g2.getComposite();
g2.setComposite(AlphaComposite.getInstance(
AlphaComposite.SRC_OVER, marker.getAlpha()));
PlotOrientation orientation = plot.getOrientation();
Rectangle2D bounds = null;
if (marker.getDrawAsLine()) {
double v = axis.getCategoryMiddle(columnIndex,
dataset.getColumnCount(), dataArea,
plot.getDomainAxisEdge());
Line2D line = null;
if (orientation == PlotOrientation.HORIZONTAL) {
line = new Line2D.Double(dataArea.getMinX(), v,
dataArea.getMaxX(), v);
}
else if (orientation == PlotOrientation.VERTICAL) {
line = new Line2D.Double(v, dataArea.getMinY(), v,
dataArea.getMaxY());
}
g2.setPaint(marker.getPaint());
g2.setStroke(marker.getStroke());
g2.draw(line);
bounds = line.getBounds2D();
}
else {
double v0 = axis.getCategoryStart(columnIndex,
dataset.getColumnCount(), dataArea,
plot.getDomainAxisEdge());
double v1 = axis.getCategoryEnd(columnIndex,
dataset.getColumnCount(), dataArea,
plot.getDomainAxisEdge());
Rectangle2D area = null;
if (orientation == PlotOrientation.HORIZONTAL) {
area = new Rectangle2D.Double(dataArea.getMinX(), v0,
dataArea.getWidth(), (v1 - v0));
}
else if (orientation == PlotOrientation.VERTICAL) {
area = new Rectangle2D.Double(v0, dataArea.getMinY(),
(v1 - v0), dataArea.getHeight());
}
g2.setPaint(marker.getPaint());
g2.fill(area);
bounds = area;
}
String label = marker.getLabel();
RectangleAnchor anchor = marker.getLabelAnchor();
if (label != null) {
Font labelFont = marker.getLabelFont();
g2.setFont(labelFont);
g2.setPaint(marker.getLabelPaint());
Point2D coordinates = calculateDomainMarkerTextAnchorPoint(
g2, orientation, dataArea, bounds, marker.getLabelOffset(),
marker.getLabelOffsetType(), anchor);
TextUtilities.drawAlignedString(label, g2,
(float) coordinates.getX(), (float) coordinates.getY(),
marker.getLabelTextAnchor());
}
g2.setComposite(savedComposite);
}
/**
* Draws a marker for the range axis.
*
* @param g2 the graphics device (not <code>null</code>).
* @param plot the plot (not <code>null</code>).
* @param axis the range axis (not <code>null</code>).
* @param marker the marker to be drawn (not <code>null</code>).
* @param dataArea the area inside the axes (not <code>null</code>).
*
* @see #drawDomainMarker(Graphics2D, CategoryPlot, CategoryAxis,
* CategoryMarker, Rectangle2D)
*/
public void drawRangeMarker(Graphics2D g2,
CategoryPlot plot,
ValueAxis axis,
Marker marker,
Rectangle2D dataArea) {
if (marker instanceof ValueMarker) {
ValueMarker vm = (ValueMarker) marker;
double value = vm.getValue();
Range range = axis.getRange();
if (!range.contains(value)) {
return;
}
final Composite savedComposite = g2.getComposite();
g2.setComposite(AlphaComposite.getInstance(
AlphaComposite.SRC_OVER, marker.getAlpha()));
PlotOrientation orientation = plot.getOrientation();
double v = axis.valueToJava2D(value, dataArea,
plot.getRangeAxisEdge());
Line2D line = null;
if (orientation == PlotOrientation.HORIZONTAL) {
line = new Line2D.Double(v, dataArea.getMinY(), v,
dataArea.getMaxY());
}
else if (orientation == PlotOrientation.VERTICAL) {
line = new Line2D.Double(dataArea.getMinX(), v,
dataArea.getMaxX(), v);
}
g2.setPaint(marker.getPaint());
g2.setStroke(marker.getStroke());
g2.draw(line);
String label = marker.getLabel();
RectangleAnchor anchor = marker.getLabelAnchor();
if (label != null) {
Font labelFont = marker.getLabelFont();
g2.setFont(labelFont);
g2.setPaint(marker.getLabelPaint());
Point2D coordinates = calculateRangeMarkerTextAnchorPoint(
g2, orientation, dataArea, line.getBounds2D(),
marker.getLabelOffset(), LengthAdjustmentType.EXPAND,
anchor);
TextUtilities.drawAlignedString(label, g2,
(float) coordinates.getX(), (float) coordinates.getY(),
marker.getLabelTextAnchor());
}
g2.setComposite(savedComposite);
}
else if (marker instanceof IntervalMarker) {
IntervalMarker im = (IntervalMarker) marker;
double start = im.getStartValue();
double end = im.getEndValue();
Range range = axis.getRange();
if (!(range.intersects(start, end))) {
return;
}
final Composite savedComposite = g2.getComposite();
g2.setComposite(AlphaComposite.getInstance(
AlphaComposite.SRC_OVER, marker.getAlpha()));
double start2d = axis.valueToJava2D(start, dataArea,
plot.getRangeAxisEdge());
double end2d = axis.valueToJava2D(end, dataArea,
plot.getRangeAxisEdge());
double low = Math.min(start2d, end2d);
double high = Math.max(start2d, end2d);
PlotOrientation orientation = plot.getOrientation();
Rectangle2D rect = null;
if (orientation == PlotOrientation.HORIZONTAL) {
// clip left and right bounds to data area
low = Math.max(low, dataArea.getMinX());
high = Math.min(high, dataArea.getMaxX());
rect = new Rectangle2D.Double(low,
dataArea.getMinY(), high - low,
dataArea.getHeight());
}
else if (orientation == PlotOrientation.VERTICAL) {
// clip top and bottom bounds to data area
low = Math.max(low, dataArea.getMinY());
high = Math.min(high, dataArea.getMaxY());
rect = new Rectangle2D.Double(dataArea.getMinX(),
low, dataArea.getWidth(),
high - low);
}
Paint p = marker.getPaint();
if (p instanceof GradientPaint) {
GradientPaint gp = (GradientPaint) p;
GradientPaintTransformer t = im.getGradientPaintTransformer();
if (t != null) {
gp = t.transform(gp, rect);
}
g2.setPaint(gp);
}
else {
g2.setPaint(p);
}
g2.fill(rect);
// now draw the outlines, if visible...
if (im.getOutlinePaint() != null && im.getOutlineStroke() != null) {
if (orientation == PlotOrientation.VERTICAL) {
Line2D line = new Line2D.Double();
double x0 = dataArea.getMinX();
double x1 = dataArea.getMaxX();
g2.setPaint(im.getOutlinePaint());
g2.setStroke(im.getOutlineStroke());
if (range.contains(start)) {
line.setLine(x0, start2d, x1, start2d);
g2.draw(line);
}
if (range.contains(end)) {
line.setLine(x0, end2d, x1, end2d);
g2.draw(line);
}
}
else { // PlotOrientation.HORIZONTAL
Line2D line = new Line2D.Double();
double y0 = dataArea.getMinY();
double y1 = dataArea.getMaxY();
g2.setPaint(im.getOutlinePaint());
g2.setStroke(im.getOutlineStroke());
if (range.contains(start)) {
line.setLine(start2d, y0, start2d, y1);
g2.draw(line);
}
if (range.contains(end)) {
line.setLine(end2d, y0, end2d, y1);
g2.draw(line);
}
}
}
String label = marker.getLabel();
RectangleAnchor anchor = marker.getLabelAnchor();
if (label != null) {
Font labelFont = marker.getLabelFont();
g2.setFont(labelFont);
g2.setPaint(marker.getLabelPaint());
Point2D coordinates = calculateRangeMarkerTextAnchorPoint(
g2, orientation, dataArea, rect,
marker.getLabelOffset(), marker.getLabelOffsetType(),
anchor);
TextUtilities.drawAlignedString(label, g2,
(float) coordinates.getX(), (float) coordinates.getY(),
marker.getLabelTextAnchor());
}
g2.setComposite(savedComposite);
}
}
/**
* Calculates the (x, y) coordinates for drawing the label for a marker on
* the range axis.
*
* @param g2 the graphics device.
* @param orientation the plot orientation.
* @param dataArea the data area.
* @param markerArea the rectangle surrounding the marker.
* @param markerOffset the marker offset.
* @param labelOffsetType the label offset type.
* @param anchor the label anchor.
*
* @return The coordinates for drawing the marker label.
*/
protected Point2D calculateDomainMarkerTextAnchorPoint(Graphics2D g2,
PlotOrientation orientation,
Rectangle2D dataArea,
Rectangle2D markerArea,
RectangleInsets markerOffset,
LengthAdjustmentType labelOffsetType,
RectangleAnchor anchor) {
Rectangle2D anchorRect = null;
if (orientation == PlotOrientation.HORIZONTAL) {
anchorRect = markerOffset.createAdjustedRectangle(markerArea,
LengthAdjustmentType.CONTRACT, labelOffsetType);
}
else if (orientation == PlotOrientation.VERTICAL) {
anchorRect = markerOffset.createAdjustedRectangle(markerArea,
labelOffsetType, LengthAdjustmentType.CONTRACT);
}
return RectangleAnchor.coordinates(anchorRect, anchor);
}
/**
* Calculates the (x, y) coordinates for drawing a marker label.
*
* @param g2 the graphics device.
* @param orientation the plot orientation.
* @param dataArea the data area.
* @param markerArea the rectangle surrounding the marker.
* @param markerOffset the marker offset.
* @param labelOffsetType the label offset type.
* @param anchor the label anchor.
*
* @return The coordinates for drawing the marker label.
*/
protected Point2D calculateRangeMarkerTextAnchorPoint(Graphics2D g2,
PlotOrientation orientation,
Rectangle2D dataArea,
Rectangle2D markerArea,
RectangleInsets markerOffset,
LengthAdjustmentType labelOffsetType,
RectangleAnchor anchor) {
Rectangle2D anchorRect = null;
if (orientation == PlotOrientation.HORIZONTAL) {
anchorRect = markerOffset.createAdjustedRectangle(markerArea,
labelOffsetType, LengthAdjustmentType.CONTRACT);
}
else if (orientation == PlotOrientation.VERTICAL) {
anchorRect = markerOffset.createAdjustedRectangle(markerArea,
LengthAdjustmentType.CONTRACT, labelOffsetType);
}
return RectangleAnchor.coordinates(anchorRect, anchor);
}
/**
* Returns a legend item for a series. This default implementation will
* return <code>null</code> if {@link #isSeriesVisible(int)} or
* {@link #isSeriesVisibleInLegend(int)} returns <code>false</code>.
*
* @param datasetIndex the dataset index (zero-based).
* @param series the series index (zero-based).
*
* @return The legend item (possibly <code>null</code>).
*
* @see #getLegendItems()
*/
public LegendItem getLegendItem(int datasetIndex, int series) {
CategoryPlot p = getPlot();
if (p == null) {
return null;
}
// check that a legend item needs to be displayed...
if (!isSeriesVisible(series) || !isSeriesVisibleInLegend(series)) {
return null;
}
CategoryDataset dataset = p.getDataset(datasetIndex);
String label = this.legendItemLabelGenerator.generateLabel(dataset,
series);
String description = label;
String toolTipText = null;
if (this.legendItemToolTipGenerator != null) {
toolTipText = this.legendItemToolTipGenerator.generateLabel(
dataset, series);
}
String urlText = null;
if (this.legendItemURLGenerator != null) {
urlText = this.legendItemURLGenerator.generateLabel(dataset,
series);
}
Shape shape = lookupLegendShape(series);
Paint paint = lookupSeriesPaint(series);
Paint outlinePaint = lookupSeriesOutlinePaint(series);
Stroke outlineStroke = lookupSeriesOutlineStroke(series);
LegendItem item = new LegendItem(label, description, toolTipText,
urlText, shape, paint, outlineStroke, outlinePaint);
item.setLabelFont(lookupLegendTextFont(series));
Paint labelPaint = lookupLegendTextPaint(series);
if (labelPaint != null) {
item.setLabelPaint(labelPaint);
}
item.setSeriesKey(dataset.getRowKey(series));
item.setSeriesIndex(series);
item.setDataset(dataset);
item.setDatasetIndex(datasetIndex);
return item;
}
/**
* Tests this renderer for equality with another object.
*
* @param obj the object.
*
* @return <code>true</code> or <code>false</code>.
*/
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof AbstractCategoryItemRenderer)) {
return false;
}
AbstractCategoryItemRenderer that = (AbstractCategoryItemRenderer) obj;
if (!ObjectUtilities.equal(this.itemLabelGeneratorList,
that.itemLabelGeneratorList)) {
return false;
}
if (!ObjectUtilities.equal(this.baseItemLabelGenerator,
that.baseItemLabelGenerator)) {
return false;
}
if (!ObjectUtilities.equal(this.toolTipGeneratorList,
that.toolTipGeneratorList)) {
return false;
}
if (!ObjectUtilities.equal(this.baseToolTipGenerator,
that.baseToolTipGenerator)) {
return false;
}
if (!ObjectUtilities.equal(this.urlGeneratorList,
that.urlGeneratorList)) {
return false;
}
if (!ObjectUtilities.equal(this.baseURLGenerator,
that.baseURLGenerator)) {
return false;
}
if (!ObjectUtilities.equal(this.legendItemLabelGenerator,
that.legendItemLabelGenerator)) {
return false;
}
if (!ObjectUtilities.equal(this.legendItemToolTipGenerator,
that.legendItemToolTipGenerator)) {
return false;
}
if (!ObjectUtilities.equal(this.legendItemURLGenerator,
that.legendItemURLGenerator)) {
return false;
}
if (!ObjectUtilities.equal(this.backgroundAnnotations,
that.backgroundAnnotations)) {
return false;
}
if (!ObjectUtilities.equal(this.foregroundAnnotations,
that.foregroundAnnotations)) {
return false;
}
return super.equals(obj);
}
/**
* Returns a hash code for the renderer.
*
* @return The hash code.
*/
public int hashCode() {
int result = super.hashCode();
return result;
}
/**
* Returns the drawing supplier from the plot.
*
* @return The drawing supplier (possibly <code>null</code>).
*/
public DrawingSupplier getDrawingSupplier() {
DrawingSupplier result = null;
CategoryPlot cp = getPlot();
if (cp != null) {
result = cp.getDrawingSupplier();
}
return result;
}
/**
* Considers the current (x, y) coordinate and updates the crosshair point
* if it meets the criteria (usually means the (x, y) coordinate is the
* closest to the anchor point so far).
*
* @param crosshairState the crosshair state (<code>null</code> permitted,
* but the method does nothing in that case).
* @param rowKey the row key.
* @param columnKey the column key.
* @param value the data value.
* @param datasetIndex the dataset index.
* @param transX the x-value translated to Java2D space.
* @param transY the y-value translated to Java2D space.
* @param orientation the plot orientation (<code>null</code> not
* permitted).
*
* @since 1.0.11
*/
protected void updateCrosshairValues(CategoryCrosshairState crosshairState,
Comparable rowKey, Comparable columnKey, double value,
int datasetIndex,
double transX, double transY, PlotOrientation orientation) {
if (orientation == null) {
throw new IllegalArgumentException("Null 'orientation' argument.");
}
if (crosshairState != null) {
if (this.plot.isRangeCrosshairLockedOnData()) {
// both axes
crosshairState.updateCrosshairPoint(rowKey, columnKey, value,
datasetIndex, transX, transY, orientation);
}
else {
crosshairState.updateCrosshairX(rowKey, columnKey,
datasetIndex, transX, orientation);
}
}
}
/**
* Draws an item label.
*
* @param g2 the graphics device.
* @param orientation the orientation.
* @param dataset the dataset.
* @param row the row.
* @param column the column.
* @param x the x coordinate (in Java2D space).
* @param y the y coordinate (in Java2D space).
* @param negative indicates a negative value (which affects the item
* label position).
*/
protected void drawItemLabel(Graphics2D g2, PlotOrientation orientation,
CategoryDataset dataset, int row, int column,
double x, double y, boolean negative) {
CategoryItemLabelGenerator generator = getItemLabelGenerator(row,
column);
if (generator != null) {
Font labelFont = getItemLabelFont(row, column);
Paint paint = getItemLabelPaint(row, column);
g2.setFont(labelFont);
g2.setPaint(paint);
String label = generator.generateLabel(dataset, row, column);
ItemLabelPosition position = null;
if (!negative) {
position = getPositiveItemLabelPosition(row, column);
}
else {
position = getNegativeItemLabelPosition(row, column);
}
Point2D anchorPoint = calculateLabelAnchorPoint(
position.getItemLabelAnchor(), x, y, orientation);
TextUtilities.drawRotatedString(label, g2,
(float) anchorPoint.getX(), (float) anchorPoint.getY(),
position.getTextAnchor(),
position.getAngle(), position.getRotationAnchor());
}
}
/**
* Draws all the annotations for the specified layer.
*
* @param g2 the graphics device.
* @param dataArea the data area.
* @param domainAxis the domain axis.
* @param rangeAxis the range axis.
* @param layer the layer.
* @param info the plot rendering info.
*
* @since 1.2.0
*/
public void drawAnnotations(Graphics2D g2, Rectangle2D dataArea,
CategoryAxis domainAxis, ValueAxis rangeAxis, Layer layer,
PlotRenderingInfo info) {
Iterator iterator = null;
if (layer.equals(Layer.FOREGROUND)) {
iterator = this.foregroundAnnotations.iterator();
}
else if (layer.equals(Layer.BACKGROUND)) {
iterator = this.backgroundAnnotations.iterator();
}
else {
// should not get here
throw new RuntimeException("Unknown layer.");
}
while (iterator.hasNext()) {
CategoryAnnotation annotation = (CategoryAnnotation) iterator.next();
annotation.draw(g2, this.plot, dataArea, domainAxis, rangeAxis,
0, info);
}
}
/**
* Returns an independent copy of the renderer. The <code>plot</code>
* reference is shallow copied.
*
* @return A clone.
*
* @throws CloneNotSupportedException can be thrown if one of the objects
* belonging to the renderer does not support cloning (for example,
* an item label generator).
*/
public Object clone() throws CloneNotSupportedException {
AbstractCategoryItemRenderer clone
= (AbstractCategoryItemRenderer) super.clone();
if (this.itemLabelGeneratorList != null) {
clone.itemLabelGeneratorList
= (ObjectList) this.itemLabelGeneratorList.clone();
}
if (this.baseItemLabelGenerator != null) {
if (this.baseItemLabelGenerator instanceof PublicCloneable) {
PublicCloneable pc
= (PublicCloneable) this.baseItemLabelGenerator;
clone.baseItemLabelGenerator
= (CategoryItemLabelGenerator) pc.clone();
}
else {
throw new CloneNotSupportedException(
"ItemLabelGenerator not cloneable.");
}
}
if (this.toolTipGeneratorList != null) {
clone.toolTipGeneratorList
= (ObjectList) this.toolTipGeneratorList.clone();
}
if (this.baseToolTipGenerator != null) {
if (this.baseToolTipGenerator instanceof PublicCloneable) {
PublicCloneable pc
= (PublicCloneable) this.baseToolTipGenerator;
clone.baseToolTipGenerator
= (CategoryToolTipGenerator) pc.clone();
}
else {
throw new CloneNotSupportedException(
"Base tool tip generator not cloneable.");
}
}
if (this.urlGeneratorList != null) {
clone.urlGeneratorList = (ObjectList) this.urlGeneratorList.clone();
}
if (this.baseURLGenerator != null) {
if (this.baseURLGenerator instanceof PublicCloneable) {
PublicCloneable pc = (PublicCloneable) this.baseURLGenerator;
clone.baseURLGenerator = (CategoryURLGenerator) pc.clone();
}
else {
throw new CloneNotSupportedException(
"Base item URL generator not cloneable.");
}
}
if (this.legendItemLabelGenerator instanceof PublicCloneable) {
clone.legendItemLabelGenerator = (CategorySeriesLabelGenerator)
ObjectUtilities.clone(this.legendItemLabelGenerator);
}
if (this.legendItemToolTipGenerator instanceof PublicCloneable) {
clone.legendItemToolTipGenerator = (CategorySeriesLabelGenerator)
ObjectUtilities.clone(this.legendItemToolTipGenerator);
}
if (this.legendItemURLGenerator instanceof PublicCloneable) {
clone.legendItemURLGenerator = (CategorySeriesLabelGenerator)
ObjectUtilities.clone(this.legendItemURLGenerator);
}
return clone;
}
/**
* Returns a domain axis for a plot.
*
* @param plot the plot.
* @param index the axis index.
*
* @return A domain axis.
*/
protected CategoryAxis getDomainAxis(CategoryPlot plot, int index) {
CategoryAxis result = plot.getDomainAxis(index);
if (result == null) {
result = plot.getDomainAxis();
}
return result;
}
/**
* Returns a range axis for a plot.
*
* @param plot the plot.
* @param index the axis index.
*
* @return A range axis.
*/
protected ValueAxis getRangeAxis(CategoryPlot plot, int index) {
ValueAxis result = plot.getRangeAxis(index);
if (result == null) {
result = plot.getRangeAxis();
}
return result;
}
/**
* Returns a (possibly empty) collection of legend items for the series
* that this renderer is responsible for drawing.
*
* @return The legend item collection (never <code>null</code>).
*
* @see #getLegendItem(int, int)
*/
public LegendItemCollection getLegendItems() {
if (this.plot == null) {
return new LegendItemCollection();
}
LegendItemCollection result = new LegendItemCollection();
int index = this.plot.getIndexOf(this);
CategoryDataset dataset = this.plot.getDataset(index);
if (dataset != null) {
int seriesCount = dataset.getRowCount();
for (int i = 0; i < seriesCount; i++) {
if (isSeriesVisibleInLegend(i)) {
LegendItem item = getLegendItem(index, i);
if (item != null) {
result.add(item);
}
}
}
}
return result;
}
/**
* Returns the legend item label generator.
*
* @return The label generator (never <code>null</code>).
*
* @see #setLegendItemLabelGenerator(CategorySeriesLabelGenerator)
*/
public CategorySeriesLabelGenerator getLegendItemLabelGenerator() {
return this.legendItemLabelGenerator;
}
/**
* Sets the legend item label generator and sends a
* {@link RendererChangeEvent} to all registered listeners.
*
* @param generator the generator (<code>null</code> not permitted).
*
* @see #getLegendItemLabelGenerator()
*/
public void setLegendItemLabelGenerator(
CategorySeriesLabelGenerator generator) {
if (generator == null) {
throw new IllegalArgumentException("Null 'generator' argument.");
}
this.legendItemLabelGenerator = generator;
fireChangeEvent();
}
/**
* Returns the legend item tool tip generator.
*
* @return The tool tip generator (possibly <code>null</code>).
*
* @see #setLegendItemToolTipGenerator(CategorySeriesLabelGenerator)
*/
public CategorySeriesLabelGenerator getLegendItemToolTipGenerator() {
return this.legendItemToolTipGenerator;
}
/**
* Sets the legend item tool tip generator and sends a
* {@link RendererChangeEvent} to all registered listeners.
*
* @param generator the generator (<code>null</code> permitted).
*
* @see #setLegendItemToolTipGenerator(CategorySeriesLabelGenerator)
*/
public void setLegendItemToolTipGenerator(
CategorySeriesLabelGenerator generator) {
this.legendItemToolTipGenerator = generator;
fireChangeEvent();
}
/**
* Returns the legend item URL generator.
*
* @return The URL generator (possibly <code>null</code>).
*
* @see #setLegendItemURLGenerator(CategorySeriesLabelGenerator)
*/
public CategorySeriesLabelGenerator getLegendItemURLGenerator() {
return this.legendItemURLGenerator;
}
/**
* Sets the legend item URL generator and sends a
* {@link RendererChangeEvent} to all registered listeners.
*
* @param generator the generator (<code>null</code> permitted).
*
* @see #getLegendItemURLGenerator()
*/
public void setLegendItemURLGenerator(
CategorySeriesLabelGenerator generator) {
this.legendItemURLGenerator = generator;
fireChangeEvent();
}
/**
* Adds an entity with the specified hotspot.
*
* @param entities the entity collection.
* @param dataset the dataset.
* @param row the row index.
* @param column the column index.
* @param hotspot the hotspot (<code>null</code> not permitted).
*/
protected void addItemEntity(EntityCollection entities,
CategoryDataset dataset, int row, int column,
Shape hotspot) {
if (hotspot == null) {
throw new IllegalArgumentException("Null 'hotspot' argument.");
}
if (!getItemCreateEntity(row, column)) {
return;
}
String tip = null;
CategoryToolTipGenerator tipster = getToolTipGenerator(row, column);
if (tipster != null) {
tip = tipster.generateToolTip(dataset, row, column);
}
String url = null;
CategoryURLGenerator urlster = getURLGenerator(row, column);
if (urlster != null) {
url = urlster.generateURL(dataset, row, column);
}
CategoryItemEntity entity = new CategoryItemEntity(hotspot, tip, url,
dataset, dataset.getRowKey(row), dataset.getColumnKey(column));
entities.add(entity);
}
/**
* Adds an entity to the collection.
*
* @param entities the entity collection being populated.
* @param hotspot the entity area (if <code>null</code> a default will be
* used).
* @param dataset the dataset.
* @param row the series.
* @param column the item.
* @param entityX the entity's center x-coordinate in user space (only
* used if <code>area</code> is <code>null</code>).
* @param entityY the entity's center y-coordinate in user space (only
* used if <code>area</code> is <code>null</code>).
*
* @since 1.0.13
*/
protected void addEntity(EntityCollection entities, Shape hotspot,
CategoryDataset dataset, int row, int column,
double entityX, double entityY) {
if (!getItemCreateEntity(row, column)) {
return;
}
Shape s = hotspot;
if (hotspot == null) {
double r = getDefaultEntityRadius();
double w = r * 2;
if (getPlot().getOrientation() == PlotOrientation.VERTICAL) {
s = new Ellipse2D.Double(entityX - r, entityY - r, w, w);
}
else {
s = new Ellipse2D.Double(entityY - r, entityX - r, w, w);
}
}
String tip = null;
CategoryToolTipGenerator generator = getToolTipGenerator(row, column);
if (generator != null) {
tip = generator.generateToolTip(dataset, row, column);
}
String url = null;
CategoryURLGenerator urlster = getURLGenerator(row, column);
if (urlster != null) {
url = urlster.generateURL(dataset, row, column);
}
CategoryItemEntity entity = new CategoryItemEntity(s, tip, url,
dataset, dataset.getRowKey(row), dataset.getColumnKey(column));
entities.add(entity);
}
}
|
package com.velocicaptor.squidb.gson;
import com.google.gson.Gson;
import com.yahoo.squidb.data.AbstractModel;
import com.yahoo.squidb.sql.Property;
public class SquidbGsonSupport {
public static final Gson GSON = new Gson();
@SuppressWarnings("unchecked")
public static <T> T fromJson(AbstractModel model, Property.StringProperty property, Class<T> type) {
if (!model.hasTransitory(property.getName())) {
T data = null;
if (model.containsNonNullValue(property)) {
data = (T) GSON.fromJson(model.get(property), type);
}
model.putTransitory(property.getName(), data);
return data;
}
return (T) model.getTransitory(property.getName());
}
/**
* Sets the given GSON-serialized property to the given value
*
* @return true if the value object was successfully serialized, false otherwise
* @see {@link #toJson}
*/
public static boolean toJson(AbstractModel model, Property.StringProperty property, Object data) {
String json = null;
if (data != null) {
json = GSON.toJson(data);
if (model.containsNonNullValue(property)
&& json.equals(model.get(property))) {
return false;
}
}
model.set(property, json);
model.putTransitory(property.getName(), data);
return true;
}
}
|
package org.evilbinary.tv.widget;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.RectF;
import android.util.AttributeSet;
import evilbinary.org.lib.R;
/**
* :evilbinary on 3/20/16.
* :rootdebug@163.com
*/
public class RoundImpl {
private float mRadius;
private float mTopLeftRadius;
private float mTopRightRadius;
private float mBottomLeftRadius;
private float mBottomRightRadius;
private Paint mPaint;
private Path mPath;
private RoundedView mView;
public RoundImpl(RoundedView view, Context context, AttributeSet attrs, int defStyle) {
init(context, attrs, defStyle);
mView = view;
}
private void init(Context context, AttributeSet attrs, int defStyle) {
mPaint = new Paint();
mPaint.setColor(Color.WHITE);
mPaint.setAntiAlias(true);
mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
mPath = new Path();
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.RoundImpl, defStyle, 0);
mBottomLeftRadius = a.getDimension(R.styleable.RoundImpl_bottomLeftRadius, -1);
mBottomRightRadius = a.getDimension(R.styleable.RoundImpl_bottomRightRadius, -1);
mTopLeftRadius = a.getDimension(R.styleable.RoundImpl_topLeftRadius, -1);
mTopRightRadius = a.getDimension(R.styleable.RoundImpl_topRightRadius, -1);
mRadius = a.getDimension(R.styleable.RoundImpl_radius, -1);
if (mRadius > 0) {
if (mBottomLeftRadius < 0)
mBottomLeftRadius = mRadius;
if (mBottomRightRadius < 0)
mBottomRightRadius = mRadius;
if (mTopLeftRadius < 0)
mTopLeftRadius = mRadius;
if (mTopRightRadius < 0)
mTopRightRadius = mRadius;
}
a.recycle();
}
public interface RoundedView {
public void drawSuper(Canvas canvas);
public Context getContext();
public RoundImpl getRoundImpl();
public int getWidth();
public int getHeight();
}
public void draw(Canvas canvas) {
if (mBottomLeftRadius <= 0 && mBottomRightRadius <= 0 && mTopRightRadius <= 0 && mTopLeftRadius <= 0) {
mView.drawSuper(canvas);
return;
}
int width = mView.getWidth();
int height = mView.getHeight();
int count = canvas.save();
int count2 = canvas.saveLayer(0, 0, width, height, null, Canvas.ALL_SAVE_FLAG);
addRoundPath(width, height);
mView.drawSuper(canvas);
canvas.drawPath(mPath, mPaint);
canvas.restoreToCount(count2);
//drawBorder(canvas);
canvas.restoreToCount(count);
}
private void addRoundPath(int width, int height) {
//topleft path
if (mTopLeftRadius > 0) {
Path topLeftPath = new Path();
topLeftPath.moveTo(0, mTopLeftRadius);
topLeftPath.lineTo(0, 0);
topLeftPath.lineTo(mTopLeftRadius, 0);
RectF arc = new RectF(0, 0, mTopLeftRadius * 2, mTopLeftRadius * 2);
topLeftPath.arcTo(arc, -90, -90);
topLeftPath.close();
mPath.addPath(topLeftPath);
}
//topRight path
if (mTopRightRadius > 0) {
Path topRightPath = new Path();
topRightPath.moveTo(width, mTopRightRadius);
topRightPath.lineTo(width, 0);
topRightPath.lineTo(width - mTopRightRadius, 0);
RectF arc = new RectF(width - mTopRightRadius * 2, 0, width, mTopRightRadius * 2);
topRightPath.arcTo(arc, -90, 90);
topRightPath.close();
mPath.addPath(topRightPath);
}
//bottomLeft path
if (mBottomLeftRadius > 0) {
Path bottomLeftPath = new Path();
bottomLeftPath.moveTo(0, height - mBottomLeftRadius);
bottomLeftPath.lineTo(0, height);
bottomLeftPath.lineTo(mBottomLeftRadius, height);
RectF arc = new RectF(0, height - mBottomLeftRadius * 2, mBottomLeftRadius * 2, height);
bottomLeftPath.arcTo(arc, 90, 90);
bottomLeftPath.close();
mPath.addPath(bottomLeftPath);
}
//bottomRight path
if (mBottomRightRadius > 0) {
Path bottomRightPath = new Path();
bottomRightPath.moveTo(width - mBottomRightRadius, height);
bottomRightPath.lineTo(width, height);
bottomRightPath.lineTo(width, height - mBottomRightRadius);
RectF arc = new RectF(width - mBottomRightRadius * 2, height - mBottomRightRadius * 2, width, height);
bottomRightPath.arcTo(arc, 0, 90);
bottomRightPath.close();
mPath.addPath(bottomRightPath);
}
}
public static Bitmap getRoundBitmap(Bitmap bitmap, int roundWidth, int roundHeight) {
Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
bitmap.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(output);
int count = canvas.save(Canvas.ALL_SAVE_FLAG);
final Paint paint = new Paint();
final RectF rectF = new RectF(0, 0, bitmap.getWidth(), bitmap.getHeight());
paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
canvas.drawRoundRect(rectF, roundWidth, roundHeight, paint);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(bitmap, 0, 0, paint);
canvas.restoreToCount(count);
return output;
}
}
|
package com.github.rvesse.airline;
import com.google.common.base.Joiner;
import org.testng.annotations.Test;
public class TestPing
{
@Test
public void test()
{
// simple command parsing example
ping();
ping("-c", "5");
ping("--count", "9");
ping("--count=8");
// show help
ping("-h");
ping("--help");
}
private void ping(String... args)
{
System.out.println("$ ping " + Joiner.on(' ').join(args));
Ping.main(args);
System.out.println();
}
}
|
package oci.lib;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
/**
* This class contains all methods for an edge service registration and un-registration at the local OCI coordinator
* @author Marc Koerner
*/
public class ServiceNameRegistration {
public final static byte[] IPADDRESS = {(byte) 127, (byte) 0, (byte) 0, (byte) 1}; // LOCIC IP (first iteration)
public final static int PORT = ServiceNameResolver.PORT + 1; // Port 5534
private final static int SOCKET_TIMEOUT = 5000; // 5 seconds timeout
/**
* This method registers an edge service at the local OCI coordinator
* @param serviceName Name of the edge service
* @param ip IP address of the edge service
* @return registration key if successful and ServiceNameEntry.NO_ID if an error appeared
*/
public final static int registerEdgeService(String serviceName, InetAddress ip) {
ServiceNameEntry edgeServiceEntry = new ServiceNameEntry(serviceName, ip);
return registerEdgeService(edgeServiceEntry);
}
/**
* This method registers an edge service at the local OCI coordinator
* @param serviceNameEntry Service name entry of the edge service
* @return registration key if successful and ServiceNameEntry.NO_ID if an error appeared
*/
public final static int registerEdgeService(ServiceNameEntry serviceNameEntry) {
// TODO: check method parameters for safety
int ret = ServiceNameEntry.NO_KEY;
if( serviceNameEntry.getServiceName() == null
|| serviceNameEntry.getIpAddress() == null) return ret;
try {
Socket locicSocket = new Socket(InetAddress.getByAddress(IPADDRESS), PORT);
//locicSocket.setSoTimeout(SOCKET_TIMEOUT);
ObjectOutputStream oos = new ObjectOutputStream(locicSocket.getOutputStream());
ObjectInputStream ois = new ObjectInputStream(locicSocket.getInputStream());
oos.writeObject(serviceNameEntry);
oos.flush();
int id = ois.readInt();
serviceNameEntry.setKey(id);
ois.close();
oos.close();
locicSocket.close();
ret = id;
} catch (IOException e) {
e.printStackTrace();
}
return ret;
}
/**
* This method un-registers an edge service at the local OCI coordinator
* @param serviceName Name of the edge service
* @param registrationKey return value of the registration aka registration key
* @return true if service was successful un-registered
*/
public final static boolean unregisterEdgeService(String serviceName, int registrationKey) {
ServiceNameEntry serviceNameEntry = null;
try {
// workaround for safety on null pointer in registerEdgeService() method
serviceNameEntry = new ServiceNameEntry(serviceName, InetAddress.getByAddress(IPADDRESS));
} catch (UnknownHostException e) {
e.printStackTrace();
return false;
}
serviceNameEntry.setKey(registrationKey);
return unregisterEdgeService(serviceNameEntry);
}
/**
* This method un-registers an edge service at the local OCI coordinator
* @param serviceNameEntry Service name entry of the edge service
* @return true if service was successful un-registered
*/
public final static boolean unregisterEdgeService(ServiceNameEntry serviceNameEntry) {
// TODO: check method parameters for safety
boolean ret = true;
if(serviceNameEntry.getKey() == registerEdgeService(serviceNameEntry)) ret = false;
return ret;
}
} // class ServiceNameRegistration
|
package com.dqc.qlibrary.utils;
import android.content.Context;
import android.content.SharedPreferences;
import java.util.Map;
/**
* Android SharedPreferences
* <p/>
* Application
*/
public class SPUtils {
private static String SP_NAME = "SPUtils";
private static SharedPreferences sharedPreferences;
private static SharedPreferences.Editor editor;
/**
* spNameApplication
*/
public static void init(String spName) {
SP_NAME = spName;
}
/**
* initspName
*/
public static void putBoolen(Context context, String key, boolean val) {
sharedPreferences = context.getApplicationContext().getSharedPreferences(SP_NAME, Context.MODE_PRIVATE);
editor = sharedPreferences.edit();
editor.putBoolean(key, val);
editor.apply();
}
/**
* spName
*/
public static void putBoolen(Context context, String spName, String key, boolean val) {
sharedPreferences = context.getApplicationContext().getSharedPreferences(spName, Context.MODE_PRIVATE);
editor = sharedPreferences.edit();
editor.putBoolean(key, val);
editor.apply();
}
/**
* initspName
*/
public static void putInt(Context context, String key, int val) {
sharedPreferences = context.getApplicationContext().getSharedPreferences(SP_NAME, Context.MODE_PRIVATE);
editor = sharedPreferences.edit();
editor.putInt(key, val);
editor.apply();
}
/**
* spName
*/
public static void putInt(Context context, String spName, String key, int val) {
sharedPreferences = context.getApplicationContext().getSharedPreferences(spName, Context.MODE_PRIVATE);
editor = sharedPreferences.edit();
editor.putInt(key, val);
editor.apply();
}
/**
* initspName
*/
public static void putFloat(Context context, String key, float val) {
sharedPreferences = context.getApplicationContext().getSharedPreferences(SP_NAME, Context.MODE_PRIVATE);
editor = sharedPreferences.edit();
editor.putFloat(key, val);
editor.apply();
}
/**
* spName
*/
public static void putFloat(Context context, String spName, String key, float val) {
sharedPreferences = context.getApplicationContext().getSharedPreferences(spName, Context.MODE_PRIVATE);
editor = sharedPreferences.edit();
editor.putFloat(key, val);
editor.apply();
}
/**
* initspName
*/
public static void putLong(Context context, String key, long val) {
sharedPreferences = context.getApplicationContext().getSharedPreferences(SP_NAME, Context.MODE_PRIVATE);
editor = sharedPreferences.edit();
editor.putLong(key, val);
editor.apply();
}
/**
* spName
*/
public static void putLong(Context context, String spName, String key, long val) {
sharedPreferences = context.getApplicationContext().getSharedPreferences(spName, Context.MODE_PRIVATE);
editor = sharedPreferences.edit();
editor.putLong(key, val);
editor.apply();
}
/**
* initspName
*/
public static void putString(Context context, String key, String val) {
sharedPreferences = context.getApplicationContext().getSharedPreferences(SP_NAME, Context.MODE_PRIVATE);
editor = sharedPreferences.edit();
editor.putString(key, val);
editor.apply();
}
/**
* spName
*/
public static void putString(Context context, String spName, String key, String val) {
sharedPreferences = context.getApplicationContext().getSharedPreferences(spName, Context.MODE_PRIVATE);
editor = sharedPreferences.edit();
editor.putString(key, val);
editor.apply();
}
/**
* initspName
*/
public static boolean getBoolen(Context context, String key, boolean defaultVal) {
sharedPreferences = context.getApplicationContext().getSharedPreferences(SP_NAME, Context.MODE_PRIVATE);
return sharedPreferences.getBoolean(key, defaultVal);
}
/**
* spName
*/
public static boolean getBoolen(Context context, String spName, String key, boolean defaultVal) {
sharedPreferences = context.getApplicationContext().getSharedPreferences(spName, Context.MODE_PRIVATE);
return sharedPreferences.getBoolean(key, defaultVal);
}
/**
* initspName
*/
public static int getInt(Context context, String key, int defaultVal) {
sharedPreferences = context.getApplicationContext().getSharedPreferences(SP_NAME, Context.MODE_PRIVATE);
return sharedPreferences.getInt(key, defaultVal);
}
/**
* spName
*/
public static int getInt(Context context, String spName, String key, int defaultVal) {
sharedPreferences = context.getApplicationContext().getSharedPreferences(spName, Context.MODE_PRIVATE);
return sharedPreferences.getInt(key, defaultVal);
}
/**
* initspName
*/
public static float getFloat(Context context, String key, float defaultVal) {
sharedPreferences = context.getApplicationContext().getSharedPreferences(SP_NAME, Context.MODE_PRIVATE);
return sharedPreferences.getFloat(key, defaultVal);
}
/**
* spName
*/
public static float getFloat(Context context, String spName, String key, float defaultVal) {
sharedPreferences = context.getApplicationContext().getSharedPreferences(spName, Context.MODE_PRIVATE);
return sharedPreferences.getFloat(key, defaultVal);
}
/**
* initspName
*/
public static long getLong(Context context, String key, long defaultVal) {
sharedPreferences = context.getApplicationContext().getSharedPreferences(SP_NAME, Context.MODE_PRIVATE);
return sharedPreferences.getLong(key, defaultVal);
}
/**
* spName
*/
public static long getLong(Context context, String spName, String key, long defaultVal) {
sharedPreferences = context.getApplicationContext().getSharedPreferences(spName, Context.MODE_PRIVATE);
return sharedPreferences.getLong(key, defaultVal);
}
/**
* initspName
*/
public static String getString(Context context, String key, String defaultVal) {
sharedPreferences = context.getApplicationContext().getSharedPreferences(SP_NAME, Context.MODE_PRIVATE);
return sharedPreferences.getString(key, defaultVal);
}
/**
* spName
*/
public static String getString(Context context, String spName, String key, String defaultVal) {
sharedPreferences = context.getApplicationContext().getSharedPreferences(spName, Context.MODE_PRIVATE);
return sharedPreferences.getString(key, defaultVal);
}
/**
* initspName
*/
public static Map<String, ?> getAll(Context context) {
sharedPreferences = context.getApplicationContext().getSharedPreferences(SP_NAME, Context.MODE_PRIVATE);
return sharedPreferences.getAll();
}
/**
* spName
*/
public static Map<String, ?> getAll(Context context, String spName) {
sharedPreferences = context.getApplicationContext().getSharedPreferences(spName, Context.MODE_PRIVATE);
return sharedPreferences.getAll();
}
/**
* initspName
*/
public static void remove(Context context, String key) {
sharedPreferences = context.getApplicationContext().getSharedPreferences(SP_NAME, Context.MODE_PRIVATE);
editor = sharedPreferences.edit();
editor.remove(key);
editor.apply();
}
/**
* spName
*/
public static void remove(Context context, String spName, String key) {
sharedPreferences = context.getApplicationContext().getSharedPreferences(spName, Context.MODE_PRIVATE);
editor = sharedPreferences.edit();
editor.remove(key);
editor.apply();
}
/**
* initspName
*/
public static void clearAll(Context context) {
sharedPreferences = context.getApplicationContext().getSharedPreferences(SP_NAME, Context.MODE_PRIVATE);
editor = sharedPreferences.edit();
editor.clear();
editor.apply();
}
/**
* spName
*/
public static void clearAll(Context context, String spName) {
sharedPreferences = context.getApplicationContext().getSharedPreferences(spName, Context.MODE_PRIVATE);
editor = sharedPreferences.edit();
editor.clear();
editor.apply();
}
/**
* keyinitspName
*/
public static boolean contains(Context context, String key) {
sharedPreferences = context.getApplicationContext().getSharedPreferences(SP_NAME, Context.MODE_PRIVATE);
return sharedPreferences.contains(key);
}
/**
* keyspName
*/
public static boolean contains(Context context, String spName, String key) {
sharedPreferences = context.getApplicationContext().getSharedPreferences(spName, Context.MODE_PRIVATE);
return sharedPreferences.contains(key);
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package nl.uva.cs.lobcder;
import java.io.*;
import java.math.BigInteger;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.crypto.NoSuchPaddingException;
import lombok.extern.java.Log;
import nl.uva.vlet.data.StringUtil;
import nl.uva.vlet.exception.ResourceNotFoundException;
import nl.uva.vlet.exception.VRLSyntaxException;
import nl.uva.vlet.exception.VlException;
import nl.uva.vlet.io.CircularStreamBufferTransferer;
import nl.uva.vlet.vfs.*;
import nl.uva.vlet.vfs.cloud.CloudFile;
import nl.uva.vlet.vrl.VRL;
import nl.uva.vlet.vrs.ServerInfo;
import nl.uva.vlet.vrs.VRSContext;
import nl.uva.vlet.vrs.io.VRandomReadable;
/**
* A test PDRI to implement the delete get/set data methods with the VRS API
*
* @author S. koulouzis
*/
@Log
public class VPDRI implements PDRI {
static {
try {
GridHelper.InitGlobalVFS();
} catch (Exception ex) {
Logger.getLogger(VPDRI.class.getName()).log(Level.SEVERE, null, ex);
}
}
private VFSClient vfsClient;
// private MyStorageSite storageSite;
private VRL vrl;
private final String username;
private final String password;
private final Long storageSiteId;
private final String baseDir = "LOBCDER-REPLICA-vTEST";//"LOBCDER-REPLICA-v2.0";
private final String fileName;
private int reconnectAttemts = 0;
private final static boolean debug = true;
private BigInteger keyInt;
private boolean encrypt;
private final String resourceUrl;
private boolean doChunked;
private int sleeTime = 5;
// private static final Map<String, GridProxy> proxyCache = new HashMap<>();
private boolean destroyCert;
private final int bufferSize;
private final boolean qosCopy;
private final double lim;
private int warnings;
private double progressThresshold;
public VPDRI(String fileName, Long storageSiteId, String resourceUrl,
String username, String password, boolean encrypt, BigInteger keyInt,
boolean doChunkUpload) throws IOException {
try {
this.fileName = fileName;
if (this.fileName == null) {
throw new NullPointerException("fileName is null");
}
this.resourceUrl = resourceUrl;
if (this.resourceUrl == null) {
throw new NullPointerException("resourceUrl is null");
}
String encoded = VRL.encode(fileName);
if (encoded == null) {
throw new NullPointerException("encoded is null");
}
vrl = new VRL(resourceUrl).appendPath(baseDir).append(encoded);
if (this.vrl == null) {
throw new NullPointerException("vrl is null");
}
this.storageSiteId = storageSiteId;
if (this.storageSiteId == null) {
throw new NullPointerException("storageSiteId is null");
}
this.username = username;
if (this.username == null) {
throw new NullPointerException("username is null");
}
this.password = password;
if (this.password == null) {
throw new NullPointerException("password is null");
}
this.encrypt = encrypt;
this.keyInt = keyInt;
this.doChunked = doChunkUpload;
Logger.getLogger(VPDRI.class.getName()).log(Level.FINE, "fileName: {0}, storageSiteId: {1}, username: {2}, password: {3}, VRL: {4}", new Object[]{fileName, storageSiteId, username, password, vrl});
if (vrl.getScheme().equals("file")) {
}
initVFS();
bufferSize = Util.getBufferSize();
qosCopy = Util.doQosCopy();
lim = Util.getRateOfChangeLim();
warnings = Util.getNumOfWarnings();
progressThresshold = Util.getProgressThresshold();
} catch (Exception ex) {
throw new IOException(ex);
}
}
private void initVFS() {
try {
this.vfsClient = new VFSClient();
VRSContext context = this.getVfsClient().getVRSContext();
//Bug in sftp: We have to put the username in the url
ServerInfo info = context.getServerInfoFor(vrl, true);
String authScheme = info.getAuthScheme();
if (StringUtil.equals(authScheme, ServerInfo.GSI_AUTH)) {
GridHelper.initGridProxy(username, password, context, destroyCert);
// copyVomsAndCerts();
// GridProxy gridProxy = context.getGridProxy();
// if (destroyCert) {
// gridProxy.destroy();
// gridProxy = null;
// if (gridProxy == null || gridProxy.isValid() == false) {
// context.setProperty("grid.proxy.location", Constants.PROXY_FILE);
// // Default to $HOME/.globus
// context.setProperty("grid.certificate.location", Global.getUserHome() + "/.globus");
// String vo = username;
// context.setProperty("grid.proxy.voName", vo);
// context.setProperty("grid.proxy.lifetime", "200");
// gridProxy = context.getGridProxy();
// if (gridProxy.isValid() == false) {
// gridProxy.setEnableVOMS(true);
// gridProxy.setDefaultVOName(vo);
// gridProxy.createWithPassword(password);
// if (gridProxy.isValid() == false) {
// throw new VlException("Created Proxy is not Valid!");
// gridProxy.saveProxyTo(Constants.PROXY_FILE);
//// proxyCache.put(password, gridProxy);
}
if (StringUtil.equals(authScheme, ServerInfo.PASSWORD_AUTH)
|| StringUtil.equals(authScheme, ServerInfo.PASSWORD_OR_PASSPHRASE_AUTH)
|| StringUtil.equals(authScheme, ServerInfo.PASSPHRASE_AUTH)) {
// String username = storageSite.getCredential().getStorageSiteUsername();
if (username == null) {
throw new NullPointerException("Username is null!");
}
info.setUsername(username);
// String password = storageSite.getCredential().getStorageSitePassword();
if (password == null) {
throw new NullPointerException("password is null!");
}
info.setPassword(password);
}
info.setAttribute(ServerInfo.ATTR_DEFAULT_YES_NO_ANSWER, true);
// if(getVrl().getScheme().equals(VRS.SFTP_SCHEME)){
//patch for bug with ssh driver
info.setAttribute("sshKnownHostsFile", System.getProperty("user.home") + "/.ssh/known_hosts");
context.setProperty("chunk.upload", doChunked);
// info.setAttribute(new VAttribute("chunk.upload", true));
info.store();
} catch (IOException ex) {
Logger.getLogger(VPDRI.class.getName()).log(Level.SEVERE, null, ex);
} catch (VlException ex) {
Logger.getLogger(VPDRI.class.getName()).log(Level.SEVERE, null, ex);
} catch (Exception ex) {
Logger.getLogger(VPDRI.class.getName()).log(Level.SEVERE, null, ex);
}
}
@Override
public void delete() throws IOException {
try {
getVfsClient().openLocation(vrl).delete();
} catch (VlException ex) {
//Maybe it's from assimilation. We must remove the baseDir
if (ex instanceof ResourceNotFoundException || ex.getMessage().contains("Couldn open location. Get NULL object for location")) {
try {
// VRL assimilationVRL = new VRL(resourceUrl).append(URLEncoder.encode(fileName, "UTF-8").replace("+", "%20"));
// String encoded = VRL.encode(fileName);
VRL assimilationVRL = new VRL(resourceUrl).append(fileName);
getVfsClient().openLocation(assimilationVRL).delete();
} catch (IOException | VlException ex1) {
Logger.getLogger(VPDRI.class.getName()).log(Level.SEVERE, null, ex1);
}
} else {
Logger.getLogger(VPDRI.class.getName()).log(Level.SEVERE, null, ex);
}
} finally {
}
// //it's void so do it asynchronously
// Runnable asyncDel = getAsyncDelete(this.vfsClient, vrl);
// asyncDel.run();
}
@Override
public InputStream getData() throws IOException {
InputStream in = null;
VFile file;
int read;
try {
file = (VFile) getVfsClient().openLocation(vrl);
in = file.getInputStream();
} catch (Exception ex) {
if (ex instanceof ResourceNotFoundException
|| ex.getMessage().contains("Couldn open location. Get NULL object for location:")
|| ex.getMessage().contains("Resource not found.:Couldn't locate path")) {
try {
// VRL assimilationVRL = new VRL(resourceUrl).append(URLEncoder.encode(fileName, "UTF-8"));
VRL assimilationVRL = new VRL(resourceUrl).append(fileName);
in = ((VFile) getVfsClient().openLocation(assimilationVRL)).getInputStream();
sleeTime = 5;
} catch (VRLSyntaxException ex1) {
throw new IOException(ex1);
} catch (VlException ex1) {
if (ex instanceof ResourceNotFoundException) { //|| ex.getMessage().contains("Couldn open location. Get NULL object for location:")) {
throw new IOException(ex1);
}
if (reconnectAttemts < Constants.RECONNECT_NTRY) {
try {
sleeTime = sleeTime + 5;
Thread.sleep(sleeTime);
reconnect();
return getData();
} catch (InterruptedException ex2) {
throw new IOException(ex1);
}
} else {
throw new IOException(ex1);
}
}
} else if (reconnectAttemts < Constants.RECONNECT_NTRY) {
if (ex instanceof org.globus.common.ChainedIOException) {
destroyCert = true;
}
try {
reconnect();
sleeTime = sleeTime + 5;
Thread.sleep(sleeTime);
return getData();
} catch (InterruptedException ex1) {
throw new IOException(ex);
}
} else {
throw new IOException(ex);
}
} finally {
// reconnect();
}
return in;
}
@Override
public void putData(InputStream in) throws IOException {
OutputStream out = null;
Logger.getLogger(VPDRI.class.getName()).log(Level.FINE, "putData:");
// VFile tmpFile = null;
try {
// upload(in);
VRL parentVrl = vrl.getParent();
VDir remoteDir = getVfsClient().mkdirs(parentVrl, true);
getVfsClient().createFile(vrl, true);
out = getVfsClient().getFile(vrl).getOutputStream();
if (!getEncrypted()) {
CircularStreamBufferTransferer cBuff = new CircularStreamBufferTransferer((bufferSize), in, out);
cBuff.startTransfer(new Long(-1));
// int read;
// byte[] copyBuffer = new byte[Constants.BUF_SIZE];
// while ((read = in.read(copyBuffer, 0, copyBuffer.length)) != -1) {
// out.write(copyBuffer, 0, read);
} else {
DesEncrypter encrypter = new DesEncrypter(getKeyInt());
encrypter.encrypt(in, out);
}
reconnectAttemts = 0;
} catch (nl.uva.vlet.exception.VlAuthenticationException | NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | InvalidAlgorithmParameterException ex) {
throw new IOException(ex);
} catch (VlException ex) {
if (ex.getMessage() != null) {
Logger.getLogger(VPDRI.class.getName()).log(Level.FINE, "\tVlException {0}", ex.getMessage());
}
if (reconnectAttemts <= 2) {
Logger.getLogger(VPDRI.class.getName()).log(Level.FINE, "\treconnectAttemts {0}", reconnectAttemts);
reconnect();
putData(in);
} else {
throw new IOException(ex);
}
// if (ex instanceof ResourceNotFoundException || ex.getMessage().contains("not found") || ex.getMessage().contains("Couldn open location") || ex.getMessage().contains("not found in container")) {
// try {
// vfsClient.mkdirs(vrl.getParent(), true);
// vfsClient.createFile(vrl, true);
// putData(in);
// } catch (VlException ex1) {
// throw new IOException(ex1);
} finally {
if (out != null) {
try {
out.flush();
out.close();
} catch (java.io.IOException ex) {
}
}
if (in != null) {
in.close();
}
}
}
@Override
public Long getStorageSiteId() {
return this.storageSiteId;//storageSite.getStorageSiteId();
}
@Override
public String getFileName() {
return this.fileName;
}
@Override
public String getHost() throws UnknownHostException {
if (vrl.getScheme().equals("file")
|| StringUtil.isEmpty(vrl.getHostname())
|| vrl.getHostname().equals("localhost")
|| vrl.getHostname().equals("127.0.0.1")) {
return getIP("localhost");
} else {
return vrl.getHostname();
}
}
private String getIP(String hostName) {
try {
return InetAddress.getByName(hostName).getHostAddress();
} catch (UnknownHostException ex) {
return hostName;
}
}
@Override
public long getLength() throws IOException {
try {
return getVfsClient().getFile(vrl).getLength();
} catch (Exception ex) {
if (reconnectAttemts < Constants.RECONNECT_NTRY) {
reconnect();
getLength();
} else {
throw new IOException(ex);
}
} finally {
}
return 0;
}
@Override
public void reconnect() throws IOException {
reconnectAttemts++;
getVfsClient().close();
getVfsClient().dispose();
// VRS.exit();
try {
initVFS();
} catch (Exception ex1) {
throw new IOException(ex1);
}
}
@Override
public Long getChecksum() throws IOException {
try {
VFile physicalFile = getVfsClient().getFile(vrl);
if (physicalFile instanceof VChecksum) {
BigInteger bi = new BigInteger(((VChecksum) physicalFile).getChecksum("MD5"), 16);
return bi.longValue();
}
} catch (VlException ex) {
throw new IOException(ex);
} finally {
}
return null;
}
// private void debug(String msg) {
// if (debug) {
//// System.err.println(this.getClass().getName() + ": " + msg);
// log.debug(msg);
private void upload(PDRI source) throws VlException, IOException {
if (getVfsClient() == null) {
reconnect();
}
CloudFile thisFile = (CloudFile) getVfsClient().createFile(vrl, true);
VFile sourceFile = getVfsClient().openFile(new VRL(source.getURI()));
thisFile.uploadFrom(sourceFile);
}
@Override
public void replicate(PDRI source) throws IOException {
try {
VRL sourceVRL = new VRL(source.getURI());
String sourceScheme = sourceVRL.getScheme();
String desteScheme = vrl.getScheme();
Logger.getLogger(VPDRI.class.getName()).log(Level.INFO, "Start replicating {0} to {1}", new Object[]{source.getURI(), getURI()});
double start = System.currentTimeMillis();
if (!vfsClient.existsDir(vrl.getParent())) {
VDir remoteDir = vfsClient.mkdirs(vrl.getParent(), true);
}
if (desteScheme.equals("swift") && sourceScheme.equals("file")) {
upload(source);
} else {
VFile destFile = getVfsClient().createFile(vrl, true);
VFile sourceFile = getVfsClient().openFile(sourceVRL);
getVfsClient().copy(sourceFile, destFile);
}
// putData(source.getData());
double elapsed = System.currentTimeMillis() - start;
double speed = ((source.getLength() * 8.0) * 1000.0) / (elapsed * 1000.0);
String msg = "Source: " + source.getHost() + " Destination: " + vrl.getScheme() + "://" + getHost() + " Replication_Speed: " + speed + " Kbites/sec Repl_Size: " + (getLength()) + " bytes";
Logger.getLogger(VPDRI.class.getName()).log(Level.INFO, msg);
// getAsyncDelete(getVfsClient(), vrl).run();
} catch (VlException ex) {
Logger.getLogger(VPDRI.class.getName()).log(Level.SEVERE, null, ex);
}
}
// @Override
// public void setKeyInt(BigInteger keyInt) {
// this.keyInt = keyInt;
@Override
public BigInteger getKeyInt() {
return this.keyInt;
}
@Override
public boolean getEncrypted() {
return this.encrypt;
}
@Override
public String getURI() throws IOException {
try {
return this.vrl.toURIString();
} catch (VRLSyntaxException ex) {
throw new IOException(ex);
}
}
/**
* @return the vfsClient
*/
private VFSClient getVfsClient() throws IOException {
if (vfsClient == null) {
reconnect();
}
return vfsClient;
}
@Override
public void copyRange(OutputStream output, long start, long length) throws IOException {
try {
VFile file = (VFile) getVfsClient().openLocation(vrl);
if (file instanceof VRandomReadable) {
VRandomReadable ra = (VRandomReadable) file;
// Write partial range.
byte[] buffer = new byte[bufferSize];
int read;
long toRead = length;
long total = 0;
double speed;
double rateOfChange = 0;
double speedPrev = 0;
long startTime = System.currentTimeMillis();
int count = 0;
progressThresshold = 100.0 * Math.exp(-0.0022 * (length * 1024.0 * 1024.0));
while ((read = ra.readBytes(start, buffer, 0, buffer.length)) > 0) {
if ((toRead -= read) > 0) {
output.write(buffer, 0, read);
start += read;
} else {
output.write(buffer, 0, (int) toRead + read);
start += read;
break;
}
total += read;
double progress = (100.0 * total) / length;
if (progress % 5 == 0 && progress >= progressThresshold && progress <= 80) {
long elapsed = System.currentTimeMillis() - startTime;
speed = (total / elapsed);
rateOfChange = (speed - speedPrev);
speedPrev = speed;
Logger.getLogger(WorkerServlet.class.getName()).log(Level.INFO, "progressThresshold: {0} speed: {1} rateOfChange: {2}", new Object[]{progressThresshold, speed, rateOfChange});
if (rateOfChange < lim) {
count++;
Logger.getLogger(WorkerServlet.class.getName()).log(Level.WARNING, "We will not tolarate this !!!! Next time line is off");
if (count >= warnings) {
Logger.getLogger(WorkerServlet.class.getName()).log(Level.WARNING, "We will not tolarate this !!!! Find a new worker. rateOfChange: " + rateOfChange);
break;
}
}
}
}
} else {
throw new IOException("Backend at " + vrl.getScheme() + "://" + vrl.getHostname() + "does not support random reads");
}
} catch (VlException ex) {
Logger.getLogger(VPDRI.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
|
package devfest.controller;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
public class BaseActivity extends AppCompatActivity implements FirebaseAuth.AuthStateListener {
public FirebaseUser user;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
}
public void goToLoginScreen(){
Intent intent = new Intent(this, LoginActivity.class);
startActivity(intent);
Log.e("WHF?", "goToLoginScreen");
}
@Override
protected void onResume() {
super.onResume();
}
}
|
package raptor.pref;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.eclipse.jface.preference.PreferenceConverter;
import org.eclipse.jface.preference.PreferenceStore;
import org.eclipse.jface.resource.StringConverter;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.FontData;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Display;
import raptor.Quadrant;
import raptor.Raptor;
import raptor.chat.ChatEvent;
import raptor.chat.ChatType;
import raptor.swt.BugPartnersWindowItem;
import raptor.swt.SWTUtils;
import raptor.swt.SeekTableWindowItem;
import raptor.swt.chess.controller.InactiveMouseAction;
import raptor.swt.chess.controller.ObservingMouseAction;
import raptor.swt.chess.controller.PlayingMouseAction;
import raptor.util.RaptorStringUtils;
/**
* The RaptorPreferenceStore. Automatically loads and saves itself at
* Raptor.USER_RAPTOR_DIR/raptor.properties . Had additional data type support.
*/
public class RaptorPreferenceStore extends PreferenceStore implements
PreferenceKeys {
private static final Log LOG = LogFactory
.getLog(RaptorPreferenceStore.class);
public static final String PREFERENCE_PROPERTIES_FILE = "raptor.properties";
public static final File RAPTOR_PROPERTIES = new File(
Raptor.USER_RAPTOR_DIR, "raptor.properties");
protected String defaultMonospacedFontName;
protected String defaultFontName;
protected int defaultLargeFontSize;
protected int defaultSmallFontSize;
protected int defaultMediumFontSize;
protected int defaultTinyFontSize;
private IPropertyChangeListener propertyChangeListener = new IPropertyChangeListener() {
public void propertyChange(PropertyChangeEvent arg0) {
if (arg0.getProperty().endsWith("color")) {
Raptor.getInstance().getColorRegistry()
.put(
arg0.getProperty(),
PreferenceConverter.getColor(
RaptorPreferenceStore.this, arg0
.getProperty()));
} else if (arg0.getProperty().endsWith("font")) {
Raptor.getInstance().getFontRegistry()
.put(
arg0.getProperty(),
PreferenceConverter.getFontDataArray(
RaptorPreferenceStore.this, arg0
.getProperty()));
}
}
};
public RaptorPreferenceStore() {
super();
FileInputStream fileIn = null;
FileOutputStream fileOut = null;
try {
LOG.info("Loading RaptorPreferenceStore store "
+ PREFERENCE_PROPERTIES_FILE);
loadDefaults();
if (RAPTOR_PROPERTIES.exists()) {
load(fileIn = new FileInputStream(RAPTOR_PROPERTIES));
} else {
RAPTOR_PROPERTIES.getParentFile().mkdir();
RAPTOR_PROPERTIES.createNewFile();
save(fileOut = new FileOutputStream(RAPTOR_PROPERTIES),
"Last saved on " + new Date());
}
setFilename(RAPTOR_PROPERTIES.getAbsolutePath());
} catch (Exception e) {
LOG.error("Error reading or writing to file ", e);
throw new RuntimeException(e);
} finally {
if (fileIn != null) {
try {
fileIn.close();
} catch (Throwable t) {
}
}
if (fileOut != null) {
try {
fileOut.flush();
fileOut.close();
} catch (Throwable t) {
}
}
}
addPropertyChangeListener(propertyChangeListener);
LOG.info("Loaded preferences from "
+ RAPTOR_PROPERTIES.getAbsolutePath());
}
/**
* Returns the foreground color to use for the specified chat event. Returns
* null if no special color should be used.
*/
public Color getColor(ChatEvent event) {
Color result = null;
String key = null;
if (event.getType() == ChatType.CHANNEL_TELL) {
key = CHAT_CHAT_EVENT_TYPE_COLOR_APPEND_TO + event.getType() + "-"
+ event.getChannel() + "-color";
} else {
key = CHAT_CHAT_EVENT_TYPE_COLOR_APPEND_TO + event.getType()
+ "-color";
}
try {
if (!Raptor.getInstance().getColorRegistry().hasValueFor(key)) {
// We don't want the default color if not found we want to
// return null, so use
// StringConverter instead of PreferenceConverter.
String value = getString(key);
if (StringUtils.isNotBlank(value)) {
RGB rgb = StringConverter.asRGB(value, null);
if (rgb != null) {
Raptor.getInstance().getColorRegistry().put(key, rgb);
} else {
return null;
}
} else {
return null;
}
}
result = Raptor.getInstance().getColorRegistry().get(key);
} catch (Throwable t) {
result = null;
}
return result;
}
/**
* Returns the color for the specified key. Returns BLACK if the key was not
* found.
*/
public Color getColor(String key) {
try {
if (!Raptor.getInstance().getColorRegistry().hasValueFor(key)) {
RGB rgb = PreferenceConverter.getColor(this, key);
if (rgb != null) {
Raptor.getInstance().getColorRegistry().put(key, rgb);
}
}
return Raptor.getInstance().getColorRegistry().get(key);
} catch (Throwable t) {
LOG.error("Error in getColor(" + key + ") Returning black.", t);
return new Color(Display.getCurrent(), new RGB(0, 0, 0));
}
}
public Rectangle getCurrentLayoutRectangle(String key) {
key = "app-" + getString(APP_LAYOUT) + "-" + key;
return getRectangle(key);
}
public int[] getCurrentLayoutSashWeights(String key) {
key = "app-" + getString(APP_LAYOUT) + "-" + key;
return getIntArray(key);
}
public RGB getDefaultColor(String key) {
return PreferenceConverter.getDefaultColor(this, key);
}
public int[] getDefaultIntArray(String key) {
return RaptorStringUtils.intArrayFromString(getDefaultString(key));
}
public String[] getDefaultStringArray(String key) {
return RaptorStringUtils.stringArrayFromString(getDefaultString(key));
}
public String getDefauultMonospacedFont() {
FontData[] fonts = Raptor.getInstance().getDisplay().getFontList(null,
true);
String[] preferredFontNames = null;
String osName = System.getProperty("os.name");
if (osName.startsWith("Mac OS")) {
preferredFontNames = SWTUtils.OSX_MONOSPACED_FONTS;
} else if (osName.startsWith("Windows")) {
preferredFontNames = SWTUtils.WINDOWS_MONOSPACED_FONTS;
} else {
preferredFontNames = SWTUtils.OTHER_MONOSPACED_FONTS;
}
String result = null;
outer: for (int i = 0; i < preferredFontNames.length; i++) {
for (FontData fontData : fonts) {
if (fontData.getName().equalsIgnoreCase(preferredFontNames[i])) {
result = preferredFontNames[i];
break outer;
}
}
}
if (result == null) {
result = "Courier";
}
return result;
}
/**
* Returns the font for the specified key. Returns the default font if key
* was not found.
*/
public Font getFont(String key) {
try {
if (!Raptor.getInstance().getFontRegistry().hasValueFor(key)) {
FontData[] fontData = PreferenceConverter.getFontDataArray(
this, key);
Raptor.getInstance().getFontRegistry().put(key, fontData);
}
return Raptor.getInstance().getFontRegistry().get(key);
} catch (Throwable t) {
LOG.error("Error in getFont(" + key + ") Returning default font.",
t);
return Raptor.getInstance().getFontRegistry().defaultFont();
}
}
public int[] getIntArray(String key) {
return RaptorStringUtils.intArrayFromString(getString(key));
}
public Point getPoint(String key) {
return PreferenceConverter.getPoint(this, key);
}
public Quadrant getQuadrant(String key) {
return Quadrant.valueOf(getString(key));
}
public Rectangle getRectangle(String key) {
return PreferenceConverter.getRectangle(this, key);
}
public String[] getStringArray(String key) {
return RaptorStringUtils.stringArrayFromString(getString(key));
}
public void loadDefaults() {
defaultFontName = Raptor.getInstance().getFontRegistry().defaultFont()
.getFontData()[0].getName();
defaultMonospacedFontName = getDefauultMonospacedFont();
setDefaultMonitorBasedSizes();
// Action
setDefault(ACTION_SEPARATOR_SEQUENCE, 400);
// Board
setDefault(BOARD_ALLOW_MOUSE_WHEEL_NAVIGATION_WHEEL_PLAYING, false);
setDefault(BOARD_SHOW_PLAYING_GAME_STATS_ON_GAME_END, true);
setDefault(BOARD_PLAY_CHALLENGE_SOUND, true);
setDefault(BOARD_PLAY_ABORT_REQUEST_SOUND, true);
setDefault(BOARD_PLAY_DRAW_OFFER_SOUND, true);
setDefault(BOARD_USER_MOVE_INPUT_MODE, "DragAndDrop");
setDefault(BOARD_SHOW_BUGHOUSE_SIDE_UP_TIME, true);
setDefault(BOARD_PIECE_JAIL_LABEL_PERCENTAGE, 40);
setDefault(BOARD_COOLBAR_MODE, true);
setDefault(BOARD_COOLBAR_ON_TOP, true);
setDefault(BOARD_CHESS_SET_NAME, "Wiki");
setDefault(BOARD_SQUARE_BACKGROUND_NAME, "GreenMarble");
setDefault(BOARD_IS_SHOW_COORDINATES, true);
setDefault(BOARD_PIECE_SIZE_ADJUSTMENT, .06);
setDefault(BOARD_IS_SHOWING_PIECE_JAIL, false);
setDefault(BOARD_CLOCK_SHOW_MILLIS_WHEN_LESS_THAN, Integer.MIN_VALUE);
setDefault(BOARD_CLOCK_SHOW_SECONDS_WHEN_LESS_THAN,
1000L * 60L * 60L + 1L);
setDefault(BOARD_IS_PLAYING_10_SECOND_COUNTDOWN_SOUNDS, true);
setDefault(BOARD_PREMOVE_ENABLED, true);
setDefault(BOARD_PLAY_MOVE_SOUND_WHEN_OBSERVING, true);
setDefault(BOARD_IS_SHOWING_PIECE_UNICODE_CHARS, true);
setDefault(BOARD_QUEUED_PREMOVE_ENABLED, false);
setDefault(BOARD_IS_USING_CROSSHAIRS_CURSOR, false);
setDefault(BOARD_LAYOUT, "raptor.swt.chess.layout.RightOrientedLayout");
setDefault(BOARD_TAKEOVER_INACTIVE_GAMES, true);
setDefault(BOARD_PIECE_JAIL_SHADOW_ALPHA, 30);
setDefault(BOARD_PIECE_SHADOW_ALPHA, 60);
setDefault(BOARD_COORDINATES_SIZE_PERCENTAGE, 26);
setDefault(BOARD_ANNOUNCE_CHECK_WHEN_OPPONENT_CHECKS_ME, false);
setDefault(BOARD_ANNOUNCE_CHECK_WHEN_I_CHECK_OPPONENT, false);
setDefault(BOARD_SPEAK_MOVES_OPP_MAKES, false);
setDefault(BOARD_SPEAK_MOVES_I_MAKE, false);
setDefault(BOARD_SPEAK_WHEN_OBSERVING, false);
setDefault(BOARD_SPEAK_RESULTS, false);
setDefault(BOARD_IGNORE_OBSERVED_GAMES_IF_PLAYING, false);
setDefault(PLAYING_CONTROLLER + LEFT_MOUSE_BUTTON_ACTION,
PlayingMouseAction.None.toString());
setDefault(PLAYING_CONTROLLER + RIGHT_MOUSE_BUTTON_ACTION,
PlayingMouseAction.PopupMenu.toString());
setDefault(PLAYING_CONTROLLER + MIDDLE_MOUSE_BUTTON_ACTION,
PlayingMouseAction.SmartMove.toString());
setDefault(PLAYING_CONTROLLER + MISC1_MOUSE_BUTTON_ACTION,
PlayingMouseAction.None.toString());
setDefault(PLAYING_CONTROLLER + MISC2_MOUSE_BUTTON_ACTION,
PlayingMouseAction.None.toString());
setDefault(PLAYING_CONTROLLER + LEFT_DOUBLE_CLICK_MOUSE_BUTTON_ACTION,
PlayingMouseAction.None.toString());
setDefault(OBSERVING_CONTROLLER + LEFT_MOUSE_BUTTON_ACTION,
ObservingMouseAction.MakePrimaryGame.toString());
setDefault(OBSERVING_CONTROLLER + RIGHT_MOUSE_BUTTON_ACTION,
ObservingMouseAction.AddGameChatTab.toString());
setDefault(OBSERVING_CONTROLLER + MIDDLE_MOUSE_BUTTON_ACTION,
ObservingMouseAction.MatchWinner.toString());
setDefault(OBSERVING_CONTROLLER + MISC1_MOUSE_BUTTON_ACTION,
ObservingMouseAction.None.toString());
setDefault(OBSERVING_CONTROLLER + MISC2_MOUSE_BUTTON_ACTION,
ObservingMouseAction.None.toString());
setDefault(
OBSERVING_CONTROLLER + LEFT_DOUBLE_CLICK_MOUSE_BUTTON_ACTION,
ObservingMouseAction.None.toString());
setDefault(INACTIVE_CONTROLLER + LEFT_MOUSE_BUTTON_ACTION,
InactiveMouseAction.None.toString());
setDefault(INACTIVE_CONTROLLER + RIGHT_MOUSE_BUTTON_ACTION,
InactiveMouseAction.None.toString());
setDefault(INACTIVE_CONTROLLER + MIDDLE_MOUSE_BUTTON_ACTION,
InactiveMouseAction.Rematch.toString());
setDefault(INACTIVE_CONTROLLER + MISC1_MOUSE_BUTTON_ACTION,
InactiveMouseAction.None.toString());
setDefault(INACTIVE_CONTROLLER + MISC2_MOUSE_BUTTON_ACTION,
InactiveMouseAction.None.toString());
setDefault(INACTIVE_CONTROLLER + LEFT_DOUBLE_CLICK_MOUSE_BUTTON_ACTION,
InactiveMouseAction.None.toString());
PreferenceConverter.setDefault(this, BOARD_BACKGROUND_COLOR, new RGB(0,
0, 0));
PreferenceConverter.setDefault(this, BOARD_COORDINATES_COLOR, new RGB(
0, 0, 0));
PreferenceConverter.setDefault(this, BOARD_ACTIVE_CLOCK_COLOR, new RGB(
0, 255, 0));
PreferenceConverter.setDefault(this, BOARD_INACTIVE_CLOCK_COLOR,
new RGB(128, 128, 128));
PreferenceConverter.setDefault(this, BOARD_CONTROL_COLOR, new RGB(128,
128, 128));
PreferenceConverter.setDefault(this, BOARD_LAG_OVER_20_SEC_COLOR,
new RGB(255, 0, 0));
PreferenceConverter.setDefault(this, BOARD_PIECE_JAIL_LABEL_COLOR,
new RGB(0, 255, 0));
PreferenceConverter.setDefault(this, BOARD_PIECE_JAIL_BACKGROUND_COLOR,
new RGB(0, 0, 0));
PreferenceConverter.setDefault(this, BOARD_COORDINATES_FONT,
new FontData[] { new FontData(defaultFontName,
defaultMediumFontSize, 0) });
PreferenceConverter.setDefault(this, BOARD_CLOCK_FONT,
new FontData[] { new FontData(defaultMonospacedFontName, 24,
SWT.BOLD) });
PreferenceConverter.setDefault(this, BOARD_LAG_FONT,
new FontData[] { new FontData(defaultFontName,
defaultTinyFontSize, 0) });
PreferenceConverter.setDefault(this, BOARD_PLAYER_NAME_FONT,
new FontData[] { new FontData(defaultFontName,
defaultLargeFontSize, 0) });
PreferenceConverter.setDefault(this, BOARD_PIECE_JAIL_FONT,
new FontData[] { new FontData(defaultFontName,
defaultMediumFontSize, 0) });
PreferenceConverter.setDefault(this, BOARD_OPENING_DESC_FONT,
new FontData[] { new FontData(defaultFontName,
defaultTinyFontSize, 0) });
PreferenceConverter.setDefault(this, BOARD_STATUS_FONT,
new FontData[] { new FontData(defaultFontName,
defaultTinyFontSize, 0) });
PreferenceConverter.setDefault(this, BOARD_GAME_DESCRIPTION_FONT,
new FontData[] { new FontData(defaultFontName,
defaultTinyFontSize, 0) });
PreferenceConverter.setDefault(this, BOARD_PREMOVES_FONT,
new FontData[] { new FontData(defaultFontName,
defaultTinyFontSize, 0) });
// BugArena
setDefault(BUG_ARENA_PARTNERS_INDEX, 0);
setDefault(BUG_ARENA_MAX_PARTNERS_INDEX, BugPartnersWindowItem
.getRatings().length - 1);
setDefault(BUG_ARENA_TEAMS_INDEX, 0);
setDefault(BUG_ARENA_TEAMS_IS_RATED, true);
// SeekTable
setDefault(SEEK_TABLE_RATINGS_INDEX, 0);
setDefault(SEEK_TABLE_MAX_RATINGS_INDEX, SeekTableWindowItem
.getRatings().length - 1);
setDefault(SEEK_TABLE_RATED_INDEX, 0);
setDefault(SEEK_TABLE_SHOW_COMPUTERS, true);
setDefault(SEEK_TABLE_SHOW_LIGHTNING, true);
setDefault(SEEK_TABLE_SHOW_BLITZ, true);
setDefault(SEEK_TABLE_SHOW_STANDARD, true);
setDefault(SEEK_TABLE_SHOW_CRAZYHOUSE, true);
setDefault(SEEK_TABLE_SHOW_FR, true);
setDefault(SEEK_TABLE_SHOW_WILD, true);
setDefault(SEEK_TABLE_SHOW_ATOMIC, true);
setDefault(SEEK_TABLE_SHOW_SUICIDE, true);
setDefault(SEEK_TABLE_SHOW_LOSERS, true);
setDefault(SEEK_TABLE_SHOW_UNTIMED, true);
// Arrows
PreferenceConverter.setDefault(this, ARROW_OBS_OPP_COLOR, new RGB(255,
0, 255));
PreferenceConverter
.setDefault(this, ARROW_MY_COLOR, new RGB(0, 0, 255));
PreferenceConverter.setDefault(this, ARROW_PREMOVE_COLOR, new RGB(0, 0,
255));
PreferenceConverter.setDefault(this, ARROW_OBS_COLOR,
new RGB(0, 0, 255));
setDefault(ARROW_SHOW_ON_OBS_AND_OPP_MOVES, true);
setDefault(ARROW_SHOW_ON_MOVE_LIST_MOVES, true);
setDefault(ARROW_SHOW_ON_MY_PREMOVES, true);
setDefault(ARROW_SHOW_ON_MY_MOVES, false);
setDefault(ARROW_ANIMATION_DELAY, 300L);
setDefault(ARROW_FADE_AWAY_MODE, true);
setDefault(ARROW_WIDTH_PERCENTAGE, 15);
// Highlights
PreferenceConverter.setDefault(this, HIGHLIGHT_OBS_OPP_COLOR, new RGB(
255, 0, 255));
PreferenceConverter.setDefault(this, HIGHLIGHT_MY_COLOR, new RGB(0, 0,
255));
PreferenceConverter.setDefault(this, HIGHLIGHT_PREMOVE_COLOR, new RGB(
0, 0, 255));
PreferenceConverter.setDefault(this, HIGHLIGHT_OBS_COLOR, new RGB(0, 0,
255));
setDefault(HIGHLIGHT_SHOW_ON_OBS_AND_OPP_MOVES, true);
setDefault(HIGHLIGHT_SHOW_ON_MOVE_LIST_MOVES, true);
setDefault(HIGHLIGHT_SHOW_ON_MY_PREMOVES, true);
setDefault(HIGHLIGHT_SHOW_ON_MY_MOVES, false);
setDefault(HIGHLIGHT_FADE_AWAY_MODE, false);
setDefault(HIGHLIGHT_ANIMATION_DELAY, 300L);
setDefault(HIGHLIGHT_WIDTH_PERCENTAGE, 3);
// Game Results
PreferenceConverter.setDefault(this, RESULTS_COLOR, new RGB(255, 0, 0));
PreferenceConverter.setDefault(this, RESULTS_FONT,
new FontData[] { new FontData(defaultMonospacedFontName, 40,
SWT.BOLD) });
setDefault(RESULTS_IS_SHOWING, true);
setDefault(RESULTS_FADE_AWAY_MODE, true);
setDefault(RESULTS_ANIMATION_DELAY, 500L);
setDefault(RESULTS_WIDTH_PERCENTAGE, 80);
// Chat
setDefault(CHAT_MAX_CONSOLE_CHARS, 500000);
setDefault(CHAT_TIMESTAMP_CONSOLE, false);
setDefault(CHAT_TIMESTAMP_CONSOLE_FORMAT, "'['hh:mma']'");
setDefault(CHAT_UNDERLINE_SINGLE_QUOTES, false);
setDefault(CHAT_IS_PLAYING_CHAT_ON_PTELL, true);
setDefault(CHAT_IS_PLAYING_CHAT_ON_PERSON_TELL, true);
setDefault(CHAT_IS_SMART_SCROLL_ENABLED, true);
setDefault(CHAT_OPEN_CHANNEL_TAB_ON_CHANNEL_TELLS, false);
setDefault(CHAT_OPEN_PERSON_TAB_ON_PERSON_TELLS, false);
setDefault(CHAT_OPEN_PARTNER_TAB_ON_PTELLS, false);
setDefault(CHAT_REMOVE_SUB_TAB_MESSAGES_FROM_MAIN_TAB, true);
PreferenceConverter.setDefault(this, CHAT_INPUT_FONT,
new FontData[] { new FontData(defaultMonospacedFontName,
defaultLargeFontSize, 0) });
PreferenceConverter.setDefault(this, CHAT_OUTPUT_FONT,
new FontData[] { new FontData(defaultMonospacedFontName,
defaultLargeFontSize, 0) });
PreferenceConverter.setDefault(this, CHAT_PROMPT_FONT,
new FontData[] { new FontData(defaultMonospacedFontName,
defaultLargeFontSize, 0) });
PreferenceConverter.setDefault(this, CHAT_INPUT_BACKGROUND_COLOR,
new RGB(0, 0, 0));
PreferenceConverter.setDefault(this, CHAT_CONSOLE_BACKGROUND_COLOR,
new RGB(0, 0, 0));
PreferenceConverter.setDefault(this, CHAT_INPUT_DEFAULT_TEXT_COLOR,
new RGB(128, 128, 128));
PreferenceConverter.setDefault(this, CHAT_OUTPUT_BACKGROUND_COLOR,
new RGB(255, 255, 255));
PreferenceConverter.setDefault(this, CHAT_OUTPUT_TEXT_COLOR, new RGB(0,
0, 0));
PreferenceConverter.setDefault(this,
CHAT_CHAT_EVENT_TYPE_COLOR_APPEND_TO + ChatType.CHALLENGE
+ "-color", new RGB(100, 149, 237));
PreferenceConverter.setDefault(this,
CHAT_CHAT_EVENT_TYPE_COLOR_APPEND_TO + ChatType.CSHOUT
+ "-color", new RGB(221, 160, 221));
PreferenceConverter.setDefault(this,
CHAT_CHAT_EVENT_TYPE_COLOR_APPEND_TO + ChatType.SHOUT
+ "-color", new RGB(221, 160, 221));
PreferenceConverter.setDefault(this,
CHAT_CHAT_EVENT_TYPE_COLOR_APPEND_TO + ChatType.KIBITZ
+ "-color", new RGB(100, 149, 237));
PreferenceConverter.setDefault(this,
CHAT_CHAT_EVENT_TYPE_COLOR_APPEND_TO + ChatType.WHISPER
+ "-color", new RGB(100, 149, 237));
PreferenceConverter.setDefault(this,
CHAT_CHAT_EVENT_TYPE_COLOR_APPEND_TO + ChatType.OUTBOUND
+ "-color", new RGB(128, 128, 128));
PreferenceConverter.setDefault(this,
CHAT_CHAT_EVENT_TYPE_COLOR_APPEND_TO + ChatType.PARTNER_TELL
+ "-color", new RGB(255, 0, 0));
PreferenceConverter.setDefault(this,
CHAT_CHAT_EVENT_TYPE_COLOR_APPEND_TO + ChatType.DRAW_REQUEST
+ "-color", new RGB(255, 0, 0));
PreferenceConverter.setDefault(this,
CHAT_CHAT_EVENT_TYPE_COLOR_APPEND_TO + ChatType.ABORT_REQUEST
+ "-color", new RGB(255, 0, 0));
PreferenceConverter
.setDefault(this, CHAT_CHAT_EVENT_TYPE_COLOR_APPEND_TO
+ ChatType.TELL + "-color", new RGB(255, 0, 0));
PreferenceConverter.setDefault(this,
CHAT_CHAT_EVENT_TYPE_COLOR_APPEND_TO + ChatType.CHANNEL_TELL
+ "-" + 1 + "-color", new RGB(255, 200, 0));
PreferenceConverter.setDefault(this,
CHAT_CHAT_EVENT_TYPE_COLOR_APPEND_TO + ChatType.CHANNEL_TELL
+ "-" + 4 + "-color", new RGB(0, 255, 0));
PreferenceConverter.setDefault(this,
CHAT_CHAT_EVENT_TYPE_COLOR_APPEND_TO + ChatType.CHANNEL_TELL
+ "-" + 50 + "-color", new RGB(255, 175, 175));
PreferenceConverter.setDefault(this,
CHAT_CHAT_EVENT_TYPE_COLOR_APPEND_TO + ChatType.CHANNEL_TELL
+ "-" + 53 + "-color", new RGB(255, 0, 255));
PreferenceConverter.setDefault(this,
CHAT_CHAT_EVENT_TYPE_COLOR_APPEND_TO + ChatType.INTERNAL
+ "-color", new RGB(255, 0, 0));
PreferenceConverter.setDefault(this,
CHAT_CHAT_EVENT_TYPE_COLOR_APPEND_TO
+ ChatType.PLAYING_STATISTICS + "-color", new RGB(100,
149, 237));
PreferenceConverter.setDefault(this,
CHAT_CHAT_EVENT_TYPE_COLOR_APPEND_TO + ChatType.QTELL
+ "-color", new RGB(128, 128, 128));
PreferenceConverter.setDefault(this,
CHAT_CHAT_EVENT_TYPE_COLOR_APPEND_TO + ChatType.FINGER
+ "-color", new RGB(128, 128, 128));
PreferenceConverter.setDefault(this, CHAT_PROMPT_COLOR, new RGB(128,
128, 128));
PreferenceConverter.setDefault(this, CHAT_QUOTE_UNDERLINE_COLOR,
new RGB(0, 255, 0));
PreferenceConverter.setDefault(this, CHAT_LINK_UNDERLINE_COLOR,
new RGB(11, 133, 238));
// Bug house buttons settings.
PreferenceConverter.setDefault(this, BUG_BUTTONS_FONT,
new FontData[] { new FontData(defaultFontName,
defaultSmallFontSize, SWT.BOLD) });
// Bug house
setDefault(BUGHOUSE_PLAYING_OPEN_PARTNER_BOARD, true);
setDefault(BUGHOUSE_OBSERVING_OPEN_PARTNER_BOARD, true);
setDefault(BUGHOUSE_SPEAK_COUNTDOWN_ON_PARTNER_BOARD, true);
setDefault(BUGHOUSE_SPEAK_PARTNER_TELLS, true);
setDefault(BUGHOUSE_IS_PLAYING_PARTNERSHIP_OFFERED_SOUND, true);
// App settings.
setDefault(APP_NAME, "Raptor .94d");
setDefault(APP_SASH_WIDTH, 8);
PreferenceConverter.setDefault(this, APP_PING_FONT,
new FontData[] { new FontData(defaultFontName,
defaultSmallFontSize, 0) });
PreferenceConverter.setDefault(this, APP_PING_COLOR, new RGB(0, 0, 0));
PreferenceConverter.setDefault(this, APP_STATUS_BAR_FONT,
new FontData[] { new FontData(defaultFontName,
defaultSmallFontSize, 0) });
PreferenceConverter.setDefault(this, APP_STATUS_BAR_COLOR, new RGB(0,
0, 0));
setDefault(APP_HOME_URL,
"http://code.google.com/p/raptor-chess-interface/");
setDefault(APP_SOUND_ENABLED, true);
setDefault(APP_IS_LOGGING_GAMES, true);
setDefault(APP_LAYOUT, "Layout1");
setDefault(APP_OPEN_LINKS_IN_EXTERNAL_BROWSER, false);
setDefault(APP_BROWSER_QUADRANT, Quadrant.III);
setDefault(APP_PGN_RESULTS_QUADRANT, Quadrant.III);
setDefault(APP_CHESS_BOARD_QUADRANT, Quadrant.III);
setDefault(APP_CHESS_BOARD_SECONDARY_QUADRANT, Quadrant.V);
setDefault(APP_OPEN_LINKS_IN_EXTERNAL_BROWSER, false);
setDefault(APP_IS_LAUNCHNG_HOME_PAGE, true);
setDefault(APP_WINDOW_ITEM_POLL_INTERVAL, 3);
// Layout 1 settings.
setDefault(APP_WINDOW_BOUNDS, new Rectangle(0, 0, -1, -1));
setDefault(APP_QUAD9_QUAD12345678_SASH_WEIGHTS, new int[] { 10, 90 });
setDefault(APP_QUAD1_QUAD2345678_SASH_WEIGHTS, new int[] { 10, 90 });
setDefault(APP_QUAD2345_QUAD678_SASH_WEIGHTS, new int[] { 70, 30 });
setDefault(APP_QUAD2_QUAD3_QUAD4_QUAD5_SASH_WEIGHTS, new int[] { 10,
40, 10, 40 });
setDefault(APP_QUAD67_QUAD8_SASH_WEIGHTS, new int[] { 70, 30 });
setDefault(APP_QUAD6_QUAD7_SASH_WEIGHTS, new int[] { 50, 50 });
// Fics
setDefault(FICS_KEEP_ALIVE, false);
setDefault(FICS_AUTO_CONNECT, false);
setDefault(FICS_LOGIN_SCRIPT, "set seek 0\nset autoflag 1\n");
setDefault(FICS_AUTO_CONNECT, false);
setDefault(FICS_PROFILE, "Primary");
setDefault(FICS_CLOSE_TABS_ON_DISCONNECT, false);
setDefault(FICS_SHOW_BUGBUTTONS_ON_PARTNERSHIP, true);
setDefault(FICS_NO_WRAP_ENABLED, true);
setDefault(FICS_CHANNEL_COMMANDS,
"+channel $channel,-channel $channel,in $channel");
setDefault(
FICS_PERSON_COMMANDS,
"finger $person,variables $person,history $person,partner $person,"
+ "observe $person,follow $person,pstat $userName $person,"
+ "oldpstat $userName $person,separator,"
+ "+censor $person,-censor $person,+notify $person,-notify $person,+gnotify $person,-gnotify $person,separator,"
+ "match $person 1 0,match $person 3 0,match $person 4 0,match $person 5 0");
setDefault(FICS_GAME_COMMANDS,
"observe $gameId,allobservers $gameId,moves $gameId");
setDefault(FICS_SEEK_GAME_TYPE, "");
setDefault(FICS_SEEK_MINUTES, "5");
setDefault(FICS_SEEK_INC, "0");
setDefault(FICS_SEEK_MIN_RATING, "Any");
setDefault(FICS_SEEK_MAX_RATING, "Any");
setDefault(FICS_SEEK_MANUAL, false);
setDefault(FICS_SEEK_FORMULA, true);
setDefault(FICS_SEEK_RATED, true);
setDefault(FICS_SEEK_COLOR, "");
setDefault(FICS_KEEP_ALIVE_COMMAND, "set busy in another window");
// Fics Primary
setDefault(FICS_PRIMARY_USER_NAME, "");
setDefault(FICS_PRIMARY_PASSWORD, "");
setDefault(FICS_PRIMARY_IS_NAMED_GUEST, false);
setDefault(FICS_PRIMARY_IS_ANON_GUEST, false);
setDefault(FICS_PRIMARY_SERVER_URL, "freechess.org");
setDefault(FICS_PRIMARY_PORT, 5000);
setDefault(FICS_PRIMARY_TIMESEAL_ENABLED, true);
// Fics Secondary
setDefault(FICS_SECONDARY_USER_NAME, "");
setDefault(FICS_SECONDARY_PASSWORD, "");
setDefault(FICS_SECONDARY_IS_NAMED_GUEST, false);
setDefault(FICS_SECONDARY_IS_ANON_GUEST, false);
setDefault(FICS_SECONDARY_SERVER_URL, "freechess.org");
setDefault(FICS_SECONDARY_PORT, 5000);
setDefault(FICS_SECONDARY_TIMESEAL_ENABLED, true);
// Fics Tertiary
setDefault(FICS_TERTIARY_USER_NAME, "");
setDefault(FICS_TERTIARY_PASSWORD, "");
setDefault(FICS_TERTIARY_IS_NAMED_GUEST, false);
setDefault(FICS_TERTIARY_IS_ANON_GUEST, false);
setDefault(FICS_TERTIARY_SERVER_URL, "freechess.org");
setDefault(FICS_TERTIARY_PORT, 5000);
setDefault(FICS_TERTIARY_TIMESEAL_ENABLED, true);
// Bics
setDefault(BICS_KEEP_ALIVE, false);
setDefault(BICS_AUTO_CONNECT, false);
setDefault(BICS_LOGIN_SCRIPT, "set autoflag 1\n\n");
setDefault(BICS_AUTO_CONNECT, false);
setDefault(BICS_PROFILE, "Primary");
setDefault(BICS_CLOSE_TABS_ON_DISCONNECT, false);
setDefault(BICS_SHOW_BUGBUTTONS_ON_PARTNERSHIP, true);
setDefault(BICS_KEEP_ALIVE_COMMAND, "set busy in another window");
setDefault(BICS_CHANNEL_COMMANDS,
"+channel $channel,-channel $channel,in $channel");
setDefault(
BICS_PERSON_COMMANDS,
"finger $person,variables $person,history $person,partner $person,"
+ "observe $person,follow $person,pstat $userName $person,"
+ "oldpstat $userName $person,separator,"
+ "+censor $person,-censor $person,+notify $person,-notify $person,+gnotify $person,-gnotify $person,separator,"
+ "match $person 1 0 zh,match $person 3 0 zh,match $person 1 0 zh fr,match $person 3 0 zh fr,match $person 2 0 bughouse,"
+ "match $person 2 0 bughouse fr, match $person 2 0 bughouse w5");
setDefault(BICS_GAME_COMMANDS,
"observe $gameId,allobservers $gameId,moves $gameId");
// Bics Primary
setDefault(BICS_PRIMARY_USER_NAME, "");
setDefault(BICS_PRIMARY_PASSWORD, "");
setDefault(BICS_PRIMARY_IS_NAMED_GUEST, false);
setDefault(BICS_PRIMARY_IS_ANON_GUEST, false);
setDefault(BICS_PRIMARY_SERVER_URL, "chess.sipay.ru");
setDefault(BICS_PRIMARY_PORT, 5000);
setDefault(BICS_PRIMARY_TIMESEAL_ENABLED, true);
// Bics Secondary
setDefault(BICS_SECONDARY_USER_NAME, "");
setDefault(BICS_SECONDARY_PASSWORD, "");
setDefault(BICS_SECONDARY_IS_NAMED_GUEST, false);
setDefault(BICS_SECONDARY_IS_ANON_GUEST, false);
setDefault(BICS_SECONDARY_SERVER_URL, "chess.sipay.ru");
setDefault(BICS_SECONDARY_PORT, 5000);
setDefault(BICS_SECONDARY_TIMESEAL_ENABLED, true);
// Bics Tertiary
setDefault(BICS_TERTIARY_USER_NAME, "");
setDefault(BICS_TERTIARY_PASSWORD, "");
setDefault(BICS_TERTIARY_IS_NAMED_GUEST, false);
setDefault(BICS_TERTIARY_IS_ANON_GUEST, false);
setDefault(BICS_TERTIARY_SERVER_URL, "chess.sipay.ru");
setDefault(BICS_TERTIARY_PORT, 5000);
setDefault(BICS_TERTIARY_TIMESEAL_ENABLED, true);
// Quadrant settings.
setDefault("fics-" + MAIN_TAB_QUADRANT, Quadrant.VI);
setDefault("fics-" + CHANNEL_TAB_QUADRANT, Quadrant.VI);
setDefault("fics-" + PERSON_TAB_QUADRANT, Quadrant.VI);
setDefault("fics-" + REGEX_TAB_QUADRANT, Quadrant.VI);
setDefault("fics-" + PARTNER_TELL_TAB_QUADRANT, Quadrant.VI);
setDefault("fics-" + CHESS_BOARD_QUADRANT, Quadrant.III);
setDefault("fics-" + CHESS_BOARD_SECONDARY_QUADRANT, Quadrant.V);
setDefault("fics-" + BUG_WHO_QUADRANT, Quadrant.VIII);
setDefault("fics-" + SEEK_TABLE_QUADRANT, Quadrant.VIII);
setDefault("fics-" + BUG_BUTTONS_QUADRANT, Quadrant.II);
setDefault("fics-" + GAME_CHAT_TAB_QUADRANT, Quadrant.VI);
setDefault("fics2-" + MAIN_TAB_QUADRANT, Quadrant.VII);
setDefault("fics2-" + CHANNEL_TAB_QUADRANT, Quadrant.VII);
setDefault("fics2-" + PERSON_TAB_QUADRANT, Quadrant.VII);
setDefault("fics2-" + REGEX_TAB_QUADRANT, Quadrant.VII);
setDefault("fics2-" + PARTNER_TELL_TAB_QUADRANT, Quadrant.VII);
setDefault("fics2-" + CHESS_BOARD_QUADRANT, Quadrant.III);
setDefault("fics2-" + CHESS_BOARD_SECONDARY_QUADRANT, Quadrant.V);
setDefault("fics2-" + BUG_WHO_QUADRANT, Quadrant.VIII);
setDefault("fics2-" + SEEK_TABLE_QUADRANT, Quadrant.VIII);
setDefault("fics2-" + BUG_BUTTONS_QUADRANT, Quadrant.II);
setDefault("fics2-" + GAME_CHAT_TAB_QUADRANT, Quadrant.VII);
setDefault("bics-" + MAIN_TAB_QUADRANT, Quadrant.VI);
setDefault("bics-" + CHANNEL_TAB_QUADRANT, Quadrant.VI);
setDefault("bics-" + PERSON_TAB_QUADRANT, Quadrant.VI);
setDefault("bics-" + REGEX_TAB_QUADRANT, Quadrant.VI);
setDefault("bics-" + PARTNER_TELL_TAB_QUADRANT, Quadrant.VI);
setDefault("bics-" + CHESS_BOARD_QUADRANT, Quadrant.III);
setDefault("bics-" + CHESS_BOARD_SECONDARY_QUADRANT, Quadrant.V);
setDefault("bics-" + BUG_WHO_QUADRANT, Quadrant.VIII);
setDefault("bics-" + SEEK_TABLE_QUADRANT, Quadrant.VIII);
setDefault("bics-" + BUG_BUTTONS_QUADRANT, Quadrant.II);
setDefault("bics-" + GAME_CHAT_TAB_QUADRANT, Quadrant.VI);
setDefault("bics2-" + MAIN_TAB_QUADRANT, Quadrant.VII);
setDefault("bics2-" + CHANNEL_TAB_QUADRANT, Quadrant.VII);
setDefault("bics2-" + PERSON_TAB_QUADRANT, Quadrant.VII);
setDefault("bics2-" + REGEX_TAB_QUADRANT, Quadrant.VII);
setDefault("bics2-" + PARTNER_TELL_TAB_QUADRANT, Quadrant.VII);
setDefault("bics2-" + CHESS_BOARD_QUADRANT, Quadrant.III);
setDefault("bics2-" + CHESS_BOARD_SECONDARY_QUADRANT, Quadrant.V);
setDefault("bics2-" + BUG_WHO_QUADRANT, Quadrant.VIII);
setDefault("bics2-" + SEEK_TABLE_QUADRANT, Quadrant.VIII);
setDefault("bics2-" + BUG_BUTTONS_QUADRANT, Quadrant.II);
setDefault("bics2-" + GAME_CHAT_TAB_QUADRANT, Quadrant.VII);
setDefault(TIMESEAL_INIT_STRING, "TIMESTAMP|iv|OpenSeal|");
LOG.info("Loaded defaults " + PREFERENCE_PROPERTIES_FILE);
}
@Override
public void save() {
FileOutputStream fileOut = null;
try {
save(fileOut = new FileOutputStream(RAPTOR_PROPERTIES),
"Last saved on " + new Date());
fileOut.flush();
} catch (IOException ioe) {
LOG.error("Error saving raptor preferences:", ioe);
throw new RuntimeException(ioe);
} finally {
try {
fileOut.close();
} catch (Throwable t) {
}
}
}
public void setDefault(String key, Font font) {
PreferenceConverter.setValue(this, key, font.getFontData());
}
public void setDefault(String key, FontData[] fontData) {
PreferenceConverter.setValue(this, key, fontData);
}
public void setDefault(String key, int[] values) {
setDefault(key, RaptorStringUtils.toString(values));
}
public void setDefault(String key, Point point) {
PreferenceConverter.setValue(this, key, point);
}
public void setDefault(String key, Quadrant quadrant) {
setDefault(key, quadrant.name());
}
public void setDefault(String key, Rectangle rectangle) {
PreferenceConverter.setDefault(this, key, rectangle);
}
public void setDefault(String key, RGB rgb) {
PreferenceConverter.setValue(this, key, rgb);
}
public void setDefault(String key, String[] values) {
setDefault(key, RaptorStringUtils.toString(values));
}
public void setValue(String key, Font font) {
PreferenceConverter.setValue(this, key, font.getFontData());
}
public void setValue(String key, FontData[] fontData) {
PreferenceConverter.setValue(this, key, fontData);
}
public void setValue(String key, int[] values) {
setValue(key, RaptorStringUtils.toString(values));
}
public void setValue(String key, Point point) {
PreferenceConverter.setValue(this, key, point);
}
public void setValue(String key, Quadrant quadrant) {
setValue(key, quadrant.name());
}
public void setValue(String key, Rectangle rectangle) {
PreferenceConverter.setValue(this, key, rectangle);
}
public void setValue(String key, RGB rgb) {
PreferenceConverter.setValue(this, key, rgb);
}
public void setValue(String key, String[] values) {
setValue(key, RaptorStringUtils.toString(values));
}
protected void setDefaultMonitorBasedSizes() {
Rectangle fullViewBounds = Display.getCurrent().getPrimaryMonitor()
.getBounds();
int toolbarPieceSize = 12;
String iconSize = "tiny";
defaultLargeFontSize = 10;
defaultMediumFontSize = 10;
defaultSmallFontSize = 8;
defaultTinyFontSize = 6;
if (fullViewBounds.height >= 1200) {
iconSize = "large";
toolbarPieceSize = 24;
defaultLargeFontSize = 18;
defaultMediumFontSize = 16;
defaultSmallFontSize = 14;
defaultTinyFontSize = 12;
} else if (fullViewBounds.height >= 1024) {
iconSize = "medium";
toolbarPieceSize = 20;
defaultLargeFontSize = 16;
defaultMediumFontSize = 14;
defaultSmallFontSize = 12;
defaultTinyFontSize = 10;
} else if (fullViewBounds.height >= 800) {
iconSize = "small";
toolbarPieceSize = 16;
defaultLargeFontSize = 12;
defaultMediumFontSize = 12;
defaultSmallFontSize = 10;
defaultTinyFontSize = 8;
}
getDefauultMonospacedFont();
setDefault(PreferenceKeys.APP_ICON_SIZE, iconSize);
setDefault(PreferenceKeys.APP_TOOLBAR_PIECE_SIZE, toolbarPieceSize);
}
}
|
package org.mskcc.cgds.scripts;
import org.mskcc.cgds.dao.*;
import org.mskcc.cgds.model.SecretKey;
import org.mskcc.cgds.util.DatabaseProperties;
/**
* Empty the database.
*
* @author Ethan Cerami
* @author Arthur Goldberg goldberg@cbio.mskcc.org
*/
public class ResetDatabase {
public static final int MAX_RESET_SIZE = 6;
/**
* Remove all records from any size database.
* Whenever a new Dao* class is defined, must add its deleteAllRecords() method here.
*
* @throws DaoException
*/
public static void resetAnySizeDatabase() throws DaoException {
DaoSecretKey.deleteAllRecords();
DaoUser.deleteAllRecords();
DaoUserAccessRight.deleteAllRecords();
DaoTypeOfCancer.deleteAllRecords();
DaoCancerStudy.deleteAllRecords();
DaoMicroRna daoMicroRna = new DaoMicroRna();
daoMicroRna.deleteAllRecords();
DaoGeneOptimized daoGene = DaoGeneOptimized.getInstance();
daoGene.deleteAllRecords();
DaoCase daoCase = new DaoCase();
daoCase.deleteAllRecords();
DaoGeneticAlteration daoGenetic = DaoGeneticAlteration.getInstance();
daoGenetic.deleteAllRecords();
DaoMicroRnaAlteration daoMicroRnaAlteration = DaoMicroRnaAlteration.getInstance();
daoMicroRnaAlteration.deleteAllRecords();
DaoMutSig daoMutSig = DaoMutSig.getInstance();
daoMutSig.deleteAllRecords();
DaoGeneticProfile daoGeneticProfile = new DaoGeneticProfile();
daoGeneticProfile.deleteAllRecords();
DaoCaseList daoCaseList = new DaoCaseList();
daoCaseList.deleteAllRecords();
DaoClinicalData daoClinicalData = new DaoClinicalData();
daoClinicalData.deleteAllRecords();
DaoMutation daoMutation = DaoMutation.getInstance();
daoMutation.deleteAllRecords();
DaoMutationFrequency daoMutationFrequency = new DaoMutationFrequency();
daoMutationFrequency.deleteAllRecords();
DaoGeneticProfileCases daoGeneticProfileCases = new DaoGeneticProfileCases();
daoGeneticProfileCases.deleteAllRecords();
DaoInteraction daoInteraction = DaoInteraction.getInstance();
daoInteraction.deleteAllRecords();
// No production keys stored in filesystem or code: digest the key; put it in properties; load it into dbms on startup
DatabaseProperties databaseProperties = DatabaseProperties.getInstance();
SecretKey secretKey = new SecretKey();
secretKey.setEncryptedKey(databaseProperties.getDbEncryptedKey());
DaoSecretKey.addSecretKey(secretKey);
}
public static void resetDatabase() throws DaoException {
// safety measure: don't reset a big database
if (MAX_RESET_SIZE < DaoCancerStudy.getCount()) {
throw new DaoException("Database has " + DaoCancerStudy.getCount() +
" studies, and we don't reset a database with more than " + MAX_RESET_SIZE + " records.");
} else {
resetAnySizeDatabase();
}
}
public static void main(String[] args) throws DaoException {
StatDatabase.statDb();
ResetDatabase.resetDatabase();
System.err.println("Database Cleared and Reset.");
}
}
|
package org.jetel.graph;
import java.io.*;
import java.text.DateFormat;
import java.util.*;
import java.util.logging.Logger;
import org.jetel.data.Defaults;
import org.jetel.database.DBConnection;
import org.jetel.exception.ComponentNotReadyException;
import org.jetel.util.StringUtils;
/**
* Description of the Class
*
* @author dpavlis
* @since July 29, 2002
* @revision $Revision$
*/
class WatchDog extends Thread {
private PrintStream log;
private int trackingInterval;
private int watchDogStatus;
private TransformationGraph graph;
private Phase[] phases;
private Phase currentPhase;
private Runtime javaRuntime;
private int freeMemoryStampKB;
/** Description of the Field */
public final static int WATCH_DOG_STATUS_READY = 0;
/** Description of the Field */
public final static int WATCH_DOG_STATUS_ERROR = -1;
/** Description of the Field */
public final static int WATCH_DOG_STATUS_RUNNING = 1;
/** Description of the Field */
public final static int WATCH_DOG_STATUS_FINISHED_OK = 2;
static Logger logger = Logger.getLogger("org.jetel");
/**
*Constructor for the WatchDog object
*
* @param graph Description of the Parameter
* @param phases Description of the Parameter
* @since September 02, 2003
*/
WatchDog(TransformationGraph graph, Phase[] phases) {
super("WatchDog");
log = System.out;
trackingInterval = Defaults.WatchDog.DEFAULT_WATCHDOG_TRACKING_INTERVAL;
setDaemon(true);
this.graph = graph;
this.phases = phases;
currentPhase = null;
watchDogStatus = WATCH_DOG_STATUS_READY;
javaRuntime = Runtime.getRuntime();
freeMemoryStampKB = (int) javaRuntime.freeMemory()/1024;
}
/**
*Constructor for the WatchDog object
*
* @param out Description of Parameter
* @param tracking Description of Parameter
* @param graph Description of the Parameter
* @param phases Description of the Parameter
* @since September 02, 2003
*/
WatchDog(TransformationGraph graph, Phase[] phases, PrintStream out, int tracking) {
this(graph,phases);
log = out;
trackingInterval = tracking;
}
/** Main processing method for the WatchDog object */
public void run() {
watchDogStatus = WATCH_DOG_STATUS_RUNNING;
log.println("[WatchDog] Thread started.");
log.print("[WatchDog] Running on " + javaRuntime.availableProcessors() + " CPU(s)");
log.println(" max available memory for JVM " + javaRuntime.freeMemory() / 1024 + " KB");
for (int i = 0; i < phases.length; i++) {
if (!runPhase(phases[i])) {
watchDogStatus = WATCH_DOG_STATUS_ERROR;
log.println("[WatchDog] !!! Phase finished with error - stopping graph run !!!");
return;
}
// force running of garbage collector
log.println("[WatchDog] Forcing garbage collection ...");
javaRuntime.runFinalization();
javaRuntime.gc();
}
watchDogStatus = WATCH_DOG_STATUS_FINISHED_OK;
printPhasesSummary();
}
/**
* Execute transformation - start-up all Nodes & watch them running
*
* @param phase Description of the Parameter
* @param leafNodes Description of the Parameter
* @return Description of the Return Value
* @since July 29, 2002
*/
public boolean watch(Phase phase, List leafNodes) {
int phaseMemUtilizationMaxKB;
int usedMemoryKB;
Iterator leafNodesIterator;
Iterator nodesIterator;
Node node;
int ticker = Defaults.WatchDog.NUMBER_OF_TICKS_BETWEEN_STATUS_CHECKS;
long lastTimestamp;
long currentTimestamp;
long startTimestamp;
//get current memory utilization
phaseMemUtilizationMaxKB=freeMemoryStampKB - (int) javaRuntime.freeMemory()/1024;
//let's take timestamp so we can measure processing
startTimestamp = lastTimestamp = System.currentTimeMillis();
// entering the loop awaiting completion of work by all leaf nodes
while (true) {
if (leafNodes.isEmpty()) {
phase.setPhaseMemUtilization(phaseMemUtilizationMaxKB);
phase.setPhaseExecTime((int) (System.currentTimeMillis() - startTimestamp));
log.print("[WatchDog] Execution of phase [" + phase.getPhaseNum() + "] successfully finished - elapsed time(sec): ");
log.println(phase.getPhaseExecTime() / 1000);
printProcessingStatus(phase.getNodes().iterator(), phase.getPhaseNum());
return true;
// nothing else to do in this phase
}
leafNodesIterator = leafNodes.iterator();
while (leafNodesIterator.hasNext()) {
node = (Node) leafNodesIterator.next();
// is this Node still alive - ? doing something
if (!node.isAlive()) {
leafNodesIterator.remove();
}
}
// from time to time perform some task
if ((ticker
// reinitialize ticker
ticker = Defaults.WatchDog.NUMBER_OF_TICKS_BETWEEN_STATUS_CHECKS;
// get memory usage mark
usedMemoryKB = freeMemoryStampKB - (int) javaRuntime.freeMemory()/1024;
if (phaseMemUtilizationMaxKB < usedMemoryKB) {
phaseMemUtilizationMaxKB = usedMemoryKB;
}
// check that no Node finished with some fatal error
nodesIterator = phase.getNodes().iterator();
while (nodesIterator.hasNext()) {
node = (Node) nodesIterator.next();
if ((!node.isAlive()) && (node.getResultCode() != Node.RESULT_OK)) {
log.println("[WatchDog] !!! Fatal Error !!! - graph execution is aborting");
logger.severe("Node " + node.getID() + " finished with fatal error: " + node.getResultMsg());
watchDogStatus = WATCH_DOG_STATUS_ERROR;
abort();
printProcessingStatus(phase.getNodes().iterator(), phase.getPhaseNum());
return false;
}
}
}
// Display processing status, if it is time
currentTimestamp = System.currentTimeMillis();
if ((currentTimestamp - lastTimestamp) >= Defaults.WatchDog.DEFAULT_WATCHDOG_TRACKING_INTERVAL) {
printProcessingStatus(phase.getNodes().iterator(), phase.getPhaseNum());
lastTimestamp = currentTimestamp;
}
// rest for some time
try {
sleep(Defaults.WatchDog.WATCHDOG_SLEEP_INTERVAL);
} catch (InterruptedException ex) {
watchDogStatus = WATCH_DOG_STATUS_ERROR;
return false;
}
}
}
/**
* Gets the Status of the WatchDog
*
* @return 0 if successful, -1 otherwise
* @since July 30, 2002
*/
int getStatus() {
return watchDogStatus;
}
/**
* Outputs basic LOG information about graph processing
*
* @param iterator Description of Parameter
* @param phaseNo Description of the Parameter
* @since July 30, 2002
*/
void printProcessingStatus(Iterator iterator, int phaseNo) {
int i;
int recCount;
Node node;
StringBuffer stringBuf;
stringBuf = new StringBuffer(90);
log.println("
log.print("Time: ");
// France is here just to get 24hour time format
log.println(DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.MEDIUM, Locale.FRANCE).
format(Calendar.getInstance().getTime()));
log.println("Node Status Port #Records");
log.println("
while (iterator.hasNext()) {
node = (Node) iterator.next();
Object nodeInfo[] = {node.getID(), node.getStatus()};
int nodeSizes[] = {-28, -15};
log.println(StringUtils.formatString(nodeInfo, nodeSizes));
//in ports
i = 0;
while ((recCount = node.getRecordCount(Node.INPUT_PORT, i)) != -1) {
Object portInfo[] = {"In:", Integer.toString(i), Integer.toString(recCount)};
int portSizes[] = {47, -2, 32};
log.println(StringUtils.formatString(portInfo, portSizes));
i++;
}
//out ports
i = 0;
while ((recCount = node.getRecordCount(Node.OUTPUT_PORT, i)) != -1) {
Object portInfo[] = {"Out:", Integer.toString(i), Integer.toString(recCount)};
int portSizes[] = {47, -2, 32};
log.println(StringUtils.formatString(portInfo, portSizes));
i++;
}
}
log.println("
log.flush();
}
/** Outputs summary info about executed phases */
void printPhasesSummary() {
log.println("
log.println("Phase# Finished Status RunTime(sec) MemoryAllocation(KB)");
for (int i = 0; i < phases.length; i++) {
Object nodeInfo[] = {new Integer(phases[i].getPhaseNum()), new Integer(0),
new Integer(phases[i].getPhaseExecTime()/1000), new Integer(phases[i].getPhaseMemUtilization())};
int nodeSizes[] = {-18, -24, 12, 18};
log.println(StringUtils.formatString(nodeInfo, nodeSizes));
}
log.println("
}
/**
* aborts execution of current phase
*
* @since July 29, 2002
*/
void abort() {
Iterator iterator = currentPhase.getNodes().iterator();
Node node;
// iterate through all the nodes and stop them
while (iterator.hasNext()) {
node = (Node) iterator.next();
node.abort();
log.print("[WatchDog] Interrupted node: ");
log.println(node.getID());
log.flush();
}
}
/**
* Description of the Method
*
* @param nodesIterator Description of Parameter
* @param leafNodesList Description of Parameter
* @since July 31, 2002
*/
private void startUpNodes(Iterator nodesIterator, List leafNodesList) {
Node node;
while (nodesIterator.hasNext()) {
node = (Node) nodesIterator.next();
log.print("[WatchDog] ");
log.print(node.getID());
node.start();
if (node.isLeaf() || node.isPhaseLeaf()) {
leafNodesList.add(node);
}
log.println(" ... started");
log.flush();
}
}
/**
* Description of the Method
*
* @param phase Description of the Parameter
* @return Description of the Return Value
*/
private boolean runPhase(Phase phase) {
boolean result;
currentPhase = phase;
List leafNodes = new LinkedList();
phase.check();
// init phase
if (!phase.init(log)) {
// something went wrong !
return false;
}
log.println("[WatchDog] Starting up all nodes in phase [" + phase.getPhaseNum() + "]");
startUpNodes(phase.getNodes().iterator(), leafNodes);
log.println("[WatchDog] Sucessfully started all nodes in phase!");
// watch running nodes in phase
result = watch(phase, leafNodes);
//end of phase, destroy it
phase.destroy();
return result;
}
/*
* private void initialize(){
* }
*/
}
|
package net.teamio.taam.rendering;
import java.util.Random;
import org.lwjgl.opengl.GL11;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.entity.RenderItem;
import net.minecraft.client.renderer.texture.TextureMap;
import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer;
import net.minecraft.client.resources.model.IBakedModel;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumFacing;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.common.gameevent.TickEvent;
import net.teamio.taam.content.IRotatable;
import net.teamio.taam.content.conveyors.TileEntityConveyorProcessor;
import net.teamio.taam.content.conveyors.TileEntityConveyorSieve;
import net.teamio.taam.conveyors.ConveyorUtil;
import net.teamio.taam.conveyors.ItemWrapper;
import net.teamio.taam.conveyors.api.IConveyorAwareTE;
import net.teamio.taam.piping.IPipe;
public class TaamRenderer extends TileEntitySpecialRenderer<TileEntity> {
private RenderItem ri;
private float rot = 0;
private float rot_sensor = 0;
public static double rotSin = 0;
public TaamRenderer() {
ri = Minecraft.getMinecraft().getRenderItem();
}
@SubscribeEvent
public void onClientTick(TickEvent.ClientTickEvent event) {
if (event.phase == TickEvent.Phase.END) {
rot++;
rot_sensor++;
if(rot_sensor > 360) {
rot_sensor -= 360;
}
rotSin = Math.sin(Math.toRadians(rot*32));
}
}
@Override
public void renderTileEntityAt(TileEntity tileEntity, double x, double y, double z, float partialTicks, int destroyStage) {
if(tileEntity instanceof IConveyorAwareTE) {
renderConveyorItems((IConveyorAwareTE) tileEntity, x, y, z);
}
if(tileEntity instanceof IPipe) {
IPipe pipe = (IPipe)tileEntity;
GL11.glPushMatrix();
GL11.glTranslated(x, y, z);
GL11.glPushMatrix();
GL11.glTranslated(0.4f, 0.4f, 0.25f);
GL11.glScalef(.02f, .02f, .02f);
GL11.glRotatef(180, 0, 0, 1);
Minecraft.getMinecraft().fontRendererObj.drawString(pipe.getPressure() + "-" + pipe.getSuction(), 0, 0, 0xFFFFFF);
//GL11.glTranslated(0, y+0.5f, z-0.1f);
Minecraft.getMinecraft().fontRendererObj.drawString("E: " + (pipe.getPressure() - pipe.getSuction()), 0, 8, 0xFFFF00);
GL11.glPopMatrix();
GL11.glTranslated(.5f, .5f, .5f);
GL11.glRotatef(180, 0, 1, 0);
GL11.glTranslated(-.5f, -.5f, -.5f);
GL11.glPushMatrix();
GL11.glTranslated(0.4f, 0.4f, 0.25f);
GL11.glScalef(.02f, .02f, .02f);
GL11.glRotatef(180, 0, 0, 1);
// GL11.glTranslated(0, 0, -25f);
Minecraft.getMinecraft().fontRendererObj.drawString(pipe.getPressure() + "-" + pipe.getSuction(), 0, 0, 0xFFFFFF);
//GL11.glTranslated(0, y+0.5f, z-0.1f);
Minecraft.getMinecraft().fontRendererObj.drawString("E: " + (pipe.getPressure() - pipe.getSuction()), 0, 8, 0xFFFF00);
GL11.glPopMatrix();
GL11.glPopMatrix();
}
}
private EnumFacing conveyorGetDirection(IConveyorAwareTE tileEntity) {
EnumFacing direction;
if(tileEntity instanceof IRotatable) {
direction = ((IRotatable) tileEntity).getFacingDirection();
} else {
direction = EnumFacing.SOUTH;
}
return direction;
}
public void renderConveyorItems(IConveyorAwareTE tileEntity, double x, double y, double z) {
GL11.glPushMatrix();
GL11.glTranslated(x, y, z);
if(tileEntity != null) {
Minecraft.getMinecraft().getTextureManager().bindTexture(TextureMap.locationBlocksTexture);
if(tileEntity instanceof TileEntityConveyorProcessor) {
/*
* Get Rotation
*/
EnumFacing direction = conveyorGetDirection(tileEntity);
float rotationDegrees = 0;
if(direction == EnumFacing.WEST) {
rotationDegrees = 270;
} else if(direction == EnumFacing.NORTH) {
rotationDegrees = 180;
} else if(direction == EnumFacing.EAST) {
rotationDegrees = 90;
}
TileEntityConveyorProcessor processor = (TileEntityConveyorProcessor) tileEntity;
ItemStack processingStack = processor.getStackInSlot(0);
if(processingStack != null) {
GL11.glPushMatrix();
Random rand = processor.getWorld().rand;
GL11.glTranslatef(0.5f, 0.4f, 0.5f);
/*
* Rotate the items
*/
GL11.glRotatef(rotationDegrees, 0, 1, 0);
/*
* Shaking inside the processor
*/
if(!processor.isShutdown) {
GL11.glTranslatef(
0.015f * (1-rand.nextFloat()),
0.025f * (1-rand.nextFloat()),
0.015f * (1-rand.nextFloat()));
}
GL11.glScalef(0.4f, 0.4f, 0.4f);
IBakedModel model = ri.getItemModelMesher().getItemModel(processingStack);
ri.renderItem(processingStack, model);
GL11.glPopMatrix();
}
}
/*
* Regular rendering, meaning conveyors & similar
*/
if(tileEntity.shouldRenderItemsDefault()) {
float posY = 0.1f;
if(tileEntity instanceof TileEntityConveyorSieve) {
//TODO extract into separate method getItemRenderPosY() in IConveyorAwareTE
if(((TileEntityConveyorSieve) tileEntity).isShutdown) {
//posY = 0;
} else {
posY += (float)(rotSin*0.04);
}
}
for(int slot = 0; slot < 9; slot++) {
ItemWrapper wrapper = tileEntity.getSlot(slot);
ItemStack itemStack;
if(wrapper == null || wrapper.isEmpty()
|| (itemStack = wrapper.itemStack) == null) {
continue;
}
int movementProgress = tileEntity.getMovementProgress(slot);
if(movementProgress < 0) {
movementProgress = 0;
}
float speedsteps = tileEntity.getSpeedsteps();
EnumFacing renderDirection = tileEntity.getNextSlot(slot);
float posX = (float)ConveyorUtil.getItemPositionX(slot, movementProgress / speedsteps, renderDirection);
float posZ = (float)ConveyorUtil.getItemPositionZ(slot, movementProgress / speedsteps, renderDirection);
GL11.glPushMatrix();
GL11.glTranslatef(posX, posY + 0.51f, posZ);
GL11.glScalef(0.4f, 0.4f, 0.4f);
IBakedModel model = ri.getItemModelMesher().getItemModel(itemStack);
ri.renderItem(itemStack, model);
GL11.glPopMatrix();
}
}
}
GL11.glPopMatrix();
}
}
|
/**
* Helps simplify the programs code by creating helper methods that perform a certain function.
*/
package kuroodo.discordbot.helpers;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import kuroodo.discordbot.Init;
import net.dv8tion.jda.core.OnlineStatus;
import net.dv8tion.jda.core.entities.Guild;
import net.dv8tion.jda.core.entities.Member;
import net.dv8tion.jda.core.entities.Role;
import net.dv8tion.jda.core.entities.TextChannel;
import net.dv8tion.jda.core.entities.User;
import net.dv8tion.jda.core.entities.VoiceChannel;
import net.dv8tion.jda.core.managers.GuildController;
public class JDAHelper {
public static TextChannel getTextChannelByName(String channelName) {
for (TextChannel channel : getGuild().getTextChannels()) {
if (channel.getName().equals(channelName)) {
return channel;
}
}
System.out.println("ERROR Could not get text channel by name");
return null;
}
public static int getTextChannelCount() {
return getGuild().getTextChannels().size();
}
public static List<TextChannel> getTextChannels() {
return getGuild().getTextChannels();
}
public static VoiceChannel getVoiceChannelByName(String channelName) {
for (VoiceChannel channel : getGuild().getVoiceChannels()) {
if (channel.getName().equals(channelName)) {
return channel;
}
}
System.out.println("ERROR Could not get voice channel by name");
return null;
}
/**
* Gets the voice channel a specific user is in
*
* @param username
* the users username
* @return the voice channel
*/
public static VoiceChannel getUserVoiceChannel(String username) {
for (VoiceChannel channel : getGuild().getVoiceChannels()) {
for (Member member : channel.getMembers()) {
if (member.getUser().getName().equals(username)) {
return channel;
}
}
}
return null;
}
public static int getVoiceChannelCount() {
return getGuild().getVoiceChannels().size();
}
public static List<VoiceChannel> getVoiceChannels() {
return getGuild().getVoiceChannels();
}
/**
* Gets the voice channel index of a channel that a specific user is in
*
* @param username
* the users username
* @return the voice channels index in the list of voice channels
*/
public static Integer getUserVoiceChannelIndex(String username) {
for (int voiceChannelIndex = 0; voiceChannelIndex < getVoiceChannelCount(); voiceChannelIndex++) {
for (Member member : getVoiceChannels().get(voiceChannelIndex).getMembers()) {
if (member.getUser().getName().equals(username)) {
return voiceChannelIndex;
}
}
}
System.out.println("Error, could not return a channel index");
return 0;
}
public static User getUserByUsername(String username) {
for (Member member : getGuild().getMembers()) {
if (member.getUser().getName().equals(username)) {
return member.getUser();
}
}
System.out.println("ERROR Could Not Get User By Username");
return null;
}
public static Member getMemberByUsername(String username) {
for (Member member : getGuild().getMembers()) {
if (member.getUser().getName().equals(username)) {
return member;
}
}
System.out.println("ERROR Could Not Get MEMBER By Username");
return null;
}
public static User getUserByID(String ID) {
Member memberToGet = getGuild().getMemberById(ID);
if (memberToGet != null) {
return getGuild().getMemberById(ID).getUser();
} else {
System.out.println("ERROR could not get user by ID!");
return null;
}
}
public static Member getMemberByID(String ID) {
return getGuild().getMemberById(ID);
}
public static String getUsernameById(String ID) {
return getUserByID(ID).getName();
}
public static User getRandomOnlineUser() {
Random rand = new Random();
rand.setSeed(System.nanoTime());
ArrayList<User> onlineUsers = new ArrayList<User>();
for (Member member : getGuild().getMembers()) {
if (member.getOnlineStatus() == OnlineStatus.ONLINE) {
onlineUsers.add(member.getUser());
}
}
return onlineUsers.get(rand.nextInt(onlineUsers.size()));
}
public static User getRandomUser() {
Random rand = new Random();
rand.setSeed(System.nanoTime());
return getMembers().get(rand.nextInt(getUserCount())).getUser();
}
public static void giveRoleToMember(Role role, Member member) {
if (member == null || role == null) {
System.out.println("ERROR: COULD NOT GIVE USER A ROLE");
return;
}
getGuild().getController().addRolesToMember(member, role);
// GuildController guilControllerr = getGuild().getController();
// guildManager.addRoleToUser(user, role).update();
}
public static Role getRoleByName(String roleName) {
for (Role role : getGuild().getRoles()) {
if (role.getName().equals(roleName)) {
return role;
}
}
System.out.println("Error, could not get role by name");
return null;
}
public static Boolean isMemberAdmin(Member member) {
for (Role role : member.getRoles()) {
if (role.getName().equals("Admin")) {
return true;
}
}
return false;
}
public static Boolean isMemberModerator(Member member) {
for (Role role : member.getRoles()) {
if (role.getName().equals("Moderator")) {
return true;
}
}
return false;
}
public static boolean isUsernameValidUser(String userName) {
return getUserByUsername(userName) != null;
}
public static int getUserCount() {
return getGuild().getMembers().size();
}
public static List<Member> getMembers() {
return getGuild().getMembers();
}
public static Guild getGuild() {
return Init.getJDA().getGuilds().get(0);
}
/**
* Checks the list of audioqueues to find out if a command/message is an
* audioqueue
*
* @param The
* message/command that the entered. Specifically the word that
* may reperesnt the audioqueue
* @return Whether it was an audioqueue or not (true/false)
*/
public static boolean isMessageAnAudioQueue(String message) {
try {
return new File("sounds/" + message.substring(1) + ".mp3").exists();
} catch (Exception e) {
return false;
}
}
public static GuildController removeUsersRoles(Member member, GuildController controller) {
ArrayList<Role> membersRoles = new ArrayList<Role>(member.getRoles());
controller.removeRolesFromMember(member, membersRoles).queue();
return controller;
}
// Split a string in 2
public static String[] splitString(String stringToSplit) {
String[] splittedMessage = { "", "" };
splittedMessage[1] = stringToSplit;
if (stringToSplit.contains(" ")) {
splittedMessage[0] = stringToSplit.split(" ", -1)[0];
splittedMessage[1] = splittedMessage[1].replaceAll(splittedMessage[0] + " ", "");
} else {
splittedMessage[0] = stringToSplit;
splittedMessage[1] = "";
}
// System.out.println("debug");
// System.out.println(splittedMessage[0]);
// System.out.println(splittedMessage[1]);
return splittedMessage;
}
}
|
package bisq.core.user;
import bisq.core.btc.nodes.BtcNodes;
import bisq.core.btc.nodes.LocalBitcoinNode;
import bisq.core.btc.wallet.Restrictions;
import bisq.core.locale.Country;
import bisq.core.locale.CountryUtil;
import bisq.core.locale.CryptoCurrency;
import bisq.core.locale.CurrencyUtil;
import bisq.core.locale.FiatCurrency;
import bisq.core.locale.GlobalSettings;
import bisq.core.locale.TradeCurrency;
import bisq.core.payment.PaymentAccount;
import bisq.core.payment.PaymentAccountUtil;
import bisq.core.setup.CoreNetworkCapabilities;
import bisq.network.p2p.network.BridgeAddressProvider;
import bisq.common.app.DevEnv;
import bisq.common.config.BaseCurrencyNetwork;
import bisq.common.config.Config;
import bisq.common.proto.persistable.PersistedDataHost;
import bisq.common.storage.Storage;
import bisq.common.util.Utilities;
import org.bitcoinj.core.Coin;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.collections.FXCollections;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;
import javafx.collections.ObservableMap;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Random;
import java.util.stream.Collectors;
import lombok.Getter;
import lombok.Setter;
import lombok.experimental.Delegate;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import javax.annotation.Nullable;
import static com.google.common.base.Preconditions.checkNotNull;
@Slf4j
@Singleton
public final class Preferences implements PersistedDataHost, BridgeAddressProvider {
private static final ArrayList<BlockChainExplorer> BTC_MAIN_NET_EXPLORERS = new ArrayList<>(Arrays.asList(
new BlockChainExplorer("mempool.space (@wiz)", "https:
new BlockChainExplorer("mempool.space Tor V3", "http:
new BlockChainExplorer("mempool.emzy.de (@emzy)", "https:
new BlockChainExplorer("mempool.emzy.de Tor V3", "http:
new BlockChainExplorer("mempool.bisq.services (@devinbileck)", "https:
new BlockChainExplorer("mempool.bisq.services Tor V3", "http:
new BlockChainExplorer("Blockstream.info", "https:
new BlockChainExplorer("Blockstream.info Tor V3", "http:
new BlockChainExplorer("OXT", "https:
new BlockChainExplorer("Bitaps", "https:
new BlockChainExplorer("Blockcypher", "https:
new BlockChainExplorer("Tradeblock", "https:
new BlockChainExplorer("Biteasy", "https:
new BlockChainExplorer("Blockonomics", "https://www.blockonomics.co/api/tx?txid=", "https://www.blockonomics.co/#/search?q="),
new BlockChainExplorer("Chainflyer", "http:
new BlockChainExplorer("Smartbit", "https:
new BlockChainExplorer("SoChain. Wow.", "https:
new BlockChainExplorer("Blockchain.info", "https:
new BlockChainExplorer("Insight", "https:
new BlockChainExplorer("Blockchair", "https:
));
private static final ArrayList<BlockChainExplorer> BTC_TEST_NET_EXPLORERS = new ArrayList<>(Arrays.asList(
new BlockChainExplorer("Blockstream.info", "https:
new BlockChainExplorer("Blockstream.info Tor V3", "http:
new BlockChainExplorer("Blockcypher", "https:
new BlockChainExplorer("Blocktrail", "https:
new BlockChainExplorer("Biteasy", "https:
new BlockChainExplorer("Smartbit", "https:
new BlockChainExplorer("SoChain. Wow.", "https:
new BlockChainExplorer("Blockchair", "https:
));
private static final ArrayList<BlockChainExplorer> BTC_DAO_TEST_NET_EXPLORERS = new ArrayList<>(Collections.singletonList(
new BlockChainExplorer("BTC DAO-testnet explorer", "https:
));
public static final ArrayList<BlockChainExplorer> BSQ_MAIN_NET_EXPLORERS = new ArrayList<>(Arrays.asList(
new BlockChainExplorer("bsq.ninja (@wiz)", "https:
new BlockChainExplorer("bsq.sqrrm.net (@sqrrm)", "https:
new BlockChainExplorer("bsq.bisq.services (@devinbileck)", "https:
new BlockChainExplorer("bsq.vante.me (@mrosseel)", "https:
new BlockChainExplorer("bsq.emzy.de (@emzy)", "https:
new BlockChainExplorer("bsq.bisq.cc (@m52go)", "https:
));
// list of XMR proof providers : this list will be used if no preference has been set
public static final List<String> getDefaultXmrProofProviders() {
if (DevEnv.isDevMode()) {
return new ArrayList<>(Arrays.asList("78.47.61.90:8081"));
} else {
// TODO we need at least 2 for release
return new ArrayList<>(Arrays.asList(
"monero3bec7m26vx6si6qo7q7imlaoz45ot5m2b5z2ppgoooo6jx2rqd.onion"));
}
}
public static final boolean USE_SYMMETRIC_SECURITY_DEPOSIT = true;
// payload is initialized so the default values are available for Property initialization.
@Setter
@Delegate(excludes = ExcludesDelegateMethods.class)
private PreferencesPayload prefPayload = new PreferencesPayload();
private boolean initialReadDone = false;
@Getter
private final BooleanProperty useAnimationsProperty = new SimpleBooleanProperty(prefPayload.isUseAnimations());
@Getter
private final IntegerProperty cssThemeProperty = new SimpleIntegerProperty(prefPayload.getCssTheme());
private final ObservableList<FiatCurrency> fiatCurrenciesAsObservable = FXCollections.observableArrayList();
private final ObservableList<CryptoCurrency> cryptoCurrenciesAsObservable = FXCollections.observableArrayList();
private final ObservableList<TradeCurrency> tradeCurrenciesAsObservable = FXCollections.observableArrayList();
private final ObservableMap<String, Boolean> dontShowAgainMapAsObservable = FXCollections.observableHashMap();
private final Storage<PreferencesPayload> storage;
private final Config config;
private final LocalBitcoinNode localBitcoinNode;
private final String btcNodesFromOptions, referralIdFromOptions,
rpcUserFromOptions, rpcPwFromOptions;
private final int blockNotifyPortFromOptions;
private final boolean fullDaoNodeFromOptions;
@Getter
private final BooleanProperty useStandbyModeProperty = new SimpleBooleanProperty(prefPayload.isUseStandbyMode());
// Constructor
@SuppressWarnings("WeakerAccess")
@Inject
public Preferences(Storage<PreferencesPayload> storage,
Config config,
LocalBitcoinNode localBitcoinNode,
@Named(Config.BTC_NODES) String btcNodesFromOptions,
@Named(Config.REFERRAL_ID) String referralId,
@Named(Config.FULL_DAO_NODE) boolean fullDaoNode,
@Named(Config.RPC_USER) String rpcUser,
@Named(Config.RPC_PASSWORD) String rpcPassword,
@Named(Config.RPC_BLOCK_NOTIFICATION_PORT) int rpcBlockNotificationPort) {
this.storage = storage;
this.config = config;
this.localBitcoinNode = localBitcoinNode;
this.btcNodesFromOptions = btcNodesFromOptions;
this.referralIdFromOptions = referralId;
this.fullDaoNodeFromOptions = fullDaoNode;
this.rpcUserFromOptions = rpcUser;
this.rpcPwFromOptions = rpcPassword;
this.blockNotifyPortFromOptions = rpcBlockNotificationPort;
useAnimationsProperty.addListener((ov) -> {
prefPayload.setUseAnimations(useAnimationsProperty.get());
GlobalSettings.setUseAnimations(prefPayload.isUseAnimations());
persist();
});
cssThemeProperty.addListener((ov) -> {
prefPayload.setCssTheme(cssThemeProperty.get());
persist();
});
useStandbyModeProperty.addListener((ov) -> {
prefPayload.setUseStandbyMode(useStandbyModeProperty.get());
persist();
});
fiatCurrenciesAsObservable.addListener((javafx.beans.Observable ov) -> {
prefPayload.getFiatCurrencies().clear();
prefPayload.getFiatCurrencies().addAll(fiatCurrenciesAsObservable);
prefPayload.getFiatCurrencies().sort(TradeCurrency::compareTo);
persist();
});
cryptoCurrenciesAsObservable.addListener((javafx.beans.Observable ov) -> {
prefPayload.getCryptoCurrencies().clear();
prefPayload.getCryptoCurrencies().addAll(cryptoCurrenciesAsObservable);
prefPayload.getCryptoCurrencies().sort(TradeCurrency::compareTo);
persist();
});
fiatCurrenciesAsObservable.addListener(this::updateTradeCurrencies);
cryptoCurrenciesAsObservable.addListener(this::updateTradeCurrencies);
}
@Override
public void readPersisted() {
PreferencesPayload persisted = storage.initAndGetPersistedWithFileName("PreferencesPayload", 100);
BaseCurrencyNetwork baseCurrencyNetwork = Config.baseCurrencyNetwork();
TradeCurrency preferredTradeCurrency;
if (persisted != null) {
prefPayload = persisted;
GlobalSettings.setLocale(new Locale(prefPayload.getUserLanguage(), prefPayload.getUserCountry().code));
GlobalSettings.setUseAnimations(prefPayload.isUseAnimations());
preferredTradeCurrency = checkNotNull(prefPayload.getPreferredTradeCurrency(), "preferredTradeCurrency must not be null");
setPreferredTradeCurrency(preferredTradeCurrency);
setFiatCurrencies(prefPayload.getFiatCurrencies());
setCryptoCurrencies(prefPayload.getCryptoCurrencies());
setBsqBlockChainExplorer(prefPayload.getBsqBlockChainExplorer());
} else {
prefPayload = new PreferencesPayload();
prefPayload.setUserLanguage(GlobalSettings.getLocale().getLanguage());
prefPayload.setUserCountry(CountryUtil.getDefaultCountry());
GlobalSettings.setLocale(new Locale(prefPayload.getUserLanguage(), prefPayload.getUserCountry().code));
preferredTradeCurrency = checkNotNull(CurrencyUtil.getCurrencyByCountryCode(prefPayload.getUserCountry().code),
"preferredTradeCurrency must not be null");
prefPayload.setPreferredTradeCurrency(preferredTradeCurrency);
setFiatCurrencies(CurrencyUtil.getMainFiatCurrencies());
setCryptoCurrencies(CurrencyUtil.getMainCryptoCurrencies());
switch (baseCurrencyNetwork.getCurrencyCode()) {
case "BTC":
setBlockChainExplorerMainNet(BTC_MAIN_NET_EXPLORERS.get(0));
setBlockChainExplorerTestNet(BTC_TEST_NET_EXPLORERS.get(0));
break;
default:
throw new RuntimeException("BaseCurrencyNetwork not defined. BaseCurrencyNetwork=" + baseCurrencyNetwork);
}
prefPayload.setDirectoryChooserPath(Utilities.getSystemHomeDirectory());
prefPayload.setOfferBookChartScreenCurrencyCode(preferredTradeCurrency.getCode());
prefPayload.setTradeChartsScreenCurrencyCode(preferredTradeCurrency.getCode());
prefPayload.setBuyScreenCurrencyCode(preferredTradeCurrency.getCode());
prefPayload.setSellScreenCurrencyCode(preferredTradeCurrency.getCode());
}
// We don't want to pass Preferences to all popups where the don't show again checkbox is used, so we use
// that static lookup class to avoid static access to the Preferences directly.
DontShowAgainLookup.setPreferences(this);
GlobalSettings.setDefaultTradeCurrency(preferredTradeCurrency);
// set all properties
useAnimationsProperty.set(prefPayload.isUseAnimations());
useStandbyModeProperty.set(prefPayload.isUseStandbyMode());
cssThemeProperty.set(prefPayload.getCssTheme());
// if no valid Bitcoin block explorer is set, select the 1st valid Bitcoin block explorer
ArrayList<BlockChainExplorer> btcExplorers = getBlockChainExplorers();
if (!blockExplorerExists(btcExplorers, getBlockChainExplorer()))
setBlockChainExplorer(btcExplorers.get(0));
// if no valid BSQ block explorer is set, randomly select a valid BSQ block explorer
ArrayList<BlockChainExplorer> bsqExplorers = getBsqBlockChainExplorers();
if (!blockExplorerExists(bsqExplorers, getBsqBlockChainExplorer()))
setBsqBlockChainExplorer(bsqExplorers.get((new Random()).nextInt(bsqExplorers.size())));
tradeCurrenciesAsObservable.addAll(prefPayload.getFiatCurrencies());
tradeCurrenciesAsObservable.addAll(prefPayload.getCryptoCurrencies());
dontShowAgainMapAsObservable.putAll(getDontShowAgainMap());
// Override settings with options if set
if (config.useTorForBtcOptionSetExplicitly)
setUseTorForBitcoinJ(config.useTorForBtc);
if (btcNodesFromOptions != null && !btcNodesFromOptions.isEmpty()) {
if (getBitcoinNodes() != null && !getBitcoinNodes().equals(btcNodesFromOptions)) {
log.warn("The Bitcoin node(s) from the program argument and the one(s) persisted in the UI are different. " +
"The Bitcoin node(s) {} from the program argument will be used.", btcNodesFromOptions);
}
setBitcoinNodes(btcNodesFromOptions);
setBitcoinNodesOptionOrdinal(BtcNodes.BitcoinNodesOption.CUSTOM.ordinal());
}
if (referralIdFromOptions != null && !referralIdFromOptions.isEmpty())
setReferralId(referralIdFromOptions);
if (prefPayload.getIgnoreDustThreshold() < Restrictions.getMinNonDustOutput().value) {
setIgnoreDustThreshold(600);
}
// For users from old versions the 4 flags a false but we want to have it true by default
// PhoneKeyAndToken is also null so we can use that to enable the flags
if (prefPayload.getPhoneKeyAndToken() == null) {
setUseSoundForMobileNotifications(true);
setUseTradeNotifications(true);
setUseMarketNotifications(true);
setUsePriceNotifications(true);
}
// We set the capability in CoreNetworkCapabilities if the program argument is set.
// If we have set it in the preferences view we handle it here.
CoreNetworkCapabilities.maybeApplyDaoFullMode(config);
initialReadDone = true;
persist();
}
// API
public void dontShowAgain(String key, boolean dontShowAgain) {
prefPayload.getDontShowAgainMap().put(key, dontShowAgain);
persist();
dontShowAgainMapAsObservable.put(key, dontShowAgain);
}
public void resetDontShowAgain() {
prefPayload.getDontShowAgainMap().clear();
persist();
dontShowAgainMapAsObservable.clear();
}
// Setter
public void setUseAnimations(boolean useAnimations) {
this.useAnimationsProperty.set(useAnimations);
}
public void setCssTheme(boolean useDarkMode) {
this.cssThemeProperty.set(useDarkMode ? 1 : 0);
}
public void addFiatCurrency(FiatCurrency tradeCurrency) {
if (!fiatCurrenciesAsObservable.contains(tradeCurrency))
fiatCurrenciesAsObservable.add(tradeCurrency);
}
public void removeFiatCurrency(FiatCurrency tradeCurrency) {
if (tradeCurrenciesAsObservable.size() > 1) {
fiatCurrenciesAsObservable.remove(tradeCurrency);
if (prefPayload.getPreferredTradeCurrency() != null &&
prefPayload.getPreferredTradeCurrency().equals(tradeCurrency))
setPreferredTradeCurrency(tradeCurrenciesAsObservable.get(0));
} else {
log.error("you cannot remove the last currency");
}
}
public void addCryptoCurrency(CryptoCurrency tradeCurrency) {
if (!cryptoCurrenciesAsObservable.contains(tradeCurrency))
cryptoCurrenciesAsObservable.add(tradeCurrency);
}
public void removeCryptoCurrency(CryptoCurrency tradeCurrency) {
if (tradeCurrenciesAsObservable.size() > 1) {
cryptoCurrenciesAsObservable.remove(tradeCurrency);
if (prefPayload.getPreferredTradeCurrency() != null &&
prefPayload.getPreferredTradeCurrency().equals(tradeCurrency))
setPreferredTradeCurrency(tradeCurrenciesAsObservable.get(0));
} else {
log.error("you cannot remove the last currency");
}
}
public void setBlockChainExplorer(BlockChainExplorer blockChainExplorer) {
if (Config.baseCurrencyNetwork().isMainnet())
setBlockChainExplorerMainNet(blockChainExplorer);
else
setBlockChainExplorerTestNet(blockChainExplorer);
}
public void setTacAccepted(boolean tacAccepted) {
prefPayload.setTacAccepted(tacAccepted);
persist();
}
public void setTacAcceptedV120(boolean tacAccepted) {
prefPayload.setTacAcceptedV120(tacAccepted);
persist();
}
// AutoConfirmSettings is currently only used for XMR. Although it could
// potentially in the future be used for others too. In the interest of flexibility
// we store it as a list in the proto definition, but in practical terms the
// application is not coded to handle more than one entry. For now this API
// to get/set AutoConfirmSettings is the gatekeeper. If in the future we adapt
// the application to manage more than one altcoin AutoConfirmSettings then
// this API will need to incorporate lookup by coin.
public AutoConfirmSettings getAutoConfirmSettings() {
if (prefPayload.getAutoConfirmSettingsList().size() == 0) {
// default values for AutoConfirmSettings when persisted payload is empty:
prefPayload.getAutoConfirmSettingsList().add(new AutoConfirmSettings(
false, 5, Coin.COIN.value, getDefaultXmrProofProviders(), "XMR"));
}
return prefPayload.getAutoConfirmSettingsList().get(0);
}
public void setAutoConfirmSettings(AutoConfirmSettings autoConfirmSettings) {
// see above comment regarding only one entry in this list currently
prefPayload.getAutoConfirmSettingsList().clear();
prefPayload.getAutoConfirmSettingsList().add(autoConfirmSettings);
persist();
}
public void setAutoConfServiceAddresses(List<String> serviceAddresses) {
AutoConfirmSettings x = this.getAutoConfirmSettings();
this.setAutoConfirmSettings(new AutoConfirmSettings(
x.enabled, x.requiredConfirmations, x.tradeLimit, serviceAddresses, x.currencyCode));
}
private void persist() {
if (initialReadDone)
storage.queueUpForSave(prefPayload);
}
public void setUserLanguage(@NotNull String userLanguageCode) {
prefPayload.setUserLanguage(userLanguageCode);
if (prefPayload.getUserCountry() != null && prefPayload.getUserLanguage() != null)
GlobalSettings.setLocale(new Locale(prefPayload.getUserLanguage(), prefPayload.getUserCountry().code));
persist();
}
public void setUserCountry(@NotNull Country userCountry) {
prefPayload.setUserCountry(userCountry);
if (prefPayload.getUserLanguage() != null)
GlobalSettings.setLocale(new Locale(prefPayload.getUserLanguage(), userCountry.code));
persist();
}
public void setPreferredTradeCurrency(TradeCurrency preferredTradeCurrency) {
if (preferredTradeCurrency != null) {
prefPayload.setPreferredTradeCurrency(preferredTradeCurrency);
GlobalSettings.setDefaultTradeCurrency(preferredTradeCurrency);
persist();
}
}
public void setUseTorForBitcoinJ(boolean useTorForBitcoinJ) {
prefPayload.setUseTorForBitcoinJ(useTorForBitcoinJ);
persist();
}
public void setShowOwnOffersInOfferBook(boolean showOwnOffersInOfferBook) {
prefPayload.setShowOwnOffersInOfferBook(showOwnOffersInOfferBook);
persist();
}
public void setMaxPriceDistanceInPercent(double maxPriceDistanceInPercent) {
prefPayload.setMaxPriceDistanceInPercent(maxPriceDistanceInPercent);
persist();
}
public void setBackupDirectory(String backupDirectory) {
prefPayload.setBackupDirectory(backupDirectory);
persist();
}
public void setAutoSelectArbitrators(boolean autoSelectArbitrators) {
prefPayload.setAutoSelectArbitrators(autoSelectArbitrators);
persist();
}
public void setUsePercentageBasedPrice(boolean usePercentageBasedPrice) {
prefPayload.setUsePercentageBasedPrice(usePercentageBasedPrice);
persist();
}
public void setTagForPeer(String fullAddress, String tag) {
prefPayload.getPeerTagMap().put(fullAddress, tag);
persist();
}
public void setOfferBookChartScreenCurrencyCode(String offerBookChartScreenCurrencyCode) {
prefPayload.setOfferBookChartScreenCurrencyCode(offerBookChartScreenCurrencyCode);
persist();
}
public void setBuyScreenCurrencyCode(String buyScreenCurrencyCode) {
prefPayload.setBuyScreenCurrencyCode(buyScreenCurrencyCode);
persist();
}
public void setSellScreenCurrencyCode(String sellScreenCurrencyCode) {
prefPayload.setSellScreenCurrencyCode(sellScreenCurrencyCode);
persist();
}
public void setIgnoreTradersList(List<String> ignoreTradersList) {
prefPayload.setIgnoreTradersList(ignoreTradersList);
persist();
}
public void setDirectoryChooserPath(String directoryChooserPath) {
prefPayload.setDirectoryChooserPath(directoryChooserPath);
persist();
}
public void setTradeChartsScreenCurrencyCode(String tradeChartsScreenCurrencyCode) {
prefPayload.setTradeChartsScreenCurrencyCode(tradeChartsScreenCurrencyCode);
persist();
}
public void setTradeStatisticsTickUnitIndex(int tradeStatisticsTickUnitIndex) {
prefPayload.setTradeStatisticsTickUnitIndex(tradeStatisticsTickUnitIndex);
persist();
}
public void setSortMarketCurrenciesNumerically(boolean sortMarketCurrenciesNumerically) {
prefPayload.setSortMarketCurrenciesNumerically(sortMarketCurrenciesNumerically);
persist();
}
public void setBitcoinNodes(String bitcoinNodes) {
prefPayload.setBitcoinNodes(bitcoinNodes);
persist();
}
public void setUseCustomWithdrawalTxFee(boolean useCustomWithdrawalTxFee) {
prefPayload.setUseCustomWithdrawalTxFee(useCustomWithdrawalTxFee);
persist();
}
public void setWithdrawalTxFeeInBytes(long withdrawalTxFeeInBytes) {
prefPayload.setWithdrawalTxFeeInBytes(withdrawalTxFeeInBytes);
persist();
}
public void setBuyerSecurityDepositAsPercent(double buyerSecurityDepositAsPercent, PaymentAccount paymentAccount) {
double max = Restrictions.getMaxBuyerSecurityDepositAsPercent();
double min = Restrictions.getMinBuyerSecurityDepositAsPercent();
if (PaymentAccountUtil.isCryptoCurrencyAccount(paymentAccount))
prefPayload.setBuyerSecurityDepositAsPercentForCrypto(Math.min(max, Math.max(min, buyerSecurityDepositAsPercent)));
else
prefPayload.setBuyerSecurityDepositAsPercent(Math.min(max, Math.max(min, buyerSecurityDepositAsPercent)));
persist();
}
public void setSelectedPaymentAccountForCreateOffer(@Nullable PaymentAccount paymentAccount) {
prefPayload.setSelectedPaymentAccountForCreateOffer(paymentAccount);
persist();
}
public void setPayFeeInBtc(boolean payFeeInBtc) {
prefPayload.setPayFeeInBtc(payFeeInBtc);
persist();
}
private void setFiatCurrencies(List<FiatCurrency> currencies) {
fiatCurrenciesAsObservable.setAll(currencies.stream()
.map(fiatCurrency -> new FiatCurrency(fiatCurrency.getCurrency()))
.distinct().collect(Collectors.toList()));
}
private void setCryptoCurrencies(List<CryptoCurrency> currencies) {
cryptoCurrenciesAsObservable.setAll(currencies.stream().distinct().collect(Collectors.toList()));
}
public void setBsqBlockChainExplorer(BlockChainExplorer bsqBlockChainExplorer) {
prefPayload.setBsqBlockChainExplorer(bsqBlockChainExplorer);
persist();
}
private void setBlockChainExplorerTestNet(BlockChainExplorer blockChainExplorerTestNet) {
prefPayload.setBlockChainExplorerTestNet(blockChainExplorerTestNet);
persist();
}
private void setBlockChainExplorerMainNet(BlockChainExplorer blockChainExplorerMainNet) {
prefPayload.setBlockChainExplorerMainNet(blockChainExplorerMainNet);
persist();
}
public void setResyncSpvRequested(boolean resyncSpvRequested) {
prefPayload.setResyncSpvRequested(resyncSpvRequested);
// We call that before shutdown so we dont want a delay here
storage.queueUpForSave(prefPayload, 1);
}
public void setBridgeAddresses(List<String> bridgeAddresses) {
prefPayload.setBridgeAddresses(bridgeAddresses);
// We call that before shutdown so we dont want a delay here
storage.queueUpForSave(prefPayload, 1);
}
// Only used from PB but keep it explicit as it may be used from the client and then we want to persist
public void setPeerTagMap(Map<String, String> peerTagMap) {
prefPayload.setPeerTagMap(peerTagMap);
persist();
}
public void setBridgeOptionOrdinal(int bridgeOptionOrdinal) {
prefPayload.setBridgeOptionOrdinal(bridgeOptionOrdinal);
persist();
}
public void setTorTransportOrdinal(int torTransportOrdinal) {
prefPayload.setTorTransportOrdinal(torTransportOrdinal);
persist();
}
public void setCustomBridges(String customBridges) {
prefPayload.setCustomBridges(customBridges);
persist();
}
public void setBitcoinNodesOptionOrdinal(int bitcoinNodesOptionOrdinal) {
prefPayload.setBitcoinNodesOptionOrdinal(bitcoinNodesOptionOrdinal);
persist();
}
public void setReferralId(String referralId) {
prefPayload.setReferralId(referralId);
persist();
}
public void setPhoneKeyAndToken(String phoneKeyAndToken) {
prefPayload.setPhoneKeyAndToken(phoneKeyAndToken);
persist();
}
public void setUseSoundForMobileNotifications(boolean value) {
prefPayload.setUseSoundForMobileNotifications(value);
persist();
}
public void setUseTradeNotifications(boolean value) {
prefPayload.setUseTradeNotifications(value);
persist();
}
public void setUseMarketNotifications(boolean value) {
prefPayload.setUseMarketNotifications(value);
persist();
}
public void setUsePriceNotifications(boolean value) {
prefPayload.setUsePriceNotifications(value);
persist();
}
public void setUseStandbyMode(boolean useStandbyMode) {
this.useStandbyModeProperty.set(useStandbyMode);
}
public void setTakeOfferSelectedPaymentAccountId(String value) {
prefPayload.setTakeOfferSelectedPaymentAccountId(value);
persist();
}
public void setDaoFullNode(boolean value) {
// We only persist if we have not set the program argument
if (config.fullDaoNodeOptionSetExplicitly) {
prefPayload.setDaoFullNode(value);
persist();
}
}
public void setRpcUser(String value) {
// We only persist if we have not set the program argument
if (!rpcUserFromOptions.isEmpty()) {
prefPayload.setRpcUser(value);
persist();
}
prefPayload.setRpcUser(value);
persist();
}
public void setRpcPw(String value) {
// We only persist if we have not set the program argument
if (rpcPwFromOptions.isEmpty()) {
prefPayload.setRpcPw(value);
persist();
}
}
public void setBlockNotifyPort(int value) {
// We only persist if we have not set the program argument
if (blockNotifyPortFromOptions == Config.UNSPECIFIED_PORT) {
prefPayload.setBlockNotifyPort(value);
persist();
}
}
public void setIgnoreDustThreshold(int value) {
prefPayload.setIgnoreDustThreshold(value);
persist();
}
// Getter
public BooleanProperty useAnimationsProperty() {
return useAnimationsProperty;
}
public ObservableList<FiatCurrency> getFiatCurrenciesAsObservable() {
return fiatCurrenciesAsObservable;
}
public ObservableList<CryptoCurrency> getCryptoCurrenciesAsObservable() {
return cryptoCurrenciesAsObservable;
}
public ObservableList<TradeCurrency> getTradeCurrenciesAsObservable() {
return tradeCurrenciesAsObservable;
}
public ObservableMap<String, Boolean> getDontShowAgainMapAsObservable() {
return dontShowAgainMapAsObservable;
}
public BlockChainExplorer getBlockChainExplorer() {
BaseCurrencyNetwork baseCurrencyNetwork = Config.baseCurrencyNetwork();
switch (baseCurrencyNetwork) {
case BTC_MAINNET:
return prefPayload.getBlockChainExplorerMainNet();
case BTC_TESTNET:
case BTC_REGTEST:
return prefPayload.getBlockChainExplorerTestNet();
case BTC_DAO_TESTNET:
return BTC_DAO_TEST_NET_EXPLORERS.get(0);
case BTC_DAO_BETANET:
return prefPayload.getBlockChainExplorerMainNet();
case BTC_DAO_REGTEST:
return BTC_DAO_TEST_NET_EXPLORERS.get(0);
default:
throw new RuntimeException("BaseCurrencyNetwork not defined. BaseCurrencyNetwork=" + baseCurrencyNetwork);
}
}
public ArrayList<BlockChainExplorer> getBlockChainExplorers() {
BaseCurrencyNetwork baseCurrencyNetwork = Config.baseCurrencyNetwork();
switch (baseCurrencyNetwork) {
case BTC_MAINNET:
return BTC_MAIN_NET_EXPLORERS;
case BTC_TESTNET:
case BTC_REGTEST:
return BTC_TEST_NET_EXPLORERS;
case BTC_DAO_TESTNET:
return BTC_DAO_TEST_NET_EXPLORERS;
case BTC_DAO_BETANET:
return BTC_MAIN_NET_EXPLORERS;
case BTC_DAO_REGTEST:
return BTC_DAO_TEST_NET_EXPLORERS;
default:
throw new RuntimeException("BaseCurrencyNetwork not defined. BaseCurrencyNetwork=" + baseCurrencyNetwork);
}
}
public ArrayList<BlockChainExplorer> getBsqBlockChainExplorers() {
return BSQ_MAIN_NET_EXPLORERS;
}
public boolean showAgain(String key) {
return !prefPayload.getDontShowAgainMap().containsKey(key) || !prefPayload.getDontShowAgainMap().get(key);
}
public boolean getUseTorForBitcoinJ() {
// We override the useTorForBitcoinJ and set it to false if we will use a
// localhost Bitcoin node or if we are not on mainnet, unless the useTorForBtc
// parameter is explicitly provided. On testnet there are very few Bitcoin tor
// nodes and we don't provide tor nodes.
if ((!Config.baseCurrencyNetwork().isMainnet()
|| localBitcoinNode.shouldBeUsed())
&& !config.useTorForBtcOptionSetExplicitly)
return false;
else
return prefPayload.isUseTorForBitcoinJ();
}
public double getBuyerSecurityDepositAsPercent(PaymentAccount paymentAccount) {
double value = PaymentAccountUtil.isCryptoCurrencyAccount(paymentAccount) ?
prefPayload.getBuyerSecurityDepositAsPercentForCrypto() : prefPayload.getBuyerSecurityDepositAsPercent();
if (value < Restrictions.getMinBuyerSecurityDepositAsPercent()) {
value = Restrictions.getMinBuyerSecurityDepositAsPercent();
setBuyerSecurityDepositAsPercent(value, paymentAccount);
}
return value == 0 ? Restrictions.getDefaultBuyerSecurityDepositAsPercent() : value;
}
//TODO remove and use isPayFeeInBtc instead
public boolean getPayFeeInBtc() {
return prefPayload.isPayFeeInBtc();
}
@Override
@Nullable
public List<String> getBridgeAddresses() {
return prefPayload.getBridgeAddresses();
}
public long getWithdrawalTxFeeInBytes() {
return Math.max(prefPayload.getWithdrawalTxFeeInBytes(), Config.baseCurrencyNetwork().getDefaultMinFeePerByte());
}
public boolean isDaoFullNode() {
if (config.fullDaoNodeOptionSetExplicitly) {
return fullDaoNodeFromOptions;
} else {
return prefPayload.isDaoFullNode();
}
}
public String getRpcUser() {
if (!rpcUserFromOptions.isEmpty()) {
return rpcUserFromOptions;
} else {
return prefPayload.getRpcUser();
}
}
public String getRpcPw() {
if (!rpcPwFromOptions.isEmpty()) {
return rpcPwFromOptions;
} else {
return prefPayload.getRpcPw();
}
}
public int getBlockNotifyPort() {
if (blockNotifyPortFromOptions != Config.UNSPECIFIED_PORT) {
try {
return blockNotifyPortFromOptions;
} catch (Throwable ignore) {
return 0;
}
} else {
return prefPayload.getBlockNotifyPort();
}
}
// Private
private void updateTradeCurrencies(ListChangeListener.Change<? extends TradeCurrency> change) {
change.next();
if (change.wasAdded() && change.getAddedSize() == 1 && initialReadDone)
tradeCurrenciesAsObservable.add(change.getAddedSubList().get(0));
else if (change.wasRemoved() && change.getRemovedSize() == 1 && initialReadDone)
tradeCurrenciesAsObservable.remove(change.getRemoved().get(0));
}
private boolean blockExplorerExists(ArrayList<BlockChainExplorer> explorers,
BlockChainExplorer explorer) {
if (explorer != null && explorers != null && explorers.size() > 0)
for (int i = 0; i < explorers.size(); i++)
if (explorers.get(i).name.equals(explorer.name))
return true;
return false;
}
private interface ExcludesDelegateMethods {
void setTacAccepted(boolean tacAccepted);
void setUseAnimations(boolean useAnimations);
void setCssTheme(int cssTheme);
void setUserLanguage(@NotNull String userLanguageCode);
void setUserCountry(@NotNull Country userCountry);
void setPreferredTradeCurrency(TradeCurrency preferredTradeCurrency);
void setUseTorForBitcoinJ(boolean useTorForBitcoinJ);
void setShowOwnOffersInOfferBook(boolean showOwnOffersInOfferBook);
void setMaxPriceDistanceInPercent(double maxPriceDistanceInPercent);
void setBackupDirectory(String backupDirectory);
void setAutoSelectArbitrators(boolean autoSelectArbitrators);
void setUsePercentageBasedPrice(boolean usePercentageBasedPrice);
void setTagForPeer(String hostName, String tag);
void setOfferBookChartScreenCurrencyCode(String offerBookChartScreenCurrencyCode);
void setBuyScreenCurrencyCode(String buyScreenCurrencyCode);
void setSellScreenCurrencyCode(String sellScreenCurrencyCode);
void setIgnoreTradersList(List<String> ignoreTradersList);
void setDirectoryChooserPath(String directoryChooserPath);
void setTradeChartsScreenCurrencyCode(String tradeChartsScreenCurrencyCode);
void setTradeStatisticsTickUnitIndex(int tradeStatisticsTickUnitIndex);
void setSortMarketCurrenciesNumerically(boolean sortMarketCurrenciesNumerically);
void setBitcoinNodes(String bitcoinNodes);
void setUseCustomWithdrawalTxFee(boolean useCustomWithdrawalTxFee);
void setWithdrawalTxFeeInBytes(long withdrawalTxFeeInBytes);
void setSelectedPaymentAccountForCreateOffer(@Nullable PaymentAccount paymentAccount);
void setBsqBlockChainExplorer(BlockChainExplorer bsqBlockChainExplorer);
void setPayFeeInBtc(boolean payFeeInBtc);
void setFiatCurrencies(List<FiatCurrency> currencies);
void setCryptoCurrencies(List<CryptoCurrency> currencies);
void setBlockChainExplorerTestNet(BlockChainExplorer blockChainExplorerTestNet);
void setBlockChainExplorerMainNet(BlockChainExplorer blockChainExplorerMainNet);
void setResyncSpvRequested(boolean resyncSpvRequested);
void setDontShowAgainMap(Map<String, Boolean> dontShowAgainMap);
void setPeerTagMap(Map<String, String> peerTagMap);
void setBridgeAddresses(List<String> bridgeAddresses);
void setBridgeOptionOrdinal(int bridgeOptionOrdinal);
void setTorTransportOrdinal(int torTransportOrdinal);
void setCustomBridges(String customBridges);
void setBitcoinNodesOptionOrdinal(int bitcoinNodesOption);
void setReferralId(String referralId);
void setPhoneKeyAndToken(String phoneKeyAndToken);
void setUseSoundForMobileNotifications(boolean value);
void setUseTradeNotifications(boolean value);
void setUseMarketNotifications(boolean value);
void setUsePriceNotifications(boolean value);
List<String> getBridgeAddresses();
long getWithdrawalTxFeeInBytes();
void setUseStandbyMode(boolean useStandbyMode);
void setTakeOfferSelectedPaymentAccountId(String value);
void setIgnoreDustThreshold(int value);
void setBuyerSecurityDepositAsPercent(double buyerSecurityDepositAsPercent);
double getBuyerSecurityDepositAsPercent();
void setDaoFullNode(boolean value);
void setRpcUser(String value);
void setRpcPw(String value);
void setBlockNotifyPort(int value);
boolean isDaoFullNode();
String getRpcUser();
String getRpcPw();
int getBlockNotifyPort();
void setTacAcceptedV120(boolean tacAccepted);
void setAutoConfirmSettings(AutoConfirmSettings autoConfirmSettings);
}
}
|
package hudson.slaves;
import jenkins.model.Jenkins;
import hudson.Functions;
import hudson.model.Computer;
import hudson.model.User;
import org.acegisecurity.Authentication;
import org.jvnet.localizer.Localizable;
import org.kohsuke.stapler.export.ExportedBean;
import org.kohsuke.stapler.export.Exported;
/**
* Represents a cause that puts a {@linkplain Computer#isOffline() computer offline}.
*
* <h2>Views</h2>
* <p>
* {@link OfflineCause} must have <tt>cause.jelly</tt> that renders a cause
* into HTML. This is used to tell users why the node is put offline.
* This view should render a block element like DIV.
*
* @author Kohsuke Kawaguchi
* @since 1.320
*/
@ExportedBean
public abstract class OfflineCause {
/**
* {@link OfflineCause} that renders a static text,
* but without any further UI.
*/
public static class SimpleOfflineCause extends OfflineCause {
public final Localizable description;
private SimpleOfflineCause(Localizable description) {
this.description = description;
}
@Exported(name="description") @Override
public String toString() {
return description.toString();
}
}
public static OfflineCause create(Localizable d) {
if (d==null) return null;
return new SimpleOfflineCause(d);
}
/**
* Caused by unexpected channel termination.
*/
public static class ChannelTermination extends OfflineCause {
@Exported
public final Exception cause;
public ChannelTermination(Exception cause) {
this.cause = cause;
}
public String getShortDescription() {
return cause.toString();
}
@Override public String toString() {
return Messages.OfflineCause_connection_was_broken_(Functions.printThrowable(cause));
}
}
/**
* Caused by failure to launch.
*/
public static class LaunchFailed extends OfflineCause {
@Override
public String toString() {
return Messages.OfflineCause_LaunchFailed();
}
}
/**
* Taken offline by user.
* @since 1.551
*/
public static class UserCause extends SimpleOfflineCause {
private final User user;
public UserCause(User user, String message) {
super(hudson.slaves.Messages._SlaveComputer_DisconnectedBy(
user.getId(),
message != null ? " : " + message : ""
));
this.user = user;
}
public User getUser() {
return user;
}
}
public static class ByCLI extends UserCause {
@Exported
public final String message;
public ByCLI(String message) {
super(User.current(), message);
this.message = message;
}
}
}
|
package org.cache2k.impl;
import org.cache2k.BulkCacheSource;
import org.cache2k.CacheEntry;
import org.cache2k.CacheException;
import org.cache2k.CacheMisconfigurationException;
import org.cache2k.ClosableIterator;
import org.cache2k.EntryExpiryCalculator;
import org.cache2k.ExceptionExpiryCalculator;
import org.cache2k.ExperimentalBulkCacheSource;
import org.cache2k.Cache;
import org.cache2k.CacheConfig;
import org.cache2k.MutableCacheEntry;
import org.cache2k.RefreshController;
import org.cache2k.StorageConfiguration;
import org.cache2k.ValueWithExpiryTime;
import org.cache2k.impl.threading.Futures;
import org.cache2k.impl.threading.LimitedPooledExecutor;
import org.cache2k.impl.timer.GlobalTimerService;
import org.cache2k.impl.timer.TimerService;
import org.cache2k.impl.util.ThreadDump;
import org.cache2k.CacheSourceWithMetaInfo;
import org.cache2k.CacheSource;
import org.cache2k.PropagatedCacheException;
import org.cache2k.storage.StorageEntry;
import org.cache2k.impl.util.Log;
import org.cache2k.impl.util.TunableConstants;
import org.cache2k.impl.util.TunableFactory;
import java.lang.reflect.Array;
import java.security.SecureRandom;
import java.util.AbstractList;
import java.util.AbstractMap;
import java.util.AbstractSet;
import java.util.Arrays;
import java.util.BitSet;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.Timer;
import java.util.concurrent.Executor;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
/**
* Foundation for all cache variants. All common functionality is in here.
* For a (in-memory) cache we need three things: a fast hash table implementation, an
* LRU list (a simple double linked list), and a fast timer.
* The variants implement different eviction strategies.
*
* <p>Locking: The cache has a single structure lock obtained via {@link #lock} and also
* locks on each entry for operations on it. Though, mutation operations that happen on a
* single entry get serialized.
*
* @author Jens Wilke; created: 2013-07-09
*/
@SuppressWarnings({"unchecked", "SynchronizationOnLocalVariableOrMethodParameter"})
public abstract class BaseCache<E extends BaseCache.Entry, K, T>
implements Cache<K, T>, CanCheckIntegrity, Iterable<CacheEntry<K, T>>, StorageAdapter.Parent {
static final Random SEED_RANDOM = new Random(new SecureRandom().nextLong());
static int cacheCnt = 0;
protected static final Tunable TUNABLE = TunableFactory.get(Tunable.class);
/**
* Instance of expiry calculator that extracts the expiry time from the value.
*/
final static EntryExpiryCalculator<?, ValueWithExpiryTime> ENTRY_EXPIRY_CALCULATOR_FROM_VALUE = new
EntryExpiryCalculator<Object, ValueWithExpiryTime>() {
@Override
public long calculateExpiryTime(
Object _key, ValueWithExpiryTime _value, long _fetchTime,
CacheEntry<Object, ValueWithExpiryTime> _oldEntry) {
return _value.getCacheExpiryTime();
}
};
protected int hashSeed;
{
if (TUNABLE.disableHashRandomization) {
hashSeed = TUNABLE.hashSeed;
} else {
hashSeed = SEED_RANDOM.nextInt();
}
}
/** Maximum amount of elements in cache */
protected int maxSize = 5000;
protected String name;
protected CacheManagerImpl manager;
protected CacheSourceWithMetaInfo<K, T> source;
/** Statistics */
/** Time in milliseconds we keep an element */
protected long maxLinger = 10 * 60 * 1000;
protected long exceptionMaxLinger = 1 * 60 * 1000;
protected EntryExpiryCalculator<K, T> entryExpiryCalculator;
protected ExceptionExpiryCalculator<K> exceptionExpiryCalculator;
protected Info info;
protected long clearedTime = 0;
protected long startedTime;
protected long touchedTime;
protected int timerCancelCount = 0;
protected long keyMutationCount = 0;
protected long putCnt = 0;
protected long putNewEntryCnt = 0;
protected long removedCnt = 0;
protected long expiredKeptCnt = 0;
protected long expiredRemoveCnt = 0;
protected long evictedCnt = 0;
protected long refreshCnt = 0;
protected long suppressedExceptionCnt = 0;
protected long fetchExceptionCnt = 0;
/* that is a miss, but a hit was already counted. */
protected long peekHitNotFreshCnt = 0;
/* no heap hash hit */
protected long peekMissCnt = 0;
protected long fetchCnt = 0;
protected long fetchButHitCnt = 0;
protected long bulkGetCnt = 0;
protected long fetchMillis = 0;
protected long refreshHitCnt = 0;
protected long newEntryCnt = 0;
/**
* Loaded from storage, but the entry was not fresh and cannot be returned.
*/
protected long loadNonFreshCnt = 0;
/**
* Entry was loaded from storage and fresh.
*/
protected long loadHitCnt = 0;
/**
* Separate counter for loaded entries that needed a fetch.
*/
protected long loadNonFreshAndFetchedCnt;
protected long refreshSubmitFailedCnt = 0;
/**
* An exception that should not have happened and was not thrown to the
* application. Only used for the refresh thread yet.
*/
protected long internalExceptionCnt = 0;
/**
* Needed to correct the counter invariants, because during eviction the entry
* might be removed from the replacement list, but still in the hash.
*/
protected int evictedButInHashCnt = 0;
/**
* Storage did not contain the requested entry.
*/
protected long loadMissCnt = 0;
/**
* A newly inserted entry was removed by the eviction without the fetch to complete.
*/
protected long virginEvictCnt = 0;
protected int maximumBulkFetchSize = 100;
/**
* Structure lock of the cache. Every operation that needs a consistent structure
* of the cache or modifies it needs to synchronize on this. Since this is a global
* lock, locking on it should be avoided and any operation under the lock should be
* quick.
*/
protected final Object lock = new Object();
protected CacheRefreshThreadPool refreshPool;
protected Hash<E> mainHashCtrl;
protected E[] mainHash;
protected Hash<E> refreshHashCtrl;
protected E[] refreshHash;
protected ExperimentalBulkCacheSource<K, T> experimentalBulkCacheSource;
protected BulkCacheSource<K, T> bulkCacheSource;
protected HashSet<K> bulkKeysCurrentlyRetrieved;
protected Timer timer;
/** Stuff that we need to wait for before shutdown may complete */
protected Futures.WaitForAllFuture<?> shutdownWaitFuture;
protected boolean shutdownInitiated = false;
/**
* Flag during operation that indicates, that the cache is full and eviction needs
* to be done. Eviction is only allowed to happen after an entry is fetched, so
* at the end of an cache operation that increased the entry count we check whether
* something needs to be evicted.
*/
protected boolean evictionNeeded = false;
protected StorageAdapter storage;
protected TimerService timerService = GlobalTimerService.getInstance();
private int featureBits = 0;
private static final int SHARP_TIMEOUT_FEATURE = 1;
private static final int KEEP_AFTER_EXPIRED = 2;
private static final int SUPPRESS_EXCEPTIONS = 4;
protected final boolean hasSharpTimeout() {
return (featureBits & SHARP_TIMEOUT_FEATURE) > 0;
}
protected final boolean hasKeepAfterExpired() {
return (featureBits & KEEP_AFTER_EXPIRED) > 0;
}
protected final boolean hasSuppressExceptions() {
return (featureBits & SUPPRESS_EXCEPTIONS) > 0;
}
protected final void setFeatureBit(int _bitmask, boolean _flag) {
if (_flag) {
featureBits |= _bitmask;
} else {
featureBits &= ~_bitmask;
}
}
/**
* Enabling background refresh means also serving expired values.
*/
protected final boolean hasBackgroundRefreshAndServesExpiredValues() {
return refreshPool != null;
}
/**
* Returns name of the cache with manager name.
*/
protected String getCompleteName() {
if (manager != null) {
return manager.getName() + ":" + name;
}
return name;
}
/**
* Normally a cache itself logs nothing, so just construct when needed.
*/
protected Log getLog() {
return
Log.getLog(Cache.class.getName() + '/' + getCompleteName());
}
@Override
public void resetStorage(StorageAdapter _from, StorageAdapter to) {
synchronized (lock) {
storage = to;
}
}
/** called via reflection from CacheBuilder */
public void setCacheConfig(CacheConfig c) {
if (name != null) {
throw new IllegalStateException("already configured");
}
setName(c.getName());
maxSize = c.getMaxSize();
if (c.getHeapEntryCapacity() >= 0) {
maxSize = c.getHeapEntryCapacity();
}
if (c.isBackgroundRefresh()) {
refreshPool = CacheRefreshThreadPool.getInstance();
}
long _expiryMillis = c.getExpiryMillis();
if (_expiryMillis == Long.MAX_VALUE || _expiryMillis < 0) {
maxLinger = -1;
} else if (_expiryMillis >= 0) {
maxLinger = _expiryMillis;
}
long _exceptionExpiryMillis = c.getExceptionExpiryMillis();
if (_exceptionExpiryMillis == -1) {
if (maxLinger == -1) {
exceptionMaxLinger = -1;
} else {
exceptionMaxLinger = maxLinger / 10;
}
} else {
exceptionMaxLinger = _exceptionExpiryMillis;
}
setFeatureBit(KEEP_AFTER_EXPIRED, c.isKeepDataAfterExpired());
setFeatureBit(SHARP_TIMEOUT_FEATURE, c.isSharpExpiry());
setFeatureBit(SUPPRESS_EXCEPTIONS, c.isSuppressExceptions());
/*
if (c.isPersistent()) {
storage = new PassingStorageAdapter();
}
-*/
List<StorageConfiguration> _stores = c.getStorageModules();
if (_stores.size() == 1) {
StorageConfiguration cfg = _stores.get(0);
if (cfg.getEntryCapacity() < 0) {
cfg.setEntryCapacity(c.getMaxSize());
}
storage = new PassingStorageAdapter(this, c, _stores.get(0));
} else if (_stores.size() > 1) {
throw new UnsupportedOperationException("no aggregation support yet");
}
if (ValueWithExpiryTime.class.isAssignableFrom(c.getValueType()) &&
entryExpiryCalculator == null) {
entryExpiryCalculator =
(EntryExpiryCalculator<K, T>)
ENTRY_EXPIRY_CALCULATOR_FROM_VALUE;
}
}
public void setEntryExpiryCalculator(EntryExpiryCalculator<K, T> v) {
entryExpiryCalculator = v;
}
public void setExceptionExpiryCalculator(ExceptionExpiryCalculator<K> v) {
exceptionExpiryCalculator = v;
}
/** called via reflection from CacheBuilder */
public void setRefreshController(final RefreshController<T> lc) {
entryExpiryCalculator = new EntryExpiryCalculator<K, T>() {
@Override
public long calculateExpiryTime(K _key, T _value, long _fetchTime, CacheEntry<K, T> _oldEntry) {
if (_oldEntry != null) {
return lc.calculateNextRefreshTime(_oldEntry.getValue(), _value, _oldEntry.getLastModification(), _fetchTime);
} else {
return lc.calculateNextRefreshTime(null, _value, 0L, _fetchTime);
}
}
};
}
@SuppressWarnings("unused")
public void setSource(CacheSourceWithMetaInfo<K, T> eg) {
source = eg;
}
@SuppressWarnings("unused")
public void setSource(final CacheSource<K, T> g) {
if (g != null) {
source = new CacheSourceWithMetaInfo<K, T>() {
@Override
public T get(K key, long _currentTime, T _previousValue, long _timeLastFetched) throws Throwable {
return g.get(key);
}
};
}
}
@SuppressWarnings("unused")
public void setExperimentalBulkCacheSource(ExperimentalBulkCacheSource<K, T> g) {
experimentalBulkCacheSource = g;
}
public void setBulkCacheSource(BulkCacheSource<K, T> s) {
bulkCacheSource = s;
if (source == null) {
source = new CacheSourceWithMetaInfo<K, T>() {
@Override
public T get(final K key, final long _currentTime, final T _previousValue, final long _timeLastFetched) throws Throwable {
final CacheEntry<K, T> entry = new CacheEntry<K, T>() {
@Override
public K getKey() {
return key;
}
@Override
public T getValue() {
return _previousValue;
}
@Override
public Throwable getException() {
return null;
}
@Override
public long getLastModification() {
return _timeLastFetched;
}
};
List<CacheEntry<K, T>> _entryList = new AbstractList<CacheEntry<K, T>>() {
@Override
public CacheEntry<K, T> get(int index) {
return entry;
}
@Override
public int size() {
return 1;
}
};
return bulkCacheSource.getValues(_entryList, _currentTime).get(0);
}
};
}
}
/**
* Set the name and configure a logging, used within cache construction.
*/
public void setName(String n) {
if (n == null) {
n = this.getClass().getSimpleName() + "#" + cacheCnt++;
}
name = n;
}
/**
* Set the time in seconds after which the cache does an refresh of the
* element. -1 means the element will be hold forever.
* 0 means the element will not be cached at all.
*/
public void setExpirySeconds(int s) {
if (s < 0 || s == Integer.MAX_VALUE) {
maxLinger = -1;
return;
}
maxLinger = s * 1000;
}
public String getName() {
return name;
}
public void setCacheManager(CacheManagerImpl cm) {
manager = cm;
}
public StorageAdapter getStorage() { return storage; }
/**
* Registers the cache in a global set for the clearAllCaches function and
* registers it with the resource monitor.
*/
public void init() {
synchronized (lock) {
if (name == null) {
name = "" + cacheCnt++;
}
if (storage == null && maxSize == 0) {
throw new IllegalArgumentException("maxElements must be >0");
}
if (storage != null) {
bulkCacheSource = null;
storage.open();
}
initializeHeapCache();
initTimer();
if (refreshPool != null &&
source == null) {
throw new CacheMisconfigurationException("backgroundRefresh, but no source");
}
if (refreshPool != null && timer == null) {
if (maxLinger == 0) {
getLog().warn("Background refresh is enabled, but elements are fetched always. Disable background refresh!");
} else {
getLog().warn("Background refresh is enabled, but elements are eternal. Disable background refresh!");
}
refreshPool.destroy();
refreshPool = null;
}
}
}
/**
* Executor for evictoins / expiry from within timer callback. Never blocks.
*/
private Executor getEvictionExecutor() {
return manager.getEvictionExecutor();
}
boolean isNeedingTimer() {
return
maxLinger > 0 || entryExpiryCalculator != null ||
exceptionMaxLinger > 0 || exceptionExpiryCalculator != null;
}
/**
* Either add a timer or remove the timer if needed or not needed.
*/
private void initTimer() {
if (isNeedingTimer()) {
if (timer == null) {
timer = new Timer(name, true);
}
} else {
if (timer != null) {
timer.cancel();
timer = null;
}
}
}
/**
* Clear may be called during operation, e.g. to reset all the cache content. We must make sure
* that there is no ongoing operation when we send the clear to the storage. That is because the
* storage implementation has a guarantee that there is only one storage operation ongoing for
* one entry or key at any time. Clear, of course, affects all entries.
*/
private void processClearWithStorage() {
StorageClearTask t = new StorageClearTask();
boolean _untouchedHeapCache;
synchronized (lock) {
checkClosed();
_untouchedHeapCache = touchedTime == clearedTime && getLocalSize() == 0;
if (!storage.checkStorageStillDisconnectedForClear()) {
t.allLocalEntries = iterateAllLocalEntries();
t.allLocalEntries.setStopOnClear(false);
}
t.storage = storage;
t.storage.disconnectStorageForClear();
}
try {
if (_untouchedHeapCache) {
FutureTask<Void> f = new FutureTask<Void>(t);
updateShutdownWaitFuture(f);
f.run();
} else {
updateShutdownWaitFuture(manager.getThreadPool().execute(t));
}
} catch (Exception ex) {
throw new CacheStorageException(ex);
}
clearLocalCache();
}
protected void updateShutdownWaitFuture(Future<?> f) {
synchronized (lock) {
if (shutdownWaitFuture == null || shutdownWaitFuture.isDone()) {
shutdownWaitFuture = new Futures.WaitForAllFuture(f);
} else {
shutdownWaitFuture.add((Future) f);
}
}
}
class StorageClearTask implements LimitedPooledExecutor.NeverRunInCallingTask<Void> {
ClosableConcurrentHashEntryIterator<Entry> allLocalEntries;
StorageAdapter storage;
@Override
public Void call() {
try {
if (allLocalEntries != null) {
waitForEntryOperations();
}
storage.clearAndReconnect();
storage = null;
return null;
} catch (Throwable t) {
if (allLocalEntries != null) {
allLocalEntries.close();
}
getLog().warn("clear exception, when signalling storage", t);
storage.disable(t);
throw new CacheStorageException(t);
}
}
private void waitForEntryOperations() {
Iterator<Entry> it = allLocalEntries;
while (it.hasNext()) {
Entry e = it.next();
synchronized (e) { }
}
}
}
protected void checkClosed() {
if (isClosed()) {
throw new CacheClosedException();
}
}
public final void clear() {
if (storage != null) {
processClearWithStorage();
return;
}
clearLocalCache();
}
protected final void clearLocalCache() {
synchronized (lock) {
checkClosed();
Iterator<Entry> it = iterateAllLocalEntries();
int _count = 0;
while (it.hasNext()) {
Entry e = it.next();
e.removedFromList();
cancelExpiryTimer(e);
_count++;
}
removedCnt += getLocalSize();
initializeHeapCache();
clearedTime = System.currentTimeMillis();
touchedTime = clearedTime;
}
}
protected void initializeHeapCache() {
if (mainHashCtrl != null) {
mainHashCtrl.cleared();
refreshHashCtrl.cleared();
}
mainHashCtrl = new Hash<E>();
refreshHashCtrl = new Hash<E>();
mainHash = mainHashCtrl.init((Class<E>) newEntry().getClass());
refreshHash = refreshHashCtrl.init((Class<E>) newEntry().getClass());
if (startedTime == 0) {
startedTime = System.currentTimeMillis();
}
if (timer != null) {
timer.cancel();
timer = null;
initTimer();
}
}
public void clearTimingStatistics() {
synchronized (lock) {
fetchCnt = 0;
fetchMillis = 0;
}
}
/**
* Preparation for shutdown. Cancel all pending timer jobs e.g. for
* expiry/refresh or flushing the storage.
*/
Future<Void> cancelTimerJobs() {
synchronized (lock) {
if (timer != null) {
timer.cancel();
}
Future<Void> _waitFuture = new Futures.BusyWaitFuture<Void>() {
@Override
public boolean isDone() {
synchronized (lock) {
return getFetchesInFlight() == 0;
}
}
};
if (storage != null) {
Future<Void> f = storage.cancelTimerJobs();
if (f != null) {
_waitFuture = new Futures.WaitForAllFuture(_waitFuture, f);
}
}
return _waitFuture;
}
}
public void purge() {
if (storage != null) {
storage.purge();
}
}
public void flush() {
if (storage != null) {
storage.flush();
}
}
protected boolean isClosed() {
return shutdownInitiated;
}
/**
* Free all resources.
*/
public void destroy() {
synchronized (lock) {
if (shutdownInitiated) {
return;
}
shutdownInitiated = true;
}
Future<Void> _await = cancelTimerJobs();
try {
_await.get(TUNABLE.waitForTimerJobsSeconds, TimeUnit.SECONDS);
} catch (TimeoutException ex) {
int _fetchesInFlight;
synchronized (lock) {
_fetchesInFlight = getFetchesInFlight();
}
if (_fetchesInFlight > 0) {
getLog().warn(
"Fetches still in progress after " +
TUNABLE.waitForTimerJobsSeconds + " seconds. " +
"fetchesInFlight=" + _fetchesInFlight);
} else {
getLog().warn(
"timeout waiting for timer jobs termination" +
" (" + TUNABLE.waitForTimerJobsSeconds + " seconds)", ex);
getLog().warn("Thread dump:\n" + ThreadDump.generateThredDump());
}
getLog().warn("State: " + toString());
} catch (Exception ex) {
getLog().warn("exception waiting for timer jobs termination", ex);
}
synchronized (lock) {
mainHashCtrl.close();
refreshHashCtrl.close();
}
try {
Future<?> _future = shutdownWaitFuture;
if (_future != null) {
_future.get();
}
} catch (Exception ex) {
throw new CacheException(ex);
}
Future<Void> _waitForStorage = null;
if (storage != null) {
_waitForStorage = storage.shutdown();
}
if (_waitForStorage != null) {
try {
_waitForStorage.get();
} catch (Exception ex) {
StorageAdapter.rethrow("shutdown", ex);
}
}
synchronized (lock) {
storage = null;
}
synchronized (lock) {
if (timer != null) {
timer.cancel();
timer = null;
}
if (refreshPool != null) {
refreshPool.destroy();
refreshPool = null;
}
mainHash = refreshHash = null;
source = null;
if (manager != null) {
manager.cacheDestroyed(this);
manager = null;
}
}
}
/**
* Complete iteration of all entries in the cache, including
* storage / persisted entries. The iteration may include expired
* entries or entries with no valid data.
*/
protected ClosableIterator<Entry> iterateLocalAndStorage() {
if (storage == null) {
synchronized (lock) {
return iterateAllLocalEntries();
}
} else {
return storage.iterateAll();
}
}
@Override
public ClosableIterator<CacheEntry<K, T>> iterator() {
return new IteratorFilterEntry2Entry(iterateLocalAndStorage());
}
/**
* Filter out non valid entries and wrap each entry with a cache
* entry object.
*/
class IteratorFilterEntry2Entry implements ClosableIterator<CacheEntry<K, T>> {
ClosableIterator<Entry> iterator;
Entry entry;
IteratorFilterEntry2Entry(ClosableIterator<Entry> it) { iterator = it; }
/**
* Between hasNext() and next() an entry may be evicted or expired.
* In practise we have to deliver a next entry if we return hasNext() with
* true, furthermore, there should be no big gap between the calls to
* hasNext() and next().
*/
@Override
public boolean hasNext() {
while (iterator.hasNext()) {
entry = iterator.next();
if (entry.hasFreshData()) {
return true;
}
}
return false;
}
@Override
public void close() {
if (iterator != null) {
iterator.close();
iterator = null;
}
}
@Override
public CacheEntry<K, T> next() { return returnEntry(entry); }
@Override
public void remove() {
BaseCache.this.remove((K) entry.getKey());
}
}
protected static void removeFromList(final Entry e) {
e.prev.next = e.next;
e.next.prev = e.prev;
e.removedFromList();
}
protected static void insertInList(final Entry _head, final Entry e) {
e.prev = _head;
e.next = _head.next;
e.next.prev = e;
_head.next = e;
}
protected static final int getListEntryCount(final Entry _head) {
Entry e = _head.next;
int cnt = 0;
while (e != _head) {
cnt++;
if (e == null) {
return -cnt;
}
e = e.next;
}
return cnt;
}
protected static final <E extends Entry> void moveToFront(final E _head, final E e) {
removeFromList(e);
insertInList(_head, e);
}
protected static final <E extends Entry> E insertIntoTailCyclicList(final E _head, final E e) {
if (_head == null) {
return (E) e.shortCircuit();
}
e.next = _head;
e.prev = _head.prev;
_head.prev = e;
e.prev.next = e;
return _head;
}
protected static <E extends Entry> E removeFromCyclicList(final E _head, E e) {
if (e.next == e) {
e.removedFromList();
return null;
}
Entry _eNext = e.next;
e.prev.next = _eNext;
e.next.prev = e.prev;
e.removedFromList();
return e == _head ? (E) _eNext : _head;
}
protected static Entry removeFromCyclicList(final Entry e) {
Entry _eNext = e.next;
e.prev.next = _eNext;
e.next.prev = e.prev;
e.removedFromList();
return _eNext == e ? null : _eNext;
}
protected static int getCyclicListEntryCount(Entry e) {
if (e == null) { return 0; }
final Entry _head = e;
int cnt = 0;
do {
cnt++;
e = e.next;
if (e == null) {
return -cnt;
}
} while (e != _head);
return cnt;
}
protected static boolean checkCyclicListIntegrity(Entry e) {
if (e == null) { return true; }
Entry _head = e;
do {
if (e.next == null) {
return false;
}
if (e.next.prev == null) {
return false;
}
if (e.next.prev != e) {
return false;
}
e = e.next;
} while (e != _head);
return true;
}
/**
* Record an entry hit.
*/
protected abstract void recordHit(E e);
/**
* New cache entry, put it in the replacement algorithm structure
*/
protected abstract void insertIntoReplcamentList(E e);
/**
* Entry object factory. Return an entry of the proper entry subtype for
* the replacement/eviction algorithm.
*/
protected abstract E newEntry();
/**
* Find an entry that should be evicted. Called within structure lock.
* The replacement algorithm can actually remove the entry from the replacement
* list or keep it in the replacement list, this is detected via
* {@link org.cache2k.impl.BaseCache.Entry#isRemovedFromReplacementList()} by the
* basic cache implementation. The entry is finally removed from the cache hash
* later in time.
*
* <p/>Rationale: Within the structure lock we can check for an eviction candidate
* and may remove it from the list. However, we cannot process additional operations or
* events which affect the entry. For this, we need to acquire the lock on the entry
* first.
*/
protected E findEvictionCandidate() {
return null;
}
protected void removeEntryFromReplacementList(E e) {
removeFromList(e);
}
/**
* Check whether we have an entry in the ghost table
* remove it from ghost and insert it into the replacement list.
* null if nothing there. This may also do an optional eviction
* if the size limit of the cache is reached, because some replacement
* algorithms (ARC) do this together.
*/
protected E checkForGhost(K key, int hc) { return null; }
/**
* Implement unsynchronized lookup if it is supported by the eviction.
* If a null is returned the lookup is redone synchronized.
*/
protected E lookupEntryUnsynchronized(K key, int hc) { return null; }
@Override
public T get(K key) {
return returnValue(getEntryInternal(key));
}
/**
* Wrap entry in a separate object instance. We can return the entry directly, however we lock on
* the entry object.
*/
protected CacheEntry<K, T> returnEntry(final Entry<E, K, T> e) {
if (e == null) {
return null;
}
CacheEntry<K,T> ce = new CacheEntry<K, T>() {
@Override
public K getKey() { return e.getKey(); }
@Override
public T getValue() { return e.getValue(); }
@Override
public Throwable getException() { return e.getException(); }
@Override
public long getLastModification() { return e.getLastModification(); }
@Override
public String toString() {
return "CacheEntry(" +
"key=" + getKey() + ", " +
"value=" + getValue() + ", " +
((getException() != null) ? "exception=" + e.getException() + ", " : "") +
"lastModification='" + (new java.sql.Timestamp(getLastModification())) + "')";
}
};
return ce;
}
public CacheEntry<K, T> getEntry(K key) {
return returnEntry(getEntryInternal(key));
}
protected E getEntryInternal(K key) {
int _spinCount = TUNABLE.maximumEntryLockSpins;
for (;;) {
if (_spinCount-- <= 0) { throw new CacheLockSpinsExceededError(); }
E e = lookupOrNewEntrySynchronized(key);
if (e.hasFreshData()) { return e; }
synchronized (e) {
if (!e.hasFreshData()) {
if (e.isRemovedState()) {
continue;
}
fetch(e);
}
}
evictEventually();
return e;
}
}
/**
* Insert the storage entry in the heap cache and return it. Used when storage entries
* are queried. We need to check whether the entry is present meanwhile, get the entry lock
* and maybe fetch it from the source. Doubles with {@link #getEntryInternal(Object)}
* except we do not need to retrieve the data from the storage again.
*
* @param _needsFetch if true the entry is fetched from CacheSource when expired.
* @return a cache entry is always returned, however, it may be outdated
*/
protected Entry insertEntryFromStorage(StorageEntry se, boolean _needsFetch) {
int _spinCount = TUNABLE.maximumEntryLockSpins;
for (;;) {
if (_spinCount-- <= 0) { throw new CacheLockSpinsExceededError(); }
E e = lookupOrNewEntrySynchronized((K) se.getKey());
if (e.hasFreshData()) { return e; }
synchronized (e) {
if (!e.isDataValidState()) {
if (e.isRemovedState()) {
continue;
}
insertEntryFromStorage(se, e, _needsFetch);
}
}
evictEventually();
return e;
}
}
/**
* Insert a cache entry for the given key and run action under the entry
* lock. If the cache entry has fresh data, we do not run the action.
* Called from storage. The entry referenced by the key is expired and
* will be purged.
*/
protected void lockAndRunForPurge(Object key, Runnable _action) {
int _spinCount = TUNABLE.maximumEntryLockSpins;
for (;;) {
if (_spinCount-- <= 0) { throw new CacheLockSpinsExceededError(); }
E e = lookupOrNewEntrySynchronized((K) key);
if (e.hasFreshData()) { return; }
synchronized (e) {
if (!e.isDataValidState()) {
if (e.isRemovedState()) {
continue;
}
_action.run();
if (e.isVirgin()) {
evictEntryFromHeap(e);
}
}
}
break;
}
}
protected final void evictEventually() {
while (evictionNeeded) {
E e;
synchronized (lock) {
if (getLocalSize() <= maxSize) {
evictionNeeded = false;
return;
}
e = findEvictionCandidate();
if (e.isRemovedFromReplacementList()) {
evictedButInHashCnt++;
}
}
synchronized (e) {
if (e.isRemovedState()) {
continue;
}
boolean _shouldStore =
(storage != null) &&
((hasKeepAfterExpired() && (e.getValueExpiryTime() > 0)) || e.hasFreshData());
if (_shouldStore) {
storage.evict(e);
}
evictEntryFromHeap(e);
}
}
}
private void evictEntryFromHeap(E e) {
synchronized (lock) {
if (e.isRemovedFromReplacementList()) {
if (removeEntryFromHash(e)) {
evictedButInHashCnt
evictedCnt++;
}
} else {
if (removeEntry(e)) {
evictedCnt++;
}
}
evictionNeeded = getLocalSize() > maxSize;
}
}
/**
* Remove the entry from the hash and the replacement list.
* There is a race condition to catch: The eviction may run
* in a parallel thread and may have already selected this
* entry.
*/
protected boolean removeEntry(E e) {
if (!e.isRemovedFromReplacementList()) {
removeEntryFromReplacementList(e);
}
return removeEntryFromHash(e);
}
/**
* Return the entry, if it is in the cache, without invoking the
* cache source.
*
* <p>The cache storage is asked whether the entry is present.
* If the entry is not present, this result is cached in the local
* cache.
*/
protected E peekEntryInternal(K key) {
final int hc = modifiedHash(key.hashCode());
int _spinCount = TUNABLE.maximumEntryLockSpins;
for (;;) {
if (_spinCount-- <= 0) { throw new CacheLockSpinsExceededError(); }
E e = lookupEntryUnsynchronized(key, hc);
if (e == null) {
synchronized (lock) {
e = lookupEntry(key, hc);
if (e == null && storage != null) {
e = newEntry(key, hc);
}
}
}
if (e == null) {
peekMissCnt++;
return null;
}
if (e.hasFreshData()) { return e; }
boolean _hasFreshData = false;
if (storage != null) {
synchronized (e) {
_hasFreshData = e.hasFreshData();
if (!_hasFreshData) {
if (e.isRemovedState()) {
continue;
}
fetchWithStorage(e, false);
_hasFreshData = e.hasFreshData();
}
}
}
evictEventually();
if (_hasFreshData) {
return e;
}
peekHitNotFreshCnt++;
return null;
}
}
@Override
public T peek(K key) {
E e = peekEntryInternal(key);
if (e != null) {
return returnValue(e);
}
return null;
}
@Override
public CacheEntry<K, T> peekEntry(K key) {
return returnEntry(peekEntryInternal(key));
}
@Override
public boolean putIfAbsent(K key, T value) {
int _spinCount = TUNABLE.maximumEntryLockSpins;
boolean _success = false;
for (;;) {
if (_spinCount-- <= 0) { throw new CacheLockSpinsExceededError(); }
E e = lookupOrNewEntrySynchronized(key);
synchronized (e) {
if (e.isRemovedState()) {
continue;
}
if (e.isVirgin() && storage != null) {
fetchWithStorage(e, false);
}
long t = System.currentTimeMillis();
if (!e.hasFreshData(t)) {
insertOnPut(e, value, t, t);
synchronized (lock) {
peekHitNotFreshCnt++;
}
_success = true;
}
}
break;
}
evictEventually();
return _success;
}
@Override
public void put(K key, T value) {
int _spinCount = TUNABLE.maximumEntryLockSpins;
E e;
for (;;) {
if (_spinCount-- <= 0) { throw new CacheLockSpinsExceededError(); }
e = lookupOrNewEntrySynchronized(key);
synchronized (e) {
long t = System.currentTimeMillis();
if (e.isRemovedState()) {
continue;
}
if (e.isDataValidState()) {
e.setReputState();
}
insertOnPut(e, value, t, t);
}
break;
}
evictEventually();
}
/**
* Remove the object mapped to a key from the cache.
*
* <p>Operation with storage: If there is no entry within the cache there may
* be one in the storage, so we need to send the remove to the storage. However,
* if a remove() and a get() is going on in parallel it may happen that the entry
* gets removed from the storage and added again by the tail part of get(). To
* keep the cache and the storage consistent it must be ensured that this thread
* is the only one working on the entry.
*/
public boolean removeWithFlag(K key) {
if (storage == null) {
E e = lookupEntrySynchronized(key);
if (e != null) {
synchronized (e) {
if (!e.isRemovedState()) {
synchronized (lock) {
boolean f = e.hasFreshData();
if (removeEntry(e)) {
removedCnt++;
return f;
}
return false;
}
}
}
}
return false;
}
int _spinCount = TUNABLE.maximumEntryLockSpins;
for (;;) {
if (_spinCount-- <= 0) { throw new CacheLockSpinsExceededError(); }
E e = lookupOrNewEntrySynchronized(key);
synchronized (e) {
if (e.isRemovedState()) { continue; }
fetchWithStorage(e, false);
boolean _hasFreshData = e.hasFreshData();
boolean _storageRemove = storage.remove(key);
boolean _heapRemove;
synchronized (lock) {
if (removeEntry(e)) {
removedCnt++;
_heapRemove = true;
} else {
_heapRemove = false;
}
}
return _hasFreshData && (_heapRemove || _storageRemove);
}
}
}
@Override
public void remove(K key) {
removeWithFlag(key);
}
@Override
public void prefetch(final K key) {
if (refreshPool == null ||
lookupEntrySynchronized(key) != null) {
return;
}
Runnable r = new Runnable() {
@Override
public void run() {
get(key);
}
};
refreshPool.submit(r);
}
public void prefetch(final List<K> keys, final int _startIndex, final int _endIndexExclusive) {
if (keys.size() == 0 || _startIndex == _endIndexExclusive) {
return;
}
if (keys.size() <= _endIndexExclusive) {
throw new IndexOutOfBoundsException("end > size");
}
if (_startIndex > _endIndexExclusive) {
throw new IndexOutOfBoundsException("start > end");
}
if (_startIndex > 0) {
throw new IndexOutOfBoundsException("end < 0");
}
Set<K> ks = new AbstractSet<K>() {
@Override
public Iterator<K> iterator() {
return new Iterator<K>() {
int idx = _startIndex;
@Override
public boolean hasNext() {
return idx < _endIndexExclusive;
}
@Override
public K next() {
return keys.get(idx++);
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
@Override
public int size() {
return _endIndexExclusive - _startIndex;
}
};
prefetch(ks);
}
@Override
public void prefetch(final Set<K> keys) {
if (refreshPool == null) {
getAll(keys);
return;
}
boolean _complete = true;
for (K k : keys) {
if (lookupEntryUnsynchronized(k, modifiedHash(k.hashCode())) == null) {
_complete = false; break;
}
}
if (_complete) {
return;
}
Runnable r = new Runnable() {
@Override
public void run() {
getAll(keys);
}
};
refreshPool.submit(r);
}
/**
* Lookup or create a new entry. The new entry is created, because we need
* it for locking within the data fetch.
*/
protected E lookupOrNewEntrySynchronized(K key) {
int hc = modifiedHash(key.hashCode());
E e = lookupEntryUnsynchronized(key, hc);
if (e == null) {
synchronized (lock) {
checkClosed();
e = lookupEntry(key, hc);
if (e == null) {
e = newEntry(key, hc);
}
}
}
return e;
}
protected T returnValue(Entry<E, K,T> e) {
T v = e.value;
if (v instanceof ExceptionWrapper) {
throw new PropagatedCacheException(((ExceptionWrapper) v).getException());
}
return v;
}
protected E lookupEntrySynchronized(K key) {
int hc = modifiedHash(key.hashCode());
E e = lookupEntryUnsynchronized(key, hc);
if (e == null) {
synchronized (lock) {
e = lookupEntry(key, hc);
}
}
return e;
}
protected E lookupEntry(K key, int hc) {
E e = Hash.lookup(mainHash, key, hc);
if (e != null) {
recordHit(e);
return e;
}
e = refreshHashCtrl.remove(refreshHash, key, hc);
if (e != null) {
refreshHitCnt++;
mainHash = mainHashCtrl.insert(mainHash, e);
recordHit(e);
return e;
}
return null;
}
/**
* Insert new entry in all structures (hash and replacement list). May evict an
* entry if the maximum capacity is reached.
*/
protected E newEntry(K key, int hc) {
if (getLocalSize() >= maxSize) {
evictionNeeded = true;
}
E e = checkForGhost(key, hc);
if (e == null) {
e = newEntry();
e.key = key;
e.hashCode = hc;
insertIntoReplcamentList(e);
}
mainHash = mainHashCtrl.insert(mainHash, e);
newEntryCnt++;
return e;
}
/**
* Called when expiry of an entry happens. Remove it from the
* main cache, refresh cache and from the (lru) list. Also cancel the timer.
* Called under big lock.
*/
/**
* The entry is already removed from the replacement list. stop/reset timer, if needed.
* Called under big lock.
*/
private boolean removeEntryFromHash(E e) {
boolean f = mainHashCtrl.remove(mainHash, e) || refreshHashCtrl.remove(refreshHash, e);
checkForHashCodeChange(e);
cancelExpiryTimer(e);
if (e.isVirgin()) {
virginEvictCnt++;
}
e.setRemovedState();
return f;
}
private void cancelExpiryTimer(Entry e) {
if (e.task != null) {
e.task.cancel();
timerCancelCount++;
if (timerCancelCount >= 10000) {
timer.purge();
timerCancelCount = 0;
}
e.task = null;
}
}
/**
* Check whether the key was modified during the stay of the entry in the cache.
* We only need to check this when the entry is removed, since we expect that if
* the key has changed, the stored hash code in the cache will not match any more and
* the item is evicted very fast.
*/
private void checkForHashCodeChange(Entry e) {
if (modifiedHash(e.key.hashCode()) != e.hashCode && !e.isStale()) {
if (keyMutationCount == 0) {
getLog().warn("Key mismatch! Key hashcode changed! keyClass=" + e.key.getClass().getName());
String s;
try {
s = e.key.toString();
if (s != null) {
getLog().warn("Key mismatch! key.toString(): " + s);
}
} catch (Throwable t) {
getLog().warn("Key mismatch! key.toString() threw exception", t);
}
}
keyMutationCount++;
}
}
/**
* Time when the element should be fetched again from the underlying storage.
* If 0 then the object should not be cached at all. -1 means no expiry.
*
* @param _newObject might be a fetched value or an exception wrapped into the {@link ExceptionWrapper}
*/
static <K, T> long calcNextRefreshTime(
K _key, T _newObject, long now, Entry _entry,
EntryExpiryCalculator<K, T> ec, long _maxLinger,
ExceptionExpiryCalculator<K> _exceptionEc, long _exceptionMaxLinger) {
if (!(_newObject instanceof ExceptionWrapper)) {
if (_maxLinger == 0) {
return 0;
}
if (ec != null) {
long t = ec.calculateExpiryTime(_key, _newObject, now, _entry);
return limitExpiryToMaxLinger(now, _maxLinger, t);
}
if (_maxLinger > 0) {
return _maxLinger + now;
} else {
return _maxLinger;
}
}
if (_exceptionMaxLinger == 0) {
return 0;
}
if (_exceptionEc != null) {
long t = _exceptionEc.calculateExpiryTime(_key, ((ExceptionWrapper) _newObject).getException(), now);
return limitExpiryToMaxLinger(now, _exceptionMaxLinger, t);
}
if (_exceptionMaxLinger > 0) {
return _exceptionMaxLinger + now;
} else {
return _exceptionMaxLinger;
}
}
static long limitExpiryToMaxLinger(long now, long _maxLinger, long t) {
if (_maxLinger > 0) {
long _tMaximum = _maxLinger + now;
if (t > _tMaximum) {
return _tMaximum;
}
if (t < -1 && -t > _tMaximum) {
return -_tMaximum;
}
}
return t;
}
protected long calcNextRefreshTime(K _key, T _newObject, long now, Entry _entry) {
return calcNextRefreshTime(
_key, _newObject, now, _entry,
entryExpiryCalculator, maxLinger,
exceptionExpiryCalculator, exceptionMaxLinger);
}
protected void fetch(final E e) {
if (storage != null) {
fetchWithStorage(e, true);
} else {
fetchFromSource(e);
}
}
/**
*
* @param e
* @param _needsFetch true if value needs to be fetched from the cache source.
* This is false, when the we only need to peek for an value already mapped.
*/
protected void fetchWithStorage(E e, boolean _needsFetch) {
if (!e.isVirgin()) {
if (_needsFetch) {
fetchFromSource(e);
}
return;
}
StorageEntry se = storage.get(e.key);
if (se == null) {
if (_needsFetch) {
synchronized (lock) {
loadMissCnt++;
}
fetchFromSource(e);
return;
}
e.setLoadedNonValid();
synchronized (lock) {
touchedTime = System.currentTimeMillis();
loadNonFreshCnt++;
}
return;
}
insertEntryFromStorage(se, e, _needsFetch);
}
protected void insertEntryFromStorage(StorageEntry se, E e, boolean _needsFetch) {
e.setLastModificationFromStorage(se.getCreatedOrUpdated());
long now = System.currentTimeMillis();
T v = (T) se.getValueOrException();
long _nextRefreshTime = maxLinger == 0 ? Entry.FETCH_NEXT_TIME_STATE : Entry.FETCHED_STATE;
long _expiryTimeFromStorage = se.getValueExpiryTime();
boolean _expired = _expiryTimeFromStorage != 0 && _expiryTimeFromStorage <= now;
if (!_expired && timer != null) {
_nextRefreshTime = calcNextRefreshTime((K) se.getKey(), v, se.getCreatedOrUpdated(), null);
_expired = _nextRefreshTime > Entry.EXPIRY_TIME_MIN && _nextRefreshTime <= now;
}
boolean _fetchAlways = timer == null && maxLinger == 0;
if (_expired || _fetchAlways) {
if (_needsFetch) {
e.value = se.getValueOrException();
e.setLoadedNonValidAndFetch();
fetchFromSource(e);
return;
} else {
e.setLoadedNonValid();
synchronized (lock) {
touchedTime = now;
loadNonFreshCnt++;
}
return;
}
}
insert(e, (T) se.getValueOrException(), 0, now, INSERT_STAT_UPDATE, _nextRefreshTime);
}
protected void fetchFromSource(E e) {
T v;
long t0 = System.currentTimeMillis();
try {
if (source == null) {
throw new CacheUsageExcpetion("source not set");
}
if (e.isVirgin() || e.hasException()) {
v = source.get((K) e.key, t0, null, e.getLastModification());
} else {
v = source.get((K) e.key, t0, (T) e.getValue(), e.getLastModification());
}
e.setLastModification(t0);
} catch (Throwable _ouch) {
v = (T) new ExceptionWrapper(_ouch);
}
long t = System.currentTimeMillis();
insertFetched(e, v, t0, t);
}
protected final void insertFetched(E e, T v, long t0, long t) {
insert(e, v, t0, t, INSERT_STAT_UPDATE);
}
protected final void insertOnPut(E e, T v, long t0, long t) {
e.setLastModification(t0);
insert(e, v, t0, t, INSERT_STAT_PUT);
}
/**
* Calculate the next refresh time if a timer / expiry is needed and call insert.
*/
protected final void insert(E e, T v, long t0, long t, byte _updateStatistics) {
long _nextRefreshTime = maxLinger == 0 ? Entry.FETCH_NEXT_TIME_STATE : Entry.FETCHED_STATE;
if (timer != null) {
if (e.isVirgin() || e.hasException()) {
_nextRefreshTime = calcNextRefreshTime((K) e.getKey(), v, t0, null);
} else {
_nextRefreshTime = calcNextRefreshTime((K) e.getKey(), v, t0, e);
}
}
insert(e,v,t0,t, _updateStatistics, _nextRefreshTime);
}
final static byte INSERT_STAT_NO_UPDATE = 0;
final static byte INSERT_STAT_UPDATE = 1;
final static byte INSERT_STAT_PUT = 2;
protected final void insert(E e, T v, long t0, long t, byte _updateStatistics, long _nextRefreshTime) {
synchronized (lock) {
checkClosed();
touchedTime = t;
if (_updateStatistics == INSERT_STAT_UPDATE) {
if (t0 == 0) {
loadHitCnt++;
} else {
if (v instanceof ExceptionWrapper) {
if (hasSuppressExceptions() && e.getValue() != INITIAL_VALUE && !e.hasException()) {
v = (T) e.getValue();
suppressedExceptionCnt++;
}
fetchExceptionCnt++;
}
fetchCnt++;
fetchMillis += t - t0;
if (e.isGettingRefresh()) {
refreshCnt++;
}
if (e.isLoadedNonValidAndFetch()) {
loadNonFreshAndFetchedCnt++;
} else if (!e.isVirgin()) {
fetchButHitCnt++;
}
}
} else if (_updateStatistics == INSERT_STAT_PUT) {
putCnt++;
if (e.isVirgin()) {
putNewEntryCnt++;
}
}
if (e.task != null) {
e.task.cancel();
}
e.value = v;
if (hasSharpTimeout() && _nextRefreshTime > Entry.EXPIRY_TIME_MIN) {
_nextRefreshTime = -_nextRefreshTime;
}
if (timer != null &&
(_nextRefreshTime > Entry.EXPIRY_TIME_MIN || _nextRefreshTime < -1)) {
if (_nextRefreshTime < -1) {
long _timerTime =
-_nextRefreshTime - TUNABLE.sharpExpirySafetyGapMillis;
if (_timerTime >= t) {
MyTimerTask tt = new MyTimerTask();
tt.entry = e;
timer.schedule(tt, new Date(_timerTime));
e.task = tt;
_nextRefreshTime = -_nextRefreshTime;
}
} else {
MyTimerTask tt = new MyTimerTask();
tt.entry = e;
timer.schedule(tt, new Date(_nextRefreshTime));
e.task = tt;
}
} else {
if (_nextRefreshTime == 0) {
_nextRefreshTime = Entry.FETCH_NEXT_TIME_STATE;
} else if (_nextRefreshTime == -1) {
_nextRefreshTime = Entry.FETCHED_STATE;
} else {
}
}
} // synchronized (lock)
e.nextRefreshTime = _nextRefreshTime;
if (storage != null && e.isDirty()) {
storage.put(e);
e.resetDirty();
}
}
/**
* When the time has come remove the entry from the cache.
*/
protected void timerEvent(final E e, long _executionTime) {
if (e.isRemovedFromReplacementList()) {
return;
}
if (refreshPool != null) {
synchronized (lock) {
if (isClosed()) { return; }
if (e.task == null) {
return;
}
if (e.isRemovedFromReplacementList()) {
return;
}
if (mainHashCtrl.remove(mainHash, e)) {
refreshHash = refreshHashCtrl.insert(refreshHash, e);
if (e.hashCode != modifiedHash(e.key.hashCode())) {
Runnable r = new Runnable() {
@Override
public void run() {
synchronized (lock) {
synchronized (e) {
if (!e.isRemovedState() && removeEntryFromHash(e)) {
expiredRemoveCnt++;
}
}
}
}
};
getEvictionExecutor().execute(r);
return;
}
Runnable r = new Runnable() {
@Override
public void run() {
synchronized (e) {
try {
if (e.isRemovedFromReplacementList()) {
return;
}
e.setGettingRefresh();
fetch(e);
} catch (CacheClosedException ignore) {
} catch (Throwable ex) {
synchronized (lock) {
internalExceptionCnt++;
}
getLog().warn("Refresh exception", ex);
expireEntry(e);
}
}
}
};
boolean _submitOkay = refreshPool.submit(r);
if (_submitOkay) {
return;
}
refreshSubmitFailedCnt++;
}
}
} else {
if (_executionTime < e.nextRefreshTime && e.nextRefreshTime > Entry.EXPIRY_TIME_MIN) {
Runnable r = new Runnable() {
@Override
public void run() {
synchronized (e) {
if (!e.isRemovedState()) {
long t = System.currentTimeMillis();
if (t < e.nextRefreshTime && e.nextRefreshTime > Entry.EXPIRY_TIME_MIN) {
e.nextRefreshTime = -e.nextRefreshTime;
return;
} else if (t >= e.nextRefreshTime) {
expireEntry(e);
}
}
}
}
};
getEvictionExecutor().execute(r);
return;
}
}
Runnable r = new Runnable() {
@Override
public void run() {
synchronized (e) {
long t = System.currentTimeMillis();
if (t >= e.nextRefreshTime) {
expireEntry(e);
}
}
}
};
getEvictionExecutor().execute(r);
}
protected void expireEntry(E e) {
synchronized (e) {
if (e.isRemovedState() || e.isExpiredState()) {
return;
}
e.setExpiredState();
if (storage != null && !hasKeepAfterExpired()) {
storage.expire(e);
}
synchronized (lock) {
checkClosed();
if (hasKeepAfterExpired()) {
expiredKeptCnt++;
} else {
if (removeEntry(e)) {
expiredRemoveCnt++;
}
}
}
}
}
/**
* Returns all cache entries within the heap cache. Entries that
* are expired or contain no valid data are not filtered out.
*/
final protected ClosableConcurrentHashEntryIterator<Entry> iterateAllLocalEntries() {
return
new ClosableConcurrentHashEntryIterator(
mainHashCtrl, mainHash, refreshHashCtrl, refreshHash);
}
@Override
public void removeAllAtOnce(Set<K> _keys) {
}
/** JSR107 convenience getAll from array */
public Map<K, T> getAll(K[] _keys) {
return getAll(new HashSet<K>(Arrays.asList(_keys)));
}
/**
* JSR107 bulk interface
*/
public Map<K, T> getAll(final Set<? extends K> _keys) {
K[] ka = (K[]) new Object[_keys.size()];
int i = 0;
for (K k : _keys) {
ka[i++] = k;
}
T[] va = (T[]) new Object[ka.length];
getBulk(ka, va, new BitSet(), 0, ka.length);
return new AbstractMap<K, T>() {
@Override
public T get(Object key) {
if (containsKey(key)) {
return BaseCache.this.get((K) key);
}
return null;
}
@Override
public boolean containsKey(Object key) {
return _keys.contains(key);
}
@Override
public Set<Entry<K, T>> entrySet() {
return new AbstractSet<Entry<K, T>>() {
@Override
public Iterator<Entry<K, T>> iterator() {
return new Iterator<Entry<K, T>>() {
Iterator<? extends K> it = _keys.iterator();
@Override
public boolean hasNext() {
return it.hasNext();
}
@Override
public Entry<K, T> next() {
final K k = it.next();
final T t = BaseCache.this.get(k);
return new Entry<K, T>() {
@Override
public K getKey() {
return k;
}
@Override
public T getValue() {
return t;
}
@Override
public T setValue(T value) {
throw new UnsupportedOperationException();
}
};
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
@Override
public int size() {
return _keys.size();
}
};
}
};
}
/**
* Retrieve
*/
@SuppressWarnings("unused")
public void getBulk(K[] _keys, T[] _result, BitSet _fetched, int s, int e) {
E[] _entries = (E[]) new Entry[_keys.length];
boolean _mayDeadlock;
synchronized (lock) {
int _fetchCount = checkAndCreateEntries(_keys, _result, _fetched, _entries, s, e);
if (_fetchCount == 0) {
return;
}
_mayDeadlock = checkForDeadLockOrExceptions(_entries, s, e);
if (!_mayDeadlock) {
bulkGetCnt++;
}
}
if (!_mayDeadlock) {
try {
for (int i = s; i < e; i += maximumBulkFetchSize) {
long t = System.currentTimeMillis();
int _endIdx = Math.min(e, i + maximumBulkFetchSize);
fetchBulkLoop(_entries, _keys, _result, _fetched, i, _endIdx - 1, _endIdx, t);
}
return;
} finally {
freeBulkKeyRetrievalMarkers(_entries);
}
}
sequentialGetFallBack(_keys, _result, _fetched, s, e);
}
/**
* This is called recursively to synchronize on each hash entry.
*
* this implementation may deadlock if called on the same data concurrently and in different order.
* for reason we keep track of all keys that are currently retrieved via bulk request and
* fall back to the sequential get if needed.
*
* @param s start index
* @param end end index, exclusive
* @param i working index starting with e-1
*/
final long fetchBulkLoop(final E[] ea, K[] k, T[] r, BitSet _fetched, int s, int i, int end, long t) {
for (; i >= s; i
E e = ea[i];
if (e == null) { continue; }
if (!e.isDataValidState()) {
synchronized (e) {
if (!e.isDataValidState()) {
r[i] = null;
_fetched.set(i, false);
long t2 = fetchBulkLoop(ea, k, r, _fetched, s, i - 1, end, t);
if (!e.isDataValidState()) {
e.setLastModification(t);
insertFetched(e, r[i], t, t2);
}
return t2;
} else {
}
}
}
r[i] = (T) e.getValue();
_fetched.set(i);
}
int _needsFetchCnt = 0;
for (i = s; i < end; i++) {
if (!_fetched.get(i)) {
_needsFetchCnt++;
}
}
if (_needsFetchCnt == 0) {
return 0;
}
if (experimentalBulkCacheSource == null && bulkCacheSource == null) {
sequentialFetch(ea, k, r, _fetched, s, end);
return 0;
} if (bulkCacheSource != null) {
final int[] _index = new int[_needsFetchCnt];
int idx = 0;
for (i = s; i < end; i++) {
if (!_fetched.get(i)) {
_index[idx++] = i;
}
}
List<CacheEntry<K, T>> _entries = new AbstractList<CacheEntry<K,T>>() {
@Override
public CacheEntry<K, T> get(int index) {
return ea[_index[index]];
}
@Override
public int size() {
return _index.length;
}
};
try {
List<T> _resultList = bulkCacheSource.getValues(_entries, t);
if (_resultList.size() != _index.length) {
throw new CacheUsageExcpetion("bulk source returned list with wrong length");
}
for (i = 0; i < _index.length; i++) {
r[_index[i]] = _resultList.get(i);
}
} catch (Throwable _ouch) {
T v = (T) new ExceptionWrapper(_ouch);
for (i = s; i < end; i++) {
if (!_fetched.get(i)) {
r[i] = v;
}
}
}
} else {
try {
experimentalBulkCacheSource.getBulk(k, r, _fetched, s, end);
} catch (Throwable _ouch) {
T v = (T) new ExceptionWrapper(_ouch);
for (i = s; i < end; i++) {
Entry e = ea[i];
if (!e.isDataValidState()) {
r[i] = v;
}
}
}
}
return System.currentTimeMillis();
}
final void sequentialFetch(E[] ea, K[] _keys, T[] _result, BitSet _fetched, int s, int end) {
for (int i = s; i < end; i++) {
E e = ea[i];
if (e == null) { continue; }
if (!e.isDataValidState()) {
synchronized (e) {
if (!e.isDataValidState()) {
fetch(e);
}
_result[i] = (T) e.getValue();
}
}
}
}
final void sequentialGetFallBack(K[] _keys, T[] _result, BitSet _fetched, int s, int e) {
for (int i = s; i < e; i++) {
if (!_fetched.get(i)) {
_result[i] = get(_keys[i]);
}
}
}
final void freeBulkKeyRetrievalMarkers(Entry[] _entries) {
synchronized (lock) {
for (Entry<E, K, T> et : _entries) {
if (et == null) { continue; }
bulkKeysCurrentlyRetrieved.remove(et.key);
}
}
}
private boolean checkForDeadLockOrExceptions(Entry[] _entries, int s, int e) {
if (bulkKeysCurrentlyRetrieved == null) {
bulkKeysCurrentlyRetrieved = new HashSet<K>();
}
for (int i = s; i < e; i++) {
Entry _entry = _entries[i];
if (_entry != null) {
if ((_entry.getException() != null) ||
bulkKeysCurrentlyRetrieved.contains(_entry.key)) {
return true;
}
}
}
for (int i = s; i < e; i++) {
Entry<E, K, T> _entry = _entries[i];
if (_entry != null) {
bulkKeysCurrentlyRetrieved.add(_entry.key);
}
}
return false;
}
/**
* lookup entries or create new ones if needed, already fill the result
* if the entry was fetched
*/
private int checkAndCreateEntries(K[] _keys, T[] _result, BitSet _fetched, Entry[] _entries, int s, int e) {
int _fetchCount = e - s;
for (int i = s; i < e; i++) {
if (_fetched.get(i)) { _fetchCount--; continue; }
K key = _keys[i];
int hc = modifiedHash(key.hashCode());
Entry<E,K,T> _entry = lookupEntry(key, hc);
if (_entry == null) {
_entries[i] = newEntry(key, hc);
} else {
if (_entry.isDataValidState()) {
_result[i] = _entry.getValue();
_fetched.set(i);
_fetchCount
} else {
_entries[i] = _entry;
}
}
}
return _fetchCount;
}
public abstract long getHitCnt();
protected final int calculateHashEntryCount() {
return Hash.calcEntryCount(mainHash) + Hash.calcEntryCount(refreshHash);
}
protected final int getLocalSize() {
return mainHashCtrl.size + refreshHashCtrl.size;
}
public final int getTotalEntryCount() {
synchronized (lock) {
if (storage != null) {
return storage.getTotalEntryCount();
}
return getLocalSize();
}
}
public long getExpiredCnt() {
return expiredRemoveCnt + expiredKeptCnt;
}
/**
* For peek no fetch is counted if there is a storage miss, hence the extra counter.
*/
public long getFetchesBecauseOfNewEntries() {
return fetchCnt - fetchButHitCnt;
}
protected int getFetchesInFlight() {
long _fetchesBecauseOfNoEntries = getFetchesBecauseOfNewEntries();
return (int) (newEntryCnt - putNewEntryCnt - virginEvictCnt
- loadNonFreshCnt
- loadHitCnt
- _fetchesBecauseOfNoEntries);
}
protected IntegrityState getIntegrityState() {
synchronized (lock) {
return new IntegrityState()
.checkEquals(
"newEntryCnt - virginEvictCnt == " +
"getFetchesBecauseOfNewEntries() + getFetchesInFlight() + putNewEntryCnt + loadNonFreshCnt + loadHitCnt",
newEntryCnt - virginEvictCnt,
getFetchesBecauseOfNewEntries() + getFetchesInFlight() + putNewEntryCnt + loadNonFreshCnt + loadHitCnt)
.checkLessOrEquals("getFetchesInFlight() <= 100", getFetchesInFlight(), 100)
.checkEquals("newEntryCnt == getSize() + evictedCnt + expiredRemoveCnt + removeCnt", newEntryCnt, getLocalSize() + evictedCnt + expiredRemoveCnt + removedCnt)
.checkEquals("newEntryCnt == getSize() + evictedCnt + getExpiredCnt() - expiredKeptCnt + removeCnt", newEntryCnt, getLocalSize() + evictedCnt + getExpiredCnt() - expiredKeptCnt + removedCnt)
.checkEquals("mainHashCtrl.size == Hash.calcEntryCount(mainHash)", mainHashCtrl.size, Hash.calcEntryCount(mainHash))
.checkEquals("refreshHashCtrl.size == Hash.calcEntryCount(refreshHash)", refreshHashCtrl.size, Hash.calcEntryCount(refreshHash))
.check("!!evictionNeeded | (getSize() <= maxSize)", !!evictionNeeded | (getLocalSize() <= maxSize))
.checkLessOrEquals("bulkKeysCurrentlyRetrieved.size() <= getSize()",
bulkKeysCurrentlyRetrieved == null ? 0 : bulkKeysCurrentlyRetrieved.size(), getLocalSize())
.check("storage => storage.getAlert() < 2", storage == null || storage.getAlert() < 2);
}
}
/** Check internal data structures and throw and exception if something is wrong, used for unit testing */
public final void checkIntegrity() {
synchronized (lock) {
IntegrityState is = getIntegrityState();
if (is.getStateFlags() > 0) {
throw new CacheIntegrityError(is.getStateDescriptor(), is.getFailingChecks(), toString());
}
}
}
public final Info getInfo() {
synchronized (lock) {
long t = System.currentTimeMillis();
if (info != null &&
(info.creationTime + info.creationDeltaMs * 17 + 333 > t)) {
return info;
}
info = getLatestInfo(t);
}
return info;
}
public final Info getLatestInfo() {
return getLatestInfo(System.currentTimeMillis());
}
private Info getLatestInfo(long t) {
synchronized (lock) {
info = new Info();
info.creationTime = t;
info.creationDeltaMs = (int) (System.currentTimeMillis() - t);
return info;
}
}
protected String getExtraStatistics() { return ""; }
static String timestampToString(long t) {
if (t == 0) {
return "-";
}
return (new java.sql.Timestamp(t)).toString();
}
/**
* Return status information. The status collection is time consuming, so this
* is an expensive operation.
*/
@Override
public String toString() {
synchronized (lock) {
Info fo = getLatestInfo();
return "Cache{" + name + "}"
+ "("
+ "size=" + fo.getSize() + ", "
+ "maxSize=" + fo.getMaxSize() + ", "
+ "usageCnt=" + fo.getUsageCnt() + ", "
+ "missCnt=" + fo.getMissCnt() + ", "
+ "fetchCnt=" + fo.getFetchCnt() + ", "
+ "fetchButHitCnt=" + fetchButHitCnt + ", "
+ "heapHitCnt=" + fo.hitCnt + ", "
+ "virginEvictCnt=" + virginEvictCnt + ", "
+ "fetchesInFlightCnt=" + fo.getFetchesInFlightCnt() + ", "
+ "newEntryCnt=" + fo.getNewEntryCnt() + ", "
+ "bulkGetCnt=" + fo.getBulkGetCnt() + ", "
+ "refreshCnt=" + fo.getRefreshCnt() + ", "
+ "refreshSubmitFailedCnt=" + fo.getRefreshSubmitFailedCnt() + ", "
+ "refreshHitCnt=" + fo.getRefreshHitCnt() + ", "
+ "putCnt=" + fo.getPutCnt() + ", "
+ "putNewEntryCnt=" + fo.getPutNewEntryCnt() + ", "
+ "expiredCnt=" + fo.getExpiredCnt() + ", "
+ "evictedCnt=" + fo.getEvictedCnt() + ", "
+ "removedCnt=" + fo.getRemovedCnt() + ", "
+ "storageLoadCnt=" + fo.getStorageLoadCnt() + ", "
+ "storageMissCnt=" + fo.getStorageMissCnt() + ", "
+ "storageHitCnt=" + fo.getStorageHitCnt() + ", "
+ "hitRate=" + fo.getDataHitString() + ", "
+ "collisionCnt=" + fo.getCollisionCnt() + ", "
+ "collisionSlotCnt=" + fo.getCollisionSlotCnt() + ", "
+ "longestCollisionSize=" + fo.getLongestCollisionSize() + ", "
+ "hashQuality=" + fo.getHashQualityInteger() + ", "
+ "msecs/fetch=" + (fo.getMillisPerFetch() >= 0 ? fo.getMillisPerFetch() : "-") + ", "
+ "created=" + timestampToString(fo.getStarted()) + ", "
+ "cleared=" + timestampToString(fo.getCleared()) + ", "
+ "touched=" + timestampToString(fo.getTouched()) + ", "
+ "fetchExceptionCnt=" + fo.getFetchExceptionCnt() + ", "
+ "suppressedExceptionCnt=" + fo.getSuppressedExceptionCnt() + ", "
+ "internalExceptionCnt=" + fo.getInternalExceptionCnt() + ", "
+ "keyMutationCnt=" + fo.getKeyMutationCnt() + ", "
+ "infoCreated=" + timestampToString(fo.getInfoCreated()) + ", "
+ "infoCreationDeltaMs=" + fo.getInfoCreationDeltaMs() + ", "
+ "impl=\"" + getClass().getSimpleName() + "\""
+ getExtraStatistics() + ", "
+ "integrityState=" + fo.getIntegrityDescriptor() + ")";
}
}
/**
* Stable interface to request information from the cache, the object
* safes values that need a longer calculation time, other values are
* requested directly.
*/
public class Info {
int size = BaseCache.this.getLocalSize();
long creationTime;
int creationDeltaMs;
long missCnt = fetchCnt - refreshCnt + peekHitNotFreshCnt + peekMissCnt;
long storageMissCnt = loadMissCnt + loadNonFreshCnt + loadNonFreshAndFetchedCnt;
long storageLoadCnt = storageMissCnt + loadHitCnt;
long newEntryCnt = BaseCache.this.newEntryCnt - virginEvictCnt;
long hitCnt = getHitCnt();
long usageCnt =
hitCnt + newEntryCnt + peekMissCnt;
CollisionInfo collisionInfo;
String extraStatistics;
int fetchesInFlight = BaseCache.this.getFetchesInFlight();
{
collisionInfo = new CollisionInfo();
Hash.calcHashCollisionInfo(collisionInfo, mainHash);
Hash.calcHashCollisionInfo(collisionInfo, refreshHash);
extraStatistics = BaseCache.this.getExtraStatistics();
if (extraStatistics.startsWith(", ")) {
extraStatistics = extraStatistics.substring(2);
}
}
IntegrityState integrityState = getIntegrityState();
String percentString(double d) {
String s = Double.toString(d);
return (s.length() > 5 ? s.substring(0, 5) : s) + "%";
}
public String getName() { return name; }
public String getImplementation() { return BaseCache.this.getClass().getSimpleName(); }
public int getSize() { return size; }
public int getMaxSize() { return maxSize; }
public long getStorageHitCnt() { return loadHitCnt; }
public long getStorageLoadCnt() { return storageLoadCnt; }
public long getStorageMissCnt() { return storageMissCnt; }
public long getReadUsageCnt() { return usageCnt - putCnt; }
public long getUsageCnt() { return usageCnt; }
public long getMissCnt() { return missCnt; }
public long getNewEntryCnt() { return newEntryCnt; }
public long getFetchCnt() { return fetchCnt; }
public int getFetchesInFlightCnt() { return fetchesInFlight; }
public long getBulkGetCnt() { return bulkGetCnt; }
public long getRefreshCnt() { return refreshCnt; }
public long getInternalExceptionCnt() { return internalExceptionCnt; }
public long getRefreshSubmitFailedCnt() { return refreshSubmitFailedCnt; }
public long getSuppressedExceptionCnt() { return suppressedExceptionCnt; }
public long getFetchExceptionCnt() { return fetchExceptionCnt; }
public long getRefreshHitCnt() { return refreshHitCnt; }
public long getExpiredCnt() { return BaseCache.this.getExpiredCnt(); }
public long getEvictedCnt() { return evictedCnt - virginEvictCnt; }
public long getRemovedCnt() { return BaseCache.this.removedCnt; }
public long getPutNewEntryCnt() { return putNewEntryCnt; }
public long getPutCnt() { return putCnt; }
public long getKeyMutationCnt() { return keyMutationCount; }
public double getDataHitRate() {
long cnt = getReadUsageCnt();
return cnt == 0 ? 100 : (cnt - missCnt) * 100D / cnt;
}
public String getDataHitString() { return percentString(getDataHitRate()); }
public double getEntryHitRate() { return usageCnt == 0 ? 100 : (usageCnt - newEntryCnt + putCnt) * 100D / usageCnt; }
public String getEntryHitString() { return percentString(getEntryHitRate()); }
/** How many items will be accessed with collision */
public int getCollisionPercentage() {
return
(size - collisionInfo.collisionCnt) * 100 / size;
}
/** 100 means each collision has its own slot */
public int getSlotsPercentage() {
return collisionInfo.collisionSlotCnt * 100 / collisionInfo.collisionCnt;
}
public int getHq0() {
return Math.max(0, 105 - collisionInfo.longestCollisionSize * 5) ;
}
public int getHq1() {
final int _metricPercentageBase = 60;
int m =
getCollisionPercentage() * ( 100 - _metricPercentageBase) / 100 + _metricPercentageBase;
m = Math.min(100, m);
m = Math.max(0, m);
return m;
}
public int getHq2() {
final int _metricPercentageBase = 80;
int m =
getSlotsPercentage() * ( 100 - _metricPercentageBase) / 100 + _metricPercentageBase;
m = Math.min(100, m);
m = Math.max(0, m);
return m;
}
public int getHashQualityInteger() {
if (size == 0 || collisionInfo.collisionSlotCnt == 0) {
return 100;
}
int _metric0 = getHq0();
int _metric1 = getHq1();
int _metric2 = getHq2();
if (_metric1 < _metric0) {
int v = _metric0;
_metric0 = _metric1;
_metric1 = v;
}
if (_metric2 < _metric0) {
int v = _metric0;
_metric0 = _metric2;
_metric2 = v;
}
if (_metric2 < _metric1) {
int v = _metric1;
_metric1 = _metric2;
_metric2 = v;
}
if (_metric0 <= 0) {
return 0;
}
_metric0 = _metric0 + ((_metric1 - 50) * 5 / _metric0);
_metric0 = _metric0 + ((_metric2 - 50) * 2 / _metric0);
_metric0 = Math.max(0, _metric0);
_metric0 = Math.min(100, _metric0);
return _metric0;
}
public double getMillisPerFetch() { return fetchCnt == 0 ? -1 : (fetchMillis * 1D / fetchCnt); }
public long getFetchMillis() { return fetchMillis; }
public int getCollisionCnt() { return collisionInfo.collisionCnt; }
public int getCollisionSlotCnt() { return collisionInfo.collisionSlotCnt; }
public int getLongestCollisionSize() { return collisionInfo.longestCollisionSize; }
public String getIntegrityDescriptor() { return integrityState.getStateDescriptor(); }
public long getStarted() { return startedTime; }
public long getCleared() { return clearedTime; }
public long getTouched() { return touchedTime; }
public long getInfoCreated() { return creationTime; }
public int getInfoCreationDeltaMs() { return creationDeltaMs; }
public int getHealth() {
if (storage != null && storage.getAlert() == 2) {
return 2;
}
if (integrityState.getStateFlags() > 0 ||
getHashQualityInteger() < 5) {
return 2;
}
if (storage != null && storage.getAlert() == 1) {
return 1;
}
if (getHashQualityInteger() < 30 ||
getKeyMutationCnt() > 0 ||
getInternalExceptionCnt() > 0) {
return 1;
}
return 0;
}
public String getExtraStatistics() {
return extraStatistics;
}
}
static class CollisionInfo {
int collisionCnt; int collisionSlotCnt; int longestCollisionSize;
}
/**
* This function calculates a modified hash code. The intention is to
* "rehash" the incoming integer hash codes to overcome weak hash code
* implementations. We expect good results for integers also.
* Also add a random seed to the hash to protect against attacks on hashes.
* This is actually a slightly reduced version of the java.util.HashMap
* hash modification.
*/
protected final int modifiedHash(int h) {
h ^= hashSeed;
h ^= h >>> 7;
h ^= h >>> 15;
return h;
}
/**
* Fast hash table implementation. Why we don't want to use the Java HashMap implementation:
*
* We need to move the entries back and forth between different hashes.
* If we do this, each time an entry object needs to be allocated and deallocated.
*
* Second, we need to do countermeasures, if a key changes its value and hashcode
* during its use in the cache. Although it is a user error and therefore not
* our primary concern, the effects can be very curious and hard to find.
*
* Third, we want to have use the hash partly unsynchronized, so we should know the
* implementation details.
*
* Fourth, we can leave out "details" of a general hash table, like shrinking. Our hash table
* only expands.
*
* Access needs to be public, since we want to access the hash primitives from classes
* in another package.
*/
public static class Hash<E extends Entry> {
public int size = 0;
public int maxFill = 0;
private int suppressExpandCount;
public static int index(Entry[] _hashTable, int _hashCode) {
return _hashCode & (_hashTable.length - 1);
}
public static <E extends Entry> E lookup(E[] _hashTable, Object key, int _hashCode) {
int i = index(_hashTable, _hashCode);
E e = _hashTable[i];
while (e != null) {
if (e.hashCode == _hashCode &&
key.equals(e.key)) {
return e;
}
e = (E) e.another;
}
return null;
}
public static boolean contains(Entry[] _hashTable, Object key, int _hashCode) {
int i = index(_hashTable, _hashCode);
Entry e = _hashTable[i];
while (e != null) {
if (e.hashCode == _hashCode &&
(key == e.key || key.equals(e.key))) {
return true;
}
e = e.another;
}
return false;
}
public static void insertWoExpand(Entry[] _hashTable, Entry e) {
int i = index(_hashTable, e.hashCode);
e.another = _hashTable[i];
_hashTable[i] = e;
}
private static void rehash(Entry[] a1, Entry[] a2) {
for (Entry e : a1) {
while (e != null) {
Entry _next = e.another;
insertWoExpand(a2, e);
e = _next;
}
}
}
private static <E extends Entry> E[] expandHash(E[] _hashTable) {
E[] a2 = (E[]) Array.newInstance(
_hashTable.getClass().getComponentType(),
_hashTable.length * 2);
rehash(_hashTable, a2);
return a2;
}
public static void calcHashCollisionInfo(CollisionInfo inf, Entry[] _hashTable) {
for (Entry e : _hashTable) {
if (e != null) {
e = e.another;
if (e != null) {
inf.collisionSlotCnt++;
int _size = 1;
while (e != null) {
inf.collisionCnt++;
e = e.another;
_size++;
}
if (inf.longestCollisionSize < _size) {
inf.longestCollisionSize = _size;
}
}
}
}
}
/**
* Count the entries in the hash table, by scanning through the hash table.
* This is used for integrity checks.
*/
public static int calcEntryCount(Entry[] _hashTable) {
int _entryCount = 0;
for (Entry e : _hashTable) {
while (e != null) {
_entryCount++;
e = e.another;
}
}
return _entryCount;
}
public boolean remove(Entry[] _hashTable, Entry _entry) {
int i = index(_hashTable, _entry.hashCode);
Entry e = _hashTable[i];
if (e == _entry) {
_hashTable[i] = e.another;
size
return true;
}
while (e != null) {
Entry _another = e.another;
if (_another == _entry) {
e.another = _another.another;
size
return true;
}
e = _another;
}
return false;
}
/**
* Remove entry from the hash. We never shrink the hash table, so
* the array keeps identical. After this remove operation the entry
* object may be inserted in another hash.
*/
public E remove(E[] _hashTable, Object key, int hc) {
int i = index(_hashTable, hc);
Entry e = _hashTable[i];
if (e == null) {
return null;
}
if (e.hashCode == hc && key.equals(e.key)) {
_hashTable[i] = (E) e.another;
size
return (E) e;
}
Entry _another = e.another;
while (_another != null) {
if (_another.hashCode == hc && key.equals(_another.key)) {
e.another = _another.another;
size
return (E) _another;
}
e = _another;
_another = _another.another;
}
return null;
}
public E[] insert(E[] _hashTable, Entry _entry) {
size++;
insertWoExpand(_hashTable, _entry);
synchronized (this) {
if (size >= maxFill && suppressExpandCount == 0) {
maxFill = maxFill * 2;
return expandHash(_hashTable);
}
return _hashTable;
}
}
/**
* Usage/reference counter for iterations to suspend expand
* until the iteration finished. This is needed for correctness
* of the iteration, if an expand is done during the iteration
* process, the iterations returns duplicate entries or not
* all entries.
*
* <p>Failing to operate the increment/decrement in balance will
* mean that hash table expands are blocked forever, which is a
* serious error condition. Typical problems arise by thrown
* exceptions during an iteration.
*/
public synchronized void incrementSuppressExpandCount() {
suppressExpandCount++;
}
public synchronized void decrementSuppressExpandCount() {
suppressExpandCount
}
/**
* The cache with this hash was cleared and the hash table is no longer
* in used. Signal to iterations to abort.
*/
public void cleared() {
if (size >= 0) {
size = -1;
}
}
/**
* Cache was closed. Inform operations/iterators on the hash.
*/
public void close() { size = -2; }
/**
* Operations should terminate
*/
public boolean isCleared() { return size == -1; }
/**
* Operations should terminate and throw a {@link org.cache2k.impl.CacheClosedException}
*/
public boolean isClosed() { return size == -2; }
public boolean shouldAbort() { return size < 0; }
public E[] init(Class<E> _entryType) {
size = 0;
maxFill = TUNABLE.initialHashSize * TUNABLE.hashLoadPercent / 100;
return (E[]) Array.newInstance(_entryType, TUNABLE.initialHashSize);
}
}
protected class MyTimerTask extends java.util.TimerTask {
E entry;
public void run() {
timerEvent(entry, scheduledExecutionTime());
}
}
static class InitialValueInEntryNeverReturned extends Object { }
final static InitialValueInEntryNeverReturned INITIAL_VALUE = new InitialValueInEntryNeverReturned();
static class StaleMarker {
@Override
public boolean equals(Object o) { return false; }
}
final static StaleMarker STALE_MARKER_KEY = new StaleMarker();
public static class Entry<E extends Entry, K, T>
implements MutableCacheEntry<K,T>, StorageEntry {
static final int FETCHED_STATE = 10;
static final int REFRESH_STATE = 11;
static final int REPUT_STATE = 13;
/** Storage was checked, no data available */
static final int LOADED_NON_VALID_AND_FETCH = 6;
/** Storage was checked, no data available */
static final int LOADED_NON_VALID = 5;
static final int EXPIRED_STATE = 4;
/** Logically the same as immediately expired */
static final int FETCH_NEXT_TIME_STATE = 3;
static private final int REMOVED_STATE = 2;
static final int VIRGIN_STATE = 0;
static final int EXPIRY_TIME_MIN = 20;
public BaseCache.MyTimerTask task;
/**
* Time the entry was last updated by put or by fetching it from the cache source.
* The time is the time in millis times 2. A set bit 1 means the entry is fetched from
* the storage and not modified since then.
*/
private long fetchedTime;
/**
* Contains the next time a refresh has to occur. Low values have a special meaning, see defined constants.
* Negative values means the refresh time was expired, and we need to check the time.
*/
public volatile long nextRefreshTime;
public K key;
public volatile T value = (T) INITIAL_VALUE;
/**
* Hash implementation: the calculated, modified hash code, retrieved from the key when the entry is
* inserted in the cache
*
* @see #modifiedHash(int)
*/
public int hashCode;
/**
* Hash implementation: Link to another entry in the same hash table slot when the hash code collides.
*/
public Entry<E, K, T> another;
/** Lru list: pointer to next element or list head */
public E next;
/** Lru list: pointer to previous element or list head */
public E prev;
public void setLastModification(long t) {
fetchedTime = t << 1;
}
public boolean isDirty() {
return (fetchedTime & 1) == 0;
}
public void setLastModificationFromStorage(long t) {
fetchedTime = t << 1 | 1;
}
public void resetDirty() {
fetchedTime = fetchedTime << 1 >> 1;
}
/** Reset next as a marker for {@link #isRemovedFromReplacementList()} */
public final void removedFromList() {
next = null;
}
/** Check that this entry is removed from the list, may be used in assertions. */
public boolean isRemovedFromReplacementList() {
return isStale () || next == null;
}
public E shortCircuit() {
return next = prev = (E) this;
}
public final boolean isVirgin() {
return
nextRefreshTime == VIRGIN_STATE;
}
public final boolean isFetchNextTimeState() {
return nextRefreshTime == FETCH_NEXT_TIME_STATE;
}
/**
* The entry value was fetched and is valid, which means it can be
* returned by the cache. If a valid an entry with {@link #isDataValidState()}
* true gets removed from the cache the data is still valid. This is
* because a concurrent get needs to return the data. There is also
* the chance that an entry is removed by eviction, or is never inserted
* to the cache, before the get returns it.
*
* <p/>Even if this is true, the data may be expired. Use hasFreshData() to
* make sure to get not expired data.
*/
public final boolean isDataValidState() {
return nextRefreshTime >= FETCHED_STATE || nextRefreshTime < 0;
}
/**
* Returns true if the entry has a valid value and is fresh / not expired.
*/
public final boolean hasFreshData() {
if (nextRefreshTime >= FETCHED_STATE) {
return true;
}
if (needsTimeCheck()) {
long now = System.currentTimeMillis();
boolean f = now < -nextRefreshTime;
return f;
}
return false;
}
/**
* Same as {@link #hasFreshData}, optimization if current time is known.
*/
public final boolean hasFreshData(long now) {
if (nextRefreshTime >= FETCHED_STATE) {
return true;
}
if (needsTimeCheck()) {
return now < -nextRefreshTime;
}
return false;
}
public void setFetchedState() {
nextRefreshTime = FETCHED_STATE;
}
public void setLoadedNonValid() {
nextRefreshTime = LOADED_NON_VALID;
}
public boolean isLoadedNonValid() {
return nextRefreshTime == LOADED_NON_VALID;
}
public void setLoadedNonValidAndFetch() {
nextRefreshTime = LOADED_NON_VALID_AND_FETCH;
}
public boolean isLoadedNonValidAndFetch() {
return nextRefreshTime == LOADED_NON_VALID_AND_FETCH;
}
/** Entry is kept in the cache but has expired */
public void setExpiredState() {
nextRefreshTime = EXPIRED_STATE;
}
/**
* The entry expired, but still in the cache. This may happen if
* {@link org.cache2k.impl.BaseCache#hasKeepAfterExpired()} is true.
*/
public boolean isExpiredState() {
return nextRefreshTime == EXPIRED_STATE;
}
public void setRemovedState() {
nextRefreshTime = REMOVED_STATE;
}
public boolean isRemovedState() {
return nextRefreshTime == REMOVED_STATE;
}
public void setFetchNextTimeState() {
nextRefreshTime = FETCH_NEXT_TIME_STATE;
}
public void setGettingRefresh() {
nextRefreshTime = REFRESH_STATE;
}
public boolean isGettingRefresh() {
return nextRefreshTime == REFRESH_STATE;
}
public boolean isBeeingReput() {
return nextRefreshTime == REPUT_STATE;
}
public void setReputState() {
nextRefreshTime = REPUT_STATE;
}
public boolean needsTimeCheck() {
return nextRefreshTime < 0;
}
public boolean isStale() {
return STALE_MARKER_KEY == key;
}
public void setStale() {
key = (K) STALE_MARKER_KEY;
}
public boolean hasException() {
return value instanceof ExceptionWrapper;
}
public Throwable getException() {
if (value instanceof ExceptionWrapper) {
return ((ExceptionWrapper) value).getException();
}
return null;
}
public void setException(Throwable exception) {
value = (T) new ExceptionWrapper(exception);
}
public T getValue() {
if (value instanceof ExceptionWrapper) { return null; }
return value;
}
@Override
public void setValue(T v) {
value = v;
}
@Override
public K getKey() {
return key;
}
@Override
public long getLastModification() {
return fetchedTime >> 1;
}
/**
* Expiry time or 0.
*/
public long getValueExpiryTime() {
if (nextRefreshTime < 0) {
return -nextRefreshTime;
} else if (nextRefreshTime > EXPIRY_TIME_MIN) {
return nextRefreshTime;
}
return 0;
}
/**
* Used for the storage interface.
*
* @see StorageEntry
*/
@Override
public Object getValueOrException() {
return value;
}
/**
* Used for the storage interface.
*
* @see StorageEntry
*/
@Override
public long getCreatedOrUpdated() {
return getLastModification();
}
/**
* Used for the storage interface.
*
* @see StorageEntry
* @deprectated Always returns 0, only to fulfill the {@link StorageEntry} interface
*/
@Override
public long getEntryExpiryTime() {
return 0;
}
@Override
public String toString() {
return "Entry{" +
"createdOrUpdate=" + getCreatedOrUpdated() +
", nextRefreshTime=" + nextRefreshTime +
", valueExpiryTime=" + getValueExpiryTime() +
", entryExpiryTime=" + getEntryExpiryTime() +
", key=" + key +
", mHC=" + hashCode +
", value=" + value +
", dirty=" + isDirty() +
'}';
}
/**
* Cache entries always have the object identity as equals method.
*/
@Override
public final boolean equals(Object obj) {
return this == obj;
}
}
public static class Tunable extends TunableConstants {
/**
* Implementation class to use by default.
*/
public Class<? extends BaseCache> defaultImplementation = LruCache.class;
public int waitForTimerJobsSeconds = 5;
/**
* Limits the number of spins until an entry lock is expected to
* succeed. The limit is to detect deadlock issues during development
* and testing. It is set to an arbitrary high value to result in
* an exception after about one second of spinning.
*/
public int maximumEntryLockSpins = 333333;
/**
* Size of the hash table before inserting the first entry. Must be power
* of two. Default: 64.
*/
public int initialHashSize = 64;
/**
* Fill percentage limit. When this is reached the hash table will get
* expanded. Default: 64.
*/
public int hashLoadPercent = 64;
/**
* The hash code will randomized by default. This is a countermeasure
* against from outside that know the hash function.
*/
public boolean disableHashRandomization = false;
/**
* Seed used when randomization is disabled. Default: 0.
*/
public int hashSeed = 0;
/**
* When sharp expiry is enabled, the expiry timer goes
* before the actual expiry to switch back to a time checking
* scheme when the get method is invoked. This prevents
* that an expired value gets served by the cache if the time
* is too late. A recent GC should not produce more then 200
* milliseconds stall. If longer GC stalls are expected, this
* value needs to be changed. A value of LONG.MaxValue
* suppresses the timer usage completely.
*/
public long sharpExpirySafetyGapMillis = 666;
}
}
|
package org.restheart;
import picocli.CommandLine;
import picocli.CommandLine.Command;
import picocli.CommandLine.Option;
import picocli.CommandLine.Parameters;
import com.github.mustachejava.DefaultMustacheFactory;
import com.github.mustachejava.Mustache;
import com.github.mustachejava.MustacheNotFoundException;
import com.jayway.jsonpath.spi.json.GsonJsonProvider;
import com.jayway.jsonpath.spi.json.JsonProvider;
import com.jayway.jsonpath.spi.mapper.GsonMappingProvider;
import com.jayway.jsonpath.spi.mapper.MappingProvider;
import static com.sun.akuma.CLibrary.LIBC;
import static io.undertow.Handlers.resource;
import io.undertow.Undertow;
import io.undertow.Undertow.Builder;
import io.undertow.UndertowOptions;
import io.undertow.server.handlers.AllowedMethodsHandler;
import io.undertow.server.handlers.BlockingHandler;
import io.undertow.server.handlers.GracefulShutdownHandler;
import io.undertow.server.handlers.HttpContinueAcceptingHandler;
import io.undertow.server.handlers.RequestLimit;
import io.undertow.server.handlers.RequestLimitingHandler;
import io.undertow.server.handlers.proxy.LoadBalancingProxyClient;
import io.undertow.server.handlers.proxy.ProxyHandler;
import io.undertow.server.handlers.resource.FileResourceManager;
import io.undertow.server.handlers.resource.ResourceHandler;
import io.undertow.util.HttpString;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.GeneralSecurityException;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;
import static org.fusesource.jansi.Ansi.Color.GREEN;
import static org.fusesource.jansi.Ansi.Color.MAGENTA;
import static org.fusesource.jansi.Ansi.Color.RED;
import static org.fusesource.jansi.Ansi.ansi;
import org.fusesource.jansi.AnsiConsole;
import static org.restheart.ConfigurationKeys.STATIC_RESOURCES_MOUNT_EMBEDDED_KEY;
import static org.restheart.ConfigurationKeys.STATIC_RESOURCES_MOUNT_WELCOME_FILE_KEY;
import static org.restheart.ConfigurationKeys.STATIC_RESOURCES_MOUNT_WHAT_KEY;
import static org.restheart.ConfigurationKeys.STATIC_RESOURCES_MOUNT_WHERE_KEY;
import org.restheart.exchange.Exchange;
import static org.restheart.exchange.Exchange.MAX_CONTENT_SIZE;
import org.restheart.exchange.ExchangeKeys;
import org.restheart.exchange.PipelineInfo;
import org.restheart.graal.NativeImageBuildTimeChecker;
import static org.restheart.exchange.PipelineInfo.PIPELINE_TYPE.PROXY;
import static org.restheart.exchange.PipelineInfo.PIPELINE_TYPE.SERVICE;
import static org.restheart.exchange.PipelineInfo.PIPELINE_TYPE.STATIC_RESOURCE;
import org.restheart.handlers.CORSHandler;
import org.restheart.handlers.ConfigurableEncodingHandler;
import org.restheart.handlers.ErrorHandler;
import org.restheart.handlers.PipelinedHandler;
import static org.restheart.handlers.PipelinedHandler.pipe;
import org.restheart.handlers.PipelinedWrappingHandler;
import org.restheart.handlers.QueryStringRebuilder;
import org.restheart.handlers.RequestInterceptorsExecutor;
import org.restheart.handlers.RequestLogger;
import org.restheart.handlers.RequestNotManagedHandler;
import org.restheart.handlers.ResponseInterceptorsExecutor;
import org.restheart.handlers.ResponseSender;
import org.restheart.handlers.ServiceExchangeInitializer;
import org.restheart.handlers.TracingInstrumentationHandler;
import org.restheart.handlers.injectors.AuthHeadersRemover;
import org.restheart.handlers.injectors.ConduitInjector;
import org.restheart.handlers.injectors.PipelineInfoInjector;
import org.restheart.handlers.injectors.RequestContentInjector;
import static org.restheart.handlers.injectors.RequestContentInjector.Policy.ON_REQUIRES_CONTENT_AFTER_AUTH;
import static org.restheart.handlers.injectors.RequestContentInjector.Policy.ON_REQUIRES_CONTENT_BEFORE_AUTH;
import org.restheart.handlers.injectors.XForwardedHeadersInjector;
import org.restheart.handlers.injectors.XPoweredByInjector;
import static org.restheart.plugins.InitPoint.AFTER_STARTUP;
import static org.restheart.plugins.InitPoint.BEFORE_STARTUP;
import static org.restheart.plugins.InterceptPoint.REQUEST_AFTER_AUTH;
import static org.restheart.plugins.InterceptPoint.REQUEST_BEFORE_AUTH;
import org.restheart.plugins.PluginRecord;
import org.restheart.plugins.PluginsRegistryImpl;
import org.restheart.plugins.RegisterPlugin.MATCH_POLICY;
import org.restheart.plugins.security.AuthMechanism;
import org.restheart.plugins.security.Authorizer;
import org.restheart.plugins.security.TokenManager;
import org.restheart.security.handlers.SecurityHandler;
import org.restheart.security.plugins.authorizers.FullAuthorizer;
import org.restheart.utils.FileUtils;
import org.restheart.utils.LoggingInitializer;
import org.restheart.utils.OSChecker;
import static org.restheart.utils.PluginUtils.defaultURI;
import static org.restheart.utils.PluginUtils.uriMatchPolicy;
import static org.restheart.utils.PluginUtils.initPoint;
import org.restheart.utils.RESTHeartDaemon;
import org.restheart.utils.ResourcesExtractor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xnio.OptionMap;
import org.xnio.Options;
import org.xnio.SslClientAuthMode;
import org.xnio.Xnio;
import org.xnio.ssl.XnioSsl;
import org.yaml.snakeyaml.Yaml;
/**
*
* @author Andrea Di Cesare {@literal <andrea@softinstigate.com>}
*/
public class Bootstrapper {
private static final Logger LOGGER = LoggerFactory
.getLogger(Bootstrapper.class);
private static boolean IS_FORKED;
private static final Map<String, File> TMP_EXTRACTED_FILES = new HashMap<>();
private static Path CONFIGURATION_FILE;
private static Path PROPERTIES_FILE;
private static GracefulShutdownHandler HANDLERS = null;
private static Configuration configuration;
private static Undertow undertowServer;
private static final String EXITING = ", exiting...";
private static final String INSTANCE = " instance ";
private static final String STARTING = "Starting ";
private static final String UNDEFINED = "undefined";
private static final String RESTHEART = "RESTHeart";
private static final String VERSION = "Version {}";
/**
* getConfiguration
*
* @return the global configuration
*/
public static Configuration getConfiguration() {
return configuration;
}
private static void parseCommandLineParameters(final String[] args) {
Args parameters = new Args();
CommandLine cmd = new CommandLine(parameters);
//JCommander cmd = JCommander.newBuilder().addObject(parameters).build();
//cmd.setProgramName("java -Dfile.encoding=UTF-8 -jar -server restheart.jar");
try {
cmd.parseArgs(args);
if (cmd.isUsageHelpRequested()) {
cmd.usage(System.out);
System.exit(0);
}
String confFilePath = (parameters.configPath == null)
? System.getenv("RESTHEART__CONFFILE")
: parameters.configPath;
CONFIGURATION_FILE = FileUtils.getFileAbsolutePath(confFilePath);
FileUtils.getFileAbsolutePath(parameters.configPath);
IS_FORKED = parameters.isForked;
String propFilePath = (parameters.envFile == null)
? System.getenv("RESTHEART_ENVFILE")
: parameters.envFile;
PROPERTIES_FILE = FileUtils.getFileAbsolutePath(propFilePath);
} catch (Exception ex) {
LOGGER.error(ex.getMessage());
cmd.usage(System.out);
System.exit(1);
}
}
public static void main(final String[] args) throws ConfigurationException, IOException {
parseCommandLineParameters(args);
setJsonpathDefaults();
configuration = loadConfiguration();
run();
}
/**
* Configuration from JsonPath
*/
private static void setJsonpathDefaults() {
com.jayway.jsonpath.Configuration.setDefaults(
new com.jayway.jsonpath.Configuration.Defaults() {
private final JsonProvider jsonProvider = new GsonJsonProvider();
private final MappingProvider mappingProvider = new GsonMappingProvider();
@Override
public JsonProvider jsonProvider() {
return jsonProvider;
}
@Override
public MappingProvider mappingProvider() {
return mappingProvider;
}
@Override
public Set<com.jayway.jsonpath.Option> options() {
return EnumSet.noneOf(com.jayway.jsonpath.Option.class);
}
});
}
private static void run() {
// we are at runtime. this is used for building native image
NativeImageBuildTimeChecker.atRuntime();
if (!configuration.isAnsiConsole()) {
AnsiConsole.systemInstall();
}
if (!hasForkOption()) {
initLogging(null);
startServer(false);
} else {
if (OSChecker.isWindows()) {
LOGGER.error("Fork is not supported on Windows");
LOGGER.info(ansi().fg(GREEN).bold().a("RESTHeart stopped")
.reset().toString());
System.exit(-1);
}
// RHSecDaemon only works on POSIX OSes
final boolean isPosix = FileSystems.getDefault()
.supportedFileAttributeViews()
.contains("posix");
if (!isPosix) {
logErrorAndExit("Unable to fork process, "
+ "this is only supported on POSIX compliant OSes",
null, false, -1);
}
RESTHeartDaemon d = new RESTHeartDaemon();
if (d.isDaemonized()) {
try {
d.init();
LOGGER.info("Forked process: {}", LIBC.getpid());
initLogging(d);
} catch (Exception t) {
logErrorAndExit("Error staring forked process", t, false, false, -1);
}
startServer(true);
} else {
initLogging(d);
try {
logWindowsStart();
logLoggingConfiguration(true);
logManifestInfo();
d.daemonize();
} catch (Throwable t) {
logErrorAndExit("Error forking", t, false, false, -1);
}
}
}
}
private static void logWindowsStart() {
String version = Version.getInstance().getVersion() == null
? "Unknown, not packaged"
: Version.getInstance().getVersion();
String info = String.format(" {%n"
+ " \"Version\": \"%s\",%n"
+ " \"Instance-Name\": \"%s\",%n"
+ " \"Configuration\": \"%s\",%n"
+ " \"Environment\": \"%s\",%n"
+ " \"Build-Time\": \"%s\"%n"
+ " }",
ansi().fg(MAGENTA).a(version).reset().toString(),
ansi().fg(MAGENTA).a(getInstanceName()).reset().toString(),
ansi().fg(MAGENTA).a(CONFIGURATION_FILE).reset().toString(),
ansi().fg(MAGENTA).a(PROPERTIES_FILE).reset().toString(),
ansi().fg(MAGENTA).a(Version.getInstance().getBuildTime()).reset().toString());
LOGGER.info("Starting {}\n{}", ansi().fg(RED).a(RESTHEART).reset().toString(), info);
}
private static void logManifestInfo() {
if (LOGGER.isDebugEnabled()) {
final Set<Map.Entry<Object, Object>> MANIFEST_ENTRIES = FileUtils.findManifestInfo();
if (MANIFEST_ENTRIES != null) {
LOGGER.debug("Build Information: {}", MANIFEST_ENTRIES.toString());
} else {
LOGGER.debug("Build Information: {}", "Unknown, not packaged");
}
}
}
private static Configuration loadConfiguration() throws ConfigurationException, UnsupportedEncodingException {
if (CONFIGURATION_FILE == null) {
LOGGER.warn("No configuration file provided, starting with default values!");
return new Configuration();
} else if (PROPERTIES_FILE == null) {
try {
if (Configuration.isParametric(CONFIGURATION_FILE)) {
logErrorAndExit("Configuration is parametric but no properties file has been specified."
+ " You can use -e option to specify the properties file. "
+ "For more information check https://restheart.org/docs/setup/#configuration-files",
null, false, -1);
}
} catch (IOException ioe) {
logErrorAndExit("Configuration file not found " + CONFIGURATION_FILE, null, false, -1);
}
return new Configuration(CONFIGURATION_FILE, false);
} else {
final Properties p = new Properties();
try (InputStreamReader reader = new InputStreamReader(
new FileInputStream(PROPERTIES_FILE.toFile()), "UTF-8")) {
p.load(reader);
} catch (FileNotFoundException fnfe) {
logErrorAndExit("Properties file not found " + PROPERTIES_FILE, null, false, -1);
} catch (IOException ieo) {
logErrorAndExit("Error reading properties file " + PROPERTIES_FILE, null, false, -1);
}
final StringWriter writer = new StringWriter();
try (BufferedReader reader = new BufferedReader(new FileReader(CONFIGURATION_FILE.toFile()))) {
Mustache m = new DefaultMustacheFactory().compile(reader, "configuration-file");
m.execute(writer, p);
writer.flush();
} catch (MustacheNotFoundException ex) {
logErrorAndExit("Configuration file not found: " + CONFIGURATION_FILE, ex, false, -1);
} catch (FileNotFoundException fnfe) {
logErrorAndExit("Configuration file not found " + CONFIGURATION_FILE, null, false, -1);
} catch (IOException ieo) {
logErrorAndExit("Error reading configuration file " + CONFIGURATION_FILE, null, false, -1);
}
Map<String, Object> obj = new Yaml().load(writer.toString());
return new Configuration(obj, false);
}
}
private static void logStartMessages() {
String instanceName = getInstanceName();
LOGGER.info(STARTING + ansi().fg(RED).bold().a(RESTHEART).reset().toString()
+ INSTANCE
+ ansi().fg(RED).bold().a(instanceName).reset().toString());
LOGGER.info(VERSION, Configuration.VERSION);
LOGGER.debug("Configuration = " + configuration.toString());
}
/**
* logs warning message if pid file exists
*
* @param confFilePath
* @param propFilePath
* @return true if pid file exists
*/
private static boolean checkPidFile(Path confFilePath, Path propFilePath) {
if (OSChecker.isWindows()) {
return false;
}
// pid file name include the hash of the configuration file so that
// for each configuration we can have just one instance running
Path pidFilePath = FileUtils
.getPidFilePath(FileUtils.getFileAbsolutePathHash(confFilePath, propFilePath));
if (Files.exists(pidFilePath)) {
LOGGER.warn("Found pid file! If this instance is already "
+ "running, startup will fail with a BindException");
return true;
}
return false;
}
/**
* Shutdown the server
*
* @param args command line arguments
*/
public static void shutdown(final String[] args) {
stopServer(false);
}
/**
* initLogging
*
* @param args
* @param d
*/
private static void initLogging(final RESTHeartDaemon d) {
LoggingInitializer.setLogLevel(configuration.getLogLevel());
if (d != null && d.isDaemonized()) {
LoggingInitializer.stopConsoleLogging();
LoggingInitializer.startFileLogging(configuration
.getLogFilePath());
} else if (!hasForkOption()) {
if (!configuration.isLogToConsole()) {
LoggingInitializer.stopConsoleLogging();
}
if (configuration.isLogToFile()) {
LoggingInitializer.startFileLogging(configuration
.getLogFilePath());
}
}
}
/**
* logLoggingConfiguration
*
* @param fork
*/
private static void logLoggingConfiguration(boolean fork) {
String logbackConfigurationFile = System
.getProperty("logback.configurationFile");
boolean usesLogback = logbackConfigurationFile != null
&& !logbackConfigurationFile.isEmpty();
if (usesLogback) {
return;
}
if (configuration.isLogToFile()) {
LOGGER.info("Logging to file {} with level {}",
configuration.getLogFilePath(),
configuration.getLogLevel());
}
if (!fork) {
if (!configuration.isLogToConsole()) {
LOGGER.info("Stop logging to console ");
} else {
LOGGER.info("Logging to console with level {}",
configuration.getLogLevel());
}
}
}
/**
* hasForkOption
*
* @param args
* @return true if has fork option
*/
private static boolean hasForkOption() {
return IS_FORKED;
}
/**
* startServer
*
* @param fork
*/
private static void startServer(boolean fork) {
logStartMessages();
Path pidFilePath = FileUtils.getPidFilePath(
FileUtils.getFileAbsolutePathHash(CONFIGURATION_FILE, PROPERTIES_FILE));
boolean pidFileAlreadyExists = false;
if (!OSChecker.isWindows() && pidFilePath != null) {
pidFileAlreadyExists = checkPidFile(CONFIGURATION_FILE, PROPERTIES_FILE);
}
logLoggingConfiguration(fork);
logManifestInfo();
// re-read configuration file, to log errors new that logger is initialized
try {
loadConfiguration();
} catch (ConfigurationException | IOException ex) {
logErrorAndExit(ex.getMessage() + EXITING, ex, false, -1);
}
// force instantiation of all plugins singletons
try {
PluginsRegistryImpl.getInstance().instantiateAll();
} catch (IllegalArgumentException iae) {
// this occurs instatiating plugin missing external dependencies
if (iae.getMessage() != null
&& iae.getMessage().contains("NoClassDefFoundError")) {
logErrorAndExit("Error instantiating plugins: "
+ "an external dependency is missing. "
+ "Copy the missing dependency jar to the plugins directory to add it to the classpath",
iae, false, -112);
} else {
logErrorAndExit("Error instantiating plugins", iae, false, -110);
}
} catch (NoClassDefFoundError ncdfe) {
// this occurs instatiating plugin missing external dependencies
logErrorAndExit("Error instantiating plugins: "
+ "an external dependency is missing. "
+ "Copy the missing dependency jar to the plugins directory to add it to the classpath",
ncdfe, false, -112);
} catch (LinkageError le) {
// this occurs executing plugin code compiled
// with wrong version of restheart-commons
String version = Version.getInstance().getVersion() == null
? "of correct version"
: "v" + Version.getInstance().getVersion();
logErrorAndExit("Linkage error instantiating plugins "
+ "Check that all plugins were compiled against restheart-commons "
+ version, le, false, -111);
} catch (Throwable t) {
logErrorAndExit("Error instantiating plugins", t, false, -110);
}
// run pre startup initializers
PluginsRegistryImpl.getInstance()
.getInitializers()
.stream()
.filter(i -> initPoint(i.getInstance()) == BEFORE_STARTUP)
.forEach(i -> {
try {
i.getInstance().init();
} catch (NoClassDefFoundError iae) {
// this occurs executing interceptors missing external dependencies
LOGGER.error("Error executing initializer {} "
+ "An external dependency is missing. "
+ "Copy the missing dependency jar to the plugins directory to add it to the classpath",
i.getName(), iae);
} catch (LinkageError le) {
// this occurs executing plugin code compiled
// with wrong version of restheart-commons
String version = Version.getInstance().getVersion() == null
? "of correct version"
: "v" + Version.getInstance().getVersion();
LOGGER.error("Linkage error executing initializer {} "
+ "Check that it was compiled against restheart-commons {}",
i.getName(), version, le);
} catch (Throwable t) {
LOGGER.error("Error executing initializer {}", i.getName());
}
});
try {
startCoreSystem();
} catch (Throwable t) {
logErrorAndExit("Error starting RESTHeart. Exiting...",
t,
false,
!pidFileAlreadyExists, -2);
}
Runtime.getRuntime()
.addShutdownHook(new Thread() {
@Override
public void run() {
stopServer(false);
}
}
);
// create pid file on supported OSes
if (!OSChecker.isWindows()
&& pidFilePath != null) {
FileUtils.createPidFile(pidFilePath);
}
// log pid file path on supported OSes
if (!OSChecker.isWindows()
&& pidFilePath != null) {
LOGGER.info("Pid file {}", pidFilePath);
}
// run initializers
PluginsRegistryImpl.getInstance()
.getInitializers()
.stream()
.filter(i -> initPoint(i.getInstance()) == AFTER_STARTUP)
.forEach(i -> {
try {
i.getInstance().init();
} catch (NoClassDefFoundError iae) {
// this occurs executing interceptors missing external dependencies
LOGGER.error("Error executing initializer {} "
+ "An external dependency is missing. "
+ "Copy the missing dependency jar to the plugins directory to add it to the classpath",
i.getName(), iae);
} catch (LinkageError le) {
// this occurs executing plugin code compiled
// with wrong version of restheart-commons
String version = Version.getInstance().getVersion() == null
? "of correct version"
: "v" + Version.getInstance().getVersion();
LOGGER.error("Linkage error executing initializer {} "
+ "Check that it was compiled against restheart-commons {}",
i.getName(), version, le);
} catch (Throwable t) {
LOGGER.error("Error executing initializer {}",
i.getName(),
t);
}
});
LOGGER.info(ansi().fg(GREEN).bold().a("RESTHeart started").reset().toString());
}
private static String getInstanceName() {
return configuration == null ? UNDEFINED
: configuration.getInstanceName() == null
? UNDEFINED
: configuration.getInstanceName();
}
/**
* stopServer
*
* @param silent
*/
private static void stopServer(boolean silent) {
stopServer(silent, true);
}
/**
* stopServer
*
* @param silent
* @param removePid
*/
private static void stopServer(boolean silent, boolean removePid) {
if (!silent) {
LOGGER.info("Stopping RESTHeart...");
}
if (HANDLERS != null) {
if (!silent) {
LOGGER.info("Waiting for pending request "
+ "to complete (up to 1 minute)...");
}
try {
HANDLERS.shutdown();
HANDLERS.awaitShutdown(60 * 1000); // up to 1 minute
} catch (InterruptedException ie) {
LOGGER.error("Error while waiting for pending request "
+ "to complete", ie);
Thread.currentThread().interrupt();
}
}
Path pidFilePath = FileUtils.getPidFilePath(FileUtils
.getFileAbsolutePathHash(CONFIGURATION_FILE, PROPERTIES_FILE));
if (removePid && pidFilePath != null) {
if (!silent) {
LOGGER.info("Removing the pid file {}",
pidFilePath.toString());
}
try {
Files.deleteIfExists(pidFilePath);
} catch (IOException ex) {
LOGGER.error("Can't delete pid file {}",
pidFilePath.toString(), ex);
}
}
if (!silent) {
LOGGER.info("Cleaning up temporary directories...");
}
TMP_EXTRACTED_FILES.keySet().forEach(k -> {
try {
ResourcesExtractor.deleteTempDir(Bootstrapper.class,
k,
TMP_EXTRACTED_FILES.get(k));
} catch (URISyntaxException | IOException ex) {
LOGGER.error("Error cleaning up temporary directory {}",
TMP_EXTRACTED_FILES.get(k).toString(), ex);
}
});
if (undertowServer != null) {
undertowServer.stop();
}
if (!silent) {
LOGGER.info(ansi().fg(GREEN).bold().a("RESTHeart stopped")
.reset().toString());
}
LoggingInitializer.stopLogging();
}
/**
* startCoreSystem
*/
private static void startCoreSystem() {
if (configuration == null) {
logErrorAndExit("No configuration found. exiting..", null, false, -1);
}
if (!configuration.isHttpsListener()
&& !configuration.isHttpListener()
&& !configuration.isAjpListener()) {
logErrorAndExit("No listener specified. exiting..", null, false, -1);
}
final var tokenManager = PluginsRegistryImpl.getInstance()
.getTokenManager();
final var authMechanisms = PluginsRegistryImpl
.getInstance()
.getAuthMechanisms();
if (authMechanisms == null || authMechanisms.isEmpty()) {
LOGGER.warn(ansi().fg(RED).bold()
.a("No Authentication Mechanisms defined")
.reset().toString());
}
final var authorizers = PluginsRegistryImpl
.getInstance()
.getAuthorizers();
if (authorizers == null || authorizers.isEmpty()) {
LOGGER.warn(ansi().fg(RED).bold()
.a("No Authorizers defined")
.reset().toString());
}
SSLContext sslContext = null;
try {
sslContext = SSLContext.getInstance("TLS");
KeyManagerFactory kmf = KeyManagerFactory
.getInstance(KeyManagerFactory.getDefaultAlgorithm());
TrustManagerFactory tmf = TrustManagerFactory
.getInstance(TrustManagerFactory.getDefaultAlgorithm());
KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
if (getConfiguration().isUseEmbeddedKeystore()) {
char[] storepass = "restheart".toCharArray();
char[] keypass = "restheart".toCharArray();
String storename = "sskeystore.jks";
ks.load(Bootstrapper.class
.getClassLoader()
.getResourceAsStream(storename), storepass);
kmf.init(ks, keypass);
} else if (configuration.getKeystoreFile() != null
&& configuration.getKeystorePassword() != null
&& configuration.getCertPassword() != null) {
try (FileInputStream fis = new FileInputStream(
new File(configuration.getKeystoreFile()))) {
ks.load(fis, configuration.getKeystorePassword().toCharArray());
kmf.init(ks, configuration.getCertPassword().toCharArray());
}
} else {
LOGGER.error(
"The keystore is not configured. "
+ "Check the keystore-file, "
+ "keystore-password and certpassword options.");
}
tmf.init(ks);
sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
} catch (KeyManagementException
| NoSuchAlgorithmException
| KeyStoreException
| CertificateException
| UnrecoverableKeyException ex) {
logErrorAndExit(
"Couldn't start RESTHeart, error with specified keystore. "
+ "Check the keystore-file, "
+ "keystore-password and certpassword options. Exiting..",
ex, false, -1);
} catch (FileNotFoundException ex) {
logErrorAndExit(
"Couldn't start RESTHeart, keystore file not found. "
+ "Check the keystore-file, "
+ "keystore-password and certpassword options. Exiting..",
ex, false, -1);
} catch (IOException ex) {
logErrorAndExit(
"Couldn't start RESTHeart, error reading the keystore file. "
+ "Check the keystore-file, "
+ "keystore-password and certpassword options. Exiting..",
ex, false, -1);
}
Builder builder = Undertow.builder();
if (configuration.isHttpsListener()) {
builder.addHttpsListener(configuration.getHttpsPort(),
configuration.getHttpsHost(),
sslContext);
if (configuration.getHttpsHost().equals("127.0.0.1")
|| configuration.getHttpsHost().equalsIgnoreCase("localhost")) {
LOGGER.warn("HTTPS listener bound to localhost:{}. "
+ "Remote systems will be unable to connect to this server.",
configuration.getHttpsPort());
} else {
LOGGER.info("HTTPS listener bound at {}:{}",
configuration.getHttpsHost(), configuration.getHttpsPort());
}
}
if (configuration.isHttpListener()) {
builder.addHttpListener(configuration.getHttpPort(),
configuration.getHttpHost());
if (configuration.getHttpHost().equals("127.0.0.1")
|| configuration.getHttpHost().equalsIgnoreCase("localhost")) {
LOGGER.warn("HTTP listener bound to localhost:{}. "
+ "Remote systems will be unable to connect to this server.",
configuration.getHttpPort());
} else {
LOGGER.info("HTTP listener bound at {}:{}",
configuration.getHttpHost(), configuration.getHttpPort());
}
}
if (configuration.isAjpListener()) {
builder.addAjpListener(configuration.getAjpPort(),
configuration.getAjpHost());
if (configuration.getAjpHost().equals("127.0.0.1")
|| configuration.getAjpHost().equalsIgnoreCase("localhost")) {
LOGGER.warn("AJP listener bound to localhost:{}. "
+ "Remote systems will be unable to connect to this server.",
configuration.getAjpPort());
} else {
LOGGER.info("AJP listener bound at {}:{}",
configuration.getAjpHost(), configuration.getAjpPort());
}
}
HANDLERS = getPipeline(authMechanisms,
authorizers,
tokenManager);
// update buffer size in
Exchange.updateBufferSize(configuration.getBufferSize());
builder = builder
.setIoThreads(configuration.getIoThreads())
.setWorkerThreads(configuration.getWorkerThreads())
.setDirectBuffers(configuration.isDirectBuffers())
.setBufferSize(configuration.getBufferSize())
.setHandler(HANDLERS);
// starting from undertow 1.4.23 URL checks become much stricter
// (undertow commit 09d40a13089dbff37f8c76d20a41bf0d0e600d9d)
// allow unescaped chars in URL (otherwise not allowed by default)
builder.setServerOption(UndertowOptions.ALLOW_UNESCAPED_CHARACTERS_IN_URL,
configuration.isAllowUnescapedCharactersInUrl());
LOGGER.debug("Allow unescaped characters in URL: {}",
configuration.isAllowUnescapedCharactersInUrl());
ConfigurationHelper.setConnectionOptions(builder, configuration);
undertowServer = builder.build();
undertowServer.start();
}
/**
* logErrorAndExit
*
* @param message
* @param t
* @param silent
* @param status
*/
private static void logErrorAndExit(String message,
Throwable t,
boolean silent,
int status) {
logErrorAndExit(message, t, silent, true, status);
}
/**
* logErrorAndExit
*
* @param message
* @param t
* @param silent
* @param removePid
* @param status
*/
private static void logErrorAndExit(String message,
Throwable t,
boolean silent,
boolean removePid,
int status) {
if (t == null) {
LOGGER.error(message);
} else {
LOGGER.error(message, t);
}
stopServer(silent, removePid);
System.exit(status);
}
/**
* getHandlersPipe
*
* @param identityManager
* @param authorizers
* @param tokenManager
* @return a GracefulShutdownHandler
*/
private static GracefulShutdownHandler getPipeline(
final Set<PluginRecord<AuthMechanism>> authMechanisms,
final Set<PluginRecord<Authorizer>> authorizers,
final PluginRecord<TokenManager> tokenManager
) {
PluginsRegistryImpl
.getInstance()
.getRootPathHandler()
.addPrefixPath("/", new RequestNotManagedHandler());
LOGGER.debug("Content buffers maximun size "
+ "is {} bytes",
MAX_CONTENT_SIZE);
plugServices(authMechanisms, authorizers, tokenManager);
plugProxies(configuration, authMechanisms, authorizers, tokenManager);
plugStaticResourcesHandlers(configuration);
return getBasePipeline();
}
/**
* buildGracefulShutdownHandler
*
* @param paths
* @return
*/
private static GracefulShutdownHandler getBasePipeline() {
return new GracefulShutdownHandler(
new RequestLimitingHandler(
new RequestLimit(configuration.getRequestsLimit()),
new AllowedMethodsHandler(
new BlockingHandler(
new ErrorHandler(
new HttpContinueAcceptingHandler(
PluginsRegistryImpl
.getInstance()
.getRootPathHandler()))),
// allowed methods
HttpString.tryFromString(ExchangeKeys.METHOD.GET.name()),
HttpString.tryFromString(ExchangeKeys.METHOD.POST.name()),
HttpString.tryFromString(ExchangeKeys.METHOD.PUT.name()),
HttpString.tryFromString(ExchangeKeys.METHOD.DELETE.name()),
HttpString.tryFromString(ExchangeKeys.METHOD.PATCH.name()),
HttpString.tryFromString(ExchangeKeys.METHOD.OPTIONS.name()))));
}
/**
* plug services
*
* @param paths
* @param mechanisms
* @param authorizers
* @param tokenManager
*/
@SuppressWarnings("unchecked")
private static void plugServices(final Set<PluginRecord<AuthMechanism>> mechanisms,
final Set<PluginRecord<Authorizer>> authorizers,
final PluginRecord<TokenManager> tokenManager) {
PluginsRegistryImpl.getInstance().getServices().stream().forEach(srv -> {
var srvConfArgs = srv.getConfArgs();
String uri;
MATCH_POLICY mp = uriMatchPolicy(srv.getInstance());
if (srvConfArgs == null
|| !srvConfArgs.containsKey("uri")
|| srvConfArgs.get("uri") == null) {
uri = defaultURI(srv.getInstance());
} else {
if (!(srvConfArgs.get("uri") instanceof String)) {
LOGGER.error("Cannot start service {}:"
+ " the configuration property 'uri' must be a string",
srv.getName());
return;
} else {
uri = (String) srvConfArgs.get("uri");
}
}
if (uri == null) {
LOGGER.error("Cannot start service {}:"
+ " the configuration property 'uri' is not defined"
+ " and the service does not have a default value",
srv.getName());
return;
}
if (!uri.startsWith("/")) {
LOGGER.error("Cannot start service {}:"
+ " the configuration property 'uri' must start with /",
srv.getName(),
uri);
return;
}
boolean secured = srvConfArgs != null
&& srvConfArgs.containsKey("secured")
&& srvConfArgs.get("secured") instanceof Boolean
? (boolean) srvConfArgs.get("secured")
: false;
SecurityHandler securityHandler;
if (secured) {
securityHandler = new SecurityHandler(
mechanisms,
authorizers,
tokenManager);
} else {
var _fauthorizers = new LinkedHashSet<PluginRecord<Authorizer>>();
PluginRecord<Authorizer> _fauthorizer = new PluginRecord<>(
"fullAuthorizer",
"authorize any operation to any user",
true,
FullAuthorizer.class
.getName(),
new FullAuthorizer(false),
null
);
_fauthorizers.add(_fauthorizer);
securityHandler = new SecurityHandler(
mechanisms,
_fauthorizers,
tokenManager);
}
var _srv = pipe(new PipelineInfoInjector(),
new TracingInstrumentationHandler(),
new RequestLogger(),
new ServiceExchangeInitializer(),
new CORSHandler(),
new XPoweredByInjector(),
new RequestInterceptorsExecutor(REQUEST_BEFORE_AUTH),
new QueryStringRebuilder(),
securityHandler,
new RequestInterceptorsExecutor(REQUEST_AFTER_AUTH),
new QueryStringRebuilder(),
PipelinedWrappingHandler
.wrap(new ConfigurableEncodingHandler(
PipelinedWrappingHandler
.wrap(srv.getInstance()),
configuration.isForceGzipEncoding())),
new ResponseInterceptorsExecutor(),
new ResponseSender()
);
PluginsRegistryImpl
.getInstance()
.plugPipeline(uri, _srv,
new PipelineInfo(SERVICE, uri, mp, srv.getName()));
LOGGER.info(ansi().fg(GREEN)
.a("URI {} bound to service {}, secured: {}, uri match {}")
.reset().toString(), uri, srv.getName(), secured, mp);
});
}
/**
* plugProxies
*
* @param conf
* @param paths
* @param authMechanisms
* @param identityManager
* @param authorizers
*/
private static void plugProxies(final Configuration conf,
final Set<PluginRecord<AuthMechanism>> authMechanisms,
final Set<PluginRecord<Authorizer>> authorizers,
final PluginRecord<TokenManager> tokenManager) {
if (conf.getProxies() == null || conf.getProxies().isEmpty()) {
LOGGER.debug("No {} specified", ConfigurationKeys.PROXY_KEY);
return;
}
conf.getProxies().stream().forEachOrdered((Map<String, Object> proxies) -> {
String location = Configuration.getOrDefault(proxies,
ConfigurationKeys.PROXY_LOCATION_KEY, null, true);
Object _proxyPass = Configuration.getOrDefault(proxies,
ConfigurationKeys.PROXY_PASS_KEY, null, true);
if (location == null && _proxyPass != null) {
LOGGER.warn("Location URI not specified for resource {} ",
_proxyPass);
return;
}
if (location == null && _proxyPass == null) {
LOGGER.warn("Invalid proxies entry detected");
return;
}
// The number of connections to create per thread
Integer connectionsPerThread = Configuration.getOrDefault(proxies,
ConfigurationKeys.PROXY_CONNECTIONS_PER_THREAD, 10,
true);
Integer maxQueueSize = Configuration.getOrDefault(proxies,
ConfigurationKeys.PROXY_MAX_QUEUE_SIZE, 0, true);
Integer softMaxConnectionsPerThread = Configuration.getOrDefault(proxies,
ConfigurationKeys.PROXY_SOFT_MAX_CONNECTIONS_PER_THREAD, 5, true);
Integer ttl = Configuration.getOrDefault(proxies,
ConfigurationKeys.PROXY_TTL, -1, true);
boolean rewriteHostHeader = Configuration.getOrDefault(proxies,
ConfigurationKeys.PROXY_REWRITE_HOST_HEADER, true, true);
// Time in seconds between retries for problem server
Integer problemServerRetry = Configuration.getOrDefault(proxies,
ConfigurationKeys.PROXY_PROBLEM_SERVER_RETRY, 10,
true);
String name = Configuration.getOrDefault(proxies,
ConfigurationKeys.PROXY_NAME, null,
true);
final Xnio xnio = Xnio.getInstance();
final OptionMap optionMap = OptionMap.create(
Options.SSL_CLIENT_AUTH_MODE,
SslClientAuthMode.REQUIRED,
Options.SSL_STARTTLS,
true);
XnioSsl sslProvider = null;
try {
sslProvider = xnio.getSslProvider(optionMap);
} catch (GeneralSecurityException ex) {
logErrorAndExit("error configuring ssl", ex, false, -13);
}
try {
LoadBalancingProxyClient proxyClient
= new LoadBalancingProxyClient()
.setConnectionsPerThread(connectionsPerThread)
.setSoftMaxConnectionsPerThread(softMaxConnectionsPerThread)
.setMaxQueueSize(maxQueueSize)
.setProblemServerRetry(problemServerRetry)
.setTtl(ttl);
if (_proxyPass instanceof String) {
proxyClient = proxyClient.addHost(
new URI((String) _proxyPass), sslProvider);
} else if (_proxyPass instanceof List) {
for (Object proxyPassURL : ((Iterable<? extends Object>) _proxyPass)) {
if (proxyPassURL instanceof String) {
proxyClient = proxyClient.addHost(
new URI((String) proxyPassURL), sslProvider);
} else {
LOGGER.warn("Invalid proxy pass URL {}, location {} not bound ",
proxyPassURL, location);
}
}
} else {
LOGGER.warn("Invalid proxy pass URL {}, location {} not bound ",
_proxyPass);
}
ProxyHandler proxyHandler = ProxyHandler.builder()
.setRewriteHostHeader(rewriteHostHeader)
.setProxyClient(proxyClient)
.build();
var proxy = pipe(
new PipelineInfoInjector(),
new TracingInstrumentationHandler(),
new RequestLogger(),
new XPoweredByInjector(),
new RequestContentInjector(ON_REQUIRES_CONTENT_BEFORE_AUTH),
new RequestInterceptorsExecutor(REQUEST_BEFORE_AUTH),
new QueryStringRebuilder(),
new SecurityHandler(
authMechanisms,
authorizers,
tokenManager),
new AuthHeadersRemover(),
new XForwardedHeadersInjector(),
new RequestContentInjector(ON_REQUIRES_CONTENT_AFTER_AUTH),
new RequestInterceptorsExecutor(REQUEST_AFTER_AUTH),
new QueryStringRebuilder(),
new ConduitInjector(),
PipelinedWrappingHandler.wrap(
new ConfigurableEncodingHandler( // Must be after ConduitInjector
proxyHandler,
configuration.isForceGzipEncoding())));
PluginsRegistryImpl
.getInstance()
.plugPipeline(location, proxy,
new PipelineInfo(PROXY, location, name));
LOGGER.info(ansi().fg(GREEN)
.a("URI {} bound to proxy resource {}")
.reset().toString(), location, _proxyPass);
} catch (URISyntaxException ex) {
LOGGER.warn("Invalid location URI {}, resource {} not bound ",
location,
_proxyPass);
}
});
}
/**
* plugStaticResourcesHandlers
*
* plug the static resources specified in the configuration file
*
* @param conf
* @param pathHandler
* @param authenticationMechanism
* @param identityManager
* @param accessManager
*/
private static void plugStaticResourcesHandlers(
final Configuration conf) {
if (!conf.getStaticResourcesMounts().isEmpty()) {
conf.getStaticResourcesMounts().stream().forEach(sr -> {
try {
String path = (String) sr.get(STATIC_RESOURCES_MOUNT_WHAT_KEY);
String where = (String) sr.get(STATIC_RESOURCES_MOUNT_WHERE_KEY);
String welcomeFile = (String) sr.get(STATIC_RESOURCES_MOUNT_WELCOME_FILE_KEY);
Boolean embedded = (Boolean) sr.get(STATIC_RESOURCES_MOUNT_EMBEDDED_KEY);
if (embedded == null) {
embedded = false;
}
if (where == null || !where.startsWith("/")) {
LOGGER.error("Cannot bind static resources to {}. "
+ "parameter 'where' must start with /", where);
return;
}
if (welcomeFile == null) {
welcomeFile = "index.html";
}
File file;
if (embedded) {
if (path.startsWith("/")) {
LOGGER.error("Cannot bind embedded static resources to {}. parameter 'where'"
+ "cannot start with /. the path is relative to the jar root dir"
+ " or classpath directory", where);
return;
}
try {
file = ResourcesExtractor.extract(Bootstrapper.class,
path);
if (ResourcesExtractor.isResourceInJar(Bootstrapper.class,
path)) {
TMP_EXTRACTED_FILES.put(path, file);
LOGGER.info("Embedded static resources {} extracted in {}", path, file.toString());
}
} catch (URISyntaxException | IOException | IllegalStateException ex) {
LOGGER.error("Error extracting embedded static resource {}", path, ex);
return;
}
} else if (!path.startsWith("/")) {
// this is to allow specifying the configuration file path relative
// to the jar (also working when running from classes)
URL location = Bootstrapper.class
.getProtectionDomain()
.getCodeSource()
.getLocation();
File locationFile = new File(location.getPath());
Path _path = Paths.get(
locationFile.getParent()
.concat(File.separator)
.concat(path));
file = _path.normalize().toFile();
} else {
file = new File(path);
}
if (file.exists()) {
ResourceHandler handler = resource(new FileResourceManager(file, 3))
.addWelcomeFiles(welcomeFile)
.setDirectoryListingEnabled(false);
PipelinedHandler ph = PipelinedHandler.pipe(
new PipelineInfoInjector(),
new RequestLogger(),
PipelinedWrappingHandler.wrap(handler)
);
PluginsRegistryImpl
.getInstance()
.plugPipeline(where, ph,
new PipelineInfo(STATIC_RESOURCE,
where,
path));
LOGGER.info(ansi().fg(GREEN)
.a("URI {} bound to static resource {}")
.reset().toString(), where, file.getAbsolutePath());
} else {
LOGGER.error("Failed to bind URL {} to static resources {}."
+ " Directory does not exist.", where, path);
}
} catch (Throwable t) {
LOGGER.error("Cannot bind static resources to {}",
sr.get(STATIC_RESOURCES_MOUNT_WHERE_KEY), t);
}
});
}
}
private Bootstrapper() {
}
@Command(name="java -Dfile.encoding=UTF-8 -jar -server restheart.jar")
private static class Args {
@Parameters(index = "0", paramLabel = "FILE", description = "Main configuration file")
private String configPath = null;
@Option(names = "--fork", description = "Fork the process in background")
private boolean isForked = false;
@Option(names = {"-e", "--envFile", "--envfile"}, description = "Environment file name")
private String envFile = null;
@Option(names = {"-h", "--help"}, usageHelp = true, description = "This help message")
private boolean help = false;
}
}
|
package com.gallatinsystems.framework.dao;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Logger;
import java.util.regex.Pattern;
import javax.jdo.JDOObjectNotFoundException;
import javax.jdo.PersistenceManager;
import net.sf.jsr107cache.CacheException;
import org.datanucleus.store.appengine.query.JDOCursorHelper;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.waterforpeople.mapping.app.web.rest.security.AppRole;
import com.gallatinsystems.common.Constants;
import com.gallatinsystems.framework.domain.BaseDomain;
import com.gallatinsystems.framework.servlet.PersistenceFilter;
import com.gallatinsystems.survey.dao.SurveyUtils;
import com.gallatinsystems.survey.domain.Survey;
import com.gallatinsystems.survey.domain.SurveyGroup;
import com.gallatinsystems.user.dao.UserAuthorizationDAO;
import com.gallatinsystems.user.domain.UserAuthorization;
import com.google.appengine.api.datastore.Cursor;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
/**
* This is a reusable data access object that supports basic operations (save, find by property,
* list).
*
* @author Christopher Fagiani
* @param <T>
* a persistent class that extends BaseDomain
*/
public class BaseDAO<T extends BaseDomain> {
public static final int DEFAULT_RESULT_COUNT = 20;
protected static final int RETRY_INTERVAL_MILLIS = 200;
protected static final String STRING_TYPE = "String";
protected static final String NOT_EQ_OP = "!=";
protected static final String EQ_OP = " == ";
protected static final String GTE_OP = " >= ";
protected static final String LTE_OP = " <= ";
private Class<T> concreteClass;
protected Logger log;
public enum CURSOR_TYPE {
all
};
public BaseDAO(Class<T> e) {
setDomainClass(e);
log = Logger.getLogger(this.getClass().getName());
}
/**
* Injected version of the actual Class to pass for the persistentClass in the query creation.
* This must be set before using this implementation class or any derived class.
*
* @param e
* an instance of the type of object to use for this instance of the DAO
* implementation.
*/
public void setDomainClass(Class<T> e) {
this.concreteClass = e;
}
/**
* saves an object to the data store. This method will set the lastUpdateDateTime on the domain
* object prior to saving and will set the createdDateTime (if it is null).
*
* @param <E>
* @param obj
* @return
*/
public <E extends BaseDomain> E save(E obj) {
PersistenceManager pm = PersistenceFilter.getManager();
obj.setLastUpdateDateTime(new Date());
if (obj.getCreatedDateTime() == null) {
obj.setCreatedDateTime(obj.getLastUpdateDateTime());
}
obj = pm.makePersistent(obj);
return obj;
}
/**
* saves all instances contained within the collection passed in. This will set the
* lastUpdateDateTime for the objects prior to saving.
*
* @param <E>
* @param objList
* @return
*/
public <E extends BaseDomain> Collection<E> save(Collection<E> objList) {
if (objList != null) {
for (E item : objList) {
item.setLastUpdateDateTime(new Date());
if (item.getCreatedDateTime() == null) {
item.setCreatedDateTime(item.getLastUpdateDateTime());
}
}
PersistenceManager pm = PersistenceFilter.getManager();
objList = pm.makePersistentAll(objList);
}
return objList;
}
/**
* gets the core persistent object for the dao concrete class using the string key (obtained
* from KeyFactory.stringFromKey())
*
* @param keyString
* @return
*/
public T getByKey(String keyString) {
return getByKey(keyString, concreteClass);
}
/**
* gets an object by key
*
* @param key
* @return
*/
public T getByKey(Key key) {
return getByKey(key, concreteClass);
}
/**
* convenience method to allow loading of other persistent objects by key from this dao
*
* @param keyString
* @return
*/
public <E extends BaseDomain> E getByKey(String keyString, Class<E> clazz) {
PersistenceManager pm = PersistenceFilter.getManager();
E result = null;
Key k = KeyFactory.stringToKey(keyString);
try {
result = pm.getObjectById(clazz, k);
} catch (JDOObjectNotFoundException nfe) {
log.warning("No " + clazz.getCanonicalName() + " found with key: "
+ k);
}
return result;
}
/**
* gets a single object identified by the key passed in.
*
* @param <E>
* @param key
* @param clazz
* @return the object corresponding to the key (or null if not found)
*/
public <E extends BaseDomain> E getByKey(Key key, Class<E> clazz) {
PersistenceManager pm = PersistenceFilter.getManager();
E result = null;
try {
result = pm.getObjectById(clazz, key);
} catch (JDOObjectNotFoundException nfe) {
log.warning("No " + clazz.getCanonicalName() + " found with key: "
+ key);
}
return result;
}
/**
* gets a single object by key where the key is represented as a Long
*
* @param id
* @return
*/
public T getByKey(Long id) {
return getByKey(id, concreteClass);
}
/**
* gets a single object by key where the key is represented as a Long and the type is the class
* passed in via clazz
*
* @param <E>
* @param id
* @param clazz
* @return
*/
public <E extends BaseDomain> E getByKey(Long id, Class<E> clazz) {
PersistenceManager pm = PersistenceFilter.getManager();
String itemKey = KeyFactory.createKeyString(clazz.getSimpleName(), id);
E result = null;
try {
result = pm.getObjectById(clazz, itemKey);
} catch (JDOObjectNotFoundException nfe) {
log.warning("No " + clazz.getCanonicalName() + " found with id: "
+ id);
}
return result;
}
/**
* lists all of the concreteClass instances in the datastore, using a page size.
*
* @return
*/
public List<T> list(String cursorString, Integer pageSize) {
return list(concreteClass, cursorString, pageSize);
}
/**
* lists all of the concreteClass instances in the datastore. if we think we'll use this on
* large tables, we should use Extents
*
* @return
*/
public List<T> list(String cursorString) {
return list(concreteClass, cursorString);
}
/**
* Lists all of the concreteClass instances in the datastore
*/
public <E extends BaseDomain> List<E> list(Class<E> c, String cursorString) {
return list(c, cursorString, null);
}
/**
* lists all of the type passed in. if we think we'll use this on large tables, we should use
* Extents
*
* @return
*/
@SuppressWarnings("unchecked")
public <E extends BaseDomain> List<E> list(Class<E> c, String cursorString, Integer pageSize) {
PersistenceManager pm = PersistenceFilter.getManager();
javax.jdo.Query query = pm.newQuery(c);
if (cursorString != null
&& !cursorString.trim().toLowerCase()
.equals(Constants.ALL_RESULTS)) {
Cursor cursor = Cursor.fromWebSafeString(cursorString);
Map<String, Object> extensionMap = new HashMap<String, Object>();
extensionMap.put(JDOCursorHelper.CURSOR_EXTENSION, cursor);
query.setExtensions(extensionMap);
}
List<E> results = null;
if (pageSize == null) {
this.prepareCursor(cursorString, query);
} else {
this.prepareCursor(cursorString, pageSize, query);
}
results = (List<E>) query.execute();
return results;
}
/**
* Return a list of survey groups or surveys that are accessible by the current user
*
* @return
*/
@SuppressWarnings({
"rawtypes", "unchecked"
})
@Deprecated
public List filterByUserAuthorization(List allObjectsList) {
if (!concreteClass.isAssignableFrom(SurveyGroup.class)
&& !concreteClass.isAssignableFrom(Survey.class)) {
throw new UnsupportedOperationException("Cannot filter "
+ concreteClass.getSimpleName());
}
final Authentication authentication = SecurityContextHolder.getContext()
.getAuthentication();
final Long userId = (Long) authentication.getCredentials();
// super admin list all
if (authentication.getAuthorities().contains(AppRole.SUPER_ADMIN)) {
return allObjectsList;
}
UserAuthorizationDAO userAuthorizationDAO = new UserAuthorizationDAO();
List<UserAuthorization> userAuthorizationList = userAuthorizationDAO.listByUser(userId);
if (userAuthorizationList.isEmpty()) {
return Collections.emptyList();
}
StringBuilder authorizedPathsRegex = new StringBuilder();
StringBuilder authorizedParentPathsRegex = new StringBuilder();
for (UserAuthorization auth : userAuthorizationList) {
String authorizedPath = auth.getObjectPath();
authorizedPathsRegex.append(authorizedPath);
authorizedPathsRegex.append("|");
// include parent folders in order to be able to navigate to sub folder / project
for (String parentPath : SurveyUtils.listParentPaths(authorizedPath, false)) {
authorizedParentPathsRegex.append(parentPath);
authorizedParentPathsRegex.append("|");
}
}
// trim the last "|"s
authorizedPathsRegex.deleteCharAt(authorizedPathsRegex.length() - 1);
if (authorizedParentPathsRegex.length() > 0) {
authorizedParentPathsRegex.deleteCharAt(authorizedParentPathsRegex.length() - 1);
}
final Pattern authorizedPaths = Pattern.compile(authorizedPathsRegex.toString());
final Pattern authorizedParentPaths = Pattern
.compile(authorizedParentPathsRegex.toString());
List authorizedList = new ArrayList();
if (concreteClass.isAssignableFrom(SurveyGroup.class)) {
for (Object obj : allObjectsList) {
SurveyGroup sg = (SurveyGroup) obj;
String sgPath = sg.getPath();
if (sgPath != null
&& (authorizedPaths.matcher(sgPath).lookingAt() ||
authorizedParentPaths.matcher(sgPath).matches())) {
authorizedList.add(sg);
}
}
} else {
for (Object obj : allObjectsList) {
Survey s = (Survey) obj;
String sPath = s.getPath();
if (sPath != null &&
(authorizedPaths.matcher(sPath).lookingAt() ||
authorizedParentPaths.matcher(sPath).matches())) {
authorizedList.add(s);
}
}
}
return authorizedList;
}
/**
* Return a list of survey groups or surveys that are accessible by the current user, filtered
* by object ids
*
* @return
*/
@SuppressWarnings({
"rawtypes", "unchecked"
})
public List filterByUserAuthorizationObjectId(List allObjectsList) {
if (!concreteClass.isAssignableFrom(SurveyGroup.class)
&& !concreteClass.isAssignableFrom(Survey.class)) {
throw new UnsupportedOperationException("Cannot filter "
+ concreteClass.getSimpleName());
}
final Authentication authentication = SecurityContextHolder.getContext()
.getAuthentication();
final Long userId = (Long) authentication.getCredentials();
// super admin list all
if (authentication.getAuthorities().contains(AppRole.SUPER_ADMIN)) {
return allObjectsList;
}
UserAuthorizationDAO userAuthorizationDAO = new UserAuthorizationDAO();
List<UserAuthorization> userAuthorizationList = userAuthorizationDAO.listByUser(userId);
if (userAuthorizationList.isEmpty()) {
return Collections.emptyList();
}
Set<Long> securedObjectIds = new HashSet<Long>();
for (UserAuthorization auth : userAuthorizationList) {
if (auth.getSecuredObjectId() != null) {
securedObjectIds.add(auth.getSecuredObjectId());
}
}
List authorizedList = new ArrayList();
if (concreteClass.isAssignableFrom(SurveyGroup.class)) {
for (Object obj : allObjectsList) {
SurveyGroup sg = (SurveyGroup) obj;
List<Long> ancestorIds = sg.getAncestorIds();
if (hasAuthorizedAncestors(ancestorIds, securedObjectIds)) {
authorizedList.add(sg);
}
}
} else {
for (Object obj : allObjectsList) {
Survey s = (Survey) obj;
List<Long> ancestorIds = s.getAncestorIds();
if (hasAuthorizedAncestors(ancestorIds, securedObjectIds)) {
authorizedList.add(s);
}
}
}
return authorizedList;
}
/**
* Check whether one or more items in the list of an entity's ancestor ids is present in the
* list of authorized objects for a user. Return true if this is the case
*
* @param ancestorIds
* @param securedObjectIds
* @return
*/
private boolean hasAuthorizedAncestors(List<Long> ancestorIds, Set<Long> securedObjectIds) {
return ancestorIds != null && ancestorIds.removeAll(securedObjectIds);
}
/**
* returns a single object based on the property value
*
* @param propertyName
* @param propertyValue
* @param propertyType
* @return
*/
protected T findByProperty(String propertyName, Object propertyValue,
String propertyType) {
T result = null;
List<T> results = listByProperty(propertyName, propertyValue,
propertyType);
if (results.size() > 0) {
result = results.get(0);
}
return result;
}
/**
* gets a List of object by key where the key is represented as a Long
*
* @param ids
* Array of Long representing the keys of objects
* @return null if ids is null, otherwise a list of objects
*/
public List<T> listByKeys(Long[] ids) {
if (ids == null) {
return null;
}
final List<T> list = new ArrayList<T>();
for (Long id : ids) {
final T obj = getByKey(id);
if (obj != null) {
list.add(obj);
}
}
return list;
}
/**
* Retrieves a List of objects by key where the keys are represented by a Collection of Longs
*
* @param ids List of Long representing the keys of objects
* @return empty list if ids is null, otherwise a list of objects
*/
public List<T> listByKeys(List<Long> ids) {
if (ids == null) {
return Collections.emptyList();
}
final List<T> list = new ArrayList<T>();
for (Long id : ids) {
final T obj = getByKey(id);
if (obj != null) {
list.add(obj);
}
}
return list;
}
/**
* lists all the objects of the same type as the concreteClass with property equal to the value
* passed in since using this requires the caller know the persistence data type of the field
* and the field name, this method is protected so that it can only be used by subclass DAOs. We
* don't want those details to leak into higher layers of the code.
*
* @param propertyName
* @param propertyValue
* @param propertyType
* @return
*/
protected List<T> listByProperty(String propertyName, Object propertyValue,
String propertyType) {
return listByProperty(propertyName, propertyValue, propertyType, null,
null, EQ_OP, concreteClass);
}
/**
* lists all objects of type class that have the property name/value passed in
*
* @param <E>
* @param propertyName
* @param propertyValue
* @param propertyType
* @param clazz
* @return
*/
protected <E extends BaseDomain> List<E> listByProperty(
String propertyName, Object propertyValue, String propertyType,
Class<E> clazz) {
return listByProperty(propertyName, propertyValue, propertyType, null,
null, EQ_OP, clazz);
}
/**
* lists all instances of type clazz that have the property equal to the value passed in and
* orders the results by the field specified. NOTE: for this to work on the datastore, you may
* need to have an index defined.
*
* @param <E>
* @param propertyName
* @param propertyValue
* @param propertyType
* @param orderBy
* @param clazz
* @return
*/
protected <E extends BaseDomain> List<E> listByProperty(
String propertyName, Object propertyValue, String propertyType,
String orderBy, Class<E> clazz) {
return listByProperty(propertyName, propertyValue, propertyType,
orderBy, null, EQ_OP, clazz);
}
/**
* lists all instances that have the property name/value matching those passed in optionally
* sorted by the order by column and direction. NOTE: depending on the sort being done, you may
* need an index in the datastore for this to work.
*
* @param propertyName
* @param propertyValue
* @param propertyType
* @param orderByCol
* @param orderByDir
* @return
*/
protected List<T> listByProperty(String propertyName, Object propertyValue,
String propertyType, String orderByCol, String orderByDir) {
return listByProperty(propertyName, propertyValue,
propertyType, orderByCol, orderByDir, EQ_OP, concreteClass);
}
/**
* lists all instances that have the property name/value matching those passed in optionally
* sorted by the order by column. NOTE: depending on the sort being done, you may need an index
* in the datastore for this to work.
*
* @param propertyName
* @param propertyValue
* @param propertyType
* @param orderByCol
* @return
*/
protected List<T> listByProperty(String propertyName, Object propertyValue,
String propertyType, String orderByCol) {
return listByProperty(propertyName, propertyValue, propertyType,
orderByCol, null, EQ_OP, concreteClass);
}
/**
* convenience method to list all instances of the type passed in that match the property since
* using this requires the caller know the persistence data type of the field and the field
* name, this method is protected so that it can only be used by subclass DAOs. We don't want
* those details to leak into higher layers of the code.
*
* @param propertyName
* @param propertyValue
* @param propertyType
* @return
*/
@SuppressWarnings("unchecked")
protected <E extends BaseDomain> List<E> listByProperty(
String propertyName, Object propertyValue, String propertyType,
String orderByField, String orderByDir, String operator,
Class<E> clazz) {
PersistenceManager pm = PersistenceFilter.getManager();
List<E> results = null;
String paramName = propertyName + "Param";
if (paramName.contains(".")) {
paramName = paramName.substring(paramName.indexOf(".") + 1);
}
javax.jdo.Query query = pm.newQuery(clazz);
query.setFilter(propertyName + " " + operator + " " + paramName);
if (orderByField != null) {
query.setOrdering(orderByField
+ (orderByDir != null ? " " + orderByDir : ""));
}
query.declareParameters(propertyType + " " + paramName);
if (propertyValue instanceof Date) {
query.declareImports("import java.util.Date");
}
results = (List<E>) query.execute(propertyValue);
return results;
}
/**
* deletes an object from the db
*
* @param <E>
* @param obj
*/
public <E extends BaseDomain> void delete(E obj) {
PersistenceManager pm = PersistenceFilter.getManager();
pm.deletePersistent(obj);
}
/**
* deletes a list of objects in a single datastore interaction
*/
public <E extends BaseDomain> void delete(Collection<E> obj) {
PersistenceManager pm = PersistenceFilter.getManager();
pm.deletePersistentAll(obj);
}
/**
* utility method to form a hash map of query parameters using an equality operator
*
* @param paramName
* - name of object property
* @param filter
* - in/out stringBuilder of query filters
* @param param
* -in/out stringBuilder of param names
* @param type
* - data type of field
* @param value
* - value to bind to param
* @param paramMap
* - in/out parameter map
*/
protected void appendNonNullParam(String paramName, StringBuilder filter,
StringBuilder param, String type, Object value,
Map<String, Object> paramMap) {
appendNonNullParam(paramName, filter, param, type, value, paramMap,
EQ_OP);
}
/**
* utility method to form a hash map of query parameters
*
* @param paramName
* - name of object property
* @param filter
* - in/out stringBuilder of query filters
* @param param
* -in/out stringBuilder of param names
* @param type
* - data type of field
* @param value
* - value to bind to param
* @param paramMap
* - in/out parameter map
* @param operator
* - operator to use
*/
protected void appendNonNullParam(String paramName, StringBuilder filter,
StringBuilder param, String type, Object value,
Map<String, Object> paramMap, String operator) {
if (value != null) {
if (paramMap.keySet().size() > 0) {
filter.append(" && ");
param.append(", ");
}
String paramValName = paramName + "Param"
+ paramMap.keySet().size();
filter.append(paramName).append(" ").append(operator).append(" ")
.append(paramValName);
param.append(type).append(" ").append(paramValName);
paramMap.put(paramValName, value);
}
}
/**
* gets a GAE datastore cursor based on the results list passed in. The list must be a non-null
* list of persistent entities (entites retrived from the datastore in the same session).
*
* @param results
* @return
*/
@SuppressWarnings("rawtypes")
public static String getCursor(List results) {
if (results != null && results.size() > 0) {
Cursor cursor = JDOCursorHelper.getCursor(results);
if (cursor != null) {
return cursor.toWebSafeString();
} else {
return null;
}
}
return null;
}
/**
* sets up the cursor with the given page size (or no page size if the cursor string is set to
* the ALL_RESULTS constant)
*
* @param cursorString
* @param pageSize
* @param query
*/
protected void prepareCursor(String cursorString, Integer pageSize,
javax.jdo.Query query) {
if (cursorString != null
&& !cursorString.trim().toLowerCase()
.equals(Constants.ALL_RESULTS)) {
Cursor cursor = Cursor.fromWebSafeString(cursorString);
Map<String, Object> extensionMap = new HashMap<String, Object>();
extensionMap.put(JDOCursorHelper.CURSOR_EXTENSION, cursor);
query.setExtensions(extensionMap);
}
if (cursorString == null || !cursorString.equals(Constants.ALL_RESULTS)) {
if (pageSize == null) {
query.setRange(0, DEFAULT_RESULT_COUNT);
} else {
query.setRange(0, pageSize);
}
}
}
/**
* this method should only be used when running a lot of datastore operations in a single
* request to a task queue and or backend (regular online requests can't accumulate enough data
* to require a flush without timing out).
*/
public void flushBatch() {
PersistenceManager pm = PersistenceFilter.getManager();
pm.flush();
}
/**
* sets up the cursor using the default page size
*
* @param cursorString
* @param query
*/
protected void prepareCursor(String cursorString, javax.jdo.Query query) {
prepareCursor(cursorString, DEFAULT_RESULT_COUNT, query);
}
/**
* method used to sleep in the event of a retry
*/
protected static void sleep() {
try {
Thread.sleep(RETRY_INTERVAL_MILLIS);
} catch (InterruptedException e) {
// no-op
}
}
/**
* Default format for cache key string
*
* @param object
* @return
* @throws CacheException
*/
public String getCacheKey(BaseDomain object) throws CacheException {
if (object.getKey() == null) {
throw new CacheException("Trying to get cache key from an unsaved object");
}
return object.getClass().getSimpleName() + "-" + object.getKey().getId();
}
/**
* Default format for cache key string
*
* @param objectId
* @return
* @throws CacheException
*/
public String getCacheKey(String objectId) throws CacheException {
if (objectId == null) {
throw new CacheException("Trying to get cache key from an unsaved object");
}
return concreteClass.getSimpleName() + "-" + objectId;
}
}
|
package main.swapship.util;
import main.swapship.common.Constants;
import main.swapship.components.ShipColorsComp;
import main.swapship.components.ShipSpritesComp;
import main.swapship.components.SpatialComp;
import main.swapship.components.VelocityComp;
import main.swapship.components.dist.PlayerComp;
import com.artemis.Entity;
import com.artemis.World;
import com.artemis.managers.GroupManager;
import com.badlogic.gdx.Gdx;
public class EntityFactory {
/**
* Creates the player, returning so other classes can have easy access to it
* @param world
* @return
*/
public static Entity createPlayer(World world) {
Entity e = world.createEntity();
SpatialComp sc = world.createComponent(SpatialComp.class);
sc.setValues(Gdx.graphics.getWidth() / 2 - Constants.Player.WIDTH / 2,
Constants.Player.MIN_Y, Constants.Player.WIDTH,
Constants.Player.HEIGHT);
e.addComponent(sc);
ShipSpritesComp ssc = world.createComponent(ShipSpritesComp.class);
ssc.setValues(Constants.Player.ARTEMIS_TOP,
Constants.Player.ARTEMIS_MID, Constants.Player.ARTEMIS_BOT);
e.addComponent(ssc);
ShipColorsComp scc = world.createComponent(ShipColorsComp.class);
scc.setValues(Constants.Player.DEFAULT_COLOR,
Constants.Player.DEFAULT_COLOR, Constants.Player.DEFAULT_COLOR);
e.addComponent(scc);
VelocityComp vc = world.createComponent(VelocityComp.class);
vc.setValues(Constants.Player.START_VEL, Constants.Player.START_VEL);
e.addComponent(vc);
e.addComponent(world.createComponent(PlayerComp.class));
world.getManager(GroupManager.class).add(e, Constants.Groups.PLAYER);
e.addToWorld();
return e;
}
}
|
package me.vogeldev.dungeon.Bodies;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.math.Vector2;
import java.util.Arrays;
import me.vogeldev.dungeon.support.Global;
public class Enemy {
public final static int MOVE_UP = 1,
MOVE_RIGHT = 2,
MOVE_DOWN = 3,
MOVE_LEFT = 4;
private ConeSight lineOfSight;
protected TextureAtlas textureAtlas;
private TextureRegion textureUp;
private TextureRegion textureDown;
private TextureRegion textureRight;
private TextureRegion textureLeft;
TextureRegion sprite;
private boolean inRange;
private boolean inSight;
private boolean inSightX;
private boolean inSightY;
int x, y, hp, velocity, level, range;
double angleVel;
int[] moving;
public Enemy(int x, int y, int hp) {
this.x = x;
this.y = y;
this.hp = hp;
level = 1;
velocity = 5;
angleVel = Math.sqrt(Math.pow(velocity, 2) / 2);
range = Global.RANGE; //The range that an enemy can see.
double t = Math.acos(34);
lineOfSight = new ConeSight(this, Global.RANGE, Global.RANGE, 45);
textureAtlas = new TextureAtlas("game_atlas.pack");
textureUp = textureAtlas.findRegion("enemy_debug_up");
textureDown = textureAtlas.findRegion("enemy_debug_down");
textureRight = textureAtlas.findRegion("enemy_debug_right");
textureLeft = textureAtlas.findRegion("enemy_debug_left");
sprite = textureLeft;
}
public void update(Player player) {
Double playerX = 0.0, playerY = 0.0, XComponents, YComponents, distance;
playerX = (double) player.getX();
playerY = (double) player.getY();
XComponents = (playerX - x);
YComponents = (playerY - y);
//Distance formula. Could not use the "^2" for some reason so I had to just
//Multiply them together.
distance = Math.sqrt((XComponents * XComponents) + (YComponents * YComponents));
inRange = distance <= range;
if(sprite == textureUp){
inSightX = ((player.getX() > lineOfSight.getaX()) && (player.getX() < lineOfSight.getbX()));
inSightY = ((player.getY() < lineOfSight.getaY()) && (player.getY() < lineOfSight.getbY()) && (player.getY() > (y - 100)));
}
else if(sprite == textureDown){
lineOfSight.recalcCone(this, 225);
inSightX = ((player.getX() < lineOfSight.getaX()) && (player.getX() > lineOfSight.getbX()));
inSightY = ((player.getY() > lineOfSight.getaY()) && (player.getY() > lineOfSight.getbY()) && (player.getY() < (y + 50)));
}
else if(sprite == textureRight){
lineOfSight.recalcCone(this, -45);
inSightX = ((player.getX() < lineOfSight.getaX()) && (player.getX() < lineOfSight.getbX()));
inSightY = ((player.getY() > lineOfSight.getaY()) && (player.getY() < lineOfSight.getbY()) && (player.getY() > (y - 100)));
}
else if(sprite == textureLeft){
lineOfSight.recalcCone(this, -45);
inSightX = ((player.getX() > lineOfSight.getaX()) && (player.getX() < lineOfSight.getbX()));
inSightY = ((player.getY() < lineOfSight.getaY()) && (player.getY() < lineOfSight.getbY()) && (player.getY() > (y - 100)));
}
inSight = (inSightX && inSightY && inRange);
}
@Override
public String toString() {
return "Player{" +
"x=" + x +
", y=" + y +
", hp=" + hp +
", moving=" + Arrays.toString(moving) +
'}';
}
public void draw(SpriteBatch batch, Vector2 playerPos, Vector2 screenRes){
batch.draw(sprite, x - playerPos.x + screenRes.x / 2, y - playerPos.y + screenRes.y / 2, sprite.getRegionWidth(), sprite.getRegionHeight());
}
public void move(int dir){
moving[dir] = velocity;
}
public void stop(int dir){
moving[dir] = 0;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public int getHp() {
return hp;
}
public void setHp(int hp) {
this.hp = hp;
}
public int getLevel() {
return level;
}
public void setLevel(int level) {
this.level = level;
}
public boolean isInRange() {
return inRange;
}
public void setInRange(boolean inRange) {
this.inRange = inRange;
}
public boolean isInSight() {
return inSight;
}
public void setInSight(boolean inSight) {
this.inSight = inSight;
}
public ConeSight getLineOfSight() {
return lineOfSight;
}
public boolean isInSightX() {
return inSightX;
}
public boolean isInSightY() {
return inSightY;
}
public class ConeSight{
private double sideA;
private double aX;
private double aY;
private double sideB;
private double bX;
private double by;
private int angle;
ConeSight(Enemy e,double a, double b, int ang){
a = -(Math.sin(Math.toRadians(ang)) * Global.RANGE);
aX = e.getX() + a;
aY = e.getY() - a;
b = (Math.sin(Math.toRadians(ang)) * Global.RANGE);
bX = e.getX() + b;
by = e.getY() + b;
sideA = a;
sideB = b;
angle = ang;
}
private void recalcCone(Enemy e, int angle){
if(e.sprite == textureRight || e.sprite == textureLeft){
sideA = -(Math.sin(Math.toRadians(angle)) * Global.RANGE);
aX = e.getX() + sideA;
aY = e.getY() - sideA;
sideB = -(Math.sin(Math.toRadians(angle))* Global.RANGE);
bX = e.getX() + sideB;
by = e.getY() + sideB;
}
else{
sideA = -(Math.sin(Math.toRadians(angle)) * Global.RANGE);
aX = e.getX() + sideA;
aY = e.getY() - sideA;
sideB = (Math.sin(Math.toRadians(angle))* Global.RANGE);
bX = e.getX() + sideB;
by = e.getY() + sideB;
}
}
public int getAngle() {
return angle;
}
public void setAngle(int angle) {
this.angle = angle;
}
public double getaX() {
return aX;
}
public void setaX(double aX) {
this.aX = aX;
}
public double getaY() {
return aY;
}
public void setaY(double aY) {
this.aY = aY;
}
public double getbX() {
return bX;
}
public void setbX(double bX) {
this.bX = bX;
}
public double getbY() {
return by;
}
public void setBY(double by) {
this.by = by;
}
public double getSideA() {
return sideA;
}
public void setSideA(double sideA) {
this.sideA = sideA;
}
public double getSideB() {
return sideB;
}
public void setSideB(double sideB) {
this.sideB = sideB;
}
}
}
|
package StatementClasses;
import BaseClasses.Function;
import BaseClasses.Statement;
import StatementExecuteClasses.Executor;
import java.util.ArrayList;
/**
* @author viki
*
*/
public class OverSegStatement extends Statement {
public OverSegStatement() {
}
public boolean executeStatement(){
boolean result =true;
System.out.println("execute-OverSegStatement");
if(Executor.statementArraylist.get(Executor.statementArraylist.size()-1).type==3){
Executor.waitElse=true;
Executor.Condition = Executor.statementArraylist.get(Executor.statementArraylist.size()-1).trueOrfalse;
}
// else if(Executor.statementArraylist.get(Executor.statementArraylist.size()-1).type==9){//
// Executor.funcDefFlag=false;
//TODO
if ((Executor.statementArraylist.get(Executor.statementArraylist.size()-1).type==8)){
Executor.removeInvalidVarFunc();
}
else {
if (Executor.statementArraylist.get(Executor.statementArraylist.size()-1).type!=9) {
} else
if(!isFuncdefOver()){
Executor.functionArraylist.get(Executor.functionArraylist.size()-1).getFunctionBody().add(new OverSegStatement());
return result;
}
}
Executor.statementArraylist.remove(Executor.statementArraylist.size()-1);
return result;
}
public boolean isFuncdefOver(){
boolean res=false;
ArrayList<Statement> flist = null;
if (Executor.functionArraylist.size() > 0) {
flist = Executor.functionArraylist.get(Executor.functionArraylist.size() - 1).getFunctionBody();
} else {
return false;
}
int statecount=0;
int overcount=0;
for (int i=0;i<flist.size();i++){
if(flist.get(i).getClass().equals(IfStatement.class)||flist.get(i).getClass().equals(ElseStatement.class)
||(flist.get(i).getClass().equals(ForStatement.class))||(flist.get(i).getClass().equals(WhileStatement.class))
||(flist.get(i).getClass().equals(SwitchStatement.class))||(flist.get(i).getClass().equals(FuncCallStatement.class))
||(flist.get(i).getClass().equals(NewSegStatement.class))||(flist.get(i).getClass().equals(FuncDefStatement.class))){
statecount++;
}
else if (flist.get(i).getClass().equals(OverSegStatement.class)){
overcount++;
}
}
if (statecount==overcount)
res=true;
return res;
}
}
|
/*
* $Log: HttpSender.java,v $
* Revision 1.31 2007-12-28 12:09:33 europe\L190409
* added timeout exception detection
*
* Revision 1.30 2007/10/03 08:46:40 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* added link to IBM site with JDK policy files
*
* Revision 1.29 2007/02/21 15:59:02 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* remove debug message
*
* Revision 1.28 2007/02/05 15:16:53 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* made number of connection- and execution retries configurable
*
* Revision 1.27 2006/08/24 11:01:25 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* retries instead of attempts
*
* Revision 1.26 2006/08/23 11:24:39 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* retry when method fails
*
* Revision 1.25 2006/08/21 07:56:41 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* return of the IbisMultiThreadedConnectionManager
*
* Revision 1.24 2006/07/17 09:02:46 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* corrected typos in documentation
*
* Revision 1.23 2006/06/14 09:40:35 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* improved logging
*
* Revision 1.22 2006/05/03 07:09:38 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* fixed null pointer exception that occured when no statusline was found
*
* Revision 1.21 2006/01/23 12:57:06 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* determine port-default if not found from uri
*
* Revision 1.20 2006/01/19 12:14:41 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* corrected logging output, improved javadoc
*
* Revision 1.19 2006/01/05 14:22:57 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* POST method now appends parameters to body instead of header
*
* Revision 1.18 2005/12/28 08:40:12 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* corrected javadoc
*
* Revision 1.17 2005/12/19 16:42:11 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* added authentication using authentication-alias
*
* Revision 1.16 2005/10/18 07:06:48 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* improved logging config, based now on ISenderWithParametersBase
*
* Revision 1.15 2005/10/03 13:19:07 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* replaced IbisMultiThreadedConnectionManager with original MultiThreadedConnectionMananger
*
* Revision 1.14 2005/02/24 12:13:14 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* added follow redirects and truststoretype
*
* Revision 1.13 2005/02/02 16:36:26 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* added hostname verification, default=false
*
* Revision 1.12 2004/12/23 16:11:13 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* Explicit check for open connections
*
* Revision 1.11 2004/12/23 12:12:12 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* staleChecking optional
*
* Revision 1.10 2004/10/19 06:39:21 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* modified parameter handling, introduced IWithParameters
*
* Revision 1.9 2004/10/14 15:35:10 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* refactored AuthSSLProtocolSocketFactory group
*
* Revision 1.8 2004/10/12 15:10:17 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* made parameterized version
*
* Revision 1.7 2004/09/09 14:50:07 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* added JDK1.3.x compatibility
*
* Revision 1.6 2004/09/08 14:18:34 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* early initialization of SocketFactory
*
* Revision 1.5 2004/09/01 12:24:16 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* improved fault handling
*
* Revision 1.4 2004/08/31 15:51:37 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* added extractResult method
*
* Revision 1.3 2004/08/31 10:13:35 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* added security handling
*
* Revision 1.2 2004/08/24 11:41:27 unknown <unknown@ibissource.org>
* Remove warnings
*
* Revision 1.1 2004/08/20 13:04:40 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* first version
*
*/
package nl.nn.adapterframework.http;
import java.io.IOException;
import java.net.SocketException;
import java.net.URL;
import java.net.URLEncoder;
import java.security.Security;
import org.apache.commons.httpclient.Credentials;
import org.apache.commons.httpclient.HostConfiguration;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpConnection;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.StatusLine;
import org.apache.commons.httpclient.URI;
import org.apache.commons.httpclient.URIException;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.protocol.Protocol;
import org.apache.commons.lang.StringUtils;
import nl.nn.adapterframework.configuration.ConfigurationException;
import nl.nn.adapterframework.core.HasPhysicalDestination;
import nl.nn.adapterframework.core.ParameterException;
import nl.nn.adapterframework.core.SenderException;
import nl.nn.adapterframework.core.SenderWithParametersBase;
import nl.nn.adapterframework.core.TimeOutException;
import nl.nn.adapterframework.parameters.ParameterResolutionContext;
import nl.nn.adapterframework.parameters.ParameterValue;
import nl.nn.adapterframework.parameters.ParameterValueList;
import nl.nn.adapterframework.util.ClassUtils;
import nl.nn.adapterframework.util.CredentialFactory;
public class HttpSender extends SenderWithParametersBase implements HasPhysicalDestination {
public static final String version = "$RCSfile: HttpSender.java,v $ $Revision: 1.31 $ $Date: 2007-12-28 12:09:33 $";
private String url;
private String methodType="GET"; // GET or POST
private int timeout=60000;
private int maxConnections=2;
private int maxConnectionRetries=10;
private int maxExecuteRetries=5;
private String authAlias;
private String userName;
private String password;
private String proxyHost;
private int proxyPort=80;
private String proxyAuthAlias;
private String proxyUserName;
private String proxyPassword;
private String proxyRealm=null;
private String keystoreType="pkcs12";
private String certificate;
private String certificateAuthAlias;
private String certificatePassword;
private String truststore=null;
private String truststorePassword=null;
private String truststoreAuthAlias;
private String truststoreType="jks";
private boolean verifyHostname=true;
private boolean followRedirects=true;
private boolean jdk13Compatibility=false;
private boolean staleChecking=true;
private boolean encodeMessages=false;
protected URI uri;
private MultiThreadedHttpConnectionManager connectionManager;
protected HttpClient httpclient;
/*
* connection manager that checks connections to be open before handing them to HttpMethod.
* Use of this connection manager prevents SocketExceptions to occur.
*
*/
private class IbisMultiThreadedHttpConnectionManager extends MultiThreadedHttpConnectionManager {
protected boolean checkConnection(HttpConnection connection) {
boolean status = connection.isOpen();
//log.debug(getLogPrefix()+"IbisMultiThreadedHttpConnectionManager connection open ["+status+"]");
if (status) {
try {
connection.setSoTimeout(connection.getSoTimeout());
} catch (SocketException e) {
log.warn(getLogPrefix()+"IbisMultiThreadedHttpConnectionManager SocketException while checking: "+ e.getMessage());
connection.close();
return false;
} catch (IllegalStateException e) {
log.warn(getLogPrefix()+"IbisMultiThreadedHttpConnectionManager IllegalStateException while checking: "+ e.getMessage());
connection.close();
return false;
}
}
return true;
}
public HttpConnection getConnection(HostConfiguration hostConfiguration) {
//log.debug(getLogPrefix()+"IbisMultiThreadedHttpConnectionManager getConnection(HostConfiguration)");
HttpConnection result = super.getConnection(hostConfiguration);
int count=getMaxConnectionRetries();
while (count-->0 && !checkConnection(result)) {
log.info("releasing failed connection, connectionRetries left ["+count+"]");
releaseConnection(result);
result= super.getConnection(hostConfiguration);
}
return result;
}
public HttpConnection getConnection(HostConfiguration hostConfiguration, long timeout) throws HttpException {
//log.debug(getLogPrefix()+"IbisMultiThreadedHttpConnectionManager getConnection(HostConfiguration, timeout["+timeout+"])");
HttpConnection result = super.getConnection(hostConfiguration, timeout);
int count=getMaxConnectionRetries();
while (count-->0 && !checkConnection(result)) {
log.info("releasing failed connection, connectionRetries left ["+count+"]");
releaseConnection(result);
result= super.getConnection(hostConfiguration, timeout);
}
return result;
}
}
protected void addProvider(String name) {
try {
Class clazz = Class.forName(name);
Security.addProvider((java.security.Provider)clazz.newInstance());
} catch (Throwable t) {
log.error(getLogPrefix()+"cannot add provider ["+name+"], "+t.getClass().getName()+": "+t.getMessage());
}
}
public void configure() throws ConfigurationException {
super.configure();
// System.setProperty("javax.net.debug","all"); // normaal Java
// System.setProperty("javax.net.debug","true"); // IBM java
httpclient = new HttpClient();
httpclient.setTimeout(getTimeout());
httpclient.setConnectionTimeout(getTimeout());
if (paramList!=null) {
paramList.configure();
}
if (StringUtils.isEmpty(getUrl())) {
throw new ConfigurationException(getLogPrefix()+"Url must be specified");
}
try {
uri = new URI(getUrl());
int port = uri.getPort();
if (port<1) {
try {
log.debug(getLogPrefix()+"looking up protocol for scheme ["+uri.getScheme()+"]");
port = Protocol.getProtocol(uri.getScheme()).getDefaultPort();
} catch (IllegalStateException e) {
log.debug(getLogPrefix()+"protocol for scheme ["+uri.getScheme()+"] not found, setting port to 80",e);
port=80;
}
}
log.info(getLogPrefix()+"created uri: scheme=["+uri.getScheme()+"] host=["+uri.getHost()+"] port=["+port+"] path=["+uri.getPath()+"]");
URL certificateUrl=null;
URL truststoreUrl=null;
if (!StringUtils.isEmpty(getCertificate())) {
certificateUrl = ClassUtils.getResourceURL(this, getCertificate());
if (certificateUrl==null) {
throw new ConfigurationException(getLogPrefix()+"cannot find URL for certificate resource ["+getCertificate()+"]");
}
log.info(getLogPrefix()+"resolved certificate-URL to ["+certificateUrl.toString()+"]");
}
if (!StringUtils.isEmpty(getTruststore())) {
truststoreUrl = ClassUtils.getResourceURL(this, getTruststore());
if (truststoreUrl==null) {
throw new ConfigurationException(getLogPrefix()+"cannot find URL for truststore resource ["+getTruststore()+"]");
}
log.info(getLogPrefix()+"resolved truststore-URL to ["+truststoreUrl.toString()+"]");
}
HostConfiguration hostconfiguration = httpclient.getHostConfiguration();
if (certificateUrl!=null || truststoreUrl!=null) {
AuthSSLProtocolSocketFactoryBase socketfactory ;
try {
CredentialFactory certificateCf = new CredentialFactory(getCertificateAuthAlias(), null, getCertificatePassword());
CredentialFactory truststoreCf = new CredentialFactory(getTruststoreAuthAlias(), null, getTruststorePassword());
if (isJdk13Compatibility()) {
addProvider("sun.security.provider.Sun");
addProvider("com.sun.net.ssl.internal.ssl.Provider");
System.setProperty("java.protocol.handler.pkgs","com.sun.net.ssl.internal.www.protocol");
socketfactory = new AuthSSLProtocolSocketFactoryForJsse10x(
certificateUrl, certificateCf.getPassword(), getKeystoreType(),
truststoreUrl, truststoreCf.getPassword(), getTruststoreType(), isVerifyHostname());
} else {
socketfactory = new AuthSSLProtocolSocketFactory(
certificateUrl, certificateCf.getPassword(), getKeystoreType(),
truststoreUrl, truststoreCf.getPassword(), getTruststoreType(),isVerifyHostname());
}
socketfactory.initSSLContext();
} catch (Throwable t) {
throw new ConfigurationException(getLogPrefix()+"cannot create or initialize SocketFactory",t);
}
Protocol authhttps = new Protocol(uri.getScheme(), socketfactory, port);
hostconfiguration.setHost(uri.getHost(),port,authhttps);
} else {
hostconfiguration.setHost(uri.getHost(),port,uri.getScheme());
}
log.info(getLogPrefix()+"configured httpclient for host ["+hostconfiguration.getHostURL()+"]");
CredentialFactory cf = new CredentialFactory(getAuthAlias(), getUserName(), getPassword());
if (!StringUtils.isEmpty(cf.getUsername())) {
httpclient.getState().setAuthenticationPreemptive(true);
Credentials defaultcreds = new UsernamePasswordCredentials(cf.getUsername(), cf.getPassword());
httpclient.getState().setCredentials(null, uri.getHost(), defaultcreds);
}
if (!StringUtils.isEmpty(getProxyHost())) {
CredentialFactory pcf = new CredentialFactory(getProxyAuthAlias(), getProxyUserName(), getProxyPassword());
httpclient.getHostConfiguration().setProxy(getProxyHost(), getProxyPort());
httpclient.getState().setProxyCredentials(getProxyRealm(), getProxyHost(),
new UsernamePasswordCredentials(pcf.getUsername(), pcf.getPassword()));
}
} catch (URIException e) {
throw new ConfigurationException(getLogPrefix()+"cannot interprete uri ["+getUrl()+"]");
}
}
public void open() {
connectionManager = new IbisMultiThreadedHttpConnectionManager();
connectionManager.setMaxConnectionsPerHost(getMaxConnections());
log.debug(getLogPrefix()+"set up connectionManager, stale checking ["+connectionManager.isConnectionStaleCheckingEnabled()+"]");
if (connectionManager.isConnectionStaleCheckingEnabled() != isStaleChecking()) {
log.info(getLogPrefix()+"set up connectionManager, setting stale checking ["+isStaleChecking()+"]");
connectionManager.setConnectionStaleCheckingEnabled(isStaleChecking());
}
httpclient.setHttpConnectionManager(connectionManager);
}
public void close() {
connectionManager.shutdown();
connectionManager=null;
}
public boolean isSynchronous() {
return true;
}
protected boolean appendParameters(boolean parametersAppended, StringBuffer path, ParameterValueList parameters) {
if (parameters!=null) {
log.debug(getLogPrefix()+"appending ["+parameters.size()+"] parameters");
}
for(int i=0; i<parameters.size(); i++) {
if (parametersAppended) {
path.append("&");
} else {
path.append("?");
parametersAppended = true;
}
ParameterValue pv = parameters.getParameterValue(i);
String parameterToAppend=pv.getDefinition().getName()+"="+URLEncoder.encode(pv.asStringValue(""));
log.debug(getLogPrefix()+"appending parameter ["+parameterToAppend+"]");
path.append(parameterToAppend);
}
return parametersAppended;
}
protected HttpMethod getMethod(String message, ParameterValueList parameters) throws SenderException {
try {
boolean queryParametersAppended = false;
if (isEncodeMessages()) {
message = URLEncoder.encode(message);
}
StringBuffer path = new StringBuffer(uri.getPath());
if (!StringUtils.isEmpty(uri.getQuery())) {
path.append("?"+uri.getQuery());
queryParametersAppended = true;
}
if (getMethodType().equals("GET")) {
if (parameters!=null) {
queryParametersAppended = appendParameters(queryParametersAppended,path,parameters);
log.debug(getLogPrefix()+"path after appending of parameters ["+path.toString()+"]");
}
GetMethod result = new GetMethod(path+(parameters==null? message:""));
log.debug(getLogPrefix()+"HttpSender constructed GET-method ["+result.getQueryString()+"]");
return result;
} else {
if (getMethodType().equals("POST")) {
PostMethod postMethod = new PostMethod(path.toString());
if (parameters!=null) {
StringBuffer msg = new StringBuffer(message);
appendParameters(true,msg,parameters);
if (StringUtils.isEmpty(message) && msg.length()>1) {
message=msg.substring(1);
} else {
message=msg.toString();
}
}
postMethod.setRequestBody(message);
return postMethod;
} else {
throw new SenderException("unknown methodtype ["+getMethodType()+"], must be either POST or GET");
}
}
} catch (URIException e) {
throw new SenderException(getLogPrefix()+"cannot find path from url ["+getUrl()+"]", e);
}
}
public String extractResult(HttpMethod httpmethod) throws SenderException {
int statusCode = httpmethod.getStatusCode();
if (statusCode!=200) {
throw new SenderException(getLogPrefix()+"httpstatus "+statusCode+": "+httpmethod.getStatusText());
}
return httpmethod.getResponseBodyAsString();
}
public String sendMessage(String correlationID, String message, ParameterResolutionContext prc) throws SenderException, TimeOutException {
ParameterValueList pvl = null;
try {
if (prc !=null && paramList !=null) {
pvl=prc.getValues(paramList);
}
} catch (ParameterException e) {
throw new SenderException(getLogPrefix()+"Sender ["+getName()+"] caught exception evaluating parameters",e);
}
HttpMethod httpmethod=getMethod(message, pvl);
httpmethod.setFollowRedirects(isFollowRedirects());
String result = null;
int statusCode = -1;
int count=getMaxExecuteRetries();
String msg = null;
try {
while (count-->0 && statusCode==-1) {
try {
log.debug(getLogPrefix()+"executing method");
statusCode = httpclient.executeMethod(httpmethod);
log.debug(getLogPrefix()+"executed method");
if (log.isDebugEnabled()) {
StatusLine statusline = httpmethod.getStatusLine();
if (statusline!=null) {
log.debug(getLogPrefix()+"status:"+statusline.toString());
} else {
log.debug(getLogPrefix()+"no statusline found");
}
}
result = extractResult(httpmethod);
if (log.isDebugEnabled()) {
log.debug(getLogPrefix()+"retrieved result ["+result+"]");
}
} catch (HttpException e) {
Throwable throwable = e.getCause();
String cause = null;
if (throwable!=null) {
cause = throwable.toString();
}
if (e!=null) {
msg = e.getMessage();
}
log.warn("httpException with message [" + msg + "] and cause [" + cause + "], executeRetries left [" + count + "]");
} catch (IOException e) {
throw new SenderException(e);
}
}
} finally {
httpmethod.releaseConnection();
}
if (statusCode==-1){
if (StringUtils.contains(msg.toUpperCase(), "TIMEOUTEXCEPTION")) {
//java.net.SocketTimeoutException: Read timed out
throw new TimeOutException("Failed to recover from timeout exception");
} else {
throw new SenderException("Failed to recover from exception");
}
}
return result;
}
public String sendMessage(String correlationID, String message) throws SenderException, TimeOutException {
return sendMessage(correlationID, message, null);
}
public String getPhysicalDestinationName() {
return getUrl();
}
public String getUrl() {
return url;
}
public String getProxyHost() {
return proxyHost;
}
public String getProxyPassword() {
return proxyPassword;
}
public int getProxyPort() {
return proxyPort;
}
public String getProxyUserName() {
return proxyUserName;
}
public void setUrl(String string) {
url = string;
}
public void setProxyHost(String string) {
proxyHost = string;
}
public void setProxyPassword(String string) {
proxyPassword = string;
}
public void setProxyPort(int i) {
proxyPort = i;
}
public void setProxyUserName(String string) {
proxyUserName = string;
}
public String getProxyRealm() {
return proxyRealm;
}
public void setProxyRealm(String string) {
proxyRealm = string;
}
public String getPassword() {
return password;
}
public String getUserName() {
return userName;
}
public void setPassword(String string) {
password = string;
}
public void setUserName(String string) {
userName = string;
}
public String getMethodType() {
return methodType;
}
public void setMethodType(String string) {
methodType = string;
}
public String getCertificate() {
return certificate;
}
public String getCertificatePassword() {
return certificatePassword;
}
public String getKeystoreType() {
return keystoreType;
}
public void setCertificate(String string) {
certificate = string;
}
public void setCertificatePassword(String string) {
certificatePassword = string;
}
public void setKeystoreType(String string) {
keystoreType = string;
}
public String getTruststore() {
return truststore;
}
public String getTruststorePassword() {
return truststorePassword;
}
public void setTruststore(String string) {
truststore = string;
}
public void setTruststorePassword(String string) {
truststorePassword = string;
}
public int getTimeout() {
return timeout;
}
public void setTimeout(int i) {
timeout = i;
}
public int getMaxConnections() {
return maxConnections;
}
public void setMaxConnections(int i) {
maxConnections = i;
}
public boolean isJdk13Compatibility() {
return jdk13Compatibility;
}
public void setJdk13Compatibility(boolean b) {
jdk13Compatibility = b;
}
public boolean isEncodeMessages() {
return encodeMessages;
}
public void setEncodeMessages(boolean b) {
encodeMessages = b;
}
public boolean isStaleChecking() {
return staleChecking;
}
public void setStaleChecking(boolean b) {
staleChecking = b;
}
public boolean isVerifyHostname() {
return verifyHostname;
}
public void setVerifyHostname(boolean b) {
verifyHostname = b;
}
public boolean isFollowRedirects() {
return followRedirects;
}
public void setFollowRedirects(boolean b) {
followRedirects = b;
}
public String getTruststoreType() {
return truststoreType;
}
public void setTruststoreType(String string) {
truststoreType = string;
}
public String getAuthAlias() {
return authAlias;
}
public String getCertificateAuthAlias() {
return certificateAuthAlias;
}
public String getProxyAuthAlias() {
return proxyAuthAlias;
}
public String getTruststoreAuthAlias() {
return truststoreAuthAlias;
}
public void setAuthAlias(String string) {
authAlias = string;
}
public void setCertificateAuthAlias(String string) {
certificateAuthAlias = string;
}
public void setProxyAuthAlias(String string) {
proxyAuthAlias = string;
}
public void setTruststoreAuthAlias(String string) {
truststoreAuthAlias = string;
}
public void setMaxConnectionRetries(int i) {
maxConnectionRetries = i;
}
public int getMaxConnectionRetries() {
return maxConnectionRetries;
}
public void setMaxExecuteRetries(int i) {
maxExecuteRetries = i;
}
public int getMaxExecuteRetries() {
return maxExecuteRetries;
}
}
|
package com.parc.ccn.security.crypto;
import java.math.BigInteger;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import com.parc.ccn.Library;
import com.parc.ccn.data.util.DataUtils;
/**
* Specifies encryption algorithm and keys to use for encrypting content.
*/
public class ContentKeys {
/**
* The core encryption algorithms supported. Any native encryption
* mode supported by Java *should* work, but these are compactly
* encodable.
*/
public static final String AES_CTR_MODE = "AES/CTR/NoPadding";
public static final String AES_CBC_MODE = "AES/CBC/PKCS5Padding";
public static final String DEFAULT_CIPHER_ALGORITHM = AES_CTR_MODE;
public static final String DEFAULT_KEY_ALGORITHM = "AES";
public static final int DEFAULT_KEY_LENGTH = 16;
public static final int DEFAULT_AES_KEY_LENGTH = 16; // bytes, 128 bits
public static final int IV_MASTER_LENGTH = 8; // bytes
public static final int SEGMENT_NUMBER_LENGTH = 6; // bytes
public static final int BLOCK_COUNTER_LENGTH = 2; // bytes
private static final byte [] INITIAL_BLOCK_COUNTER_VALUE = new byte[]{0x00, 0x01};
public String encryptionAlgorithm;
public SecretKeySpec encryptionKey;
public IvParameterSpec masterIV;
public ContentKeys(String encryptionAlgorithm, SecretKeySpec encryptionKey,
IvParameterSpec masterIV) throws NoSuchAlgorithmException, NoSuchPaddingException {
// ensure NoSuchPaddingException cannot be thrown later when a Cipher is made
Cipher.getInstance(encryptionAlgorithm);
// TODO check secret key/iv not empty?
this.encryptionAlgorithm = encryptionAlgorithm;
this.encryptionKey = encryptionKey;
this.masterIV = masterIV;
}
@SuppressWarnings("unused")
private ContentKeys() {
}
/**
* A number of users of ContentKeys only support using the default algorithm.
* @throws UnsupportedOperationException if the algorithm is not the default.
*/
public void OnlySupportDefaultAlg() {
// For now we only support the default algorithm.
if (!encryptionAlgorithm.equals(ContentKeys.DEFAULT_CIPHER_ALGORITHM)) {
String err = "Right now the only encryption algorithm we support is: " +
ContentKeys.DEFAULT_CIPHER_ALGORITHM + ", " + encryptionAlgorithm +
" will come later.";
Library.logger().severe(err);
throw new UnsupportedOperationException(err);
}
}
public Cipher getCipher() {
// We have tried a dummy call to Cipher.getInstance on construction of this ContentKeys - so
// further "NoSuch" exceptions should not happen here.
try {
return Cipher.getInstance(encryptionAlgorithm);
} catch (NoSuchAlgorithmException e) {
String err = "Unexpected NoSuchAlgorithmException for an algorithm we have already used!";
Library.logger().severe(err);
throw new RuntimeException(err, e);
} catch (NoSuchPaddingException e) {
String err = "Unexpected NoSuchPaddingException for an algorithm we have already used!";
Library.logger().severe(err);
throw new RuntimeException(err, e);
}
}
/**
* Create a set of encryption/decryption keys using the default algorithm.
*/
public static ContentKeys generateRandomKeys() {
try {
return new ContentKeys(
DEFAULT_CIPHER_ALGORITHM,
new SecretKeySpec(SecureRandom.getSeed(DEFAULT_KEY_LENGTH), DEFAULT_KEY_ALGORITHM),
new IvParameterSpec(SecureRandom.getSeed(IV_MASTER_LENGTH)));
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
} catch (NoSuchPaddingException e) {
throw new RuntimeException(e);
}
}
/**
* Make an encrypting or decrypting Cipher to be used in making a CipherStream to
* wrap CCN data.
*
* This will use the CCN defaults for IV handling, to ensure that segments
* of a given larger piece of content do not have overlapping key streams.
* Higher-level functionality embodied in the library (or application-specific
* code) should be used to make sure that the key, masterIV pair used for a
* given multi-block piece of content is unique for that content.
*
* CCN encryption algorithms assume deterministic IV generation (e.g. from
* cryptographic MAC or ciphers themselves), and therefore do not transport
* the IV explicitly. Applications that wish to do so need to arrange
* IV transport.
*
* We assume this stream starts on the first block of a multi-block segement,
* so for CTR mode, the initial block counter is 1 (block == encryption
* block). (Conventions for counter start them at 1, not 0.) The cipher
* will automatically increment the counter; if it overflows the two bytes
* we've given to it it will start to increment into the segment number.
* This runs the risk of potentially using up some of the IV space of
* other segments.
*
* CTR_init = IV_master || segment_number || block_counter
* CBC_iv = E_Ko(IV_master || segment_number || 0x0001)
* (just to make it easier, use the same feed value)
*
* CTR value is 16 bytes.
* 8 bytes are the IV.
* 6 bytes are the segment number.
* last 2 bytes are the block number (for 16 byte blocks); if you
* have more space, use it for the block counter.
* IV value is the block width of the cipher.
*
* @throws InvalidAlgorithmParameterException
* @throws InvalidKeyException
*/
public Cipher getSegmentEncryptionCipher(long segmentNumber)
throws InvalidKeyException, InvalidAlgorithmParameterException {
return getSegmentCipher(segmentNumber, true);
}
public Cipher getSegmentDecryptionCipher(long segmentNumber)
throws InvalidKeyException, InvalidAlgorithmParameterException {
return getSegmentCipher(segmentNumber, true);
}
protected Cipher getSegmentCipher(long segmentNumber, boolean encryption)
throws InvalidKeyException, InvalidAlgorithmParameterException {
Cipher cipher = getCipher();
// Construct the IV/initial counter.
if (0 == cipher.getBlockSize()) {
Library.logger().warning(encryptionAlgorithm + " is not a block cipher!");
throw new InvalidAlgorithmParameterException(encryptionAlgorithm + " is not a block cipher!");
}
if (masterIV.getIV().length < IV_MASTER_LENGTH) {
throw new InvalidAlgorithmParameterException("Master IV length must be at least " + IV_MASTER_LENGTH + " bytes, it is: " + masterIV.getIV().length);
}
IvParameterSpec iv_ctrSpec = buildIVCtr(masterIV, segmentNumber, cipher.getBlockSize());
Library.logger().finest(encryption?"En":"De"+"cryption Key: "+DataUtils.printHexBytes(encryptionKey.getEncoded())+" iv="+DataUtils.printHexBytes(iv_ctrSpec.getIV()));
cipher.init(encryption?Cipher.ENCRYPT_MODE:Cipher.DECRYPT_MODE, encryptionKey, iv_ctrSpec);
return cipher;
}
public static IvParameterSpec buildIVCtr(IvParameterSpec masterIV, long segmentNumber, int ivLen) {
Library.logger().finest("Thread="+Thread.currentThread()+" Building IV - master="+DataUtils.printHexBytes(masterIV.getIV())+" segment="+segmentNumber+" ivLen="+ivLen);
byte [] iv_ctr = new byte[ivLen];
System.arraycopy(masterIV.getIV(), 0, iv_ctr, 0, IV_MASTER_LENGTH);
byte [] byteSegNum = segmentNumberToByteArray(segmentNumber);
System.arraycopy(byteSegNum, 0, iv_ctr, IV_MASTER_LENGTH, byteSegNum.length);
System.arraycopy(INITIAL_BLOCK_COUNTER_VALUE, 0, iv_ctr,
iv_ctr.length - BLOCK_COUNTER_LENGTH, BLOCK_COUNTER_LENGTH);
IvParameterSpec iv_ctrSpec = new IvParameterSpec(iv_ctr);
Library.logger().finest("ivParameterSpec source="+DataUtils.printHexBytes(iv_ctr)+"ivParameterSpec.getIV()="+DataUtils.printHexBytes(masterIV.getIV()));
return iv_ctrSpec;
}
public static byte [] segmentNumberToByteArray(long segmentNumber) {
byte [] ba = new byte[SEGMENT_NUMBER_LENGTH];
// Is this the fastest way to do this?
byte [] bv = BigInteger.valueOf(segmentNumber).toByteArray();
System.arraycopy(bv, 0, ba, SEGMENT_NUMBER_LENGTH-bv.length, bv.length);
return ba;
}
}
|
package net.fortuna.ical4j.model;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import net.fortuna.ical4j.util.Dates;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* Represents a timezone offset from UTC time.
*
* @author Ben Fortuna
*/
public class UtcOffset {
private static final int HOUR_START_INDEX = 1;
private static final int HOUR_END_INDEX = 3;
private static final int MINUTE_START_INDEX = 3;
private static final int MINUTE_END_INDEX = 5;
private static final int SECOND_START_INDEX = 5;
private static final int SECOND_END_INDEX = 7;
private static final NumberFormat HOUR_FORMAT = new DecimalFormat("00");
private static final NumberFormat MINUTE_FORMAT = new DecimalFormat("00");
private static final NumberFormat SECOND_FORMAT = new DecimalFormat("00");
private static Log log = LogFactory.getLog(UtcOffset.class);
private long offset;
/**
* @param value
*/
public UtcOffset(final String value) {
// debugging..
if (log.isDebugEnabled()) {
log.debug("Parsing string [" + value + "]");
}
boolean negative = value.startsWith("-");
offset = 0;
offset += Integer.parseInt(value.substring(HOUR_START_INDEX,
HOUR_END_INDEX))
* Dates.MILLIS_PER_HOUR;
offset += Integer.parseInt(value.substring(MINUTE_START_INDEX,
MINUTE_END_INDEX))
* Dates.MILLIS_PER_MINUTE;
try {
offset += Integer.parseInt(value.substring(SECOND_START_INDEX,
SECOND_END_INDEX))
* Dates.MILLIS_PER_SECOND;
}
catch (Exception e) {
// seconds not supplied..
log.debug("Seconds not specified", e);
}
if (negative) {
offset = -offset;
}
}
/**
* @param offset
*/
public UtcOffset(final long offset) {
this.offset = (long) Math.floor(offset / (double) Dates.MILLIS_PER_SECOND) * Dates.MILLIS_PER_SECOND;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
public final String toString() {
StringBuffer b = new StringBuffer();
long remainder = Math.abs(offset);
if (offset < 0) {
b.append('-');
}
else {
b.append('+');
}
b.append(HOUR_FORMAT.format(remainder / Dates.MILLIS_PER_HOUR));
remainder = remainder % Dates.MILLIS_PER_HOUR;
b.append(MINUTE_FORMAT.format(remainder / Dates.MILLIS_PER_MINUTE));
remainder = remainder % Dates.MILLIS_PER_MINUTE;
if (remainder > 0) {
b.append(SECOND_FORMAT.format(remainder / Dates.MILLIS_PER_SECOND));
}
return b.toString();
}
/**
* @return Returns the offset.
*/
public final long getOffset() {
return offset;
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
public final boolean equals(final Object arg0) {
if (arg0 instanceof UtcOffset) {
return getOffset() == ((UtcOffset) arg0).getOffset();
}
return super.equals(arg0);
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
public final int hashCode() {
return (int) getOffset();
}
}
|
package org.jasig.portal;
import java.util.Date;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import org.jasig.portal.services.LogService;
import org.jasig.portal.utils.IPortalDocument;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
/**
* Describes a published channel.
* @author George Lindholm, ITServices, UBC
* @version $Revision$
*/
public class ChannelDefinition implements IBasicEntity {
private int id;
private String chanFName;
private String chanName;
private String chanDesc;
private String chanTitle;
private String chanClass;
private int chanTimeout;
private int chanTypeId;
private int chanPupblUsrId;
private int chanApvlId;
private Date chanPublDt;
private Date chanApvlDt;
private boolean chanEditable;
private boolean chanHasHelp;
private boolean chanHasAbout;
private boolean chanIsSecure;
private Map parameters; // Consider implementing as a Set
private String chanLocale;
private Hashtable chanDescs;
private Hashtable chanTitles;
private Hashtable chanNames;
/**
* Constructs a channel definition.
* @param id the channel definition ID
*/
public ChannelDefinition(int id) {
this.id = id;
this.chanTitle = "";
this.chanDesc = "";
this.chanClass = "";
this.parameters = new HashMap();
this.chanLocale = null;
this.chanTitles = new Hashtable();
this.chanNames = new Hashtable();
this.chanDescs = new Hashtable();
}
// Getter methods
public int getId() { return id; }
public String getFName() { return chanFName; }
public String getName() { return chanName; }
public String getDescription() { return chanDesc; }
public String getTitle() { return chanTitle; }
public String getJavaClass() { return chanClass; }
public int getTimeout() { return chanTimeout; }
public int getTypeId() { return chanTypeId; }
public int getPublisherId() { return chanPupblUsrId; }
public int getApproverId() { return chanApvlId; }
public Date getPublishDate() { return chanPublDt; }
public Date getApprovalDate() { return chanApvlDt;}
public boolean isEditable() { return chanEditable; }
public boolean hasHelp() { return chanHasHelp; }
public boolean hasAbout() { return chanHasAbout; }
public boolean isSecure() { return chanIsSecure; }
public ChannelParameter[] getParameters() { return (ChannelParameter[])parameters.values().toArray(new ChannelParameter[0]); }
public String getLocale() { return chanLocale; }
// I18n
public String getName(String locale) {
String chanName=(String)chanNames.get(locale);
if (chanName == null) {
return this.chanName; // fallback on "en_US"
} else {
return chanName;
}
}
public String getDescription(String locale) {
/*
return chanDesc;
*/
String chanDesc=(String)chanDescs.get(locale);
if (chanDesc == null) {
return this.chanDesc; // fallback on "en_US"
} else {
return chanDesc;
}
}
public String getTitle(String locale) {
/*
return chanTitle;
*/
String chanTitle=(String)chanTitles.get(locale);
if (chanTitle == null) {
return this.chanTitle; // fallback on "en_US"
} else {
return chanTitle;
}
}
// Setter methods
public void setFName(String fname) {this.chanFName =fname; }
public void setName(String name) {this.chanName = name; }
public void setDescription(String descr) {this.chanDesc = descr; }
public void setTitle(String title) {this.chanTitle = title; }
public void setJavaClass(String javaClass) {this.chanClass = javaClass; }
public void setTimeout(int timeout) {this.chanTimeout = timeout; }
public void setTypeId(int typeId) {this.chanTypeId = typeId; }
public void setPublisherId(int publisherId) {this.chanPupblUsrId = publisherId; }
public void setApproverId(int approvalId) {this.chanApvlId = approvalId; }
public void setPublishDate(Date publishDate) {this.chanPublDt = publishDate; }
public void setApprovalDate(Date approvalDate) {this.chanApvlDt = approvalDate; }
public void setEditable(boolean editable) {this.chanEditable = editable; }
public void setHasHelp(boolean hasHelp) {this.chanHasHelp = hasHelp; }
public void setHasAbout(boolean hasAbout) {this.chanHasAbout = hasAbout; }
public void setIsSecure(boolean isSecure) {this.chanIsSecure = isSecure; }
public void setLocale(String locale) {
if (locale!=null)
this.chanLocale = locale;
}
public void clearParameters() { this.parameters.clear(); }
public void setParameters(ChannelParameter[] parameters) {
for (int i = 0; i < parameters.length; i++) {
this.parameters.put(parameters[i].getName(), parameters[i]);
}
}
public void replaceParameters(ChannelParameter[] parameters) {
clearParameters();
setParameters(parameters);
}
public void putChanTitles(String locale, String chanTitle) {
chanTitles.put(locale, chanTitle);
}
public void putChanNames(String locale, String chanName) {
chanNames.put(locale, chanName);
}
public void putChanDescs(String locale, String chanDesc) {
chanDescs.put(locale, chanDesc);
}
/**
* Implementation required by IBasicEntity interface.
* @return EntityIdentifier
*/
public EntityIdentifier getEntityIdentifier() {
return new EntityIdentifier(String.valueOf(id), ChannelDefinition.class);
}
/**
* Adds a parameter to this channel definition
* @param parameter the channel parameter to add
*/
public void addParameter(ChannelParameter parameter) {
addParameter(parameter.getName(), parameter.getValue(), String.valueOf(parameter.getOverride()));
}
/**
* Adds a parameter to this channel definition
* @param name the channel parameter name
* @param value the channel parameter value
* @param override the channel parameter override setting
*/
public void addParameter(String name, String value, String override) {
parameters.put(name, new ChannelParameter(name, value, override));
}
/**
* Removes a parameter from this channel definition
* @param parameter the channel parameter to remove
*/
public void removeParameter(ChannelParameter parameter) {
removeParameter(parameter.getName());
}
/**
* Removes a parameter from this channel definition
* @param name the parameter name
*/
public void removeParameter(String name) {
parameters.remove(name);
}
/**
* Minimum attributes a channel must have
*/
private Element getBase(Document doc, String idTag, String chanClass,
boolean editable, boolean hasHelp, boolean hasAbout) {
Element channel = doc.createElement("channel");
if (doc instanceof IPortalDocument) {
((IPortalDocument)doc).putIdentifier(idTag, channel);
} else {
StringBuffer msg = new StringBuffer(128);
msg.append("ChannelDefinition::getBase() : ");
msg.append("Document does not implement IPortalDocument, ");
msg.append("so element caching cannot be performed.");
LogService.log(LogService.ERROR, msg.toString());
}
channel.setAttribute("ID", idTag);
channel.setAttribute("chanID", id + "");
channel.setAttribute("timeout", chanTimeout + "");
if (chanLocale != null) {
channel.setAttribute("name", getName(chanLocale));
channel.setAttribute("title", getTitle(chanLocale));
channel.setAttribute("locale", chanLocale);
} else {
channel.setAttribute("name", chanName);
channel.setAttribute("title", chanTitle);
}
channel.setAttribute("fname", chanFName);
channel.setAttribute("class", chanClass);
channel.setAttribute("typeID", chanTypeId + "");
channel.setAttribute("editable", editable ? "true" : "false");
channel.setAttribute("hasHelp", hasHelp ? "true" : "false");
channel.setAttribute("hasAbout", hasAbout ? "true" : "false");
channel.setAttribute("secure", chanIsSecure ? "true" : "false");
return channel;
}
private final Element nodeParameter(Document doc, String name, int value) {
return nodeParameter(doc, name, Integer.toString(value));
}
private final Element nodeParameter(Document doc, String name, String value) {
Element parameter = doc.createElement("parameter");
parameter.setAttribute("name", name);
parameter.setAttribute("value", value);
return parameter;
}
private final void addParameters(Document doc, Element channel) {
if (parameters != null) {
Iterator iter = parameters.values().iterator();
while (iter.hasNext()) {
ChannelParameter cp = (ChannelParameter)iter.next();
Element parameter = nodeParameter(doc, cp.name, cp.value);
if (cp.override) {
parameter.setAttribute("override", "yes");
}
channel.appendChild(parameter);
}
}
}
/**
* Display a message where this channel should be
*/
public Element getDocument(Document doc, String idTag, String statusMsg, int errorId) {
Element channel = getBase(doc, idTag, "org.jasig.portal.channels.CError", false, false, false);
addParameters(doc, channel);
channel.appendChild(nodeParameter(doc, "CErrorMessage", statusMsg));
channel.appendChild(nodeParameter(doc, "CErrorChanId", idTag));
channel.appendChild(nodeParameter(doc, "CErrorErrorId", errorId));
return channel;
}
/**
* return an xml representation of this channel
*/
public Element getDocument(Document doc, String idTag) {
Element channel = getBase(doc, idTag, chanClass, chanEditable, chanHasHelp, chanHasAbout);
channel.setAttribute("description", chanDesc);
addParameters(doc, channel);
return channel;
}
/**
* Is it time to reload me from the data store
*/
public boolean refreshMe() {
return false;
}
}
|
package org.jfree.data.gantt;
import java.util.Date;
import org.jfree.chart.axis.SymbolAxis;
import org.jfree.chart.renderer.xy.XYBarRenderer;
import org.jfree.data.general.DatasetChangeEvent;
import org.jfree.data.general.DatasetChangeListener;
import org.jfree.data.time.TimePeriod;
import org.jfree.data.xy.AbstractXYDataset;
import org.jfree.data.xy.IntervalXYDataset;
public class XYTaskDataset extends AbstractXYDataset
implements IntervalXYDataset, DatasetChangeListener {
/** The underlying tasks. */
private TaskSeriesCollection underlying;
/** The series interval width (typically 0.0 < w <= 1.0). */
private double seriesWidth;
/** A flag that controls whether or not the data values are transposed. */
private boolean transposed;
/**
* Creates a new dataset based on the supplied collection of tasks.
*
* @param tasks the underlying dataset (<code>null</code> not permitted).
*/
public XYTaskDataset(TaskSeriesCollection tasks) {
if (tasks == null) {
throw new IllegalArgumentException("Null 'tasks' argument.");
}
this.underlying = tasks;
this.seriesWidth = 0.8;
this.underlying.addChangeListener(this);
}
/**
* Returns the underlying task series collection that was supplied to the
* constructor.
*
* @return The underlying collection (never <code>null</code>).
*/
public TaskSeriesCollection getTasks() {
return this.underlying;
}
/**
* Returns the width of the interval for each series this dataset.
*
* @return The width of the series interval.
*
* @see #setSeriesWidth(double)
*/
public double getSeriesWidth() {
return this.seriesWidth;
}
/**
* Sets the series interval width and sends a {@link DatasetChangeEvent} to
* all registered listeners.
*
* @param w the width.
*
* @see #getSeriesWidth()
*/
public void setSeriesWidth(double w) {
if (w <= 0.0) {
throw new IllegalArgumentException("Requires 'w' > 0.0.");
}
this.seriesWidth = w;
fireDatasetChanged();
}
/**
* Returns a flag that indicates whether or not the dataset is transposed.
* The default is <code>false</code> which means the x-values are integers
* corresponding to the series indices, and the y-values are millisecond
* values corresponding to the task date/time intervals. If the flag
* is set to <code>true</code>, the x and y-values are reversed.
*
* @return The flag.
*
* @see #setTransposed(boolean)
*/
public boolean isTransposed() {
return this.transposed;
}
/**
* Sets the flag that controls whether or not the dataset is transposed
* and sends a {@link DatasetChangeEvent} to all registered listeners.
*
* @param transposed the new flag value.
*
* @see #isTransposed()
*/
public void setTransposed(boolean transposed) {
this.transposed = transposed;
fireDatasetChanged();
}
/**
* Returns the number of series in the dataset.
*
* @return The series count.
*/
public int getSeriesCount() {
return this.underlying.getSeriesCount();
}
/**
* Returns the name of a series.
*
* @param series the series index (zero-based).
*
* @return The name of a series.
*/
public Comparable getSeriesKey(int series) {
return this.underlying.getSeriesKey(series);
}
/**
* Returns the number of items (tasks) in the specified series.
*
* @param series the series index (zero-based).
*
* @return The item count.
*/
public int getItemCount(int series) {
return this.underlying.getSeries(series).getItemCount();
}
/**
* Returns the x-value (as a double primitive) for an item within a series.
*
* @param series the series index (zero-based).
* @param item the item index (zero-based).
*
* @return The value.
*/
public double getXValue(int series, int item) {
if (!this.transposed) {
return getSeriesValue(series);
}
else {
return getItemValue(series, item);
}
}
/**
* Returns the starting date/time for the specified item (task) in the
* given series, measured in milliseconds since 1-Jan-1970 (as in
* java.util.Date).
*
* @param series the series index.
* @param item the item (or task) index.
*
* @return The start date/time.
*/
public double getStartXValue(int series, int item) {
if (!this.transposed) {
return getSeriesStartValue(series);
}
else {
return getItemStartValue(series, item);
}
}
/**
* Returns the ending date/time for the specified item (task) in the
* given series, measured in milliseconds since 1-Jan-1970 (as in
* java.util.Date).
*
* @param series the series index.
* @param item the item (or task) index.
*
* @return The end date/time.
*/
public double getEndXValue(int series, int item) {
if (!this.transposed) {
return getSeriesEndValue(series);
}
else {
return getItemEndValue(series, item);
}
}
/**
* Returns the x-value for the specified series.
*
* @param series the series index.
* @param item the item index.
*
* @return The x-value (in milliseconds).
*/
public Number getX(int series, int item) {
return new Double(getXValue(series, item));
}
/**
* Returns the starting date/time for the specified item (task) in the
* given series, measured in milliseconds since 1-Jan-1970 (as in
* java.util.Date).
*
* @param series the series index.
* @param item the item (or task) index.
*
* @return The start date/time.
*/
public Number getStartX(int series, int item) {
return new Double(getStartXValue(series, item));
}
/**
* Returns the ending date/time for the specified item (task) in the
* given series, measured in milliseconds since 1-Jan-1970 (as in
* java.util.Date).
*
* @param series the series index.
* @param item the item (or task) index.
*
* @return The end date/time.
*/
public Number getEndX(int series, int item) {
return new Double(getEndXValue(series, item));
}
/**
* Returns the y-value (as a double primitive) for an item within a series.
*
* @param series the series index (zero-based).
* @param item the item index (zero-based).
*
* @return The value.
*/
public double getYValue(int series, int item) {
if (!this.transposed) {
return getItemValue(series, item);
}
else {
return getSeriesValue(series);
}
}
/**
* Returns the starting value of the y-interval for an item in the
* given series.
*
* @param series the series index.
* @param item the item (or task) index.
*
* @return The y-interval start.
*/
public double getStartYValue(int series, int item) {
if (!this.transposed) {
return getItemStartValue(series, item);
}
else {
return getSeriesStartValue(series);
}
}
/**
* Returns the ending value of the y-interval for an item in the
* given series.
*
* @param series the series index.
* @param item the item (or task) index.
*
* @return The y-interval end.
*/
public double getEndYValue(int series, int item) {
if (!this.transposed) {
return getItemEndValue(series, item);
}
else {
return getSeriesEndValue(series);
}
}
/**
* Returns the y-value for the specified series/item. In this
* implementation, we return the series index as the y-value (this means
* that every item in the series has a constant integer value).
*
* @param series the series index.
* @param item the item index.
*
* @return The y-value.
*/
public Number getY(int series, int item) {
return new Double(getYValue(series, item));
}
/**
* Returns the starting value of the y-interval for an item in the
* given series.
*
* @param series the series index.
* @param item the item (or task) index.
*
* @return The y-interval start.
*/
public Number getStartY(int series, int item) {
return new Double(getStartYValue(series, item));
}
/**
* Returns the ending value of the y-interval for an item in the
* given series.
*
* @param series the series index.
* @param item the item (or task) index.
*
* @return The y-interval end.
*/
public Number getEndY(int series, int item) {
return new Double(getEndYValue(series, item));
}
private double getSeriesValue(int series) {
return series;
}
private double getSeriesStartValue(int series) {
return series - this.seriesWidth / 2.0;
}
private double getSeriesEndValue(int series) {
return series + this.seriesWidth / 2.0;
}
private double getItemValue(int series, int item) {
TaskSeries s = this.underlying.getSeries(series);
Task t = s.get(item);
TimePeriod duration = t.getDuration();
Date start = duration.getStart();
Date end = duration.getEnd();
return (start.getTime() + end.getTime()) / 2.0;
}
private double getItemStartValue(int series, int item) {
TaskSeries s = this.underlying.getSeries(series);
Task t = s.get(item);
TimePeriod duration = t.getDuration();
Date start = duration.getStart();
return start.getTime();
}
private double getItemEndValue(int series, int item) {
TaskSeries s = this.underlying.getSeries(series);
Task t = s.get(item);
TimePeriod duration = t.getDuration();
Date end = duration.getEnd();
return end.getTime();
}
/**
* Receives a change event from the underlying dataset and responds by
* firing a change event for this dataset.
*
* @param event the event.
*/
public void datasetChanged(DatasetChangeEvent event) {
fireDatasetChanged();
}
/**
* Tests this dataset for equality with an arbitrary object.
*
* @param obj the object (<code>null</code> permitted).
*
* @return A boolean.
*/
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof XYTaskDataset)) {
return false;
}
XYTaskDataset that = (XYTaskDataset) obj;
if (this.seriesWidth != that.seriesWidth) {
return false;
}
if (this.transposed != that.transposed) {
return false;
}
if (!this.underlying.equals(that.underlying)) {
return false;
}
return true;
}
/**
* Returns a clone of this dataset.
*
* @return A clone of this dataset.
*
* @throws CloneNotSupportedException if there is a problem cloning.
*/
public Object clone() throws CloneNotSupportedException {
XYTaskDataset clone = (XYTaskDataset) super.clone();
clone.underlying = (TaskSeriesCollection) this.underlying.clone();
return clone;
}
}
|
package html;
import java.io.File;
import java.io.IOException;
import java.lang.ProcessBuilder.Redirect;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import com.google.common.collect.Lists;
import com.google.common.io.Files;
public class HtmlToPdf {
private static final String CMD_WK = "/usr/bin/wkhtmltopdf";
private static final String CMD_PANDOC = "/usr/bin/pandoc";
private static final String CMD_WEASYPRINT = "/usr/bin/weasyprint";
public File toPdf(String name, String html, String playSession, String converter, String copts) {
String filename = FilenameUtils.removeExtension(name)+".html";
File htmlFile = new HtmlZip().toFolder(Files.createTempDir(), filename, html, playSession);
return pdf(htmlFile, converter, copts);
}
private File pdf(File in, String converter, String copts) {
try {
File destfolder = Files.createTempDir();
File out = new File(destfolder, FilenameUtils.removeExtension(in.getName())+".pdf");
ProcessBuilder pb = converter(choose(converter), copts, in, out);
pb.directory(in.getParentFile());
pb.redirectErrorStream(true);
File log = new File(destfolder, "converter.log");
pb.redirectErrorStream(true);
pb.redirectOutput(Redirect.to(log));
Process p = pb.start();
// TODO do not wait forever
int es = p.waitFor();
if(out.exists()) {
return out;
} else {
String msg = "pdf creation failed with exit status "+es;
if(log.exists()) {
throw new RuntimeException(msg+"\n"+FileUtils.readFileToString(log)+
"\nfrom "+log.getAbsolutePath());
} else {
throw new RuntimeException(msg+" "+destfolder.getAbsolutePath());
}
}
} catch(Exception e) {
throw new RuntimeException(String.format("failed to create pdf from %s",in.getName()),e);
}
}
private String choose(String converter) {
List<String> available = Lists.newArrayList();
if(new File(CMD_WEASYPRINT).exists()) {
available.add(CMD_WEASYPRINT);
}
if(new File(CMD_WK).exists()) {
available.add(CMD_WK);
}
if(new File(CMD_PANDOC).exists()) {
available.add(CMD_PANDOC);
}
if(available.isEmpty()) {
throw new RuntimeException("no converter available (install pandoc/wkhtmltopdf/weasyprint)");
} else if(available.size() == 1) {
return available.get(0);
} else {
for(String s : available) {
if(StringUtils.contains(s, converter)) {
return s;
}
}
return available.get(0);
}
}
private ProcessBuilder converter(String converter, String copts, File in, File out) throws IOException {
if(StringUtils.equals(converter, CMD_WK)) {
return new ProcessBuilder(cmd(converter,
options(copts), in.getName(), out.getAbsolutePath()));
} else if(StringUtils.equals(converter,CMD_PANDOC)) {
return new ProcessBuilder(cmd(converter,
options(copts), "-o", out.getAbsolutePath(), in.getName()));
} else if(StringUtils.equals(converter, CMD_WEASYPRINT)) {
File css = new File(in.getParentFile(), "usercss.css");
FileUtils.writeStringToFile(css, "img {max-width: 100%;}");
return new ProcessBuilder(cmd(converter, "--stylesheet", css.getAbsolutePath(),
options(copts), in.getName(), out.getAbsolutePath()));
} else {
throw new RuntimeException(String.format("unknown converter '%s'", converter));
}
}
private List<String> cmd(Object... params) {
List<String> cmd = Lists.newArrayList();
for(Object o : params) {
if(o instanceof String) {
cmd.add((String)o);
} else if(o instanceof List<?>) {
for(Object o2 : (List<?>)o) {
if(o2 instanceof String) {
cmd.add((String)o2);
} else {
throw new RuntimeException();
}
}
} else {
throw new RuntimeException();
}
}
return cmd;
}
private List<String> options(String copts) {
return split(copts);
}
private List<String> split(String copts) {
List<String> matchList = Lists.newArrayList();
Pattern regex = Pattern.compile("[^\\s\"']+|\"([^\"]*)\"|'([^']*)'");
Matcher regexMatcher = regex.matcher(copts);
while (regexMatcher.find()) {
if (regexMatcher.group(1) != null) {
// Add double-quoted string without the quotes
matchList.add(regexMatcher.group(1));
} else if (regexMatcher.group(2) != null) {
// Add single-quoted string without the quotes
matchList.add(regexMatcher.group(2));
} else {
// Add unquoted word
matchList.add(regexMatcher.group());
}
}
return matchList;
}
}
|
package controllers;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import com.avaje.ebean.Ebean;
import com.avaje.ebean.Expr;
import com.avaje.ebean.Expression;
import com.avaje.ebean.RawSql;
import com.avaje.ebean.RawSqlBuilder;
import com.avaje.ebean.SqlUpdate;
import com.feth.play.module.pa.PlayAuthenticate;
import com.typesafe.plugin.*;
import models.*;
import play.*;
import play.data.*;
import play.libs.Json;
import play.mvc.*;
import play.mvc.Http.Context;
@Security.Authenticated(EditorSecured.class)
public class CRM extends Controller {
static Form<Person> personForm = Form.form(Person.class);
static Form<Comment> commentForm = Form.form(Comment.class);
static Form<Donation> donationForm = Form.form(Donation.class);
public static Result people() {
List<Comment> recent_comments = Comment.find.orderBy("created DESC").setMaxRows(20).findList();
return ok(views.html.people_index.render(Person.all(), recent_comments));
}
public static Result person(Integer id) {
Person the_person = Person.find.ref(id);
List<Person> family_members =
Person.find.where().isNotNull("family").eq("family", the_person.family).
ne("person_id", the_person.person_id).findList();
Set<Integer> family_ids = new HashSet<Integer>();
family_ids.add(the_person.person_id);
for (Person family : family_members) {
family_ids.add(family.person_id);
}
List<Comment> all_comments = Comment.find.where().in("person_id", family_ids).
order("created DESC").findList();
List<Donation> all_donations = Donation.find.where().in("person_id", family_ids).
order("date DESC").findList();
return ok(views.html.family.render(
the_person,
family_members,
all_comments,
all_donations));
}
public static Result jsonPeople(String query) {
Expression search_expr = null;
HashSet<Person> selected_people = new HashSet<Person>();
boolean first_time = true;
for (String term : query.split(" ")) {
List<Person> people_matched_this_round;
Expression this_expr =
Expr.or(Expr.ilike("last_name", "%" + term + "%"),
Expr.ilike("first_name", "%" + term + "%"));
this_expr = Expr.or(this_expr,
Expr.ilike("address", "%" + term + "%"));
this_expr = Expr.or(this_expr,
Expr.ilike("email", "%" + term + "%"));
people_matched_this_round =
Person.find.where(this_expr).findList();
List<PhoneNumber> phone_numbers =
PhoneNumber.find.where().ilike("number", "%" + term + "%").findList();
for (PhoneNumber pn : phone_numbers) {
people_matched_this_round.add(pn.owner);
}
if (first_time) {
selected_people.addAll(people_matched_this_round);
} else {
selected_people.retainAll(people_matched_this_round);
}
first_time = false;
}
List<Map<String, String> > result = new ArrayList<Map<String, String> > ();
for (Person p : selected_people) {
HashMap<String, String> values = new HashMap<String, String>();
String label = p.first_name;
if (p.last_name != null) {
label = label + " " + p.last_name;
}
values.put("label", label);
values.put("id", "" + p.person_id);
result.add(values);
}
return ok(Json.stringify(Json.toJson(result)));
}
public static Result jsonTags(String term, Integer personId) {
String like_arg = "%" + term + "%";
List<Tag> selected_tags =
Tag.find.where().ilike("title", "%" + term + "%").findList();
List<Tag> existing_tags = null;
Person p = Person.find.byId(personId);
if (p != null) {
existing_tags = p.tags;
}
List<Map<String, String> > result = new ArrayList<Map<String, String> > ();
for (Tag t : selected_tags) {
if (existing_tags == null || !existing_tags.contains(t)) {
HashMap<String, String> values = new HashMap<String, String>();
values.put("label", t.title);
values.put("id", "" + t.id);
result.add(values);
}
}
HashMap<String, String> values = new HashMap<String, String>();
values.put("label", "Create new tag: " + term);
values.put("id", "-1");
result.add(values);
return ok(Json.stringify(Json.toJson(result)));
}
public static Collection<Person> getTagMembers(Integer tagId, String familyMode) {
List<Person> people = getPeopleForTag(tagId);
Set<Person> selected_people = new HashSet<Person>();
selected_people.addAll(people);
if (!familyMode.equals("just_tags")) {
for (Person p : people) {
if (p.family != null) {
selected_people.addAll(p.family.family_members);
}
}
}
if (familyMode.equals("family_no_kids")) {
Set<Person> no_kids = new HashSet<Person>();
for (Person p2 : selected_people) {
if (p2.dob == null ||
CRM.calcAge(p2) > 18) {
no_kids.add(p2);
}
}
selected_people = no_kids;
}
return selected_people;
}
public static Result renderTagMembers(Integer tagId, String familyMode) {
Tag the_tag = Tag.find.byId(tagId);
return ok(views.html.to_address_fragment.render(the_tag.title,
getTagMembers(tagId, familyMode)));
}
public static Result addTag(Integer tagId, String title, Integer personId) {
Person p = Person.find.byId(personId);
if (p == null) {
return badRequest();
}
Tag the_tag;
if (tagId == null) {
the_tag = Tag.create(title);
} else {
the_tag = Tag.find.ref(tagId);
}
PersonTag pt = PersonTag.create(
the_tag,
p,
Application.getCurrentUser());
p.tags.add(the_tag);
return ok(views.html.tag_fragment.render(the_tag, p));
}
public static Result removeTag(Integer person_id, Integer tag_id) {
Ebean.createSqlUpdate("DELETE from person_tag where person_id=" + person_id +
" AND tag_id=" + tag_id).execute();
return ok();
}
public static List<Person> getPeopleForTag(Integer id) {
RawSql rawSql = RawSqlBuilder
.parse("SELECT person.person_id, person.first_name, person.last_name, person.display_name from "+
"person join person_tag pt on person.person_id=pt.person_id "+
"join tag on pt.tag_id=tag.id")
.columnMapping("person.person_id", "person_id")
.columnMapping("person.first_name", "first_name")
.columnMapping("person.last_name", "last_name")
.columnMapping("person.display_name", "display_name")
.create();
return Ebean.find(Person.class).setRawSql(rawSql).
where().eq("tag.id", id).orderBy("person.last_name, person.first_name").findList();
}
public static Result viewTag(Integer id) {
Tag the_tag = Tag.find.byId(id);
List<Person> people = getPeopleForTag(id);
Set<Person> people_with_family = new HashSet<Person>();
for (Person p : people) {
if (p.family != null) {
people_with_family.addAll(p.family.family_members);
}
}
if (the_tag.use_student_display)
{
return viewIntentToEnroll(the_tag, people, people_with_family);
}
else
{
return ok(views.html.tag.render(the_tag, people, people_with_family));
}
}
public static Result viewIntentToEnroll(Tag the_tag, List<Person> students,
Set<Person> family_members)
{
return ok(views.html.intent_to_enroll_tag.render(the_tag, students, family_members));
}
public static Result newPerson() {
return ok(views.html.new_person.render(personForm));
}
public static Result makeNewPerson() {
Form<Person> filledForm = personForm.bindFromRequest();
if(filledForm.hasErrors()) {
return badRequest(
views.html.new_person.render(filledForm)
);
} else {
Person new_person = Person.create(filledForm);
return redirect(routes.CRM.person(new_person.person_id));
}
}
static Email getPendingEmail() {
return Email.find.where().eq("deleted", false).eq("sent", false).orderBy("id ASC").setMaxRows(1).findUnique();
}
public static boolean hasPendingEmail() {
return getPendingEmail() != null;
}
public static Result viewPendingEmail() {
Email e = getPendingEmail();
if (e == null) {
return redirect(routes.CRM.people());
}
Tag staff_tag = Tag.find.where().eq("title", "Staff").findUnique();
List<Person> people = getPeopleForTag(staff_tag.id);
ArrayList<String> test_addresses = new ArrayList<String>();
for (Person p : people) {
test_addresses.add(p.email);
}
test_addresses.add("staff@threeriversvillageschool.org");
ArrayList<String> from_addresses = new ArrayList<String>();
from_addresses.add("office@threeriversvillageschool.org");
from_addresses.add("evan@threeriversvillageschool.org");
from_addresses.add("jmp@threeriversvillageschool.org");
from_addresses.add("jancey@threeriversvillageschool.org");
from_addresses.add("info@threeriversvillageschool.org");
from_addresses.add("staff@threeriversvillageschool.org");
e.parseMessage();
return ok(views.html.view_pending_email.render(e, test_addresses, from_addresses));
}
public static Result sendTestEmail() {
final Map<String, String[]> values = request().body().asFormUrlEncoded();
Email e = Email.find.byId(Integer.parseInt(values.get("id")[0]));
e.parseMessage();
try {
MimeMessage to_send = new MimeMessage(e.parsedMessage);
to_send.addRecipient(Message.RecipientType.TO,
new InternetAddress(values.get("dest_email")[0]));
to_send.setFrom(new InternetAddress("Papal DB <noreply@threeriversvillageschool.org>"));
Transport.send(to_send);
} catch (MessagingException ex) {
ex.printStackTrace();
}
return ok();
}
public static Result sendEmail() {
final Map<String, String[]> values = request().body().asFormUrlEncoded();
Email e = Email.find.byId(Integer.parseInt(values.get("id")[0]));
e.parseMessage();
int tagId = Integer.parseInt(values.get("tagId")[0]);
Tag theTag = Tag.find.byId(tagId);
String familyMode = values.get("familyMode")[0];
Collection<Person> recipients = getTagMembers(tagId, familyMode);
boolean hadErrors = false;
for (Person p : recipients) {
if (p.email != null && !p.email.equals("")) {
try {
MimeMessage to_send = new MimeMessage(e.parsedMessage);
to_send.addRecipient(Message.RecipientType.TO,
new InternetAddress(p.first_name + " " + p.last_name + "<" + p.email + ">"));
to_send.setFrom(new InternetAddress(values.get("from")[0]));
Transport.send(to_send);
} catch (MessagingException ex) {
ex.printStackTrace();
hadErrors = true;
}
}
}
// Send confirmation email
try {
MimeMessage to_send = new MimeMessage(e.parsedMessage);
to_send.addRecipient(Message.RecipientType.TO,
new InternetAddress("Staff <staff@threeriversvillageschool.org>"));
String subject = "(Sent to " + theTag.title + " " + familyMode + ") " + to_send.getSubject();
if (hadErrors) {
subject = "***ERRORS*** " + subject;
}
to_send.setSubject(subject);
to_send.setFrom(new InternetAddress(values.get("from")[0]));
Transport.send(to_send);
} catch (MessagingException ex) {
ex.printStackTrace();
}
e.delete();
return ok();
}
public static Result deleteEmail() {
final Map<String, String[]> values = request().body().asFormUrlEncoded();
Email e = Email.find.byId(Integer.parseInt(values.get("id")[0]));
e.delete();
return ok();
}
public static Result deletePerson(Integer id) {
Person.delete(id);
return redirect(routes.CRM.people());
}
public static Result editPerson(Integer id) {
return ok(views.html.edit_person.render(Person.find.ref(id).fillForm()));
}
public static Result savePersonEdits() {
return redirect(routes.CRM.person(Person.updateFromForm(personForm.bindFromRequest()).person_id));
}
public static String getInitials(Person p) {
String result = "";
if (p.first_name != null && p.first_name.length() > 0) {
result += p.first_name.charAt(0);
}
if (p.last_name != null && p.last_name.length() > 0) {
result += p.last_name.charAt(0);
}
return result;
}
public static Result addComment() {
Form<Comment> filledForm = commentForm.bindFromRequest();
Comment new_comment = new Comment();
new_comment.person = Person.find.byId(Integer.parseInt(filledForm.field("person").value()));
new_comment.user = Application.getCurrentUser();
new_comment.message = filledForm.field("message").value();
String task_id_string = filledForm.field("comment_task_ids").value();
if (task_id_string.length() > 0 || new_comment.message.length() > 0) {
new_comment.save();
String[] task_ids = task_id_string.split(",");
for (String id_string : task_ids) {
if (!id_string.isEmpty()) {
int id = Integer.parseInt(id_string);
if (id >= 1) {
CompletedTask.create(Task.find.byId(id), new_comment);
}
}
}
if (filledForm.field("send_email").value() != null) {
MailerAPI mail = play.Play.application().plugin(MailerPlugin.class).email();
mail.setSubject("Papal comment: " + new_comment.user.name + " & " + getInitials(new_comment.person));
mail.addRecipient("TRVS Staff <staff@threeriversvillageschool.org>");
mail.addFrom("Papal DB <noreply@threeriversvillageschool.org>");
mail.sendHtml(views.html.comment_email.render(Comment.find.byId(new_comment.id)).toString());
}
return ok(views.html.comment_fragment.render(Comment.find.byId(new_comment.id), false));
} else {
return ok();
}
}
public static Result addDonation() {
Form<Donation> filledForm = donationForm.bindFromRequest();
Donation new_donation = new Donation();
new_donation.person = Person.find.byId(Integer.parseInt(filledForm.field("person").value()));
new_donation.description = filledForm.field("description").value();
new_donation.dollar_value = Float.parseFloat(filledForm.field("dollar_value").value());
try
{
new_donation.date = new SimpleDateFormat("yyyy-MM-dd").parse(filledForm.field("date").value());
// Set time to 12 noon so that time zone issues won't bump us to the wrong day.
new_donation.date.setHours(12);
}
catch (ParseException e)
{
new_donation.date = new Date();
}
new_donation.is_cash = filledForm.field("donation_type").value().equals("Cash");
if (filledForm.field("needs_thank_you").value() != null) {
new_donation.thanked = !filledForm.field("needs_thank_you").value().equals("on");
} else {
new_donation.thanked = true;
}
if (filledForm.field("needs_indiegogo_reward").value() != null) {
new_donation.indiegogo_reward_given = !filledForm.field("needs_indiegogo_reward").value().equals("on");
} else {
new_donation.indiegogo_reward_given = true;
}
new_donation.save();
return ok(views.html.donation_fragment.render(Donation.find.byId(new_donation.id)));
}
public static Result donationThankYou(int id)
{
Donation d = Donation.find.byId(id);
d.thanked = true;
d.thanked_by_user = Application.getCurrentUser();
d.thanked_time = new Date();
d.save();
return ok();
}
public static Result donationIndiegogoReward(int id)
{
Donation d = Donation.find.byId(id);
d.indiegogo_reward_given = true;
d.indiegogo_reward_by_user = Application.getCurrentUser();
d.indiegogo_reward_given_time = new Date();
d.save();
return ok();
}
public static Result donationsNeedingThankYou()
{
List<Donation> donations = Donation.find.where().eq("thanked", false).orderBy("date DESC").findList();
return ok(views.html.donation_list.render("Donations needing thank you", donations));
}
public static Result donationsNeedingIndiegogo()
{
List<Donation> donations = Donation.find.where().eq("indiegogo_reward_given", false).orderBy("date DESC").findList();
return ok(views.html.donation_list.render("Donations needing Indiegogo reward", donations));
}
public static Result donations()
{
return ok(views.html.donation_list.render("All donations", Donation.find.orderBy("date DESC").findList()));
}
public static int calcAge(Person p) {
return (int)((new Date().getTime() - p.dob.getTime()) / 1000 / 60 / 60 / 24 / 365.25);
}
public static int calcAgeAtBeginningOfSchool(Person p) {
if (p.dob == null) {
return -1;
}
return (int)((new Date(114, 7, 25).getTime() - p.dob.getTime()) / 1000 / 60 / 60 / 24 / 365.25);
}
public static String formatDob(Date d) {
if (d == null) {
return "
}
return new SimpleDateFormat("MM/dd/yy").format(d);
}
public static String formatDate(Date d) {
d = new Date(d.getTime() +
(Application.getConfiguration().getInt("time_zone_offset") * 1000L * 60 * 60));
Date now = new Date();
long diffHours = (now.getTime() - d.getTime()) / 1000 / 60 / 60;
// String format = "EEE MMMM d, h:mm a";
String format;
if (diffHours < 24) {
format = "h:mm a";
} else if (diffHours < 24 * 7) {
format = "EEEE, MMMM d";
} else {
format = "MM/d/yy";
}
return new SimpleDateFormat(format).format(d);
}
public static Result viewTaskList(Integer id) {
TaskList list = TaskList.find.byId(id);
List<Person> people = getPeopleForTag(list.tag.id);
return ok(views.html.task_list.render(list, people));
}
}
|
package models;
import java.time.Duration;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.OrderBy;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Transient;
import com.avaje.ebean.Model;
import com.avaje.ebean.annotation.UpdatedTimestamp;
import com.fasterxml.jackson.annotation.JsonIgnore;
import play.Logger;
import play.data.validation.Constraints.Required;
@Entity
public class Invitee extends Model implements Comparable<Invitee> {
@Id
public String irn;
@Required
public String displayName;
public boolean plusOne;
public boolean edinburgh;
public boolean australia;
public int numberInvited;
public boolean kids;
public int numberKidsInvited;
public Date rsvpByDate;
public String email;
public boolean inviteSent;
@OneToMany(fetch = FetchType.EAGER, mappedBy="invitee", cascade=CascadeType.ALL)
@OrderBy("id")
public List<Rsvp> rsvps = new ArrayList<>();
@Temporal(TemporalType.TIMESTAMP)
@UpdatedTimestamp
public Date lastViewed;
public static Finder<String, Invitee> find = new Finder<>(Invitee.class);
public Invitee() {
}
public Invitee(String irn, String displayName, boolean plusOne, int numberInvited, boolean edinburgh, boolean australia, Date rsvpDate) {
super();
this.irn = irn;
this.displayName = displayName;
this.plusOne = plusOne;
this.edinburgh = edinburgh;
this.australia = australia;
this.numberInvited = numberInvited;
this.rsvpByDate = rsvpDate;
}
@Transient
@JsonIgnore
public Rsvp getLatestRsvp() {
if (rsvps == null) {
rsvps = new ArrayList<>();
}
if (rsvps.size() == 0) {
Rsvp rsvp = new Rsvp();
rsvp.invitee = this;
rsvp.name = this.displayName;
rsvp.rsvp = null;
rsvp.guestNumber = this.numberInvited;
rsvp.email = this.email;
rsvp.kids = this.numberKidsInvited;
return rsvp;
} else {
Logger.debug("Size: " + rsvps.get(rsvps.size()-1));
return rsvps.get(rsvps.size()-1);
}
}
@Transient
@JsonIgnore
public Optional<Rsvp> getLastSubmittedRsvp() {
if (rsvps.size() == 0)
return Optional.empty();
return Optional.ofNullable(rsvps.get(rsvps.size()-1));
}
@Override
public int compareTo(Invitee o) {
if (o.australia && !this.australia) {
return 1;
} else if (!o.australia && this.australia) {
return -1;
} else if (o.edinburgh && !this.edinburgh) {
return 1;
} else if (!o.edinburgh && this.edinburgh) {
return -1;
}
return this.displayName.compareTo(o.displayName);
}
@Transient
@JsonIgnore
public String getLastViewedString() {
Duration since = Duration.between(LocalDateTime.ofInstant(Instant.ofEpochMilli(getLastViewed().getTime()), ZoneId.systemDefault()), LocalDateTime.now());
return (since.getSeconds() < 3600) ? (since.getSeconds() / 60) + " minutes ago" :
(since.getSeconds() > (86400*2)) ? (long)(Math.floor(since.getSeconds() / 86400D)) + " days ago" :
(long)(Math.round(since.getSeconds() / 3600D)) + " hours ago";
}
public String getIrn() {
return irn;
}
public void setIrn(String irn) {
this.irn = irn;
}
public String getDisplayName() {
return displayName;
}
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
public boolean isPlusOne() {
return plusOne;
}
public void setPlusOne(boolean plusOne) {
this.plusOne = plusOne;
}
public boolean isEdinburgh() {
return edinburgh;
}
public void setEdinburgh(boolean edinburgh) {
this.edinburgh = edinburgh;
}
public boolean isAustralia() {
return australia;
}
public void setAustralia(boolean australia) {
this.australia = australia;
}
public int getNumberInvited() {
return numberInvited;
}
public void setNumberInvited(int numberInvited) {
this.numberInvited = numberInvited;
}
public boolean isKids() {
return kids;
}
public void setKids(boolean kids) {
this.kids = kids;
}
public int getNumberKidsInvited() {
return numberKidsInvited;
}
public void setNumberKidsInvited(int numberKidsInvited) {
this.numberKidsInvited = numberKidsInvited;
}
public Date getRsvpByDate() {
return rsvpByDate;
}
public void setRsvpByDate(Date rsvpByDate) {
this.rsvpByDate = rsvpByDate;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public boolean isInviteSent() {
return inviteSent;
}
public void setInviteSent(boolean inviteSent) {
this.inviteSent = inviteSent;
}
public List<Rsvp> getRsvps() {
return rsvps;
}
public void setRsvps(List<Rsvp> rsvps) {
this.rsvps = rsvps;
}
public Date getLastViewed() {
return lastViewed;
}
public void setLastViewed(Date lastViewed) {
this.lastViewed = lastViewed;
}
}
|
package models;
import static com.avaje.ebean.Expr.contains;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import jxl.Workbook;
import jxl.format.Alignment;
import jxl.format.Border;
import jxl.format.BorderLineStyle;
import jxl.format.Colour;
import jxl.format.ScriptStyle;
import jxl.format.UnderlineStyle;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import models.enumeration.Direction;
import models.enumeration.IssueState;
import models.enumeration.Matching;
import models.enumeration.StateType;
import models.support.FinderTemplate;
import models.support.Options;
import models.support.OrderParams;
import models.support.SearchParams;
import org.joda.time.Duration;
import play.data.format.Formats;
import play.data.validation.Constraints;
import play.db.ebean.Model;
import utils.JodaDateUtil;
import com.avaje.ebean.Page;
import controllers.SearchApp;
/**
* @author Taehyun Park
*
* Issue entity mangaed by Ebean
* @param id
* ID
* @param title
*
* @param body
*
* @param state
* (, , , )
* @param statusType
* , => , =>
* @param date
*
* @param authorId
* ID
* @param project
*
* @param issueType
*
* @param assigneeId
* Id
* @param componentName
*
* @param milestone
*
* @param importance
*
* @param diagnosisResult
*
* @param filePath
*
* @param osType
* OS
* @param browserType
*
* @param dbmsType
* DBMS
*/
@Entity
public class Issue extends Model {
private static final long serialVersionUID = 1L;
private static Finder<Long, Issue> find = new Finder<Long, Issue>(Long.class, Issue.class);
public static final int FIRST_PAGE_NUMBER = 0;
public static final int ISSUE_COUNT_PER_PAGE = 25;
public static final int NUMBER_OF_ONE_MORE_COMMENTS = 1;
public static final String DEFAULT_SORTER = "date";
public static final String TO_BE_ASSIGNED = "TBA";
@Id
public Long id;
@Constraints.Required
public String title;
@Constraints.Required
public String body;
@Formats.DateTime(pattern = "yyyy-MM-dd")
public Date date;
public int numOfComments;
public Long milestoneId;
public Long assigneeId;
public Long authorId;
public String authorName;
public IssueState state;
public StateType stateType;
public String issueType;
public String componentName;
// TODO ?
public String filePath;
public String osType;
public String browserType;
public String dbmsType;
public String importance;
public String diagnosisResult;
@ManyToOne
public Project project;
@OneToMany(mappedBy = "issue", cascade = CascadeType.ALL)
public List<IssueComment> comments = new ArrayList<IssueComment>();
public Issue() {
this.date = JodaDateUtil.now();
}
public String issueTypeLabel() {
return issueTypes().get(issueType);
}
public Duration ago() {
return JodaDateUtil.ago(this.date);
}
public String reporterName() {
return User.findNameById(this.authorId);
}
/**
* issueList, issue view assignee . getAssigneeName
* .
*/
public String assigneeName() {
return (this.assigneeId != null ? User.findNameById(this.assigneeId) : "issue.noAssignee");
}
/**
* .
*
* @return boolean
*/
public boolean isOpen() {
return StateType.OPEN.equals(this.stateType);
}
/**
* View .
*
* @return
*/
public String state() {
if (this.state.equals(IssueState.ASSIGNED)) {
return IssueState.ASSIGNED.state();
} else if (this.state.equals(IssueState.SOLVED)) {
return IssueState.SOLVED.state();
} else if (this.state.equals(IssueState.FINISHED)) {
return IssueState.FINISHED.state();
} else
return IssueState.ENROLLED.state();
}
/**
* (state) (stateType) .
* diagnosisResult 2 "" , .
*
* @param state
*/
public void updateStateType(Issue issue) {
if (this.state == null || this.state.equals(IssueState.ASSIGNED)
|| this.state.equals(IssueState.ENROLLED)) {
this.stateType = StateType.OPEN;
} else {
this.stateType = StateType.CLOSED;
}
}
/**
* (assignee) (diagnosisResult)
* .
*
* @param issue
*/
public void updateState(Issue issue) {
if (isEnrolled(issue)) {
this.state = IssueState.ENROLLED;
} else if (isFinished(issue)) {
this.state = IssueState.FINISHED;
} else if (isAssigned(issue)) {
this.state = IssueState.ASSIGNED;
} else if (isSolved(issue)) {
this.state = IssueState.SOLVED;
} else
this.state = IssueState.ENROLLED;
updateStateType(issue);
}
/**
* "" .
*
* @param issue
* @return boolean
*/
public boolean isEnrolled(Issue issue) {
if (issue.assigneeId == null && issue.diagnosisResult.equals("")) {
return true;
} else
return false;
}
/**
* , "" .
*
* @param issue
* @return
*/
public boolean isAssigned(Issue issue) {
if (issue.assigneeId != null && issue.diagnosisResult.equals("")) {
return true;
} else
return false;
}
/**
* 2 ( ) "" .
*
* @param issue
* @return
*/
public boolean isSolved(Issue issue) {
if (issue.assigneeId != null && issue.diagnosisResult.equals("2")) {
return true;
} else
return false;
}
/**
* , 2 "" .
*
* @param issue
* @return
*/
public boolean isFinished(Issue issue) {
if (!issue.diagnosisResult.equals("2") && !issue.diagnosisResult.equals("")) {
return true;
} else
return false;
}
/**
* View . Purpose : View Select i18n
* .
*
* @return
*/
public static Map<String, String> issueTypes() {
return new Options("issue.new.detailInfo.issueType.worst",
"issue.new.detailInfo.issueType.worse", "issue.new.detailInfo.issueType.bad",
"issue.new.detailInfo.issueType.enhancement",
"issue.new.detailInfo.issueType.recommendation");
}
/**
* View OS . Purpose : View Select i18n
* .
*
* @return
*/
public static Map<String, String> osTypes() {
return new Options("issue.new.environment.osType.windows",
"issue.new.environment.osType.Mac", "issue.new.environment.osType.Linux");
}
/**
* View . Purpose : View Select i18n
* .
*
* @return
*/
public static Map<String, String> browserTypes() {
return new Options("issue.new.environment.browserType.ie",
"issue.new.environment.browserType.chrome",
"issue.new.environment.browserType.firefox",
"issue.new.environment.browserType.safari",
"issue.new.environment.browserType.opera");
}
/**
* View DBMS . Purpose : View Select i18n
* .
*
* @return
*/
public static Map<String, String> dbmsTypes() {
return new Options("issue.new.environment.dbmsType.postgreSQL",
"issue.new.environment.dbmsType.CUBRID", "issue.new.environment.dbmsType.MySQL");
}
/**
* View . Purpose : View Select i18n
* .
*
* @return
*/
public static Map<String, String> importances() {
return new Options("issue.new.result.importance.highest",
"issue.new.result.importance.high", "issue.new.result.importance.average",
"issue.new.result.importance.low", "issue.new.result.importance.lowest");
}
/**
* View . Purpose : View Select i18n
* .
*
* @return
*/
public static Map<String, String> diagnosisResults() {
return new Options("issue.new.result.diagnosisResult.bug",
"issue.new.result.diagnosisResult.fixed",
"issue.new.result.diagnosisResult.willNotFixed",
"issue.new.result.diagnosisResult.notaBug",
"issue.new.result.diagnosisResult.awaitingResponse",
"issue.new.result.diagnosisResult.unreproducible",
"issue.new.result.diagnosisResult.duplicated",
"issue.new.result.diagnosisResult.works4me");
}
/**
* id .
*
* @param id
* @return
*/
public static Issue findById(Long id) {
return find.byId(id);
}
/**
* .
*
* @param issue
* @return
*/
public static Long create(Issue issue) {
issue.save();
if (issue.milestoneId != null) {
Milestone milestone = Milestone.findById(issue.milestoneId);
milestone.add(issue);
}
issue.updateStateType(issue);
return issue.id;
}
/**
* .
*
* @param id
*/
public static void delete(Long id) {
Issue issue = find.byId(id);
if (!issue.milestoneId.equals(0l) || issue.milestoneId != null) {
Milestone milestone = Milestone.findById(issue.milestoneId);
milestone.delete(issue);
}
issue.delete();
}
/**
* & .
*
* @param issue
*/
public static void edit(Issue issue) {
Issue previousIssue = findById(issue.id);
if (issue.filePath == null) {
issue.filePath = previousIssue.filePath;
}
issue.updateStateType(issue);
issue.update();
}
/**
* , open ..
*
* @param projectName
* @return
*/
public static Page<Issue> findOpenIssues(String projectName) {
return Issue.findIssues(projectName, StateType.OPEN);
}
/**
* , closed .
*
* @param projectName
* @return
*/
public static Page<Issue> findClosedIssues(String projectName) {
return Issue.findIssues(projectName, StateType.CLOSED);
}
/**
* State .
*
* @param projectName
* @param state
* @return
*/
public static Page<Issue> findIssues(String projectName, StateType state) {
return findIssues(projectName, FIRST_PAGE_NUMBER, state, DEFAULT_SORTER, Direction.DESC,
"", null, false, false);
}
/**
* query(filter) .
*
* @param projectName
* @param filter
* @param state
* @param commentedCheck
* @param fileAttachedCheck
* @return
*/
public static Page<Issue> findFilteredIssues(String projectName, String filter,
StateType state, boolean commentedCheck, boolean fileAttachedCheck) {
return findIssues(projectName, FIRST_PAGE_NUMBER, state, DEFAULT_SORTER, Direction.DESC,
filter, null, commentedCheck, fileAttachedCheck);
}
/**
* .
*
* @param projectName
* @param filter
* @return
*/
public static Page<Issue> findCommentedIssues(String projectName, String filter) {
return findIssues(projectName, FIRST_PAGE_NUMBER, StateType.ALL, DEFAULT_SORTER,
Direction.DESC, filter, null, true, false);
}
/**
* .
*
* @param projectName
* @param filter
* @return
*/
public static Page<Issue> findFileAttachedIssues(String projectName, String filter) {
return findIssues(projectName, FIRST_PAGE_NUMBER, StateType.ALL, DEFAULT_SORTER,
Direction.DESC, filter, null, false, true);
}
/**
* Id .
*
* @param projectName
* @param milestoneId
* @return
*/
public static Page<Issue> findIssuesByMilestoneId(String projectName, Long milestoneId) {
return findIssues(projectName, FIRST_PAGE_NUMBER, StateType.ALL, DEFAULT_SORTER,
Direction.DESC, "", milestoneId, false, false);
}
/**
* parameter Page .
*
* @param projectName
* project ID to find issues
* @param pageNumber
* Page to display
* @param state
* state type of issue(OPEN or CLOSED
* @param sortBy
* Issue property used for sorting, but, it might be fixed to
* enum type
* @param order
* Sort order(either asc or desc)
* @param filter
* filter applied on the title column
* @param commentedCheck
* filter applied on the commetedCheck column,
* @param fileAttachedCheck
* filter applied on the fileAttachedCheck column,
*
* @return Page .
*/
public static Page<Issue> findIssues(String projectName, int pageNumber, StateType state,
String sortBy, Direction order, String filter, Long milestoneId,
boolean commentedCheck, boolean fileAttachedCheck) {
OrderParams orderParams = new OrderParams().add(sortBy, order);
SearchParams searchParams = new SearchParams().add("project.name", projectName,
Matching.EQUALS);
if (filter != null && !filter.isEmpty()) {
searchParams.add("title", filter, Matching.CONTAINS);
}
if (milestoneId != null) {
searchParams.add("milestoneId", milestoneId, Matching.EQUALS);
}
if (commentedCheck) {
searchParams.add("numOfComments", NUMBER_OF_ONE_MORE_COMMENTS, Matching.GE);
}
if (fileAttachedCheck) {
searchParams.add("filePath", "", Matching.NOT_EQUALS);
}
if (state == null) {
state = StateType.ALL;
}
switch (state)
{
case OPEN:
searchParams.add("stateType", StateType.OPEN, Matching.EQUALS);
break;
case CLOSED:
searchParams.add("stateType", StateType.CLOSED, Matching.EQUALS);
break;
default:
}
return FinderTemplate.getPage(orderParams, searchParams, find, ISSUE_COUNT_PER_PAGE,
pageNumber);
}
public static Long findAssigneeIdByIssueId(String projectName, Long issueId) {
return find.byId(issueId).assigneeId;
}
/**
* .
*
* @param milestoneId
* @return
*/
public static List<Issue> findByMilestoneId(Long milestoneId) {
SearchParams searchParams = new SearchParams().add("milestoneId", milestoneId,
Matching.EQUALS);
return FinderTemplate.findBy(null, searchParams, find);
}
/**
* JXL , .
*
* @param resultList
*
* @param pageName
* (, ex , )
* @return
* @throws Exception
*/
public static String excelSave(List<Issue> resultList, String pageName) throws Exception {
String excelFile = pageName + "_" + JodaDateUtil.today().getTime() + ".xls";
String fullPath = "public/uploadFiles/" + excelFile;
WritableWorkbook workbook = null;
WritableSheet sheet = null;
try {
WritableFont wf1 = new WritableFont(WritableFont.TIMES, 13, WritableFont.BOLD, false,
UnderlineStyle.SINGLE, Colour.BLUE_GREY, ScriptStyle.NORMAL_SCRIPT);
WritableCellFormat cf1 = new WritableCellFormat(wf1);
cf1.setBorder(Border.ALL, BorderLineStyle.DOUBLE);
cf1.setAlignment(Alignment.CENTRE);
WritableFont wf2 = new WritableFont(WritableFont.TAHOMA, 11, WritableFont.NO_BOLD,
false, UnderlineStyle.NO_UNDERLINE, Colour.BLACK, ScriptStyle.NORMAL_SCRIPT);
WritableCellFormat cf2 = new WritableCellFormat(wf2);
cf2.setShrinkToFit(true);
cf2.setBorder(Border.ALL, BorderLineStyle.THIN);
cf2.setAlignment(Alignment.CENTRE);
workbook = Workbook.createWorkbook(new File(fullPath));
sheet = workbook.createSheet(String.valueOf(JodaDateUtil.today().getTime()), 0);
String[] labalArr = { "ID", "STATE", "TITLE", "ASSIGNEE", "DATE" };
for (int i = 0; i < labalArr.length; i++) {
sheet.addCell(new Label(i, 0, labalArr[i], cf1));
sheet.setColumnView(i, 20);
}
for (int i = 1; i < resultList.size() + 1; i++) {
Issue issue = (Issue) resultList.get(i - 1);
int colcnt = 0;
sheet.addCell(new Label(colcnt++, i, issue.id.toString(), cf2));
sheet.addCell(new Label(colcnt++, i, issue.state.toString(), cf2));
sheet.addCell(new Label(colcnt++, i, issue.title, cf2));
sheet.addCell(new Label(colcnt++, i, getAssigneeName(issue.assigneeId), cf2));
sheet.addCell(new Label(colcnt++, i, issue.date.toString(), cf2));
}
workbook.write();
} catch (Exception e) {
e.printStackTrace();
throw e;
} finally {
try {
if (workbook != null)
workbook.close();
} catch (WriteException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return excelFile;
}
/**
* excelSave assignee .
*
* @param uId
* @return
*/
private static String getAssigneeName(Long uId) {
return (uId != null ? User.findNameById(uId) : TO_BE_ASSIGNED);
}
// FIXME , view
/**
* comment delete create , numOfComment comment.size() .
*
* @param id
*/
public static void updateNumOfComments(Long id) {
Issue issue = Issue.findById(id);
issue.numOfComments = issue.comments.size();
issue.update();
}
/**
* condition.filter .
*
* @param project
* @param condition
* @return
*/
public static Page<Issue> findIssues(Project project, SearchApp.ContentSearchCondition condition) {
String filter = condition.filter;
return find.where().eq("project.id", project.id)
.or(contains("title", filter), contains("body", filter))
.findPagingList(condition.pageSize).getPage(condition.page - 1);
}
}
|
package ucar.nc2.iosp.grid;
import ucar.nc2.*;
import ucar.nc2.iosp.mcidas.McIDASLookup;
import ucar.nc2.iosp.gempak.GempakLookup;
import ucar.nc2.constants._Coordinate;
import ucar.nc2.constants.FeatureType;
import ucar.nc2.dt.fmr.FmrcCoordSys;
import ucar.nc2.units.DateFormatter;
import ucar.nc2.util.CancelTask;
import ucar.grib.grib2.Grib2GridTableLookup;
import ucar.grib.grib1.Grib1GridTableLookup;
import ucar.unidata.util.StringUtil;
import ucar.grid.*;
import java.io.*;
import java.util.*;
/**
* Create a Netcdf File from a GridIndex
*
* @author caron
*/
public class GridIndexToNC {
/**
* logger
*/
static private org.slf4j.Logger logger =
org.slf4j.LoggerFactory.getLogger(GridIndexToNC.class);
/**
* map of horizontal coordinate systems
*/
private Map<String,GridHorizCoordSys> hcsHash = new HashMap<String,GridHorizCoordSys>(10); // GridHorizCoordSys
/**
* date formattter
*/
private DateFormatter formatter = new DateFormatter();
/**
* debug flag
*/
private boolean debug = false;
/**
* flag for using GridParameter description for variable names
*/
private boolean useDescriptionForVariableName = true;
/**
* Make the level name
*
* @param gr grid record
* @param lookup lookup table
* @return name for the level
*/
public static String makeLevelName(GridRecord gr, GridTableLookup lookup) {
// for grib2, we need to add the layer to disambiguate
if ( lookup instanceof Grib2GridTableLookup ) {
String vname = lookup.getLevelName(gr);
return lookup.isLayer(gr)
? vname + "_layer"
: vname;
} else {
return lookup.getLevelName(gr); // GEMPAK
}
}
/**
* Get suffix name of variable if it exists
*
* @param gr grid record
* @param lookup lookup table
* @return name of the suffix, ensemble, probability, error, etc
*/
public static String makeSuffixName(GridRecord gr, GridTableLookup lookup) {
if ( ! (lookup instanceof Grib2GridTableLookup) )
return "";
Grib2GridTableLookup g2lookup = (Grib2GridTableLookup) lookup;
return g2lookup.makeSuffix( gr );
}
/**
* Make the variable name
*
* @param gr grid record
* @param lookup lookup table
* @return variable name
*/
public String makeVariableName(GridRecord gr, GridTableLookup lookup) {
GridParameter param = lookup.getParameter(gr);
String levelName = makeLevelName(gr, lookup);
String suffixName = makeSuffixName(gr, lookup);
String paramName = (useDescriptionForVariableName)
? param.getDescription()
: param.getName();
paramName = (suffixName.length() == 0)
? paramName : paramName + "_" + suffixName;
paramName = (levelName.length() == 0)
? paramName : paramName + "_" + levelName;
return paramName;
}
/**
* moved to GridVariable = made sense since it knows what it is
* Make a long name for the variable
*
* @param gr grid record
* @param lookup lookup table
*
* @return long variable name
public static String makeLongName(GridRecord gr, GridTableLookup lookup) {
GridParameter param = lookup.getParameter(gr);
String levelName = makeLevelName(gr, lookup);
return (levelName.length() == 0)
? param.getDescription()
: param.getDescription() + " @ " + makeLevelName(gr, lookup);
}
*/
/**
* Fill in the netCDF file
*
* @param index grid index
* @param lookup lookup table
* @param version version of data
* @param ncfile netCDF file to fill in
* @param fmrcCoordSys forecast model run CS
* @param cancelTask cancel task
* @throws IOException Problem reading from the file
*/
public void open(GridIndex index, GridTableLookup lookup, int version,
NetcdfFile ncfile, FmrcCoordSys fmrcCoordSys,
CancelTask cancelTask)
throws IOException {
// create the HorizCoord Systems : one for each gds
List<GridDefRecord> hcsList = index.getHorizCoordSys();
boolean needGroups = (hcsList.size() > 1);
for (GridDefRecord gds : hcsList) {
Group g = null;
if (needGroups) {
g = new Group(ncfile, null, gds.getGroupName());
ncfile.addGroup(null, g);
}
// (GridDefRecord gdsIndex, String grid_name, String shape_name, Group g)
GridHorizCoordSys hcs = new GridHorizCoordSys(gds, lookup, g);
hcsHash.put(gds.getParam(GridDefRecord.GDS_KEY), hcs);
}
// run through each record
GridRecord firstRecord = null;
List<GridRecord> records = index.getGridRecords();
if (GridServiceProvider.debugOpen) {
System.out.println(" number of products = " + records.size());
}
for (GridRecord gribRecord : records) {
if (firstRecord == null)
firstRecord = gribRecord;
GridHorizCoordSys hcs = hcsHash.get(gribRecord.getGridDefRecordId());
String name = makeVariableName(gribRecord, lookup);
// combo gds, param name and level name
GridVariable pv = (GridVariable) hcs.varHash.get(name);
if (null == pv) {
String pname = lookup.getParameter(gribRecord).getDescription();
pv = new GridVariable(name, pname, hcs, lookup);
hcs.varHash.put(name, pv);
//System.out.printf("Add name=%s pname=%s%n", name, pname);
// keep track of all products with same parameter name
List<GridVariable> plist = hcs.productHash.get(pname);
if (null == plist) {
plist = new ArrayList<GridVariable>();
hcs.productHash.put(pname, plist);
}
plist.add(pv);
}
pv.addProduct(gribRecord);
}
// global CF Conventions
// Conventions attribute change must be in sync with CDM code
ncfile.addAttribute(null, new Attribute("Conventions", "CF-1.4"));
String center = null;
String subcenter = null;
if ( lookup instanceof Grib2GridTableLookup ) {
Grib2GridTableLookup g2lookup = (Grib2GridTableLookup) lookup;
center = g2lookup.getFirstCenterName();
subcenter = g2lookup.getFirstSubcenterName();
ncfile.addAttribute(null, new Attribute("Originating_center", center));
//if (subcenter != null)
// ncfile.addAttribute(null, new Attribute("Originating_subcenter", subcenter));
String genType = g2lookup.getTypeGenProcessName(firstRecord);
if (genType != null)
ncfile.addAttribute(null, new Attribute("Generating_Process_or_Model", genType));
if (null != g2lookup.getFirstProductStatusName())
ncfile.addAttribute(null, new Attribute("Product_Status", g2lookup.getFirstProductStatusName()));
ncfile.addAttribute(null, new Attribute("Product_Type", g2lookup.getFirstProductTypeName()));
} else if ( lookup instanceof Grib1GridTableLookup ) {
Grib1GridTableLookup g1lookup = (Grib1GridTableLookup) lookup;
center = g1lookup.getFirstCenterName();
subcenter = g1lookup.getFirstSubcenterName();
ncfile.addAttribute(null, new Attribute("Originating_center", center));
if (subcenter != null)
ncfile.addAttribute(null, new Attribute("Originating_subcenter", subcenter));
String genType = g1lookup.getTypeGenProcessName(firstRecord);
if (genType != null)
ncfile.addAttribute(null, new Attribute("Generating_Process_or_Model", genType));
if (null != g1lookup.getFirstProductStatusName())
ncfile.addAttribute(null, new Attribute("Product_Status", g1lookup.getFirstProductStatusName()));
ncfile.addAttribute(null, new Attribute("Product_Type", g1lookup.getFirstProductTypeName()));
}
// CF Global attributes
ncfile.addAttribute(null, new Attribute("title", lookup.getTitle() +" at "+
formatter.toDateTimeStringISO(lookup.getFirstBaseTime()) ));
if ( lookup.getInstitution() != null)
ncfile.addAttribute(null, new Attribute("institution", lookup.getInstitution()));
String source = lookup.getSource();
if ( source != null && ! source.startsWith( "Unknown"))
ncfile.addAttribute(null, new Attribute("source", source));
String now = formatter.toDateTimeStringISO( Calendar.getInstance().getTime());
ncfile.addAttribute(null, new Attribute("history", now +" Direct read of "+
lookup.getGridType() +" into NetCDF-Java 4 API"));
if ( lookup.getComment() != null)
ncfile.addAttribute(null, new Attribute("comment", lookup.getComment()));
// dataset discovery
//if ( center != null)
// ncfile.addAttribute(null, new Attribute("center_name", center));
// CDM attributes
ncfile.addAttribute(null, new Attribute("CF:feature_type", FeatureType.GRID.toString()));
ncfile.addAttribute(null, new Attribute("file_format", lookup.getGridType()));
ncfile.addAttribute(null,
new Attribute("location", ncfile.getLocation()));
ncfile.addAttribute(null, new Attribute(_Coordinate.ModelRunDate,
formatter.toDateTimeStringISO(lookup.getFirstBaseTime())));
if (fmrcCoordSys != null) {
makeDefinedCoordSys(ncfile, lookup, fmrcCoordSys);
} else {
makeDenseCoordSys(ncfile, lookup, cancelTask);
}
if (GridServiceProvider.debugMissing) {
int count = 0;
Collection<GridHorizCoordSys> hcset = hcsHash.values();
for (GridHorizCoordSys hcs : hcset) {
List<GridVariable> gribvars = new ArrayList<GridVariable>(hcs.varHash.values());
for (GridVariable gv : gribvars) {
count += gv.dumpMissingSummary();
}
}
System.out.println(" total missing= " + count);
}
if (GridServiceProvider.debugMissingDetails) {
Collection<GridHorizCoordSys> hcset = hcsHash.values();
for (GridHorizCoordSys hcs : hcset) {
System.out.println("******** Horiz Coordinate= " + hcs.getGridName());
String lastVertDesc = null;
List<GridVariable> gribvars = new ArrayList<GridVariable>(hcs.varHash.values());
Collections.sort(gribvars, new CompareGridVariableByVertName());
for (GridVariable gv : gribvars) {
String vertDesc = gv.getVertName();
if (!vertDesc.equals(lastVertDesc)) {
System.out.println("---Vertical Coordinate= " + vertDesc);
lastVertDesc = vertDesc;
}
gv.dumpMissing();
}
}
}
// clean out stuff we dont need anymore
//for (GridHorizCoordSys ghcs : hcsHash.values()) {
// ghcs.empty();
}
// debugging
public GridHorizCoordSys getHorizCoordSys(GridRecord gribRecord) {
return hcsHash.get(gribRecord.getGridDefRecordId());
}
public Map<String,GridHorizCoordSys> getHorizCoordSystems() {
return hcsHash;
}
/**
* Make coordinate system without missing data - means that we
* have to make a coordinate axis for each unique set
* of time or vertical levels.
*
* @param ncfile netCDF file
* @param lookup lookup table
* @param cancelTask cancel task
* @throws IOException problem reading file
*/
private void makeDenseCoordSys(NetcdfFile ncfile, GridTableLookup lookup, CancelTask cancelTask) throws IOException {
List<GridTimeCoord> timeCoords = new ArrayList<GridTimeCoord>();
List<GridVertCoord> vertCoords = new ArrayList<GridVertCoord>();
List<GridEnsembleCoord> ensembleCoords = new ArrayList<GridEnsembleCoord>();
// loop over HorizCoordSys
Collection<GridHorizCoordSys> hcset = hcsHash.values();
for (GridHorizCoordSys hcs : hcset) {
if ((cancelTask != null) && cancelTask.isCancel()) break;
// loop over GridVariables in the HorizCoordSys
// create the time and vertical coordinates
List<GridVariable> gribvars = new ArrayList<GridVariable>(hcs.varHash.values());
for (GridVariable pv : gribvars) {
if ((cancelTask != null) && cancelTask.isCancel()) break;
List<GridRecord> recordList = pv.getRecords();
GridRecord record = recordList.get(0);
String vname = makeLevelName(record, lookup);
// look to see if vertical already exists
GridVertCoord useVertCoord = null;
for (GridVertCoord gvcs : vertCoords) {
if (vname.equals(gvcs.getLevelName())) {
if (gvcs.matchLevels(recordList)) { // must have the same levels
useVertCoord = gvcs;
}
}
}
if (useVertCoord == null) { // nope, got to create it
useVertCoord = new GridVertCoord(recordList, vname, lookup, hcs);
vertCoords.add(useVertCoord);
}
pv.setVertCoord(useVertCoord);
// look to see if time coord already exists
GridTimeCoord useTimeCoord = null;
for (GridTimeCoord gtc : timeCoords) {
if (gtc.matchLevels(recordList)) { // must have the same levels
useTimeCoord = gtc;
}
}
if (useTimeCoord == null) { // nope, got to create it
useTimeCoord = new GridTimeCoord(recordList, lookup);
timeCoords.add(useTimeCoord);
}
pv.setTimeCoord(useTimeCoord);
// check for ensemble members
//System.out.println( pv.getName() +" "+ pv.getParamName() );
GridEnsembleCoord useEnsembleCoord = null;
GridEnsembleCoord ensembleCoord = new GridEnsembleCoord(recordList, lookup);
for (GridEnsembleCoord gec : ensembleCoords) {
if (ensembleCoord.getNEnsembles() == gec.getNEnsembles()) {
useEnsembleCoord = gec;
break;
}
}
if (useEnsembleCoord == null) {
//useEnsembleCoord = new GridEnsembleCoord(recordList, lookup);
useEnsembleCoord = ensembleCoord;
ensembleCoords.add(useEnsembleCoord);
}
// only add ensemble dimensions
if (useEnsembleCoord.getNEnsembles() > 1)
pv.setEnsembleCoord(useEnsembleCoord);
}
//// assign time coordinate names
// find time dimensions with largest length
GridTimeCoord tcs0 = null;
int maxTimes = 0;
for (GridTimeCoord tcs : timeCoords) {
if (tcs.getNTimes() > maxTimes) {
tcs0 = tcs;
maxTimes = tcs.getNTimes();
}
}
// add time dimensions, give time dimensions unique names
int seqno = 1;
for (GridTimeCoord tcs : timeCoords) {
if (tcs != tcs0) {
tcs.setSequence(seqno++);
}
tcs.addDimensionsToNetcdfFile(ncfile, hcs.getGroup());
}
// add Ensemble dimensions, give Ensemble dimensions unique names
seqno = 0;
for (GridEnsembleCoord gec : ensembleCoords) {
gec.setSequence(seqno++);
if (gec.getNEnsembles() > 1)
gec.addDimensionsToNetcdfFile(ncfile, hcs.getGroup());
}
// add x, y dimensions
hcs.addDimensionsToNetcdfFile(ncfile);
// add vertical dimensions, give them unique names
Collections.sort(vertCoords);
int vcIndex = 0;
String listName = null;
int start = 0;
for (vcIndex = 0; vcIndex < vertCoords.size(); vcIndex++) {
GridVertCoord gvcs = (GridVertCoord) vertCoords.get(vcIndex);
String vname = gvcs.getLevelName();
if (listName == null) {
listName = vname; // initial
}
if (!vname.equals(listName)) {
makeVerticalDimensions(vertCoords.subList(start, vcIndex), ncfile, hcs.getGroup());
listName = vname;
start = vcIndex;
}
}
makeVerticalDimensions(vertCoords.subList(start, vcIndex), ncfile, hcs.getGroup());
// create a variable for each entry, but check for other products with same desc
// to disambiguate by vertical coord
List<List<GridVariable>> products = new ArrayList<List<GridVariable>>(hcs.productHash.values());
Collections.sort( products, new CompareGridVariableListByName());
for (List<GridVariable> plist : products) {
if ((cancelTask != null) && cancelTask.isCancel()) break;
if (plist.size() == 1) {
GridVariable pv = plist.get(0);
Variable v;
if ( (lookup instanceof GempakLookup) || (lookup instanceof McIDASLookup )) {
v = pv.makeVariable(ncfile, hcs.getGroup(), false );
} else {
v = pv.makeVariable(ncfile, hcs.getGroup(), true);
}
ncfile.addVariable(hcs.getGroup(), v);
} else {
Collections.sort(plist, new CompareGridVariableByNumberVertLevels());
boolean isGrib2 = false;
Grib2GridTableLookup g2lookup = null;
if ( (lookup instanceof Grib2GridTableLookup) ) {
g2lookup = (Grib2GridTableLookup) lookup;
isGrib2 = true;
}
// finally, add the variables
for (int k = 0; k < plist.size(); k++) {
GridVariable pv = plist.get(k);
if (isGrib2 && ( g2lookup.isEnsemble( pv.getFirstRecord()) ||
g2lookup.isProbability( pv.getFirstRecord() ) ) ||
(lookup instanceof GempakLookup) || (lookup instanceof McIDASLookup ) ) {
ncfile.addVariable(hcs.getGroup(), pv.makeVariable(ncfile, hcs.getGroup(), false));
} else {
ncfile.addVariable(hcs.getGroup(), pv.makeVariable(ncfile, hcs.getGroup(), (k == 0)));
}
}
} // multipe vertical levels
} // create variable
// add coordinate variables at the end
for (GridTimeCoord tcs : timeCoords) {
tcs.addToNetcdfFile(ncfile, hcs.getGroup());
}
for (GridEnsembleCoord gec : ensembleCoords) {
if (gec.getNEnsembles() > 1)
gec.addToNetcdfFile(ncfile, hcs.getGroup());
}
hcs.addToNetcdfFile(ncfile);
for (GridVertCoord gvcs : vertCoords) {
gvcs.addToNetcdfFile(ncfile, hcs.getGroup());
}
} // loop over hcs
// TODO: check this, in ToolsUI it caused problems
//for (GridVertCoord gvcs : vertCoords) {
// gvcs.empty();
}
/**
* Make a vertical dimensions
*
* @param vertCoordList vertCoords all with the same name
* @param ncfile netCDF file to add to
* @param group group in ncfile
*/
private void makeVerticalDimensions(List<GridVertCoord> vertCoordList, NetcdfFile ncfile, Group group) {
// find biggest vert coord
GridVertCoord gvcs0 = null;
int maxLevels = 0;
for (GridVertCoord gvcs : vertCoordList) {
if (gvcs.getNLevels() > maxLevels) {
gvcs0 = gvcs;
maxLevels = gvcs.getNLevels();
}
}
int seqno = 1;
for (GridVertCoord gvcs : vertCoordList) {
if (gvcs != gvcs0) {
gvcs.setSequence(seqno++);
}
gvcs.addDimensionsToNetcdfFile(ncfile, group);
}
}
/**
* Make coordinate system from a Definition object
*
* @param ncfile netCDF file to add to
* @param lookup lookup table
* @param fmr FmrcCoordSys
* @throws IOException problem reading from file
*/
private void makeDefinedCoordSys(NetcdfFile ncfile,
GridTableLookup lookup, FmrcCoordSys fmr) throws IOException {
List<GridTimeCoord> timeCoords = new ArrayList<GridTimeCoord>();
List<GridVertCoord> vertCoords = new ArrayList<GridVertCoord>();
List<GridEnsembleCoord> ensembleCoords = new ArrayList<GridEnsembleCoord>();
List<String> removeVariables = new ArrayList<String>();
// loop over HorizCoordSys
Collection<GridHorizCoordSys> hcset = hcsHash.values();
for (GridHorizCoordSys hcs : hcset) {
// loop over GridVariables in the HorizCoordSys
// create the time and vertical coordinates
Set<String> keys = hcs.varHash.keySet();
for (String key : keys) {
GridVariable pv = hcs.varHash.get(key);
GridRecord record = pv.getFirstRecord();
// we dont know the name for sure yet, so have to try several
String searchName = findVariableName(ncfile, record, lookup, fmr);
if (searchName == null) { // cant find - just remove
removeVariables.add(key); // cant remove (concurrentModException) so save for later
continue;
}
pv.setVarName( searchName);
// get the vertical coordinate for this variable, if it exists
FmrcCoordSys.VertCoord vc_def = fmr.findVertCoordForVariable( searchName);
if (vc_def != null) {
String vc_name = vc_def.getName();
// look to see if GridVertCoord already made
GridVertCoord useVertCoord = null;
for (GridVertCoord gvcs : vertCoords) {
if (vc_name.equals(gvcs.getLevelName()))
useVertCoord = gvcs;
}
if (useVertCoord == null) { // nope, got to create it
useVertCoord = new GridVertCoord(record, vc_name, lookup, vc_def.getValues1(), vc_def.getValues2());
useVertCoord.addDimensionsToNetcdfFile( ncfile, hcs.getGroup());
vertCoords.add( useVertCoord);
}
pv.setVertCoord( useVertCoord);
} else {
pv.setVertCoord( new GridVertCoord(searchName)); // fake
}
// get the time coordinate for this variable
FmrcCoordSys.TimeCoord tc_def = fmr.findTimeCoordForVariable( searchName, lookup.getFirstBaseTime());
String tc_name = tc_def.getName();
// look to see if GridTimeCoord already made
GridTimeCoord useTimeCoord = null;
for (GridTimeCoord gtc : timeCoords) {
if (tc_name.equals(gtc.getName()))
useTimeCoord = gtc;
}
if (useTimeCoord == null) { // nope, got to create it
useTimeCoord = new GridTimeCoord(tc_name, tc_def.getOffsetHours(), lookup);
useTimeCoord.addDimensionsToNetcdfFile( ncfile, hcs.getGroup());
timeCoords.add( useTimeCoord);
}
pv.setTimeCoord( useTimeCoord);
// check for ensemble members
//System.out.println( pv.getName() +" "+ pv.getParamName() );
GridEnsembleCoord useEnsembleCoord = null;
GridEnsembleCoord ensembleCoord = new GridEnsembleCoord(record, lookup);
for (GridEnsembleCoord gec : ensembleCoords) {
if (ensembleCoord.getNEnsembles() == gec.getNEnsembles()) {
useEnsembleCoord = gec;
break;
}
}
if (useEnsembleCoord == null) {
useEnsembleCoord = ensembleCoord;
ensembleCoords.add(useEnsembleCoord);
}
// only add ensemble dimensions
if (useEnsembleCoord.getNEnsembles() > 1)
pv.setEnsembleCoord(useEnsembleCoord);
}
// any need to be removed?
for (String key : removeVariables) {
hcs.varHash.remove(key);
}
// add x, y dimensions
hcs.addDimensionsToNetcdfFile( ncfile);
// create a variable for each entry
Collection<GridVariable> vars = hcs.varHash.values();
for (GridVariable pv : vars) {
Group g = hcs.getGroup() == null ? ncfile.getRootGroup() : hcs.getGroup();
Variable v = pv.makeVariable(ncfile, g, true);
if (g.findVariable( v.getShortName()) != null) { // already got. can happen when a new vert level is added
logger.warn("GribGridServiceProvider.GridIndexToNC: FmrcCoordSys has 2 variables mapped to ="+v.getShortName()+
" for file "+ncfile.getLocation());
} else
g.addVariable( v);
}
// add coordinate variables at the end
for (GridTimeCoord tcs : timeCoords) {
tcs.addToNetcdfFile(ncfile, hcs.getGroup());
}
for (GridEnsembleCoord gec : ensembleCoords) {
if (gec.getNEnsembles() > 1)
gec.addToNetcdfFile(ncfile, hcs.getGroup());
}
hcs.addToNetcdfFile( ncfile);
for (GridVertCoord gvcs : vertCoords) {
gvcs.addToNetcdfFile(ncfile, hcs.getGroup());
}
} // loop over hcs
if (debug) System.out.println("GridIndexToNC.makeDefinedCoordSys for "+ncfile.getLocation());
}
/**
* Find the variable name for the grid
*
* @param ncfile netCDF file
* @param gr grid record
* @param lookup lookup table
* @param fmr FmrcCoordSys
* @return name for the grid
*
private String findVariableName(NetcdfFile ncfile, GridRecord gr, GridTableLookup lookup, FmrcCoordSys fmr) {
// first lookup with name & vert name
String name = AbstractIOServiceProvider.createValidNetcdfObjectName(makeVariableName(gr, lookup));
if (fmr.hasVariable(name)) {
return name;
}
// now try just the name
String pname = AbstractIOServiceProvider.createValidNetcdfObjectName( lookup.getParameter(gr).getDescription());
if (fmr.hasVariable(pname)) {
return pname;
}
logger.warn( "GridIndexToNC: FmrcCoordSys does not have the variable named ="
+ name + " or " + pname + " for file " + ncfile.getLocation());
return null;
} */
private String findVariableName(NetcdfFile ncfile, GridRecord gr, GridTableLookup lookup, FmrcCoordSys fmr) {
// first lookup with name & vert name
String name = makeVariableName(gr, lookup);
if (debug)
System.out.println( "name ="+ name );
if (fmr.hasVariable( name))
return name;
// now try just the name
String pname = lookup.getParameter(gr).getDescription();
if (debug)
System.out.println( "pname ="+ pname );
if (fmr.hasVariable( pname))
return pname;
// try replacing the blanks
String nameWunder = StringUtil.replace(name, ' ', "_");
if (debug)
System.out.println( "nameWunder ="+ nameWunder );
if (fmr.hasVariable( nameWunder))
return nameWunder;
String pnameWunder = StringUtil.replace(pname, ' ', "_");
if (debug)
System.out.println( "pnameWunder ="+ pnameWunder );
if (fmr.hasVariable( pnameWunder))
return pnameWunder;
logger.warn("GridServiceProvider.GridIndexToNC: FmrcCoordSys does not have the variable named ="+name+" or "+pname+" or "+
nameWunder+" or "+pnameWunder+" for file "+ncfile.getLocation());
return null;
}
/**
* Comparable object for grid variable
*
* @author IDV Development Team
* @version $Revision: 1.3 $
*/
private class CompareGridVariableListByName implements Comparator {
/**
* Compare the two lists of names
*
* @param o1 first list
* @param o2 second list
* @return comparison
*/
public int compare(Object o1, Object o2) {
ArrayList list1 = (ArrayList) o1;
ArrayList list2 = (ArrayList) o2;
GridVariable gv1 = (GridVariable) list1.get(0);
GridVariable gv2 = (GridVariable) list2.get(0);
return gv1.getName().compareToIgnoreCase(gv2.getName());
}
}
/**
* Comparator for grids by vertical variable name
*
* @author IDV Development Team
* @version $Revision: 1.3 $
*/
private class CompareGridVariableByVertName implements Comparator {
/**
* Compare the two lists of names
*
* @param o1 first list
* @param o2 second list
* @return comparison
*/
public int compare(Object o1, Object o2) {
GridVariable gv1 = (GridVariable) o1;
GridVariable gv2 = (GridVariable) o2;
return gv1.getVertName().compareToIgnoreCase(gv2.getVertName());
}
}
/**
* Comparator for grid variables by number of vertical levels
*
* @author IDV Development Team
* @version $Revision: 1.3 $
*/
private class CompareGridVariableByNumberVertLevels implements Comparator {
/**
* Compare the two lists of names
*
* @param o1 first list
* @param o2 second list
* @return comparison
*/
public int compare(Object o1, Object o2) {
GridVariable gv1 = (GridVariable) o1;
GridVariable gv2 = (GridVariable) o2;
int n1 = gv1.getVertCoord().getNLevels();
int n2 = gv2.getVertCoord().getNLevels();
if (n1 == n2) { // break ties for consistency
return gv1.getVertCoord().getLevelName().compareTo(
gv2.getVertCoord().getLevelName());
} else {
return n2 - n1; // highest number first
}
}
}
/**
* Should use the description for the variable name.
*
* @param value false to use name instead of description
*/
public void setUseDescriptionForVariableName(boolean value) {
useDescriptionForVariableName = value;
}
}
|
package camelinaction;
import java.io.File;
import javax.inject.Inject;
import org.apache.camel.CamelContext;
import org.apache.camel.Exchange;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.cdi.Uri;
import org.apache.camel.test.cdi.CamelCdiRunner;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.apache.camel.test.junit4.TestSupport.deleteDirectory;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* Our first unit test with the Camel Test Kit.
* We test the Hello World example of integration kits, which is moving a file.
*/
@RunWith(CamelCdiRunner.class)
public class FirstTest {
@Inject
private CamelContext context;
@Inject @Uri("file:target/inbox")
private ProducerTemplate template;
@Before
public void setUp() throws Exception {
// delete directories so we have a clean start
deleteDirectory("target/inbox");
deleteDirectory("target/outbox");
}
@Test
public void testMoveFile() throws Exception {
// create a new file in the inbox folder with the name hello.txt and containing Hello World as body
template.sendBodyAndHeader("Hello World", Exchange.FILE_NAME, "hello.txt");
// wait a while to let the file be moved
Thread.sleep(2000);
// test the file was moved
File target = new File("target/outbox/hello.txt");
assertTrue("File should have been moved", target.exists());
// test that its content is correct as well
String content = context.getTypeConverter().convertTo(String.class, target);
assertEquals("Hello World", content);
}
}
|
package ru.job4j.condition;
/**
* Point.
* @author Aleksandr Shigin
* @version $Id$
* @since 0.1
*/
public class Point {
/**
* Coordinate x.
*/
private int x;
/**
* Coordinate y.
*/
private int y;
/**
* Constructor.
* @param x - x coordinate
* @param y - y coordinate
*/
public Point(int x, int y) {
this.x = x;
this.y = y;
}
/**
* getX.
* @return x
*/
public int getX() {
return this.x;
}
/**
* getY.
* @return y
*/
public int getY() {
return this.y;
}
/**
* Function y(x) = a * x + b.
* @param a - first value
* @param b - second value
* @return true or false
*/
public boolean is(int a, int b) {
return this.y == this.x * a + b;
}
}
|
package ru.osetsky;
public class Paint{
public String piramid (int h) {
StringBuilder builder = new StringBuilder();
for(int i = 0; i < h; i++) {
for(int i2 = 0; i2 < i; i2++) {
builder.append(" ");
}
for(int i2 = 0; i2 <= i; i2++) {
builder.append("^");
if(i2 > 0) {
builder.append(" ");
}
}
}
return builder.toString();
}
}
|
package ru.job4j.loop;
/**
* Paint.
*
* @author Alex Proshak (olexandr_proshak@ukr.net)
* @version $Id$
* @since 0.1
*/
public class Paint {
/**
* Paint of the piramid.
* @param h - height.
* @return returning string of piramid.
*/
public String piramid(int h) {
char c = 94;
int width = h - 1 + h;
StringBuilder str = new StringBuilder();
StringBuilder st = new StringBuilder();
//initialisation of builder.
for (int i = 0; i < width; i++) {
st.append(" ");
}
if (h == 1) {
str.append(c);
} else {
for (int i = h; i > 1; i
for (int j = 0; j <= i; j++) {
st.setCharAt(i, c);
st.setCharAt(i + j, c);
st.setCharAt(i - j, c);
str.append(st);
str.append("\n");
//easy code duplication.
for (int l = 0; l < width; l++) {
st.append(" ");
}
}
}
}
return str.toString();
}
}
|
package okapi.service;
import okapi.bean.ModuleDescriptor;
import okapi.bean.ModuleInstance;
import okapi.bean.Modules;
import okapi.bean.Ports;
import okapi.bean.ProcessModuleHandle;
import okapi.bean.Tenant;
import io.vertx.core.Vertx;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.http.HttpClient;
import io.vertx.core.http.HttpClientRequest;
import io.vertx.core.json.DecodeException;
import io.vertx.core.json.Json;
import io.vertx.core.streams.ReadStream;
import io.vertx.ext.web.RoutingContext;
import java.util.ArrayList;
import java.util.List;
import java.util.Iterator;
public class ModuleService {
private Modules modules;
private Ports ports;
private HttpClient httpClient;
private TenantService tenantService;
final private Vertx vertx;
public ModuleService(Vertx vertx, int port_start, int port_end, TenantService ts) {
this.vertx = vertx;
this.ports = new Ports(port_start, port_end);
this.modules = new Modules();
this.tenantService = ts;
this.httpClient = vertx.createHttpClient();
}
public void create(RoutingContext ctx) {
try {
final ModuleDescriptor md = Json.decodeValue(ctx.getBodyAsString(),
ModuleDescriptor.class);
final String name = md.getName();
ModuleInstance m = modules.get(name);
if (m != null) {
ctx.response().setStatusCode(400).end("module " + name
+ " already deployed");
return;
}
final String uri = ctx.request().uri() + "/" + name;
final int use_port = ports.get();
if (use_port == -1) {
ctx.response().setStatusCode(400).end("module " + name
+ " can not be deployed: all ports in use");
}
// enable it now so that activation for 2nd one will fail
ProcessModuleHandle pmh = new ProcessModuleHandle(vertx, md.getDescriptor(),
use_port);
modules.put(name, new ModuleInstance(md, pmh, use_port));
pmh.start(future -> {
if (future.succeeded()) {
ctx.response().setStatusCode(201).putHeader("Location", uri).end();
} else {
modules.remove(md.getName());
ports.free(use_port);
ctx.response().setStatusCode(500).end(future.cause().getMessage());
}
});
} catch (DecodeException ex) {
ctx.response().setStatusCode(400).end(ex.getMessage());
}
}
public void get(RoutingContext ctx) {
final String id = ctx.request().getParam("id");
ModuleInstance m = modules.get(id);
if (m == null) {
ctx.response().setStatusCode(404).end();
return;
}
String s = Json.encodePrettily(modules.get(id).getModuleDescriptor());
ctx.response().end(s);
}
public void list(RoutingContext ctx) {
String s = Json.encodePrettily(modules.list());
ctx.response().end(s);
}
public void delete(RoutingContext ctx) {
final String id = ctx.request().getParam("id");
ModuleInstance m = modules.get(id);
if (id == null) {
ctx.response().setStatusCode(404).end();
return;
}
ProcessModuleHandle pmh = m.getProcessModuleHandle();
pmh.stop(future -> {
if (future.succeeded()) {
modules.remove(id);
ports.free(pmh.getPort());
ctx.response().setStatusCode(204).end();
} else {
ctx.response().setStatusCode(500).end(future.cause().getMessage());
}
});
}
/**
* Add the trace headers to the response
*/
private void addTraceHeaders(RoutingContext ctx, List<String> traceHeaders) {
for ( String th : traceHeaders ) {
ctx.response().headers().add("X-Okapi-Trace", th);
}
}
private void makeTraceHeader(RoutingContext ctx, ModuleInstance mi, int statusCode, long startTime, List<String> traceHeaders) {
long timeDiff = (System.nanoTime() - startTime) / 1000;
traceHeaders.add(ctx.request().method() + " "
+ mi.getModuleDescriptor().getName() + ":"
+ statusCode+ " " + timeDiff + "us");
addTraceHeaders(ctx, traceHeaders);
}
public void proxy(RoutingContext ctx) {
String tenant_id = ctx.request().getHeader("X-Okapi-Tenant");
if (tenant_id == null) {
ctx.response().setStatusCode(403).end("Missing Tenant");
return;
}
Tenant tenant = tenantService.get(tenant_id);
if (tenant == null) {
ctx.response().setStatusCode(400).end("No such Tenant " + tenant_id);
return;
}
Iterator<ModuleInstance> it = modules.getModulesForRequest(ctx.request(), tenant);
List<String> traceHeaders = new ArrayList<>();
ReadStream<Buffer> content = ctx.request();
content.pause();
proxyR(ctx, it, traceHeaders, content, null);
}
private void proxyRequestHttpClient(RoutingContext ctx,
Iterator<ModuleInstance> it,
List<String> traceHeaders, Buffer bcontent,
ModuleInstance mi, long startTime)
{
HttpClientRequest c_req = httpClient.request(ctx.request().method(), mi.getPort(),
"localhost", ctx.request().uri(), res -> {
if (res.statusCode() < 200 || res.statusCode() >= 300) {
ctx.response().setChunked(true);
ctx.response().setStatusCode(res.statusCode());
ctx.response().headers().setAll(res.headers());
makeTraceHeader(ctx, mi, res.statusCode(), startTime, traceHeaders);
res.handler(data -> {
ctx.response().write(data);
});
res.endHandler(x -> {
ctx.response().end();
});
res.exceptionHandler(x -> {
System.out.println("res exception " + x.getMessage());
});
} else if (it.hasNext()) {
makeTraceHeader(ctx, mi, res.statusCode(), startTime, traceHeaders);
proxyR(ctx, it, traceHeaders, null, bcontent);
} else {
ctx.response().setChunked(true);
ctx.response().setStatusCode(res.statusCode());
ctx.response().headers().setAll(res.headers());
makeTraceHeader(ctx, mi, res.statusCode(), startTime, traceHeaders);
res.endHandler(x -> {
ctx.response().end(bcontent);
});
res.exceptionHandler(x -> {
System.out.println("res exception " + x.getMessage());
});
}
});
c_req.exceptionHandler(res -> {
ctx.response().setStatusCode(500).end("connect port "
+ mi.getPort() + ": " + res.getMessage());
});
c_req.setChunked(true);
c_req.headers().setAll(ctx.request().headers());
c_req.end(bcontent);
}
private void proxyRequestOnly(RoutingContext ctx,
Iterator<ModuleInstance> it, List<String> traceHeaders,
ReadStream<Buffer> content, Buffer bcontent, ModuleInstance mi, long startTime)
{
if (bcontent != null) {
proxyRequestHttpClient(ctx, it, traceHeaders, bcontent, mi, startTime);
} else {
final Buffer incoming = Buffer.buffer();
content.handler(data -> {
incoming.appendBuffer(data);
});
content.endHandler(v -> {
proxyRequestHttpClient(ctx, it, traceHeaders, incoming, mi, startTime);
});
content.resume();
}
}
private void proxyRequestResponse(RoutingContext ctx,
Iterator<ModuleInstance> it, List<String> traceHeaders,
ReadStream<Buffer> content, Buffer bcontent, ModuleInstance mi, long startTime)
{
HttpClientRequest c_req = httpClient.request(ctx.request().method(), mi.getPort(),
"localhost", ctx.request().uri(), res -> {
if (res.statusCode() >= 200 && res.statusCode() < 300
&& it.hasNext()) {
makeTraceHeader(ctx, mi, res.statusCode(), startTime, traceHeaders);
res.pause();
proxyR(ctx, it, traceHeaders, res, null);
} else {
ctx.response().setChunked(true);
ctx.response().setStatusCode(res.statusCode());
ctx.response().headers().setAll(res.headers());
makeTraceHeader(ctx, mi, res.statusCode(), startTime, traceHeaders);
res.handler(data -> {
ctx.response().write(data);
});
res.endHandler(v -> {
ctx.response().end();
});
res.exceptionHandler(v -> {
System.out.println("res exception " + v.getMessage());
});
}
});
c_req.exceptionHandler(res -> {
ctx.response().setStatusCode(500).end("connect port "
+ mi.getPort() + ": " + res.getMessage());
});
c_req.setChunked(true);
c_req.headers().setAll(ctx.request().headers());
if (bcontent != null) {
c_req.end(bcontent);
} else {
content.handler(data -> {
c_req.write(data);
});
content.endHandler(v -> {
c_req.end();
});
content.exceptionHandler(v -> {
System.out.println("content exception " + v.getMessage());
});
content.resume();
}
}
private void proxyHeaders(RoutingContext ctx,
Iterator<ModuleInstance> it, List<String> traceHeaders,
ReadStream<Buffer> content, Buffer bcontent, ModuleInstance mi, long startTime) {
HttpClientRequest c_req = httpClient.request(ctx.request().method(), mi.getPort(),
"localhost", ctx.request().uri(), res -> {
if (res.statusCode() < 200 || res.statusCode() >= 300) {
ctx.response().setChunked(true);
ctx.response().setStatusCode(res.statusCode());
ctx.response().headers().setAll(res.headers());
makeTraceHeader(ctx, mi, res.statusCode(), startTime, traceHeaders);
res.handler(data -> {
ctx.response().write(data);
});
res.endHandler(v -> {
ctx.response().end();
});
res.exceptionHandler(v -> {
System.out.println("res exception " + v.getMessage());
});
} else if (it.hasNext()) {
res.endHandler(x -> {
proxyR(ctx, it, traceHeaders, content, bcontent);
});
} else {
ctx.response().setChunked(true);
ctx.response().setStatusCode(res.statusCode());
ctx.response().headers().setAll(res.headers());
makeTraceHeader(ctx, mi, res.statusCode(), startTime, traceHeaders);
if (bcontent == null) {
content.handler(data -> {
ctx.response().write(data);
});
content.endHandler(v -> {
ctx.response().end();
});
content.exceptionHandler(v -> {
System.out.println("content exception " + v.getMessage());
});
content.resume();
} else {
ctx.response().end(bcontent);
}
}
});
c_req.exceptionHandler(res -> {
ctx.response().setStatusCode(500).end("connect port "
+ mi.getPort() + ": " + res.getMessage());
});
// c_req.setChunked(true);
// c_req.headers().setAll(ctx.request().headers());
c_req.end();
}
private void proxyR(RoutingContext ctx,
Iterator<ModuleInstance> it, List<String> traceHeaders,
ReadStream<Buffer> content, Buffer bcontent) {
if (!it.hasNext()) {
addTraceHeaders(ctx, traceHeaders);
ctx.response().setStatusCode(404).end();
} else {
ModuleInstance mi = it.next();
final long startTime = System.nanoTime();
String rtype = mi.getRoutingEntry().getType();
if ("request-only".equals(rtype)) {
proxyRequestOnly(ctx, it, traceHeaders, content, bcontent, mi, startTime);
} else if ("request-response".equals(rtype)) {
proxyRequestResponse(ctx, it, traceHeaders, content, bcontent, mi, startTime);
} else if ("headers".equals(rtype)) {
proxyHeaders(ctx, it, traceHeaders, content, bcontent, mi, startTime);
} else {
System.out.println("rtype = " + rtype);
}
}
}
} // class
|
package ru.job4j.model;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Random;
/**It's a base class-task for accounting system.
*@author gimazetdinov
*@since 31.01.2017
*@version 1.0
*/
public class Item {
/**Name of the item.*/
private String name;
/**Description of the item.*/
private String description;
/**Date and time when item was created.*/
private Calendar create;
/**Max size of the comments list.*/
private final int maxSizeOfCommentsList = 30;
/**Array of comments.*/
private Comment[] comments = new Comment[maxSizeOfCommentsList];
private String id;
/**An amount of elements in the array of comments. */
private int commentCounter = 0;
/**A number for generate the next pseudorandom number.*/
private final int numberForRand = 25;
/**Name setter.
*@param name name
*/
public void setName(String name) {
this.name = name;
}
/**Description setter.
*@param desc description
*/
public void setDescription(String desc) {
this.description = desc;
}
/**Date and time setter.
*@param millis - time in milliseconds*/
public void setCreate(long millis) {
this.create = new GregorianCalendar();
this.create.setTimeInMillis(millis);
}
/**Add a comment to item.
*@param comment - text of the comment
*@param author - author's name
*@param millis - current time in milliseconds
*/
public void addComment(String comment, String author, long millis) {
if (this.commentCounter < this.comments.length) {
this.comments[commentCounter] = new Comment();
this.comments[commentCounter].setAuthor(author);
this.comments[commentCounter].setText(comment);
this.comments[commentCounter].setCreate(millis);
this.commentCounter++;
}
}
/**Generates unique id for item.*/
public void generateId() {
Random ran = new Random();
this.id = String.valueOf(ran.nextInt());
}
/**Name getter.
*@return name of the item*/
public String getName() {
return this.name;
}
/**Description getter.
*@return description of the item*/
public String getDescription() {
return this.description;
}
/**Date and time getter.
*@return date and time, when the item was created*/
public String getCreate() {
return new StringBuilder()
.append(this.create.get(Calendar.HOUR_OF_DAY))
.append(":")
.append(this.create.get(Calendar.MINUTE))
.append(" ")
.append(this.create.get(Calendar.DAY_OF_MONTH))
.append("/")
.append(this.create.get(Calendar.MONTH) + 1)
.append("/")
.append(this.create.get(Calendar.YEAR))
.toString();
}
/**Comments getter.
*@return comments - array of item's comments*/
public Comment[] getComments() {
return this.comments;
}
/**ID getter.
*@return id*/
public String getId() {
return this.id;
}
}
|
package cn.ymex.cute.kits;
public class Null {
/**
* NullPointerException
*
* @param notice
* @param t
* @param <T>
* @return
*/
public static <T> T checkNull(T t, String notice) {
if (null == t) {
if (notice == null) {
throw new NullPointerException();
}
throw new NullPointerException(notice);
}
return t;
}
/**
* NullPointerException
*
* @param t
* @param <T>
* @return
*/
public static <T> T checkNull(T t) {
return checkNull(t, null);
}
/**
*
*
* @param t
* @param <T>
* @return
*/
public static <T> boolean isNull(T t) {
if (null == t) {
return true;
}
return false;
}
/**
*
* @param value
* @param <T>
* @return
*/
public static <T> T get(final T value) {
return checkNull(value,null);
}
/**
*
* @param value
* @param defValue
* @param <T>
* @return
*/
public static <T> T or(final T value, T defValue) {
if (isNull(value)) {
return defValue;
}
return value;
}
}
|
package edu.utexas.cycic;
import java.util.Optional;
import edu.utah.sci.cyclist.core.controller.CyclistController;
import edu.utexas.cycic.tools.FormBuilderTool;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.control.Alert;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuItem;
import javafx.scene.control.TextInputDialog;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
import javafx.scene.paint.Color;
import javafx.scene.shape.Line;
import javafx.scene.shape.Shape;
import javafx.scene.text.Font;
import javafx.scene.text.TextAlignment;
import javafx.stage.Window;
/**
* The class used to build a new Prototype Facility node.
* @author Robert
*
*/
public class CycicCircles{
protected static double mousey;
protected static double mousex;
protected static double x;
protected static double y;
protected static int defRadius = 45;
protected static int mouseOverRadius = 52;
static Window window;
/**
* Function to build a prototype facility node. This node will contain
* the facilities available to institutions and regions. All children
* built from this node will mimic its structure.
* @param name Name of the new prototype facility.
*/
static FacilityCircle addNode(String name, final facilityNode parent) {
final FacilityCircle circle = parent.cycicCircle;
circle.setRadius(defRadius);
circle.setCenterX(60);
circle.setCenterY(60);
circle.type = "Parent";
circle.childrenShow = true;
//Setting up the name and naming structure of the circle.
circle.text.setText(name);
circle.tooltip.setText(name);
circle.text.setTooltip(circle.tooltip);
// Setting the circle color //
circle.setStroke(Color.BLACK);
circle.rgbColor=VisFunctions.stringToColor(parent.facilityType);
circle.setFill(Color.rgb(circle.rgbColor.get(0), circle.rgbColor.get(1), circle.rgbColor.get(2), 0.9));
// Place text after color to get font color right //
VisFunctions.placeTextOnCircle(circle, "bottom");
for(int i = 0; i < Cycic.pane.getChildren().size(); i++){
if(Cycic.pane.getChildren().get(i).getId() == "cycicNode"){
((Shape) Cycic.pane.getChildren().get(i)).setStroke(Color.BLACK);
((Shape) Cycic.pane.getChildren().get(i)).setStrokeWidth(1);
}
}
circle.setEffect(VisFunctions.lighting);
circle.setStrokeWidth(5);
circle.setStroke(Color.DARKGRAY);
// Adding the menu and it's menu items.
final Menu menu1 = new Menu("Options");
MenuItem facForm = new MenuItem("Facility Form");
EventHandler<ActionEvent> circleAction = new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
try{
CyclistController._presenter.addTool(new FormBuilderTool());
circle.menu.setVisible(false);
} catch (Exception e) {
e.printStackTrace();
}
}
};
facForm.setOnAction(circleAction);
circle.image.setLayoutX(circle.getCenterX()-60);
circle.image.setLayoutY(circle.getCenterY()-60);
MenuItem delete = new MenuItem("Delete");
delete.setOnAction(new EventHandler<ActionEvent>(){
public void handle(ActionEvent e){
deleteNode(parent);
circle.menu.setVisible(false);
}
});
MenuItem changeNiche = new MenuItem("Change Niche");
changeNiche.setOnAction(new EventHandler<ActionEvent>(){
public void handle(ActionEvent e){
/** TODO CHANGE NICHE OF CIRCLE */
TextInputDialog dg = new TextInputDialog("Test");
dg.setContentText("ADSFA");
Optional<String> result = dg.showAndWait();
if (result.isPresent()){
System.out.println("test");
}
circle.menu.setVisible(false);
}
});
MenuItem showImage = new MenuItem("Show Image");
showImage.setOnAction(new EventHandler<ActionEvent>(){
public void handle(ActionEvent e){
circle.image.setVisible(true);
circle.image.toBack();
circle.setOpacity(0);
circle.menu.setVisible(false);
}
});
MenuItem hideImage = new MenuItem("Hide Image");
hideImage.setOnAction(new EventHandler<ActionEvent>(){
public void handle(ActionEvent e){
circle.image.setVisible(false);
circle.setOpacity(100);
circle.menu.setVisible(false); }
});
menu1.getItems().addAll(facForm, changeNiche, delete, showImage, hideImage);
circle.menu.getMenus().add(menu1);
circle.menu.setLayoutX(circle.getCenterX());
circle.menu.setLayoutY(circle.getCenterY());
circle.menu.setVisible(false);
// Piece of test code for changing the look of the facility circles.
//circle.image.setImage(new Image("reactor.png"));
circle.image.setLayoutX(circle.getCenterX()-60);
circle.image.setLayoutY(circle.getCenterY()-60);
circle.image.setMouseTransparent(true);
circle.image.setVisible(false);
// Mouse pressed to add in movement of the facilityCircle.
circle.onMousePressedProperty().set(new EventHandler<MouseEvent>(){
@Override
public void handle(MouseEvent event){
Cycic.workingNode = parent;
circle.childrenDeltaX.clear();
circle.childrenDeltaY.clear();
for(int i = 0; i < circle.childrenList.size(); i++){
circle.childrenDeltaX.add(circle.getCenterX() - circle.childrenList.get(i).getCenterX());
circle.childrenDeltaY.add(circle.getCenterY() - circle.childrenList.get(i).getCenterY());
}
x = circle.getCenterX() - event.getX();
y = circle.getCenterY() - event.getY();
mousex = event.getX();
mousey = event.getY();
}
});
// To allow the facilityCircle to be moved through the pane and setting bounding regions.
circle.onMouseDraggedProperty().set(new EventHandler<MouseEvent>(){
public void handle(MouseEvent event){
Line line = new Line();
if(event.isShiftDown() == true){
Cycic.pane.getChildren().add(line);
line.setEndX(event.getX());
line.setEndY(event.getY());
line.setStartX(circle.getCenterX());
line.setStartY(circle.getCenterY());
} else {
circle.setCenterX(mousex+x);
circle.setCenterY(mousey+y);
if(circle.getCenterX() <= Cycic.pane.getLayoutBounds().getMinX()+circle.getRadius()){
circle.setCenterX(Cycic.pane.getLayoutBounds().getMinX()+circle.getRadius());
}
if(circle.getCenterY() <= Cycic.pane.getLayoutBounds().getMinY()+circle.getRadius()){
circle.setCenterY(Cycic.pane.getLayoutBounds().getMinY()+circle.getRadius());
}
if(circle.getCenterY() >= Cycic.pane.getLayoutBounds().getMaxY()-circle.getRadius()){
circle.setCenterY(Cycic.pane.getLayoutBounds().getMaxY()-circle.getRadius());
}
if(circle.getCenterX() >= Cycic.pane.getLayoutBounds().getMaxX()-circle.getRadius()){
circle.setCenterX(Cycic.pane.getLayoutBounds().getMaxX()-circle.getRadius());
}
circle.menu.setLayoutX(circle.getCenterX());
circle.menu.setLayoutY(circle.getCenterY());
circle.image.setLayoutX(circle.getCenterX()-60);
circle.image.setLayoutY(circle.getCenterY()-50);
VisFunctions.placeTextOnCircle(circle, "bottom");
for(int i = 0; i < CycicScenarios.workingCycicScenario.Links.size(); i++){
if(CycicScenarios.workingCycicScenario.Links.get(i).source == circle){
CycicScenarios.workingCycicScenario.Links.get(i).line.setStartX(circle.getCenterX());
CycicScenarios.workingCycicScenario.Links.get(i).line.setStartY(circle.getCenterY());
CycicScenarios.workingCycicScenario.Links.get(i).line.updatePosition();
}
if(CycicScenarios.workingCycicScenario.Links.get(i).target == circle){
CycicScenarios.workingCycicScenario.Links.get(i).line.setEndX(circle.getCenterX());
CycicScenarios.workingCycicScenario.Links.get(i).line.setEndY(circle.getCenterY());
CycicScenarios.workingCycicScenario.Links.get(i).line.updatePosition();
}
}
for(int i = 0; i < circle.childrenLinks.size(); i++){
circle.childrenLinks.get(i).line.setStartX(circle.getCenterX());
circle.childrenLinks.get(i).line.setStartY(circle.getCenterY());
circle.childrenList.get(i).setCenterX(mousex-circle.childrenDeltaX.get(i)+x);
circle.childrenList.get(i).setCenterY(mousey-circle.childrenDeltaY.get(i)+y);
circle.childrenLinks.get(i).line.setEndX(circle.childrenList.get(i).getCenterX());
circle.childrenLinks.get(i).line.setEndY(circle.childrenList.get(i).getCenterY());
circle.childrenList.get(i).menu.setLayoutX(circle.childrenList.get(i).getCenterX());
circle.childrenList.get(i).menu.setLayoutY(circle.childrenList.get(i).getCenterY());
VisFunctions.placeTextOnCircle(circle.childrenList.get(i), "bottom");
for(int ii = 0; ii < CycicScenarios.workingCycicScenario.Links.size(); ii++){
if(circle.childrenList.get(i) == CycicScenarios.workingCycicScenario.Links.get(ii).source){
CycicScenarios.workingCycicScenario.Links.get(ii).line.setStartX(circle.childrenList.get(i).getCenterX());
CycicScenarios.workingCycicScenario.Links.get(ii).line.setStartY(circle.childrenList.get(i).getCenterY());
CycicScenarios.workingCycicScenario.Links.get(ii).line.updatePosition();
}
}
}
mousex = event.getX();
mousey = event.getY();
}
event.consume();
/*if(event.isConsumed()){
Cycic.pane.getChildren().remove(line);
}*/
}
});
// Double click functionality to show/hide children. As well as a bloom feature to show which node is selected.
circle.setOnMouseClicked(new EventHandler<MouseEvent>(){
@Override
public void handle(MouseEvent event){
if(event.getButton().equals(MouseButton.SECONDARY)){
circle.menu.setVisible(true);
event.consume();
}
if(event.isAltDown() && event.isControlDown()){
}
if (event.getClickCount() >= 2){
event.consume();
CyclistController._presenter.addTool(new FormBuilderTool());
} else if (event.getButton().equals(MouseButton.PRIMARY)){
for(int i = 0; i < Cycic.pane.getChildren().size(); i++){
if(Cycic.pane.getChildren().get(i).getId() == "cycicNode"){
((Shape) Cycic.pane.getChildren().get(i)).setStroke(Color.BLACK);
((Shape) Cycic.pane.getChildren().get(i)).setStrokeWidth(1);
}
}
circle.setStrokeWidth(5);
circle.setStroke(Color.DARKGRAY);
}
}
});
Cycic.workingScenario.FacilityNodes.add(parent);
// Code for allow a shift + (drag and drop) to start a new facility form for this facilityCircle.
/*DnD.LocalClipboard clipboard = DnD.getInstance().createLocalClipboard();
clipboard.put(DnD.TOOL_FORMAT, Tool.class, new FormBuilderTool());
Dragboard db = circle.startDragAndDrop(TransferMode.COPY);
//Dragboard db = circle.startDragAndDrop(TransferMode.NONE);
ClipboardContent content = new ClipboardContent();
content.put(DnD.TOOL_FORMAT, "Facility Form");
db.setContent(content);
Line line = new Line();
Cycic.pane.getChildren().add(line);
line.setEndX(event.getX());
line.setEndY(event.getY());
line.setStartX(circle.getCenterX());
line.setStartY(circle.getCenterY());
event.consume();
Cycic.pane.getChildren().remove(line);
}
}
});*/
circle.setOnMouseEntered(new EventHandler<MouseEvent>(){
public void handle(MouseEvent e){
circle.setRadius(mouseOverRadius);
}
});
circle.setOnMouseExited(new EventHandler<MouseEvent>(){
public void handle(MouseEvent e){
circle.setRadius(defRadius);
}
});
// Adding facilityCircle to the pane.
Cycic.pane.getChildren().add(circle);
Cycic.pane.getChildren().add(circle.menu);
Cycic.pane.getChildren().add(circle.text);
Cycic.pane.getChildren().add(circle.image);
circle.image.toBack();
return circle;
}
/**
* Removes a facilityCircle from the simulation.
* @param circle The facilityCircle to be removed.
*/
static void deleteNode(facilityNode node){
for(int i = 0; i < CycicScenarios.workingCycicScenario.Links.size(); i++){
if(CycicScenarios.workingCycicScenario.Links.get(i).source == node.cycicCircle){
CycicScenarios.workingCycicScenario.Links.remove(i);
}
}
for(int i = 0; i < CycicScenarios.workingCycicScenario.FacilityNodes.size(); i++){
if(CycicScenarios.workingCycicScenario.FacilityNodes.get(i) == node){
for(int ii = 0; ii < CycicScenarios.workingCycicScenario.FacilityNodes.get(i).cycicCircle.childrenList.size();ii++){
for(int iii = 0; iii < CycicScenarios.workingCycicScenario.Links.size(); iii++){
if(CycicScenarios.workingCycicScenario.Links.get(i).source == CycicScenarios.workingCycicScenario.FacilityNodes.get(i).cycicCircle.childrenList.get(iii)){
CycicScenarios.workingCycicScenario.Links.remove(i);
}
}
}
CycicScenarios.workingCycicScenario.FacilityNodes.remove(i);
}
}
for(int i = 0; i < CycicScenarios.workingCycicScenario.FacilityNodes.size(); i++){
for(int ii = 0; ii < CycicScenarios.workingCycicScenario.FacilityNodes.get(i).cycicCircle.childrenList.size(); ii++){
CycicScenarios.workingCycicScenario.FacilityNodes.get(i).cycicCircle.childrenList.get(ii).parentIndex = i;
}
}
VisFunctions.redrawPane();
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.