repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
CBIIT/caaers
caAERS/software/web/src/main/java/gov/nih/nci/cabig/caaers/web/fields/DefaultInputFieldGroup.java
1153
/******************************************************************************* * Copyright SemanticBits, Northwestern University and Akaza Research * * Distributed under the OSI-approved BSD 3-Clause License. * See http://ncip.github.com/caaers/LICENSE.txt for details. ******************************************************************************/ package gov.nih.nci.cabig.caaers.web.fields; import java.util.LinkedList; import java.util.List; /** * @author Rhett Sutphin */ public class DefaultInputFieldGroup extends AbstractInputFieldGroup { private List<InputField> fields = new LinkedList<InputField>(); public DefaultInputFieldGroup() { } public DefaultInputFieldGroup(String name) { super(name); } public DefaultInputFieldGroup(String name, String displayName) { super(name, displayName); } public DefaultInputFieldGroup addField(InputField newField) { getFields().add(newField); return this; } public List<InputField> getFields() { return fields; } public void setFields(List<InputField> fields) { this.fields = fields; } }
bsd-3-clause
codeaudit/jbosen
jbosen/src/main/java/org/petuum/jbosen/common/network/NettyCommBusEncoder.java
918
package org.petuum.jbosen.common.network; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.MessageToByteEncoder; import java.nio.ByteBuffer; class NettyCommBusEncoder extends MessageToByteEncoder<Msg> { @Override protected void encode(ChannelHandlerContext ctx, Msg msg, ByteBuf out) throws Exception { out.writeInt(msg.getSender()); out.writeInt(msg.getDest()); out.writeInt(msg.getMsgType()); out.writeInt(msg.getNumPayloads()); int numPayloads = msg.getNumPayloads(); for (int i = 0; i < numPayloads; i++) { ByteBuffer buffer = msg.getPayload(i); if (buffer != null) { out.writeInt(buffer.capacity()); out.writeBytes(buffer); } else { out.writeInt(0); } } } }
bsd-3-clause
yanqingmen/BIDMach
src/main/java/edu/berkeley/bid/CUMACH.java
6203
package edu.berkeley.bid; import jcuda.*; public final class CUMACH { private CUMACH() {} static { jcuda.LibUtils.loadLibrary("bidmachcuda"); } public static native int applylinks(Pointer A, Pointer L, Pointer C, int nrows, int ncols); public static native int applypreds(Pointer A, Pointer L, Pointer C, int nrows, int ncols); public static native int applylls(Pointer A, Pointer B, Pointer L, Pointer C, int nrows, int ncols); public static native int applyderivs(Pointer A, Pointer B, Pointer L, Pointer C, int nrows, int ncols); public static native int applydlinks(Pointer A, Pointer L, Pointer C, int nrows, int ncols); public static native int applydpreds(Pointer A, Pointer L, Pointer C, int nrows, int ncols); public static native int applydlls(Pointer A, Pointer B, Pointer L, Pointer C, int nrows, int ncols); public static native int applydderivs(Pointer A, Pointer B, Pointer L, Pointer C, int nrows, int ncols); public static native int LDAgibbs(int nr, int nnz, Pointer A, Pointer B, Pointer AN, Pointer BN, Pointer Cir, Pointer Cic, Pointer P, float nsamps); public static native int LDAgibbsBino(int nr, int nnz, Pointer A, Pointer B, Pointer AN, Pointer BN, Pointer Cir, Pointer Cic, Pointer Cv, Pointer P, int nsamps); public static native int LDAgibbsx(int nr, int nnz, Pointer A, Pointer B, Pointer Cir, Pointer Cic, Pointer P, Pointer Ms, Pointer Us, int k); public static native int LDAgibbsv(int nr, int nnz, Pointer A, Pointer B, Pointer AN, Pointer BN, Pointer Cir, Pointer Cic, Pointer P, Pointer nsamps); public static native int treeprod(Pointer trees, Pointer feats, Pointer tpos, Pointer otvs, int nrows, int ncols, int ns, int tstride, int ntrees); public static native int treesteps(Pointer trees, Pointer feats, Pointer tpos, Pointer otpos, int nrows, int ncols, int ns, int tstride, int ntrees, int tdepth); public static native int veccmp(Pointer A, Pointer B, Pointer C); public static native int hammingdists(Pointer A, Pointer B, Pointer W, Pointer OP, Pointer OW, int n); public static native int treePack(Pointer id, Pointer tn, Pointer icats, Pointer out, Pointer fl, int nrows, int ncols, int ntrees, int nsamps, int seed); public static native int treePackfc(Pointer id, Pointer tn, Pointer icats, Pointer out, Pointer fl, int nrows, int ncols, int ntrees, int nsamps, int seed); public static native int treePackInt(Pointer id, Pointer tn, Pointer icats, Pointer out, Pointer fl, int nrows, int ncols, int ntrees, int nsamps, int seed); public static native int treeWalk(Pointer fdata, Pointer inodes, Pointer fnodes, Pointer itrees, Pointer ftrees, Pointer vtrees, Pointer ctrees, int nrows, int ncols, int ntrees, int nnodes, int getcat, int nbits, int nlevels); public static native int minImpurity(Pointer keys, Pointer counts, Pointer outv, Pointer outf, Pointer outg, Pointer outc, Pointer jc, Pointer fieldlens, int nnodes, int ncats, int nsamps, int impType); public static native int findBoundaries(Pointer keys, Pointer jc, int n, int njc, int shift); public static native int floatToInt(int n, Pointer in, Pointer out, int nbits); public static native int jfeatsToIfeats(int itree, Pointer inodes, Pointer jfeats, Pointer ifeats, int n, int nfeats, int seed); public static native int mergeInds(Pointer keys, Pointer okeys, Pointer counts, int n, Pointer cspine); public static native int getMergeIndsLen(Pointer keys, int n, Pointer cspine); public static native int hashMult(int nrows, int nfeats, int ncols, int bound1, int bound2, Pointer jA, Pointer jBdata, Pointer jBir, Pointer jBjc, Pointer jC, int transpose); public static native int hashCross(int nrows, int nfeats, int ncols, Pointer jA, Pointer jBdata, Pointer jBir, Pointer jBjc, Pointer jCdata, Pointer jCir, Pointer jCjc, Pointer D, int transpose); public static native int cumsumc(int nrows, int ncols, Pointer jA, Pointer jB); public static native int multinomial(int nrows, int ncols, Pointer jA, Pointer jB, Pointer jNorm, int nvals); public static native int multinomial2(int nrows, int ncols, Pointer jA, Pointer jB, int nvals); public static native int multADAGrad(int nrows, int ncols, int nnz, Pointer A, Pointer Bdata, Pointer Bir, Pointer Bic, Pointer MM, Pointer Sumsq, Pointer Mask, int maskrows, Pointer lrate, int lrlen, Pointer vexp, int vexplen, Pointer texp, int texplen, float istep, int addgrad, float epsilon); public static native int hashmultADAGrad(int nrows, int nfeats, int ncols, int bound1, int bound2, Pointer A, Pointer Bdata, Pointer Bir, Pointer Bjc, int transpose, Pointer MM, Pointer Sumsq, Pointer Mask, int maskrows, Pointer lrate, int lrlen, Pointer vexp, int vexplen, Pointer texp, int texplen, float istep, int addgrad, float epsilon); public static native int word2vecPos(int nrows, int ncols, int shift, Pointer W, Pointer LB, Pointer UB, Pointer A, Pointer B, float lrate, float vexp); public static native int word2vecNeg(int nrows, int ncols, int nwa, int nwb, Pointer WA, Pointer WB, Pointer A, Pointer B, float lrate, float vexp); public static native int word2vecNegFilt(int nrows, int ncols, int nwords, int nwa, int nwb, Pointer WA, Pointer WB, Pointer A, Pointer B, float lrate, float vexp); public static native int word2vecEvalPos(int nrows, int ncols, int shift, Pointer W, Pointer LB, Pointer UB, Pointer A, Pointer B, Pointer retVal); public static native int word2vecEvalNeg(int nrows, int ncols, int nwa, int nwb, Pointer WA, Pointer WB, Pointer A, Pointer B, Pointer retVal); public static native int word2vecFwd(int nrows, int ncols, int nwa, int nwb, Pointer WA, Pointer WB, Pointer A, Pointer B, Pointer C); public static native int word2vecBwd(int nrows, int ncols, int nwa, int nwb, Pointer WA, Pointer WB, Pointer A, Pointer B, Pointer C, float lrate); }
bsd-3-clause
beiyuxinke/CONNECT
Product/Production/Adapters/DocumentSubmission_a0/src/main/java/gov/hhs/fha/nhinc/docsubmission/adapter/component/deferred/request/AdapterComponentXDRRequest.java
2536
/* * Copyright (c) 2009-2015, United States Government, as represented by the Secretary of Health and Human Services. * 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 United States Government 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 UNITED STATES GOVERNMENT 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 gov.hhs.fha.nhinc.docsubmission.adapter.component.deferred.request; import javax.annotation.Resource; import javax.xml.ws.BindingType; import javax.xml.ws.WebServiceContext; import javax.xml.ws.soap.Addressing; /** * * @author JHOPPESC */ @BindingType(value = javax.xml.ws.soap.SOAPBinding.SOAP12HTTP_BINDING) @Addressing(enabled = true) public class AdapterComponentXDRRequest implements gov.hhs.fha.nhinc.adaptercomponentxdrrequest.AdapterComponentXDRRequestPortType { @Resource private WebServiceContext context; public gov.hhs.healthit.nhin.XDRAcknowledgementType provideAndRegisterDocumentSetBRequest( gov.hhs.fha.nhinc.common.nhinccommonadapter.AdapterProvideAndRegisterDocumentSetRequestType body) { return new AdapterComponentXDRRequestImpl().provideAndRegisterDocumentSetBRequest(body, context); } }
bsd-3-clause
googleapis/gax-java
gax-httpjson/src/main/java/com/google/api/gax/httpjson/ApiMethodDescriptor.java
3804
/* * Copyright 2017 Google LLC * * 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 Google LLC 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 com.google.api.gax.httpjson; import com.google.api.core.BetaApi; import com.google.auto.value.AutoValue; import javax.annotation.Nullable; @BetaApi @AutoValue /* Method descriptor for messages to be transmitted over HTTP. */ public abstract class ApiMethodDescriptor<RequestT, ResponseT> { public enum MethodType { UNARY, CLIENT_STREAMING, SERVER_STREAMING, BIDI_STREAMING, UNKNOWN; } public abstract String getFullMethodName(); public abstract HttpRequestFormatter<RequestT> getRequestFormatter(); public abstract HttpResponseParser<ResponseT> getResponseParser(); /** Return the HTTP method for this request message type. */ @Nullable public abstract String getHttpMethod(); @Nullable public abstract OperationSnapshotFactory<RequestT, ResponseT> getOperationSnapshotFactory(); @Nullable public abstract PollingRequestFactory<RequestT> getPollingRequestFactory(); public abstract MethodType getType(); public static <RequestT, ResponseT> Builder<RequestT, ResponseT> newBuilder() { return new AutoValue_ApiMethodDescriptor.Builder<RequestT, ResponseT>() .setType(MethodType.UNARY); } public abstract Builder<RequestT, ResponseT> toBuilder(); @AutoValue.Builder public abstract static class Builder<RequestT, ResponseT> { public abstract Builder<RequestT, ResponseT> setFullMethodName(String fullMethodName); public abstract Builder<RequestT, ResponseT> setRequestFormatter( HttpRequestFormatter<RequestT> requestFormatter); public abstract HttpRequestFormatter<RequestT> getRequestFormatter(); public abstract Builder<RequestT, ResponseT> setResponseParser( HttpResponseParser<ResponseT> responseParser); public abstract Builder<RequestT, ResponseT> setHttpMethod(String httpMethod); public abstract Builder<RequestT, ResponseT> setOperationSnapshotFactory( OperationSnapshotFactory<RequestT, ResponseT> operationSnapshotFactory); public abstract Builder<RequestT, ResponseT> setPollingRequestFactory( PollingRequestFactory<RequestT> pollingRequestFactory); public abstract Builder<RequestT, ResponseT> setType(MethodType type); public abstract ApiMethodDescriptor<RequestT, ResponseT> build(); } }
bsd-3-clause
lockss/lockss-daemon
src/org/lockss/daemon/OpenUrlResolver.java
96414
/* Copyright (c) 2000-2017 Board of Trustees of Leland Stanford Jr. University, all rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL STANFORD UNIVERSITY BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Except as contained in this notice, the name of Stanford University shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from Stanford University. */ package org.lockss.daemon; import static org.lockss.db.SqlConstants.*; import java.io.IOException; import java.lang.reflect.Method; import java.net.HttpURLConnection; import java.sql.*; import java.text.ParseException; import java.util.*; import com.jcabi.aspects.*; import org.apache.commons.lang3.StringEscapeUtils; import org.lockss.app.LockssDaemon; import org.lockss.config.*; import org.lockss.daemon.AuParamType.InvalidFormatException; import org.lockss.db.*; import org.lockss.exporter.biblio.*; import org.lockss.plugin.*; import org.lockss.plugin.AuUtil.AuProxyInfo; import org.lockss.plugin.PluginManager.CuContentReq; import org.lockss.plugin.PrintfConverter.UrlListConverter; import org.lockss.plugin.definable.DefinableArchivalUnit; import org.lockss.proxy.ProxyManager; import org.lockss.util.*; import org.lockss.util.urlconn.*; /** * This class implements an OpenURL resolver that locates an article matching * properties corresponding to OpenURL keys. Both OpenURL 1.0 and the earlier * OpenURL 0.1 syntax are supported. Queries can be made by: * <ul> * <li>URL</li> * <li>DOI</li> * * <li>ISSN/volume/issue/page</li> * <li>ISSN/volume/issue/article-number</li> * <li>ISSN/volume/issue/author</li> * <li>ISSN/volume/issue/article-title</li> * <li>ISSN/date/page</li> * <li>ISSN/date/article-number</li> * <li>ISSN/date/author</li> * <li>ISSN/date/article-title</li> * * <li>journal-title/volume/issue/page</li> * <li>journal-title/volume/issue/article-number</li> * <li>journal-title/volume/issue/author</li> * <li>journal-title/volume/issue/article-title</li> * <li>journal-title/date/page</li> * <li>journal-title/date/article-number</li> * <li>journal-title/date/author</li> * <li>journal-title/date/article-title</li> * * <li>ISBN/page</li> * <li>ISBN/chapter-author</li> * <li>ISBN/chapter-title</li> * * <li>book-title/page</li> * <li>book-title/chapter-author</li> * <li>book-title/chapter-title</li> * * <li>book-publisher/book-title/page</li> * <li>book-publisher/book-title/chapter-author</li> * <li>book-publisher/book-title/chapter-title</li> * * <li>SICI</li> * <li>BICI</li> * </ul> * <p> * Note: the TDB of the current configuration is used to resolve journal or * if the entry is not in the metadata database, or if the query gives a * journal or book title but no ISSN or ISBN. If there are multiple entries * for the journal or book title, one of them is selected. OpenURL 1.0 allows * specifying a book publisher, so if both publisher and title are specified, * there is a good chance that the match will be unique. * * @author Philip Gust * @version 1.0 */ @Loggable(value = Loggable.TRACE, prepend = true) public class OpenUrlResolver { private static final Logger log = Logger.getLogger(OpenUrlResolver.class); /** the LOCKSS daemon */ private final LockssDaemon daemon; /** the PluginManager */ private final PluginManager pluginMgr; /** the ProxyManager */ private final ProxyManager proxyMgr; /** maximum redirects for looking up DOI url */ private static final int MAX_REDIRECTS = 10; /** prefix for config properties */ public static final String PREFIX = Configuration.PREFIX + "openUrlResolver."; /** * Determines the maximum number of OpenUrlResolver publishers+providers * that publish the same article when querying the metadata database.This * number will certainly be very small (< 10) * */ public static final String PARAM_MAX_PUBLISHERS_PER_ARTICLE = PREFIX + "max_publishers_per_article"; /** * Default value of OpenUrlResolver max_publishers_per_article default * configuration parameter. */ public static final int DEFAULT_MAX_PUBLISHERS_PER_ARTICLE = 10; public static String PARAM_NEVER_PROXY = org.lockss.servlet.ServeContent.PARAM_NEVER_PROXY; public static boolean DEFAULT_NEVER_PROXY = org.lockss.servlet. ServeContent.DEFAULT_NEVER_PROXY; static final class FeatureEntry { final String auFeatureKey; final OpenUrlInfo.ResolvedTo resolvedTo; public FeatureEntry(String auFeatureKey, OpenUrlInfo.ResolvedTo resolvedTo) { this.auFeatureKey = auFeatureKey; this.resolvedTo = resolvedTo; } } private static final String FEATURE_URLS = DefinableArchivalUnit.KEY_AU_FEATURE_URL_MAP; private static final String START_URLS = DefinableArchivalUnit.KEY_AU_START_URL; /** * Keys to search for a matching journal feature. The order of the keys * is the order they will be tried, from article, to issue, to volume, * to title, to publisher. */ static final FeatureEntry[] auJournalFeatures = { // FEATURE_URLS + "/au_abstract", new FeatureEntry(FEATURE_URLS + "/au_article",OpenUrlInfo.ResolvedTo.ARTICLE), new FeatureEntry(FEATURE_URLS + "/au_issue", OpenUrlInfo.ResolvedTo.ISSUE), new FeatureEntry(FEATURE_URLS + "/au_volume", OpenUrlInfo.ResolvedTo.VOLUME), new FeatureEntry(START_URLS, OpenUrlInfo.ResolvedTo.VOLUME), new FeatureEntry(FEATURE_URLS + "/au_title", OpenUrlInfo.ResolvedTo.TITLE), new FeatureEntry(FEATURE_URLS + "/au_publisher", OpenUrlInfo.ResolvedTo.PUBLISHER), }; /** * Keys to search for a matching book feature. The order of the keys is the * the order they will be tried, from chapter, to volume, to title, to * publisher. */ private static final FeatureEntry[] auBookAuFeatures = { new FeatureEntry(FEATURE_URLS + "/au_chapter", OpenUrlInfo.ResolvedTo.CHAPTER), new FeatureEntry(FEATURE_URLS + "/au_volume", OpenUrlInfo.ResolvedTo.VOLUME), new FeatureEntry(START_URLS, OpenUrlInfo.ResolvedTo.VOLUME), new FeatureEntry(FEATURE_URLS + "/au_title", OpenUrlInfo.ResolvedTo.TITLE), new FeatureEntry(FEATURE_URLS + "/au_publisher", OpenUrlInfo.ResolvedTo.PUBLISHER), }; /** The name of the TDB au_feature key selector */ static final String AU_FEATURE_KEY = "au_feature_key"; // pre-defined OpenUrlInfo for no url public static final OpenUrlInfo OPEN_URL_INFO_NONE = new OpenUrlInfo(null, null, OpenUrlInfo.ResolvedTo.NONE); /** * Information returned by OpenUrlResolver includes the resolvedUrl * and the resolvedTo enumeration. */ public static final class OpenUrlInfo implements Iterable<OpenUrlInfo> { static public enum ResolvedTo { PUBLISHER, // resolved to a publisher TITLE, // resolved to a tite of a serial (e.g. a journal or // a book series) or other pubication VOLUME, // resolved to a volume of a serial or other pubication, // or the title of an individual book CHAPTER, // resolved to a chapter of a book or other publication ISSUE, // resolved to an issue of a serial or other publication ARTICLE, // resolved to an article of a serial, book, or other pubication OTHER, // resolved to an element of a publication NONE, // not resolved if URL is null, or not in cache if has URL }; private String resolvedUrl; private String proxySpec; private ResolvedTo resolvedTo; private BibliographicItem resolvedBibliographicItem = null; private OpenUrlInfo nextInfo = null; private OpenUrlInfo(String resolvedUrl, String proxySpec, ResolvedTo resolvedTo) { this.resolvedUrl = resolvedUrl; this.resolvedTo = resolvedTo; this.proxySpec = proxySpec; } protected static OpenUrlInfo newInstance( String resolvedUrl, String proxySpec, ResolvedTo resolvedTo) { return ((resolvedTo == ResolvedTo.NONE) && (resolvedUrl == null)) ? OPEN_URL_INFO_NONE : new OpenUrlInfo(resolvedUrl, proxySpec, resolvedTo); } protected static OpenUrlInfo newInstance(String resolvedUrl) { return (resolvedUrl == null) ? OPEN_URL_INFO_NONE : new OpenUrlInfo(resolvedUrl, null, OpenUrlInfo.ResolvedTo.OTHER); } protected static OpenUrlInfo newInstance(String resolvedUrl, String proxySpec) { return (resolvedUrl == null) ? OPEN_URL_INFO_NONE : new OpenUrlInfo(resolvedUrl, proxySpec, OpenUrlInfo.ResolvedTo.OTHER); } public boolean isResolved() { return resolvedTo != null && resolvedTo != ResolvedTo.NONE; } public boolean isNotResolved() { return resolvedTo == null || resolvedTo == ResolvedTo.NONE; } public String getProxySpec() { return proxySpec; } public String getProxyHost() { if (proxySpec == null) { return null; } int i = proxySpec.indexOf(':'); return (i < 0) ? proxySpec : proxySpec.substring(0,i); } public int getProxyPort() { if (proxySpec == null) { return 0; } int i = proxySpec.indexOf(':'); try { return (i < 0) ? 0 : Integer.parseInt(proxySpec.substring(i+1)); } catch (NumberFormatException ex) { return 0; } } public String getResolvedUrl() { return resolvedUrl; } public ResolvedTo getResolvedTo() { return resolvedTo; } public BibliographicItem getBibliographicItem() { return resolvedBibliographicItem; } @Override public Iterator<OpenUrlInfo> iterator() { return new Iterator<OpenUrlInfo>() { OpenUrlInfo nextInfo = OpenUrlInfo.this; @Override public boolean hasNext() { return nextInfo != null; } @Override public OpenUrlInfo next() { if (nextInfo == null) { throw new NoSuchElementException(); } OpenUrlInfo curInfo = nextInfo; nextInfo = curInfo.nextInfo; return curInfo; } @Override public void remove() { throw new UnsupportedOperationException(); } }; } public void add(OpenUrlInfo nextInfo) { if (nextInfo == null) { throw new IllegalArgumentException("nextInfo cannot be null"); } last().nextInfo = nextInfo; } public int size() { int count = 1; OpenUrlInfo info = this; while (info.nextInfo != null) { info = info.nextInfo; count++; } return count; } public OpenUrlInfo last() { OpenUrlInfo info = this; while (info.nextInfo != null) { info = info.nextInfo; } return info; } public OpenUrlInfo next() { return nextInfo; } public boolean hasNext() { return nextInfo != null; } public String getOpenUrlQuery() { // don't use publisher or title url // because we don't preserve them if ( resolvedUrl != null && resolvedTo != null && !resolvedTo.equals(ResolvedTo.PUBLISHER) && !resolvedTo.equals(ResolvedTo.TITLE)) { return "rft_id=" + UrlUtil.encodeQueryArg(resolvedUrl); } if (resolvedBibliographicItem != null) { return OpenUrlResolver .getOpenUrlQueryForBibliographicItem(resolvedBibliographicItem); } return null; } public String toString() { StringBuilder sb = new StringBuilder(); sb.append("[OpenUrlInfo: "); sb.append(resolvedTo); if (resolvedTo != ResolvedTo.NONE) { if (resolvedUrl != null) { sb.append(", url: "); sb.append(resolvedUrl); } if (resolvedBibliographicItem != null) { sb.append(", bib: "); sb.append(resolvedBibliographicItem); } } if (nextInfo != null) { sb.append(", next: "); sb.append(nextInfo); } sb.append("]"); return sb.toString(); } } /** * Create a resolver for the specified database manager. * * @param daemon the LOCKSS daemon */ public OpenUrlResolver(LockssDaemon daemon) { if (daemon == null) { throw new IllegalArgumentException("LOCKSS daemon not specified"); } this.daemon = daemon; this.pluginMgr = daemon.getPluginManager(); this.proxyMgr = daemon.getProxyManager(); } /** * Get an parameter either without or with the "rft." prefix. * * @param params the parameters * @param key the key * @return the value or <code>null</code> if not present */ private String getRftParam(Map<String,String> params, String key) { String value = params.get(key); if (value == null) { value = params.get("rft." + key); } return value; } /** * Get date based on date, ssn (season), and quarter rft parameters. * * @param params the parameters * @return a normalized date string of the form YYYY{-MM{-DD}} * or YYYY-Qn for nth quarter, or YYYY-Sn for nth season for * n between 1 and 4. */ private String getRftDate(Map<String,String> params) { String ssn = getRftParam(params, "ssn"); // spring, summer, fall, winter String quarter = getRftParam(params, "quarter"); // 1, 2, 3, 4 String date = getRftParam(params, "date"); // YYYY{-MM{-DD}} // fill in month if only year specified if ((date != null) && (date.indexOf('-') < 0)) { if (quarter != null) { // fill in month based on quarter switch (quarter) { case "1": date += "-Q1"; break; case "2": date += "-Q2"; break; case "3": date += "-Q3"; break; case "4": date += "-Q4"; break; default: log.warning("Invalid quarter: " + quarter); } } else if (ssn != null) { // fill in month based on season switch (ssn) { case "spring": date += "-S1"; break; case "summer": date += "-S2"; break; case "fall": date += "-S3"; break; case "winter": date += "-S4"; break; default: log.warning("Invalid ssn: " + ssn); } } } return date; } /** * Returns the TdbTitle corresponding to the specified OpenUrl params. * * @param params the OpenURL parameters * @return a TdbTitle or <code>null</code> if not found */ public TdbTitle resolveTdbTitleForOpenUrl(Map<String,String> params) { Tdb tdb = ConfigManager.getCurrentConfig().getTdb(); if (tdb != null) { // get TdbTitle for ISBN String isbn = getRftParam(params, "isbn"); if (isbn != null) { Collection<TdbAu> tdbAus = tdb.getTdbAusByIsbn(isbn); return tdbAus.isEmpty() ? null : tdbAus.iterator().next().getTdbTitle(); } // get TdbTitle for ISSN String issn = getRftParam(params, "issn"); if (issn != null) { return tdb.getTdbTitleByIssn(issn); } // get TdbTitle for BICI String bici = getRftParam(params, "bici"); if (bici != null) { int i = bici.indexOf('('); if (i > 0) { isbn = bici.substring(0,i); Collection<TdbAu> tdbAus = tdb.getTdbAusByIsbn(isbn); return tdbAus.isEmpty() ? null : tdbAus.iterator().next().getTdbTitle(); } } // get TdbTitle for SICI String sici = getRftParam(params, "sici"); if (sici != null) { int i = sici.indexOf('('); if (i > 0) { issn = sici.substring(0,i); return tdb.getTdbTitleByIssn(issn); } } // get TdbTitle for journal pubisher and title String publisher = getRftParam(params, "publisher"); String title = getRftParam(params, "jtitle"); if (title == null) { title = getRftParam(params, "title"); } if (title != null) { Collection<TdbTitle> tdbTitles; if (publisher != null) { TdbPublisher tdbPublisher = tdb.getTdbPublisher(publisher); tdbTitles = (tdbPublisher == null) ? Collections.<TdbTitle>emptyList() :tdbPublisher.getTdbTitlesLikeName(title); } else { tdbTitles = tdb.getTdbTitlesByName(title); } return tdbTitles.isEmpty() ? null : tdbTitles.iterator().next(); } // get TdbTitle for book pubisher and title String btitle = getRftParam(params, "btitle"); if (btitle != null) { Collection<TdbAu> tdbAus; if (publisher != null) { TdbPublisher tdbPublisher = tdb.getTdbPublisher(publisher); tdbAus = (tdbPublisher == null) ? Collections.<TdbAu>emptyList() :tdbPublisher.getTdbAusLikeName(title); } else { tdbAus = tdb.getTdbAusByName(title); } return tdbAus.isEmpty() ? null : tdbAus.iterator().next().getTdbTitle(); } } return null; } /** * Resolve an OpenURL from a set of parameter keys and values. * * @param params the OpenURL parameters * @return a url or <code>null</code> if not found */ public OpenUrlInfo resolveOpenUrl(Map<String,String> params) { log.debug3("params = " + params); OpenUrlInfo resolvedDirectly = OPEN_URL_INFO_NONE; if (params.containsKey("rft_id")) { String rft_id = params.get("rft_id"); // handle rft_id that is an HTTP or HTTPS URL if (UrlUtil.isHttpOrHttpsUrl(rft_id)) { resolvedDirectly = resolveFromUrl(rft_id); if (resolvedDirectly.isResolved()) { return resolvedDirectly; } log.debug3("Failed to resolve from URL: " + rft_id); } else if (rft_id.startsWith("info:doi/")) { String doi = rft_id.substring("info:doi/".length()); resolvedDirectly = resolveFromDOI(doi); if (resolvedDirectly.isResolved()) { return resolvedDirectly; } log.debug3("Failed to resolve from DOI: " + doi); } } if (params.containsKey("id")) { // handle OpenURL 0.1 DOI specification String id = params.get("id"); if (id.startsWith("doi:")) { String doi = id.substring("doi:".length()); resolvedDirectly = resolveFromDOI(doi); if (resolvedDirectly.isResolved()) { return resolvedDirectly; } log.debug3("Failed to resolve from DOI: " + doi); } } if (params.containsKey("doi")) { String doi = params.get("doi"); resolvedDirectly = resolveFromDOI(doi); if (resolvedDirectly.isResolved()) { return resolvedDirectly; } log.debug3("Failed to resolve from DOI: " + doi); } String pub = getRftParam(params, "pub"); String spage = getRftParam(params, "spage"); String artnum = getRftParam(params, "artnum"); String author = getRftParam(params, "au"); String atitle = getRftParam(params, "atitle"); String isbn = getRftParam(params, "isbn"); String eisbn = getRftParam(params, "eisbn"); String edition = getRftParam(params, "edition"); String date = getRftDate(params); String volume = getRftParam(params, "volume"); Tdb tdb = ConfigManager.getCurrentConfig().getTdb(); String anyIsbn = (eisbn != null) ? eisbn : isbn; if (anyIsbn != null) { OpenUrlInfo resolved = resolveFromIsbn( anyIsbn, pub, date, volume, edition, artnum, spage, author, atitle); if (resolved.isResolved()) { log.debug3( "Located url " + ((resolved.resolvedUrl == null) ? "" : resolved.resolvedUrl) + " for book ISBN " + anyIsbn); return resolved; } log.debug3("Failed to resolve from ISBN: " + isbn); } String eissn = getRftParam(params, "eissn"); String issn = getRftParam(params, "issn"); String issue = getRftParam(params, "issue"); // process a journal based on EISSN or ISSN String anyIssn = (eissn != null) ? eissn : issn; if (anyIssn != null) { // allow returning one result per publisher because // the item may be available from multiple publishers OpenUrlInfo resolved = resolveFromIssn( anyIssn, pub, date, volume, issue, spage, artnum, author, atitle); if (resolved.isResolved()) { if (log.isDebug3()) { String title = getRftParam(params, "jtitle"); if (title == null) { title = getRftParam(params, "title"); } log.debug3("Located url " + ((resolved.resolvedUrl == null) ? "" : resolved.resolvedUrl) + " for article \"" + atitle + "\"" + ", ISSN " + anyIssn + ", title \"" + title + "\""); } return resolved; } log.debug3("Failed to resolve from ISSN: " + anyIssn); } String bici = params.get("rft.bici"); if (bici != null) { // get cached URL from book book ICI code OpenUrlInfo resolved = null; try { resolved = resolveFromBici(bici); if (resolved.isResolved()) { log.debug3( "Located url " + ((resolved.resolvedUrl == null) ? "" : resolved.resolvedUrl) + "for bici " + bici); return resolved; } } catch (ParseException ex) { log.warning(ex.getMessage()); } log.debug3("Failed to resolve from BICI: " + bici); } String sici = params.get("rft.sici"); // get cached URL from serial ICI code if (sici != null) { OpenUrlInfo resolved = null; try { resolved = resolveFromSici(sici); if (resolved.isResolved()) { log.debug3( "Located url " + ((resolved.resolvedUrl == null) ? "" : resolved.resolvedUrl) + "for sici " + sici); return resolved; } } catch (ParseException ex) { log.warning(ex.getMessage()); } log.debug3("Failed to resolve from SICI: " + sici); } // process a journal or book based on its title String title = getRftParam(params, "title"); boolean isbook = false; if (title == null) { title = params.get("rft.btitle"); isbook = title != null; } if (title == null) { title = params.get("rft.jtitle"); } if (title != null) { if (tdb == null) { // TODO: need to search metadata database only // for articles if no title database is specified } else { // only search the named publisher TdbPublisher tdbPub = null; if (pub != null) { tdbPub = tdb.getTdbPublisher(pub); // report no match if no matching publisher if (tdbPub == null) { return resolvedDirectly; } } if (isbook) { // search as though it is a book title Collection<TdbAu> tdbAus; if (tdbPub != null) { tdbAus = tdbPub.getTdbAusLikeName(title); } else { tdbAus = tdb.getTdbAusLikeName(title); } OpenUrlInfo resolved = null; Collection<TdbAu> noTdbAus = new ArrayList<TdbAu>(); for (TdbAu tdbAu : tdbAus) { // search for book through its ISBN to ensure that both // metadata database and title database are consulted String id = tdbAu.getIsbn(); if (id != null) { // try resolving from ISBN // note: non-standard treatment of 'artnum' as chapter identifier String tdbPubName = tdbAu.getPublisherName(); OpenUrlInfo info = resolveFromIsbn( id, tdbPubName, date, volume, issue, artnum, spage, author, atitle); if (info.isResolved()) { if (log.isDebug3()) { log.debug3("Located url " + ((info.resolvedUrl == null) ? "" : info.resolvedUrl) + " for article \"" + atitle + "\"" + ", ISBN " + id + ", title \"" + title + "\"" + ", publisher \"" + tdbAu.getPublisherName() + "\""); } if (resolved == null) { resolved = info; } else { resolved.add(info); } } } else { // add to list of titles with no ISBN noTdbAus.add(tdbAu); } } if (resolved != null) { return resolved; } // search matching titles without ISBNs resolved =resolveBookFromTdbAus( noTdbAus, date, volume, edition, artnum, spage); if (resolved.isResolved()) { if (log.isDebug3()) { log.debug3( "Located url " + resolved.resolvedUrl + ", title \"" + title + "\""); } } return resolved; } else { // search as though it is a journal title Collection<TdbTitle> tdbTitles; if (tdbPub != null) { // find title from specified publisher tdbTitles = tdbPub.getTdbTitlesByName(title); // find "like" titles if no exact matches if (tdbTitles.isEmpty()) { tdbTitles = tdbPub.getTdbTitlesLikeName(title); } } else { // find title from any publisher tdbTitles = tdb.getTdbTitlesByName(title); // find "like" titles if no exact matches if (tdbTitles.isEmpty()) { tdbTitles = tdb.getTdbTitlesLikeName(title); } } OpenUrlInfo resolved = null; Collection<TdbTitle> noTdbTitles = new ArrayList<TdbTitle>(); for (TdbTitle tdbTitle : tdbTitles) { // search for journal through its ISSN to ensure that both // metadata database and title database are consulted String id = tdbTitle.getIssn(); if (id != null) { // try resolving from ISSN String tdbPubName = tdbTitle.getPublisherName(); OpenUrlInfo info = resolveFromIssn(id, tdbPubName, date, volume, issue, spage, artnum, author, atitle); if (info.isResolved()) { if (log.isDebug3()) { log.debug3("Located url " + ((info.resolvedUrl == null) ? "" : info.resolvedUrl) + " for article \"" + atitle + "\"" + ", ISSN " + id + ", title \"" + title + "\"" + ", publisher \"" + tdbPubName + "\""); } if (resolved == null) { resolved = info; } else { resolved.add(info); } } } else { // add to list of titles with no ISBN or ISSN noTdbTitles.add(tdbTitle); } } if (resolved != null) { return resolved; } // search matching titles without ISSNs for (TdbTitle noTdbTitle : noTdbTitles) { Collection<TdbAu> tdbAus = noTdbTitle.getTdbAus(); OpenUrlInfo info = resolveJournalFromTdbAus(tdbAus,date,volume,issue, spage, artnum); if (info.isResolved()) { if (log.isDebug3()) { log.debug3( "Located url " + ((resolved.resolvedUrl == null) ? "" : resolved.resolvedUrl) + ", title \"" + title + "\""); } if (resolved == null) { resolved = info; } else { resolved.add(info); } } } if (resolved != null) { return resolved; } } } OpenUrlInfo resolved = OpenUrlInfo.newInstance(null, null, isbook ? OpenUrlInfo.ResolvedTo.VOLUME : OpenUrlInfo.ResolvedTo.TITLE); // create bibliographic item with only title properties resolved.resolvedBibliographicItem = new BibliographicItemImpl() .setPublisherName(pub) .setPublicationTitle(title); return resolved; } else if (pub != null) { OpenUrlInfo resolved = OpenUrlInfo.newInstance( null, null, OpenUrlInfo.ResolvedTo.PUBLISHER); // create bibliographic item with only publisher properties resolved.resolvedBibliographicItem = new BibliographicItemImpl() .setPublisherName(pub); return resolved; } return resolvedDirectly; } /** * Resolve serials article based on the SICI descriptor. For an article * "Who are These Independent Information Brokers?", Bulletin of the * American Society for Information Science, Feb-Mar 1995, Vol. 21, no 3, * page 12, the SICI would be: 0095-4403(199502/03)21:3<12:WATIIB>2.0.TX;2-J * * @param sici a string representing the serials article SICI * @return the article url or <code>null</code> if not resolved * @throws ParseException if error parsing SICI */ public OpenUrlInfo resolveFromSici(String sici) throws ParseException { int i = sici.indexOf('('); if (i < 0) { // did not find end of date section throw new ParseException("Missing start of date section", 0); } // validate ISSN after normalizing to remove punctuation String issn = sici.substring(0,i).replaceFirst("-", ""); if (!MetadataUtil.isIssn(issn)) { // ISSN is 8 characters throw new ParseException("Malformed ISSN", 0); } // skip over date section (199502/03) int j = sici.indexOf(')',i+1); if (j < 0) { // did not find end of date section throw new ParseException("Missing end of date section", i+1); } // get volume and issue between end of // date section and start of article section i = j+1; // advance to start of volume j = sici.indexOf('<',i); if (j < 0) { // did not find start of issue section throw new ParseException("Missing start of issue section", i); } // get volume delimiter int k = sici.indexOf(':', i); if ((k < 0) || (k >= j)) { // no volume delimiter before start of issue section throw new ParseException("Missing volume delimiter", i); } String volume = sici.substring(i,k); String issue = sici.substring(k+1,j); // get end of issue section i = j+1; k = sici.indexOf('>', i+1); if (k < 0) { // did not find end of issue section throw new ParseException("Missing end of issue section", i+1); } j = sici.indexOf(':',i+1); if ((j < 0) || (j >= k)) { throw new ParseException("Missing page delimiter", i+1); } String spage = sici.substring(i,j); // get the cached URL from the parsed paramaters // note: no publisher with sici OpenUrlInfo resolved = resolveFromIssn(issn, null, null, volume, issue, spage, null, null, null); if ((resolved.isResolved()) && log.isDebug()) { // report on the found article Tdb tdb = ConfigManager.getCurrentConfig().getTdb(); String jTitle = null; if (tdb != null) { TdbTitle title = tdb.getTdbTitleByIssn(issn); if (title != null) { jTitle = title.getName(); } } if (log.isDebug3()) { String s = "Located cachedURL " + ((resolved.resolvedUrl == null) ? "" : resolved.resolvedUrl) + " for ISSN " + issn + ", volume: " + volume + ", issue: " + issue + ", start page: " + spage; if (jTitle != null) { s += ", journal title \"" + jTitle + "\""; } log.debug3(s); } } return OPEN_URL_INFO_NONE; } /** * Resolve a book chapter based on the BICI descriptor. For an item "English * as a World Language", Chapter 10, in "The English Language: A Historical * Introduction", 1993, pp. 234-261, ISBN 0-521-41620-5, the BICI would be * 0521416205(1993)(10;EAAWL;234-261)2.2.TX;1-1 * * @param bici a string representing the book chapter BICI * @return the article url or <code>null</code> if not resolved * @throws ParseException if error parsing BICI */ public OpenUrlInfo resolveFromBici(String bici) throws ParseException { int i = bici.indexOf('('); if (i < 0) { // did not find end of date section throw new ParseException("Missing start of date section", 0); } String isbn = bici.substring(0,i).replaceAll("-", ""); // match ISBN-10 or ISBN-13 with 0-9 or X checksum character if (!MetadataUtil.isIsbn(isbn, false)) { // ISSB is 10 or 13 characters throw new ParseException("Malformed ISBN", 0); } // skip over date section (1993) int j = bici.indexOf(')',i+1); if (j < 0) { // did not find end of date section throw new ParseException("Missing end of date section", i+5); } String date = bici.substring(i+1, j); // get volume and issue between end of // date section and start of article section if (bici.charAt(j+1) != '(') { // did not find start of chapter section throw new ParseException("Missing start of chapter section", j+1); } i = j+2; // advance to start of chapter j = bici.indexOf(')',i); if (j < 0) { // did not find end of chapter section throw new ParseException("Missing end of chapter section", i); } // get chapter number delimiter int k = bici.indexOf(';', i); if ((k < 0) || (k >= j)) { // no chapter number delimiter before end of chapter section throw new ParseException("Missing chapter number delimiter", i); } String chapter = bici.substring(i,k); // get end of chapter section i = k+1; k = bici.indexOf(';', i+1); if ((k < 0) || (k >= j)) { // no chapter abbreviation delimiter before end of chapter section throw new ParseException("Missing chapter abbreviation delimiter", i); } // extract the start page String spage = bici.substring(k+1,j); if (spage.indexOf('-') > 0) { spage = spage.substring(0, spage.indexOf('-')); } // (isbn, date, volume, edition, chapter, spage, author, title) // note: no publisher specified with bici OpenUrlInfo resolved = resolveFromIsbn(isbn, null, date, null, null, chapter, spage, null, null); if ((resolved.isResolved()) && log.isDebug()) { Tdb tdb = ConfigManager.getCurrentConfig().getTdb(); String bTitle = null; if (tdb != null) { Collection<TdbAu> tdbAus = tdb.getTdbAusByIsbn(isbn); if (!tdbAus.isEmpty()) { bTitle = tdbAus.iterator().next().getPublicationTitle(); } } if (log.isDebug3()) { String s = "Located cachedURL " + ((resolved.resolvedUrl == null) ? "" : resolved.resolvedUrl) + " for ISBN " + isbn + ", year: " + date + ", chapter: " + chapter + ", start page: " + spage; if (bTitle != null) { s += ", book title \"" + bTitle + "\""; } log.debug3(s); } } return OPEN_URL_INFO_NONE; } /** * Resolves from a url. * * @param aUrl the URL * @return a resolved URL */ public OpenUrlInfo resolveFromUrl(String aUrl) { return resolveFromUrl(aUrl, null); // no proxy specified } /** * Resolves from a url. If URL is not in cache, returned OpenUrlInfo * resolvedTo indicator is ResolvedTo.NONE. * * @param aUrl the URL * @param proxySpec a proxy string of the form "host:port" * @return OpenURLInfo with resolved URL */ public OpenUrlInfo resolveFromUrl(String aUrl, String proxySpec) { String url = resolveUrl(aUrl, proxySpec); if (url != null) { CachedUrl cu = pluginMgr.findCachedUrl(url, CuContentReq.PreferContent); if (cu != null) { return OpenUrlInfo.newInstance(url, proxySpec); } } return OPEN_URL_INFO_NONE; } /** * Validates a URL and resolve it by following indirects, and stopping * early if a URL that is in the LOCKSS cache is found. * * @param aUrl the URL * @param auProxySpec an AU proxy spec of the form "host:port" * @return a resolved URL */ String resolveUrl(String aUrl, String auProxySpec) { // protected for testing if (isNeverProxy()) { if (pluginMgr.findCachedUrl(aUrl) != null) { return aUrl; } else { return null; } } String url = aUrl; try { final LockssUrlConnectionPool connectionPool = proxyMgr.getQuickConnectionPool(); // get proxy host and port for the proxy spec or the current config AuProxyInfo proxyInfo = AuUtil.getAuProxyInfo(auProxySpec); String proxyHost = proxyInfo.getHost(); int proxyPort = proxyInfo.getPort(); for (int i = 0; i < MAX_REDIRECTS; i++) { // no need to look further if content already cached if (pluginMgr.findCachedUrl(url) != null) { return url; } // test URL by opening connection LockssUrlConnection conn = null; try { conn = UrlUtil.openConnection(url, connectionPool); conn.setFollowRedirects(false); conn.setRequestProperty("user-agent", LockssDaemon.getUserAgent()); if (!StringUtil.isNullString(proxyHost) && (proxyPort > 0)) { try { conn.setProxy(proxyHost, proxyPort); } catch (UnsupportedOperationException ex) { log.warning("Unsupported connection request proxy: " + proxyHost + ":" + proxyPort); } } conn.execute(); // if not redirected, validate based on response code String url2 = conn.getResponseHeaderValue("Location"); if (url2 == null) { int response = conn.getResponseCode(); log.debug3(i + " response code: " + response); if (response == HttpURLConnection.HTTP_OK) { return url; } return null; } // resolve redirected URL and try again url = UrlUtil.resolveUri(url, url2); log.debug3(i + " resolved to: " + url); } finally { IOUtil.safeRelease(conn); } } } catch (IOException ex) { log.error("resolving from URL:" + aUrl + " with URL: " + url, ex); } return null; } /** * Return the article URL from a DOI, using either the MDB or TDB. * @param doi the DOI * @return the article url */ public OpenUrlInfo resolveFromDOI(String doi) { if (!MetadataUtil.isDoi(doi)) { return OPEN_URL_INFO_NONE; } OpenUrlInfo resolved = OPEN_URL_INFO_NONE; try { // resolve from database manager DbManager dbMgr = daemon.getDbManager(); resolved = resolveFromDoi(dbMgr, doi); } catch (IllegalArgumentException ex) { } if (resolved.isNotResolved()) { // use DOI International resolver for DOI resolved = resolveFromUrl("http://dx.doi.org/" + doi); } return resolved; } /** * Return the OpenUrl query string for the specified auid. * * @param auid the auid * @return the OpenUrl query string, or null if not available */ public String getOpenUrlQueryForAuid(String auid) { TdbAu tdbau = TdbUtil.getTdbAu(auid); if (tdbau != null) { return getOpenUrlQueryForBibliographicItem(tdbau); } // Try returning an OpenURL with the starting URL // corresponding to the AU with a SpiderCrawlSpec; // by convention, the first URL is the manifest page // (not for OAICrawlSpec or other types of CrawlSpec) ArchivalUnit au = pluginMgr.getAuFromId(auid); if (au != null) { Collection<String> urls = au.getAccessUrls(); if (urls.size() > 0) { return "rft_id=" + urls.iterator().next(); } } return null; } /** * Return the OpenUrl query string for the specified bibliographic item. * * @param bibitem the BibliographicItem * @return the OpenUrl query string, or null if not available */ @Loggable(value = Loggable.TRACE, prepend = true) static public String getOpenUrlQueryForBibliographicItem( BibliographicItem bibitem) { StringBuffer sb = new StringBuffer(); String isbn = bibitem.getIsbn(); if (!StringUtil.isNullString(isbn)) { sb.append("&isbn="); sb.append(UrlUtil.encodeQueryArg(MetadataUtil.formatIsbn(isbn))); } String issn = bibitem.getIssn(); if (!StringUtil.isNullString(issn)) { sb.append("&issn="); sb.append(UrlUtil.encodeQueryArg(MetadataUtil.formatIssn(issn))); } String publisher = bibitem.getPublisherName(); if (!StringUtil.isNullString(publisher)) { sb.append("&publisher="); sb.append(UrlUtil.encodeQueryArg(publisher)); } String title = bibitem.getPublicationTitle(); if (!StringUtil.isNullString(title)) { String pubType = bibitem.getPublicationType(); if ( !StringUtil.isNullString(pubType) && pubType.startsWith("book")) { sb.append("&btitle"); } else { sb.append("&jtitle="); } sb.append(UrlUtil.encodeQueryArg(title)); } String year = bibitem.getStartYear(); if ( !StringUtil.isNullString(year) && year.equals(bibitem.getYear())) { sb.append("&year="); sb.append(UrlUtil.encodeQueryArg(year)); } String volume = bibitem.getStartVolume(); if ( !StringUtil.isNullString(volume) && volume.equals(bibitem.getVolume())) { sb.append("&volume="); sb.append(UrlUtil.encodeQueryArg(volume)); } String issue = bibitem.getStartIssue(); if ( !StringUtil.isNullString(issue) && volume.equals(bibitem.getIssue())) { sb.append("&issue="); sb.append(UrlUtil.encodeQueryArg(issue)); } return (sb.length() == 0) ? null : sb.substring(1); } /** * Return the article URL from a DOI using the MDB. * @param dbMgr the database manager * @param doi the DOI * @return the OpenUrlInfo */ @Loggable(value = Loggable.TRACE, prepend = true) private OpenUrlInfo resolveFromDoi(DbManager dbMgr, String doi) { Connection conn = null; try { conn = dbMgr.getConnection(); String query = "select u." + URL_COLUMN + " from " + URL_TABLE + " u," + DOI_TABLE + " d" + " where u." + MD_ITEM_SEQ_COLUMN + " = d." + MD_ITEM_SEQ_COLUMN + " and upper(d." + DOI_COLUMN + ") = ?"; PreparedStatement stmt = dbMgr.prepareStatement(conn, query); stmt.setString(1, doi.toUpperCase()); ResultSet resultSet = dbMgr.executeQuery(stmt); if (resultSet.next()) { String url = resultSet.getString(1); OpenUrlInfo resolved = resolveFromUrl(url); return resolved; } } catch (SQLException ex) { log.error("Getting DOI:" + doi, ex); } catch (DbException dbe) { log.error("Getting DOI:" + doi, dbe); } finally { DbManager.safeRollbackAndClose(conn); } return OPEN_URL_INFO_NONE; } /** * Return article URL from an ISSN, date, volume, issue, spage, and author. * The first author will only be used when the starting page is not given. * * @param issn the issn * @param pub the publisher * @param date the publication date * @param volume the volume * @param issue the issue * @param spage the starting page * @param artnum the article number * @param author the first author's full name * @param atitle the article title * @return the article URL */ @Loggable(value = Loggable.TRACE, prepend = true, trim = false) public OpenUrlInfo resolveFromIssn( String issn, String pub, String date, String volume, String issue, String spage, String artnum, String author, String atitle) { OpenUrlInfo resolved = null; // try resolving from the metadata database first try { DbManager dbMgr = daemon.getDbManager(); OpenUrlInfo aResolved = resolveFromIssn(dbMgr, issn, pub, date, volume, issue, spage, artnum, author, atitle); if (aResolved.isResolved()) { return aResolved; } } catch (IllegalArgumentException ex) { } // get list of TdbTitles for issn Tdb tdb = ConfigManager.getCurrentConfig().getTdb(); Collection<TdbTitle> titles; if (tdb == null) { titles = Collections.<TdbTitle>emptyList(); } else if (pub != null) { TdbPublisher tdbPub = tdb.getTdbPublisher(pub); titles = (tdbPub == null) ? Collections.<TdbTitle>emptyList() : tdbPub.getTdbTitlesByIssn(issn); } else { titles = tdb.getTdbTitlesByIssn(issn); } // try resolving from the title database for (TdbTitle title : titles) { OpenUrlInfo aResolved = null; // resolve title, volume, AU, or issue TOC from TDB Collection<TdbAu> tdbAus = title.getTdbAus(); aResolved = resolveJournalFromTdbAus(tdbAus, date, volume, issue, spage, artnum); if (aResolved.isNotResolved()) { aResolved = OpenUrlInfo.newInstance( null,null, OpenUrlInfo.ResolvedTo.TITLE); // create bibliographic item with only title properties aResolved.resolvedBibliographicItem = new BibliographicItemImpl() .setPublisherName(title.getPublisherName()) .setPublicationTitle(title.getName()) .setProprietaryIds(title.getProprietaryIds()) .setCoverageDepth(title.getCoverageDepth()) .setPrintIssn(title.getPrintIssn()) .setEissn(title.getEissn()) .setIssnL(title.getIssnL()); if (resolved == null) { resolved = aResolved; } else { resolved.add(aResolved); } } else { if (resolved != null) { // add ahead of any fall-back OpenUrlInfo records aResolved.add(resolved); } resolved = aResolved; } } return (resolved == null) ? OPEN_URL_INFO_NONE : resolved; } /** * Return article URL from an ISSN, date, volume, issue, spage, and author. * The first author will only be used when the starting page is not given. * * @param dbMgr the database manager * @param issns a list of alternate ISSNs for the title * @param pub the publisher * @param date the publication date * @param volume the volume * @param issue the issue * @param spage the starting page * @param artnum the article number * @param author the first author's full name * @param atitle the article title * @return the article URL */ @Loggable(value = Loggable.TRACE, prepend = true) private OpenUrlInfo resolveFromIssn( DbManager dbMgr, String issn, String pub, String date, String volume, String issue, String spage, String artnum, String author, String atitle) { // true if properties specified a journal item boolean hasJournalSpec = (date != null) || (volume != null) || (issue != null); // true if properties specify an article boolean hasArticleSpec = (spage != null) || (artnum != null) || (author != null) || (atitle != null); Connection conn = null; OpenUrlInfo resolved = null; try { conn = dbMgr.getConnection(); StringBuilder select = new StringBuilder("select distinct "); StringBuilder from = new StringBuilder(" from "); StringBuilder where = new StringBuilder(" where "); ArrayList<String> args = new ArrayList<String>(); // return all related values for debugging purposes select.append("u." + URL_COLUMN); select.append(",pb." + PUBLISHER_NAME_COLUMN); select.append(",n1." + NAME_COLUMN + " as publication_name"); select.append(",i." + ISSN_COLUMN); select.append(",bi." + VOLUME_COLUMN); select.append(",bi." + ISSUE_COLUMN); select.append(",bi." + START_PAGE_COLUMN); select.append(",bi." + END_PAGE_COLUMN); select.append(",bi." + ITEM_NO_COLUMN); select.append(",n2." + NAME_COLUMN + " as article_name"); select.append(",pv2." + PROVIDER_NAME_COLUMN); from.append(MD_ITEM_TABLE + " mi1"); // publication md_item from.append("," + MD_ITEM_TABLE + " mi2"); // article md_item from.append("," + ISSN_TABLE + " i"); from.append("," + PUBLICATION_TABLE + " pu"); from.append("," + PUBLISHER_TABLE + " pb"); from.append("," + MD_ITEM_NAME_TABLE + " n1"); // publication name from.append("," + MD_ITEM_NAME_TABLE + " n2"); // article name from.append("," + URL_TABLE + " u"); from.append("," + BIB_ITEM_TABLE + " bi"); from.append("," + PROVIDER_TABLE + " pv2"); from.append("," + AU_MD_TABLE + " am2"); where.append("mi2." + PARENT_SEQ_COLUMN + "="); where.append("mi1." + MD_ITEM_SEQ_COLUMN); where.append(" and i." + MD_ITEM_SEQ_COLUMN + "="); where.append("mi1." + MD_ITEM_SEQ_COLUMN); where.append(" and i." + ISSN_COLUMN + " = ?"); args.add(MetadataUtil.toUnpunctuatedIssn(issn)); // strip punctuation where.append(" and pu." + MD_ITEM_SEQ_COLUMN + "="); where.append("mi1." + MD_ITEM_SEQ_COLUMN); where.append(" and pb." + PUBLISHER_SEQ_COLUMN + "="); where.append("pu." + PUBLISHER_SEQ_COLUMN); if (pub != null) { // match publisher if specified where.append(" and pb." + PUBLISHER_NAME_COLUMN + "= ?"); args.add(pub); } where.append(" and n1." + MD_ITEM_SEQ_COLUMN + "="); where.append("mi1." + MD_ITEM_SEQ_COLUMN); where.append(" and n1." + NAME_TYPE_COLUMN + "='primary'"); where.append(" and u." + MD_ITEM_SEQ_COLUMN + "="); where.append("mi2." + MD_ITEM_SEQ_COLUMN); where.append(" and u." + FEATURE_COLUMN + "='Access'"); where.append(" and bi." + MD_ITEM_SEQ_COLUMN + "="); where.append("mi2." + MD_ITEM_SEQ_COLUMN); where.append(" and n2." + MD_ITEM_SEQ_COLUMN + "="); where.append("mi2." + MD_ITEM_SEQ_COLUMN); where.append(" and n2." + NAME_TYPE_COLUMN + "='primary'"); where.append(" and mi2." + AU_MD_SEQ_COLUMN + "="); where.append("am2." + AU_MD_SEQ_COLUMN); where.append(" and am2." + PROVIDER_SEQ_COLUMN + "="); where.append("pv2." + PROVIDER_SEQ_COLUMN); if (hasJournalSpec) { // can specify an issue by a combination of date, volume and issue; // how these combine varies, so do the most liberal match possible // and filter based on multiple results if (date != null) { // enables query "2009" to match "2009-05-10" in database where.append(" and mi2." + DATE_COLUMN); where.append(" like ? escape '\\'"); args.add(date.replace("\\","\\\\").replace("%","\\%") + "%"); } if (volume != null) { where.append(" and bi." + VOLUME_COLUMN + " = ?"); args.add(volume); } if (issue != null) { where.append(" and bi." + ISSUE_COLUMN + " = ?"); args.add(issue); } } // handle start page, author, and article title as // equivalent ways to specify an article within an issue if (hasArticleSpec) { // accept any of the three where.append(" and ( "); if (spage != null) { where.append("bi." + START_PAGE_COLUMN + " = ?"); args.add(spage); } if (artnum != null) { if (spage != null) { where.append(" or "); } where.append("bi." + ITEM_NO_COLUMN + " = ?"); args.add(artnum); } if (atitle != null) { if ((spage != null) || (artnum != null)) { where.append(" or "); } where.append("upper(n2." + NAME_COLUMN); where.append(") like ? escape '\\'"); args.add(atitle.toUpperCase().replace("%","\\%") + "%"); } if (author != null) { if ((spage != null) || (artnum != null) || (atitle != null)) { where.append(" or "); } from.append("," + AUTHOR_TABLE + " au"); // add the author query to the query addAuthorQuery(author, where, args); } where.append(")"); } String qstr = select.toString() + from.toString() + where.toString(); // only one value expected; any more and the query was under-specified int maxPublishersPerArticle = getMaxPublishersPerArticle(); String[][] results = new String[maxPublishersPerArticle+1][11]; int count = resolveFromQuery(conn, qstr, args, results); if (count <= maxPublishersPerArticle) { // ensure at most one result per publisher+provider in case // more than one publisher+provider publishes the same serial Set<String> pubs = new HashSet<String>(); for (int i = 0; i < count; i++) { // combine publisher and provider columns to determine uniqueness if (!pubs.add(results[i][1] + results[i][10])) { return OPEN_URL_INFO_NONE; } OpenUrlInfo info = OpenUrlInfo.newInstance(results[i][0], null, OpenUrlInfo.ResolvedTo.ARTICLE); if (resolved == null) { resolved = info; } else { resolved.add(info); } } } } catch (DbException dbe) { log.error("Getting ISSN:" + issn, dbe); } finally { DbManager.safeRollbackAndClose(conn); } return (resolved == null) ? OPEN_URL_INFO_NONE : resolved; } /** * Returns the maximumn number of publishers per article to allow when * querying the metadata database. * * @return the maximum number of publishers per article to allow */ static private int getMaxPublishersPerArticle() { int maxpubs = ConfigManager.getCurrentConfig() .getInt(PARAM_MAX_PUBLISHERS_PER_ARTICLE, DEFAULT_MAX_PUBLISHERS_PER_ARTICLE); return (maxpubs <= 0) ? DEFAULT_MAX_PUBLISHERS_PER_ARTICLE : maxpubs; } // Doesn't account for noproxy query param in ServeContent request static private boolean isNeverProxy() { return ConfigManager.getCurrentConfig().getBoolean(PARAM_NEVER_PROXY, DEFAULT_NEVER_PROXY); } /** * Resolve query if a single URL matches. * * @param conn the connection * @param query the query * @param args the args * @param results the results * @return the number of results returned * @throws DbException */ @Loggable(value = Loggable.TRACE, prepend = true) private int resolveFromQuery(Connection conn, String query, List<String> args, String[][] results) throws DbException { final String DEBUG_HEADER = "resolveFromQuery(): "; log.debug3(DEBUG_HEADER + "query: " + query); PreparedStatement stmt = daemon.getDbManager().prepareStatement(conn, query); int count = 0; try { for (int i = 0; i < args.size(); i++) { log.debug3(DEBUG_HEADER + " query arg: " + args.get(i)); stmt.setString(i + 1, args.get(i)); } stmt.setMaxRows(results.length); // only need 2 to to determine if unique ResultSet resultSet = daemon.getDbManager().executeQuery(stmt); for ( ; count < results.length && resultSet.next(); count++) { for (int i = 0; i < results[count].length; i++) { results[count][i] = resultSet.getString(i+1); } } } catch (SQLException sqle) { throw new DbException("Cannot resolve from query", sqle); } return count; } /** * Return article URL from a TdbTitle, date, volume, and issue. * * @param tdbAus a collection of TdbAus that match an ISSNs * @param date the publication date * @param volume the volume * @param issue the issue * @param spage the start page * @param artnum the article number * @return the article URL */ @Loggable(value = Loggable.TRACE, prepend = true) private OpenUrlInfo resolveJournalFromTdbAus( Collection<TdbAu> tdbAus, String date, String volume, String issue, String spage, String artnum) { // get the year from the date String year = null; if (date != null) { try { year = Integer.toString(PublicationDate.parse(date).getYear()); } catch (ParseException ex) {} } log.debug3("resolveJournalFromTdbAus: year=" + year + ": " + tdbAus); // list of AUs that match volume and year specified ArrayList<TdbAu> foundTdbAuList = new ArrayList<TdbAu>(); // list of AUs that do not match volume and year specified ArrayList<TdbAu> notFoundTdbAuList = new ArrayList<TdbAu>(); // find a TdbAu that matches the date, and volume for (TdbAu tdbAu : tdbAus) { // if neither year or volume specified, pick any TdbAu if ((volume == null) && (year == null)) { notFoundTdbAuList.add(tdbAu); continue; } // if volume specified, see if this TdbAu matches if (volume != null) { if (!tdbAu.includesVolume(volume)) { notFoundTdbAuList.add(tdbAu); continue; } } // if year specified, see if this TdbAu matches if (year != null) { if (!tdbAu.includesYear(year)) { notFoundTdbAuList.add(tdbAu); continue; } } foundTdbAuList.add(tdbAu); } log.debug3("foundTdbAuList: " + foundTdbAuList); // look for URL that is cached from list of matching AUs for (TdbAu tdbau : foundTdbAuList) { String aYear = year; if (aYear == null) { aYear = tdbau.getStartYear(); } String aVolume = volume; if (aVolume == null) { aVolume = tdbau.getStartVolume(); } String anIssue = issue; if (anIssue == null) { anIssue = tdbau.getStartIssue(); } OpenUrlInfo aResolved = getJournalUrl(tdbau, aYear, aVolume, anIssue, spage, artnum); if (aResolved.resolvedUrl != null) { if ( pluginMgr.findCachedUrl(aResolved.resolvedUrl) != null) { // found the URL if in cache return aResolved; } // even though getJournalUrl() checks that page exists, // we can't rely on resolved URL being usable if the TdbAu is down if (!tdbau.isDown()) { return aResolved; } log.debug2( "discarding URL " + aResolved.resolvedUrl + " because tdbau is down: " + tdbau.getName()); } } // use tdbau that is not down from notFoundTdbAuList to find the // title or publisher URL, since that is all we can return at this point for (TdbAu tdbau : notFoundTdbAuList) { if (!tdbau.isDown()) { OpenUrlInfo aResolved = getJournalUrl(tdbau, null, null, null, null, null); return aResolved; } log.debug2("discarding URL because tdbau is down: " + tdbau.getName()); } // pick any AU to use for resolving the title as a last resort if (!notFoundTdbAuList.isEmpty()) { OpenUrlInfo aResolved = getJournalUrl(notFoundTdbAuList.get(0), null, null, null, null, null); aResolved.resolvedUrl = null; return aResolved; } return OPEN_URL_INFO_NONE; } /** * Return the type entry parameter map for the specified Plugin and TdbAu. * @param plugin the plugin * @param tdbau the AU * @return the parameter map */ private static TypedEntryMap getParamMap(Plugin plugin, TdbAu tdbau) { TypedEntryMap paramMap = new TypedEntryMap(); List<ConfigParamDescr> descrs = plugin.getAuConfigDescrs(); for (ConfigParamDescr descr : descrs) { String key = descr.getKey(); String sval = tdbau.getParam(key); if (sval == null) { sval = tdbau.getPropertyByName(key); if (sval == null) { sval = tdbau.getAttr(key); } } if (sval != null) { try { Object val = descr.getValueOfType(sval); paramMap.setMapElement(key, val); } catch (InvalidFormatException ex) { log.warning("invalid value for key: " + key + " value: " + sval, ex); } } } // add entries for attributes that do not correspond to AU params for (Map.Entry<String,String> entry : tdbau.getAttrs().entrySet()) { if (!paramMap.containsKey(entry.getKey())) { paramMap.setMapElement(entry.getKey(), entry.getValue()); } } return paramMap; } /** * Return the type entry parameter map for the specified AU. * @param au the AU * @return the parameter map */ /* for later use (pjg) private static TypedEntryMap getParamMap(ArchivalUnit au) { TypedEntryMap paramMap = new TypedEntryMap(); Configuration config = au.getConfiguration(); Plugin plugin = au.getPlugin(); for (ConfigParamDescr descr : plugin.getAuConfigDescrs()) { String key = descr.getKey(); if (config.containsKey(key)) { try { Object val = descr.getValueOfType(config.get(key)); paramMap.setMapElement(key, val); } catch (Exception ex) { log.error("Error configuring: " + key + " " + ex.getMessage()); } } } return paramMap; } */ /** * Gets the book URL for an AU indicated by the DefinablePlugin * and parameter definitions specified by the TdbAu. * * @param plugin the DefinablePlugin * @param tdbau the TdbAu * @param year the year * @param volumeName the volume name * @param issue the issue * @return the issue URL */ /* for later use (pjg) private static String getBooklUrl( ArchivalUnit au, String volumeName, String year, String edition) { TypedEntryMap paramMap = getParamMap(au); Plugin plugin = au.getPlugin(); String url = getBookUrl(plugin, paramMap, volumeName, year, edition); return url; } */ /** * Gets the book URL for a TdbAU indicated by the DefinablePlugin * and parameter definitions specified by the TdbAu. * @param tdbau the TdbAu * @param year the year * @param volumeName the volume name * @param edition the edition * @param chapter the chapter * @param spage the start page * @return the starting URL */ @Loggable(value = Loggable.TRACE, prepend = true) private OpenUrlInfo getBookUrl( TdbAu tdbau, String year, String volumeName, String edition, String chapter, String spage) { String pluginKey = PluginManager.pluginKeyFromId(tdbau.getPluginId()); Plugin plugin = pluginMgr.getPlugin(pluginKey); OpenUrlInfo resolved = null; if (plugin != null) { log.debug3( "getting book feature url for plugin: " + plugin.getClass().getName()); // get starting URL from a DefinablePlugin TypedEntryMap paramMap = getParamMap(plugin, tdbau); // add volume with type and spelling of existing element paramMap.setMapElement("volume", volumeName); paramMap.setMapElement("volume_str",volumeName); paramMap.setMapElement("volume_name", volumeName); paramMap.setMapElement("year", year); if (!StringUtil.isNullString(year)) { try { paramMap.setMapElement("au_short_year", String.format("%02d", NumberUtil.parseInt(year)%100)); } catch (NumberFormatException ex) { log.info( "Error parsing year '" + year + "' as an int -- not setting au_short_year"); } } paramMap.setMapElement("edition", edition); paramMap.setMapElement("chapter", chapter); paramMap.setMapElement("page", spage); // auFeatureKey selects feature from a map of values // for the same feature (e.g. au_feature_urls/au_year) paramMap.setMapElement("auFeatureKey", tdbau.getAttr(AU_FEATURE_KEY)); String isbn = tdbau.getAttr("isbn"); if (isbn != null) { paramMap.setMapElement("isbn", isbn); } String eisbn = tdbau.getAttr("eisbn"); if (eisbn != null) { paramMap.setMapElement("eisbn", eisbn); } resolved = getBookUrl(tdbau, plugin, paramMap); if (resolved.isResolved()) { resolved.resolvedBibliographicItem = tdbau; log.debug3("Resolved book url from plugin: " + resolved.resolvedUrl); } } else { log.debug3("No plugin found for key: " + pluginKey); } return resolved; } /** * Find the most specific bool feature URL that can be determined from * the supplied parameters. * @param tdbAu TdbAu describing AU to be accessed * @param plugin the plugin * @param paramMap param map containing properties and AU config params * from TdbAu, plus possibly <code>issn</code>, <code>eissn</code>, * <code>feature_key</code>, <code>volume</code>, * <code>volume_str</code>, <code>volume_name</code>, * <code>year</code>, <code>au_short_year</code>, <code>issue</code>, * <code>article</code>, <code>page</code>, <code>item</code> (article * number). * @return a feature URL */ @Loggable(value = Loggable.TRACE, prepend = true) public OpenUrlInfo getBookUrl(TdbAu tdbAu, Plugin plugin, TypedEntryMap paramMap) { OpenUrlInfo resolved = getPluginUrl(tdbAu, plugin, auBookAuFeatures, paramMap); return resolved; } /* * * Gets the issue URL for an AU indicated by the DefinablePlugin * and parameter definitions specified by the TdbAu. * * @param plugin the DefinablePlugin * @param tdbau the TdbAu * @param year the year * @param volumeName the volume name * @param issue the issue * @return the issue URL */ /* for later use (pjg) private static String getJournalUrl( ArchivalUnit au, String year, String volumeName, String issue) { TypedEntryMap paramMap = getParamMap(au); Plugin plugin = au.getPlugin(); String url = getJournalUrl(plugin, paramMap, year, volumeName, issue); return url; } */ /** * Get starting url from TdbAu. * @param tdbau the TdbAu * @param year the year * @param volumeName the volume name * @param issue the issue * @param spage the start page * @param artnum the article number * @return the starting URL */ @Loggable(value = Loggable.TRACE, prepend = true) private OpenUrlInfo getJournalUrl( TdbAu tdbau, String year, String volumeName, String issue, String spage, String artnum) { String pluginKey = PluginManager.pluginKeyFromId(tdbau.getPluginId()); Plugin plugin = pluginMgr.getPlugin(pluginKey); OpenUrlInfo resolved = OPEN_URL_INFO_NONE; if (plugin != null) { log.debug3("getting journal feature url for plugin: " + plugin.getClass().getName()); // get starting URL from a DefinablePlugin // add volume with type and spelling of existing element TypedEntryMap paramMap = getParamMap(plugin, tdbau); paramMap.setMapElement("volume", volumeName); paramMap.setMapElement("volume_str", volumeName); paramMap.setMapElement("volume_name", volumeName); paramMap.setMapElement("year", year); String issn = tdbau.getPrintIssn(); if (issn != null) { paramMap.setMapElement("issn", issn); } String eissn = tdbau.getEissn(); if (eissn != null) { paramMap.setMapElement("eissn", eissn); } if (!StringUtil.isNullString(year)) { try { paramMap.setMapElement("au_short_year", String.format("%02d", NumberUtil.parseInt(year)%100)); } catch (NumberFormatException ex) { log.info("Error parsing year '" + year + "' as an integer -- not setting au_short_year"); } } paramMap.setMapElement("issue", issue); paramMap.setMapElement("article", spage); paramMap.setMapElement("page", spage); paramMap.setMapElement("item", artnum); // for journals without page numbers // AU_FEATURE_KEY selects feature from a map of values // for the same feature (e.g. au_feature_urls/au_year) paramMap.setMapElement(AU_FEATURE_KEY, tdbau.getAttr(AU_FEATURE_KEY)); resolved = getJournalUrl(tdbau, plugin, paramMap); if (resolved.isResolved()) { if (resolved.resolvedTo == OpenUrlInfo.ResolvedTo.TITLE) { // create bibliographic item with only title properties resolved.resolvedBibliographicItem = new BibliographicItemImpl() .setPublisherName(tdbau.getPublisherName()) .setPublicationTitle(tdbau.getPublicationTitle()) .setProprietaryIds(tdbau.getProprietaryIds()) .setCoverageDepth(tdbau.getCoverageDepth()) .setPrintIssn(tdbau.getPrintIssn()) .setEissn(tdbau.getEissn()) .setIssnL(tdbau.getIssnL()); } else { resolved.resolvedBibliographicItem = tdbau; } log.debug3("Resolved journal url from plugin: " + resolved.resolvedUrl); } } else { log.debug3("No plugin found for key: " + pluginKey); } return resolved; } /** * Find the most specific journal feature URL that can be determined from * the supplied parameters. * @param tdbAu TdbAu describing AU to be accessed * @param plugin the plugin * @param paramMap param map containing properties and AU config params * from TdbAu, plus possibly <code>issn</code>, <code>eissn</code>, * <code>feature_key</code>, <code>volume</code>, * <code>volume_str</code>, <code>volume_name</code>, * <code>year</code>, <code>au_short_year</code>, <code>issue</code>, * <code>article</code>, <code>page</code>, <code>item</code> (article * number). * @return a feature URL */ public OpenUrlInfo getJournalUrl(TdbAu tdbAu, Plugin plugin, TypedEntryMap paramMap) { OpenUrlInfo resolved = getPluginUrl(tdbAu, plugin, auJournalFeatures, paramMap); return resolved; } public OpenUrlInfo getPluginUrl(Plugin plugin, FeatureEntry[] pluginEntries, TypedEntryMap paramMap) { return getPluginUrl(null, plugin, pluginEntries, paramMap); } /** * Get the URL for the specified key from the plugin. * @param plugin the plugin * @param pluginEntries array of FeatureEntry to try * @param paramMap parameters for feature printfs * @return OpenUrlInfo for the first FeatureEntry that evaluates without * error */ @Loggable(value = Loggable.TRACE, prepend = true) OpenUrlInfo getPluginUrl(TdbAu tdbAu, Plugin plugin, FeatureEntry[] pluginEntries, TypedEntryMap paramMap) { ArchivalUnit au = null; if (tdbAu != null) { String auid = tdbAu.getAuId(pluginMgr); au = pluginMgr.getAuFromId(auid); } ExternalizableMap map; // get printf pattern for pluginKey property try { Method method = plugin.getClass().getMethod("getDefinitionMap", (new Class[0])); Object obj = method.invoke(plugin); if (!(obj instanceof ExternalizableMap)) { return OPEN_URL_INFO_NONE; } map = (ExternalizableMap)obj; } catch (Exception ex) { log.error("getDefinitionMap", ex); return OPEN_URL_INFO_NONE; } String proxySpec = null; try { proxySpec = paramMap.getString(ConfigParamDescr.CRAWL_PROXY.getKey()); } catch (NoSuchElementException ex) { // no crawl_proxy param specified } for (FeatureEntry pluginEntry : pluginEntries) { // locate object value for plugin key path String pluginKey = pluginEntry.auFeatureKey; String[] pluginKeyPath = pluginKey.split("/"); Object obj = map.getMapElement(pluginKeyPath[0]); for (int i = 1; (i < pluginKeyPath.length); i++) { if (obj instanceof Map) { obj = ((Map<String,?>)obj).get(pluginKeyPath[i]); } else { // all path elements except last one must be a map; obj = null; break; } } if (obj instanceof Map) { // match TDB AU_FEATURE_KEY value to key in map String auFeatureKey = "*"; // default entry try { auFeatureKey = paramMap.getString(AU_FEATURE_KEY); } catch (NoSuchElementException ex) {} // entry may have multiple keys; '*' is the default entry Object val = null; for (Map.Entry<String,?> entry : ((Map<String,?>)obj).entrySet()) { String key = entry.getKey(); if ( key.equals(auFeatureKey) || key.startsWith(auFeatureKey + ";") || key.endsWith(";" + auFeatureKey) || (key.indexOf(";" + auFeatureKey + ";") >= 0)) { val = entry.getValue(); break; } } obj = val; pluginKey += "/" + auFeatureKey; } if (obj == null) { log.debug("unknown plugin key: " + pluginKey); continue; } Collection<String> printfStrings = null; if (obj instanceof String) { // get single pattern for start url printfStrings = Collections.singleton((String)obj); } else if (obj instanceof Collection) { printfStrings = (Collection<String>)obj; } else { log.debug( "unknown type for plugin key: " + pluginKey + ": " + obj.getClass().getName()); continue; } log.debug3( "Trying plugin key: " + pluginKey + " for plugin: " + plugin.getPluginId() + " with " + printfStrings.size() + " printf strings"); // set up converter for use with feature URL printf strings UrlListConverter converter = PrintfConverter.newUrlListConverter(plugin, paramMap); converter.setAllowUntypedArgs(true); for (String s : printfStrings) { String url = null; // terminal value in maps may be a string, printf string or the // name of a FeatureUrlHelperFactory FeatureUrlHelper helper = null; if (!s.startsWith("\"")) { try { FeatureUrlHelperFactory fact = plugin.newAuxClass(s, FeatureUrlHelperFactory.class); if (fact != null) { helper = fact.createFeatureUrlHelper(plugin); } } catch (Exception e) { log.error("Can't create FeatureUrlHelper for " + plugin.getPluginName(), e); } } if (helper != null) { try { List<String> urls = helper.getFeatureUrls(au, pluginEntry.resolvedTo, paramMap); if ((urls != null) && !urls.isEmpty()) { // if multiple urls match, the first one will do url = urls.get(0); } } catch (PluginException | RuntimeException | IOException e) { log.error("Error in FeatureUrlHelper(" + plugin + ", " + paramMap, e); } } else { s = StringEscapeUtils.unescapeHtml4(s); try { List<String> urls = converter.getUrlList(s); if ((urls != null) && !urls.isEmpty()) { // if multiple urls match, the first one will do url = urls.get(0); } } catch (Throwable ex) { log.debug("invalid conversion for " + s, ex); continue; } } // validate URL: either it's cached, or it can be reached if (!StringUtil.isNullString(url)) { log.debug3("Resolving from url: " + url); url = resolveUrl(url, proxySpec); if (url != null) { return OpenUrlInfo.newInstance(url, proxySpec, pluginEntry.resolvedTo); } } } } return OPEN_URL_INFO_NONE; } /** * Return the book URL from TdbTitle and edition. * * @param tdbAus a collection of TdbAus that match an ISBN * @param date the publication date * @param volume the volume * @param edition the edition * @param chapter the chapter * @param spage the start page * @return the book URL */ @Loggable(value = Loggable.TRACE, prepend = true) private OpenUrlInfo resolveBookFromTdbAus( Collection<TdbAu> tdbAus, String date, String volume, String edition, String chapter, String spage) { // get the year from the date String year = null; if (date != null) { try { year = Integer.toString(PublicationDate.parse(date).getYear()); } catch (ParseException ex) {} } // list of AUs that match volume and year specified ArrayList<TdbAu> foundTdbAuList = new ArrayList<TdbAu>(); // list of AUs that do not match volume, edition, and year specified ArrayList<TdbAu> notFoundTdbAuList = new ArrayList<TdbAu>(); for (TdbAu tdbAu : tdbAus) { // if none of year, volume, or edition specified, pick any TdbAu if ((volume == null) && (year == null) && (edition == null)) { notFoundTdbAuList.add(tdbAu); continue; } // if volume specified, see if this TdbAu matches if (volume != null) { if (!tdbAu.includesVolume(volume)) { notFoundTdbAuList.add(tdbAu); continue; } } // if year specified, see if this TdbAu matches if (year != null) { if (!tdbAu.includesYear(year)) { notFoundTdbAuList.add(tdbAu); continue; } } // get the plugin id for the TdbAu that matches the specified edition if (edition != null) { String auEdition = tdbAu.getEdition(); if ((auEdition != null) && !edition.equals(auEdition)) { notFoundTdbAuList.add(tdbAu); continue; } } foundTdbAuList.add(tdbAu); } OpenUrlInfo resolved = null; // look for URL that is cached from list of matching AUs for (TdbAu tdbau : foundTdbAuList) { String aYear = year; if (aYear == null) { aYear = tdbau.getStartYear(); } String aVolume = volume; if (aVolume == null) { aVolume = tdbau.getStartVolume(); } String anEdition = edition; if (edition == null) { anEdition = tdbau.getEdition(); } OpenUrlInfo aResolved = getBookUrl( tdbau, year, aVolume, anEdition, chapter, spage); if (aResolved.resolvedUrl != null) { // found the URL if in cache if (pluginMgr.findCachedUrl(aResolved.resolvedUrl) != null) { if (resolved == null) { resolved = aResolved; } else { resolved.add(aResolved); } } // not a viable URL if the AU is down // note: even though getBookUrl() checks that page exists, // we can't rely on it being usable if TdbAu is down else if (!tdbau.isDown()) { if (resolved == null) { resolved = aResolved; } else { resolved.add(aResolved); } } else { log.debug2( "discarding URL " + aResolved.resolvedUrl + " because tdbau is down: " + tdbau.getName()); } } } if (resolved != null) { return resolved; } // use tdbau that is not down from notFoundTdbAuList to find the // title or publisher URL, since that is all we can return at this point for (TdbAu tdbau : notFoundTdbAuList) { if (!tdbau.isDown()) { OpenUrlInfo aResolved = getBookUrl(tdbau, tdbau.getStartYear(), tdbau.getStartVolume(), tdbau.getStartIssue(), null, null); if (aResolved.isResolved()) { if (resolved == null) { resolved = aResolved; } else { resolved.add(aResolved); } } } else { log.debug2("discarding URL because tdbau is down: " + tdbau.getName()); } } if (resolved != null) { return resolved; } // pick any AU to use for resolving the title as a last resort if (!notFoundTdbAuList.isEmpty()) { OpenUrlInfo aResolved = OpenUrlInfo.newInstance(null, null, OpenUrlInfo.ResolvedTo.VOLUME); aResolved.resolvedBibliographicItem = notFoundTdbAuList.get(0); return aResolved; } return OPEN_URL_INFO_NONE; } /** * Return the article URL from an ISBN, edition, spage, and author. * The first author will only be used when the starting page is not given. * "Volume" is used to hold edition information in the database manager * schema for books. First author can be used in place of start page. * * @param isbn the isbn * @param pub the publisher * @param date the date * @param volume the volume * @param edition the edition * @param chapter the chapter * @param spage the start page * @param author the first author * @param atitle the chapter title * @return the article URL */ public OpenUrlInfo resolveFromIsbn( String isbn, String pub, String date, String volume, String edition, String chapter, String spage, String author, String atitle) { // only go to database manager if requesting individual article/chapter try { // resolve from database manager DbManager dbMgr = daemon.getDbManager(); OpenUrlInfo aResolved = resolveFromIsbn( dbMgr, isbn, pub, date, volume, edition, chapter, spage, author, atitle); if (aResolved.isResolved()) { return aResolved; } } catch (IllegalArgumentException ex) { } // resolve from TDB Tdb tdb = ConfigManager.getCurrentConfig().getTdb(); // get list of TdbTitles for issn Collection<TdbAu> tdbAus; if (tdb == null) { tdbAus = Collections.<TdbAu>emptyList(); } else if (pub != null) { TdbPublisher tdbPub = tdb.getTdbPublisher(pub); tdbAus = (tdbPub == null) ? Collections.<TdbAu>emptyList() : tdbPub.getTdbAusByIsbn(isbn); } else { tdbAus = tdb.getTdbAusByIsbn(isbn); } OpenUrlInfo resolved = resolveBookFromTdbAus(tdbAus, date, volume, edition, chapter, spage); return resolved; } /** * Return the article URL from an ISBN, edition, start page, author, and * article title using the metadata database. * <p> * The algorithm matches the ISBN and optionally the edition, and either * the start page, author, or article title. The reason for matching on any * of the three is that typos in author and article title are always * possible so we want to be more forgiving in matching an article. * <p> * If none of the three are specified, the URL for the book table of contents * is returned. * * @param dbMgr the database manager * @param isbn the isbn * @param pub the publisher * @param String date the date * @param String volumeName the volumeName * @param edition the edition * @param chapter the chapter * @param spage the start page * @param author the first author * @param atitle the chapter title * @return the url */ @Loggable(value = Loggable.TRACE, prepend = true) private OpenUrlInfo resolveFromIsbn( DbManager dbMgr, String isbn, String pub, String date, String volume, String edition, String chapter, String spage, String author, String atitle) { final String DEBUG_HEADER = "resolveFromIsbn(): "; OpenUrlInfo resolved = null; Connection conn = null; // error if input ISBN is not a ISBN-10 or ISBN-13 String strippedIsbn10 = MetadataUtil.toUnpunctuatedIsbn10(isbn); String strippedIsbn13 = MetadataUtil.toUnpunctuatedIsbn13(isbn); if ((strippedIsbn10 == null) && (strippedIsbn13 == null)) { return OPEN_URL_INFO_NONE; } boolean hasBookSpec = (date != null) || (volume != null) || (edition != null); boolean hasArticleSpec = (chapter != null) || (spage != null) || (author != null) || (atitle != null); try { conn = dbMgr.getConnection(); StringBuilder select = new StringBuilder("select distinct "); StringBuilder from = new StringBuilder(" from "); StringBuilder where = new StringBuilder(" where "); ArrayList<String> args = new ArrayList<String>(); // return all related values for debugging purposes select.append("u." + URL_COLUMN); select.append(",pb." + PUBLISHER_NAME_COLUMN); select.append(",n1." + NAME_COLUMN + " as book_title"); select.append(",i." + ISBN_COLUMN); select.append(",bi." + VOLUME_COLUMN); select.append(",bi." + ISSUE_COLUMN + " as edition"); select.append(",bi." + START_PAGE_COLUMN); select.append(",bi." + END_PAGE_COLUMN); select.append(",bi." + ITEM_NO_COLUMN + " as chapt_no"); select.append(",n2." + NAME_COLUMN + " as chapt_title"); select.append(",pv2." + PROVIDER_NAME_COLUMN); from.append(MD_ITEM_TABLE + " mi1"); // publication md_item from.append("," + MD_ITEM_TABLE + " mi2"); // article md_item from.append("," + ISBN_TABLE + " i"); from.append("," + PUBLICATION_TABLE + " pu"); from.append("," + PUBLISHER_TABLE + " pb"); from.append("," + MD_ITEM_NAME_TABLE + " n1"); // publication name from.append("," + MD_ITEM_NAME_TABLE + " n2"); // article name from.append("," + URL_TABLE + " u"); from.append("," + BIB_ITEM_TABLE + " bi"); from.append("," + PROVIDER_TABLE + " pv2"); from.append("," + AU_MD_TABLE + " am2"); where.append("mi2." + PARENT_SEQ_COLUMN + "="); where.append("mi1." + MD_ITEM_SEQ_COLUMN); where.append(" and i." + MD_ITEM_SEQ_COLUMN + "="); where.append("mi1." + MD_ITEM_SEQ_COLUMN); where.append(" and i." + ISBN_COLUMN); if ((strippedIsbn10 != null) && (strippedIsbn13 != null)) { // check both ISBN-10 and ISBN-13 forms where.append(" in (?,?)"); args.add(strippedIsbn10); args.add(strippedIsbn13); } else { // can't convert to ISBN-10 or ISBN-13 because input isbn // is not well formed, so use whichever one is available where.append(" = ?"); args.add((strippedIsbn13 != null) ? strippedIsbn13 : strippedIsbn10); } where.append(" and pu." + MD_ITEM_SEQ_COLUMN + "="); where.append("mi1." + MD_ITEM_SEQ_COLUMN); where.append(" and pb." + PUBLISHER_SEQ_COLUMN + "="); where.append("pu." + PUBLISHER_SEQ_COLUMN); if (pub != null) { // match publisher if specified where.append(" and pb." + PUBLISHER_NAME_COLUMN + "= ?"); args.add(pub); } where.append(" and n1." + MD_ITEM_SEQ_COLUMN + "="); where.append("mi1." + MD_ITEM_SEQ_COLUMN); where.append(" and n1." + NAME_TYPE_COLUMN + "='primary'"); where.append(" and u." + MD_ITEM_SEQ_COLUMN + "="); where.append("mi2." + MD_ITEM_SEQ_COLUMN); where.append(" and u." + FEATURE_COLUMN + "='Access'"); where.append(" and bi." + MD_ITEM_SEQ_COLUMN + "="); where.append("mi2." + MD_ITEM_SEQ_COLUMN); where.append(" and n2." + MD_ITEM_SEQ_COLUMN + "="); where.append("mi2." + MD_ITEM_SEQ_COLUMN); where.append(" and n2." + NAME_TYPE_COLUMN + "='primary'"); where.append(" and mi2." + AU_MD_SEQ_COLUMN + "="); where.append("am2." + AU_MD_SEQ_COLUMN); where.append(" and am2." + PROVIDER_SEQ_COLUMN + "="); where.append("pv2." + PROVIDER_SEQ_COLUMN); if (hasBookSpec) { // can specify an issue by a combination of date, volume and edition; // how these combine varies, so do the most liberal match possible // and filter based on multiple results if (date != null) { // enables query "2009" to match "2009-05-10" in database where.append(" and mi2." + DATE_COLUMN); where.append(" like ? escape '\\'"); args.add(date.replace("\\","\\\\").replace("%","\\%") + "%"); } if (volume != null) { where.append(" and bi." + VOLUME_COLUMN + " = ?"); args.add(volume); } if (edition != null) { where.append(" and bi." + ISSUE_COLUMN + " = ?"); args.add(edition); } } // handle start page, author, and article title as // equivalent ways to specify an article within an issue if (hasArticleSpec) { // accept any of the three where.append(" and ( "); if (spage != null) { where.append("bi." + START_PAGE_COLUMN + " = ?"); args.add(spage); } if (chapter != null) { if (spage != null) { where.append(" or "); } where.append("bi." + ITEM_NO_COLUMN + " = ?"); args.add(chapter); } if (atitle != null) { if ((spage != null) || (chapter != null)) { where.append(" or "); } where.append("upper(n2." + NAME_COLUMN); where.append(") like ? escape '\\'"); args.add(atitle.toUpperCase().replace("%","\\%") + "%"); } if (author != null) { if ((spage != null) || (chapter != null) || (atitle != null)) { where.append(" or "); } from.append("," + AUTHOR_TABLE + " au"); // add the author query to the query addAuthorQuery(author, where, args); } where.append(")"); } String qstr = select.toString() + from.toString() + where.toString(); int maxPublishersPerArticle = getMaxPublishersPerArticle(); String[][] results = new String[maxPublishersPerArticle+1][11]; int count = resolveFromQuery(conn, qstr, args, results); log.debug3(DEBUG_HEADER + "count = " + count); if (count <= maxPublishersPerArticle) { // ensure at most one result per publisher+provider in case // more than one publisher+provider publishes the same book Set<String> pubs = new HashSet<String>(); for (int i = 0; i < count; i++) { // combine publisher and provider columns to determine uniqueness if (!pubs.add(results[i][1] + results[i][10])) { return OPEN_URL_INFO_NONE; } OpenUrlInfo info = OpenUrlInfo.newInstance(results[i][0], null, OpenUrlInfo.ResolvedTo.CHAPTER); if (resolved == null) { resolved = info; } else { resolved.add(info); } } } } catch (DbException dbe) { log.error("Getting ISBN:" + isbn, dbe); } finally { DbManager.safeRollbackAndClose(conn); } return (resolved == null) ? OPEN_URL_INFO_NONE : resolved; } /** * Add author query to the query buffer and argument list. * @param author the author * @param where the query buffer * @param args the argument list */ private void addAuthorQuery(String author, StringBuilder where, List<String> args) { where.append("mi2." + MD_ITEM_SEQ_COLUMN + " = "); where.append("au." + MD_ITEM_SEQ_COLUMN + " and ("); String authorUC = author.toUpperCase(); // match single author where.append("upper(au."); where.append(AUTHOR_NAME_COLUMN); where.append(") = ?"); args.add(authorUC); // escape escape character and then wildcard characters String authorEsc = authorUC.replace("\\", "\\\\").replace("%","\\%"); // match last name of author // (last, first name separated by ',') where.append(" or upper(au."); where.append(AUTHOR_NAME_COLUMN); where.append(") like ? escape '\\'"); args.add(authorEsc+",%"); // match last name of author // (first last name separated by ' ') where.append(" or upper(au."); where.append(AUTHOR_NAME_COLUMN); where.append(") like ? escape '\\'"); args.add("% " + authorEsc); where.append(")"); } }
bsd-3-clause
edina/lockss-daemon
test/src/org/lockss/test/MockURLConnection.java
6612
/* * $Id$ */ /* Copyright (c) 2000-2003 Board of Trustees of Leland Stanford Jr. University, all rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL STANFORD UNIVERSITY BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Except as contained in this notice, the name of Stanford University shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from Stanford University. */ package org.lockss.test; import java.util.List; import java.net.*; import java.security.Permission; import java.io.*; public class MockURLConnection extends URLConnection { List headerFieldKeys = null; List headerFields = null; public MockURLConnection(URL url){ super(url); } public static synchronized FileNameMap getFileNameMap() { throw new UnsupportedOperationException("Not Implemented"); } public static void setFileNameMap(FileNameMap map) { throw new UnsupportedOperationException("Not Implemented"); } public void connect() throws IOException{ throw new UnsupportedOperationException("Not Implemented"); } public URL getURL() { throw new UnsupportedOperationException("Not Implemented"); } public int getContentLength() { throw new UnsupportedOperationException("Not Implemented"); } public String getContentType() { throw new UnsupportedOperationException("Not Implemented"); } public String getContentEncoding() { throw new UnsupportedOperationException("Not Implemented"); } public long getExpiration() { throw new UnsupportedOperationException("Not Implemented"); } public long getDate() { throw new UnsupportedOperationException("Not Implemented"); } public long getLastModified() { throw new UnsupportedOperationException("Not Implemented"); } public String getHeaderField(String name) { throw new UnsupportedOperationException("Not Implemented"); } public int getHeaderFieldInt(String name, int Default) { throw new UnsupportedOperationException("Not Implemented"); } public long getHeaderFieldDate(String name, long Default) { throw new UnsupportedOperationException("Not Implemented"); } public String getHeaderFieldKey(int n) { if (headerFieldKeys == null || headerFieldKeys.size() <= n) { return null; } return (String)headerFieldKeys.get(n); } public String getHeaderField(int n) { if (headerFields == null || headerFields.size() <= n) { return null; } return (String)headerFields.get(n); } public void setHeaderFieldKeys(List keys) { this.headerFieldKeys = keys; } public void setHeaderFields(List fields) { this.headerFields = fields; } public Object getContent() throws IOException { throw new UnsupportedOperationException("Not Implemented"); } public Object getContent(Class[] classes) throws IOException { throw new UnsupportedOperationException("Not Implemented"); } public Permission getPermission() throws IOException { throw new UnsupportedOperationException("Not Implemented"); } public InputStream getInputStream() throws IOException { throw new UnknownServiceException("protocol doesn't support input"); } public OutputStream getOutputStream() throws IOException { throw new UnknownServiceException("protocol doesn't support output"); } public String toString() { throw new UnsupportedOperationException("Not Implemented"); } public void setDoInput(boolean doinput) { throw new UnsupportedOperationException("Not Implemented"); } public boolean getDoInput() { throw new UnsupportedOperationException("Not Implemented"); } public void setDoOutput(boolean dooutput) { throw new UnsupportedOperationException("Not Implemented"); } public boolean getDoOutput() { throw new UnsupportedOperationException("Not Implemented"); } public void setAllowUserInteraction(boolean allowuserinteraction) { throw new UnsupportedOperationException("Not Implemented"); } public boolean getAllowUserInteraction() { throw new UnsupportedOperationException("Not Implemented"); } public static void setDefaultAllowUserInteraction(boolean defaultAUI) { throw new UnsupportedOperationException("Not Implemented"); } public static boolean getDefaultAllowUserInteraction() { throw new UnsupportedOperationException("Not Implemented"); } public void setUseCaches(boolean usecaches) { throw new UnsupportedOperationException("Not Implemented"); } public boolean getUseCaches() { throw new UnsupportedOperationException("Not Implemented"); } public void setIfModifiedSince(long ifmodifiedsince) { throw new UnsupportedOperationException("Not Implemented"); } public long getIfModifiedSince() { throw new UnsupportedOperationException("Not Implemented"); } public boolean getDefaultUseCaches() { throw new UnsupportedOperationException("Not Implemented"); } public void setDefaultUseCaches(boolean defaultusecaches) { throw new UnsupportedOperationException("Not Implemented"); } public void setRequestProperty(String key, String value) { throw new UnsupportedOperationException("Not Implemented"); } public String getRequestProperty(String key) { throw new UnsupportedOperationException("Not Implemented"); } public static synchronized void setContentHandlerFactory(ContentHandlerFactory fac) { throw new UnsupportedOperationException("Not Implemented"); } static public String guessContentTypeFromStream(InputStream is) throws IOException { throw new UnsupportedOperationException("Not Implemented"); } }
bsd-3-clause
Clashsoft/Dyvil
compiler/src/main/java/dyvilx/tools/compiler/ast/generic/GenericData.java
4485
package dyvilx.tools.compiler.ast.generic; import dyvil.annotation.internal.NonNull; import dyvilx.tools.compiler.ast.context.IContext; import dyvilx.tools.compiler.ast.header.IClassCompilableList; import dyvilx.tools.compiler.ast.header.ICompilableList; import dyvilx.tools.compiler.ast.type.IType; import dyvilx.tools.compiler.ast.type.IType.TypePosition; import dyvilx.tools.compiler.ast.type.TypeList; import dyvilx.tools.compiler.ast.type.builtin.Types; import dyvilx.tools.compiler.phase.Resolvable; import dyvilx.tools.parsing.marker.MarkerList; public final class GenericData implements Resolvable, ITypeContext { protected @NonNull ITypeParametricMember member; protected @NonNull TypeList generics; protected int lockedCount; protected ITypeContext fallbackTypeContext; public GenericData() { this.generics = new TypeList(); } public GenericData(ITypeParametricMember member) { this(member, member.typeArity()); } public GenericData(ITypeParametricMember member, int capacity) { this.member = member; this.generics = new TypeList(capacity); } public GenericData(ITypeParametricMember member, IType... generics) { this.member = member; this.generics = new TypeList(generics); } public ITypeParametricMember getMember() { return this.member; } public void setMember(ITypeParametricMember member) { this.member = member; } public ITypeContext getFallbackTypeContext() { return this.fallbackTypeContext; } public void setFallbackTypeContext(ITypeContext fallbackTypeContext) { this.fallbackTypeContext = fallbackTypeContext; } public TypeList getTypes() { return this.generics; } public void lockAvailable() { this.lock(this.generics.size()); } public void lock(int lockedCount) { if (lockedCount > this.lockedCount) { this.lockedCount = lockedCount; } } private boolean isMethodTypeVariable(ITypeParameter typeVar) { if (this.member == null) { return false; } if (typeVar.getGeneric() == this.member) { return true; } final int index = typeVar.getIndex(); return index >= 0 && index < this.member.typeArity() && this.member.getTypeParameters().get(index) == typeVar; } @Override public IType resolveType(ITypeParameter typeParameter) { if (this.isMethodTypeVariable(typeParameter)) { final int index = typeParameter.getIndex(); if (index >= this.lockedCount || index >= this.generics.size()) { return null; } return this.generics.get(index); } if (this.fallbackTypeContext != null && typeParameter.getGeneric() == this.member.getEnclosingClass()) { return Types.resolveTypeSafely(this.fallbackTypeContext, typeParameter); } return null; } @Override public boolean isReadonly() { return false; } @Override public boolean addMapping(ITypeParameter typeParameter, IType type) { if (!this.isMethodTypeVariable(typeParameter)) { return false; } final int index = typeParameter.getIndex(); while (index >= this.generics.size()) { this.generics.add(null); } final IType current = this.generics.get(index); if (current == null) { this.generics.set(index, type); return true; } if (index < this.lockedCount) { return false; } this.generics.set(index, Types.combine(current, type)); return true; } @Override public void resolveTypes(MarkerList markers, IContext context) { this.generics.resolveTypes(markers, context); this.lockedCount = this.generics.size(); } @Override public void resolve(MarkerList markers, IContext context) { this.generics.resolve(markers, context); } @Override public void checkTypes(MarkerList markers, IContext context) { this.generics.checkTypes(markers, context, TypePosition.GENERIC_ARGUMENT | TypePosition.REIFY_FLAG); } @Override public void check(MarkerList markers, IContext context) { this.generics.check(markers, context); } @Override public void foldConstants() { this.generics.foldConstants(); } @Override public void cleanup(ICompilableList compilableList, IClassCompilableList classCompilableList) { this.generics.cleanup(compilableList, classCompilableList); } @Override public String toString() { final StringBuilder builder = new StringBuilder(); this.toString("", builder); return builder.toString(); } public void toString(@NonNull String indent, @NonNull StringBuilder buffer) { if (this.generics.size() > 0) { this.generics.toString(indent, buffer); } } }
bsd-3-clause
lockss/lockss-daemon
src/org/lockss/ws/status/client/QueryTdbPublishersClient.java
2558
/* * $Id$ */ /* Copyright (c) 2014 Board of Trustees of Leland Stanford Jr. University, all rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL STANFORD UNIVERSITY BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Except as contained in this notice, the name of Stanford University shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from Stanford University. */ package org.lockss.ws.status.client; import java.util.List; import org.lockss.ws.entities.TdbPublisherWsResult; /** * A client for the DaemonStatusService.queryTdbPublishers() web service * operation. */ public class QueryTdbPublishersClient extends QueryBaseClient { /** * The main method. * * @param args * A String[] with the command line arguments. * @throws Exception */ public static void main(String args[]) throws Exception { QueryTdbPublishersClient thisClient = new QueryTdbPublishersClient(); // Get the query. String query = thisClient.getQueryFromCommandLine(args); System.out.println("query = " + query); // Call the service and get the results of the query. List<TdbPublisherWsResult> tdbPublishers = thisClient.getProxy().queryTdbPublishers(query); if (tdbPublishers != null) { System.out.println("tdbPublishers.size() = " + tdbPublishers.size()); for (TdbPublisherWsResult tdbPublisherResult : tdbPublishers) { System.out.println("tdbPublisherResult = " + tdbPublisherResult); } } else { System.out.println("tdbPublishers = " + tdbPublishers); } } }
bsd-3-clause
ripple/ripple-lib-java
ripple-bouncycastle/src/main/java/org/ripple/bouncycastle/crypto/tls/TlsPeer.java
1790
package org.ripple.bouncycastle.crypto.tls; import java.io.IOException; public interface TlsPeer { /** * draft-mathewson-no-gmtunixtime-00 2. "If existing users of a TLS implementation may rely on * gmt_unix_time containing the current time, we recommend that implementors MAY provide the * ability to set gmt_unix_time as an option only, off by default." * * @return <code>true</code> if the current time should be used in the gmt_unix_time field of * Random, or <code>false</code> if gmt_unix_time should contain a cryptographically * random value. */ boolean shouldUseGMTUnixTime(); void notifySecureRenegotiation(boolean secureNegotiation) throws IOException; TlsCompression getCompression() throws IOException; TlsCipher getCipher() throws IOException; /** * This method will be called when an alert is raised by the protocol. * * @param alertLevel {@link AlertLevel} * @param alertDescription {@link AlertDescription} * @param message A human-readable message explaining what caused this alert. May be null. * @param cause The {@link Throwable} that caused this alert to be raised. May be null. */ void notifyAlertRaised(short alertLevel, short alertDescription, String message, Throwable cause); /** * This method will be called when an alert is received from the remote peer. * * @param alertLevel {@link AlertLevel} * @param alertDescription {@link AlertDescription} */ void notifyAlertReceived(short alertLevel, short alertDescription); /** * Notifies the peer that the handshake has been successfully completed. */ void notifyHandshakeComplete() throws IOException; }
isc
devs4v/devs4v-information-retrieval15
project/lucene/pylucene-4.9.0-0/java/org/apache/pylucene/search/spans/PythonSpans.java
1706
/* ==================================================================== * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== */ package org.apache.pylucene.search.spans; import java.io.IOException; import java.util.Collection; import org.apache.lucene.search.spans.Spans; public class PythonSpans extends Spans { private long pythonObject; public PythonSpans() { } public void pythonExtension(long pythonObject) { this.pythonObject = pythonObject; } public long pythonExtension() { return this.pythonObject; } public void finalize() throws Throwable { pythonDecRef(); } public native void pythonDecRef(); public native boolean next() throws IOException; public native boolean skipTo(int target) throws IOException; public native int doc(); public native int start(); public native int end(); public native Collection<byte[]> getPayload() throws IOException; public native boolean isPayloadAvailable() throws IOException; public native long cost(); }
mit
osiam/osiam
src/main/java/org/osiam/resources/scim/SCIMSearchResult.java
3556
/** * The MIT License (MIT) * * Copyright (C) 2013-2016 tarent solutions GmbH * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.osiam.resources.scim; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.*; /** * A class that holds all information from a search request * <p> * For more detailed information please look at the <a * href="http://tools.ietf.org/html/draft-ietf-scim-core-schema-02">SCIM core schema 2.0</a> * </p> * * @param <T> {@link User} or {@link Group} */ @JsonInclude(JsonInclude.Include.NON_EMPTY) public class SCIMSearchResult<T> { public static final String SCHEMA = "urn:ietf:params:scim:api:messages:2.0:ListResponse"; public static final int MAX_RESULTS = 100; private long totalResults; private long itemsPerPage; private long startIndex; private Set<String> schemas = new HashSet<>(Collections.singletonList(SCHEMA)); private List<T> resources = new ArrayList<>(); /** * Default constructor for Jackson */ SCIMSearchResult() { } public SCIMSearchResult(List<T> resources, long totalResults, long itemsPerPage, long startIndex) { this.resources = resources; this.totalResults = totalResults; this.itemsPerPage = itemsPerPage; this.startIndex = startIndex; } /** * gets a list of found {@link User}s or {@link Group}s * * @return a list of found resources */ @JsonProperty("Resources") public List<T> getResources() { return resources; } /** * The total number of results returned by the list or query operation. This may not be equal to the number of * elements in the Resources attribute of the list response if pagination is requested. * * @return the total result */ public long getTotalResults() { return totalResults; } /** * Gets the schemas of the search result * * @return the search result schemas */ public Set<String> getSchemas() { return schemas; } /** * The number of Resources returned in a list response page. * * @return items per page */ public long getItemsPerPage() { return itemsPerPage; } /** * The 1-based index of the first result in the current set of list results. * * @return the start index of the actual page */ public long getStartIndex() { return startIndex; } }
mit
SWE574-Groupago/heritago
Heritandroid/app/src/main/java/com/heritago/heritandroid/model/Heritage.java
3092
package com.heritago.heritandroid.model; import com.heritago.heritandroid.api.ApiClient; import java.util.ArrayList; import java.util.List; /** * Created by onurtokoglu on 02/04/2017. */ public class Heritage { private final String defaultImageUrl = "https://www.proyas.org/wp-content/themes/404/images/placeholder.jpg"; public String id; private String title; private String description; public String createdAt; private List<BasicInformation> basicInformation = new ArrayList<>(); public List<Origin> origin = new ArrayList<>(); public List<String> tags = new ArrayList<>(); public int annotationCount; private Owner owner; public List<Multimedia> multimedia; public Heritage(String id, String title, String description, Owner owner) { this.id = id; this.title = title; this.description = description; this.owner = owner; } public String getThumbnailImageUrl(){ for (Multimedia m: multimedia){ if (m.getType().equals(Multimedia.Type.image)){ return ApiClient.imageBaseUrl + m.url; } } return defaultImageUrl; } public String getOwnerName(){ try { return owner.name; }catch (Exception e){ return ""; } } public String getTitle() { return (title != null)? title : "" ; } public String getDescription() { return (title != null)? description : ""; } public List<BasicInformation> getBasicInformation() { return (basicInformation != null)? basicInformation : new ArrayList<BasicInformation>(); } public static class Owner { public String id; public String name; public Owner(String id, String name) { this.id = id; this.name = name; } } public static class Origin { public String name; public Origin(String name) { this.name = name; } } public static class BasicInformation { public String name; public String value; public BasicInformation(String name, String value) { this.name = name; this.value = value; } } public static class Multimedia { public String type; public String id; private String url; public String createdAt; public Selector selector; public Multimedia(Type t){ this.type = t.name(); } public Type getType(){ for (Type t: Type.values()){ if (this.type.equals(t.name())){ return t; } } return Type.unknown; } public String getUrl(){ if (url == null) return null; return ApiClient.imageBaseUrl + url; } public class Selector { public String type; public Object value; } public enum Type { image, video, audio, location, unknown } } }
mit
IDPF/epubcheck
src/main/java/org/idpf/epubcheck/util/css/CssReader.java
8911
/* * Copyright (c) 2012 International Digital Publishing Forum * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ package org.idpf.epubcheck.util.css; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; import java.io.BufferedReader; import java.io.IOException; import java.io.Reader; import java.util.List; import com.google.common.base.CharMatcher; import com.google.common.base.MoreObjects; import com.google.common.collect.Lists; import com.google.common.primitives.Ints; /** * A wrapper around java.io.Reader with a pushback buffer, offset and * line+column tracking. This is used by CssScanner. * * @author mgylling */ final class CssReader { static final int DEFAULT_PUSHBACK_BUFFER_SIZE = 8096; private final int[] buf; private int pos; private final Reader in; private int prevLine = 1; /** * The systemID of the resource being read. If the resource being read * is virtual the value is set to CssLocaton.NO_SID */ final String systemID; /** * The char that this reader is currently positioned at, or -1 if EOF is * reached. */ int curChar = 0; /** * The previous char, or 0 if curChar is the first character in the resource * being read. */ int prevChar = 0; /** * The offset (in characters) of prevChar from the start of the resource * being read. */ int offset = 0; /** * The current line in the resource being read */ int line = 1; /** * The current column in the resource being read */ int col = 1; CssReader(Reader reader, String systemID, int pushbackSize) { this.in = checkNotNull(reader) instanceof BufferedReader ? reader : new BufferedReader(reader); this.systemID = checkNotNull(systemID); checkArgument(pushbackSize >= 1); this.pos = pushbackSize; this.buf = new int[pushbackSize]; } /** * Returns the next character in the stream and advances the readers * position. If there are no more characters, -1 is returned the first time * this method is invoked in that state; multiple invocations at EOF will * yield an IllegalStateException. */ int next() throws IOException { prevChar = curChar; checkState(prevChar > -1); if (pos < buf.length) { curChar = buf[pos++]; } else { curChar = in.read(); } offset++; /* * Handle line and col * lf=\n, cr=\r */ if (curChar == '\r' || curChar == '\n') { if (curChar == '\n' && prevChar == '\r') { //second char in a windows CR+LF } else { prevLine = line; line++; } } else if (prevLine < line) { col = 1; prevLine = line; } else { if (prevChar != 0) { col++; } } return curChar; } /** * Returns the next character in the stream without advancing the readers * position. If there are no more characters, -1 is returned. */ int peek() throws IOException { Mark m = mark(); int ch = next(); unread(ch, m); return ch; } /** * Returns the the next n characters in the stream without advancing the * readers position. * * @param n the number of characters to read * @return An array with guaranteed length n, with -1 being the value for * all elements at and after EOF. * @throws IOException */ int[] peek(int n) throws IOException { int[] buf = new int[n]; Mark m = mark(); boolean seenEOF = false; for (int i = 0; i < buf.length; i++) { if (!seenEOF) { buf[i] = next(); } else { buf[i] = -1; } if (buf[i] == -1) { seenEOF = true; } } if (!seenEOF) { unread(buf, m); } else { List<Integer> ints = Lists.newArrayList(); for (int aBuf : buf) { ints.add(aBuf); if (aBuf == -1) { break; } } unread(ints, m); } return buf; } /** * Peek and return the character at position n from current position, or -1 * if EOF is reached before or at that position. */ int at(int n) throws IOException { Mark mark = mark(); List<Integer> cbuf = Lists.newArrayList(); for (int i = 0; i < n; i++) { cbuf.add(next()); if (curChar == -1) { break; } } unread(cbuf, mark); return cbuf.get(cbuf.size() - 1); } /** * Reads forward and returns the the next n characters in the stream. Escapes * are returned verbatim. At return, the reader is at positioned such that * next() will return n+1 or EOF (-1). * * @param n the number of characters to read * @return An array with guaranteed length n, with -1 being the value for * all elements at and after EOF. * @throws IOException */ int[] collect(int n) throws IOException { int[] buf = new int[n]; boolean seenEOF = false; for (int i = 0; i < buf.length; i++) { if (seenEOF) { buf[i] = -1; } else { buf[i] = next(); if (curChar == -1) { seenEOF = true; } } } return buf; } /** * Read forward until the next non-escaped character matches the given * CharMatcher or is EOF. * * @throws IOException */ CssReader forward(CharMatcher matcher) throws IOException { while (true) { Mark mark = mark(); next(); //TODO escape awareness if (curChar == -1 || (matcher.matches((char) curChar) && prevChar != '\\')) { unread(curChar, mark); break; } } return this; } /** * Read forward n characters, or until the next character is EOF. * * @throws IOException */ CssReader forward(int n) throws IOException { for (int i = 0; i < n; i++) { //TODO escape awareness Mark mark = mark(); next(); if (curChar == -1) { unread(curChar, mark); break; } } return this; } void unread(final int ch, final Mark mark) { checkState(pos > 0); buf[--pos] = ch; reset(mark); } void unread(final int cbuf[], final Mark mark) throws IOException { unread(cbuf, 0, cbuf.length, mark); } void unread(final List<Integer> cbuf, final Mark mark) throws IOException { unread(Ints.toArray(cbuf), mark); } void unread(final int cbuf[], final int off, final int len, final Mark mark) { checkArgument(len < pos); pos -= len; System.arraycopy(cbuf, off, buf, pos, len); reset(mark); } Mark mark() { return new Mark(curChar, prevChar, line, col, prevLine, offset); } private CssReader reset(final Mark mark) { this.curChar = mark.mCur; this.prevChar = mark.mPrev; this.line = mark.mLine; this.col = mark.mCol; this.prevLine = mark.mPrevLine; this.offset = mark.mOffset; return this; } final class Mark { final int mLine; final int mCol; final int mPrev; final int mCur; final int mPrevLine; final int mOffset; private Mark(final int curChar, final int prevChar, final int line, final int col, final int prevLine, final int offset) { this.mCur = curChar; this.mPrev = prevChar; this.mLine = line; this.mCol = col; this.mPrevLine = prevLine; this.mOffset = offset; } } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("curChar", (char) curChar) .add("prevChar", (char) prevChar) .toString(); } }
mit
xupyprmv/takes
src/main/java/org/takes/rs/xe/XeWrap.java
1862
/** * The MIT License (MIT) * * Copyright (c) 2014-2016 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.takes.rs.xe; import java.io.IOException; import lombok.EqualsAndHashCode; import org.xembly.Directive; /** * Wrap of Xembly source. * * <p>The class is immutable and thread-safe. * * @author Yegor Bugayenko (yegor@teamed.io) * @version $Id$ * @since 0.4 */ @EqualsAndHashCode(of = "origin") public class XeWrap implements XeSource { /** * Source to add. */ private final transient XeSource origin; /** * Ctor. * @param src Original source */ public XeWrap(final XeSource src) { this.origin = src; } @Override public final Iterable<Directive> toXembly() throws IOException { return this.origin.toXembly(); } }
mit
DapauCo/FriendlyChatTutorial
android-start/app/src/main/java/com/google/firebase/codelab/friendlychat/MainActivity.java
7286
/** * Copyright Google Inc. All Rights Reserved. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.firebase.codelab.friendlychat; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.annotation.NonNull; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.text.Editable; import android.text.InputFilter; import android.text.TextWatcher; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import com.bumptech.glide.Glide; import com.firebase.ui.database.FirebaseRecyclerAdapter; import com.google.android.gms.ads.AdRequest; import com.google.android.gms.ads.AdView; import com.google.android.gms.appinvite.AppInvite; import com.google.android.gms.appinvite.AppInviteInvitation; import com.google.android.gms.auth.api.Auth; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.firebase.analytics.FirebaseAnalytics; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.crash.FirebaseCrash; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.remoteconfig.FirebaseRemoteConfig; import com.google.firebase.remoteconfig.FirebaseRemoteConfigSettings; import java.util.HashMap; import java.util.Map; import de.hdodenhof.circleimageview.CircleImageView; public class MainActivity extends AppCompatActivity implements GoogleApiClient.OnConnectionFailedListener { public static class MessageViewHolder extends RecyclerView.ViewHolder { public TextView messageTextView; public TextView messengerTextView; public CircleImageView messengerImageView; public MessageViewHolder(View v) { super(v); messageTextView = (TextView) itemView.findViewById(R.id.messageTextView); messengerTextView = (TextView) itemView.findViewById(R.id.messengerTextView); messengerImageView = (CircleImageView) itemView.findViewById(R.id.messengerImageView); } } private static final String TAG = "MainActivity"; public static final String MESSAGES_CHILD = "messages"; private static final int REQUEST_INVITE = 1; public static final int DEFAULT_MSG_LENGTH_LIMIT = 10; public static final String ANONYMOUS = "anonymous"; private static final String MESSAGE_SENT_EVENT = "message_sent"; private String mUsername; private String mPhotoUrl; private SharedPreferences mSharedPreferences; private GoogleApiClient mGoogleApiClient; private Button mSendButton; private RecyclerView mMessageRecyclerView; private LinearLayoutManager mLinearLayoutManager; private ProgressBar mProgressBar; private EditText mMessageEditText; // Firebase instance variables @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); // Set default username is anonymous. mUsername = ANONYMOUS; mGoogleApiClient = new GoogleApiClient.Builder(this) .enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */) .addApi(Auth.GOOGLE_SIGN_IN_API) .build(); // Initialize ProgressBar and RecyclerView. mProgressBar = (ProgressBar) findViewById(R.id.progressBar); mMessageRecyclerView = (RecyclerView) findViewById(R.id.messageRecyclerView); mLinearLayoutManager = new LinearLayoutManager(this); mLinearLayoutManager.setStackFromEnd(true); mMessageRecyclerView.setLayoutManager(mLinearLayoutManager); mProgressBar.setVisibility(ProgressBar.INVISIBLE); mMessageEditText = (EditText) findViewById(R.id.messageEditText); mMessageEditText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(mSharedPreferences .getInt(CodelabPreferences.FRIENDLY_MSG_LENGTH, DEFAULT_MSG_LENGTH_LIMIT))}); mMessageEditText.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { if (charSequence.toString().trim().length() > 0) { mSendButton.setEnabled(true); } else { mSendButton.setEnabled(false); } } @Override public void afterTextChanged(Editable editable) { } }); mSendButton = (Button) findViewById(R.id.sendButton); mSendButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // Send messages on click. } }); } @Override public void onStart() { super.onStart(); // Check if user is signed in. // TODO: Add code to check if user is signed in. } @Override public void onPause() { super.onPause(); } @Override public void onResume() { super.onResume(); } @Override public void onDestroy() { super.onDestroy(); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.main_menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { return super.onOptionsItemSelected(item); } @Override public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { // An unresolvable error has occurred and Google APIs (including Sign-In) will not // be available. Log.d(TAG, "onConnectionFailed:" + connectionResult); Toast.makeText(this, "Google Play Services error.", Toast.LENGTH_SHORT).show(); } }
mit
aj-michael/minijavac
src/test/resources/typechecker/java/testcase95_01.java
283
class Main { public static void main(String[] args) { SomeClass a = new AnotherClass(); System.out.println(a.getInt()); } } class SomeClass { public int getInt() { return 41; } } class AnotherClass extends SomeClass { public int getInt() { return 42; } }
mit
lanyudhy/Halite-II
airesources/Java/hlt/Entity.java
956
package hlt; public class Entity extends Position { private final int owner; private final int id; private final int health; private final double radius; public Entity(final int owner, final int id, final double xPos, final double yPos, final int health, final double radius) { super(xPos, yPos); this.owner = owner; this.id = id; this.health = health; this.radius = radius; } public int getOwner() { return owner; } public int getId() { return id; } public int getHealth() { return health; } public double getRadius() { return radius; } @Override public String toString() { return "Entity[" + super.toString() + ", owner=" + owner + ", id=" + id + ", health=" + health + ", radius=" + radius + "]"; } }
mit
dierksen/robolectric
src/test/java/org/robolectric/shadows/ToastTest.java
893
package org.robolectric.shadows; import android.app.Activity; import android.widget.Toast; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.TestRunners; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; @RunWith(TestRunners.WithDefaults.class) public class ToastTest { @Test public void shouldHaveShortDuration() throws Exception { Toast toast = Toast.makeText(new Activity(), "short toast", Toast.LENGTH_SHORT); assertNotNull(toast); assertEquals(Toast.LENGTH_SHORT, toast.getDuration()); } @Test public void shouldHaveLongDuration() throws Exception { Toast toast = Toast.makeText(new Activity(), "long toast", Toast.LENGTH_LONG); assertNotNull(toast); assertEquals(Toast.LENGTH_LONG, toast.getDuration()); } }
mit
ncounter/saltstack-netapi-client-java
src/main/java/com/suse/saltstack/netapi/exception/ParsingException.java
565
package com.suse.saltstack.netapi.exception; import java.io.IOException; /** * Exception to be thrown in case of problems parsing service responses. */ public class ParsingException extends IOException { /** * Constructor expecting a custom cause. * * @param cause the cause */ public ParsingException(Throwable cause) { super(cause); } /** * Constructor expecting a custom message. * * @param message the message */ public ParsingException(String message) { super(message); } }
mit
mateusmcosta/gradle-plugins
scd4j/src/main/java/com/datamaio/scd4j/util/EncodingHelper.java
4799
/** * The MIT License (MIT) * * Copyright (C) 2014 scd4j scd4j.tools@gmail.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.datamaio.scd4j.util; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.nio.charset.Charset; import java.util.Properties; import java.util.logging.Logger; /** * Classe que visita dentro das configurações do eclipse para saber exatamente o encoding configurado para cada arquivo. <br> * Se não exisitr um encoding configura, esta classe considera o encoding padrão do SO. * * @author Fernando Rubbo */ public class EncodingHelper { private static final Logger LOGGER = Logger.getLogger(Logger.GLOBAL_LOGGER_NAME); private static final String DEFAULT_ECLIPSE_CONF = ".settings/org.eclipse.core.resources.prefs"; private static final String ENCODING_PREFIX = "encoding/"; private Properties props = new Properties(); public EncodingHelper() { this(DEFAULT_ECLIPSE_CONF); } public EncodingHelper(String... fileNames) { loadEncodingFromEclipseConf(fileNames); printConfiguredEncodings(); } public EncodingHelper(InputStream... ins) { loadEncodingsFromEclipseConf(ins); printConfiguredEncodings(); } private void loadEncodingFromEclipseConf(String... fileNames) { try { for (String fileName : fileNames) { final File file = new File(fileName); if (file.exists()) { loadEncodingsFromEclipseConf(new BufferedInputStream(new FileInputStream(file))); } } } catch (Exception e) { throw new RuntimeException("não foi possível ler o arquivo de encode dos arquivos", e); } } private void loadEncodingsFromEclipseConf(InputStream... ins) { try { for (InputStream in : ins) { props.load(in); } } catch (Exception e) { throw new RuntimeException("não foi possível ler o arquivo de encode dos arquivos", e); } } public void printConfiguredEncodings() { LOGGER.info("================================ CONFIGURED ENCODINGS in ECLIPSE =========================================="); for (Object key : props.keySet()) { if (isTheKeyAnEncoding((String) key)) { Object value = props.get(key); LOGGER.info(key + " = " + value); } } LOGGER.info("==========================================================================================================="); } public Charset getCharset(String fileName, String defaultEncoding) { fileName = fileName.replaceAll("\\\\", "/"); String encode = props.getProperty(ENCODING_PREFIX + fileName); if (encode == null) { encode = props.getProperty(ENCODING_PREFIX + "/" + fileName); } if (encode == null) { // TODO : improve performance. once it will be executed for each // file merged for (Object _key : props.keySet()) { String key = (String) _key; if (isTheKeyAnEncoding(key)) { if (key.contains(fileName) || fileName.contains(key.substring(ENCODING_PREFIX.length() + 1))) { LOGGER.fine("t\t\tFound in the inverse logic"); encode = props.getProperty(key); break; } } } } final String result = encode == null ? defaultEncoding : encode; final Charset cs = Charset.forName(result); LOGGER.fine("\t\tEncoding for " + fileName + " is " + cs); return cs; } public Charset getCharset(String fileName) { return getCharset(fileName, System.getProperty("file.encoding")); } private boolean isTheKeyAnEncoding(final String key) { return key.startsWith(ENCODING_PREFIX) && (!key.equals(ENCODING_PREFIX + "<project>") && !key .equals(ENCODING_PREFIX + "/<project>")); } }
mit
openhab/openhab2
bundles/org.openhab.transform.regex/src/main/java/org/openhab/transform/regex/internal/profiles/RegexTransformationProfile.java
4888
/** * Copyright (c) 2010-2020 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.transform.regex.internal.profiles; import org.eclipse.jdt.annotation.NonNullByDefault; import org.openhab.core.library.types.StringType; import org.openhab.core.thing.profiles.ProfileCallback; import org.openhab.core.thing.profiles.ProfileContext; import org.openhab.core.thing.profiles.ProfileTypeUID; import org.openhab.core.thing.profiles.StateProfile; import org.openhab.core.transform.TransformationException; import org.openhab.core.transform.TransformationHelper; import org.openhab.core.transform.TransformationService; import org.openhab.core.types.Command; import org.openhab.core.types.State; import org.openhab.core.types.Type; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Profile to offer the RegexTransformationservice on a ItemChannelLink * * @author Stefan Triller - initial contribution * */ @NonNullByDefault public class RegexTransformationProfile implements StateProfile { public static final ProfileTypeUID PROFILE_TYPE_UID = new ProfileTypeUID( TransformationService.TRANSFORM_PROFILE_SCOPE, "REGEX"); private final Logger logger = LoggerFactory.getLogger(RegexTransformationProfile.class); private final TransformationService service; private final ProfileCallback callback; private static final String FUNCTION_PARAM = "function"; private static final String SOURCE_FORMAT_PARAM = "sourceFormat"; @NonNullByDefault({}) private final String function; @NonNullByDefault({}) private final String sourceFormat; public RegexTransformationProfile(ProfileCallback callback, ProfileContext context, TransformationService service) { this.service = service; this.callback = callback; Object paramFunction = context.getConfiguration().get(FUNCTION_PARAM); Object paramSource = context.getConfiguration().get(SOURCE_FORMAT_PARAM); logger.debug("Profile configured with '{}'='{}', '{}'={}", FUNCTION_PARAM, paramFunction, SOURCE_FORMAT_PARAM, paramSource); // SOURCE_FORMAT_PARAM is an advanced parameter and we assume "%s" if it is not set if (paramSource == null) { paramSource = "%s"; } if (paramFunction instanceof String && paramSource instanceof String) { function = (String) paramFunction; sourceFormat = (String) paramSource; } else { logger.error("Parameter '{}' and '{}' have to be Strings. Profile will be inactive.", FUNCTION_PARAM, SOURCE_FORMAT_PARAM); function = null; sourceFormat = null; } } @Override public ProfileTypeUID getProfileTypeUID() { return PROFILE_TYPE_UID; } @Override public void onStateUpdateFromItem(State state) { } @Override public void onCommandFromItem(Command command) { callback.handleCommand(command); } @Override public void onCommandFromHandler(Command command) { if (function == null || sourceFormat == null) { logger.warn( "Please specify a function and a source format for this Profile in the '{}', and '{}' parameters. Returning the original command now.", FUNCTION_PARAM, SOURCE_FORMAT_PARAM); callback.sendCommand(command); return; } callback.sendCommand((Command) transformState(command)); } @Override public void onStateUpdateFromHandler(State state) { if (function == null || sourceFormat == null) { logger.warn( "Please specify a function and a source format for this Profile in the '{}' and '{}' parameters. Returning the original state now.", FUNCTION_PARAM, SOURCE_FORMAT_PARAM); callback.sendUpdate(state); return; } callback.sendUpdate((State) transformState(state)); } private Type transformState(Type state) { String result = state.toFullString(); try { result = TransformationHelper.transform(service, function, sourceFormat, state.toFullString()); } catch (TransformationException e) { logger.warn("Could not transform state '{}' with function '{}' and format '{}'", state, function, sourceFormat); } StringType resultType = new StringType(result); logger.debug("Transformed '{}' into '{}'", state, resultType); return resultType; } }
epl-1.0
menghanli/ice
org.eclipse.ice.reflectivity.test/src/org/eclipse/ice/reflectivity/test/ReflectivityModelTester.java
3730
/******************************************************************************* * Copyright (c) 2013, 2014 UT-Battelle, LLC. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Initial API and implementation and/or initial documentation - Jay Jay Billings, * Jordan H. Deyton, Dasha Gorin, Alexander J. McCaskey, Taylor Patterson, * Claire Saunders, Matthew Wang, Anna Wojtowicz *******************************************************************************/ package org.eclipse.ice.reflectivity.test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import java.util.List; import org.eclipse.ice.datastructures.ICEObject.ListComponent; import org.eclipse.ice.datastructures.form.Material; import org.eclipse.ice.materials.IMaterialsDatabase; import org.eclipse.ice.reflectivity.ReflectivityModel; import org.junit.Test; import ca.odell.glazedlists.EventList; import ca.odell.glazedlists.gui.TableFormat; /** * This class is responsible for testing the ReflectivityModel. It implements * the IMaterialsDatabase interface so that it can make sure the reflectivity * model initializes properly when setupFormWithServices() is called. * * @author Jay Jay Billings * */ public class ReflectivityModelTester implements IMaterialsDatabase { /** * This operation checks the ReflectivityModel and makes sure that it can * properly construct its Form. */ @Test public void checkConstruction() { // Local Declarations ListComponent<Material> list; // Just create one with the nullary constructor // No need to check the Item with a IProject instance ReflectivityModel model = new ReflectivityModel(); model.setMaterialsDatabase(this); model.setupFormWithServices(); // Make sure we have a form and some components assertNotNull(model.getForm()); assertEquals(4, model.getForm().getComponents().size()); // Get the table component list = (ListComponent<Material>) model.getForm() .getComponent(ReflectivityModel.matListId); // Make sure it's not null and the name is correct assertNotNull(list); assertEquals("Reflectivity Input Data", list.getName()); // Make sure that the element source of the list is set to insure that // setupFormWithServices() worked. assertNotNull(list.getElementSource()); assertEquals(list.getElementSource(), this); // Make sure the other components are being created properly. assertNotNull( model.getForm().getComponent(ReflectivityModel.paramsCompId)); assertNotNull( model.getForm().getComponent(ReflectivityModel.resourceCompId)); assertNotNull( model.getForm().getComponent(ReflectivityModel.outputCompId)); return; } @Override public EventList<Material> getElements() { // TODO Auto-generated method stub return null; } @Override public TableFormat<Material> getTableFormat() { // TODO Auto-generated method stub return null; } @Override public List<Material> getMaterials() { // TODO Auto-generated method stub return null; } @Override public void addMaterial(Material material) { // TODO Auto-generated method stub } @Override public void deleteMaterial(String name) { // TODO Auto-generated method stub } @Override public void deleteMaterial(Material material) { // TODO Auto-generated method stub } @Override public void updateMaterial(Material material) { // TODO Auto-generated method stub } @Override public void restoreDefaults() { // TODO Auto-generated method stub } }
epl-1.0
sguan-actuate/birt
UI/org.eclipse.birt.report.designer.ui.lib/src/org/eclipse/birt/report/designer/internal/lib/editors/actions/ExportAction.java
1914
/******************************************************************************* * Copyright (c) 2004 Actuate Corporation . * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Actuate Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.birt.report.designer.internal.lib.editors.actions; import java.util.List; import org.eclipse.birt.report.designer.nls.Messages; import org.eclipse.birt.report.model.api.DesignElementHandle; import org.eclipse.gef.EditPart; import org.eclipse.gef.ui.actions.SelectionAction; import org.eclipse.ui.IWorkbenchPart; /** * Exports the designelement handle of the seletion to a other file. * */ public class ExportAction extends SelectionAction { /** * display label of action */ private static final String ACTION_MSG_INSERT = Messages.getString( "ExportAction.actionMsg.export" ); //$NON-NLS-1$ /** * action id */ public static final String ID = "org.eclipse.birt.report.designer.ui.actions.ExportAction"; //$NON-NLS-1$ /** * @param part */ public ExportAction( IWorkbenchPart part ) { super( part ); setId( ID ); setText( ACTION_MSG_INSERT ); } /* * (non-Javadoc) * * @see org.eclipse.gef.ui.actions.WorkbenchPartAction#calculateEnabled() */ protected boolean calculateEnabled( ) { List list = getSelectedObjects( ); if ( list.isEmpty( ) && list.size() != 1) { return false; } Object obj = list.get(0); if (obj instanceof EditPart) { return ((EditPart)obj).getModel() instanceof DesignElementHandle; } return false; } /** * Runs action. * */ public void run( ) { //Do nothing } }
epl-1.0
riuvshin/che-plugins
plugin-runner/che-plugin-runner-ext-runner/src/test/java/org/eclipse/che/ide/ext/runner/client/tabs/container/TabContainerPresenterTest.java
9224
/******************************************************************************* * Copyright (c) 2012-2015 Codenvy, S.A. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Codenvy, S.A. - initial API and implementation *******************************************************************************/ package org.eclipse.che.ide.ext.runner.client.tabs.container; import com.google.gwt.user.client.ui.AcceptsOneWidget; import com.google.gwtmockito.GwtMockitoTestRunner; import org.eclipse.che.ide.ext.runner.client.RunnerLocalizationConstant; import org.eclipse.che.ide.ext.runner.client.state.PanelState; import org.eclipse.che.ide.ext.runner.client.tabs.common.Tab; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.InjectMocks; import org.mockito.Matchers; import org.mockito.Mock; import java.util.Map; import static org.eclipse.che.ide.ext.runner.client.manager.menu.SplitterState.SPLITTER_OFF; import static org.eclipse.che.ide.ext.runner.client.state.State.RUNNERS; import static org.eclipse.che.ide.ext.runner.client.tabs.container.PanelLocation.LEFT_PROPERTIES; import static org.eclipse.che.ide.ext.runner.client.tabs.container.PanelLocation.RIGHT_PROPERTIES; import static org.hamcrest.CoreMatchers.equalTo; import static org.junit.Assert.assertThat; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.reset; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; /** * @author Andrienko Alexander * @author Dmitry Shnurenko */ @RunWith(GwtMockitoTestRunner.class) public class TabContainerPresenterTest { private static final String TITLE2 = "title2"; private static final String TITLE1 = "title1"; //variables for constructor @Mock private TabContainerView view; @Mock private PanelState panelState; @Mock private RunnerLocalizationConstant locale; @Mock private Tab tab1; @Mock private Tab tab2; @Captor private ArgumentCaptor<Map<String, Boolean>> mapCaptor; @InjectMocks private TabContainerPresenter tabContainerPresenter; @Before public void setUp() { when(tab2.getTitle()).thenReturn(TITLE2); when(locale.runnerTabTerminal()).thenReturn(TITLE2); when(tab1.getTitle()).thenReturn(TITLE1); when(tab2.getTitle()).thenReturn(TITLE2); when(panelState.getState()).thenReturn(RUNNERS); } @Test public void shouldGo() { AcceptsOneWidget container = mock(AcceptsOneWidget.class); tabContainerPresenter.go(container); verify(container).setWidget(view); } @Test public void shouldAddFirstTab() { tabContainerPresenter.addTab(tab1); verify(tab1).getTitle(); verify(view).addTab(tab1); verify(view).showTab(tab1); verify(view).selectTab(tab1); } @Test public void terminalTabShouldBeAdded() { tabContainerPresenter.addTab(tab1); tabContainerPresenter.addTab(tab2); verify(view).addTab(tab1); verify(view).addTab(tab2); verify(view).showTab(tab1); verify(view).showTab(tab2); } @Test public void tabTitleShouldBeShown() { tabContainerPresenter.showTabTitle(TITLE2, true); verify(view).showTabTitle(TITLE2, true); } @Test public void shouldAddTwoTabs() { shouldAddFirstTab(); tabContainerPresenter.addTab(tab2); verify(tab2).getTitle(); verify(view).addTab(tab2); } @Test(expected = IllegalStateException.class) public void shouldAddTabWhichIsAlreadyExist() { tabContainerPresenter.addTab(tab1); //add tab1 again tabContainerPresenter.addTab(tab1); verify(tab1).getTitle(); verifyNoMoreInteractions(view); } @Test public void shouldOnTabClicked() { addTwoTabs(); tabContainerPresenter.onTabClicked(TITLE2); verify(tab2, times(2)).getTitle(); verify(tab2).performHandler(); verify(view).showTab(tab2); verify(view).selectTab(tab2); } @Test public void shouldOnTabClickedWhenTitleIsWrong() { addTwoTabs(); tabContainerPresenter.onTabClicked("some not exist title"); verify(tab1).getTitle(); verify(tab2).getTitle(); verifyNoMoreInteractions(view, tab1, tab2); } @Test public void shouldShowTab() { addTwoTabs(); tabContainerPresenter.showTab(TITLE2); verify(tab2, times(2)).getTitle(); verify(tab2).performHandler(); verify(view).showTab(tab2); verify(view).selectTab(tab2); } @Test public void shouldShowTabWhenTitleIsWrong() { addTwoTabs(); tabContainerPresenter.showTab("some not exist title"); verify(tab1).getTitle(); verify(tab2).getTitle(); verifyNoMoreInteractions(view, tab1, tab2); } @Test public void firstTabShouldBeVisibleWhenItIsNotRightPanel() { when(panelState.getState()).thenReturn(RUNNERS); when(tab2.isAvailableScope(RUNNERS)).thenReturn(true); addTwoTabs(); tabContainerPresenter.setLocation(LEFT_PROPERTIES); tabContainerPresenter.onStateChanged(); verify(view).setVisibleTitle(mapCaptor.capture()); Map<String, Boolean> tabVisibilities = mapCaptor.getValue(); assertThat(tabVisibilities.get(TITLE2), equalTo(true)); assertThat(tabVisibilities.get(TITLE1), equalTo(false)); } @Test public void firstTabShouldBeVisibleWhenSplitterIsOff() { when(panelState.getState()).thenReturn(RUNNERS); when(tab1.isAvailableScope(RUNNERS)).thenReturn(true); when(panelState.getSplitterState()).thenReturn(SPLITTER_OFF); addTwoTabs(); tabContainerPresenter.setLocation(RIGHT_PROPERTIES); tabContainerPresenter.onStateChanged(); verify(view).setVisibleTitle(mapCaptor.capture()); Map<String, Boolean> tabVisibilities = mapCaptor.getValue(); assertThat(tabVisibilities.get(TITLE1), equalTo(true)); assertThat(tabVisibilities.get(TITLE2), equalTo(false)); } @Test public void shouldOnStateChangedWhenOneTabIsVisible() { when(tab1.isAvailableScope(RUNNERS)).thenReturn(true); when(tab2.isAvailableScope(RUNNERS)).thenReturn(false); addTwoTabs(); tabContainerPresenter.onStateChanged(); verify(panelState).getState(); verify(tab1).isAvailableScope(RUNNERS); verify(tab2).isAvailableScope(RUNNERS); verify(tab1, times(2)).getTitle(); verify(tab2, times(2)).getTitle(); verify(view).setVisibleTitle(Matchers.<Map<String, Boolean>>anyObject()); verify(view).showTab(tab1); verify(view).selectTab(tab1); } @Test public void shouldOnStateChangedWhenNoneTabIsVisible() { when(tab1.isAvailableScope(RUNNERS)).thenReturn(false); when(tab2.isAvailableScope(RUNNERS)).thenReturn(false); addTwoTabs(); tabContainerPresenter.onStateChanged(); verify(panelState).getState(); verify(tab1).isAvailableScope(RUNNERS); verify(tab2).isAvailableScope(RUNNERS); verify(tab1, times(2)).getTitle(); verify(tab2, times(2)).getTitle(); verify(view).setVisibleTitle(Matchers.<Map<String, Boolean>>anyObject()); verifyNoMoreInteractions(view); } @Test public void shouldOnStateChangedWhenNoneTabAreNotExist() { tabContainerPresenter.onStateChanged(); verify(panelState).getState(); verify(view).setVisibleTitle(Matchers.<Map<String, Boolean>>anyObject()); verify(view, never()).showTab(any(Tab.class)); verify(view, never()).selectTab(any(Tab.class)); } @Test /* Two tabs are visible, but we should select first of them */ public void shouldOnStateChangedWhenTwoTabAreVisible() { when(tab1.isAvailableScope(RUNNERS)).thenReturn(true); when(tab2.isAvailableScope(RUNNERS)).thenReturn(true); addTwoTabs(); tabContainerPresenter.onStateChanged(); verify(panelState).getState(); verify(tab1).isAvailableScope(RUNNERS); verify(tab2).isAvailableScope(RUNNERS); verify(tab1, times(2)).getTitle(); verify(tab2, times(2)).getTitle(); verify(view).setVisibleTitle(Matchers.<Map<String, Boolean>>anyObject()); verify(view).showTab(tab1); verify(view).selectTab(tab1); } private void addTwoTabs() { tabContainerPresenter.addTab(tab1); tabContainerPresenter.addTab(tab2); reset(view); } }
epl-1.0
mandeepdhami/netvirt-ctrl
sdnplatform/src/test/java/org/sdnplatform/core/internal/RoleChangerTest.java
22068
/* * Copyright (c) 2013 Big Switch Networks, Inc. * * Licensed under the Eclipse Public License, Version 1.0 (the * "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at * * http://www.eclipse.org/legal/epl-v10.html * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ package org.sdnplatform.core.internal; import static org.easymock.EasyMock.capture; import static org.easymock.EasyMock.createMock; import static org.easymock.EasyMock.expect; import static org.easymock.EasyMock.expectLastCall; import static org.easymock.EasyMock.replay; import static org.easymock.EasyMock.reset; import static org.easymock.EasyMock.verify; import static org.junit.Assert.*; import java.io.IOException; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.util.Collection; import java.util.LinkedList; import java.util.List; import org.easymock.Capture; import org.easymock.EasyMock; import org.jboss.netty.channel.Channel; import org.junit.Before; import org.junit.Test; import org.openflow.protocol.OFError; import org.openflow.protocol.OFError.OFErrorType; import org.openflow.protocol.OFMessage; import org.openflow.protocol.OFType; import org.openflow.protocol.OFVendor; import org.openflow.protocol.factory.BasicFactory; import org.openflow.protocol.vendor.OFVendorData; import org.openflow.vendor.nicira.OFNiciraVendorData; import org.openflow.vendor.nicira.OFRoleRequestVendorData; import org.openflow.vendor.nicira.OFRoleVendorData; import org.sdnplatform.core.ListenerContext; import org.sdnplatform.core.IOFSwitch; import org.sdnplatform.core.IControllerService.Role; import org.sdnplatform.core.internal.Controller; import org.sdnplatform.core.internal.OFSwitchImpl; import org.sdnplatform.core.internal.RoleChanger; import org.sdnplatform.core.internal.RoleChanger.PendingRoleRequestEntry; import org.sdnplatform.core.internal.RoleChanger.RoleChangeTask; public class RoleChangerTest { public RoleChanger roleChanger; Controller controller; @Before public void setUp() throws Exception { controller = createMock(Controller.class); roleChanger = new RoleChanger(controller); BasicFactory factory = new BasicFactory(); expect(controller.getOFMessageFactory()).andReturn(factory).anyTimes(); } /** * Send a role request for SLAVE to a switch that doesn't support it. * The connection should be closed. */ @Test public void testSendRoleRequestSlaveNotSupported() throws Exception { LinkedList<IOFSwitch> switches = new LinkedList<IOFSwitch>(); // a switch that doesn't support role requests IOFSwitch sw1 = EasyMock.createMock(IOFSwitch.class); // No support for NX_ROLE expect(sw1.getAttribute(IOFSwitch.SWITCH_SUPPORTS_NX_ROLE)) .andReturn(false); sw1.disconnectOutputStream(); switches.add(sw1); replay(sw1); roleChanger.sendRoleRequest(switches, Role.SLAVE, 123456); verify(sw1); // sendRoleRequest needs to remove the switch from the list since // it closed its connection assertTrue(switches.isEmpty()); } /** * Send a role request for MASTER to a switch that doesn't support it. * The connection should stay open. */ @Test public void testSendRoleRequestMasterNotSupported() throws Exception { LinkedList<IOFSwitch> switches = new LinkedList<IOFSwitch>(); // a switch that doesn't support role requests IOFSwitch sw1 = EasyMock.createMock(IOFSwitch.class); // No support for NX_ROLE expect(sw1.getAttribute(IOFSwitch.SWITCH_SUPPORTS_NX_ROLE)) .andReturn(false); sw1.setHARole(Role.MASTER, false); switches.add(sw1); replay(sw1); roleChanger.sendRoleRequest(switches, Role.MASTER, 123456); verify(sw1); assertEquals(1, switches.size()); } /** * Check error handling * hasn't had a role request send to it yet */ @SuppressWarnings("unchecked") @Test public void testSendRoleRequestErrorHandling () throws Exception { LinkedList<IOFSwitch> switches = new LinkedList<IOFSwitch>(); // a switch that supports role requests IOFSwitch sw1 = EasyMock.createMock(IOFSwitch.class); // No support for NX_ROLE expect(sw1.getAttribute(IOFSwitch.SWITCH_SUPPORTS_NX_ROLE)) .andReturn(true); expect(sw1.getNextTransactionId()).andReturn(1); sw1.write((List<OFMessage>)EasyMock.anyObject(), (ListenerContext)EasyMock.anyObject()); expectLastCall().andThrow(new IOException()); sw1.disconnectOutputStream(); switches.add(sw1); replay(sw1, controller); roleChanger.sendRoleRequest(switches, Role.MASTER, 123456); verify(sw1, controller); assertTrue(switches.isEmpty()); } /** * Send a role request a switch that supports it and one that * hasn't had a role request send to it yet */ @SuppressWarnings("unchecked") @Test public void testSendRoleRequestSupported() throws Exception { LinkedList<IOFSwitch> switches = new LinkedList<IOFSwitch>(); // a switch that supports role requests IOFSwitch sw1 = EasyMock.createMock(IOFSwitch.class); // Support for NX_ROLE expect(sw1.getAttribute(IOFSwitch.SWITCH_SUPPORTS_NX_ROLE)) .andReturn(true); expect(sw1.getNextTransactionId()).andReturn(1); sw1.write((List<OFMessage>)EasyMock.anyObject(), (ListenerContext)EasyMock.anyObject()); switches.add(sw1); // second switch IOFSwitch sw2 = EasyMock.createMock(IOFSwitch.class); // No role request yet expect(sw2.getAttribute(IOFSwitch.SWITCH_SUPPORTS_NX_ROLE)) .andReturn(null); expect(sw2.getNextTransactionId()).andReturn(1); sw2.write((List<OFMessage>)EasyMock.anyObject(), (ListenerContext)EasyMock.anyObject()); switches.add(sw2); replay(sw1, sw2, controller); roleChanger.sendRoleRequest(switches, Role.MASTER, 123456); verify(sw1, sw2, controller); assertEquals(2, switches.size()); } @Test public void testVerifyRoleReplyReceived() throws Exception { Collection<IOFSwitch> switches = new LinkedList<IOFSwitch>(); // Add a switch that has received a role reply IOFSwitch sw1 = EasyMock.createMock(IOFSwitch.class); LinkedList<PendingRoleRequestEntry> pendingList1 = new LinkedList<PendingRoleRequestEntry>(); roleChanger.pendingRequestMap.put(sw1, pendingList1); switches.add(sw1); // Add a switch that has not yet received a role reply IOFSwitch sw2 = EasyMock.createMock(IOFSwitch.class); LinkedList<PendingRoleRequestEntry> pendingList2 = new LinkedList<PendingRoleRequestEntry>(); roleChanger.pendingRequestMap.put(sw2, pendingList2); PendingRoleRequestEntry entry = new PendingRoleRequestEntry(1, Role.MASTER, 123456); pendingList2.add(entry); // Timed out switch should become active expect(sw2.getAttribute(IOFSwitch.SWITCH_DESCRIPTION_DATA)) .andReturn(null); expect(sw2.getHARole()).andReturn(null); sw2.setHARole(Role.MASTER, false); EasyMock.expectLastCall(); switches.add(sw2); replay(sw1, sw2); roleChanger.verifyRoleReplyReceived(switches, 123456); verify(sw1, sw2); assertEquals(2, switches.size()); } @Test public void testRoleChangeTask() { @SuppressWarnings("unchecked") Collection<IOFSwitch> switches = EasyMock.createMock(Collection.class); long now = System.nanoTime(); long dt1 = 10 * 1000*1000*1000L; long dt2 = 20 * 1000*1000*1000L; long dt3 = 15 * 1000*1000*1000L; RoleChangeTask t1 = new RoleChangeTask(switches, null, now+dt1); RoleChangeTask t2 = new RoleChangeTask(switches, null, now+dt2); RoleChangeTask t3 = new RoleChangeTask(switches, null, now+dt3); // FIXME: cannot test comparison against self. grrr //assertTrue( t1.compareTo(t1) <= 0 ); assertTrue( t1.compareTo(t2) < 0 ); assertTrue( t1.compareTo(t3) < 0 ); assertTrue( t2.compareTo(t1) > 0 ); //assertTrue( t2.compareTo(t2) <= 0 ); assertTrue( t2.compareTo(t3) > 0 ); } @SuppressWarnings("unchecked") @Test public void testSubmitRequest() throws Exception { LinkedList<IOFSwitch> switches = new LinkedList<IOFSwitch>(); roleChanger.timeout = 100*1000*1000; // 100 ms // a switch that supports role requests IOFSwitch sw1 = EasyMock.createStrictMock(IOFSwitch.class); // Support for NX_ROLE expect(sw1.getAttribute(IOFSwitch.SWITCH_SUPPORTS_NX_ROLE)) .andReturn(true); expect(sw1.getNextTransactionId()).andReturn(1); sw1.write((List<OFMessage>)EasyMock.anyObject(), (ListenerContext)EasyMock.anyObject()); // Second request expect(sw1.getAttribute(IOFSwitch.SWITCH_SUPPORTS_NX_ROLE)) .andReturn(true); expect(sw1.getNextTransactionId()).andReturn(2); sw1.write((List<OFMessage>)EasyMock.anyObject(), (ListenerContext)EasyMock.anyObject()); expect(sw1.getAttribute(IOFSwitch.SWITCH_DESCRIPTION_DATA)) .andReturn(null); expect(sw1.getHARole()).andReturn(null); sw1.setHARole(Role.MASTER, false); expect(sw1.getAttribute(IOFSwitch.SWITCH_DESCRIPTION_DATA)) .andReturn(null); expect(sw1.getHARole()).andReturn(Role.MASTER); sw1.setHARole(Role.SLAVE, false); // Disconnect on timing out SLAVE request sw1.disconnectOutputStream(); switches.add(sw1); // Add to switch when timing out the MASTER request controller.addSwitch(sw1, true); replay(sw1, controller); roleChanger.submitRequest(switches, Role.MASTER); roleChanger.submitRequest(switches, Role.SLAVE); // Wait until role request has been sent. synchronized (roleChanger.pendingTasks) { while (RoleChanger.RoleChangeTask.Type.TIMEOUT != roleChanger.pendingTasks.peek().type) { roleChanger.pendingTasks.wait(); } } // Now there should be exactly one timeout task pending for each request assertEquals(2, roleChanger.pendingTasks.size()); // Check that RoleChanger indeed made a copy of switches collection assertNotSame(switches, roleChanger.pendingTasks.peek().switches); // Wait until the timeout triggers synchronized (roleChanger.pendingTasks) { while (roleChanger.pendingTasks.size() != 0) { roleChanger.pendingTasks.wait(); } } verify(sw1, controller); } // Helper function protected void setupPendingRoleRequest(IOFSwitch sw, int xid, Role role, long cookie) { LinkedList<PendingRoleRequestEntry> pendingList = new LinkedList<PendingRoleRequestEntry>(); roleChanger.pendingRequestMap.put(sw, pendingList); PendingRoleRequestEntry entry = new PendingRoleRequestEntry(xid, role, cookie); pendingList.add(entry); } @Test public void testDeliverRoleReplyOk() { // test normal case int xid = (int) System.currentTimeMillis(); long cookie = System.nanoTime(); Role role = Role.MASTER; OFSwitchImpl sw = new OFSwitchImpl(); setupPendingRoleRequest(sw, xid, role, cookie); roleChanger.deliverRoleReply(sw, xid, role); assertEquals(true, sw.getAttribute(IOFSwitch.SWITCH_SUPPORTS_NX_ROLE)); assertEquals(role, sw.getHARole()); assertEquals(0, roleChanger.pendingRequestMap.get(sw).size()); } @Test public void testDeliverRoleReplyOkRepeated() { // test normal case. Not the first role reply int xid = (int) System.currentTimeMillis(); long cookie = System.nanoTime(); Role role = Role.MASTER; OFSwitchImpl sw = new OFSwitchImpl(); setupPendingRoleRequest(sw, xid, role, cookie); sw.setAttribute(IOFSwitch.SWITCH_SUPPORTS_NX_ROLE, true); roleChanger.deliverRoleReply(sw, xid, role); assertEquals(true, sw.getAttribute(IOFSwitch.SWITCH_SUPPORTS_NX_ROLE)); assertEquals(role, sw.getHARole()); assertEquals(0, roleChanger.pendingRequestMap.get(sw).size()); } @Test public void testDeliverRoleReplyNonePending() { // nothing pending OFSwitchImpl sw = new OFSwitchImpl(); Channel ch = createMock(Channel.class); SocketAddress sa = new InetSocketAddress(42); expect(ch.getRemoteAddress()).andReturn(sa).anyTimes(); sw.setChannel(ch); roleChanger.deliverRoleReply(sw, 1, Role.MASTER); assertEquals(null, sw.getHARole()); } @Test public void testDeliverRoleReplyWrongXid() { // wrong xid received int xid = (int) System.currentTimeMillis(); long cookie = System.nanoTime(); Role role = Role.MASTER; OFSwitchImpl sw = new OFSwitchImpl(); setupPendingRoleRequest(sw, xid, role, cookie); Channel ch = createMock(Channel.class); SocketAddress sa = new InetSocketAddress(42); expect(ch.getRemoteAddress()).andReturn(sa).anyTimes(); sw.setChannel(ch); expect(ch.close()).andReturn(null); replay(ch); roleChanger.deliverRoleReply(sw, xid+1, role); verify(ch); assertEquals(null, sw.getAttribute(IOFSwitch.SWITCH_SUPPORTS_NX_ROLE)); assertEquals(0, roleChanger.pendingRequestMap.get(sw).size()); } @Test public void testDeliverRoleReplyWrongRole() { // correct xid but incorrect role received int xid = (int) System.currentTimeMillis(); long cookie = System.nanoTime(); Role role = Role.MASTER; OFSwitchImpl sw = new OFSwitchImpl(); setupPendingRoleRequest(sw, xid, role, cookie); Channel ch = createMock(Channel.class); SocketAddress sa = new InetSocketAddress(42); expect(ch.getRemoteAddress()).andReturn(sa).anyTimes(); sw.setChannel(ch); expect(ch.close()).andReturn(null); replay(ch); roleChanger.deliverRoleReply(sw, xid, Role.SLAVE); verify(ch); assertEquals(null, sw.getAttribute(IOFSwitch.SWITCH_SUPPORTS_NX_ROLE)); assertEquals(0, roleChanger.pendingRequestMap.get(sw).size()); } @Test public void testCheckFirstPendingRoleRequestXid() { int xid = 54321; long cookie = 232323; Role role = Role.MASTER; OFSwitchImpl sw = new OFSwitchImpl(); setupPendingRoleRequest(sw, xid, role, cookie); assertEquals(true, roleChanger.checkFirstPendingRoleRequestXid(sw, xid)); assertEquals(false, roleChanger.checkFirstPendingRoleRequestXid(sw, 0)); roleChanger.pendingRequestMap.get(sw).clear(); assertEquals(false, roleChanger.checkFirstPendingRoleRequestXid(sw, xid)); } @Test public void testCheckFirstPendingRoleRequestNullSw() { int xid = 54321; long cookie = 232323; Role role = Role.MASTER; OFSwitchImpl sw = new OFSwitchImpl(); setupPendingRoleRequest(sw, xid, role, cookie); // pass null as sw object, which is true during handshake assertEquals(false, roleChanger.checkFirstPendingRoleRequestXid(null, xid)); roleChanger.pendingRequestMap.get(sw).clear(); } @Test public void testCheckFirstPendingRoleRequestCookie() { int xid = 54321; long cookie = 232323; Role role = Role.MASTER; OFSwitchImpl sw = new OFSwitchImpl(); setupPendingRoleRequest(sw, xid, role, cookie); assertNotSame(null, roleChanger.checkFirstPendingRoleRequestCookie(sw, cookie)); assertEquals(null, roleChanger.checkFirstPendingRoleRequestCookie(sw, 0)); roleChanger.pendingRequestMap.get(sw).clear(); assertEquals(null, roleChanger.checkFirstPendingRoleRequestCookie(sw, cookie)); } @Test public void testDeliverRoleRequestError() { // normal case. xid is pending int xid = (int) System.currentTimeMillis(); long cookie = System.nanoTime(); Role role = Role.MASTER; OFSwitchImpl sw = new OFSwitchImpl(); Channel ch = createMock(Channel.class); SocketAddress sa = new InetSocketAddress(42); expect(ch.getRemoteAddress()).andReturn(sa).anyTimes(); sw.setChannel(ch); setupPendingRoleRequest(sw, xid, role, cookie); OFError error = new OFError(); error.setErrorType(OFErrorType.OFPET_BAD_REQUEST); error.setXid(xid); replay(ch); roleChanger.deliverRoleRequestError(sw, error); verify(ch); assertEquals(false, sw.getAttribute(IOFSwitch.SWITCH_SUPPORTS_NX_ROLE)); assertEquals(role, sw.getHARole()); assertEquals(0, roleChanger.pendingRequestMap.get(sw).size()); } @Test public void testDeliverRoleRequestErrorNonePending() { // nothing pending OFSwitchImpl sw = new OFSwitchImpl(); Channel ch = createMock(Channel.class); SocketAddress sa = new InetSocketAddress(42); expect(ch.getRemoteAddress()).andReturn(sa).anyTimes(); sw.setChannel(ch); OFError error = new OFError(); error.setErrorType(OFErrorType.OFPET_BAD_REQUEST); error.setXid(1); replay(ch); roleChanger.deliverRoleRequestError(sw, error); verify(ch); assertEquals(null, sw.getHARole()); } @Test public void testDeliverRoleRequestErrorWrongXid() { // wrong xid received // wrong xid received int xid = (int) System.currentTimeMillis(); long cookie = System.nanoTime(); Role role = Role.MASTER; OFSwitchImpl sw = new OFSwitchImpl(); setupPendingRoleRequest(sw, xid, role, cookie); Channel ch = createMock(Channel.class); SocketAddress sa = new InetSocketAddress(42); expect(ch.getRemoteAddress()).andReturn(sa).anyTimes(); expect(ch.close()).andReturn(null); sw.setChannel(ch); replay(ch); OFError error = new OFError(); error.setErrorCode(OFError.OFErrorType.OFPET_BAD_REQUEST.getValue()); error.setXid(xid + 1); roleChanger.deliverRoleRequestError(sw, error); verify(ch); assertEquals(null, sw.getAttribute(IOFSwitch.SWITCH_SUPPORTS_NX_ROLE)); assertEquals(1, roleChanger.pendingRequestMap.get(sw).size()); } public void doSendNxRoleRequest(Role role, int nx_role) throws Exception { long cookie = System.nanoTime(); OFSwitchImpl sw = new OFSwitchImpl(); Channel ch = createMock(Channel.class); sw.setChannel(ch); sw.setControllerProvider(controller); // verify that the correct OFMessage is sent Capture<List<OFMessage>> msgCapture = new Capture<List<OFMessage>>(); // expect(sw.channel.getRemoteAddress()).andReturn(null); controller.handleOutgoingMessage( (IOFSwitch)EasyMock.anyObject(), (OFMessage)EasyMock.anyObject(), (ListenerContext)EasyMock.anyObject()); expect(ch.write(capture(msgCapture))).andReturn(null); replay(ch, controller); int xid = roleChanger.sendHARoleRequest(sw, role, cookie); verify(ch, controller); List<OFMessage> msgList = msgCapture.getValue(); assertEquals(1, msgList.size()); OFMessage msg = msgList.get(0); assertEquals("Transaction Ids must match", xid, msg.getXid()); assertTrue("Message must be an OFVendor type", msg instanceof OFVendor); assertEquals(OFType.VENDOR, msg.getType()); OFVendor vendorMsg = (OFVendor)msg; assertEquals("Vendor message must be vendor Nicira", OFNiciraVendorData.NX_VENDOR_ID, vendorMsg.getVendor()); OFVendorData vendorData = vendorMsg.getVendorData(); assertTrue("Vendor Data must be an OFRoleRequestVendorData", vendorData instanceof OFRoleRequestVendorData); OFRoleRequestVendorData roleRequest = (OFRoleRequestVendorData)vendorData; assertEquals(nx_role, roleRequest.getRole()); reset(ch); } @Test public void testSendNxRoleRequestMaster() throws Exception { doSendNxRoleRequest(Role.MASTER, OFRoleVendorData.NX_ROLE_MASTER); } @Test public void testSendNxRoleRequestSlave() throws Exception { doSendNxRoleRequest(Role.SLAVE, OFRoleVendorData.NX_ROLE_SLAVE); } @Test public void testSendNxRoleRequestEqual() throws Exception { doSendNxRoleRequest(Role.EQUAL, OFRoleVendorData.NX_ROLE_OTHER); } }
epl-1.0
Charling-Huang/birt
UI/org.eclipse.birt.report.designer.ui/src/org/eclipse/birt/report/designer/internal/ui/dialogs/BlockPreferencePage.java
10452
/******************************************************************************* * Copyright (c) 2004 Actuate Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Actuate Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.birt.report.designer.internal.ui.dialogs; import org.eclipse.birt.report.designer.internal.ui.util.IHelpContextIds; import org.eclipse.birt.report.designer.internal.ui.util.UIUtil; import org.eclipse.birt.report.designer.nls.Messages; import org.eclipse.birt.report.designer.ui.views.attributes.providers.ChoiceSetFactory; import org.eclipse.birt.report.model.api.StyleHandle; import org.eclipse.birt.report.model.api.elements.ReportDesignConstants; import org.eclipse.birt.report.model.api.metadata.IChoice; import org.eclipse.birt.report.model.api.metadata.IChoiceSet; import org.eclipse.swt.layout.GridData; /** * Provides block preference page. */ public class BlockPreferencePage extends BaseStylePreferencePage { /** * the preference store( model ) for the preference page. */ private Object model; /** * field editors. * */ private ComboBoxMeasureFieldEditor lineHeight; private ComboBoxMeasureFieldEditor charSpacing; private ComboBoxMeasureFieldEditor wordSpacing; private ComboBoxMeasureFieldEditor textIndent; private ComboBoxFieldEditor verticalAlign; private ComboBoxFieldEditor textAlign; private ComboBoxFieldEditor textTrans; private ComboBoxFieldEditor whiteSpace; private ComboBoxFieldEditor display; private ComboBoxFieldEditor direction; // bidi_hcg /** * Constructs a new instance of block preference page. * * @param model * the preference store( model ) for the following field editors. */ public BlockPreferencePage( Object model ) { super( model ); setTitle( Messages.getString( "BlockPreferencePage.displayname.Title" ) ); //$NON-NLS-1$ this.model = model; } /* * (non-Javadoc) * * @see org.eclipse.jface.preference.FieldEditorPreferencePage#adjustGridLayout() */ protected void adjustGridLayout( ) { super.adjustGridLayout( ); ( (GridData) verticalAlign.getComboBoxControl( getFieldEditorParent( ) ) .getLayoutData( ) ).widthHint = 167; ( (GridData) textAlign.getComboBoxControl( getFieldEditorParent( ) ) .getLayoutData( ) ).widthHint = 167; ( (GridData) textTrans.getComboBoxControl( getFieldEditorParent( ) ) .getLayoutData( ) ).widthHint = 167; ( (GridData) whiteSpace.getComboBoxControl( getFieldEditorParent( ) ) .getLayoutData( ) ).widthHint = 167; ( (GridData) display.getComboBoxControl( getFieldEditorParent( ) ) .getLayoutData( ) ).widthHint = 167; // bidi_hcg ( (GridData) direction.getComboBoxControl( getFieldEditorParent( ) ) .getLayoutData( ) ).widthHint = 167; } /* * (non-Javadoc) * * @see org.eclipse.jface.preference.FieldEditorPreferencePage#createFieldEditors() */ protected void createFieldEditors( ) { // super.createFieldEditors( ); lineHeight = new ComboBoxMeasureFieldEditor( StyleHandle.LINE_HEIGHT_PROP, Messages.getString( ( (StyleHandle) model ).getPropertyHandle( StyleHandle.LINE_HEIGHT_PROP ) .getDefn( ) .getDisplayNameID( ) ), getChoiceArray( ChoiceSetFactory.getElementChoiceSet( ReportDesignConstants.STYLE_ELEMENT, StyleHandle.LINE_HEIGHT_PROP ) ), getChoiceArray( ChoiceSetFactory.getDimensionChoiceSet( ReportDesignConstants.STYLE_ELEMENT, StyleHandle.LINE_HEIGHT_PROP ) ), getFieldEditorParent( ) ); lineHeight.setDefaultUnit( ( (StyleHandle) model ).getPropertyHandle( StyleHandle.LINE_HEIGHT_PROP ) .getDefaultUnit( ) ); charSpacing = new ComboBoxMeasureFieldEditor( StyleHandle.LETTER_SPACING_PROP, Messages.getString( ( (StyleHandle) model ).getPropertyHandle( StyleHandle.LETTER_SPACING_PROP ) .getDefn( ) .getDisplayNameID( ) ), getChoiceArray( ChoiceSetFactory.getElementChoiceSet( ReportDesignConstants.STYLE_ELEMENT, StyleHandle.LETTER_SPACING_PROP ) ), getChoiceArray( ChoiceSetFactory.getDimensionChoiceSet( ReportDesignConstants.STYLE_ELEMENT, StyleHandle.LETTER_SPACING_PROP ) ), getFieldEditorParent( ) ); charSpacing.setDefaultUnit( ( (StyleHandle) model ).getPropertyHandle( StyleHandle.LETTER_SPACING_PROP ) .getDefaultUnit( ) ); wordSpacing = new ComboBoxMeasureFieldEditor( StyleHandle.WORD_SPACING_PROP, Messages.getString( ( (StyleHandle) model ).getPropertyHandle( StyleHandle.WORD_SPACING_PROP ) .getDefn( ) .getDisplayNameID( ) ), getChoiceArray( ChoiceSetFactory.getElementChoiceSet( ReportDesignConstants.STYLE_ELEMENT, StyleHandle.WORD_SPACING_PROP ) ), getChoiceArray( ChoiceSetFactory.getDimensionChoiceSet( ReportDesignConstants.STYLE_ELEMENT, StyleHandle.WORD_SPACING_PROP ) ), getFieldEditorParent( ) ); wordSpacing.setDefaultUnit( ( (StyleHandle) model ).getPropertyHandle( StyleHandle.WORD_SPACING_PROP ) .getDefaultUnit( ) ); verticalAlign = new ComboBoxFieldEditor( StyleHandle.VERTICAL_ALIGN_PROP, Messages.getString( ( (StyleHandle) model ).getPropertyHandle( StyleHandle.VERTICAL_ALIGN_PROP ) .getDefn( ) .getDisplayNameID( ) ), getChoiceArray( ChoiceSetFactory.getElementChoiceSet( ReportDesignConstants.STYLE_ELEMENT, StyleHandle.VERTICAL_ALIGN_PROP ), true ), getFieldEditorParent( ) ); textAlign = new ComboBoxFieldEditor( StyleHandle.TEXT_ALIGN_PROP, Messages.getString( ( (StyleHandle) model ).getPropertyHandle( StyleHandle.TEXT_ALIGN_PROP ) .getDefn( ) .getDisplayNameID( ) ), getChoiceArray( ChoiceSetFactory.getElementChoiceSet( ReportDesignConstants.STYLE_ELEMENT, StyleHandle.TEXT_ALIGN_PROP ), true ), getFieldEditorParent( ) ); textIndent = new ComboBoxMeasureFieldEditor( StyleHandle.TEXT_INDENT_PROP, Messages.getString( ( (StyleHandle) model ).getPropertyHandle( StyleHandle.TEXT_INDENT_PROP ) .getDefn( ) .getDisplayNameID( ) ), getChoiceArray( ChoiceSetFactory.getDimensionChoiceSet( ReportDesignConstants.STYLE_ELEMENT, StyleHandle.TEXT_INDENT_PROP ) ), getFieldEditorParent( ) ); textIndent.setDefaultUnit( ( (StyleHandle) model ).getPropertyHandle( StyleHandle.TEXT_INDENT_PROP ) .getDefaultUnit( ) ); textTrans = new ComboBoxFieldEditor( StyleHandle.TEXT_TRANSFORM_PROP, Messages.getString( ( (StyleHandle) model ).getPropertyHandle( StyleHandle.TEXT_TRANSFORM_PROP ) .getDefn( ) .getDisplayNameID( ) ), getChoiceArray( ChoiceSetFactory.getElementChoiceSet( ReportDesignConstants.STYLE_ELEMENT, StyleHandle.TEXT_TRANSFORM_PROP ) ), getFieldEditorParent( ) ); whiteSpace = new ComboBoxFieldEditor( StyleHandle.WHITE_SPACE_PROP, Messages.getString( ( (StyleHandle) model ).getPropertyHandle( StyleHandle.WHITE_SPACE_PROP ) .getDefn( ) .getDisplayNameID( ) ), getChoiceArray( ChoiceSetFactory.getElementChoiceSet( ReportDesignConstants.STYLE_ELEMENT, StyleHandle.WHITE_SPACE_PROP ) ), getFieldEditorParent( ) ); display = new ComboBoxFieldEditor( StyleHandle.DISPLAY_PROP, Messages.getString( ( (StyleHandle) model ).getPropertyHandle( StyleHandle.DISPLAY_PROP ) .getDefn( ) .getDisplayNameID( ) ), getChoiceArray( ChoiceSetFactory.getElementChoiceSet( ReportDesignConstants.STYLE_ELEMENT, StyleHandle.DISPLAY_PROP ) ), getFieldEditorParent( ) ); addField( lineHeight ); addField( charSpacing ); addField( wordSpacing ); addField( verticalAlign ); addField( textAlign ); addField( textIndent ); addField( textTrans ); addField( whiteSpace ); addField( display ); // bidi_hcg start direction = new ComboBoxFieldEditor( StyleHandle.TEXT_DIRECTION_PROP, Messages.getString( ( (StyleHandle) model ).getPropertyHandle( StyleHandle.TEXT_DIRECTION_PROP ) .getDefn( ) .getDisplayNameID( ) ), getChoiceArray( ChoiceSetFactory.getElementChoiceSet( ReportDesignConstants.STYLE_ELEMENT, StyleHandle.TEXT_DIRECTION_PROP ), true ), getFieldEditorParent( ) ); addField( direction ); // bidi_hcg end UIUtil.bindHelp( getFieldEditorParent( ).getParent( ), IHelpContextIds.STYLE_BUILDER_TEXTBLOCK_ID ); } /** * Gets choice array of the given choise set. * * @param set * The given choice set. * @return String[][]: The choice array of the key, which contains he names * (labels) and underlying values, will be arranged as: { {name1, * value1}, {name2, value2}, ...} */ private String[][] getChoiceArray( IChoiceSet set ) { return getChoiceArray( set, false ); } /** * Gets choice array of the given choise set. * * @param set * The given choice set. * @return String[][]: The choice array of the key, which contains he names * (labels) and underlying values, will be arranged as: { {name1, * value1}, {name2, value2}, ...} */ private String[][] getChoiceArray( IChoiceSet set, boolean addAuto ) { IChoice[] choices = set.getChoices( ); String[][] names = null; if ( choices.length > 0 ) { int offset = 0; if ( addAuto ) { offset = 1; names = new String[choices.length + 1][2]; names[0][0] = ChoiceSetFactory.CHOICE_AUTO; names[0][1] = ""; //$NON-NLS-1$ } else { names = new String[choices.length][2]; } for ( int i = 0; i < choices.length; i++ ) { names[i + offset][0] = choices[i].getDisplayName( ); names[i + offset][1] = choices[i].getName( ); } } else if ( addAuto ) { names = new String[][]{ { ChoiceSetFactory.CHOICE_AUTO, "" //$NON-NLS-1$ } }; } return names; } protected String[] getPreferenceNames( ) { return new String[]{ StyleHandle.LINE_HEIGHT_PROP, StyleHandle.LETTER_SPACING_PROP, StyleHandle.WORD_SPACING_PROP, StyleHandle.VERTICAL_ALIGN_PROP, StyleHandle.TEXT_ALIGN_PROP, StyleHandle.TEXT_INDENT_PROP, StyleHandle.TEXT_TRANSFORM_PROP, StyleHandle.WHITE_SPACE_PROP, StyleHandle.DISPLAY_PROP, StyleHandle.TEXT_DIRECTION_PROP, }; } }
epl-1.0
openhab/openhab2
bundles/org.openhab.binding.digitalstrom/src/main/java/org/openhab/binding/digitalstrom/internal/lib/manager/impl/StructureManagerImpl.java
15106
/** * Copyright (c) 2010-2020 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.binding.digitalstrom.internal.lib.manager.impl; import java.util.Collections; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import org.openhab.binding.digitalstrom.internal.lib.manager.ConnectionManager; import org.openhab.binding.digitalstrom.internal.lib.manager.StructureManager; import org.openhab.binding.digitalstrom.internal.lib.serverconnection.DsAPI; import org.openhab.binding.digitalstrom.internal.lib.structure.devices.AbstractGeneralDeviceInformations; import org.openhab.binding.digitalstrom.internal.lib.structure.devices.Circuit; import org.openhab.binding.digitalstrom.internal.lib.structure.devices.Device; import org.openhab.binding.digitalstrom.internal.lib.structure.devices.deviceparameters.CachedMeteringValue; import org.openhab.binding.digitalstrom.internal.lib.structure.devices.deviceparameters.impl.DSID; import com.google.gson.JsonArray; import com.google.gson.JsonObject; /** * The {@link StructureManagerImpl} is the implementation of the {@link StructureManager}. * * @author Michael Ochel - Initial contribution * @author Matthias Siegele - Initial contribution */ public class StructureManagerImpl implements StructureManager { private class ZoneGroupsNameAndIDMap { public final String zoneName; public final int zoneID; private final Map<Short, String> groupIdNames; private final Map<String, Short> groupNameIds; public ZoneGroupsNameAndIDMap(final int zoneID, final String zoneName, JsonArray groups) { this.zoneID = zoneID; this.zoneName = zoneName; groupIdNames = new HashMap<>(groups.size()); groupNameIds = new HashMap<>(groups.size()); for (int k = 0; k < groups.size(); k++) { short groupID = ((JsonObject) groups.get(k)).get("group").getAsShort(); String groupName = ((JsonObject) groups.get(k)).get("name").getAsString(); groupIdNames.put(groupID, groupName); groupNameIds.put(groupName, groupID); } } public String getGroupName(Short groupID) { return groupIdNames.get(groupID); } public short getGroupID(String groupName) { final Short tmp = groupNameIds.get(groupName); return tmp != null ? tmp : -1; } } /** * Query to get all zone and group names. Can be executed with {@link DsAPI#query(String, String)} or * {@link DsAPI#query2(String, String)}. */ public static final String ZONE_GROUP_NAMES = "/apartment/zones/*(ZoneID,name)/groups/*(group,name)"; private final Map<Integer, Map<Short, List<Device>>> zoneGroupDeviceMap = Collections .synchronizedMap(new HashMap<>()); private final Map<DSID, Device> deviceMap = Collections.synchronizedMap(new HashMap<>()); private final Map<DSID, Circuit> circuitMap = Collections.synchronizedMap(new HashMap<>()); private final Map<String, DSID> dSUIDToDSIDMap = Collections.synchronizedMap(new HashMap<>()); private Map<Integer, ZoneGroupsNameAndIDMap> zoneGroupIdNameMap; private Map<String, ZoneGroupsNameAndIDMap> zoneGroupNameIdMap; /** * Creates a new {@link StructureManagerImpl} with the {@link Device}s of the given referenceDeviceList. * * @param referenceDeviceList to add */ public StructureManagerImpl(List<Device> referenceDeviceList) { handleStructure(referenceDeviceList); } /** * Creates a new {@link StructureManagerImpl} with the {@link Device}s of the given referenceDeviceList. * * @param referenceDeviceList to add * @param referenceCircuitList to add */ public StructureManagerImpl(List<Device> referenceDeviceList, List<Circuit> referenceCircuitList) { handleStructure(referenceDeviceList); addCircuitList(referenceCircuitList); } /** * Creates a new {@link StructureManagerImpl} without {@link Device}s. */ public StructureManagerImpl() { } @Override public boolean generateZoneGroupNames(ConnectionManager connectionManager) { JsonObject resultJsonObj = connectionManager.getDigitalSTROMAPI().query(connectionManager.getSessionToken(), ZONE_GROUP_NAMES); if (resultJsonObj != null && resultJsonObj.get("zones") instanceof JsonArray) { JsonArray zones = (JsonArray) resultJsonObj.get("zones"); if (zoneGroupIdNameMap == null) { zoneGroupIdNameMap = new HashMap<>(zones.size()); zoneGroupNameIdMap = new HashMap<>(zones.size()); } if (zones != null) { for (int i = 0; i < zones.size(); i++) { if (((JsonObject) zones.get(i)).get("groups") instanceof JsonArray) { JsonArray groups = (JsonArray) ((JsonObject) zones.get(i)).get("groups"); ZoneGroupsNameAndIDMap zoneGoupIdNameMap = new ZoneGroupsNameAndIDMap( ((JsonObject) zones.get(i)).get("ZoneID").getAsInt(), ((JsonObject) zones.get(i)).get("name").getAsString(), groups); zoneGroupIdNameMap.put(zoneGoupIdNameMap.zoneID, zoneGoupIdNameMap); zoneGroupNameIdMap.put(zoneGoupIdNameMap.zoneName, zoneGoupIdNameMap); } } } } return true; } @Override public String getZoneName(int zoneID) { if (zoneGroupIdNameMap == null) { return null; } final ZoneGroupsNameAndIDMap tmp = zoneGroupIdNameMap.get(zoneID); return tmp != null ? tmp.zoneName : null; } @Override public String getZoneGroupName(int zoneID, short groupID) { if (zoneGroupIdNameMap == null) { return null; } final ZoneGroupsNameAndIDMap tmp = zoneGroupIdNameMap.get(zoneID); return tmp != null ? tmp.getGroupName(groupID) : null; } @Override public int getZoneId(String zoneName) { if (zoneGroupNameIdMap == null) { return -1; } final ZoneGroupsNameAndIDMap tmp = zoneGroupNameIdMap.get(zoneName); return tmp != null ? tmp.zoneID : -1; } @Override public boolean checkZoneID(int zoneID) { return getGroupsFromZoneX(zoneID) != null; } @Override public boolean checkZoneGroupID(int zoneID, short groupID) { final Map<Short, List<Device>> tmp = getGroupsFromZoneX(zoneID); return tmp != null ? tmp.get(groupID) != null : false; } @Override public short getZoneGroupId(String zoneName, String groupName) { if (zoneGroupNameIdMap == null) { return -1; } final ZoneGroupsNameAndIDMap tmp = zoneGroupNameIdMap.get(zoneName); return tmp != null ? tmp.getGroupID(groupName) : -1; } @Override public Map<DSID, Device> getDeviceMap() { return new HashMap<>(deviceMap); } private void putDeviceToHashMap(Device device) { if (device.getDSID() != null) { deviceMap.put(device.getDSID(), device); addDSIDtoDSUID((AbstractGeneralDeviceInformations) device); } } /** * This method build the digitalSTROM structure as an {@link HashMap} with the zone id as key * and an {@link HashMap} as value. This {@link HashMap} has the group id as key and a {@link List} * with all digitalSTROM {@link Device}s.<br> * <br> * <b>Note:</b> the zone id 0 is the broadcast address and the group id 0, too. */ private void handleStructure(List<Device> deviceList) { Map<Short, List<Device>> groupXHashMap = new HashMap<>(); groupXHashMap.put((short) 0, deviceList); zoneGroupDeviceMap.put(0, groupXHashMap); for (Device device : deviceList) { addDeviceToStructure(device); } } @Override public Map<DSID, Device> getDeviceHashMapReference() { return deviceMap; } @Override public Map<Integer, Map<Short, List<Device>>> getStructureReference() { return zoneGroupDeviceMap; } @Override public Map<Short, List<Device>> getGroupsFromZoneX(int zoneID) { return zoneGroupDeviceMap.get(zoneID); } @Override public List<Device> getReferenceDeviceListFromZoneXGroupX(int zoneID, short groupID) { final Map<Short, List<Device>> tmp = getGroupsFromZoneX(zoneID); return tmp != null ? tmp.get(groupID) : null; } @Override public Device getDeviceByDSID(String dSID) { return getDeviceByDSID(new DSID(dSID)); } @Override public Device getDeviceByDSID(DSID dSID) { return deviceMap.get(dSID); } @Override public Device getDeviceByDSUID(String dSUID) { final DSID tmp = dSUIDToDSIDMap.get(dSUID); return tmp != null ? getDeviceByDSID(tmp) : null; } @Override public void updateDevice(int oldZone, List<Short> oldGroups, Device device) { int intOldZoneID = oldZone; if (intOldZoneID == -1) { intOldZoneID = device.getZoneId(); } deleteDevice(intOldZoneID, oldGroups, device); addDeviceToStructure(device); } @Override public void updateDevice(Device device) { if (device != null) { int oldZoneID = -1; List<Short> oldGroups = null; Device internalDevice = this.getDeviceByDSID(device.getDSID()); if (internalDevice != null) { if (device.getZoneId() != internalDevice.getZoneId()) { oldZoneID = internalDevice.getZoneId(); internalDevice.setZoneId(device.getZoneId()); } if (!internalDevice.getGroups().equals(device.getGroups())) { oldGroups = internalDevice.getGroups(); internalDevice.setGroups(device.getGroups()); } if (deleteDevice(oldZoneID, oldGroups, internalDevice)) { addDeviceToStructure(internalDevice); } } } } @Override public void deleteDevice(Device device) { dSUIDToDSIDMap.remove(device.getDSUID()); deviceMap.remove(device.getDSID()); deleteDevice(device.getZoneId(), device.getGroups(), device); } private boolean deleteDevice(int zoneID, List<Short> groups, Device device) { List<Short> intGroups = groups; int intZoneID = zoneID; if (intGroups != null || intZoneID >= 0) { if (intGroups == null) { intGroups = device.getGroups(); } if (intZoneID == -1) { intZoneID = device.getZoneId(); } for (Short groupID : intGroups) { List<Device> deviceList = getReferenceDeviceListFromZoneXGroupX(intZoneID, groupID); if (deviceList != null) { deviceList.remove(device); } deviceList = getReferenceDeviceListFromZoneXGroupX(0, groupID); if (deviceList != null) { deviceList.remove(device); } } return true; } return false; } @Override public void addDeviceToStructure(Device device) { putDeviceToHashMap(device); addDevicetoZoneXGroupX(0, (short) 0, device); int zoneID = device.getZoneId(); addDevicetoZoneXGroupX(zoneID, (short) 0, device); for (Short groupID : device.getGroups()) { addDevicetoZoneXGroupX(zoneID, groupID, device); if (groupID <= 16) { addDevicetoZoneXGroupX(0, groupID, device); } } } private void addDevicetoZoneXGroupX(int zoneID, short groupID, Device device) { Map<Short, List<Device>> groupXHashMap = zoneGroupDeviceMap.get(zoneID); if (groupXHashMap == null) { groupXHashMap = new HashMap<>(); zoneGroupDeviceMap.put(zoneID, groupXHashMap); } List<Device> groupDeviceList = groupXHashMap.get(groupID); if (groupDeviceList == null) { groupDeviceList = new LinkedList<>(); groupDeviceList.add(device); groupXHashMap.put(groupID, groupDeviceList); } else { if (!groupDeviceList.contains(device)) { groupDeviceList.add(device); } } } @Override public Set<Integer> getZoneIDs() { return zoneGroupDeviceMap.keySet(); } @Override public void addCircuitList(List<Circuit> referenceCircuitList) { for (Circuit circuit : referenceCircuitList) { addCircuit(circuit); } } @Override public Circuit addCircuit(Circuit circuit) { addDSIDtoDSUID((AbstractGeneralDeviceInformations) circuit); return circuitMap.put(circuit.getDSID(), circuit); } private void addDSIDtoDSUID(AbstractGeneralDeviceInformations deviceInfo) { if (deviceInfo.getDSID() != null) { dSUIDToDSIDMap.put(deviceInfo.getDSUID(), deviceInfo.getDSID()); } } @Override public Circuit getCircuitByDSID(DSID dSID) { return circuitMap.get(dSID); } @Override public Circuit getCircuitByDSUID(String dSUID) { final DSID tmp = dSUIDToDSIDMap.get(dSUID); return tmp != null ? getCircuitByDSID(tmp) : null; } @Override public Circuit getCircuitByDSID(String dSID) { return getCircuitByDSID(new DSID(dSID)); } @Override public Circuit updateCircuitConfig(Circuit newCircuit) { Circuit intCircuit = circuitMap.get(newCircuit.getDSID()); if (intCircuit != null && !intCircuit.equals(newCircuit)) { for (CachedMeteringValue meteringValue : intCircuit.getAllCachedMeteringValues()) { newCircuit.addMeteringValue(meteringValue); } if (intCircuit.isListenerRegisterd()) { newCircuit.registerDeviceStatusListener(intCircuit.getDeviceStatusListener()); } } return addCircuit(newCircuit); } @Override public Circuit deleteCircuit(DSID dSID) { return circuitMap.remove(dSID); } @Override public Circuit deleteCircuit(String dSUID) { return deleteCircuit(dSUIDToDSIDMap.get(dSUID)); } @Override public Map<DSID, Circuit> getCircuitMap() { return new HashMap<>(circuitMap); } }
epl-1.0
mickey4u/new_mart
addons/binding/org.openhab.binding.squeezebox/src/main/java/org/openhab/binding/squeezebox/handler/SqueezeBoxServerHandler.java
30058
/** * Copyright (c) 2014-2015 openHAB UG (haftungsbeschraenkt) and others. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package org.openhab.binding.squeezebox.handler; import static org.openhab.binding.squeezebox.SqueezeBoxBindingConstants.SQUEEZEBOXSERVER_THING_TYPE; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.net.Socket; import java.net.URLDecoder; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import org.apache.commons.lang.StringUtils; import org.eclipse.smarthome.core.thing.Bridge; import org.eclipse.smarthome.core.thing.ChannelUID; import org.eclipse.smarthome.core.thing.Thing; import org.eclipse.smarthome.core.thing.ThingStatus; import org.eclipse.smarthome.core.thing.ThingStatusDetail; import org.eclipse.smarthome.core.thing.ThingTypeUID; import org.eclipse.smarthome.core.thing.binding.BaseBridgeHandler; import org.eclipse.smarthome.core.thing.binding.ThingHandler; import org.eclipse.smarthome.core.types.Command; import org.openhab.binding.squeezebox.config.SqueezeBoxServerConfig; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Handles connection and event handling to a SqueezeBox Server. * * @author Markus Wolters * @author Ben Jones * @author Dan Cunningham (OH2 Port) */ public class SqueezeBoxServerHandler extends BaseBridgeHandler { private Logger logger = LoggerFactory.getLogger(SqueezeBoxServerHandler.class); public final static Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections .singleton(SQUEEZEBOXSERVER_THING_TYPE); // time in seconds to try to reconnect private int RECONNECT_TIME = 60; // the value by which the volume is changed by each INCREASE or // DECREASE-Event private static final int VOLUME_CHANGE_SIZE = 5; private static final String NEW_LINE = System.getProperty("line.separator"); private List<SqueezeBoxPlayerEventListener> squeezeBoxPlayerListeners = Collections .synchronizedList(new ArrayList<SqueezeBoxPlayerEventListener>()); private Map<String, SqueezeBoxPlayer> players = Collections .synchronizedMap(new HashMap<String, SqueezeBoxPlayer>()); // client socket and listener thread private Socket clientSocket; private SqueezeServerListener listener; private ScheduledFuture<?> reconnectFuture; private String host; private int cliport; private int webport; public SqueezeBoxServerHandler(Bridge bridge) { super(bridge); } @Override public void initialize() { scheduler.schedule(new Runnable() { @Override public void run() { connect(); } }, 0, TimeUnit.SECONDS); }; @Override public void dispose() { cancelReconnect(); disconnect(); }; @Override public void handleCommand(ChannelUID channelUID, Command command) { } /** * Checks if we have a connection to the Server * * @return */ public synchronized boolean isConnected() { if (clientSocket == null) { return false; } // NOTE: isConnected() returns true once a connection is made and will // always return true even after the socket is closed // http://stackoverflow.com/questions/10163358/ return clientSocket.isConnected() && !clientSocket.isClosed(); } public void mute(String mac) { setVolume(mac, 0); } public void unMute(String mac, int unmuteVolume) { setVolume(mac, unmuteVolume); } public void powerOn(String mac) { sendCommand(mac + " power 1"); } public void powerOff(String mac) { sendCommand(mac + " power 0"); } public void syncPlayer(String mac, String player2mac) { sendCommand(mac + " sync " + player2mac); } public void unSyncPlayer(String mac) { sendCommand(mac + " sync -"); } public void play(String mac) { sendCommand(mac + " play"); } public void playUrl(String mac, String url) { sendCommand(mac + " playlist play " + url); } public void pause(String mac) { sendCommand(mac + " pause 1"); } public void unPause(String mac) { sendCommand(mac + " pause 0"); } public void stop(String mac) { sendCommand(mac + " stop"); } public void prev(String mac) { sendCommand(mac + " playlist index -1"); } public void next(String mac) { sendCommand(mac + " playlist index +1"); } public void clearPlaylist(String mac) { sendCommand(mac + " playlist clear"); } public void deletePlaylistItem(String mac, int playlistIndex) { sendCommand(mac + " playlist delete " + playlistIndex); } public void playPlaylistItem(String mac, int playlistIndex) { sendCommand(mac + " playlist index " + playlistIndex); } public void addPlaylistItem(String mac, String url) { sendCommand(mac + " playlist add " + url); } public void setPlayingTime(String mac, int time) { sendCommand(mac + " time " + time); } public void setRepeatMode(String mac, int repeatMode) { sendCommand(mac + " playlist repeat " + repeatMode); } public void setShuffleMode(String mac, int shuffleMode) { sendCommand(mac + " playlist shuffle " + shuffleMode); } public void volumeUp(String mac, int currentVolume) { setVolume(mac, currentVolume + VOLUME_CHANGE_SIZE); } public void volumeDown(String mac, int currentVolume) { setVolume(mac, currentVolume - VOLUME_CHANGE_SIZE); } public void setVolume(String mac, int volume) { if (0 > volume) { volume = 0; } else if (volume > 100) { volume = 100; } sendCommand(mac + " mixer volume " + String.valueOf(volume)); } public void showString(String mac, String line) { showString(mac, line, 5); } public void showString(String mac, String line, int duration) { sendCommand(mac + " show line1:" + line + " duration:" + String.valueOf(duration)); } public void showStringHuge(String mac, String line) { showStringHuge(mac, line, 5); } public void showStringHuge(String mac, String line, int duration) { sendCommand(mac + " show line1:" + line + " font:huge duration:" + String.valueOf(duration)); } public void showStrings(String mac, String line1, String line2) { showStrings(mac, line1, line2, 5); } public void showStrings(String mac, String line1, String line2, int duration) { sendCommand(mac + " show line1:" + line1 + " line2:" + line2 + " duration:" + String.valueOf(duration)); } /** * Send a generic command to a given player * * @param playerId * @param command */ public void playerCommand(String mac, String command) { sendCommand(mac + " " + command); } /** * Ask for player list */ public void requestPlayers() { sendCommand("players 0"); } /** * Send a command to the Squeeze Server. */ private synchronized void sendCommand(String command) { if (getThing().getStatus() != ThingStatus.ONLINE) { return; } if (!isConnected()) { logger.debug("No connection to SqueezeServer, will attempt to reconnect now..."); connect(); if (!isConnected()) { logger.error("Failed to reconnect to SqueezeServer, unable to send command {}", command); return; } } logger.debug("Sending command: {}", command); try { BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream())); writer.write(command + NEW_LINE); writer.flush(); } catch (IOException e) { logger.error("Error while sending command to Squeeze Server (" + command + ")", e); } } /** * Connects to a SqueezeBox Server */ private void connect() { disconnect(); SqueezeBoxServerConfig config = getConfigAs(SqueezeBoxServerConfig.class); this.host = config.ipAddress; this.cliport = config.cliport; this.webport = config.webport; if (StringUtils.isEmpty(this.host)) { updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.CONFIGURATION_ERROR, "host is not set"); return; } try { clientSocket = new Socket(host, cliport); } catch (IOException e) { updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.COMMUNICATION_ERROR, e.getMessage()); return; } try { listener = new SqueezeServerListener(); listener.start(); logger.info("Squeeze Server connection started to server " + this.host); } catch (IllegalThreadStateException e) { updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage()); } } /** * Disconnects from a SqueezeBox Server */ private void disconnect() { try { if (listener != null) { listener.terminate(); } if (clientSocket != null) { clientSocket.close(); } } catch (Exception e) { logger.trace("Error attempting to disconnect from Squeeze Server", e); return; } finally { clientSocket = null; listener = null; } players.clear(); logger.trace("Squeeze Server connection stopped."); } private class SqueezeServerListener extends Thread { private boolean terminate = false; public SqueezeServerListener() { super("Squeeze Server Listener"); } public void terminate() { logger.debug("Squeeze Server listener being terminated"); this.terminate = true; } @Override public void run() { BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); updateStatus(ThingStatus.ONLINE); requestPlayers(); sendCommand("listen 1"); String message; while (!terminate && (message = reader.readLine()) != null) { logger.debug("Message received: {}", message); if (message.startsWith("listen 1")) { continue; } if (message.startsWith("players 0")) { handlePlayersList(message); } else { handlePlayerUpdate(message); } } } catch (IOException e) { if (!terminate) { updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage()); scheduleReconnect(); } } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { // ignore } reader = null; } } logger.debug("Squeeze Server listener exiting."); } private String decode(String raw) { try { return URLDecoder.decode(raw, "UTF-8"); } catch (UnsupportedEncodingException e) { logger.debug("Failed to decode '" + raw + "'", e); return null; } } private void handlePlayersList(String message) { String[] playersList = decode(message).split("playerindex:\\d+\\s"); for (String playerParams : playersList) { String[] parameterList = playerParams.split("\\s"); // parse out the MAC address first String macAddress = null; for (String parameter : parameterList) { if (parameter.contains("playerid")) { macAddress = parameter.substring(parameter.indexOf(":") + 1); break; } } // if none found then ignore this set of params if (macAddress == null) { continue; } // if we already know about it, ignore this set of params if (players.containsKey(macAddress)) { continue; } final SqueezeBoxPlayer player = new SqueezeBoxPlayer(); player.setMacAddress(macAddress); // populate the player state for (String parameter : parameterList) { if (parameter.contains("ip")) { player.setIpAddr(parameter.substring(parameter.indexOf(":") + 1)); } else if (parameter.contains("uuid")) { player.setUuid(parameter.substring(parameter.indexOf(":") + 1)); } else if (parameter.contains("name")) { player.setName(parameter.substring(parameter.indexOf(":") + 1)); } else if (parameter.contains("model")) { player.setModel(parameter.substring(parameter.indexOf(":") + 1)); } } players.put(macAddress, player); updatePlayer(new PlayerUpdateEvent() { @Override public void updateListener(SqueezeBoxPlayerEventListener listener) { listener.playerAdded(player); } }); // tell the server we want to subscribe to player updates sendCommand(player.getMacAddress() + " status - 1 subscribe:10 tags:yagJlN"); } } private void handlePlayerUpdate(String message) { String[] messageParts = message.split("\\s"); if (messageParts.length < 2) { logger.warn("Invalid message - expecting at least 2 parts. Ignoring."); return; } final String mac = decode(messageParts[0]); // get the message type String messageType = messageParts[1]; if (messageType.equals("status")) { handleStatusMessage(mac, messageParts); } else if (messageType.equals("playlist")) { handlePlaylistMessage(mac, messageParts); } else if (messageType.equals("prefset")) { handlePrefsetMessage(mac, messageParts); } else if (messageType.equals("ir")) { final String ircode = messageParts[2]; updatePlayer(new PlayerUpdateEvent() { @Override public void updateListener(SqueezeBoxPlayerEventListener listener) { listener.irCodeChangeEvent(mac, ircode); } }); } else if (messageType.equals("power")) { // ignore these for now // player.setPowered(messageParts[1].equals("1")); } else if (messageType.equals("play") || messageType.equals("pause") || messageType.equals("stop")) { // ignore these for now // player.setMode(Mode.valueOf(messageType)); } else if (messageType.equals("mixer") || messageType.equals("menustatus") || messageType.equals("button")) { // ignore these for now } else { logger.debug("Unhandled message type '{}'. Ignoring.", messageType); } } private void handleStatusMessage(final String mac, String[] messageParts) { for (String messagePart : messageParts) { // Parameter Power if (messagePart.startsWith("power%3A")) { String value = messagePart.substring("power%3A".length()); final boolean power = value.matches("1"); updatePlayer(new PlayerUpdateEvent() { @Override public void updateListener(SqueezeBoxPlayerEventListener listener) { listener.powerChangeEvent(mac, power); } }); } // Parameter Volume else if (messagePart.startsWith("mixer%20volume%3A")) { String value = messagePart.substring("mixer%20volume%3A".length()); final int volume = (int) Double.parseDouble(value); updatePlayer(new PlayerUpdateEvent() { @Override public void updateListener(SqueezeBoxPlayerEventListener listener) { listener.volumeChangeEvent(mac, volume); ; } }); } // Parameter Mode else if (messagePart.startsWith("mode%3A")) { final String mode = messagePart.substring("mode%3A".length()); updatePlayer(new PlayerUpdateEvent() { @Override public void updateListener(SqueezeBoxPlayerEventListener listener) { listener.modeChangeEvent(mac, mode); } }); } // Parameter Playing Time else if (messagePart.startsWith("time%3A")) { String value = messagePart.substring("time%3A".length()); final int time = (int) Double.parseDouble(value); updatePlayer(new PlayerUpdateEvent() { @Override public void updateListener(SqueezeBoxPlayerEventListener listener) { listener.currentPlayingTimeEvent(mac, time); } }); } // Parameter Playing Playlist Index else if (messagePart.startsWith("playlist_cur_index%3A")) { String value = messagePart.substring("playlist_cur_index%3A".length()); // player.setCurrentPlaylistIndex((int) // Integer.parseInt(value)); final int index = (int) Double.parseDouble(value); updatePlayer(new PlayerUpdateEvent() { @Override public void updateListener(SqueezeBoxPlayerEventListener listener) { listener.currentPlaylistIndexEvent(mac, index); } }); } // Parameter Playlist Number Tracks else if (messagePart.startsWith("playlist_tracks%3A")) { String value = messagePart.substring("playlist_tracks%3A".length()); final int track = (int) Double.parseDouble(value); updatePlayer(new PlayerUpdateEvent() { @Override public void updateListener(SqueezeBoxPlayerEventListener listener) { listener.numberPlaylistTracksEvent(mac, track); } }); } // Parameter Playlist Repeat Mode else if (messagePart.startsWith("playlist%20repeat%3A")) { String value = messagePart.substring("playlist%20repeat%3A".length()); final int repeat = (int) Double.parseDouble(value); updatePlayer(new PlayerUpdateEvent() { @Override public void updateListener(SqueezeBoxPlayerEventListener listener) { listener.currentPlaylistRepeatEvent(mac, repeat); } }); } // Parameter Playlist Shuffle Mode else if (messagePart.startsWith("playlist%20shuffle%3A")) { String value = messagePart.substring("playlist%20shuffle%3A".length()); final int shuffle = (int) Double.parseDouble(value); updatePlayer(new PlayerUpdateEvent() { @Override public void updateListener(SqueezeBoxPlayerEventListener listener) { listener.currentPlaylistShuffleEvent(mac, shuffle); } }); } // Parameter Title else if (messagePart.startsWith("title%3A")) { final String value = messagePart.substring("title%3A".length()); updatePlayer(new PlayerUpdateEvent() { @Override public void updateListener(SqueezeBoxPlayerEventListener listener) { listener.titleChangeEvent(mac, decode(value)); } }); } // Parameter Remote Title (radio) else if (messagePart.startsWith("remote_title%3A")) { final String value = messagePart.substring("remote_title%3A".length()); updatePlayer(new PlayerUpdateEvent() { @Override public void updateListener(SqueezeBoxPlayerEventListener listener) { listener.remoteTitleChangeEvent(mac, decode(value)); } }); } // Parameter Artist else if (messagePart.startsWith("artist%3A")) { final String value = messagePart.substring("artist%3A".length()); updatePlayer(new PlayerUpdateEvent() { @Override public void updateListener(SqueezeBoxPlayerEventListener listener) { listener.artistChangeEvent(mac, decode(value)); } }); } // Parameter Album else if (messagePart.startsWith("album%3A")) { final String value = messagePart.substring("album%3A".length()); updatePlayer(new PlayerUpdateEvent() { @Override public void updateListener(SqueezeBoxPlayerEventListener listener) { listener.albumChangeEvent(mac, decode(value)); } }); } // Parameter Genre else if (messagePart.startsWith("genre%3A")) { final String value = messagePart.substring("genre%3A".length()); updatePlayer(new PlayerUpdateEvent() { @Override public void updateListener(SqueezeBoxPlayerEventListener listener) { listener.genreChangeEvent(mac, decode(value)); } }); } // Parameter Year else if (messagePart.startsWith("year%3A")) { final String value = messagePart.substring("year%3A".length()); updatePlayer(new PlayerUpdateEvent() { @Override public void updateListener(SqueezeBoxPlayerEventListener listener) { listener.yearChangeEvent(mac, decode(value)); } }); } // Parameter Artwork else if (messagePart.startsWith("artwork_track_id%3A")) { String url = messagePart.substring("artwork_track_id%3A".length()); // NOTE: what is returned if not an artwork id? i.e. if a // space? if (!url.startsWith(" ")) { url = "http://" + host + ":" + webport + "/music/" + url + "/cover.jpg"; } final String value = url; updatePlayer(new PlayerUpdateEvent() { @Override public void updateListener(SqueezeBoxPlayerEventListener listener) { listener.coverArtChangeEvent(mac, decode(value)); } }); } } } private void handlePlaylistMessage(final String mac, String[] messageParts) { String action = messageParts[2]; String mode = "play"; if (action.equals("newsong")) { mode = "play"; } else if (action.equals("pause")) { mode = messageParts[3].equals("0") ? "play" : "pause"; } else if (action.equals("stop")) { mode = "stop"; } final String value = mode; updatePlayer(new PlayerUpdateEvent() { @Override public void updateListener(SqueezeBoxPlayerEventListener listener) { listener.modeChangeEvent(mac, value); } }); } private void handlePrefsetMessage(final String mac, String[] messageParts) { if (messageParts.length < 5) { return; } // server prefsets if (messageParts[2].equals("server")) { String function = messageParts[3]; String value = messageParts[4]; if (function.equals("power")) { final boolean power = value.equals("1"); updatePlayer(new PlayerUpdateEvent() { @Override public void updateListener(SqueezeBoxPlayerEventListener listener) { listener.powerChangeEvent(mac, power); } }); } else if (function.equals("volume")) { final int volume = (int) Double.parseDouble(value); updatePlayer(new PlayerUpdateEvent() { @Override public void updateListener(SqueezeBoxPlayerEventListener listener) { listener.volumeChangeEvent(mac, volume); ; } }); } } } } /** * Interface to allow us to pass function call-backs to SqueezeBox Player * Event Listeners * * @author Dan Cunningham * */ interface PlayerUpdateEvent { void updateListener(SqueezeBoxPlayerEventListener listener); } /** * Update Listeners and child Squeeze Player Things * * @param event */ private void updatePlayer(PlayerUpdateEvent event) { // update listeners like disco services for (SqueezeBoxPlayerEventListener listener : squeezeBoxPlayerListeners) { event.updateListener(listener); } // update our children Bridge bridge = getThing(); if (bridge == null) { return; } List<Thing> things = bridge.getThings(); for (Thing thing : things) { ThingHandler handler = thing.getHandler(); if (handler instanceof SqueezeBoxPlayerEventListener && !squeezeBoxPlayerListeners.contains(handler)) { event.updateListener((SqueezeBoxPlayerEventListener) handler); } } } /** * Adds a listener for player events * * @param squeezeBoxPlayerListener * @return */ public boolean registerSqueezeBoxPlayerListener(SqueezeBoxPlayerEventListener squeezeBoxPlayerListener) { return squeezeBoxPlayerListeners.add(squeezeBoxPlayerListener); } /** * Removes a listener from player events * * @param squeezeBoxPlayerListener * @return */ public boolean unregisterSqueezeBoxPlayerListener(SqueezeBoxPlayerEventListener squeezeBoxPlayerListener) { return squeezeBoxPlayerListeners.remove(squeezeBoxPlayerListener); } /** * Removed a player from our known list of players, will populate again if * player is seen * * @param mac */ public void removePlayerCache(String mac) { players.remove(mac); } /** * Schedule the server to try and reconnect */ private void scheduleReconnect() { cancelReconnect(); reconnectFuture = scheduler.schedule(new Runnable() { @Override public void run() { connect(); } }, RECONNECT_TIME, TimeUnit.SECONDS); } /** * Clears our reconnect job if exists */ private void cancelReconnect() { if (reconnectFuture != null) { reconnectFuture.cancel(true); } } }
epl-1.0
boniatillo-com/PhaserEditor
source/thirdparty/jsdt/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/cleanup/CodeStyleTabPage.java
5391
/******************************************************************************* * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.wst.jsdt.internal.ui.preferences.cleanup; import java.util.Map; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Group; import org.eclipse.wst.jsdt.internal.corext.fix.CleanUpConstants; import org.eclipse.wst.jsdt.internal.ui.fix.ControlStatementsCleanUp; import org.eclipse.wst.jsdt.internal.ui.fix.ExpressionsCleanUp; import org.eclipse.wst.jsdt.internal.ui.fix.ICleanUp; import org.eclipse.wst.jsdt.internal.ui.fix.VariableDeclarationCleanUp; import org.eclipse.wst.jsdt.internal.ui.preferences.formatter.ModifyDialog; public final class CodeStyleTabPage extends CleanUpTabPage { public CodeStyleTabPage(ModifyDialog dialog, Map values) { this(dialog, values, false); } public CodeStyleTabPage(IModificationListener listener, Map values, boolean isSaveParticipantConfiguration) { super(listener, values, isSaveParticipantConfiguration); } protected ICleanUp[] createPreviewCleanUps(Map values) { return new ICleanUp[] { new ControlStatementsCleanUp(values), new ExpressionsCleanUp(values), new VariableDeclarationCleanUp(values) }; } protected void doCreatePreferences(Composite composite, int numColumns) { Group controlGroup= createGroup(numColumns, composite, CleanUpMessages.CodeStyleTabPage_GroupName_ControlStatments); final CheckboxPreference useBlockPref= createCheckboxPref(controlGroup, numColumns, CleanUpMessages.CodeStyleTabPage_CheckboxName_UseBlocks, CleanUpConstants.CONTROL_STATEMENTS_USE_BLOCKS, CleanUpModifyDialog.FALSE_TRUE); intent(controlGroup); final RadioPreference useBlockAlwaysPref= createRadioPref(controlGroup, numColumns - 1, CleanUpMessages.CodeStyleTabPage_RadioName_AlwaysUseBlocks, CleanUpConstants.CONTROL_STATMENTS_USE_BLOCKS_ALWAYS, CleanUpModifyDialog.FALSE_TRUE); intent(controlGroup); final RadioPreference useBlockJDTStylePref= createRadioPref(controlGroup, numColumns - 1, CleanUpMessages.CodeStyleTabPage_RadioName_UseBlocksSpecial, CleanUpConstants.CONTROL_STATMENTS_USE_BLOCKS_NO_FOR_RETURN_AND_THROW, CleanUpModifyDialog.FALSE_TRUE); intent(controlGroup); final RadioPreference useBlockNeverPref= createRadioPref(controlGroup, numColumns - 1, CleanUpMessages.CodeStyleTabPage_RadioName_NeverUseBlocks, CleanUpConstants.CONTROL_STATMENTS_USE_BLOCKS_NEVER, CleanUpModifyDialog.FALSE_TRUE); registerSlavePreference(useBlockPref, new RadioPreference[] {useBlockAlwaysPref, useBlockJDTStylePref, useBlockNeverPref}); Group expressionsGroup= createGroup(numColumns, composite, CleanUpMessages.CodeStyleTabPage_GroupName_Expressions); final CheckboxPreference useParenthesesPref= createCheckboxPref(expressionsGroup, numColumns, CleanUpMessages.CodeStyleTabPage_CheckboxName_UseParentheses, CleanUpConstants.EXPRESSIONS_USE_PARENTHESES, CleanUpModifyDialog.FALSE_TRUE); intent(expressionsGroup); final RadioPreference useParenthesesAlwaysPref= createRadioPref(expressionsGroup, 1, CleanUpMessages.CodeStyleTabPage_RadioName_AlwaysUseParantheses, CleanUpConstants.EXPRESSIONS_USE_PARENTHESES_ALWAYS, CleanUpModifyDialog.FALSE_TRUE); final RadioPreference useParenthesesNeverPref= createRadioPref(expressionsGroup, 1, CleanUpMessages.CodeStyleTabPage_RadioName_NeverUseParantheses, CleanUpConstants.EXPRESSIONS_USE_PARENTHESES_NEVER, CleanUpModifyDialog.FALSE_TRUE); registerSlavePreference(useParenthesesPref, new RadioPreference[] {useParenthesesAlwaysPref, useParenthesesNeverPref}); // Group variableGroup= createGroup(numColumns, composite, CleanUpMessages.CodeStyleTabPage_GroupName_VariableDeclarations); // final CheckboxPreference useFinalPref= createCheckboxPref(variableGroup, numColumns, CleanUpMessages.CodeStyleTabPage_CheckboxName_UseFinal, CleanUpConstants.VARIABLE_DECLARATIONS_USE_FINAL, CleanUpModifyDialog.FALSE_TRUE); // intent(variableGroup); // final CheckboxPreference useFinalFieldsPref= createCheckboxPref(variableGroup, 1, CleanUpMessages.CodeStyleTabPage_CheckboxName_UseFinalForFields, CleanUpConstants.VARIABLE_DECLARATIONS_USE_FINAL_PRIVATE_FIELDS, CleanUpModifyDialog.FALSE_TRUE); // final CheckboxPreference useFinalParametersPref= createCheckboxPref(variableGroup, 1, CleanUpMessages.CodeStyleTabPage_CheckboxName_UseFinalForParameters, CleanUpConstants.VARIABLE_DECLARATIONS_USE_FINAL_PARAMETERS, CleanUpModifyDialog.FALSE_TRUE); // final CheckboxPreference useFinalVariablesPref= createCheckboxPref(variableGroup, 1, CleanUpMessages.CodeStyleTabPage_CheckboxName_UseFinalForLocals, CleanUpConstants.VARIABLE_DECLARATIONS_USE_FINAL_LOCAL_VARIABLES, CleanUpModifyDialog.FALSE_TRUE); // registerSlavePreference(useFinalPref, new CheckboxPreference[] {useFinalFieldsPref, useFinalParametersPref, useFinalVariablesPref}); } }
epl-1.0
bmaggi/Papyrus-SysML11
plugins/org.eclipse.papyrus.sysml.edit/src/org/eclipse/papyrus/sysml/allocations/provider/AllocatedItemProvider.java
6029
/***************************************************************************** * Copyright (c) 2009 CEA LIST. * * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Yann Tanguy (CEA LIST) yann.tanguy@cea.fr - Initial API and implementation * *****************************************************************************/ package org.eclipse.papyrus.sysml.allocations.provider; import java.util.Collection; import java.util.List; import org.eclipse.emf.common.notify.AdapterFactory; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.common.util.ResourceLocator; import org.eclipse.emf.edit.provider.ComposeableAdapterFactory; import org.eclipse.emf.edit.provider.IEditingDomainItemProvider; import org.eclipse.emf.edit.provider.IItemLabelProvider; import org.eclipse.emf.edit.provider.IItemPropertyDescriptor; import org.eclipse.emf.edit.provider.IItemPropertySource; import org.eclipse.emf.edit.provider.IStructuredItemContentProvider; import org.eclipse.emf.edit.provider.ITreeItemContentProvider; import org.eclipse.emf.edit.provider.ItemProviderAdapter; import org.eclipse.papyrus.sysml.allocations.AllocationsPackage; import org.eclipse.papyrus.sysml.provider.SysmlEditPlugin; /** * This is the item provider adapter for a {@link org.eclipse.papyrus.sysml.allocations.Allocated} object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ public class AllocatedItemProvider extends ItemProviderAdapter implements IEditingDomainItemProvider, IStructuredItemContentProvider, ITreeItemContentProvider, IItemLabelProvider, IItemPropertySource { /** * This constructs an instance from a factory and a notifier. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ public AllocatedItemProvider(AdapterFactory adapterFactory) { super(adapterFactory); } /** * This returns the property descriptors for the adapted class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override public List<IItemPropertyDescriptor> getPropertyDescriptors(Object object) { if (itemPropertyDescriptors == null) { super.getPropertyDescriptors(object); addBase_NamedElementPropertyDescriptor(object); addAllocatedFromPropertyDescriptor(object); addAllocatedToPropertyDescriptor(object); } return itemPropertyDescriptors; } /** * This adds a property descriptor for the Base Named Element feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ protected void addBase_NamedElementPropertyDescriptor(Object object) { itemPropertyDescriptors.add(createItemPropertyDescriptor(((ComposeableAdapterFactory) adapterFactory).getRootAdapterFactory(), getResourceLocator(), getString("_UI_Allocated_base_NamedElement_feature"), getString("_UI_PropertyDescriptor_description", "_UI_Allocated_base_NamedElement_feature", "_UI_Allocated_type"), AllocationsPackage.Literals.ALLOCATED__BASE_NAMED_ELEMENT, true, false, true, null, null, null)); } /** * This adds a property descriptor for the Allocated From feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ protected void addAllocatedFromPropertyDescriptor(Object object) { itemPropertyDescriptors.add(createItemPropertyDescriptor(((ComposeableAdapterFactory) adapterFactory).getRootAdapterFactory(), getResourceLocator(), getString("_UI_Allocated_allocatedFrom_feature"), getString("_UI_PropertyDescriptor_description", "_UI_Allocated_allocatedFrom_feature", "_UI_Allocated_type"), AllocationsPackage.Literals.ALLOCATED__ALLOCATED_FROM, false, false, false, null, null, null)); } /** * This adds a property descriptor for the Allocated To feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ protected void addAllocatedToPropertyDescriptor(Object object) { itemPropertyDescriptors.add(createItemPropertyDescriptor(((ComposeableAdapterFactory) adapterFactory).getRootAdapterFactory(), getResourceLocator(), getString("_UI_Allocated_allocatedTo_feature"), getString("_UI_PropertyDescriptor_description", "_UI_Allocated_allocatedTo_feature", "_UI_Allocated_type"), AllocationsPackage.Literals.ALLOCATED__ALLOCATED_TO, false, false, false, null, null, null)); } /** * This returns Allocated.gif. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override public Object getImage(Object object) { return overlayImage(object, getResourceLocator().getImage("full/obj16/Allocated")); } /** * This returns the label text for the adapted class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override public String getText(Object object) { return getString("_UI_Allocated_type"); } /** * This handles model notifications by calling {@link #updateChildren} to update any cached * children and by creating a viewer notification, which it passes to {@link #fireNotifyChanged}. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override public void notifyChanged(Notification notification) { updateChildren(notification); super.notifyChanged(notification); } /** * This adds {@link org.eclipse.emf.edit.command.CommandParameter}s describing the children * that can be created under this object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override protected void collectNewChildDescriptors(Collection<Object> newChildDescriptors, Object object) { super.collectNewChildDescriptors(newChildDescriptors, object); } /** * Return the resource locator for this item provider's resources. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override public ResourceLocator getResourceLocator() { return SysmlEditPlugin.INSTANCE; } }
epl-1.0
ianopolous/JPC
src/org/jpc/emulator/execution/opcodes/vm/fdivr_ST2_ST6.java
2048
/* JPC: An x86 PC Hardware Emulator for a pure Java Virtual Machine Copyright (C) 2012-2013 Ian Preston This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Details (including contact information) can be found at: jpc.sourceforge.net or the developer website sourceforge.net/projects/jpc/ End of licence header */ package org.jpc.emulator.execution.opcodes.vm; import org.jpc.emulator.execution.*; import org.jpc.emulator.execution.decoder.*; import org.jpc.emulator.processor.*; import org.jpc.emulator.processor.fpu64.*; import static org.jpc.emulator.processor.Processor.*; public class fdivr_ST2_ST6 extends Executable { public fdivr_ST2_ST6(int blockStart, int eip, int prefices, PeekableInputStream input) { super(blockStart, eip); int modrm = input.readU8(); } public Branch execute(Processor cpu) { double freg0 = cpu.fpu.ST(2); double freg1 = cpu.fpu.ST(6); if (((freg0 == 0.0) && (freg1 == 0.0)) || (Double.isInfinite(freg0) && Double.isInfinite(freg1))) cpu.fpu.setInvalidOperation(); if ((freg0 == 0.0) && !Double.isNaN(freg1) && !Double.isInfinite(freg1)) cpu.fpu.setZeroDivide(); cpu.fpu.setST(2, freg1/freg0); return Branch.None; } public boolean isBranch() { return false; } public String toString() { return this.getClass().getName(); } }
gpl-2.0
ysangkok/JPC
src/org/jpc/emulator/execution/opcodes/vm/faddp_ST5_ST6.java
2015
/* JPC: An x86 PC Hardware Emulator for a pure Java Virtual Machine Copyright (C) 2012-2013 Ian Preston This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Details (including contact information) can be found at: jpc.sourceforge.net or the developer website sourceforge.net/projects/jpc/ End of licence header */ package org.jpc.emulator.execution.opcodes.vm; import org.jpc.emulator.execution.*; import org.jpc.emulator.execution.decoder.*; import org.jpc.emulator.processor.*; import org.jpc.emulator.processor.fpu64.*; import static org.jpc.emulator.processor.Processor.*; public class faddp_ST5_ST6 extends Executable { public faddp_ST5_ST6(int blockStart, int eip, int prefices, PeekableInputStream input) { super(blockStart, eip); int modrm = input.readU8(); } public Branch execute(Processor cpu) { double freg0 = cpu.fpu.ST(5); double freg1 = cpu.fpu.ST(6); if ((freg0 == Double.NEGATIVE_INFINITY && freg1 == Double.POSITIVE_INFINITY) || (freg0 == Double.POSITIVE_INFINITY && freg1 == Double.NEGATIVE_INFINITY)) cpu.fpu.setInvalidOperation(); cpu.fpu.setST(5, freg0+freg1); cpu.fpu.pop(); return Branch.None; } public boolean isBranch() { return false; } public String toString() { return this.getClass().getName(); } }
gpl-2.0
tonysparks/seventh
src/seventh/client/screens/Screen.java
612
/* * see license.txt */ package seventh.client.screens; import seventh.client.gfx.Canvas; import seventh.client.inputs.Inputs; import seventh.shared.State; /** * A screen such as a TitleScreen, InGameScreen, etc. * * @author Tony * */ public interface Screen extends State { /** * Clean up resources associated with this screen */ public void destroy(); /** * Render this object. * * @param renderer */ public void render(Canvas canvas, float alpha); /** * @return the {@link Inputs} handler */ public Inputs getInputs(); }
gpl-2.0
ianopolous/JPC
src/org/jpc/emulator/execution/opcodes/rm/fxch_ST0_ST0.java
1778
/* JPC: An x86 PC Hardware Emulator for a pure Java Virtual Machine Copyright (C) 2012-2013 Ian Preston This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Details (including contact information) can be found at: jpc.sourceforge.net or the developer website sourceforge.net/projects/jpc/ End of licence header */ package org.jpc.emulator.execution.opcodes.rm; import org.jpc.emulator.execution.*; import org.jpc.emulator.execution.decoder.*; import org.jpc.emulator.processor.*; import org.jpc.emulator.processor.fpu64.*; import static org.jpc.emulator.processor.Processor.*; public class fxch_ST0_ST0 extends Executable { public fxch_ST0_ST0(int blockStart, int eip, int prefices, PeekableInputStream input) { super(blockStart, eip); int modrm = input.readU8(); } public Branch execute(Processor cpu) { double tmp = cpu.fpu.ST(0); cpu.fpu.setST(0, cpu.fpu.ST(0)); cpu.fpu.setST(0, tmp); return Branch.None; } public boolean isBranch() { return false; } public String toString() { return this.getClass().getName(); } }
gpl-2.0
teamfx/openjfx-8u-dev-tests
functional/FxmlTests/test/test/fxmltests/functional/MenuDefaultValueTest.java
5449
/* * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package test.fxmltests.functional; import javafx.scene.Node; import javafx.scene.Scene; import javafx.scene.control.MenuBar; import javafx.scene.control.Menu; import javafx.scene.control.MenuItem; import org.jemmy.Point; import org.jemmy.action.GetAction; import org.jemmy.control.Wrap; import org.jemmy.fx.Root; import org.jemmy.input.StringMenuOwner; import org.jemmy.interfaces.Parent; import org.jemmy.lookup.LookupCriteria; import org.jemmy.timing.State; import org.junit.BeforeClass; import org.junit.Test; import org.junit.Assert; import test.fxmltests.app.MenuDefaultValue; import test.fxmltests.app.MenuDefaultValue.Pages; import test.javaclient.shared.TestBase; import test.javaclient.shared.Utils; /** * * @author cementovoz */ public class MenuDefaultValueTest extends TestBase { @BeforeClass public static void runUI() { Utils.launch(MenuDefaultValue.class, null); } /** * this test verified creation menu with MenuItems from xml, RT-19007 */ @Test public void testMenu() throws InterruptedException { testCommon(Pages.menuPage.name(), null, false, true); checkMenu(); } /** * this test verified creation menuBar and menu width MenuItems from xml,RT-19007 */ @Test public void testMenuBar() throws InterruptedException { testCommon(Pages.menuBarPage.name(), null, false, true); checkMenu(); } /** * this test verified creation menu with custom children from xml, RT-19007 */ @Test public void testMenuItemCustom() throws InterruptedException { testCommon(Pages.menuItemCustomPage.name(), null, false, true); checkMenu(); } private void checkMenu () { Wrap<? extends Scene> sceneWrap = Root.ROOT.lookup(Scene.class).wrap(); Wrap<? extends Menu> menuWrap = getMenu(sceneWrap, MenuDefaultValue.MENU_FILE_ID); expand(menuWrap); Wrap<? extends Scene> scenePopup = Root.ROOT.lookup(Scene.class).wrap(0);//todo Parent<MenuItem> menuParent = menuWrap.as(Parent.class, MenuItem.class); Assert.assertEquals(MenuDefaultValue.COUNT_MENUITEMS, menuParent.lookup().size()); for (int i=0; i < menuParent.lookup().size(); i++) { Wrap<? extends MenuItem> menuItemWrap = menuParent.lookup().wrap(i); Assert.assertNotNull(menuItemWrap); Wrap<? extends Node> menuItem = lookupByMenuItem(scenePopup, menuItemWrap.getControl()); Assert.assertNotNull(menuItem); } sceneWrap.mouse().move(new Point(0, 0)); sceneWrap.mouse().click(); } private Wrap<? extends Menu> getMenu (Wrap<? extends Scene> scene, String text) { Parent<Node> sceneParent = scene.as(Parent.class, Node.class); Wrap<? extends MenuBar> menuBar = sceneParent.lookup(MenuBar.class).wrap(0); Assert.assertNotNull(menuBar); StringMenuOwner<? extends Menu> menuBarParent = menuBar.as(StringMenuOwner.class, Menu.class); Assert.assertNotNull(menuBarParent); final Wrap<? extends Menu> menu = menuBarParent.select(MenuDefaultValue.MENU_FILE_ID); Assert.assertNotNull(menu); return menu; } protected Wrap lookupByMenuItem(Wrap<? extends Scene> scene, final MenuItem menu) { final Wrap<Node> item = scene.as(Parent.class, Node.class).lookup(Node.class, new LookupCriteria<Node>() { public boolean check(Node node) { if (node.getProperties().get(MenuItem.class) == menu) { return true; } return false; } }).wrap(); return item; } private static void expand(final Wrap<? extends Menu> menu) { if (new GetAction<Boolean>() { @Override public void run(Object... parameters) { setResult(menu.getControl().isShowing()); } }.dispatch(Root.ROOT.getEnvironment()) == Boolean.FALSE) { menu.mouse().click(); } menu.waitState(new State() { public Object reached() { return (menu.getControl().isShowing() ? Boolean.TRUE : null); } }); } }
gpl-2.0
ysangkok/JPC
src/org/jpc/emulator/execution/opcodes/pm/mov_rBXr11_Id.java
1719
/* JPC: An x86 PC Hardware Emulator for a pure Java Virtual Machine Copyright (C) 2012-2013 Ian Preston This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Details (including contact information) can be found at: jpc.sourceforge.net or the developer website sourceforge.net/projects/jpc/ End of licence header */ package org.jpc.emulator.execution.opcodes.pm; import org.jpc.emulator.execution.*; import org.jpc.emulator.execution.decoder.*; import org.jpc.emulator.processor.*; import org.jpc.emulator.processor.fpu64.*; import static org.jpc.emulator.processor.Processor.*; public class mov_rBXr11_Id extends Executable { final int immd; public mov_rBXr11_Id(int blockStart, int eip, int prefices, PeekableInputStream input) { super(blockStart, eip); immd = Modrm.Id(input); } public Branch execute(Processor cpu) { cpu.r_ebx.set32(immd); return Branch.None; } public boolean isBranch() { return false; } public String toString() { return this.getClass().getName(); } }
gpl-2.0
murat8505/BombusMod-xmpp_client
android/src/org/microemu/android/device/AndroidDisplayGraphics.java
11202
/** * MicroEmulator * Copyright (C) 2008 Bartek Teodorczyk <barteo@barteo.net> * * It is licensed under the following two licenses as alternatives: * 1. GNU Lesser General Public License (the "LGPL") version 2.1 or any newer version * 2. Apache License (the "AL") Version 2.0 * * You may not use this file except in compliance with at least one of * the above two licenses. * * You may obtain a copy of the LGPL at * http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt * * You may obtain a copy of the AL at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the LGPL or the AL for the specific language governing permissions and * limitations. * * @version $Id: AndroidDisplayGraphics.java 2522 2011-11-28 13:44:59Z barteo@gmail.com $ */ package org.microemu.android.device; import javax.microedition.lcdui.Font; import javax.microedition.lcdui.Image; import org.microemu.log.Logger; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.DashPathEffect; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.Path; import android.graphics.Rect; import android.graphics.RectF; import android.graphics.Region; public class AndroidDisplayGraphics extends javax.microedition.lcdui.Graphics { public Paint strokePaint = new Paint(); public Paint fillPaint = new Paint(); public AndroidFont androidFont; private static final DashPathEffect dashPathEffect = new DashPathEffect(new float[] { 5, 5 }, 0); private static final Matrix identityMatrix = new Matrix(); private Canvas canvas; private GraphicsDelegate delegate; private Rect clip; private Font font; private int strokeStyle = SOLID; private Rect tmpRect = new Rect(); private Rect tmpRectSecond = new Rect(); private Matrix tmpMatrix = new Matrix(); public AndroidDisplayGraphics() { this.delegate = null; strokePaint.setAntiAlias(true); strokePaint.setStyle(Paint.Style.STROKE); strokePaint.setDither(true); fillPaint.setAntiAlias(true); fillPaint.setDither(true); fillPaint.setStyle(Paint.Style.FILL); } public AndroidDisplayGraphics(Bitmap bitmap) { this.canvas = new Canvas(bitmap); this.canvas.clipRect(0, 0, bitmap.getWidth(), bitmap.getHeight()); this.delegate = null; strokePaint.setAntiAlias(true); strokePaint.setDither(true); strokePaint.setStyle(Paint.Style.STROKE); fillPaint.setAntiAlias(true); fillPaint.setDither(true); fillPaint.setStyle(Paint.Style.FILL); reset(this.canvas); } public final void reset(Canvas canvas) { this.canvas = canvas; Rect tmp = this.canvas.getClipBounds(); // this.canvas.setMatrix(identityMatrix); // bugs with BombusMod SplashScreen // setMatrix changes the clipping too this.canvas.clipRect(tmp, Region.Op.REPLACE); clip = this.canvas.getClipBounds(); setFont(Font.getDefaultFont()); } public Canvas getCanvas() { return canvas; } public void setDelegate(GraphicsDelegate delegate) { this.delegate = delegate; } public void clipRect(int x, int y, int width, int height) { canvas.clipRect(x, y, x + width, y + height); clip = canvas.getClipBounds(); if (delegate != null) { delegate.setClip(clip.left, clip.top, clip.right - clip.left, clip.bottom - clip.top); } } public void drawArc(int x, int y, int width, int height, int startAngle, int arcAngle) { RectF rect = new RectF(x, y, x + width, y + height); canvas.drawArc(rect, -startAngle, -arcAngle, false, strokePaint); } public void drawImage(Image img, int x, int y, int anchor) { if (delegate != null) { delegate.drawImage(img, x, y, anchor); } else { int newx = x; int newy = y; if (anchor == 0) { anchor = javax.microedition.lcdui.Graphics.TOP | javax.microedition.lcdui.Graphics.LEFT; } if ((anchor & javax.microedition.lcdui.Graphics.RIGHT) != 0) { newx -= img.getWidth(); } else if ((anchor & javax.microedition.lcdui.Graphics.HCENTER) != 0) { newx -= img.getWidth() / 2; } if ((anchor & javax.microedition.lcdui.Graphics.BOTTOM) != 0) { newy -= img.getHeight(); } else if ((anchor & javax.microedition.lcdui.Graphics.VCENTER) != 0) { newy -= img.getHeight() / 2; } if (img.isMutable()) { canvas.drawBitmap(((AndroidMutableImage) img).getBitmap(), newx, newy, strokePaint); } else { canvas.drawBitmap(((AndroidImmutableImage) img).getBitmap(), newx, newy, strokePaint); } } } public void drawLine(int x1, int y1, int x2, int y2) { if (delegate != null) { delegate.drawLine(x1, y1, x2, y2); } else { if (x1 == x2) { canvas.drawLine(x1, y1, x2, y2 + 1, strokePaint); } else if (y1 == y2) { canvas.drawLine(x1, y1, x2 + 1, y2, strokePaint); } else { canvas.drawLine(x1, y1, x2 + 1, y2 + 1, strokePaint); } } } public void drawRect(int x, int y, int width, int height) { if (delegate != null) { delegate.drawRect(x, y, width, height); } else { canvas.drawRect(x, y, x + width, y + height, strokePaint); } } public void drawRoundRect(int x, int y, int width, int height, int arcWidth, int arcHeight) { canvas.drawRoundRect(new RectF(x, y, x + width, y + height), (float) arcWidth, (float) arcHeight, strokePaint); } public void drawString(String str, int x, int y, int anchor) { drawSubstring(str, 0, str.length(), x, y, anchor); } public void drawSubstring(String str, int offset, int len, int x, int y, int anchor) { int newx = x; int newy = y; if (anchor == 0) { anchor = javax.microedition.lcdui.Graphics.TOP | javax.microedition.lcdui.Graphics.LEFT; } if ((anchor & javax.microedition.lcdui.Graphics.TOP) != 0) { newy -= androidFont.metrics.ascent; } else if ((anchor & javax.microedition.lcdui.Graphics.BOTTOM) != 0) { newy -= androidFont.metrics.descent; } if ((anchor & javax.microedition.lcdui.Graphics.HCENTER) != 0) { newx -= androidFont.paint.measureText(str) / 2; } else if ((anchor & javax.microedition.lcdui.Graphics.RIGHT) != 0) { newx -= androidFont.paint.measureText(str); } androidFont.paint.setColor(strokePaint.getColor()); if (delegate != null) { delegate.drawSubstringDelegate(str, offset, len, newx, newy, anchor); } else { canvas.drawText(str, offset, len + offset, newx, newy, androidFont.paint); } } public void fillArc(int x, int y, int width, int height, int startAngle, int arcAngle) { RectF rect = new RectF(x, y, x + width, y + height); canvas.drawArc(rect, -startAngle, -arcAngle, true, fillPaint); } public void fillRect(int x, int y, int width, int height) { if (delegate != null) { delegate.fillRect(x, y, width, height); } else { canvas.drawRect(x, y, x + width, y + height, fillPaint); } } public void fillRoundRect(int x, int y, int width, int height, int arcWidth, int arcHeight) { canvas.drawRoundRect(new RectF(x, y, x + width, y + height), (float) arcWidth, (float) arcHeight, fillPaint); } public int getClipHeight() { return clip.bottom - clip.top; } public int getClipWidth() { return clip.right - clip.left; } public int getClipX() { return clip.left; } public int getClipY() { return clip.top; } public int getColor() { return strokePaint.getColor(); } public Font getFont() { return font; } public int getStrokeStyle() { return strokeStyle; } public void setClip(int x, int y, int width, int height) { if (x == clip.left && x + width == clip.right && y == clip.top && y + height == clip.bottom) { return; } if (delegate != null) { delegate.setClip(x, y, width, height); } clip.left = x; clip.top = y; clip.right = x + width; clip.bottom = y + height; canvas.clipRect(clip, Region.Op.REPLACE); } public void setColor(int RGB) { strokePaint.setColor(0xff000000 | RGB); fillPaint.setColor(0xff000000 | RGB); } public void setFont(Font font) { this.font = font; androidFont = AndroidFontManager.getFont(font); } public void setStrokeStyle(int style) { if (style != SOLID && style != DOTTED) { throw new IllegalArgumentException(); } this.strokeStyle = style; if (style == SOLID) { strokePaint.setPathEffect(null); fillPaint.setPathEffect(null); } else { // DOTTED strokePaint.setPathEffect(dashPathEffect); fillPaint.setPathEffect(dashPathEffect); } } public void translate(int x, int y) { if (delegate != null) { delegate.translate(x, y); } else { canvas.translate(x, y); } super.translate(x, y); clip.left -= x; clip.right -= x; clip.top -= y; clip.bottom -= y; } public void drawRGB(int[] rgbData, int offset, int scanlength, int x, int y, int width, int height, boolean processAlpha) { if (rgbData == null) throw new NullPointerException(); if (width == 0 || height == 0) { return; } int l = rgbData.length; if (width < 0 || height < 0 || offset < 0 || offset >= l || (scanlength < 0 && scanlength * (height - 1) < 0) || (scanlength >= 0 && scanlength * (height - 1) + width - 1 >= l)) { throw new ArrayIndexOutOfBoundsException(); } // MIDP allows almost any value of scanlength, drawBitmap is more strict with the stride if (scanlength == 0) { scanlength = width; } int rows = rgbData.length / scanlength; if (rows < height) { height = rows; } canvas.drawBitmap(rgbData, offset, scanlength, x, y, width, height, processAlpha, strokePaint); } public void fillTriangle(int x1, int y1, int x2, int y2, int x3, int y3) { if (delegate != null) { delegate.fillTriangle(x1, y1, x2, y2, x3, y3); } else { Path path = new Path(); path.moveTo(x1, y1); path.lineTo(x2, y2); path.lineTo(x3, y3); path.lineTo(x1, y1); canvas.drawPath(path, fillPaint); } } public void copyArea(int x_src, int y_src, int width, int height, int x_dest, int y_dest, int anchor) { Logger.debug("copyArea"); } public int getDisplayColor(int color) { Logger.debug("getDisplayColor"); return -1; } }
gpl-2.0
whipermr5/teammates
src/client/java/teammates/client/scripts/GenerateFeedbackReport.java
1642
package teammates.client.scripts; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import teammates.client.remoteapi.RemoteApiClient; import teammates.common.exception.EntityDoesNotExistException; import teammates.common.exception.ExceedingRangeException; import teammates.logic.api.Logic; /** * Generates the feedback report as a csv. */ public class GenerateFeedbackReport extends RemoteApiClient { public static void main(String[] args) throws IOException { GenerateFeedbackReport reportGenerator = new GenerateFeedbackReport(); reportGenerator.doOperationRemotely(); } @Override protected void doOperation() { Logic logic = new Logic(); try { String fileContent = logic.getFeedbackSessionResultSummaryAsCsv( "CourseID", "Session Name", "instructor@email.com", true, true, null); writeToFile("result.csv", fileContent); } catch (EntityDoesNotExistException | ExceedingRangeException e) { e.printStackTrace(); } } private void writeToFile(String fileName, String fileContent) { try { File file = new File(fileName); // if file doesnt exists, then create it if (!file.exists()) { file.createNewFile(); } try (BufferedWriter bw = new BufferedWriter(new FileWriter(file.getAbsoluteFile()))) { bw.write(fileContent); } } catch (IOException e) { e.printStackTrace(); } } }
gpl-2.0
SomeRandomPerson9/3DT
lib/jbullet-20101010/jbullet-20101010/src/com/bulletphysics/demos/opengl/FastFormat.java
1889
/* * Java port of Bullet (c) 2008 Martin Dvorak <jezek2@advel.cz> * * Bullet Continuous Collision Detection and Physics Library * Copyright (c) 2003-2008 Erwin Coumans http://www.bulletphysics.com/ * * This software is provided 'as-is', without any express or implied warranty. * In no event will the authors be held liable for any damages arising from * the use of this software. * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ package com.bulletphysics.demos.opengl; /** * * @author jezek2 */ public class FastFormat { private static final char[] DIGITS = "0123456789".toCharArray(); public static void append(StringBuilder b, int i) { if (i < 0) { b.append('-'); i = Math.abs(i); } int digit = 1000000000; boolean first = true; while (digit >= 1) { int v = (i/digit); if (v != 0 || !first) { b.append(DIGITS[v]); first = false; } i -= v*digit; digit /= 10; } if (first) b.append('0'); } public static void append(StringBuilder b, float f) { append(b, f, 2); } public static void append(StringBuilder b, float f, int fracDigits) { int mult = 10*fracDigits; int val = Math.round(f*mult); append(b, val / mult); b.append('.'); append(b, Math.abs(val % mult)); } }
gpl-2.0
ysangkok/JPC
src/org/jpc/emulator/execution/opcodes/pm/and_Ew_Iw.java
1982
/* JPC: An x86 PC Hardware Emulator for a pure Java Virtual Machine Copyright (C) 2012-2013 Ian Preston This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Details (including contact information) can be found at: jpc.sourceforge.net or the developer website sourceforge.net/projects/jpc/ End of licence header */ package org.jpc.emulator.execution.opcodes.pm; import org.jpc.emulator.execution.*; import org.jpc.emulator.execution.decoder.*; import org.jpc.emulator.processor.*; import org.jpc.emulator.processor.fpu64.*; import static org.jpc.emulator.processor.Processor.*; public class and_Ew_Iw extends Executable { final int op1Index; final int immw; public and_Ew_Iw(int blockStart, int eip, int prefices, PeekableInputStream input) { super(blockStart, eip); int modrm = input.readU8(); op1Index = Modrm.Ew(modrm); immw = Modrm.Iw(input); } public Branch execute(Processor cpu) { Reg op1 = cpu.regs[op1Index]; cpu.of = cpu.af = cpu.cf = false; cpu.flagResult = (short)(op1.get16() & immw); op1.set16((short)cpu.flagResult); cpu.flagStatus = SZP; return Branch.None; } public boolean isBranch() { return false; } public String toString() { return this.getClass().getName(); } }
gpl-2.0
ikoula/cloudstack
plugins/api/solidfire-intg-test/src/org/apache/cloudstack/api/response/solidfire/ApiSolidFireVolumeAccessGroupIdResponse.java
1379
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. package org.apache.cloudstack.api.response.solidfire; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; import org.apache.cloudstack.api.BaseResponse; public class ApiSolidFireVolumeAccessGroupIdResponse extends BaseResponse { @SerializedName("solidFireVolumeAccessGroupId") @Param(description = "SolidFire Volume Access Group Id") private long solidFireVolumeAccessGroupId; public ApiSolidFireVolumeAccessGroupIdResponse(long sfVolumeAccessGroupId) { solidFireVolumeAccessGroupId = sfVolumeAccessGroupId; } }
gpl-2.0
GiGatR00n/Aion-Core-v4.7.5
AC-Game/src/com/aionemu/gameserver/model/gm/GmPanelCommands.java
2505
/** * This file is part of Aion-Lightning <aion-lightning.org>. * * Aion-Lightning is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Aion-Lightning is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * * You should have received a copy of the GNU General Public License * along with Aion-Lightning. * If not, see <http://www.gnu.org/licenses/>. * * * Credits goes to all Open Source Core Developer Groups listed below * Please do not change here something, ragarding the developer credits, except the "developed by XXXX". * Even if you edit a lot of files in this source, you still have no rights to call it as "your Core". * Everybody knows that this Emulator Core was developed by Aion Lightning * @-Aion-Unique- * @-Aion-Lightning * @Aion-Engine * @Aion-Extreme * @Aion-NextGen * @Aion-Core Dev. */ package com.aionemu.gameserver.model.gm; /** * @author Ever' - Magenik */ public enum GmPanelCommands { /** * @STANDARD FUNCTION TAB */ REMOVE_SKILL_DELAY_ALL, ITEMCOOLTIME, CLEARUSERCOOLT, SET_MAKEUP_BONUS, SET_VITALPOINT, SET_DISABLE_ITEMUSE_GAUGE, PARTYRECALL, ATTRBONUS, TELEPORTTO, RESURRECT, INVISIBLE, VISIBLE, /** * @CHARACTER SETTING TAB */ LEVELDOWN, LEVELUP, CHANGECLASS, CLASSUP, DELETECQUEST, ADDQUEST, ENDQUEST, SETINVENTORYGROWTH, SKILLPOINT, COMBINESKILL, ADDSKILL, DELETESKILL, GIVETITLE, /** * @OVERALL FUNCTION TAB */ ENCHANT100, FREEFLY, /** * @NPC QUEST ITEM TAB */ TELEPORT_TO_NAMED, WISH, WISHID, DELETE_ITEMS, /** * @PLAYER INFO */ BOOKMARK_ADD, SEARCH; public static GmPanelCommands getValue(String command) { for (GmPanelCommands value : values()) { if (value.name().equals(command.toUpperCase())) { return value; } } throw new IllegalArgumentException("Invalid GmPanelCommands id: " + command); } }
gpl-2.0
SOKP/device_xiaomi_cancro
doze/src/org/cyanogenmod/doze/cancro/DozeService.java
2900
/* * Copyright (c) 2015 The CyanogenMod Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.cyanogenmod.doze.cancro; import android.app.Activity; import android.app.IntentService; import android.app.Service; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.os.IBinder; import android.provider.Settings; import android.util.Log; public class DozeService extends Service { private static final boolean DEBUG = false; private static final String TAG = "DozeService"; private Context mContext; private TiltSensor mTiltSensor; @Override public void onCreate() { if (DEBUG) Log.d(TAG, "Creating service"); super.onCreate(); mContext = this; mTiltSensor = new TiltSensor(mContext); } @Override public int onStartCommand(Intent intent, int flags, int startId) { if (DEBUG) Log.d(TAG, "Starting service"); IntentFilter screenStateFilter = new IntentFilter(Intent.ACTION_SCREEN_ON); screenStateFilter.addAction(Intent.ACTION_SCREEN_OFF); mContext.registerReceiver(mScreenStateReceiver, screenStateFilter); return START_STICKY; } @Override public void onDestroy() { if (DEBUG) Log.d(TAG, "Destroying service"); super.onDestroy(); mTiltSensor.disable(); } @Override public IBinder onBind(Intent intent) { return null; } private boolean isDozeEnabled() { return Settings.Secure.getInt(mContext.getContentResolver(), Settings.Secure.DOZE_ENABLED, 1) != 0; } private void onDisplayOn() { if (DEBUG) Log.d(TAG, "Display on"); mTiltSensor.disable(); } private void onDisplayOff() { if (DEBUG) Log.d(TAG, "Display off"); if (isDozeEnabled()) { mTiltSensor.enable(); } } private BroadcastReceiver mScreenStateReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) { onDisplayOff(); } else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) { onDisplayOn(); } } }; }
gpl-2.0
geneos/adempiere
base/src/org/compiere/model/X_AD_Attribute.java
14892
/****************************************************************************** * Product: Adempiere ERP & CRM Smart Business Solution * * Copyright (C) 1999-2007 ComPiere, Inc. All Rights Reserved. * * This program is free software, you can redistribute it and/or modify it * * under the terms version 2 of the GNU General Public License as published * * by the Free Software Foundation. This program is distributed in the hope * * that it will be useful, but WITHOUT ANY WARRANTY, without even the implied * * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * * with this program, if not, write to the Free Software Foundation, Inc., * * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * * For the text or an alternative of this public license, you may reach us * * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * * or via info@compiere.org or http://www.compiere.org/license.html * *****************************************************************************/ /** Generated Model - DO NOT CHANGE */ package org.compiere.model; import java.sql.ResultSet; import java.util.Properties; import org.compiere.util.KeyNamePair; /** Generated Model for AD_Attribute * @author Adempiere (generated) * @version Release 3.7.0LTS - $Id$ */ public class X_AD_Attribute extends PO implements I_AD_Attribute, I_Persistent { /** * */ private static final long serialVersionUID = 20110831L; /** Standard Constructor */ public X_AD_Attribute (Properties ctx, int AD_Attribute_ID, String trxName) { super (ctx, AD_Attribute_ID, trxName); /** if (AD_Attribute_ID == 0) { setAD_Attribute_ID (0); setAD_Reference_ID (0); setAD_Table_ID (0); setIsEncrypted (false); setIsFieldOnly (false); setIsHeading (false); setIsMandatory (false); setIsReadOnly (false); setIsSameLine (false); setIsUpdateable (false); setName (null); } */ } /** Load Constructor */ public X_AD_Attribute (Properties ctx, ResultSet rs, String trxName) { super (ctx, rs, trxName); } /** AccessLevel * @return 7 - System - Client - Org */ protected int get_AccessLevel() { return accessLevel.intValue(); } /** Load Meta Data */ protected POInfo initPO (Properties ctx) { POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName()); return poi; } public String toString() { StringBuffer sb = new StringBuffer ("X_AD_Attribute[") .append(get_ID()).append("]"); return sb.toString(); } /** Set System Attribute. @param AD_Attribute_ID System Attribute */ public void setAD_Attribute_ID (int AD_Attribute_ID) { if (AD_Attribute_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_Attribute_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_Attribute_ID, Integer.valueOf(AD_Attribute_ID)); } /** Get System Attribute. @return System Attribute */ public int getAD_Attribute_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Attribute_ID); if (ii == null) return 0; return ii.intValue(); } public org.compiere.model.I_AD_Reference getAD_Reference() throws RuntimeException { return (org.compiere.model.I_AD_Reference)MTable.get(getCtx(), org.compiere.model.I_AD_Reference.Table_Name) .getPO(getAD_Reference_ID(), get_TrxName()); } /** Set Reference. @param AD_Reference_ID System Reference and Validation */ public void setAD_Reference_ID (int AD_Reference_ID) { if (AD_Reference_ID < 1) set_Value (COLUMNNAME_AD_Reference_ID, null); else set_Value (COLUMNNAME_AD_Reference_ID, Integer.valueOf(AD_Reference_ID)); } /** Get Reference. @return System Reference and Validation */ public int getAD_Reference_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Reference_ID); if (ii == null) return 0; return ii.intValue(); } public org.compiere.model.I_AD_Reference getAD_Reference_Value() throws RuntimeException { return (org.compiere.model.I_AD_Reference)MTable.get(getCtx(), org.compiere.model.I_AD_Reference.Table_Name) .getPO(getAD_Reference_Value_ID(), get_TrxName()); } /** Set Reference Key. @param AD_Reference_Value_ID Required to specify, if data type is Table or List */ public void setAD_Reference_Value_ID (int AD_Reference_Value_ID) { if (AD_Reference_Value_ID < 1) set_Value (COLUMNNAME_AD_Reference_Value_ID, null); else set_Value (COLUMNNAME_AD_Reference_Value_ID, Integer.valueOf(AD_Reference_Value_ID)); } /** Get Reference Key. @return Required to specify, if data type is Table or List */ public int getAD_Reference_Value_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Reference_Value_ID); if (ii == null) return 0; return ii.intValue(); } public org.compiere.model.I_AD_Table getAD_Table() throws RuntimeException { return (org.compiere.model.I_AD_Table)MTable.get(getCtx(), org.compiere.model.I_AD_Table.Table_Name) .getPO(getAD_Table_ID(), get_TrxName()); } /** Set Table. @param AD_Table_ID Database Table information */ public void setAD_Table_ID (int AD_Table_ID) { if (AD_Table_ID < 1) set_Value (COLUMNNAME_AD_Table_ID, null); else set_Value (COLUMNNAME_AD_Table_ID, Integer.valueOf(AD_Table_ID)); } /** Get Table. @return Database Table information */ public int getAD_Table_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Table_ID); if (ii == null) return 0; return ii.intValue(); } public org.compiere.model.I_AD_Val_Rule getAD_Val_Rule() throws RuntimeException { return (org.compiere.model.I_AD_Val_Rule)MTable.get(getCtx(), org.compiere.model.I_AD_Val_Rule.Table_Name) .getPO(getAD_Val_Rule_ID(), get_TrxName()); } /** Set Dynamic Validation. @param AD_Val_Rule_ID Dynamic Validation Rule */ public void setAD_Val_Rule_ID (int AD_Val_Rule_ID) { if (AD_Val_Rule_ID < 1) set_Value (COLUMNNAME_AD_Val_Rule_ID, null); else set_Value (COLUMNNAME_AD_Val_Rule_ID, Integer.valueOf(AD_Val_Rule_ID)); } /** Get Dynamic Validation. @return Dynamic Validation Rule */ public int getAD_Val_Rule_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Val_Rule_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Callout. @param Callout Fully qualified class names and method - separated by semicolons */ public void setCallout (String Callout) { set_Value (COLUMNNAME_Callout, Callout); } /** Get Callout. @return Fully qualified class names and method - separated by semicolons */ public String getCallout () { return (String)get_Value(COLUMNNAME_Callout); } /** Set Default Logic. @param DefaultValue Default value hierarchy, separated by ; */ public void setDefaultValue (String DefaultValue) { set_Value (COLUMNNAME_DefaultValue, DefaultValue); } /** Get Default Logic. @return Default value hierarchy, separated by ; */ public String getDefaultValue () { return (String)get_Value(COLUMNNAME_DefaultValue); } /** Set Description. @param Description Optional short description of the record */ public void setDescription (String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Description. @return Optional short description of the record */ public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** Set Display Length. @param DisplayLength Length of the display in characters */ public void setDisplayLength (int DisplayLength) { set_Value (COLUMNNAME_DisplayLength, Integer.valueOf(DisplayLength)); } /** Get Display Length. @return Length of the display in characters */ public int getDisplayLength () { Integer ii = (Integer)get_Value(COLUMNNAME_DisplayLength); if (ii == null) return 0; return ii.intValue(); } /** Set Display Logic. @param DisplayLogic If the Field is displayed, the result determines if the field is actually displayed */ public void setDisplayLogic (String DisplayLogic) { set_Value (COLUMNNAME_DisplayLogic, DisplayLogic); } /** Get Display Logic. @return If the Field is displayed, the result determines if the field is actually displayed */ public String getDisplayLogic () { return (String)get_Value(COLUMNNAME_DisplayLogic); } /** Set Length. @param FieldLength Length of the column in the database */ public void setFieldLength (int FieldLength) { set_Value (COLUMNNAME_FieldLength, Integer.valueOf(FieldLength)); } /** Get Length. @return Length of the column in the database */ public int getFieldLength () { Integer ii = (Integer)get_Value(COLUMNNAME_FieldLength); if (ii == null) return 0; return ii.intValue(); } /** Set Comment/Help. @param Help Comment or Hint */ public void setHelp (String Help) { set_Value (COLUMNNAME_Help, Help); } /** Get Comment/Help. @return Comment or Hint */ public String getHelp () { return (String)get_Value(COLUMNNAME_Help); } /** Set Encrypted. @param IsEncrypted Display or Storage is encrypted */ public void setIsEncrypted (boolean IsEncrypted) { set_Value (COLUMNNAME_IsEncrypted, Boolean.valueOf(IsEncrypted)); } /** Get Encrypted. @return Display or Storage is encrypted */ public boolean isEncrypted () { Object oo = get_Value(COLUMNNAME_IsEncrypted); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Field Only. @param IsFieldOnly Label is not displayed */ public void setIsFieldOnly (boolean IsFieldOnly) { set_Value (COLUMNNAME_IsFieldOnly, Boolean.valueOf(IsFieldOnly)); } /** Get Field Only. @return Label is not displayed */ public boolean isFieldOnly () { Object oo = get_Value(COLUMNNAME_IsFieldOnly); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Heading only. @param IsHeading Field without Column - Only label is displayed */ public void setIsHeading (boolean IsHeading) { set_Value (COLUMNNAME_IsHeading, Boolean.valueOf(IsHeading)); } /** Get Heading only. @return Field without Column - Only label is displayed */ public boolean isHeading () { Object oo = get_Value(COLUMNNAME_IsHeading); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Mandatory. @param IsMandatory Data entry is required in this column */ public void setIsMandatory (boolean IsMandatory) { set_Value (COLUMNNAME_IsMandatory, Boolean.valueOf(IsMandatory)); } /** Get Mandatory. @return Data entry is required in this column */ public boolean isMandatory () { Object oo = get_Value(COLUMNNAME_IsMandatory); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Read Only. @param IsReadOnly Field is read only */ public void setIsReadOnly (boolean IsReadOnly) { set_Value (COLUMNNAME_IsReadOnly, Boolean.valueOf(IsReadOnly)); } /** Get Read Only. @return Field is read only */ public boolean isReadOnly () { Object oo = get_Value(COLUMNNAME_IsReadOnly); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Same Line. @param IsSameLine Displayed on same line as previous field */ public void setIsSameLine (boolean IsSameLine) { set_Value (COLUMNNAME_IsSameLine, Boolean.valueOf(IsSameLine)); } /** Get Same Line. @return Displayed on same line as previous field */ public boolean isSameLine () { Object oo = get_Value(COLUMNNAME_IsSameLine); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Updatable. @param IsUpdateable Determines, if the field can be updated */ public void setIsUpdateable (boolean IsUpdateable) { set_Value (COLUMNNAME_IsUpdateable, Boolean.valueOf(IsUpdateable)); } /** Get Updatable. @return Determines, if the field can be updated */ public boolean isUpdateable () { Object oo = get_Value(COLUMNNAME_IsUpdateable); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } /** Set Sequence. @param SeqNo Method of ordering records; lowest number comes first */ public void setSeqNo (int SeqNo) { set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Sequence. @return Method of ordering records; lowest number comes first */ public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); } /** Set Max. Value. @param ValueMax Maximum Value for a field */ public void setValueMax (String ValueMax) { set_Value (COLUMNNAME_ValueMax, ValueMax); } /** Get Max. Value. @return Maximum Value for a field */ public String getValueMax () { return (String)get_Value(COLUMNNAME_ValueMax); } /** Set Min. Value. @param ValueMin Minimum Value for a field */ public void setValueMin (String ValueMin) { set_Value (COLUMNNAME_ValueMin, ValueMin); } /** Get Min. Value. @return Minimum Value for a field */ public String getValueMin () { return (String)get_Value(COLUMNNAME_ValueMin); } /** Set Value Format. @param VFormat Format of the value; Can contain fixed format elements, Variables: "_lLoOaAcCa09" */ public void setVFormat (String VFormat) { set_Value (COLUMNNAME_VFormat, VFormat); } /** Get Value Format. @return Format of the value; Can contain fixed format elements, Variables: "_lLoOaAcCa09" */ public String getVFormat () { return (String)get_Value(COLUMNNAME_VFormat); } }
gpl-2.0
GiGatR00n/Aion-Core-v4.7.5
AC-Game/data/scripts/system/handlers/quest/elementis_forest/_30404ASpiritualConsultation.java
4154
/** * This file is part of Aion-Lightning <aion-lightning.org>. * * Aion-Lightning is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Aion-Lightning is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * * You should have received a copy of the GNU General Public License * along with Aion-Lightning. * If not, see <http://www.gnu.org/licenses/>. * * * Credits goes to all Open Source Core Developer Groups listed below * Please do not change here something, ragarding the developer credits, except the "developed by XXXX". * Even if you edit a lot of files in this source, you still have no rights to call it as "your Core". * Everybody knows that this Emulator Core was developed by Aion Lightning * @-Aion-Unique- * @-Aion-Lightning * @Aion-Engine * @Aion-Extreme * @Aion-NextGen * @Aion-Core Dev. */ package quest.elementis_forest; import com.aionemu.gameserver.model.gameobjects.player.Player; import com.aionemu.gameserver.questEngine.handlers.QuestHandler; import com.aionemu.gameserver.model.DialogAction; import com.aionemu.gameserver.questEngine.model.QuestEnv; import com.aionemu.gameserver.questEngine.model.QuestState; import com.aionemu.gameserver.questEngine.model.QuestStatus; import com.aionemu.gameserver.services.QuestService; /** * * @author Ritsu */ public class _30404ASpiritualConsultation extends QuestHandler { private static final int questId = 30404; public _30404ASpiritualConsultation() { super(questId); } @Override public void register() { qe.registerQuestNpc(799551).addOnQuestStart(questId); qe.registerQuestNpc(799551).addOnTalkEvent(questId); qe.registerQuestNpc(205575).addOnTalkEvent(questId); } @Override public boolean onDialogEvent(QuestEnv env) { Player player = env.getPlayer(); QuestState qs = player.getQuestStateList().getQuestState(questId); DialogAction dialog = env.getDialog(); int targetId = env.getTargetId(); if (qs == null || qs.getStatus() == QuestStatus.NONE) { if (targetId == 799551) { if (dialog == DialogAction.QUEST_SELECT) { return sendQuestDialog(env, 1011); } else { return sendQuestStartDialog(env); } } } else if (qs.getStatus() == QuestStatus.START) { int var = qs.getQuestVarById(0); switch (targetId) { case 205575: { switch (dialog) { case QUEST_SELECT: { if (var == 0) { return sendQuestDialog(env, 1352); } else if (var == 1) { return sendQuestDialog(env, 2375); } } case SETPRO1: { return defaultCloseDialog(env, 0, 1); } case CHECK_USER_HAS_QUEST_ITEM_SIMPLE: { if (QuestService.collectItemCheck(env, true)) { changeQuestStep(env, 1, 2, true); return sendQuestDialog(env, 5); } else { return closeDialogWindow(env); } } } } } } else if (qs.getStatus() == QuestStatus.REWARD) { if (targetId == 205575) { return sendQuestEndDialog(env); } } return false; } }
gpl-2.0
josmarsm/openwonderland
core/src/classes/org/jdesktop/wonderland/client/cell/utils/CellUtils.java
10889
/** * Open Wonderland * * Copyright (c) 2010 - 2012, Open Wonderland Foundation, All Rights Reserved * * Redistributions in source code form must reproduce the above * copyright and this condition. * * The contents of this file are subject to the GNU General Public * License, Version 2 (the "License"); you may not use this file * except in compliance with the License. A copy of the License is * available at http://www.opensource.org/licenses/gpl-license.php. * * The Open Wonderland Foundation designates this particular file as * subject to the "Classpath" exception as provided by the Open Wonderland * Foundation in the License file that accompanied this code. */ /** * Project Wonderland * * Copyright (c) 2004-2010, Sun Microsystems, Inc., All Rights Reserved * * Redistributions in source code form must reproduce the above * copyright and this condition. * * The contents of this file are subject to the GNU General Public * License, Version 2 (the "License"); you may not use this file * except in compliance with the License. A copy of the License is * available at http://www.opensource.org/licenses/gpl-license.php. * * Sun designates this particular file as subject to the "Classpath" * exception as provided by Sun in the License file that accompanied * this code. */ package org.jdesktop.wonderland.client.cell.utils; import com.jme.bounding.BoundingSphere; import com.jme.bounding.BoundingVolume; import com.jme.math.Vector3f; import java.util.logging.Level; import java.util.logging.Logger; import org.jdesktop.wonderland.client.cell.Cell; import org.jdesktop.wonderland.client.cell.CellEditChannelConnection; import org.jdesktop.wonderland.client.cell.view.ViewCell; import org.jdesktop.wonderland.client.comms.WonderlandSession; import org.jdesktop.wonderland.client.jme.ViewManager; import org.jdesktop.wonderland.client.jme.utils.ScenegraphUtils; import org.jdesktop.wonderland.client.login.ServerSessionManager; import org.jdesktop.wonderland.common.cell.CellEditConnectionType; import org.jdesktop.wonderland.common.cell.CellID; import org.jdesktop.wonderland.common.cell.CellTransform; import org.jdesktop.wonderland.common.cell.messages.CellCreateMessage; import org.jdesktop.wonderland.common.cell.messages.CellCreatedMessage; import org.jdesktop.wonderland.common.cell.messages.CellDeleteMessage; import org.jdesktop.wonderland.common.cell.state.BoundingVolumeHint; import org.jdesktop.wonderland.common.cell.state.CellServerState; import org.jdesktop.wonderland.common.cell.state.PositionComponentServerState; import org.jdesktop.wonderland.common.cell.state.ViewComponentServerState; import org.jdesktop.wonderland.common.messages.ResponseMessage; /** * A collection of useful utility routines pertaining to Cells. * * @author Jordan Slott <jslott@dev.java.net> */ public class CellUtils { private static Logger logger = Logger.getLogger(CellUtils.class.getName()); /** The default bounds radius to use if no hint is given */ private static final float DEFAULT_RADIUS = 1.0f; /** * Creates a cell in the world given the CellServerState of the cell. If the * given CellServerState is null, this method simply does not create a Cell. * This method attempts to position the Cell "optimally" so that the avatar * can see it, based upon "hints" about the Cell bounds given to it in the * CellServerState. * * @param state The cell server state for the new cell * @throw CellCreationException Upon error creating the cell */ public static CellID createCell(CellServerState state) throws CellCreationException { // Find the parent cell for this creation (may be null) CellID parentID = null; Cell parent = CellCreationParentRegistry.getCellCreationParent(); if (parent != null) { parentID = parent.getCellID(); logger.info("Using parent with Cell ID " + parentID.toString()); } return createCell(state, parentID); } /** * Creates a cell in the world given the CellServerState of the cell. If the * given CellServerState is null, this method simply does not create a Cell. * This method attempts to position the Cell "optimally" so that the avatar * can see it, based upon "hints" about the Cell bounds given to it in the * CellServerState. * * @param state The cell server state for the new cell * @param parentCellID The Cell ID of the parent, of null for world root * @throw CellCreationException Upon error creating the cell */ public static CellID createCell(CellServerState state, CellID parentCellID) throws CellCreationException { // Check to see if the Cell server state is null, and fail quietly if // so if (state == null) { logger.fine("Creating cell with null server state. Returning."); return null; } // Fetch the transform of the view (avatar) Cell and its "look at" // direction. ViewManager vm = ViewManager.getViewManager(); ViewCell viewCell = vm.getPrimaryViewCell(); CellTransform viewTransform = viewCell.getWorldTransform(); ServerSessionManager manager = viewCell.getCellCache().getSession().getSessionManager(); // The Cell Transform to apply to the Cell CellTransform transform = null; // Look for the "bounds hint" provided by the Cell. There are three // possible cases: // // (1) There is a hint and the Cell wants us to do the optimal layout // so go ahead and do it. // // (2) There is no hint, so use the default bounds radius and do the // optimal layout // // (3) There is a hint that says do not do the optimal layout, so we // will just put the Cell right on top of the avatar. BoundingVolumeHint hint = state.getBoundingVolumeHint(); logger.info("Using bounding volume hint " + hint.getBoundsHint() + ", do placement=" + hint.isDoSystemPlacement()); if (hint != null && hint.isDoSystemPlacement() == true) { // Case (1): We have a bounds hint and we want to do the layout, // so we find the distance away from the avatar and also the height // above the ground. BoundingVolume boundsHint = hint.getBoundsHint(); transform = CellPlacementUtils.getCellTransform(manager, boundsHint, viewTransform); } else if (hint == null) { // Case (2): Do the optimal placement using the default radius. BoundingVolume boundsHint = new BoundingSphere(DEFAULT_RADIUS, Vector3f.ZERO); transform = CellPlacementUtils.getCellTransform(manager, boundsHint, viewTransform); } else if (hint != null && hint.isDoSystemPlacement() == false) { // Case (3): The Cell will take care of its own placement, use // the origin of the avatar as the initial placement. // Issue 998: make sure this is actually the current location of // the avatar, and not the origin. This guarantees that the // cell will be in the viewcache of the creator at least, so // that the cell object can be (for example) positioned manually // by the client. transform = viewTransform; } // We also need to convert the initial origin of the Cell (in world // coordinates to the coordinates of the parent Cell (if non-null) if (parentCellID != null) { Cell parent = viewCell.getCellCache().getCell(parentCellID); CellTransform worldTransform = new CellTransform(null, null); CellTransform parentTransform = parent.getWorldTransform(); logger.info("Transform of the parent cell: translation=" + parentTransform.getTranslation(null).toString() + ", rotation=" + parentTransform.getRotation(null).toString()); transform = ScenegraphUtils.computeChildTransform(parentTransform, transform); } logger.info("Final adjusted origin " + transform.getTranslation(null).toString()); // Create a position component that will set the initial origin PositionComponentServerState position = (PositionComponentServerState) state.getComponentServerState(PositionComponentServerState.class); if (position == null) { position = new PositionComponentServerState(); state.addComponentServerState(position); } position.setTranslation(transform.getTranslation(null)); position.setRotation(transform.getRotation(null)); position.setScaling(transform.getScaling(null)); // Always pass in the view transform to the Cell's server state state.addComponentServerState(new ViewComponentServerState(viewTransform)); // Send the message to the server WonderlandSession session = manager.getPrimarySession(); CellEditChannelConnection connection = (CellEditChannelConnection) session.getConnection(CellEditConnectionType.CLIENT_TYPE); CellCreateMessage msg = new CellCreateMessage(parentCellID, state); // connection.send(msg); ResponseMessage response = null; try { response = connection.sendAndWait(msg); } catch (InterruptedException ex) { Logger.getLogger(CellUtils.class.getName()).log(Level.SEVERE, null, ex); } if(response == null || !(response instanceof CellCreatedMessage)) { //handle here. return null; } //if things went okay, go ahead and cast and return; CellCreatedMessage ccm = (CellCreatedMessage)response; return ccm.getCellID(); } /** * Requests the server to delete the given cell from the world * of the primary session. Returns true if the deletion succeeds. * <br><br> * Note: currently always returns true because the server doesn't send * any response to the cell delete message. */ public static boolean deleteCell (Cell cell) { WonderlandSession session = cell.getCellCache().getSession(); CellEditChannelConnection connection = (CellEditChannelConnection) session.getConnection(CellEditConnectionType.CLIENT_TYPE); CellDeleteMessage msg = new CellDeleteMessage(cell.getCellID()); connection.send(msg); // TODO: there really really should be an OK/Error response from the server! return true; } }
gpl-2.0
hexbinary/landing
src/main/java/org/oscarehr/common/NativeSql.java
1646
/** * Copyright (c) 2001-2002. Department of Family Medicine, McMaster University. All Rights Reserved. * This software is published under the GPL GNU General Public License. * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * This software was written for the * Department of Family Medicine * McMaster University * Hamilton * Ontario, Canada */ package org.oscarehr.common; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Indicates that a method uses a native SQL query that may need to be translated or re-factored. */ @Documented @Retention(RetentionPolicy.SOURCE) @Target(ElementType.METHOD) public @interface NativeSql { /** * Defines list of tables used in this statement. * * @return * Returns the list of all tables names used in this native SQL. */ String[] value() default ""; }
gpl-2.0
rex-xxx/mt6572_x201
external/ganymed-ssh2/src/main/java/ch/ethz/ssh2/packets/PacketUserauthBanner.java
1391
/* * Copyright (c) 2006-2011 Christian Plattner. All rights reserved. * Please refer to the LICENSE.txt for licensing details. */ package ch.ethz.ssh2.packets; import java.io.IOException; /** * PacketUserauthBanner. * * @author Christian Plattner * @version 2.50, 03/15/10 */ public class PacketUserauthBanner { byte[] payload; String message; String language; public PacketUserauthBanner(String message, String language) { this.message = message; this.language = language; } public String getBanner() { return message; } public PacketUserauthBanner(byte payload[], int off, int len) throws IOException { this.payload = new byte[len]; System.arraycopy(payload, off, this.payload, 0, len); TypesReader tr = new TypesReader(payload, off, len); int packet_type = tr.readByte(); if (packet_type != Packets.SSH_MSG_USERAUTH_BANNER) throw new IOException("This is not a SSH_MSG_USERAUTH_BANNER! (" + packet_type + ")"); message = tr.readString("UTF-8"); language = tr.readString(); if (tr.remain() != 0) throw new IOException("Padding in SSH_MSG_USERAUTH_REQUEST packet!"); } public byte[] getPayload() { if (payload == null) { TypesWriter tw = new TypesWriter(); tw.writeByte(Packets.SSH_MSG_USERAUTH_BANNER); tw.writeString(message); tw.writeString(language); payload = tw.getBytes(); } return payload; } }
gpl-2.0
atomicknight/checker-framework
eclipse/checker-framework-eclipse-plugin/src/org/checkerframework/eclipse/builder/CheckerBuilder.java
3246
package org.checkerframework.eclipse.builder; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.checkerframework.eclipse.util.PluginUtil; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResourceDelta; import org.eclipse.core.resources.IncrementalProjectBuilder; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jface.preference.IPreferenceStore; import org.checkerframework.eclipse.CheckerPlugin; import org.checkerframework.eclipse.actions.CheckerManager; import org.checkerframework.eclipse.actions.CheckerWorker; import org.checkerframework.eclipse.prefs.CheckerPreferences; import org.checkerframework.eclipse.util.MutexSchedulingRule; import org.checkerframework.eclipse.util.ResourceUtils; public class CheckerBuilder extends IncrementalProjectBuilder { public static final String BUILDER_ID = "checkers.eclipse.checkerbuilder"; public CheckerBuilder() { super(); } @Override protected IProject[] build(int kind, Map args, IProgressMonitor monitor) throws CoreException { if (isBuildEnabled()) { if (kind == FULL_BUILD) { fullBuild(); } else { IResourceDelta delta = getDelta(getProject()); if (delta == null) { fullBuild(); } else { incrementalBuild(delta); } } } return null; } private boolean isBuildEnabled() { IPreferenceStore store = CheckerPlugin.getDefault() .getPreferenceStore(); return store.getBoolean(CheckerPreferences.PREF_CHECKER_AUTO_BUILD); } private void incrementalBuild(IResourceDelta delta) { CheckerResourceVisitor visitor = new CheckerResourceVisitor(); try { delta.accept(visitor); } catch (CoreException e) { // TODO Auto-generated catch block e.printStackTrace(); } runWorker(JavaCore.create(getProject()), new LinkedHashSet<String>(visitor.getBuildFiles()), CheckerManager.getSelectedClasses()); } private void fullBuild() throws CoreException { IJavaProject project = JavaCore.create(getProject()); Set<String> sourceNames = ResourceUtils.sourceFilesOf(project); runWorker(project, sourceNames, CheckerManager.getSelectedClasses()); } private void runWorker(IJavaProject project, Set<String> sourceNames, List<String> checkerNames) { Job checkerJob = new CheckerWorker(project, sourceNames.toArray(new String[] {}), PluginUtil.join(",", checkerNames), true); checkerJob.setUser(true); checkerJob.setPriority(Job.BUILD); checkerJob.setRule(new MutexSchedulingRule()); checkerJob.schedule(); } }
gpl-2.0
qiuxs/ice-demos
java/IceBox/hello/HelloI.java
394
// ********************************************************************** // // Copyright (c) 2003-2015 ZeroC, Inc. All rights reserved. // // ********************************************************************** import Demo.*; public class HelloI extends _HelloDisp { @Override public void sayHello(Ice.Current current) { System.out.println("Hello World!"); } }
gpl-2.0
berl/v3draw-bioformats
components/forks/poi/src/loci/poi/hssf/record/formula/AreaNPtg.java
3183
/* * #%L * Fork of Apache Jakarta POI. * %% * Copyright (C) 2008 - 2013 Open Microscopy Environment: * - Board of Regents of the University of Wisconsin-Madison * - Glencoe Software, Inc. * - University of Dundee * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ /* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ /* * AreaPtg.java * * Created on November 17, 2001, 9:30 PM */ package loci.poi.hssf.record.formula; import loci.poi.util.LittleEndian; import loci.poi.util.BitField; import loci.poi.hssf.record.RecordInputStream; import loci.poi.hssf.util.AreaReference; import loci.poi.hssf.util.CellReference; import loci.poi.hssf.model.Workbook; /** * Specifies a rectangular area of cells A1:A4 for instance. * @author Jason Height (jheight at chariot dot net dot au) */ public class AreaNPtg extends AreaPtg { public final static short sid = 0x2D; protected AreaNPtg() { //Required for clone methods } public AreaNPtg(RecordInputStream in) { super(in); } public void writeBytes(byte [] array, int offset) { super.writeBytes(array,offset); //this should be a warning...there doesn't seem to be any rationale to throwing an exception here... //this excpeiton appears to break user defined named ranges... //throw new RuntimeException("Coding Error: This method should never be called. This ptg should be converted"); } public String getAreaPtgName() { return "AreaNPtg"; } public String toFormulaString(Workbook book) { throw new RuntimeException("Coding Error: This method should never be called. This ptg should be converted"); } public Object clone() { throw new RuntimeException("Coding Error: This method should never be called. This ptg should be converted"); } }
gpl-2.0
bobocop/gsn35
src/gsn/acquisition2/wrappers/AbstractWrapper2.java
3874
package gsn.acquisition2.wrappers; import gsn.beans.AddressBean; import java.io.Serializable; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.concurrent.LinkedBlockingQueue; import org.apache.log4j.Logger; import org.apache.mina.common.IoSession; public abstract class AbstractWrapper2 extends Thread{ private AddressBean activeAddressBean; private final transient Logger logger = Logger.getLogger( AbstractWrapper2.class ); private LinkedBlockingQueue<Long> queue = new LinkedBlockingQueue<Long>(); private String tableName; private IoSession network; private PreparedStatement insertPS; private boolean keepProcessedSafeStorageEntries = true; public String getTableName() { return tableName; } public void setTableName(String tableName) { this.tableName = tableName; } public final AddressBean getActiveAddressBean ( ) { if (this.activeAddressBean==null) { throw new RuntimeException("There is no active address bean associated with the wrapper."); } return activeAddressBean; } /** * Only sets if there is no other activeAddressBean configured. * @param newVal the activeAddressBean to set */ public void setActiveAddressBean ( AddressBean newVal ) { if (this.activeAddressBean!=null) { throw new RuntimeException("There is already an active address bean associated with the wrapper."); } this.activeAddressBean = newVal; } public IoSession getNetwork() { return network; } public void setNetwork(IoSession network) { this.network = network; } /** * Data stored as an array into the storage. * The meaning of each item should be specified through the documentation in the header. * @param values */ protected void postStreamElement(Serializable... values) { try { insertPS.clearParameters(); insertPS.setObject(1,values); insertPS.executeUpdate(); if (queue.isEmpty()) { final ResultSet generatedKeys = insertPS.getGeneratedKeys(); generatedKeys.next(); Long sqlNo = generatedKeys.getLong(1);// Getting the SEQ_NO generatedKeys.close(); queue.put(sqlNo); } }catch (Exception e) { logger.fatal(e.getMessage(),e); // TODO, Logging the data into some other storage. } } public void setPreparedStatement(PreparedStatement preparedStatement) { this.insertPS = preparedStatement; } /** * Only called by the handler once handler has consumed every non-processed entries from the db. * @throws InterruptedException */ public void canReaderDB() throws InterruptedException { queue.take(); } /** * The addressing is provided in the ("ADDRESS",Collection<KeyValue>). If * the DataSource can't initialize itself because of either internal error or * inaccessibility of the host specified in the address the method returns * false. The dbAliasName of the DataSource is also specified with the * "DBALIAS" in the context. The "STORAGEMAN" points to the StorageManager * which should be used for querying. * * @return True if the initialization do successfully otherwise false; */ public abstract boolean initialize ( ); public abstract void dispose ( ); // TODO, the safe storage should stop the acquisition part. public abstract String getWrapperName ( ); public abstract void run(); public boolean isKeepProcessedSafeStorageEntries() { return keepProcessedSafeStorageEntries; } public void setKeepProcessedSafeStorageEntries(boolean keepProcessedInSafeStorage) { this.keepProcessedSafeStorageEntries = keepProcessedInSafeStorage; } }
gpl-3.0
CL-Team2/Signal-Android-Eschrow
libs/libsignal-protocol-java/java/src/main/java/org/whispersystems/libsignal/state/SessionStore.java
2480
/** * Copyright (C) 2014-2016 Open Whisper Systems * * Licensed according to the LICENSE file in this repository. */ package org.whispersystems.libsignal.state; import org.whispersystems.libsignal.SignalProtocolAddress; import java.util.List; /** * The interface to the durable store of session state information * for remote clients. * * @author Moxie Marlinspike */ public interface SessionStore { /** * Returns a copy of the {@link SessionRecord} corresponding to the recipientId + deviceId tuple, * or a new SessionRecord if one does not currently exist. * <p> * It is important that implementations return a copy of the current durable information. The * returned SessionRecord may be modified, but those changes should not have an effect on the * durable session state (what is returned by subsequent calls to this method) without the * store method being called here first. * * @param address The name and device ID of the remote client. * @return a copy of the SessionRecord corresponding to the recipientId + deviceId tuple, or * a new SessionRecord if one does not currently exist. */ public SessionRecord loadSession(SignalProtocolAddress address); /** * Returns all known devices with active sessions for a recipient * * @param name the name of the client. * @return all known sub-devices with active sessions. */ public List<Integer> getSubDeviceSessions(String name); /** * Commit to storage the {@link SessionRecord} for a given recipientId + deviceId tuple. * @param address the address of the remote client. * @param record the current SessionRecord for the remote client. */ public void storeSession(SignalProtocolAddress address, SessionRecord record); /** * Determine whether there is a committed {@link SessionRecord} for a recipientId + deviceId tuple. * @param address the address of the remote client. * @return true if a {@link SessionRecord} exists, false otherwise. */ public boolean containsSession(SignalProtocolAddress address); /** * Remove a {@link SessionRecord} for a recipientId + deviceId tuple. * * @param address the address of the remote client. */ public void deleteSession(SignalProtocolAddress address); /** * Remove the {@link SessionRecord}s corresponding to all devices of a recipientId. * * @param name the name of the remote client. */ public void deleteAllSessions(String name); }
gpl-3.0
bserdar/lightblue-core
crud/src/main/java/com/redhat/lightblue/eval/FieldProjector.java
2979
/* Copyright 2013 Red Hat, Inc. and/or its affiliates. This file is part of lightblue. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.redhat.lightblue.eval; import com.redhat.lightblue.util.Path; import com.redhat.lightblue.query.FieldProjection; import com.redhat.lightblue.query.Projection; import com.redhat.lightblue.metadata.FieldTreeNode; public class FieldProjector extends Projector { private final Path field; private final boolean include; private final boolean recursive; public FieldProjector(FieldProjection p, Path ctxPath, FieldTreeNode ctx) { super(ctxPath, ctx); field = new Path(ctxPath, p.getField()); include = p.isInclude(); recursive = p.isRecursive(); } @Override public Projector getNestedProjector() { return null; } @Override public Projection.Inclusion project(Path p, QueryEvaluationContext ctx) { if (p.matchingPrefix(field)) { // If this is true, we're checking an ancestor of the // projection field, or the projection field itself, but // not a field that is a descendant of the projection // field if (include) { return Projection.Inclusion.explicit_inclusion; // Inclusion implies, because if we're going to // include a descendant of this field, this field // should also be included } else if (p.matches(field)) { return Projection.Inclusion.explicit_exclusion; // If this field is exclusively excluded, exclude it } // Otherwise, this projection does not tell anything about this particular field. } else if (recursive && // If this is a recursive projection p.numSegments() > field.numSegments() && // If we're checking a field deeper than our field p.prefix(field.numSegments()).matches(field) // And if we're checking a field under the subtree of our field ) { // This is an implied inclusion or exclusion, because the // projection is for an ancestor of this field. return include ? Projection.Inclusion.implicit_inclusion : Projection.Inclusion.implicit_exclusion; } return Projection.Inclusion.undecided; } }
gpl-3.0
s20121035/rk3288_android5.1_repo
cts/tests/tests/permission/src/android/permission/cts/FileUtils.java
4175
package android.permission.cts; /* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import com.google.common.primitives.Ints; import android.system.OsConstants; import java.util.HashSet; import java.util.Set; /** Bits and pieces copied from hidden API of android.os.FileUtils. */ public class FileUtils { public static final int S_IFMT = 0170000; public static final int S_IFSOCK = 0140000; public static final int S_IFLNK = 0120000; public static final int S_IFREG = 0100000; public static final int S_IFBLK = 0060000; public static final int S_IFDIR = 0040000; public static final int S_IFCHR = 0020000; public static final int S_IFIFO = 0010000; public static final int S_ISUID = 0004000; public static final int S_ISGID = 0002000; public static final int S_ISVTX = 0001000; public static final int S_IRWXU = 00700; public static final int S_IRUSR = 00400; public static final int S_IWUSR = 00200; public static final int S_IXUSR = 00100; public static final int S_IRWXG = 00070; public static final int S_IRGRP = 00040; public static final int S_IWGRP = 00020; public static final int S_IXGRP = 00010; public static final int S_IRWXO = 00007; public static final int S_IROTH = 00004; public static final int S_IWOTH = 00002; public static final int S_IXOTH = 00001; static { System.loadLibrary("ctspermission_jni"); } public static class FileStatus { public int dev; public int ino; public int mode; public int nlink; public int uid; public int gid; public int rdev; public long size; public int blksize; public long blocks; public long atime; public long mtime; public long ctime; public boolean hasModeFlag(int flag) { if (((S_IRWXU | S_IRWXG | S_IRWXO) & flag) != flag) { throw new IllegalArgumentException("Inappropriate flag " + flag); } return (mode & flag) == flag; } public boolean isOfType(int type) { if ((type & S_IFMT) != type) { throw new IllegalArgumentException("Unknown type " + type); } return (mode & S_IFMT) == type; } } public static class CapabilitySet { private final Set<Integer> mCapabilities = new HashSet<Integer>(); public CapabilitySet add(int capability) { if ((capability < 0) || (capability > OsConstants.CAP_LAST_CAP)) { throw new IllegalArgumentException(String.format( "capability id %d out of valid range", capability)); } mCapabilities.add(capability); return this; } private native static boolean fileHasOnly(String path, int[] capabilities); public boolean fileHasOnly(String path) { return fileHasOnly(path, Ints.toArray(mCapabilities)); } } /** * @param path of the file to stat * @param status object to set the fields on * @param statLinks or don't stat links (lstat vs stat) * @return whether or not we were able to stat the file */ public native static boolean getFileStatus(String path, FileStatus status, boolean statLinks); public native static String getUserName(int uid); public native static String getGroupName(int gid); public native static boolean hasSetUidCapability(String path); public native static boolean hasSetGidCapability(String path); }
gpl-3.0
WhisperSystems/Signal-Android
app/src/main/java/org/thoughtcrime/securesms/util/views/SimpleProgressDialog.java
3215
package org.thoughtcrime.securesms.util.views; import android.content.Context; import androidx.annotation.AnyThread; import androidx.annotation.MainThread; import androidx.annotation.NonNull; import androidx.appcompat.app.AlertDialog; import org.signal.core.util.ThreadUtil; import org.signal.core.util.logging.Log; import org.thoughtcrime.securesms.R; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicReference; /** * Helper class to show a fullscreen blocking indeterminate progress dialog. */ public final class SimpleProgressDialog { private static final String TAG = Log.tag(SimpleProgressDialog.class); private SimpleProgressDialog() {} @MainThread public static @NonNull AlertDialog show(@NonNull Context context) { AlertDialog dialog = new AlertDialog.Builder(context) .setView(R.layout.progress_dialog) .setCancelable(false) .create(); dialog.show(); dialog.getWindow().setLayout(context.getResources().getDimensionPixelSize(R.dimen.progress_dialog_size), context.getResources().getDimensionPixelSize(R.dimen.progress_dialog_size)); return dialog; } @AnyThread public static @NonNull DismissibleDialog showDelayed(@NonNull Context context) { return showDelayed(context, 300, 1000); } /** * Shows the dialog after {@param delayMs} ms. * <p> * To dismiss, call {@link DismissibleDialog#dismiss()} on the result. If dismiss is called before * the delay has elapsed, the dialog will not show at all. * <p> * Dismiss can be called on any thread. * * @param minimumShowTimeMs If the dialog does display, then it will be visible for at least this duration. * This is to prevent flicker. */ @AnyThread public static @NonNull DismissibleDialog showDelayed(@NonNull Context context, int delayMs, int minimumShowTimeMs) { AtomicReference<AlertDialog> dialogAtomicReference = new AtomicReference<>(); AtomicLong shownAt = new AtomicLong(); Runnable showRunnable = () -> { Log.i(TAG, "Taking some time. Showing a progress dialog."); shownAt.set(System.currentTimeMillis()); dialogAtomicReference.set(show(context)); }; ThreadUtil.runOnMainDelayed(showRunnable, delayMs); return () -> { ThreadUtil.cancelRunnableOnMain(showRunnable); ThreadUtil.runOnMain(() -> { AlertDialog alertDialog = dialogAtomicReference.getAndSet(null); if (alertDialog != null) { long beenShowingForMs = System.currentTimeMillis() - shownAt.get(); long remainingTimeMs = minimumShowTimeMs - beenShowingForMs; if (remainingTimeMs > 0) { ThreadUtil.runOnMainDelayed(alertDialog::dismiss, remainingTimeMs); } else { alertDialog.dismiss(); } } }); }; } public interface DismissibleDialog { @AnyThread void dismiss(); } }
gpl-3.0
landryb/georchestra
datafeeder/src/main/java/org/georchestra/datafeeder/config/DataFeederConfigurationProperties.java
7517
/* * Copyright (C) 2020 by the geOrchestra PSC * * This file is part of geOrchestra. * * geOrchestra is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free * Software Foundation, either version 3 of the License, or (at your option) * any later version. * * geOrchestra is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along with * geOrchestra. If not, see <http://www.gnu.org/licenses/>. */ package org.georchestra.datafeeder.config; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URI; import java.net.URL; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.HashMap; import java.util.Map; import org.springframework.boot.context.properties.ConfigurationProperties; import com.google.common.io.ByteStreams; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.extern.slf4j.Slf4j; /** * {@link ConfigurationProperties @ConfigurationProperties} for the DataFeeder * application */ @Slf4j(topic = "org.georchestra.datafeeder.config") public @Data class DataFeederConfigurationProperties { private URI frontEndConfigFile; private FileUploadConfig fileUpload = new FileUploadConfig(); private PublishingConfiguration publishing = new PublishingConfiguration(); private EmailConfig email = new EmailConfig(); public static @Data class EmailConfig { boolean send; URI ackTemplate; URI analysisFailedTemplate; URI publishFailedTemplate; URI publishSuccessTemplate; } public static @Data class FileUploadConfig { /** maximum size allowed for uploaded files. */ private String maxFileSize; /** maximum size allowed for multipart/form-data requests */ private String maxRequestSize; /** size threshold after which files will be written to disk. */ private String fileSizeThreshold; /** * directory location where files will be stored by the servlet container once * the request exceeds the {@link #fileSizeThreshold} */ private String temporaryLocation = ""; /** directory location where files will be stored. */ private Path persistentLocation = Paths.get("/tmp/datafeeder/uploads"); } public static @Data class PublishingConfiguration { private GeoServerPublishingConfiguration geoserver = new GeoServerPublishingConfiguration(); private GeonetworkPublishingConfiguration geonetwork = new GeonetworkPublishingConfiguration(); private BackendConfiguration backend = new BackendConfiguration(); } @Data @EqualsAndHashCode(callSuper = true) public static class GeonetworkPublishingConfiguration extends ExternalApiConfiguration { private String templateRecordId; private URI templateRecord; private URI templateTransform; } @Data @EqualsAndHashCode(callSuper = true) public static class GeoServerPublishingConfiguration extends ExternalApiConfiguration { private String baseNamespaceURI; /** * If set, the number of seconds to set on published layers as their HTTP cache * timeout */ private Integer layerClientCacheSeconds; } public static @Data class ExternalApiConfiguration { private URL apiUrl; private URL publicUrl; private boolean logRequests; private Auth auth = new Auth(); } public static @Data class Auth { public static enum AuthType { none, basic, headers } private AuthType type = AuthType.none; private BasicAuth basic; private Map<String, String> headers = new HashMap<>(); } public static @Data class BasicAuth { private String username; private String password; } public static @Data class BackendConfiguration { /** * Connection parameters for the back-end, matching the connection parameters of * a GeoTools data-store, used by this application to set up the target data * store where to import uploaded datasets. The application uses these * parameters as a template and may tweak them to match application specific * business rules. For example, the georchestra configuration strategy may * create one postgis database schema for each organization short name. */ private Map<String, String> local = new HashMap<>(); /** * Connection parameters used as template to create a matching geoserver data * store during publishing. It must provide access to the same backend as the * {@link #local} parameters, albeit it could use a different strategy (for * example, {@link #local} may set up a regular postgis data store, while in * geoserver it might use a JNDI resource) */ private Map<String, String> geoserver = new HashMap<>(); } /** * Loads a resource from a configuration property. * * @param uri the resource URI, can be a file or a remote URL * @param configPropName the config property name, used for logging and * exception throwing * @return the contents of the resource * * @throws IllegalArgumentException if the resource can't be loaded for any * reason */ public byte[] loadResource(URI uri, String configPropName) { log.info("loading {} from {}", configPropName, uri); final boolean isFile = null == uri.getScheme() || "file".equalsIgnoreCase(uri.getScheme()); final byte[] contents = isFile ? loadFile(uri, configPropName) : loadURL(uri, configPropName); return contents; } public String loadResourceAsString(URI uri, String configPropName) { byte[] contents = loadResource(uri, configPropName); return new String(contents, StandardCharsets.UTF_8); } private byte[] loadURL(URI uri, String configPropName) { URL url; try { url = uri.toURL(); } catch (MalformedURLException e) { throw throwIAE(e, "Invalid config: %s=%s", configPropName, uri); } try (InputStream in = url.openStream()) { return ByteStreams.toByteArray(in); } catch (IOException e) { throw throwIAE(e, "Error loading: %s=%s", configPropName, uri); } } private byte[] loadFile(URI uri, String configPropName) { Path path = Paths.get(uri.getRawSchemeSpecificPart()).toAbsolutePath(); if (!Files.exists(path)) { throw throwIAE(null, "File does not exist: %s=%s, file:%s", configPropName, uri, path.toAbsolutePath().toString()); } uri = path.toUri(); return loadURL(uri, configPropName); } private IllegalArgumentException throwIAE(Exception cause, String msg, Object... msgParams) { String message = String.format(msg, msgParams); throw new IllegalArgumentException(message, cause); } }
gpl-3.0
tempbottle/CJBE
src/org/gjt/jclasslib/mdi/BasicDesktopManager.java
14370
/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the license, or (at your option) any later version. */ package org.gjt.jclasslib.mdi; import javax.swing.*; import javax.swing.event.InternalFrameEvent; import javax.swing.event.InternalFrameListener; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ComponentAdapter; import java.awt.event.ComponentEvent; import java.beans.PropertyChangeEvent; import java.beans.PropertyVetoException; import java.beans.VetoableChangeListener; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.ListIterator; /** * <tt>DesktopManager</tt> for MDI application. * * @author <a href="mailto:jclasslib@ej-technologies.com">Ingo Kegel</a> * @version $Revision: 1.1 $ $Date: 2005/11/01 13:18:23 $ */ public class BasicDesktopManager extends DefaultDesktopManager implements VetoableChangeListener, InternalFrameListener { /** * Parent frame of this <tt>DesktopManager</tt>. */ protected BasicMDIFrame parentFrame; private int newInternalX = 0; private int newInternalY = 0; private JDesktopPane desktopPane; private HashMap frameToMenuItem = new HashMap(); private BasicInternalFrame activeFrame; private LinkedList openFrames = new LinkedList(); private int rollover = 0; private int separatorMenuIndex = -1; private boolean maximizationInProgress; private boolean anyFrameMaximized; /** * Constructor. * * @param parentFrame the parent frame. */ public BasicDesktopManager(BasicMDIFrame parentFrame) { this.parentFrame = parentFrame; desktopPane = parentFrame.desktopPane; } /** * Get the parent frame. * * @return the frame */ public BasicMDIFrame getParentFrame() { return parentFrame; } /** * Get the associated <tt>JDesktopPane</tt>. * * @return the <tt>JDesktopPane</tt> */ public JDesktopPane getDesktopPane() { return desktopPane; } /** * Get the list of open child frames. * * @return the list */ public java.util.List getOpenFrames() { return openFrames; } /** * Get a rectangle for a new child frame. * * @return the rectangle */ public Rectangle getNextInternalFrameBounds() { int NEW_INTERNAL_X_OFFSET = 22; int NEW_INTERNAL_HEIGHT = 400; if (newInternalY + NEW_INTERNAL_HEIGHT > desktopPane.getHeight()) { rollover++; newInternalY = 0; newInternalX = rollover * NEW_INTERNAL_X_OFFSET; } int NEW_INTERNAL_WIDTH = 600; Rectangle nextBounds = new Rectangle(newInternalX, newInternalY, NEW_INTERNAL_WIDTH, NEW_INTERNAL_HEIGHT); newInternalX += NEW_INTERNAL_X_OFFSET; int NEW_INTERNAL_Y_OFFSET = 22; newInternalY += NEW_INTERNAL_Y_OFFSET; return nextBounds; } /** * Set the index of the frame to be shown on top after a call to <tt>showAll()</tt>. * * @param activeFrame the index */ public void setActiveFrame(BasicInternalFrame activeFrame) { this.activeFrame = activeFrame; } /** * Look for an open frame with an equivalent init parameter. * * @param initParam the init parameter to look for. * @return the open frame or <tt>null</tt>. */ public BasicInternalFrame getOpenFrame(Object initParam) { for (Object openFrame : openFrames) { BasicInternalFrame frame = (BasicInternalFrame) openFrame; if (frame.getInitParam().equals(initParam)) { return frame; } } return null; } /** * Show all internal frames. */ public void showAll() { for (Object openFrame : openFrames) { ((BasicInternalFrame) openFrame).setVisible(true); } if (activeFrame != null) { try { activeFrame.setSelected(true); } catch (PropertyVetoException ignored) { } } checkSize(); } /** * Add a child frame to this <tt>DesktopManager</tt>. * * @param frame the frame */ public void addInternalFrame(JInternalFrame frame) { frame.addComponentListener(new ComponentAdapter() { public void componentResized(ComponentEvent event) { checkSize(); } }); if (frameToMenuItem.size() == 0) { separatorMenuIndex = parentFrame.menuWindow.getMenuComponentCount(); parentFrame.menuWindow.addSeparator(); } Action action = new WindowActivateAction(frame); JCheckBoxMenuItem menuItem = new JCheckBoxMenuItem(action); menuItem.setSelected(false); parentFrame.menuWindow.add(menuItem); desktopPane.add(frame); frameToMenuItem.put(frame, menuItem); openFrames.add(frame); setWindowActionsEnabled(true); checkSize(); } /** * Cycle to the next child window. */ public void cycleToNextWindow() { cycleWindows(true); } /** * Cycle to the previous child window. */ public void cycleToPreviousWindow() { cycleWindows(false); } /** * Tile all child windows. */ public void tileWindows() { int framesCount = openFrames.size(); if (framesCount == 0) { return; } resetSize(); int sqrt = (int) Math.sqrt(framesCount); int rows = sqrt; int cols = sqrt; if (rows * cols < framesCount) { cols++; if (rows * cols < framesCount) { rows++; } } Dimension size = desktopPane.getSize(); int width = size.width / cols; int height = size.height / rows; int offsetX = 0; int offsetY = 0; JInternalFrame currentFrame; Iterator it = openFrames.iterator(); for (int i = 0; i < rows; i++) { for (int j = 0; j < cols && (i * cols + j < framesCount); j++) { currentFrame = (JInternalFrame) it.next(); normalizeFrame(currentFrame); resizeFrame(currentFrame, offsetX, offsetY, width, height); offsetX += width; } offsetX = 0; offsetY += height; } } /** * Stack all child windows. */ public void stackWindows() { newInternalX = newInternalY = rollover = 0; Rectangle currentBounds; JInternalFrame currentFrame; for (Object openFrame : openFrames) { currentFrame = (JInternalFrame) openFrame; normalizeFrame(currentFrame); currentBounds = getNextInternalFrameBounds(); resizeFrame(currentFrame, currentBounds.x, currentBounds.y, currentBounds.width, currentBounds.height); try { currentFrame.setSelected(true); } catch (PropertyVetoException ignored) { } } checkSize(); } public void vetoableChange(PropertyChangeEvent changeEvent) throws PropertyVetoException { String eventName = changeEvent.getPropertyName(); if (JInternalFrame.IS_MAXIMUM_PROPERTY.equals(eventName)) { if (maximizationInProgress) { return; } boolean isMaximum = ((Boolean) changeEvent.getNewValue()).booleanValue(); if (isMaximum) { resetSize(); } anyFrameMaximized = isMaximum; JInternalFrame source = (JInternalFrame) changeEvent.getSource(); maximizeAllFrames(source, isMaximum); } } public void activateFrame(JInternalFrame frame) { super.activateFrame(frame); for (Object o : frameToMenuItem.values()) { JCheckBoxMenuItem menuItem = (JCheckBoxMenuItem) o; menuItem.setSelected(false); } ((JCheckBoxMenuItem) frameToMenuItem.get(frame)).setSelected(true); } public void internalFrameDeiconified(InternalFrameEvent event) { } public void internalFrameOpened(InternalFrameEvent event) { } public void internalFrameIconified(InternalFrameEvent event) { } public void internalFrameClosing(InternalFrameEvent event) { JInternalFrame frame = event.getInternalFrame(); removeInternalFrame(frame); } public void internalFrameActivated(InternalFrameEvent event) { } public void internalFrameDeactivated(InternalFrameEvent event) { } public void internalFrameClosed(InternalFrameEvent event) { parentFrame.desktopPane.remove(event.getInternalFrame()); checkSize(); } public void endResizingFrame(JComponent f) { super.endResizingFrame(f); checkSize(); } public void endDraggingFrame(JComponent f) { super.endDraggingFrame(f); checkSize(); } /** * Check if the desktop pane should be resized. */ public void checkSize() { Dimension size = new Dimension(); JInternalFrame[] frames = desktopPane.getAllFrames(); for (JInternalFrame frame : frames) { size.width = Math.max(size.width, frame.getX() + frame.getWidth()); size.height = Math.max(size.height, frame.getY() + frame.getHeight()); } if (size.width > 0 && size.height > 0) { desktopPane.setPreferredSize(size); } else { desktopPane.setPreferredSize(null); } desktopPane.revalidate(); } /** * Check whether the desktop pane must be resized if in the maximized state. */ public void checkResizeInMaximizedState() { if (anyFrameMaximized) { resetSize(); } } /** * Scroll the destop pane such that the given frame becoes fully visible. * * @param frame the frame. */ public void scrollToVisible(JInternalFrame frame) { desktopPane.scrollRectToVisible(frame.getBounds()); } private void removeInternalFrame(JInternalFrame frame) { JMenuItem menuItem = (JMenuItem) frameToMenuItem.remove(frame); if (menuItem != null) { parentFrame.menuWindow.remove(menuItem); openFrames.remove(frame); if (frameToMenuItem.size() == 0 && separatorMenuIndex > -1) { parentFrame.menuWindow.remove(separatorMenuIndex); separatorMenuIndex = -1; setWindowActionsEnabled(false); } } } private void resetSize() { desktopPane.setPreferredSize(null); desktopPane.invalidate(); desktopPane.getParent().validate(); parentFrame.scpDesktop.invalidate(); parentFrame.scpDesktop.validate(); } private void normalizeFrame(JInternalFrame frame) { try { if (frame.isIcon()) { frame.setIcon(false); } if (frame.isMaximum()) { frame.setMaximum(false); } } catch (PropertyVetoException ignored) { } } private void cycleWindows(boolean forward) { JInternalFrame currentFrame = desktopPane.getSelectedFrame(); JInternalFrame nextFrame; ListIterator it = openFrames.listIterator(); while (it.hasNext() && it.next() != currentFrame) { } if (forward) { if (it.hasNext()) { nextFrame = (JInternalFrame) it.next(); } else { nextFrame = (JInternalFrame) openFrames.getFirst(); } } else { if (it.hasPrevious() && it.previous() != null && it.hasPrevious()) { nextFrame = (JInternalFrame) it.previous(); } else { nextFrame = (JInternalFrame) openFrames.getLast(); } } try { if (nextFrame.isIcon()) { nextFrame.setIcon(false); } nextFrame.setSelected(true); scrollToVisible(nextFrame); } catch (PropertyVetoException ignored) { } } private void setWindowActionsEnabled(boolean enabled) { parentFrame.actionNextWindow.setEnabled(enabled); parentFrame.actionPreviousWindow.setEnabled(enabled); parentFrame.actionTileWindows.setEnabled(enabled); parentFrame.actionStackWindows.setEnabled(enabled); } private void maximizeAllFrames(JInternalFrame source, boolean isMaximum) { synchronized (this) { if (maximizationInProgress) { return; } maximizationInProgress = true; } try { JInternalFrame[] frames = desktopPane.getAllFrames(); for (JInternalFrame frame : frames) { if (frame == source) { continue; } try { frame.setMaximum(isMaximum); } catch (PropertyVetoException ignored) { } } } finally { maximizationInProgress = false; } } private class WindowActivateAction extends AbstractAction { private JInternalFrame frame; private WindowActivateAction(JInternalFrame frame) { super(frame.getTitle()); this.frame = frame; } public void actionPerformed(ActionEvent event) { try { if (frame.isIcon()) { frame.setIcon(false); } if (frame.isSelected()) { ((JCheckBoxMenuItem) event.getSource()).setSelected(true); } else { frame.setSelected(true); } scrollToVisible(frame); } catch (PropertyVetoException ignored) { } } } }
gpl-3.0
RalfBarkow/Zettelkasten
src/main/java/de/danielluedecke/zettelkasten/util/ListUtil.java
4234
/* * Zettelkasten - nach Luhmann * Copyright (C) 2001-2015 by Daniel Lüdecke (http://www.danielluedecke.de) * * Homepage: http://zettelkasten.danielluedecke.de * * * This program is free software; you can redistribute it and/or modify it under the terms of the * GNU General Public License as published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with this program; * if not, see <http://www.gnu.org/licenses/>. * * * Dieses Programm ist freie Software. Sie können es unter den Bedingungen der GNU * General Public License, wie von der Free Software Foundation veröffentlicht, weitergeben * und/oder modifizieren, entweder gemäß Version 3 der Lizenz oder (wenn Sie möchten) * jeder späteren Version. * * Die Veröffentlichung dieses Programms erfolgt in der Hoffnung, daß es Ihnen von Nutzen sein * wird, aber OHNE IRGENDEINE GARANTIE, sogar ohne die implizite Garantie der MARKTREIFE oder * der VERWENDBARKEIT FÜR EINEN BESTIMMTEN ZWECK. Details finden Sie in der * GNU General Public License. * * Sie sollten ein Exemplar der GNU General Public License zusammen mit diesem Programm * erhalten haben. Falls nicht, siehe <http://www.gnu.org/licenses/>. */ package de.danielluedecke.zettelkasten.util; import java.awt.event.KeyEvent; import javax.swing.ListModel; /** * * @author Daniel Luedecke */ public class ListUtil { /** * This method retrieves the key-code {@code keyCode} of a released key in the * JList {@code list} and checks whether this key was a navigation key (i.e. * cursor up/down/left/right or home/end). If so, the method tries to select the next * related entry of that JList, according to the pressed key.<br><br> * Furthermore, the related content is made visible (scroll rect to visible or ensure * index is visible). * * @param list a reference to the JList where the related key was released * @param keyCode the keycode of the released key */ public static void navigateThroughList(javax.swing.JList list, int keyCode) { if (KeyEvent.VK_LEFT == keyCode || KeyEvent.VK_RIGHT == keyCode) { return; } int selectedRow = list.getSelectedIndex(); ListModel lm = list.getModel(); if (-1 == selectedRow) { selectedRow = 0; } switch (keyCode) { case KeyEvent.VK_HOME: selectedRow = 0; break; case KeyEvent.VK_END: selectedRow = lm.getSize() - 1; break; case KeyEvent.VK_DOWN: if (lm.getSize() > (selectedRow + 1)) { selectedRow++; } break; case KeyEvent.VK_UP: if (selectedRow > 0) { selectedRow--; } break; } list.setSelectedIndex(selectedRow); list.ensureIndexIsVisible(selectedRow); } /** * This method selects the first entry in the JList {@code list} that start with the * text that is entered in the filter-textfield {@code textfield}. * * @param list the JList where the item should be selected * @param textfield the related filtertextfield that contains the user-input */ public static void selectByTyping(javax.swing.JList list, javax.swing.JTextField textfield) { String text = textfield.getText().toLowerCase(); ListModel lm = list.getModel(); for (int cnt = 0; cnt < lm.getSize(); cnt++) { String val = lm.getElementAt(cnt).toString(); if (val.toLowerCase().startsWith(text)) { list.setSelectedIndex(cnt); list.ensureIndexIsVisible(cnt); // and leave method return; } } } }
gpl-3.0
MartyParty21/AwakenDreamsClient
mcp/src/minecraft/net/minecraft/potion/PotionUtils.java
9196
package net.minecraft.potion; import com.google.common.base.Objects; import com.google.common.collect.Lists; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Map.Entry; import javax.annotation.Nullable; import net.minecraft.entity.ai.attributes.AttributeModifier; import net.minecraft.entity.ai.attributes.IAttribute; import net.minecraft.init.PotionTypes; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import net.minecraft.util.ResourceLocation; import net.minecraft.util.Tuple; import net.minecraft.util.text.TextFormatting; import net.minecraft.util.text.translation.I18n; public class PotionUtils { public static List<PotionEffect> getEffectsFromStack(ItemStack stack) { return getEffectsFromTag(stack.getTagCompound()); } public static List<PotionEffect> mergeEffects(PotionType potionIn, Collection<PotionEffect> effects) { List<PotionEffect> list = Lists.<PotionEffect>newArrayList(); list.addAll(potionIn.getEffects()); list.addAll(effects); return list; } public static List<PotionEffect> getEffectsFromTag(@Nullable NBTTagCompound tag) { List<PotionEffect> list = Lists.<PotionEffect>newArrayList(); list.addAll(getPotionTypeFromNBT(tag).getEffects()); addCustomPotionEffectToList(tag, list); return list; } public static List<PotionEffect> getFullEffectsFromItem(ItemStack itemIn) { return getFullEffectsFromTag(itemIn.getTagCompound()); } public static List<PotionEffect> getFullEffectsFromTag(@Nullable NBTTagCompound tag) { List<PotionEffect> list = Lists.<PotionEffect>newArrayList(); addCustomPotionEffectToList(tag, list); return list; } public static void addCustomPotionEffectToList(@Nullable NBTTagCompound tag, List<PotionEffect> effectList) { if (tag != null && tag.hasKey("CustomPotionEffects", 9)) { NBTTagList nbttaglist = tag.getTagList("CustomPotionEffects", 10); for (int i = 0; i < nbttaglist.tagCount(); ++i) { NBTTagCompound nbttagcompound = nbttaglist.getCompoundTagAt(i); PotionEffect potioneffect = PotionEffect.readCustomPotionEffectFromNBT(nbttagcompound); if (potioneffect != null) { effectList.add(potioneffect); } } } } public static int getPotionColor(PotionType potionIn) { return getPotionColorFromEffectList(potionIn.getEffects()); } public static int getPotionColorFromEffectList(Collection<PotionEffect> effects) { int i = 3694022; if (effects.isEmpty()) { return 3694022; } else { float f = 0.0F; float f1 = 0.0F; float f2 = 0.0F; int j = 0; for (PotionEffect potioneffect : effects) { if (potioneffect.doesShowParticles()) { int k = potioneffect.getPotion().getLiquidColor(); int l = potioneffect.getAmplifier() + 1; f += (float)(l * (k >> 16 & 255)) / 255.0F; f1 += (float)(l * (k >> 8 & 255)) / 255.0F; f2 += (float)(l * (k >> 0 & 255)) / 255.0F; j += l; } } if (j == 0) { return 0; } else { f = f / (float)j * 255.0F; f1 = f1 / (float)j * 255.0F; f2 = f2 / (float)j * 255.0F; return (int)f << 16 | (int)f1 << 8 | (int)f2; } } } public static PotionType getPotionFromItem(ItemStack itemIn) { return getPotionTypeFromNBT(itemIn.getTagCompound()); } /** * If no correct potion is found, returns the default one : PotionTypes.water */ public static PotionType getPotionTypeFromNBT(@Nullable NBTTagCompound tag) { return tag == null ? PotionTypes.WATER : PotionType.getPotionTypeForName(tag.getString("Potion")); } public static ItemStack addPotionToItemStack(ItemStack itemIn, PotionType potionIn) { ResourceLocation resourcelocation = (ResourceLocation)PotionType.REGISTRY.getNameForObject(potionIn); if (resourcelocation != null) { NBTTagCompound nbttagcompound = itemIn.hasTagCompound() ? itemIn.getTagCompound() : new NBTTagCompound(); nbttagcompound.setString("Potion", resourcelocation.toString()); itemIn.setTagCompound(nbttagcompound); } return itemIn; } public static ItemStack appendEffects(ItemStack itemIn, Collection<PotionEffect> effects) { if (effects.isEmpty()) { return itemIn; } else { NBTTagCompound nbttagcompound = (NBTTagCompound)Objects.firstNonNull(itemIn.getTagCompound(), new NBTTagCompound()); NBTTagList nbttaglist = nbttagcompound.getTagList("CustomPotionEffects", 9); for (PotionEffect potioneffect : effects) { nbttaglist.appendTag(potioneffect.writeCustomPotionEffectToNBT(new NBTTagCompound())); } nbttagcompound.setTag("CustomPotionEffects", nbttaglist); itemIn.setTagCompound(nbttagcompound); return itemIn; } } public static void addPotionTooltip(ItemStack itemIn, List<String> lores, float durationFactor) { List<PotionEffect> list = getEffectsFromStack(itemIn); List<Tuple<String, AttributeModifier>> list1 = Lists.<Tuple<String, AttributeModifier>>newArrayList(); if (list.isEmpty()) { String s = I18n.translateToLocal("effect.none").trim(); lores.add(TextFormatting.GRAY + s); } else { for (PotionEffect potioneffect : list) { String s1 = I18n.translateToLocal(potioneffect.getEffectName()).trim(); Potion potion = potioneffect.getPotion(); Map<IAttribute, AttributeModifier> map = potion.getAttributeModifierMap(); if (!map.isEmpty()) { for (Entry<IAttribute, AttributeModifier> entry : map.entrySet()) { AttributeModifier attributemodifier = (AttributeModifier)entry.getValue(); AttributeModifier attributemodifier1 = new AttributeModifier(attributemodifier.getName(), potion.getAttributeModifierAmount(potioneffect.getAmplifier(), attributemodifier), attributemodifier.getOperation()); list1.add(new Tuple(((IAttribute)entry.getKey()).getAttributeUnlocalizedName(), attributemodifier1)); } } if (potioneffect.getAmplifier() > 0) { s1 = s1 + " " + I18n.translateToLocal("potion.potency." + potioneffect.getAmplifier()).trim(); } if (potioneffect.getDuration() > 20) { s1 = s1 + " (" + Potion.getPotionDurationString(potioneffect, durationFactor) + ")"; } if (potion.isBadEffect()) { lores.add(TextFormatting.RED + s1); } else { lores.add(TextFormatting.BLUE + s1); } } } if (!list1.isEmpty()) { lores.add(""); lores.add(TextFormatting.DARK_PURPLE + I18n.translateToLocal("potion.whenDrank")); for (Tuple<String, AttributeModifier> tuple : list1) { AttributeModifier attributemodifier2 = (AttributeModifier)tuple.getSecond(); double d0 = attributemodifier2.getAmount(); double d1; if (attributemodifier2.getOperation() != 1 && attributemodifier2.getOperation() != 2) { d1 = attributemodifier2.getAmount(); } else { d1 = attributemodifier2.getAmount() * 100.0D; } if (d0 > 0.0D) { lores.add(TextFormatting.BLUE + I18n.translateToLocalFormatted("attribute.modifier.plus." + attributemodifier2.getOperation(), new Object[] {ItemStack.DECIMALFORMAT.format(d1), I18n.translateToLocal("attribute.name." + (String)tuple.getFirst())})); } else if (d0 < 0.0D) { d1 = d1 * -1.0D; lores.add(TextFormatting.RED + I18n.translateToLocalFormatted("attribute.modifier.take." + attributemodifier2.getOperation(), new Object[] {ItemStack.DECIMALFORMAT.format(d1), I18n.translateToLocal("attribute.name." + (String)tuple.getFirst())})); } } } } }
gpl-3.0
VegasGoat/TFCraft
src/Common/com/bioxx/tfc/Items/Tools/ItemTerraTool.java
4036
package com.bioxx.tfc.Items.Tools; import java.util.List; import java.util.Set; import net.minecraft.block.Block; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.item.ItemTool; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.EnumChatFormatting; import net.minecraft.util.IIcon; import net.minecraftforge.common.ForgeHooks; import com.bioxx.tfc.Reference; import com.bioxx.tfc.Core.TFCTabs; import com.bioxx.tfc.Core.TFC_Core; import com.bioxx.tfc.Core.TFC_Textures; import com.bioxx.tfc.Items.ItemTerra; import com.bioxx.tfc.api.Crafting.AnvilManager; import com.bioxx.tfc.api.Enums.EnumItemReach; import com.bioxx.tfc.api.Enums.EnumSize; import com.bioxx.tfc.api.Enums.EnumWeight; import com.bioxx.tfc.api.Interfaces.ICausesDamage; import com.bioxx.tfc.api.Interfaces.ISize; import com.bioxx.tfc.api.Util.Helper; public class ItemTerraTool extends ItemTool implements ISize { //private static boolean registeredGlobalTex = false; public ItemTerraTool(float par2, ToolMaterial par3, Set<Block> par4) { super(par2, par3, par4); this.setCreativeTab(TFCTabs.TFC_TOOLS); setNoRepair(); } @Override public void addInformation(ItemStack is, EntityPlayer player, List arraylist, boolean flag) { //Minecraft.getMinecraft().gameSettings.advancedItemTooltips = false; ItemTerra.addSizeInformation(is, arraylist); ItemTerra.addHeatInformation(is, arraylist); if(is.getItem() instanceof ICausesDamage) arraylist.add(EnumChatFormatting.AQUA + TFC_Core.translate(((ICausesDamage)this).getDamageType().toString())); ItemTerraTool.addSmithingBonusInformation(is, arraylist); addExtraInformation(is, player, arraylist); } public static void addSmithingBonusInformation(ItemStack is, List<String> arraylist) { if (AnvilManager.getDurabilityBuff(is) > 0) arraylist.add(TFC_Core.translate("gui.SmithingBonus") + " : +" + Helper.roundNumber(AnvilManager.getDurabilityBuff(is) * 100, 10) + "%"); } public void addExtraInformation(ItemStack is, EntityPlayer player, List<String> arraylist) { } @Override public int getItemStackLimit() { if(canStack()) return this.getSize(null).stackSize * getWeight(null).multiplier; else return 1; } @Override public void registerIcons(IIconRegister registerer) { this.itemIcon = registerer.registerIcon(Reference.MOD_ID + ":" + "tools/" + this.getUnlocalizedName().replace("item.", "")); if (TFC_Textures.brokenItem == null) TFC_Textures.brokenItem = registerer.registerIcon(Reference.MOD_ID + ":" + "tools/Broken Item"); if (TFC_Textures.wip == null) TFC_Textures.wip = registerer.registerIcon(Reference.MOD_ID + ":" + "wip"); } @Override public EnumItemReach getReach(ItemStack is) { return EnumItemReach.SHORT; } @Override public EnumSize getSize(ItemStack is) { return EnumSize.LARGE; } @Override public boolean canStack() { return false; } @Override public EnumWeight getWeight(ItemStack is) { return EnumWeight.MEDIUM; } @Override public int getMaxDamage(ItemStack stack) { return (int) (getMaxDamage()+(getMaxDamage() * AnvilManager.getDurabilityBuff(stack))); } @Override public float getDigSpeed(ItemStack stack, Block block, int meta) { float digSpeed = super.getDigSpeed(stack, block, meta); if (ForgeHooks.isToolEffective(stack, block, meta)) { return digSpeed + (digSpeed * AnvilManager.getDurabilityBuff(stack)); } return digSpeed; } @Override public boolean requiresMultipleRenderPasses() { return true; } @Override public IIcon getIcon(ItemStack stack, int pass) { NBTTagCompound nbt = stack.getTagCompound(); if(pass == 1 && nbt != null && nbt.hasKey("broken")) return TFC_Textures.brokenItem; else return getIconFromDamageForRenderPass(stack.getItemDamage(), pass); } }
gpl-3.0
H5AutomationFreamWorkForLeadingTreasure/H5AutoFrameWorkLibrary
PageObject/src/main/java/page/app/wallet/TradeCaptialPage.java
796
package page.app.wallet; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.ui.ExpectedConditions; import basicTool.WaitTool; import io.appium.java_client.AppiumDriver; import page.app.AbstractAppPage; public class TradeCaptialPage extends AbstractAppPage { @FindBy(xpath = "//UIAStaticText[@name='余额生息']|//android.widget.TextView[@text='余额生息']") private WebElement tradeCaptialLabel; public TradeCaptialPage(AppiumDriver appiumDriver) { super(appiumDriver); WaitTool.waitFor(appiumDriver, ExpectedConditions.visibilityOf(tradeCaptialLabel), DefaultWaitElementTime4Page); try { Thread.sleep(10000); } catch (InterruptedException e) { } } }
gpl-3.0
cbaakman/Tropicraft
src/main/java/net/tropicraft/block/BlockBambooDoor.java
2819
package net.tropicraft.block; import java.util.Random; import net.minecraft.block.BlockDoor; import net.minecraft.block.material.Material; import net.minecraft.client.renderer.IconFlipped; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.item.Item; import net.minecraft.util.IIcon; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; import net.tropicraft.info.TCInfo; import net.tropicraft.info.TCNames; import net.tropicraft.registry.TCItemRegistry; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; public class BlockBambooDoor extends BlockDoor { @SideOnly(Side.CLIENT) private IIcon[] images; public BlockBambooDoor() { super(Material.plants); this.setBlockTextureName(TCNames.bambooDoor); } /** * Gets the block's texture. Args: side, meta */ @Override @SideOnly(Side.CLIENT) public IIcon getIcon(int side, int meta) { return images[0]; } @Override @SideOnly(Side.CLIENT) public IIcon getIcon(IBlockAccess par1IBlockAccess, int par2, int par3, int par4, int par5) { if (par5 != 1 && par5 != 0) { int i1 = this.func_150012_g(par1IBlockAccess, par2, par3, par4); int j1 = i1 & 3; boolean flag = (i1 & 4) != 0; boolean flag1 = false; boolean flag2 = (i1 & 8) != 0; if (flag) { if (j1 == 0 && par5 == 2) { flag1 = !flag1; } else if (j1 == 1 && par5 == 5) { flag1 = !flag1; } else if (j1 == 2 && par5 == 3) { flag1 = !flag1; } else if (j1 == 3 && par5 == 4) { flag1 = !flag1; } } else { if (j1 == 0 && par5 == 5) { flag1 = !flag1; } else if (j1 == 1 && par5 == 3) { flag1 = !flag1; } else if (j1 == 2 && par5 == 4) { flag1 = !flag1; } else if (j1 == 3 && par5 == 2) { flag1 = !flag1; } if ((i1 & 16) != 0) { flag1 = !flag1; } } return this.images[0 + (flag1 ? 2 : 0) + (flag2 ? 1 : 0)]; } else { return this.images[0]; } } /** * Gets an item for the block being called on. Args: world, x, y, z */ @Override @SideOnly(Side.CLIENT) public Item getItem(World world, int x, int y, int z) { return TCItemRegistry.bambooDoor; } @Override public Item getItemDropped(int p_149650_1_, Random p_149650_2_, int p_149650_3_) { return (p_149650_1_ & 8) != 0 ? null : (TCItemRegistry.bambooDoor); } @Override @SideOnly(Side.CLIENT) public void registerBlockIcons(IIconRegister register) { this.images = new IIcon[4]; this.images[0] = register.registerIcon(TCInfo.ICON_LOCATION + this.getTextureName() + "_Bottom"); this.images[1] = register.registerIcon(TCInfo.ICON_LOCATION + this.getTextureName() + "_Top"); this.images[2] = new IconFlipped(this.images[0], true, false); this.images[3] = new IconFlipped(this.images[1], true, false); } }
mpl-2.0
tarique313/nBilling
src/java/com/sapienter/jbilling/server/process/task/BasicAgeingTask.java
19891
/* * JBILLING CONFIDENTIAL * _____________________ * * [2003] - [2012] Enterprise jBilling Software Ltd. * All Rights Reserved. * * NOTICE: All information contained herein is, and remains * the property of Enterprise jBilling Software. * The intellectual and technical concepts contained * herein are proprietary to Enterprise jBilling Software * and are protected by trade secret or copyright law. * Dissemination of this information or reproduction of this material * is strictly forbidden. */ package com.sapienter.jbilling.server.process.task; import com.sapienter.jbilling.server.invoice.InvoiceBL; import com.sapienter.jbilling.server.invoice.db.InvoiceDAS; import com.sapienter.jbilling.server.invoice.db.InvoiceDTO; import com.sapienter.jbilling.server.notification.INotificationSessionBean; import com.sapienter.jbilling.server.notification.MessageDTO; import com.sapienter.jbilling.server.notification.NotificationBL; import com.sapienter.jbilling.server.notification.NotificationNotFoundException; import com.sapienter.jbilling.server.order.OrderBL; import com.sapienter.jbilling.server.order.db.OrderDAS; import com.sapienter.jbilling.server.order.db.OrderDTO; import com.sapienter.jbilling.server.pluggableTask.PluggableTask; import com.sapienter.jbilling.server.process.AgeingDTOEx; import com.sapienter.jbilling.server.process.db.AgeingEntityStepDAS; import com.sapienter.jbilling.server.process.db.AgeingEntityStepDTO; import com.sapienter.jbilling.server.process.event.NewUserStatusEvent; import com.sapienter.jbilling.server.system.event.EventManager; import com.sapienter.jbilling.server.user.UserBL; import com.sapienter.jbilling.server.user.UserDTOEx; import com.sapienter.jbilling.server.user.db.UserDAS; import com.sapienter.jbilling.server.user.db.UserDTO; import com.sapienter.jbilling.server.user.db.UserStatusDAS; import com.sapienter.jbilling.server.user.db.UserStatusDTO; import com.sapienter.jbilling.server.util.Constants; import com.sapienter.jbilling.server.util.Context; import com.sapienter.jbilling.server.util.PreferenceBL; import com.sapienter.jbilling.server.util.audit.EventLogger; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.NameValuePair; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.log4j.Logger; import org.hibernate.ScrollableResults; import org.springframework.dao.EmptyResultDataAccessException; import javax.naming.NamingException; import javax.sql.rowset.CachedRowSet; import java.sql.SQLException; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; /** * BasicAgeingTask * * @author Brian Cowdery * @since 28/04/11 */ public class BasicAgeingTask extends PluggableTask implements IAgeingTask { private static final Logger LOG = Logger.getLogger(BasicAgeingTask.class); private final EventLogger eLogger = EventLogger.getInstance(); private static Calendar calendar = GregorianCalendar.getInstance(); static { calendar.clear(); } private Map<Integer, Integer> gracePeriodCache = new HashMap<Integer, Integer>(); protected int getGracePeriod(Integer entityId) { if (!gracePeriodCache.containsKey(entityId)) { PreferenceBL preference = new PreferenceBL(); preference.set(entityId, Constants.PREFERENCE_GRACE_PERIOD); gracePeriodCache.put(entityId, preference.getInt()); } return gracePeriodCache.get(entityId); } /** * Review all users for the given day, and age those that have outstanding invoices over * the set number of days for an ageing step. * * @param steps ageing steps * @param today today's date * @param executorId executor id */ public void reviewAllUsers(Integer entityId, Set<AgeingEntityStepDTO> steps, Date today, Integer executorId) { LOG.debug("Reviewing users for entity " + entityId + " ..."); // go over all the users already in the ageing system for (UserDTO user : new UserDAS().findAgeing(entityId)) { ageUser(steps, user, today, executorId); } // go over the active users with payable invoices try { UserDAS userDas = new UserDAS(); InvoiceDAS invoiceDas = new InvoiceDAS(); CachedRowSet users = new UserBL().findActiveWithOpenInvoices(entityId); while (users.next()) { Integer userId = users.getInt(1); UserDTO user = userDas.find(userId); int gracePeriod = getGracePeriod(entityId); LOG.debug("Reviewing invoices for user " + user.getId() + " using a grace period of " + gracePeriod + " days."); for (InvoiceDTO invoice : invoiceDas.findProccesableByUser(user)) { if (isInvoiceOverdue(invoice, user, gracePeriod, today)) { ageUser(steps, user, today, executorId); break; } } } } catch (SQLException e) { LOG.error("Failed to fetch users with payable invoices.", e); } catch (NamingException e) { LOG.error("Exception fetching users with payable invoices.", e); } } /** * Moves a user one step forward in the ageing process (move from active -> suspended etc.). The * user will only be moved if they have spent long enough in their present status. * * @param steps ageing steps * @param user user to age * @param today today's date * @return the resulting ageing step for the user after ageing */ public AgeingEntityStepDTO ageUser(Set<AgeingEntityStepDTO> steps, UserDTO user, Date today, Integer executorId) { LOG.debug("Ageing user " + user.getId()); Integer currentStatusId = user.getStatus().getId(); UserStatusDTO nextStatus = null; AgeingEntityStepDTO ageingStep = null; if (currentStatusId.equals(UserDTOEx.STATUS_ACTIVE)) { // send welcome message (initial step after active). nextStatus = getNextAgeingStep(steps, UserDTOEx.STATUS_ACTIVE); } else { // user already in the ageing process ageingStep = new AgeingEntityStepDAS().findStep(user.getEntity().getId(), currentStatusId); if (ageingStep != null) { // determine the next ageing step if (isAgeingRequired(user, ageingStep, today)) { nextStatus = getNextAgeingStep(steps, currentStatusId); LOG.debug("User " + user.getId() + " needs to be aged to '" + getStatusDescription(nextStatus) + "'"); } } else { // User is in a non-existent ageing status... Either the status was removed or // the data is bad. As a workaround, just move to the next status. nextStatus = getNextAgeingStep(steps, currentStatusId); LOG.warn("User " + user.getId() + " is in an invalid ageing step. Moving to '" + getStatusDescription(nextStatus) + "'"); } } // set status if (nextStatus != null) { setUserStatus(user, nextStatus, today, null); } else { LOG.debug("Next status is null, no further ageing steps are available."); eLogger.warning(user.getEntity().getId(), user.getUserId(), user.getUserId(), EventLogger.MODULE_USER_MAINTENANCE, EventLogger.NO_FURTHER_STEP, Constants.TABLE_BASE_USER); } return ageingStep; } /** * Returns true if the given invoice is overdue. * * @param invoice invoice to check * @param user user owning the invoice * @param gracePeriod company wide grace period * @param today today's date * @return true if invoice is overdue, false if not */ public boolean isInvoiceOverdue(InvoiceDTO invoice, UserDTO user, Integer gracePeriod, Date today) { calendar.clear(); calendar.setTime(invoice.getDueDate()); calendar.add(Calendar.DATE, gracePeriod); if (calendar.getTime().before(today)) { LOG.debug("Invoice is overdue (due date " + invoice.getDueDate() + " + " + gracePeriod + " days grace, is before today " + today + ")"); return true; } LOG.debug("Invoice is NOT overdue (due date " + invoice.getDueDate() + " + " + gracePeriod + " days grace is after today " + today + ")"); return false; } /** * Returns true if the user requires ageing. * * @param user user being reviewed * @param currentStep current ageing step of the user * @param today today's date * @return true if user requires ageing, false if not */ public boolean isAgeingRequired(UserDTO user, AgeingEntityStepDTO currentStep, Date today) { Date lastStatusChange = user.getLastStatusChange() != null ? user.getLastStatusChange() : user.getCreateDatetime(); calendar.clear(); calendar.setTime(lastStatusChange); calendar.add(Calendar.DATE, currentStep.getDays()); if (calendar.getTime().equals(today) || calendar.getTime().before(today)) { LOG.debug("User status has expired (last change " + lastStatusChange + " + " + currentStep.getDays() + " days is before today " + today + ")"); return true; } LOG.debug("User does not need to be aged (last change " + lastStatusChange + " + " + currentStep.getDays() + " days is after today " + today + ")"); return false; } /** * Removes a user from the ageing process (makes them active), ONLY if they do not * still have overdue invoices. * * @param user user to make active * @param excludedInvoiceId invoice id to ignore when determining if the user CAN be made active * @param executorId executor id */ public void removeUser(UserDTO user, Integer executorId, Integer excludedInvoiceId) { Date now = new Date(); // validate that the user actually needs a status change if (user.getStatus().getId() != UserDTOEx.STATUS_ACTIVE) { LOG.debug("User " + user.getId() + " is already active, no need to remove from ageing."); return; } // validate that the user does not still have overdue invoices try { if (new InvoiceBL().isUserWithOverdueInvoices(user.getUserId(), now, excludedInvoiceId)) { LOG.debug("User " + user.getId() + " still has overdue invoices, cannot remove from ageing."); return; } } catch (SQLException e) { LOG.error("Exception occurred checking for overdue invoices.", e); return; } // make the status change. LOG.debug("Removing user " + user.getUserId() + " from ageing (making active)."); UserStatusDTO status = new UserStatusDAS().find(UserDTOEx.STATUS_ACTIVE); setUserStatus(user, status, now, null); } /** * Sets the user status to the given "aged" status. If the user status is already set to the aged status * no changes will be made. This method also performs an HTTP callback and sends a notification * message when a status change is made. * * If the user becomes suspended and can no longer log-in to the system, all of their active orders will * be automatically suspended. * * If the user WAS suspended and becomes active (and can now log-in to the system), any automatically * suspended orders will be re-activated. * * @param user user * @param status status to set * @param today today's date * @param executorId executor id */ public void setUserStatus(UserDTO user, UserStatusDTO status, Date today, Integer executorId) { // only set status if the new "aged" status is different from the users current status if (status.getId() == user.getStatus().getId()) { return; } LOG.debug("Setting user " + user.getId() + " status to '" + getStatusDescription(status) + "'"); if (executorId != null) { // this came from the gui eLogger.audit(executorId, user.getId(), Constants.TABLE_BASE_USER, user.getId(), EventLogger.MODULE_USER_MAINTENANCE, EventLogger.STATUS_CHANGE, user.getStatus().getId(), null, null); } else { // this is from a process, no executor involved eLogger.auditBySystem(user.getCompany().getId(), user.getId(), Constants.TABLE_BASE_USER, user.getId(), EventLogger.MODULE_USER_MAINTENANCE, EventLogger.STATUS_CHANGE, user.getStatus().getId(), null, null); } // make the change boolean couldLogin = user.getStatus().getCanLogin() == 1; UserStatusDTO oldStatus = user.getStatus(); user.setUserStatus(status); user.setLastStatusChange(today); // status changed to deleted, remove user if (status.getId() == UserDTOEx.STATUS_DELETED) { LOG.debug("Deleting user " + user.getId()); new UserBL(user.getId()).delete(executorId); return; } // status changed from active to suspended // suspend customer orders if (couldLogin && status.getCanLogin() == 0) { LOG.debug("User " + user.getId() + " cannot log-in to the system. Suspending active orders."); OrderBL orderBL = new OrderBL(); ScrollableResults orders = new OrderDAS().findByUser_Status(user.getId(), Constants.ORDER_STATUS_ACTIVE); while (orders.next()) { OrderDTO order = (OrderDTO) orders.get()[0]; orderBL.set(order); orderBL.setStatus(executorId, Constants.ORDER_STATUS_SUSPENDED_AGEING); } orders.close(); } // status changed from suspended to active // re-active suspended customer orders if (!couldLogin && status.getCanLogin() == 1) { LOG.debug("User " + user.getId() + " can now log-in to the system. Activating previously suspended orders."); OrderBL orderBL = new OrderBL(); ScrollableResults orders = new OrderDAS().findByUser_Status(user.getId(), Constants.ORDER_STATUS_SUSPENDED_AGEING); while (orders.next()) { OrderDTO order = (OrderDTO) orders.get()[0]; orderBL.set(order); orderBL.setStatus(executorId, Constants.ORDER_STATUS_ACTIVE); } orders.close(); } // perform callbacks and notifications performAgeingCallback(user, oldStatus, status); sendAgeingNotification(user, oldStatus, status); // emit NewUserStatusEvent NewUserStatusEvent event = new NewUserStatusEvent(user.getCompany().getId(), user.getId(), oldStatus.getId(), status.getId()); EventManager.process(event); } protected boolean performAgeingCallback(UserDTO user, UserStatusDTO oldStatus, UserStatusDTO newStatus) { String url = null; try { PreferenceBL pref = new PreferenceBL(); pref.set(user.getEntity().getId(), Constants.PREFERENCE_URL_CALLBACK); url = pref.getString(); } catch (EmptyResultDataAccessException e) { /* ignore, no callback preference configured */ } if (url != null && url.length() > 0) { try { LOG.debug("Performing ageing HTTP callback for URL: " + url); // cook the parameters to be sent NameValuePair[] data = new NameValuePair[6]; data[0] = new NameValuePair("cmd", "ageing_update"); data[1] = new NameValuePair("user_id", String.valueOf(user.getId())); data[2] = new NameValuePair("login_name", user.getUserName()); data[3] = new NameValuePair("from_status", String.valueOf(oldStatus.getId())); data[4] = new NameValuePair("to_status", String.valueOf(newStatus.getId())); data[5] = new NameValuePair("can_login", String.valueOf(newStatus.getCanLogin())); // make the call HttpClient client = new HttpClient(); client.setConnectionTimeout(30000); PostMethod post = new PostMethod(url); post.setRequestBody(data); client.executeMethod(post); } catch (Exception e) { LOG.error("Exception occurred posting ageing HTTP callback for URL: " + url, e); return false; } } return true; } protected boolean sendAgeingNotification(UserDTO user, UserStatusDTO oldStatus, UserStatusDTO newStatus) { try { MessageDTO message = new NotificationBL().getAgeingMessage(user.getEntity().getId(), user.getLanguage().getId(), newStatus.getId(), user.getId()); INotificationSessionBean notification = (INotificationSessionBean) Context.getBean(Context.Name.NOTIFICATION_SESSION); notification.notify(user, message); } catch (NotificationNotFoundException e) { LOG.warn("Failed to send ageing notification. Entity " + user.getEntity().getId() + " does not have an ageing message configured for status '" + getStatusDescription(newStatus) + "'."); return false; } return true; } /** * Get the status for the next step in the ageing process, based on the users * current status. * * @param steps configured ageing steps * @param currentStatusId the current user status */ public UserStatusDTO getNextAgeingStep(Set<AgeingEntityStepDTO> steps, Integer currentStatusId) { for (AgeingEntityStepDTO step : steps) { Integer stepStatusId = step.getUserStatus().getId(); if (stepStatusId.compareTo(currentStatusId) > 0) { return step.getUserStatus(); } } return null; } /** * Null safe convenience method to return the status description. * * @param status user status * @return description */ private String getStatusDescription(UserStatusDTO status) { if (status != null) { return status.getDescription(); } return null; } }
agpl-3.0
ufosky-server/actor-platform
actor-sdk/sdk-core-android/android-sdk/src/main/java/im/actor/sdk/intents/ActorIntentFragmentActivity.java
592
package im.actor.sdk.intents; import android.content.Intent; public class ActorIntentFragmentActivity extends ActorIntentActivity { android.support.v4.app.Fragment fragment; public ActorIntentFragmentActivity(Intent intent) { super(intent); } public ActorIntentFragmentActivity(Intent intent, android.support.v4.app.Fragment fragment) { super(intent); this.fragment = fragment; } public ActorIntentFragmentActivity() { super(null); } public android.support.v4.app.Fragment getFragment() { return fragment; } }
agpl-3.0
brtonnies/rapidminer-studio
src/main/java/com/rapidminer/gui/tools/EditBlockingProgressThread.java
2462
/** * Copyright (C) 2001-2015 by RapidMiner and the contributors * * Complete list of developers available at our web site: * * http://rapidminer.com * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see http://www.gnu.org/licenses/. */ package com.rapidminer.gui.tools; import java.util.concurrent.atomic.AtomicInteger; import javax.swing.SwingUtilities; /** * Thread that disables GUI components that interfere with process editing while running. * * @author Simon Fischer * */ public abstract class EditBlockingProgressThread extends ProgressThread { private Object lock = new Object(); private boolean isComplete = false; private boolean mustReenable = false; private static AtomicInteger pendingThreads = new AtomicInteger(0); public EditBlockingProgressThread(String i18nKey) { super(i18nKey); } /** Implement this method rather than {@link #run()} to perform the actual task. */ public abstract void execute(); @Override public final void run() { try { execute(); } finally { synchronized (lock) { lock.notify(); isComplete = true; if ((pendingThreads.decrementAndGet() == 0) && mustReenable) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { SwingTools.setProcessEditorsEnabled(true); } }); } } } } @Override public void start() { super.start(); // We are on the EDT. BLock GUI a few milliseconds and see if we are complete synchronized (lock) { pendingThreads.incrementAndGet(); try { lock.wait(200); } catch (InterruptedException e) { } if (!isComplete) { mustReenable = true; SwingTools.setProcessEditorsEnabled(false); } } } public static boolean isEditing() { return pendingThreads.get() > 0; } }
agpl-3.0
mediaworx/opencms-core
src-modules/org/opencms/workplace/tools/modules/CmsModulesEditBase.java
12068
/* * This library is part of OpenCms - * the Open Source Content Management System * * Copyright (c) Alkacon Software GmbH (http://www.alkacon.com) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * For further information about Alkacon Software GmbH, please see the * company website: http://www.alkacon.com * * For further information about OpenCms, please see the * project website: http://www.opencms.org * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package org.opencms.workplace.tools.modules; import org.opencms.db.CmsExportPoint; import org.opencms.file.types.CmsResourceTypeFolder; import org.opencms.jsp.CmsJspActionElement; import org.opencms.main.CmsException; import org.opencms.main.OpenCms; import org.opencms.module.CmsModule; import org.opencms.util.CmsStringUtil; import org.opencms.workplace.CmsDialog; import org.opencms.workplace.CmsWidgetDialog; import org.opencms.workplace.CmsWorkplace; import org.opencms.workplace.CmsWorkplaceSettings; import java.util.List; import java.util.Map; import java.util.Set; import java.util.StringTokenizer; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.jsp.PageContext; /** * Base class to edit an exiting module.<p> * * @since 6.0.0 */ public class CmsModulesEditBase extends CmsWidgetDialog { /** localized messages Keys prefix. */ public static final String KEY_PREFIX = "modules"; /** The dialog type. */ public static final String DIALOG_TYPE = "ModulesEdit"; /** Defines which pages are valid for this dialog. */ public static final String[] PAGES = {"page1"}; /** Classes folder within the module. */ public static final String PATH_CLASSES = "classes/"; /** Elements folder within the module. */ public static final String PATH_ELEMENTS = "elements/"; /** Lib folder within the module. */ public static final String PATH_LIB = "lib/"; /** Resources folder within the module. */ public static final String PATH_RESOURCES = "resources/"; /** Schemas folder within the module. */ public static final String PATH_SCHEMAS = "schemas/"; /** Template folder within the module. */ public static final String PATH_TEMPLATES = "templates/"; /** The formatters folder within the module. */ public static final String PATH_FORMATTERS = "formatters/"; /** The module object that is edited on this dialog. */ protected CmsModule m_module; /** Module name. */ protected String m_paramModule; /** * Public constructor with JSP action element.<p> * * @param jsp an initialized JSP action element */ public CmsModulesEditBase(CmsJspActionElement jsp) { super(jsp); } /** * Public constructor with JSP variables.<p> * * @param context the JSP page context * @param req the JSP request * @param res the JSP response */ public CmsModulesEditBase(PageContext context, HttpServletRequest req, HttpServletResponse res) { this(new CmsJspActionElement(context, req, res)); } /** * Commits the edited module.<p> */ @Override public void actionCommit() { if (!hasCommitErrors()) { //check if we have to update an existing module or to create a new one Set<String> moduleNames = OpenCms.getModuleManager().getModuleNames(); if (moduleNames.contains(m_module.getName())) { // update the module information try { OpenCms.getModuleManager().updateModule(getCms(), m_module); } catch (CmsException e) { addCommitError(e); } } else { try { m_module = createModuleFolders((CmsModule)m_module.clone()); OpenCms.getModuleManager().addModule(getCms(), m_module); } catch (CmsException e) { addCommitError(e); } } } if (!hasCommitErrors()) { // refresh the list Map<?, ?> objects = (Map<?, ?>)getSettings().getListObject(); if (objects != null) { objects.remove(CmsModulesList.class.getName()); } } } /** * @see org.opencms.workplace.CmsDialog#getCancelAction() */ @Override public String getCancelAction() { // set the default action setParamPage(getPages().get(0)); return DIALOG_SET; } /** * Gets the module parameter.<p> * * @return the module parameter */ public String getParamModule() { return m_paramModule; } /** * Sets the module parameter.<p> * @param paramModule the module parameter */ public void setParamModule(String paramModule) { m_paramModule = paramModule; } /** * Creates the list of widgets for this dialog.<p> */ @Override protected void defineWidgets() { initModule(); setKeyPrefix(KEY_PREFIX); } /** * @see org.opencms.workplace.CmsWidgetDialog#getPageArray() */ @Override protected String[] getPageArray() { return PAGES; } /** * @see org.opencms.workplace.CmsWorkplace#initMessages() */ @Override protected void initMessages() { // add specific dialog resource bundle addMessages(Messages.get().getBundleName()); // add default resource bundles super.initMessages(); } /** * Initializes the module to work with depending on the dialog state and request parameters.<p> */ protected void initModule() { Object o; if (CmsStringUtil.isEmpty(getParamAction()) || CmsDialog.DIALOG_INITIAL.equals(getParamAction())) { // this is the initial dialog call if (CmsStringUtil.isNotEmpty(m_paramModule)) { // edit an existing module, get it from manager o = OpenCms.getModuleManager().getModule(m_paramModule); } else { // create a new module o = null; } } else { // this is not the initial call, get module from session o = getDialogObject(); } if (!(o instanceof CmsModule)) { // create a new module m_module = new CmsModule(); } else { // reuse module stored in session m_module = (CmsModule)((CmsModule)o).clone(); } } /** * @see org.opencms.workplace.CmsWorkplace#initWorkplaceRequestValues(org.opencms.workplace.CmsWorkplaceSettings, javax.servlet.http.HttpServletRequest) */ @Override protected void initWorkplaceRequestValues(CmsWorkplaceSettings settings, HttpServletRequest request) { // set the dialog type setParamDialogtype(DIALOG_TYPE); super.initWorkplaceRequestValues(settings, request); // save the current state of the module (may be changed because of the widget values) setDialogObject(m_module); } /** * @see org.opencms.workplace.CmsWidgetDialog#validateParamaters() */ @Override protected void validateParamaters() throws Exception { String moduleName = getParamModule(); // check module if (!isNewModule()) { CmsModule module = OpenCms.getModuleManager().getModule(moduleName); if (module == null) { throw new Exception(); } } } /** * Creates all module folders that are selected in the input form.<p> * * @param module the module * * @return the updated module * * @throws CmsException if somehting goes wrong */ private CmsModule createModuleFolders(CmsModule module) throws CmsException { String modulePath = CmsWorkplace.VFS_PATH_MODULES + module.getName() + "/"; List<CmsExportPoint> exportPoints = module.getExportPoints(); List<String> resources = module.getResources(); // set the createModuleFolder flag if any other flag is set if (module.isCreateClassesFolder() || module.isCreateElementsFolder() || module.isCreateLibFolder() || module.isCreateResourcesFolder() || module.isCreateSchemasFolder() || module.isCreateTemplateFolder() || module.isCreateFormattersFolder()) { module.setCreateModuleFolder(true); } // check if we have to create the module folder int folderId = CmsResourceTypeFolder.getStaticTypeId(); if (module.isCreateModuleFolder()) { getCms().createResource(modulePath, folderId); // add the module folder to the resource list resources.add(modulePath); module.setResources(resources); } // check if we have to create the template folder if (module.isCreateTemplateFolder()) { String path = modulePath + PATH_TEMPLATES; getCms().createResource(path, folderId); } // check if we have to create the elements folder if (module.isCreateElementsFolder()) { String path = modulePath + PATH_ELEMENTS; getCms().createResource(path, folderId); } if (module.isCreateFormattersFolder()) { String path = modulePath + PATH_FORMATTERS; getCms().createResource(path, folderId); } // check if we have to create the schemas folder if (module.isCreateSchemasFolder()) { String path = modulePath + PATH_SCHEMAS; getCms().createResource(path, folderId); } // check if we have to create the resources folder if (module.isCreateResourcesFolder()) { String path = modulePath + PATH_RESOURCES; getCms().createResource(path, folderId); } // check if we have to create the lib folder if (module.isCreateLibFolder()) { String path = modulePath + PATH_LIB; getCms().createResource(path, folderId); CmsExportPoint exp = new CmsExportPoint(path, "WEB-INF/lib/"); exportPoints.add(exp); module.setExportPoints(exportPoints); } // check if we have to create the classes folder if (module.isCreateClassesFolder()) { String path = modulePath + PATH_CLASSES; getCms().createResource(path, folderId); CmsExportPoint exp = new CmsExportPoint(path, "WEB-INF/classes/"); exportPoints.add(exp); module.setExportPoints(exportPoints); // now create all subfolders for the package structure StringTokenizer tok = new StringTokenizer(m_module.getName(), "."); while (tok.hasMoreTokens()) { String folder = tok.nextToken(); path += folder + "/"; getCms().createResource(path, folderId); } } return module; } /** * Checks if the new module dialog has to be displayed.<p> * * @return <code>true</code> if the new module dialog has to be displayed */ private boolean isNewModule() { return getCurrentToolPath().equals("/modules/modules_new"); } }
lgpl-2.1
JordanReiter/railo
railo-java/railo-core/src/railo/runtime/listener/JavaSettingsImpl.java
2267
package railo.runtime.listener; import java.util.ArrayList; import java.util.List; import railo.commons.io.res.Resource; import railo.commons.io.res.util.ResourceUtil; import railo.runtime.type.util.ArrayUtil; public class JavaSettingsImpl implements JavaSettings { private final Resource[] resources; private Resource[] resourcesTranslated; private final boolean loadCFMLClassPath; private final boolean reloadOnChange; private final int watchInterval; private final String[] watchedExtensions; public JavaSettingsImpl(){ this.resources=new Resource[0]; this.loadCFMLClassPath=false; this.reloadOnChange=false; this.watchInterval=60; this.watchedExtensions=new String[]{"jar","class"}; } public JavaSettingsImpl(Resource[] resources, Boolean loadCFMLClassPath,boolean reloadOnChange, int watchInterval, String[] watchedExtensions) { this.resources=resources; this.loadCFMLClassPath=loadCFMLClassPath; this.reloadOnChange=reloadOnChange; this.watchInterval=watchInterval; this.watchedExtensions=watchedExtensions; } @Override public Resource[] getResources() { return resources; } // FUTURE add to interface public Resource[] getResourcesTranslated() { if(resourcesTranslated==null) { List<Resource> list=new ArrayList<Resource>(); _getResourcesTranslated(list,resources, true); resourcesTranslated=list.toArray(new Resource[list.size()]); } return resourcesTranslated; } public static void _getResourcesTranslated(List<Resource> list, Resource[] resources, boolean deep) { if(ArrayUtil.isEmpty(resources)) return; for(int i=0;i<resources.length;i++){ if(resources[i].isFile()) { if(ResourceUtil.getExtension(resources[i], "").equalsIgnoreCase("jar")) list.add(resources[i]); } else if(deep && resources[i].isDirectory()){ list.add(resources[i]); // add as possible classes dir _getResourcesTranslated(list,resources[i].listResources(),false); } } } @Override public boolean loadCFMLClassPath() { return loadCFMLClassPath; } @Override public boolean reloadOnChange() { return reloadOnChange; } @Override public int watchInterval() { return watchInterval; } @Override public String[] watchedExtensions() { return watchedExtensions; } }
lgpl-2.1
sbliven/biojava
biojava3-aa-prop/src/main/java/org/biojava3/aaproperties/profeat/convertor/Convertor.java
2557
package org.biojava3.aaproperties.profeat.convertor; import org.biojava3.core.sequence.ProteinSequence; public abstract class Convertor { /** * Based on Table 2 of http://nar.oxfordjournals.org/content/34/suppl_2/W32.full.pdf<br/> * An abstract class to convert a protein sequence into representation of different attribute with each attribute having 3 groups.<br/> * The seven different attributes are<p/> * Hydrophobicity (Polar, Neutral, Hydrophobicity)<br/> * Normalized van der Waals volume (Range 0 - 2.78, 2.95 - 4.0, 4.03 - 8.08)<br/> * Polarity (Value 4.9 - 6.2, 8.0 - 9.2, 10.4 - 13.0)<br/> * Polarizability (Value 0 - 1.08, 0.128 - 0.186, 0.219 - 0.409)<br/> * Charge (Positive, Neutral, Negative)<br/> * Secondary structure (Helix, Strand, Coil)<br/> * Solvent accessibility (Buried, Exposed, Intermediate)<br/> * * @author kohchuanhock * @version 2011.06.09 */ public final static char group1 = '1'; public final static char group2 = '2'; public final static char group3 = '3'; public final static char unknownGroup = '0'; /** * Returns the grouping of the amino acid character. * The aminoAcid argument is preferably of non-ambiguous characters. * Standard amino acids will be converted to '1', '2' or '3' depending on its grouping * Non-standard amino acids are simply converted to '0'. * * @param aminoAcid * an amino acid character preferably of non-ambiguous characters * @return its grouping */ public abstract char convert(char aminoAcid); /** * Returns the groupings of the attribute * @return the groupings of the attribute */ public abstract String[] getGrouping(); /** * Return the attribute of the grouping * @return the attribute of the grouping */ public abstract String getAttribute(); /** * Returns the converted sequence. * The sequence argument must be a protein sequence consisting of preferably non-ambiguous characters only. * Standard amino acids will be converted to '1', '2' or '3' depending on its grouping * Non-standard amino acids are simply converted to '0'. * * @param sequence * a protein sequence consisting of preferably non-ambiguous characters only * @return the converted sequence */ public String convert(ProteinSequence sequence){ String convertedSequence = ""; String uppercaseSequence = sequence.getSequenceAsString().toUpperCase(); for(int x = 0; x < uppercaseSequence.length(); x++){ convertedSequence += convert(uppercaseSequence.charAt(x)); } return convertedSequence; } }
lgpl-2.1
boredherobrine13/morefuelsmod-1.10
build/tmp/recompileMc/sources/net/minecraft/entity/projectile/EntityWitherSkull.java
5563
package net.minecraft.entity.projectile; import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.boss.EntityWither; import net.minecraft.init.MobEffects; import net.minecraft.network.datasync.DataParameter; import net.minecraft.network.datasync.DataSerializers; import net.minecraft.network.datasync.EntityDataManager; import net.minecraft.potion.PotionEffect; import net.minecraft.util.DamageSource; import net.minecraft.util.datafix.DataFixer; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.RayTraceResult; import net.minecraft.world.EnumDifficulty; import net.minecraft.world.Explosion; import net.minecraft.world.World; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; public class EntityWitherSkull extends EntityFireball { private static final DataParameter<Boolean> INVULNERABLE = EntityDataManager.<Boolean>createKey(EntityWitherSkull.class, DataSerializers.BOOLEAN); public EntityWitherSkull(World worldIn) { super(worldIn); this.setSize(0.3125F, 0.3125F); } public EntityWitherSkull(World worldIn, EntityLivingBase shooter, double accelX, double accelY, double accelZ) { super(worldIn, shooter, accelX, accelY, accelZ); this.setSize(0.3125F, 0.3125F); } public static void registerFixesWitherSkull(DataFixer fixer) { EntityFireball.registerFixesFireball(fixer, "WitherSkull"); } /** * Return the motion factor for this projectile. The factor is multiplied by the original motion. */ protected float getMotionFactor() { return this.isInvulnerable() ? 0.73F : super.getMotionFactor(); } @SideOnly(Side.CLIENT) public EntityWitherSkull(World worldIn, double x, double y, double z, double accelX, double accelY, double accelZ) { super(worldIn, x, y, z, accelX, accelY, accelZ); this.setSize(0.3125F, 0.3125F); } /** * Returns true if the entity is on fire. Used by render to add the fire effect on rendering. */ public boolean isBurning() { return false; } /** * Explosion resistance of a block relative to this entity */ public float getExplosionResistance(Explosion explosionIn, World worldIn, BlockPos pos, IBlockState blockStateIn) { float f = super.getExplosionResistance(explosionIn, worldIn, pos, blockStateIn); Block block = blockStateIn.getBlock(); if (this.isInvulnerable() && block.canEntityDestroy(blockStateIn, worldIn, pos, this)) { f = Math.min(0.8F, f); } return f; } /** * Called when this EntityFireball hits a block or entity. */ protected void onImpact(RayTraceResult result) { if (!this.worldObj.isRemote) { if (result.entityHit != null) { if (this.shootingEntity != null) { if (result.entityHit.attackEntityFrom(DamageSource.causeMobDamage(this.shootingEntity), 8.0F)) { if (result.entityHit.isEntityAlive()) { this.applyEnchantments(this.shootingEntity, result.entityHit); } else { this.shootingEntity.heal(5.0F); } } } else { result.entityHit.attackEntityFrom(DamageSource.magic, 5.0F); } if (result.entityHit instanceof EntityLivingBase) { int i = 0; if (this.worldObj.getDifficulty() == EnumDifficulty.NORMAL) { i = 10; } else if (this.worldObj.getDifficulty() == EnumDifficulty.HARD) { i = 40; } if (i > 0) { ((EntityLivingBase)result.entityHit).addPotionEffect(new PotionEffect(MobEffects.WITHER, 20 * i, 1)); } } } this.worldObj.newExplosion(this, this.posX, this.posY, this.posZ, 1.0F, false, this.worldObj.getGameRules().getBoolean("mobGriefing")); this.setDead(); } } /** * Returns true if other Entities should be prevented from moving through this Entity. */ public boolean canBeCollidedWith() { return false; } /** * Called when the entity is attacked. */ public boolean attackEntityFrom(DamageSource source, float amount) { return false; } protected void entityInit() { this.dataManager.register(INVULNERABLE, Boolean.valueOf(false)); } /** * Return whether this skull comes from an invulnerable (aura) wither boss. */ public boolean isInvulnerable() { return ((Boolean)this.dataManager.get(INVULNERABLE)).booleanValue(); } /** * Set whether this skull comes from an invulnerable (aura) wither boss. */ public void setInvulnerable(boolean invulnerable) { this.dataManager.set(INVULNERABLE, Boolean.valueOf(invulnerable)); } protected boolean isFireballFiery() { return false; } }
lgpl-2.1
ambs/exist
extensions/indexes/range/src/main/java/org/exist/xquery/modules/range/Lookup.java
20229
/* * eXist-db Open Source Native XML Database * Copyright (C) 2001 The eXist-db Authors * * info@exist-db.org * http://www.exist-db.org * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ package org.exist.xquery.modules.range; import org.exist.collections.Collection; import org.exist.dom.persistent.DocumentSet; import org.exist.dom.persistent.NodeSet; import org.exist.dom.QName; import org.exist.dom.persistent.VirtualNodeSet; import org.exist.indexing.range.RangeIndex; import org.exist.indexing.range.RangeIndexConfig; import org.exist.indexing.range.RangeIndexConfigElement; import org.exist.indexing.range.RangeIndexWorker; import org.exist.storage.ElementValue; import org.exist.storage.IndexSpec; import org.exist.storage.NodePath; import org.exist.xmldb.XmldbURI; import org.exist.xquery.*; import org.exist.xquery.value.*; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; public class Lookup extends Function implements Optimizable { private final static SequenceType[] PARAMETER_TYPE = new SequenceType[] { new FunctionParameterSequenceType("nodes", Type.NODE, Cardinality.ZERO_OR_MORE, "The node set to search using a range index which is defined on those nodes"), new FunctionParameterSequenceType("key", Type.ATOMIC, Cardinality.ZERO_OR_MORE, "The key to look up.") }; private final static String DESCRIPTION = "Search for nodes matching the given keys in the range " + "index. Normally this function will be called by the query optimizer."; public final static FunctionSignature[] signatures = { new FunctionSignature( new QName("eq", RangeIndexModule.NAMESPACE_URI, RangeIndexModule.PREFIX), DESCRIPTION, PARAMETER_TYPE, new FunctionReturnSequenceType(Type.NODE, Cardinality.ZERO_OR_MORE, "all nodes from the input node set whose node value is equal to the key.") ), new FunctionSignature( new QName("gt", RangeIndexModule.NAMESPACE_URI, RangeIndexModule.PREFIX), DESCRIPTION, PARAMETER_TYPE, new FunctionReturnSequenceType(Type.NODE, Cardinality.ZERO_OR_MORE, "all nodes from the input node set whose node value is equal to the key.") ), new FunctionSignature( new QName("lt", RangeIndexModule.NAMESPACE_URI, RangeIndexModule.PREFIX), DESCRIPTION, PARAMETER_TYPE, new FunctionReturnSequenceType(Type.NODE, Cardinality.ZERO_OR_MORE, "all nodes from the input node set whose node value is equal to the key.") ), new FunctionSignature( new QName("le", RangeIndexModule.NAMESPACE_URI, RangeIndexModule.PREFIX), DESCRIPTION, PARAMETER_TYPE, new FunctionReturnSequenceType(Type.NODE, Cardinality.ZERO_OR_MORE, "all nodes from the input node set whose node value is equal to the key.") ), new FunctionSignature( new QName("ge", RangeIndexModule.NAMESPACE_URI, RangeIndexModule.PREFIX), DESCRIPTION, PARAMETER_TYPE, new FunctionReturnSequenceType(Type.NODE, Cardinality.ZERO_OR_MORE, "all nodes from the input node set whose node value is equal to the key.") ), new FunctionSignature( new QName("ne", RangeIndexModule.NAMESPACE_URI, RangeIndexModule.PREFIX), DESCRIPTION, PARAMETER_TYPE, new FunctionReturnSequenceType(Type.NODE, Cardinality.ZERO_OR_MORE, "all nodes from the input node set whose node value is not equal to the key.") ), new FunctionSignature( new QName("starts-with", RangeIndexModule.NAMESPACE_URI, RangeIndexModule.PREFIX), DESCRIPTION, PARAMETER_TYPE, new FunctionReturnSequenceType(Type.NODE, Cardinality.ZERO_OR_MORE, "all nodes from the input node set whose node value is equal to the key.") ), new FunctionSignature( new QName("ends-with", RangeIndexModule.NAMESPACE_URI, RangeIndexModule.PREFIX), DESCRIPTION, PARAMETER_TYPE, new FunctionReturnSequenceType(Type.NODE, Cardinality.ZERO_OR_MORE, "all nodes from the input node set whose node value is equal to the key.") ), new FunctionSignature( new QName("contains", RangeIndexModule.NAMESPACE_URI, RangeIndexModule.PREFIX), DESCRIPTION, PARAMETER_TYPE, new FunctionReturnSequenceType(Type.NODE, Cardinality.ZERO_OR_MORE, "all nodes from the input node set whose node value is equal to the key.") ), new FunctionSignature( new QName("matches", RangeIndexModule.NAMESPACE_URI, RangeIndexModule.PREFIX), DESCRIPTION, new SequenceType[] { new FunctionParameterSequenceType("nodes", Type.NODE, Cardinality.ZERO_OR_MORE, "The node set to search using a range index which is defined on those nodes"), new FunctionParameterSequenceType("regex", Type.STRING, Cardinality.ZERO_OR_MORE, "The regular expression.") }, new FunctionReturnSequenceType(Type.NODE, Cardinality.ZERO_OR_MORE, "all nodes from the input node set whose node value matches the regular expression. Regular expression " + "syntax is limited to what Lucene supports. See http://lucene.apache.org/core/4_5_1/core/org/apache/lucene/util/automaton/RegExp.html") ) }; public static Lookup create(XQueryContext context, RangeIndex.Operator operator, NodePath contextPath) { for (FunctionSignature sig: signatures) { if (sig.getName().getLocalPart().equals(operator.toString())) { return new Lookup(context, sig, contextPath); } } return null; } private LocationStep contextStep = null; protected QName contextQName = null; protected int axis = Constants.UNKNOWN_AXIS; private NodeSet preselectResult = null; protected boolean canOptimize = false; protected boolean optimizeSelf = false; protected boolean optimizeChild = false; protected boolean usesCollation = false; protected Expression fallback = null; protected NodePath contextPath = null; public Lookup(XQueryContext context, FunctionSignature signature) { this(context, signature, null); } public Lookup(XQueryContext context, FunctionSignature signature, NodePath contextPath) { super(context, signature); this.contextPath = contextPath; } public void setFallback(Expression expression, int optimizeAxis) { if (expression instanceof InternalFunctionCall) { expression = ((InternalFunctionCall)expression).getFunction(); } this.fallback = expression; // we need to know the axis at this point. the optimizer will call // getOptimizeAxis before analyze this.axis = optimizeAxis; } public Expression getFallback() { return fallback; } public void setArguments(List<Expression> arguments) throws XPathException { steps.clear(); Expression path = arguments.get(0); steps.add(path); Expression arg = arguments.get(1).simplify(); arg = new DynamicCardinalityCheck(context, Cardinality.ZERO_OR_MORE, arg, new org.exist.xquery.util.Error(org.exist.xquery.util.Error.FUNC_PARAM_CARDINALITY, "2", mySignature)); steps.add(arg); } @Override public void analyze(AnalyzeContextInfo contextInfo) throws XPathException { super.analyze(new AnalyzeContextInfo(contextInfo)); List<LocationStep> steps = BasicExpressionVisitor.findLocationSteps(getArgument(0)); if (!steps.isEmpty()) { LocationStep firstStep = steps.get(0); LocationStep lastStep = steps.get(steps.size() - 1); if (firstStep != null && steps.size() == 1 && firstStep.getAxis() == Constants.SELF_AXIS) { Expression outerExpr = contextInfo.getContextStep(); if (outerExpr != null && outerExpr instanceof LocationStep) { LocationStep outerStep = (LocationStep) outerExpr; NodeTest test = outerStep.getTest(); if (test.getName() == null) { contextQName = new QName(null, null, null); } else if (test.isWildcardTest()) { contextQName = test.getName(); } else { contextQName = new QName(test.getName()); } if (outerStep.getAxis() == Constants.ATTRIBUTE_AXIS || outerStep.getAxis() == Constants.DESCENDANT_ATTRIBUTE_AXIS) { contextQName = new QName(contextQName.getLocalPart(), contextQName.getNamespaceURI(), contextQName.getPrefix(), ElementValue.ATTRIBUTE); } contextStep = firstStep; axis = outerStep.getAxis(); optimizeSelf = true; } } else if (lastStep != null && firstStep != null) { NodeTest test = lastStep.getTest(); if(test.getName() == null) { contextQName = new QName(null, null, null); } else if(test.isWildcardTest()) { contextQName = test.getName(); } else { contextQName = new QName(test.getName()); } if (lastStep.getAxis() == Constants.ATTRIBUTE_AXIS || lastStep.getAxis() == Constants.DESCENDANT_ATTRIBUTE_AXIS) { contextQName = new QName(contextQName.getLocalPart(), contextQName.getNamespaceURI(), contextQName.getPrefix(), ElementValue.ATTRIBUTE); } axis = firstStep.getAxis(); optimizeChild = steps.size() == 1 && (axis == Constants.CHILD_AXIS || axis == Constants.ATTRIBUTE_AXIS); contextStep = lastStep; } } if (fallback != null) { AnalyzeContextInfo newContextInfo = new AnalyzeContextInfo(contextInfo); newContextInfo.setStaticType(Type.NODE); fallback.analyze(newContextInfo); } } @Override public NodeSet preSelect(Sequence contextSequence, boolean useContext) throws XPathException { if (!canOptimize) { return ((Optimizable)fallback).preSelect(contextSequence, useContext); } if (contextSequence != null && !contextSequence.isPersistentSet()) // in-memory docs won't have an index return NodeSet.EMPTY_SET; // throw an exception if substring match operation is applied to collated index final RangeIndex.Operator operator = getOperator(); if (usesCollation && !operator.supportsCollation()) { throw new XPathException(this, RangeIndexModule.EXXQDYFT0001, "Index defines a collation which cannot be " + "used with the '" + operator + "' operation."); } long start = System.currentTimeMillis(); // the expression can be called multiple times, so we need to clear the previous preselectResult preselectResult = null; RangeIndexWorker index = (RangeIndexWorker) context.getBroker().getIndexController().getWorkerByIndexId(RangeIndex.ID); DocumentSet docs = contextSequence.getDocumentSet(); AtomicValue[] keys = getKeys(contextSequence); if (keys.length == 0) { return NodeSet.EMPTY_SET; } List<QName> qnames = null; if (contextQName != null) { qnames = new ArrayList<>(1); qnames.add(contextQName); } try { preselectResult = index.query(getExpressionId(), docs, contextSequence.toNodeSet(), qnames, keys, operator, NodeSet.DESCENDANT); } catch (XPathException | IOException e) { throw new XPathException(this, "Error while querying full text index: " + e.getMessage(), e); } //LOG.info("preselect for " + Arrays.toString(keys) + " on " + contextSequence.getItemCount() + "returned " + preselectResult.getItemCount() + // " and took " + (System.currentTimeMillis() - start)); if( context.getProfiler().traceFunctions() ) { context.getProfiler().traceIndexUsage( context, "new-range", this, PerformanceStats.OPTIMIZED_INDEX, System.currentTimeMillis() - start ); } if (preselectResult == null) { preselectResult = NodeSet.EMPTY_SET; } return preselectResult; } private RangeIndex.Operator getOperator() { final String calledAs = getSignature().getName().getLocalPart(); return RangeIndexModule.OPERATOR_MAP.get(calledAs); } private AtomicValue[] getKeys(Sequence contextSequence) throws XPathException { RangeIndexConfigElement config = findConfiguration(contextSequence); int targetType = config != null ? config.getType() : Type.ITEM; Sequence keySeq = Atomize.atomize(getArgument(1).eval(contextSequence)); AtomicValue[] keys = new AtomicValue[keySeq.getItemCount()]; for (int i = 0; i < keys.length; i++) { if (targetType == Type.ITEM) { keys[i] = (AtomicValue) keySeq.itemAt(i); } else { keys[i] = keySeq.itemAt(i).convertTo(targetType); } } return keys; } @Override public Sequence eval(Sequence contextSequence, Item contextItem) throws XPathException { if (!canOptimize && fallback != null) { return fallback.eval(contextSequence, contextItem); } if (contextItem != null) contextSequence = contextItem.toSequence(); if (contextSequence != null && !contextSequence.isPersistentSet()) { // in-memory docs won't have an index if (fallback == null) { return Sequence.EMPTY_SEQUENCE; } else { return fallback.eval(contextSequence, contextItem); } } NodeSet result; if (preselectResult == null) { long start = System.currentTimeMillis(); Sequence input = getArgument(0).eval(contextSequence); if (!(input instanceof VirtualNodeSet) && input.isEmpty()) result = NodeSet.EMPTY_SET; else { RangeIndexWorker index = (RangeIndexWorker) context.getBroker().getIndexController().getWorkerByIndexId(RangeIndex.ID); AtomicValue[] keys = getKeys(contextSequence); if (keys.length == 0) { return NodeSet.EMPTY_SET; } List<QName> qnames = null; if (contextQName != null) { qnames = new ArrayList<>(1); qnames.add(contextQName); } final RangeIndex.Operator operator = getOperator(); // throw an exception if substring match operation is applied to collated index if (usesCollation && !operator.supportsCollation()) { throw new XPathException(this, RangeIndexModule.EXXQDYFT0001, "Index defines a collation which cannot be " + "used with the '" + operator + "' operation."); } try { NodeSet inNodes = input.toNodeSet(); DocumentSet docs = inNodes.getDocumentSet(); result = index.query(getExpressionId(), docs, inNodes, qnames, keys, operator, NodeSet.ANCESTOR); } catch (IOException e) { throw new XPathException(this, e.getMessage()); } } if( context.getProfiler().traceFunctions() ) { context.getProfiler().traceIndexUsage( context, "new-range", this, PerformanceStats.BASIC_INDEX, System.currentTimeMillis() - start ); } // LOG.info("eval plain took " + (System.currentTimeMillis() - start)); } else { // long start = System.currentTimeMillis(); contextStep.setPreloadedData(preselectResult.getDocumentSet(), preselectResult); result = getArgument(0).eval(contextSequence).toNodeSet(); //LOG.info("eval took " + (System.currentTimeMillis() - start)); } return result; } @Override public void resetState(boolean postOptimization) { super.resetState(postOptimization); if (fallback != null) { fallback.resetState(postOptimization); } if (!postOptimization) { preselectResult = null; canOptimize = false; } } @Override public boolean canOptimize(Sequence contextSequence) { if (contextQName == null) { return false; } RangeIndexConfigElement rice = findConfiguration(contextSequence); if (rice == null) { canOptimize = false; if (fallback instanceof Optimizable) { return ((Optimizable)fallback).canOptimize(contextSequence); } return false; } usesCollation = rice.usesCollation(); canOptimize = true; return canOptimize; } private RangeIndexConfigElement findConfiguration(Sequence contextSequence) { NodePath path = contextPath; if (path == null) { if (contextQName == null) { return null; } path = new NodePath(contextQName); } for (final Iterator<Collection> i = contextSequence.getCollectionIterator(); i.hasNext(); ) { final Collection collection = i.next(); if (collection.getURI().startsWith(XmldbURI.SYSTEM_COLLECTION_URI)) { continue; } IndexSpec idxConf = collection.getIndexConfiguration(context.getBroker()); if (idxConf != null) { RangeIndexConfig config = (RangeIndexConfig) idxConf.getCustomIndexSpec(RangeIndex.ID); if (config != null) { RangeIndexConfigElement rice = config.find(path); if (rice != null && !rice.isComplex()) { return rice; } } } } return null; } @Override public boolean optimizeOnSelf() { return optimizeSelf; } @Override public boolean optimizeOnChild() { return optimizeChild; } @Override public int getOptimizeAxis() { return axis; } @Override public int getDependencies() { final Expression stringArg = getArgument(0); if (!Dependency.dependsOn(stringArg, Dependency.CONTEXT_ITEM)) { return Dependency.CONTEXT_SET; } else { return Dependency.CONTEXT_SET + Dependency.CONTEXT_ITEM; } } public int returnsType() { return Type.NODE; } }
lgpl-2.1
learking/beast2-2.1.3
src/beast/evolution/speciation/GeneTreeForSpeciesTreeDistribution.java
16304
package beast.evolution.speciation; import java.util.Arrays; import java.util.List; import java.util.PriorityQueue; import java.util.Random; import beast.core.Description; import beast.core.Input; import beast.core.State; import beast.core.Input.Validate; import beast.core.parameter.RealParameter; import beast.evolution.alignment.Taxon; import beast.evolution.alignment.TaxonSet; import beast.evolution.speciation.SpeciesTreePrior.TreePopSizeFunction; import beast.evolution.tree.Node; import beast.evolution.tree.Tree; import beast.evolution.tree.TreeDistribution; import beast.evolution.tree.TreeInterface; @Description("Calculates probability of gene tree conditioned on a species tree (multi-species coalescent)") public class GeneTreeForSpeciesTreeDistribution extends TreeDistribution { public Input<TreeInterface> speciesTreeInput = new Input<TreeInterface>("speciesTree", "species tree containing the associated gene tree", Validate.REQUIRED); // public enum PLOIDY {autosomal_nuclear, X, Y, mitrochondrial}; public Input<Double> ploidyInput = new Input<Double>("ploidy", "ploidy (copy number) for this gene, typically a whole number or half (default 2 for autosomal_nuclear)", 2.0); // public Input<PLOIDY> m_ploidy = // new Input<PLOIDY>("ploidy", "ploidy for this gene (default X, Possible values: " + PLOIDY.values(), PLOIDY.X, PLOIDY.values()); public Input<SpeciesTreePrior> speciesTreePriorInput = new Input<SpeciesTreePrior>("speciesTreePrior", "defines population function and its parameters", Validate.REQUIRED); public Input<TreeTopFinder> treeTopFinderInput = new Input<TreeTopFinder>("treetop", "calculates height of species tree, required only for linear *beast analysis"); // intervals for each of the species tree branches private PriorityQueue<Double>[] intervalsInput; // count nr of lineages at the bottom of species tree branches private int[] nrOfLineages; // maps gene tree leaf nodes to species tree leaf nodes. Indexed by node number. protected int[] nrOfLineageToSpeciesMap; beast.evolution.speciation.SpeciesTreePrior.TreePopSizeFunction isConstantPopFunction; RealParameter popSizesBottom; RealParameter popSizesTop; // Ploidy is a constant - cache value of input here private double ploidy; //??? public GeneTreeForSpeciesTreeDistribution() { treeInput.setRule(Validate.REQUIRED); } @Override public void initAndValidate() throws Exception { ploidy = ploidyInput.get(); // switch (m_ploidy.get()) { // case autosomal_nuclear: m_fPloidy = 2.0; break; // case X: m_fPloidy = 1.5; break; // case Y: m_fPloidy = 0.5; break; // case mitrochondrial: m_fPloidy = 0.5; break; // default: throw new Exception("Unknown value for ploidy"); // } final Node[] gtNodes = treeInput.get().getNodesAsArray(); final int nGtLineages = treeInput.get().getLeafNodeCount(); final Node[] sptNodes = speciesTreeInput.get().getNodesAsArray(); final int nSpecies = speciesTreeInput.get().getNodeCount(); if (nSpecies <= 1 && sptNodes[0].getID().equals("Beauti2DummyTaxonSet")) { // we are in Beauti, don't initialise return; } // reserve memory for priority queues intervalsInput = new PriorityQueue[nSpecies]; for (int i = 0; i < nSpecies; i++) { intervalsInput[i] = new PriorityQueue<Double>(); } // sanity check lineage nodes are all at height=0 for (int i = 0; i < nGtLineages; i++) { if (gtNodes[i].getHeight() != 0) { throw new Exception("Cannot deal with taxon " + gtNodes[i].getID() + ", which has non-zero height + " + gtNodes[i].getHeight()); } } // set up m_nLineageToSpeciesMap nrOfLineageToSpeciesMap = new int[nGtLineages]; Arrays.fill(nrOfLineageToSpeciesMap, -1); for (int i = 0; i < nGtLineages; i++) { final String sSpeciesID = getSetID(gtNodes[i].getID()); // ??? can this be a startup check? can this happen during run due to tree change? if (sSpeciesID == null) { throw new Exception("Cannot find species for lineage " + gtNodes[i].getID()); } for (int iSpecies = 0; iSpecies < nSpecies; iSpecies++) { if (sSpeciesID.equals(sptNodes[iSpecies].getID())) { nrOfLineageToSpeciesMap[i] = iSpecies; break; } } if (nrOfLineageToSpeciesMap[i] < 0) { throw new Exception("Cannot find species with name " + sSpeciesID + " in species tree"); } } // calculate nr of lineages per species nrOfLineages = new int[nSpecies]; // for (final Node node : gtNodes) { // if (node.isLeaf()) { // final int iSpecies = m_nLineageToSpeciesMap[node.getNr()]; // m_nLineages[iSpecies]++; // } // } final SpeciesTreePrior popInfo = speciesTreePriorInput.get(); isConstantPopFunction = popInfo.popFunctionInput.get(); popSizesBottom = popInfo.popSizesBottomInput.get(); popSizesTop = popInfo.popSizesTopInput.get(); assert( ! (isConstantPopFunction == TreePopSizeFunction.linear && treeTopFinderInput.get() == null ) ); } /** * @param sLineageID * @return species ID to which the lineage ID belongs according to the TaxonSets */ String getSetID(final String sLineageID) { final TaxonSet taxonSuperset = speciesTreePriorInput.get().taxonSetInput.get(); final List<Taxon> taxonSets = taxonSuperset.taxonsetInput.get(); for (final Taxon taxonSet : taxonSets) { final List<Taxon> taxa = ((TaxonSet) taxonSet).taxonsetInput.get(); for (final Taxon aTaxa : taxa) { if (aTaxa.getID().equals(sLineageID)) { return taxonSet.getID(); } } } return null; } @Override public double calculateLogP() { logP = 0; for (final PriorityQueue<Double> m_interval : intervalsInput) { m_interval.clear(); } Arrays.fill(nrOfLineages, 0); final TreeInterface stree = speciesTreeInput.get(); final Node[] speciesNodes = stree.getNodesAsArray(); traverseLineageTree(speciesNodes, treeInput.get().getRoot()); // System.err.println(getID()); // for (int i = 0; i < m_intervals.length; i++) { // System.err.println(m_intervals[i]); // } // if the gene tree does not fit the species tree, logP = -infinity by now if (logP == 0) { traverseSpeciesTree(stree.getRoot()); } // System.err.println("logp=" + logP); return logP; } /** * calculate contribution to logP for each of the branches of the species tree * * @param node* */ private void traverseSpeciesTree(final Node node) { if (!node.isLeaf()) { traverseSpeciesTree(node.getLeft()); traverseSpeciesTree(node.getRight()); } // calculate contribution of a branch in the species tree to the log probability final int iNode = node.getNr(); // k, as defined in the paper //System.err.println(Arrays.toString(m_nLineages)); final int k = intervalsInput[iNode].size(); final double[] fTimes = new double[k + 2]; fTimes[0] = node.getHeight(); for (int i = 1; i <= k; i++) { fTimes[i] = intervalsInput[iNode].poll(); } if (!node.isRoot()) { fTimes[k + 1] = node.getParent().getHeight(); } else { if (isConstantPopFunction == TreePopSizeFunction.linear) { fTimes[k + 1] = treeTopFinderInput.get().getHighestTreeHeight(); } else { fTimes[k + 1] = Math.max(node.getHeight(), treeInput.get().getRoot().getHeight()); } } // sanity check for (int i = 0; i <= k; i++) { if (fTimes[i] > fTimes[i + 1]) { System.err.println("invalid times"); calculateLogP(); } } final int nLineagesBottom = nrOfLineages[iNode]; switch (isConstantPopFunction) { case constant: calcConstantPopSizeContribution(nLineagesBottom, popSizesBottom.getValue(iNode), fTimes, k); break; case linear: logP += calcLinearPopSizeContributionJH(nLineagesBottom, iNode, fTimes, k, node); break; case linear_with_constant_root: if (node.isRoot()) { final double fPopSize = getTopPopSize(node.getLeft().getNr()) + getTopPopSize(node.getRight().getNr()); calcConstantPopSizeContribution(nLineagesBottom, fPopSize, fTimes, k); } else { logP += calcLinearPopSizeContribution(nLineagesBottom, iNode, fTimes, k, node); } break; } } /* the contribution of a branch in the species tree to * the log probability, for constant population function. */ private void calcConstantPopSizeContribution(final int nLineagesBottom, final double fPopSize2, final double[] fTimes, final int k) { final double fPopSize = fPopSize2 * ploidy; logP += -k * Math.log(fPopSize); // System.err.print(logP); for (int i = 0; i <= k; i++) { logP += -((nLineagesBottom - i) * (nLineagesBottom - i - 1.0) / 2.0) * (fTimes[i + 1] - fTimes[i]) / fPopSize; } // System.err.println(" " + logP + " " + Arrays.toString(fTimes) + " " + iNode + " " + k); } /* the contribution of a branch in the species tree to * the log probability, for linear population function. */ private double calcLinearPopSizeContribution(final int nLineagesBottom, final int iNode, final double[] fTimes, final int k, final Node node) { double lp = 0.0; final double fPopSizeBottom; if (node.isLeaf()) { fPopSizeBottom = popSizesBottom.getValue(iNode) * ploidy; } else { // use sum of left and right child branches for internal nodes fPopSizeBottom = (getTopPopSize(node.getLeft().getNr()) + getTopPopSize(node.getRight().getNr())) * ploidy; } final double fPopSizeTop = getTopPopSize(iNode) * ploidy; final double a = (fPopSizeTop - fPopSizeBottom) / (fTimes[k + 1] - fTimes[0]); final double b = fPopSizeBottom; for (int i = 0; i < k; i++) { //double fPopSize = fPopSizeBottom + (fPopSizeTop-fPopSizeBottom) * fTimes[i+1]/(fTimes[k]-fTimes[0]); final double fPopSize = a * (fTimes[i + 1] - fTimes[0]) + b; lp += -Math.log(fPopSize); } for (int i = 0; i <= k; i++) { if (Math.abs(fPopSizeTop - fPopSizeBottom) < 1e-10) { // slope = 0, so population function is constant final double fPopSize = a * (fTimes[i + 1] - fTimes[0]) + b; lp += -((nLineagesBottom - i) * (nLineagesBottom - i - 1.0) / 2.0) * (fTimes[i + 1] - fTimes[i]) / fPopSize; } else { final double f = (a * (fTimes[i + 1] - fTimes[0]) + b) / (a * (fTimes[i] - fTimes[0]) + b); lp += -((nLineagesBottom - i) * (nLineagesBottom - i - 1.0) / 2.0) * Math.log(f) / a; } } return lp; } private double calcLinearPopSizeContributionJH(final int nLineagesBottom, final int iNode, final double[] fTimes, final int k, final Node node) { double lp = 0.0; double fPopSizeBottom; if (node.isLeaf()) { fPopSizeBottom = popSizesBottom.getValue(iNode); } else { // use sum of left and right child branches for internal nodes fPopSizeBottom = (getTopPopSize(node.getLeft().getNr()) + getTopPopSize(node.getRight().getNr())); } fPopSizeBottom *= ploidy; final double fPopSizeTop = getTopPopSize(iNode) * ploidy; final double d5 = fPopSizeTop - fPopSizeBottom; final double fTime0 = fTimes[0]; final double a = d5 / (fTimes[k + 1] - fTime0); final double b = fPopSizeBottom; if (Math.abs(d5) < 1e-10) { // use approximation for small values to bypass numerical instability for (int i = 0; i <= k; i++) { final double fTimeip1 = fTimes[i + 1]; final double fPopSize = a * (fTimeip1 - fTime0) + b; if( i < k ) { lp += -Math.log(fPopSize); } // slope = 0, so population function is constant final int i1 = nLineagesBottom - i; lp -= (i1 * (i1 - 1.0) / 2.0) * (fTimeip1 - fTimes[i]) / fPopSize; } } else { final double vv = b - a * fTime0; for (int i = 0; i <= k; i++) { final double fPopSize = a * fTimes[i + 1] + vv; if( i < k ) { lp += -Math.log(fPopSize); } final double f = fPopSize / (a * fTimes[i] + vv); final int i1 = nLineagesBottom - i; lp += -(i1 * (i1 - 1.0) / 2.0) * Math.log(f) / a; } } return lp; } /** * collect intervals for each of the branches of the species tree * as defined by the lineage tree. * * @param speciesNodes * @param node * @return */ private int traverseLineageTree(final Node[] speciesNodes, final Node node) { if (node.isLeaf()) { final int iSpecies = nrOfLineageToSpeciesMap[node.getNr()]; nrOfLineages[iSpecies]++; return iSpecies; } else { int nSpeciesLeft = traverseLineageTree(speciesNodes, node.getLeft()); int nSpeciesRight = traverseLineageTree(speciesNodes, node.getRight()); final double fHeight = node.getHeight(); while (!speciesNodes[nSpeciesLeft].isRoot() && fHeight > speciesNodes[nSpeciesLeft].getParent().getHeight()) { nSpeciesLeft = speciesNodes[nSpeciesLeft].getParent().getNr(); nrOfLineages[nSpeciesLeft]++; } while (!speciesNodes[nSpeciesRight].isRoot() && fHeight > speciesNodes[nSpeciesRight].getParent().getHeight()) { nSpeciesRight = speciesNodes[nSpeciesRight].getParent().getNr(); nrOfLineages[nSpeciesRight]++; } // validity check if (nSpeciesLeft != nSpeciesRight) { // if we got here, it means the gene tree does // not fit in the species tree logP = Double.NEGATIVE_INFINITY; } intervalsInput[nSpeciesRight].add(fHeight); return nSpeciesRight; } } /* return population size at top. For linear with constant root, there is no * entry for the root. An internal node can have the number equal to dimension * of m_fPopSizesTop, then the root node can be numbered with a lower number * and we can use that entry in m_fPopSizesTop for the rogue internal node. */ private double getTopPopSize(final int iNode) { if (iNode < popSizesTop.getDimension()) { return popSizesTop.getArrayValue(iNode); } return popSizesTop.getArrayValue(speciesTreeInput.get().getRoot().getNr()); } @Override public boolean requiresRecalculation() { // TODO: check whether this is worth optimising? return true; } @Override public List<String> getArguments() { return null; } @Override public List<String> getConditions() { return null; } @Override public void sample(final State state, final Random random) { } }
lgpl-2.1
ljo/exist
test/src/xquery/arrays/ArrayTests.java
200
package xquery.arrays; import org.exist.test.runner.XSuite; import org.junit.runner.RunWith; @RunWith(XSuite.class) @XSuite.XSuiteFiles({ "test/src/xquery/arrays" }) public class ArrayTests { }
lgpl-2.1
emmanuelbernard/hibernate-ogm
core/src/main/java/org/hibernate/ogm/service/listener/impl/OgmDefaultReplicateEventListener.java
6417
/* * Hibernate OGM, Domain model persistence for NoSQL datastores * * License: GNU Lesser General Public License (LGPL), version 2.1 or later * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. */ package org.hibernate.ogm.service.listener.impl; import java.io.Serializable; import org.hibernate.LockMode; import org.hibernate.action.internal.AbstractEntityInsertAction; import org.hibernate.action.internal.EntityIdentityInsertAction; import org.hibernate.action.internal.EntityInsertAction; import org.hibernate.bytecode.instrumentation.spi.FieldInterceptor; import org.hibernate.engine.internal.Versioning; import org.hibernate.engine.spi.EntityEntry; import org.hibernate.engine.spi.EntityKey; import org.hibernate.engine.spi.Status; import org.hibernate.event.internal.DefaultPersistEventListener; import org.hibernate.event.internal.DefaultReplicateEventListener; import org.hibernate.event.spi.EventSource; import org.hibernate.ogm.entityentry.impl.OgmEntityEntryState; import org.hibernate.persister.entity.EntityPersister; import org.hibernate.type.Type; import org.hibernate.type.TypeHelper; /** * A almost 1:1 copy of ORM's {@link DefaultPersistEventListener}. Used as a temp. work-around until HHH-9451 is * resolved. The only difference to the original class is that the extra entity state of temporary entity entries is * propagated to the final entries in * {@link #performSaveOrReplicate(Object, EntityKey, EntityPersister, boolean, Object, EventSource, boolean)}. * * @author Gavin King * @author Gunnar Morling */ public class OgmDefaultReplicateEventListener extends DefaultReplicateEventListener { /** * Performs all the actual work needed to save an entity (well to get the save moved to * the execution queue). * * @param entity The entity to be saved * @param key The id to be used for saving the entity (or null, in the case of identity columns) * @param persister The entity's persister instance. * @param useIdentityColumn Should an identity column be used for id generation? * @param anything Generally cascade-specific information. * @param source The session which is the source of the current event. * @param requiresImmediateIdAccess Is access to the identifier required immediately * after the completion of the save? persist(), for example, does not require this... * * @return The id used to save the entity; may be null depending on the * type of id generator used and the requiresImmediateIdAccess value */ @Override protected Serializable performSaveOrReplicate( Object entity, EntityKey key, EntityPersister persister, boolean useIdentityColumn, Object anything, EventSource source, boolean requiresImmediateIdAccess) { Serializable id = key == null ? null : key.getIdentifier(); boolean inTxn = source.getTransactionCoordinator().isTransactionInProgress(); boolean shouldDelayIdentityInserts = !inTxn && !requiresImmediateIdAccess; // Put a placeholder in entries, so we don't recurse back and try to save() the // same object again. QUESTION: should this be done before onSave() is called? // likewise, should it be done before onUpdate()? EntityEntry original = source.getPersistenceContext().addEntry( entity, Status.SAVING, null, null, id, null, LockMode.WRITE, useIdentityColumn, persister, false, false ); cascadeBeforeSave( source, persister, entity, anything ); Object[] values = persister.getPropertyValuesToInsert( entity, getMergeMap( anything ), source ); Type[] types = persister.getPropertyTypes(); boolean substitute = substituteValuesIfNecessary( entity, id, values, persister, source ); if ( persister.hasCollections() ) { substitute = substitute || visitCollectionsBeforeSave( entity, id, values, types, source ); } if ( substitute ) { persister.setPropertyValues( entity, values ); } TypeHelper.deepCopy( values, types, persister.getPropertyUpdateability(), values, source ); AbstractEntityInsertAction insert = addInsertAction( values, id, entity, persister, useIdentityColumn, source, shouldDelayIdentityInserts ); // postpone initializing id in case the insert has non-nullable transient dependencies // that are not resolved until cascadeAfterSave() is executed cascadeAfterSave( source, persister, entity, anything ); if ( useIdentityColumn && insert.isEarlyInsert() ) { if ( !EntityIdentityInsertAction.class.isInstance( insert ) ) { throw new IllegalStateException( "Insert should be using an identity column, but action is of unexpected type: " + insert.getClass().getName() ); } id = ((EntityIdentityInsertAction) insert).getGeneratedId(); insert.handleNaturalIdPostSaveNotifications( id ); } markInterceptorDirty( entity, persister, source ); EntityEntry newEntry = source.getPersistenceContext().getEntry( entity ); if ( newEntry != original ) { OgmEntityEntryState ogmEntityState = newEntry.getExtraState( OgmEntityEntryState.class ); if ( ogmEntityState == null ) { newEntry.addExtraState( original.getExtraState( OgmEntityEntryState.class ) ); } } return id; } private AbstractEntityInsertAction addInsertAction( Object[] values, Serializable id, Object entity, EntityPersister persister, boolean useIdentityColumn, EventSource source, boolean shouldDelayIdentityInserts) { if ( useIdentityColumn ) { EntityIdentityInsertAction insert = new EntityIdentityInsertAction( values, entity, persister, isVersionIncrementDisabled(), source, shouldDelayIdentityInserts ); source.getActionQueue().addAction( insert ); return insert; } else { Object version = Versioning.getVersion( values, persister ); EntityInsertAction insert = new EntityInsertAction( id, values, entity, version, persister, isVersionIncrementDisabled(), source ); source.getActionQueue().addAction( insert ); return insert; } } private void markInterceptorDirty(Object entity, EntityPersister persister, EventSource source) { if ( persister.getInstrumentationMetadata().isInstrumented() ) { FieldInterceptor interceptor = persister.getInstrumentationMetadata().injectInterceptor( entity, persister.getEntityName(), null, source ); interceptor.dirty(); } } }
lgpl-2.1
marksantos/Java-Lang
lang/src/test/java/net/openhft/lang/io/LockingViaFileLockMain.java
3737
/* * Copyright (C) 2015 higherfrequencytrading.com * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package net.openhft.lang.io; import java.io.File; import java.io.IOException; import java.io.RandomAccessFile; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; import java.nio.channels.FileLock; /** * User: peter * Date: 22/12/13 * Time: 11:05 * * <p>Toggled 10,000,128 times with an average delay of 2,402 ns */ public class LockingViaFileLockMain { static int RECORDS = Integer.getInteger("records", 128); static int RECORD_SIZE = Integer.getInteger("record_size", 64); // cache line size static int WARMUP = Integer.getInteger("warmup", RECORDS * 100); static int RUNS = Integer.getInteger("runs", 5 * 1000 * 1000); // offsets // static int LOCK = 0; static int FLAG = 8; public static void main(String... args) throws IOException, InterruptedException { boolean toggleTo = Boolean.parseBoolean(args[0]); File tmpFile = new File(System.getProperty("java.io.tmpdir"), "lock-test.dat"); FileChannel fc = new RandomAccessFile(tmpFile, "rw").getChannel(); MappedByteBuffer mbb = fc.map(FileChannel.MapMode.READ_WRITE, 0, RECORDS * RECORD_SIZE); ByteBufferBytes bytes = new ByteBufferBytes(mbb); long start = 0; for (int i = -WARMUP / RECORDS; i < (RUNS + RECORDS - 1) / RECORDS; i++) { if (i == 0) { start = System.nanoTime(); System.out.println("Started"); } for (int j = 0; j < RECORDS; j++) { int recordOffset = j * RECORD_SIZE; for (int t = 9999; t >= 0; t--) { if (t == 0) if (i >= 0) { throw new AssertionError("Didn't toggle in time !??"); } else { System.out.println("waiting"); t = 99999; Thread.sleep(200); } final FileLock lock = fc.lock(); try { bytes.readBarrier(); boolean flag = bytes.readBoolean(recordOffset + FLAG); if (flag == toggleTo) { if (t % 100 == 0) System.out.println("j: " + j + " is " + flag); continue; } bytes.writeBoolean(recordOffset + FLAG, toggleTo); bytes.writeBarrier(); break; } finally { lock.release(); } } } } long time = System.nanoTime() - start; final int toggles = (RUNS + RECORDS - 1) / RECORDS * RECORDS * 2; // one for each of two processes. System.out.printf("Toggled %,d times with an average delay of %,d ns%n", toggles, time / toggles); fc.close(); tmpFile.deleteOnExit(); } }
lgpl-3.0
dschanoeh/Kayak
Kayak-kcd/src/main/java/com/github/kayak/canio/kcd/ObjectFactory.java
4472
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2013.06.24 at 08:37:14 PM CEST // package com.github.kayak.canio.kcd; import javax.xml.bind.JAXBElement; import javax.xml.bind.annotation.XmlElementDecl; import javax.xml.bind.annotation.XmlRegistry; import javax.xml.namespace.QName; /** * This object contains factory methods for each * Java content interface and Java element interface * generated in the com.github.kayak.canio.kcd package. * <p>An ObjectFactory allows you to programatically * construct new instances of the Java representation * for XML content. The Java representation of XML * content can consist of schema derived interfaces * and classes representing the binding of schema * type definitions, element declarations and model * groups. Factory methods for each of these are * provided in this class. * */ @XmlRegistry public class ObjectFactory { private final static QName _Notes_QNAME = new QName("http://kayak.2codeornot2code.org/1.0", "Notes"); /** * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: com.github.kayak.canio.kcd * */ public ObjectFactory() { } /** * Create an instance of {@link LabelGroup } * */ public LabelGroup createLabelGroup() { return new LabelGroup(); } /** * Create an instance of {@link BasicLabelType } * */ public BasicLabelType createBasicLabelType() { return new BasicLabelType(); } /** * Create an instance of {@link Document } * */ public Document createDocument() { return new Document(); } /** * Create an instance of {@link NodeRef } * */ public NodeRef createNodeRef() { return new NodeRef(); } /** * Create an instance of {@link Value } * */ public Value createValue() { return new Value(); } /** * Create an instance of {@link Message } * */ public Message createMessage() { return new Message(); } /** * Create an instance of {@link Producer } * */ public Producer createProducer() { return new Producer(); } /** * Create an instance of {@link Multiplex } * */ public Multiplex createMultiplex() { return new Multiplex(); } /** * Create an instance of {@link BasicSignalType } * */ public BasicSignalType createBasicSignalType() { return new BasicSignalType(); } /** * Create an instance of {@link MuxGroup } * */ public MuxGroup createMuxGroup() { return new MuxGroup(); } /** * Create an instance of {@link Signal } * */ public Signal createSignal() { return new Signal(); } /** * Create an instance of {@link Consumer } * */ public Consumer createConsumer() { return new Consumer(); } /** * Create an instance of {@link LabelSet } * */ public LabelSet createLabelSet() { return new LabelSet(); } /** * Create an instance of {@link Label } * */ public Label createLabel() { return new Label(); } /** * Create an instance of {@link NetworkDefinition } * */ public NetworkDefinition createNetworkDefinition() { return new NetworkDefinition(); } /** * Create an instance of {@link Node } * */ public Node createNode() { return new Node(); } /** * Create an instance of {@link Var } * */ public Var createVar() { return new Var(); } /** * Create an instance of {@link Bus } * */ public Bus createBus() { return new Bus(); } /** * Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}} * */ @XmlElementDecl(namespace = "http://kayak.2codeornot2code.org/1.0", name = "Notes") public JAXBElement<String> createNotes(String value) { return new JAXBElement<String>(_Notes_QNAME, String.class, null, value); } }
lgpl-3.0
daitangio/exchangews
src/main/java/microsoft/exchange/webservices/data/ServiceResponseException.java
2738
/************************************************************************** * copyright file="ServiceResponseException.java" company="Microsoft" * Copyright (c) Microsoft Corporation. All rights reserved. * * Defines the ServiceResponseException.java. **************************************************************************/ package microsoft.exchange.webservices.data; /** * Represents a remote service exception that has a single response. * */ public class ServiceResponseException extends ServiceRemoteException { /** Error details Value keys. */ private static final String ExceptionClassKey = "ExceptionClass"; /** The Exception message key. */ private static final String ExceptionMessageKey = "ExceptionMessage"; /** The Stack trace key. */ private static final String StackTraceKey = "StackTrace"; /** * ServiceResponse when service operation failed remotely. */ private ServiceResponse response; /** * Initializes a new instance. * * @param response * the response */ protected ServiceResponseException(ServiceResponse response) { this.response = response; } /** * Gets the ServiceResponse for the exception. * * @return the response */ public ServiceResponse getResponse() { return response; } /** * Gets the service error code. * * @return the error code */ public ServiceError getErrorCode() { return this.response.getErrorCode(); } /** * Gets a message that describes the current exception. * * @return The error message that explains the reason for the exception. */ public String getMessage() { // Bug E14:134792 -- Special case for Internal Server Error. If the // server returned // stack trace information, include it in the exception message. if (this.response.getErrorCode() == ServiceError.ErrorInternalServerError) { String exceptionClass; String exceptionMessage; String stackTrace; if (this.response.getErrorDetails().containsKey(ExceptionClassKey) && this.response.getErrorDetails().containsKey( ExceptionMessageKey) && this.response.getErrorDetails().containsKey( StackTraceKey)) { exceptionClass = this.response.getErrorDetails().get( ExceptionClassKey); exceptionMessage = this.response.getErrorDetails().get( ExceptionMessageKey); stackTrace = this.response.getErrorDetails().get(StackTraceKey); // return return String.format( Strings.ServerErrorAndStackTraceDetails, this.response .getErrorMessage(), exceptionClass, exceptionMessage, stackTrace); } } return this.response.getErrorMessage(); } }
lgpl-3.0
oakes/Nightweb
common/java/router/net/i2p/data/i2np/TunnelDataMessage.java
10290
package net.i2p.data.i2np; /* * free (adj.): unencumbered; not under the control of others * Written by jrandom in 2003 and released into the public domain * with no warranty of any kind, either expressed or implied. * It probably won't make your computer catch on fire, or eat * your children, but it might. Use at your own risk. * */ import net.i2p.I2PAppContext; import net.i2p.data.ByteArray; import net.i2p.data.DataHelper; import net.i2p.data.TunnelId; import net.i2p.util.ByteCache; /** * Defines the message sent between routers as part of the tunnel delivery * * The tunnel ID is changed in-place by TunnelParticipant.send(), so * we can't reuse the checksum on output, but we still subclass * FastI2NPMessageImpl so we don't verify the checksum on input... * because this is a high-usage class. * */ public class TunnelDataMessage extends FastI2NPMessageImpl { private long _tunnelId; private TunnelId _tunnelIdObj; private byte[] _data; private ByteArray _dataBuf; public final static int MESSAGE_TYPE = 18; public static final int DATA_SIZE = 1024; /** if we can't deliver a tunnel message in 10s, fuck it */ private static final int EXPIRATION_PERIOD = 10*1000; private static final ByteCache _cache; /** * When true, it means this tunnelDataMessage is being used as part of a tunnel * processing pipeline, where the byte array is acquired during the TunnelDataMessage's * creation (per readMessage), held onto through several transitions (updating and * moving that array between different TunnelDataMessage instances or the fragment * handler's cache, etc), until it is finally released back into the cache when written * to the next peer (or explicitly by the fragment handler's completion). * Setting this to false just increases memory churn * * Well, this is tricky to get right and avoid data corruption, * here's an example after checks were put in: * * 10:57:05.197 CRIT [NTCP read 1 ] 2p.data.i2np.TunnelDataMessage: TDM boom net.i2p.data.i2np.I2NPMessageException: TDM data buf use after free at net.i2p.data.i2np.TunnelDataMessage.writeMessageBody(TunnelDataMessage.java:124) at net.i2p.data.i2np.I2NPMessageImpl.toByteArray(I2NPMessageImpl.java:217) at net.i2p.router.transport.ntcp.NTCPConnection.bufferedPrepare(NTCPConnection.java:678) at net.i2p.router.transport.ntcp.NTCPConnection.send(NTCPConnection.java:293) at net.i2p.router.transport.ntcp.NTCPTransport.outboundMessageReady(NTCPTransport.java:185) at net.i2p.router.transport.TransportImpl.send(TransportImpl.java:357) at net.i2p.router.transport.GetBidsJob.getBids(GetBidsJob.java:80) at net.i2p.router.transport.CommSystemFacadeImpl.processMessage(CommSystemFacadeImpl.java:129) at net.i2p.router.OutNetMessagePool.add(OutNetMessagePool.java:61) at net.i2p.router.transport.TransportImpl.afterSend(TransportImpl.java:252) at net.i2p.router.transport.TransportImpl.afterSend(TransportImpl.java:163) at net.i2p.router.transport.udp.UDPTransport.failed(UDPTransport.java:1314) at net.i2p.router.transport.udp.PeerState.add(PeerState.java:1064) at net.i2p.router.transport.udp.OutboundMessageFragments.add(OutboundMessageFragments.java:146) at net.i2p.router.transport.udp.UDPTransport.send(UDPTransport.java:1098) at net.i2p.router.transport.GetBidsJob.getBids(GetBidsJob.java:80) at net.i2p.router.transport.CommSystemFacadeImpl.processMessage(CommSystemFacadeImpl.java:129) at net.i2p.router.OutNetMessagePool.add(OutNetMessagePool.java:61) at net.i2p.router.tunnel.TunnelParticipant.send(TunnelParticipant.java:172) at net.i2p.router.tunnel.TunnelParticipant.dispatch(TunnelParticipant.java:86) at net.i2p.router.tunnel.TunnelDispatcher.dispatch(TunnelDispatcher.java:351) at net.i2p.router.InNetMessagePool.doShortCircuitTunnelData(InNetMessagePool.java:306) at net.i2p.router.InNetMessagePool.shortCircuitTunnelData(InNetMessagePool.java:291) at net.i2p.router.InNetMessagePool.add(InNetMessagePool.java:160) at net.i2p.router.transport.TransportManager.messageReceived(TransportManager.java:462) at net.i2p.router.transport.TransportImpl.messageReceived(TransportImpl.java:416) at net.i2p.router.transport.ntcp.NTCPConnection$ReadState.receiveLastBlock(NTCPConnection.java:1285) at net.i2p.router.transport.ntcp.NTCPConnection$ReadState.receiveSubsequent(NTCPConnection.java:1248) at net.i2p.router.transport.ntcp.NTCPConnection$ReadState.receiveBlock(NTCPConnection.java:1205) at net.i2p.router.transport.ntcp.NTCPConnection.recvUnencryptedI2NP(NTCPConnection.java:1035) at net.i2p.router.transport.ntcp.NTCPConnection.recvEncryptedI2NP(NTCPConnection.java:1018) at net.i2p.router.transport.ntcp.Reader.processRead(Reader.java:167) at net.i2p.router.transport.ntcp.Reader.access$400(Reader.java:17) at net.i2p.router.transport.ntcp.Reader$Runner.run(Reader.java:106) at java.lang.Thread.run(Thread.java:619) at net.i2p.util.I2PThread.run(I2PThread.java:71) * */ private static final boolean PIPELINED_CACHE = true; static { if (PIPELINED_CACHE) _cache = ByteCache.getInstance(512, DATA_SIZE); else _cache = null; } /** For use-after-free checks. Always false if PIPELINED_CACHE is false. */ private boolean _hadCache; public TunnelDataMessage(I2PAppContext context) { super(context); setMessageExpiration(context.clock().now() + EXPIRATION_PERIOD); } public long getTunnelId() { return _tunnelId; } /** * (correctly) Invalidates stored checksum */ public void setTunnelId(long id) { _hasChecksum = false; _tunnelId = id; } public TunnelId getTunnelIdObj() { if (_tunnelIdObj == null) _tunnelIdObj = new TunnelId(_tunnelId); // not thread safe, but immutable, so who cares return _tunnelIdObj; } /** * (correctly) Invalidates stored checksum */ public void setTunnelId(TunnelId id) { _hasChecksum = false; _tunnelIdObj = id; _tunnelId = id.getTunnelId(); } public byte[] getData() { if (_hadCache && _dataBuf == null) { RuntimeException e = new RuntimeException("TDM data buf use after free"); _log.error("TDM boom", e); throw e; } return _data; } /** * @throws IllegalStateException if data previously set, to protect saved checksum */ public void setData(byte data[]) { if (_data != null) throw new IllegalStateException(); if ( (data == null) || (data.length <= 0) ) throw new IllegalArgumentException("Empty tunnel payload?"); _data = data; } public void readMessage(byte data[], int offset, int dataSize, int type) throws I2NPMessageException { if (type != MESSAGE_TYPE) throw new I2NPMessageException("Message type is incorrect for this message"); int curIndex = offset; _tunnelId = DataHelper.fromLong(data, curIndex, 4); curIndex += 4; if (_tunnelId <= 0) throw new I2NPMessageException("Invalid tunnel Id " + _tunnelId); // we cant cache it in trivial form, as other components (e.g. HopProcessor) // call getData() and use it as the buffer to write with. it is then used // again to pass to the 'receiver', which may even cache it in a FragmentMessage. if (PIPELINED_CACHE) { _dataBuf = _cache.acquire(); _data = _dataBuf.getData(); _hadCache = true; } else { _data = new byte[DATA_SIZE]; } System.arraycopy(data, curIndex, _data, 0, DATA_SIZE); } /** calculate the message body's length (not including the header and footer */ protected int calculateWrittenLength() { return 4 + DATA_SIZE; } /** write the message body to the output array, starting at the given index */ protected int writeMessageBody(byte out[], int curIndex) throws I2NPMessageException { if ( (_tunnelId <= 0) || (_data == null) ) throw new I2NPMessageException("Not enough data to write out (id=" + _tunnelId + ")"); if (_data.length <= 0) throw new I2NPMessageException("Not enough data to write out (data.length=" + _data.length + ")"); if (_hadCache && _dataBuf == null) { I2NPMessageException e = new I2NPMessageException("TDM data buf use after free"); _log.error("TDM boom", e); throw e; } DataHelper.toLong(out, curIndex, 4, _tunnelId); curIndex += 4; System.arraycopy(_data, 0, out, curIndex, DATA_SIZE); curIndex += _data.length; // We can use from the cache, we just can't release to the cache, due to the bug // noted above. In effect, this means that transmitted TDMs don't get their // dataBufs released - but received TDMs do (via FragmentHandler) //if (_hadCache) { // _cache.release(_dataBuf); // _dataBuf = null; //} return curIndex; } public int getType() { return MESSAGE_TYPE; } @Override public int hashCode() { return (int)_tunnelId + DataHelper.hashCode(_data); } @Override public boolean equals(Object object) { if ( (object != null) && (object instanceof TunnelDataMessage) ) { TunnelDataMessage msg = (TunnelDataMessage)object; return _tunnelId == msg.getTunnelId() && DataHelper.eq(getData(),msg.getData()); } else { return false; } } @Override public byte[] toByteArray() { byte rv[] = super.toByteArray(); if (rv == null) throw new RuntimeException("unable to toByteArray(): " + toString()); return rv; } @Override public String toString() { StringBuilder buf = new StringBuilder(); buf.append("[TunnelDataMessage:"); buf.append(" MessageId: ").append(_uniqueId); buf.append(" Tunnel ID: ").append(_tunnelId); buf.append("]"); return buf.toString(); } }
unlicense
vtkhir/kaa
server/appenders/file-appender/src/main/java/org/kaaproject/kaa/server/appenders/file/config/FileSystemAppenderConfig.java
1433
/* * Copyright 2014-2016 CyberVision, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kaaproject.kaa.server.appenders.file.config; import org.apache.avro.Schema; import org.kaaproject.kaa.server.appenders.file.config.gen.FileConfig; import org.kaaproject.kaa.server.common.plugin.KaaPluginConfig; import org.kaaproject.kaa.server.common.plugin.PluginConfig; import org.kaaproject.kaa.server.common.plugin.PluginType; @KaaPluginConfig(pluginType = PluginType.LOG_APPENDER) public class FileSystemAppenderConfig implements PluginConfig { public FileSystemAppenderConfig() { } @Override public String getPluginTypeName() { return "File"; } @Override public String getPluginClassName() { return "org.kaaproject.kaa.server.appenders.file.appender.FileSystemLogAppender"; } @Override public Schema getPluginConfigSchema() { return FileConfig.getClassSchema(); } }
apache-2.0
tombujok/hazelcast
hazelcast/src/main/java/com/hazelcast/ringbuffer/OverflowPolicy.java
3028
/* * Copyright (c) 2008-2017, Hazelcast, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hazelcast.ringbuffer; /** * Using this policy one can control the behavior what should to be done when an item is about to be added to the ringbuffer, * but there is 0 remaining capacity. * * Overflowing happens when a time-to-live is set and the oldest item in the ringbuffer (the head) is not old enough to expire. * * @see Ringbuffer#addAsync(Object, OverflowPolicy) * @see Ringbuffer#addAllAsync(java.util.Collection, OverflowPolicy) */ public enum OverflowPolicy { /** * Using this policy the oldest item is overwritten no matter it is not old enough to retire. Using this policy you are * sacrificing the time-to-live in favor of being able to write. * * Example: if there is a time-to-live of 30 seconds, the buffer is full and the oldest item in the ring has been placed a * second ago, then there are 29 seconds remaining for that item. Using this policy you are going to overwrite no matter * what. */ OVERWRITE(0), /** * Using this policy the call will fail immediately and the oldest item will not be overwritten before it is old enough * to retire. So this policy sacrificing the ability to write in favor of time-to-live. * * The advantage of fail is that the caller can decide what to do since it doesn't trap the thread due to backoff. * * Example: if there is a time-to-live of 30 seconds, the buffer is full and the oldest item in the ring has been placed a * second ago, then there are 29 seconds remaining for that item. Using this policy you are not going to overwrite that * item for the next 29 seconds. */ FAIL(1); private final int id; OverflowPolicy(int id) { this.id = id; } /** * Gets the ID for the given OverflowPolicy. * * This reason this ID is used instead of an the ordinal value is that the ordinal value is more prone to changes due to * reordering. * * @return the ID */ public int getId() { return id; } /** * Returns the OverflowPolicy for the given ID. * * @return the OverflowPolicy found or null if not found */ public static OverflowPolicy getById(final int id) { for (OverflowPolicy policy : values()) { if (policy.id == id) { return policy; } } return null; } }
apache-2.0
Terracotta-OSS/terracotta-platform
dynamic-config/server/configuration-provider/src/main/java/org/terracotta/dynamic_config/server/configuration/startup/DefaultGroupPortMapperImpl.java
979
/* * Copyright Terracotta, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.terracotta.dynamic_config.server.configuration.startup; import org.terracotta.dynamic_config.api.model.Node; import org.terracotta.dynamic_config.server.api.GroupPortMapper; public class DefaultGroupPortMapperImpl implements GroupPortMapper { @Override public int getPeerGroupPort(Node peerNode, Node thisNode) { return peerNode.getGroupPort().orDefault(); } }
apache-2.0
topicusonderwijs/wicket
wicket-core/src/test/java/org/apache/wicket/markup/MarkupVariationTest.java
3438
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.wicket.markup; import org.apache.wicket.MarkupContainer; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.markup.html.AjaxLink; import org.apache.wicket.markup.html.WebPage; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.form.Form; import org.apache.wicket.markup.html.panel.Panel; import org.apache.wicket.util.resource.IResourceStream; import org.apache.wicket.util.resource.StringResourceStream; import org.apache.wicket.util.tester.WicketTestCase; import org.junit.Test; /** * Tests that changing component's variation will use the correct markup */ public class MarkupVariationTest extends WicketTestCase { /** * https://issues.apache.org/jira/browse/WICKET-3931 */ @Test public void changeVariation() { tester.startPage(new VariationPage()); tester.assertContainsNot("Two"); tester.assertMarkupVariation(getVariationPanel(), "one"); tester.assertMarkupVariation(tester.getLastRenderedPage(), null); tester.clickLink("p:l"); tester.assertContainsNot("One"); tester.assertMarkupVariation(getVariationPanel(), "two"); tester.assertMarkupVariation(tester.getLastRenderedPage(), null); tester.clickLink("p:l"); tester.assertContainsNot("Two"); tester.assertMarkupVariation(getVariationPanel(), "one"); tester.assertMarkupVariation(tester.getLastRenderedPage(), null); tester.clickLink("p:l"); } private MarkupContainer getVariationPanel() { return (MarkupContainer) tester.getComponentFromLastRenderedPage("p"); } private static class VariationPage extends WebPage implements IMarkupResourceStreamProvider { private VariationPage() { add(new VariationPanel("p")); } @Override public IResourceStream getMarkupResourceStream(MarkupContainer container, Class<?> containerClass) { return new StringResourceStream("<html><body><div wicket:id='p'></div></body></html>"); } } private static class VariationPanel extends Panel { private String variation; public VariationPanel(String id) { super(id); setOutputMarkupId(true); variation = "one"; add(new AjaxLink<Void>("l") { @Override public void onClick(AjaxRequestTarget target) { variation = "one".equals(variation) ? "two" : "one"; target.add(VariationPanel.this); } }); add(new Label("simpleLabel", "Label")); add(new Form<Void>("a_form")); add(new Label("child", "Inline Enclosure child text")); add(new Label("nestedChild", "Nested Inline Enclosure child text")); } @Override public String getVariation() { return variation; } } }
apache-2.0
gfyoung/elasticsearch
server/src/main/java/org/elasticsearch/action/ingest/PutPipelineTransportAction.java
4272
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.action.ingest; import org.elasticsearch.action.ActionListener; import org.elasticsearch.action.admin.cluster.node.info.NodeInfo; import org.elasticsearch.action.admin.cluster.node.info.NodesInfoRequest; import org.elasticsearch.action.admin.cluster.node.info.NodesInfoResponse; import org.elasticsearch.action.support.ActionFilters; import org.elasticsearch.action.support.master.AcknowledgedResponse; import org.elasticsearch.action.support.master.TransportMasterNodeAction; import org.elasticsearch.client.node.NodeClient; import org.elasticsearch.cluster.ClusterState; import org.elasticsearch.cluster.block.ClusterBlockException; import org.elasticsearch.cluster.block.ClusterBlockLevel; import org.elasticsearch.cluster.metadata.IndexNameExpressionResolver; import org.elasticsearch.cluster.node.DiscoveryNode; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.ingest.IngestService; import org.elasticsearch.ingest.IngestInfo; import org.elasticsearch.threadpool.ThreadPool; import org.elasticsearch.transport.TransportService; import java.util.HashMap; import java.util.Map; public class PutPipelineTransportAction extends TransportMasterNodeAction<PutPipelineRequest, AcknowledgedResponse> { private final IngestService ingestService; private final NodeClient client; @Inject public PutPipelineTransportAction(Settings settings, ThreadPool threadPool, TransportService transportService, ActionFilters actionFilters, IndexNameExpressionResolver indexNameExpressionResolver, IngestService ingestService, NodeClient client) { super( settings, PutPipelineAction.NAME, transportService, ingestService.getClusterService(), threadPool, actionFilters, indexNameExpressionResolver, PutPipelineRequest::new ); this.client = client; this.ingestService = ingestService; } @Override protected String executor() { return ThreadPool.Names.SAME; } @Override protected AcknowledgedResponse newResponse() { return new AcknowledgedResponse(); } @Override protected void masterOperation(PutPipelineRequest request, ClusterState state, ActionListener<AcknowledgedResponse> listener) throws Exception { NodesInfoRequest nodesInfoRequest = new NodesInfoRequest(); nodesInfoRequest.clear(); nodesInfoRequest.ingest(true); client.admin().cluster().nodesInfo(nodesInfoRequest, new ActionListener<NodesInfoResponse>() { @Override public void onResponse(NodesInfoResponse nodeInfos) { try { Map<DiscoveryNode, IngestInfo> ingestInfos = new HashMap<>(); for (NodeInfo nodeInfo : nodeInfos.getNodes()) { ingestInfos.put(nodeInfo.getNode(), nodeInfo.getIngest()); } ingestService.putPipeline(ingestInfos, request, listener); } catch (Exception e) { onFailure(e); } } @Override public void onFailure(Exception e) { listener.onFailure(e); } }); } @Override protected ClusterBlockException checkBlock(PutPipelineRequest request, ClusterState state) { return state.blocks().globalBlockedException(ClusterBlockLevel.METADATA_WRITE); } }
apache-2.0
joobn72/qi4j-sdk
libraries/logging/src/main/java/org/qi4j/logging/view/ConsoleViewerComposite.java
827
/* * Copyright 2006 Niclas Hedhman. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. * * See the License for the specific language governing permissions and * limitations under the License. */ package org.qi4j.logging.view; import org.qi4j.api.composite.Composite; import org.qi4j.api.mixin.Mixins; @Mixins( { ConsoleViewerMixin.class } ) public interface ConsoleViewerComposite extends Composite { }
apache-2.0
Muks14x/susi_android
app/src/main/java/org/fossasia/susi/ai/rest/clients/WebSearchClient.java
759
package org.fossasia.susi.ai.rest.clients; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; /** * <h1>Class to get retrofit client to get websearch results.</h1> * * Created by mayank on 12-12-2016. */ public class WebSearchClient { private static final String BASE_URL = "http://api.duckduckgo.com"; private static Retrofit retrofit = null; /** * Gets client. * * @return the client */ public static Retrofit getClient() { if (retrofit==null) { retrofit = new Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .build(); } return retrofit; } }
apache-2.0
agileowl/tapestry-5
tapestry-hibernate/src/test/java/org/example/app0/pages/CachedForm.java
1612
// Copyright 2008 The Apache Software Foundation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.example.app0.pages; import org.apache.tapestry5.annotations.Cached; import org.apache.tapestry5.annotations.Property; import org.apache.tapestry5.hibernate.annotations.CommitAfter; import org.apache.tapestry5.ioc.annotations.Inject; import org.example.app0.entities.User; import org.example.app0.services.UserDAO; import org.hibernate.Session; import java.util.List; @SuppressWarnings("unused") public class CachedForm { @Property private String name; @Property private User user; @Property private int index; @Inject private Session session; @Inject private UserDAO userDAO; @CommitAfter void onSuccess() { User user = new User(); user.setFirstName(name); session.save(user); } @SuppressWarnings("unchecked") @Cached public List<User> getUsers() { return session.createQuery("from User").list(); } void onActionFromSetup() { userDAO.deleteAll(); } }
apache-2.0
apache/tinkerpop
gremlin-core/src/test/java/org/apache/tinkerpop/gremlin/process/traversal/strategy/decoration/VertexProgramStrategyTest.java
4542
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.tinkerpop.gremlin.process.traversal.strategy.decoration; import org.apache.tinkerpop.gremlin.process.computer.Computer; import org.apache.tinkerpop.gremlin.process.computer.traversal.step.map.ComputerResultStep; import org.apache.tinkerpop.gremlin.process.computer.traversal.step.map.TraversalVertexProgramStep; import org.apache.tinkerpop.gremlin.process.computer.traversal.strategy.decoration.VertexProgramStrategy; import org.apache.tinkerpop.gremlin.process.traversal.Step; import org.apache.tinkerpop.gremlin.process.traversal.Translator; import org.apache.tinkerpop.gremlin.process.traversal.Traversal; import org.apache.tinkerpop.gremlin.process.traversal.TraversalStrategies; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.DefaultGraphTraversal; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__; import org.apache.tinkerpop.gremlin.process.traversal.strategy.verification.ComputerVerificationStrategy; import org.apache.tinkerpop.gremlin.process.traversal.translator.GroovyTranslator; import org.apache.tinkerpop.gremlin.process.traversal.util.DefaultTraversalStrategies; import org.apache.tinkerpop.gremlin.process.traversal.util.EmptyTraversal; import org.apache.tinkerpop.gremlin.structure.util.empty.EmptyGraph; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import java.util.Arrays; import static org.junit.Assert.assertEquals; /** * @author Marko A. Rodriguez (http://markorodriguez.com) */ @RunWith(Parameterized.class) public class VertexProgramStrategyTest { private static final Translator.ScriptTranslator translator = GroovyTranslator.of("__"); @Parameterized.Parameter(value = 0) public Traversal.Admin original; @Parameterized.Parameter(value = 1) public Traversal optimized; @Test public void doTest() { final String repr = translator.translate(original.getBytecode()).getScript(); final TraversalStrategies strategies = new DefaultTraversalStrategies(); strategies.addStrategies(new VertexProgramStrategy(Computer.compute()), ComputerVerificationStrategy.instance()); original.asAdmin().setStrategies(strategies); original.asAdmin().applyStrategies(); assertEquals(repr, optimized, original); } @Parameterized.Parameters(name = "{0}") public static Iterable<Object[]> generateTestParameters() { final ComputerResultStep computerResultStep = new ComputerResultStep(EmptyTraversal.instance()); return Arrays.asList(new Traversal[][]{ {__.V().out().count(), start().addStep(traversal(__.V().out().count())).addStep(computerResultStep)}, {__.V().pageRank().out().count(), start().pageRank().asAdmin().addStep(traversal(__.V().out().count())).addStep(computerResultStep)}, {__.V().out().pageRank(), start().addStep(traversal(__.V().out())).pageRank().asAdmin().addStep(traversal(__.identity())).addStep(computerResultStep)}, {__.V().out().pageRank().count(), start().addStep(traversal(__.V().out())).pageRank().asAdmin().addStep(traversal(__.count())).addStep(computerResultStep)}, {__.V().pageRank().order().limit(1), start().pageRank().asAdmin().addStep(traversal(__.V().order().limit(1))).addStep(computerResultStep)} }); } private static GraphTraversal.Admin<?, ?> start() { return new DefaultGraphTraversal<>().asAdmin(); } private static Step<?, ?> traversal(final Traversal<?, ?> traversal) { return new TraversalVertexProgramStep(EmptyTraversal.instance(), traversal.asAdmin()); } }
apache-2.0
alexzaitzev/ignite
modules/core/src/test/java/org/apache/ignite/testsuites/IgnitePerformanceTestSuite.java
6797
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.ignite.testsuites; import junit.framework.TestSuite; import org.apache.ignite.internal.processors.cache.GridCacheConcurrentTxMultiNodeLoadTest; import org.apache.ignite.internal.processors.cache.GridCacheIteratorPerformanceTest; import org.apache.ignite.internal.processors.cache.distributed.dht.GridCacheDhtPreloadPerformanceTest; import org.apache.ignite.internal.processors.cache.distributed.near.GridCachePartitionedAffinityExcludeNeighborsPerformanceTest; import org.apache.ignite.internal.processors.cache.eviction.sorted.SortedEvictionPolicyPerformanceTest; import org.apache.ignite.internal.processors.datastreamer.IgniteDataStreamerPerformanceTest; import org.apache.ignite.internal.util.offheap.unsafe.GridUnsafeMapPerformanceTest; import org.apache.ignite.internal.util.offheap.unsafe.GridUnsafePartitionedMapPerformanceTest; import org.apache.ignite.lang.GridBasicPerformanceTest; import org.apache.ignite.lang.GridFuncPerformanceTest; import org.apache.ignite.lang.GridFutureListenPerformanceTest; import org.apache.ignite.lang.GridMetadataAwareAdapterLoadTest; import org.apache.ignite.lang.utils.GridCircularBufferPerformanceTest; import org.apache.ignite.lang.utils.GridLeanMapPerformanceTest; import org.apache.ignite.loadtests.GridCacheMultiNodeLoadTest; import org.apache.ignite.loadtests.GridSingleExecutionTest; import org.apache.ignite.loadtests.cache.GridCacheDataStructuresLoadTest; import org.apache.ignite.loadtests.cache.GridCacheLoadTest; import org.apache.ignite.loadtests.cache.GridCacheWriteBehindStoreLoadTest; import org.apache.ignite.loadtests.capacity.GridCapacityLoadTest; import org.apache.ignite.loadtests.continuous.GridContinuousOperationsLoadTest; import org.apache.ignite.loadtests.datastructures.GridCachePartitionedAtomicLongLoadTest; import org.apache.ignite.loadtests.direct.multisplit.GridMultiSplitsLoadTest; import org.apache.ignite.loadtests.direct.multisplit.GridMultiSplitsRedeployLoadTest; import org.apache.ignite.loadtests.direct.newnodes.GridSingleSplitsNewNodesMulticastLoadTest; import org.apache.ignite.loadtests.direct.redeploy.GridSingleSplitsRedeployLoadTest; import org.apache.ignite.loadtests.direct.session.GridSessionLoadTest; import org.apache.ignite.loadtests.direct.stealing.GridStealingLoadTest; import org.apache.ignite.loadtests.discovery.GridGcTimeoutTest; import org.apache.ignite.loadtests.dsi.cacheget.GridBenchmarkCacheGetLoadTest; import org.apache.ignite.loadtests.hashmap.GridBoundedConcurrentLinkedHashSetLoadTest; import org.apache.ignite.loadtests.hashmap.GridHashMapLoadTest; import org.apache.ignite.loadtests.job.GridJobExecutionSingleNodeLoadTest; import org.apache.ignite.loadtests.job.GridJobExecutionSingleNodeSemaphoreLoadTest; import org.apache.ignite.loadtests.job.GridJobLoadTest; import org.apache.ignite.loadtests.mergesort.GridMergeSortLoadTest; import org.apache.ignite.loadtests.nio.GridNioBenchmarkTest; import org.apache.ignite.marshaller.GridMarshallerPerformanceTest; import org.apache.ignite.spi.communication.tcp.GridTcpCommunicationSpiLanLoadTest; /** * Tests suite for performance tests tests. * Note: Most of these are resource-consuming or non-terminating. */ public class IgnitePerformanceTestSuite extends TestSuite { /** * @return Tests suite for orphaned tests (not in any test sute previously). */ public static TestSuite suite() { TestSuite suite = new TestSuite("Ignite Load-Test Suite"); suite.addTestSuite(GridCacheDhtPreloadPerformanceTest.class); suite.addTestSuite(GridCacheIteratorPerformanceTest.class); suite.addTestSuite(GridCacheMultiNodeLoadTest.class); suite.addTestSuite(GridCacheConcurrentTxMultiNodeLoadTest.class); suite.addTestSuite(GridCachePartitionedAffinityExcludeNeighborsPerformanceTest.class); suite.addTestSuite(GridCachePartitionedAtomicLongLoadTest.class); suite.addTestSuite(GridCacheWriteBehindStoreLoadTest.class); suite.addTestSuite(GridCircularBufferPerformanceTest.class); suite.addTestSuite(GridFuncPerformanceTest.class); suite.addTestSuite(GridHashMapLoadTest.class); suite.addTestSuite(GridLeanMapPerformanceTest.class); suite.addTestSuite(GridMarshallerPerformanceTest.class); suite.addTestSuite(GridMetadataAwareAdapterLoadTest.class); suite.addTestSuite(GridMultiSplitsLoadTest.class); suite.addTestSuite(GridMultiSplitsRedeployLoadTest.class); suite.addTestSuite(GridSessionLoadTest.class); suite.addTestSuite(GridSingleSplitsNewNodesMulticastLoadTest.class); suite.addTestSuite(GridSingleSplitsRedeployLoadTest.class); suite.addTestSuite(GridStealingLoadTest.class); suite.addTestSuite(GridTcpCommunicationSpiLanLoadTest.class); suite.addTestSuite(GridUnsafeMapPerformanceTest.class); suite.addTestSuite(GridUnsafePartitionedMapPerformanceTest.class); suite.addTestSuite(IgniteDataStreamerPerformanceTest.class); suite.addTestSuite(SortedEvictionPolicyPerformanceTest.class); // Non-JUnit classes with Test in name, which should be either converted to JUnit or removed in the future // Main classes: Class[] _$ = new Class[] { GridBasicPerformanceTest.class, GridBenchmarkCacheGetLoadTest.class, GridBoundedConcurrentLinkedHashSetLoadTest.class, GridCacheDataStructuresLoadTest.class, GridCacheLoadTest.class, GridCapacityLoadTest.class, GridContinuousOperationsLoadTest.class, GridFutureListenPerformanceTest.class, GridGcTimeoutTest.class, GridJobExecutionSingleNodeLoadTest.class, GridJobExecutionSingleNodeSemaphoreLoadTest.class, GridJobLoadTest.class, GridMergeSortLoadTest.class, GridNioBenchmarkTest.class, GridSingleExecutionTest.class }; return suite; } }
apache-2.0
codescale/logging-log4j2
log4j-perf/src/main/java/org/apache/logging/log4j/perf/jmh/GelfLayoutBenchmark.java
4207
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache license, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the license for the specific language governing permissions and * limitations under the license. */ package org.apache.logging.log4j.perf.jmh; import org.apache.logging.log4j.Marker; import org.apache.logging.log4j.ThreadContext; import org.apache.logging.log4j.core.Appender; import org.apache.logging.log4j.core.LogEvent; import org.apache.logging.log4j.core.config.NullConfiguration; import org.apache.logging.log4j.core.impl.Log4jLogEvent; import org.apache.logging.log4j.core.layout.GelfLayout; import org.apache.logging.log4j.core.util.KeyValuePair; import org.apache.logging.log4j.message.Message; import org.apache.logging.log4j.message.SimpleMessage; import org.apache.logging.log4j.perf.util.DemoAppender; import org.openjdk.jmh.annotations.*; import java.util.Map; import java.util.concurrent.TimeUnit; /** * Benchmarks Log4j 2 GelfLayout. */ // HOW TO RUN THIS TEST // java -jar target/benchmarks.jar GelfLayoutBenchmark -f 1 -i 5 -wi 5 -bm sample -tu ns @State(Scope.Thread) public class GelfLayoutBenchmark { private static final CharSequence MESSAGE = "This is rather long and chatty log message with quite some interesting information and a bit of fun in it which is suitable here"; private static final LogEvent EVENT = createLogEvent(); private static final KeyValuePair[] ADDITIONAL_FIELDS = new KeyValuePair[0]; private static LogEvent createLogEvent() { final Marker marker = null; final String fqcn = "com.mycom.myproject.mypackage.MyClass"; final org.apache.logging.log4j.Level level = org.apache.logging.log4j.Level.DEBUG; final Message message = new SimpleMessage(MESSAGE); final Throwable t = null; final Map<String, String> mdc = null; final ThreadContext.ContextStack ndc = null; final String threadName = null; final StackTraceElement location = null; final long timestamp = 12345678; return Log4jLogEvent.newBuilder() // .setLoggerName("name(ignored)") // .setMarker(marker) // .setLoggerFqcn(fqcn) // .setLevel(level) // .setMessage(message) // .setThrown(t) // .setContextMap(mdc) // .setContextStack(ndc) // .setThreadName(threadName) // .setSource(location) // .setTimeMillis(timestamp) // .build(); } Appender appender; int j; @Setup public void setUp() { System.setProperty("log4j2.enable.direct.encoders", "true"); appender = new DemoAppender(GelfLayout.newBuilder() .setConfiguration(new NullConfiguration()) .setHost("host") .setAdditionalFields(ADDITIONAL_FIELDS) .setCompressionType(GelfLayout.CompressionType.OFF) .setCompressionThreshold(0) .setIncludeStacktrace(true) .setIncludeThreadContext(true) .build()); j = 0; } @TearDown public void tearDown() { System.clearProperty("log4j2.enable.direct.encoders"); } @BenchmarkMode(Mode.Throughput) @OutputTimeUnit(TimeUnit.MILLISECONDS) @Benchmark public boolean baseline() { ++j; return true; } @BenchmarkMode(Mode.Throughput) @OutputTimeUnit(TimeUnit.MILLISECONDS) @Benchmark public void log4j2Gelf() { appender.append(EVENT); } }
apache-2.0
NJUJYB/disYarn
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-common/src/main/java/org/apache/hadoop/yarn/server/webapp/AppBlock.java
15084
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn.server.webapp; import static org.apache.hadoop.yarn.util.StringHelper.join; import static org.apache.hadoop.yarn.webapp.YarnWebParams.APPLICATION_ID; import static org.apache.hadoop.yarn.webapp.YarnWebParams.WEB_UI_TYPE; import java.security.PrivilegedExceptionAction; import java.util.Collection; import java.util.Map; import org.apache.commons.lang.StringEscapeUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.security.UserGroupInformation; import org.apache.hadoop.security.http.RestCsrfPreventionFilter; import org.apache.hadoop.util.StringUtils; import org.apache.hadoop.yarn.api.ApplicationBaseProtocol; import org.apache.hadoop.yarn.api.protocolrecords.GetApplicationAttemptsRequest; import org.apache.hadoop.yarn.api.protocolrecords.GetApplicationReportRequest; import org.apache.hadoop.yarn.api.protocolrecords.GetContainerReportRequest; import org.apache.hadoop.yarn.api.records.ApplicationAttemptReport; import org.apache.hadoop.yarn.api.records.ApplicationId; import org.apache.hadoop.yarn.api.records.ApplicationReport; import org.apache.hadoop.yarn.api.records.ContainerReport; import org.apache.hadoop.yarn.api.records.FinalApplicationStatus; import org.apache.hadoop.yarn.api.records.LogAggregationStatus; import org.apache.hadoop.yarn.api.records.YarnApplicationState; import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.apache.hadoop.yarn.exceptions.ContainerNotFoundException; import org.apache.hadoop.yarn.server.webapp.dao.AppAttemptInfo; import org.apache.hadoop.yarn.server.webapp.dao.AppInfo; import org.apache.hadoop.yarn.server.webapp.dao.ContainerInfo; import org.apache.hadoop.yarn.util.Apps; import org.apache.hadoop.yarn.util.Times; import org.apache.hadoop.yarn.webapp.ResponseInfo; import org.apache.hadoop.yarn.webapp.YarnWebParams; import org.apache.hadoop.yarn.webapp.hamlet.Hamlet; import org.apache.hadoop.yarn.webapp.hamlet.Hamlet.TABLE; import org.apache.hadoop.yarn.webapp.hamlet.Hamlet.TBODY; import org.apache.hadoop.yarn.webapp.util.WebAppUtils; import org.apache.hadoop.yarn.webapp.view.HtmlBlock; import org.apache.hadoop.yarn.webapp.view.InfoBlock; import com.google.inject.Inject; public class AppBlock extends HtmlBlock { private static final Log LOG = LogFactory.getLog(AppBlock.class); protected ApplicationBaseProtocol appBaseProt; protected Configuration conf; protected ApplicationId appID = null; @Inject protected AppBlock(ApplicationBaseProtocol appBaseProt, ViewContext ctx, Configuration conf) { super(ctx); this.appBaseProt = appBaseProt; this.conf = conf; } @Override protected void render(Block html) { String webUiType = $(WEB_UI_TYPE); String aid = $(APPLICATION_ID); if (aid.isEmpty()) { puts("Bad request: requires Application ID"); return; } try { appID = Apps.toAppID(aid); } catch (Exception e) { puts("Invalid Application ID: " + aid); return; } UserGroupInformation callerUGI = getCallerUGI(); ApplicationReport appReport; try { final GetApplicationReportRequest request = GetApplicationReportRequest.newInstance(appID); if (callerUGI == null) { appReport = appBaseProt.getApplicationReport(request).getApplicationReport(); } else { appReport = callerUGI.doAs( new PrivilegedExceptionAction<ApplicationReport> () { @Override public ApplicationReport run() throws Exception { return appBaseProt.getApplicationReport(request) .getApplicationReport(); } }); } } catch (Exception e) { String message = "Failed to read the application " + appID + "."; LOG.error(message, e); html.p()._(message)._(); return; } if (appReport == null) { puts("Application not found: " + aid); return; } AppInfo app = new AppInfo(appReport); setTitle(join("Application ", aid)); if (webUiType != null && webUiType.equals(YarnWebParams.RM_WEB_UI) && conf.getBoolean(YarnConfiguration.RM_WEBAPP_UI_ACTIONS_ENABLED, YarnConfiguration.DEFAULT_RM_WEBAPP_UI_ACTIONS_ENABLED)) { // Application Kill html.div() .button() .$onclick("confirmAction()").b("Kill Application")._() ._(); StringBuilder script = new StringBuilder(); script.append("function confirmAction() {") .append(" b = confirm(\"Are you sure?\");") .append(" if (b == true) {") .append(" $.ajax({") .append(" type: 'PUT',") .append(" url: '/ws/v1/cluster/apps/").append(aid).append("/state',") .append(" contentType: 'application/json',") .append(getCSRFHeaderString(conf)) .append(" data: '{\"state\":\"KILLED\"}',") .append(" dataType: 'json'") .append(" }).done(function(data){") .append(" setTimeout(function(){") .append(" location.href = '/cluster/app/").append(aid).append("';") .append(" }, 1000);") .append(" }).fail(function(data){") .append(" console.log(data);") .append(" });") .append(" }") .append("}"); html.script().$type("text/javascript")._(script.toString())._(); } String schedulerPath = WebAppUtils.getResolvedRMWebAppURLWithScheme(conf) + "/cluster/scheduler?openQueues=" + app.getQueue(); ResponseInfo overviewTable = info("Application Overview") ._("User:", schedulerPath, app.getUser()) ._("Name:", app.getName()) ._("Application Type:", app.getType()) ._("Application Tags:", app.getApplicationTags() == null ? "" : app.getApplicationTags()) ._("Application Priority:", clarifyAppPriority(app.getPriority())) ._( "YarnApplicationState:", app.getAppState() == null ? UNAVAILABLE : clarifyAppState(app .getAppState())) ._("Queue:", schedulerPath, app.getQueue()) ._("FinalStatus Reported by AM:", clairfyAppFinalStatus(app.getFinalAppStatus())) ._("Started:", Times.format(app.getStartedTime())) ._( "Elapsed:", StringUtils.formatTime(Times.elapsed(app.getStartedTime(), app.getFinishedTime()))) ._( "Tracking URL:", app.getTrackingUrl() == null || app.getTrackingUrl().equals(UNAVAILABLE) ? null : root_url(app .getTrackingUrl()), app.getTrackingUrl() == null || app.getTrackingUrl().equals(UNAVAILABLE) ? "Unassigned" : app .getAppState() == YarnApplicationState.FINISHED || app.getAppState() == YarnApplicationState.FAILED || app.getAppState() == YarnApplicationState.KILLED ? "History" : "ApplicationMaster"); if (webUiType != null && webUiType.equals(YarnWebParams.RM_WEB_UI)) { LogAggregationStatus status = getLogAggregationStatus(); if (status == null) { overviewTable._("Log Aggregation Status:", "N/A"); } else if (status == LogAggregationStatus.DISABLED || status == LogAggregationStatus.NOT_START || status == LogAggregationStatus.SUCCEEDED) { overviewTable._("Log Aggregation Status:", status.name()); } else { overviewTable._("Log Aggregation Status:", root_url("logaggregationstatus", app.getAppId()), status.name()); } } overviewTable._("Diagnostics:", app.getDiagnosticsInfo() == null ? "" : app.getDiagnosticsInfo()); overviewTable._("Unmanaged Application:", app.isUnmanagedApp()); overviewTable._("Application Node Label expression:", app.getAppNodeLabelExpression() == null ? "<Not set>" : app.getAppNodeLabelExpression()); overviewTable._("AM container Node Label expression:", app.getAmNodeLabelExpression() == null ? "<Not set>" : app.getAmNodeLabelExpression()); Collection<ApplicationAttemptReport> attempts; try { final GetApplicationAttemptsRequest request = GetApplicationAttemptsRequest.newInstance(appID); if (callerUGI == null) { attempts = appBaseProt.getApplicationAttempts(request) .getApplicationAttemptList(); } else { attempts = callerUGI.doAs( new PrivilegedExceptionAction<Collection<ApplicationAttemptReport>> () { @Override public Collection<ApplicationAttemptReport> run() throws Exception { return appBaseProt.getApplicationAttempts(request) .getApplicationAttemptList(); } }); } } catch (Exception e) { String message = "Failed to read the attempts of the application " + appID + "."; LOG.error(message, e); html.p()._(message)._(); return; } createApplicationMetricsTable(html); html._(InfoBlock.class); generateApplicationTable(html, callerUGI, attempts); } protected void generateApplicationTable(Block html, UserGroupInformation callerUGI, Collection<ApplicationAttemptReport> attempts) { // Application Attempt Table TBODY<TABLE<Hamlet>> tbody = html.table("#attempts").thead().tr().th(".id", "Attempt ID") .th(".started", "Started").th(".node", "Node").th(".logs", "Logs") ._()._().tbody(); StringBuilder attemptsTableData = new StringBuilder("[\n"); for (final ApplicationAttemptReport appAttemptReport : attempts) { AppAttemptInfo appAttempt = new AppAttemptInfo(appAttemptReport); ContainerReport containerReport; try { final GetContainerReportRequest request = GetContainerReportRequest.newInstance( appAttemptReport.getAMContainerId()); if (callerUGI == null) { containerReport = appBaseProt.getContainerReport(request).getContainerReport(); } else { containerReport = callerUGI.doAs( new PrivilegedExceptionAction<ContainerReport>() { @Override public ContainerReport run() throws Exception { ContainerReport report = null; if (request.getContainerId() != null) { try { report = appBaseProt.getContainerReport(request) .getContainerReport(); } catch (ContainerNotFoundException ex) { LOG.warn(ex.getMessage()); } } return report; } }); } } catch (Exception e) { String message = "Failed to read the AM container of the application attempt " + appAttemptReport.getApplicationAttemptId() + "."; LOG.error(message, e); html.p()._(message)._(); return; } long startTime = 0L; String logsLink = null; String nodeLink = null; if (containerReport != null) { ContainerInfo container = new ContainerInfo(containerReport); startTime = container.getStartedTime(); logsLink = containerReport.getLogUrl(); nodeLink = containerReport.getNodeHttpAddress(); } attemptsTableData .append("[\"<a href='") .append(url("appattempt", appAttempt.getAppAttemptId())) .append("'>") .append(appAttempt.getAppAttemptId()) .append("</a>\",\"") .append(startTime) .append("\",\"<a ") .append(nodeLink == null ? "#" : "href='" + nodeLink) .append("'>") .append(nodeLink == null ? "N/A" : StringEscapeUtils .escapeJavaScript(StringEscapeUtils.escapeHtml(nodeLink))) .append("</a>\",\"<a ") .append(logsLink == null ? "#" : "href='" + logsLink).append("'>") .append(logsLink == null ? "N/A" : "Logs").append("</a>\"],\n"); } if (attemptsTableData.charAt(attemptsTableData.length() - 2) == ',') { attemptsTableData.delete(attemptsTableData.length() - 2, attemptsTableData.length() - 1); } attemptsTableData.append("]"); html.script().$type("text/javascript") ._("var attemptsTableData=" + attemptsTableData)._(); tbody._()._(); } private String clarifyAppState(YarnApplicationState state) { String ret = state.toString(); switch (state) { case NEW: return ret + ": waiting for application to be initialized"; case NEW_SAVING: return ret + ": waiting for application to be persisted in state-store."; case SUBMITTED: return ret + ": waiting for application to be accepted by scheduler."; case ACCEPTED: return ret + ": waiting for AM container to be allocated, launched and" + " register with RM."; case RUNNING: return ret + ": AM has registered with RM and started running."; default: return ret; } } private String clarifyAppPriority(int priority) { return priority + " (Higher Integer value indicates higher priority)"; } private String clairfyAppFinalStatus(FinalApplicationStatus status) { if (status == FinalApplicationStatus.UNDEFINED) { return "Application has not completed yet."; } return status.toString(); } // The preemption metrics only need to be shown in RM WebUI protected void createApplicationMetricsTable(Block html) { } // This will be overrided in RMAppBlock protected LogAggregationStatus getLogAggregationStatus() { return null; } public static String getCSRFHeaderString(Configuration conf) { String ret = ""; if (conf.getBoolean(YarnConfiguration.RM_CSRF_ENABLED, false)) { ret = " headers : { '"; Map<String, String> filterParams = RestCsrfPreventionFilter .getFilterParams(conf, YarnConfiguration.RM_CSRF_PREFIX); if (filterParams .containsKey(RestCsrfPreventionFilter.CUSTOM_HEADER_PARAM)) { ret += filterParams.get(RestCsrfPreventionFilter.CUSTOM_HEADER_PARAM); } else { ret += RestCsrfPreventionFilter.HEADER_DEFAULT; } ret += "' : 'null' },"; } return ret; } }
apache-2.0
Fitzoh/pact-jvm
pact-jvm-provider-junit/src/main/java/au/com/dius/pact/provider/junit/VerificationReports.java
582
package au.com.dius.pact.provider.junit; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Annotation to control the generation of verification reports */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface VerificationReports { /** * Names of the reports to generate */ String[] value() default "console"; /** * Directory where reports should be written */ String reportDir() default "target/pact/reports"; }
apache-2.0
akdasari/SparkAdmin
spark-open-admin-platform/src/main/java/org/sparkcommerce/openadmin/server/service/persistence/module/provider/RuleFieldPersistenceProvider.java
21610
/* * #%L * SparkCommerce Open Admin Platform * %% * Copyright (C) 2009 - 2013 Spark Commerce * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ package org.sparkcommerce.openadmin.server.service.persistence.module.provider; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang.StringUtils; import org.sparkcommerce.common.presentation.RuleIdentifier; import org.sparkcommerce.common.presentation.client.SupportedFieldType; import org.sparkcommerce.common.rule.QuantityBasedRule; import org.sparkcommerce.common.rule.SimpleRule; import org.sparkcommerce.common.sandbox.SandBoxHelper; import org.sparkcommerce.openadmin.dto.BasicFieldMetadata; import org.sparkcommerce.openadmin.dto.FieldMetadata; import org.sparkcommerce.openadmin.dto.Property; import org.sparkcommerce.openadmin.server.service.persistence.PersistenceException; import org.sparkcommerce.openadmin.server.service.persistence.module.FieldManager; import org.sparkcommerce.openadmin.server.service.persistence.module.FieldNotAvailableException; import org.sparkcommerce.openadmin.server.service.persistence.module.provider.request.AddFilterPropertiesRequest; import org.sparkcommerce.openadmin.server.service.persistence.module.provider.request.ExtractValueRequest; import org.sparkcommerce.openadmin.server.service.persistence.module.provider.request.PopulateValueRequest; import org.sparkcommerce.openadmin.server.service.type.FieldProviderResponse; import org.sparkcommerce.openadmin.web.rulebuilder.DataDTOToMVELTranslator; import org.sparkcommerce.openadmin.web.rulebuilder.MVELToDataWrapperTranslator; import org.sparkcommerce.openadmin.web.rulebuilder.MVELTranslationException; import org.sparkcommerce.openadmin.web.rulebuilder.dto.DataDTO; import org.sparkcommerce.openadmin.web.rulebuilder.dto.DataWrapper; import org.sparkcommerce.openadmin.web.rulebuilder.service.RuleBuilderFieldServiceFactory; import org.codehaus.jackson.map.ObjectMapper; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.annotation.Resource; import javax.persistence.EntityManager; /** * @author Jeff Fischer */ @Component("blRuleFieldPersistenceProvider") @Scope("prototype") public class RuleFieldPersistenceProvider extends FieldPersistenceProviderAdapter { protected boolean canHandlePersistence(PopulateValueRequest populateValueRequest, Serializable instance) { return populateValueRequest.getMetadata().getFieldType() == SupportedFieldType.RULE_WITH_QUANTITY || populateValueRequest.getMetadata().getFieldType() == SupportedFieldType.RULE_SIMPLE; } protected boolean canHandleExtraction(ExtractValueRequest extractValueRequest, Property property) { return extractValueRequest.getMetadata().getFieldType() == SupportedFieldType.RULE_WITH_QUANTITY || extractValueRequest.getMetadata().getFieldType() == SupportedFieldType.RULE_SIMPLE; } @Resource(name = "blRuleBuilderFieldServiceFactory") protected RuleBuilderFieldServiceFactory ruleBuilderFieldServiceFactory; @Resource(name = "blSandBoxHelper") protected SandBoxHelper sandBoxHelper; @Resource(name = "blRuleFieldExtractionUtility") protected RuleFieldExtractionUtility ruleFieldExtractionUtility; @Override public FieldProviderResponse populateValue(PopulateValueRequest populateValueRequest, Serializable instance) throws PersistenceException { if (!canHandlePersistence(populateValueRequest, instance)) { return FieldProviderResponse.NOT_HANDLED; } boolean dirty = false; try { setNonDisplayableValues(populateValueRequest); switch (populateValueRequest.getMetadata().getFieldType()) { case RULE_WITH_QUANTITY:{ //currently, this only works with Collection fields Class<?> valueType = getListFieldType(instance, populateValueRequest .getFieldManager(), populateValueRequest.getProperty(), populateValueRequest.getPersistenceManager()); if (valueType == null) { throw new IllegalAccessException("Unable to determine the valueType for the rule field (" + populateValueRequest.getProperty().getName() + ")"); } DataDTOToMVELTranslator translator = new DataDTOToMVELTranslator(); Collection<QuantityBasedRule> rules; try { rules = (Collection<QuantityBasedRule>) populateValueRequest.getFieldManager().getFieldValue (instance, populateValueRequest.getProperty().getName()); } catch (FieldNotAvailableException e) { throw new IllegalArgumentException(e); } //AntiSamy HTML encodes the rule JSON - pass the unHTMLEncoded version dirty = populateQuantityBaseRuleCollection(populateValueRequest.getPersistenceManager().getDynamicEntityDao().getStandardEntityManager(), translator, RuleIdentifier.ENTITY_KEY_MAP.get(populateValueRequest.getMetadata().getRuleIdentifier()), populateValueRequest.getMetadata().getRuleIdentifier(), populateValueRequest.getProperty().getUnHtmlEncodedValue(), rules, valueType); break; } case RULE_SIMPLE:{ DataDTOToMVELTranslator translator = new DataDTOToMVELTranslator(); //AntiSamy HTML encodes the rule JSON - pass the unHTMLEncoded version DataWrapper dw = ruleFieldExtractionUtility.convertJsonToDataWrapper(populateValueRequest.getProperty().getUnHtmlEncodedValue()); if (dw == null || StringUtils.isEmpty(dw.getError())) { String mvel = ruleFieldExtractionUtility.convertSimpleMatchRuleJsonToMvel(translator, RuleIdentifier.ENTITY_KEY_MAP.get(populateValueRequest.getMetadata().getRuleIdentifier()), populateValueRequest.getMetadata().getRuleIdentifier(), dw); Class<?> valueType = null; //is this a regular field? if (!populateValueRequest.getProperty().getName().contains(FieldManager.MAPFIELDSEPARATOR)) { valueType = populateValueRequest.getReturnType(); } else { String valueClassName = populateValueRequest.getMetadata().getMapFieldValueClass(); if (valueClassName != null) { valueType = Class.forName(valueClassName); } if (valueType == null) { valueType = populateValueRequest.getReturnType(); } } if (valueType == null) { throw new IllegalAccessException("Unable to determine the valueType for the rule field (" + populateValueRequest.getProperty().getName() + ")"); } //This is a simple String field (or String map field) if (String.class.isAssignableFrom(valueType)) { //first check if the property is null and the mvel is null if (instance != null && mvel == null) { Object value = populateValueRequest.getFieldManager().getFieldValue(instance, populateValueRequest.getProperty().getName()); dirty = value != null; } else { dirty = checkDirtyState(populateValueRequest, instance, mvel); } populateValueRequest.getFieldManager().setFieldValue(instance, populateValueRequest.getProperty().getName(), mvel); } if (SimpleRule.class.isAssignableFrom(valueType)) { //see if there's an existing rule SimpleRule rule; try { rule = (SimpleRule) populateValueRequest.getFieldManager().getFieldValue(instance, populateValueRequest.getProperty().getName()); } catch (FieldNotAvailableException e) { throw new IllegalArgumentException(e); } if (mvel == null) { //cause the rule to be deleted dirty = populateValueRequest.getFieldManager().getFieldValue(instance, populateValueRequest.getProperty().getName()) != null; populateValueRequest.getFieldManager().setFieldValue(instance, populateValueRequest.getProperty().getName(), null); } else if (rule != null) { dirty = !rule.getMatchRule().equals(mvel); rule.setMatchRule(mvel); } else { //create a new instance, persist and set dirty = true; rule = (SimpleRule) valueType.newInstance(); rule.setMatchRule(mvel); populateValueRequest.getPersistenceManager().getDynamicEntityDao().persist(rule); populateValueRequest.getFieldManager().setFieldValue(instance, populateValueRequest.getProperty().getName(), rule); } } } break; } } } catch (Exception e) { throw new PersistenceException(e); } populateValueRequest.getProperty().setIsDirty(dirty); return FieldProviderResponse.HANDLED_BREAK; } @Override public FieldProviderResponse extractValue(ExtractValueRequest extractValueRequest, Property property) throws PersistenceException { if (!canHandleExtraction(extractValueRequest, property)) { return FieldProviderResponse.NOT_HANDLED; } String val = null; ObjectMapper mapper = new ObjectMapper(); MVELToDataWrapperTranslator translator = new MVELToDataWrapperTranslator(); if (extractValueRequest.getMetadata().getFieldType()== SupportedFieldType.RULE_SIMPLE) { if (extractValueRequest.getRequestedValue() != null) { if (extractValueRequest.getRequestedValue() instanceof String) { val = (String) extractValueRequest.getRequestedValue(); property.setValue(val); property.setDisplayValue(extractValueRequest.getDisplayVal()); } if (extractValueRequest.getRequestedValue() instanceof SimpleRule) { SimpleRule simpleRule = (SimpleRule) extractValueRequest.getRequestedValue(); if (simpleRule != null) { val = simpleRule.getMatchRule(); property.setValue(val); property.setDisplayValue(extractValueRequest.getDisplayVal()); } } } Property jsonProperty = ruleFieldExtractionUtility.convertSimpleRuleToJson(translator, mapper, val, property.getName() + "Json", extractValueRequest.getMetadata().getRuleIdentifier()); extractValueRequest.getProps().add(jsonProperty); } if (extractValueRequest.getMetadata().getFieldType()==SupportedFieldType.RULE_WITH_QUANTITY) { if (extractValueRequest.getRequestedValue() != null) { if (extractValueRequest.getRequestedValue() instanceof Collection) { //these quantity rules are in a list - this is a special, valid case for quantity rules Property jsonProperty = ruleFieldExtractionUtility.convertQuantityBasedRuleToJson(translator, mapper, (Collection<QuantityBasedRule>) extractValueRequest.getRequestedValue(), extractValueRequest.getMetadata().getName() + "Json", extractValueRequest.getMetadata().getRuleIdentifier()); extractValueRequest.getProps().add(jsonProperty); } else { //TODO support a single quantity based rule throw new UnsupportedOperationException("RULE_WITH_QUANTITY type is currently only supported" + "on collection fields. A single field with this type is not currently supported."); } } } return FieldProviderResponse.HANDLED; } @Override public FieldProviderResponse filterProperties(AddFilterPropertiesRequest addFilterPropertiesRequest, Map<String, FieldMetadata> properties) { //This may contain rule Json fields - convert and filter out List<Property> propertyList = new ArrayList<Property>(); propertyList.addAll(Arrays.asList(addFilterPropertiesRequest.getEntity().getProperties())); Iterator<Property> itr = propertyList.iterator(); List<Property> additionalProperties = new ArrayList<Property>(); while(itr.hasNext()) { Property prop = itr.next(); if (prop.getName().endsWith("Json")) { for (Map.Entry<String, FieldMetadata> entry : properties.entrySet()) { if (prop.getName().startsWith(entry.getKey())) { BasicFieldMetadata originalFM = (BasicFieldMetadata) entry.getValue(); if (originalFM.getFieldType() == SupportedFieldType.RULE_SIMPLE || originalFM.getFieldType() == SupportedFieldType.RULE_WITH_QUANTITY) { Property originalProp = addFilterPropertiesRequest.getEntity().findProperty(entry.getKey()); if (originalProp == null) { originalProp = new Property(); originalProp.setName(entry.getKey()); additionalProperties.add(originalProp); } originalProp.setValue(prop.getValue()); originalProp.setRawValue(prop.getRawValue()); originalProp.setUnHtmlEncodedValue(prop.getUnHtmlEncodedValue()); itr.remove(); break; } } } } } propertyList.addAll(additionalProperties); addFilterPropertiesRequest.getEntity().setProperties(propertyList.toArray(new Property[propertyList.size()])); return FieldProviderResponse.HANDLED; } protected boolean populateQuantityBaseRuleCollection(EntityManager em, DataDTOToMVELTranslator translator, String entityKey, String fieldService, String jsonPropertyValue, Collection<QuantityBasedRule> criteriaList, Class<?> memberType) { boolean dirty = false; if (!StringUtils.isEmpty(jsonPropertyValue)) { DataWrapper dw = ruleFieldExtractionUtility.convertJsonToDataWrapper(jsonPropertyValue); if (dw != null && StringUtils.isEmpty(dw.getError())) { List<QuantityBasedRule> updatedRules = new ArrayList<QuantityBasedRule>(); for (DataDTO dto : dw.getData()) { if (dto.getId() != null && !CollectionUtils.isEmpty(criteriaList)) { checkId: { //updates are comprehensive, even data that was not changed //is submitted here //Update Existing Criteria for (QuantityBasedRule quantityBasedRule : criteriaList) { //make compatible with enterprise module Long sandBoxVersionId = sandBoxHelper.getSandBoxVersionId(em, quantityBasedRule.getClass(), dto.getId()); if (sandBoxVersionId == null) { sandBoxVersionId = dto.getId(); } if (sandBoxVersionId.equals(quantityBasedRule.getId())){ //don't update if the data has not changed if (!quantityBasedRule.getQuantity().equals(dto.getQuantity())) { quantityBasedRule.setQuantity(dto.getQuantity()); dirty = true; } try { String mvel = ruleFieldExtractionUtility.convertDTOToMvelString(translator, entityKey, dto, fieldService); if (!quantityBasedRule.getMatchRule().equals(mvel)) { quantityBasedRule.setMatchRule(mvel); dirty = true; } } catch (MVELTranslationException e) { throw new RuntimeException(e); } //make compatible with enterprise module em.flush(); updatedRules.add(quantityBasedRule); break checkId; } } throw new IllegalArgumentException("Unable to update the rule of type (" + memberType.getName() + ") because an update was requested for id (" + dto.getId() + "), which does not exist."); } } else { //Create a new Criteria QuantityBasedRule quantityBasedRule; try { quantityBasedRule = (QuantityBasedRule) memberType.newInstance(); quantityBasedRule.setQuantity(dto.getQuantity()); quantityBasedRule.setMatchRule(ruleFieldExtractionUtility.convertDTOToMvelString(translator, entityKey, dto, fieldService)); if (StringUtils.isEmpty(quantityBasedRule.getMatchRule()) && !StringUtils.isEmpty(dw.getRawMvel())) { quantityBasedRule.setMatchRule(dw.getRawMvel()); } } catch (Exception e) { throw new RuntimeException(e); } sandBoxHelper.setupSandBoxState(quantityBasedRule, em); em.persist(quantityBasedRule); criteriaList.add(quantityBasedRule); updatedRules.add(quantityBasedRule); dirty = true; } } //if an item was not included in the comprehensive submit from the client, we can assume that the //listing was deleted, so we remove it here. Iterator<QuantityBasedRule> itr = criteriaList.iterator(); while(itr.hasNext()) { checkForRemove: { QuantityBasedRule original = itr.next(); for (QuantityBasedRule quantityBasedRule : updatedRules) { if (String.valueOf(original.getId()).equals(String.valueOf(quantityBasedRule.getId()))) { break checkForRemove; } } sandBoxHelper.archiveObject(original, em); itr.remove(); dirty = true; } } } } return dirty; } @Override public int getOrder() { return FieldPersistenceProvider.RULE; } }
apache-2.0
darciopacifico/omr
vesionamento/msaf_validador-v1.0/ejb/src/main/java/com/msaf/validador/consultaonline/dao/exceptions/PersistenciaException.java
2687
package com.msaf.validador.consultaonline.dao.exceptions; /** * source: PersistenciaException.java * author: Ekler Paulino de Mattos * description: <DESCRIPTION> * version: First version * creation date: 2008-11-10 */ public class PersistenciaException extends Exception { /** * @param * @date 2008-11-12 * @author Ekler Paulino de Mattos * @exception * @roseuid 491853D000C5 */ public PersistenciaException() { super(); } /** * Constructs a new exception with the specified detail message. The * cause is not initialized, and may subsequently be initialized by * a call to {@link #initCause}. * * @param message the detail message. The detail message is saved for * later retrieval by the {@link #getMessage()} method. * @date 2008-11-12 * @author Ekler Paulino de Mattos */ public PersistenciaException(String message) { super(message); } /** * Constructs a new exception with the specified detail message and * cause. <p>Note that the detail message associated with * <code>cause</code> is <i>not</i> automatically incorporated in * this exception's detail message. * * @param message the detail message (which is saved for later retrieval * by the {@link #getMessage()} method). * @param cause the cause (which is saved for later retrieval by the * {@link #getCause()} method). (A <tt>null</tt> value is * permitted, and indicates that the cause is nonexistent or * unknown.) * @date 2008-11-12 * @author Ekler Paulino de Mattos */ public PersistenciaException(String message, Throwable cause) { super(message, cause); } /** * Constructs a new exception with the specified cause and a detail * message of <tt>(cause==null ? null : cause.toString())</tt> (which * typically contains the class and detail message of <tt>cause</tt>). * This constructor is useful for exceptions that are little more than * wrappers for other throwables (for example, {@link * java.security.PrivilegedActionException}). * * @param cause the cause (which is saved for later retrieval by the * {@link #getCause()} method). (A <tt>null</tt> value is * permitted, and indicates that the cause is nonexistent or * unknown.) * @date 2008-11-12 * @author Ekler Paulino de Mattos */ public PersistenciaException(Throwable cause) { super(cause); } }
apache-2.0
flofreud/aws-sdk-java
aws-java-sdk-iot/src/main/java/com/amazonaws/services/iot/model/transform/CloudwatchAlarmActionJsonUnmarshaller.java
3717
/* * Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights * Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.iot.model.transform; import java.util.Map; import java.util.Map.Entry; import java.math.*; import java.nio.ByteBuffer; import com.amazonaws.services.iot.model.*; import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*; import com.amazonaws.transform.*; import com.fasterxml.jackson.core.JsonToken; import static com.fasterxml.jackson.core.JsonToken.*; /** * CloudwatchAlarmAction JSON Unmarshaller */ public class CloudwatchAlarmActionJsonUnmarshaller implements Unmarshaller<CloudwatchAlarmAction, JsonUnmarshallerContext> { public CloudwatchAlarmAction unmarshall(JsonUnmarshallerContext context) throws Exception { CloudwatchAlarmAction cloudwatchAlarmAction = new CloudwatchAlarmAction(); int originalDepth = context.getCurrentDepth(); String currentParentElement = context.getCurrentParentElement(); int targetDepth = originalDepth + 1; JsonToken token = context.getCurrentToken(); if (token == null) token = context.nextToken(); if (token == VALUE_NULL) return null; while (true) { if (token == null) break; if (token == FIELD_NAME || token == START_OBJECT) { if (context.testExpression("roleArn", targetDepth)) { context.nextToken(); cloudwatchAlarmAction.setRoleArn(context.getUnmarshaller( String.class).unmarshall(context)); } if (context.testExpression("alarmName", targetDepth)) { context.nextToken(); cloudwatchAlarmAction.setAlarmName(context.getUnmarshaller( String.class).unmarshall(context)); } if (context.testExpression("stateReason", targetDepth)) { context.nextToken(); cloudwatchAlarmAction.setStateReason(context .getUnmarshaller(String.class).unmarshall(context)); } if (context.testExpression("stateValue", targetDepth)) { context.nextToken(); cloudwatchAlarmAction.setStateValue(context .getUnmarshaller(String.class).unmarshall(context)); } } else if (token == END_ARRAY || token == END_OBJECT) { if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals( currentParentElement)) { if (context.getCurrentDepth() <= originalDepth) break; } } token = context.nextToken(); } return cloudwatchAlarmAction; } private static CloudwatchAlarmActionJsonUnmarshaller instance; public static CloudwatchAlarmActionJsonUnmarshaller getInstance() { if (instance == null) instance = new CloudwatchAlarmActionJsonUnmarshaller(); return instance; } }
apache-2.0
ruebot/fcrepo4
fcrepo-http-commons/src/test/java/org/fcrepo/http/commons/exceptionhandlers/TombstoneExceptionMapperTest.java
2023
/* * Copyright 2015 DuraSpace, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.fcrepo.http.commons.exceptionhandlers; import org.fcrepo.kernel.api.exception.TombstoneException; import org.fcrepo.kernel.api.models.Tombstone; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import javax.ws.rs.core.Link; import javax.ws.rs.core.Response; import javax.ws.rs.ext.ExceptionMapper; import static javax.ws.rs.core.Response.Status.GONE; import static org.junit.Assert.assertEquals; import static org.mockito.MockitoAnnotations.initMocks; /** * @author cabeer */ public class TombstoneExceptionMapperTest { private ExceptionMapper<TombstoneException> testObj; @Mock public Tombstone mockTombstone; @Before public void setUp() { initMocks(this); testObj = new TombstoneExceptionMapper(); } @Test public void testUrilessException() { final Response response = testObj.toResponse(new TombstoneException(mockTombstone)); assertEquals(GONE.getStatusCode(), response.getStatus()); } @Test public void testExceptionWithUri() { final Response response = testObj.toResponse(new TombstoneException(mockTombstone, "some:uri")); assertEquals(GONE.getStatusCode(), response.getStatus()); final Link link = Link.valueOf(response.getHeaderString("Link")); assertEquals("some:uri", link.getUri().toString()); assertEquals("hasTombstone", link.getRel()); } }
apache-2.0
msebire/intellij-community
platform/external-system-api/src/com/intellij/openapi/externalSystem/importing/ImportSpecImpl.java
4042
/* * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.openapi.externalSystem.importing; import com.intellij.openapi.externalSystem.model.ProjectSystemId; import com.intellij.openapi.externalSystem.service.execution.ProgressExecutionMode; import com.intellij.openapi.externalSystem.service.project.ExternalProjectRefreshCallback; import com.intellij.openapi.project.Project; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /** * @author Vladislav.Soroka */ public class ImportSpecImpl implements ImportSpec { @NotNull private final Project myProject; @NotNull private final ProjectSystemId myExternalSystemId; @NotNull private ProgressExecutionMode myProgressExecutionMode; private boolean forceWhenUptodate; private boolean whenAutoImportEnabled; @Nullable private ExternalProjectRefreshCallback myCallback; private boolean isPreviewMode; private boolean createDirectoriesForEmptyContentRoots; private boolean isReportRefreshError; @Nullable private String myVmOptions; @Nullable private String myArguments; public ImportSpecImpl(@NotNull Project project, @NotNull ProjectSystemId id) { myProject = project; myExternalSystemId = id; myProgressExecutionMode = ProgressExecutionMode.MODAL_SYNC; } @NotNull @Override public Project getProject() { return myProject; } @NotNull @Override public ProjectSystemId getExternalSystemId() { return myExternalSystemId; } @NotNull @Override public ProgressExecutionMode getProgressExecutionMode() { return myProgressExecutionMode; } public void setProgressExecutionMode(@NotNull ProgressExecutionMode progressExecutionMode) { myProgressExecutionMode = progressExecutionMode; } @Override public boolean isForceWhenUptodate() { return forceWhenUptodate; } public void setForceWhenUptodate(boolean forceWhenUptodate) { this.forceWhenUptodate = forceWhenUptodate; } @Override public boolean whenAutoImportEnabled() { return whenAutoImportEnabled; } public void setWhenAutoImportEnabled(boolean whenAutoImportEnabled) { this.whenAutoImportEnabled = whenAutoImportEnabled; } public void setCallback(@Nullable ExternalProjectRefreshCallback callback) { myCallback = callback; } @Nullable @Override public ExternalProjectRefreshCallback getCallback() { return myCallback; } @Override public boolean isPreviewMode() { return isPreviewMode; } public void setPreviewMode(boolean isPreviewMode) { this.isPreviewMode = isPreviewMode; } @Override public boolean shouldCreateDirectoriesForEmptyContentRoots() { return createDirectoriesForEmptyContentRoots; } public void setCreateDirectoriesForEmptyContentRoots(boolean createDirectoriesForEmptyContentRoots) { this.createDirectoriesForEmptyContentRoots = createDirectoriesForEmptyContentRoots; } @Override public boolean isReportRefreshError() { return isReportRefreshError; } public void setReportRefreshError(boolean isReportRefreshError) { this.isReportRefreshError = isReportRefreshError; } @Nullable @Override public String getVmOptions() { return myVmOptions; } public void setVmOptions(@Nullable String vmOptions) { myVmOptions = vmOptions; } @Nullable @Override public String getArguments() { return myArguments; } public void setArguments(@Nullable String arguments) { myArguments = arguments; } }
apache-2.0
gdgjodhpur/gdgapp
app/src/main/java/org/gdg/frisbee/android/api/model/HomeGdgRequest.java
1044
/* * Copyright 2013 The GDG Frisbee Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gdg.frisbee.android.api.model; /** * Created with IntelliJ IDEA. * User: maui * Date: 26.08.13 * Time: 01:46 * To change this template use File | Settings | File Templates. */ public class HomeGdgRequest { private String homeGdg; public String getHomeGdg() { return homeGdg; } public void setHomeGdg(String homeGdg) { this.homeGdg = homeGdg; } }
apache-2.0
AromaTech/banana-java-client
src/main/java/tech/aroma/client/exceptions/AromaOperationFailedException.java
1157
/* * Copyright 2018 RedRoma, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * You may not use this file except in compliance with the License. * * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package tech.aroma.client.exceptions; /** * Thrown when an Operation could not be completed. * * @author SirWellington */ public class AromaOperationFailedException extends AromaException { public AromaOperationFailedException() { } public AromaOperationFailedException(String message) { super(message); } public AromaOperationFailedException(String message, Throwable cause) { super(message, cause); } public AromaOperationFailedException(Throwable cause) { super(cause); } }
apache-2.0
VladiMihaylenko/omim
android/src/com/mapswithme/maps/editor/HoursMinutesPickerFragment.java
6904
package com.mapswithme.maps.editor; import android.annotation.SuppressLint; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.content.res.ColorStateList; import android.os.Bundle; import android.support.annotation.IntRange; import android.support.annotation.NonNull; import android.support.design.widget.TabLayout; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v7.app.AlertDialog; import android.text.format.DateFormat; import android.view.LayoutInflater; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.TimePicker; import com.mapswithme.maps.R; import com.mapswithme.maps.base.BaseMwmDialogFragment; import com.mapswithme.maps.editor.data.HoursMinutes; import com.mapswithme.util.ThemeUtils; public class HoursMinutesPickerFragment extends BaseMwmDialogFragment { private static final String EXTRA_FROM = "HoursMinutesFrom"; private static final String EXTRA_TO = "HoursMinutesTo"; private static final String EXTRA_SELECT_FIRST = "SelectedTab"; private static final String EXTRA_ID = "Id"; public static final int TAB_FROM = 0; public static final int TAB_TO = 1; private HoursMinutes mFrom; private HoursMinutes mTo; private TimePicker mPicker; private View mPickerHoursLabel; @IntRange(from = 0, to = 1) private int mSelectedTab; private TabLayout mTabs; private int mId; private Button mOkButton; public interface OnPickListener { void onHoursMinutesPicked(HoursMinutes from, HoursMinutes to, int id); } public static void pick(Context context, FragmentManager manager, @NonNull HoursMinutes from, @NonNull HoursMinutes to, @IntRange(from = 0, to = 1) int selectedPosition, int id) { final Bundle args = new Bundle(); args.putParcelable(EXTRA_FROM, from); args.putParcelable(EXTRA_TO, to); args.putInt(EXTRA_SELECT_FIRST, selectedPosition); args.putInt(EXTRA_ID, id); final HoursMinutesPickerFragment fragment = (HoursMinutesPickerFragment) Fragment.instantiate(context, HoursMinutesPickerFragment.class.getName(), args); fragment.show(manager, null); } @NonNull @Override public Dialog onCreateDialog(Bundle savedInstanceState) { readArgs(); final View root = createView(); //noinspection ConstantConditions mTabs.getTabAt(mSelectedTab).select(); final int theme = ThemeUtils.isNightTheme() ? R.style.MwmMain_DialogFragment_TimePicker_Night : R.style.MwmMain_DialogFragment_TimePicker; final AlertDialog dialog = new AlertDialog.Builder(getActivity(), theme) .setView(root) .setNegativeButton(android.R.string.cancel, null) .setPositiveButton(android.R.string.ok, null) .setCancelable(true) .create(); dialog.setOnShowListener(new DialogInterface.OnShowListener() { @Override public void onShow(DialogInterface dialogInterface) { mOkButton = dialog.getButton(AlertDialog.BUTTON_POSITIVE); mOkButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (mSelectedTab == TAB_FROM) { //noinspection ConstantConditions mTabs.getTabAt(TAB_TO).select(); return; } saveHoursMinutes(); dismiss(); if (getParentFragment() instanceof OnPickListener) ((OnPickListener) getParentFragment()).onHoursMinutesPicked(mFrom, mTo, mId); } }); refreshPicker(); } }); return dialog; } private void readArgs() { final Bundle args = getArguments(); mFrom = args.getParcelable(EXTRA_FROM); mTo = args.getParcelable(EXTRA_TO); mSelectedTab = args.getInt(EXTRA_SELECT_FIRST); mId = args.getInt(EXTRA_ID); } private View createView() { final LayoutInflater inflater = LayoutInflater.from(getActivity()); @SuppressLint("InflateParams") final View root = inflater.inflate(R.layout.fragment_timetable_picker, null); mPicker = (TimePicker) root.findViewById(R.id.picker); mPicker.setIs24HourView(DateFormat.is24HourFormat(getActivity())); int id = getResources().getIdentifier("hours", "id", "android"); if (id != 0) { mPickerHoursLabel = mPicker.findViewById(id); if (!(mPickerHoursLabel instanceof TextView)) mPickerHoursLabel = null; } mTabs = (TabLayout) root.findViewById(R.id.tabs); TextView tabView = (TextView) inflater.inflate(R.layout.tab_timepicker, mTabs, false); // TODO @yunik add translations tabView.setText("From"); final ColorStateList textColor = getResources().getColorStateList(ThemeUtils.isNightTheme() ? R.color.accent_color_selector_night : R.color.accent_color_selector); tabView.setTextColor(textColor); mTabs.addTab(mTabs.newTab().setCustomView(tabView), true); tabView = (TextView) inflater.inflate(R.layout.tab_timepicker, mTabs, false); tabView.setText("To"); tabView.setTextColor(textColor); mTabs.addTab(mTabs.newTab().setCustomView(tabView), true); mTabs.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() { @Override public void onTabSelected(TabLayout.Tab tab) { if (!isInit()) return; saveHoursMinutes(); mSelectedTab = tab.getPosition(); refreshPicker(); if (mPickerHoursLabel != null) mPickerHoursLabel.performClick(); } @Override public void onTabUnselected(TabLayout.Tab tab) {} @Override public void onTabReselected(TabLayout.Tab tab) {} }); return root; } private void saveHoursMinutes() { final HoursMinutes hoursMinutes = new HoursMinutes(mPicker.getCurrentHour(), mPicker.getCurrentMinute()); if (mSelectedTab == TAB_FROM) mFrom = hoursMinutes; else mTo = hoursMinutes; } private boolean isInit() { return mOkButton != null && mPicker != null; } private void refreshPicker() { if (!isInit()) return; HoursMinutes hoursMinutes; int okBtnRes; if (mSelectedTab == TAB_FROM) { hoursMinutes = mFrom; okBtnRes = R.string.whats_new_next_button; } else { hoursMinutes = mTo; okBtnRes = R.string.ok; } mPicker.setCurrentMinute((int) hoursMinutes.minutes); mPicker.setCurrentHour((int) hoursMinutes.hours); mOkButton.setText(okBtnRes); } }
apache-2.0