code
stringlengths
1
2.01M
repo_name
stringlengths
3
62
path
stringlengths
1
267
language
stringclasses
231 values
license
stringclasses
13 values
size
int64
1
2.01M
/* * OptionInfo.java * * Copyright (c) 2011, Ralf Biedert All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package net.xeoh.plugins.diagnosis.local.options.status; import java.io.Serializable; import net.xeoh.plugins.diagnosis.local.options.StatusOption; public class OptionInfo implements StatusOption { /** */ private static final long serialVersionUID = 5703900703387071451L; /** */ private final Serializable value; /** */ private final String key; /** * @param key * @param value */ public OptionInfo(String key, Serializable value) { this.key = key; this.value = value; } /** * @return the value */ public Serializable getValue() { return this.value; } /** * @return the key */ public String getKey() { return this.key; } }
100json-jspf
modules/core/src/net/xeoh/plugins/diagnosis/local/options/status/OptionInfo.java
Java
bsd
2,320
/* * StatusChange.java * * Copyright (c) 2011, Ralf Biedert All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package net.xeoh.plugins.diagnosis.local; import java.io.Serializable; import net.xeoh.plugins.diagnosis.local.options.status.OptionInfo; /** * Reflects a new diagnosis status on a given channel. * * @author Ralf Biedert * * @param <T> */ public interface DiagnosisStatus<T extends Serializable> { /** * Returns the channel for which some change happened. * * @return The channel for which something happened. */ public Class<? extends DiagnosisChannelID<T>> getChannel(); /** * Returns the channel as a string. Mostly used for replay. * * @return String representation of the channel. */ public String getChannelAsString(); /** * Returns the new value. * * @return The value. */ public T getValue(); /** * Returns the associated info object. * * @return the info objects. */ public OptionInfo[] getInfos(); /** * Returns the date when this status was generated. * * @return The date. */ public long getDate(); }
100json-jspf
modules/core/src/net/xeoh/plugins/diagnosis/local/DiagnosisStatus.java
Java
bsd
2,662
/* * Diagnosis.java * * Copyright (c) 2011, Ralf Biedert All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package net.xeoh.plugins.diagnosis.local; import java.io.Serializable; import net.xeoh.plugins.base.Plugin; import net.xeoh.plugins.base.PluginConfiguration; import net.xeoh.plugins.base.util.JSPFProperties; import net.xeoh.plugins.diagnosis.local.options.ChannelOption; import net.xeoh.plugins.diagnosis.local.util.DiagnosisUtil; /** * Main enty point to the diagnosis. Allows your application to record diagnosis data to various channels, which * can then be stored in a diagnosis.record for later analysis. * * * The following configuration sub-keys are usually known for this class (see {@link PluginConfiguration}, keys must be set * <em>before</em> createPluginManager() is being called, i.e., set in the {@link JSPFProperties} object!):<br/><br/> * * <ul> * <li><b>recording.enabled</b> - If we should record to a file or not. If switched off, diagnosis has virtually no overhead. Specify either {true, false}.</li> * <li><b>recording.file</b> - File to which the record should be writte (will be overwritten).</li> * <li><b>recording.format</b> - Format to write. Should be <code>java/serialization</code> for now.</li> * <li><b>analysis.stacktraces.enabled</b> - If true, a stack trace will also be written. Very helpful, rather slow. Specify either {true, false}.</li> * <li><b>analysis.stacktraces.depth</b> - Depth of the stacktrace. Specify either something from 1 to 10000.</li> * </ul><br/> * * @author Ralf Biedert * @since 1.1 * @see DiagnosisUtil */ public interface Diagnosis extends Plugin { /** * Returns a given channel. * * @param <T> * @param channel * @param options * @return . */ public <T extends Serializable> DiagnosisChannel<T> channel(Class<? extends DiagnosisChannelID<T>> channel, ChannelOption... options); /** * Registers a listener to the diagnosis. * * @param <T> * @param channel * @param listener */ public <T extends Serializable> void registerMonitor(Class<? extends DiagnosisChannelID<T>> channel, DiagnosisMonitor<T> listener); /** * Adds a replay listener for a given file. * * @param file * @param listener */ public void replay(String file, DiagnosisMonitor<?> listener); }
100json-jspf
modules/core/src/net/xeoh/plugins/diagnosis/local/Diagnosis.java
Java
bsd
3,915
/* * DiagnosisImpl.java * * Copyright (c) 2011, Ralf Biedert All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package net.xeoh.plugins.diagnosis.local.impl; import static net.jcores.jre.CoreKeeper.$; import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import net.xeoh.plugins.base.PluginConfiguration; import net.xeoh.plugins.base.annotations.PluginImplementation; import net.xeoh.plugins.base.annotations.events.Shutdown; import net.xeoh.plugins.base.util.PluginConfigurationUtil; import net.xeoh.plugins.diagnosis.local.Diagnosis; import net.xeoh.plugins.diagnosis.local.DiagnosisChannel; import net.xeoh.plugins.diagnosis.local.DiagnosisChannelID; import net.xeoh.plugins.diagnosis.local.DiagnosisMonitor; import net.xeoh.plugins.diagnosis.local.DiagnosisStatus; import net.xeoh.plugins.diagnosis.local.impl.serialization.java.Entry; import net.xeoh.plugins.diagnosis.local.impl.serialization.java.EntryCallback; import net.xeoh.plugins.diagnosis.local.impl.serialization.java.LogFileReader; import net.xeoh.plugins.diagnosis.local.impl.serialization.java.LogFileWriter; import net.xeoh.plugins.diagnosis.local.options.ChannelOption; import net.xeoh.plugins.diagnosis.local.options.status.OptionInfo; @PluginImplementation public class DiagnosisImpl implements Diagnosis { /** Stores information on a key */ class KeyEntry { /** Locks access to this item */ final Lock entryLock = new ReentrantLock(); /** All listeners subscribed to this item */ final Collection<DiagnosisMonitor<?>> allListeners = new ArrayList<DiagnosisMonitor<?>>(); /** The current channel holder */ DiagnosisStatus<?> lastItem = null; } /** Manages all information regarding a key */ final Map<Class<? extends DiagnosisChannelID<?>>, KeyEntry> items = new ConcurrentHashMap<Class<? extends DiagnosisChannelID<?>>, KeyEntry>(); /** Plugin configuration (will be injected manually by the PluginManager) */ public PluginConfiguration configuration; /** If true, the whole plugin will be disabled */ boolean isDisabled = false; /** If true, if we should dump stack traces */ boolean useStackTraces = false; /** If we should compress our output */ boolean compressOutput = true; /** Depth of stack traces */ int stackTracesDepth = 1; /** The file to which we record to */ String recordingFile = null; /** The actual serializer we use */ volatile LogFileWriter serializer = null; /** If recording should be enabled */ boolean recordingEnabled = false; /* * (non-Javadoc) * * @see net.xeoh.plugins.diagnosis.local.Diagnosis#channel(java.lang.Class, * net.xeoh.plugins.diagnosis.local.options.ChannelOption[]) */ @SuppressWarnings("unchecked") @Override public <T extends Serializable> DiagnosisChannel<T> channel(Class<? extends DiagnosisChannelID<T>> channel, ChannelOption... options) { // In case we are disabled, return a dummy if (this.isDisabled) { final DiagnosisChannel<?> impl = new DiagnosisChannelDummyImpl(this, channel); return (DiagnosisChannel<T>) impl; } // In case this was the first call, create a serializer synchronized (this) { if (this.serializer == null && this.recordingEnabled) { this.serializer = createWriter(); } } final DiagnosisChannel<?> impl = new DiagnosisChannelImpl(this, channel); return (DiagnosisChannel<T>) impl; } /** * Try to create a write for our logging data. * * @return */ LogFileWriter createWriter() { // First try to return a writer with the given name try { return new LogFileWriter(this.recordingFile, this.compressOutput); } catch (Exception e) {} // First try to return a writer with some time stamp attached (in case the old one was not overwritable) try { return new LogFileWriter(this.recordingFile + "." + System.currentTimeMillis(), this.compressOutput); } catch (Exception e) {} // Now we are out of luck return null; } /** * Stores the given entry to our record file * * @param status * @param entry */ @SuppressWarnings({ "rawtypes", "unchecked" }) public void recordEntry(DiagnosisStatus<?> status, Entry entry) { if (this.serializer != null) this.serializer.record(entry); final KeyEntry keyEntry = getKeyEntry(status.getChannel()); // Now process entry try { keyEntry.entryLock.lock(); keyEntry.lastItem = status; // Check if we should publish silently. for (DiagnosisMonitor<?> listener : keyEntry.allListeners) { try { ((DiagnosisMonitor<?>) listener).onStatusChange((DiagnosisStatus) status); } catch (Exception e) { e.printStackTrace(); } } } finally { keyEntry.entryLock.unlock(); } } /** Opens all required streams */ @SuppressWarnings("boxing") // This MUST NOT be tagged with @Init, as it will be executed manually by the PluginManager. public void init() { final PluginConfigurationUtil util = new PluginConfigurationUtil(this.configuration); this.isDisabled = !util.getBoolean(Diagnosis.class, "general.enabled", true); this.recordingEnabled = util.getBoolean(Diagnosis.class, "recording.enabled", false); this.recordingFile = util.getString(Diagnosis.class, "recording.file", "diagnosis.record"); this.useStackTraces = util.getBoolean(Diagnosis.class, "analysis.stacktraces.enabled", false); this.stackTracesDepth = util.getInt(Diagnosis.class, "analysis.stacktraces.depth", 1); String mode = util.getString(Diagnosis.class, "recording.format", "java/serialization/gzip"); if ("java/serialization/gzip".equals(mode)) { this.compressOutput = true; } if ("java/serialization".equals(mode)) { this.compressOutput = false; } } /** Close the log file */ @Shutdown public void shutdown() { // TODO // this.serializer...() } /* * (non-Javadoc) * * @see net.xeoh.plugins.diagnosis.local.Diagnosis#registerListener(java.lang.Class, * net.xeoh.plugins.diagnosis.local.DiagnosisListener) */ @SuppressWarnings("unchecked") @Override public <T extends Serializable> void registerMonitor(Class<? extends DiagnosisChannelID<T>> channel, DiagnosisMonitor<T> listener) { if (channel == null || listener == null) return; // Get the meta information for the requested id final KeyEntry keyEntry = getKeyEntry(channel); // Now process and add the entry try { keyEntry.entryLock.lock(); // If there has been a channel established, use that one if (keyEntry.lastItem != null) { try { listener.onStatusChange((DiagnosisStatus<T>) keyEntry.lastItem); } catch (Exception e) { e.printStackTrace(); } } keyEntry.allListeners.add(listener); } finally { keyEntry.entryLock.unlock(); } } /** * Returns the key entry of a given ID. * * @param id The ID to request * @return The key entry. */ private KeyEntry getKeyEntry(Class<? extends DiagnosisChannelID<?>> id) { KeyEntry keyEntry = null; synchronized (this.items) { keyEntry = this.items.get(id); if (keyEntry == null) { keyEntry = new KeyEntry(); this.items.put(id, keyEntry); } } return keyEntry; } /* * (non-Javadoc) * * @see net.xeoh.plugins.diagnosis.local.Diagnosis#replay(java.lang.String, * net.xeoh.plugins.diagnosis.local.DiagnosisMonitor) */ @Override public void replay(final String file, final DiagnosisMonitor<?> listener) { final LogFileReader reader = new LogFileReader(file); reader.replay(new EntryCallback() { @SuppressWarnings({ "rawtypes", "unchecked" }) @Override public void nextEntry(Entry entry) { // Convert the entry to a status events final List<OptionInfo> infos = new ArrayList<OptionInfo>(); for (String value : entry.additionalInfo.keySet()) { infos.add(new OptionInfo(value, (Serializable) entry.additionalInfo.get(value))); } final DiagnosisStatusImpl<?> event = new DiagnosisStatusImpl(entry.channel, (Serializable) entry.value, entry.date, $(infos).array(OptionInfo.class)); listener.onStatusChange((DiagnosisStatus) event); } }); } }
100json-jspf
modules/core/src/net/xeoh/plugins/diagnosis/local/impl/DiagnosisImpl.java
Java
bsd
10,898
/* * DiagnosisStatusImpl.java * * Copyright (c) 2011, Ralf Biedert All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package net.xeoh.plugins.diagnosis.local.impl; import java.io.Serializable; import net.xeoh.plugins.diagnosis.local.DiagnosisChannelID; import net.xeoh.plugins.diagnosis.local.DiagnosisStatus; import net.xeoh.plugins.diagnosis.local.options.status.OptionInfo; /** * @author Ralf Biedert * * @param <T> */ public class DiagnosisStatusImpl<T extends Serializable> implements DiagnosisStatus<T> { /** */ final private Class<? extends DiagnosisChannelID<T>> channel; /** */ final private String channelString; /** */ final private T value; /** */ final private long date; /** */ final private OptionInfo[] infos; /** * @param channel * @param value * @param date * @param infos */ public DiagnosisStatusImpl(Class<? extends DiagnosisChannelID<T>> channel, T value, long date, OptionInfo[] infos) { this.channel = channel; this.channelString = channel.getCanonicalName(); this.value = value; this.date = date; this.infos = infos; } /** * @param channelName * @param value * @param date * @param infos */ public DiagnosisStatusImpl(String channelName, T value, long date, OptionInfo[] infos) { this.channel = null; this.channelString = channelName; this.value = value; this.date = date; this.infos = infos; } /* * (non-Javadoc) * * @see net.xeoh.plugins.diagnosis.local.DiagnosisStatus#getChannel() */ @Override public Class<? extends DiagnosisChannelID<T>> getChannel() { return this.channel; } /* * (non-Javadoc) * * @see net.xeoh.plugins.diagnosis.local.DiagnosisStatus#getValue() */ @Override public T getValue() { return this.value; } /* * (non-Javadoc) * * @see net.xeoh.plugins.diagnosis.local.DiagnosisStatus#getInfos() */ @Override public OptionInfo[] getInfos() { return this.infos; } /* * (non-Javadoc) * * @see net.xeoh.plugins.diagnosis.local.DiagnosisStatus#getDate() */ @Override public long getDate() { return this.date; } /* (non-Javadoc) * @see net.xeoh.plugins.diagnosis.local.DiagnosisStatus#getChannelAsString() */ @Override public String getChannelAsString() { return this.channelString; } }
100json-jspf
modules/core/src/net/xeoh/plugins/diagnosis/local/impl/DiagnosisStatusImpl.java
Java
bsd
4,027
/* * EntryCallback.java * * Copyright (c) 2011, Ralf Biedert All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package net.xeoh.plugins.diagnosis.local.impl.serialization.java; public interface EntryCallback { public void nextEntry(Entry entry); }
100json-jspf
modules/core/src/net/xeoh/plugins/diagnosis/local/impl/serialization/java/EntryCallback.java
Java
bsd
1,707
/* * Entry.java * * Copyright (c) 2011, Ralf Biedert All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package net.xeoh.plugins.diagnosis.local.impl.serialization.java; import java.io.IOException; import java.io.Serializable; import java.util.HashMap; import java.util.Map; /** * Reflects an entry on a given channel. * * @author Ralf Biedert */ public class Entry implements Serializable { /** */ private static final long serialVersionUID = -361673738793578516L; /** The actual version we serialize */ private short version = 1; /** Specifies when this entry was observed */ public long date; /** Thread ID for which this entry was observed */ public long threadID; /** Stack trace for this call */ public String[] stackTrace; /** Channel this entry was observed on */ public String channel; /** Value that was observed */ public Object value; /** Additional information */ public Map<String, Object> additionalInfo = new HashMap<String, Object>(); /** * We do this ourself. * * @param stream * @throws IOException */ private void writeObject(java.io.ObjectOutputStream stream) throws IOException { stream.writeShort(this.version); stream.writeLong(this.date); stream.writeLong(this.threadID); stream.writeUnshared(this.stackTrace); stream.writeUnshared(this.channel); stream.writeUnshared(this.value); stream.writeUnshared(this.additionalInfo); } /** * We do this ourself. * * @param stream * @throws IOException * @throws ClassNotFoundException */ @SuppressWarnings("unchecked") private void readObject(java.io.ObjectInputStream stream) throws IOException, ClassNotFoundException { this.version = stream.readShort(); if (this.version != 1) throw new ClassNotFoundException("Version mismatch, cannot handle " + this.version); this.date = stream.readLong(); this.threadID = stream.readLong(); this.stackTrace = (String[]) stream.readUnshared(); this.channel = (String) stream.readUnshared(); this.value = stream.readUnshared(); try { this.additionalInfo = (Map<String, Object>) stream.readUnshared(); } catch (ClassNotFoundException e) { // FIXME: Due to a Java 'feature' we cannot prevent the CNFException to propagate upwards ... This means the object // will be missing ... // System.err.println("Unknown type in infos (" + e.getMessage() + "). You should run this in the orig app's classpath!"); } } }
100json-jspf
modules/core/src/net/xeoh/plugins/diagnosis/local/impl/serialization/java/Entry.java
Java
bsd
4,189
/* * SerializationFile.java * * Copyright (c) 2011, Ralf Biedert All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package net.xeoh.plugins.diagnosis.local.impl.serialization.java; import static net.jcores.jre.CoreKeeper.$; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; import java.util.concurrent.LinkedBlockingQueue; import java.util.zip.GZIPOutputStream; public class LogFileWriter { /** Raw file to write into */ FileOutputStream fileOutputStream; /** Object stream to use when writing */ ObjectOutputStream objectOutputStream; /** Zip stream to compress */ GZIPOutputStream zipStream; /** Entries to write into the file */ LinkedBlockingQueue<Entry> eventQueue = new LinkedBlockingQueue<Entry>(); /** * Creates a new serializer * * @param file The file to write into. * @param compressOutput */ public LogFileWriter(String file, boolean compressOutput) { try { $(file).file().delete(); this.fileOutputStream = new FileOutputStream($(file).get("diagnosis.fallback.record")); if (compressOutput) { this.zipStream = new GZIPOutputStream(this.fileOutputStream); this.objectOutputStream = new ObjectOutputStream(this.zipStream); } else this.objectOutputStream = new ObjectOutputStream(this.fileOutputStream); } catch (Exception e) { e.printStackTrace(); return; } // Create recording thread final Thread thread = new Thread(new Runnable() { @Override public void run() { int flushCount = 0; while (true) { try { final Entry take = LogFileWriter.this.eventQueue.take(); LogFileWriter.this.objectOutputStream.writeUnshared(take); if (flushCount++ > 50) { LogFileWriter.this.objectOutputStream.reset(); LogFileWriter.this.objectOutputStream.flush(); if (LogFileWriter.this.zipStream != null) { LogFileWriter.this.zipStream.flush(); } LogFileWriter.this.fileOutputStream.flush(); flushCount = 0; } } catch (InterruptedException e) {} catch (IOException e) { e.printStackTrace(); } } } }); thread.setName("LogFileWriter.serializer"); thread.setDaemon(true); thread.start(); // Registers a shutdown hook to flush the queue Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { @Override public void run() { terminate(); } })); } /** Flushes and closes the recording streams */ void terminate() { try { this.objectOutputStream.flush(); if (this.zipStream != null) this.zipStream.flush(); this.fileOutputStream.flush(); // this.objectOutputStream.close(); // this.fileOutputStream.close(); } catch (IOException e) { e.printStackTrace(); } } /** * Records the given entry. * * @param entry Entry to record. */ public void record(Entry entry) { this.eventQueue.add(entry); } }
100json-jspf
modules/core/src/net/xeoh/plugins/diagnosis/local/impl/serialization/java/LogFileWriter.java
Java
bsd
5,106
/* * SerializationFile.java * * Copyright (c) 2011, Ralf Biedert All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package net.xeoh.plugins.diagnosis.local.impl.serialization.java; import static net.jcores.jre.CoreKeeper.$; import java.io.EOFException; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.ObjectInputStream; import java.io.StreamCorruptedException; public class LogFileReader { /** */ private final String file; /** * Creates a new serializer * * @param file The file to write into. */ public LogFileReader(String file) { this.file = file; } /** * @param callback */ public void replay(EntryCallback callback) { try { final ObjectInputStream stream = new ObjectInputStream(new FileInputStream(this.file)); while (true) { try { callback.nextEntry((Entry) stream.readObject()); } catch(Exception e) { if(e instanceof EOFException) break; if(e instanceof StreamCorruptedException) break; if(e instanceof ClassNotFoundException) { System.err.println("Skipping one entry due to a class not found: " + e.getMessage()); continue; } e.printStackTrace(); } } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { // e.printStackTrace(); System.out.println("End of File"); } } /** * @param args */ public static void main(String[] args) { final LogFileReader reader = new LogFileReader("diagnosis.record"); reader.replay(new EntryCallback() { @Override public void nextEntry(Entry entry) { final long time = entry.date; final String name = $(entry.channel).split("\\.").get(-1); final Object value = entry.value; final StringBuilder sb = new StringBuilder(100); for (final String string : entry.additionalInfo.keySet()) { sb.append(":" + string + "=" + entry.additionalInfo.get(string)); } final String opts = (sb.length() > 0) ? sb.substring(1) : ""; final String output = time + "\t" + name + "\t" + value + "\t" + opts; System.out.println(output); } }); } }
100json-jspf
modules/core/src/net/xeoh/plugins/diagnosis/local/impl/serialization/java/LogFileReader.java
Java
bsd
3,983
/* * DiagnosisChannel.java * * Copyright (c) 2011, Ralf Biedert All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package net.xeoh.plugins.diagnosis.local.impl; import static net.jcores.jre.CoreKeeper.$; import java.io.Serializable; import net.xeoh.plugins.diagnosis.local.DiagnosisChannel; import net.xeoh.plugins.diagnosis.local.DiagnosisChannelID; import net.xeoh.plugins.diagnosis.local.impl.serialization.java.Entry; import net.xeoh.plugins.diagnosis.local.options.StatusOption; import net.xeoh.plugins.diagnosis.local.options.status.OptionInfo; public class DiagnosisChannelImpl implements DiagnosisChannel<Object> { /** Main diagnosis */ private final DiagnosisImpl diagnosis; /** Main channel */ private final Class<? extends DiagnosisChannelID<?>> channel; /** * Creates a new channel * * @param diagnosis * * @param channel */ public DiagnosisChannelImpl(DiagnosisImpl diagnosis, Class<? extends DiagnosisChannelID<?>> channel) { this.diagnosis = diagnosis; this.channel = channel; } /* * (non-Javadoc) * * @see net.xeoh.plugins.diagnosis.local.DiagnosisChannel#status(java.lang.Object) */ @SuppressWarnings({ "rawtypes", "unchecked" }) @Override public void status(Object value, StatusOption... options) { final long timestamp = System.currentTimeMillis(); final long id = Thread.currentThread().getId(); final Entry entry = new Entry(); entry.date = timestamp; entry.threadID = id; entry.channel = this.channel.getCanonicalName(); entry.value = value; // Generate stack trace if requested if (this.diagnosis.useStackTraces) { final StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace(); entry.stackTrace = $(stackTrace).slice(2, Math.min(this.diagnosis.stackTracesDepth, stackTrace.length - 2)).string().array(String.class); } // Process all option infos final OptionInfo[] infos = $(options).cast(OptionInfo.class).array(OptionInfo.class); for (OptionInfo oi : infos) { entry.additionalInfo.put(oi.getKey(), oi.getValue()); } // Create status object final DiagnosisStatusImpl status = new DiagnosisStatusImpl((Class<? extends DiagnosisChannelID>) this.channel, (Serializable) value, timestamp, infos); this.diagnosis.recordEntry(status, entry); } }
100json-jspf
modules/core/src/net/xeoh/plugins/diagnosis/local/impl/DiagnosisChannelImpl.java
Java
bsd
3,984
/* * DiagnosisChannel.java * * Copyright (c) 2011, Ralf Biedert All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package net.xeoh.plugins.diagnosis.local.impl; import net.xeoh.plugins.diagnosis.local.DiagnosisChannel; import net.xeoh.plugins.diagnosis.local.DiagnosisChannelID; import net.xeoh.plugins.diagnosis.local.options.StatusOption; public class DiagnosisChannelDummyImpl implements DiagnosisChannel<Object> { /** * @param diagnosis * @param channel */ public DiagnosisChannelDummyImpl(DiagnosisImpl diagnosis, Class<? extends DiagnosisChannelID<?>> channel) { // } /* * (non-Javadoc) * * @see net.xeoh.plugins.diagnosis.local.DiagnosisChannel#status(java.lang.Object) */ @Override public void status(Object value, StatusOption... options) { // } }
100json-jspf
modules/core/src/net/xeoh/plugins/diagnosis/local/impl/DiagnosisChannelDummyImpl.java
Java
bsd
2,332
/* * DiagnosisChannelUtil.java * * Copyright (c) 2011, Ralf Biedert All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package net.xeoh.plugins.diagnosis.local.util; import static net.jcores.jre.CoreKeeper.$; import java.io.Serializable; import net.jcores.jre.interfaces.functions.Fn; import net.jcores.jre.utils.VanillaUtil; import net.xeoh.plugins.diagnosis.local.DiagnosisChannel; import net.xeoh.plugins.diagnosis.local.options.StatusOption; import net.xeoh.plugins.diagnosis.local.options.status.OptionInfo; /** * Wraps a {@link DiagnosisChannel} and provides helper functions. * * @author Ralf Biedert * * @param <T> The type of the diagnosis object. */ public class DiagnosisChannelUtil<T> extends VanillaUtil<DiagnosisChannel<T>> implements DiagnosisChannel<T> { /** * Creates a new util with the given channel. * * @param object */ public DiagnosisChannelUtil(DiagnosisChannel<T> object) { super(object); } /* (non-Javadoc) * @see net.xeoh.plugins.diagnosis.local.DiagnosisChannel#status(java.lang.Object, net.xeoh.plugins.diagnosis.local.options.StatusOption[]) */ @Override public void status(T value, StatusOption... options) { this.object.status(value, options); } /** * Logs the value and creates an {@link OptionInfo} for each * two info parameters (key, value). * * @param value The value to log. * @param infos The info parameters. */ public void status(T value, Serializable... infos) { if(infos == null) { this.object.status(value); return; } // Convert the options we have final OptionInfo[] options = $(infos).forEach(new Fn<Serializable, OptionInfo>() { @Override public OptionInfo f(Serializable... arg0) { return new OptionInfo(arg0[0].toString(), arg0[1]); } }, 2).array(OptionInfo.class); this.object.status(value, options); } }
100json-jspf
modules/core/src/net/xeoh/plugins/diagnosis/local/util/DiagnosisChannelUtil.java
Java
bsd
3,479
/* * DiagnosisUtil.java * * Copyright (c) 2011, Ralf Biedert All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package net.xeoh.plugins.diagnosis.local.util; import java.io.Serializable; import net.xeoh.plugins.base.util.VanillaPluginUtil; import net.xeoh.plugins.diagnosis.local.Diagnosis; import net.xeoh.plugins.diagnosis.local.DiagnosisChannelID; import net.xeoh.plugins.diagnosis.local.DiagnosisMonitor; import net.xeoh.plugins.diagnosis.local.options.ChannelOption; import net.xeoh.plugins.diagnosis.local.util.conditions.Condition; /** * Wraps a {@link Diagnosis} object and provides helper functions. * * @author Ralf Biedert */ public class DiagnosisUtil extends VanillaPluginUtil<Diagnosis> implements Diagnosis { /** * @param diagnosis */ public DiagnosisUtil(Diagnosis diagnosis) { super(diagnosis); } /** * Registers a monitor listening to many channels. * * @param listener * @param all */ @SuppressWarnings("unchecked") public void registerMonitors(final DiagnosisMonitor<?> listener, final Class<?>... all) { if (listener == null || all == null || all.length == 0) return; // Stores all items we received so far for (final Class<?> c : all) { final Class<? extends DiagnosisChannelID<Serializable>> cc = (Class<? extends DiagnosisChannelID<Serializable>>) c; this.object.registerMonitor(cc, (DiagnosisMonitor<Serializable>) listener); } } /** * Registers a condition to the enclode diagnosis. * * @param condition */ public void registerCondition(Condition condition) { if(condition == null) return; registerMonitors(condition, condition.getRequiredChannels()); } /* (non-Javadoc) * @see net.xeoh.plugins.diagnosis.local.Diagnosis#channel(java.lang.Class, net.xeoh.plugins.diagnosis.local.options.ChannelOption[]) */ @Override public <T extends Serializable> DiagnosisChannelUtil<T> channel(Class<? extends DiagnosisChannelID<T>> channel, ChannelOption... options) { return new DiagnosisChannelUtil<T>(this.object.channel(channel, options)); } /* (non-Javadoc) * @see net.xeoh.plugins.diagnosis.local.Diagnosis#registerMonitor(java.lang.Class, net.xeoh.plugins.diagnosis.local.DiagnosisMonitor) */ @Override public <T extends Serializable> void registerMonitor(Class<? extends DiagnosisChannelID<T>> channel, DiagnosisMonitor<T> listener) { this.object.registerMonitor(channel, listener); } /* (non-Javadoc) * @see net.xeoh.plugins.diagnosis.local.Diagnosis#replay(java.lang.String, net.xeoh.plugins.diagnosis.local.DiagnosisMonitor) */ @Override public void replay(String file, DiagnosisMonitor<?> listener) { this.object.replay(file, listener); } }
100json-jspf
modules/core/src/net/xeoh/plugins/diagnosis/local/util/DiagnosisUtil.java
Java
bsd
4,474
/* * TwoStateCondition.java * * Copyright (c) 2011, Ralf Biedert All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package net.xeoh.plugins.diagnosis.local.util.conditions; import java.io.Serializable; import java.util.Set; import net.xeoh.plugins.diagnosis.local.DiagnosisChannelID; import net.xeoh.plugins.diagnosis.local.DiagnosisStatus; import net.xeoh.plugins.diagnosis.local.util.conditions.matcher.Matcher; /** * Reflects an abstract two-state condition, that can either be on, or off. * * @author Ralf Biedert */ public abstract class TwoStateMatcherAND extends TwoStateMatcher { /* (non-Javadoc) * @see net.xeoh.plugins.diagnosis.local.DiagnosisMonitor#onStatusChange(net.xeoh.plugins.diagnosis.local.DiagnosisStatus) */ @Override public void onStatusChange(DiagnosisStatus<Serializable> status) { // First, update our values this.currentStatus.put(status.getChannel(), status.getValue()); // Next match status agains on status Set<Class<? extends DiagnosisChannelID<?>>> keySet = this.onRequirements.keySet(); for (Class<? extends DiagnosisChannelID<?>> c : keySet) { final Matcher requirement = this.onRequirements.get(c); final Object is = this.currentStatus.get(c); if(!requirement.matches(is)) { announceState(STATE.OFF); return; } } // Match dependant conditions for (@SuppressWarnings("unused") TwoStateCondition twoState : this.requiredConditions) { // FIXME: Aarrgh. javac failes on the following line while eclipse doesn't ... //if(!$(twoState.getRequiredChannels()).contains(status.getChannel())) continue; // twoState.onStatusChange(status); /* if(twoState.getState() == STATE.OFF) { announceState(STATE.OFF); return; } */ } announceState(STATE.ON); } }
100json-jspf
modules/core/src/net/xeoh/plugins/diagnosis/local/util/conditions/TwoStateMatcherAND.java
Java
bsd
3,508
/* * TwoStateCondition.java * * Copyright (c) 2011, Ralf Biedert All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package net.xeoh.plugins.diagnosis.local.util.conditions; /** * Reflects an abstract two-state condition, that can either be on, or off. * * @author Ralf Biedert */ public abstract class TwoStateCondition extends Condition { /** The state of this condition */ public static enum STATE { ON, OFF } /** Memorize last state we had */ STATE lastState = STATE.OFF; /** * Announces the state in case it differs from our last announcement. * * @param state */ public void announceState(STATE state) { if(state == this.lastState) return; stateChanged(state); this.lastState = state; } /** * Called when the state has changed based on some matching input. * * @param state The new state. */ public abstract void stateChanged(STATE state); /** * Returns the current state of this condition. * * @return The current state. */ public STATE getState() { return this.lastState; } }
100json-jspf
modules/core/src/net/xeoh/plugins/diagnosis/local/util/conditions/TwoStateCondition.java
Java
bsd
2,614
/* * Matcher.java * * Copyright (c) 2011, Ralf Biedert All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package net.xeoh.plugins.diagnosis.local.util.conditions.matcher; /** * @author Ralf Biedert */ public abstract class Matcher { /** * Returns true if the matcher matches, false if not. * @param object * @return . */ public abstract boolean matches(Object object); }
100json-jspf
modules/core/src/net/xeoh/plugins/diagnosis/local/util/conditions/matcher/Matcher.java
Java
bsd
1,856
/* * Contains * * Copyright (c) 2011, Ralf Biedert All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package net.xeoh.plugins.diagnosis.local.util.conditions.matcher; /** * @author Ralf Biedert */ public class Contains extends Matcher { private String string; /** * @param string */ public Contains(String string) { this.string = string; } /* (non-Javadoc) * @see net.xeoh.plugins.diagnosis.local.util.conditions.matcher.Matcher#matches(java.lang.Object) */ @Override public boolean matches(Object object) { if(object == null) return false; if(!(object instanceof String)) return false; String s = (String) object; return s.contains(this.string); } }
100json-jspf
modules/core/src/net/xeoh/plugins/diagnosis/local/util/conditions/matcher/Contains.java
Java
bsd
2,212
/* * Exact.java * * Copyright (c) 2011, Ralf Biedert All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package net.xeoh.plugins.diagnosis.local.util.conditions.matcher; public class Is extends Matcher { private Object value; public Is(Object value) { this.value = value; } /* (non-Javadoc) * @see net.xeoh.plugins.diagnosis.local.util.conditions.matcher.Matcher#matches(java.lang.Object) */ @Override public boolean matches(Object object) { if(object == null && this.value == null) return true; if(object == null && this.value != null) return false; return this.value.equals(object); } }
100json-jspf
modules/core/src/net/xeoh/plugins/diagnosis/local/util/conditions/matcher/Is.java
Java
bsd
2,124
/* * TwoStateCondition.java * * Copyright (c) 2011, Ralf Biedert All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package net.xeoh.plugins.diagnosis.local.util.conditions; import java.io.Serializable; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import net.xeoh.plugins.diagnosis.local.DiagnosisChannelID; import net.xeoh.plugins.diagnosis.local.util.conditions.matcher.Matcher; /** * Reflects an abstract two-state condition, that tries to match against a * number of requirements. * * @author Ralf Biedert */ public abstract class TwoStateMatcher extends TwoStateCondition { /** Stores the values we need for matching */ final Map<Class<? extends DiagnosisChannelID<?>>, Matcher> onRequirements = new HashMap<Class<? extends DiagnosisChannelID<?>>, Matcher>(); /** Stores the values we need for matching */ final Map<Class<? extends DiagnosisChannelID<?>>, Object> currentStatus = new HashMap<Class<? extends DiagnosisChannelID<?>>, Object>(); /** Additional required conditions to match. */ final List<TwoStateCondition> requiredConditions = new ArrayList<TwoStateCondition>(); /** */ public TwoStateMatcher() { setupMatcher(); } /** Override this method to set up your matcher */ protected void setupMatcher() { // } /** * Makes the condition match a number of channel states (linked with AND). * * @param <T> * @param channel * @param matcher */ public <T extends Serializable> void match(Class<? extends DiagnosisChannelID<T>> channel, Matcher matcher) { require(channel); this.onRequirements.put(channel, matcher); } /** * Makes the condition match another dependant condition. * * @param condition */ @SuppressWarnings("unchecked") public void match(TwoStateCondition condition) { // Require all dependant conditions final Class<? extends DiagnosisChannelID<?>>[] requiredChannels = (Class<? extends DiagnosisChannelID<?>>[]) condition.getRequiredChannels(); for (Class<? extends DiagnosisChannelID<?>> class1 : requiredChannels) { require(class1); } // And also store condition this.requiredConditions.add(condition); } }
100json-jspf
modules/core/src/net/xeoh/plugins/diagnosis/local/util/conditions/TwoStateMatcher.java
Java
bsd
3,806
/* * Condition.java * * Copyright (c) 2011, Ralf Biedert All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package net.xeoh.plugins.diagnosis.local.util.conditions; import static net.jcores.jre.CoreKeeper.$; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import net.xeoh.plugins.diagnosis.local.DiagnosisChannelID; import net.xeoh.plugins.diagnosis.local.DiagnosisMonitor; /** * Abstract class for any condition. * * @author Ralf Biedert */ public abstract class Condition implements DiagnosisMonitor<Serializable> { /** The channels to observe */ private List<Class<?>> channels = new ArrayList<Class<?>>(); /** * Adds a channel to the list of required channels. * * @param channel */ public void require(Class<? extends DiagnosisChannelID<?>> channel) { if(this.channels.contains(channel)) return; this.channels.add(channel); } /** * Returns the required channels for this condition. * * @return The required channels */ public Class<?>[] getRequiredChannels() { return $(this.channels).array(Class.class); } }
100json-jspf
modules/core/src/net/xeoh/plugins/diagnosis/local/util/conditions/Condition.java
Java
bsd
2,624
/* * InformationItem.java * * Copyright (c) 2009, Ralf Biedert All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package net.xeoh.plugins.informationbroker; /** * Represents an information item that can be acquired using the * information broker. You must create a subclass for each item you * wish to trade using the broker. * * @author Ralf Biedert * @param <T> The content's type. * @see InformationBroker */ public interface InformationItem<T> {}
100json-jspf
modules/core/src/net/xeoh/plugins/informationbroker/InformationItem.java
Java
bsd
1,915
/* * Infobroker.java * * Copyright (c) 2009, Ralf Biedert All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package net.xeoh.plugins.informationbroker; import java.util.Map; import net.xeoh.plugins.base.Plugin; import net.xeoh.plugins.informationbroker.options.PublishOption; import net.xeoh.plugins.informationbroker.options.SubscribeOption; import net.xeoh.plugins.informationbroker.util.InformationBrokerUtil; /** * Think of the information broker as a large, shared and type-safe hybrid between a * {@link Map} and a Bus. It enables you to exchange information between a number of * plugins by well known * keys. In contrast to a Bus, the exchanged items are stored and can be retrieved * by their key any time. Like the bus, however, listeners can register for updates to * certain * keys to be able to react on changes to them.<br> * </br> * * The new InformationBroker interface supersedes the old Bus (previously present in * JSPF), as it provides similar functionality.<br> * </br> * * @author Ralf Biedert * * @see InformationItem * @see InformationBrokerUtil */ public interface InformationBroker extends Plugin { /** * Publishes a new information item. The item will be made available to all listeners * subscribed to the item, or requesting it later. For example, to publish the current * user * name you could write:<br/> * <br/> * * <code> * publish(UserName.class, "John Doe"); * </code><br/> * <br/> * * @param <T> The type of the item to wait for. * @param channel The channel for which the new object should be published. * @param item The items to publish. * @param options A number of options the <code>publish()</code> method understands. */ public <T> void publish(Class<? extends InformationItem<T>> channel, T item, PublishOption... options); /** * Subscribes to a given information item. The listener will be called as soon as the * item changes. It will also be called when the item has already been set before. For * example, to subscribe to the latest location of a device (provided as a String) * you could write:<br/> * <br/> * * <code> * plugin.subscribe(UserName.class, new InformationListener&lt;String>() {<br/> * &nbsp;&nbsp;&nbsp;&nbsp;public void update(String item) {<br/> * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; ...<br/> * &nbsp;&nbsp;&nbsp;&nbsp;}<br/> * }); * </code><br/> * <br/> * * Also see the {@link InformationBrokerUtil}, it contains many useful convenience * functions. * * @param <T> The type of the item to wait for. * @param channel The item / ID / channel to subscribe to * @param listener The lister will be called whenever the value of the ID changes; and * it will * be called right away if the information item has already been set before. * @param options A number of options the <code>subscribe()</code> method understands. */ public <T> void subscribe(Class<? extends InformationItem<T>> channel, InformationListener<T> listener, SubscribeOption... options); /** * Unsubscribes the given information listener. It will not be called anymore * afterwards. * * @param listener The listener to unsubscribe. */ public void unsubscribe(InformationListener<?> listener); }
100json-jspf
modules/core/src/net/xeoh/plugins/informationbroker/InformationBroker.java
Java
bsd
4,937
/* * InformationListener.java * * Copyright (c) 2009, Ralf Biedert All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package net.xeoh.plugins.informationbroker; /** * Listens to a give information item. It is called back whenever the information item * changes. * * @author Ralf Biedert * * @param <X> The type of the delivered object. * @see InformationBroker */ public interface InformationListener<X> { /** * Called when the subscription requirements are met and a new item * has been posted. * * @param item The newly posted item. */ public void update(X item); }
100json-jspf
modules/core/src/net/xeoh/plugins/informationbroker/InformationListener.java
Java
bsd
2,067
/** * Top level package for the information broker. * * @since 1.0 */ package net.xeoh.plugins.informationbroker;
100json-jspf
modules/core/src/net/xeoh/plugins/informationbroker/package-info.java
Java
bsd
122
/* * OptionDummy.java * * Copyright (c) 2009, Ralf Biedert All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package net.xeoh.plugins.informationbroker.options.subscribe; import net.xeoh.plugins.informationbroker.InformationBroker; import net.xeoh.plugins.informationbroker.options.SubscribeOption; /** * Requests the {@link InformationBroker} to call <code>subscribe()</code> to obtain the * current value instantly. The listener will not be registered. Instead, it is ensured * that after <code>subscribe()</code> returns the listener will not be called again.<br/><br/> * * For example, to make a single, instant request to an item, you could write:<br/><br/> * * <code> * informationBroker.subscribe(id, listener, new OptionInstantRequest()); * </code> * * @author Ralf Biedert * @see InformationBroker */ public class OptionInstantRequest implements SubscribeOption { /** */ private static final long serialVersionUID = -8362751446846683259L; }
100json-jspf
modules/core/src/net/xeoh/plugins/informationbroker/options/subscribe/OptionInstantRequest.java
Java
bsd
2,435
/** * Options to <code>subscribe()</code>. * * @since 1.0 */ package net.xeoh.plugins.informationbroker.options.subscribe;
100json-jspf
modules/core/src/net/xeoh/plugins/informationbroker/options/subscribe/package-info.java
Java
bsd
130
/** * Options to <code>publish()</code>. * * @since 1.0 */ package net.xeoh.plugins.informationbroker.options.publish;
100json-jspf
modules/core/src/net/xeoh/plugins/informationbroker/options/publish/package-info.java
Java
bsd
126
/* * OptionDummy.java * * Copyright (c) 2009, Ralf Biedert All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package net.xeoh.plugins.informationbroker.options.publish; import net.xeoh.plugins.informationbroker.InformationBroker; import net.xeoh.plugins.informationbroker.options.PublishOption; /** * Requests the {@link InformationBroker} to <code>publish()</code> to update * the item silently, i.e., without calling any registered subscriber.<br/><br/> * * For example, to update a value silently, you could write:<br/><br/> * * <code> * informationBroker.publish(item, new OptionSilentPublish()); * </code> * * @author Ralf Biedert * @see InformationBroker */ public class OptionSilentPublish implements PublishOption { /** */ private static final long serialVersionUID = -8362751446846683259L; }
100json-jspf
modules/core/src/net/xeoh/plugins/informationbroker/options/publish/OptionSilentPublish.java
Java
bsd
2,284
/* * GetPluginOption.java * * Copyright (c) 2009, Ralf Biedert All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package net.xeoh.plugins.informationbroker.options; import net.xeoh.plugins.base.Option; import net.xeoh.plugins.informationbroker.InformationBroker; /** * The base type for all <code>subscribe()</code> options. * * @author Ralf Biedert * @see InformationBroker */ public interface SubscribeOption extends Option { // }
100json-jspf
modules/core/src/net/xeoh/plugins/informationbroker/options/SubscribeOption.java
Java
bsd
1,899
/** * Top level package for information broker options. * * @since 1.0 */ package net.xeoh.plugins.informationbroker.options;
100json-jspf
modules/core/src/net/xeoh/plugins/informationbroker/options/package-info.java
Java
bsd
134
/* * GetPluginOption.java * * Copyright (c) 2009, Ralf Biedert All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package net.xeoh.plugins.informationbroker.options; import net.xeoh.plugins.base.Option; import net.xeoh.plugins.informationbroker.InformationBroker; /** * The base type for all <code>publish()</code> options. * * @author Ralf Biedert * @see InformationBroker */ public interface PublishOption extends Option { // }
100json-jspf
modules/core/src/net/xeoh/plugins/informationbroker/options/PublishOption.java
Java
bsd
1,895
/* * InformationBrokerImpl.java * * Copyright (c) 2009, Ralf Biedert All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package net.xeoh.plugins.informationbroker.impl; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import java.util.logging.Logger; import net.xeoh.plugins.base.annotations.PluginImplementation; import net.xeoh.plugins.base.annotations.meta.Author; import net.xeoh.plugins.base.util.OptionUtils; import net.xeoh.plugins.informationbroker.InformationBroker; import net.xeoh.plugins.informationbroker.InformationItem; import net.xeoh.plugins.informationbroker.InformationListener; import net.xeoh.plugins.informationbroker.options.PublishOption; import net.xeoh.plugins.informationbroker.options.SubscribeOption; import net.xeoh.plugins.informationbroker.options.publish.OptionSilentPublish; import net.xeoh.plugins.informationbroker.options.subscribe.OptionInstantRequest; /** * Nothing to see here. * * @author Ralf Biedert */ @Author(name = "Ralf Biedert") @PluginImplementation public class InformationBrokerImpl implements InformationBroker { /** Stores information on a key */ class KeyEntry { /** Locks access to this item */ final Lock entryLock = new ReentrantLock(); /** All listeners subscribed to this item */ final Collection<InformationListener<?>> allListeners = new ArrayList<InformationListener<?>>(); /** The current channel holder */ Object lastItem = null; } /** Manages all information regarding a key */ final Map<Class<? extends InformationItem<?>>, KeyEntry> items = new HashMap<Class<? extends InformationItem<?>>, KeyEntry>(); /** Locks access to the items */ final Lock itemsLock = new ReentrantLock(); /** */ final Logger logger = Logger.getLogger(this.getClass().getName()); /* * (non-Javadoc) * * @see net.xeoh.plugins.informationbroker.InformationBroker#publish(net.xeoh.plugins. * informationbroker.InformationItem, * net.xeoh.plugins.informationbroker.options.PublishOption[]) */ @SuppressWarnings({ "unchecked" }) @Override public <T> void publish(Class<? extends InformationItem<T>> channel, T item, PublishOption... options) { if (channel == null || item == null) return; // Get our options final OptionUtils<PublishOption> ou = new OptionUtils<PublishOption>(options); final boolean silentPublish = ou.contains(OptionSilentPublish.class); final KeyEntry keyEntry = getKeyEntry(channel); // Now process entry try { keyEntry.entryLock.lock(); keyEntry.lastItem = item; // Check if we should publish silently. if (!silentPublish) { for (InformationListener<?> listener : keyEntry.allListeners) { try { ((InformationListener<T>) listener).update(item); } catch (Exception e) { e.printStackTrace(); } } } } finally { keyEntry.entryLock.unlock(); } } /* * (non-Javadoc) * * @see * net.xeoh.plugins.informationbroker.InformationBroker#subscribe(net.xeoh.plugins * .informationbroker.InformationItemIdentifier, * net.xeoh.plugins.informationbroker.InformationListener, * net.xeoh.plugins.informationbroker.options.SubscribeOption[]) */ @SuppressWarnings({ "unchecked" }) @Override public <T> void subscribe(Class<? extends InformationItem<T>> id, InformationListener<T> listener, SubscribeOption... options) { if (id == null || listener == null) return; // Get our options final OptionUtils<SubscribeOption> ou = new OptionUtils<SubscribeOption>(options); final boolean instantRequest = ou.contains(OptionInstantRequest.class); // Get the meta information for the requested id final KeyEntry keyEntry = getKeyEntry(id); // Now process and add the entry try { keyEntry.entryLock.lock(); // Only add the listener if we don't have an instant request. if (!instantRequest) keyEntry.allListeners.add(listener); // If there has been a channel established, use that one if (keyEntry.lastItem != null) { ((InformationListener<Object>) listener).update(keyEntry.lastItem); } } finally { keyEntry.entryLock.unlock(); } } /* * (non-Javadoc) * * @see * net.xeoh.plugins.informationbroker.InformationBroker#unsubscribe(net.xeoh.plugins * .informationbroker.InformationListener) */ @Override public void unsubscribe(InformationListener<?> listener) { if (listener == null) return; // Well, not the fastest and best solution given this interface. this.itemsLock.lock(); try { final Set<Class<? extends InformationItem<?>>> keySet = this.items.keySet(); for (Class<? extends InformationItem<?>> uri : keySet) { final KeyEntry keyEntry = this.items.get(uri); keyEntry.entryLock.lock(); try { keyEntry.allListeners.remove(listener); } finally { keyEntry.entryLock.unlock(); } } } finally { this.itemsLock.unlock(); } } /** * Returns the key entry of a given ID. * * @param id The ID to request * @return The key entry. */ private KeyEntry getKeyEntry(Class<? extends InformationItem<?>> id) { KeyEntry keyEntry = null; this.itemsLock.lock(); try { keyEntry = this.items.get(id); if (keyEntry == null) { keyEntry = new KeyEntry(); this.items.put(id, keyEntry); } } finally { this.itemsLock.unlock(); } return keyEntry; } }
100json-jspf
modules/core/src/net/xeoh/plugins/informationbroker/impl/InformationBrokerImpl.java
Java
bsd
7,746
/* * InformationBrokerUtil.java * * Copyright (c) 2009, Ralf Biedert All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package net.xeoh.plugins.informationbroker.util; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicReference; import net.xeoh.plugins.base.util.VanillaPluginUtil; import net.xeoh.plugins.informationbroker.InformationBroker; import net.xeoh.plugins.informationbroker.InformationItem; import net.xeoh.plugins.informationbroker.InformationListener; import net.xeoh.plugins.informationbroker.options.PublishOption; import net.xeoh.plugins.informationbroker.options.SubscribeOption; import net.xeoh.plugins.informationbroker.options.subscribe.OptionInstantRequest; /** * Helper functions for the {@link InformationBroker} interface. The util uses the * embedded * interface to provide more convenience features. * * @author Ralf Biedert * @see InformationBroker */ public class InformationBrokerUtil extends VanillaPluginUtil<InformationBroker> implements InformationBroker { /** * Creates a new InformationBrokerUtil. * * @param broker */ public InformationBrokerUtil(InformationBroker broker) { super(broker); } /** * Returns the value for the given id or <code>dflt</code> if neither the key * nor the default was present. For example, to retrieve the current user name * and to get "unknown" if none was present, you could write:<br/> * <br/> * * <code> * get(UserName.class, "unknown"); * </code><br/> * <br/> * * @param <T> The type of the return value. * @param id The ID to request. * @param dflt The default value to return if no item was found. * @return Returns the requested item, a default if the item was not present or null * in case neither was found. */ public <T> T get(Class<? extends InformationItem<T>> id, T... dflt) { final AtomicReference<T> o = new AtomicReference<T>(); this.object.subscribe(id, new InformationListener<T>() { @Override public void update(T item) { o.set(item); } }, new OptionInstantRequest()); final T rval = o.get(); // Now check if we have a sensible return value or not, and return the default // if we must if (rval == null && dflt.length > 0) return dflt[0]; return rval; } /** * Subscribes to a number of items. The listener is called only when all items are * available or when all were available and a single item changed. For example, to * subscribe to two items you could write:<br/> * <br/> * <code> * subscribeAll(listener, ItemA.class, ItemB.class); * </code><br/> * <br/> * * Use <code>get()</code> from inside the listener to obtain the specific items. * * @param listener The listener called when all prerequisites are met. Note that the * listener will be called <b>without</b> any object (i.e., <code>item</code> is * <code>null</code>). You must use the broker's <code>get()</code> function. * @param all All IDs we should subscribe to. */ @SuppressWarnings("unchecked") public void subscribeAll(final InformationListener<Void> listener, final Class<?>... all) { if (listener == null || all == null || all.length == 0) return; // Stores all items we received so far final Map<Class<?>, AtomicReference<Object>> map = new ConcurrentHashMap<Class<?>, AtomicReference<Object>>(); for (final Class<?> c : all) { final Class<? extends InformationItem<Object>> cc = (Class<? extends InformationItem<Object>>) c; this.object.subscribe(cc, new InformationListener<Object>() { @Override public void update(Object item) { // First update the map map.put(cc, new AtomicReference<Object>(item)); // then check if we are complete if (map.keySet().size() == all.length) { listener.update(null); } } }); } } @Override public <T> void publish(Class<? extends InformationItem<T>> channel, T item, PublishOption... options) { // TODO Auto-generated method stub } @Override public <T> void subscribe(Class<? extends InformationItem<T>> channel, InformationListener<T> listener, SubscribeOption... options) { // TODO Auto-generated method stub } @Override public void unsubscribe(InformationListener<?> listener) { // TODO Auto-generated method stub } }
100json-jspf
modules/core/src/net/xeoh/plugins/informationbroker/util/InformationBrokerUtil.java
Java
bsd
6,319
/** * Utils for various {@link net.xeoh.plugins.informationbroker.InformationBroker} classes and objects. * * @since 1.0 */ package net.xeoh.plugins.informationbroker.util;
100json-jspf
modules/core/src/net/xeoh/plugins/informationbroker/util/package-info.java
Java
bsd
180
/* * Main.java * * Copyright (c) 2008, Ralf Biedert All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package quickstart; import java.io.File; import java.net.MalformedURLException; import net.xeoh.plugins.base.PluginManager; import net.xeoh.plugins.base.impl.PluginManagerFactory; import quickstart.outputservice.OutputService; /** * @author rb * */ public class Main { /** * @param args * @throws MalformedURLException */ public static void main(final String[] args) throws MalformedURLException { /* * The is the only time you have to access a class directly. Just returns the * Plugin manager. */ final PluginManager pmf = PluginManagerFactory.createPluginManager(); /* * Add plugins from somewhere. Be sure to put *the right path* in here. This * method may be called multiple times. If you plan to deliver your application * replace bin/ with for example myplugins.jar */ pmf.addPluginsFrom(new File("bin/").toURI()); /* * Thats it. Technically all plugins have now been loaded and are running. If you * would like to retrieve one, do it like this: */ final OutputService plugin = pmf.getPlugin(OutputService.class); plugin.doSomething(); } }
100json-jspf
modules/core/example/quickstart/Main.java
Java
bsd
2,851
/* * TestPlugin.java * * Copyright (c) 2008, Ralf Biedert All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package quickstart.outputservice; import net.xeoh.plugins.base.Plugin; /** * Just define your interface as you would do normally. The only thing you have to do: * extend Plugin. * */ public interface OutputService extends Plugin { /** * */ public void doSomething(); }
100json-jspf
modules/core/example/quickstart/outputservice/OutputService.java
Java
bsd
1,892
/* * TestPluginImpl.java * * Copyright (c) 2008, Ralf Biedert All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package quickstart.outputservice.impl; import net.xeoh.plugins.base.annotations.PluginImplementation; import net.xeoh.plugins.base.annotations.events.Init; import net.xeoh.plugins.base.annotations.injections.InjectPlugin; import quickstart.dataservice.DataService; import quickstart.outputservice.OutputService; /** * Now a bit more complex than the DataService: we require that class to be able to work. */ @PluginImplementation public class OutputServiceImpl implements OutputService { /** * Even more magic. If the service has been loaded * before this plugin, inject it. */ @InjectPlugin(isOptional = true) public DataService service; public void doSomething() { System.out.println(this.service.provideData()); } /** * Magic. Will be called after the plugin is fully loaded. */ @Init public void init() { System.out.println("Output Service online."); } }
100json-jspf
modules/core/example/quickstart/outputservice/impl/OutputServiceImpl.java
Java
bsd
2,566
package quickstart.outputservice.impl; import net.xeoh.plugins.base.annotations.PluginImplementation; import net.xeoh.plugins.base.annotations.events.Init; import net.xeoh.plugins.base.annotations.injections.InjectPlugin; import quickstart.dataservice.DataService; import quickstart.outputservice.OutputService; /** * @author rb * */ @PluginImplementation public class TheOtherOutputServiceImpl implements OutputService { /** * Even more magic. If the service has been loaded (ensured by the requiredPlugins) * before this plugin, inject it. */ @InjectPlugin(requiredCapabilities = { "plugin:DataService" }) public DataService service; public void doSomething() { System.out.println(this.service.provideData() + " another one bites the dust"); } /** * Magic. Will be called after the plugin is fully loaded. */ @Init public void initA() { System.out.println("This time I AM THERE"); } /** * Magic. Will be called after the plugin is fully loaded. */ @Init public void initB() { System.out.println("It's a little longer"); } }
100json-jspf
modules/core/example/quickstart/outputservice/impl/TheOtherOutputServiceImpl.java
Java
bsd
1,188
/* * DataService.java * * Copyright (c) 2008, Ralf Biedert All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package quickstart.dataservice; import net.xeoh.plugins.base.Plugin; /** * Just define your interface as you would do normally. The only thing you have to do: * extend Plugin. * */ public interface DataService extends Plugin { /** * @return . */ public String provideData(); }
100json-jspf
modules/core/example/quickstart/dataservice/DataService.java
Java
bsd
1,900
/* * TestPluginImpl.java * * Copyright (c) 2008, Ralf Biedert All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package quickstart.dataservice.impl; import net.xeoh.plugins.base.annotations.PluginImplementation; import net.xeoh.plugins.base.annotations.configuration.IsDisabled; import quickstart.dataservice.DataService; /** * One implementation of the DataServiceImpl plugin. The following annotation does all the * magic. */ @IsDisabled @PluginImplementation public class DataServiceImpl implements DataService { public String provideData() { return "Wooohoooo :-)"; } }
100json-jspf
modules/core/example/quickstart/dataservice/impl/DataServiceImpl.java
Java
bsd
2,091
/* * Main.java * * Copyright (c) 2008, Ralf Biedert All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package multipleplugins; import java.io.File; import java.net.MalformedURLException; import java.util.Collection; import net.xeoh.plugins.base.PluginManager; import net.xeoh.plugins.base.impl.PluginManagerFactory; import net.xeoh.plugins.base.util.PluginManagerUtil; import quickstart.outputservice.OutputService; /** * @author rb * */ public class Main { /** * @param args * @throws MalformedURLException */ public static void main(final String[] args) throws MalformedURLException { /* * The is the only time you have to access a class directly. Just returns the * Plugin manager. */ final PluginManager pmf = PluginManagerFactory.createPluginManager(); /* * Add plugins from somewhere. Be sure to put *the right path* in here. This * method may be called multiple times. If you plan to deliver your application * replace bin/ with for example myplugins.jar */ pmf.addPluginsFrom(new File("target/test-classes/").toURI()); /* * Obtain multiple plugins */ PluginManagerUtil pmu = new PluginManagerUtil(pmf); final Collection<OutputService> plugins = pmu.getPlugins(OutputService.class); /* * Do something */ for (final OutputService s : plugins) { s.doSomething(); } } }
100json-jspf
modules/core/example/multipleplugins/Main.java
Java
bsd
3,030
/* * RemoteAPIJSON * * Copyright (c) 2010, Ralf Biedert All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package net.xeoh.plugins.remote; /** * Allows the network export of plugins.<br/> <br/> * * @author Ralf Biedert * */ public interface RemoteAPIJSON extends RemoteAPI { // }
100json-jspf
modules/plugins/remote.json/src/net/xeoh/plugins/remote/RemoteAPIJSON.java
Java
bsd
1,776
/* * RemoteAPIImpl.java * * Copyright (c) 2009, Ralf Biedert All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package net.xeoh.plugins.remote.impl.json; import java.io.IOException; import java.lang.reflect.Array; import java.net.ServerSocket; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Random; import java.util.logging.Logger; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import net.xeoh.plugins.base.Plugin; import net.xeoh.plugins.base.PluginConfiguration; import net.xeoh.plugins.base.annotations.Capabilities; import net.xeoh.plugins.base.annotations.PluginImplementation; import net.xeoh.plugins.base.annotations.events.Shutdown; import net.xeoh.plugins.base.annotations.injections.InjectPlugin; import net.xeoh.plugins.base.annotations.meta.Author; import net.xeoh.plugins.remote.ExportResult; import net.xeoh.plugins.remote.PublishMethod; import net.xeoh.plugins.remote.RemoteAPI; import net.xeoh.plugins.remote.RemoteAPIJSON; import net.xeoh.plugins.remote.util.internal.PluginExport; import net.xeoh.plugins.remote.util.vanilla.ExportResultImpl; import net.xeoh.plugins.remotediscovery.RemoteDiscovery; import org.apache.bcel.Repository; import org.apache.bcel.classfile.Constant; import org.apache.bcel.classfile.ConstantClass; import org.apache.bcel.classfile.ConstantPool; import org.apache.bcel.classfile.ConstantUtf8; import org.apache.bcel.classfile.JavaClass; import org.jabsorb.JSONRPCBridge; import org.jabsorb.JSONRPCServlet; import org.mortbay.jetty.Server; import org.mortbay.jetty.servlet.Context; import org.mortbay.jetty.servlet.ServletHolder; /** * Exports plugins to be accessible by JavaScript. * * FIXME: This class leaks memory. The Bridge should be cleared from time to time ... * * @author Thomas Lottermann */ @Author(name = "Thomas Lottermann") @PluginImplementation public class RemoteAPIImpl implements RemoteAPIJSON { /** Log events */ final Logger logger = Logger.getLogger(this.getClass().getName()); /** */ @InjectPlugin public PluginConfiguration configuration; /** Base URL to return (without trailing slash) */ private String location; /** Jetty reference */ Server server = null; /** JSON Bidge */ JSONRPCBridge bridge = null; /** Classes already registered to the bridge */ Collection<Class<?>> registered = new ArrayList<Class<?>>(); /** */ @InjectPlugin public RemoteDiscovery discovery; /* (non-Javadoc) * @see net.xeoh.plugins.remote.RemoteAPI#exportPlugin(net.xeoh.plugins.base.Plugin) */ public synchronized ExportResult exportPlugin(final Plugin plugin) { if (this.server == null) { initServer(); } String originalName = PluginExport.getExportName(plugin); String className = PluginExport.getHashedName(plugin); this.bridge.registerObject(className, plugin); // Set to true for powerful exports and memory leaks, or false if you need neither feature. if (true) { registerCallableRecursively(this.bridge, this.registered, plugin.getClass(), 3); } // Return browser-compatible URI + className URI uri = createURI(this.location + "/" + className); this.logger.info("Exported " + originalName + " at " + uri); // Announce the plugin this.discovery.announcePlugin(plugin, getPublishMethod(), uri); return new ExportResultImpl(uri); } /** * Returns all related classes * * @param start * @return */ private static Collection<Class<?>> getAllRelatedClasses(Class<?> start) { List<Class<?>> rval = new ArrayList<Class<?>>(); JavaClass lookupClass; // In case the class fails, return empty. try { lookupClass = Repository.lookupClass(start); } catch (ClassNotFoundException e) { e.printStackTrace(); return rval; } ConstantPool constantPool = lookupClass.getConstantPool(); int length = constantPool.getLength(); for (int i = 0; i < length; i++) { Constant constant = constantPool.getConstant(i); if (constant instanceof ConstantClass) { ConstantClass cc = (ConstantClass) constant; ConstantUtf8 constant2 = (ConstantUtf8) constantPool.getConstant(cc.getNameIndex()); // In case a subclass fails, skip, but print warning. try { String toLoad = constant2.getBytes().replace('/', '.'); if (toLoad.contains("[")) continue; Class<?> forName = Class.forName(toLoad); rval.add(forName); } catch (ClassNotFoundException e) { e.printStackTrace(); } } } return rval; } /** * Recursively registers all return types to be accessible, down to the java.lang.Class. * By calling this function you ensure a) that all returned objects are accessible * from JavaScript, no matter how nested they are and b) memory leaks. * * @param brdge * @param reg * @param start */ private static void registerCallableRecursively(JSONRPCBridge brdge, Collection<Class<?>> reg, Class<?> start, int levelOfRecursion) { if (levelOfRecursion == 0) return; try { Collection<Class<?>> allRelatedClasses = getAllRelatedClasses(start); //= start.getDeclaredClasses(); // Method[] methods = start.getMethods(); //for (Method method : methods) { for (Class<?> returnType : allRelatedClasses) { //Class<?> returnType = method.getReturnType(); if (reg.contains(returnType)) continue; // I think these classes are already serialized by JSON, so don't make them accessible. if (returnType.equals(String.class)) continue; if (returnType.equals(Void.class)) continue; if (returnType.equals(Float.class)) continue; if (returnType.equals(Double.class)) continue; if (returnType.equals(Integer.class)) continue; if (returnType.equals(ArrayList.class)) continue; if (returnType.equals(Array.class)) continue; reg.add(returnType); brdge.registerCallableReference(returnType); registerCallableRecursively(brdge, reg, returnType, levelOfRecursion - 1); } } catch (Exception e1) { e1.printStackTrace(); } } /* (non-Javadoc) * @see net.xeoh.plugins.remote.RemoteAPI#getPublishMethod() */ public PublishMethod getPublishMethod() { return PublishMethod.JSON; } /* (non-Javadoc) * @see net.xeoh.plugins.remote.RemoteAPI#getRemoteProxy(java.net.URL, java.lang.Class) */ public <R extends Plugin> R getRemoteProxy(final URI url, final Class<R> remote) { this.logger.warning("JavaScript Plugin was requested to return remote proxy for an JSON instance. This does not work. Sorry."); return null; } /* (non-Javadoc) * @see net.xeoh.plugins.remote.RemoteAPI#unexportPlugin(net.xeoh.plugins.base.Plugin) */ public void unexportPlugin(final Plugin plugin) { // TODO Auto-generated method stub } /** * Call this once to bring up the server */ private void initServer() { String _servername = this.configuration.getConfiguration(RemoteAPI.class, "export.server"); String servername = _servername == null ? "127.0.0.1" : _servername; String _port = this.configuration.getConfiguration(RemoteAPIImpl.class, "export.port"); int port = getFreePort(); if (_port != null) { port = Integer.parseInt(_port); } // Set the location and server this.location = "http://" + servername + ":" + port; this.server = new Server(port); this.bridge = new JSONRPCBridge(); //JSONRPCBridge.getGlobalBridge(); // Create context and our specially hacked jsonrpc servlet. final Context context = new Context(this.server, "/", Context.SESSIONS); final JSONRPCServlet servlet = new JSONRPCServlet() { /** */ private static final long serialVersionUID = 7129007024968608285L; @Override public void service(HttpServletRequest arg0, HttpServletResponse arg1) throws IOException { // Register our global bridge, so jabsorb does not complain about // sessionless globals final HttpSession session = arg0.getSession(); session.setAttribute("JSONRPCBridge", RemoteAPIImpl.this.bridge); super.service(arg0, arg1); } }; final ServletHolder servletholder = new ServletHolder(servlet); servletholder.setInitParameter("gzip_threshold", "200"); context.addServlet(servletholder, "/*"); try { this.server.start(); } catch (final Exception e) { e.printStackTrace(); } } /** * Internally used to create an URL without 'try' * * @param string * @return */ URI createURI(final String string) { try { return new URI(string); } catch (URISyntaxException e) { e.printStackTrace(); } return null; } /** * @return */ private static int getFreePort() { try { final ServerSocket serverSocket = new ServerSocket(0); final int port = serverSocket.getLocalPort(); serverSocket.close(); return port; } catch (IOException e) { e.printStackTrace(); } return 1025 + new Random().nextInt(50000); } /** * JSPF Shutdown hook. */ @Shutdown public void shutdown() { if (this.server == null) return; try { this.server.stop(); } catch (Exception e) { e.printStackTrace(); } } /** * @return . */ @Capabilities public String[] getCapabilites() { return new String[] { "json", "JSON" }; } }
100json-jspf
modules/plugins/remote.json/src/net/xeoh/plugins/remote/impl/json/RemoteAPIImpl.java
Java
bsd
12,182
package net.xeoh.plugins.remote.impl.javascript; import org.directwebremoting.extend.AbstractCreator; import org.directwebremoting.extend.Creator; /** * Used to put in our own objects. * * @author Thomas Lottermann * */ public class ObjectCreator extends AbstractCreator implements Creator { Object instance; /** * @param object */ public ObjectCreator(final Object object) { this.instance = object; setJavascript(this.instance.getClass().getSimpleName()); } /** * Gets the name of the class to create. * @return The name of the class to create */ public String getClassName() { return this.instance.getClass().getSimpleName(); } public Object getInstance() { return this.instance; } public Class<?> getType() { return this.instance.getClass(); } }
100json-jspf
modules/plugins/remote.javascript/src/net/xeoh/plugins/remote/impl/javascript/ObjectCreator.java
Java
bsd
912
/* * RemoteAPIImpl.java * * Copyright (c) 2009, Ralf Biedert All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package net.xeoh.plugins.remote.impl.javascript; import java.io.IOException; import java.net.ServerSocket; import java.net.URI; import java.net.URISyntaxException; import java.util.Random; import java.util.logging.Logger; import net.xeoh.plugins.base.Plugin; import net.xeoh.plugins.base.PluginConfiguration; import net.xeoh.plugins.base.annotations.Capabilities; import net.xeoh.plugins.base.annotations.PluginImplementation; import net.xeoh.plugins.base.annotations.events.Shutdown; import net.xeoh.plugins.base.annotations.injections.InjectPlugin; import net.xeoh.plugins.base.annotations.meta.Author; import net.xeoh.plugins.remote.ExportResult; import net.xeoh.plugins.remote.PublishMethod; import net.xeoh.plugins.remote.RemoteAPIJavaScript; import net.xeoh.plugins.remote.util.internal.PluginExport; import net.xeoh.plugins.remote.util.vanilla.ExportResultImpl; import net.xeoh.plugins.remotediscovery.RemoteDiscovery; import org.directwebremoting.convert.BeanConverter; import org.directwebremoting.extend.ConverterManager; import org.directwebremoting.extend.CreatorManager; import org.directwebremoting.servlet.DwrServlet; import org.mortbay.jetty.Server; import org.mortbay.jetty.servlet.Context; import org.mortbay.jetty.servlet.ServletHolder; /** * Exports plugins to be accessible by JavaScript. * * @author Thomas Lottermann */ @Author(name = "Thomas Lottermann") @PluginImplementation public class RemoteAPIImpl implements RemoteAPIJavaScript { /** Log events */ final Logger logger = Logger.getLogger(this.getClass().getName()); /** */ @InjectPlugin public PluginConfiguration configuration; /** Accepts objects */ CreatorManager creatorManager; /** Converts objects and variables */ ConverterManager converterManager; /** Base URL to return (without trailing slash) */ private String location; /** Jetty reference */ Server server = null; /** */ @InjectPlugin public RemoteDiscovery discovery; /* (non-Javadoc) * @see net.xeoh.plugins.remote.RemoteAPI#exportPlugin(net.xeoh.plugins.base.Plugin) */ public synchronized ExportResult exportPlugin(final Plugin plugin) { if (this.server == null) { initServer(); } // Wrap object final ObjectCreator creator = new ObjectCreator(plugin); // Register object to manager this.creatorManager.addCreator(creator.getClassName(), creator); //this.converterManager.addConverter("java.util.concurrent.locks.ReentrantLock", new BeanConverter()); //FIXME: Doesn't work. Maybe get Converters by inspection at export time. this.converterManager.addConverter("*", new BeanConverter()); this.converterManager.addConverter("com.*", new BeanConverter()); this.converterManager.addConverter("org.*", new BeanConverter()); this.converterManager.addConverter("de.*", new BeanConverter()); this.converterManager.addConverter("uk.*", new BeanConverter()); this.converterManager.addConverter("java.*", new BeanConverter()); this.converterManager.addConverter("javax.*", new BeanConverter()); this.converterManager.addConverter("net.*", new BeanConverter()); // Return browser-compatible URL URI uri = createURI(this.location + "/test/" + PluginExport.getExportName(plugin)); this.logger.info("Plugin exported as JavaScript to " + uri); // Announce the plugin this.discovery.announcePlugin(plugin, getPublishMethod(), uri); return new ExportResultImpl(uri); } /* (non-Javadoc) * @see net.xeoh.plugins.remote.RemoteAPI#getPublishMethod() */ public PublishMethod getPublishMethod() { return PublishMethod.JAVASCRIPT; } /* (non-Javadoc) * @see net.xeoh.plugins.remote.RemoteAPI#getRemoteProxy(java.net.URL, java.lang.Class) */ public <R extends Plugin> R getRemoteProxy(final URI url, final Class<R> remote) { this.logger.warning("JavaScript Plugin was requested to return remote proxy for an JavaScript instance. This does not work. Sorry."); return null; } /* (non-Javadoc) * @see net.xeoh.plugins.remote.RemoteAPI#unexportPlugin(net.xeoh.plugins.base.Plugin) */ public void unexportPlugin(final Plugin plugin) { // TODO Auto-generated method stub } /** * Call this once to bring up the server */ private void initServer() { String _servername = this.configuration.getConfiguration(RemoteAPIImpl.class, "export.server"); String servername = _servername == null ? "127.0.0.1" : _servername; String _port = this.configuration.getConfiguration(RemoteAPIImpl.class, "port"); int port = getFreePort(); if (_port != null) { port = Integer.parseInt(_port); } // Set the location and server this.location = "http://" + servername + ":" + port; this.server = new Server(port); final Context context = new Context(this.server, "/", Context.SESSIONS); final DwrServlet servlet = new DwrServlet(); final ServletHolder servletholder = new ServletHolder(servlet); servletholder.setInitParameter("debug", "true"); servletholder.setInitParameter("activeReverseAjaxEnabled", "true"); servletholder.setInitParameter("initApplicationScopeCreatorsAtStartup", "true"); servletholder.setInitParameter("jsonRpcEnabled", "true"); servletholder.setInitParameter("jsonpEnabled", "true"); servletholder.setInitParameter("preferDataUrlSchema", "false"); servletholder.setInitParameter("maxWaitAfterWrite", "-1"); servletholder.setInitParameter("jsonpEnabled", "true"); servletholder.setInitParameter("allowScriptTagRemoting", "true"); servletholder.setInitParameter("crossDomainSessionSecurity", "false"); servletholder.setInitParameter("overridePath", this.location); servletholder.setInitParameter("allowGetForSafariButMakeForgeryEasier", "true"); context.addServlet(servletholder, "/*"); try { this.server.start(); } catch (final Exception e) { e.printStackTrace(); } this.creatorManager = servlet.getContainer().getBean(CreatorManager.class); this.converterManager = servlet.getContainer().getBean(ConverterManager.class); } /** * @return */ private static int getFreePort() { try { final ServerSocket serverSocket = new ServerSocket(0); final int port = serverSocket.getLocalPort(); serverSocket.close(); return port; } catch (IOException e) { e.printStackTrace(); } return 1025 + new Random().nextInt(50000); } /** * Internally used to create an URL without 'try' * * @param string * @return */ URI createURI(final String string) { try { return new URI(string); } catch (URISyntaxException e) { e.printStackTrace(); } return null; } /** * JSPF Shutdown hook. */ @Shutdown public void shutdown() { if (this.server == null) return; try { this.server.stop(); } catch (Exception e) { e.printStackTrace(); } } /** * @return . */ @Capabilities public String[] getCapabilites() { return new String[] { "javascript", "JAVASCRIPT" }; } }
100json-jspf
modules/plugins/remote.javascript/src/net/xeoh/plugins/remote/impl/javascript/RemoteAPIImpl.java
Java
bsd
9,148
/* * RemoteAPIJavaScript * * Copyright (c) 2010, Ralf Biedert All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package net.xeoh.plugins.remote; /** * Allows the network export of plugins.<br/> <br/> * * @author Ralf Biedert * */ public interface RemoteAPIJavaScript extends RemoteAPI { // }
100json-jspf
modules/plugins/remote.javascript/src/net/xeoh/plugins/remote/RemoteAPIJavaScript.java
Java
bsd
1,788
/* * RemoteAPIImpl.java * * Copyright (c) 2008, Ralf Biedert All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package net.xeoh.plugins.remote.impl.ermi; import java.io.IOException; import java.net.InetAddress; import java.net.ServerSocket; import java.net.URI; import java.net.URISyntaxException; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorCompletionService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.logging.Logger; import net.xeoh.plugins.base.Plugin; import net.xeoh.plugins.base.PluginConfiguration; import net.xeoh.plugins.base.annotations.Capabilities; import net.xeoh.plugins.base.annotations.PluginImplementation; import net.xeoh.plugins.base.annotations.events.Init; import net.xeoh.plugins.base.annotations.events.Shutdown; import net.xeoh.plugins.base.annotations.injections.InjectPlugin; import net.xeoh.plugins.base.annotations.meta.Author; import net.xeoh.plugins.base.util.PluginConfigurationUtil; import net.xeoh.plugins.remote.ExportResult; import net.xeoh.plugins.remote.PublishMethod; import net.xeoh.plugins.remote.RemoteAPI; import net.xeoh.plugins.remote.RemoteAPIERMI; import net.xeoh.plugins.remote.util.internal.PluginExport; import net.xeoh.plugins.remote.util.vanilla.ExportResultImpl; import net.xeoh.plugins.remotediscovery.RemoteDiscovery; import net.xeoh.plugins.remotediscovery.util.RemoteAPIDiscoveryUtil; import org.freshvanilla.rmi.Proxies; import org.freshvanilla.rmi.VanillaRmiServer; /** * Essence RMI Implementation. Nice framework ... * * @author Ralf Biedert * */ @Author(name = "Ralf Biedert") @PluginImplementation public class RemoteAPIImpl implements RemoteAPIERMI { /** */ @InjectPlugin public PluginConfiguration configuration; /** */ @InjectPlugin public PluginConfiguration facade; private String exportServer = "127.0.0.1"; /** Where this server can be found */ private final String protocol = "ermi://"; /** Port to start using */ //private final int START_PORT = 22719; /** Needed for shutdown. */ final List<VanillaRmiServer<Plugin>> allServer = new ArrayList<VanillaRmiServer<Plugin>>(); /** Log events */ final Logger logger = Logger.getLogger(this.getClass().getName()); /** */ @InjectPlugin public RemoteDiscovery discovery; /** */ private RemoteAPIDiscoveryUtil remoteAPIDiscoveryUtil; /* (non-Javadoc) * @see net.xeoh.plugins.remote.RemoteAPI#exportPlugin(net.xeoh.plugins.base.Plugin) */ public ExportResult exportPlugin(final Plugin plugin) { // Get some (very) random start port. final int startInt = getFreePort(); //this.START_PORT + r.nextInt(10000); for (int d = 0; d < 10; d++) { final URI exportPlugin = exportPlugin(plugin, startInt + d); if (exportPlugin != null) return new ExportResultImpl(exportPlugin); } return null; } /* (non-Javadoc) * @see net.xeoh.plugins.remote.RemoteAPIERMI#exportPlugin(net.xeoh.plugins.base.Plugin, int) */ public URI exportPlugin(final Plugin plugin, final int port) { // Try to set the servername to something sensible String servername = this.configuration.getConfiguration(RemoteAPI.class, "export.server"); if (servername == null) { servername = this.exportServer; } // Sanity checks if (plugin == null) { this.logger.warning("Cannot export plugin, as it is null"); return null; } final String name = PluginExport.getExportName(plugin); try { final VanillaRmiServer<Plugin> newServer = Proxies.newServer(name, port, plugin); synchronized (this.allServer) { this.allServer.add(newServer); } } catch (final IOException e) { this.logger.warning("Unable to export the plugin, Proxes.newServer excepted ..."); e.printStackTrace(); return null; } // Return a proper URL URI createURI = createURI(this.protocol + servername + ":" + port + "/" + name); // Announce the plugin this.discovery.announcePlugin(plugin, getPublishMethod(), createURI); return createURI; } /** * Returns the capabilities of this plugin. * * @return . */ @Capabilities public String[] getCapabilites() { return new String[] { "ermi", "ERMI" }; } /* (non-Javadoc) * @see net.xeoh.plugins.remote.RemoteAPI#getPublishMethod() */ public PublishMethod getPublishMethod() { return PublishMethod.ERMI; } /* (non-Javadoc) * @see net.xeoh.plugins.remote.RemoteAPI#getRemoteProxy(java.net.URI, java.lang.Class) */ @SuppressWarnings( { "unchecked", "boxing" }) public <R extends Plugin> R getRemoteProxy(final URI url, final Class<R> remote) { // In case this is a remote url, let the discoverer work. if (this.remoteAPIDiscoveryUtil.isDiscoveryURI(url)) { return this.remoteAPIDiscoveryUtil.getRemoteProxy(url, remote); } if (url == null) { this.logger.warning("URL was null. Cannot get a proxy for that, returning null."); return null; } this.logger.info("Trying to retrieve remote proxy for " + url); final String address = url.getHost() + ":" + url.getPort(); final String name = url.getPath().substring(1); final PluginConfigurationUtil pcu = new PluginConfigurationUtil(this.configuration); // Obtain timeout when creating proxy final int timeout = pcu.getInt(RemoteAPI.class, "proxy.timeout", 500); // Tricky part, obtaining the proxy works fast, but we only know everything works fine after the first call, // so lets try that ... final R newClient = Proxies.newClient(name, address, remote); // Execute collection asynchronously final ExecutorCompletionService<String> ecs = new ExecutorCompletionService(Executors.newCachedThreadPool()); ecs.submit(new Callable<String>() { public String call() throws Exception { return newClient.toString(); } }); // Wait at most half a second (TODO: Make this configurable) try { final Future<String> poll = ecs.poll(timeout, TimeUnit.MILLISECONDS); if (poll == null) return null; poll.get(timeout, TimeUnit.MILLISECONDS); return newClient; } catch (final InterruptedException e) { this.logger.fine("Error while waiting for a getRemoteProxy() result"); e.printStackTrace(); } catch (final ExecutionException e) { e.printStackTrace(); } catch (final TimeoutException e) { e.printStackTrace(); } return null; } /** */ @Init public void init() { // Try to obtain a proper address try { this.exportServer = InetAddress.getLocalHost().getHostAddress(); } catch (final UnknownHostException e) { // } this.remoteAPIDiscoveryUtil = new RemoteAPIDiscoveryUtil(this.discovery, this); } /** */ @Shutdown public void shutdown() { synchronized (this.allServer) { for (final VanillaRmiServer<Plugin> server : this.allServer) { server.close(); } } } /* (non-Javadoc) * @see net.xeoh.plugins.remote.RemoteAPI#unexportPlugin(net.xeoh.plugins.base.Plugin) */ public void unexportPlugin(final Plugin plugin) { // Implement this } /** * Internally used to create an URL without 'try' * * @param string * @return */ URI createURI(final String string) { try { return new URI(string); } catch (URISyntaxException e) { e.printStackTrace(); } return null; } /** * @return */ private static int getFreePort() { try { final ServerSocket serverSocket = new ServerSocket(0); final int port = serverSocket.getLocalPort(); serverSocket.close(); return port; } catch (IOException e) { e.printStackTrace(); } return 1025 + new Random().nextInt(50000); } }
100json-jspf
modules/plugins/remote.ermi/src/net/xeoh/plugins/remote/impl/ermi/RemoteAPIImpl.java
Java
bsd
10,437
/* * RemoteAPI.java * * Copyright (c) 2008, Ralf Biedert All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package net.xeoh.plugins.remote; import java.net.URI; import net.xeoh.plugins.base.Plugin; /** * Allows the network export of plugins.<br/> <br/> * * Please note there may be constraints on the plugin usage depending on the remote type. * For example, XMLRPC might have problems with null or void types. * * @author Ralf Biedert * */ public interface RemoteAPIERMI extends RemoteAPI { /** * Exports a plugin over the network at a given port. * * @param plugin * @param port * @return The URL where the plugin is accessible */ public URI exportPlugin(Plugin plugin, int port); }
100json-jspf
modules/plugins/remote.ermi/src/net/xeoh/plugins/remote/RemoteAPIERMI.java
Java
bsd
2,236
/* * RemoteAPILipe.java * * Copyright (c) 2009, Ralf Biedert All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package net.xeoh.plugins.remote; /** * @author rb * */ public interface RemoteAPILipe extends RemoteAPI { // }
100json-jspf
modules/plugins/remote.lipermi/src/net/xeoh/plugins/remote/RemoteAPILipe.java
Java
bsd
1,684
/* * RemoteAPIImpl.java * * Copyright (c) 2008, Ralf Biedert All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package net.xeoh.plugins.remote.impl.lipermi; import java.io.IOException; import java.net.InetAddress; import java.net.ServerSocket; import java.net.URI; import java.net.URISyntaxException; import java.net.UnknownHostException; import java.util.Random; import java.util.logging.Logger; import net.sf.lipermi.exception.LipeRMIException; import net.sf.lipermi.handler.CallHandler; import net.sf.lipermi.net.Client; import net.sf.lipermi.net.Server; import net.xeoh.plugins.base.Plugin; import net.xeoh.plugins.base.PluginConfiguration; import net.xeoh.plugins.base.annotations.Capabilities; import net.xeoh.plugins.base.annotations.PluginImplementation; import net.xeoh.plugins.base.annotations.events.Init; import net.xeoh.plugins.base.annotations.events.Shutdown; import net.xeoh.plugins.base.annotations.injections.InjectPlugin; import net.xeoh.plugins.base.util.PluginConfigurationUtil; import net.xeoh.plugins.base.util.PluginUtil; import net.xeoh.plugins.remote.ExportResult; import net.xeoh.plugins.remote.PublishMethod; import net.xeoh.plugins.remote.RemoteAPI; import net.xeoh.plugins.remote.RemoteAPILipe; import net.xeoh.plugins.remote.util.internal.PluginExport; import net.xeoh.plugins.remote.util.vanilla.ExportResultImpl; import net.xeoh.plugins.remotediscovery.RemoteDiscovery; import net.xeoh.plugins.remotediscovery.util.RemoteAPIDiscoveryUtil; /** * Essence RMI Implementation. Nice framework ... * * @author Ralf Biedert * */ @PluginImplementation public class RemoteAPIImpl implements RemoteAPILipe { /** */ @InjectPlugin public PluginConfiguration configuration; /** */ @InjectPlugin public PluginConfiguration facade; /** */ private String exportServer = "127.0.0.1"; /** Where this server can be found */ private final String protocol = "lipe://"; /** Port to start using */ //private final int START_PORT = 22719; /** Log events */ final Logger logger = Logger.getLogger(this.getClass().getName()); /** */ @InjectPlugin public RemoteDiscovery discovery; /** */ private RemoteAPIDiscoveryUtil remoteAPIDiscoveryUtil; /** */ private Server lipeServer; /** */ private CallHandler callHandler; /** */ int port; /* (non-Javadoc) * @see net.xeoh.plugins.remote.RemoteAPI#exportPlugin(net.xeoh.plugins.base.Plugin) */ public ExportResult exportPlugin(final Plugin plugin) { // Try to set the servername to something sensible String servername = this.configuration.getConfiguration(RemoteAPI.class, "export.server"); if (servername == null) { servername = this.exportServer; } // Sanity checks if (plugin == null) { this.logger.warning("Cannot export plugin, as it is null"); return null; } final String name = PluginExport.getExportName(plugin); final Class<? extends Plugin> exporter = new PluginUtil(plugin).getPrimaryInterfaces().iterator().next(); /* // FIXME: Might need improvement. final Class<?>[] interfaces = plugin.getClass().getInterfaces(); Class<?> exporter = null; // All interfaces this class implements for (final Class<?> class1 : interfaces) { if (Plugin.class.isAssignableFrom(class1)) { exporter = class1; } } */ this.logger.fine("Using exporter " + exporter); try { this.callHandler.registerGlobal(exporter, plugin); } catch (LipeRMIException e) { e.printStackTrace(); } // Return a proper URL URI createURI = createURI(this.protocol + servername + ":" + this.port + "/" + name); // Announce the plugin this.discovery.announcePlugin(plugin, getPublishMethod(), createURI); return new ExportResultImpl(createURI); } /** * Returns the capabilities of this plugin. * * @return . */ @Capabilities public String[] getCapabilites() { return new String[] { "lipe", "LIPE" }; } /* (non-Javadoc) * @see net.xeoh.plugins.remote.RemoteAPI#getPublishMethod() */ public PublishMethod getPublishMethod() { return PublishMethod.LIPE; } /* (non-Javadoc) * @see net.xeoh.plugins.remote.RemoteAPI#getRemoteProxy(java.net.URI, java.lang.Class) */ @SuppressWarnings( { "unchecked" }) public <R extends Plugin> R getRemoteProxy(final URI url, final Class<R> remote) { // In case this is a remote url, let the discoverer work. if (this.remoteAPIDiscoveryUtil.isDiscoveryURI(url)) { return this.remoteAPIDiscoveryUtil.getRemoteProxy(url, remote); } if (url == null) { this.logger.warning("URL was null. Cannot get a proxy for that, returning null."); return null; } this.logger.fine("Trying to retrieve remote proxy for " + url); final CallHandler handler = new CallHandler(); try { final Client client = new Client(url.getHost(), url.getPort(), handler); final R proxy = (R) client.getGlobal(remote); return proxy; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } /** */ @SuppressWarnings("boxing") @Init public void init() { // Try to obtain a proper address try { this.exportServer = InetAddress.getLocalHost().getHostAddress(); } catch (final UnknownHostException e) { // } this.remoteAPIDiscoveryUtil = new RemoteAPIDiscoveryUtil(this.discovery, this); this.port = new PluginConfigurationUtil(this.configuration).getInt(getClass(), "export.port", getFreePort()); this.callHandler = new CallHandler(); this.lipeServer = new Server(); try { this.lipeServer.bind(this.port, this.callHandler); } catch (IOException e) { e.printStackTrace(); } } /** */ @Shutdown public void shutdown() { this.lipeServer.close(); } /* (non-Javadoc) * @see net.xeoh.plugins.remote.RemoteAPI#unexportPlugin(net.xeoh.plugins.base.Plugin) */ public void unexportPlugin(final Plugin plugin) { // Implement this } /** * Internally used to create an URL without 'try' * * @param string * @return */ URI createURI(final String string) { try { return new URI(string); } catch (URISyntaxException e) { e.printStackTrace(); } return null; } /** * @return */ private static int getFreePort() { try { final ServerSocket serverSocket = new ServerSocket(0); final int port = serverSocket.getLocalPort(); serverSocket.close(); return port; } catch (IOException e) { e.printStackTrace(); } return 1025 + new Random().nextInt(50000); } }
100json-jspf
modules/plugins/remote.lipermi/src/net/xeoh/plugins/remote/impl/lipermi/RemoteAPIImpl.java
Java
bsd
8,965
/* * PublishMethod.java * * Copyright (c) 2008, Ralf Biedert All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package net.xeoh.plugins.remote; import net.xeoh.plugins.base.annotations.Capabilities; /** * How an implementation publishes something. As this enum is only hardly extensible from * outside, we have to list here all possible methods beforehand, so other might implement * the plugins and use a value from in here. Currently, we only have XMLRPC. * * Note: All Remote plugins also should use the &#064;{@link Capabilities} annotation to tell their * functionality. * * @author Ralf Biedert * @see RemoteAPI */ public enum PublishMethod { /** <a href="http://code.google.com/p/essence-rmi/">Essence RMI</a> plugin. */ ERMI, /** In case you implemented a method not specified here. Use Capabilities then. */ OTHER, /** Use <a href="http://en.wikipedia.org/wiki/XML-RPC">XMLRPC</a> for communication. Might have problems with void or null. */ XMLRPC, /** DFKI's <a href="http://delight.opendfki.de/">XMLRPC Delight</a> service */ XMLRPCDELIGHT, /** Make plugins accessible by JavaScript (currently defunct) */ JAVASCRIPT, /** Make plugins accessible by JavaScript through <a href="http://jabsorb.org/">Jabsorb (JSON)</a>. Note that browser * restrictions might prevent you from using the plugin properly. */ JSON, /** * <a href="http://lipermi.sourceforge.net/">Lipe RMI</a> appears to be the first sensible RMI provider that supports * callbacks. The version we use however was hacked a bit to support automatic export of interfaces and contains less * bugs and deadlocks. Preferred way of exporting plugins! */ LIPE }
100json-jspf
modules/plugins/remote/src/net/xeoh/plugins/remote/PublishMethod.java
Java
bsd
3,246
/* * RemoteAPI.java * * Copyright (c) 2008, Ralf Biedert All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package net.xeoh.plugins.remote; import java.net.URI; import net.xeoh.plugins.base.Plugin; /** * Allows the network export and import of plugins. The plugins will usually be made * available on the same machine and the local network. The currently preferred way * to export and import plugins is using the LipeRMI implementation, as it allows * for listeners and transparent network callbacks.<br/><br/> * * Please note there may be constraints on the plugin usage depending on the remote type. * For example, XMLRPC might have problems with null or void types. Plugins implementing * the RemoteAPI should be sensitive to the following configuration subkeys:<br/><br/> * * 'export.server' - When exporting and constructing the URL, use this server port and IP. * * @author Ralf Biedert */ public interface RemoteAPI extends Plugin { /** * Exports a plugin over the network. The implementation decides how to do that. An * export result is returned containing additional information about the import. Please * keep in mind that the simpler the plugin's interface is, the more likely the export * will succeed (depends on the export method; Lipe can handle pretty much, XMLRPC * doesn't).<br/><br/> * * For example, if <code>plugin</code> is a local plugin and <code>remote</code> * a remote plugin, you could export your local plugin like this: * <br/><br/> * * <code> * exportPlugin(plugin); * </code><br/><br/> * * Your plugin would afterwards be accessible from other VMs on the same machine and the * local network. Again, you should keep in mind that some details might differ, depending * on the export method you select, so don't be surprised if a specific method call * fails (as a rule of thumb, the more complex a method-signature looks like, the less * likely it is to work with all exporters). * * @param plugin The plugin to export. * @return The export result */ public ExportResult exportPlugin(Plugin plugin); /** * The method by which this remoteAPI publishes plugins with <code>exportPlugin()</code>. * Can be used to select the right export method. * * @return The method the plugin uses to export. */ public PublishMethod getPublishMethod(); /** * Returns a proxy for the remotely exported object. This is the complement to * <code>exportPlugin()</code>. A pseudo-plugin will be return implementing all * methods of the requested interface that forwards all calls to the originally * exported plugin. Depending on the export type a number of method * signatures might not work.<br/><br/> * * For example, if <code>url</code> is a url contianed in the {@link ExportResult} * object returned by <code>exportPlugin()</code> and <code>remote</code> * a remote plugin of the same type as the plugin (which might be of type * <code>ChatService</code> was exported with, you could import your distant plugin * like this: * <br/><br/> * * <code> * ChatService service = getRemoteProxy(uri, ChatService.class); * </code><br/><br/> * * For your convenince there also exist a number of special URIs, the so called * <i>discovery URIs</i>. They enable you to detect services on the network without * having any prior knowledge about its location. These are: * * <ul> * <li><code>discover://any</code> - discovers the next best service implementing the given interface</li> * <li><code>discover://nearest</code> - the nearest (in terms of network ping) instance</li> * <li><code>discover://youngest</code> - the most recently started instance</li> * <li><code>discover://oldest</code> - the instance running the longest time</li> * </ul> * * These special URIs can dramatically change the time the method takes. For example, <code>any</code> * and <code>nearest</code> should generally be the fastest in case a local service (on the same * machine) is found, while <code>youngest</code> and <code>oldest</code> always consider all * available services and take longer. Also, within the first five seconds of application lifetime * the discovery passes can take up to five seconds, while the remaining passes or any discovery call * after five seconds usually take only a fraction of a second. * * @param <R> * @param uri The URI to discover. See {@link ExportResult} and the description above. * @param remote The Plugin interface to request. * @return A pseudo-plugin serving as a stub to the remote object. */ public <R extends Plugin> R getRemoteProxy(URI uri, Class<R> remote); /** * Stops the export of a plugin. * * @param plugin The plugin to unexport (must have been exported previously by the same * remote service) */ public void unexportPlugin(Plugin plugin); }
100json-jspf
modules/plugins/remote/src/net/xeoh/plugins/remote/RemoteAPI.java
Java
bsd
6,718
/* * RemoteConnectionXXX.java * * Copyright (c) 2009, Ralf Biedert All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package net.xeoh.plugins.remote; /** * Plugins returned by {@link RemoteAPI}.<code>getRemoteProxy()</code> may also implement this * interface to provide meta handling facilities of this connection. * * @author Ralf Biedert */ public interface RemotePluginHandler { /** * Disconnects the remote connection and closes all related sockets. * */ public void disconnect(); /** * Measures the time a call takes until it is answered. * * @return The time in milliseconds, or a negative value if the call never returned. */ public int getRoundtripDelay(); }
100json-jspf
modules/plugins/remote/src/net/xeoh/plugins/remote/RemotePluginHandler.java
Java
bsd
2,188
/** * Interfaces related to exporting and importing plugin over the network. * * @since 1.0 */ package net.xeoh.plugins.remote;
100json-jspf
modules/plugins/remote/src/net/xeoh/plugins/remote/package-info.java
Java
bsd
131
/* * ExportResultImpl.java * * Copyright (c) 2009, Ralf Biedert All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package net.xeoh.plugins.remote.util.vanilla; import java.net.URI; import java.util.Arrays; import java.util.Collection; import java.util.List; import net.xeoh.plugins.remote.ExportResult; /** * Only used internally. * * @author Ralf Biedert */ public class ExportResultImpl implements ExportResult { private final List<URI> uris; /** * @param uris */ public ExportResultImpl(URI... uris) { this.uris = Arrays.asList(uris); } /* (non-Javadoc) * @see net.xeoh.plugins.remote.ExportResult#getExportURIs() */ public Collection<URI> getExportURIs() { return this.uris; } }
100json-jspf
modules/plugins/remote/src/net/xeoh/plugins/remote/util/vanilla/ExportResultImpl.java
Java
bsd
2,212
/* * PluginExport.java * * Copyright (c) 2010, Ralf Biedert All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package net.xeoh.plugins.remote.util.internal; import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Collection; import java.util.logging.Logger; import net.xeoh.plugins.base.Plugin; import net.xeoh.plugins.base.util.PluginUtil; /** * Some utils for exporting plugins. Only used internally. * * @author Ralf Biedert */ public class PluginExport { /** * @param plugin * * @return . */ public static String getExportName(Plugin plugin) { final Collection<Class<? extends Plugin>> primaryInterfaces = new PluginUtil(plugin).getPrimaryInterfaces(); final Logger logger = Logger.getLogger(PluginExport.class.getName()); if (primaryInterfaces.size() < 1) { logger.severe("CRITICAL ERROR: UNABLE TO GET ANY INTERFACE NAME FOR " + plugin); return "ERROR"; } if (primaryInterfaces.size() > 1) { logger.warning("Multiple plugin names found ... that is very bad and means your export names will be unstable!"); } Class<? extends Plugin> next = primaryInterfaces.iterator().next(); return next.getCanonicalName(); } /** * @param plugin * * @return . */ @SuppressWarnings("boxing") public static String getHashedName(Plugin plugin) { final String exportName = getExportName(plugin); try { // Convert name to bytes final byte[] bytes = exportName.getBytes("UTF-8"); final MessageDigest digest = java.security.MessageDigest.getInstance("MD5"); // Update the hash digest.update(bytes, 0, bytes.length); // Get result final byte[] hash = digest.digest(); // Assemble hash string final StringBuilder sb = new StringBuilder(); for (final byte b : hash) { final String format = String.format("%02x", b); sb.append(format); } char replacements[] = { 'a', 'b', 'c', 'd', 'e', 'f', 'a', 'b', 'c', 'd', 'e' }; String rval = sb.toString(); char charAt = rval.charAt(0); if (Character.isDigit(charAt)) { int i = Integer.parseInt("" + charAt); rval = replacements[i] + rval.substring(1); } return rval; } catch (final NoSuchAlgorithmException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return "ERROR_CREATING_FINGERPRINT"; } }
100json-jspf
modules/plugins/remote/src/net/xeoh/plugins/remote/util/internal/PluginExport.java
Java
bsd
4,234
/* * ExportResult.java * * Copyright (c) 2009, Ralf Biedert All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package net.xeoh.plugins.remote; import java.net.URI; import java.util.Collection; /** * The export result of the <code>exportPlugin()</code> operation. * * @author Ralf Biedert * @see RemoteAPI */ public interface ExportResult { /** * Returns all URIs where this plugin was exported. Every network interface to which this PC is * connected can have a different URI. * * @return A collection of all exported URIs. */ public Collection<URI> getExportURIs(); }
100json-jspf
modules/plugins/remote/src/net/xeoh/plugins/remote/ExportResult.java
Java
bsd
2,067
/* * DiscoveredPlugin.java * * Copyright (c) 2009, Ralf Biedert All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package net.xeoh.plugins.remotediscovery; import java.net.URI; import java.util.List; import net.xeoh.plugins.remote.PublishMethod; /** * Reflects one discovered plugin. * * @author Ralf Biedert * */ public interface DiscoveredPlugin { /** * Where the plugin can be found. * * @return . */ public URI getPublishURI(); /** * Returns the relative distance of the exported plugin. The lower the number, the closer. * * @return . */ public int getDistance(); /** * The method the plugins was published. * * @return . */ public PublishMethod getPublishMethod(); /** * Returns the capabilities. * * @return . */ public List<String> getCapabilities(); /** * Returns the time since the export of the pluign in milliseconds. * * @return . */ public long getTimeSinceExport(); }
100json-jspf
modules/plugins/remote.discovery/src/net/xeoh/plugins/remotediscovery/DiscoveredPlugin.java
Java
bsd
2,497
/* * OptionLatest.java * * Copyright (c) 2009, Ralf Biedert All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package net.xeoh.plugins.remotediscovery.options.discover; import net.xeoh.plugins.remotediscovery.options.DiscoverOption; /** * Specifies that the oldest service should be located (i.e. the one which is * running for the most time) * * @author rb * */ public class OptionOldest implements DiscoverOption { /** */ private static final long serialVersionUID = -7822509531460390344L; // }
100json-jspf
modules/plugins/remote.discovery/src/net/xeoh/plugins/remotediscovery/options/discover/OptionOldest.java
Java
bsd
1,973
/* * OptionCapabilities.java * * Copyright (c) 2009, Ralf Biedert All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package net.xeoh.plugins.remotediscovery.options.discover; import net.xeoh.plugins.remotediscovery.options.DiscoverOption; /** * Requests a plugin which has certain capabilities. * * @author Ralf Biedert. */ public class OptionRemotePluginCapabilities implements DiscoverOption { /** */ private static final long serialVersionUID = 6650512259925035708L; private String[] caps; /** * @return the caps */ public String[] getCapabilites() { return this.caps; } /** * The caps to use. * * @param caps */ public OptionRemotePluginCapabilities(String... caps) { this.caps = caps; } }
100json-jspf
modules/plugins/remote.discovery/src/net/xeoh/plugins/remotediscovery/options/discover/OptionRemotePluginCapabilities.java
Java
bsd
2,246
/* * OptionCapabilities.java * * Copyright (c) 2009, Ralf Biedert All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package net.xeoh.plugins.remotediscovery.options.discover; import net.xeoh.plugins.remotediscovery.options.DiscoverOption; /** * Requests the nearest service available. * * @author Ralf Biedert. */ public class OptionNearest implements DiscoverOption { /** */ private static final long serialVersionUID = -2239987106439454233L; // }
100json-jspf
modules/plugins/remote.discovery/src/net/xeoh/plugins/remotediscovery/options/discover/OptionNearest.java
Java
bsd
1,924
/* * OptionCapabilities.java * * Copyright (c) 2009, Ralf Biedert All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package net.xeoh.plugins.remotediscovery.options.discover; import net.xeoh.plugins.remotediscovery.options.DiscoverOption; /** * Tries to return all suitable local plugins only, not only the best one. * * @author Ralf Biedert. */ public class OptionDiscoverAllLocal implements DiscoverOption { /** */ private static final long serialVersionUID = -2239987106439454233L; // }
100json-jspf
modules/plugins/remote.discovery/src/net/xeoh/plugins/remotediscovery/options/discover/OptionDiscoverAllLocal.java
Java
bsd
1,965
/* * OptionLatest.java * * Copyright (c) 2009, Ralf Biedert All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package net.xeoh.plugins.remotediscovery.options.discover; import net.xeoh.plugins.remotediscovery.options.DiscoverOption; /** * Specifies that the latest service should be located (i.e. the one which is * running for the least time) * * @author rb * */ public class OptionYoungest implements DiscoverOption { /** */ private static final long serialVersionUID = -3232585171353676863L; }
100json-jspf
modules/plugins/remote.discovery/src/net/xeoh/plugins/remotediscovery/options/discover/OptionYoungest.java
Java
bsd
1,969
/* * OptionCapabilities.java * * Copyright (c) 2009, Ralf Biedert All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package net.xeoh.plugins.remotediscovery.options.discover; import net.xeoh.plugins.remotediscovery.options.DiscoverOption; /** * Tries to discover all services instead of just finding the most suitable * one and returning asap. * * @author Ralf Biedert. */ public class OptionDiscoverAll implements DiscoverOption { /** */ private static final long serialVersionUID = -2239987106439454233L; // }
100json-jspf
modules/plugins/remote.discovery/src/net/xeoh/plugins/remotediscovery/options/discover/OptionDiscoverAll.java
Java
bsd
1,990
/* * OptionCapabilities.java * * Copyright (c) 2009, Ralf Biedert All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package net.xeoh.plugins.remotediscovery.options.discover; import java.util.Collection; import net.xeoh.plugins.remotediscovery.DiscoveredPlugin; import net.xeoh.plugins.remotediscovery.options.DiscoverOption; /** * Requests a callback upon the detection of an appropriate plugin. The callback is executed as soon as the first matching * plugin is detected and then removed. * * @author Ralf Biedert. */ public class OptionCallback implements DiscoverOption { /** */ private static final long serialVersionUID = 8533647106985234966L; /** * Callback to implement for listeners. */ public static interface Callback { /** * Called with all plugins found since the request. * * @param plugins */ public void pluginsDiscovered(Collection<DiscoveredPlugin> plugins); /** * Called when the timout occurred before the detection of any plugin. */ public void timeout(); } final int timeout; final Callback callback; /** * The caps to use. * @param callback */ public OptionCallback(Callback callback) { this(callback, 0); } /** * @param callback * @param timeout */ public OptionCallback(Callback callback, int timeout) { this.callback = callback; this.timeout = timeout; } /** * @return the timeout */ public int getTimeout() { return this.timeout; } /** * @return the callback */ public Callback getCallback() { return this.callback; } }
100json-jspf
modules/plugins/remote.discovery/src/net/xeoh/plugins/remotediscovery/options/discover/OptionCallback.java
Java
bsd
3,189
/* * DiscoverOption.java * * Copyright (c) 2009, Ralf Biedert All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package net.xeoh.plugins.remotediscovery.options; import net.xeoh.plugins.base.Option; /** * * @author rb */ public interface DiscoverOption extends Option { // }
100json-jspf
modules/plugins/remote.discovery/src/net/xeoh/plugins/remotediscovery/options/DiscoverOption.java
Java
bsd
1,739
package net.xeoh.plugins.remotediscovery.impl.v4; import java.net.URI; import java.util.ArrayList; import java.util.List; import net.xeoh.plugins.remote.PublishMethod; import net.xeoh.plugins.remotediscovery.DiscoveredPlugin; /** * @author Thomas Lottermann */ public class DiscoveredPluginImpl implements DiscoveredPlugin { private final List<String> capabilities; private final PublishMethod publishMethod; private final URI publishURI; private final int distance; private final long timeSinceExport; /* (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { return "DiscoveredPlugin [" + this.publishMethod + "]"; } /** * @param capabilities * @param publishMethod * @param publishURI * @param distance * @param timeSincceExport */ public DiscoveredPluginImpl(List<String> capabilities, PublishMethod publishMethod, URI publishURI, int distance, long timeSincceExport) { this.capabilities = capabilities; this.publishMethod = publishMethod; this.publishURI = publishURI; this.distance = distance; this.timeSinceExport = timeSincceExport; } /** * @param publishMethod * @param publishURI * @param distance */ public DiscoveredPluginImpl(PublishMethod publishMethod, URI publishURI, int distance) { this(new ArrayList<String>(), publishMethod, publishURI, distance, 0); } /** * @param publishMethod * @param publishURI * @param distance * @param timeSinceExport */ public DiscoveredPluginImpl(PublishMethod publishMethod, URI publishURI, int distance, long timeSinceExport) { this(new ArrayList<String>(), publishMethod, publishURI, distance, timeSinceExport); } /* (non-Javadoc) * @see net.xeoh.plugins.remotediscovery.DiscoveredPlugin#getCapabilities() */ public List<String> getCapabilities() { return this.capabilities; } /* (non-Javadoc) * @see net.xeoh.plugins.remotediscovery.DiscoveredPlugin#getPublishMethod() */ public PublishMethod getPublishMethod() { return this.publishMethod; } /* (non-Javadoc) * @see net.xeoh.plugins.remotediscovery.DiscoveredPlugin#getPublishURI() */ public URI getPublishURI() { return this.publishURI; } /* (non-Javadoc) * @see net.xeoh.plugins.remotediscovery.DiscoveredPlugin#getDistance() */ public int getDistance() { return this.distance; } /* (non-Javadoc) * @see net.xeoh.plugins.remotediscovery.DiscoveredPlugin#getTimeSinceExport() */ public long getTimeSinceExport() { return this.timeSinceExport; } }
100json-jspf
modules/plugins/remote.discovery/src/net/xeoh/plugins/remotediscovery/impl/v4/DiscoveredPluginImpl.java
Java
bsd
2,940
/* * LocalFileProbe.java * * Copyright (c) 2010, Ralf Biedert All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package net.xeoh.plugins.remotediscovery.impl.v4.probes.local; import java.net.URI; import java.util.ArrayList; import java.util.Collection; import java.util.logging.Logger; import net.xeoh.plugins.base.Plugin; import net.xeoh.plugins.base.PluginManager; import net.xeoh.plugins.remote.PublishMethod; import net.xeoh.plugins.remotediscovery.DiscoveredPlugin; import net.xeoh.plugins.remotediscovery.impl.common.discoverymanager.ExportInfo; import net.xeoh.plugins.remotediscovery.impl.common.discoverymanager.ExportedPlugin; import net.xeoh.plugins.remotediscovery.impl.common.discoverymanager.impl.filepreferences.DiscoveryMangerFileImpl; import net.xeoh.plugins.remotediscovery.impl.v4.DiscoveredPluginImpl; import net.xeoh.plugins.remotediscovery.impl.v4.probes.AbstractProbe; import net.xeoh.plugins.remotediscovery.options.DiscoverOption; /** * @author rb * */ public class LocalProbe extends AbstractProbe { /** */ final Logger logger = Logger.getLogger(this.getClass().getName()); /** Where we keep our local files */ final DiscoveryMangerFileImpl dmp = new DiscoveryMangerFileImpl(); /* (non-Javadoc) * @see net.xeoh.plugins.remotediscovery.impl.v4.probes.AbstractProbe#startup() */ @Override public void startup() { super.startup(); } /** * @param pluginManager */ public LocalProbe(PluginManager pluginManager) { super(pluginManager); } /* (non-Javadoc) * @see net.xeoh.plugins.remotediscovery.RemoteDiscovery#announcePlugin(net.xeoh.plugins.base.Plugin, net.xeoh.plugins.remote.PublishMethod, java.net.URI) */ @Override public void announcePlugin(Plugin plugin, PublishMethod publishMethod, URI uri) { this.dmp.anouncePlugin(plugin, publishMethod, uri); } /* (non-Javadoc) * @see net.xeoh.plugins.remotediscovery.RemoteDiscovery#discover(java.lang.Class, net.xeoh.plugins.remotediscovery.options.DiscoverOption[]) */ @Override public Collection<DiscoveredPlugin> discover(Class<? extends Plugin> plugin, DiscoverOption... options) { final Collection<DiscoveredPlugin> rval = new ArrayList<DiscoveredPlugin>(); final ExportInfo exportInfoFor = this.dmp.getExportInfoFor(plugin.getCanonicalName()); final Collection<ExportedPlugin> allExported = exportInfoFor.allExported; for (final ExportedPlugin e : allExported) { rval.add(new DiscoveredPluginImpl(PublishMethod.valueOf(e.exportMethod), e.exportURI, 0 , e.timeSinceExport)); } return rval; } /* (non-Javadoc) * @see net.xeoh.plugins.remotediscovery.RemoteDiscovery#revokePlugin(net.xeoh.plugins.base.Plugin, net.xeoh.plugins.remote.PublishMethod, java.net.URI) */ @Override public void revokePlugin(Plugin plugin, PublishMethod publishMethod, URI uri) { this.dmp.revokePlugin(plugin, publishMethod, uri); } }
100json-jspf
modules/plugins/remote.discovery/src/net/xeoh/plugins/remotediscovery/impl/v4/probes/local/LocalProbe.java
Java
bsd
4,537
/* * NetworkProbe.java * * Copyright (c) 2010, Ralf Biedert All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package net.xeoh.plugins.remotediscovery.impl.v4.probes.network; import java.io.IOException; import java.net.InetAddress; import java.net.URI; import java.net.URISyntaxException; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Random; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.Callable; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorCompletionService; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import java.util.logging.Logger; import javax.jmdns.JmDNS; import javax.jmdns.ServiceInfo; import javax.jmdns.impl.tasks.ServiceResolver; import net.xeoh.plugins.base.Plugin; import net.xeoh.plugins.base.PluginConfiguration; import net.xeoh.plugins.base.PluginManager; import net.xeoh.plugins.base.util.OptionUtils; import net.xeoh.plugins.base.util.PluginConfigurationUtil; import net.xeoh.plugins.diagnosis.local.Diagnosis; import net.xeoh.plugins.diagnosis.local.util.DiagnosisChannelUtil; import net.xeoh.plugins.remote.PublishMethod; import net.xeoh.plugins.remotediscovery.DiscoveredPlugin; import net.xeoh.plugins.remotediscovery.RemoteDiscovery; import net.xeoh.plugins.remotediscovery.diagnosis.channel.tracer.ProbeTracer; import net.xeoh.plugins.remotediscovery.impl.common.discoverymanager.DiscoveryManager; import net.xeoh.plugins.remotediscovery.impl.common.discoverymanager.ExportInfo; import net.xeoh.plugins.remotediscovery.impl.common.discoverymanager.ExportedPlugin; import net.xeoh.plugins.remotediscovery.impl.common.discoverymanager.impl.AbstractDiscoveryManager; import net.xeoh.plugins.remotediscovery.impl.common.discoverymanager.impl.tcpip.DiscoveryManagerTCPIPImpl; import net.xeoh.plugins.remotediscovery.impl.v4.CallbackRequest; import net.xeoh.plugins.remotediscovery.impl.v4.DiscoveredPluginImpl; import net.xeoh.plugins.remotediscovery.impl.v4.RemoteDiscoveryImpl; import net.xeoh.plugins.remotediscovery.impl.v4.probes.AbstractProbe; import net.xeoh.plugins.remotediscovery.options.DiscoverOption; import net.xeoh.plugins.remotediscovery.options.discover.OptionNearest; import net.xeoh.plugins.remotediscovery.options.discover.OptionOldest; import net.xeoh.plugins.remotediscovery.options.discover.OptionYoungest; import org.freshvanilla.rmi.Proxies; import org.freshvanilla.rmi.VanillaRmiServer; import org.freshvanilla.utils.SimpleResource; /** * @author Ralf Biedert */ public class NetworkProbe extends AbstractProbe { /** Export name of the manager */ private static final String EXPORT_NAME = "DiscoveryManager"; /** Network announce name */ private static final String NAME = "JSPF"; /** ZeroConf type */ private static final String TYPE = "_jspfplugindiscovery._tcp.local."; /** How we lock for the first call? */ private String lockMode; /** */ private final PluginConfiguration pluginConfiguration; /** Time to lock after startup */ private int startupLock; /** */ private Timer timer; /** */ protected final Lock jmdnsLock = new ReentrantLock(); /** The local manager */ protected final AbstractDiscoveryManager localTCPIPManager = new DiscoveryManagerTCPIPImpl(); /** Contains a list of remote DiscoveryManagers all over the network and also the local manager. This is not final as we replace * it every iteration. This way the client has the chance to grab a local "copy" and work on it while a more receent version is * being prepared*/ protected volatile Collection<RemoteManagerEndpoint> remoteManagersEndpoints = new ArrayList<RemoteManagerEndpoint>(); /** usually should contain only all DiscoveryManager; */ protected final Collection<ServiceInfo> serviceInfos = new ArrayList<ServiceInfo>(); /** */ protected final Lock serviceInfosLock = new ReentrantLock(); /** */ protected final CountDownLatch startupLatch = new CountDownLatch(1); /** */ AtomicLong discoverThreadCounter = new AtomicLong(); /** Main JmDNS object */ JmDNS jmdns; /** Server of the exported local manager */ VanillaRmiServer<DiscoveryManager> localManagerExportServer; /** */ final Logger _logger = Logger.getLogger(this.getClass().getName()); final DiagnosisChannelUtil<String> logger; long timeOfStartup; /** * @param pluginManager */ public NetworkProbe(final PluginManager pluginManager) { super(pluginManager); this.pluginConfiguration = pluginManager.getPlugin(PluginConfiguration.class); this.logger = new DiagnosisChannelUtil<String>(pluginManager.getPlugin(Diagnosis.class).channel(ProbeTracer.class)); } /** * @param plugin * @param publishMethod * @param uri */ @Override public void announcePlugin(final Plugin plugin, final PublishMethod publishMethod, final URI uri) { this.localTCPIPManager.anouncePlugin(plugin, publishMethod, uri); } /** */ @SuppressWarnings("boxing") public void backgroundInit() { // (Ralf:) zomfg, this is one of the worst hacks i've done the last years. Deep within jmdns we placed a variable to // override a check if it is already safe to transmit something. jmDNS usually takes 5 seconds to reach that state, but that's // too long for us. If you set this variable the check will be skipped and the request should take place much faster. // Appears to work(tm). ServiceResolver.ANNOUNCE_OVERRIDE = true; this.logger.status("backgroundinit/start"); final PluginConfigurationUtil pcu = new PluginConfigurationUtil(this.pluginConfiguration); this.startupLock = pcu.getInt(RemoteDiscovery.class, "startup.locktime", 1000); this.lockMode = pcu.getString(RemoteDiscovery.class, "startup.lockmode", "onepass"); try { this.logger.status("backgroundinit/lock"); this.jmdnsLock.lock(); this.jmdns = JmDNS.create(); // Maybe init with local loopback in case no other network card is present, otherwise returns null this.timeOfStartup = System.currentTimeMillis(); final int port = RemoteDiscoveryImpl.getFreePort(); final ServiceInfo service = ServiceInfo.create(TYPE, NAME + " @" + this.timeOfStartup, port, 0, 0, EXPORT_NAME); this.logger.status("backgroundinit/export", "port", port); this.localManagerExportServer = Proxies.newServer(EXPORT_NAME, port, (DiscoveryManager) this.localTCPIPManager); this.logger.status("backgroundinit/announce", "port", port); this.jmdns.registerService(service); // Set it again, this time for the lock below this.timeOfStartup = System.currentTimeMillis(); } catch (final IOException e) { e.printStackTrace(); } catch (final IllegalStateException e) { this.logger.status("backgroundinit/exception/illegalstate", "message", e.getMessage()); } finally { this.logger.status("backgroundinit/unlock"); this.startupLatch.countDown(); this.jmdnsLock.unlock(); } this.logger.status("backgroundinit/end"); } /** * @param plugin * @param options * @return . */ @Override public Collection<DiscoveredPlugin> discover(final Class<? extends Plugin> plugin, final DiscoverOption... options) { this.logger.status("discover/start", "plugin", plugin); // Wait until init is done ... try { this.startupLatch.await(); } catch (final InterruptedException e) { return new ArrayList<DiscoveredPlugin>(); } // Timelock: Wait for a certain time to pass since startup if (this.lockMode.equals("timelock")) { if (awaitInitializationTime() == false) return new ArrayList<DiscoveredPlugin>(); } // Onepass: Wait for the discover to execute once if (this.lockMode.equals("onepass")) { // Also wait some time here, otherwise we won't find all plugins in all cases awaitInitializationTime(); // Wait at least one discoverThreadTurn final long lastDisoverValue = this.discoverThreadCounter.get(); final long startOfWait = System.currentTimeMillis(); while (this.discoverThreadCounter.get() == lastDisoverValue) { try { java.lang.Thread.sleep(100); } catch (final InterruptedException e) { e.printStackTrace(); return new ArrayList<DiscoveredPlugin>(); } // Safety check if (System.currentTimeMillis() > startOfWait + 1000) throw new IllegalStateException("We are waiting way too long."); } } this.logger.status("discover/end"); // Eventually resolve the request. return resolve(plugin, options); } /** */ void discoverThread() { try { this.startupLatch.await(); } catch (final InterruptedException e) { e.printStackTrace(); return; } // Increase counter this.discoverThreadCounter.incrementAndGet(); // Create empty data. ServiceInfo[] infos = {}; // Magic: Get all network services of our type. try { this.jmdnsLock.lock(); // TODO: jmdsn can be null if no network card is present infos = this.jmdns.list(TYPE); } catch (final IllegalStateException e) { this.logger.status("discoverthread/exception", "message", e.getMessage()); } finally { this.jmdnsLock.unlock(); } // Reset all service infos try { this.serviceInfosLock.lock(); this.serviceInfos.clear(); this.serviceInfos.addAll(Arrays.asList(infos)); } finally { this.serviceInfosLock.unlock(); } // Process all callbacks. @SuppressWarnings("unused") final Collection<CallbackRequest> toRemove = new ArrayList<CallbackRequest>(); // // TODO: This callback handling needs improvement. Check for unsynchronized access to the allRequest structure // } /** * @param plugin * @param publishMethod * @param uri */ @Override public void revokePlugin(final Plugin plugin, final PublishMethod publishMethod, final URI uri) { this.localTCPIPManager.revokePlugin(plugin, publishMethod, uri); } /* (non-Javadoc) * @see net.xeoh.plugins.remotediscovery.impl.v4.probes.AbstractProbe#shutdown() */ @Override public void shutdown() { super.shutdown(); try { this.timer.cancel(); } catch (final Exception e) { // } final java.lang.Thread t = new java.lang.Thread(new Runnable() { public void run() { NetworkProbe.this.jmdnsLock.lock(); // All of these statements tend to fail because of various reasons. During the shutdown however, // we want to ignore them all ... try { try { NetworkProbe.this.localManagerExportServer.close(); } catch (final Exception e) { // } try { NetworkProbe.this.jmdns.unregisterAllServices(); } catch (final Exception e) { // } try { NetworkProbe.this.jmdns.close(); } catch (final Exception e) { // } } finally { NetworkProbe.this.jmdnsLock.unlock(); } } }); t.setDaemon(true); t.start(); } /* (non-Javadoc) * @see net.xeoh.plugins.remotediscovery.impl.v4.probes.AbstractProbe#startup() */ @Override public void startup() { super.startup(); final Thread thread = new Thread(new Runnable() { @Override public void run() { backgroundInit(); } }); thread.setDaemon(true); thread.start(); this.timer = new Timer(); this.timer.schedule(new TimerTask() { @Override public void run() { discoverThread(); } }, 0, 260); } /** * @return */ private boolean awaitInitializationTime() { // Check if we're still on startup lock final long delay = this.timeOfStartup + this.startupLock - System.currentTimeMillis(); if (delay > 0) { // If we are, halt this thread until lock time has passed. Unfortunatly the lookup is a // bit "unstable" during the first few miliseconds. try { java.lang.Thread.sleep(delay); } catch (final InterruptedException e) { e.printStackTrace(); return false; } } return true; } @SuppressWarnings({ "unchecked", "boxing", "rawtypes" }) private DiscoveryManager getRemoteProxyToDiscoveryManager(final String ip, final int port) { final String address = ip + ":" + port; final int timeout = 500; // 500 ms RemoteAPIImpl if need detailed version... this.logger.status("remoteproxytodiscovery/start", "ip", ip, "port", port); final DiscoveryManager newClient = Proxies.newClient(EXPORT_NAME, address, getClass().getClassLoader(), DiscoveryManager.class); // Execute collection asynchronously (TODO: cache pool usage could be improved) final ExecutorService cachePool = Executors.newCachedThreadPool(RemoteDiscoveryImpl.threadFactory); final ExecutorCompletionService<String> ecs = new ExecutorCompletionService(cachePool); final Future<String> future = ecs.submit(new Callable<String>() { public String call() throws Exception { return AccessController.doPrivileged(new PrivilegedAction<String>() { public String run() { return newClient.ping(667) == 667 ? "OK" : null; } }); } }); // Wait at most half a second (TODO: Make this configurable) try { final String string = future.get(timeout, TimeUnit.MILLISECONDS); if (string == null) return null; return newClient; } catch (final InterruptedException e) { this.logger.status("remoteproxytodiscovery/exception/interrupted", "message", e.getMessage()); e.printStackTrace(); } catch (final ExecutionException e) { this.logger.status("remoteproxytodiscovery/exception/executionexception", "message", e.getMessage()); } catch (final TimeoutException e) { this.logger.status("remoteproxytodiscovery/exception/timeoutexception", "message", e.getMessage()); } catch (final SecurityException e) { this.logger.status("remoteproxytodiscovery/exception/securityexception", "message", e.getMessage()); e.printStackTrace(); } finally { AccessController.doPrivileged(new PrivilegedAction<Object>() { public Object run() { future.cancel(true); cachePool.shutdownNow(); return null; } }); this.logger.status("remoteproxytodiscovery/end"); } this.logger.status("remoteproxytodiscovery/end"); return null; } /** * Refreshes all known discovery managers. */ private void refreshKnownDiscoveryManagers() { this.serviceInfosLock.lock(); try { final List<RemoteManagerEndpoint> endpoints = new ArrayList<RemoteManagerEndpoint>(); // Check all service infos with discovery managers for (final ServiceInfo serviceInfo : this.serviceInfos) { final InetAddress address = serviceInfo.getAddress(); final int port = serviceInfo.getPort(); endpoints.add(new RemoteManagerEndpoint(address, port)); } // Eventually update the endpoints this.remoteManagersEndpoints = endpoints; } finally { this.serviceInfosLock.unlock(); } } /** * Checks all known service infos for matches to the given class, returns all matching entries. * * @param plugin * @param options * @return */ @SuppressWarnings("boxing") private Collection<DiscoveredPlugin> resolve(final Class<? extends Plugin> plugin, final DiscoverOption[] options) { // Refreshes all known remote discovery managers. refreshKnownDiscoveryManagers(); // The result we intend to return final Collection<DiscoveredPlugin> result = new ArrayList<DiscoveredPlugin>(); final Collection<RemoteManagerEndpoint> endpoints = this.remoteManagersEndpoints; // Query all managers for (final RemoteManagerEndpoint endpoint : endpoints) { // The manager to use ... final DiscoveryManager mgr = getRemoteProxyToDiscoveryManager(endpoint.address.getHostAddress(), endpoint.port); // No matter what happens, close the manager try { if (mgr == null) { this.logger.status("resolve/vanished", "address", endpoint.address.getHostAddress(), "port", endpoint.port); continue; } // final AtomicInteger pingTime = new AtomicInteger(Integer.MAX_VALUE); // Get ping time AccessController.doPrivileged(new PrivilegedAction<Object>() { public Object run() { try { final long start = System.nanoTime(); // Perform the ping mgr.ping(new Random().nextInt()); // Obtain the time final long stop = System.nanoTime(); final long time = (stop - start) / 1000; // And set it NetworkProbe.this.logger.status("resolve/ping", "time", time); pingTime.set((int) time); } catch (final Exception e) { NetworkProbe.this.logger.status("resolve/exception/ping", "message", e.getMessage()); } return null; } }); // Query the information (needs to be inside a privileged block, otherwise applets might complain. final ExportInfo exportInfo = AccessController.doPrivileged(new PrivilegedAction<ExportInfo>() { public ExportInfo run() { return mgr.getExportInfoFor(plugin.getCanonicalName()); } }); // If the plugin in not exported, do nothing if (!exportInfo.isExported) { continue; } // If it is, construct required data. for (final ExportedPlugin p : exportInfo.allExported) { final PublishMethod method = PublishMethod.valueOf(p.exportMethod); final URI uri = p.exportURI; String _newURI = ""; _newURI += uri.getScheme(); _newURI += "://"; if (endpoint.address != null) { _newURI += endpoint.address.getHostAddress(); } else { _newURI += "127.0.0.1"; } _newURI += ":"; _newURI += uri.getPort(); _newURI += uri.getPath(); try { // TODO: Compute distance properly. result.add(new DiscoveredPluginImpl(method, new URI(_newURI), pingTime.get(), p.timeSinceExport)); } catch (final URISyntaxException e) { e.printStackTrace(); } } } catch (final Exception e) { this.logger.status("resolve/exception/versionmess", "address", endpoint.address, "port", endpoint.port); e.printStackTrace(); } finally { // In case the manager is of the type simple resource (which it should be), try to close it. if (mgr instanceof SimpleResource) { try { // Try to close our device again AccessController.doPrivileged(new PrivilegedAction<Object>() { public Object run() { ((SimpleResource) mgr).close(); return null; } }); } catch (final Exception e) { e.printStackTrace(); this.logger.status("resolve/exception/close", "address", endpoint.address, "port", endpoint.port); } } } } // If we have no result there is nothing to do if (result.size() == 0) return result; // Prepapare filter options ... final OptionUtils<DiscoverOption> ou = new OptionUtils<DiscoverOption>(options); DiscoveredPlugin best = result.iterator().next(); if (ou.contains(OptionNearest.class)) { // Check all plugins for (final DiscoveredPlugin p : result) { // If this one is closer, replace them if (p.getDistance() < best.getDistance()) { best = p; } } // Remove all other plugins result.clear(); result.add(best); } if (ou.contains(OptionYoungest.class)) { // Check all plugins for (final DiscoveredPlugin p : result) { // If this one is closer, replace them if (p.getTimeSinceExport() < best.getTimeSinceExport()) { best = p; } } // Remove all other plugins result.clear(); result.add(best); } if (ou.contains(OptionOldest.class)) { // Check all plugins for (final DiscoveredPlugin p : result) { // If this one is closer, replace them if (p.getTimeSinceExport() > best.getTimeSinceExport()) { best = p; } } // Remove all other plugins result.clear(); result.add(best); } // Debug plugins for (final DiscoveredPlugin p : result) { this.logger.status("resolve/return/", "plugin", p.getPublishURI()); } return result; } }
100json-jspf
modules/plugins/remote.discovery/src/net/xeoh/plugins/remotediscovery/impl/v4/probes/network/NetworkProbe.java
Java
bsd
25,869
package net.xeoh.plugins.remotediscovery.impl.v4.probes.network; import java.net.InetAddress; /** * * @author rb * */ public class RemoteManagerEndpoint { /** */ public InetAddress address; /** */ public int port; /** * @param adr * @param port */ public RemoteManagerEndpoint(InetAddress adr, int port) { this.address = adr; this.port = port; } /** * */ public RemoteManagerEndpoint() { // TODO Auto-generated constructor stub } }
100json-jspf
modules/plugins/remote.discovery/src/net/xeoh/plugins/remotediscovery/impl/v4/probes/network/RemoteManagerEndpoint.java
Java
bsd
535
/* * AbstractProbe.java * * Copyright (c) 2010, Ralf Biedert All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package net.xeoh.plugins.remotediscovery.impl.v4.probes; import net.xeoh.plugins.base.PluginManager; import net.xeoh.plugins.remotediscovery.RemoteDiscovery; /** * * @author Ralf Biedert */ public abstract class AbstractProbe implements RemoteDiscovery { /** */ final PluginManager pluginManager; /** * @param pluginManager */ public AbstractProbe(PluginManager pluginManager) { this.pluginManager = pluginManager; } /** * Called when the probe should start up. */ public void startup() { // } /** * Called when the probe should shut down. */ public void shutdown() { // } }
100json-jspf
modules/plugins/remote.discovery/src/net/xeoh/plugins/remotediscovery/impl/v4/probes/AbstractProbe.java
Java
bsd
2,250
package net.xeoh.plugins.remotediscovery.impl.v4; import java.io.IOException; import java.net.ServerSocket; import java.net.URI; import java.util.Collection; import java.util.Random; import java.util.concurrent.ThreadFactory; import net.xeoh.plugins.base.Plugin; import net.xeoh.plugins.base.PluginManager; import net.xeoh.plugins.base.annotations.PluginImplementation; import net.xeoh.plugins.base.annotations.events.Init; import net.xeoh.plugins.base.annotations.events.Shutdown; import net.xeoh.plugins.base.annotations.injections.InjectPlugin; import net.xeoh.plugins.base.util.OptionUtils; import net.xeoh.plugins.diagnosis.local.util.DiagnosisChannelUtil; import net.xeoh.plugins.diagnosis.local.util.DiagnosisUtil; import net.xeoh.plugins.remote.PublishMethod; import net.xeoh.plugins.remotediscovery.DiscoveredPlugin; import net.xeoh.plugins.remotediscovery.RemoteDiscovery; import net.xeoh.plugins.remotediscovery.diagnosis.channel.tracer.DiscoveryTracer; import net.xeoh.plugins.remotediscovery.impl.v4.probes.local.LocalProbe; import net.xeoh.plugins.remotediscovery.impl.v4.probes.network.NetworkProbe; import net.xeoh.plugins.remotediscovery.options.DiscoverOption; import net.xeoh.plugins.remotediscovery.options.discover.OptionNearest; /** * * * @author Ralf Biedert */ @PluginImplementation public class RemoteDiscoveryImpl implements RemoteDiscovery { /** * Constructs daemonic threads */ public static ThreadFactory threadFactory = new ThreadFactory() { public java.lang.Thread newThread(Runnable r) { java.lang.Thread rval = new java.lang.Thread(r); rval.setDaemon(true); return rval; } }; /** * out of net.xeoh.plugins.remote.impl.ermi.RemoteAPIImpl * @return . */ public static int getFreePort() { try { final ServerSocket serverSocket = new ServerSocket(0); final int port = serverSocket.getLocalPort(); serverSocket.close(); return port; } catch (IOException e) { e.printStackTrace(); } return 1025 + new Random().nextInt(50000); } /** */ @InjectPlugin public PluginManager pluginManager; /** */ @InjectPlugin public DiagnosisUtil diagnosis; /** All of our probes */ NetworkProbe networkProbe; /** Local probe */ LocalProbe localProbe; /* (non-Javadoc) * @see net.xeoh.plugins.remotediscovery.RemoteDiscovery#announcePlugin(net.xeoh.plugins.base.Plugin, net.xeoh.plugins.remote.PublishMethod, java.net.URI) */ public void announcePlugin(Plugin plugin, PublishMethod publishMethod, URI uri) { this.localProbe.announcePlugin(plugin, publishMethod, uri); this.networkProbe.announcePlugin(plugin, publishMethod, uri); } /* (non-Javadoc) * @see net.xeoh.plugins.remotediscovery.RemoteDiscovery#discover(java.lang.Class, net.xeoh.plugins.remotediscovery.options.DiscoverOption[]) */ public Collection<DiscoveredPlugin> discover(final Class<? extends Plugin> plugin, final DiscoverOption... options) { final DiagnosisChannelUtil<String> channel = this.diagnosis.channel(DiscoveryTracer.class); final OptionUtils<DiscoverOption> ou = new OptionUtils<DiscoverOption>(options); channel.status("discover/start", "plugin", plugin); // Check if we are allowed to use the local discovery (nearest or nothing specified), // and return with it instantly. if(ou.contains(OptionNearest.class) || options.length == 0) { channel.status("discover/nearest"); final Collection<DiscoveredPlugin> discover = this.localProbe.discover(plugin, options); if(discover.size() > 0) { channel.status("discover/end/notfound"); return discover; } channel.status("discover/nearest/fallback"); } channel.status("discover/classic"); final Collection<DiscoveredPlugin> discover = this.networkProbe.discover(plugin, options); channel.status("discover/end"); return discover; } /* (non-Javadoc) * @see net.xeoh.plugins.remotediscovery.RemoteDiscovery#revokePlugin(net.xeoh.plugins.base.Plugin, net.xeoh.plugins.remote.PublishMethod, java.net.URI) */ public void revokePlugin(Plugin plugin, PublishMethod publishMethod, URI uri) { this.networkProbe.revokePlugin(plugin, publishMethod, uri); this.localProbe.revokePlugin(plugin, publishMethod, uri); } /** */ @Init public void init() { this.networkProbe = new NetworkProbe(this.pluginManager); this.localProbe = new LocalProbe(this.pluginManager); this.networkProbe.startup(); this.localProbe.startup(); } /** */ @Shutdown public void shutdown() { this.networkProbe.shutdown(); this.localProbe.shutdown(); } }
100json-jspf
modules/plugins/remote.discovery/src/net/xeoh/plugins/remotediscovery/impl/v4/RemoteDiscoveryImpl.java
Java
bsd
5,205
package net.xeoh.plugins.remotediscovery.impl.v4; import java.util.Timer; import java.util.TimerTask; import net.xeoh.plugins.base.Plugin; import net.xeoh.plugins.remotediscovery.options.DiscoverOption; import net.xeoh.plugins.remotediscovery.options.discover.OptionCallback; /** * A request for callbacks. * * @author rb * */ public class CallbackRequest { /** * */ final RemoteDiscoveryImpl remoteDiscoveryImpl; Class<? extends Plugin> req; OptionCallback oc; DiscoverOption[] moreOptions; Timer timer = new Timer(); /** * @param remoteDiscoveryImpl * @param p * @param c * @param moreOptions */ public CallbackRequest(final RemoteDiscoveryImpl remoteDiscoveryImpl, final Class<? extends Plugin> p, final OptionCallback c, final DiscoverOption... moreOptions) { this.remoteDiscoveryImpl = remoteDiscoveryImpl; this.req = p; this.oc = c; this.moreOptions = moreOptions; if (this.oc.getTimeout() > 0) { this.timer.schedule(new TimerTask() { @Override public void run() { c.getCallback().timeout(); cancelTimeout(); //remoteDiscoveryImpl.allRequests.remove(remoteDiscoveryImpl); } }, this.oc.getTimeout()); } } /** * */ public void cancelTimeout() { try { this.timer.cancel(); } catch (Throwable t) { // } } }
100json-jspf
modules/plugins/remote.discovery/src/net/xeoh/plugins/remotediscovery/impl/v4/CallbackRequest.java
Java
bsd
1,603
package net.xeoh.plugins.remotediscovery.impl.v3; import java.net.URI; import java.util.ArrayList; import java.util.List; import net.xeoh.plugins.remote.PublishMethod; import net.xeoh.plugins.remotediscovery.DiscoveredPlugin; /** * @author Thomas Lottermann */ public class DiscoveredPluginImpl implements DiscoveredPlugin { private final List<String> capabilities; private final PublishMethod publishMethod; private final URI publishURI; private final int distance; private final long timeSinceExport; /** * @param capabilities * @param publishMethod * @param publishURI * @param distance * @param timeSincceExport */ public DiscoveredPluginImpl(List<String> capabilities, PublishMethod publishMethod, URI publishURI, int distance, long timeSincceExport) { this.capabilities = capabilities; this.publishMethod = publishMethod; this.publishURI = publishURI; this.distance = distance; this.timeSinceExport = timeSincceExport; } /** * @param publishMethod * @param publishURI * @param distance */ public DiscoveredPluginImpl(PublishMethod publishMethod, URI publishURI, int distance) { this(new ArrayList<String>(), publishMethod, publishURI, distance, 0); } /** * @param publishMethod * @param publishURI * @param distance * @param timeSinceExport */ public DiscoveredPluginImpl(PublishMethod publishMethod, URI publishURI, int distance, long timeSinceExport) { this(new ArrayList<String>(), publishMethod, publishURI, distance, timeSinceExport); } /* (non-Javadoc) * @see net.xeoh.plugins.remotediscovery.DiscoveredPlugin#getCapabilities() */ public List<String> getCapabilities() { return this.capabilities; } /* (non-Javadoc) * @see net.xeoh.plugins.remotediscovery.DiscoveredPlugin#getPublishMethod() */ public PublishMethod getPublishMethod() { return this.publishMethod; } /* (non-Javadoc) * @see net.xeoh.plugins.remotediscovery.DiscoveredPlugin#getPublishURI() */ public URI getPublishURI() { return this.publishURI; } /* (non-Javadoc) * @see net.xeoh.plugins.remotediscovery.DiscoveredPlugin#getDistance() */ public int getDistance() { return this.distance; } /* (non-Javadoc) * @see net.xeoh.plugins.remotediscovery.DiscoveredPlugin#getTimeSinceExport() */ public long getTimeSinceExport() { return this.timeSinceExport; } }
100json-jspf
modules/plugins/remote.discovery/src/net/xeoh/plugins/remotediscovery/impl/v3/DiscoveredPluginImpl.java
Java
bsd
2,747
package net.xeoh.plugins.remotediscovery.impl.v3; import java.io.IOException; import java.net.InetAddress; import java.net.ServerSocket; import java.net.URI; import java.net.URISyntaxException; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Random; import java.util.concurrent.Callable; import java.util.concurrent.CompletionService; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorCompletionService; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import java.util.logging.Logger; import javax.jmdns.JmDNS; import javax.jmdns.ServiceInfo; import javax.jmdns.impl.tasks.ServiceResolver; import net.xeoh.plugins.base.Plugin; import net.xeoh.plugins.base.PluginConfiguration; import net.xeoh.plugins.base.PluginInformation; import net.xeoh.plugins.base.annotations.PluginImplementation; import net.xeoh.plugins.base.annotations.Thread; import net.xeoh.plugins.base.annotations.configuration.IsDisabled; import net.xeoh.plugins.base.annotations.events.Shutdown; import net.xeoh.plugins.base.annotations.injections.InjectPlugin; import net.xeoh.plugins.base.util.OptionUtils; import net.xeoh.plugins.base.util.PluginConfigurationUtil; import net.xeoh.plugins.remote.PublishMethod; import net.xeoh.plugins.remotediscovery.DiscoveredPlugin; import net.xeoh.plugins.remotediscovery.RemoteDiscovery; import net.xeoh.plugins.remotediscovery.impl.common.discoverymanager.DiscoveryManager; import net.xeoh.plugins.remotediscovery.impl.common.discoverymanager.ExportInfo; import net.xeoh.plugins.remotediscovery.impl.common.discoverymanager.ExportedPlugin; import net.xeoh.plugins.remotediscovery.impl.common.discoverymanager.impl.tcpip.DiscoveryManagerTCPIPImpl; import net.xeoh.plugins.remotediscovery.options.DiscoverOption; import net.xeoh.plugins.remotediscovery.options.discover.OptionCallback; import net.xeoh.plugins.remotediscovery.options.discover.OptionNearest; import net.xeoh.plugins.remotediscovery.options.discover.OptionOldest; import net.xeoh.plugins.remotediscovery.options.discover.OptionYoungest; import org.freshvanilla.rmi.Proxies; import org.freshvanilla.rmi.VanillaRmiServer; import org.freshvanilla.utils.SimpleResource; /** * @author Thomas Lottermann * */ @IsDisabled @PluginImplementation public class RemoteDiscoveryImpl implements RemoteDiscovery { private static final String EXPORT_NAME = "DiscoveryManager"; private static final String NAME = "JSPF"; private static final String TYPE = "_jspfplugindiscovery._tcp.local."; /** * @return */ private static int getFreePort() { try { final ServerSocket serverSocket = new ServerSocket(0); final int port = serverSocket.getLocalPort(); serverSocket.close(); return port; } catch (IOException e) { e.printStackTrace(); } return 1025 + new Random().nextInt(50000); } /** */ @InjectPlugin public PluginConfiguration pluginConfiguration; /** */ @InjectPlugin public PluginInformation pluginInformation; /** How we lock for the first call? */ private String lockMode; private int startupLock; /** All callbacks for discovered plugins */ protected final List<CallbackRequest> allRequests = new ArrayList<CallbackRequest>(); protected final Lock jmdnsLock = new ReentrantLock(); /** The local manager */ protected final DiscoveryManagerTCPIPImpl localManager = new DiscoveryManagerTCPIPImpl(); /** * Contains a list of remote DiscoveryManagers all over the network and also * the local manager */ protected final HashSet<RemoteManagerEndpoint> remoteManagersEndpoints = new HashSet<RemoteManagerEndpoint>(); /** usually should contain only all DiscoveryManager; */ protected final Collection<ServiceInfo> serviceInfos = new ArrayList<ServiceInfo>(); /** */ protected final Lock serviceInfosLock = new ReentrantLock(); protected final CountDownLatch startupLatch = new CountDownLatch(1); final CheckCacheCall checkCache = new CheckCacheCall(this); final DiscoverCall discover = new DiscoverCall(this); /** */ AtomicLong discoverThreadCounter = new AtomicLong(); JmDNS jmdns; /** Server of the exported local manager */ VanillaRmiServer<DiscoveryManager> localManagerExportServer; /** */ final Logger logger = Logger.getLogger(this.getClass().getName()); /** * Constructs daemonic threads */ ThreadFactory threadFactory = new ThreadFactory() { public java.lang.Thread newThread(Runnable r) { java.lang.Thread rval = new java.lang.Thread(r); rval.setDaemon(true); return rval; } }; long timeOfStartup; /* * (non-Javadoc) * * @see * net.xeoh.plugins.remotediscovery.RemoteDiscovery#announcePlugin(net.xeoh * .plugins.base.Plugin, net.xeoh.plugins.remote.PublishMethod, * java.net.URI) */ public void announcePlugin(Plugin plugin, PublishMethod publishMethod, URI uri) { this.localManager.anouncePlugin(plugin, publishMethod, uri); } /** */ @SuppressWarnings("boxing") @Thread(isDaemonic = true) public void backgroundInit() { // (Ralf:) zomfg, this is one of the worst hacks i've done the last // couple of months. Deep within jmdns we placed a variable to // override a check if it is already save to transmit something. jmDNS // usually takes 5 seconds to reach that state, but that's // too long for us. If you set this variable the check will be skipped // and the request should take place much faster. // Appears to work(tm). ServiceResolver.ANNOUNCE_OVERRIDE = true; final PluginConfigurationUtil pcu = new PluginConfigurationUtil(this.pluginConfiguration); this.startupLock = pcu.getInt(RemoteDiscovery.class, "startup.locktime", 1000); this.lockMode = pcu.getString(RemoteDiscovery.class, "startup.lockmode", "onepass"); // TODO put this in a thread this.checkCache.loadCache(); try { this.jmdnsLock.lock(); this.jmdns = JmDNS.create(); // Maybe init with local loopback in case no other network card is present, otherwise returns null this.timeOfStartup = System.currentTimeMillis(); final int port = getFreePort(); final ServiceInfo service = ServiceInfo.create(TYPE, NAME + " @" + this.timeOfStartup, port, 0, 0, EXPORT_NAME); this.localManagerExportServer = Proxies.newServer(EXPORT_NAME, port, (DiscoveryManager) this.localManager); this.jmdns.registerService(service); // Set it again, this time for the lock below this.timeOfStartup = System.currentTimeMillis(); } catch (IOException e) { e.printStackTrace(); } catch (IllegalStateException e) { this.logger.warning("Error starting discovery."); } finally { this.startupLatch.countDown(); this.jmdnsLock.unlock(); } // and load our cache... // todo make this configurable... // this.checkCache.loadCache(fileName) } /* (non-Javadoc) * @see net.xeoh.plugins.remotediscovery.RemoteDiscovery#discover(java.lang.Class, net.xeoh.plugins.remotediscovery.options.DiscoverOption[]) */ public Collection<DiscoveredPlugin> discover(Class<? extends Plugin> plugin, DiscoverOption... options) { refreshKnownDiscoveryManagers(); //* new 2 final CompletionService<Collection<DiscoveredPlugin>> compService = new ExecutorCompletionService<Collection<DiscoveredPlugin>>(Executors.newFixedThreadPool(2, this.threadFactory)); this.checkCache.initCall(plugin, options); this.discover.initCall(plugin, options); List<Future<Collection<DiscoveredPlugin>>> futures = new ArrayList<Future<Collection<DiscoveredPlugin>>>(); futures.add(compService.submit(this.checkCache)); futures.add(compService.submit(this.discover)); Future<Collection<DiscoveredPlugin>> completedFuture; Collection<DiscoveredPlugin> foundPlugins = null; while (!futures.isEmpty()) { try { completedFuture = compService.take(); } catch (InterruptedException e) { e.printStackTrace(); return null; } futures.remove(completedFuture); try { foundPlugins = completedFuture.get(); if (foundPlugins != null && !foundPlugins.isEmpty() && !futures.isEmpty()) { // so we found something, just remote the other one... futures.get(0).cancel(true); break; } } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } } return foundPlugins; } /** */ @net.xeoh.plugins.base.annotations.Timer(period = 260) public void discoverThread() { this.logger.fine("Starting new discover pass"); try { this.logger.finer("Awaiting latch"); this.startupLatch.await(); } catch (InterruptedException e) { e.printStackTrace(); return; } this.logger.finer("Latch passed"); // Increase counter this.discoverThreadCounter.incrementAndGet(); // Create empty data. ServiceInfo[] infos = new ServiceInfo[0]; // Magic: Get all network services of our type. try { this.logger.finer("Trying to lock jmDNS lock"); this.jmdnsLock.lock(); this.logger.finer("Lock obtained. Listing known entries of our type"); // TODO: jmdsn can be null if no network card is present infos = this.jmdns.list(TYPE); this.logger.finer("List obtained."); } catch (IllegalStateException e) { this.logger.warning("Error discovering plugins ..."); } finally { this.jmdnsLock.unlock(); this.logger.finer("Lock unlocked."); } // Reset all service infos try { this.logger.finer("Trying to obtain service info lock."); this.serviceInfosLock.lock(); this.logger.finer("Service info lock obtained. Transferring data."); this.serviceInfos.clear(); this.serviceInfos.addAll(Arrays.asList(infos)); this.logger.finer("Data transferred."); } finally { this.serviceInfosLock.unlock(); this.logger.finer("Service info unlocked."); } // Process all callbacks. final Collection<CallbackRequest> toRemove = new ArrayList<CallbackRequest>(); // // TODO: This callback handling needs improvement. Check for // unsynchronized access to the allRequest structure // // Check all callbacks, if they need, well, a callback for (CallbackRequest cr : this.allRequests) { final Collection<DiscoveredPlugin> found = resolve(cr.req, cr.moreOptions); if (found.size() > 0) { cr.oc.getCallback().pluginsDiscovered(found); toRemove.add(cr); } } this.logger.finer("Callbacks executed. Removing items."); // Remove all resolved callbacks for (CallbackRequest callbackRequest : toRemove) { callbackRequest.cancelTimeout(); this.allRequests.remove(callbackRequest); } this.logger.fine("Disover pass ended."); } /* (non-Javadoc) * @see net.xeoh.plugins.remotediscovery.RemoteDiscovery#revokePlugin(net.xeoh.plugins.base.Plugin, net.xeoh.plugins.remote.PublishMethod, java.net.URI) */ public void revokePlugin(Plugin plugin, PublishMethod publishMethod, URI uri) { // TODO Auto-generated method stub } /** */ @Shutdown public void shutdown() { final java.lang.Thread t = new java.lang.Thread(new Runnable() { public void run() { RemoteDiscoveryImpl.this.jmdnsLock.lock(); // All of these statements tend to fail because of various reasons. During the shutdown however, // we want to ignore them all ... try { try { RemoteDiscoveryImpl.this.localManagerExportServer.close(); } catch (Exception e) { // } try { RemoteDiscoveryImpl.this.jmdns.unregisterAllServices(); } catch (Exception e) { // } try { RemoteDiscoveryImpl.this.jmdns.close(); } catch (Exception e) { // } } finally { RemoteDiscoveryImpl.this.jmdnsLock.unlock(); } } }); t.setDaemon(true); t.start(); // this.checkCache.printCache(); this.checkCache.saveCache(); } private boolean awaitInitializationTime() { // Check if we're still on startup lock final long delay = this.timeOfStartup + this.startupLock - System.currentTimeMillis(); if (delay > 0) { // If we are, halt this thread until lock time has passed. // Unfortunatly the lookup is a // bit "unstable" during the first few miliseconds. try { java.lang.Thread.sleep(delay); } catch (InterruptedException e) { e.printStackTrace(); return false; } } return true; } /** * Returns the remote proxy to a discovery manager for a given IP / port * * @param ip * @param port * @return */ @SuppressWarnings("unchecked") DiscoveryManager getRemoteProxy(String ip, int port) { try { final String address = ip + ":" + port; final int timeout = 500; // 500 ms RemoteAPIImpl if need detailed // version... final DiscoveryManager newClient = Proxies.newClient(EXPORT_NAME, address, RemoteDiscoveryImpl.class.getClassLoader(), DiscoveryManager.class); /* * TODO: With this one we still get the message: * * "org.freshvanilla.net.VanillaDataSocket allocateBuffer * INFO: DiscoveryManager: Running low on memory, pausing..." * * but, there is no TimeoutException.... * * @sa DiscoveredPluginTest.testMultiplePlugins() */ @SuppressWarnings("unused") int pingRes = newClient.ping(123321); // Execute collection asynchronously (TODO: cache pool usage could be // improved) final ExecutorService cachePool = Executors.newCachedThreadPool(); final ExecutorCompletionService<String> ecs = new ExecutorCompletionService(cachePool); final Future<String> future = ecs.submit(new Callable<String>() { public String call() throws Exception { return AccessController.doPrivileged(new PrivilegedAction<String>() { public String run() { return newClient.toString(); } }); } }); // Wait at most half a second (TODO: Make this configurable) try { final String string = future.get(timeout, TimeUnit.MILLISECONDS); /* * TODO: Probably it is possible to put here some conversion routines... Because it looks like that * only the ExportInfo makes trouble.... Or just make the ExportInfo much better, ie downwards compatible */ if (string == null || newClient.getVersion() != this.localManager.getVersion()) { return null; } return newClient; } catch (final InterruptedException e) { // TODO: This one is not an error anymore. // Interruption is called because we are running cache thread. // System.err // .println("Error while waiting for a getRemoteProxy() result"); // e.printStackTrace(); } catch (final ExecutionException e) { e.printStackTrace(); } catch (final TimeoutException e) { e.printStackTrace(); } catch (final SecurityException e) { e.printStackTrace(); } finally { AccessController.doPrivileged(new PrivilegedAction<Object>() { public Object run() { future.cancel(true); cachePool.shutdownNow(); return null; } }); } return null; } finally { } } /** * Refreshes all known discovery managers. */ private void refreshKnownDiscoveryManagers() { this.serviceInfosLock.lock(); try { this.remoteManagersEndpoints.clear(); // Check all service infos with discovery managers for (ServiceInfo serviceInfo : this.serviceInfos) { final InetAddress address = serviceInfo.getAddress(); final int port = serviceInfo.getPort(); System.out.println("mgr: " + address + " " + port); this.remoteManagersEndpoints.add(new RemoteManagerEndpoint(address, port)); } } finally { this.serviceInfosLock.unlock(); } } /** * Checks all known service infos for matches to the given class, returns * all matching entries. * * @param plugin * @param options * @return */ private Collection<DiscoveredPlugin> resolve(final Class<? extends Plugin> plugin, DiscoverOption[] options) { // Refreshes all known remote discovery managers. // refreshKnownDiscoveryManagers(); // The result we intend to return Collection<DiscoveredPlugin> result = new ArrayList<DiscoveredPlugin>(); // new ArrayList<DiscoveredPlugin>(); // Query all managers for (final RemoteManagerEndpoint endpoint : this.remoteManagersEndpoints) { // The manager to use ... final DiscoveryManager mgr = RemoteDiscoveryImpl.this.getRemoteProxy(endpoint.address.getHostAddress(), endpoint.port); // No matter what happens, close the manager try { if (mgr == null) { this.logger.info("Remote DiscoveryManager at " + endpoint.address.getHostAddress() + ":" + endpoint.port + " did not answer or has not the right version."); continue; } // TODO: here are probably not the complete information as it was before.... // RemoteDiscoveryImpl.this.logger.info("Error getting ping time of remote manager " + // endpoint.address + ":" + endpoint.port); final AtomicInteger pingTime = getPingTime(mgr, endpoint.address.getHostAddress(), endpoint.port); // Query the information (needs to be inside a privileged block, otherwise applets might complain. final ExportInfo exportInfo = AccessController.doPrivileged(new PrivilegedAction<ExportInfo>() { public ExportInfo run() { return mgr.getExportInfoFor(plugin.getCanonicalName()); } }); // If the plugin in not exported, do nothing if (!exportInfo.isExported) continue; // If it is, construct required data. String hostAddress = (endpoint.address != null) ? endpoint.address.getHostAddress() : "127.0.0.1"; DiscoveredPlugin discPlugin = constructPlugins(hostAddress, exportInfo.allExported, pingTime.get()); this.checkCache.addToCache(plugin, endpoint, discPlugin); result.add(discPlugin); } catch (ClassCastException e) { // This should not be happen anymore.... this.logger.warning(" Trying to convert a object from v2 to v3."); e.printStackTrace(); } finally { // In case the manager is of the type simple resource (which it should be), try to close it. if (mgr instanceof SimpleResource) { try { // Try to close our device again AccessController.doPrivileged(new PrivilegedAction<Object>() { public Object run() { ((SimpleResource) mgr).close(); return null; } }); } catch (Exception e) { e.printStackTrace(); this.logger.fine("Error closing remote DiscoveryManager ..."); } } } } // If we have no result there is nothing to do if (result.size() == 0) { return new ArrayList<DiscoveredPlugin>(); } // doFilter(result, options); return result; } final DiscoveredPlugin constructPlugins(final String hostAddress, final Collection<ExportedPlugin> plugins, final int pingTime) { // If it is, construct required data. for (ExportedPlugin p : plugins) { final PublishMethod method = PublishMethod.valueOf(p.exportMethod); final URI uri = p.exportURI; String _newURI = ""; _newURI += uri.getScheme(); _newURI += "://"; _newURI += hostAddress; _newURI += ":"; _newURI += uri.getPort(); _newURI += uri.getPath(); try { // TODO: Compute distance properly. return new DiscoveredPluginImpl(method, new URI(_newURI), pingTime, p.timeSinceExport); } catch (URISyntaxException e) { e.printStackTrace(); } } return null; } final void doFilter(Collection<DiscoveredPlugin> plugins, DiscoverOption[] options) { final OptionUtils<DiscoverOption> ou = new OptionUtils<DiscoverOption>(options); DiscoveredPlugin best = plugins.iterator().next(); if (ou.contains(OptionNearest.class)) { // Check all plugins for (DiscoveredPlugin p : plugins) { // If this one is closer, replace them if (p.getDistance() < best.getDistance()) { best = p; } } // Remove all other plugins plugins.clear(); plugins.add(best); } if (ou.contains(OptionYoungest.class)) { // Check all plugins for (DiscoveredPlugin p : plugins) { // If this one is closer, replace them if (p.getTimeSinceExport() < best.getTimeSinceExport()) { best = p; } } // Remove all other plugins plugins.clear(); plugins.add(best); } if (ou.contains(OptionOldest.class)) { // Check all plugins for (DiscoveredPlugin p : plugins) { // If this one is closer, replace them if (p.getTimeSinceExport() > best.getTimeSinceExport()) { best = p; } } // Remove all other plugins plugins.clear(); plugins.add(best); } } /* * we are passing the InterruptedException, because this fct can be interrupted by cache-thread. */ Collection<DiscoveredPlugin> doRemoteDiscover(Class<? extends Plugin> plugin, DiscoverOption... options) throws InterruptedException { // Wait until init is done ... try { this.startupLatch.await(); } catch (InterruptedException e) { e.printStackTrace(); return new ArrayList<DiscoveredPlugin>(); } // Timelock: Wait for a certain time to pass since startup if (this.lockMode.equals("timelock")) { if (awaitInitializationTime() == false) { return new ArrayList<DiscoveredPlugin>(); } } // Onepass: Wait for the discover to execute once if (this.lockMode.equals("onepass")) { // Also wait some time here, otherwise we won't find all plugins in // all cases awaitInitializationTime(); // Wait at least one discoverThreadTurn final long lastDisoverValue = this.discoverThreadCounter.get(); final long startOfWait = System.currentTimeMillis(); while (this.discoverThreadCounter.get() == lastDisoverValue) { java.lang.Thread.sleep(100); // Safety check if (System.currentTimeMillis() > startOfWait + 1000) { throw new IllegalStateException("We are waiting way too long."); } } } for (DiscoverOption option : options) { // If we have a callback option, add to request list. if (option instanceof OptionCallback) { this.allRequests.add(new CallbackRequest(this, plugin, (OptionCallback) option, options)); } } // Eventually resolve the request. return resolve(plugin, options); } final AtomicInteger getPingTime(final DiscoveryManager mgr, final String address, final int port) { final AtomicInteger pingTime = new AtomicInteger(Integer.MAX_VALUE); // Get ping time AccessController.doPrivileged(new PrivilegedAction<Object>() { public Object run() { try { final long start = System.nanoTime(); // Perform the ping mgr.ping(new Random().nextInt()); // Obtain the time final long stop = System.nanoTime(); final long time = (stop - start) / 1000; // And set it RemoteDiscoveryImpl.this.logger.finer("Ping time to manager was " + time + "µs"); pingTime.set((int) time); } catch (Exception e) { RemoteDiscoveryImpl.this.logger.info("Error getting ping time of remote manager " + address + ":" + port); } return null; } }); return pingTime; } void syso(final String s) { synchronized (System.out) { System.out.println(s); } } }
100json-jspf
modules/plugins/remote.discovery/src/net/xeoh/plugins/remotediscovery/impl/v3/RemoteDiscoveryImpl.java
Java
bsd
29,092
package net.xeoh.plugins.remotediscovery.impl.v3; import java.util.Timer; import java.util.TimerTask; import net.xeoh.plugins.base.Plugin; import net.xeoh.plugins.remotediscovery.options.DiscoverOption; import net.xeoh.plugins.remotediscovery.options.discover.OptionCallback; /** * A request for callbacks. * * @author rb * */ public class CallbackRequest { /** */ final RemoteDiscoveryImpl remoteDiscoveryImpl; /** */ Class<? extends Plugin> req; /** */ OptionCallback oc; /** */ DiscoverOption[] moreOptions; /** */ Timer timer = new Timer(); /** * @param remoteDiscoveryImpl * @param p * @param c * @param moreOptions */ public CallbackRequest(final RemoteDiscoveryImpl remoteDiscoveryImpl, Class<? extends Plugin> p, OptionCallback c, DiscoverOption... moreOptions) { this.remoteDiscoveryImpl = remoteDiscoveryImpl; this.req = p; this.oc = c; this.moreOptions = moreOptions; if (this.oc.getTimeout() > 0) { this.timer.schedule(new TimerTask() { @Override public void run() { CallbackRequest.this.oc.getCallback().timeout(); cancelTimeout(); remoteDiscoveryImpl.allRequests.remove(remoteDiscoveryImpl); } }, this.oc.getTimeout()); } } /** * */ public void cancelTimeout() { try { this.timer.cancel(); } catch (Throwable t) { // } } }
100json-jspf
modules/plugins/remote.discovery/src/net/xeoh/plugins/remotediscovery/impl/v3/CallbackRequest.java
Java
bsd
1,647
package net.xeoh.plugins.remotediscovery.impl.v3; import java.io.Serializable; import java.net.InetAddress; /** * * @author rb * */ final class RemoteManagerEndpoint implements Serializable { private static final long serialVersionUID = -7370418870963776624L; public InetAddress address; public int port; /** * @param adr * @param port */ public RemoteManagerEndpoint(InetAddress adr, int port) { this.address = adr; this.port = port; } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ @Override public int hashCode() { return this.address.hashCode() ^ this.port; } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || !(o instanceof RemoteManagerEndpoint)) return false; RemoteManagerEndpoint rme = (RemoteManagerEndpoint) o; return this.address == rme.address && this.port == rme.port; } }
100json-jspf
modules/plugins/remote.discovery/src/net/xeoh/plugins/remotediscovery/impl/v3/RemoteManagerEndpoint.java
Java
bsd
1,062
/* * DiscoverCall.java * * Copyright (c) 2010, Ralf Biedert All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package net.xeoh.plugins.remotediscovery.impl.v3; import java.util.Collection; import net.xeoh.plugins.remotediscovery.DiscoveredPlugin; class DiscoverCall extends BaseCall { /** * */ private final RemoteDiscoveryImpl remoteDiscoveryImpl; /** * @param remoteDiscoveryImpl */ DiscoverCall(RemoteDiscoveryImpl remoteDiscoveryImpl) { this.remoteDiscoveryImpl = remoteDiscoveryImpl; } public Collection<DiscoveredPlugin> call() { try { this.remoteDiscoveryImpl.syso("discover 1"); // TODO: doRemoteDiscover() and e.resolve() above are the most time consuming functions!!!! Collection<DiscoveredPlugin> res = this.remoteDiscoveryImpl.doRemoteDiscover(this.getPlugin(), this.getDiscoverOptions()); this.remoteDiscoveryImpl.syso("discover 2"); if (res == null) { this.remoteDiscoveryImpl.syso("discover 3"); return null; } // so we are ready... // Filter is there, so that cache contains unfiltered plugins this.remoteDiscoveryImpl.syso("discover 4"); if (!res.isEmpty()) { this.remoteDiscoveryImpl.syso("discover 5"); this.remoteDiscoveryImpl.doFilter(res, getDiscoverOptions()); } if (!res.isEmpty()) this.remoteDiscoveryImpl.syso("---> discovery cache miss."); this.remoteDiscoveryImpl.syso("discover 6"); return res; } catch (InterruptedException e) { // so cache thread was faster... return null; } } }
100json-jspf
modules/plugins/remote.discovery/src/net/xeoh/plugins/remotediscovery/impl/v3/DiscoverCall.java
Java
bsd
3,209
/* * BaseCall.java * * Copyright (c) 2010, Ralf Biedert All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package net.xeoh.plugins.remotediscovery.impl.v3; import java.util.Collection; import java.util.concurrent.Callable; import net.xeoh.plugins.base.Plugin; import net.xeoh.plugins.remotediscovery.DiscoveredPlugin; import net.xeoh.plugins.remotediscovery.options.DiscoverOption; /** * @author Eugen Massini * */ abstract class BaseCall implements Callable<Collection<DiscoveredPlugin>> { private DiscoverOption[] discoverOptions; private Class<? extends Plugin> plugin; public final void initCall(final Class<? extends Plugin> plugin1, final DiscoverOption[] options) { this.plugin = plugin1; this.discoverOptions = options; } protected final DiscoverOption[] getDiscoverOptions() { return this.discoverOptions; } protected final Class<? extends Plugin> getPlugin() { return this.plugin; } }
100json-jspf
modules/plugins/remote.discovery/src/net/xeoh/plugins/remotediscovery/impl/v3/BaseCall.java
Java
bsd
2,453
package net.xeoh.plugins.remotediscovery.impl.v3; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.net.URI; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; import net.xeoh.plugins.base.Plugin; import net.xeoh.plugins.remote.PublishMethod; import net.xeoh.plugins.remotediscovery.DiscoveredPlugin; import net.xeoh.plugins.remotediscovery.impl.common.discoverymanager.DiscoveryManager; import net.xeoh.plugins.remotediscovery.impl.common.discoverymanager.ExportInfo; import org.freshvanilla.utils.SimpleResource; /** * * NOTE: This cache saves only one host for a plugin and not the whole bunch.... * * @author massini * */ final class CheckCacheCall extends BaseCall { /** * */ private final RemoteDiscoveryImpl remoteDiscoveryImpl; /** * @param remoteDiscoveryImpl */ CheckCacheCall(RemoteDiscoveryImpl remoteDiscoveryImpl) { this.remoteDiscoveryImpl = remoteDiscoveryImpl; } /** * Contains plugins which are exported by a specified DiscoveryManager * * @author massini * */ class Entry implements Serializable { private static final long serialVersionUID = -7595621607661329454L; RemoteManagerEndpoint manager; String plugin; DiscoveredPlugin src; public Entry(final String plugin, final RemoteManagerEndpoint manager, final DiscoveredPlugin src) { this.plugin = plugin; this.manager = manager; this.src = src; } /* @Override public String toString(){ StringBuffer buf=new StringBuffer(); buf.append("\t"+this.plugin+"\n"); buf.append("\tmgr: "+this.manager+"\n"); buf.append("\tsrc: "+this.src.getPublishURI()+" "+this.src.getPublishMethod()+"\n"); buf.append("\t"+this.src.getCapabilities()); return buf.toString(); } //*/ @SuppressWarnings("boxing") private synchronized void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { this.plugin = (String) in.readObject(); this.manager = (RemoteManagerEndpoint) in.readObject(); // read DiscoveredPlugin URI uri = (URI) in.readObject(); int dist = (Integer) in.readObject(); PublishMethod method = (PublishMethod) in.readObject(); int numCaps = (Integer) in.readObject(); List<String> caps = new ArrayList<String>(); for (int i = 0; i < numCaps; ++i) caps.add((String) in.readObject()); // TODO: put some method to aquire update of timeSinceStartUp this.src = new DiscoveredPluginImpl(caps, method, uri, dist, 0); } @SuppressWarnings( { "boxing", "cast" }) private synchronized void writeObject(ObjectOutputStream out) throws IOException { // TODO: !!! WICHTIG!! was ist mit serialVersionUID muss sie auch gespeichert werden? out.writeObject(this.plugin); out.writeObject(this.manager); // write discoveredPlugin out.writeObject(this.src.getPublishURI()); out.writeObject((Integer) this.src.getDistance()); out.writeObject(this.src.getPublishMethod()); out.writeObject(this.src.getCapabilities().size()); for (String s : this.src.getCapabilities()) out.writeObject(s); } // TODO: WICHTIG:::: Save/Load DiscoveredPlugin with the right methods } private static final String CACHE_FILE = "d:\\cachefile.dat"; private HashMap<Class<? extends Plugin>, HashMap<RemoteManagerEndpoint, Entry>> cache = new HashMap<Class<? extends Plugin>, HashMap<RemoteManagerEndpoint, Entry>>(); public void addToCache(Class<? extends Plugin> plugin, final RemoteManagerEndpoint manager, final DiscoveredPlugin src) { synchronized (this.cache) { // 1) get all managers providing this plugin HashMap<RemoteManagerEndpoint, Entry> managers = this.cache.get(plugin); if (null == managers) { // if we dont have one, so create managers = new HashMap<RemoteManagerEndpoint, Entry>(); managers.put(manager, new Entry(plugin.getCanonicalName(), manager, src)); this.cache.put(plugin, managers); return; } // 2) get the entry providing this plugin. Entry entry = managers.get(manager); if (null == entry) { // no entry managers.put(manager, new Entry(plugin.getCanonicalName(), manager, src)); return; } // 3) here it means we have already an entry... so skip!!! } } public Collection<DiscoveredPlugin> call() { this.remoteDiscoveryImpl.syso("cache 1"); final Collection<Entry> entries = getEntryList(getPlugin()); this.remoteDiscoveryImpl.syso("cache entries " + entries.size()); this.remoteDiscoveryImpl.syso("cache 2"); Collection<DiscoveredPlugin> available = remoteUnavailable(entries); this.remoteDiscoveryImpl.syso("cache 3"); this.remoteDiscoveryImpl.syso("cache available " + available.size()); this.remoteDiscoveryImpl.syso("cache 4"); if (!available.isEmpty()) { this.remoteDiscoveryImpl.syso("cache 5"); this.remoteDiscoveryImpl.doFilter(available, getDiscoverOptions()); } this.remoteDiscoveryImpl.syso("cache 6"); this.remoteDiscoveryImpl.syso("cache: available " + available.size()); this.remoteDiscoveryImpl.syso("cache 7"); if (!available.isEmpty()) this.remoteDiscoveryImpl.syso("---> discovery cache hit."); this.remoteDiscoveryImpl.syso("cache 8"); return available; } @SuppressWarnings( { "boxing", "unchecked" }) public void loadCache() { this.cache.clear(); try { ObjectInputStream in = new ObjectInputStream(new FileInputStream(CACHE_FILE)); this.remoteDiscoveryImpl.syso("load cache"); try { final int cacheSize = (Integer) in.readObject(); // syso("size "+cacheSize); for (int i = 0; i < cacheSize; ++i) { HashMap<RemoteManagerEndpoint, Entry> rmee = new HashMap<RemoteManagerEndpoint, Entry>(); Class<? extends Plugin> plugin = (Class<? extends Plugin>) in.readObject(); this.remoteDiscoveryImpl.syso(plugin.getCanonicalName()); // syso("\t"+i+"'"+pluginName+"'"); int numEntries = (Integer) in.readObject(); // syso("\t"+numEntries); for (int j = 0; j < numEntries; ++j) { Entry entry = (Entry) in.readObject(); // syso("\t\t"+entry); rmee.put(entry.manager, entry); } this.cache.put(plugin, rmee); } } catch (ClassNotFoundException e) { e.printStackTrace(); } finally { in.close(); } } catch (FileNotFoundException e) { this.remoteDiscoveryImpl.logger.warning("Loading cache file" + CACHE_FILE + " failed."); } catch (IOException e) { e.printStackTrace(); } } // public void printCache() { // for(Map.Entry<String, Entry> e: this.cache.entrySet()){ // System.out.println(e.getKey()+" "+e.getValue()); // } // } @SuppressWarnings("boxing") public void saveCache() { try { ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(CACHE_FILE)); this.remoteDiscoveryImpl.syso("save cache"); try { // syso("size"+this.cache.size()); out.writeObject(this.cache.size()); for (Map.Entry<Class<? extends Plugin>, HashMap<RemoteManagerEndpoint, Entry>> he : this.cache.entrySet()) { // syso(he.getKey()+" " +he.getValue().size()); this.remoteDiscoveryImpl.syso(he.getKey().getCanonicalName()); out.writeObject(he.getKey()); out.writeObject(he.getValue().size()); for (Entry me : he.getValue().values()) { // syso("\t"+me); out.writeObject(me); } } // out.writeObject(this.cache); } finally { out.close(); } } catch (IOException e) { e.printStackTrace(); } } private Collection<Entry> getEntryList(Class<? extends Plugin> plugin) { synchronized (this.cache) { HashMap<RemoteManagerEndpoint, Entry> managers = this.cache.get(plugin); if (managers == null) return new ArrayList<Entry>(); return managers.values(); } } private Collection<DiscoveredPlugin> remoteUnavailable(final Collection<Entry> lst) { Collection<DiscoveredPlugin> res = new ArrayList<DiscoveredPlugin>(); this.remoteDiscoveryImpl.syso("cache rem 1"); for (Entry entry : lst) { this.remoteDiscoveryImpl.syso("cache rem 2"); // try to establish connection to the discovery manager this.remoteDiscoveryImpl.syso("cache rem 3"); final DiscoveryManager mgr = this.remoteDiscoveryImpl.getRemoteProxy(entry.manager.address.getHostAddress(), entry.manager.port); this.remoteDiscoveryImpl.syso("cache rem 4"); if (null == mgr) { this.remoteDiscoveryImpl.syso("cache rem 5"); // so manager not available. -> remote from cache // TODO!!! continue; } this.remoteDiscoveryImpl.syso("cache rem 6"); // so our manager is available...... try { this.remoteDiscoveryImpl.syso("cache rem 7"); // TODO: here are probably not the complete information as it was before.... // RemoteDiscoveryImpl.this.logger.info("Error getting ping time of remote manager " + // endpoint.address + ":" + endpoint.port); @SuppressWarnings("unused") final AtomicInteger pingTime = this.remoteDiscoveryImpl.getPingTime(mgr, entry.manager.address.getHostAddress(), entry.manager.port); this.remoteDiscoveryImpl.syso("cache rem 8"); // Query the information (needs to be inside a privileged block, otherwise applets might complain. final ExportInfo exportInfo = AccessController.doPrivileged(new PrivilegedAction<ExportInfo>() { public ExportInfo run() { return mgr.getExportInfoFor(getPlugin().getCanonicalName()); } }); this.remoteDiscoveryImpl.syso("cache rem 9"); // If the plugin in not exported, do nothing if (!exportInfo.isExported) { this.remoteDiscoveryImpl.syso("cache rem 10"); // this plugin is not exported anymore... // TODO: remote from cache list continue; } this.remoteDiscoveryImpl.syso("cache rem 11"); // ... otherwise the plugin is available! put in list res.add(entry.src); this.remoteDiscoveryImpl.syso("cache rem 12"); } finally { this.remoteDiscoveryImpl.syso("cache rem 13"); // In case the manager is of the type simple resource (which it should be), try to close it. if (mgr instanceof SimpleResource) { try { // Try to close our device again AccessController.doPrivileged(new PrivilegedAction<Object>() { public Object run() { ((SimpleResource) mgr).close(); return null; } }); } catch (Exception e) { e.printStackTrace(); this.remoteDiscoveryImpl.logger.fine("Error closing remote DiscoveryManager ..."); } } this.remoteDiscoveryImpl.syso("cache rem 14"); } } // for each Entry this.remoteDiscoveryImpl.syso("cache rem 15"); return res; } }
100json-jspf
modules/plugins/remote.discovery/src/net/xeoh/plugins/remotediscovery/impl/v3/CheckCacheCall.java
Java
bsd
13,466
package net.xeoh.plugins.remotediscovery.impl.v2; import java.net.URI; import java.util.ArrayList; import java.util.List; import net.xeoh.plugins.remote.PublishMethod; import net.xeoh.plugins.remotediscovery.DiscoveredPlugin; /** * @author Thomas Lottermann */ public class DiscoveredPluginImpl implements DiscoveredPlugin { private final List<String> capabilities; private final PublishMethod publishMethod; private final URI publishURI; private final int distance; private final long timeSinceExport; /* (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { return "DiscoveredPlugin [" + this.publishMethod + "]"; } /** * @param capabilities * @param publishMethod * @param publishURI * @param distance * @param timeSincceExport */ public DiscoveredPluginImpl(List<String> capabilities, PublishMethod publishMethod, URI publishURI, int distance, long timeSincceExport) { this.capabilities = capabilities; this.publishMethod = publishMethod; this.publishURI = publishURI; this.distance = distance; this.timeSinceExport = timeSincceExport; } /** * @param publishMethod * @param publishURI * @param distance */ public DiscoveredPluginImpl(PublishMethod publishMethod, URI publishURI, int distance) { this(new ArrayList<String>(), publishMethod, publishURI, distance, 0); } /** * @param publishMethod * @param publishURI * @param distance * @param timeSinceExport */ public DiscoveredPluginImpl(PublishMethod publishMethod, URI publishURI, int distance, long timeSinceExport) { this(new ArrayList<String>(), publishMethod, publishURI, distance, timeSinceExport); } /* (non-Javadoc) * @see net.xeoh.plugins.remotediscovery.DiscoveredPlugin#getCapabilities() */ public List<String> getCapabilities() { return this.capabilities; } /* (non-Javadoc) * @see net.xeoh.plugins.remotediscovery.DiscoveredPlugin#getPublishMethod() */ public PublishMethod getPublishMethod() { return this.publishMethod; } /* (non-Javadoc) * @see net.xeoh.plugins.remotediscovery.DiscoveredPlugin#getPublishURI() */ public URI getPublishURI() { return this.publishURI; } /* (non-Javadoc) * @see net.xeoh.plugins.remotediscovery.DiscoveredPlugin#getDistance() */ public int getDistance() { return this.distance; } /* (non-Javadoc) * @see net.xeoh.plugins.remotediscovery.DiscoveredPlugin#getTimeSinceExport() */ public long getTimeSinceExport() { return this.timeSinceExport; } }
100json-jspf
modules/plugins/remote.discovery/src/net/xeoh/plugins/remotediscovery/impl/v2/DiscoveredPluginImpl.java
Java
bsd
2,940
package net.xeoh.plugins.remotediscovery.impl.v2; import java.io.IOException; import java.net.InetAddress; import java.net.ServerSocket; import java.net.URI; import java.net.URISyntaxException; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Random; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.Callable; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorCompletionService; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import java.util.logging.Logger; import javax.jmdns.JmDNS; import javax.jmdns.ServiceInfo; import javax.jmdns.impl.tasks.ServiceResolver; import net.xeoh.plugins.base.Plugin; import net.xeoh.plugins.base.PluginConfiguration; import net.xeoh.plugins.base.PluginInformation; import net.xeoh.plugins.base.annotations.PluginImplementation; import net.xeoh.plugins.base.annotations.Thread; import net.xeoh.plugins.base.annotations.configuration.IsDisabled; import net.xeoh.plugins.base.annotations.events.Shutdown; import net.xeoh.plugins.base.annotations.injections.InjectPlugin; import net.xeoh.plugins.base.util.OptionUtils; import net.xeoh.plugins.base.util.PluginConfigurationUtil; import net.xeoh.plugins.remote.PublishMethod; import net.xeoh.plugins.remotediscovery.DiscoveredPlugin; import net.xeoh.plugins.remotediscovery.RemoteDiscovery; import net.xeoh.plugins.remotediscovery.impl.common.discoverymanager.DiscoveryManager; import net.xeoh.plugins.remotediscovery.impl.common.discoverymanager.ExportInfo; import net.xeoh.plugins.remotediscovery.impl.common.discoverymanager.ExportedPlugin; import net.xeoh.plugins.remotediscovery.impl.common.discoverymanager.impl.AbstractDiscoveryManager; import net.xeoh.plugins.remotediscovery.impl.common.discoverymanager.impl.tcpip.DiscoveryManagerTCPIPImpl; import net.xeoh.plugins.remotediscovery.options.DiscoverOption; import net.xeoh.plugins.remotediscovery.options.discover.OptionCallback; import net.xeoh.plugins.remotediscovery.options.discover.OptionNearest; import net.xeoh.plugins.remotediscovery.options.discover.OptionOldest; import net.xeoh.plugins.remotediscovery.options.discover.OptionYoungest; import org.freshvanilla.rmi.Proxies; import org.freshvanilla.rmi.VanillaRmiServer; import org.freshvanilla.utils.SimpleResource; /** * @author Thomas Lottermann * */ @IsDisabled @PluginImplementation public class RemoteDiscoveryImpl implements RemoteDiscovery { /** */ final Logger logger = Logger.getLogger(this.getClass().getName()); private static final String TYPE = "_jspfplugindiscovery._tcp.local."; private static final String EXPORT_NAME = "DiscoveryManager"; private static final String NAME = "JSPF"; private int startupLock; /** How we lock for the first call? */ private String lockMode; /** * Constructs daemonic threads */ ThreadFactory threadFactory = new ThreadFactory() { public java.lang.Thread newThread(Runnable r) { java.lang.Thread rval = new java.lang.Thread(r); rval.setDaemon(true); return rval; } }; /** * A request for callbacks. * * @author rb * */ class CallbackRequest { Class<? extends Plugin> req; OptionCallback oc; DiscoverOption[] moreOptions; Timer timer = new Timer(); public CallbackRequest(Class<? extends Plugin> p, OptionCallback c, DiscoverOption... moreOptions) { this.req = p; this.oc = c; this.moreOptions = moreOptions; if (this.oc.getTimeout() > 0) { this.timer.schedule(new TimerTask() { @Override public void run() { CallbackRequest.this.oc.getCallback().timeout(); cancelTimeout(); RemoteDiscoveryImpl.this.allRequests.remove(CallbackRequest.this); } }, this.oc.getTimeout()); } } public void cancelTimeout() { try { this.timer.cancel(); } catch (Throwable t) { // } } } /** * * @author rb * */ static class RemoteManagerEndpoint { /** */ public InetAddress address; /** */ public int port; /** * @param adr * @param port */ public RemoteManagerEndpoint(InetAddress adr, int port) { this.address = adr; this.port = port; } public RemoteManagerEndpoint() { // TODO Auto-generated constructor stub } } /** All callbacks for discovered plugins */ protected final List<CallbackRequest> allRequests = new ArrayList<CallbackRequest>(); /** */ protected final Lock serviceInfosLock = new ReentrantLock(); /** */ protected final Lock jmdnsLock = new ReentrantLock(); /** */ protected final CountDownLatch startupLatch = new CountDownLatch(1); /** usually should contain only all DiscoveryManager; */ protected final Collection<ServiceInfo> serviceInfos = new ArrayList<ServiceInfo>(); /** Contains a list of remote DiscoveryManagers all over the network and also the local manager. This is not final as we replace * it every iteration. This way the client has the chance to grab a local "copy" and work on it while a more receent version is * being prepared*/ protected volatile Collection<RemoteManagerEndpoint> remoteManagersEndpoints = new ArrayList<RemoteManagerEndpoint>(); /** The local manager */ protected final AbstractDiscoveryManager localTCPIPManager = new DiscoveryManagerTCPIPImpl(); /** Server of the exported local manager */ VanillaRmiServer<DiscoveryManager> localManagerExportServer; JmDNS jmdns; long timeOfStartup; /** */ AtomicLong discoverThreadCounter = new AtomicLong(); /** */ @InjectPlugin public PluginInformation pluginInformation; /** */ @InjectPlugin public PluginConfiguration pluginConfiguration; /** */ @SuppressWarnings("boxing") @Thread(isDaemonic = true) public void backgroundInit() { // (Ralf:) zomfg, this is one of the worst hacks i've done the last couple of months. Deep within jmdns we placed a variable to // override a check if it is already save to transmit something. jmDNS usually takes 5 seconds to reach that state, but that's // too long for us. If you set this variable the check will be skipped and the request should take place much faster. // Appears to work(tm). ServiceResolver.ANNOUNCE_OVERRIDE = true; this.logger.fine("Staring background init"); final PluginConfigurationUtil pcu = new PluginConfigurationUtil(this.pluginConfiguration); this.startupLock = pcu.getInt(RemoteDiscovery.class, "startup.locktime", 1000); this.lockMode = pcu.getString(RemoteDiscovery.class, "startup.lockmode", "onepass"); try { this.logger.finer("Locking"); this.jmdnsLock.lock(); this.jmdns = JmDNS.create(); // Maybe init with local loopback in case no other network card is present, otherwise returns null this.timeOfStartup = System.currentTimeMillis(); final int port = getFreePort(); final ServiceInfo service = ServiceInfo.create(TYPE, NAME + " @" + this.timeOfStartup, port, 0, 0, EXPORT_NAME); this.logger.finer("Exporting at port " + port); this.localManagerExportServer = Proxies.newServer(EXPORT_NAME, port, (DiscoveryManager) this.localTCPIPManager); this.logger.finer("Announcing at port " + port); this.jmdns.registerService(service); // Set it again, this time for the lock below this.timeOfStartup = System.currentTimeMillis(); } catch (IOException e) { e.printStackTrace(); } catch (IllegalStateException e) { this.logger.warning("Error starting discovery."); } finally { this.logger.finer("Unlocking"); this.startupLatch.countDown(); this.jmdnsLock.unlock(); } } /** */ @Shutdown public void shutdown() { final java.lang.Thread t = new java.lang.Thread(new Runnable() { public void run() { RemoteDiscoveryImpl.this.jmdnsLock.lock(); // All of these statements tend to fail because of various reasons. During the shutdown however, // we want to ignore them all ... try { try { RemoteDiscoveryImpl.this.localManagerExportServer.close(); } catch (Exception e) { // } try { RemoteDiscoveryImpl.this.jmdns.unregisterAllServices(); } catch (Exception e) { // } try { RemoteDiscoveryImpl.this.jmdns.close(); } catch (Exception e) { // } } finally { RemoteDiscoveryImpl.this.jmdnsLock.unlock(); } } }); t.setDaemon(true); t.start(); } /** */ @net.xeoh.plugins.base.annotations.Timer(period = 260) public void discoverThread() { this.logger.finer("Starting new discover pass"); try { this.logger.finer("Awaiting latch"); this.startupLatch.await(); } catch (InterruptedException e) { e.printStackTrace(); return; } this.logger.finer("Latch passed"); // Increase counter this.discoverThreadCounter.incrementAndGet(); // Create empty data. ServiceInfo[] infos = new ServiceInfo[0]; // Magic: Get all network services of our type. try { this.logger.finer("Trying to lock jmDNS lock"); this.jmdnsLock.lock(); this.logger.finer("Lock obtained. Listing known entries of our type"); // TODO: jmdsn can be null if no network card is present infos = this.jmdns.list(TYPE); this.logger.finer("List obtained."); } catch (IllegalStateException e) { this.logger.warning("Error discovering plugins ..."); } finally { this.jmdnsLock.unlock(); this.logger.finer("Lock unlocked."); } // Reset all service infos try { this.logger.finer("Trying to obtain service info lock."); this.serviceInfosLock.lock(); this.logger.finer("Service info lock obtained. Transferring data."); this.serviceInfos.clear(); this.serviceInfos.addAll(Arrays.asList(infos)); this.logger.finer("Data transferred."); } finally { this.serviceInfosLock.unlock(); this.logger.finer("Service info unlocked."); } // Process all callbacks. final Collection<CallbackRequest> toRemove = new ArrayList<CallbackRequest>(); // // TODO: This callback handling needs improvement. Check for unsynchronized access to the allRequest structure // // Check all callbacks, if they need, well, a callback for (CallbackRequest cr : this.allRequests) { final Collection<DiscoveredPlugin> found = resolve(cr.req, cr.moreOptions); if (found.size() > 0) { cr.oc.getCallback().pluginsDiscovered(found); toRemove.add(cr); } } this.logger.finer("Callbacks executed. Removing items."); // Remove all resolved callbacks for (CallbackRequest callbackRequest : toRemove) { callbackRequest.cancelTimeout(); this.allRequests.remove(callbackRequest); } this.logger.finer("Disover pass ended."); } @SuppressWarnings("unchecked") private DiscoveryManager getRemoteProxyToDiscoveryManager(String ip, int port) { final String address = ip + ":" + port; final int timeout = 500; // 500 ms RemoteAPIImpl if need detailed version... this.logger.fine("Construction proxy to remote endpoint " + address); final DiscoveryManager newClient = Proxies.newClient(EXPORT_NAME, address, getClass().getClassLoader(), DiscoveryManager.class); // Execute collection asynchronously (TODO: cache pool usage could be improved) final ExecutorService cachePool = Executors.newCachedThreadPool(this.threadFactory); final ExecutorCompletionService<String> ecs = new ExecutorCompletionService(cachePool); final Future<String> future = ecs.submit(new Callable<String>() { public String call() throws Exception { return AccessController.doPrivileged(new PrivilegedAction<String>() { public String run() { return newClient.ping(667) == 667 ? "OK" : null; } }); } }); // Wait at most half a second (TODO: Make this configurable) try { final String string = future.get(timeout, TimeUnit.MILLISECONDS); if (string == null) return null; return newClient; } catch (final InterruptedException e) { this.logger.warning("Error while waiting for a getRemoteProxy() result"); e.printStackTrace(); } catch (final ExecutionException e) { e.printStackTrace(); } catch (final TimeoutException e) { this.logger.fine("Connection to the manager times out ... very strange."); //e.printStackTrace(); } catch (final SecurityException e) { e.printStackTrace(); } finally { AccessController.doPrivileged(new PrivilegedAction<Object>() { public Object run() { future.cancel(true); cachePool.shutdownNow(); return null; } }); } return null; } /** * Refreshes all known discovery managers. */ private void refreshKnownDiscoveryManagers() { this.serviceInfosLock.lock(); try { final List<RemoteManagerEndpoint> endpoints = new ArrayList<RemoteManagerEndpoint>(); // Check all service infos with discovery managers for (ServiceInfo serviceInfo : this.serviceInfos) { final InetAddress address = serviceInfo.getAddress(); final int port = serviceInfo.getPort(); endpoints.add(new RemoteManagerEndpoint(address, port)); } // Eventually update the endpoints this.remoteManagersEndpoints = endpoints; } finally { this.serviceInfosLock.unlock(); } } /* (non-Javadoc) * @see net.xeoh.plugins.remotediscovery.RemoteDiscovery#announcePlugin(net.xeoh.plugins.base.Plugin, net.xeoh.plugins.remote.PublishMethod, java.net.URI) */ public void announcePlugin(Plugin plugin, PublishMethod publishMethod, URI uri) { this.localTCPIPManager.anouncePlugin(plugin, publishMethod, uri); } /** * @return */ private boolean awaitInitializationTime() { // Check if we're still on startup lock final long delay = this.timeOfStartup + this.startupLock - System.currentTimeMillis(); if (delay > 0) { // If we are, halt this thread until lock time has passed. Unfortunatly the lookup is a // bit "unstable" during the first few miliseconds. try { java.lang.Thread.sleep(delay); } catch (InterruptedException e) { e.printStackTrace(); return false; } } return true; } /* (non-Javadoc) * @see net.xeoh.plugins.remotediscovery.RemoteDiscovery#discover(java.lang.Class, net.xeoh.plugins.remotediscovery.options.DiscoverOption[]) */ public Collection<DiscoveredPlugin> discover(Class<? extends Plugin> plugin, DiscoverOption... options) { this.logger.fine("Got request to discover " + plugin); // Our options ... final OptionUtils<DiscoverOption> ou = new OptionUtils<DiscoverOption>(options); // Wait until init is done ... try { this.startupLatch.await(); } catch (InterruptedException e) { e.printStackTrace(); return new ArrayList<DiscoveredPlugin>(); } // Timelock: Wait for a certain time to pass since startup if (this.lockMode.equals("timelock")) { if (awaitInitializationTime() == false) { return new ArrayList<DiscoveredPlugin>(); } } // Onepass: Wait for the discover to execute once if (this.lockMode.equals("onepass")) { // Also wait some time here, otherwise we won't find all plugins in all cases awaitInitializationTime(); // Wait at least one discoverThreadTurn final long lastDisoverValue = this.discoverThreadCounter.get(); final long startOfWait = System.currentTimeMillis(); while (this.discoverThreadCounter.get() == lastDisoverValue) { try { java.lang.Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); return new ArrayList<DiscoveredPlugin>(); } // Safety check if (System.currentTimeMillis() > startOfWait + 1000) { throw new IllegalStateException("We are waiting way too long."); } } } // Check if we should use callbacks if (ou.contains(OptionCallback.class)) { this.allRequests.add(new CallbackRequest(plugin, ou.get(OptionCallback.class), options)); } // Eventually resolve the request. return resolve(plugin, options); } /** * Checks all known service infos for matches to the given class, returns all matching entries. * * @param plugin * @param options * @return */ private Collection<DiscoveredPlugin> resolve(final Class<? extends Plugin> plugin, DiscoverOption[] options) { // Refreshes all known remote discovery managers. refreshKnownDiscoveryManagers(); // The result we intend to return final Collection<DiscoveredPlugin> result = new ArrayList<DiscoveredPlugin>(); final Collection<RemoteManagerEndpoint> endpoints = this.remoteManagersEndpoints; // Query all managers for (final RemoteManagerEndpoint endpoint : endpoints) { // The manager to use ... final DiscoveryManager mgr = getRemoteProxyToDiscoveryManager(endpoint.address.getHostAddress(), endpoint.port); // No matter what happens, close the manager try { if (mgr == null) { this.logger.info("Remote DiscoveryManager at " + endpoint.address.getHostAddress() + ":" + endpoint.port + " did not answer even though it appears to be there. ."); continue; } // final AtomicInteger pingTime = new AtomicInteger(Integer.MAX_VALUE); // Get ping time AccessController.doPrivileged(new PrivilegedAction<Object>() { public Object run() { try { final long start = System.nanoTime(); // Perform the ping mgr.ping(new Random().nextInt()); // Obtain the time final long stop = System.nanoTime(); final long time = (stop - start) / 1000; // And set it RemoteDiscoveryImpl.this.logger.finer("Ping time to manager was " + time + "µs"); pingTime.set((int) time); } catch (Exception e) { RemoteDiscoveryImpl.this.logger.info("Error getting ping time of remote manager " + endpoint.address + ":" + endpoint.port); } return null; } }); // Query the information (needs to be inside a privileged block, otherwise applets might complain. final ExportInfo exportInfo = AccessController.doPrivileged(new PrivilegedAction<ExportInfo>() { public ExportInfo run() { return mgr.getExportInfoFor(plugin.getCanonicalName()); } }); // If the plugin in not exported, do nothing if (!exportInfo.isExported) continue; // If it is, construct required data. for (ExportedPlugin p : exportInfo.allExported) { final PublishMethod method = PublishMethod.valueOf(p.exportMethod); final URI uri = p.exportURI; String _newURI = ""; _newURI += uri.getScheme(); _newURI += "://"; if (endpoint.address != null) { _newURI += endpoint.address.getHostAddress(); } else { _newURI += "127.0.0.1"; } _newURI += ":"; _newURI += uri.getPort(); _newURI += uri.getPath(); try { // TODO: Compute distance properly. result.add(new DiscoveredPluginImpl(method, new URI(_newURI), pingTime.get(), p.timeSinceExport)); } catch (URISyntaxException e) { e.printStackTrace(); } } } catch (Exception e) { this.logger.warning("Error talking to " + endpoint.address + ":" + endpoint.port + ". This usually means you have some version mess on the network."); e.printStackTrace(); } finally { // In case the manager is of the type simple resource (which it should be), try to close it. if (mgr instanceof SimpleResource) { try { // Try to close our device again AccessController.doPrivileged(new PrivilegedAction<Object>() { public Object run() { ((SimpleResource) mgr).close(); return null; } }); } catch (Exception e) { e.printStackTrace(); this.logger.fine("Error closing remote DiscoveryManager ..."); } } } } // If we have no result there is nothing to do if (result.size() == 0) return result; // Prepapare filter options ... final OptionUtils<DiscoverOption> ou = new OptionUtils<DiscoverOption>(options); DiscoveredPlugin best = result.iterator().next(); if (ou.contains(OptionNearest.class)) { // Check all plugins for (DiscoveredPlugin p : result) { // If this one is closer, replace them if (p.getDistance() < best.getDistance()) { best = p; } } // Remove all other plugins result.clear(); result.add(best); } if (ou.contains(OptionYoungest.class)) { // Check all plugins for (DiscoveredPlugin p : result) { // If this one is closer, replace them if (p.getTimeSinceExport() < best.getTimeSinceExport()) { best = p; } } // Remove all other plugins result.clear(); result.add(best); } if (ou.contains(OptionOldest.class)) { // Check all plugins for (DiscoveredPlugin p : result) { // If this one is closer, replace them if (p.getTimeSinceExport() > best.getTimeSinceExport()) { best = p; } } // Remove all other plugins result.clear(); result.add(best); } // Debug plugins for (DiscoveredPlugin p : result) { this.logger.fine("Returning plugin " + p); } return result; } /** * out of net.xeoh.plugins.remote.impl.ermi.RemoteAPIImpl * @return */ private static int getFreePort() { try { final ServerSocket serverSocket = new ServerSocket(0); final int port = serverSocket.getLocalPort(); serverSocket.close(); return port; } catch (IOException e) { e.printStackTrace(); } return 1025 + new Random().nextInt(50000); } /* (non-Javadoc) * @see net.xeoh.plugins.remotediscovery.RemoteDiscovery#revokePlugin(net.xeoh.plugins.base.Plugin, net.xeoh.plugins.remote.PublishMethod, java.net.URI) */ public void revokePlugin(Plugin plugin, PublishMethod publishMethod, URI uri) { this.localTCPIPManager.revokePlugin(plugin, publishMethod, uri); } }
100json-jspf
modules/plugins/remote.discovery/src/net/xeoh/plugins/remotediscovery/impl/v2/RemoteDiscoveryImpl.java
Java
bsd
27,368
package net.xeoh.plugins.remotediscovery.impl.common.discoverymanager; /** * * * @author rb * */ public interface DiscoveryManager { /** * Returns the version of this manager. * * @return Version number * @since 100 */ public int getVersion(); /** * Return an export-info for the queried plugin. * * @param pluginInteraceName * @since 100 * @return . */ public ExportInfo getExportInfoFor(String pluginInteraceName); /** * Performs a ping returning the passed value. * * @param value * @return value * @since 100 */ public int ping(int value); /** * Returns the time since the startup of this manager * * @since 200 * @return . */ public long getTimeSinceStartup(); }
100json-jspf
modules/plugins/remote.discovery/src/net/xeoh/plugins/remotediscovery/impl/common/discoverymanager/DiscoveryManager.java
Java
bsd
875
/* * ExportEntry.java * * Copyright (c) 2009, Ralf Biedert All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package net.xeoh.plugins.remotediscovery.impl.common.discoverymanager; import java.io.IOException; import java.io.ObjectStreamException; import java.io.Serializable; import java.net.URI; /** * @author rb * */ public class ExportedPlugin implements Serializable { /** */ private static final long serialVersionUID = -279653795803017797L; /** */ private int version = 100; /** */ public String exportMethod; /** */ public int port; /** */ public URI exportURI; /** */ public long timeSinceExport; /** * @param out * @throws IOException */ private void writeObject(java.io.ObjectOutputStream out) throws IOException { out.writeInt(this.version); out.writeObject(this.exportMethod); out.writeInt(this.port); out.writeObject(this.exportURI); out.writeLong(this.timeSinceExport); } /** * @param in * @throws IOException * @throws ClassNotFoundException */ private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException { this.version = in.readInt(); this.exportMethod = (String) in.readObject(); this.port = in.readInt(); this.exportURI = (URI) in.readObject(); this.timeSinceExport = in.readLong(); } /** * @throws ObjectStreamException */ @SuppressWarnings("unused") private void readObjectNoData() throws ObjectStreamException { // What to do here? } }
100json-jspf
modules/plugins/remote.discovery/src/net/xeoh/plugins/remotediscovery/impl/common/discoverymanager/ExportedPlugin.java
Java
bsd
3,138
/* * ExportInfo.java * * Copyright (c) 2009, Ralf Biedert All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package net.xeoh.plugins.remotediscovery.impl.common.discoverymanager; import java.io.IOException; import java.io.ObjectStreamException; import java.io.Serializable; import java.util.Collection; /** * * @author Ralf Biedert */ public class ExportInfo implements Serializable { /** */ private static final long serialVersionUID = -1167139290124669982L; /** */ private int version = 100; /** true if the plugin was exported there */ public boolean isExported; /** */ public Collection<ExportedPlugin> allExported; /** * @param out * @throws IOException */ private void writeObject(java.io.ObjectOutputStream out) throws IOException { out.writeInt(this.version); out.writeBoolean(this.isExported); out.writeObject(this.allExported); } /** * @param in * @throws IOException * @throws ClassNotFoundException */ @SuppressWarnings("unchecked") private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException { this.version = in.readInt(); this.isExported = in.readBoolean(); this.allExported = (Collection<ExportedPlugin>) in.readObject(); } /** * @throws ObjectStreamException */ @SuppressWarnings("unused") private void readObjectNoData() throws ObjectStreamException { // What to do here? } }
100json-jspf
modules/plugins/remote.discovery/src/net/xeoh/plugins/remotediscovery/impl/common/discoverymanager/ExportInfo.java
Java
bsd
3,030
package net.xeoh.plugins.remotediscovery.impl.common.discoverymanager.impl.tcpip; import java.net.URI; import java.util.ArrayList; import java.util.Collection; import net.xeoh.plugins.base.Plugin; import net.xeoh.plugins.remote.PublishMethod; import net.xeoh.plugins.remotediscovery.impl.common.discoverymanager.DiscoveryManager; import net.xeoh.plugins.remotediscovery.impl.common.discoverymanager.ExportInfo; import net.xeoh.plugins.remotediscovery.impl.common.discoverymanager.ExportedPlugin; import net.xeoh.plugins.remotediscovery.impl.common.discoverymanager.impl.AbstractDiscoveryManager; import net.xeoh.plugins.remotediscovery.impl.common.discoverymanager.impl.ExportEntry; /** * @author Ralf Biedert */ public class DiscoveryManagerTCPIPImpl extends AbstractDiscoveryManager implements DiscoveryManager { /** A list of all exported entities we have */ public final Collection<ExportEntry> allExported = new ArrayList<ExportEntry>(); /* (non-Javadoc) * @see net.xeoh.plugins.remotediscovery.impl.v2.DiscoveryManager#getExportInfoFor(java.lang.String) */ public ExportInfo getExportInfoFor(String pluginInteraceName) { this.logger.fine("Was queried for plugin name " + pluginInteraceName); final ExportInfo exportInfo = new ExportInfo(); exportInfo.isExported = false; exportInfo.allExported = new ArrayList<ExportedPlugin>(); for (ExportEntry entry : this.allExported) { final Collection<Class<? extends Plugin>> allPluginClasses = getAllPluginClasses(entry.plugin); final Collection<String> allPluginClassNames = new ArrayList<String>(); for (Class<?> c : allPluginClasses) { allPluginClassNames.add(c.getCanonicalName()); } // Now check if the plugins is really exported if (!allPluginClassNames.contains(pluginInteraceName)) continue; // It is, add it to the list exportInfo.isExported = true; final ExportedPlugin exported = new ExportedPlugin(); exported.exportMethod = entry.method.name(); exported.exportURI = entry.uri; exported.port = entry.uri.getPort(); exported.timeSinceExport = System.currentTimeMillis() - entry.timeOfExport; exportInfo.allExported.add(exported); } return exportInfo; } /** * Tells the manager that a new plugin is available. * * @param plugin * @param method * @param url */ @Override public void anouncePlugin(Plugin plugin, PublishMethod method, URI url) { final ExportEntry entry = new ExportEntry(); entry.plugin = plugin; entry.method = method; entry.uri = url; entry.timeOfExport = System.currentTimeMillis(); synchronized (this.allExported) { this.allExported.add(entry); } } /** * @param plugin * @param publishMethod * @param uri */ @Override public void revokePlugin(Plugin plugin, PublishMethod publishMethod, URI uri) { final Collection<ExportEntry> toRemove = new ArrayList<ExportEntry>(); synchronized (this.allExported) { for (ExportEntry e : this.allExported) { if (e.plugin == plugin && e.method == publishMethod && e.uri.equals(uri)) toRemove.add(e); } } this.allExported.removeAll(toRemove); } }
100json-jspf
modules/plugins/remote.discovery/src/net/xeoh/plugins/remotediscovery/impl/common/discoverymanager/impl/tcpip/DiscoveryManagerTCPIPImpl.java
Java
bsd
3,605
/* * ExportEntry.java * * Copyright (c) 2010, Ralf Biedert All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package net.xeoh.plugins.remotediscovery.impl.common.discoverymanager.impl.filepreferences; import java.io.Serializable; import java.util.HashMap; import java.util.Map; /** * @author Ralf Biedert */ public class LocalExportEntry implements Serializable { /** */ private static final long serialVersionUID = 553498463031460205L; /** if of parent */ public String uid; /** Stores values for every entry. */ public Map<String, String> values = new HashMap<String, String>(); }
100json-jspf
modules/plugins/remote.discovery/src/net/xeoh/plugins/remotediscovery/impl/common/discoverymanager/impl/filepreferences/LocalExportEntry.java
Java
bsd
2,068
/* * DiscoveryMangerPreferences.java * * Copyright (c) 2010, Ralf Biedert All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package net.xeoh.plugins.remotediscovery.impl.common.discoverymanager.impl.filepreferences; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.Random; import java.util.Set; import java.util.logging.Logger; import net.xeoh.plugins.base.Plugin; import net.xeoh.plugins.base.PluginManager; import net.xeoh.plugins.base.impl.PluginManagerFactory; import net.xeoh.plugins.base.util.JSPFProperties; import net.xeoh.plugins.remote.PublishMethod; import net.xeoh.plugins.remotediscovery.impl.common.discoverymanager.DiscoveryManager; import net.xeoh.plugins.remotediscovery.impl.common.discoverymanager.ExportInfo; import net.xeoh.plugins.remotediscovery.impl.common.discoverymanager.ExportedPlugin; import net.xeoh.plugins.remotediscovery.impl.common.discoverymanager.impl.AbstractDiscoveryManager; import net.xeoh.plugins.remotediscovery.impl.common.discoverymanager.impl.ExportEntry; /** * @author rb * */ public class DiscoveryMangerFileImpl extends AbstractDiscoveryManager implements DiscoveryManager { /** Discovery Root */ final File root = new File(System.getProperty("java.io.tmpdir") + "/jspf.discovery/"); final String ourID = "" + new Random().nextInt(1000000000); /** A list of all exported entities we have */ final Collection<LocalExportEntry> allExported = new ArrayList<LocalExportEntry>(); /** * Creates a new preferences manager */ public DiscoveryMangerFileImpl() { init(); } /** */ private void init() { final Logger lgger = DiscoveryMangerFileImpl.this.logger; this.logger.fine("Using UID " + this.ourID); this.root.mkdirs(); // Runs regularly to clean up unused names final Thread update = new Thread(new Runnable() { @Override public void run() { while (true) { try { final long time = System.currentTimeMillis(); // Store our array store(); // Clean up final File r = DiscoveryMangerFileImpl.this.root; final File[] list = r.listFiles(); for (File l : list) { final String abs = l.getAbsolutePath().replaceAll("\\\\", "/"); final String f = abs.substring(abs.lastIndexOf("/")); final String[] split = f.split("\\."); long tme = Long.parseLong(split[1]); if (time - tme > 3000) { l.delete(); } } Thread.sleep(1000); } catch (InterruptedException e) { lgger.fine("Sleep Interrupted."); } } } }); update.setDaemon(true); update.start(); } void store() { try { final long time = System.currentTimeMillis(); final String prefix = DiscoveryMangerFileImpl.this.root.getAbsolutePath() + "/" + DiscoveryMangerFileImpl.this.ourID + "." + time; final File file = new File(prefix + ".creation"); final FileOutputStream fos = new FileOutputStream(file); final ObjectOutputStream oos = new ObjectOutputStream(fos); synchronized (DiscoveryMangerFileImpl.this.allExported) { oos.writeObject(DiscoveryMangerFileImpl.this.allExported); } fos.flush(); fos.close(); // Finally rename the file file.renameTo(new File(prefix + ".ser")); file.delete(); } catch (IOException e) { e.printStackTrace(); } } /* (non-Javadoc) * @see net.xeoh.plugins.remotediscovery.impl.common.discoverymanager.impl.AbstractDiscoveryManager#anouncePlugin(net.xeoh.plugins.base.Plugin, net.xeoh.plugins.remote.PublishMethod, java.net.URI) */ @Override public synchronized void anouncePlugin(Plugin plugin, PublishMethod method, URI url) { final LocalExportEntry localExportEntry = new LocalExportEntry(); final Collection<Class<? extends Plugin>> allPluginClasses = getAllPluginClasses(plugin); final StringBuilder sb = new StringBuilder(); for (Class<?> c : allPluginClasses) { sb.append(c.getCanonicalName()); sb.append(";"); } localExportEntry.uid = this.ourID; localExportEntry.values.put("export.uri", url.toString()); localExportEntry.values.put("export.method", method.name()); localExportEntry.values.put("export.time", "" + System.currentTimeMillis()); localExportEntry.values.put("export.plugins", sb.toString()); synchronized (this.allExported) { this.allExported.add(localExportEntry); } store(); } /* (non-Javadoc) * @see net.xeoh.plugins.remotediscovery.impl.common.discoverymanager.impl.AbstractDiscoveryManager#revokePlugin(net.xeoh.plugins.base.Plugin, net.xeoh.plugins.remote.PublishMethod, java.net.URI) */ @Override public synchronized void revokePlugin(Plugin plugin, PublishMethod publishMethod, URI uri) { final Collection<ExportEntry> toRemove = new ArrayList<ExportEntry>(); synchronized (this.allExported) { for (LocalExportEntry e : this.allExported) { // TODO: Implement ME! e.hashCode(); } this.allExported.removeAll(toRemove); } } /* (non-Javadoc) * @see net.xeoh.plugins.remotediscovery.impl.common.discoverymanager.DiscoveryManager#getExportInfoFor(java.lang.String) */ @SuppressWarnings( { "boxing", "unchecked" }) @Override public synchronized ExportInfo getExportInfoFor(String pluginInteraceName) { this.logger.fine("Was queried for plugin name " + pluginInteraceName); final ExportInfo exportInfo = new ExportInfo(); exportInfo.isExported = false; exportInfo.allExported = new ArrayList<ExportedPlugin>(); try { final File[] listFiles = this.root.listFiles(); final Map<Integer, Long> best = new HashMap<Integer, Long>(); // Get latest entries for each file for (File l : listFiles) { final String abs = l.getAbsolutePath().replaceAll("\\\\", "/"); final String f = abs.substring(abs.lastIndexOf("/") + 1); final String[] split = f.split("\\."); // Only final files if (!f.contains("ser")) continue; long tme = Long.parseLong(split[1]); int id = Integer.parseInt(split[0]); if (best.containsKey(id)) { long last = best.get(id); if (last < tme) best.put(id, tme); } else best.put(id, tme); } // Load all files and do final Set<Integer> keySet = best.keySet(); for (Integer integer : keySet) { int id = integer; long time = best.get(id); try { final File file = new File(this.root.getAbsolutePath() + "/" + id + "." + time + ".ser"); final FileInputStream fis = new FileInputStream(file); final ObjectInputStream ois = new ObjectInputStream(fis); final Collection<LocalExportEntry> exported = (Collection<LocalExportEntry>) ois.readObject(); for (LocalExportEntry localExportEntry : exported) { this.logger.finer("Found export node " + localExportEntry.uid); final Map<String, String> exportNode = localExportEntry.values; final String[] interfaces = exportNode.get("export.plugins").split(";"); boolean found = false; // Check if one of the interface names matches for (String iface : interfaces) { this.logger.finest("Exported plugin interface " + iface); if (!iface.equals(pluginInteraceName)) continue; found = true; } if (!found) continue; // In here we have an exported plugin final ExportedPlugin exportedPlugin = new ExportedPlugin(); exportedPlugin.exportMethod = exportNode.get("export.method"); exportedPlugin.exportURI = URI.create(exportNode.get("export.uri")); exportedPlugin.timeSinceExport = Long.parseLong(exportNode.get("export.time")); exportedPlugin.port = exportedPlugin.exportURI.getPort(); exportInfo.allExported.add(exportedPlugin); } } catch (Exception e) { // e.printStackTrace(); } } } catch (Exception e) { e.printStackTrace(); } return exportInfo; } /** * @param args * @throws InterruptedException * @throws URISyntaxException */ public static void main(String[] args) throws InterruptedException, URISyntaxException { final JSPFProperties props = new JSPFProperties(); props.setProperty(PluginManager.class, "cache.enabled", "true"); props.setProperty(PluginManager.class, "cache.file", "myjspf.cache"); final PluginManager pm = PluginManagerFactory.createPluginManager(props); DiscoveryMangerFileImpl dmp = new DiscoveryMangerFileImpl(); dmp.anouncePlugin(pm, PublishMethod.JAVASCRIPT, new URI("http://xxx.com")); Thread.sleep(2000); ExportInfo exportInfoFor = dmp.getExportInfoFor("net.xeoh.plugins.base.Plugin"); Collection<ExportedPlugin> all = exportInfoFor.allExported; for (ExportedPlugin e : all) { System.out.println(e.exportURI); } Thread.sleep(4000); } }
100json-jspf
modules/plugins/remote.discovery/src/net/xeoh/plugins/remotediscovery/impl/common/discoverymanager/impl/filepreferences/DiscoveryMangerFileImpl.java
Java
bsd
12,274
/* * LocalExportEntry.java * * Copyright (c) 2010, Ralf Biedert All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package net.xeoh.plugins.remotediscovery.impl.common.discoverymanager.impl.localpreferences; import net.xeoh.plugins.remotediscovery.impl.common.discoverymanager.impl.ExportEntry; /** * @author rb * */ public class LocalExportEntry extends ExportEntry { /** */ public String nodeID; }
100json-jspf
modules/plugins/remote.discovery/src/net/xeoh/plugins/remotediscovery/impl/common/discoverymanager/impl/localpreferences/LocalExportEntry.java
Java
bsd
1,866
/* * DiscoveryMangerPreferences.java * * Copyright (c) 2010, Ralf Biedert All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package net.xeoh.plugins.remotediscovery.impl.common.discoverymanager.impl.localpreferences; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Collection; import java.util.UUID; import java.util.logging.Logger; import java.util.prefs.BackingStoreException; import java.util.prefs.Preferences; import net.xeoh.plugins.base.Plugin; import net.xeoh.plugins.base.PluginManager; import net.xeoh.plugins.base.impl.PluginManagerFactory; import net.xeoh.plugins.base.util.JSPFProperties; import net.xeoh.plugins.remote.PublishMethod; import net.xeoh.plugins.remotediscovery.impl.common.discoverymanager.DiscoveryManager; import net.xeoh.plugins.remotediscovery.impl.common.discoverymanager.ExportInfo; import net.xeoh.plugins.remotediscovery.impl.common.discoverymanager.ExportedPlugin; import net.xeoh.plugins.remotediscovery.impl.common.discoverymanager.impl.AbstractDiscoveryManager; import net.xeoh.plugins.remotediscovery.impl.common.discoverymanager.impl.ExportEntry; /** * @author rb * */ public class DiscoveryMangerPreferencesImpl extends AbstractDiscoveryManager implements DiscoveryManager { /** Root for all agents */ private Preferences agentsRoot; /** All of our exports node */ private Preferences ourExportsNode; /** Only valid results if this is true ...*/ boolean initSuccessful = false; /** Our ID */ final String ourID; /** A list of all exported entities we have */ final Collection<LocalExportEntry> allExported = new ArrayList<LocalExportEntry>(); /** * Creates a new preferences manager */ public DiscoveryMangerPreferencesImpl() { this.ourID = UUID.randomUUID().toString(); try { this.agentsRoot = Preferences.systemNodeForPackage(getClass()).node("agents"); this.agentsRoot.sync(); init(); } catch (Exception e) { e.printStackTrace(); this.logger.fine("Error initializing loopback discovery"); } this.initSuccessful = true; } /** */ private void init() { final Logger lgger = DiscoveryMangerPreferencesImpl.this.logger; final Preferences root = DiscoveryMangerPreferencesImpl.this.agentsRoot; final Preferences ournode = this.agentsRoot.node(this.ourID); this.ourExportsNode = ournode.node("exports"); this.logger.fine("Using UID " + this.ourID); // Runs regularly to clean up unused names final Thread cleanup = new Thread(new Runnable() { @Override public void run() { while (true) { // First, update the timestamp of OUR NODE ... ournode.putLong("last.pass", System.currentTimeMillis()); // ... and eventually clear ALL NODES which have been up for too long try { final String[] childrenNames = root.childrenNames(); for (String string : childrenNames) { final Preferences node = root.node(string); long time = node.getLong("last.pass", 0); if (time < System.currentTimeMillis() - 2000) { lgger.fine("Removing old node " + node.name()); node.removeNode(); } } } catch (BackingStoreException e1) { lgger.fine("Error getting children ..."); e1.printStackTrace(); } // And sleep some moment before we try again try { root.sync(); Thread.sleep(250); } catch (InterruptedException e) { lgger.fine("Sleep Interrupted."); } catch (BackingStoreException e) { lgger.fine("Errow syncing node."); e.printStackTrace(); } } } }); cleanup.setDaemon(true); cleanup.start(); } /* (non-Javadoc) * @see net.xeoh.plugins.remotediscovery.impl.common.discoverymanager.impl.AbstractDiscoveryManager#anouncePlugin(net.xeoh.plugins.base.Plugin, net.xeoh.plugins.remote.PublishMethod, java.net.URI) */ @Override public synchronized void anouncePlugin(Plugin plugin, PublishMethod method, URI url) { final LocalExportEntry localExportEntry = new LocalExportEntry(); localExportEntry.plugin = plugin; localExportEntry.method = method; localExportEntry.uri = url; localExportEntry.timeOfExport = System.currentTimeMillis(); localExportEntry.nodeID = UUID.randomUUID().toString(); final Preferences ournode = this.ourExportsNode.node(localExportEntry.nodeID); ournode.put("export.uri", url.toString()); ournode.put("export.method", method.name()); ournode.putLong("export.time", localExportEntry.timeOfExport); final Collection<Class<? extends Plugin>> allPluginClasses = getAllPluginClasses(plugin); final StringBuilder sb = new StringBuilder(); for (Class<?> c : allPluginClasses) { sb.append(c.getCanonicalName()); sb.append(";"); } ournode.put("export.plugins", sb.toString()); // Store the new plugin try { this.agentsRoot.sync(); } catch (BackingStoreException e) { e.printStackTrace(); } this.allExported.add(localExportEntry); } /* (non-Javadoc) * @see net.xeoh.plugins.remotediscovery.impl.common.discoverymanager.impl.AbstractDiscoveryManager#revokePlugin(net.xeoh.plugins.base.Plugin, net.xeoh.plugins.remote.PublishMethod, java.net.URI) */ @Override public synchronized void revokePlugin(Plugin plugin, PublishMethod publishMethod, URI uri) { final Collection<ExportEntry> toRemove = new ArrayList<ExportEntry>(); synchronized (this.allExported) { for (LocalExportEntry e : this.allExported) { if (e.plugin == plugin && e.method == publishMethod && e.uri.equals(uri)) { toRemove.add(e); final Preferences ournode = this.ourExportsNode.node(e.nodeID); try { ournode.removeNode(); this.agentsRoot.sync(); } catch (BackingStoreException e1) { e1.printStackTrace(); } } } } this.allExported.removeAll(toRemove); } /* (non-Javadoc) * @see net.xeoh.plugins.remotediscovery.impl.common.discoverymanager.DiscoveryManager#getExportInfoFor(java.lang.String) */ @Override public synchronized ExportInfo getExportInfoFor(String pluginInteraceName) { this.logger.fine("Was queried for plugin name " + pluginInteraceName); final ExportInfo exportInfo = new ExportInfo(); exportInfo.isExported = false; exportInfo.allExported = new ArrayList<ExportedPlugin>(); // We have to iterate over all agents ... and all their nodes try { // Sync! this.agentsRoot.sync(); // Get all child nodes ... final String[] allAgents = this.agentsRoot.childrenNames(); for (String entry : allAgents) { this.logger.fine("Found agent " + entry); final Preferences currentNode = this.agentsRoot.node(entry + "/exports"); final String[] allExports = currentNode.childrenNames(); for (String string : allExports) { this.logger.finer("Found export node " + string); final Preferences exportNode = currentNode.node(string); final String[] interfaces = exportNode.get("export.plugins", "").split(";"); boolean found = false; // Check if one of the interface names matches for (String iface : interfaces) { this.logger.finest("Exported plugin interface " + iface); if (!iface.equals(pluginInteraceName)) continue; found = true; } if (!found) continue; // In here we have an exported plugin final ExportedPlugin exportedPlugin = new ExportedPlugin(); exportedPlugin.exportMethod = exportNode.get("export.method", ""); exportedPlugin.exportURI = URI.create(exportNode.get("export.uri", "")); exportedPlugin.timeSinceExport = Long.parseLong(exportNode.get("export.time", "")); exportedPlugin.port = exportedPlugin.exportURI.getPort(); exportInfo.allExported.add(exportedPlugin); } } } catch (Exception e) { e.printStackTrace(); } return exportInfo; } /** * Debugs the structure */ public void debug() { try { this.agentsRoot.sync(); } catch (BackingStoreException e) { // TODO Auto-generated catch block e.printStackTrace(); } debug(this.agentsRoot); } /** * @param start */ private void debug(Preferences start) { System.out.println(start.absolutePath()); try { String[] keys = start.keys(); for (String string : keys) { System.out.println(" " + string + " -> " + start.get(string, "")); } String[] childrenNames = start.childrenNames(); for (String string : childrenNames) { debug(start.node(string)); } } catch (BackingStoreException e) { e.printStackTrace(); } } /** * @param args * @throws InterruptedException * @throws URISyntaxException */ public static void main(String[] args) throws InterruptedException, URISyntaxException { final JSPFProperties props = new JSPFProperties(); props.setProperty(PluginManager.class, "cache.enabled", "true"); props.setProperty(PluginManager.class, "cache.file", "myjspf.cache"); final PluginManager pm = PluginManagerFactory.createPluginManager(props); DiscoveryMangerPreferencesImpl dmp = new DiscoveryMangerPreferencesImpl(); dmp.anouncePlugin(pm, PublishMethod.JAVASCRIPT, new URI("http://xxx.com")); dmp.debug(); ExportInfo exportInfoFor = dmp.getExportInfoFor("net.xeoh.plugins.base.Plugin"); Collection<ExportedPlugin> all = exportInfoFor.allExported; for (ExportedPlugin e : all) { System.out.println(e.exportURI); } Thread.sleep(1000); } }
100json-jspf
modules/plugins/remote.discovery/src/net/xeoh/plugins/remotediscovery/impl/common/discoverymanager/impl/localpreferences/DiscoveryMangerPreferencesImpl.java
Java
bsd
12,825
package net.xeoh.plugins.remotediscovery.impl.common.discoverymanager.impl; import java.io.Serializable; import java.net.URI; import net.xeoh.plugins.base.Plugin; import net.xeoh.plugins.remote.PublishMethod; /** * @author rb */ public class ExportEntry implements Serializable { /** */ private static final long serialVersionUID = 953738903386891643L; /** */ public Plugin plugin; /** */ public PublishMethod method; /** */ public URI uri; /** */ public long timeOfExport; }
100json-jspf
modules/plugins/remote.discovery/src/net/xeoh/plugins/remotediscovery/impl/common/discoverymanager/impl/ExportEntry.java
Java
bsd
524
/* * AbstractDiscoveryManager.java * * Copyright (c) 2010, Ralf Biedert All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package net.xeoh.plugins.remotediscovery.impl.common.discoverymanager.impl; import java.net.URI; import java.util.ArrayList; import java.util.Collection; import java.util.logging.Logger; import net.xeoh.plugins.base.Plugin; import net.xeoh.plugins.base.util.PluginUtil; import net.xeoh.plugins.remote.PublishMethod; /** * @author rb * */ public abstract class AbstractDiscoveryManager { protected final Logger logger = Logger.getLogger(this.getClass().getName()); /** Stores the time of startup of this plugin */ private final long timeOfStartup = System.currentTimeMillis(); /** * @param plugin * @return . */ public static Collection<Class<? extends Plugin>> getAllPluginClasses(Plugin plugin) { return new PluginUtil(plugin).getAllPluginInterfaces(); } /** * @param c * @return . */ public static Collection<Class<?>> getAllSuperInterfaces(Class<?> c) { Collection<Class<?>> rval = new ArrayList<Class<?>>(); rval.add(c); Class<?>[] interfaces = c.getInterfaces(); for (Class<?> class1 : interfaces) { Collection<Class<?>> allSuperInterfaces = getAllSuperInterfaces(class1); for (Class<?> class2 : allSuperInterfaces) { rval.add(class2); } } return rval; } /** * @return . */ public int getVersion() { return 200; } /** * @param value * @return . */ public int ping(int value) { this.logger.fine("Was pinged with " + value); return value; } /** * @return . */ public long getTimeSinceStartup() { return System.currentTimeMillis() - this.timeOfStartup; } /** * @param plugin * @param method * @param url */ public abstract void anouncePlugin(Plugin plugin, PublishMethod method, URI url); /** * * @param plugin * @param publishMethod * @param uri */ public abstract void revokePlugin(Plugin plugin, PublishMethod publishMethod, URI uri); }
100json-jspf
modules/plugins/remote.discovery/src/net/xeoh/plugins/remotediscovery/impl/common/discoverymanager/impl/AbstractDiscoveryManager.java
Java
bsd
3,675
/* * DiscoveryTracer.java * * Copyright (c) 2011, Ralf Biedert All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package net.xeoh.plugins.remotediscovery.diagnosis.channel.tracer; import net.xeoh.plugins.diagnosis.local.DiagnosisChannelID; public class DiscoveryTracer extends DiagnosisChannelID<String> { }
100json-jspf
modules/plugins/remote.discovery/src/net/xeoh/plugins/remotediscovery/diagnosis/channel/tracer/DiscoveryTracer.java
Java
bsd
1,764
/* * ProbeTracer.java * * Copyright (c) 2011, Ralf Biedert All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package net.xeoh.plugins.remotediscovery.diagnosis.channel.tracer; import net.xeoh.plugins.diagnosis.local.DiagnosisChannelID; public class ProbeTracer extends DiagnosisChannelID<String> { }
100json-jspf
modules/plugins/remote.discovery/src/net/xeoh/plugins/remotediscovery/diagnosis/channel/tracer/ProbeTracer.java
Java
bsd
1,756
/* * RemoteAPIDiscoveryUtil.java * * Copyright (c) 2009, Ralf Biedert All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package net.xeoh.plugins.remotediscovery.util; import java.net.URI; import java.util.ArrayList; import java.util.Collection; import java.util.List; import net.xeoh.plugins.base.Plugin; import net.xeoh.plugins.remote.RemoteAPI; import net.xeoh.plugins.remotediscovery.DiscoveredPlugin; import net.xeoh.plugins.remotediscovery.RemoteDiscovery; import net.xeoh.plugins.remotediscovery.options.DiscoverOption; import net.xeoh.plugins.remotediscovery.options.discover.OptionNearest; import net.xeoh.plugins.remotediscovery.options.discover.OptionOldest; import net.xeoh.plugins.remotediscovery.options.discover.OptionYoungest; /** * This util is only relevant for RemoteAPI implementors which want to use * the discovery:// URL * * @author rb * */ public class RemoteAPIDiscoveryUtil { /** */ private RemoteDiscovery discovery; /** */ private RemoteAPI remoteAPI; /** * @param discovery * @param remoteAPI */ public RemoteAPIDiscoveryUtil(RemoteDiscovery discovery, RemoteAPI remoteAPI) { this.discovery = discovery; this.remoteAPI = remoteAPI; } /** * If this function returns false, just proceed normally. If it returns true, control should be handed over to this module. * * @param uri * @return . */ public boolean isDiscoveryURI(URI uri) { if (uri == null) return false; if (uri.getScheme() == null) return false; return uri.getScheme().toLowerCase().equals("discover"); } /** * Requests a remote service based on a discovery uri * * @param <R> * @param url * @param remote * @return . */ public <R extends Plugin> R getRemoteProxy(final URI url, final Class<R> remote) { final String authority = url.getAuthority().toLowerCase(); final List<DiscoverOption> options = new ArrayList<DiscoverOption>(); // Process options if (authority.equals("any")) { // } if (authority.equals("nearest")) { options.add(new OptionNearest()); } if (authority.equals("youngest")) { options.add(new OptionYoungest()); } if (authority.equals("oldest")) { options.add(new OptionOldest()); } final Collection<DiscoveredPlugin> discovered = this.discovery.discover(remote, options.toArray(new DiscoverOption[0])); // Now find a matching plugin for (DiscoveredPlugin discoveredPlugin : discovered) { if (discoveredPlugin.getPublishMethod() != this.remoteAPI.getPublishMethod()) continue; URI publishURI = discoveredPlugin.getPublishURI(); return this.remoteAPI.getRemoteProxy(publishURI, remote); } // This is bad, we didn't find anything. return null; } }
100json-jspf
modules/plugins/remote.discovery/src/net/xeoh/plugins/remotediscovery/util/RemoteAPIDiscoveryUtil.java
Java
bsd
4,436
/* * RemoteDiscovery.java * * Copyright (c) 2009, Ralf Biedert All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package net.xeoh.plugins.remotediscovery; import java.net.URI; import java.util.Collection; import net.xeoh.plugins.base.Plugin; import net.xeoh.plugins.remote.PublishMethod; import net.xeoh.plugins.remotediscovery.options.DiscoverOption; /** * Discovers remote services. * * @author Ralf Biedert */ public interface RemoteDiscovery extends Plugin { /** * Announces the given plugin on the local network. * * @param plugin * @param publishMethod * @param uri */ public void announcePlugin(Plugin plugin, PublishMethod publishMethod, URI uri); /** * Unpublishes the plugin on the network. * * @param plugin * @param publishMethod * @param uri */ public void revokePlugin(Plugin plugin, PublishMethod publishMethod, URI uri); /** * Discovers a set of plugins that is compatible with the requested interface. * * @param plugin * @param options * * @return . */ public Collection<DiscoveredPlugin> discover(Class<? extends Plugin> plugin, DiscoverOption... options); }
100json-jspf
modules/plugins/remote.discovery/src/net/xeoh/plugins/remotediscovery/RemoteDiscovery.java
Java
bsd
2,721
/* * RemoteAPI.java * * Copyright (c) 2008, Ralf Biedert All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package net.xeoh.plugins.remote; import java.net.URI; import net.xeoh.plugins.base.Plugin; import net.xeoh.plugins.remote.RemoteAPI; /** * Allows the network export of plugins.<br/> <br/> * * Please note there may be constraints on the plugin usage depending on the remote type. * For example, XMLRPC might have problems with null or void types. * * @author Ralf Biedert * */ public interface RemoteAPIXMLRPC extends RemoteAPI { /** * Exports a plugin over the network at a given port. * * @param plugin * @param port * @return The URL where the plugin is accessible */ public URI exportPlugin(Plugin plugin, int port); }
100json-jspf
modules/plugins/remote.xmlrpc/src/net/xeoh/plugins/remote/RemoteAPIXMLRPC.java
Java
bsd
2,281
/* * RemoteAPIImpl.java * * Copyright (c) 2008, Ralf Biedert All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package net.xeoh.plugins.remote.impl.xmlrpc; import java.io.IOException; import java.net.InetAddress; import java.net.ServerSocket; import java.net.URI; import java.net.URISyntaxException; import java.net.UnknownHostException; import java.util.Random; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import java.util.logging.Logger; import net.xeoh.plugins.base.Plugin; import net.xeoh.plugins.base.PluginConfiguration; import net.xeoh.plugins.base.annotations.Capabilities; import net.xeoh.plugins.base.annotations.PluginImplementation; import net.xeoh.plugins.base.annotations.events.Init; import net.xeoh.plugins.base.annotations.events.Shutdown; import net.xeoh.plugins.base.annotations.injections.InjectPlugin; import net.xeoh.plugins.base.annotations.meta.Author; import net.xeoh.plugins.remote.ExportResult; import net.xeoh.plugins.remote.PublishMethod; import net.xeoh.plugins.remote.RemoteAPIXMLRPC; import net.xeoh.plugins.remote.util.internal.PluginExport; import net.xeoh.plugins.remote.util.vanilla.ExportResultImpl; import net.xeoh.plugins.remotediscovery.RemoteDiscovery; import net.xeoh.plugins.remotediscovery.util.RemoteAPIDiscoveryUtil; import com.flat502.rox.client.XmlRpcClient; import com.flat502.rox.server.XmlRpcServer; /** * TODO: XMLRPC impl. appears to be crappy: marshalling problems with chars, no null or * void support, ... replace this with something different in the future. * * @author Ralf Biedert * */ @Author(name = "Ralf Biedert") @PluginImplementation public class RemoteAPIImpl implements RemoteAPIXMLRPC { /** */ @InjectPlugin public PluginConfiguration configuration; /** * Where this server can be found */ private String exportUrl = "http://"; /** * Server object to receive requests */ private volatile XmlRpcServer server; /** * Lock server from concurrent access */ private final Lock serverLock = new ReentrantLock(); /** */ @InjectPlugin public RemoteDiscovery discovery; /** * Log events */ final Logger logger = Logger.getLogger(this.getClass().getName()); /** */ private RemoteAPIDiscoveryUtil remoteAPIDiscoveryUtil; /* * (non-Javadoc) * * @see net.xeoh.plugins.remote.RemoteAPI#exportPlugin(net.xeoh.plugins.base.Plugin) */ public URI exportPlugin(final Plugin plugin, int port) { this.serverLock.lock(); if (this.server == null) { initServer(); } this.serverLock.unlock(); // If this server is still null now, return if (this.server == null) return null; // // Try to find the most appropriate export name // String exportName = PluginExport.getExportName(plugin); // All interfaces this class implements /* * // FIXME: Might need improvement. final Class<?>[] interfaces = plugin.getClass().getInterfaces(); for (final Class<?> class1 : interfaces) { if (Plugin.class.isAssignableFrom(class1)) { exportName = class1.getSimpleName(); } }*/ // The URL we export at final String exportURL = this.exportUrl + exportName; this.serverLock.lock(); try { this.server.registerProxyingHandler(null, "^" + exportName + "\\.(.*)", plugin); } finally { this.serverLock.unlock(); } URI createURI = createURI(exportURL); // Announce the plugin this.discovery.announcePlugin(plugin, getPublishMethod(), createURI); return createURI; } /* (non-Javadoc) * @see net.xeoh.plugins.remote.RemoteAPI#exportPlugin(net.xeoh.plugins.base.Plugin) */ public ExportResult exportPlugin(final Plugin plugin) { return new ExportResultImpl(exportPlugin(plugin, 0)); } /** * @return . */ @Capabilities public String[] getCapabilites() { return new String[] { "xmlrpc", "XMLRPC" }; } /** */ @Init public void init() { this.remoteAPIDiscoveryUtil = new RemoteAPIDiscoveryUtil(this.discovery, this); } public PublishMethod getPublishMethod() { return PublishMethod.XMLRPC; } @SuppressWarnings("unchecked") public <R extends Plugin> R getRemoteProxy(final URI url, final Class<R> remote) { // In case this is a remote url, let the discoverer work. if (this.remoteAPIDiscoveryUtil.isDiscoveryURI(url)) { return this.remoteAPIDiscoveryUtil.getRemoteProxy(url, remote); } try { final String prefix = url.getPath().substring(1) + "."; final XmlRpcClient client = new XmlRpcClient(url.toURL()); return (R) client.proxyObject(prefix, remote); } catch (final IOException e) { e.printStackTrace(); } catch (final Exception e) { e.printStackTrace(); } return null; } /** */ @Shutdown public void shutdown() { try { if (this.server != null) { this.server.stop(); } this.server = null; } catch (final IOException e) { // } } public void unexportPlugin(final Plugin plugin) { // TODO Auto-generated method stub } /** * Internally used to create an URL without 'try' * * @param string * @return */ URI createURI(final String string) { try { return new URI(string); } catch (URISyntaxException e) { e.printStackTrace(); } return null; } /** * Try to setup the server if it's not already there */ void initServer() { int NUM_RETRIES = 10; int SERVER_PORT = getFreePort(); try { SERVER_PORT = Integer.parseInt(this.configuration.getConfiguration(RemoteAPIImpl.class, "xmlrpc.port")); } catch (final NumberFormatException e) { // Do nothing, as the most probable reason is the config was not set. } this.logger.info("Setting up XMLRPC-server on port " + SERVER_PORT); boolean succeded = false; while (!succeded && NUM_RETRIES-- > 0) { try { this.exportUrl += InetAddress.getLocalHost().getCanonicalHostName(); this.exportUrl += ":" + SERVER_PORT + "/"; // FIXME: Export to public network, not to localhost ... this.server = new XmlRpcServer(SERVER_PORT); this.server.start(); this.logger.info("XMLRPC server listening on baseroot " + this.exportUrl); succeded = true; } catch (final UnknownHostException e) { this.logger.warning("Unable to create XMLRPC handler for this host"); e.printStackTrace(); } catch (final IOException e) { this.logger.warning("Unable to create XMLRPC handler for this host"); e.printStackTrace(); } SERVER_PORT++; } } /** * @return */ private static int getFreePort() { try { final ServerSocket serverSocket = new ServerSocket(0); final int port = serverSocket.getLocalPort(); serverSocket.close(); return port; } catch (IOException e) { e.printStackTrace(); } return 1025 + new Random().nextInt(50000); } }
100json-jspf
modules/plugins/remote.xmlrpc/src/net/xeoh/plugins/remote/impl/xmlrpc/RemoteAPIImpl.java
Java
bsd
9,426
/* * RemoteAPI.java * * Copyright (c) 2008, Ralf Biedert All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package net.xeoh.plugins.remote; import java.net.URI; import net.xeoh.plugins.remote.RemoteAPI; import net.xeoh.plugins.remote.options.ExportVanillaObjectOption; /** * Allows the network export of plugins.<br/> <br/> * * Please note there may be constraints on the plugin usage depending on the remote type. * For example, XMLRPC might have problems with null or void types. * * @author Ralf Biedert, Andreas Lauer, Christian Reuschling * */ public interface RemoteAPIXMLRPCDelight extends RemoteAPI { /** * @param toExport * @param option * @return . */ public URI exportVanillaObject(Object toExport, ExportVanillaObjectOption... option); }
100json-jspf
modules/plugins/remote.xmlrpcdelight/src/net/xeoh/plugins/remote/RemoteAPIXMLRPCDelight.java
Java
bsd
2,288
/* * OptionDummy.java * * Copyright (c) 2009, Ralf Biedert All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package net.xeoh.plugins.remote.options.exportvanillaobject; import net.xeoh.plugins.remote.options.ExportVanillaObjectOption; /** * * @author Ralf Biedert */ public class OptionExportName implements ExportVanillaObjectOption { /** */ private static final long serialVersionUID = -4815581927810499544L; /** * @param name */ public OptionExportName(String name) { // TODO } }
100json-jspf
modules/plugins/remote.xmlrpcdelight/src/net/xeoh/plugins/remote/options/exportvanillaobject/OptionExportName.java
Java
bsd
1,984