repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15 values |
|---|---|---|---|---|
Ztiany/AndroidBase | lib_network/src/main/java/com/android/sdk/net/provider/HttpConfig.java | 628 | package com.android.sdk.net.provider;
import io.reactivex.schedulers.Schedulers;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
/**
* @author Ztiany
* Email: ztiany3@gmail.com
* Date : 2018-11-08 16:42
*/
public interface HttpConfig {
void configHttp(OkHttpClient.Builder builder);
/**
* default config is {@link retrofit2.converter.gson.GsonConverterFactory}、{@link retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory} with {@link Schedulers#io()}
*
* @return if true, default config do nothing.
*/
boolean configRetrofit(Retrofit.Builder builder);
String baseUrl();
}
| apache-2.0 |
jsmadja/clients | hudson/src/main/generated/net/awired/visuwall/hudsonclient/generated/hudson/mavenmoduleset/HudsonModelBallColor.java | 3304 | /**
* Copyright (C) 2010 Julien SMADJA <julien dot smadja at gmail dot com> - Arnaud LEMAIRE <alemaire at norad dot fr>
*
* 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.
*/
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2011.02.21 at 12:18:20 PM CET
//
package net.awired.visuwall.hudsonclient.generated.hudson.mavenmoduleset;
import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlEnumValue;
import javax.xml.bind.annotation.XmlType;
/**
* <p>
* Java class for hudson.model.BallColor.
*
* <p>
* The following schema fragment specifies the expected content contained within this class.
* <p>
*
* <pre>
* <simpleType name="hudson.model.BallColor">
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <enumeration value="red"/>
* <enumeration value="red_anime"/>
* <enumeration value="yellow"/>
* <enumeration value="yellow_anime"/>
* <enumeration value="blue"/>
* <enumeration value="blue_anime"/>
* <enumeration value="grey"/>
* <enumeration value="grey_anime"/>
* <enumeration value="disabled"/>
* <enumeration value="disabled_anime"/>
* <enumeration value="aborted"/>
* <enumeration value="aborted_anime"/>
* </restriction>
* </simpleType>
* </pre>
*
*/
@XmlType(name = "hudson.model.BallColor")
@XmlEnum
public enum HudsonModelBallColor {
@XmlEnumValue("red")
RED("red"), @XmlEnumValue("red_anime")
RED_ANIME("red_anime"), @XmlEnumValue("yellow")
YELLOW("yellow"), @XmlEnumValue("yellow_anime")
YELLOW_ANIME("yellow_anime"), @XmlEnumValue("blue")
BLUE("blue"), @XmlEnumValue("blue_anime")
BLUE_ANIME("blue_anime"), @XmlEnumValue("grey")
GREY("grey"), @XmlEnumValue("grey_anime")
GREY_ANIME("grey_anime"), @XmlEnumValue("disabled")
DISABLED("disabled"), @XmlEnumValue("disabled_anime")
DISABLED_ANIME("disabled_anime"), @XmlEnumValue("aborted")
ABORTED("aborted"), @XmlEnumValue("aborted_anime")
ABORTED_ANIME("aborted_anime");
private final String value;
HudsonModelBallColor(String v) {
value = v;
}
public String value() {
return value;
}
public static HudsonModelBallColor fromValue(String v) {
for (HudsonModelBallColor c : HudsonModelBallColor.values()) {
if (c.value.equals(v)) {
return c;
}
}
throw new IllegalArgumentException(v);
}
}
| apache-2.0 |
nince-wyj/jahhan | frameworkx/dubbo-remoting/dubbo-remoting-grizzly/src/main/java/com/alibaba/dubbo/remoting/transport/grizzly/GrizzlyHandler.java | 4136 | /*
* Copyright 1999-2011 Alibaba Group.
*
* 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.alibaba.dubbo.remoting.transport.grizzly;
import java.io.IOException;
import org.glassfish.grizzly.Connection;
import org.glassfish.grizzly.filterchain.BaseFilter;
import org.glassfish.grizzly.filterchain.FilterChainContext;
import org.glassfish.grizzly.filterchain.NextAction;
import com.alibaba.dubbo.common.URL;
import com.alibaba.dubbo.remoting.RemotingException;
import lombok.extern.slf4j.Slf4j;
import net.jahhan.common.extension.utils.StringUtils;
import net.jahhan.spi.ChannelHandler;
/**
* GrizzlyHandler
*
* @author william.liangf
*/
@Slf4j
public class GrizzlyHandler extends BaseFilter {
private final URL url;
private final ChannelHandler handler;
public GrizzlyHandler(URL url, ChannelHandler handler){
this.url = url;
this.handler = handler;
}
@Override
public NextAction handleConnect(FilterChainContext ctx) throws IOException {
Connection<?> connection = ctx.getConnection();
GrizzlyChannel channel = GrizzlyChannel.getOrAddChannel(connection, url, handler);
try {
handler.connected(channel);
} catch (RemotingException e) {
throw new IOException(StringUtils.toString(e));
} finally {
GrizzlyChannel.removeChannelIfDisconnectd(connection);
}
return ctx.getInvokeAction();
}
@Override
public NextAction handleClose(FilterChainContext ctx) throws IOException {
Connection<?> connection = ctx.getConnection();
GrizzlyChannel channel = GrizzlyChannel.getOrAddChannel(connection, url, handler);
try {
handler.disconnected(channel);
} catch (RemotingException e) {
throw new IOException(StringUtils.toString(e));
} finally {
GrizzlyChannel.removeChannelIfDisconnectd(connection);
}
return ctx.getInvokeAction();
}
@Override
public NextAction handleRead(FilterChainContext ctx) throws IOException {
Connection<?> connection = ctx.getConnection();
GrizzlyChannel channel = GrizzlyChannel.getOrAddChannel(connection, url, handler);
try {
handler.received(channel, ctx.getMessage());
} catch (RemotingException e) {
throw new IOException(StringUtils.toString(e));
} finally {
GrizzlyChannel.removeChannelIfDisconnectd(connection);
}
return ctx.getInvokeAction();
}
@Override
public NextAction handleWrite(FilterChainContext ctx) throws IOException {
Connection<?> connection = ctx.getConnection();
GrizzlyChannel channel = GrizzlyChannel.getOrAddChannel(connection, url, handler);
try {
handler.sent(channel, ctx.getMessage());
} catch (RemotingException e) {
throw new IOException(StringUtils.toString(e));
} finally {
GrizzlyChannel.removeChannelIfDisconnectd(connection);
}
return ctx.getInvokeAction();
}
@Override
public void exceptionOccurred(FilterChainContext ctx, Throwable error) {
Connection<?> connection = ctx.getConnection();
GrizzlyChannel channel = GrizzlyChannel.getOrAddChannel(connection, url, handler);
try {
handler.caught(channel, error);
} catch (RemotingException e) {
log.error("RemotingException on channel " + channel, e);
} finally {
GrizzlyChannel.removeChannelIfDisconnectd(connection);
}
}
} | apache-2.0 |
bhargav1/Android-M-Permission | app/src/main/java/permissiondemo/ContactPermissionFragment.java | 2715 | package permissiondemo;
import android.Manifest;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.domo.permissiondemo.R;
import permission.utility.PermissionUtil;
/**
* Created by bhargavsuthar on 9/22/15.
*/
public class ContactPermissionFragment extends PermissionFragment {
private final static int REQUEST_GROUP_PERMISSION = 234;
public static ContactPermissionFragment newInstance(){
return new ContactPermissionFragment();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_demo, container, false);
boolean isPermissionGranted = PermissionUtil.hasSelfPermission(getActivity(), Manifest.permission.READ_CONTACTS);
if(!isPermissionGranted){
if(!shouldShowRequestPermissionRationale(Manifest.permission.READ_CONTACTS)){
PermissionUtil.showMessageOKCancel(getActivity(), "You need to allow access to Contacts", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if(which == DialogInterface.BUTTON_POSITIVE) {
//Todo on Ok button click
requestPermissions(new String[]{Manifest.permission.READ_CONTACTS}, REQUEST_GROUP_PERMISSION);
return;
}
}
});
}
requestPermissions(new String[]{Manifest.permission.READ_CONTACTS}, REQUEST_GROUP_PERMISSION);
} else {
//Todo with result
((TextView) rootView.findViewById(R.id.section_label)).setText("Contact permission Granted already !!!!");
}
return rootView;
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case REQUEST_GROUP_PERMISSION:
if(grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//Todo with first granted result
((TextView) getActivity().findViewById(R.id.section_label)).setText("Now Contact permission grandted !!!");
}
break;
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
break;
}
}
}
| apache-2.0 |
jentfoo/aws-sdk-java | aws-java-sdk-workdocs/src/main/java/com/amazonaws/services/workdocs/model/transform/UserMetadataMarshaller.java | 3123 | /*
* Copyright 2014-2019 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.workdocs.model.transform;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.services.workdocs.model.*;
import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;
/**
* UserMetadataMarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class UserMetadataMarshaller {
private static final MarshallingInfo<String> ID_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
.marshallLocationName("Id").build();
private static final MarshallingInfo<String> USERNAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
.marshallLocationName("Username").build();
private static final MarshallingInfo<String> GIVENNAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
.marshallLocationName("GivenName").build();
private static final MarshallingInfo<String> SURNAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
.marshallLocationName("Surname").build();
private static final MarshallingInfo<String> EMAILADDRESS_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("EmailAddress").build();
private static final UserMetadataMarshaller instance = new UserMetadataMarshaller();
public static UserMetadataMarshaller getInstance() {
return instance;
}
/**
* Marshall the given parameter object.
*/
public void marshall(UserMetadata userMetadata, ProtocolMarshaller protocolMarshaller) {
if (userMetadata == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(userMetadata.getId(), ID_BINDING);
protocolMarshaller.marshall(userMetadata.getUsername(), USERNAME_BINDING);
protocolMarshaller.marshall(userMetadata.getGivenName(), GIVENNAME_BINDING);
protocolMarshaller.marshall(userMetadata.getSurname(), SURNAME_BINDING);
protocolMarshaller.marshall(userMetadata.getEmailAddress(), EMAILADDRESS_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
}
}
| apache-2.0 |
Groostav/CMPT880-term-project | intruder/test/tests/benchmarks/instrumented/java15/swing/text/html/HTML.java | 27593 | /*
* Copyright (c) 1998, 2008, Oracle and/or its affiliates. All rights reserved.
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*/
package benchmarks.instrumented.java15.swing.text.html;
import java.io.*;
import java.util.Hashtable;
import javax.swing.text.AttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyleContext;
/**
* Constants used in the <code>HTMLDocument</code>. These
* are basically tag and attribute definitions.
*
* @author Timothy Prinzing
* @author Sunita Mani
*
*/
public class HTML {
/**
* Typesafe enumeration for an HTML tag. Although the
* set of HTML tags is a closed set, we have left the
* set open so that people can add their own tag types
* to their custom parser and still communicate to the
* reader.
*/
public static class Tag {
/** @since 1.3 */
public Tag() {}
/**
* Creates a new <code>Tag</code> with the specified <code>id</code>,
* and with <code>causesBreak</code> and <code>isBlock</code>
* set to <code>false</code>.
*
* @param id the id of the new tag
*/
protected Tag(String id) {
this(id, false, false);
}
/**
* Creates a new <code>Tag</code> with the specified <code>id</code>;
* <code>causesBreak</code> and <code>isBlock</code> are defined
* by the user.
*
* @param id the id of the new tag
* @param causesBreak <code>true</code> if this tag
* causes a break to the flow of data
* @param isBlock <code>true</code> if the tag is used
* to add structure to a document
*/
protected Tag(String id, boolean causesBreak, boolean isBlock) {
name = id;
this.breakTag = causesBreak;
this.blockTag = isBlock;
}
/**
* Returns <code>true</code> if this tag is a block
* tag, which is a tag used to add structure to a
* document.
*
* @return <code>true</code> if this tag is a block
* tag, otherwise returns <code>false</code>
*/
public boolean isBlock() {
return blockTag;
}
/**
* Returns <code>true</code> if this tag causes a
* line break to the flow of data, otherwise returns
* <code>false</code>.
*
* @return <code>true</code> if this tag causes a
* line break to the flow of data, otherwise returns
* <code>false</code>
*/
public boolean breaksFlow() {
return breakTag;
}
/**
* Returns <code>true</code> if this tag is pre-formatted,
* which is true if the tag is either <code>PRE</code> or
* <code>TEXTAREA</code>.
*
* @return <code>true</code> if this tag is pre-formatted,
* otherwise returns <code>false</code>
*/
public boolean isPreformatted() {
return (this == PRE || this == TEXTAREA);
}
/**
* Returns the string representation of the
* tag.
*
* @return the <code>String</code> representation of the tag
*/
public String toString() {
return name;
}
/**
* Returns <code>true</code> if this tag is considered to be a paragraph
* in the internal HTML model. <code>false</code> - otherwise.
*
* @return <code>true</code> if this tag is considered to be a paragraph
* in the internal HTML model. <code>false</code> - otherwise.
* @see HTMLDocument.HTMLReader.ParagraphAction
*/
boolean isParagraph() {
return (
this == P
|| this == IMPLIED
|| this == DT
|| this == H1
|| this == H2
|| this == H3
|| this == H4
|| this == H5
|| this == H6
);
}
boolean blockTag;
boolean breakTag;
String name;
boolean unknown;
// --- Tag Names -----------------------------------
public static final Tag A = new Tag("a");
public static final Tag ADDRESS = new Tag("address");
public static final Tag APPLET = new Tag("applet");
public static final Tag AREA = new Tag("area");
public static final Tag B = new Tag("b");
public static final Tag BASE = new Tag("base");
public static final Tag BASEFONT = new Tag("basefont");
public static final Tag BIG = new Tag("big");
public static final Tag BLOCKQUOTE = new Tag("blockquote", true, true);
public static final Tag BODY = new Tag("body", true, true);
public static final Tag BR = new Tag("br", true, false);
public static final Tag CAPTION = new Tag("caption");
public static final Tag CENTER = new Tag("center", true, false);
public static final Tag CITE = new Tag("cite");
public static final Tag CODE = new Tag("code");
public static final Tag DD = new Tag("dd", true, true);
public static final Tag DFN = new Tag("dfn");
public static final Tag DIR = new Tag("dir", true, true);
public static final Tag DIV = new Tag("div", true, true);
public static final Tag DL = new Tag("dl", true, true);
public static final Tag DT = new Tag("dt", true, true);
public static final Tag EM = new Tag("em");
public static final Tag FONT = new Tag("font");
public static final Tag FORM = new Tag("form", true, false);
public static final Tag FRAME = new Tag("frame");
public static final Tag FRAMESET = new Tag("frameset");
public static final Tag H1 = new Tag("h1", true, true);
public static final Tag H2 = new Tag("h2", true, true);
public static final Tag H3 = new Tag("h3", true, true);
public static final Tag H4 = new Tag("h4", true, true);
public static final Tag H5 = new Tag("h5", true, true);
public static final Tag H6 = new Tag("h6", true, true);
public static final Tag HEAD = new Tag("head", true, true);
public static final Tag HR = new Tag("hr", true, false);
public static final Tag HTML = new Tag("html", true, false);
public static final Tag I = new Tag("i");
public static final Tag IMG = new Tag("img");
public static final Tag INPUT = new Tag("input");
public static final Tag ISINDEX = new Tag("isindex", true, false);
public static final Tag KBD = new Tag("kbd");
public static final Tag LI = new Tag("li", true, true);
public static final Tag LINK = new Tag("link");
public static final Tag MAP = new Tag("map");
public static final Tag MENU = new Tag("menu", true, true);
public static final Tag META = new Tag("meta");
/*public*/ static final Tag NOBR = new Tag("nobr");
public static final Tag NOFRAMES = new Tag("noframes", true, true);
public static final Tag OBJECT = new Tag("object");
public static final Tag OL = new Tag("ol", true, true);
public static final Tag OPTION = new Tag("option");
public static final Tag P = new Tag("p", true, true);
public static final Tag PARAM = new Tag("param");
public static final Tag PRE = new Tag("pre", true, true);
public static final Tag SAMP = new Tag("samp");
public static final Tag SCRIPT = new Tag("script");
public static final Tag SELECT = new Tag("select");
public static final Tag SMALL = new Tag("small");
public static final Tag SPAN = new Tag("span");
public static final Tag STRIKE = new Tag("strike");
public static final Tag S = new Tag("s");
public static final Tag STRONG = new Tag("strong");
public static final Tag STYLE = new Tag("style");
public static final Tag SUB = new Tag("sub");
public static final Tag SUP = new Tag("sup");
public static final Tag TABLE = new Tag("table", false, true);
public static final Tag TD = new Tag("td", true, true);
public static final Tag TEXTAREA = new Tag("textarea");
public static final Tag TH = new Tag("th", true, true);
public static final Tag TITLE = new Tag("title", true, true);
public static final Tag TR = new Tag("tr", false, true);
public static final Tag TT = new Tag("tt");
public static final Tag U = new Tag("u");
public static final Tag UL = new Tag("ul", true, true);
public static final Tag VAR = new Tag("var");
/**
* All text content must be in a paragraph element.
* If a paragraph didn't exist when content was
* encountered, a paragraph is manufactured.
* <p>
* This is a tag synthesized by the HTML reader.
* Since elements are identified by their tag type,
* we create a some fake tag types to mark the elements
* that were manufactured.
*/
public static final Tag IMPLIED = new Tag("p-implied");
/**
* All text content is labeled with this tag.
* <p>
* This is a tag synthesized by the HTML reader.
* Since elements are identified by their tag type,
* we create a some fake tag types to mark the elements
* that were manufactured.
*/
public static final Tag CONTENT = new Tag("content");
/**
* All comments are labeled with this tag.
* <p>
* This is a tag synthesized by the HTML reader.
* Since elements are identified by their tag type,
* we create a some fake tag types to mark the elements
* that were manufactured.
*/
public static final Tag COMMENT = new Tag("comment");
static final Tag allTags[] = {
A, ADDRESS, APPLET, AREA, B, BASE, BASEFONT, BIG,
BLOCKQUOTE, BODY, BR, CAPTION, CENTER, CITE, CODE,
DD, DFN, DIR, DIV, DL, DT, EM, FONT, FORM, FRAME,
FRAMESET, H1, H2, H3, H4, H5, H6, HEAD, HR, HTML,
I, IMG, INPUT, ISINDEX, KBD, LI, LINK, MAP, MENU,
META, NOBR, NOFRAMES, OBJECT, OL, OPTION, P, PARAM,
PRE, SAMP, SCRIPT, SELECT, SMALL, SPAN, STRIKE, S,
STRONG, STYLE, SUB, SUP, TABLE, TD, TEXTAREA,
TH, TITLE, TR, TT, U, UL, VAR
};
static {
// Force HTMLs static initialize to be loaded.
getTag("html");
}
}
// There is no unique instance of UnknownTag, so we allow it to be
// Serializable.
public static class UnknownTag extends Tag implements Serializable {
/**
* Creates a new <code>UnknownTag</code> with the specified
* <code>id</code>.
* @param id the id of the new tag
*/
public UnknownTag(String id) {
super(id);
}
/**
* Returns the hash code which corresponds to the string
* for this tag.
*/
public int hashCode() {
return toString().hashCode();
}
/**
* Compares this object to the specifed object.
* The result is <code>true</code> if and only if the argument is not
* <code>null</code> and is an <code>UnknownTag</code> object
* with the same name.
*
* @param obj the object to compare this tag with
* @return <code>true</code> if the objects are equal;
* <code>false</code> otherwise
*/
public boolean equals(Object obj) {
if (obj instanceof UnknownTag) {
return toString().equals(obj.toString());
}
return false;
}
private void writeObject(java.io.ObjectOutputStream s)
throws IOException {
s.defaultWriteObject();
s.writeBoolean(blockTag);
s.writeBoolean(breakTag);
s.writeBoolean(unknown);
s.writeObject(name);
}
private void readObject(ObjectInputStream s)
throws ClassNotFoundException, IOException {
s.defaultReadObject();
blockTag = s.readBoolean();
breakTag = s.readBoolean();
unknown = s.readBoolean();
name = (String)s.readObject();
}
}
/**
* Typesafe enumeration representing an HTML
* attribute.
*/
public static final class Attribute {
/**
* Creates a new <code>Attribute</code> with the specified
* <code>id</code>.
*
* @param id the id of the new <code>Attribute</code>
*/
Attribute(String id) {
name = id;
}
/**
* Returns the string representation of this attribute.
* @return the string representation of this attribute
*/
public String toString() {
return name;
}
private String name;
public static final Attribute SIZE = new Attribute("size");
public static final Attribute COLOR = new Attribute("color");
public static final Attribute CLEAR = new Attribute("clear");
public static final Attribute BACKGROUND = new Attribute("background");
public static final Attribute BGCOLOR = new Attribute("bgcolor");
public static final Attribute TEXT = new Attribute("text");
public static final Attribute LINK = new Attribute("link");
public static final Attribute VLINK = new Attribute("vlink");
public static final Attribute ALINK = new Attribute("alink");
public static final Attribute WIDTH = new Attribute("width");
public static final Attribute HEIGHT = new Attribute("height");
public static final Attribute ALIGN = new Attribute("align");
public static final Attribute NAME = new Attribute("name");
public static final Attribute HREF = new Attribute("href");
public static final Attribute REL = new Attribute("rel");
public static final Attribute REV = new Attribute("rev");
public static final Attribute TITLE = new Attribute("title");
public static final Attribute TARGET = new Attribute("target");
public static final Attribute SHAPE = new Attribute("shape");
public static final Attribute COORDS = new Attribute("coords");
public static final Attribute ISMAP = new Attribute("ismap");
public static final Attribute NOHREF = new Attribute("nohref");
public static final Attribute ALT = new Attribute("alt");
public static final Attribute ID = new Attribute("id");
public static final Attribute SRC = new Attribute("src");
public static final Attribute HSPACE = new Attribute("hspace");
public static final Attribute VSPACE = new Attribute("vspace");
public static final Attribute USEMAP = new Attribute("usemap");
public static final Attribute LOWSRC = new Attribute("lowsrc");
public static final Attribute CODEBASE = new Attribute("codebase");
public static final Attribute CODE = new Attribute("code");
public static final Attribute ARCHIVE = new Attribute("archive");
public static final Attribute VALUE = new Attribute("value");
public static final Attribute VALUETYPE = new Attribute("valuetype");
public static final Attribute TYPE = new Attribute("type");
public static final Attribute CLASS = new Attribute("class");
public static final Attribute STYLE = new Attribute("style");
public static final Attribute LANG = new Attribute("lang");
public static final Attribute FACE = new Attribute("face");
public static final Attribute DIR = new Attribute("dir");
public static final Attribute DECLARE = new Attribute("declare");
public static final Attribute CLASSID = new Attribute("classid");
public static final Attribute DATA = new Attribute("data");
public static final Attribute CODETYPE = new Attribute("codetype");
public static final Attribute STANDBY = new Attribute("standby");
public static final Attribute BORDER = new Attribute("border");
public static final Attribute SHAPES = new Attribute("shapes");
public static final Attribute NOSHADE = new Attribute("noshade");
public static final Attribute COMPACT = new Attribute("compact");
public static final Attribute START = new Attribute("start");
public static final Attribute ACTION = new Attribute("action");
public static final Attribute METHOD = new Attribute("method");
public static final Attribute ENCTYPE = new Attribute("enctype");
public static final Attribute CHECKED = new Attribute("checked");
public static final Attribute MAXLENGTH = new Attribute("maxlength");
public static final Attribute MULTIPLE = new Attribute("multiple");
public static final Attribute SELECTED = new Attribute("selected");
public static final Attribute ROWS = new Attribute("rows");
public static final Attribute COLS = new Attribute("cols");
public static final Attribute DUMMY = new Attribute("dummy");
public static final Attribute CELLSPACING = new Attribute("cellspacing");
public static final Attribute CELLPADDING = new Attribute("cellpadding");
public static final Attribute VALIGN = new Attribute("valign");
public static final Attribute HALIGN = new Attribute("halign");
public static final Attribute NOWRAP = new Attribute("nowrap");
public static final Attribute ROWSPAN = new Attribute("rowspan");
public static final Attribute COLSPAN = new Attribute("colspan");
public static final Attribute PROMPT = new Attribute("prompt");
public static final Attribute HTTPEQUIV = new Attribute("http-equiv");
public static final Attribute CONTENT = new Attribute("content");
public static final Attribute LANGUAGE = new Attribute("language");
public static final Attribute VERSION = new Attribute("version");
public static final Attribute N = new Attribute("n");
public static final Attribute FRAMEBORDER = new Attribute("frameborder");
public static final Attribute MARGINWIDTH = new Attribute("marginwidth");
public static final Attribute MARGINHEIGHT = new Attribute("marginheight");
public static final Attribute SCROLLING = new Attribute("scrolling");
public static final Attribute NORESIZE = new Attribute("noresize");
public static final Attribute ENDTAG = new Attribute("endtag");
public static final Attribute COMMENT = new Attribute("comment");
static final Attribute MEDIA = new Attribute("media");
static final Attribute allAttributes[] = {
FACE,
COMMENT,
SIZE,
COLOR,
CLEAR,
BACKGROUND,
BGCOLOR,
TEXT,
LINK,
VLINK,
ALINK,
WIDTH,
HEIGHT,
ALIGN,
NAME,
HREF,
REL,
REV,
TITLE,
TARGET,
SHAPE,
COORDS,
ISMAP,
NOHREF,
ALT,
ID,
SRC,
HSPACE,
VSPACE,
USEMAP,
LOWSRC,
CODEBASE,
CODE,
ARCHIVE,
VALUE,
VALUETYPE,
TYPE,
CLASS,
STYLE,
LANG,
DIR,
DECLARE,
CLASSID,
DATA,
CODETYPE,
STANDBY,
BORDER,
SHAPES,
NOSHADE,
COMPACT,
START,
ACTION,
METHOD,
ENCTYPE,
CHECKED,
MAXLENGTH,
MULTIPLE,
SELECTED,
ROWS,
COLS,
DUMMY,
CELLSPACING,
CELLPADDING,
VALIGN,
HALIGN,
NOWRAP,
ROWSPAN,
COLSPAN,
PROMPT,
HTTPEQUIV,
CONTENT,
LANGUAGE,
VERSION,
N,
FRAMEBORDER,
MARGINWIDTH,
MARGINHEIGHT,
SCROLLING,
NORESIZE,
MEDIA,
ENDTAG
};
}
// The secret to 73, is that, given that the Hashtable contents
// never change once the static initialization happens, the initial size
// that the hashtable grew to was determined, and then that very size
// is used.
//
private static final Hashtable<String, Tag> tagHashtable = new Hashtable<String, Tag>(73);
/** Maps from StyleConstant key to HTML.Tag. */
private static final Hashtable<Object, Tag> scMapping = new Hashtable<Object, Tag>(8);
static {
for (int i = 0; i < Tag.allTags.length; i++ ) {
tagHashtable.put(Tag.allTags[i].toString(), Tag.allTags[i]);
StyleContext.registerStaticAttributeKey(Tag.allTags[i]);
}
StyleContext.registerStaticAttributeKey(Tag.IMPLIED);
StyleContext.registerStaticAttributeKey(Tag.CONTENT);
StyleContext.registerStaticAttributeKey(Tag.COMMENT);
for (int i = 0; i < Attribute.allAttributes.length; i++) {
StyleContext.registerStaticAttributeKey(Attribute.
allAttributes[i]);
}
StyleContext.registerStaticAttributeKey(HTML.NULL_ATTRIBUTE_VALUE);
scMapping.put(StyleConstants.Bold, Tag.B);
scMapping.put(StyleConstants.Italic, Tag.I);
scMapping.put(StyleConstants.Underline, Tag.U);
scMapping.put(StyleConstants.StrikeThrough, Tag.STRIKE);
scMapping.put(StyleConstants.Superscript, Tag.SUP);
scMapping.put(StyleConstants.Subscript, Tag.SUB);
scMapping.put(StyleConstants.FontFamily, Tag.FONT);
scMapping.put(StyleConstants.FontSize, Tag.FONT);
}
/**
* Returns the set of actual HTML tags that
* are recognized by the default HTML reader.
* This set does not include tags that are
* manufactured by the reader.
*/
public static Tag[] getAllTags() {
Tag[] tags = new Tag[Tag.allTags.length];
System.arraycopy(Tag.allTags, 0, tags, 0, Tag.allTags.length);
return tags;
}
/**
* Fetches a tag constant for a well-known tag name (i.e. one of
* the tags in the set {A, ADDRESS, APPLET, AREA, B,
* BASE, BASEFONT, BIG,
* BLOCKQUOTE, BODY, BR, CAPTION, CENTER, CITE, CODE,
* DD, DFN, DIR, DIV, DL, DT, EM, FONT, FORM, FRAME,
* FRAMESET, H1, H2, H3, H4, H5, H6, HEAD, HR, HTML,
* I, IMG, INPUT, ISINDEX, KBD, LI, LINK, MAP, MENU,
* META, NOBR, NOFRAMES, OBJECT, OL, OPTION, P, PARAM,
* PRE, SAMP, SCRIPT, SELECT, SMALL, SPAN, STRIKE, S,
* STRONG, STYLE, SUB, SUP, TABLE, TD, TEXTAREA,
* TH, TITLE, TR, TT, U, UL, VAR}. If the given
* name does not represent one of the well-known tags, then
* <code>null</code> will be returned.
*
* @param tagName the <code>String</code> name requested
* @return a tag constant corresponding to the <code>tagName</code>,
* or <code>null</code> if not found
*/
public static Tag getTag(String tagName) {
Tag t = tagHashtable.get(tagName);
return (t == null ? null : t);
}
/**
* Returns the HTML <code>Tag</code> associated with the
* <code>StyleConstants</code> key <code>sc</code>.
* If no matching <code>Tag</code> is found, returns
* <code>null</code>.
*
* @param sc the <code>StyleConstants</code> key
* @return tag which corresponds to <code>sc</code>, or
* <code>null</code> if not found
*/
static Tag getTagForStyleConstantsKey(StyleConstants sc) {
return scMapping.get(sc);
}
/**
* Fetches an integer attribute value. Attribute values
* are stored as a string, and this is a convenience method
* to convert to an actual integer.
*
* @param attr the set of attributes to use to try to fetch a value
* @param key the key to use to fetch the value
* @param def the default value to use if the attribute isn't
* defined or there is an error converting to an integer
*/
public static int getIntegerAttributeValue(AttributeSet attr,
Attribute key, int def) {
int value = def;
String istr = (String) attr.getAttribute(key);
if (istr != null) {
try {
value = Integer.valueOf(istr).intValue();
} catch (NumberFormatException e) {
value = def;
}
}
return value;
}
// This is used in cases where the value for the attribute has not
// been specified.
//
public static final String NULL_ATTRIBUTE_VALUE = "#DEFAULT";
// size determined similar to size of tagHashtable
private static final Hashtable<String, Attribute> attHashtable = new Hashtable<String, Attribute>(77);
static {
for (int i = 0; i < Attribute.allAttributes.length; i++ ) {
attHashtable.put(Attribute.allAttributes[i].toString(), Attribute.allAttributes[i]);
}
}
/**
* Returns the set of HTML attributes recognized.
* @return the set of HTML attributes recognized
*/
public static Attribute[] getAllAttributeKeys() {
Attribute[] attributes = new Attribute[Attribute.allAttributes.length];
System.arraycopy(Attribute.allAttributes, 0,
attributes, 0, Attribute.allAttributes.length);
return attributes;
}
/**
* Fetches an attribute constant for a well-known attribute name
* (i.e. one of the attributes in the set {FACE, COMMENT, SIZE,
* COLOR, CLEAR, BACKGROUND, BGCOLOR, TEXT, LINK, VLINK, ALINK,
* WIDTH, HEIGHT, ALIGN, NAME, HREF, REL, REV, TITLE, TARGET,
* SHAPE, COORDS, ISMAP, NOHREF, ALT, ID, SRC, HSPACE, VSPACE,
* USEMAP, LOWSRC, CODEBASE, CODE, ARCHIVE, VALUE, VALUETYPE,
* TYPE, CLASS, STYLE, LANG, DIR, DECLARE, CLASSID, DATA, CODETYPE,
* STANDBY, BORDER, SHAPES, NOSHADE, COMPACT, START, ACTION, METHOD,
* ENCTYPE, CHECKED, MAXLENGTH, MULTIPLE, SELECTED, ROWS, COLS,
* DUMMY, CELLSPACING, CELLPADDING, VALIGN, HALIGN, NOWRAP, ROWSPAN,
* COLSPAN, PROMPT, HTTPEQUIV, CONTENT, LANGUAGE, VERSION, N,
* FRAMEBORDER, MARGINWIDTH, MARGINHEIGHT, SCROLLING, NORESIZE,
* MEDIA, ENDTAG}).
* If the given name does not represent one of the well-known attributes,
* then <code>null</code> will be returned.
*
* @param attName the <code>String</code> requested
* @return the <code>Attribute</code> corresponding to <code>attName</code>
*/
public static Attribute getAttributeKey(String attName) {
Attribute a = attHashtable.get(attName);
if (a == null) {
return null;
}
return a;
}
}
| apache-2.0 |
MondecaLabs/rdf2xml | src/rocfox/rdf2xml/exceptions/ExceptionBuilder.java | 2152 | /*
* Copyright 2008 Nicolas Cochard
* 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 rocfox.rdf2xml.exceptions;
import rocfox.rdf2xml.utilities.StringUtility;
/**
*
* @author Nicolas
*/
public class ExceptionBuilder
{
public static final UnsupportedOperationException createUnsupportedOperationException(String message)
{
if(StringUtility.isNullOrEmpty(message))
{
throw createNullArgumentException("message");
}
return new UnsupportedOperationException(message);
}
public static final UnsupportedOperationException createNotImplementedOperationException(String operationName)
{
if(StringUtility.isNullOrEmpty(operationName))
{
throw createNullArgumentException("operationName");
}
StringBuilder builder = new StringBuilder();
builder.append("The operation '");
builder.append(operationName);
builder.append("' is not implemented.");
return new UnsupportedOperationException(builder.toString());
}
public static final IllegalArgumentException createIllegalArgumentException(String message)
{
if(StringUtility.isNullOrEmpty(message))
{
throw createNullArgumentException("message");
}
return new IllegalArgumentException(message);
}
public static final IllegalArgumentException createNullArgumentException(String argumentName)
{
if(StringUtility.isNullOrEmpty(argumentName))
{
throw createNullArgumentException("argumentName");
}
StringBuilder builder = new StringBuilder();
builder.append("The argument '");
builder.append(argumentName);
builder.append("' cannot be null.");
return createIllegalArgumentException(builder.toString());
}
}
| apache-2.0 |
Unicon/cas | core/cas-server-core-webflow/src/main/java/org/apereo/cas/web/flow/resolver/impl/mfa/RegisteredServiceMultifactorAuthenticationPolicyEventResolver.java | 6305 | package org.apereo.cas.web.flow.resolver.impl.mfa;
import org.apache.commons.lang3.StringUtils;
import org.apereo.cas.CentralAuthenticationService;
import org.apereo.cas.authentication.Authentication;
import org.apereo.cas.authentication.AuthenticationServiceSelectionPlan;
import org.apereo.cas.authentication.AuthenticationSystemSupport;
import org.apereo.cas.authentication.principal.Principal;
import org.apereo.cas.services.MultifactorAuthenticationProvider;
import org.apereo.cas.services.MultifactorAuthenticationProviderSelector;
import org.apereo.cas.services.RegisteredService;
import org.apereo.cas.services.RegisteredServiceMultifactorPolicy;
import org.apereo.cas.services.ServicesManager;
import org.apereo.cas.ticket.registry.TicketRegistrySupport;
import org.apereo.cas.util.CollectionUtils;
import org.apereo.cas.web.flow.authentication.BaseMultifactorAuthenticationProviderEventResolver;
import org.apereo.cas.web.support.WebUtils;
import org.apereo.inspektr.audit.annotation.Audit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.util.CookieGenerator;
import org.springframework.webflow.execution.Event;
import org.springframework.webflow.execution.RequestContext;
import java.util.Collection;
import java.util.Set;
/**
* This is {@link RegisteredServiceMultifactorAuthenticationPolicyEventResolver}
* that attempts to resolve the next event based on the authentication providers of this service.
*
* @author Misagh Moayyed
* @since 5.0.0
*/
public class RegisteredServiceMultifactorAuthenticationPolicyEventResolver extends BaseMultifactorAuthenticationProviderEventResolver {
private static final Logger LOGGER = LoggerFactory.getLogger(RegisteredServiceMultifactorAuthenticationPolicyEventResolver.class);
public RegisteredServiceMultifactorAuthenticationPolicyEventResolver(final AuthenticationSystemSupport authenticationSystemSupport,
final CentralAuthenticationService centralAuthenticationService,
final ServicesManager servicesManager,
final TicketRegistrySupport ticketRegistrySupport,
final CookieGenerator warnCookieGenerator,
final AuthenticationServiceSelectionPlan authSelectionStrategies,
final MultifactorAuthenticationProviderSelector selector) {
super(authenticationSystemSupport, centralAuthenticationService, servicesManager,
ticketRegistrySupport, warnCookieGenerator, authSelectionStrategies, selector);
}
@Override
public Set<Event> resolveInternal(final RequestContext context) {
final RegisteredService service = resolveRegisteredServiceInRequestContext(context);
final Authentication authentication = WebUtils.getAuthentication(context);
if (service == null || authentication == null) {
LOGGER.debug("No service or authentication is available to determine event for principal");
return null;
}
final RegisteredServiceMultifactorPolicy policy = service.getMultifactorPolicy();
if (policy == null || policy.getMultifactorAuthenticationProviders().isEmpty()) {
LOGGER.debug("Authentication policy does not contain any multifactor authentication providers");
return null;
}
if (StringUtils.isNotBlank(policy.getPrincipalAttributeNameTrigger()) || StringUtils.isNotBlank(policy.getPrincipalAttributeValueToMatch())) {
LOGGER.debug("Authentication policy for [{}] has defined principal attribute triggers. Skipping...", service.getServiceId());
return null;
}
return resolveEventPerAuthenticationProvider(authentication.getPrincipal(), context, service);
}
/**
* Resolve event per authentication provider event.
*
* @param principal the principal
* @param context the context
* @param service the service
* @return the event
*/
protected Set<Event> resolveEventPerAuthenticationProvider(final Principal principal,
final RequestContext context,
final RegisteredService service) {
try {
final Collection<MultifactorAuthenticationProvider> providers = flattenProviders(getAuthenticationProviderForService(service));
if (providers != null && !providers.isEmpty()) {
final MultifactorAuthenticationProvider provider = this.multifactorAuthenticationProviderSelector.resolve(providers, service, principal);
LOGGER.debug("Selected multifactor authentication provider for this transaction is [{}]", provider);
if (!provider.isAvailable(service)) {
LOGGER.warn("Multifactor authentication provider [{}] could not be verified/reached.", provider);
return null;
}
final String identifier = provider.getId();
LOGGER.debug("Attempting to build an event based on the authentication provider [{}] and service [{}]", provider, service.getName());
final Event event = validateEventIdForMatchingTransitionInContext(identifier, context, buildEventAttributeMap(principal, service, provider));
return CollectionUtils.wrapSet(event);
}
LOGGER.debug("No multifactor authentication providers could be located for [{}]", service);
return null;
} catch (final Exception e) {
throw new RuntimeException(e.getMessage(), e);
}
}
@Audit(action = "AUTHENTICATION_EVENT",
actionResolverName = "AUTHENTICATION_EVENT_ACTION_RESOLVER",
resourceResolverName = "AUTHENTICATION_EVENT_RESOURCE_RESOLVER")
@Override
public Event resolveSingle(final RequestContext context) {
return super.resolveSingle(context);
}
}
| apache-2.0 |
NemoLee/Gap | Gap_Source/src/GameThings/Player.java | 2911 | /**
*
*/
package GameThings;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.ParticleEffect;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.BodyDef;
import com.badlogic.gdx.physics.box2d.BodyDef.BodyType;
import com.badlogic.gdx.physics.box2d.CircleShape;
import com.badlogic.gdx.physics.box2d.FixtureDef;
import com.badlogic.gdx.physics.box2d.MassData;
import com.badlogic.gdx.physics.box2d.World;
import com.badlogic.gdx.scenes.scene2d.Actor;
/**
* @author Nemo
*
*/
public class Player extends Actor {
/**
*
*/
public Body body;
BodyDef ballBodyDef;
Texture T_player;
ParticleEffect PE_player;
public Player() {
// TODO Auto-generated constructor stub
}
public Player(World world, float x, float y) {
initBox2D(world, x, y);
setSize(20, 20);
T_player = new Texture("test/player.png");
PE_player = new ParticleEffect();
PE_player.load(Gdx.files.internal("Player/player.p"),
Gdx.files.internal("Player/"));
}
@Override
public void act(float delta) {
// TODO Auto-generated method stub
super.act(delta);
// setPosition(body.getPosition().x, body.getPosition().y);
}
@Override
public void draw(SpriteBatch batch, float parentAlpha) {
// TODO Auto-generated method stub
// batch.draw(T_player, body.getPosition().x, body.getPosition().y,
// getWidth(), getHeight());
PE_player.setPosition(body.getPosition().x, body.getPosition().y);
PE_player.draw(batch, Gdx.graphics.getDeltaTime());
super.draw(batch, parentAlpha);
}
private void initBox2D(World world, float x, float y) {
ballBodyDef = new BodyDef();
ballBodyDef.type = BodyType.DynamicBody;
ballBodyDef.position.set(x, y);
body = world.createBody(ballBodyDef);
// PolygonShape playerShape = new PolygonShape();
CircleShape playerShape = new CircleShape();
// playerShape.setAsBox(10, 10);
playerShape.setRadius(10);
FixtureDef ballShapeDef = new FixtureDef();
ballShapeDef.shape = playerShape;
ballShapeDef.density = 1f;
ballShapeDef.friction = 0f;
ballShapeDef.restitution = 0f;
body.createFixture(ballShapeDef);
body.setFixedRotation(true);
MassData md = body.getMassData();
md.mass = 1;
body.setMassData(md);
}
public void forceRight() {
body.setLinearVelocity(20, body.getLinearVelocity().y);
}
public void forceLeft() {
body.setLinearVelocity(-20, body.getLinearVelocity().y);
}
public void forceJump() {
body.setLinearVelocity(body.getLinearVelocity().x, 30f);
}
public void forceStop() {
body.setAwake(false);
body.applyForceToCenter(new Vector2(0, -500), true);
}
public void setposition(float x, float y) {
body.setTransform(x, y, 0);
}
public void dispose() {
// TODO Auto-generated method stub
PE_player.dispose();
}
}
| apache-2.0 |
pdeva/druid | processing/src/main/java/io/druid/query/filter/DimFilters.java | 2866 | /*
* Licensed to Metamarkets Group Inc. (Metamarkets) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. Metamarkets 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 io.druid.query.filter;
import com.google.common.base.Function;
import com.google.common.base.Predicates;
import com.google.common.collect.Collections2;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import java.util.Arrays;
import java.util.List;
/**
*/
public class DimFilters
{
public static SelectorDimFilter dimEquals(String dimension, String value)
{
return new SelectorDimFilter(dimension, value);
}
public static AndDimFilter and(DimFilter... filters)
{
return and(Arrays.asList(filters));
}
public static AndDimFilter and(List<DimFilter> filters)
{
return new AndDimFilter(filters);
}
public static OrDimFilter or(DimFilter... filters)
{
return or(Arrays.asList(filters));
}
public static OrDimFilter or(List<DimFilter> filters)
{
return new OrDimFilter(filters);
}
public static NotDimFilter not(DimFilter filter)
{
return new NotDimFilter(filter);
}
public static RegexDimFilter regex(String dimension, String pattern)
{
return new RegexDimFilter(dimension, pattern);
}
public static DimFilter dimEquals(final String dimension, String... values)
{
return or(
Lists.transform(
Arrays.asList(values),
new Function<String, DimFilter>()
{
@Override
public DimFilter apply(String input)
{
return dimEquals(dimension, input);
}
}
)
);
}
public static List<DimFilter> optimize(List<DimFilter> filters)
{
return filterNulls(
Lists.transform(
filters, new Function<DimFilter, DimFilter>()
{
@Override
public DimFilter apply(DimFilter input)
{
return input.optimize();
}
}
)
);
}
public static List<DimFilter> filterNulls(List<DimFilter> optimized)
{
return Lists.newArrayList(Iterables.filter(optimized, Predicates.notNull()));
}
}
| apache-2.0 |
taimos/dvalin | test/src/main/java/de/taimos/dvalin/test/AbstractMockitoTest.java | 1055 | package de.taimos.dvalin.test;
/*-
* #%L
* Test support for dvalin
* %%
* Copyright (C) 2016 - 2017 Taimos GmbH
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import org.junit.BeforeClass;
import org.junit.runner.RunWith;
import org.mockito.junit.MockitoJUnitRunner;
import de.taimos.daemon.log4j.Log4jLoggingConfigurer;
@RunWith(MockitoJUnitRunner.class)
public class AbstractMockitoTest {
@BeforeClass
public static void init() throws Exception {
new Log4jLoggingConfigurer().simpleLogging();
}
}
| apache-2.0 |
Crigges/WurstScript | de.peeeq.wurstscript/src/de/peeeq/wurstio/objectreader/ObjectFileType.java | 1491 | package de.peeeq.wurstio.objectreader;
public enum ObjectFileType {
UNITS ("w3u", "Units\\UnitData.slk", "Units\\UnitMetaData.slk", false),
ITEMS ("w3t", "Units\\ItemData.slk", "Units\\UnitMetaData.slk", false),
DESTRUCTABLES("w3b", "Units\\DestructableData.slk", "Units\\DestructableMetaData.slk", false),
DOODADS ("w3d", "Doodads\\Doodads.slk", "Doodads\\DoodadMetaData.slk", true),
ABILITIES ("w3a", "Units\\AbilityData.slk", "Units\\AbilityMetaData.slk", true),
BUFFS ("w3h", "Units\\AbilityBuffData.slk", "Units\\AbilityBuffMetaData.slk", false),
UPGRADES ("w3q", "Units\\UpgradeData.slk", "Units\\UpgradeMetaData.slk", true);
private boolean usesLevels;
private String ext;
private String objectIDs;
private String modIDs;
public boolean usesLevels() {
return usesLevels;
}
public String getExt() {
return ext;
}
public String getObjectIDs() {
return objectIDs;
}
public String getModIDs() {
return modIDs;
}
ObjectFileType(String ext, String objectIDs, String modIDs, boolean usesLevels) {
this.ext = ext;
this.objectIDs = objectIDs;
this.modIDs = modIDs;
this.usesLevels = usesLevels;
}
public static ObjectFileType fromExt(String fileExtension) {
for (ObjectFileType t : ObjectFileType.values()) {
if (t.getExt().equals(fileExtension)) {
return t;
}
}
throw new Error("Unsupoorted filetype: " + fileExtension);
}
}
| apache-2.0 |
xfournet/intellij-community | platform/platform-impl/src/com/intellij/openapi/project/impl/ProjectManagerImpl.java | 32103 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.project.impl;
import com.intellij.configurationStore.StorageUtilKt;
import com.intellij.conversion.ConversionResult;
import com.intellij.conversion.ConversionService;
import com.intellij.ide.AppLifecycleListener;
import com.intellij.ide.impl.ProjectUtil;
import com.intellij.ide.plugins.PluginManager;
import com.intellij.ide.startup.StartupManagerEx;
import com.intellij.ide.startup.impl.StartupManagerImpl;
import com.intellij.notification.Notification;
import com.intellij.notification.NotificationType;
import com.intellij.notification.NotificationsManager;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.application.*;
import com.intellij.openapi.application.impl.LaterInvocator;
import com.intellij.openapi.components.ProjectComponent;
import com.intellij.openapi.components.impl.stores.StoreUtil;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.progress.ProcessCanceledException;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.progress.Task;
import com.intellij.openapi.project.*;
import com.intellij.openapi.project.ex.ProjectManagerEx;
import com.intellij.openapi.startup.StartupManager;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.util.*;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.io.FileUtilRt;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.impl.ZipHandler;
import com.intellij.openapi.wm.impl.welcomeScreen.WelcomeFrame;
import com.intellij.ui.GuiUtils;
import com.intellij.util.ArrayUtil;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.containers.UnsafeWeakList;
import com.intellij.util.messages.MessageBus;
import com.intellij.util.ref.GCUtil;
import com.intellij.util.ui.UIUtil;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.TestOnly;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
public class ProjectManagerImpl extends ProjectManagerEx implements Disposable {
private static final Logger LOG = Logger.getInstance(ProjectManagerImpl.class);
private static final Key<List<ProjectManagerListener>> LISTENERS_IN_PROJECT_KEY = Key.create("LISTENERS_IN_PROJECT_KEY");
@SuppressWarnings("FieldAccessedSynchronizedAndUnsynchronized")
private ProjectImpl myDefaultProject; // Only used asynchronously in save and dispose, which itself are synchronized.
private Project[] myOpenProjects = {}; // guarded by lock
private final Map<String, Project> myOpenProjectByHash = ContainerUtil.newConcurrentMap();
private final Object lock = new Object();
// we cannot use the same approach to migrate to message bus as CompilerManagerImpl because of method canCloseProject
private final List<ProjectManagerListener> myListeners = ContainerUtil.createLockFreeCopyOnWriteList();
private final ProgressManager myProgressManager;
private volatile boolean myDefaultProjectWasDisposed;
private final ProjectManagerListener myBusPublisher;
@NotNull
private static List<ProjectManagerListener> getListeners(@NotNull Project project) {
List<ProjectManagerListener> array = project.getUserData(LISTENERS_IN_PROJECT_KEY);
if (array == null) return Collections.emptyList();
return array;
}
public ProjectManagerImpl(ProgressManager progressManager) {
myProgressManager = progressManager;
MessageBus messageBus = ApplicationManager.getApplication().getMessageBus();
myBusPublisher = messageBus.syncPublisher(TOPIC);
messageBus.connect().subscribe(ProjectManager.TOPIC, new ProjectManagerListener() {
@Override
public void projectOpened(@NotNull Project project) {
for (ProjectManagerListener listener : getAllListeners(project)) {
try {
listener.projectOpened(project);
}
catch (Exception e) {
handleListenerError(e, listener);
}
}
}
@Override
public void projectClosed(Project project) {
for (ProjectManagerListener listener : getAllListeners(project)) {
try {
listener.projectClosed(project);
}
catch (Exception e) {
handleListenerError(e, listener);
}
}
ZipHandler.clearFileAccessorCache();
LaterInvocator.purgeExpiredItems();
}
@Override
public void projectClosing(Project project) {
for (ProjectManagerListener listener : getAllListeners(project)) {
try {
listener.projectClosing(project);
}
catch (Exception e) {
handleListenerError(e, listener);
}
}
}
@Override
public void projectClosingBeforeSave(@NotNull Project project) {
for (ProjectManagerListener listener : getAllListeners(project)) {
try {
listener.projectClosingBeforeSave(project);
}
catch (Exception e) {
handleListenerError(e, listener);
}
}
}
});
}
private static void handleListenerError(@NotNull Throwable e, @NotNull ProjectManagerListener listener) {
if (e instanceof ProcessCanceledException) {
throw (ProcessCanceledException)e;
}
else {
LOG.error("From listener " + listener + " (" + listener.getClass() + ")", e);
}
}
@Override
public void dispose() {
ApplicationManager.getApplication().assertWriteAccessAllowed();
if (myDefaultProject != null) {
Disposer.dispose(myDefaultProject);
myDefaultProject = null;
myDefaultProjectWasDisposed = true;
}
}
@SuppressWarnings("StaticNonFinalField") public static int TEST_PROJECTS_CREATED;
private static final boolean LOG_PROJECT_LEAKAGE_IN_TESTS = Boolean.parseBoolean(System.getProperty("idea.log.leaked.projects.in.tests", "true"));
private static final int MAX_LEAKY_PROJECTS = 5;
private static final long LEAK_CHECK_INTERVAL = TimeUnit.MINUTES.toMillis(30);
private static long CHECK_START = System.currentTimeMillis();
@SuppressWarnings("FieldCanBeLocal") private final Map<Project, String> myProjects = new WeakHashMap<>();
@Override
@Nullable
public Project newProject(@Nullable String projectName, @NotNull String filePath, boolean useDefaultProjectSettings, boolean isDummy) {
filePath = toCanonicalName(filePath);
if (ApplicationManager.getApplication().isUnitTestMode()) {
//noinspection AssignmentToStaticFieldFromInstanceMethod
TEST_PROJECTS_CREATED++;
//noinspection TestOnlyProblems
checkProjectLeaksInTests();
}
File projectFile = new File(filePath);
if (projectFile.isFile()) {
FileUtil.delete(projectFile);
}
else {
File[] files = new File(projectFile, Project.DIRECTORY_STORE_FOLDER).listFiles();
if (files != null) {
for (File file : files) {
FileUtil.delete(file);
}
}
}
ProjectImpl project = createProject(projectName, filePath, false);
try {
initProject(project, useDefaultProjectSettings ? getDefaultProject() : null);
if (LOG_PROJECT_LEAKAGE_IN_TESTS) {
myProjects.put(project, null);
}
return project;
}
catch (Throwable t) {
LOG.info(t);
Messages.showErrorDialog(message(t), ProjectBundle.message("project.load.default.error"));
return null;
}
}
@NonNls
@NotNull
private static String message(@NotNull Throwable e) {
String message = e.getMessage();
if (message != null) return message;
message = e.getLocalizedMessage();
//noinspection ConstantConditions
if (message != null) return message;
message = e.toString();
Throwable cause = e.getCause();
if (cause != null) {
String causeMessage = message(cause);
return message + " (cause: " + causeMessage + ")";
}
return message;
}
@TestOnly
private void checkProjectLeaksInTests() {
if (!LOG_PROJECT_LEAKAGE_IN_TESTS || getLeakedProjectsCount() < MAX_LEAKY_PROJECTS) {
return;
}
long currentTime = System.currentTimeMillis();
if (currentTime - CHECK_START < LEAK_CHECK_INTERVAL) {
return; // check every N minutes
}
for (int i = 0; i < 3 && getLeakedProjectsCount() >= MAX_LEAKY_PROJECTS; i++) {
GCUtil.tryGcSoftlyReachableObjects();
}
//noinspection AssignmentToStaticFieldFromInstanceMethod
CHECK_START = currentTime;
if (getLeakedProjectsCount() >= MAX_LEAKY_PROJECTS) {
System.gc();
Collection<Project> copy = getLeakedProjects();
myProjects.clear();
if (ContainerUtil.collect(copy.iterator()).size() >= MAX_LEAKY_PROJECTS) {
throw new TooManyProjectLeakedException(copy);
}
}
}
@TestOnly
private Collection<Project> getLeakedProjects() {
myProjects.remove(getDefaultProject()); // process queue
return myProjects.keySet().stream().filter(project -> project.isDisposed() && !((ProjectImpl)project).isTemporarilyDisposed()).collect(Collectors.toCollection(UnsafeWeakList::new));
}
@TestOnly
private int getLeakedProjectsCount() {
myProjects.remove(getDefaultProject()); // process queue
return (int)myProjects.keySet().stream().filter(project -> project.isDisposed() && !((ProjectImpl)project).isTemporarilyDisposed()).count();
}
private void initProject(@NotNull ProjectImpl project, @Nullable Project template) {
ProgressIndicator indicator = myProgressManager.getProgressIndicator();
if (indicator != null && !project.isDefault()) {
indicator.setIndeterminate(false);
indicator.setText(ProjectBundle.message("loading.components.for", project.getName()));
}
ApplicationManager.getApplication().getMessageBus().syncPublisher(ProjectLifecycleListener.TOPIC).beforeProjectLoaded(project);
boolean succeed = false;
try {
if (template != null) {
project.getStateStore().loadProjectFromTemplate(template);
}
project.init();
succeed = true;
}
finally {
if (!succeed && !project.isDefault()) {
TransactionGuard.submitTransaction(project, () -> WriteAction.run(() -> Disposer.dispose(project)));
}
}
}
@NotNull
private static ProjectImpl createProject(@Nullable String projectName, @NotNull String filePath, boolean isDefault) {
if (isDefault) {
return new DefaultProject("");
}
return new ProjectImpl(FileUtilRt.toSystemIndependentName(filePath), projectName);
}
@Override
@Nullable
public Project loadProject(@NotNull String filePath) throws IOException {
return loadProject(filePath, null);
}
@Override
@Nullable
public Project loadProject(@NotNull String filePath, @Nullable String projectName) throws IOException {
try {
ProjectImpl project = createProject(projectName, new File(filePath).getAbsolutePath(), false);
initProject(project, null);
return project;
}
catch (Throwable t) {
LOG.info(t);
throw new IOException(t);
}
}
@NotNull
private static String toCanonicalName(@NotNull final String filePath) {
try {
return FileUtil.resolveShortWindowsName(filePath);
}
catch (IOException e) {
// OK. File does not yet exist so it's canonical path will be equal to its original path.
}
return filePath;
}
@TestOnly
public synchronized boolean isDefaultProjectInitialized() {
return myDefaultProject != null;
}
@Override
@NotNull
public synchronized Project getDefaultProject() {
LOG.assertTrue(!myDefaultProjectWasDisposed, "Default project has been already disposed!");
if (myDefaultProject == null) {
ProgressManager.getInstance().executeNonCancelableSection(() -> {
try {
myDefaultProject = createProject(null, "", true);
initProject(myDefaultProject, null);
}
catch (Throwable t) {
PluginManager.processException(t);
}
});
}
return myDefaultProject;
}
@Override
@NotNull
public Project[] getOpenProjects() {
synchronized (lock) {
return myOpenProjects;
}
}
@Override
public boolean isProjectOpened(Project project) {
synchronized (lock) {
return ArrayUtil.contains(project, myOpenProjects);
}
}
@Override
public boolean openProject(@NotNull final Project project) {
if (isLight(project)) {
((ProjectImpl)project).setTemporarilyDisposed(false);
boolean isInitialized = StartupManagerEx.getInstanceEx(project).startupActivityPassed();
if (isInitialized) {
addToOpened(project);
// events already fired
return true;
}
}
for (Project p : getOpenProjects()) {
if (ProjectUtil.isSameProject(project.getProjectFilePath(), p)) {
GuiUtils.invokeLaterIfNeeded(() -> ProjectUtil.focusProjectWindow(p, false), ModalityState.NON_MODAL);
return false;
}
}
if (!addToOpened(project)) {
return false;
}
Runnable process = () -> {
TransactionGuard.getInstance().submitTransactionAndWait(() -> fireProjectOpened(project));
StartupManagerImpl startupManager = (StartupManagerImpl)StartupManager.getInstance(project);
startupManager.runStartupActivities();
// Startup activities (e.g. the one in FileBasedIndexProjectHandler) have scheduled dumb mode to begin "later"
// Now we schedule-and-wait to the same event queue to guarantee that the dumb mode really begins now:
// Post-startup activities should not ever see unindexed and at the same time non-dumb state
TransactionGuard.getInstance().submitTransactionAndWait(startupManager::startCacheUpdate);
startupManager.runPostStartupActivitiesFromExtensions();
GuiUtils.invokeLaterIfNeeded(() -> {
if (!project.isDisposed()) {
startupManager.runPostStartupActivities();
Application application = ApplicationManager.getApplication();
if (!(application.isHeadlessEnvironment() || application.isUnitTestMode())) {
StorageUtilKt.checkUnknownMacros(project, true);
}
}
}, ModalityState.NON_MODAL);
};
if (!loadProjectUnderProgress(project, process)) {
GuiUtils.invokeLaterIfNeeded(() -> {
closeProject(project, false, false, false, true);
WriteAction.run(() -> Disposer.dispose(project));
notifyProjectOpenFailed();
}, ModalityState.defaultModalityState());
return false;
}
return true;
}
private boolean loadProjectUnderProgress(@NotNull Project project, @NotNull Runnable performLoading) {
ProgressIndicator indicator = myProgressManager.getProgressIndicator();
if (indicator != null) {
indicator.setText("Preparing workspace...");
try {
performLoading.run();
return true;
}
catch (ProcessCanceledException e) {
return false;
}
}
return myProgressManager.runProcessWithProgressSynchronously(performLoading, ProjectBundle.message("project.load.progress"), canCancelProjectLoading(), project);
}
private boolean addToOpened(@NotNull Project project) {
assert !project.isDisposed() : "Must not open already disposed project";
synchronized (lock) {
if (isProjectOpened(project)) {
return false;
}
myOpenProjects = ArrayUtil.append(myOpenProjects, project);
ProjectCoreUtil.theProject = myOpenProjects.length == 1 ? project : null;
myOpenProjectByHash.put(project.getLocationHash(), project);
}
return true;
}
private void removeFromOpened(@NotNull Project project) {
synchronized (lock) {
myOpenProjects = ArrayUtil.remove(myOpenProjects, project);
ProjectCoreUtil.theProject = myOpenProjects.length == 1 ? myOpenProjects[0] : null;
myOpenProjectByHash.values().remove(project); // remove by value and not by key!
}
}
@Nullable
public Project findOpenProjectByHash(@Nullable String locationHash) {
return myOpenProjectByHash.get(locationHash);
}
private static boolean canCancelProjectLoading() {
return !ProgressManager.getInstance().isInNonCancelableSection();
}
@Override
public Project loadAndOpenProject(@NotNull final String originalFilePath) throws IOException {
final String filePath = toCanonicalName(originalFilePath);
final ConversionResult conversionResult = ConversionService.getInstance().convert(filePath);
ProjectImpl project;
if (conversionResult.openingIsCanceled()) {
project = null;
}
else {
project = createProject(null, filePath, false);
myProgressManager.run(new Task.WithResult<Project, IOException>(project, ProjectBundle.message("project.load.progress"), true) {
@Override
protected Project compute(@NotNull ProgressIndicator indicator) throws IOException {
if (!loadProjectWithProgress(project)) {
return null;
}
if (!conversionResult.conversionNotNeeded()) {
StartupManager.getInstance(project).registerPostStartupActivity(() -> conversionResult.postStartupActivity(project));
}
openProject(project);
return project;
}
});
}
if (project == null) {
WelcomeFrame.showIfNoProjectOpened();
return null;
}
if (!project.isOpen()) {
WelcomeFrame.showIfNoProjectOpened();
ApplicationManager.getApplication().runWriteAction(() -> {
if (!project.isDisposed()) {
Disposer.dispose(project);
}
});
}
return project;
}
/**
* Converts and loads the project at the specified path.
*
* @param filePath the path to open the project.
* @return the project, or null if the user has cancelled opening the project.
*/
@Override
@Nullable
public Project convertAndLoadProject(@NotNull String filePath) throws IOException {
final String canonicalFilePath = toCanonicalName(filePath);
final ConversionResult conversionResult = ConversionService.getInstance().convert(canonicalFilePath);
if (conversionResult.openingIsCanceled()) {
return null;
}
ProjectImpl project = createProject(null, canonicalFilePath, false);
if (!loadProjectWithProgress(project)) return null;
if (!conversionResult.conversionNotNeeded()) {
StartupManager.getInstance(project).registerPostStartupActivity(() -> conversionResult.postStartupActivity(project));
}
return project;
}
private boolean loadProjectWithProgress(ProjectImpl project) throws IOException {
try {
if (!ApplicationManager.getApplication().isDispatchThread() &&
myProgressManager.getProgressIndicator() != null) {
initProject(project, null);
return true;
}
myProgressManager.runProcessWithProgressSynchronously((ThrowableComputable<Object, RuntimeException>)() -> {
initProject(project, null);
return project;
}, ProjectBundle.message("project.load.progress"), canCancelProjectLoading(), project);
return true;
}
catch (ProcessCanceledException e) {
return false;
}
catch (Throwable t) {
LOG.info(t);
throw new IOException(t);
}
}
private static void notifyProjectOpenFailed() {
Application application = ApplicationManager.getApplication();
application.getMessageBus().syncPublisher(AppLifecycleListener.TOPIC).projectOpenFailed();
if (application.isUnitTestMode()) return;
WelcomeFrame.showIfNoProjectOpened();
}
@Override
@TestOnly
public void openTestProject(@NotNull final Project project) {
assert ApplicationManager.getApplication().isUnitTestMode();
openProject(project);
UIUtil.dispatchAllInvocationEvents(); // post init activities are invokeLatered
}
@NotNull
@Override
@TestOnly
public Collection<Project> closeTestProject(@NotNull final Project project) {
assert ApplicationManager.getApplication().isUnitTestMode();
forceCloseProject(project, false);
Project[] projects = getOpenProjects();
return projects.length == 0 ? Collections.emptyList() : Arrays.asList(projects);
}
@Override
public void reloadProject(@NotNull Project project) {
doReloadProject(project);
}
public static void doReloadProject(@NotNull Project project) {
final Ref<Project> projectRef = Ref.create(project);
ProjectReloadState.getInstance(project).onBeforeAutomaticProjectReload();
ApplicationManager.getApplication().invokeLater(() -> {
LOG.debug("Reloading project.");
Project project1 = projectRef.get();
// Let it go
projectRef.set(null);
if (project1.isDisposed()) {
return;
}
// must compute here, before project dispose
String presentableUrl = project1.getPresentableUrl();
if (!ProjectUtil.closeAndDispose(project1)) {
return;
}
ProjectUtil.openProject(presentableUrl, null, true);
}, ModalityState.NON_MODAL);
}
@Override
public boolean closeProject(@NotNull final Project project) {
return closeProject(project, true, true, false, true);
}
@TestOnly
public boolean forceCloseProject(@NotNull Project project, boolean dispose) {
return closeProject(project, false, false, dispose, false);
}
// return true if successful
public boolean closeAndDisposeAllProjects(boolean checkCanClose) {
for (Project project : getOpenProjects()) {
if (!closeProject(project, true, false, true, checkCanClose)) {
return false;
}
}
return true;
}
// saveApp is ignored if saveProject is false
@SuppressWarnings("TestOnlyProblems")
private boolean closeProject(@NotNull final Project project,
final boolean saveProject,
final boolean saveApp,
final boolean dispose,
boolean checkCanClose) {
Application app = ApplicationManager.getApplication();
if (app.isWriteAccessAllowed()) {
throw new IllegalStateException("Must not call closeProject() from under write action because fireProjectClosing() listeners must have a chance to do something useful");
}
app.assertIsDispatchThread();
if (isLight(project)) {
// if we close project at the end of the test, just mark it closed; if we are shutting down the entire test framework, proceed to full dispose
if (!((ProjectImpl)project).isTemporarilyDisposed()) {
((ProjectImpl)project).setTemporarilyDisposed(true);
removeFromOpened(project);
return true;
}
((ProjectImpl)project).setTemporarilyDisposed(false);
}
else if (!isProjectOpened(project)) {
return true;
}
if (checkCanClose && !canClose(project)) {
return false;
}
final ShutDownTracker shutDownTracker = ShutDownTracker.getInstance();
shutDownTracker.registerStopperThread(Thread.currentThread());
try {
myBusPublisher.projectClosingBeforeSave(project);
if (saveProject) {
FileDocumentManager.getInstance().saveAllDocuments();
StoreUtil.saveProject(project, true);
if (saveApp) {
app.saveSettings(true);
}
}
if (checkCanClose && !ensureCouldCloseIfUnableToSave(project)) {
return false;
}
fireProjectClosing(project); // somebody can start progress here, do not wrap in write action
app.runWriteAction(() -> {
removeFromOpened(project);
fireProjectClosed(project);
if (dispose) {
Disposer.dispose(project);
}
});
}
finally {
shutDownTracker.unregisterStopperThread(Thread.currentThread());
}
return true;
}
@TestOnly
public static boolean isLight(@NotNull Project project) {
return project instanceof ProjectImpl && ((ProjectImpl)project).isLight();
}
@Override
public boolean closeAndDispose(@NotNull final Project project) {
return closeProject(project, true, true, true, true);
}
private void fireProjectClosing(@NotNull Project project) {
if (LOG.isDebugEnabled()) {
LOG.debug("enter: fireProjectClosing()");
}
myBusPublisher.projectClosing(project);
}
@Override
public void addProjectManagerListener(@NotNull ProjectManagerListener listener) {
myListeners.add(listener);
}
@Override
public void addProjectManagerListener(@NotNull VetoableProjectManagerListener listener) {
myListeners.add(listener);
}
@Override
public void addProjectManagerListener(@NotNull final ProjectManagerListener listener, @NotNull Disposable parentDisposable) {
addProjectManagerListener(listener);
Disposer.register(parentDisposable, () -> removeProjectManagerListener(listener));
}
@Override
public void removeProjectManagerListener(@NotNull ProjectManagerListener listener) {
boolean removed = myListeners.remove(listener);
LOG.assertTrue(removed);
}
@Override
public void removeProjectManagerListener(@NotNull VetoableProjectManagerListener listener) {
boolean removed = myListeners.remove(listener);
LOG.assertTrue(removed);
}
@Override
public void addProjectManagerListener(@NotNull Project project, @NotNull ProjectManagerListener listener) {
List<ProjectManagerListener> listeners = project.getUserData(LISTENERS_IN_PROJECT_KEY);
if (listeners == null) {
listeners = ((UserDataHolderEx)project)
.putUserDataIfAbsent(LISTENERS_IN_PROJECT_KEY, ContainerUtil.createLockFreeCopyOnWriteList());
}
listeners.add(listener);
}
@Override
public void removeProjectManagerListener(@NotNull Project project, @NotNull ProjectManagerListener listener) {
List<ProjectManagerListener> listeners = project.getUserData(LISTENERS_IN_PROJECT_KEY);
LOG.assertTrue(listeners != null);
boolean removed = listeners.remove(listener);
LOG.assertTrue(removed);
}
private void fireProjectOpened(@NotNull Project project) {
if (LOG.isDebugEnabled()) {
LOG.debug("projectOpened");
}
myBusPublisher.projectOpened(project);
// https://jetbrains.slack.com/archives/C5E8K7FL4/p1495015043685628
// projectOpened in the project components is called _after_ message bus event projectOpened for ages
// old behavior is preserved for now (smooth transition, to not break all), but this order is not logical,
// because ProjectComponent.projectOpened it is part of project initialization contract, but message bus projectOpened it is just an event
// (and, so, should be called after project initialization)
if (project instanceof ProjectImpl) {
for (ProjectComponent component : ((ProjectImpl)project).getComponentInstancesOfType(ProjectComponent.class)) {
try {
component.projectOpened();
}
catch (Throwable e) {
LOG.error(component.toString(), e);
}
}
}
}
private void fireProjectClosed(@NotNull Project project) {
if (LOG.isDebugEnabled()) {
LOG.debug("projectClosed");
}
myBusPublisher.projectClosed(project);
// see "why is called after message bus" in the fireProjectOpened
if (project instanceof ProjectImpl) {
List<ProjectComponent> components = ((ProjectImpl)project).getComponentInstancesOfType(ProjectComponent.class);
for (int i = components.size() - 1; i >= 0; i--) {
ProjectComponent component = components.get(i);
try {
component.projectClosed();
}
catch (Throwable e) {
LOG.error(component.toString(), e);
}
}
}
}
@Override
public boolean canClose(@NotNull Project project) {
if (LOG.isDebugEnabled()) {
LOG.debug("enter: canClose()");
}
for (ProjectManagerListener listener : getAllListeners(project)) {
try {
//noinspection deprecation
boolean canClose = listener instanceof VetoableProjectManagerListener ? ((VetoableProjectManagerListener)listener).canClose(project) : listener.canCloseProject(project);
if (!canClose) {
LOG.debug("close canceled by " + listener);
return false;
}
}
catch (Throwable e) {
handleListenerError(e, listener);
}
}
return true;
}
// both lists are thread-safe (LockFreeCopyOnWriteArrayList), but ContainerUtil.concat cannot handle situation when list size is changed during iteration
// so, we have to create list.
@NotNull
private List<ProjectManagerListener> getAllListeners(@NotNull Project project) {
List<ProjectManagerListener> projectLevelListeners = getListeners(project);
if (projectLevelListeners.isEmpty()) {
return myListeners;
}
if (myListeners.isEmpty()) {
return projectLevelListeners;
}
List<ProjectManagerListener> result = new ArrayList<>(projectLevelListeners.size() + myListeners.size());
// order is critically important due to backward compatibility - project level listeners must be first
result.addAll(projectLevelListeners);
result.addAll(myListeners);
return result;
}
private static boolean ensureCouldCloseIfUnableToSave(@NotNull Project project) {
UnableToSaveProjectNotification[] notifications =
NotificationsManager.getNotificationsManager().getNotificationsOfType(UnableToSaveProjectNotification.class, project);
if (notifications.length == 0) {
return true;
}
StringBuilder message = new StringBuilder();
message.append(String.format("%s was unable to save some project files,\nare you sure you want to close this project anyway?",
ApplicationNamesInfo.getInstance().getProductName()));
message.append("\n\nRead-only files:\n");
int count = 0;
VirtualFile[] files = notifications[0].myFiles;
for (VirtualFile file : files) {
if (count == 10) {
message.append('\n').append("and ").append(files.length - count).append(" more").append('\n');
}
else {
message.append(file.getPath()).append('\n');
count++;
}
}
return Messages.showYesNoDialog(project, message.toString(), "Unsaved Project", Messages.getWarningIcon()) == Messages.YES;
}
public static class UnableToSaveProjectNotification extends Notification {
private Project myProject;
public VirtualFile[] myFiles;
public UnableToSaveProjectNotification(@NotNull final Project project, @NotNull VirtualFile[] readOnlyFiles) {
super("Project Settings", "Could not save project", "Unable to save project files. Please ensure project files are writable and you have permissions to modify them." +
" <a href=\"\">Try to save project again</a>.", NotificationType.ERROR,
(notification, event) -> {
final UnableToSaveProjectNotification unableToSaveProjectNotification = (UnableToSaveProjectNotification)notification;
final Project _project = unableToSaveProjectNotification.myProject;
notification.expire();
if (_project != null && !_project.isDisposed()) {
_project.save();
}
});
myProject = project;
myFiles = readOnlyFiles;
}
@Override
public void expire() {
myProject = null;
super.expire();
}
}
@Override
public void saveChangedProjectFile(@NotNull VirtualFile file, @NotNull Project project) {
}
@Override
public void blockReloadingProjectOnExternalChanges() {
}
@Override
public void unblockReloadingProjectOnExternalChanges() {
}
}
| apache-2.0 |
smhoekstra/iaf | JavaSource/nl/nn/adapterframework/receivers/ServiceClient.java | 933 | /*
Copyright 2013 Nationale-Nederlanden
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 nl.nn.adapterframework.receivers;
import java.util.Map;
import nl.nn.adapterframework.core.ListenerException;
/**
* The interface clients (users) of a service may use.
*/
public interface ServiceClient {
public String processRequest(String correlationId, String message, Map requestContext) throws ListenerException;
}
| apache-2.0 |
0359xiaodong/storio | storio-sqlite/src/main/java/com/pushtorefresh/storio/sqlite/operation/get/DefaultGetResolver.java | 931 | package com.pushtorefresh.storio.sqlite.operation.get;
import android.database.Cursor;
import android.support.annotation.NonNull;
import com.pushtorefresh.storio.sqlite.StorIOSQLite;
import com.pushtorefresh.storio.sqlite.query.Query;
import com.pushtorefresh.storio.sqlite.query.RawQuery;
/**
* Default implementation of {@link GetResolver}, thread-safe
* <p>
* You need to just override mapping from Cursor
*/
public abstract class DefaultGetResolver<T> implements GetResolver<T> {
/**
* {@inheritDoc}
*/
@NonNull
@Override
public Cursor performGet(@NonNull StorIOSQLite storIOSQLite, @NonNull RawQuery rawQuery) {
return storIOSQLite.internal().rawQuery(rawQuery);
}
/**
* {@inheritDoc}
*/
@NonNull
@Override
public Cursor performGet(@NonNull StorIOSQLite storIOSQLite, @NonNull Query query) {
return storIOSQLite.internal().query(query);
}
}
| apache-2.0 |
sapcc/monasca-thresh | thresh/src/main/java/monasca/thresh/infrastructure/thresholding/AlarmCreationBolt.java | 21643 | /*
* (C) Copyright 2014-2016 Hewlett Packard Enterprise Development Company LP.
*
* 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 monasca.thresh.infrastructure.thresholding;
import monasca.common.model.alarm.AlarmState;
import monasca.common.model.alarm.AlarmSubExpression;
import monasca.common.model.event.AlarmDefinitionDeletedEvent;
import monasca.common.model.event.AlarmDefinitionUpdatedEvent;
import monasca.common.model.event.AlarmDeletedEvent;
import monasca.common.model.metric.MetricDefinition;
import monasca.common.util.Injector;
import monasca.thresh.domain.model.Alarm;
import monasca.thresh.domain.model.AlarmDefinition;
import monasca.thresh.domain.model.MetricDefinitionAndTenantId;
import monasca.thresh.domain.model.SubAlarm;
import monasca.thresh.domain.model.SubExpression;
import monasca.thresh.domain.model.TenantIdAndMetricName;
import monasca.thresh.domain.service.AlarmDAO;
import monasca.thresh.domain.service.AlarmDefinitionDAO;
import monasca.thresh.infrastructure.persistence.PersistenceModule;
import monasca.thresh.utils.Logging;
import org.apache.storm.task.OutputCollector;
import org.apache.storm.task.TopologyContext;
import org.apache.storm.topology.OutputFieldsDeclarer;
import org.apache.storm.topology.base.BaseRichBolt;
import org.apache.storm.tuple.Fields;
import org.apache.storm.tuple.Tuple;
import org.apache.storm.tuple.Values;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
/**
* Handles creation of Alarms and Alarmed Metrics.
*/
public class AlarmCreationBolt extends BaseRichBolt {
private static final long serialVersionUID = 1096706128973976599L;
public static final String ALARM_CREATION_STREAM = "alarm-creation-stream";
public static final String[] ALARM_CREATION_FIELDS = new String[] {"control",
"tenantIdAndMetricName", "metricDefinitionAndTenantId", "alarmDefinitionId", "subAlarm"};
private transient Logger logger;
private DataSourceFactory dbConfig;
private final boolean keepAlarmDefs;
private transient AlarmDefinitionDAO alarmDefDAO;
private transient AlarmDAO alarmDAO;
private OutputCollector collector;
private final Map<String, List<Alarm>> waitingAlarms = new HashMap<>();
private final Map<String, List<Alarm>> alarmCache = new HashMap<>();
private final Map<String, AlarmDefinition> alarmDefinitionCache = new HashMap<>();
private static final List<Alarm> EMPTY_LIST = Collections.<Alarm>emptyList();
public AlarmCreationBolt(DataSourceFactory dbConfig, boolean keepAlarmDefs) {
this.dbConfig = dbConfig;
this.keepAlarmDefs = keepAlarmDefs;
}
public AlarmCreationBolt(AlarmDefinitionDAO alarmDefDAO,
AlarmDAO alarmDAO) {
this.alarmDefDAO = alarmDefDAO;
this.alarmDAO = alarmDAO;
this.keepAlarmDefs = false;
}
@Override
public void declareOutputFields(OutputFieldsDeclarer declarer) {
declarer.declareStream(ALARM_CREATION_STREAM, new Fields(ALARM_CREATION_FIELDS));
}
@Override
public void execute(Tuple tuple) {
logger.debug("tuple: {}", tuple);
try {
if (MetricFilteringBolt.NEW_METRIC_FOR_ALARM_DEFINITION_STREAM.equals(tuple.getSourceStreamId())) {
final MetricDefinitionAndTenantId metricDefinitionAndTenantId =
(MetricDefinitionAndTenantId) tuple.getValue(0);
handleNewMetricDefinition(metricDefinitionAndTenantId, tuple.getString(1));
} else if (EventProcessingBolt.METRIC_SUB_ALARM_EVENT_STREAM_ID.equals(tuple
.getSourceStreamId())) {
final String eventType = tuple.getString(0);
if (EventProcessingBolt.UPDATED.equals(eventType)) {
final SubExpression subExpression = (SubExpression) tuple.getValue(1);
final String alarmDefinitionId = tuple.getString(2);
updateSubAlarms(subExpression, alarmDefinitionId);
}
} else if (EventProcessingBolt.ALARM_DEFINITION_EVENT_STREAM_ID.equals(tuple.getSourceStreamId())) {
final String eventType = tuple.getString(0);
logger.debug("Received {} Event", eventType);
if (EventProcessingBolt.ALARM_DEFINITION_EVENT_STREAM_ID.equals(tuple.getSourceStreamId())) {
if (EventProcessingBolt.DELETED.equals(eventType)) {
final AlarmDefinitionDeletedEvent event =
(AlarmDefinitionDeletedEvent) tuple.getValue(1);
deleteAlarmDefinition(event.alarmDefinitionId);
}
else if (EventProcessingBolt.UPDATED.equals(eventType)) {
updateAlarmDefinition((AlarmDefinitionUpdatedEvent) tuple.getValue(1));
}
}
} else if (EventProcessingBolt.ALARM_EVENT_STREAM_ID.equals(tuple.getSourceStreamId())) {
final String eventType = tuple.getString(0);
if (EventProcessingBolt.DELETED.equals(eventType)) {
removeAlarm((AlarmDeletedEvent) tuple.getValue(2));
}
}
else {
logger.error("Received tuple on unknown stream {}", tuple);
}
} catch (Exception e) {
logger.error("Error processing tuple {}", tuple, e);
} finally {
collector.ack(tuple);
}
}
private void removeAlarm(AlarmDeletedEvent event) {
logger.debug("Deleting alarm {} for Alarm Definition {}", event.alarmId, event.alarmDefinitionId);
final List<Alarm> alarms = alarmCache.get(event.alarmDefinitionId);
if (alarms != null) {
for (final Alarm alarm : alarms) {
if (alarm.getId().equals(event.alarmId)) {
logger.debug("Deleted alarm {} for Alarm Definition {}", event.alarmId, event.alarmDefinitionId);
alarms.remove(alarm);
break;
}
}
}
}
private void updateSubAlarms(final SubExpression subExpression, final String alarmDefinitionId) {
logger.debug("Updating SubAlarms for AlarmDefinition Id {} SubExpression {}",
alarmDefinitionId, subExpression);
int count = 0;
if (alarmDefinitionCache.containsKey(alarmDefinitionId)) {
final List<Alarm> waiting = waitingAlarms.get(alarmDefinitionId);
if (waiting != null && !waiting.isEmpty()) {
for (final Alarm alarm : waiting) {
if (!alarm.updateSubAlarm(subExpression)) {
logger.error("Did not find SubAlarms for AlarmDefinition Id {} SubExpression {} Alarm {}",
alarmDefinitionId, subExpression, alarm);
}
count++;
}
}
}
logger.debug("Updated {} SubAlarms for AlarmDefinition Id {}", count, alarmDefinitionId);
}
private void updateAlarmDefinition(final AlarmDefinitionUpdatedEvent event) {
final AlarmDefinition alarmDefinition = alarmDefinitionCache.get(event.alarmDefinitionId);
if (alarmDefinition != null) {
logger.debug("Updating AlarmDefinition {}", event.alarmDefinitionId);
alarmDefinition.setName(event.alarmName);
alarmDefinition.setDescription(event.alarmDescription);
alarmDefinition.setActionsEnabled(event.alarmActionsEnabled);
alarmDefinition.setExpression(event.alarmExpression);
alarmDefinition.setSeverity(event.severity);
final List<String> newMatchBy;
if (event.matchBy == null) {
// The API can send NULL which means empty list
newMatchBy = new ArrayList<>(0);
}
else {
newMatchBy = event.matchBy;
}
if (!alarmDefinition.getMatchBy().equals(newMatchBy)) {
logger.error("AlarmDefinition {}: match-by changed, was {} now {}",
event.alarmDefinitionId, alarmDefinition.getMatchBy(), newMatchBy);
}
alarmDefinition.setMatchBy(newMatchBy); // Should never change
for (Map.Entry<String, AlarmSubExpression> entry : event.changedSubExpressions.entrySet()) {
if (!alarmDefinition.updateSubExpression(entry.getKey(), entry.getValue())) {
logger.error("AlarmDefinition {}: Did not finding matching SubAlarmExpression id={} SubAlarmExpression{}",
event.alarmDefinitionId, entry.getKey(), entry.getValue());
}
}
}
}
private void deleteAlarmDefinition(String alarmDefinitionId) {
logger.debug("Deleting AlarmDefinition {}", alarmDefinitionId);
final List<Alarm> waiting = waitingAlarms.remove(alarmDefinitionId);
if (waiting != null && !waiting.isEmpty()) {
logger.debug("{} waiting alarms removed for Alarm Definition Id {}", waiting != null
&& !waiting.isEmpty() ? waiting.size() : "No", alarmDefinitionId);
}
alarmCache.remove(alarmDefinitionId);
alarmDefinitionCache.remove(alarmDefinitionId);
alarmDAO.deleteByDefinitionId(alarmDefinitionId);
if(!keepAlarmDefs) {
alarmDefDAO.deleteByDefinitionId(alarmDefinitionId);
}
}
protected void handleNewMetricDefinition(
final MetricDefinitionAndTenantId metricDefinitionAndTenantId, final String alarmDefinitionId) {
final long start = System.currentTimeMillis();
final AlarmDefinition alarmDefinition = lookUpAlarmDefinition(alarmDefinitionId);
if (alarmDefinition == null) {
return;
}
if (!validMetricDefinition(alarmDefinition, metricDefinitionAndTenantId)) {
return;
}
final List<Alarm> existingAlarms = getExistingAlarms(alarmDefinitionId);
if (alreadyCreated(existingAlarms, metricDefinitionAndTenantId)) {
logger.warn("MetricDefinition {} is already in existing Alarm", metricDefinitionAndTenantId);
return;
}
if (alreadyCreated(getWaitingAlarmsForAlarmDefinition(alarmDefinition),
metricDefinitionAndTenantId)) {
logger.warn("MetricDefinition {} is already in waiting Alarm", metricDefinitionAndTenantId);
return;
}
final List<Alarm> matchingAlarms =
fitsInExistingAlarm(metricDefinitionAndTenantId, alarmDefinition, existingAlarms);
if (!matchingAlarms.isEmpty()) {
for (final Alarm matchingAlarm : matchingAlarms) {
logger.info("Metric {} fits into existing alarm {}", metricDefinitionAndTenantId,
matchingAlarm.getId());
addToExistingAlarm(matchingAlarm, metricDefinitionAndTenantId);
sendNewMetricDefinition(matchingAlarm, metricDefinitionAndTenantId);
}
} else {
final List<Alarm> newAlarms =
finishesAlarm(alarmDefinition, metricDefinitionAndTenantId, existingAlarms);
for (final Alarm newAlarm : newAlarms) {
logger.info("Metric {} finishes waiting alarm {}", metricDefinitionAndTenantId, newAlarm);
existingAlarms.add(newAlarm);
for (final MetricDefinitionAndTenantId md : newAlarm.getAlarmedMetrics()) {
sendNewMetricDefinition(newAlarm, md);
}
}
}
logger.debug("Total processing took {} milliseconds", System.currentTimeMillis() - start);
}
private List<Alarm> getExistingAlarms(final String alarmDefinitionId) {
List<Alarm> alarms = alarmCache.get(alarmDefinitionId);
if (alarms != null) {
return alarms;
}
final long start = System.currentTimeMillis();
alarms = alarmDAO.findForAlarmDefinitionId(alarmDefinitionId);
logger.info("Loading {} Alarms took {} milliseconds", alarms.size(), System.currentTimeMillis() - start);
alarmCache.put(alarmDefinitionId, alarms);
return alarms;
}
private List<Alarm> fitsInExistingAlarm(final MetricDefinitionAndTenantId metricDefinitionAndTenantId,
final AlarmDefinition alarmDefinition, final List<Alarm> existingAlarms) {
final List<Alarm> result = new LinkedList<>();
if (alarmDefinition.getMatchBy().isEmpty()) {
if (!existingAlarms.isEmpty()) {
result.add(existingAlarms.get(0));
}
}
else {
for (final Alarm alarm : existingAlarms) {
if (metricFitsInAlarm(alarm, alarmDefinition, metricDefinitionAndTenantId)) {
result.add(alarm);
}
}
}
return result;
}
private void addToExistingAlarm(Alarm existingAlarm,
MetricDefinitionAndTenantId metricDefinitionAndTenantId) {
existingAlarm.addAlarmedMetric(metricDefinitionAndTenantId);
final long start = System.currentTimeMillis();
alarmDAO.addAlarmedMetric(existingAlarm.getId(), metricDefinitionAndTenantId);
logger.debug("Add Alarm Metric took {} milliseconds", System.currentTimeMillis() - start);
}
private void sendNewMetricDefinition(Alarm existingAlarm,
MetricDefinitionAndTenantId metricDefinitionAndTenantId) {
for (final SubAlarm subAlarm : existingAlarm.getSubAlarms()) {
if (metricFitsInAlarmSubExpr(subAlarm.getExpression(),
metricDefinitionAndTenantId.metricDefinition)) {
final TenantIdAndMetricName timn = new TenantIdAndMetricName(metricDefinitionAndTenantId);
final Values values =
new Values(EventProcessingBolt.CREATED, timn, metricDefinitionAndTenantId,
existingAlarm.getAlarmDefinitionId(), subAlarm);
logger.debug("Emitting new SubAlarm {}", values);
collector.emit(ALARM_CREATION_STREAM, values);
}
}
}
public static boolean metricFitsInAlarmSubExpr(AlarmSubExpression subExpr,
MetricDefinition check) {
final MetricDefinition md = subExpr.getMetricDefinition();
if (!md.name.equals(check.name)) {
return false;
}
if ((md.dimensions != null) && !md.dimensions.isEmpty()) {
for (final Map.Entry<String, String> entry : md.dimensions.entrySet()) {
if (!entry.getValue().equals(check.dimensions.get(entry.getKey()))) {
return false;
}
}
}
return true;
}
protected boolean validMetricDefinition(AlarmDefinition alarmDefinition,
MetricDefinitionAndTenantId check) {
if (!alarmDefinition.getTenantId().equals(check.tenantId)) {
return false;
}
for (final AlarmSubExpression subExpr : alarmDefinition.getAlarmExpression()
.getSubExpressions()) {
if (metricFitsInAlarmSubExpr(subExpr, check.metricDefinition)) {
return true;
}
}
return false;
}
/**
* This is only used for testing
*
* @param alarmDefinitionId
* @return
*/
protected Integer countWaitingAlarms(final String alarmDefinitionId) {
final List<Alarm> waiting = waitingAlarms.get(alarmDefinitionId);
return waiting == null ? null: Integer.valueOf(waiting.size());
}
private List<Alarm> finishesAlarm(AlarmDefinition alarmDefinition,
MetricDefinitionAndTenantId metricDefinitionAndTenantId, List<Alarm> existingAlarms) {
final List<Alarm> waitingAlarms =
findMatchingWaitingAlarms(getWaitingAlarmsForAlarmDefinition(alarmDefinition),
alarmDefinition, metricDefinitionAndTenantId);
final List<Alarm> result = new LinkedList<>();
if (waitingAlarms.isEmpty()) {
final Alarm newAlarm = new Alarm(alarmDefinition);
newAlarm.addAlarmedMetric(metricDefinitionAndTenantId);
reuseExistingMetric(newAlarm, alarmDefinition, existingAlarms);
if (alarmIsComplete(newAlarm)) {
logger.debug("New alarm is complete. Saving");
saveAlarm(newAlarm);
result.add(newAlarm);
} else {
logger.debug("Adding new alarm to the waiting list");
addToWaitingAlarms(newAlarm, alarmDefinition);
}
} else {
for (final Alarm waiting : waitingAlarms) {
waiting.addAlarmedMetric(metricDefinitionAndTenantId);
if (alarmIsComplete(waiting)) {
removeFromWaitingAlarms(waiting, alarmDefinition);
saveAlarm(waiting);
result.add(waiting);
}
}
}
return result;
}
private void reuseExistingMetric(Alarm newAlarm, final AlarmDefinition alarmDefinition,
List<Alarm> existingAlarms) {
for (final Alarm existingAlarm : existingAlarms) {
for (final MetricDefinitionAndTenantId mtid : existingAlarm.getAlarmedMetrics()) {
if (metricFitsInAlarm(newAlarm, alarmDefinition, mtid)) {
newAlarm.addAlarmedMetric(mtid);
}
}
}
}
private void saveAlarm(Alarm newAlarm) {
final long start = System.currentTimeMillis();
alarmDAO.createAlarm(newAlarm);
logger.debug("Add Alarm took {} milliseconds", System.currentTimeMillis() - start);
}
private List<Alarm> findMatchingWaitingAlarms(List<Alarm> waiting, AlarmDefinition alarmDefinition,
MetricDefinitionAndTenantId check) {
final List<Alarm> result = new LinkedList<>();
for (final Alarm alarm : waiting) {
if (metricFitsInAlarm(alarm, alarmDefinition, check)) {
result.add(alarm);
}
}
return result;
}
protected boolean metricFitsInAlarm(final Alarm alarm, AlarmDefinition alarmDefinition,
MetricDefinitionAndTenantId check) {
final Map<String, String> matchesByValues = getMatchesByValues(alarmDefinition, alarm);
boolean result = false;
for (final SubAlarm subAlarm : alarm.getSubAlarms()) {
if (metricFitsInAlarmSubExpr(subAlarm.getExpression(), check.metricDefinition)) {
result = true;
if (!matchesByValues.isEmpty()) {
boolean foundOne = false;
for (final Map.Entry<String, String> entry : matchesByValues.entrySet()) {
final String value = check.metricDefinition.dimensions.get(entry.getKey());
if (value != null) {
if (!value.equals(entry.getValue())) {
return false;
}
foundOne = true;
}
}
if (!foundOne) {
return false;
}
}
}
}
return result;
}
private Map<String, String> getMatchesByValues(AlarmDefinition alarmDefinition, final Alarm alarm) {
final Map<String, String> matchesByValues = new HashMap<>();
if (!alarmDefinition.getMatchBy().isEmpty()) {
for (final MetricDefinitionAndTenantId md : alarm.getAlarmedMetrics()) {
for (final String matchBy : alarmDefinition.getMatchBy()) {
final String value = md.metricDefinition.dimensions.get(matchBy);
if (value != null) {
matchesByValues.put(matchBy, value);
}
}
}
}
return matchesByValues;
}
private void removeFromWaitingAlarms(Alarm toRemove, AlarmDefinition alarmDefinition) {
final List<Alarm> waiting = waitingAlarms.get(alarmDefinition.getId());
if ((waiting == null) || !waiting.remove(toRemove)) {
logger.error("Did not find Alarm to remove");
}
}
private void addToWaitingAlarms(Alarm newAlarm, AlarmDefinition alarmDefinition) {
List<Alarm> waiting = waitingAlarms.get(alarmDefinition.getId());
if (waiting == null) {
waiting = new LinkedList<>();
waitingAlarms.put(alarmDefinition.getId(), waiting);
}
waiting.add(newAlarm);
}
private List<Alarm> getWaitingAlarmsForAlarmDefinition(AlarmDefinition alarmDefinition) {
final List<Alarm> waiting = waitingAlarms.get(alarmDefinition.getId());
if (waiting == null) {
return EMPTY_LIST;
}
return waiting;
}
private boolean alarmIsComplete(Alarm newAlarm) {
for (final SubAlarm subAlarm : newAlarm.getSubAlarms()) {
boolean found = false;
for (final MetricDefinitionAndTenantId md : newAlarm.getAlarmedMetrics()) {
if (metricFitsInAlarmSubExpr(subAlarm.getExpression(), md.metricDefinition)) {
found = true;
break;
}
}
if (!found) {
return false;
}
}
return true;
}
private boolean alreadyCreated(List<Alarm> existingAlarms,
MetricDefinitionAndTenantId metricDefinitionAndTenantId) {
for (final Alarm alarm : existingAlarms) {
for (final MetricDefinitionAndTenantId md : alarm.getAlarmedMetrics()) {
if (md.equals(metricDefinitionAndTenantId)) {
return true;
}
}
}
return false;
}
private AlarmDefinition lookUpAlarmDefinition(String alarmDefinitionId) {
AlarmDefinition found = alarmDefinitionCache.get(alarmDefinitionId);
if (found != null) {
return found;
}
found = alarmDefDAO.findById(alarmDefinitionId);
if (found == null) {
logger.warn("Did not find AlarmDefinition for ID {}", alarmDefinitionId);
return null;
}
alarmDefinitionCache.put(found.getId(), found);
return found;
}
@Override
@SuppressWarnings("rawtypes")
public void prepare(Map stormConf, TopologyContext context, OutputCollector collector) {
logger = LoggerFactory.getLogger(Logging.categoryFor(getClass(), context));
logger.info("Preparing");
this.collector = collector;
if (alarmDefDAO == null) {
Injector.registerIfNotBound(AlarmDefinitionDAO.class, new PersistenceModule(dbConfig));
alarmDefDAO = Injector.getInstance(AlarmDefinitionDAO.class);
}
if (alarmDAO == null) {
Injector.registerIfNotBound(AlarmDAO.class, new PersistenceModule(dbConfig));
alarmDAO = Injector.getInstance(AlarmDAO.class);
}
}
/**
* Allow override of current time for testing.
*/
protected long getCurrentTime() {
return System.currentTimeMillis() / 1000;
}
}
| apache-2.0 |
liraz/gwt-backbone | gwt-backbone-validation/src/main/java/org/lirazs/gbackbone/validation/client/adapter/ModelStringArrayAdapter.java | 357 | package org.lirazs.gbackbone.validation.client.adapter;
import org.lirazs.gbackbone.client.core.model.Model;
/**
* Created on 12/02/2016.
*/
public class ModelStringArrayAdapter implements TargetDataAdapter<Model, String[]> {
@Override
public String[] getData(final Model model, String attribute) {
return model.get(attribute);
}
}
| apache-2.0 |
Syncleus/AetherMUD | src/main/java/com/syncleus/aethermud/server/model/AetherMudSession.java | 3595 | /**
* Copyright 2017 - 2018 Syncleus, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.syncleus.aethermud.server.model;
import com.syncleus.aethermud.command.commands.Command;
import com.syncleus.aethermud.common.AetherMudEntry;
import com.syncleus.aethermud.merchant.Merchant;
import com.google.common.base.Optional;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler;
import java.util.UUID;
public class AetherMudSession {
private java.util.Optional<String> username = java.util.Optional.empty();
private Optional<String> password = Optional.absent();
private boolean isAuthed = false;
private java.util.Optional<AetherMudEntry<UUID, Command>> grabMultiLineInput = java.util.Optional.empty();
private java.util.Optional<AetherMudEntry<Merchant, SimpleChannelUpstreamHandler>> grabMerchant = java.util.Optional.empty();
private String lastMessage;
private final Long initialLoginTime;
private Long lastActivity;
public AetherMudSession() {
long currentTime = System.currentTimeMillis();
this.initialLoginTime = currentTime;
this.lastActivity = currentTime;
}
public State state;
public enum State {
promptedForPassword,
promptedForUsername,
newUserPromptedForUsername,
newUserPromptedForPassword,
newUserRegCompleted,
authed
}
public String getLastMessage() {
return lastMessage;
}
public void setLastMessage(String lastMessage) {
this.lastMessage = lastMessage;
}
public java.util.Optional<String> getUsername() {
return username;
}
public void setUsername(java.util.Optional<String> username) {
this.username = username;
}
public Optional<String> getPassword() {
return password;
}
public void setPassword(Optional<String> password) {
this.password = password;
}
public boolean isAuthed() {
return isAuthed;
}
public void setAuthed(boolean isAuthed) {
this.isAuthed = isAuthed;
}
public void setState(State state) {
this.state = state;
}
public State getState() {
return state;
}
public java.util.Optional<AetherMudEntry<UUID, Command>> getGrabMultiLineInput() {
return grabMultiLineInput;
}
public void setGrabMultiLineInput(java.util.Optional<AetherMudEntry<UUID, Command>> grabMultiLineInput) {
this.grabMultiLineInput = grabMultiLineInput;
}
public java.util.Optional<AetherMudEntry<Merchant, SimpleChannelUpstreamHandler>> getGrabMerchant() {
return grabMerchant;
}
public void setGrabMerchant(java.util.Optional<AetherMudEntry<Merchant, SimpleChannelUpstreamHandler>> grabMerchant) {
this.grabMerchant = grabMerchant;
}
public Long getInitialLoginTime() {
return initialLoginTime;
}
public Long getLastActivity() {
return lastActivity;
}
public void setLastActivity(Long lastActivity) {
this.lastActivity = lastActivity;
}
}
| apache-2.0 |
thiagohp/generic-dao-hibernate | src/main/java/br/com/arsmachina/dao/hibernate/ReadableDAOImpl.java | 9368 | // Copyright 2007-2008 Thiago H. de Paula Figueiredo
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package br.com.arsmachina.dao.hibernate;
import java.io.Serializable;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.LockMode;
import org.hibernate.SessionFactory;
import org.hibernate.classic.Session;
import org.hibernate.criterion.Example;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import br.com.arsmachina.dao.ReadableDAO;
import br.com.arsmachina.dao.SortCriterion;
/**
* {@link ReadableDAO} implementation using Hibernate. All methods use {@link #getSession()} to get
* {@link Session}.
*
* @author Thiago H. de Paula Figueiredo
* @param <T> the entity class related to this DAO.
* @param <K> the type of the field that represents the entity class' primary key.
*/
public abstract class ReadableDAOImpl<T, K extends Serializable> extends BaseHibernateDAO<T, K>
implements ReadableDAO<T, K> {
/**
* A {@link SortCriterion} array with no elements.
*/
final public static SortCriterion[] EMPTY_SORTING_CRITERIA = new SortCriterion[0];
final private String defaultHqlOrderBy = toHqlOrderBy(getDefaultSortCriteria());
/**
* Returns a HQL <code>order by</code> clause given some {@link SortCriterion}s.
*
* @param sortCriteria {@link SortCriterion} instances.
* @return a {@link String}.
*/
final public static String toHqlOrderBy(SortCriterion... sortCriteria) {
String string = "";
if (sortCriteria.length > 0) {
StringBuilder builder = new StringBuilder(" ORDER BY ");
for (int i = 0; i < sortCriteria.length - 1; i++) {
builder.append(sortCriteria.toString());
builder.append(", ");
}
builder.append(sortCriteria[sortCriteria.length - 1]);
string = builder.toString();
}
return string;
}
/**
* Constructor that takes a {@link Class} and a {@link SessionFactory}.
*
* @param clasz a {@link Class}.
* @param sessionFactory a {@link SessionFactory}. It cannot be null.
*/
@SuppressWarnings("unchecked")
public ReadableDAOImpl(SessionFactory sessionFactory) {
super(null, sessionFactory);
}
/**
* Constructor that takes a {@link Class} and a {@link SessionFactory}.
*
* @param clasz a {@link Class}.
* @param sessionFactory a {@link SessionFactory}. It cannot be null.
*/
@SuppressWarnings("unchecked")
public ReadableDAOImpl(Class<T> clasz, SessionFactory sessionFactory) {
super(clasz, sessionFactory);
}
/**
* @see br.com.arsmachina.dao.ReadableDAO#countAll()
*/
public int countAll() {
final Criteria criteria = createCriteria();
criteria.setProjection(Projections.rowCount());
return (Integer) criteria.uniqueResult();
}
/**
* Returns all the entity class' objects. They are sorted according to
* {@link #getDefaultSortCriterions()}.
*
* @see br.com.arsmachina.dao.ReadableDAO#findAll()
* @see #getDefaultSortCriterions()
*/
@SuppressWarnings("unchecked")
public List<T> findAll() {
Criteria criteria = createCriteria();
addSortCriteria(criteria, getDefaultSortCriteria());
return criteria.list();
}
/**
* @see br.com.arsmachina.dao.ReadableDAO#findById(java.io.Serializable)
*/
@SuppressWarnings("unchecked")
public T findById(K id) {
return (T) getSession().get(getEntityClass(), id);
}
/**
* @see br.com.arsmachina.dao.ReadableDAO#findByIds(K[])
*/
@SuppressWarnings("unchecked")
public List<T> findByIds(K... ids) {
Criteria criteria = createCriteria();
criteria.add(Restrictions.in(getPrimaryKeyPropertyName(), ids));
return criteria.list();
}
/**
* @see br.com.arsmachina.dao.ReadableDAO#findByExample(java.lang.Object)
*/
@SuppressWarnings("unchecked")
public List<T> findByExample(T example) {
Criteria criteria = createCriteria();
if (example != null) {
criteria.add(createExample(example));
}
return criteria.list();
}
/**
* @see br.com.arsmachina.dao.WriteableDAO#refresh(java.lang.Object)
*/
public void refresh(T object) {
getSession().refresh(object);
}
/**
* If <code>sortingConstraints</code> is <code>null</code> or empty, this implementation
* sort the results by the {@link SortCriterion}s returned by
* {@link #getDefaultSortCriterions()}.
*
* @see br.com.arsmachina.dao.ReadableDAO#findAll(int, int,
* br.com.arsmachina.dao.SortCriterion[])
*/
@SuppressWarnings("unchecked")
public List<T> findAll(int firstResult, int maximumResults, SortCriterion... sortingConstraints) {
Criteria criteria = createCriteria();
criteria.setFirstResult(firstResult);
criteria.setMaxResults(maximumResults);
if (sortingConstraints == null || sortingConstraints.length == 0) {
sortingConstraints = getDefaultSortCriteria();
}
addSortCriteria(criteria, sortingConstraints);
return criteria.list();
}
/**
* Reattaches the object to the current {@link org.hibernate.Session} using
* <code>Session.lock(object, LockMode.NONE)</code> and then returns the object.
*
* @param a <code>T</code>.
* @return <code>object</code>.
* @see br.com.arsmachina.dao.ReadableDAO#reattach(java.lang.Object)
*/
public T reattach(T object) {
getSession().lock(object, LockMode.NONE);
return object;
}
/**
* Adds <code>sortCriteria</code> to a {@link Criteria} instance.
*
* @param criteria a {@link Criteria}. It cannot be null.
* @param sortCriteria a {@link SortCriterion}<code>...</code>. It cannot be null.
* @todo Support for property paths, not just property names.
*/
final public void addSortCriteria(Criteria criteria, SortCriterion... sortCriteria) {
assert criteria != null;
if (sortCriteria == null || sortCriteria.length == 0) {
sortCriteria = getDefaultSortCriteria();
}
for (SortCriterion sortingConstraint : sortCriteria) {
final String property = sortingConstraint.getProperty();
final boolean ascending = sortingConstraint.isAscending();
final Order order = ascending ? Order.asc(property) : Order.desc(property);
criteria.addOrder(order);
}
}
/**
* Adds the default sort criteria to a {@link Criteria} instance. This method just does
* <code>addSortCriteria(criteria, getDefaultSortCriteria());</code>.
*
* @param criteria a {@link Criteria}. It cannot be null.
*/
protected void addSortCriteria(Criteria criteria) {
addSortCriteria(criteria, getDefaultSortCriteria());
}
/**
* Returns the default {@link SortCriterion}s to be used to sort the objects lists returned by
* methods like {@link #findAll()} and {@link #findAll(int, int, SortCriterion...)} when no
* sorting constraints are given. This implementation returns {@link #EMPTY_SORTING_CRITERIA}.
*
* @return a {@link SortCriterion} array. It cannot be <code>null</code>.
*/
public SortCriterion[] getDefaultSortCriteria() {
return EMPTY_SORTING_CRITERIA;
}
/**
* Creates a {@link Criteria} for this entity class.
*
* @return a {@link Criteria}.
*/
public Criteria createCriteria() {
return getSession().createCriteria(getEntityClass());
}
/**
* Creates a {@link Criteria} for this entity class with given sort criteria.
*
* @return a {@link Criteria}.
*/
public Criteria createCriteria(SortCriterion ... sortCriteria) {
Criteria criteria = createCriteria();
addSortCriteria(criteria, sortCriteria);
return criteria;
}
/**
* Creates a {@link Criteria} for this entity class with given sort criteria,
* first result index and maximum number of results.
*
* @return a {@link Criteria}.
*/
public Criteria createCriteria(int firstIndex, int maximumResults, SortCriterion ... sortCriteria) {
Criteria criteria = createCriteria(sortCriteria);
criteria.setFirstResult(firstIndex);
criteria.setMaxResults(maximumResults);
return criteria;
}
/**
* Used by {@link #findByExample(Object)} to create an {@link Example} instance.
*
* @todo add criteria for property types not handled by Example (primary keys, associations,
* etc)
* @return an {@link Example}.
*/
public Example createExample(T entity) {
Example example = Example.create(entity);
example.enableLike(MatchMode.ANYWHERE);
example.excludeZeroes();
example.ignoreCase();
return example;
}
/**
* Returns the value of the <code>defaultHqlOrderBy</code> property.
*
* @return a {@link String}.
*/
public final String getDefaultHqlOrderBy() {
return defaultHqlOrderBy;
}
}
| apache-2.0 |
KleinerHacker/jcoding | src/main/java/org/pcsoft/framework/jcoding/exception/JCodingDescriptorValidationException.java | 514 | package org.pcsoft.framework.jcoding.exception;
import org.pcsoft.framework.jcoding.jobject.JObjectDescriptor;
/**
* Exception for java descriptor validation, see {@link JObjectDescriptor#validate()}
*/
public class JCodingDescriptorValidationException extends JCodingDescriptorException {
public JCodingDescriptorValidationException(String message) {
super(message);
}
public JCodingDescriptorValidationException(String message, Throwable cause) {
super(message, cause);
}
}
| apache-2.0 |
learning-layers/SocialSemanticServer | servs/coll/coll.datatypes/src/main/java/at/kc/tugraz/ss/service/coll/datatypes/pars/SSCollUserEntryDeletePar.java | 2251 | /**
* Code contributed to the Learning Layers project
* http://www.learning-layers.eu
* Development is partly funded by the FP7 Programme of the European Commission under
* Grant Agreement FP7-ICT-318209.
* Copyright (c) 2014, Graz University of Technology - KTI (Knowledge Technologies Institute).
* For a list of contributors see the AUTHORS file at the top-level directory of this distribution.
*
* 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 at.kc.tugraz.ss.service.coll.datatypes.pars;
import at.tugraz.sss.serv.util.*;
import at.tugraz.sss.serv.datatype.*;
import at.tugraz.sss.serv.datatype.par.SSServPar; import at.tugraz.sss.serv.util.*;
public class SSCollUserEntryDeletePar extends SSServPar{
public SSUri coll = null;
public SSUri entry = null;
public void setColl(final String coll) throws SSErr{
this.coll = SSUri.get(coll);
}
public void setEntry(final String entry) throws SSErr{
this.entry = SSUri.get(entry);
}
public String getColl(){
return SSStrU.removeTrailingSlash(coll);
}
public String getEntry(){
return SSStrU.removeTrailingSlash(entry);
}
public SSCollUserEntryDeletePar(){/* Do nothing because of only JSON Jackson needs this */ }
public SSCollUserEntryDeletePar(
final SSServPar servPar,
final SSUri user,
final SSUri coll,
final SSUri entry,
final boolean withUserRestriction,
final boolean shouldCommit){
super(SSVarNames.collEntryDelete, null, user, servPar.sqlCon);
this.coll = coll;
this.entry = entry;
this.withUserRestriction = withUserRestriction;
this.shouldCommit = shouldCommit;
}
} | apache-2.0 |
lilianaziolek/neo4j-apoc-procedures | src/main/java/apoc/result/VirtualNode.java | 7154 | package apoc.result;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.Collectors;
import org.neo4j.graphdb.Direction;
import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.Label;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.Relationship;
import org.neo4j.graphdb.RelationshipType;
import org.neo4j.helpers.collection.FilteringIterable;
import org.neo4j.helpers.collection.Iterables;
import org.neo4j.helpers.collection.Iterators;
import static java.util.Arrays.asList;
/**
* @author mh
* @since 16.03.16
*/
public class VirtualNode implements Node {
private static AtomicLong MIN_ID = new AtomicLong(-1);
private final List<Label> labels = new ArrayList<Label>();
private final Map<String, Object> props = new HashMap<>();
private final List<Relationship> rels = new ArrayList<>();
private final GraphDatabaseService db;
private final long id;
public VirtualNode(Label[] labels, Map<String, Object> props, GraphDatabaseService db) {
this.id = MIN_ID.getAndDecrement();
this.db = db;
this.labels.addAll(asList(labels));
this.props.putAll(props);
}
public VirtualNode(long nodeId, GraphDatabaseService db) {
this.id = nodeId;
this.db = db;
}
@Override
public long getId() {
return id;
}
@Override
public void delete() {
for (Relationship rel : rels) {
rel.delete();
}
}
@Override
public Iterable<Relationship> getRelationships() {
return rels;
}
@Override
public boolean hasRelationship() {
return !rels.isEmpty();
}
@Override
public Iterable<Relationship> getRelationships(RelationshipType... relationshipTypes) {
return new FilteringIterable<>(rels, (r) -> isType(r, relationshipTypes));
}
private boolean isType(Relationship r, RelationshipType... relationshipTypes) {
for (RelationshipType type : relationshipTypes) {
if (r.isType(type)) return true;
}
return false;
}
@Override
public Iterable<Relationship> getRelationships(Direction direction, RelationshipType... relationshipTypes) {
return new FilteringIterable<>(rels, (r) -> isType(r, relationshipTypes) && isDirection(r, direction));
}
private boolean isDirection(Relationship r, Direction direction) {
return direction == Direction.BOTH || direction == Direction.OUTGOING && r.getStartNode().equals(this) || direction == Direction.INCOMING && r.getEndNode().equals(this);
}
@Override
public boolean hasRelationship(RelationshipType... relationshipTypes) {
return getRelationships(relationshipTypes).iterator().hasNext();
}
@Override
public boolean hasRelationship(Direction direction, RelationshipType... relationshipTypes) {
return getRelationships(direction, relationshipTypes).iterator().hasNext();
}
@Override
public Iterable<Relationship> getRelationships(Direction direction) {
return new FilteringIterable<>(rels, (r) -> isDirection(r, direction));
}
@Override
public boolean hasRelationship(Direction direction) {
return getRelationships(direction).iterator().hasNext();
}
@Override
public Iterable<Relationship> getRelationships(RelationshipType relationshipType, Direction direction) {
return new FilteringIterable<>(rels, (r) -> isType(r, relationshipType) && isDirection(r, direction));
}
@Override
public boolean hasRelationship(RelationshipType relationshipType, Direction direction) {
return getRelationships(relationshipType, direction).iterator().hasNext();
}
@Override
public Relationship getSingleRelationship(RelationshipType relationshipType, Direction direction) {
return Iterables.single(getRelationships(relationshipType, direction));
}
@Override
public Relationship createRelationshipTo(Node node, RelationshipType relationshipType) {
VirtualRelationship rel = new VirtualRelationship(this, node, relationshipType);
rels.add(rel);
return rel;
}
@Override
public Iterable<RelationshipType> getRelationshipTypes() {
return rels.stream().map(Relationship::getType).collect(Collectors.toList());
}
@Override
public int getDegree() {
return (int) rels.size();
}
@Override
public int getDegree(RelationshipType relationshipType) {
return (int) Iterables.count(getRelationships(relationshipType));
}
@Override
public int getDegree(Direction direction) {
return (int) Iterables.count(getRelationships(direction));
}
@Override
public int getDegree(RelationshipType relationshipType, Direction direction) {
return (int) Iterables.count(getRelationships(relationshipType,direction));
}
@Override
public void addLabel(Label label) {
labels.add(label);
}
@Override
public void removeLabel(Label label) {
for (Iterator<Label> iterator = labels.iterator(); iterator.hasNext(); ) {
Label next = iterator.next();
if (next.name().equals(label.name())) iterator.remove();
}
}
@Override
public boolean hasLabel(Label label) {
for (Label l : labels) {
if (l.name().equals(label.name())) return true;
}
return false;
}
@Override
public Iterable<Label> getLabels() {
return labels;
}
@Override
public GraphDatabaseService getGraphDatabase() {
return db;
}
@Override
public boolean hasProperty(String s) {
return props.containsKey(s);
}
@Override
public Object getProperty(String s) {
return props.get(s);
}
@Override
public Object getProperty(String s, Object o) {
Object value = props.get(s);
return value == null ? o : value;
}
@Override
public void setProperty(String s, Object o) {
props.put(s,o);
}
@Override
public Object removeProperty(String s) {
return props.remove(s);
}
@Override
public Iterable<String> getPropertyKeys() {
return props.keySet();
}
@Override
public Map<String, Object> getProperties(String... strings) {
HashMap<String, Object> res = new HashMap<>(props);
res.keySet().retainAll(asList(strings));
return res;
}
@Override
public Map<String, Object> getAllProperties() {
return props;
}
void delete(Relationship rel) {
rels.remove(rel);
}
@Override
public boolean equals(Object o) {
return this == o || o instanceof Node && id == ((Node) o).getId();
}
@Override
public int hashCode() {
return (int) (id ^ (id >>> 32));
}
@Override
public String toString()
{
return "VirtualNode{" + "labels=" + labels + ", props=" + props + ", rels=" + rels + '}';
}
}
| apache-2.0 |
cloudfoundry/cf-java-client | cloudfoundry-client/src/main/java/org/cloudfoundry/client/v3/applications/_TerminateApplicationInstanceRequest.java | 1180 | /*
* Copyright 2013-2021 the original author or authors.
*
* 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.cloudfoundry.client.v3.applications;
import com.fasterxml.jackson.annotation.JsonIgnore;
import org.immutables.value.Value;
/**
* The request payload for the Delete Application Process Instance operation
*/
@Value.Immutable
abstract class _TerminateApplicationInstanceRequest {
/**
* The application id
*/
@JsonIgnore
abstract String getApplicationId();
/**
* The index
*/
@JsonIgnore
abstract String getIndex();
/**
* The type
*/
@JsonIgnore
abstract String getType();
}
| apache-2.0 |
davidbeloo/FilterDrawer | app/src/main/java/com/thepinkandroid/filterdrawer/models/Category.java | 536 | package com.thepinkandroid.filterdrawer.models;
/**
* Created by DAVID-WORK on 22/11/2015.
*/
public class Category
{
private int mCode;
private String mName;
public Category(int code, String name)
{
mCode = code;
mName = name;
}
public int getCode()
{
return mCode;
}
public void setCode(int code)
{
mCode = code;
}
public String getName()
{
return mName;
}
public void setName(String name)
{
mName = name;
}
}
| apache-2.0 |
Akeshihiro/dsworkbench | Core/src/main/java/de/tor/tribes/php/UnitTableInterface.java | 3563 | /*
* Copyright 2015 Torridity.
*
* 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 de.tor.tribes.php;
import de.tor.tribes.io.DataHolder;
import de.tor.tribes.io.UnitHolder;
import de.tor.tribes.types.UnknownUnit;
import java.util.Hashtable;
/**
*
* @author Torridity
*/
public class UnitTableInterface {
private static final String[] units = new String[]{"spear", "sword", "axe", "archer", "spy", "light", "marcher", "heavy", "ram", "catapult", "knight", "snob", "militia"};
public static String createAttackerUnitTableLink(Hashtable<UnitHolder, Integer> pIn, Hashtable<UnitHolder, Integer> pOut) {
return createUnitTableLink(pIn, pOut, false);
}
public static String createAttackerUnitTableLink(Hashtable<UnitHolder, Integer> pIn) {
return createUnitTableLink(pIn, false);
}
public static String createDefenderUnitTableLink(Hashtable<UnitHolder, Integer> pIn, Hashtable<UnitHolder, Integer> pOut) {
return createUnitTableLink(pIn, pOut, true);
}
public static String createDefenderUnitTableLink(Hashtable<UnitHolder, Integer> pIn) {
return createUnitTableLink(pIn, false);
}
public static String createUnitTableLink(Hashtable<UnitHolder, Integer> pIn, Hashtable<UnitHolder, Integer> pOut, boolean pMilitia) {
StringBuilder b = new StringBuilder();
b.append("http://torridity.de/dsworkbench/unitTable.php?in=");
for (int i = 0; i < units.length; i++) {
UnitHolder u = DataHolder.getSingleton().getUnitByPlainName(units[i]);
if (!u.equals(UnknownUnit.getSingleton()) && (pMilitia || !u.getPlainName().equals("militia"))) {
Integer amount = pIn.get(u);
b.append(i).append(".").append((amount == null) ? 0 : amount);
if (i < units.length - 1) {
b.append("_");
}
}
}
b.append("&out=");
for (int i = 0; i < units.length; i++) {
UnitHolder u = DataHolder.getSingleton().getUnitByPlainName(units[i]);
if (!u.equals(UnknownUnit.getSingleton()) && (pMilitia || !u.getPlainName().equals("militia"))) {
Integer amount = pOut.get(u);
b.append(i).append(".").append((amount == null) ? 0 : amount);
b.append("_");
}
}
String result = b.toString();
return result.substring(0, result.length() - 1);
}
public static String createUnitTableLink(Hashtable<UnitHolder, Integer> pIn, boolean pMilitia) {
StringBuilder b = new StringBuilder();
b.append("http://torridity.de/dsworkbench/unitTable.php?in=");
for (int i = 0; i < units.length; i++) {
UnitHolder u = DataHolder.getSingleton().getUnitByPlainName(units[i]);
if (!u.equals(UnknownUnit.getSingleton()) && (pMilitia || !u.getPlainName().equals("militia"))) {
Integer amount = pIn.get(u);
b.append(i).append(".").append((amount == null) ? 0 : amount);
b.append("_");
}
}
String result = b.toString();
return result.substring(0, result.length() - 1);
}
}
| apache-2.0 |
dylanswartz/nakamura | libraries/utils/src/main/java/org/sakaiproject/nakamura/api/util/LocaleUtils.java | 3178 | /**
* Licensed to the Sakai Foundation (SF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The SF 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.sakaiproject.nakamura.api.util;
import org.sakaiproject.nakamura.api.lite.authorizable.Authorizable;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;
public interface LocaleUtils {
public static final String DEFAULT_LANGUAGE = "en";
public static final String DEFAULT_COUNTRY = "US";
/**
* Get a valid {@link Locale}. Checks <code>authorizable</code> for a locale setting.
* Defaults to the server configured language and country code.
*
* @param authorizable
* @return
*/
public abstract Locale getLocale(final Authorizable authorizable);
/**
* Get a valid {@link Locale}. Checks <code>properties</code> for a locale setting.
* Defaults to the server configured language and country code.
*
* @param properties
* @return
*/
public abstract Locale getLocale(final Map<String, Object> properties);
/**
* Get a TimeZone the user has selected for the default TimeZone.
*
* @param authorizable
* @return
*/
public abstract TimeZone getTimeZone(final Authorizable authorizable);
/**
* Get a TimeZone the user has selected for the default TimeZone.
*
* @param properties
* @return
*/
public abstract TimeZone getTimeZone(final Map<String, Object> properties);
/**
* Safe read the properties from an {@link Authorizable}. Useful if you want to parse
* properties once and then pass to {@link #getLocale(Map)} and
* {@link #getTimeZone(Map)} methods.
* <p>
* Copied from LiteMeServlet#getProperties(Authorizable authorizable)
*
* @param authorizable
* @return In a worst case it will return an empty Map (i.e. never null).
*/
public abstract Map<String, Object> getProperties(Authorizable authorizable);
/**
* Helper method to return ISO3Country
*
* @param locale
* @return empty string if not available (i.e. never null)
*/
public abstract String getIso3Country(final Locale locale);
/**
* Helper method to return ISO3Language
*
* @param locale
* @return empty string if not available (i.e. never null)
*/
public abstract String getIso3Language(final Locale locale);
/**
* Helper method to calculate GMT offset consistently across bundles.
*
* @param timezone
* @return number of hours offset from GMT
*/
public abstract int getOffset(final TimeZone timezone);
} | apache-2.0 |
vam-google/google-cloud-java | google-cloud-clients/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/SchemaTest.java | 2293 | /*
* Copyright 2015 Google LLC
*
* 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.google.cloud.bigquery;
import static org.junit.Assert.assertEquals;
import com.google.api.services.bigquery.model.TableSchema;
import com.google.common.collect.ImmutableList;
import java.util.List;
import org.junit.Test;
public class SchemaTest {
private static final Field FIELD_SCHEMA1 =
Field.newBuilder("StringField", LegacySQLTypeName.STRING)
.setMode(Field.Mode.NULLABLE)
.setDescription("FieldDescription1")
.build();
private static final Field FIELD_SCHEMA2 =
Field.newBuilder("IntegerField", LegacySQLTypeName.INTEGER)
.setMode(Field.Mode.REPEATED)
.setDescription("FieldDescription2")
.build();
private static final Field FIELD_SCHEMA3 =
Field.newBuilder("RecordField", LegacySQLTypeName.RECORD, FIELD_SCHEMA1, FIELD_SCHEMA2)
.setMode(Field.Mode.REQUIRED)
.setDescription("FieldDescription3")
.build();
private static final List<Field> FIELDS =
ImmutableList.of(FIELD_SCHEMA1, FIELD_SCHEMA2, FIELD_SCHEMA3);
private static final Schema TABLE_SCHEMA = Schema.of(FIELDS);
@Test
public void testOf() {
compareTableSchema(TABLE_SCHEMA, Schema.of(FIELDS));
}
@Test
public void testToAndFromPb() {
compareTableSchema(TABLE_SCHEMA, Schema.fromPb(TABLE_SCHEMA.toPb()));
}
private void compareTableSchema(Schema expected, Schema value) {
assertEquals(expected, value);
assertEquals(expected.getFields(), value.getFields());
}
@Test
public void testEmptySchema() {
TableSchema tableSchema = new TableSchema();
Schema schema = Schema.fromPb(tableSchema);
assertEquals(0, schema.getFields().size());
}
}
| apache-2.0 |
hzl1994/coolweather | app/src/main/java/com/coolweather/android/util/Utility.java | 3587 | package com.coolweather.android.util;
import android.text.TextUtils;
import com.coolweather.android.db.City;
import com.coolweather.android.db.County;
import com.coolweather.android.db.Province;
import com.coolweather.android.gson.Weather;
import com.google.gson.Gson;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
/**
* Created by 黄智龙 on 2017/3/8.
*/
public class Utility {
/**
* 解析和处理服务器返回的省级数据
*/
public static boolean handleProvinceResponse(String response){
if(!TextUtils.isEmpty(response)){
try{
JSONArray allProvinces = new JSONArray(response);
for (int i = 0; i < allProvinces.length(); i++) {
JSONObject provinceObject = allProvinces.getJSONObject(i);
Province province = new Province();
province.setProvinceName(provinceObject.getString("name"));
province.setProvinceCode(provinceObject.getInt("id"));
province.save();//将数据保存到数据库中
}
return true;
}catch (JSONException e){
e.printStackTrace();
}
}
return false;
}
/**
* 解析和处理服务器返回的市级数据
*/
public static boolean handleCityResponse(String response,int provinceId){
if(!TextUtils.isEmpty(response)){
try{
JSONArray allCitys = new JSONArray(response);
for (int i = 0; i < allCitys.length(); i++) {
JSONObject cityObject = allCitys.getJSONObject(i);
City city = new City();
city.setCityName(cityObject.getString("name"));
city.setCityCode(cityObject.getInt("id"));
city.setProvinceId(provinceId);
city.save();//将数据保存到数据库中
}
return true;
}catch (JSONException e){
e.printStackTrace();
}
}
return false;
}
/**
* 解析和处理服务器返回的县级数据
*/
public static boolean handleCountyResponse(String response,int cityId){
if(!TextUtils.isEmpty(response)){
try{
JSONArray allCounty = new JSONArray(response);
for (int i = 0; i < allCounty.length(); i++) {
JSONObject countyObject = allCounty.getJSONObject(i);
County county = new County();
county.setCountyName(countyObject.getString("name"));
county.setWeatherId(countyObject.getString("weather_id"));
county.setCityId(cityId);
county.save();//将数据保存到数据库中
}
return true;
}catch (JSONException e){
e.printStackTrace();
}
}
return false;
}
/**
* 将返回的JSON数据解析成weather实体类
*/
public static Weather handleWeatherResponse(String response){
try{
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("HeWeather");
String weatherContent = jsonArray.getJSONObject(0).toString();
return new Gson().fromJson(weatherContent,Weather.class);
}catch (Exception e){
e.printStackTrace();
}
return null;
}
}
| apache-2.0 |
Camelion/nasc-decompiler | src/main/scala/ru/jts/decompiler/model/Npc.java | 52607 | /*
* Copyright 2015-2017 JTS
*
* 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 ru.jts.decompiler.model;
import ru.jts.decompiler.annotation.EventId;
import java.util.List;
/**
* Created by Дмитрий on 12.05.2015.
*/
public class Npc {
@EventId(1040)
public int p_state;
@EventId(1048)
public int i_quest0;
@EventId(1056)
public int i_quest1;
@EventId(1064)
public int i_quest2;
@EventId(1072)
public int i_quest3;
@EventId(1080)
public int i_quest4;
@EventId(1088)
public int i_quest5;
@EventId(1096)
public int i_quest6;
@EventId(1104)
public int i_quest7;
@EventId(1112)
public int i_quest8;
@EventId(1120)
public int i_quest9;
@EventId(1128)
public int i_ai0;
@EventId(1136)
public int i_ai1;
@EventId(1144)
public int i_ai2;
@EventId(1152)
public int i_ai3;
@EventId(1160)
public int i_ai4;
@EventId(1168)
public int i_ai5;
@EventId(1176)
public int i_ai6;
@EventId(1184)
public int i_ai7;
@EventId(1192)
public int i_ai8;
@EventId(1200)
public int i_ai9;
@EventId(1208)
public int attack_tick;
@EventId(1216)
public Creature c_quest0;
@EventId(1224)
public Creature c_quest1;
@EventId(1232)
public Creature c_quest2;
@EventId(1240)
public Creature c_quest3;
@EventId(1248)
public Creature c_quest4;
@EventId(1256)
public Creature c_ai0;
@EventId(1264)
public Creature c_ai1;
@EventId(1272)
public Creature c_ai2;
@EventId(1280)
public Creature c_ai3;
@EventId(1288)
public Creature c_ai4;
@EventId(1464)
public IntList int_list;
@EventId(1472)
public int m_WorldTrapState;
@EventId(1480)
public Creature sm;
@EventId(1488)
public Creature master;
@EventId(1496)
public Creature boss;
@EventId(1504)
public Creature top_desire_target;
@EventId(1524)
public int start_x;
@EventId(1528)
public int start_y;
@EventId(1532)
public int start_z;
@EventId(1620)
public int sit_on_stop;
@EventId(1360)
public AtomicValue av_quest0;
// FUNCTIONS
@EventId(235012172)
public void ShowPage(Creature talker, String page) {
}
@EventId(234946563)
public boolean IsNullParty(Party party) {
return party == null;
}
@EventId(234946601)
public int GetDirectionToTarget(Creature creature) {
return 0;
}
@EventId(235012672)
public void Whisper(Creature creature, String msg) {
}
@EventId(234946797)
public int Skill_GetAbnormalType(int skillId) {
return 0;
}
@EventId(235012606)
public void Dispel(Creature creature, int abnormal_type) {
}
@EventId(235012143)
public void AddTimerEx(int timer_id, int delay) {
}
@EventId(235602168)
public int CreateOnePrivateEx(int npc_id, String ai_type, int i1, int i2, int x, int y, int z, int heading, int i7,
int i8, int i9) {
return 0;
}
@EventId(235143192)
public void AddEffectActionDesire(Creature creature, int action_id, int i1, double point) {
}
@EventId(234881209)
public int Castle_GetPledgeId() {
return 0;
}
@EventId(235012239)
public void FHTML_SetFileName(FHTML fhtml, String filename) {
}
@EventId(235077776)
public void FHTML_SetInt(FHTML fhtml, String find, int replacement) {
}
@EventId(234881184)
public String Castle_GetPledgeName() {
return "";
}
@EventId(234881185)
public String Castle_GetOwnerName() {
return "";
}
@EventId(234881188)
public int Residence_GetTaxRateCurrent() {
return 0;
}
@EventId(235012243)
public void ShowFHTML(Creature creature, FHTML fhtml) {
}
@EventId(235012190)
public void ShowMultisell(int multisell_id, Creature talker) {
}
@EventId(234947032)
public void ShowVariationMakeWindow(Creature talker) {
}
@EventId(234947033)
public void ShowVariationCancelWindow(Creature talker) {
}
@EventId(235078121)
public void InstantZone_Enter(Creature talker, int zone_type, int enter_type) {
}
@EventId(234947050)
public void InstantZone_Leave(Creature talker) {
}
@EventId(234947051)
public void InstantZone_Finish(int delay) {
}
@EventId(235012216)
public Creature GetMemberOfParty(Party party, int index) {
return null;
}
@EventId(235012323)
public boolean IsInCategory(int category_id, int cat) {
return false;
}
@EventId(235012210)
public int GetOneTimeQuestFlag(Creature creature, int quest) {
return 0;
}
@EventId(234946686)
public Clan GetPledge(Creature creature) {
return null;
}
@EventId(234946561)
public boolean IsNullCreature(Creature creature) {
return false;
}
@EventId(234946719)
public boolean IsMyLord(Creature creature) {
return false;
}
@EventId(234881200)
public boolean Castle_IsUnderSiege() {
return false;
}
@EventId(234881206)
public int Castle_GetRawSiegeTime() {
return 0;
}
@EventId(234881207)
public int Castle_GetRawSystemTime() {
return 0;
}
@EventId(234946679)
public Creature GetLeaderOfParty(Party party) {
return null;
}
@EventId(235077772)
public void DeleteItem1(Creature talker, int itemId, long count) {
}
@EventId(235077769)
public void GiveItem1(Creature talker, int itemId, int count) {
}
@EventId(235077743)
public void SetFlagJournal(Creature talker, int quest, int state) {
}
@EventId(235012493)
public void ShowQuestMark(Creature talker, int quest) {
}
@EventId(235012350)
public void SoundEffect(Creature talker, String sound) {
}
@EventId(234946925)
public int GetSSQSealOwner(int seal) {
return 0;
}
@EventId(234881387)
public int GetSSQStatus() {
return 0;
}
@EventId(235012386)
public void RideWyvern(Creature talker, int wyvern) {
}
@EventId(235012534)
public void CastBuffForQuestReward(Creature talker, int skill_id) {
}
@EventId(234946663)
public void OpenHennaItemListForEquip(Creature talker) {
}
@EventId(234946664)
public void OpenHennaListForUnquip(Creature talker) {
}
@EventId(235077640)
public void AddAttackDesire(Creature talker, int desire_id, double point) {
}
@EventId(235143191)
public void AddMoveToDesire(int x, int y, int z, double point) {
}
@EventId(235012103)
public void AddDoNothingDesire(int unk, double point) {
}
@EventId(235012101)
public void AddMoveAroundDesire(int unk, double point) {
}
@EventId(235208724)
public void AddUseSkillDesire(Creature talker, int skill_id, int unk1, int unk2, double point) {
}
@EventId(234946821)
public boolean InMyTerritory(Creature creature) {
return false;
}
@EventId(235143256)
public void InstantTeleport(Creature creature, int x, int y, int z) {
}
@EventId(234881114)
public void InstantRandomTeleportInMyTerritory() {
}
@EventId(235143187)
public void AddMoveToWayPointDesire(WayPointsType wayPointsType, WayPointDelaysType wayPointDelaysType, int index,
double point) {
}
@EventId(235012197)
public int GetWayPointDelay(WayPointDelaysType wayPointDelays, int way_point_index) {
return 0;
}
@EventId(234947026)
public int GetPledgeMemberCount(Creature talekr) {
return 0;
}
@EventId(234947132)
public int IsLordOfCastle(Creature talker) {
return 0;
}
@EventId(235077884)
public void IncrementParam(Creature talker, int param, int value) {
}
@EventId(235012369)
public void PledgeLevelUp(Creature talker, int level) {
}
@EventId(234946795)
public int Skill_GetConsumeMP(int skill_id) {
return 0;
}
@EventId(234946794)
public int Skill_GetConsumeHP(int skill_id) {
return 0;
}
@EventId(234946799)
public int Skill_InReuseDelay(int skill_id) {
return 0;
}
@EventId(234947019)
public int OwnPledgeNameValue(Creature talker) {
return 0;
}
@EventId(235012554)
public void UpdatePledgeNameValue(Creature talker, int value) {
}
@EventId(234947101)
public boolean IsDominionOfLord(int dominion_id) {
return false;
}
@EventId(234947023)
public boolean HasAcademy(Creature talker) {
return false;
}
@EventId(235012214)
public boolean HavePledgePower(Creature talker, int unk) {
return false;
}
@EventId(235012556)
public void CreateAcademy(Creature talker, String name) {
}
@EventId(235012558)
public boolean HasSubPledge(Creature talker, int unk) {
return false;
}
@EventId(235143629)
public void CreateSubPledge(Creature talker, int unk1, int unk2, String name) {
}
@EventId(235143394)
public void ShowGrowEtcSkillMessage(Creature talker, int skill_name_id, int unk1, String unk2) {
}
@EventId(235077857)
public void ShowEtcSkillList(Creature talker, int unk1, String unk2) {
}
@EventId(234947055)
public void ShowChangePledgeNameUI(Creature talker) {
}
@EventId(234946564)
public boolean IsNullString(String str) {
return false;
}
@EventId(234946710)
public int GetPledgeSkillLevel(Creature talker) {
return 0;
}
@EventId(235012174)
public void ShowSystemMessage(Creature talker, int msg_id) {
}
@EventId(235077747)
public void SetOneTimeQuestFlag(Creature talker, int quest_num, int flag) {
}
@EventId(235012212)
public int GetInventoryInfo(Creature talker, int param) {
return 0;
}
@EventId(235012324)
public void ClassChange(Creature talker, int class_lv) {
}
@EventId(234947013)
public boolean IsAcademyMember(Creature talker) {
return false;
}
@EventId(234946616)
public Creature GetSummon(Creature talker) {
return null;
}
@EventId(235077931)
public void GetSubJobList(Creature talker, int unk1, int state) {
}
@EventId(235012397)
public void ChangeSubJob(Creature talker, int subjob) {
}
@EventId(235012396)
public void CreateSubJob(Creature talker, int subjob) {
}
@EventId(235077934)
public void RenewSubJob(Creature talker, int unk, int subjob) {
}
@EventId(235012316)
public void ShowSkillList(Creature talker, String str) {
}
@EventId(235077854)
public void ShowGrowSkillMessage(Creature talker, int skill_name_id, String unk) {
}
@EventId(235012317)
public void ShowEnchantSkillList(Creature talker, int action_id) {
}
@EventId(234946626)
public void Say(String str) {
}
@EventId(235078117)
public void ShowEnchantSkillListDrawer(Creature talker, int skill_name_id, int action_id) {
}
@EventId(235077856)
public void ShowEnchantSkillMessage(Creature talker, int skill_name_id, int action_id) {
}
@EventId(235012607)
public void DeleteAcquireSkills(Creature talker, int unk) {
}
@EventId(235143646)
public void AddLogByNpc(int unk, Creature talker, int unk1, int unk2) {
}
@EventId(234947057)
public int GetPledgeCastleSiegeDefenceCount(Creature talker) {
return 0;
}
@EventId(235209202)
public void GiveItemByCastleSiegeDefence(Creature talker, int unk1, int unk2, int unk3, int unk4) {
}
@EventId(235143261)
public void ShowBuySell(Creature talker, BuySellItemInfo[] Buylist, BuySellItemInfo[] SellList, int unk) {
}
@EventId(235274332)
public void SellPreview(Creature talker, BuySellItemInfo[] SellList, String shopName, String html, String unk1,
String unk2) {
}
@EventId(235012237)
public ItemData GetItemData(Creature talker, int item_id) {
return null;
}
@EventId(235143454)
public void CreatePet(Creature talker, int item_id, int unk1, int unk2) {
}
@EventId(235012175)
public void ShowSystemMessageStr(Creature target, String fString) {
}
@EventId(234946656)
public int DistFromMe(Creature creature) {
return 0;
}
@EventId(235012385)
public void EvolvePetWithSameExp(Creature creature, int unk1) {
}
@EventId(235274527)
public void EvolvePet(Creature talker, int item_dbid, int class_id_baby_pet, int item_grown_pet,
int class_id_grown_pet,
int item_pet_level) {
}
@EventId(234946734)
public void Castle_GateOpenClose(int value) {
}
@EventId(234881282)
public void Despawn() {
}
@EventId(234947075)
public int GetPVPPoint(Creature talker) {
return 0;
}
@EventId(235012609)
public void UpdatePVPPoint(Creature talker, int diff) {
}
@EventId(234946980)
public void SetNobless(Creature talker) {
}
@EventId(234946955)
public boolean IsNewbie(Creature talker) {
return false;
}
@EventId(234881473)
public int GetFishingEventRewardRemainTime() {
return 0;
}
@EventId(234947012)
public void GiveFishingEventPrize(Creature talker) {
}
@EventId(234947011)
public void ShowHtmlFishingEventRanking(Creature talker) {
}
@EventId(234947010)
public int GetFishingEventRanking(Creature talker) {
return 0;
}
@EventId(235012450)
public void ShowSellSeedList(Creature talker, int manor_id) {
}
@EventId(235012451)
public void ShowProcureCropList(Creature talker, int manor_id) {
}
@EventId(235012432)
public int GetCurrentSeedSellCountSet(int state, int index) {
return 0;
}
@EventId(235012434)
public int GetCurrentSeedPrice(int state, int index) {
return 0;
}
@EventId(235012433)
public int GetCurrentSeedRemainCount(int state, int index) {
return 0;
}
@EventId(235012443)
public int GetRemainProcureCropCount(int manor_id, int index) {
return 0;
}
@EventId(235012441)
public int GetProcurementCount(int manor_id, int index) {
return 0;
}
@EventId(235012440)
public int GetProcurementRate(int manor_id, int index) {
return 0;
}
@EventId(235012442)
public int GetProcurementType(int manor_id, int index) {
return 0;
}
@EventId(235012445)
public int GetNextProcurementCount(int state, int index) {
return 0;
}
@EventId(235012444)
public int GetNextProcurementRate(int state, int index) {
return 0;
}
@EventId(235012446)
public int GetNextProcurementType(int state, int index) {
return 0;
}
@EventId(234881256)
public boolean IsManorSettingTime() {
return false;
}
@EventId(235012435)
public int GetNextSeedSellCountSet(int state, int index) {
return 0;
}
@EventId(235012436)
public int GetNextSeedPrice(int state, int index) {
return 0;
}
@EventId(235077988)
public void ShowSeedInfo(Creature talker, int id, int time) {
}
@EventId(235077989)
public void ShowCropInfo(Creature talker, int id, int time) {
}
@EventId(234946918)
public void ShowManorDefaultInfo(Creature talker) {
}
@EventId(235012457)
public void ShowProcureCropDetail(Creature talker, int state) {
}
@EventId(235012608)
public void RegisterTeleporterType(int type, int unk) {
}
@EventId(234881461)
public int GetPCCafePointEventState() {
return 0;
}
@EventId(234946994)
public int GetPCCafePoint(Creature talker) {
return 0;
}
@EventId(234881492)
public int GetPCCafeCouponEventState() {
return 0;
}
@EventId(234947027)
public boolean IsPCCafeUser(Creature talker) {
return false;
}
@EventId(234946956)
public void ShowQuestInfoList(Creature talker) {
}
@EventId(235012180)
public void ShowTelPosListPage(Creature talker, TelPosInfo[] telPosInfos) {
}
@EventId(235012531)
public boolean UpdatePCCafePoint(Creature talker, int diff) {
return false;
}
@EventId(235209140)
public void GiveItemByPCCafePoint(Creature talker, int unk1, int unk2, int unk3, int unk4) {
}
@EventId(235012597)
public void UpdatePCCafePoint2(Creature talker, int count) {
}
@EventId(234947035)
public boolean IsInCombatMode(Creature creature) {
return false;
}
@EventId(235143459)
public void RideForEvent(Creature talker, int pet_id, int unk1, int unk2) {
}
@EventId(235405397)
public void Teleport(Creature talker, TelPosInfo[] posInfos, String str1, String str2, String str3, String str4,
int unk, String msg) {
}
@EventId(234881418)
public boolean CanLotto() {
return false;
}
@EventId(235143276)
public void SetMemoStateEx(Creature talker, int quest_id, int state, int unk) {
}
@EventId(234947008)
public void CheckCursedUser(Creature talker) {
}
@EventId(234881451)
public NpcMaker GetMyMaker() {
return null;
}
@EventId(234946735)
public int Castle_GetPledgeState(Creature talker) {
return 0;
}
@EventId(234881210)
public int Castle_GetLifeControlLevel() {
return 0;
}
@EventId(235143431)
public void InstantTeleportInMyTerritory(int x, int y, int z, int unk) {
}
@EventId(234946632)
public void Shout(String str) {
}
@EventId(235078159)
public void SetNRMemoState(Creature talker, int mission, int value) {
}
@EventId(234881187)
public int Residence_GetTaxRate() {
return 0;
}
@EventId(234881253)
public int Residence_GetTaxIncome() {
return 0;
}
@EventId(234881254)
public int Residence_GetTaxIncomeReserved() {
return 0;
}
@EventId(234881255)
public int Manor_GetSeedIncome() {
return 0;
}
@EventId(234946866)
public void OpenSiegeInfo(Creature talker) {
}
@EventId(234946935)
public int GetTicketBuyCount(Creature talker) {
return 0;
}
@EventId(235012635)
public void RegisterDominion(int dominion_id, Creature talker) {
}
@EventId(234946754)
public int Agit_GetDecoLevel(int param) {
return 0;
}
@EventId(235012295)
public int Agit_GetDecoFee(int param, int deco_level) {
return 0;
}
@EventId(235012294)
public int Agit_GetDecoDay(int param, int deco_level) {
return 0;
}
@EventId(234946755)
public int Agit_GetDecoExpire(int param) {
return 0;
}
@EventId(234946747)
public void Castle_GetRelatedFortressList(Creature talker) {
}
@EventId(234946725)
public void Residence_SetTaxRate(int value) {
}
@EventId(235077675)
public void SetCookie(Creature talker, String param, int value) {
}
@EventId(235012140)
public int GetCookie(Creature talker, String cookie) {
return 0;
}
@EventId(235012404)
public void GetDoorHpLevel(Creature talker, String door_name) {
}
@EventId(235012406)
public void GetControlTowerLevel(Creature talker, String unk) {
}
@EventId(234881203)
public void Castle_BanishOthers() {
}
@EventId(235012266)
public void Residence_VaultTakeOutMoney(Creature talker, int reply) {
}
@EventId(235012267)
public void Residence_VaultSaveMoney(Creature talker, int reply) {
}
@EventId(235012431)
public int GetMaxSellableCount(int unk1, int unk2) {
return 0;
}
@EventId(235012439)
public int GetSeedDefaultPrice(int unk1, int unk2) {
return 0;
}
@EventId(235012449)
public int GetCropClassidByOrderNum(int unk, int reply) {
return 0;
}
@EventId(235012472)
public void SetTicketBuyCount(Creature talker, int unk) {
}
@EventId(235012289)
public void Agit_ResetDeco(Creature talker, int i0) {
}
@EventId(235077824)
public void Agit_SetDeco(Creature talker, int unk1, int unk2) {
}
@EventId(235012535)
public void CastBuffForAgitManager(Creature talker, int reply) {
}
@EventId(235012403)
public void SetDoorHpLevel(String door_name, int hp) {
}
@EventId(235012405)
public void SetControlTowerLevel(String towerName, int level) {
}
@EventId(235012455)
public void ShowSeedSetting(Creature talker, int state) {
}
@EventId(235012456)
public void ShowCropSetting(Creature talker, int state) {
}
@EventId(234946772)
public int Fortress_IsInBoundary(int param) {
return 0;
}
@EventId(234946685)
public Creature Pledge_GetLeader(Creature talker) {
return null;
}
@EventId(235012187)
public void TeleportToUser(Creature talker, Creature user) {
}
@EventId(234881186)
public String Castle_GetSiegeTime() {
return null;
}
@EventId(235012392)
public void TB_GetPledgeRegisterStatus(Creature talker, int status) {
}
@EventId(234946853)
public void TB_RegisterMember(Creature talker) {
}
@EventId(234946854)
public void TB_GetNpcType(Creature talker) {
}
@EventId(235012391)
public void TB_SetNpcType(Creature talker, int type) {
}
@EventId(234946857)
public void TB_GetBattleRoyalPledgeList(Creature talker) {
}
@EventId(235012205)
public void RemoveMemo(Creature talker, int memo) {
}
@EventId(234946852)
public void TB_RegisterPledge(Creature talker) {
}
@EventId(234946687)
public Clan GetPledgeByIndex(int index) {
return null;
}
@EventId(234881214)
public int Agit_GetCostFailDay() {
return 0;
}
@EventId(234946760)
public void AuctionAgit_GetAgitCostInfo(Creature talker) {
}
@EventId(234881348)
public int Lotto_GetState() {
return 0;
}
@EventId(234881061)
public int GetLifeTime() {
return 0;
}
@EventId(234881350)
public int Lotto_GetRoundNumber() {
return 0;
}
@EventId(234881358)
public String Lotto_GetChosenNumber() {
return null;
}
@EventId(234881353)
public int Lotto_GetAccumulatedReward() {
return 0;
}
@EventId(234946890)
public void Lotto_MakeFinalRewardFHTML(FHTML fhtml) {
}
@EventId(235012427)
public void Lotto_ShowPrevRewardPage(Creature talker, int reply) {
}
@EventId(235012428)
public void Lotto_GiveReward(Creature talker, int reply) {
}
@EventId(235077959)
public void Lotto_ShowBuyingPage(Creature talker, int reply, FHTML fhtml) {
}
@EventId(235077960)
public void Lotto_BuyTicket(Creature talker, int reply, int unk1) {
}
@EventId(235012429)
public void Lotto_ShowCurRewardPage(Creature talker, int reply) {
}
@EventId(234946619)
public void LookNeighbor(int radius) {
}
@EventId(234946592)
public void RemoveAttackDesire(int creature_objid) {
}
@EventId(234946803)
public void UseSoulShot(int unk) {
}
@EventId(235077876)
public void UseSpiritShot(int unk1, int spiritshot_speed_bonus, int spiritshot_heal_bonus) {
}
@EventId(234881055)
public void RemoveAllAttackDesire() {
}
@EventId(235077692)
public void BroadcastScriptEvent(int event, int event_arg, int radius) {
}
@EventId(234946600)
public int GetDirection(Creature creature) {
return 0;
}
@EventId(234881081)
public int GetTimeHour() {
return 0;
}
@EventId(234946945)
public int GetAngleFromTarget(Creature target) {
return 0;
}
@EventId(234946796)
public int Skill_GetEffectPoint(int skill_name_id) {
return 0;
}
@EventId(234881086)
public int GetPathfindFailCount() {
return 0;
}
@EventId(234881283)
public void Suicide() {
}
@EventId(234946624)
public boolean CanAttack(Creature target) {
return false;
}
@EventId(235077667)
public void MakeAttackEvent(Creature speller, double point, int unk1) {
}
@EventId(235209016)
public void AddHateInfo(Creature target, int point, int unk1, int unk2, int unk3) {
}
@EventId(234946878)
public HateInfo GetMaxHateInfo(int unk) {
return null;
}
@EventId(234946562)
public boolean IsNullHateInfo(HateInfo hateInfo) {
return false;
}
@EventId(235012418)
public void RemoveAllHateInfoIF(int unk1, int unk2) {
}
@EventId(234881338)
public int GetHateInfoCount() {
return 0;
}
@EventId(234881523)
public boolean IsMyBossAlive() {
return false;
}
@EventId(235012111)
public void AddFollowDesire(Creature creater, double point) {
}
@EventId(235077660)
public void AddMoveSuperPointDesire(String pointName, int pointMethod, double point) {
}
@EventId(235077661)
public void AddMoveFreewayDesire(int freeway_id, int freewayMethod, double point) {
}
@EventId(234946806)
public void CreatePrivates(String privates) {
}
@EventId(235012109)
public void AddFleeDesire(Creature attacker, double point) {
}
@EventId(235143415)
public void CreateOnePrivate(int npc_id, String npc_ai, int unk1, int unk2) {
}
@EventId(234881166)
public Creature GetLastAttacker() {
return null;
}
@EventId(234881516)
public void InstantZone_MarkRestriction() {
}
@EventId(235143229)
public void BroadcastScriptEventEx(int event_id, int script_event_arg1, int stript_event_arg2, int radius) {
}
@EventId(235012154)
public void Summon_SetOption(int unk1, int unk2) {
}
@EventId(234946586)
public void AddPetDefaultDesire_Follow(double unk1) {
}
@EventId(235339797)
public void AddUseSkillDesireEx(int id, int skill, int unk1, int reply, int ask, double point, int unk2) {
}
@EventId(235143195)
public void AddMoveToTargetDesire(int target_id, int unk1, int unk2, double point) {
}
@EventId(234881070)
public void StopMove() {
}
@EventId(235012198)
public void ChangeStopType(int type, int unk) // time ?
{
}
@EventId(234946609)
public boolean IsStaticObjectID(int objecti_id) {
return false;
}
@EventId(234946612)
public StaticObject GetStaticObjectFromID(int object_id) {
return null;
}
@EventId(234946658)
public int StaticObjectDistFromMe(StaticObject staticObject) {
return 0;
}
@EventId(235143177)
public void AddAttackDesireEx(int target_id, int unk1, int unk2, double point) {
}
@EventId(234881058)
public void RandomizeAttackDesire() {
}
@EventId(235077888)
public void EffectMusic(Creature object, int unk, String music) // unk is radius?
{
}
@EventId(234881063)
public int GetCurrentTick() {
return 0;
}
@EventId(235077765)
public void MPCC_SetMasterPartyRouting(int id, Creature creature, int unk) {
}
@EventId(234946692)
public int MPCC_GetMPCCId(Creature talker) {
return 0;
}
@EventId(234946688)
public Creature MPCC_GetMaster(int mpcc_id) {
return null;
}
@EventId(234946691)
public int MPCC_GetMemberCount(int master_id) {
return 0;
}
@EventId(235012334)
public boolean Skill_HaveAttribute(int skill_name_id, int unk) {
return false;
}
@EventId(235077677)
public void SetTeleportPosOnLost(int x, int y, int z) {
}
@EventId(234881454)
public void RemoveAllDesire() {
}
@EventId(235536863)
public void AddLogByNpc2(int unk0, Creature creature, String title, String msg, int unk1, int unk2, int unk3,
int unk4,
int unk5, int unk6) {
}
@EventId(234946615)
public int GetGlobalMap(int map_id) {
return 0;
}
@EventId(235012149)
public void RegisterGlobalMap(int map_id, int unk) {
}
@EventId(234946614)
public void UnregisterGlobalMap(int map_id) {
}
@EventId(235012213)
public void SetDBValue(Creature npc, int db_value) {
}
@EventId(234946939)
public void RegisterToEventListener(int unk) {
}
@EventId(234881388)
public int GetSSQWinner() {
return 0;
}
@EventId(234946938)
public boolean IsJoinableToDawn(Creature talker) {
return false;
}
@EventId(235340042)
public void EarthQuakeByNPC(Creature npc, int unk1, int unk2, int unk3, int unk4, int unk5, int unk6) {
}
@EventId(235077887)
public void VoiceEffect(Creature talker, String voice, int unk) // duration?
{
}
@EventId(235012372)
public void ShowTutorialHTML(Creature talker, String html) {
}
@EventId(235012169)
public void ShoutEx(String msg, int unk) // radius ?
{
}
@EventId(235078003)
public int GetDepositedSSQItemCount(Creature talker, int ssq_type, int item_type) {
return 0;
}
@EventId(235143542)
public void DeleteDepositedSSQItem(Creature talker, int ssq_type, int item_type, int unk) {
}
@EventId(234881489)
public int GetSSQPrevWinner() {
return 0;
}
@EventId(235274609)
public boolean AddSSQMember(Creature talker, int unk1, int unk2, int unk3, int unk4, int unk5) {
return false;
}
@EventId(234946984)
public Creature FindNeighborHero(int radius) {
return null;
}
@EventId(234946596)
public int GetTopDesireValue(int unk) {
return 0;
}
@EventId(235012377)
public void EnableTutorialEvent(Creature talker, int mask) {
}
@EventId(234946840)
public void CloseTutorialHTML(Creature talker) {
}
@EventId(235012374)
public void ShowQuestionMark(Creature talker, int unk) {
}
@EventId(235143445)
public void ShowTutorialHTML2(Creature talker, String html, int unk, String sound_effect) {
}
@EventId(235208986)
public void ShowRadar(Creature talker, int x, int y, int z, int unk) {
}
@EventId(235077739)
public void SetMemoState(Creature talker, int quest_id, int state) {
}
@EventId(235012622)
public void SetNRMemo(Creature talker, int quest_id) {
}
@EventId(235143696)
public void SetNRMemoStateEx(Creature talker, int quest_id, int unk1, int unk2) {
}
@EventId(235078163)
public void SetNRFlagJournal(Creature talker, int quest_id, int flag) {
}
@EventId(234946805)
public void SetPrivateID(int unk) {
}
@EventId(235339859)
public void ShowSysMsgToParty2(Party party, int unk1, int unk2, int unk3, int unk4, int unk5, int unk6) {
}
@EventId(234946881)
public void RemoveHateInfoByCreature(Creature creature) {
}
@EventId(235012625)
public void RemoveNRMemo(Creature talker, int quest_id) {
}
@EventId(234947102)
public int GetDominionSiegeID(Creature talker) {
return 0;
}
@EventId(235274624)
public void TeleportParty(int party_id, int x, int y, int z, int unk1, int unk2) {
}
@EventId(234946942)
public int GetTimeAttackFee(int value) {
return 0;
}
@EventId(234946631)
public void EquipItem(int weapon) {
}
@EventId(235274613)
public void DepositSSQItemEx(Creature talker, int ssq_type, int blue, int green, int red, int unk) {
}
@EventId(235012336)
public void UseSkill(Creature target, int skill) {
}
@EventId(234881386)
public int GetSSQRoundNumber() {
return 0;
}
@EventId(235077768)
public int OwnItemCountEx(Creature talker, int item_id, int unk) // count ?
{
return 0;
}
@EventId(234946988)
public void SetEnchantOfWeapon(int value) {
}
@EventId(234946930)
public int GetTimeOfSSQ(int unk) {
return 0;
}
@EventId(235077713)
public void BroadcastSystemMessage(Creature creature, int unk, int msg_id) {
}
@EventId(235077646)
public void AddFleeDesireEx(Creature victim, int distance, double point) {
}
@EventId(234881449)
public void RegisterAsOlympiadOperator() {
}
@EventId(234946968)
public int GetOlympiadPoint(Creature talker) {
return 0;
}
@EventId(234946969)
public boolean IsMainClass(Creature talker) {
return false;
}
@EventId(234881429)
public int GetOlympiadWaitingCount() {
return 0;
}
@EventId(234881431)
public int GetTeamOlympiadWaitingCount() {
return 0;
}
@EventId(234881430)
public int GetClassFreeOlympiadWaitingCount() {
return 0;
}
@EventId(234946963)
public void AddClassFreeOlympiad(Creature talker) {
}
@EventId(234946981)
public void SetHero(Creature talker) {
}
@EventId(234946964)
public void AddTeamOlympiad(Creature talker) {
}
@EventId(234946962)
public void AddOlympiad(Creature talker) {
}
@EventId(234946975)
public int GetStatusForOlympiadField(int unk) // class ?
{
return 0;
}
@EventId(234946977)
public String GetPlayer1ForOlympiadField(int unk) // class ?
{
return null;
}
@EventId(234946978)
public String GetPlayer2ForOlympiadField(int unk) // class ?
{
return null;
}
@EventId(234947029)
public int GetOlympiadTradePoint(Creature talker) {
return 0;
}
@EventId(234947000)
public boolean IsWeaponEquippedInHand(Creature creature) {
return false;
}
@EventId(234946982)
public int GetPreviousOlympiadPoint(Creature talker) {
return 0;
}
@EventId(235012566)
public void DeleteOlympiadTradePoint(Creature talker, int count) {
}
@EventId(235012508)
public int GetRankByOlympiadRankOrder(int reply, int unk) {
return 0;
}
@EventId(235012515)
public void ObserveOlympiad(Creature talker, int value) {
}
@EventId(234946970)
public void RemoveOlympiad(Creature talker) {
}
@EventId(235667724)
public void SpecialCamera(Creature creature, int unk1, int unk2, int unk3, int unk4, int unk5, int unk6, int unk7,
int unk8, int unk9, int unk10, int unk11) {
}
@EventId(235667726)
public void SpecialCamera3(Creature creature, int unk1, int unk2, int unk3, int duration, int unk4, int unk5,
int unk6,
int unk7, int unk8, int unk9, int unk10) {
}
@EventId(234947007)
public void MG_GetUnreturnedPoint(Creature talker) {
}
@EventId(235012394)
public void TB_CheckMemberRegisterStatus(int agit_id, Creature talker) {
}
@EventId(235012538)
public void MG_RegisterPledge(Creature talker, int agit_war_cretificates_count) {
}
@EventId(234947003)
public void MG_UnregisterPledge(Creature talker) {
}
@EventId(234947005)
public void MG_JoinGame(Creature talker) {
}
@EventId(235077770)
public void DropItem1(Creature creature, int item_id, int count) {
}
@EventId(234946991)
public void ChangeMoveType(int new_type) {
}
@EventId(234881501)
public void UnequipWeapon() {
}
@EventId(235078032)
public void LookItem(int radius, int unk, int item_id) {
}
@EventId(235012572)
public void PlayAnimation(int animation, int range) {
}
@EventId(234946689)
public int MPCC_GetPartyCount(int mpcc_id) {
return 0;
}
@EventId(235471328)
public void GiveEventItem(Creature talker, int consume_item, int consume_count, int item_id, int count, int unk1,
int limit_time, int unk2, int unk3) {
}
@EventId(235143307)
public void DropItem2(Creature creature, int item_id, int count, int attacker_id) {
}
@EventId(234881524)
public boolean IsEventDropTime() {
return false;
}
@EventId(234947093)
public void ShowPremiumItemList(Creature talker) {
}
@EventId(235078198)
public int RegisterAsAirportManager(int airport_id, int platform_id, int less_than_100) {
return 0;
}
@EventId(234947130)
public boolean IsOccupiedPlatform(int id) {
return false;
}
@EventId(234947129)
public void GetOnAirShip(Creature talker) {
}
@EventId(235078199)
public void SummonAirShip(Creature talker, int airport_id, int platform_id) {
}
@EventId(235012107)
public void AddGetItemDesireEx(int item_index, double point) {
}
@EventId(235143435)
public void EarthQuakeToParty(int party_id, int unk1, int unk2, int unk3) {
}
@EventId(234946768)
public int Fortress_GetState(int fortress_id) {
return 0;
}
@EventId(235077848)
public void Fortress_SetFacility(Creature talker, int unk1, int unk2) {
}
@EventId(235077833)
public void Fortress_PledgeRegister(int creature_id, int talker_id, int fortress_id) {
}
@EventId(235077834)
public void Fortress_PledgeUnregister(int creature_id, int talker_id, int fortress_id) {
}
@EventId(234947006)
public void MG_SetWinner(Creature creature) {
}
@EventId(235012664)
public void BuyAirShip(Creature talker, int unk) {
}
@EventId(234947044)
public void SetVisible(int value) {
}
@EventId(235012577)
public void SetWorldTrapVisibleByClassId(int class_id, int value) {
}
@EventId(235012578)
public void ActivateWorldTrapByClassId(int creature_id, int class_id) {
}
@EventId(235012579)
public void DefuseWorldTrapByClassId(int creature_id, int class_id) {
}
@EventId(234881510)
public int InstantZone_GetId() {
return 0;
}
@EventId(235143664)
public void SetStaticMeshStatus(Creature creature, String mesh_name, int targetable, int mesh_index) {
}
@EventId(235012226)
public int MPCC_GetPartyID(int mppc_id, int party_index) {
return 0;
}
@EventId(235471113)
public void InstantTeleportMPCC(Creature talker, int x, int y, int z, int unk1, int unk2, int unk3, int unk4,
int unk5) {
}
@EventId(234881062)
public int GetTick() {
return 0;
}
@EventId(234947034)
public void ShowBaseAttributeCancelWindow(Creature talker) {
}
@EventId(235143373)
public void Fortress_ContractCastle(int creature_id, int talker_id, int fortress_id, int castle_id) {
}
@EventId(235077714)
public void BroadcastSystemMessageStr(Creature creature, int radius, String msg) {
}
@EventId(234946777)
public void Fortress_ResetFacility(Creature talker) {
}
@EventId(234946770)
public int Fortress_GetOwnerRewardCycleCount(int fortress_id) {
return 0;
}
@EventId(235208910)
public void Fortress_GetOwnerRewardCycleCount(int creature_id, int talker_id, int fortress_id, int item_medal,
int count) {
}
@EventId(234946771)
public int Fortress_GetCastleTreasureLevel(int fortress_id) {
return 0;
}
@EventId(235077839)
public void Fortress_CastleTreasureTaken(int creature_id, int talker_id, int fortress_id) {
}
@EventId(234946775)
public int Fortress_GetPledgeSiegeState(Creature creature) {
return 0;
}
@EventId(235012300)
public void Fortress_ProtectedNpcDied(int creature_id, int fortress_id) {
}
@EventId(235077835)
public void Fortress_BarrackCaptured(int creature_id, int fortress_id, int barrack_id) {
}
@EventId(235274504)
public void InstantTeleportInMyTerritoryWithCondition(int x, int y, int z, int unk1, int unk2, int unk3) {
}
@EventId(235012605)
public void RegisterResurrectionTower(int unk1, int unk2) {
}
@EventId(234947062)
public void CreatePVPMatch(int n_type) {
}
@EventId(235012604)
public void CheckRegisterParty2(Party party1, Party party2) {
}
@EventId(235208729)
public void AddEffectActionDesire2(Creature creature, int effect_action, int unk1, int unk2, int unk3) {
}
@EventId(234946871)
public void SetMaxHateListSize(int max_size) {
}
@EventId(234946875)
public HateInfo GetHateInfoByIndex(int index) {
return null;
}
@EventId(234947095)
public boolean IsStackableItemEx(int item_index) {
return false;
}
@EventId(234947077)
public void RegisterUserResurrectionTower(int creature_id) {
}
@EventId(234947079)
public void IsUserPVPMatching(Creature creature) {
}
@EventId(235012618)
public void AddKillPointUserPVPMatch(Creature c0, int point) {
}
@EventId(234947078)
public void CheckRegisterUserPVPMatch(Creature talker) {
}
@EventId(234947081)
public void UnregisterUserPVPMatch(Creature talker) {
}
@EventId(234947080)
public void RegisterUserPVPMatch(Creature talker) {
}
@EventId(235405342)
public void AddMoveFormationDesire(String unk, int unk1, int group_id, int group_id_, int fromation_id, int unk2,
int unk3, double point) {
}
@EventId(234947108)
public void BlockUpsetManagerEnter(int group_id) {
}
@EventId(235012646)
public void BlockUpsetUserEnter(int group_id, Creature talker) {
}
@EventId(235012648)
public void BlockUpsetChangeAmount(int group_id, int amount) {
}
@EventId(234947111)
public void BlockUpsetRegisterMe(int group_id) {
}
@EventId(235012649)
public void BlockUpsetChangeColor(int ground_id, int color_id) {
}
@EventId(234881582)
public int GetEvolutionId() {
return 0;
}
@EventId(235143717)
public void BlockUpset(int ground_id, int unk, Creature creature, int block_upset_point) {
}
@EventId(235078193)
public void SetDieEvent(Creature target, int unk1, int unk2) {
}
@EventId(235077778)
public void FHTML_SetStr(FHTML fhtml, String find, String replacement) {
}
@EventId(234881274)
public int Maker_GetNpcCount() {
return 0;
}
@EventId(234947084)
public int GetOverhitBonus(Creature creature) {
return 0;
}
@EventId(234947083)
public void GetRankUserPVPMatch(Creature creature) {
}
@EventId(235209269)
public void StartScenePlayerAround(Creature creature, int scene, int radius, int min_z, int max_z) {
}
@EventId(235012679)
public void TeleportTo(Creature from, Creature to) {
}
@EventId(235078192)
public void RenewSpawnedPos(int x, int y, int z) {
}
@EventId(234947098)
public void ChangeStatus(int status) {
}
@EventId(235012600)
public void UnregisterPVPMatch(Party party, Creature creature) {
}
@EventId(235012601)
public void StartPVPMatch(Party party1, Party party2) {
}
@EventId(235012599)
public void RegisterPVPMatch(Party party, Creature talker) {
}
@EventId(234946876)
public HateInfo GetHateInfoByCreature(Creature creature) {
return null;
}
@EventId(234881578)
public void CleftManagerEnter() {
}
@EventId(234881579)
public int GetCleftState() {
return 0;
}
@EventId(234947116)
public void CleftUserEnter(Creature talker) {
}
@EventId(235012612)
public void IsToggleSkillOnOff(Creature creature, int skill_id) {
}
@EventId(235078189)
public void CleftCenterDestroyed(int zone_type, Creature creature, int destroy_point) {
}
@EventId(235274329)
public void InstantTeleportWithItem(Creature creature, int x, int y, int z, int item, int item_count) {
}
@EventId(234881597)
public void EventManagerEnter() {
}
@EventId(235143302)
public void GiveItemEx(Creature talker, int item_id, int count, int unk) {
}
@EventId(235208720)
public void AddFollowDesire2(Creature creature, int unk1, int unk2, int unk3, int unk4) {
}
@EventId(234947135)
public void SetAbilityItemDrop(int ability) {
}
@EventId(235077638)
public void AddMoveAroundLimitedDesire(int unk1, int unk2, double point) {
}
@EventId(235012659)
public void StartScenePlayer(Creature talker, int scene) {
}
@EventId(234947131)
public boolean IsCleftUser(Creature talker) {
return false;
}
@EventId(235012673)
public void ObserveEventMatch(Creature talker, int unk) {
}
@EventId(234947053)
public void InstantZone_AddExtraDuration(int duration) {
}
@EventId(234946883)
public void SetHateInfoListIndex(int index) {
}
@EventId(235078222)
public void ChangeDir(Creature creature, int creature_id,
int direction) // direction to creature_id, or to direction
{
}
@EventId(235012680)
public void ChangeNPCState(Creature creature, int state) {
}
@EventId(234881606)
public void RegisterAsFieldCycleManager() {
}
@EventId(235012685)
public void SetAttackable(Creature creature, int value) {
}
@EventId(234947148)
public boolean IsAttackable(Creature creature) {
return false;
}
@EventId(234947138)
public void BlockTimer(int timer_id) {
}
@EventId(234947139)
public void UnblockTimer(int timer_id) {
}
@EventId(235667705)
public void CreateOnePrivateInzoneEx(int npc_class_id, String ai, int weight_point, int unk1, int x, int y, int z,
int angle, int master_id, int unk2, int unk3, int instance_zone_id) {
}
@EventId(234946822)
public boolean IsInThisTerritory(String area_name) {
return false;
}
@EventId(234946989)
public void RemoveDesire(int unk) {
}
@EventId(235012682)
public void ChangeNickName(Creature sm, String nickname) {
}
@EventId(235012683)
public void ChangeMasterName(Creature sm, String mastername) {
}
@EventId(234947141)
public void FixMoveType(int type) {
}
@EventId(235012528)
public void ChangeMoveType2(int unk1, int unk2) {
}
@EventId(234947155)
public void ChangeUserTalkTarget(Creature creature) {
}
@EventId(234881057)
public void RemoveAbsoluteDesire() {
}
@EventId(235078228)
public void VoiceNPCEffect(Creature creature, String voice, int unk) {
}
@EventId(235209296)
public void IncreaseNPCLogByID(Creature target, int unk1, int unk2, int npc_class_id, int value) {
}
@EventId(235143762)
public int GetNPCLogByID(Creature target, int unk1, int unk2, int npc_class_id) {
return 0;
}
@EventId(235077952)
public HateInfo GetNthHateInfo(int unk1, int hate_index, int unk2) {
return null;
}
@EventId(235078217)
public void ChangeZoneInfo(Creature creature, int unk1, int unk2) {
}
@EventId(235143766)
public void FindRandomUser(int unk1, int unk2, int unk3, int unk4) {
}
@EventId(235340375)
public void CreateOnePrivateNearUser(Creature talker, int unk1, String ai, int weight_point, int unk2, int unk3,
int unk4) {
}
@EventId(234881621)
public void GetPlayingUserCount() {
}
@EventId(234881624)
public Creature GetMasterUser() {
return null;
}
@EventId(234946628)
public void SayInt(int value) {
}
@EventId(235078234)
public void GetEventRankerInfo(int event_id, Creature talker, int unk) {
}
@EventId(235078235)
public void DecreaseEventTopRankerReward(int event_id, int unk, Creature talker) {
}
@EventId(235078233)
public void InsertEventRanking(int eventData, Creature creature, int unk) {
}
@EventId(235012700)
public void CanGiveEventData(Creature talker, int eventData) {
}
@EventId(235077920)
public void DestroyPet(Creature talker, int dbid, int petlevel) {
}
@EventId(218169350)
public void RegisterAgitSiegeEventEx(int castle_id) {
}
@EventId(234946673)
public void SetCurrentQuestID(int quest_id) {
}
@EventId(235077742)
public void SetJournal(Creature target, int quest, int unk) {
}
@EventId(234881089)
public boolean IsSpoiled() {
return false;
}
@EventId(234947014)
public boolean HasAcademyMaster(Creature target) {
return false;
}
@EventId(234947016)
public Creature GetAcademyMaster(Creature target) {
return null;
}
@EventId(234946811)
public Creature Maker_FindNpcByKey(int key) {
return null;
}
@EventId(235208987)
public void DeleteRadar(Creature talker, int x, int y, int z, int unk) {
}
@EventId(235012314)
public void AddChoice(int choise, String name) {
}
@EventId(235012315)
public void ShowChoicePage(Creature talker, int unk) {
}
@EventId(234947015)
public boolean HasAcademyMember(Creature talker) {
return false;
}
@EventId(234947017)
public Creature GetAcademyMember(Creature talker) {
return null;
}
@EventId(235078031)
public int GetHTMLCookie(Creature talker, int quest_id, int unk) {
return 0;
}
@EventId(235077709)
public void ShowQuestPage(Creature talker, String html, int quest_id) {
}
@EventId(235012380)
public void DeleteAllRadar(Creature talker, int unk) {
}
@EventId(234946665)
public int GetMemoCount(Creature talker) {
return 0;
}
@EventId(235077780)
public void ShowQuestFHTML(Creature talker, FHTML fhtml, int quest_id) {
}
@EventId(234947107)
public boolean IsHostileInDominionSiege(Creature creature) {
return false;
}
@EventId(235012202)
public void SetMemo(Creature talker, int quest_id) {
}
@EventId(235078030)
public void SetHTMLCookie(Creature talker, int quest_id, int coockie) {
}
@EventId(234946953)
public void ClearBingoBoard(Creature talker) {
}
@EventId(235012482)
public void CreateBingoBoard(Creature talker, int unk) {
}
@EventId(235012485)
public void SelectBingoNumber(Creature talker, int number) {
}
@EventId(235012484)
public int GetNumberFromBingoBoard(Creature talker, int unk) {
return 0;
}
@EventId(235012487)
public boolean IsSelectedBingoNumber(Creature talker, int number) {
return false;
}
@EventId(234946950)
public int GetBingoSelectCount(Creature talker) {
return 0;
}
@EventId(234946952)
public int GetMatchedBingoLineCount(Creature talker) {
return 0;
}
@EventId(235078013)
public void AddTimeAttackFee(int unk1, int unk2, int party_id) {
}
@EventId(235274620)
public void AddTimeAttackRecord(int unk1, int SSQ_type, int party_id, int item_count, int time_of_day,
int memo_state) {
}
@EventId(235143551)
public void GiveTimeAttackReward(Creature talker, int unk1, int tem_id, int unk2) {
}
@EventId(235012636)
public void DeclareLord(int dominion, Creature talker) {
}
} | apache-2.0 |
Tikitoo/JavaSamples | javabase/src/main/java/generic/GenericDemo.java | 5599 | package generic;
import java.sql.Driver;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import sun.corba.Bridge;
/**
* 泛型
*
* http://tutorials.jenkov.com/java-generics/implementing-iterable.html
* http://www.cnblogs.com/sharewind/archive/2012/11/26/2788698.html
* http://peiquan.blog.51cto.com/7518552/1302898
* http://www.journaldev.com/1663/java-generics-tutorial-example-class-interface-methods-wildcards-and-much-more
* Created by Tikitoo on 2015/12/8.
*/
public class GenericDemo {
public static void main(String[] args) {
listString();
}
private void initTest() {
List list = new ArrayList();
list.add("hello");
list.add(2);
list.add(true);
}
private static void listString() {
List<String> list = new ArrayList();
list.add("hello");
for(String st : list) {
System.out.println(st);
}
}
}
// Class
class Gen<T> {
T obj;
public T getObj() {
return obj;
}
public void setObj(T obj) {
this.obj = obj;
}
public static void main(String[] args) {
Gen<String> gen = new Gen<String>();
gen.setObj("abc");
// gen.setObj(12);
String str = gen.getObj();
Gen gen2 = new Gen();
gen2.setObj("abc");
gen2.setObj(23);
Integer num = (Integer) gen2.getObj();
System.out.println("gen2 num: " + num);
}
}
// Method
class GenMethod {
public static <T> void fromArrayToCollection(T[] a, Collection<T> c) {
for(T t : a) {
c.add(t);
}
}
public static void main(String[] args) {
Object[] oc = new Object[100];
Collection<Object> collect = new ArrayList<Object>();
GenMethod.fromArrayToCollection(oc, collect);
}
}
// Class
class GenFactory<T> {
public static void main(String[] args) throws InstantiationException, IllegalAccessException {
GenFactory<String> factory = new GenFactory<String>(String.class);
String str = factory.createInstance();
GenFactory<Number> numFactory = new GenFactory<Number>(Number.class);
Number number = numFactory.createInstance();
}
Class mClass = null;
public GenFactory(Class aClass) {
mClass = aClass;
}
public T createInstance() throws IllegalAccessException, InstantiationException {
return (T) this.mClass.newInstance();
}
}
// runtime, instance
class GenRun {
public static void main(String[] args) throws InstantiationException, IllegalAccessException {
String str = getInstance(String.class);
Number number = getInstance(Number.class);
Driver driver = read(Driver.class, "select * from user where id= 1");
Bridge bridge = read(Bridge.class, "select * from bride where id= 1");
}
public static <T> T getInstance(Class<T> tClass) throws IllegalAccessException, InstantiationException {
return tClass.newInstance();
}
public static <T> T read(Class<T> tClass, String sql) throws IllegalAccessException, InstantiationException {
T o = tClass.newInstance();
return o;
}
}
// loop, iterator
class GenLoop {
public static void main(String[] args) {
// initList();
// initSet();
initMap();
}
public static void initList() {
List<String> list = new ArrayList();
list.add("dfa");
list.add("dfad");
for(String aString : list) {
System.out.println(aString);
}
}
public static void initSet() {
Set<String> set = new HashSet<String>();
set.add("dfad");
// set.add("dfad");
set.add("fdfasdf");
for(String str : set) {
System.out.println("set: " + str);
}
}
public static void initMap() {
Map<Integer, String> map = new HashMap<Integer, String>();
map.put(1, "123");
map.put(2, "123d");
map.put(3, "123dfa");
for(Integer aKey : map.keySet()) {
String aValue = map.get(aKey);
System.out.println(aKey + " : " + aValue);
}
}
}
// impl interface
class MyCollection<E> implements Iterable<E> {
public static void main(String[] args) {
MyCollection<String> strings = new MyCollection<String>();
for(String aString : strings) {
System.out.println(aString);
}
}
@Override
public Iterator<E> iterator() {
return new MyIterator<E>();
}
}
class MyIterator<T> implements Iterator<T> {
@Override
public boolean hasNext() {
return false;
}
@Override
public T next() {
return null;
}
@Override
public void remove() {
}
}
// Wildcards 通配符
class Parent {}
class SubA extends Parent {}
class SubB extends Parent {}
/**
* super: 参数类型,大于此。
* extends: 返回类型限定,小于此。
*/
class GenWild {
public static void main(String[] args) {
List<Parent> listParent = new ArrayList<Parent>();
List<SubA> listSubA = new ArrayList<SubA>();
// listParent = listSubA; error
// listSubA = listParent; error
List<?> listUkown = new ArrayList<Parent>();
List<? extends Parent> extendParentLisst = new ArrayList<Parent>();
List<? super Parent> superParentList = new ArrayList<Parent>();
}
} | apache-2.0 |
rabix/bunny | rabix-bindings-cwl/src/main/java/org/rabix/bindings/cwl/CWLValueTranslator.java | 2414 | package org.rabix.bindings.cwl;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.rabix.bindings.cwl.helper.CWLDirectoryValueHelper;
import org.rabix.bindings.cwl.helper.CWLFileValueHelper;
import org.rabix.bindings.cwl.helper.CWLSchemaHelper;
import org.rabix.bindings.model.DirectoryValue;
import org.rabix.bindings.model.FileValue;
public class CWLValueTranslator {
@SuppressWarnings("unchecked")
public static Object translateToSpecific(Object commonValue) {
if (commonValue == null) {
return null;
}
if (commonValue instanceof List<?>) {
List<Object> list = new ArrayList<>();
for (Object singleCommonValue : (List<?>) commonValue) {
list.add(translateToSpecific(singleCommonValue));
}
return list;
}
if (commonValue instanceof Map<?, ?>) {
Map<String, Object> map = new HashMap<>();
for (Entry<String, Object> entry : ((Map<String, Object>) commonValue).entrySet()) {
map.put(entry.getKey(), translateToSpecific(entry.getValue()));
}
return map;
}
if (commonValue instanceof DirectoryValue) {
return CWLDirectoryValueHelper.createDirectoryRaw((DirectoryValue) commonValue);
}
if (commonValue instanceof FileValue) {
return CWLFileValueHelper.createFileRaw((FileValue) commonValue);
}
return commonValue;
}
@SuppressWarnings("unchecked")
public static Object translateToCommon(Object nativeValue) {
if (nativeValue == null) {
return null;
}
if (CWLSchemaHelper.isDirectoryFromValue(nativeValue)) {
return CWLDirectoryValueHelper.createDirectoryValue(nativeValue);
}
if (CWLSchemaHelper.isFileFromValue(nativeValue)) {
return CWLFileValueHelper.createFileValue(nativeValue);
}
if (nativeValue instanceof List<?>) {
List<Object> list = new ArrayList<>();
for (Object singleNativeValue : (List<?>) nativeValue) {
list.add(translateToCommon(singleNativeValue));
}
return list;
}
if (nativeValue instanceof Map<?, ?>) {
Map<String, Object> map = new HashMap<>();
for (Entry<String, Object> entry : ((Map<String, Object>) nativeValue).entrySet()) {
map.put(entry.getKey(), translateToCommon(entry.getValue()));
}
return map;
}
return nativeValue;
}
}
| apache-2.0 |
digidotcom/idigi-java-monitor-api | netty/src/main/java/com/idigi/api/monitor/netty/Constants.java | 885 | /*
* Copyright 2012 Digi International, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.idigi.api.monitor.netty;
public final class Constants {
// DO NOT CHANGE
// These constants refer to the monitor ports on the iDigi server.
public static final Integer INSECURE_MONITOR_PORT = 3200;
public static final Integer SECURE_MONITOR_PORT = 3201;
}
| apache-2.0 |
HALive/AStarVisualizer | src/main/java/halive/astarvisual/AStarVisualizer.java | 2376 | package halive.astarvisual;
import halive.astarvisual.core.ui.GridRenderCanvas;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import java.awt.Dimension;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
public class AStarVisualizer {
public static final int SQUARE_SIZE = 10;
public static final int DELAY_MS = 10;
public static final boolean DRAW_GRID = false;
public static int X_OFFSET;
public static int Y_OFFSET;
public static final Dimension DEFAULT_SIZE = new Dimension(800 + X_OFFSET, 600 + Y_OFFSET);
static {
String osName = System.getProperty("os.name").toLowerCase().replace(" ", "");
ScreenSizeOffset offset = ScreenSizeOffset.OTHER;
for (int i = 0; i < ScreenSizeOffset.values().length; i++) {
ScreenSizeOffset offset1 = ScreenSizeOffset.values()[i];
if (osName.contains(offset1.lookupName)) {
offset = offset1;
break;
}
}
X_OFFSET = offset.xOffset;
Y_OFFSET = offset.yOffset;
}
public static void main(String[] args) {
final JFrame frame = new JFrame("A* 2D Grid");
frame.setSize(DEFAULT_SIZE);
final GridRenderCanvas c = new GridRenderCanvas(frame);
frame.add(c);
frame.addComponentListener(new ComponentAdapter() {
@Override
public void componentResized(ComponentEvent e) {
int newX = e.getComponent().getSize().width - X_OFFSET;
int newY = e.getComponent().getSize().height - Y_OFFSET;
c.updateScale(newX, newY);
}
});
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
frame.setVisible(true);
c.init();
}
});
}
private enum ScreenSizeOffset {
WINDOWS(17, 90, "windows"),
MACOS(2, 73, "mac"),
OTHER(2, 73, "HELLO WORLD");
private int xOffset;
private int yOffset;
private String lookupName;
ScreenSizeOffset(int xOffset, int yOffset, String lookupName) {
this.xOffset = xOffset;
this.yOffset = yOffset;
this.lookupName = lookupName;
}
}
}
| apache-2.0 |
m-m-m/util | pojo/src/main/java/net/sf/mmm/util/pojo/descriptor/base/accessor/AbstractPojoPropertyAccessorField.java | 2707 | /* Copyright (c) The m-m-m Team, Licensed under the Apache License, Version 2.0
* http://www.apache.org/licenses/LICENSE-2.0 */
package net.sf.mmm.util.pojo.descriptor.base.accessor;
import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Field;
import java.lang.reflect.Type;
import net.sf.mmm.util.pojo.descriptor.api.PojoDescriptor;
import net.sf.mmm.util.pojo.descriptor.base.PojoDescriptorDependencies;
import net.sf.mmm.util.reflect.api.GenericType;
/**
* This is the abstract implementation of the {@link net.sf.mmm.util.pojo.descriptor.api.accessor.PojoPropertyAccessor}
* interface used to access a {@link Field}.
*
* @author Joerg Hohwiller (hohwille at users.sourceforge.net)
* @since 1.1.0
*/
public abstract class AbstractPojoPropertyAccessorField extends AbstractPojoPropertyAccessorBase {
private final Field field;
/**
* The constructor.
*
* @param descriptor is the descriptor this accessor is intended for.
* @param dependencies are the {@link PojoDescriptorDependencies} to use.
* @param field is the {@link #getField() field} to access.
*/
public AbstractPojoPropertyAccessorField(PojoDescriptor<?> descriptor, PojoDescriptorDependencies dependencies,
Field field) {
this(field.getName(), field.getGenericType(), descriptor, dependencies, field);
}
/**
* The constructor.
*
* @param propertyName is the {@link #getName() name} of the property.
* @param propertyType is the {@link #getPropertyType() generic type} of the property.
* @param descriptor is the descriptor this accessor is intended for.
* @param dependencies are the {@link PojoDescriptorDependencies} to use.
* @param field is the {@link #getField() field} to access.
*/
public AbstractPojoPropertyAccessorField(String propertyName, Type propertyType, PojoDescriptor<?> descriptor,
PojoDescriptorDependencies dependencies, Field field) {
super(propertyName, propertyType, descriptor, dependencies);
this.field = field;
}
/**
* @see #getAccessibleObject()
*
* @return the field to access.
*/
protected Field getField() {
return this.field;
}
@Override
public int getModifiers() {
return this.field.getModifiers();
}
@Override
public AccessibleObject getAccessibleObject() {
return this.field;
}
@Override
public String getAccessibleObjectName() {
return this.field.getName();
}
@Override
public Class<?> getDeclaringClass() {
return this.field.getDeclaringClass();
}
@Override
public GenericType<?> getReturnType() {
return getPropertyType();
}
@Override
public Class<?> getReturnClass() {
return getPropertyClass();
}
}
| apache-2.0 |
FilteredPush/sci_name_qc | src/main/java/org/filteredpush/qc/sciname/EnumSciNameSourceAuthority.java | 1159 | /**
* EnumSciNameSourceAuthority.java
*
* Copyright 2022 President and Fellows of Harvard College
*
* 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.filteredpush.qc.sciname;
/**
* A list of source authorities for which implementations exist in this package.
*
* @author mole
*
*/
public enum EnumSciNameSourceAuthority {
GBIF_BACKBONE_TAXONOMY,
GBIF_COL,
GBIF_PALEOBIOLOGY_DATABASE,
GBIF_IPNI,
GBIF_INDEX_FUNGORUM,
GBIF_FAUNA_EUROPAEA,
GBIF_ITIS,
GBIF_UKSI,
GBIF_ARBITRARY,
WORMS;
public String getName() {
// return the exact name of the enum instance.
return name();
}
}
| apache-2.0 |
lukecampbell/webtest | src/test/java/com/canoo/webtest/steps/request/AbstractTargetActionTest.java | 2662 | // Copyright © 2002-2007 Canoo Engineering AG, Switzerland.
package com.canoo.webtest.steps.request;
import java.util.Collections;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import com.canoo.webtest.boundary.UrlBoundary;
import com.canoo.webtest.engine.StepExecutionException;
import com.canoo.webtest.engine.StepFailedException;
import com.canoo.webtest.self.TestBlock;
import com.canoo.webtest.self.ThrowAssert;
import com.canoo.webtest.steps.BaseStepTestCase;
import com.canoo.webtest.steps.Step;
import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
import com.gargoylesoftware.htmlunit.HttpMethod;
import com.gargoylesoftware.htmlunit.Page;
import com.gargoylesoftware.htmlunit.WebResponse;
import com.gargoylesoftware.htmlunit.WebResponseData;
/**
* @author Paul King
* @author Marc Guillemot
*/
public class AbstractTargetActionTest extends BaseStepTestCase
{
private TargetActionStub fTargetStep;
protected Step createStep() {
return new TargetActionStub();
}
protected void setUp() throws Exception {
super.setUp();
fTargetStep = (TargetActionStub) getStep();
}
public void testUnprotectedCall() throws Exception {
executeStep(fTargetStep);
}
public void testProtectedCalls() throws Exception {
final WebResponseData responseData = new WebResponseData(new byte[]{},
404, "Not Found", Collections.EMPTY_LIST);
final WebResponse webResponse = new WebResponse(responseData, UrlBoundary.tryCreateUrl("http://foo"), HttpMethod.GET, 1);
assertProtectionToStepFailed(new FailingHttpStatusCodeException(webResponse), StepFailedException.class);
final Logger stepLogger = Logger.getLogger(Step.class);
final Level oldLevel = stepLogger.getLevel();
//stepLogger.setLevel(Level.OFF); // dk: we produce an error log on purpose. don't show it here.
assertProtectionToStepFailed(new RuntimeException("any other"), StepExecutionException.class);
stepLogger.setLevel(oldLevel);
}
private void assertProtectionToStepFailed(final Exception toThrow, final Class expectedException) {
ThrowAssert.assertThrows(expectedException, new TestBlock()
{
public void call() throws Exception {
fTargetStep.setException(toThrow);
fTargetStep.execute();
}
});
}
private static class TargetActionStub extends AbstractTargetAction {
private Exception fException;
public void setException(final Exception exception) {
fException = exception;
}
protected Page findTarget() throws Exception {
if (fException != null) {
throw fException;
}
return null;
}
protected String getLogMessageForTarget() {
return "by stub";
}
}
}
| apache-2.0 |
Wick3r/WikiN-G-ER | Wikinger/src/test/OnlineControllerTest.java | 2642 | package test;
import java.io.IOException;
import java.util.ArrayList;
import javax.xml.parsers.ParserConfigurationException;
import org.xml.sax.SAXException;
import part.online.control.WeightingSystem;
import data.City;
import data.DataDump;
import data.Entity;
import data.EntityType;
import data.control.FileInput;
import data.control.StanfordNER;
import data.database.connection.WikiNerGraphConnector;
public class OnlineControllerTest {
private StanfordNER ner;
private WeightingSystem ws;
private EntityType[] entiWeig;
private FileInput in;
public static void main(String[] args) {
OnlineControllerTest oct = new OnlineControllerTest();
oct.compute();
}
private void compute() {
Entity[] entities;
StringBuilder temp = new StringBuilder();
String[] file;
ArrayList<Entity> ent = null;
City[] result;
WikiNerGraphConnector connector = WikiNerGraphConnector.getInstance("./database");
file = in.loadCompleteFile();
for (int i = 0; i < file.length; i++) {
temp.append(file[i]);
temp.append("\n");
}
try {
ent = ner.extractEntities(temp.toString());
} catch (IOException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
}
DataDump umwandler = new DataDump(ent);
entities = umwandler.getEntityList();
System.out.println("\n" + entities.length + "\n");
long start = System.currentTimeMillis();
result = ws.calculateCity(entities, "./database/");
long end = System.currentTimeMillis();
System.out.println("\n" + result.length + "\n");
for (int i = 0; i< result.length && i < 5; i++) {
System.out.println(i + ": " + result[i].getName() + " ; " + result[i].getScore());
}
System.out.println(end - start);
connector.shutdown();
}
public OnlineControllerTest() {
ner = new StanfordNER("./classifiers/english.muc.7class.distsim.crf.ser.gz");
EntityType[] entiWeig = new EntityType[8];
try {
in = new FileInput("./testDatenSatz.txt");
} catch (Exception e) {
e.printStackTrace();
}
entiWeig[0] = new EntityType("ORGANIZATION", 1.0);
entiWeig[1] = new EntityType("PERSON", 0.0);
entiWeig[2] = new EntityType("LOCATION", 2.0);
entiWeig[3] = new EntityType("MISC", 0.0);
entiWeig[4] = new EntityType("TIME", 0.0);
entiWeig[5] = new EntityType("MONEY", 0.0);
entiWeig[6] = new EntityType("PERCENT", 0.0);
entiWeig[7] = new EntityType("DATE", 0.0);
this.entiWeig = entiWeig;
ws = new WeightingSystem(this.entiWeig);
}
}
| apache-2.0 |
SnappyDataInc/snappy-store | gemfire-shared/src/main/java/com/gemstone/gemfire/internal/shared/jna/WinNativeCalls.java | 11744 | /*
* Copyright (c) 2010-2015 Pivotal Software, 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. See accompanying
* LICENSE file.
*/
/*
* Changes for SnappyData data platform.
*
* Portions Copyright (c) 2017-2019 TIBCO Software 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. See accompanying
* LICENSE file.
*/
package com.gemstone.gemfire.internal.shared.jna;
import java.io.InputStream;
import java.net.Socket;
import java.net.SocketException;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import com.gemstone.gemfire.internal.shared.NativeCalls;
import com.gemstone.gemfire.internal.shared.NativeErrorException;
import com.gemstone.gemfire.internal.shared.TCPSocketOptions;
import com.sun.jna.LastErrorException;
import com.sun.jna.Native;
import com.sun.jna.NativeLibrary;
import com.sun.jna.NativeLong;
import com.sun.jna.Pointer;
import com.sun.jna.Structure;
import com.sun.jna.ptr.IntByReference;
import com.sun.jna.win32.W32APIOptions;
/**
* Implementation of {@link NativeCalls} for Windows platforms.
*/
final class WinNativeCalls extends NativeCalls {
static {
// for socket operations
Native.register("Ws2_32");
}
@SuppressWarnings("unused")
public static final class TcpKeepAlive extends Structure {
public int enabled;
public int keepalivetime;
public int keepaliveinterval;
@Override
protected List<String> getFieldOrder() {
return Arrays.asList("enabled", "keepalivetime",
"keepaliveinterval");
}
}
public static native int WSAIoctl(NativeLong sock, int controlCode,
TcpKeepAlive value, int valueSize, Pointer outValue, int outValueSize,
IntByReference bytesReturned, Pointer overlapped,
Pointer completionRoutine) throws LastErrorException;
private static final int WSAENOPROTOOPT = 10042;
private static final int SIO_KEEPALIVE_VALS = -1744830460;
private static final class Kernel32 {
static {
/*
// kernel32 requires stdcall calling convention
Map<String, Object> kernel32Options = new HashMap<>();
kernel32Options.put(Library.OPTION_CALLING_CONVENTION,
StdCallLibrary.STDCALL_CONVENTION);
kernel32Options.put(Library.OPTION_FUNCTION_MAPPER,
StdCallLibrary.FUNCTION_MAPPER);
*/
final NativeLibrary kernel32Lib = NativeLibrary.getInstance("kernel32",
W32APIOptions.DEFAULT_OPTIONS);
Native.register(kernel32Lib);
}
// Values below from windows.h header are hard-coded since there
// does not seem any simple way to get those at build or run time.
// Hopefully these will never change else all hell will break
// loose in Windows world ...
static final int PROCESS_QUERY_INFORMATION = 0x0400;
static final int PROCESS_TERMINATE = 0x0001;
static final int STILL_ACTIVE = 259;
static final int INVALID_HANDLE = -1;
public static native boolean SetEnvironmentVariableA(String name,
String value) throws LastErrorException;
public static native int GetEnvironmentVariableA(String name,
byte[] pvalue, int psize);
public static native boolean SetCurrentDirectory(String path)
throws LastErrorException;
public static native int GetCurrentProcessId();
public static native Pointer OpenProcess(int desiredAccess,
boolean inheritHandle, int processId) throws LastErrorException;
public static native boolean TerminateProcess(Pointer processHandle,
int exitCode) throws LastErrorException;
public static native boolean GetExitCodeProcess(Pointer processHandle,
IntByReference exitCode) throws LastErrorException;
public static native boolean CloseHandle(Pointer handle)
throws LastErrorException;
}
private static final Map<String, String> javaEnv =
getModifiableJavaEnvWIN();
/**
* @see NativeCalls#getOSType()
*/
@Override
public OSType getOSType() {
return OSType.WIN;
}
/**
* @see NativeCalls#setEnvironment(String, String)
*/
@Override
public synchronized void setEnvironment(final String name,
final String value) {
if (name == null) {
throw new UnsupportedOperationException(
"setEnvironment() for name=NULL");
}
boolean res = false;
Throwable cause = null;
try {
res = Kernel32.SetEnvironmentVariableA(name, value);
} catch (LastErrorException le) {
// error code ERROR_ENVVAR_NOT_FOUND (203) indicates variable was not
// found so ignore
if (value == null && le.getErrorCode() == 203) {
res = true;
} else {
cause = new NativeErrorException(le.getMessage(), le.getErrorCode(),
le.getCause());
}
}
if (!res) {
throw new IllegalArgumentException("setEnvironment: given name=" + name
+ " (value=" + value + ')', cause);
}
// also change in java cached map
if (javaEnv != null) {
if (value != null) {
javaEnv.put(name, value);
} else {
javaEnv.remove(name);
}
}
}
/**
* @see NativeCalls#setCurrentWorkingDirectory(String)
*/
@Override
public void setCurrentWorkingDirectory(String path)
throws LastErrorException {
// set the java property separately in any case
System.setProperty("user.dir", path);
// now change the OS path
Kernel32.SetCurrentDirectory(path);
}
/**
* @see NativeCalls#getEnvironment(String)
*/
@Override
public synchronized String getEnvironment(final String name) {
if (name == null) {
throw new UnsupportedOperationException(
"getEnvironment() for name=NULL");
}
int psize = Kernel32.GetEnvironmentVariableA(name, null, 0);
if (psize > 0) {
for (; ; ) {
byte[] result = new byte[psize];
psize = Kernel32.GetEnvironmentVariableA(name, result, psize);
if (psize == (result.length - 1)) {
return new String(result, 0, psize);
} else if (psize <= 0) {
return null;
}
}
} else {
return null;
}
}
/**
* @see NativeCalls#getProcessId()
*/
@Override
public int getProcessId() {
return Kernel32.GetCurrentProcessId();
}
/**
* @see NativeCalls#isProcessActive(int)
*/
@Override
public boolean isProcessActive(final int processId) {
try {
final Pointer procHandle = Kernel32.OpenProcess(
Kernel32.PROCESS_QUERY_INFORMATION, false, processId);
final long hval;
if (procHandle == null || (hval = Pointer.nativeValue(procHandle)) ==
Kernel32.INVALID_HANDLE || hval == 0) {
return false;
} else {
final IntByReference status = new IntByReference();
final boolean result = Kernel32.GetExitCodeProcess(procHandle, status)
&& status.getValue() == Kernel32.STILL_ACTIVE;
Kernel32.CloseHandle(procHandle);
return result;
}
} catch (LastErrorException le) {
// some problem in getting process status
return false;
}
}
/**
* @see NativeCalls#killProcess(int)
*/
@Override
public boolean killProcess(final int processId) {
try {
final Pointer procHandle = Kernel32.OpenProcess(
Kernel32.PROCESS_TERMINATE, false, processId);
final long hval;
if (procHandle == null || (hval = Pointer.nativeValue(procHandle)) ==
Kernel32.INVALID_HANDLE || hval == 0) {
return false;
} else {
final boolean result = Kernel32.TerminateProcess(procHandle, -1);
Kernel32.CloseHandle(procHandle);
return result;
}
} catch (LastErrorException le) {
// some problem in killing the process
return false;
}
}
/**
* {@inheritDoc}
*/
@Override
public void daemonize(RehashServerOnSIGHUP callback)
throws UnsupportedOperationException, IllegalStateException {
throw new IllegalStateException(
"daemonize() not applicable for Windows platform");
}
/**
* {@inheritDoc}
*/
@Override
public Map<TCPSocketOptions, Throwable> setSocketOptions(Socket sock,
InputStream sockStream, Map<TCPSocketOptions, Object> optValueMap)
throws UnsupportedOperationException {
final TcpKeepAlive optValue = new TcpKeepAlive();
final int optSize = (Integer.SIZE / Byte.SIZE) * 3;
TCPSocketOptions errorOpt = null;
Throwable error = null;
for (Map.Entry<TCPSocketOptions, Object> e : optValueMap.entrySet()) {
TCPSocketOptions opt = e.getKey();
Object value = e.getValue();
// all options currently require an integer argument
if (value == null || !(value instanceof Integer)) {
throw new IllegalArgumentException("bad argument type "
+ (value != null ? value.getClass().getName() : "NULL") + " for "
+ opt);
}
switch (opt) {
case OPT_KEEPIDLE:
optValue.enabled = 1;
// in millis
optValue.keepalivetime = (Integer)value * 1000;
break;
case OPT_KEEPINTVL:
optValue.enabled = 1;
// in millis
optValue.keepaliveinterval = (Integer)value * 1000;
break;
case OPT_KEEPCNT:
errorOpt = opt;
error = new UnsupportedOperationException(
getUnsupportedSocketOptionMessage(opt));
break;
default:
throw new UnsupportedOperationException("unknown option " + opt);
}
}
final int sockfd = getSocketKernelDescriptor(sock, sockStream);
final IntByReference nBytes = new IntByReference(0);
try {
if (WSAIoctl(new NativeLong(sockfd), SIO_KEEPALIVE_VALS, optValue,
optSize, null, 0, nBytes, null, null) != 0) {
errorOpt = TCPSocketOptions.OPT_KEEPIDLE; // using some option here
error = new SocketException(getOSType() + ": error setting options: "
+ optValueMap);
}
} catch (LastErrorException le) {
// check if the error indicates that option is not supported
errorOpt = TCPSocketOptions.OPT_KEEPIDLE; // using some option here
if (le.getErrorCode() == WSAENOPROTOOPT) {
error = new UnsupportedOperationException(
getUnsupportedSocketOptionMessage(errorOpt),
new NativeErrorException(le.getMessage(), le.getErrorCode(),
le.getCause()));
} else {
final SocketException se = new SocketException(getOSType()
+ ": failed to set options: " + optValueMap);
se.initCause(le);
error = se;
}
}
return errorOpt != null ? Collections.singletonMap(errorOpt, error)
: null;
}
}
| apache-2.0 |
googleads/googleads-java-lib | modules/dfp_appengine/src/main/java/com/google/api/ads/admanager/jaxws/v202108/LabelEntityAssociationErrorReason.java | 2521 | // Copyright 2021 Google LLC
//
// 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.google.api.ads.admanager.jaxws.v202108;
import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for LabelEntityAssociationError.Reason.
*
* <p>The following schema fragment specifies the expected content contained within this class.
* <p>
* <pre>
* <simpleType name="LabelEntityAssociationError.Reason">
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <enumeration value="DUPLICATE_ASSOCIATION"/>
* <enumeration value="INVALID_ASSOCIATION"/>
* <enumeration value="NEGATION_NOT_ALLOWED"/>
* <enumeration value="DUPLICATE_ASSOCIATION_WITH_NEGATION"/>
* <enumeration value="UNKNOWN"/>
* </restriction>
* </simpleType>
* </pre>
*
*/
@XmlType(name = "LabelEntityAssociationError.Reason")
@XmlEnum
public enum LabelEntityAssociationErrorReason {
/**
*
* The label has already been attached to the entity.
*
*
*/
DUPLICATE_ASSOCIATION,
/**
*
* A label is being applied to an entity that does not support that entity
* type.
*
*
*/
INVALID_ASSOCIATION,
/**
*
* Label negation cannot be applied to the entity type.
*
*
*/
NEGATION_NOT_ALLOWED,
/**
*
* The same label is being applied and negated to the same entity.
*
*
*/
DUPLICATE_ASSOCIATION_WITH_NEGATION,
/**
*
* The value returned if the actual value is not exposed by the requested API version.
*
*
*/
UNKNOWN;
public String value() {
return name();
}
public static LabelEntityAssociationErrorReason fromValue(String v) {
return valueOf(v);
}
}
| apache-2.0 |
kubatatami/JudoNetworking | base/src/main/java/com/github/kubatatami/judonetworking/controllers/raw/Converter.java | 415 | package com.github.kubatatami.judonetworking.controllers.raw;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Created by Kuba on 01/09/15.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.PARAMETER})
public @interface Converter {
Class<? extends RestConverter<?>> value();
}
| apache-2.0 |
mp911de/spinach | src/main/java/biz/paluch/spinach/api/async/DisqueQueueAsyncCommands.java | 4787 | /*
* Copyright 2016 the original author or authors.
*
* 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 biz.paluch.spinach.api.async;
import java.util.List;
import java.util.Map;
import biz.paluch.spinach.api.Job;
import biz.paluch.spinach.api.PauseArgs;
import biz.paluch.spinach.api.QScanArgs;
import com.lambdaworks.redis.KeyScanCursor;
import com.lambdaworks.redis.RedisFuture;
import com.lambdaworks.redis.ScanCursor;
/**
* Asynchronous executed commands related with Disque Queues.
*
* @param <K> Key type.
* @param <V> Value type.
* @author Mark Paluch
*/
public interface DisqueQueueAsyncCommands<K, V> {
/**
* Remove the job from the queue.
*
* @param jobIds the job Id's
* @return the number of jobs actually moved from queue to active state
*/
RedisFuture<Long> dequeue(String... jobIds);
/**
* Queue jobs if not already queued.
*
* @param jobIds the job Id's
* @return the number of jobs actually move from active to queued state
*/
RedisFuture<Long> enqueue(String... jobIds);
/**
* Queue jobs if not already queued and increment the nack counter.
*
* @param jobIds the job Id's
* @return the number of jobs actually move from active to queued state
*/
RedisFuture<Long> nack(String... jobIds);
/**
* Change the {@literal PAUSE} pause state to:
* <ul>
* <li>Pause a queue</li>
* <li>Clear the pause state for a queue</li>
* <li>Query the pause state</li>
* <li>Broadcast the pause state</li>
* </ul>
*
* @param queue the queue name
* @param pauseArgs the pause args
* @return pause state of the queue.
*/
RedisFuture<String> pause(K queue, PauseArgs pauseArgs);
/**
* Return the number of jobs queued.
*
* @param queue the queue name
* @return the number of jobs queued
*/
RedisFuture<Long> qlen(K queue);
/**
* Return an array of at most "count" jobs available inside the queue "queue" without removing the jobs from the queue. This
* is basically an introspection and debugging command.
*
* @param queue the queue name
* @param count number of jobs to return
* @return List of jobs.
*/
RedisFuture<List<Job<K, V>>> qpeek(K queue, long count);
/**
* Incrementally iterate the keys space.
*
* @return KeyScanCursor<K> scan cursor.
*/
RedisFuture<KeyScanCursor<K>> qscan();
/**
* Incrementally iterate the keys space.
*
* @param scanArgs scan arguments
* @return KeyScanCursor<K> scan cursor.
*/
RedisFuture<KeyScanCursor<K>> qscan(QScanArgs scanArgs);
/**
* Incrementally iterate the keys space.
*
* @param scanCursor cursor to resume from a previous scan
* @return KeyScanCursor<K> scan cursor.
*/
RedisFuture<KeyScanCursor<K>> qscan(ScanCursor scanCursor);
/**
* Incrementally iterate the keys space.
*
* @param scanCursor cursor to resume from a previous scan
* @param scanArgs scan arguments
* @return KeyScanCursor<K> scan cursor.
*/
RedisFuture<KeyScanCursor<K>> qscan(ScanCursor scanCursor, QScanArgs scanArgs);
/**
* Retrieve information about a queue as key value pairs.
*
* @param queue the queue name
* @return map containing the statistics (key value pairs)
*/
RedisFuture<Map<String, Object>> qstat(K queue);
/**
* If the job is queued, remove it from queue and change state to active. Postpone the job requeue time in the future so
* that we'll wait the retry time before enqueueing again.
*
* * Return how much time the worker likely have before the next requeue event or an error:
* <ul>
* <li>-ACKED: The job is already acknowledged, so was processed already.</li>
* <li>-NOJOB We don't know about this job. The job was either already acknowledged and purged, or this node never received
* a copy.</li>
* <li>-TOOLATE 50% of the job TTL already elapsed, is no longer possible to delay it.</li>
* </ul>
*
* @param jobId the job Id
* @return retry count.
*/
RedisFuture<Long> working(String jobId);
}
| apache-2.0 |
desruisseaux/sis | core/sis-referencing/src/main/java/org/apache/sis/internal/jaxb/referencing/CC_Conversion.java | 5482 | /*
* 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.sis.internal.jaxb.referencing;
import javax.xml.bind.annotation.XmlElement;
import org.opengis.referencing.crs.SingleCRS;
import org.opengis.referencing.operation.Conversion;
import org.apache.sis.internal.jaxb.Context;
import org.apache.sis.internal.jaxb.gco.PropertyType;
import org.apache.sis.referencing.operation.DefaultConversion;
/**
* JAXB adapter mapping implementing class to the GeoAPI interface. See
* package documentation for more information about JAXB and interface.
*
* @author Martin Desruisseaux (Geomatys)
* @since 0.6
* @version 0.7
* @module
*/
public final class CC_Conversion extends PropertyType<CC_Conversion, Conversion> {
/**
* Temporary storage for the {@code baseCRS} during {@link org.apache.sis.referencing.crs.AbstractDerivedCRS}
* unmarshalling. A temporary location is needed because {@code AbstractDerivedCRS} does not have any explicit
* field for {@code baseCRS}.
*
* @see #setBaseCRS(Conversion, SingleCRS)
*/
private SingleCRS baseCRS;
/**
* Empty constructor for JAXB only.
*/
public CC_Conversion() {
}
/**
* Returns the GeoAPI interface which is bound by this adapter.
* This method is indirectly invoked by the private constructor
* below, so it shall not depend on the state of this object.
*
* @return {@code Conversion.class}
*/
@Override
protected Class<Conversion> getBoundType() {
return Conversion.class;
}
/**
* Constructor for the {@link #wrap} method only.
*/
private CC_Conversion(final Conversion conversion) {
super(conversion);
}
/**
* Invoked by {@link PropertyType} at marshalling time for wrapping the given value
* in a {@code <gml:Conversion>} XML element.
*
* @param conversion The element to marshall.
* @return A {@code PropertyType} wrapping the given the element.
*/
@Override
protected CC_Conversion wrap(final Conversion conversion) {
return new CC_Conversion(conversion);
}
/**
* Invoked by JAXB at marshalling time for getting the actual element to write
* inside the {@code <gml:Conversion>} XML element.
* This is the value or a copy of the value given in argument to the {@code wrap} method.
*
* @return The element to be marshalled.
*/
@XmlElement(name = "Conversion")
public DefaultConversion getElement() {
return DefaultConversion.castOrCopy(metadata);
}
/**
* Invoked by JAXB at unmarshalling time for storing the result temporarily.
*
* @param conversion The unmarshalled element.
*/
public void setElement(final DefaultConversion conversion) {
metadata = conversion;
Context.setWrapper(Context.current(), this);
if (conversion.getMethod() == null) incomplete("method");
}
/**
* Temporarily stores the {@code baseCRS} associated to the given {@code Conversion}. This temporary storage is
* needed because {@code org.apache.sis.referencing.crs.AbstractDerivedCRS} does not have any explicit field for
* {@code baseCRS}. Instead the base CRS is stored in {@link Conversion#getSourceCRS()}, but we can set this
* property only after the {@code DerivedCRS} coordinate system has been unmarshalled.
*
* See {@code AbstractDerivedCRS.afterUnmarshal(Unmarshaller, Object parent)} for more information.
*
* @param conversion The conversion to which to associate a base CRS.
* @param crs The base CRS to associate to the given conversion.
* @return The previous base CRS, or {@code null} if none.
*/
public static SingleCRS setBaseCRS(final Conversion conversion, final SingleCRS crs) {
/*
* Implementation note: we store the base CRS in the marshalling context because:
*
* - we want to keep each thread isolated (using ThreadLocal), and
* - we want to make sure that the reference is disposed even if the unmarshaller throws an exception.
* This is guaranteed because the Context is disposed by Apache SIS in "try … finally" constructs.
*/
final PropertyType<?,?> wrapper = Context.getWrapper(Context.current());
if (wrapper instanceof CC_Conversion) {
final CC_Conversion c = (CC_Conversion) wrapper;
if (c.getElement() == conversion) { // For making sure that we do not confuse with another conversion.
final SingleCRS previous = c.baseCRS;
c.baseCRS = crs;
return previous;
}
}
return null;
}
}
| apache-2.0 |
redox/OrientDB | core/src/main/java/com/orientechnologies/orient/core/serialization/serializer/OJSONWriter.java | 11256 | /*
* Copyright 2010-2012 Luca Garulli (l.garulli--at--orientechnologies.com)
*
* 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.orientechnologies.orient.core.serialization.serializer;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.reflect.Array;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import com.orientechnologies.common.log.OLogManager;
import com.orientechnologies.orient.core.db.record.OIdentifiable;
import com.orientechnologies.orient.core.db.record.ORecordLazyMultiValue;
import com.orientechnologies.orient.core.id.ORecordId;
import com.orientechnologies.orient.core.record.ORecord;
import com.orientechnologies.orient.core.serialization.OBase64Utils;
import com.orientechnologies.orient.core.serialization.serializer.record.string.ORecordSerializerJSON;
@SuppressWarnings("unchecked")
public class OJSONWriter {
private static final String DEF_FORMAT = "rid,type,version,class,attribSameRow,indent:6";
private Writer out;
private boolean prettyPrint = true;
private boolean firstAttribute = true;
private final String format;
public OJSONWriter(final Writer out, final String iJsonFormat) {
this.out = out;
format = iJsonFormat;
}
public OJSONWriter(final Writer out) {
this.out = out;
this.format = DEF_FORMAT;
}
public OJSONWriter beginObject() throws IOException {
beginObject(0, false, null);
return this;
}
public OJSONWriter beginObject(final int iIdentLevel) throws IOException {
beginObject(iIdentLevel, false, null);
return this;
}
public OJSONWriter beginObject(final Object iName) throws IOException {
beginObject(0, false, iName);
return this;
}
public OJSONWriter beginObject(final int iIdentLevel, final boolean iNewLine, final Object iName) throws IOException {
if (!firstAttribute)
out.append(", ");
format(iIdentLevel, iNewLine);
if (iName != null)
out.append("\"" + iName.toString() + "\":");
out.append('{');
firstAttribute = true;
return this;
}
public OJSONWriter writeRecord(final int iIdentLevel, final boolean iNewLine, final Object iName, final ORecord<?> iRecord)
throws IOException {
if (!firstAttribute)
out.append(", ");
format(iIdentLevel, iNewLine);
if (iName != null)
out.append("\"" + iName.toString() + "\":");
out.append(iRecord.toJSON(format));
firstAttribute = false;
return this;
}
public OJSONWriter endObject() throws IOException {
format(0, true);
out.append('}');
return this;
}
public OJSONWriter endObject(final int iIdentLevel) throws IOException {
return endObject(iIdentLevel, true);
}
public OJSONWriter endObject(final int iIdentLevel, final boolean iNewLine) throws IOException {
format(iIdentLevel, iNewLine);
out.append('}');
firstAttribute = false;
return this;
}
public OJSONWriter beginCollection(final int iIdentLevel, final boolean iNewLine, final String iName) throws IOException {
if (!firstAttribute)
out.append(", ");
format(iIdentLevel, iNewLine);
if (iName != null && !iName.isEmpty()) {
out.append(writeValue(iName));
out.append(": ");
}
out.append("[");
firstAttribute = true;
return this;
}
public OJSONWriter endCollection(final int iIdentLevel, final boolean iNewLine) throws IOException {
format(iIdentLevel, iNewLine);
firstAttribute = false;
out.append(']');
return this;
}
public void writeObjects(int iIdentLevel, boolean iNewLine, final String iName, Object[]... iPairs) throws IOException {
for (int i = 0; i < iPairs.length; ++i) {
beginObject(iIdentLevel, true, iName);
for (int k = 0; k < iPairs[i].length;) {
writeAttribute(iIdentLevel + 1, false, (String) iPairs[i][k++], iPairs[i][k++], format);
}
endObject(iIdentLevel, false);
}
}
public OJSONWriter writeAttribute(final int iIdentLevel, final boolean iNewLine, final String iName, final Object iValue)
throws IOException {
return writeAttribute(iIdentLevel, iNewLine, iName, iValue, format);
}
public OJSONWriter writeAttribute(final int iIdentLevel, final boolean iNewLine, final String iName, final Object iValue,
final String iFormat) throws IOException {
if (!firstAttribute)
out.append(", ");
format(iIdentLevel, iNewLine);
out.append(writeValue(iName, iFormat));
out.append(": ");
out.append(writeValue(iValue, iFormat));
firstAttribute = false;
return this;
}
public OJSONWriter writeValue(final int iIdentLevel, final boolean iNewLine, final Object iValue) throws IOException {
if (!firstAttribute)
out.append(", ");
format(iIdentLevel, iNewLine);
out.append(writeValue(iValue, format));
firstAttribute = false;
return this;
}
public static String writeValue(final Object iValue) throws IOException {
return writeValue(iValue, DEF_FORMAT);
}
public static String writeValue(final Object iValue, final String iFormat) throws IOException {
final StringBuilder buffer = new StringBuilder();
final boolean oldAutoConvertSettings;
if (iValue instanceof ORecordLazyMultiValue) {
oldAutoConvertSettings = ((ORecordLazyMultiValue) iValue).isAutoConvertToRecord();
((ORecordLazyMultiValue) iValue).setAutoConvertToRecord(false);
} else
oldAutoConvertSettings = false;
if (iValue == null)
buffer.append("null");
else if (iValue instanceof ORecordId) {
final ORecordId rid = (ORecordId) iValue;
buffer.append('\"');
rid.toString(buffer);
buffer.append('\"');
} else if (iValue instanceof ORecord<?>) {
final ORecord<?> linked = (ORecord<?>) iValue;
if (linked.getIdentity().isValid()) {
buffer.append('\"');
linked.getIdentity().toString(buffer);
buffer.append('\"');
} else {
buffer.append(linked.toJSON(iFormat));
}
} else if (iValue.getClass().isArray()) {
if (iValue instanceof byte[]) {
buffer.append('\"');
final byte[] source = (byte[]) iValue;
buffer.append(OBase64Utils.encodeBytes(source));
buffer.append('\"');
} else {
buffer.append('[');
for (int i = 0; i < Array.getLength(iValue); ++i) {
if (i > 0)
buffer.append(", ");
buffer.append(writeValue(Array.get(iValue, i), iFormat));
}
buffer.append(']');
}
} else if (iValue instanceof Collection<?>) {
final Collection<Object> coll = (Collection<Object>) iValue;
buffer.append('[');
int i = 0;
for (Iterator<Object> it = coll.iterator(); it.hasNext(); ++i) {
if (i > 0)
buffer.append(", ");
buffer.append(writeValue(it.next(), iFormat));
}
buffer.append(']');
} else if (iValue instanceof Map<?, ?>) {
final Map<Object, Object> map = (Map<Object, Object>) iValue;
buffer.append('{');
int i = 0;
Entry<Object, Object> entry;
for (Iterator<Entry<Object, Object>> it = map.entrySet().iterator(); it.hasNext(); ++i) {
entry = it.next();
if (i > 0)
buffer.append(", ");
buffer.append(writeValue(entry.getKey(), iFormat));
buffer.append(": ");
buffer.append(writeValue(entry.getValue(), iFormat));
}
buffer.append('}');
} else if (iValue instanceof Date) {
final SimpleDateFormat dateFormat = new SimpleDateFormat(ORecordSerializerJSON.DEF_DATE_FORMAT);
buffer.append('"');
buffer.append(dateFormat.format(iValue));
buffer.append('"');
} else if (iValue instanceof String) {
final String v = (String) iValue;
if (v.startsWith("\""))
buffer.append(v);
else {
buffer.append('"');
buffer.append(encode(v));
buffer.append('"');
}
} else
buffer.append(iValue.toString());
if (iValue instanceof ORecordLazyMultiValue)
((ORecordLazyMultiValue) iValue).setAutoConvertToRecord(oldAutoConvertSettings);
return buffer.toString();
}
public OJSONWriter flush() throws IOException {
out.flush();
return this;
}
public OJSONWriter close() throws IOException {
out.close();
return this;
}
private OJSONWriter format(final int iIdentLevel, final boolean iNewLine) throws IOException {
if (iNewLine) {
newline();
if (prettyPrint)
for (int i = 0; i < iIdentLevel; ++i)
out.append(" ");
}
return this;
}
public OJSONWriter append(final String iText) throws IOException {
out.append(iText);
return this;
}
public boolean isPrettyPrint() {
return prettyPrint;
}
public OJSONWriter setPrettyPrint(boolean prettyPrint) {
this.prettyPrint = prettyPrint;
return this;
}
public void write(final String iText) throws IOException {
out.append(iText);
}
public static Object encode(final Object iValue) {
if (iValue instanceof String) {
return OStringSerializerHelper.java2unicode(((String) iValue).replace("\\", "\\\\").replace("\"", "\\\""));
} else
return iValue;
}
public static String listToJSON(Collection<? extends OIdentifiable> iRecords) throws IOException {
final StringWriter buffer = new StringWriter();
final OJSONWriter json = new OJSONWriter(buffer);
// WRITE RECORDS
json.beginCollection(0, false, null);
if (iRecords != null) {
int counter = 0;
String objectJson;
for (OIdentifiable rec : iRecords) {
if (rec != null)
try {
objectJson = rec.getRecord().toJSON();
if (counter++ > 0)
buffer.append(", ");
buffer.append(objectJson);
} catch (Exception e) {
OLogManager.instance().error(json, "Error transforming record " + rec.getIdentity() + " to JSON", e);
}
}
}
json.endCollection(0, false);
return buffer.toString();
}
public void newline() throws IOException {
out.append("\r\n");
}
public void resetAttributes() {
firstAttribute = true;
}
}
| apache-2.0 |
mufengxuxu/myworks | i18ntoolkit/src/main/java/com/ibm/i18n/model/KeyValueBean.java | 3400 | package com.ibm.i18n.model;
import org.apache.commons.lang.StringUtils;
import com.ibm.i18n.util.ChartUtil;
import com.ibm.i18n.util.StringUtil;
import com.ibm.i18n.util.ValueUtil;
public class KeyValueBean {
private String base = "";
private String key = "";
private String value = "";
private String unicodeValue = "";
private String valueEn = "";
public KeyValueBean(String[] values) {
this.base = values[0];
this.key = values[1];
this.value = values[2];
this.valueEn = values[3];
}
public KeyValueBean(String base, String key, String value) {
this.base = base;
this.key = key;
this.value = value;
this.valueEn = value;
}
public KeyValueBean(String base, String key) {
this.base = base;
this.key = key;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return base + "," + key + ",\"" + getValue() + "\",\"" + getValueEn4Report() + "\"";
}
/**
* @return the base
*/
public String getBase() {
return base;
}
/**
* @param base
* the base to set
*/
public void setBase(String base) {
this.base = base;
}
/**
* @return the key
*/
public String getKey() {
return key;
}
/**
* @param key
* the key to set
*/
public void setKey(String key) {
this.key = key;
}
/**
* @return the value
*/
public String getValue() {
if (StringUtils.isEmpty(value) && StringUtils.isNotEmpty(unicodeValue)) {
return ChartUtil.decodeUnicode(unicodeValue);
} else {
return ValueUtil.replaceAllLF(value);
}
}
/**
* @param value
* the value to set
*/
public void setValue(String value) {
this.value = value;
}
/**
* @return the valueEn
*/
public String getValueEn() {
if (value.equals(valueEn) && StringUtil.containsChinese(valueEn)) {
return getUnicodeValue();
} else if (StringUtils.isEmpty(valueEn)) {
return getUnicodeValue();
} else {
return valueEn;
}
}
/**
* @return the valueEn
*/
public String getValueEn4Report() {
if (value.equals(valueEn) || unicodeValue.equals(valueEn)) {
return getValue();
} else {
return valueEn;
}
}
/**
* @param valueEn
* the valueEn to set
*/
public void setValueEn(String valueEn) {
this.valueEn = (valueEn == null ? "" : valueEn);
}
/**
* @return the unicodeValue
*/
public String getUnicodeValue() {
if (StringUtils.isEmpty(unicodeValue) && StringUtils.isNotEmpty(value)) {
if (StringUtil.containsChinese(value)) {
return ChartUtil.toUnicode(ValueUtil.replaceAllLF(value), true);
} else {
return ValueUtil.replaceAllLF(value);
}
} else {
return unicodeValue;
}
}
/**
* @param unicodeValue
* the unicodeValue to set
*/
public void setUnicodeValue(String unicodeValue) {
this.unicodeValue = unicodeValue;
}
}
| apache-2.0 |
abeemukthees/Arena | Domain/src/main/java/msa/domain/interactor/old/UseCaseTypeTwo.java | 3352 | /*
* Copyright 2017, Abhi Muktheeswarar
*
* 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 msa.domain.interactor.old;
import com.fernandocejas.arrow.checks.Preconditions;
import io.reactivex.Flowable;
import io.reactivex.Observable;
import io.reactivex.Scheduler;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.observers.DisposableObserver;
/**
* Abstract class for a Use Case (Interactor in terms of Clean Architecture).
* This interface represents a execution unit for different use cases (this means any use case
* in the application should implement this contract).
* <p>
* By convention each UseCase implementation will return the result using a {@link DisposableObserver}
* that will execute its job in a background thread and will post the result in the UI thread.
*/
public abstract class UseCaseTypeTwo<T, Params> {
private final Scheduler mExecutorThread;
private final Scheduler mUiThread;
private final CompositeDisposable disposables;
public UseCaseTypeTwo(Scheduler mUiThread, Scheduler mExecutorThread) {
this.mExecutorThread = mUiThread;
this.mUiThread = mExecutorThread;
this.disposables = new CompositeDisposable();
}
/**
* Builds an {@link Observable} which will be used when executing the current {@link UseCaseTypeTwo}.
*/
protected abstract Flowable<T> buildUseCaseObservable(Params params);
/**
* Executes the current use case.
*
* @param observer {@link DisposableObserver} which will be listening to the observable build
* by {@link #buildUseCaseObservable(Params)} ()} method.
* @param params Parameters (Optional) used to build/execute this use case.
*/
/*public void execute(DisposableObserver<T> observer, Params params) {
Preconditions.checkNotNull(observer);
final Observable<T> observable = this.buildUseCaseObservable(params)
.subscribeOn(mExecutorThread)
.observeOn(mUiThread);
addDisposable(observable.subscribeWith(observer));
}*/
public Flowable<T> execute(Params params) {
Preconditions.checkNotNull(params);
return this.buildUseCaseObservable(params)
.subscribeOn(mExecutorThread)
.observeOn(mUiThread);
}
/**
* Dispose from current {@link CompositeDisposable}.
*/
public void dispose() {
if (!disposables.isDisposed()) {
disposables.dispose();
}
}
/**
* Dispose from current {@link CompositeDisposable}.
*/
private void addDisposable(Disposable disposable) {
Preconditions.checkNotNull(disposable);
Preconditions.checkNotNull(disposables);
disposables.add(disposable);
}
}
| apache-2.0 |
flipkart-incubator/async-http-client | providers/grizzly/src/main/java/org/asynchttpclient/providers/grizzly/filters/SwitchingSSLFilter.java | 6339 | /*
* Copyright (c) 2013 Sonatype, Inc. All rights reserved.
*
* This program is licensed to you under the Apache License Version 2.0,
* and you may not use this file except in compliance with the Apache License Version 2.0.
* You may obtain a copy of the Apache License Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0.
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Apache License Version 2.0 is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Apache License Version 2.0 for the specific language governing permissions and limitations there under.
*/
package org.asynchttpclient.providers.grizzly.filters;
import org.asynchttpclient.providers.grizzly.filters.events.SSLSwitchingEvent;
import org.glassfish.grizzly.Connection;
import org.glassfish.grizzly.EmptyCompletionHandler;
import org.glassfish.grizzly.Grizzly;
import org.glassfish.grizzly.IOEvent;
import org.glassfish.grizzly.attributes.Attribute;
import org.glassfish.grizzly.filterchain.FilterChain;
import org.glassfish.grizzly.filterchain.FilterChainContext;
import org.glassfish.grizzly.filterchain.FilterChainEvent;
import org.glassfish.grizzly.filterchain.NextAction;
import org.glassfish.grizzly.ssl.SSLEngineConfigurator;
import org.glassfish.grizzly.ssl.SSLFilter;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLHandshakeException;
import java.io.IOException;
/**
* SSL Filter that may be present within the FilterChain and may be
* enabled/disabled by sending the appropriate {@link SSLSwitchingEvent}.
*
* @since 2.0
* @author The Grizzly Team
*/
public final class SwitchingSSLFilter extends SSLFilter {
private static final Attribute<Boolean> CONNECTION_IS_SECURE = Grizzly.DEFAULT_ATTRIBUTE_BUILDER
.createAttribute(SwitchingSSLFilter.class.getName());
private static final Attribute<Throwable> HANDSHAKE_ERROR = Grizzly.DEFAULT_ATTRIBUTE_BUILDER.createAttribute(SwitchingSSLFilter.class
.getName() + "-HANDSHAKE-ERROR");
// ------------------------------------------------------------ Constructors
public SwitchingSSLFilter(final SSLEngineConfigurator clientConfig) {
super(null, clientConfig);
}
// -------------------------------------------------- Methods from SSLFilter
@Override
protected void notifyHandshakeFailed(Connection connection, Throwable t) {
setError(connection, t);
}
@Override
public NextAction handleConnect(final FilterChainContext ctx) throws IOException {
// Suspend further handleConnect processing. We do this to ensure that
// the SSL handshake has been completed before returning the connection
// for use in processing user requests. Additionally, this allows us
// to determine if a connection is SPDY or HTTP as early as possible.
ctx.suspend();
final Connection c = ctx.getConnection();
handshake(ctx.getConnection(), new EmptyCompletionHandler<SSLEngine>() {
@Override
public void completed(SSLEngine result) {
// Handshake was successful. Resume the handleConnect
// processing. We pass in Invoke Action so the filter
// chain will call handleConnect on the next filter.
ctx.resume(ctx.getInvokeAction());
}
@Override
public void cancelled() {
// Handshake was cancelled. Stop the handleConnect
// processing. The exception will be checked and
// passed to the user later.
setError(c, new SSLHandshakeException("Handshake canceled."));
ctx.resume(ctx.getStopAction());
}
@Override
public void failed(Throwable throwable) {
// Handshake failed. Stop the handleConnect
// processing. The exception will be checked and
// passed to the user later.
setError(c, throwable);
ctx.resume(ctx.getStopAction());
}
});
// This typically isn't advised, however, we need to be able to
// read the response from the proxy and OP_READ isn't typically
// enabled on the connection until all of the handleConnect()
// processing is complete.
enableRead(c);
// Tell the FilterChain that we're suspending further handleConnect
// processing.
return ctx.getSuspendAction();
}
@Override
public NextAction handleEvent(final FilterChainContext ctx, final FilterChainEvent event) throws IOException {
if (event.type() == SSLSwitchingEvent.class) {
final SSLSwitchingEvent se = (SSLSwitchingEvent) event;
setSecureStatus(se.getConnection(), se.isSecure());
return ctx.getStopAction();
}
return ctx.getInvokeAction();
}
@Override
public NextAction handleRead(final FilterChainContext ctx) throws IOException {
if (isSecure(ctx.getConnection())) {
return super.handleRead(ctx);
}
return ctx.getInvokeAction();
}
@Override
public NextAction handleWrite(final FilterChainContext ctx) throws IOException {
if (isSecure(ctx.getConnection())) {
return super.handleWrite(ctx);
}
return ctx.getInvokeAction();
}
@Override
public void onFilterChainChanged(final FilterChain filterChain) {
// no-op
}
public static Throwable getHandshakeError(final Connection c) {
return HANDSHAKE_ERROR.remove(c);
}
// --------------------------------------------------------- Private Methods
private static boolean isSecure(final Connection c) {
Boolean secStatus = CONNECTION_IS_SECURE.get(c);
return (secStatus == null ? true : secStatus);
}
private static void setSecureStatus(final Connection c, final boolean secure) {
CONNECTION_IS_SECURE.set(c, secure);
}
private static void setError(final Connection c, Throwable t) {
HANDSHAKE_ERROR.set(c, t);
}
private static void enableRead(final Connection c) throws IOException {
c.enableIOEvent(IOEvent.READ);
}
}
| apache-2.0 |
duanze/PureNote | gasst/src/main/java/com/duanze/gasst/ui/adapter/GNoteRVAdapter.java | 11490 | package com.duanze.gasst.ui.adapter;
import android.content.Context;
import android.database.Cursor;
import android.support.v7.widget.RecyclerView;
import android.util.SparseIntArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.duanze.gasst.R;
import com.duanze.gasst.ui.activity.Note;
import com.duanze.gasst.data.model.GNote;
import com.duanze.gasst.util.GNotebookUtil;
import com.duanze.gasst.util.ProviderUtil;
import com.duanze.gasst.util.TimeUtils;
import com.duanze.gasst.util.Util;
import com.duanze.gasst.util.liteprefs.MyLitePrefs;
import java.util.HashMap;
import java.util.Set;
/**
* Created by Duanze on 2015/10/4.
*/
public class GNoteRVAdapter extends RecyclerView.Adapter<GNoteRVAdapter.GNoteItemHolder>
implements View.OnClickListener, View.OnLongClickListener {
private static final String TAG = GNoteRVAdapter.class.getSimpleName();
private LayoutInflater mInflater;
private Cursor mCursor;
private boolean mDataValid;
private Context mContext;
private boolean mCheckMode;
private HashMap<Integer, GNote> mCheckedItems;
private ItemLongPressedListener mItemLongPressedListener;
private OnItemSelectListener mOnItemSelectListener;
public interface ItemLongPressedListener {
void startActionMode();
}
public interface OnItemSelectListener {
void onSelect();
void onCancelSelect();
}
public void setmItemLongPressedListener(ItemLongPressedListener mItemLongPressedListener) {
this.mItemLongPressedListener = mItemLongPressedListener;
}
public void setmOnItemSelectListener(OnItemSelectListener mOnItemSelectListener) {
this.mOnItemSelectListener = mOnItemSelectListener;
}
public GNoteRVAdapter(Context context, Cursor cursor) {
mContext = context;
mInflater = LayoutInflater.from(context);
mCursor = cursor;
boolean cursorPresent = null != cursor;
mDataValid = cursorPresent;
}
public GNoteRVAdapter(Context context, Cursor cursor, OnItemSelectListener
onItemSelectListener, ItemLongPressedListener itemLongPressedListener) {
this(context, cursor);
mOnItemSelectListener = onItemSelectListener;
mItemLongPressedListener = itemLongPressedListener;
}
public Cursor getCursor() {
return mCursor;
}
/**
* Swap in a new Cursor, returning the old Cursor. Unlike
* {@link #changeCursor(Cursor)}, the returned old Cursor is <em>not</em>
* closed.
*
* @param newCursor The new cursor to be used.
* @return Returns the previously set Cursor, or null if there wasa not one.
* If the given new Cursor is the same instance is the previously set
* Cursor, null is also returned.
*/
public Cursor swapCursor(Cursor newCursor) {
if (newCursor == mCursor) {
return null;
}
Cursor oldCursor = mCursor;
mCursor = newCursor;
if (newCursor != null) {
mDataValid = true;
// notify the observers about the new cursor
notifyDataSetChanged();
} else {
mDataValid = false;
notifyDataSetChanged();
}
return oldCursor;
}
@Override
public GNoteItemHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = mInflater.inflate(R.layout.gnote_rv_item, viewGroup, false);
GNoteItemHolder gNoteItemHolder = new GNoteItemHolder(view);
return gNoteItemHolder;
}
@Override
public void onBindViewHolder(GNoteItemHolder gNoteItemHolder, int i) {
if (!mDataValid) {
throw new IllegalStateException("this should only be called when the cursor is valid");
}
if (!mCursor.moveToPosition(i)) {
throw new IllegalStateException("couldn't move cursor to position " + i);
}
GNote gNote = new GNote(mCursor);
gNoteItemHolder.itemLayout.setTag(R.string.gnote_data, gNote);
gNoteItemHolder.itemLayout.setOnClickListener(this);
gNoteItemHolder.itemLayout.setOnLongClickListener(this);
// gNoteItemHolder.title.setText(gNote.getContentFromHtml().toString().trim());
gNoteItemHolder.title.setText(gNote.getContent());
if (!MyLitePrefs.getBoolean(MyLitePrefs.CREATE_ORDER)) {
gNoteItemHolder.editTime.setText(TimeUtils.getConciseTime(gNote.getEditTime(), mContext));
} else {
gNoteItemHolder.editTime.setText(Util.timeStamp(gNote));
}
if (!gNote.getIsPassed()) {
gNoteItemHolder.alertTime.setText(Util.timeString(gNote));
gNoteItemHolder.alertTime.setVisibility(View.VISIBLE);
} else {
gNoteItemHolder.alertTime.setVisibility(View.GONE);
}
// 主要用于批量操作时,notifyDataSetChanged()之后改变背景
if (mCheckMode) {
if (isChecked(gNote.getId())) {
gNoteItemHolder.itemLayout.setBackgroundResource(R.drawable.hover_multi_background_normal);
} else {
gNoteItemHolder.itemLayout.setBackgroundResource(R.drawable.hover_border_normal);
}
} else {
gNoteItemHolder.itemLayout.setBackgroundResource(R.drawable.hover_background);
}
}
@Override
public int getItemCount() {
if (mDataValid && null != mCursor) return mCursor.getCount();
return 0;
}
class GNoteItemHolder extends RecyclerView.ViewHolder {
View itemLayout;
TextView title;
TextView editTime;
TextView alertTime;
public GNoteItemHolder(View itemView) {
super(itemView);
itemLayout = itemView.findViewById(R.id.rv_item_container);
title = (TextView) itemView.findViewById(R.id.note_content);
editTime = (TextView) itemView.findViewById(R.id.edit_time);
alertTime = (TextView) itemView.findViewById(R.id.alert_time);
}
}
@Override
public void onClick(View v) {
if (R.id.rv_item_container == v.getId()) {
if (!mCheckMode) {
Note.actionStart(mContext, (GNote) v.getTag(R.string.gnote_data), Note.MODE_EDIT);
} else {
GNote gNote = (GNote) v.getTag(R.string.gnote_data);
toggleCheckedId(gNote.getId(), gNote, v);
}
}
}
@Override
public boolean onLongClick(View v) {
if (!mCheckMode) {
if (null != mItemLongPressedListener) {
mItemLongPressedListener.startActionMode();
}
setCheckMode(true);
}
GNote gNote = (GNote) v.getTag(R.string.gnote_data);
toggleCheckedId(gNote.getId(), gNote, v);
return true;
}
private boolean isChecked(int id) {
if (null == mCheckedItems) {
return false;
}
return mCheckedItems.containsKey(id);
}
public int getSelectedCount() {
if (mCheckedItems == null) {
return 0;
} else {
return mCheckedItems.size();
}
}
public void setCheckMode(boolean check) {
if (!check) {
mCheckedItems = null;
}
if (check != mCheckMode) {
mCheckMode = check;
notifyDataSetChanged();
}
}
public void toggleCheckedId(int _id, GNote gNote, View v) {
if (mCheckedItems == null) {
mCheckedItems = new HashMap<Integer, GNote>();
}
if (!mCheckedItems.containsKey(_id)) {
mCheckedItems.put(_id, gNote);
if (null != mOnItemSelectListener) {
mOnItemSelectListener.onSelect();
}
} else {
mCheckedItems.remove(_id);
if (null != mOnItemSelectListener) {
mOnItemSelectListener.onCancelSelect();
}
}
notifyDataSetChanged();
}
public void deleteSelectedNotes() {
if (mCheckedItems == null || mCheckedItems.size() == 0) {
return;
} else {
Set<Integer> keys = mCheckedItems.keySet();
SparseIntArray affectedNotebooks = new SparseIntArray(mCheckedItems.size());
for (Integer key : keys) {
GNote gNote = mCheckedItems.get(key);
gNote.setSynStatus(GNote.DELETE);
gNote.setDeleted(GNote.TRUE);
ProviderUtil.updateGNote(mContext, gNote);
// 更新受到影响的笔记本的应删除数值
if (0 != gNote.getGNotebookId()) {
int num = affectedNotebooks.get(gNote.getGNotebookId());
affectedNotebooks.put(gNote.getGNotebookId(), num + 1);
}
}
GNotebookUtil.updateGNotebook(mContext, 0, -mCheckedItems.size());
for (int i = 0; i < affectedNotebooks.size(); i++) {
int key = affectedNotebooks.keyAt(i);
int value = affectedNotebooks.valueAt(i);
GNotebookUtil.updateGNotebook(mContext, key, -value);
}
mCheckedItems.clear();
if (null != mOnItemSelectListener) {
mOnItemSelectListener.onCancelSelect();
}
// new Evernote(mContext).sync(true, false, null);
}
}
public void moveSelectedNotes(int toNotebookId) {
if (mCheckedItems == null || mCheckedItems.size() == 0) {
return;
} else {
Set<Integer> keys = mCheckedItems.keySet();
SparseIntArray affectedNotebooks = new SparseIntArray(mCheckedItems.size());
for (Integer key : keys) {
GNote gNote = mCheckedItems.get(key);
// 更新受到影响的笔记本中的数值
if (0 != gNote.getGNotebookId()) {
int num = affectedNotebooks.get(gNote.getGNotebookId());
affectedNotebooks.put(gNote.getGNotebookId(), num + 1);
}
gNote.setGNotebookId(toNotebookId);
ProviderUtil.updateGNote(mContext, gNote);
}
if (0 != toNotebookId) {
GNotebookUtil.updateGNotebook(mContext, toNotebookId, +mCheckedItems.size());
}
for (int i = 0; i < affectedNotebooks.size(); i++) {
int key = affectedNotebooks.keyAt(i);
int value = affectedNotebooks.valueAt(i);
GNotebookUtil.updateGNotebook(mContext, key, -value);
}
mCheckedItems.clear();
if (null != mOnItemSelectListener) {
mOnItemSelectListener.onCancelSelect();
}
}
}
public void selectAllNotes() {
for (int i = 0; i < mCursor.getCount(); i++) {
mCursor.moveToPosition(i);
GNote gNote = new GNote(mCursor);
if (mCheckedItems == null) {
mCheckedItems = new HashMap<Integer, GNote>();
}
int _id = gNote.getId();
if (!mCheckedItems.containsKey(_id)) {
mCheckedItems.put(_id, gNote);
}
}
if (null != mOnItemSelectListener) {
mOnItemSelectListener.onSelect();
}
notifyDataSetChanged();
}
}
| apache-2.0 |
dbeaver/dbeaver | plugins/org.jkiss.dbeaver.ui.editors.data/src/org/jkiss/dbeaver/ui/data/registry/ValueManagerRegistry.java | 6711 | /*
* DBeaver - Universal Database Manager
* Copyright (C) 2010-2022 DBeaver Corp and others
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jkiss.dbeaver.ui.data.registry;
import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.IExtensionRegistry;
import org.eclipse.core.runtime.Platform;
import org.jkiss.code.NotNull;
import org.jkiss.code.Nullable;
import org.jkiss.dbeaver.model.DBPDataSource;
import org.jkiss.dbeaver.model.data.DBDContent;
import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor;
import org.jkiss.dbeaver.model.struct.DBSTypedObject;
import org.jkiss.dbeaver.ui.data.IStreamValueManager;
import org.jkiss.dbeaver.ui.data.IValueManager;
import org.jkiss.dbeaver.ui.data.managers.DefaultValueManager;
import org.jkiss.dbeaver.utils.ContentUtils;
import org.jkiss.utils.CommonUtils;
import org.jkiss.utils.MimeType;
import java.util.*;
/**
* EntityEditorsRegistry
*/
public class ValueManagerRegistry {
private static ValueManagerRegistry instance = null;
public synchronized static ValueManagerRegistry getInstance() {
if (instance == null) {
instance = new ValueManagerRegistry(Platform.getExtensionRegistry());
}
return instance;
}
private final List<ValueManagerDescriptor> managers = new ArrayList<>();
private final Map<String, StreamValueManagerDescriptor> streamManagers = new HashMap<>();
private ValueManagerRegistry(IExtensionRegistry registry) {
// Load datasource providers from external plugins
IConfigurationElement[] extElements = registry.getConfigurationElementsFor(ValueManagerDescriptor.EXTENSION_ID);
for (IConfigurationElement ext : extElements) {
if (ValueManagerDescriptor.TAG_MANAGER.equals(ext.getName())) {
managers.add(new ValueManagerDescriptor(ext));
} else if (StreamValueManagerDescriptor.TAG_STREAM_MANAGER.equals(ext.getName())) {
final StreamValueManagerDescriptor descriptor = new StreamValueManagerDescriptor(ext);
streamManagers.put(descriptor.getId(), descriptor);
}
}
}
@NotNull
public IValueManager getManager(@Nullable DBPDataSource dataSource, @NotNull DBSTypedObject type, @NotNull Class<?> valueType) {
// Check starting from most restrictive to less restrictive
IValueManager manager = findManager(dataSource, type, valueType, true, true);
if (manager == null) {
manager = findManager(dataSource, type, valueType, false, true);
}
if (manager == null) {
manager = findManager(dataSource, type, valueType, true, false);
}
if (manager == null) {
manager = findManager(dataSource, type, valueType, false, false);
}
if (manager == null) {
return DefaultValueManager.INSTANCE;
}
return manager;
}
private IValueManager findManager(@Nullable DBPDataSource dataSource, DBSTypedObject typedObject, Class<?> valueType, boolean checkDataSource, boolean checkType) {
for (ValueManagerDescriptor manager : managers) {
if (manager.supportsType(dataSource, typedObject, valueType, checkDataSource, checkType)) {
return manager.getInstance();
}
}
return null;
}
@NotNull
public static IValueManager findValueManager(@Nullable DBPDataSource dataSource, @NotNull DBSTypedObject typedObject, @NotNull Class<?> valueType) {
return getInstance().getManager(dataSource, typedObject, valueType);
}
@NotNull
public Collection<StreamValueManagerDescriptor> getAllStreamManagers() {
return Collections.unmodifiableCollection(streamManagers.values());
}
@Nullable
public StreamValueManagerDescriptor getStreamManager(@NotNull String id) {
return streamManagers.get(id);
}
public Map<StreamValueManagerDescriptor, IStreamValueManager.MatchType> getApplicableStreamManagers(@NotNull DBRProgressMonitor monitor, @NotNull DBSTypedObject attribute, @Nullable DBDContent value) {
boolean isTextContent = ContentUtils.isTextContent(value);
Map<StreamValueManagerDescriptor, IStreamValueManager.MatchType> result = new LinkedHashMap<>();
for (StreamValueManagerDescriptor contentManager : streamManagers.values()) {
if (isTextContent && !contentManager.supportsText()) {
// Skip different kind of manager
continue;
}
IStreamValueManager.MatchType matchType = contentManager.getInstance().matchesTo(monitor, attribute, value);
switch (matchType) {
case NONE:
continue;
case EXCLUSIVE:
result.clear();
result.put(contentManager, matchType);
return result;
default:
result.put(contentManager, matchType);
break;
}
}
return result;
}
public Map<StreamValueManagerDescriptor, IStreamValueManager.MatchType> getStreamManagersByMimeType(@NotNull String mimeType, String primaryType) {
MimeType mime = new MimeType(mimeType);
MimeType primaryMime = primaryType == null ? null : new MimeType(primaryType);
Map<StreamValueManagerDescriptor, IStreamValueManager.MatchType> result = new LinkedHashMap<>();
for (StreamValueManagerDescriptor contentManager : streamManagers.values()) {
for (String sm : contentManager.getSupportedMime()) {
if (!CommonUtils.isEmpty(sm) && mime.match(sm)) {
if (!CommonUtils.isEmpty(contentManager.getPrimaryMime()) && primaryMime != null && primaryMime.match(contentManager.getPrimaryMime())) {
result.put(contentManager, IStreamValueManager.MatchType.PRIMARY);
} else {
result.put(contentManager, IStreamValueManager.MatchType.DEFAULT);
}
break;
}
}
}
return result;
}
}
| apache-2.0 |
dmutti/masters | BugForest/src/gfx/Landscape.java | 4134 | package gfx;
import java.awt.*;
import java.util.*;
public class Landscape
{
// Deklaration der Variablen
private int start; // Gibt die Starthöhe der Landschaft vor
private int change; // Entscheidet, ob die Richtung der Landschaftsentwicklung geändert wird
private int faktor; // Entscheidet über Addition oder Substraktion
private int last; // Speichert die letzte Höhe der letzten gezeichneten Linie
private int plus; // Wieviel wird addiert oder subtraiert
private final int mapsize = 700; // Konstante für die Größe des Arrays
// Variable zur Erzeugung einer Zufallszahl
Random rnd = new Random ();
// Array zum Speichern der Höhenpunkte
public int [] map;
// Array zum Speichern der Farbwerte der jeweiligen Höhenpunkte
public Color [] colors;
/** Construktormethode */
Landscape ()
{
// Initialisierung der Variable plus
faktor = 1;
// Initialisierung der Arraygröße von map und colors
map = new int [mapsize];
colors = new Color [mapsize];
// Aufruf der Methode generateLandscape
generateLandscape ();
}
/** Diese Methode initialisiert das Array map mit Integerzahlen. Diese liefern später die
oberen y - Werte der Linien, die die Landschaft bilden. Hierzu wird zu Beginn der Funktion
ein Startwert zwischen 250 und 350. Diese Zahl wird als erste Position im Array gespeichert.
Nun werden alle Felder des Arrays abgelaufen und der Wert plus wird zur letzten Position
entweder hizugezählt oder abgezogen. Die eingeschlagene Richtung wird dabei in 70% der Fälle
beibehahlten, in 30% der Fälle wechselt die Richtung. Diese Positionen werden nun im Array
gespeichert */
public void generateLandscape ()
{
// Initialisierung von plus
plus = 1;
// Initialisierung des Startwertes
start = Math.abs(300 + (rnd.nextInt() % 50));
// Speichern des Startwertes an der ersten Stelle des Arrays
map [0] = start;
// Initialisierung der Startfarbwerte
int greenvalue = 200;
int redvalue = Math.abs(rnd.nextInt() % 200);
int bluevalue = Math.abs(rnd.nextInt() % 201);
// Speichern des ersten Startwertes für das Farbenarray
colors [0] = new Color (redvalue, greenvalue, bluevalue);
// Loop zur Initialisierung aller anderen Arrayfelder
for (int i = 1; i < mapsize; i ++)
{
// Speichern der letzten Arrayposition für Höhe und Farbe
last = map [i - 1];
// Entscheidet, ob die eingeschlagene Richtung gewechselt wird
change = Math.abs(rnd.nextInt() % 10);
// Wenn change > 7 ist, dann ändert sich die Richtung und möglicherweise plus
if (change > 8)
{
// Ändern der Richtung
faktor = - (faktor);
// Wieviel wird addiert bzw. substrahiert
plus = 1 + Math.abs(rnd.nextInt() % 2);
}
// Wird ein bestimmter Wert unter- bzw. überschritten, dann wird die Richtung geändert
if (last > 350 || last < 120)
{
// Ändern der Richtung
faktor = - (faktor);
}
// Hält die Farbwerte immer in einem bestimmten Rahmen
if (greenvalue > 240)
{
// Wenn Farbwert zu groß wird, erniedrigen des Wertes
greenvalue -= 10;
}
else if (greenvalue < 100)
{
// Wenn Farbwert zu klein wird erhöhen des Farbwertes
greenvalue += 10;
}
// Werte für das Feld an i - Stelle werden berechnet
map [i] = last + (faktor * plus);
/** Um die Farbewerte für zunehmende Höhe heller werden zu lassen, wird der Faktor
umgekehrt. Dies ist wegen dem umgekehrten Koordinatensystem von Java nötig */
greenvalue = greenvalue + (-faktor * plus);
colors [i] = new Color (redvalue, greenvalue, bluevalue);
}
}
/** Die Funktion paintMap zeichnet die Landschaft. Dazu werden die Felder des Arrays durchlaufen
und eine Linie wird an x - Position = Arrayindex und von der y - Position = Wert an Arrayindex
bis zum Boden wird dann gezeichnet */
public void paintMap (Graphics g)
{
// Loop zeichnet für alle Felder des Arrays eine Linie
for (int index = 0; index < mapsize; index ++)
{
// Definition der Farbe gemäß dem colors - Array (grün - türkies - blau)
g.setColor (colors [index]);
// Linie zeichnen
g.drawLine (index, map[index], index, 400);
}
}
}
| apache-2.0 |
consulo/consulo-lombok | lombok-base/src/main/java/consulo/lombok/processors/impl/ToStringAnnotationProcessor.java | 1490 | /*
* Copyright 2013 must-be.org
*
* 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 consulo.lombok.processors.impl;
import javax.annotation.Nonnull;
import com.intellij.psi.*;
import com.intellij.psi.util.MethodSignature;
import com.intellij.psi.util.MethodSignatureUtil;
/**
* @author VISTALL
* @since 20:53/30.03.13
*/
public class ToStringAnnotationProcessor extends MethodCreatorByAnnotationProcessor {
public ToStringAnnotationProcessor(String annotationClass) {
super(annotationClass);
}
@Nonnull
@Override
public MethodSignature[] getMethodSignatures(PsiClass psiClass) {
return new MethodSignature[]{
MethodSignatureUtil.createMethodSignature("toString", PsiType.EMPTY_ARRAY, PsiTypeParameter.EMPTY_ARRAY, PsiSubstitutor.EMPTY, false)
};
}
@Nonnull
@Override
public PsiType[] getReturnTypes(PsiClass psiClass) {
return new PsiType[] {PsiType.getJavaLangString(psiClass.getManager(), psiClass.getResolveScope())};
}
}
| apache-2.0 |
neeveresearch/nvx-hornet | nvx-hornet/src/test/java/com/neeve/toa/test/unit/ClusteringTest.java | 5283 | /**
* Copyright 2016 Neeve Research, LLC
*
* This product includes software developed at Neeve Research, LLC
* (http://www.neeveresearch.com/) as well as software licenced to
* Neeve Research, LLC under one or more contributor license agreements.
* See the NOTICE file distributed with this work for additional information
* regarding copyright ownership.
*
* Neeve Research licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.neeve.toa.test.unit;
import static com.neeve.toa.test.unit.SingleAppToaServer.*;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import java.util.HashMap;
import java.util.Map;
import org.junit.Test;
import com.neeve.aep.AepEngine.HAPolicy;
import com.neeve.aep.annotations.EventHandler;
import com.neeve.ods.IStoreBinding;
import com.neeve.server.app.annotations.AppHAPolicy;
/**
*
*/
public class ClusteringTest extends AbstractToaTest {
/**
* Tests a non clusterd app that does not need to be annotated
* with an {@link AppHAPolicy}
*/
public static class NonClusteredApp extends AbstractToaTestApp {
@EventHandler
public void onForwarderMessage1(ForwarderMessage1 message) {
recordReceipt(message);
}
@EventHandler
public void onForwarderMessage2(ForwarderMessage2 message) {
recordReceipt(message);
}
}
@AppHAPolicy(HAPolicy.EventSourcing)
public static class ClusteredEventSourcingApp extends AbstractToaTestApp {
@EventHandler
public void onForwarderMessage1(ForwarderMessage1 message) {
recordReceipt(message);
}
@EventHandler
public void onForwarderMessage2(ForwarderMessage2 message) {
recordReceipt(message);
}
}
@Test
public void testClusteredApp() throws Throwable {
Map<String, String> configOverrides = new HashMap<String, String>();
configOverrides.put(PROP_NAME_STORE_ENABLED, "true");
configOverrides.put(PROP_NAME_STORE_CLUSTERING_ENABLED, "true");
SingleAppToaServer<ClusteredEventSourcingApp> primaryServer = createServer(testcaseName.getMethodName(), "primary", ClusteredEventSourcingApp.class, configOverrides);
primaryServer.start();
ClusteredEventSourcingApp primaryApp = primaryServer.getApplication();
assertNotNull("Primary app should have a store", primaryApp.getAepEngine().getStore());
SingleAppToaServer<ClusteredEventSourcingApp> backupServer = createServer(testcaseName.getMethodName(), "backup", ClusteredEventSourcingApp.class, configOverrides);
backupServer.start();
ClusteredEventSourcingApp backupApp = backupServer.getApplication();
assertNotNull("Backup app should have a store", backupApp.getAepEngine().getStore());
assertEquals("Primary app doesn't have expected role", IStoreBinding.Role.Primary, primaryApp.getAepEngine().getStore().getRole());
assertEquals("Backup app doesn't have expected role", IStoreBinding.Role.Backup, backupApp.getAepEngine().getStore().getRole());
assertNotNull("Primary app doesn't have a persister", primaryApp.getAepEngine().getStore().getPersister());
assertNotNull("Backup app doesn't have a persister", primaryApp.getAepEngine().getStore().getPersister());
primaryApp.injectMessage(ForwarderMessage1.create());
primaryApp.injectMessage(ForwarderMessage2.create());
System.out.println("Waiting for messages receipt...");
backupApp.waitForMessages(5, 2);
primaryApp.waitForMessages(5, 2);
//Wait for transaction stability:
System.out.println("Waiting for transaction stability...");
primaryApp.waitForTransactionStability(5);
backupApp.waitForTransactionStability(5);
//System.out.println("Commits on backup: " + backupApp.getAepEngine().getStats().getNumCommitsCompleted() + "/" + +backupApp.getAepEngine().getStats().getNumCommitsStarted());
System.out.println("Comparing primary and backup messages...");
assertPrimaryAndBackupMessageEqual(primaryApp, backupApp);
}
@Test
public void testNonClusteredApp() throws Throwable {
Map<String, String> configOverrides = new HashMap<String, String>();
configOverrides.put(PROP_NAME_STORE_CLUSTERING_ENABLED, "false");
SingleAppToaServer<NonClusteredApp> server = createServer(testcaseName.getMethodName(), "standalone", NonClusteredApp.class, configOverrides);
server.start();
NonClusteredApp app = server.getApplication();
assertNull("Standalone app should not have a store", app.getAepEngine().getStore());
}
}
| apache-2.0 |
OpenGamma/Strata | modules/collect/src/test/java/com/opengamma/strata/collect/function/ObjIntPredicateTest.java | 2345 | /*
* Copyright (C) 2014 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.strata.collect.function;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatNullPointerException;
import org.junit.jupiter.api.Test;
/**
* Test ObjIntPredicate.
*/
public class ObjIntPredicateTest {
@Test
public void test_and() {
ObjIntPredicate<String> fn1 = (a, b) -> b > 3;
ObjIntPredicate<String> fn2 = (a, b) -> a.length() > 3;
ObjIntPredicate<String> and = fn1.and(fn2);
assertThat(fn1.test("a", 2)).isFalse();
assertThat(fn1.test("a", 4)).isTrue();
assertThat(fn2.test("a", 4)).isFalse();
assertThat(fn2.test("abcd", 4)).isTrue();
assertThat(and.test("a", 2)).isFalse();
assertThat(and.test("a", 4)).isFalse();
assertThat(and.test("abcd", 2)).isFalse();
assertThat(and.test("abcd", 4)).isTrue();
}
@Test
public void test_and_null() {
ObjIntPredicate<String> fn1 = (a, b) -> b > 3;
assertThatNullPointerException().isThrownBy(() -> fn1.and(null));
}
//-------------------------------------------------------------------------
@Test
public void test_or() {
ObjIntPredicate<String> fn1 = (a, b) -> b > 3;
ObjIntPredicate<String> fn2 = (a, b) -> a.length() > 3;
ObjIntPredicate<String> or = fn1.or(fn2);
assertThat(fn1.test("a", 2)).isFalse();
assertThat(fn1.test("a", 4)).isTrue();
assertThat(fn2.test("a", 4)).isFalse();
assertThat(fn2.test("abcd", 4)).isTrue();
assertThat(or.test("a", 2)).isFalse();
assertThat(or.test("a", 4)).isTrue();
assertThat(or.test("abcd", 2)).isTrue();
assertThat(or.test("abcd", 4)).isTrue();
}
@Test
public void test_or_null() {
ObjIntPredicate<String> fn1 = (a, b) -> b > 3;
assertThatNullPointerException().isThrownBy(() -> fn1.or(null));
}
//-------------------------------------------------------------------------
@Test
public void test_negate() {
ObjIntPredicate<String> fn1 = (a, b) -> b > 3;
ObjIntPredicate<String> negate = fn1.negate();
assertThat(fn1.test("a", 2)).isFalse();
assertThat(fn1.test("a", 4)).isTrue();
assertThat(negate.test("a", 2)).isTrue();
assertThat(negate.test("a", 4)).isFalse();
}
}
| apache-2.0 |
miguelillo/AllThatIWant | src/java/org/mig/java/Commands/RedirectRegisterCommand.java | 583 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.mig.java.Commands;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* @author Hildegard
*/
public class RedirectRegisterCommand extends ICommand {
@Override
public String executePage(HttpServletRequest request, HttpServletResponse response) throws Exception {
return "Register.jsp";
}
}
| apache-2.0 |
Brotherc/JAVA | MyTetris/src/cn/brotherchun/tetris/entities/ShapeFactory.java | 1858 | package cn.brotherchun.tetris.entities;
import java.util.Random;
import cn.brotherchun.tetris.listener.ShapeListener;
public class ShapeFactory {
protected static int shapes[][][] = new int[][][] {
{
{ 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 1, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0 }
},
{
{ 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }
},
{
{ 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0 },
{ 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0 },
},
{
{ 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0 },
{ 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0 },
},
{
{ 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0 },
{ 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0 },
},
{
{ 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 1, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0 },
{ 0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0 },
}
};
public Shape getShape(ShapeListener l){
System.out.println("ShapeFactory's getShape");
Shape shape=new Shape();
shape.addListener(l);
int type=new Random().nextInt(shapes.length);
shape.setBody(shapes[type]);
shape.setStatus(0);
return shape;
}
}
| apache-2.0 |
everttigchelaar/camel-svn | camel-core/src/test/java/org/apache/camel/issues/TwoTimerWithJMXIssue.java | 2570 | /**
* 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.camel.issues;
import org.apache.camel.CamelContext;
import org.apache.camel.ContextTestSupport;
import org.apache.camel.Processor;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.model.ProcessorDefinition;
import org.apache.camel.spi.InterceptStrategy;
/**
* Trying to reproduce CAMEL-927.
*/
public class TwoTimerWithJMXIssue extends ContextTestSupport {
private static int counter;
@Override
protected void setUp() throws Exception {
enableJMX(); // the bug was in the JMX so it must be enabled
super.setUp();
}
public void testFromWithNoOutputs() throws Exception {
MockEndpoint mock = getMockEndpoint("mock:result");
mock.expectedMinimumMessageCount(2);
assertMockEndpointsSatisfied();
assertTrue("Counter should be 2 or higher", counter >= 2);
}
@Override
protected RouteBuilder createRouteBuilder() throws Exception {
return new RouteBuilder() {
public void configure() throws Exception {
context.addInterceptStrategy(new MyTracer());
from("timer://kickoff_1?period=250").from("timer://kickoff_2?period=250&delay=10").to("mock:result");
}
};
}
private class MyTracer implements InterceptStrategy {
public Processor wrapProcessorInInterceptors(CamelContext context, ProcessorDefinition definition,
Processor target, Processor nextTarget) throws Exception {
assertNotNull(target);
counter++;
return target;
}
}
}
| apache-2.0 |
xc35/dragontoolkit | src/main/java/edu/drexel/cis/dragon/nlp/ontology/umls/UmlsOntology.java | 574 | /* */ package edu.drexel.cis.dragon.nlp.ontology.umls;
/* */
/* */ import edu.drexel.cis.dragon.nlp.ontology.AbstractOntology;
/* */ import edu.drexel.cis.dragon.nlp.tool.Lemmatiser;
/* */
/* */ public abstract class UmlsOntology extends AbstractOntology
/* */ {
/* */ public UmlsOntology(Lemmatiser lemmatiser)
/* */ {
/* 17 */ super(lemmatiser);
/* */ }
/* */ }
/* Location: C:\dragontoolikt\dragontool.jar
* Qualified Name: dragon.nlp.ontology.umls.UmlsOntology
* JD-Core Version: 0.6.2
*/ | apache-2.0 |
lookout/clouddriver | clouddriver-ecs/src/main/java/com/netflix/spinnaker/clouddriver/ecs/deploy/validators/DeleteScalingPolicyAtomicOperationValidator.java | 1324 | /*
* Copyright 2017 Lookout, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.clouddriver.ecs.deploy.validators;
import com.netflix.spinnaker.clouddriver.deploy.DescriptionValidator;
import com.netflix.spinnaker.clouddriver.ecs.EcsOperation;
import com.netflix.spinnaker.clouddriver.orchestration.AtomicOperations;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import java.util.List;
@EcsOperation(AtomicOperations.DELETE_SCALING_POLICY)
@Component("deleteScalingPolicyAtomicOperationValidator")
public class DeleteScalingPolicyAtomicOperationValidator extends DescriptionValidator {
@Override
public void validate(List priorDescriptions, Object description, Errors errors) {
// TODO - Implement this stub
}
}
| apache-2.0 |
jeanconex/Fiscal65 | Fiscal65/src/br/org/fiscal65/amazonaws/AWSFiscalizacaoUpload.java | 6991 | /**
*
*/
package br.org.fiscal65.amazonaws;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.Writer;
import java.text.SimpleDateFormat;
import java.util.Date;
import android.content.Context;
import android.os.Environment;
import br.org.fiscal65.bitmaps.ImageHandler;
import br.org.fiscal65.communications.CommunicationConstants;
import br.org.fiscal65.communications.CommunicationUtils;
import br.org.fiscal65.communications.JsonHandler;
import br.org.fiscal65.models.Fiscalizacao;
import br.org.fiscal65.utils.Municipalities;
import com.amazonaws.services.s3.model.ProgressEvent;
import com.amazonaws.services.s3.model.ProgressListener;
import com.amazonaws.services.s3.transfer.PersistableUpload;
import com.amazonaws.services.s3.transfer.Transfer;
import com.amazonaws.services.s3.transfer.TransferManager;
import com.amazonaws.services.s3.transfer.Upload;
import com.amazonaws.services.s3.transfer.exception.PauseException;
/**
* @author andre
*
*/
public class AWSFiscalizacaoUpload extends AWSTransferModel
{
private Upload mUpload;
private PersistableUpload mPersistableUpload;
private ProgressListener progressListener;
private Status mStatus;
private File fiscalizacaoJSONFile;
private String fiscalizacaoJSONFileName;
private Fiscalizacao fiscalizacao;
private Integer sleep;
private OnFiscalizacaoUploadS3PostExecuteListener listener;
private Municipalities municipalities;
public AWSFiscalizacaoUpload(Context context,OnFiscalizacaoUploadS3PostExecuteListener listener,Fiscalizacao fiscalizacao,Integer sleep)
{
super(context);
this.listener = listener;
this.fiscalizacao = fiscalizacao;
this.sleep = sleep;
municipalities = Municipalities.getInstance(context);
mStatus = Status.IN_PROGRESS;
progressListener = new ProgressListener()
{
@Override
public void progressChanged(ProgressEvent event)
{
if(event.getEventCode() == ProgressEvent.COMPLETED_EVENT_CODE)
{
mStatus = Status.COMPLETED;
AWSFiscalizacaoUpload.this.listener.finishedFiscalizacaoUploadS3ComResultado(AWSFiscalizacaoUpload.this.fiscalizacao.getIdFiscalizacao());
}else if(event.getEventCode() == ProgressEvent.FAILED_EVENT_CODE)
{
mStatus = Status.CANCELED;
if(mUpload != null)
{
mUpload.abort();
}
AWSFiscalizacaoUpload.this.listener.finishedFiscalizacaoUploadS3ComError(AWSFiscalizacaoUpload.this.fiscalizacao.getIdFiscalizacao());
}
}
};
}
public Runnable getUploadRunnable()
{
return new Runnable()
{
@Override
public void run()
{
upload();
}
};
}
/* (non-Javadoc)
* @see org.vocefiscal.amazonaws.AWSTransferModel#abort()
*/
@Override
public void abort()
{
if(mUpload != null)
{
mStatus = Status.CANCELED;
mUpload.abort();
}
}
/* (non-Javadoc)
* @see org.vocefiscal.amazonaws.AWSTransferModel#getStatus()
*/
@Override
public Status getStatus()
{
return mStatus;
}
/* (non-Javadoc)
* @see org.vocefiscal.amazonaws.AWSTransferModel#getTransfer()
*/
@Override
public Transfer getTransfer()
{
return mUpload;
}
/* (non-Javadoc)
* @see org.vocefiscal.amazonaws.AWSTransferModel#pause()
*/
@Override
public void pause()
{
if(mStatus == Status.IN_PROGRESS)
{
if(mUpload != null)
{
mStatus = Status.PAUSED;
try
{
mPersistableUpload = mUpload.pause();
} catch(PauseException e)
{
}
}
}
}
/* (non-Javadoc)
* @see org.vocefiscal.amazonaws.AWSTransferModel#resume()
*/
@Override
public void resume()
{
if(mStatus == Status.PAUSED)
{
mStatus = Status.IN_PROGRESS;
if(mPersistableUpload != null)
{
//if it paused fine, resume
mUpload = getTransferManager().resumeUpload(mPersistableUpload);
mUpload.addProgressListener(progressListener);
mPersistableUpload = null;
} else
{
//if it was actually aborted, start a new one
upload();
}
}
}
public void upload()
{
if(sleep>0)
{
try
{
Thread.sleep(sleep);
} catch (InterruptedException e)
{
}
}
boolean hasInternet = CommunicationUtils.verifyConnectivity(getContext());
if(hasInternet)
{
boolean isOnWiFi = CommunicationUtils.isWifi(getContext());
if(isOnWiFi || (fiscalizacao.getPodeEnviarRedeDados()!=null&&fiscalizacao.getPodeEnviarRedeDados().equals(1)))
{
JsonHandler jsonHandler = new JsonHandler();
try
{
String fiscalizacaoJSON = jsonHandler.fromObjectToJsonData(fiscalizacao);
fiscalizacaoJSONFile = getOutputMediaFile();
Writer writer = new BufferedWriter(new FileWriter(fiscalizacaoJSONFile));
writer.write(fiscalizacaoJSON);
writer.close();
fiscalizacaoJSONFileName= ImageHandler.nomeDaMidia(fiscalizacaoJSONFile) + ".json";
if(fiscalizacaoJSONFile != null)
{
try
{
TransferManager mTransferManager = getTransferManager();
mUpload = mTransferManager.upload(CommunicationConstants.JSON_BUCKET_NAME, AWSUtil.getPrefix(getContext())+ municipalities.getMunicipalitySlug(fiscalizacao.getEstado(), fiscalizacao.getMunicipio()) + "/zona-" + fiscalizacao.getZonaEleitoral() + "/"+ fiscalizacaoJSONFileName, fiscalizacaoJSONFile);
mUpload.addProgressListener(progressListener);
} catch(Exception e)
{
mStatus = Status.CANCELED;
if(mUpload != null)
{
mUpload.abort();
}
listener.finishedFiscalizacaoUploadS3ComError(fiscalizacao.getIdFiscalizacao());
}
}
} catch (Exception e)
{
mStatus = Status.CANCELED;
if(mUpload != null)
{
mUpload.abort();
}
listener.finishedFiscalizacaoUploadS3ComError(fiscalizacao.getIdFiscalizacao());
}
}else
{
mStatus = Status.CANCELED;
if(mUpload != null)
{
mUpload.abort();
}
listener.finishedFiscalizacaoUploadS3ComError(fiscalizacao.getIdFiscalizacao());
}
}else
{
mStatus = Status.CANCELED;
if(mUpload != null)
{
mUpload.abort();
}
listener.finishedFiscalizacaoUploadS3ComError(fiscalizacao.getIdFiscalizacao());
}
}
/** Create a File for saving */
private File getOutputMediaFile()
{
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String filePath = "BU_JSON_"+ timeStamp + ".json";
File mediaFile = new File(Environment.getExternalStorageDirectory(), filePath);
return mediaFile;
}
public interface OnFiscalizacaoUploadS3PostExecuteListener
{
public void finishedFiscalizacaoUploadS3ComResultado(Long idFiscalizacao);
public void finishedFiscalizacaoUploadS3ComError(Long idFiscalizacao);
}
/**
* @return the sleep
*/
public Integer getSleep() {
return sleep;
}
/**
* @param sleep the sleep to set
*/
public void setSleep(Integer sleep) {
this.sleep = sleep;
}
}
| apache-2.0 |
ldallen/vertx-nubes | src/test/java/integration/redirect/RedirectTest.java | 1647 | package integration.redirect;
import static io.vertx.core.http.HttpHeaders.LOCATION;
import integration.VertxNubesTestBase;
import io.vertx.ext.unit.Async;
import io.vertx.ext.unit.TestContext;
import mock.controllers.redirect.RedirectController;
import org.junit.Test;
public class RedirectTest extends VertxNubesTestBase {
@Test
public void clientRedirect(TestContext context) {
Async async = context.async();
client().getNow("/redirect/client", response -> {
context.assertEquals(302, response.statusCode());
String location = response.getHeader(LOCATION.toString());
context.assertEquals(RedirectController.REDIRECT_LOCATION, location);
async.complete();
});
}
@Test
public void clientRedirectWithCode(TestContext context) {
Async async = context.async();
client().getNow("/redirect/client/permanent", response -> {
context.assertEquals(301, response.statusCode());
String location = response.getHeader(LOCATION.toString());
context.assertEquals(RedirectController.REDIRECT_LOCATION, location);
async.complete();
});
}
@Test
public void serverRedirect(TestContext context) {
Async async = context.async();
client().getNow("/redirect/server", response -> {
context.assertEquals(204, response.statusCode());
context.assertNotNull(" before filter after redirect is called", response.getHeader("afterredirect-beforefilter"));
context.assertNotNull(" main handler after redirect is called", response.getHeader("afterredirect-method"));
context.assertNotNull(" after filter after redirect is called", response.getHeader("afterredirect-afterfilter"));
async.complete();
});
}
}
| apache-2.0 |
jmacglashan/burlap | src/main/java/burlap/behavior/singleagent/planning/Planner.java | 1065 | package burlap.behavior.singleagent.planning;
import burlap.behavior.policy.Policy;
import burlap.behavior.singleagent.MDPSolverInterface;
import burlap.mdp.core.state.State;
/**
* @author James MacGlashan.
*/
public interface Planner extends MDPSolverInterface{
/**
* This method will cause the {@link burlap.behavior.singleagent.planning.Planner} to begin planning from the specified initial {@link State}.
* It will then return an appropriate {@link burlap.behavior.policy.Policy} object that captured the planning results.
* Note that typically you can use a variety of different {@link burlap.behavior.policy.Policy} objects
* in conjunction with this {@link burlap.behavior.singleagent.planning.Planner} to get varying behavior and
* the returned {@link burlap.behavior.policy.Policy} is not required to be used.
* @param initialState the initial state of the planning problem
* @return a {@link burlap.behavior.policy.Policy} that captures the planning results from input {@link State}.
*/
Policy planFromState(State initialState);
}
| apache-2.0 |
mgroeneweg/mendix-DataTables | test/javasource/excelimporter/reader/readers/ExcelXLSReaderHeaderSecondPassListener.java | 3532 | package excelimporter.reader.readers;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.poi.hssf.eventusermodel.HSSFListener;
import org.apache.poi.hssf.record.BOFRecord;
import org.apache.poi.hssf.record.BoolErrRecord;
import org.apache.poi.hssf.record.FormulaRecord;
import org.apache.poi.hssf.record.LabelSSTRecord;
import org.apache.poi.hssf.record.NumberRecord;
import org.apache.poi.hssf.record.Record;
import org.apache.poi.hssf.record.SSTRecord;
/**
*
*
* @author H. van Kranenburg, J. van der Hoek, J. Veldhuizen
* @version $Id: ExcelXLSReaderHeaderSecondPassListener.java 8202 2008-10-03 10:05:54Z Jonathan Veldhuizen $
*/
public class ExcelXLSReaderHeaderSecondPassListener implements HSSFListener, ExcelHeadable {
private final int sheet;
private final int row;
private final HashMap<Integer, String> sstmap;
private List<ExcelColumn> excelColumns = new ArrayList<ExcelColumn>();
int workbookNow = -1;
int sheetNow = -1;
public ExcelXLSReaderHeaderSecondPassListener( int sheet, int row, HashMap<Integer, String> sstmap ) {
this.sheet = sheet;
this.row = row;
this.sstmap = sstmap;
}
/**
* This method listens for incoming records and handles them as required.
*
* @param record The record that was found while reading.
*/
@Override
public void processRecord( Record record ) {
// Most frequent encountered first...
switch (record.getSid()) {
case LabelSSTRecord.sid:
if ( this.sheetNow == this.sheet ) {
LabelSSTRecord lrec = (LabelSSTRecord) record;
if ( lrec.getRow() == this.row ) {
short col = lrec.getColumn();
String text = this.sstmap.get(lrec.getSSTIndex());
this.processRecord(col, text);
}
}
break;
case NumberRecord.sid:
if ( this.sheetNow == this.sheet ) {
NumberRecord nrec = (NumberRecord) record;
if ( nrec.getRow() == this.row ) {
short col = nrec.getColumn();
this.processRecord(col, nrec.getValue());
}
}
break;
case BoolErrRecord.sid:
if ( this.sheetNow == this.sheet ) {
BoolErrRecord brec = (BoolErrRecord) record;
if ( brec.getRow() == this.row ) {
short col = brec.getColumn();
this.processRecord(col, brec.getBooleanValue());
}
}
break;
case FormulaRecord.sid:
if ( this.sheetNow == this.sheet ) {
FormulaRecord frec = (FormulaRecord) record;
if ( frec.getRow() == this.row ) {
short col = frec.getColumn();
this.processRecord(col, frec.getValue());
}
}
break;
// the BOFRecord can represent either the beginning of a sheet or the workbook
case BOFRecord.sid:
BOFRecord bof = (BOFRecord) record;
if ( bof.getType() == BOFRecord.TYPE_WORKBOOK ) {
++this.workbookNow;
}
else if ( bof.getType() == BOFRecord.TYPE_WORKSHEET ) {
++this.sheetNow;
}
break;
case SSTRecord.sid:
// Here's the SST again... now read in strings that we need
SSTRecord sstrec = (SSTRecord) record;
for( int i = 0; i < sstrec.getNumUniqueStrings(); i++ ) {
if ( this.sstmap.get(i) != null )
this.sstmap.put(i, sstrec.getString(i).toString().trim());
}
break;
}
}
private void processRecord( short col, Object value ) {
ExcelColumn column = new ExcelColumn(new Integer(col), String.valueOf(value));
this.excelColumns.add(column);
}
@Override
public List<ExcelColumn> getColumns() {
return this.excelColumns;
}
}
| apache-2.0 |
docker-java/docker-java | docker-java/src/test/java/com/github/dockerjava/core/DockerRule.java | 7726 | package com.github.dockerjava.core;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.DockerClientDelegate;
import com.github.dockerjava.api.command.CreateContainerCmd;
import com.github.dockerjava.api.command.CreateContainerResponse;
import com.github.dockerjava.api.command.CreateNetworkCmd;
import com.github.dockerjava.api.command.CreateNetworkResponse;
import com.github.dockerjava.api.command.CreateVolumeCmd;
import com.github.dockerjava.api.command.CreateVolumeResponse;
import com.github.dockerjava.api.exception.ConflictException;
import com.github.dockerjava.api.exception.NotFoundException;
import com.github.dockerjava.cmd.CmdIT;
import com.github.dockerjava.utils.LogContainerTestCallback;
import org.junit.rules.ExternalResource;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.util.HashSet;
import java.util.Set;
/**
* @author Kanstantsin Shautsou
*/
public class DockerRule extends ExternalResource {
public static final Logger LOG = LoggerFactory.getLogger(DockerRule.class);
public static final String DEFAULT_IMAGE = "busybox:latest";
private DockerClient dockerClient;
private final Set<String> createdContainerIds = new HashSet<>();
private final Set<String> createdNetworkIds = new HashSet<>();
private final Set<String> createdVolumeNames = new HashSet<>();
private final DefaultDockerClientConfig config = config();
public DockerClient newClient() {
DockerClientImpl dockerClient = CmdIT.createDockerClient(config);
dockerClient.withDockerCmdExecFactory(
new DockerCmdExecFactoryDelegate(dockerClient.dockerCmdExecFactory) {
@Override
public CreateContainerCmd.Exec createCreateContainerCmdExec() {
CreateContainerCmd.Exec exec = super.createCreateContainerCmdExec();
return command -> {
CreateContainerResponse response = exec.exec(command);
createdContainerIds.add(response.getId());
return response;
};
}
@Override
public CreateNetworkCmd.Exec createCreateNetworkCmdExec() {
CreateNetworkCmd.Exec exec = super.createCreateNetworkCmdExec();
return command -> {
CreateNetworkResponse response = exec.exec(command);
createdNetworkIds.add(response.getId());
return response;
};
}
@Override
public CreateVolumeCmd.Exec createCreateVolumeCmdExec() {
CreateVolumeCmd.Exec exec = super.createCreateVolumeCmdExec();
return command -> {
CreateVolumeResponse response = exec.exec(command);
createdVolumeNames.add(response.getName());
return response;
};
}
}
);
return new DockerClientDelegate() {
@Override
protected DockerClient getDockerClient() {
return dockerClient;
}
};
}
public DefaultDockerClientConfig getConfig() {
return config;
}
public DockerClient getClient() {
if (dockerClient != null) {
return dockerClient;
}
return this.dockerClient = newClient();
}
@Override
public Statement apply(Statement base, Description description) {
return super.apply(base, description);
}
@Override
protected void before() throws Throwable {
// LOG.info("======================= BEFORETEST =======================");
LOG.debug("Connecting to Docker server");
try {
getClient().inspectImageCmd(DEFAULT_IMAGE).exec();
} catch (NotFoundException e) {
LOG.info("Pulling image 'busybox'");
// need to block until image is pulled completely
getClient().pullImageCmd("busybox")
.withTag("latest")
.start()
.awaitCompletion();
}
// assertThat(getClient(), notNullValue());
// LOG.info("======================= END OF BEFORETEST =======================\n\n");
}
@Override
protected void after() {
// LOG.debug("======================= END OF AFTERTEST =======================");
createdContainerIds.parallelStream().forEach(containerId -> {
try {
dockerClient.removeContainerCmd(containerId)
.withForce(true)
.withRemoveVolumes(true)
.exec();
} catch (ConflictException | NotFoundException ignored) {
} catch (Throwable e) {
if (e instanceof InterruptedException) {
Thread.currentThread().interrupt();
}
LOG.debug("Failed to remove container {}", containerId, e);
}
});
createdNetworkIds.parallelStream().forEach(networkId -> {
try {
dockerClient.removeNetworkCmd(networkId).exec();
} catch (ConflictException | NotFoundException ignored) {
} catch (Throwable e) {
if (e instanceof InterruptedException) {
Thread.currentThread().interrupt();
}
LOG.debug("Failed to remove network {}", networkId, e);
}
});
createdVolumeNames.parallelStream().forEach(volumeName -> {
try {
dockerClient.removeVolumeCmd(volumeName).exec();
} catch (ConflictException | NotFoundException ignored) {
} catch (Throwable e) {
if (e instanceof InterruptedException) {
Thread.currentThread().interrupt();
}
LOG.debug("Failed to remove volume {}", volumeName, e);
}
});
try {
dockerClient.close();
} catch (Exception e) {
LOG.warn("Failed to close the DockerClient", e);
}
}
private static DefaultDockerClientConfig config() {
return config(null);
}
public static DefaultDockerClientConfig config(String password) {
DefaultDockerClientConfig.Builder builder = DefaultDockerClientConfig.createDefaultConfigBuilder()
.withApiVersion(RemoteApiVersion.VERSION_1_30)
.withRegistryUrl("https://index.docker.io/v1/");
if (password != null) {
builder = builder.withRegistryPassword(password);
}
return builder.build();
}
public String buildImage(File baseDir) throws Exception {
return getClient().buildImageCmd(baseDir)
.withNoCache(true)
.start()
.awaitImageId();
}
public String containerLog(String containerId) throws Exception {
return getClient().logContainerCmd(containerId)
.withStdOut(true)
.exec(new LogContainerTestCallback())
.awaitCompletion()
.toString();
}
public void ensureContainerRemoved(String container1Name) {
try {
getClient().removeContainerCmd(container1Name)
.withForce(true)
.withRemoveVolumes(true)
.exec();
} catch (NotFoundException ex) {
// ignore
}
}
}
| apache-2.0 |
jotaemepereira/blog-android-filter | BlogAndroidFilter/app/src/main/java/jotaemepereira/com/blogandroidfilter/ItemFilterActivity.java | 2789 | package jotaemepereira.com.blogandroidfilter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.AbsListView;
import android.widget.EditText;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
public class ItemFilterActivity extends AppCompatActivity {
private RecyclerView mItemsRecyclerView;
private EditText mSearchEditText;
private ItemSearchFilter mItemSearchFilter;
private List<Item> mItems = new ArrayList<>();
private ItemAdapter mAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_item_filter);
initializeItemsList();
setupItemsRecyclerView();
setupSearchEditText();
}
private void setupItemsRecyclerView() {
mItemsRecyclerView = (RecyclerView) findViewById(R.id.item_list);
mItemsRecyclerView.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
mItemsRecyclerView.setLayoutManager(linearLayoutManager);
mItemsRecyclerView.setAdapter(mAdapter);
mAdapter.notifyDataSetChanged();
}
private void setupSearchEditText() {
mSearchEditText = (EditText) findViewById(R.id.search_edit_text);
mSearchEditText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable stringFilter) {
mItemSearchFilter.filter(stringFilter);
}
});
}
private void createItemsSearchFilter() {
mItemSearchFilter = new ItemSearchFilter(new ArrayList<>(mItems), this::refreshAdapter);
}
private void refreshAdapter(List<Item> items) {
mItems.clear();
mItems.addAll(items);
mAdapter.notifyDataSetChanged();
}
private void initializeItemsList() {
for (int i=0; i < 10; i++) {
Item item = new Item();
item.setName("Item " + i);
item.setPrice(new BigDecimal(i));
mItems.add(item);
}
createItemsSearchFilter();
createAdapter();
}
private void createAdapter() {
mAdapter = new ItemAdapter(mItems);
}
}
| apache-2.0 |
WestCoastInformatics/SNOMED-Terminology-Server | services/src/main/java/org/ihtsdo/otf/ts/services/RootService.java | 1473 | /*
* Copyright 2015 West Coast Informatics, LLC
*/
package org.ihtsdo.otf.ts.services;
/**
* Genericall represents a service.
*/
public interface RootService {
/**
* Open the factory.
*
* @throws Exception the exception
*/
public void openFactory() throws Exception;
/**
* Close the factory.
*
* @throws Exception the exception
*/
public void closeFactory() throws Exception;
/**
* Gets the transaction per operation.
*
* @return the transaction per operation
* @throws Exception the exception
*/
public boolean getTransactionPerOperation() throws Exception;
/**
* Sets the transaction per operation.
*
* @param transactionPerOperation the new transaction per operation
* @throws Exception the exception
*/
public void setTransactionPerOperation(boolean transactionPerOperation)
throws Exception;
/**
* Commit.
*
* @throws Exception the exception
*/
public void commit() throws Exception;
/**
* Rollback.
*
* @throws Exception the exception
*/
public void rollback() throws Exception;
/**
* Begin transaction.
*
* @throws Exception the exception
*/
public void beginTransaction() throws Exception;
/**
* Closes the manager.
*
* @throws Exception the exception
*/
public void close() throws Exception;
/**
* Clears the manager.
*
* @throws Exception the exception
*/
public void clear() throws Exception;
} | apache-2.0 |
objectos/core | core-io/src/test/java/br/com/objectos/core/io/ByteArrayReaderSource.java | 1218 | /*
* Copyright (C) 2021-2022 Objectos Software LTDA.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package br.com.objectos.core.io;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.Charset;
final class ByteArrayReaderSource implements ReaderSource {
private final String value;
ByteArrayReaderSource(String value) {
this.value = value;
}
@Override
public final Reader openReader(Charset charset) throws IOException {
byte[] bytes;
bytes = value.getBytes(charset);
ByteArrayInputStream in;
in = new ByteArrayInputStream(bytes);
return new InputStreamReader(in);
}
} | apache-2.0 |
strapdata/elassandra5-rc | core/src/main/java/org/elasticsearch/indices/recovery/RecoveryTarget.java | 20762 | /*
* 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.indices.recovery;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.message.ParameterizedMessage;
import org.apache.logging.log4j.util.Supplier;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.IndexFormatTooNewException;
import org.apache.lucene.index.IndexFormatTooOldException;
import org.apache.lucene.store.IOContext;
import org.apache.lucene.store.IndexOutput;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.BytesRefIterator;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.ExceptionsHelper;
import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.common.UUIDs;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.logging.Loggers;
import org.elasticsearch.common.lucene.Lucene;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.util.Callback;
import org.elasticsearch.common.util.CancellableThreads;
import org.elasticsearch.common.util.concurrent.AbstractRefCounted;
import org.elasticsearch.common.util.concurrent.ConcurrentCollections;
import org.elasticsearch.index.shard.IndexShard;
import org.elasticsearch.index.shard.ShardId;
import org.elasticsearch.index.shard.TranslogRecoveryPerformer;
import org.elasticsearch.index.store.Store;
import org.elasticsearch.index.store.StoreFileMetaData;
import org.elasticsearch.index.translog.Translog;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
/**
* Represents a recovery where the current node is the target node of the recovery. To track recoveries in a central place, instances of
* this class are created through {@link RecoveriesCollection}.
*/
public class RecoveryTarget extends AbstractRefCounted implements RecoveryTargetHandler {
private final Logger logger;
private static final AtomicLong idGenerator = new AtomicLong();
private static final String RECOVERY_PREFIX = "recovery.";
private final ShardId shardId;
private final long recoveryId;
private final IndexShard indexShard;
private final DiscoveryNode sourceNode;
private final String tempFilePrefix;
private final Store store;
private final PeerRecoveryTargetService.RecoveryListener listener;
private final Callback<Long> ensureClusterStateVersionCallback;
private final AtomicBoolean finished = new AtomicBoolean();
private final ConcurrentMap<String, IndexOutput> openIndexOutputs = ConcurrentCollections.newConcurrentMap();
private final CancellableThreads cancellableThreads;
// last time this status was accessed
private volatile long lastAccessTime = System.nanoTime();
// latch that can be used to blockingly wait for RecoveryTarget to be closed
private final CountDownLatch closedLatch = new CountDownLatch(1);
private final Map<String, String> tempFileNames = ConcurrentCollections.newConcurrentMap();
/**
* creates a new recovery target object that represents a recovery to the provided indexShard
*
* @param indexShard local shard where we want to recover to
* @param sourceNode source node of the recovery where we recover from
* @param listener called when recovery is completed / failed
* @param ensureClusterStateVersionCallback callback to ensure that the current node is at least on a cluster state with the provided
* version. Necessary for primary relocation so that new primary knows about all other ongoing
* replica recoveries when replicating documents (see {@link RecoverySourceHandler}).
*/
public RecoveryTarget(IndexShard indexShard, DiscoveryNode sourceNode, PeerRecoveryTargetService.RecoveryListener listener,
Callback<Long> ensureClusterStateVersionCallback) {
super("recovery_status");
this.cancellableThreads = new CancellableThreads();
this.recoveryId = idGenerator.incrementAndGet();
this.listener = listener;
this.logger = Loggers.getLogger(getClass(), indexShard.indexSettings().getSettings(), indexShard.shardId());
this.indexShard = indexShard;
this.sourceNode = sourceNode;
this.shardId = indexShard.shardId();
this.tempFilePrefix = RECOVERY_PREFIX + UUIDs.base64UUID() + ".";
this.store = indexShard.store();
this.ensureClusterStateVersionCallback = ensureClusterStateVersionCallback;
// make sure the store is not released until we are done.
store.incRef();
indexShard.recoveryStats().incCurrentAsTarget();
}
/**
* returns a fresh RecoveryTarget to retry recovery from the same source node onto the same IndexShard and using the same listener
*/
public RecoveryTarget retryCopy() {
return new RecoveryTarget(this.indexShard, this.sourceNode, this.listener, this.ensureClusterStateVersionCallback);
}
public long recoveryId() {
return recoveryId;
}
public ShardId shardId() {
return shardId;
}
public IndexShard indexShard() {
ensureRefCount();
return indexShard;
}
public DiscoveryNode sourceNode() {
return this.sourceNode;
}
public RecoveryState state() {
return indexShard.recoveryState();
}
public CancellableThreads CancellableThreads() {
return cancellableThreads;
}
/** return the last time this RecoveryStatus was used (based on System.nanoTime() */
public long lastAccessTime() {
return lastAccessTime;
}
/** sets the lasAccessTime flag to now */
public void setLastAccessTime() {
lastAccessTime = System.nanoTime();
}
public Store store() {
ensureRefCount();
return store;
}
public RecoveryState.Stage stage() {
return state().getStage();
}
/** renames all temporary files to their true name, potentially overriding existing files */
public void renameAllTempFiles() throws IOException {
ensureRefCount();
store.renameTempFilesSafe(tempFileNames);
}
/**
* Closes the current recovery target and waits up to a certain timeout for resources to be freed.
* Returns true if resetting the recovery was successful, false if the recovery target is already cancelled / failed or marked as done.
*/
boolean resetRecovery(CancellableThreads newTargetCancellableThreads) throws IOException {
if (finished.compareAndSet(false, true)) {
try {
logger.debug("reset of recovery with shard {} and id [{}]", shardId, recoveryId);
} finally {
// release the initial reference. recovery files will be cleaned as soon as ref count goes to zero, potentially now.
decRef();
}
try {
newTargetCancellableThreads.execute(closedLatch::await);
} catch (CancellableThreads.ExecutionCancelledException e) {
logger.trace("new recovery target cancelled for shard {} while waiting on old recovery target with id [{}] to close",
shardId, recoveryId);
return false;
}
RecoveryState.Stage stage = indexShard.recoveryState().getStage();
if (indexShard.recoveryState().getPrimary() && (stage == RecoveryState.Stage.FINALIZE || stage == RecoveryState.Stage.DONE)) {
// once primary relocation has moved past the finalization step, the relocation source can be moved to RELOCATED state
// and start indexing as primary into the target shard (see TransportReplicationAction). Resetting the target shard in this
// state could mean that indexing is halted until the recovery retry attempt is completed and could also destroy existing
// documents indexed and acknowledged before the reset.
assert stage != RecoveryState.Stage.DONE : "recovery should not have completed when it's being reset";
throw new IllegalStateException("cannot reset recovery as previous attempt made it past finalization step");
}
indexShard.performRecoveryRestart();
return true;
}
return false;
}
/**
* cancel the recovery. calling this method will clean temporary files and release the store
* unless this object is in use (in which case it will be cleaned once all ongoing users call
* {@link #decRef()}
* <p>
* if {@link #CancellableThreads()} was used, the threads will be interrupted.
*/
public void cancel(String reason) {
if (finished.compareAndSet(false, true)) {
try {
logger.debug("recovery canceled (reason: [{}])", reason);
cancellableThreads.cancel(reason);
} finally {
// release the initial reference. recovery files will be cleaned as soon as ref count goes to zero, potentially now
decRef();
}
}
}
/**
* fail the recovery and call listener
*
* @param e exception that encapsulating the failure
* @param sendShardFailure indicates whether to notify the master of the shard failure
*/
public void fail(RecoveryFailedException e, boolean sendShardFailure) {
if (finished.compareAndSet(false, true)) {
try {
notifyListener(e, sendShardFailure);
} finally {
try {
cancellableThreads.cancel("failed recovery [" + ExceptionsHelper.stackTrace(e) + "]");
} finally {
// release the initial reference. recovery files will be cleaned as soon as ref count goes to zero, potentially now
decRef();
}
}
}
}
public void notifyListener(RecoveryFailedException e, boolean sendShardFailure) {
listener.onRecoveryFailure(state(), e, sendShardFailure);
}
/** mark the current recovery as done */
public void markAsDone() {
if (finished.compareAndSet(false, true)) {
assert tempFileNames.isEmpty() : "not all temporary files are renamed";
try {
// this might still throw an exception ie. if the shard is CLOSED due to some other event.
// it's safer to decrement the reference in a try finally here.
indexShard.postRecovery("peer recovery done");
} finally {
// release the initial reference. recovery files will be cleaned as soon as ref count goes to zero, potentially now
decRef();
}
listener.onRecoveryDone(state());
}
}
/** Get a temporary name for the provided file name. */
public String getTempNameForFile(String origFile) {
return tempFilePrefix + origFile;
}
public IndexOutput getOpenIndexOutput(String key) {
ensureRefCount();
return openIndexOutputs.get(key);
}
/** remove and {@link org.apache.lucene.store.IndexOutput} for a given file. It is the caller's responsibility to close it */
public IndexOutput removeOpenIndexOutputs(String name) {
ensureRefCount();
return openIndexOutputs.remove(name);
}
/**
* Creates an {@link org.apache.lucene.store.IndexOutput} for the given file name. Note that the
* IndexOutput actually point at a temporary file.
* <p>
* Note: You can use {@link #getOpenIndexOutput(String)} with the same filename to retrieve the same IndexOutput
* at a later stage
*/
public IndexOutput openAndPutIndexOutput(String fileName, StoreFileMetaData metaData, Store store) throws IOException {
ensureRefCount();
String tempFileName = getTempNameForFile(fileName);
if (tempFileNames.containsKey(tempFileName)) {
throw new IllegalStateException("output for file [" + fileName + "] has already been created");
}
// add first, before it's created
tempFileNames.put(tempFileName, fileName);
IndexOutput indexOutput = store.createVerifyingOutput(tempFileName, metaData, IOContext.DEFAULT);
openIndexOutputs.put(fileName, indexOutput);
return indexOutput;
}
@Override
protected void closeInternal() {
try {
// clean open index outputs
Iterator<Entry<String, IndexOutput>> iterator = openIndexOutputs.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, IndexOutput> entry = iterator.next();
logger.trace("closing IndexOutput file [{}]", entry.getValue());
try {
entry.getValue().close();
} catch (Exception e) {
logger.debug(
(Supplier<?>) () -> new ParameterizedMessage("error while closing recovery output [{}]", entry.getValue()), e);
}
iterator.remove();
}
// trash temporary files
for (String file : tempFileNames.keySet()) {
logger.trace("cleaning temporary file [{}]", file);
store.deleteQuiet(file);
}
} finally {
// free store. increment happens in constructor
store.decRef();
indexShard.recoveryStats().decCurrentAsTarget();
closedLatch.countDown();
}
}
@Override
public String toString() {
return shardId + " [" + recoveryId + "]";
}
private void ensureRefCount() {
if (refCount() <= 0) {
throw new ElasticsearchException("RecoveryStatus is used but it's refcount is 0. Probably a mismatch between incRef/decRef " +
"calls");
}
}
/*** Implementation of {@link RecoveryTargetHandler } */
@Override
public void prepareForTranslogOperations(int totalTranslogOps, long maxUnsafeAutoIdTimestamp) throws IOException {
state().getTranslog().totalOperations(totalTranslogOps);
indexShard().skipTranslogRecovery(maxUnsafeAutoIdTimestamp);
}
@Override
public void finalizeRecovery() {
indexShard().finalizeRecovery();
}
@Override
public void ensureClusterStateVersion(long clusterStateVersion) {
ensureClusterStateVersionCallback.handle(clusterStateVersion);
}
@Override
public void indexTranslogOperations(List<Translog.Operation> operations, int totalTranslogOps) throws TranslogRecoveryPerformer
.BatchOperationException {
final RecoveryState.Translog translog = state().getTranslog();
translog.totalOperations(totalTranslogOps);
assert indexShard().recoveryState() == state();
indexShard().performBatchRecovery(operations);
}
@Override
public void receiveFileInfo(List<String> phase1FileNames,
List<Long> phase1FileSizes,
List<String> phase1ExistingFileNames,
List<Long> phase1ExistingFileSizes,
int totalTranslogOps) {
final RecoveryState.Index index = state().getIndex();
for (int i = 0; i < phase1ExistingFileNames.size(); i++) {
index.addFileDetail(phase1ExistingFileNames.get(i), phase1ExistingFileSizes.get(i), true);
}
for (int i = 0; i < phase1FileNames.size(); i++) {
index.addFileDetail(phase1FileNames.get(i), phase1FileSizes.get(i), false);
}
state().getTranslog().totalOperations(totalTranslogOps);
state().getTranslog().totalOperationsOnStart(totalTranslogOps);
}
@Override
public void cleanFiles(int totalTranslogOps, Store.MetadataSnapshot sourceMetaData) throws IOException {
state().getTranslog().totalOperations(totalTranslogOps);
// first, we go and move files that were created with the recovery id suffix to
// the actual names, its ok if we have a corrupted index here, since we have replicas
// to recover from in case of a full cluster shutdown just when this code executes...
renameAllTempFiles();
final Store store = store();
try {
store.cleanupAndVerify("recovery CleanFilesRequestHandler", sourceMetaData);
} catch (CorruptIndexException | IndexFormatTooNewException | IndexFormatTooOldException ex) {
// this is a fatal exception at this stage.
// this means we transferred files from the remote that have not be checksummed and they are
// broken. We have to clean up this shard entirely, remove all files and bubble it up to the
// source shard since this index might be broken there as well? The Source can handle this and checks
// its content on disk if possible.
try {
try {
store.removeCorruptionMarker();
} finally {
Lucene.cleanLuceneIndex(store.directory()); // clean up and delete all files
}
} catch (Exception e) {
logger.debug("Failed to clean lucene index", e);
ex.addSuppressed(e);
}
RecoveryFailedException rfe = new RecoveryFailedException(state(), "failed to clean after recovery", ex);
fail(rfe, true);
throw rfe;
} catch (Exception ex) {
RecoveryFailedException rfe = new RecoveryFailedException(state(), "failed to clean after recovery", ex);
fail(rfe, true);
throw rfe;
}
}
@Override
public void writeFileChunk(StoreFileMetaData fileMetaData, long position, BytesReference content,
boolean lastChunk, int totalTranslogOps) throws IOException {
final Store store = store();
final String name = fileMetaData.name();
state().getTranslog().totalOperations(totalTranslogOps);
final RecoveryState.Index indexState = state().getIndex();
IndexOutput indexOutput;
if (position == 0) {
indexOutput = openAndPutIndexOutput(name, fileMetaData, store);
} else {
indexOutput = getOpenIndexOutput(name);
}
BytesRefIterator iterator = content.iterator();
BytesRef scratch;
while((scratch = iterator.next()) != null) { // we iterate over all pages - this is a 0-copy for all core impls
indexOutput.writeBytes(scratch.bytes, scratch.offset, scratch.length);
}
indexState.addRecoveredBytesToFile(name, content.length());
if (indexOutput.getFilePointer() >= fileMetaData.length() || lastChunk) {
try {
Store.verify(indexOutput);
} finally {
// we are done
indexOutput.close();
}
final String temporaryFileName = getTempNameForFile(name);
assert Arrays.asList(store.directory().listAll()).contains(temporaryFileName) :
"expected: [" + temporaryFileName + "] in " + Arrays.toString(store.directory().listAll());
store.directory().sync(Collections.singleton(temporaryFileName));
IndexOutput remove = removeOpenIndexOutputs(name);
assert remove == null || remove == indexOutput; // remove maybe null if we got finished
}
}
}
| apache-2.0 |
rafizanbaharum/cfi-gov | src/main/java/net/canang/cfi/core/am/model/impl/CfModuleImpl.java | 1980 | package net.canang.cfi.core.am.model.impl;
import net.canang.cfi.core.am.model.CfModule;
import net.canang.cfi.core.am.model.CfSubModule;
import net.canang.cfi.core.so.model.CfMetadata;
import javax.persistence.*;
import java.util.Set;
/**
* @author canang.technologies
* @since 7/10/13
*/
@Table(name = "CF_MODL")
@Entity(name = "CfModule")
public class CfModuleImpl implements CfModule {
@Id
@Column(name = "ID", nullable = false)
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(name = "CODE")
private String code;
@Column(name = "ALIAS")
private String alias;
@Column(name = "DESCRIPTION")
private String description;
@Column(name = "ORDR")
private Integer order;
@OneToMany(targetEntity = CfSubModuleImpl.class, mappedBy = "module", fetch = FetchType.EAGER)
private Set<CfSubModule> subModules;
@Embedded
private CfMetadata metadata;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getAlias() {
return alias;
}
public void setAlias(String alias) {
this.alias = alias;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Integer getOrder() {
return order;
}
public void setOrder(Integer order) {
this.order = order;
}
public Set<CfSubModule> getSubModules() {
return subModules;
}
public void setSubModules(Set<CfSubModule> subModules) {
this.subModules = subModules;
}
public CfMetadata getMetadata() {
return metadata;
}
public void setMetadata(CfMetadata metadata) {
this.metadata = metadata;
}
}
| apache-2.0 |
eberson/open-sae-model | src/main/java/br/org/open/sae/model/Sexo.java | 86 | package br.org.open.sae.model;
public enum Sexo {
MASCULINO,
FEMININO
}
| apache-2.0 |
andrzejpolis/spring-webflow-sandbox | web/src/main/java/sws/dialog/DialogData.java | 6217 | package sws.dialog;
import org.springframework.util.Assert;
import java.io.Serializable;
public class DialogData implements Serializable {
private static final long serialVersionUID = 6317115735431565798L;
private DialogData(DialogData.DialogType type) {
this.type = type;
}
private DialogData.DialogType type;
private String title;
private String message;
private Object[] messageArgs;
private DialogData.DialogButton leftButton;
private DialogData.DialogButton rightButton;
private boolean definedContent;
private String include;
public DialogData.DialogType getType() {
return type;
}
public void setType(DialogData.DialogType type) {
this.type = type;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Object[] getMessageArgs() {
return messageArgs;
}
public void setMessageArgs(Object[] messageArgs) {
this.messageArgs = messageArgs;
}
public DialogData.DialogButton getLeftButton() {
return leftButton;
}
public void setLeftButton(DialogData.DialogButton leftButton) {
this.leftButton = leftButton;
}
public DialogData.DialogButton getRightButton() {
return rightButton;
}
public void setRightButton(DialogData.DialogButton rightButton) {
this.rightButton = rightButton;
}
public boolean isDefinedContent() {
return definedContent;
}
public void setDefinedContent(boolean definedContent) {
this.definedContent = definedContent;
}
public String getInclude() {
return include;
}
public void setInclude(String include) {
this.include = include;
}
public static DialogData createDefaultConfirmationDialog(String message, String action) {
DialogData confirmationDialog = createDefaultConfirmation(action);
confirmationDialog.setMessage(message);
return confirmationDialog;
}
public static DialogData createDefaultConfirmationWithDefinedBody(String action) {
DialogData confirmationDialog = createDefaultConfirmation(action);
confirmationDialog.setDefinedContent(true);
return confirmationDialog;
}
public static DialogData createWithIncludeAndAction(String action, String include) {
DialogData confirmationDialog = createDefaultConfirmation(action);
confirmationDialog.setInclude(include);
return confirmationDialog;
}
private static DialogData createDefaultConfirmation(String action) {
DialogData confirmationDialog = new DialogData(DialogType.CONFIRMATION);
confirmationDialog.setTitle("generic.confirmation.title");
confirmationDialog.setLeftButton(DialogButton.closeButton("generic.confirmation.button.back"));
confirmationDialog.setRightButton(DialogButton.proceedButton("generic.confirmation.button.next", action));
return confirmationDialog;
}
public static DialogData createDefaultSummaryDialog(String message) {
return createDefaultSummaryDialog(message, null);
}
public static DialogData createDefaultSummaryDialog(String message, Object[] arguments) {
DialogData summaryDialog = new DialogData(DialogType.SUMMARY);
summaryDialog.setTitle("generic.summary.title");
summaryDialog.setMessage(message);
summaryDialog.setMessageArgs(arguments);
summaryDialog.setRightButton(DialogButton.closeButton("generic.confirmation.button.ok"));
return summaryDialog;
}
public static DialogData createDefaultSummaryDialog(String title, String message, Object[] arguments) {
Assert.notNull(title);
DialogData dd = createDefaultSummaryDialog(message, arguments);
dd.setTitle(title);
return dd;
}
/**
* Creates dialog box with inner content defined somewhere in xhtml. Content must be defined by:
* <ui:define name="dialogBody">
* </ui:define>
* @return
*/
public static DialogData createDefaultSummaryWithDefinedBody() {
DialogData summaryDialog = new DialogData(DialogType.SUMMARY);
summaryDialog.setTitle("generic.summary.title");
summaryDialog.setDefinedContent(true);
summaryDialog.setRightButton(DialogButton.closeButton("generic.confirmation.button.next"));
return summaryDialog;
}
public static class DialogButton implements Serializable {
private static final long serialVersionUID = 2484502868086390447L;
private static enum DialogButtonType {
CLOSE, PROCEED
}
private DialogButton.DialogButtonType type;
private String label;
private String action;
public DialogButton.DialogButtonType getType() {
return type;
}
public void setType(DialogButton.DialogButtonType type) {
this.type = type;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public String getAction() {
return action;
}
public void setAction(String action) {
this.action = action;
}
public static DialogData.DialogButton closeButton(String label) {
DialogData.DialogButton dialogButton = new DialogButton();
dialogButton.setType(DialogButtonType.CLOSE);
dialogButton.setLabel(label);
return dialogButton;
}
public static DialogData.DialogButton proceedButton(String label, String action) {
DialogData.DialogButton dialogButton = new DialogButton();
dialogButton.setType(DialogButtonType.PROCEED);
dialogButton.setLabel(label);
dialogButton.setAction(action);
return dialogButton;
}
}
private static enum DialogType {
CONFIRMATION, SUMMARY
};
} | apache-2.0 |
leafclick/intellij-community | platform/lang-api/src/com/intellij/execution/target/value/DeferredTargetValue.java | 1022 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.execution.target.value;
import org.jetbrains.concurrency.AsyncPromise;
import org.jetbrains.concurrency.Promise;
import org.jetbrains.concurrency.Promises;
public class DeferredTargetValue<T> implements TargetValue<T> {
private final AsyncPromise<T> myTargetPromise = new AsyncPromise<>();
private final Promise<T> myLocalPromise;
public DeferredTargetValue(T localValue) {
myLocalPromise = Promises.resolvedPromise(localValue);
}
public void resolve(T valueToResolve) {
if (myTargetPromise.isDone()) {
throw new IllegalStateException("Target value is already resolved to '" + myTargetPromise.get() + "'");
}
myTargetPromise.setResult(valueToResolve);
}
@Override
public Promise<T> getLocalValue() {
return myLocalPromise;
}
@Override
public Promise<T> getTargetValue() {
return myTargetPromise;
}
}
| apache-2.0 |
nafae/developer | modules/dfp_axis/src/main/java/com/google/api/ads/dfp/axis/v201308/VpaidLinearRedirectCreative.java | 18340 | /**
* VpaidLinearRedirectCreative.java
*
* This file was auto-generated from WSDL
* by the Apache Axis 1.4 Mar 02, 2009 (07:08:06 PST) WSDL2Java emitter.
*/
package com.google.api.ads.dfp.axis.v201308;
/**
* A {@code Creative} that displays an externally hosted Flash-based
* ad
* and is served via VAST 2.0 XML. It is displayed in a
* linear fashion
* with a video (before, after, interrupting). This creative
* is read only.
*/
public class VpaidLinearRedirectCreative extends com.google.api.ads.dfp.axis.v201308.HasDestinationUrlCreative implements java.io.Serializable {
/* The IDs of the companion creatives that are associated with
* this creative.
* This attribute is optional. */
private long[] companionCreativeIds;
/* A map from {@code ConversionEvent} to a list of URLs that will
* be pinged
* when the event happens. This attribute is optional. */
private com.google.api.ads.dfp.axis.v201308.ConversionEvent_TrackingUrlsMapEntry[] trackingUrls;
/* A string that is supplied to the VPAID creative's init function.
* This is written into the VAST XML in the {@code AdParameters} section.
* This attribute is optional. */
private java.lang.String customParameters;
/* Duration in milliseconds for the vpaid ad given no user interaction.
* This attribute is optional. */
private java.lang.Integer duration;
/* The URL where the Flash asset resides. This attribute is required
* and has
* a maximum length of 1024 characters. */
private java.lang.String flashUrl;
/* The size of the flash asset. Note that this may differ from
* {@link #size}
* if the asset is not expected to fill the entire
* video player. This attribute
* is optional. */
private com.google.api.ads.dfp.axis.v201308.Size flashAssetSize;
/* An ad tag URL that will return a preview of the VAST XML response
* specific
* to this creative. This attribute is read-only. */
private java.lang.String vastPreviewUrl;
public VpaidLinearRedirectCreative() {
}
public VpaidLinearRedirectCreative(
java.lang.Long advertiserId,
java.lang.Long id,
java.lang.String name,
com.google.api.ads.dfp.axis.v201308.Size size,
java.lang.String previewUrl,
com.google.api.ads.dfp.axis.v201308.AppliedLabel[] appliedLabels,
com.google.api.ads.dfp.axis.v201308.DateTime lastModifiedDateTime,
com.google.api.ads.dfp.axis.v201308.BaseCustomFieldValue[] customFieldValues,
java.lang.String creativeType,
java.lang.String destinationUrl,
long[] companionCreativeIds,
com.google.api.ads.dfp.axis.v201308.ConversionEvent_TrackingUrlsMapEntry[] trackingUrls,
java.lang.String customParameters,
java.lang.Integer duration,
java.lang.String flashUrl,
com.google.api.ads.dfp.axis.v201308.Size flashAssetSize,
java.lang.String vastPreviewUrl) {
super(
advertiserId,
id,
name,
size,
previewUrl,
appliedLabels,
lastModifiedDateTime,
customFieldValues,
creativeType,
destinationUrl);
this.companionCreativeIds = companionCreativeIds;
this.trackingUrls = trackingUrls;
this.customParameters = customParameters;
this.duration = duration;
this.flashUrl = flashUrl;
this.flashAssetSize = flashAssetSize;
this.vastPreviewUrl = vastPreviewUrl;
}
/**
* Gets the companionCreativeIds value for this VpaidLinearRedirectCreative.
*
* @return companionCreativeIds * The IDs of the companion creatives that are associated with
* this creative.
* This attribute is optional.
*/
public long[] getCompanionCreativeIds() {
return companionCreativeIds;
}
/**
* Sets the companionCreativeIds value for this VpaidLinearRedirectCreative.
*
* @param companionCreativeIds * The IDs of the companion creatives that are associated with
* this creative.
* This attribute is optional.
*/
public void setCompanionCreativeIds(long[] companionCreativeIds) {
this.companionCreativeIds = companionCreativeIds;
}
public long getCompanionCreativeIds(int i) {
return this.companionCreativeIds[i];
}
public void setCompanionCreativeIds(int i, long _value) {
this.companionCreativeIds[i] = _value;
}
/**
* Gets the trackingUrls value for this VpaidLinearRedirectCreative.
*
* @return trackingUrls * A map from {@code ConversionEvent} to a list of URLs that will
* be pinged
* when the event happens. This attribute is optional.
*/
public com.google.api.ads.dfp.axis.v201308.ConversionEvent_TrackingUrlsMapEntry[] getTrackingUrls() {
return trackingUrls;
}
/**
* Sets the trackingUrls value for this VpaidLinearRedirectCreative.
*
* @param trackingUrls * A map from {@code ConversionEvent} to a list of URLs that will
* be pinged
* when the event happens. This attribute is optional.
*/
public void setTrackingUrls(com.google.api.ads.dfp.axis.v201308.ConversionEvent_TrackingUrlsMapEntry[] trackingUrls) {
this.trackingUrls = trackingUrls;
}
public com.google.api.ads.dfp.axis.v201308.ConversionEvent_TrackingUrlsMapEntry getTrackingUrls(int i) {
return this.trackingUrls[i];
}
public void setTrackingUrls(int i, com.google.api.ads.dfp.axis.v201308.ConversionEvent_TrackingUrlsMapEntry _value) {
this.trackingUrls[i] = _value;
}
/**
* Gets the customParameters value for this VpaidLinearRedirectCreative.
*
* @return customParameters * A string that is supplied to the VPAID creative's init function.
* This is written into the VAST XML in the {@code AdParameters} section.
* This attribute is optional.
*/
public java.lang.String getCustomParameters() {
return customParameters;
}
/**
* Sets the customParameters value for this VpaidLinearRedirectCreative.
*
* @param customParameters * A string that is supplied to the VPAID creative's init function.
* This is written into the VAST XML in the {@code AdParameters} section.
* This attribute is optional.
*/
public void setCustomParameters(java.lang.String customParameters) {
this.customParameters = customParameters;
}
/**
* Gets the duration value for this VpaidLinearRedirectCreative.
*
* @return duration * Duration in milliseconds for the vpaid ad given no user interaction.
* This attribute is optional.
*/
public java.lang.Integer getDuration() {
return duration;
}
/**
* Sets the duration value for this VpaidLinearRedirectCreative.
*
* @param duration * Duration in milliseconds for the vpaid ad given no user interaction.
* This attribute is optional.
*/
public void setDuration(java.lang.Integer duration) {
this.duration = duration;
}
/**
* Gets the flashUrl value for this VpaidLinearRedirectCreative.
*
* @return flashUrl * The URL where the Flash asset resides. This attribute is required
* and has
* a maximum length of 1024 characters.
*/
public java.lang.String getFlashUrl() {
return flashUrl;
}
/**
* Sets the flashUrl value for this VpaidLinearRedirectCreative.
*
* @param flashUrl * The URL where the Flash asset resides. This attribute is required
* and has
* a maximum length of 1024 characters.
*/
public void setFlashUrl(java.lang.String flashUrl) {
this.flashUrl = flashUrl;
}
/**
* Gets the flashAssetSize value for this VpaidLinearRedirectCreative.
*
* @return flashAssetSize * The size of the flash asset. Note that this may differ from
* {@link #size}
* if the asset is not expected to fill the entire
* video player. This attribute
* is optional.
*/
public com.google.api.ads.dfp.axis.v201308.Size getFlashAssetSize() {
return flashAssetSize;
}
/**
* Sets the flashAssetSize value for this VpaidLinearRedirectCreative.
*
* @param flashAssetSize * The size of the flash asset. Note that this may differ from
* {@link #size}
* if the asset is not expected to fill the entire
* video player. This attribute
* is optional.
*/
public void setFlashAssetSize(com.google.api.ads.dfp.axis.v201308.Size flashAssetSize) {
this.flashAssetSize = flashAssetSize;
}
/**
* Gets the vastPreviewUrl value for this VpaidLinearRedirectCreative.
*
* @return vastPreviewUrl * An ad tag URL that will return a preview of the VAST XML response
* specific
* to this creative. This attribute is read-only.
*/
public java.lang.String getVastPreviewUrl() {
return vastPreviewUrl;
}
/**
* Sets the vastPreviewUrl value for this VpaidLinearRedirectCreative.
*
* @param vastPreviewUrl * An ad tag URL that will return a preview of the VAST XML response
* specific
* to this creative. This attribute is read-only.
*/
public void setVastPreviewUrl(java.lang.String vastPreviewUrl) {
this.vastPreviewUrl = vastPreviewUrl;
}
private java.lang.Object __equalsCalc = null;
public synchronized boolean equals(java.lang.Object obj) {
if (!(obj instanceof VpaidLinearRedirectCreative)) return false;
VpaidLinearRedirectCreative other = (VpaidLinearRedirectCreative) obj;
if (obj == null) return false;
if (this == obj) return true;
if (__equalsCalc != null) {
return (__equalsCalc == obj);
}
__equalsCalc = obj;
boolean _equals;
_equals = super.equals(obj) &&
((this.companionCreativeIds==null && other.getCompanionCreativeIds()==null) ||
(this.companionCreativeIds!=null &&
java.util.Arrays.equals(this.companionCreativeIds, other.getCompanionCreativeIds()))) &&
((this.trackingUrls==null && other.getTrackingUrls()==null) ||
(this.trackingUrls!=null &&
java.util.Arrays.equals(this.trackingUrls, other.getTrackingUrls()))) &&
((this.customParameters==null && other.getCustomParameters()==null) ||
(this.customParameters!=null &&
this.customParameters.equals(other.getCustomParameters()))) &&
((this.duration==null && other.getDuration()==null) ||
(this.duration!=null &&
this.duration.equals(other.getDuration()))) &&
((this.flashUrl==null && other.getFlashUrl()==null) ||
(this.flashUrl!=null &&
this.flashUrl.equals(other.getFlashUrl()))) &&
((this.flashAssetSize==null && other.getFlashAssetSize()==null) ||
(this.flashAssetSize!=null &&
this.flashAssetSize.equals(other.getFlashAssetSize()))) &&
((this.vastPreviewUrl==null && other.getVastPreviewUrl()==null) ||
(this.vastPreviewUrl!=null &&
this.vastPreviewUrl.equals(other.getVastPreviewUrl())));
__equalsCalc = null;
return _equals;
}
private boolean __hashCodeCalc = false;
public synchronized int hashCode() {
if (__hashCodeCalc) {
return 0;
}
__hashCodeCalc = true;
int _hashCode = super.hashCode();
if (getCompanionCreativeIds() != null) {
for (int i=0;
i<java.lang.reflect.Array.getLength(getCompanionCreativeIds());
i++) {
java.lang.Object obj = java.lang.reflect.Array.get(getCompanionCreativeIds(), i);
if (obj != null &&
!obj.getClass().isArray()) {
_hashCode += obj.hashCode();
}
}
}
if (getTrackingUrls() != null) {
for (int i=0;
i<java.lang.reflect.Array.getLength(getTrackingUrls());
i++) {
java.lang.Object obj = java.lang.reflect.Array.get(getTrackingUrls(), i);
if (obj != null &&
!obj.getClass().isArray()) {
_hashCode += obj.hashCode();
}
}
}
if (getCustomParameters() != null) {
_hashCode += getCustomParameters().hashCode();
}
if (getDuration() != null) {
_hashCode += getDuration().hashCode();
}
if (getFlashUrl() != null) {
_hashCode += getFlashUrl().hashCode();
}
if (getFlashAssetSize() != null) {
_hashCode += getFlashAssetSize().hashCode();
}
if (getVastPreviewUrl() != null) {
_hashCode += getVastPreviewUrl().hashCode();
}
__hashCodeCalc = false;
return _hashCode;
}
// Type metadata
private static org.apache.axis.description.TypeDesc typeDesc =
new org.apache.axis.description.TypeDesc(VpaidLinearRedirectCreative.class, true);
static {
typeDesc.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201308", "VpaidLinearRedirectCreative"));
org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("companionCreativeIds");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201308", "companionCreativeIds"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "long"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
elemField.setMaxOccursUnbounded(true);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("trackingUrls");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201308", "trackingUrls"));
elemField.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201308", "ConversionEvent_TrackingUrlsMapEntry"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
elemField.setMaxOccursUnbounded(true);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("customParameters");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201308", "customParameters"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("duration");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201308", "duration"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "int"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("flashUrl");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201308", "flashUrl"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("flashAssetSize");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201308", "flashAssetSize"));
elemField.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201308", "Size"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("vastPreviewUrl");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201308", "vastPreviewUrl"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
}
/**
* Return type metadata object
*/
public static org.apache.axis.description.TypeDesc getTypeDesc() {
return typeDesc;
}
/**
* Get Custom Serializer
*/
public static org.apache.axis.encoding.Serializer getSerializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanSerializer(
_javaType, _xmlType, typeDesc);
}
/**
* Get Custom Deserializer
*/
public static org.apache.axis.encoding.Deserializer getDeserializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanDeserializer(
_javaType, _xmlType, typeDesc);
}
}
| apache-2.0 |
Poeschl/TryAndRemove | app/src/main/java/de/poeschl/apps/tryandremove/utils/AndroidAppManager.java | 2486 | /*
* Copyright (c) 2015 Markus Poeschl
*
* 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 de.poeschl.apps.tryandremove.utils;
import android.app.Application;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import java.util.List;
import javax.inject.Inject;
import de.poeschl.apps.tryandremove.interfaces.AppManager;
/**
* This class cares about the app management on the android device.
* <p/>
* Created by Markus Pöschl on 18.12.2014.
*/
public class AndroidAppManager implements AppManager {
private PackageManager packageManager;
private Application application;
@Inject
public AndroidAppManager(PackageManager packageManager, Application application) {
this.packageManager = packageManager;
this.application = application;
}
/**
* Check if the given package exists on the phone.
*
* @param appPackage The package name to check.
* @return True if the package exists.
*/
@Override
public boolean exists(String appPackage) {
try {
packageManager.getPackageInfo(appPackage, PackageManager.GET_META_DATA);
return true;
} catch (PackageManager.NameNotFoundException e) {
return false;
}
}
/**
* Uninstalls a app from the device.
*
* @param appPackage The package to be removed.
*/
@Override
public void remove(String appPackage) {
Intent intent = new Intent(Intent.ACTION_DELETE, Uri.fromParts("package", appPackage, null));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
application.startActivity(intent);
}
/**
* Uninstall a bundle of apps from the device.
*
* @param appPackages The package ids of the packages.
*/
@Override
public void remove(List<String> appPackages) {
for (String appPackage : appPackages) {
remove(appPackage);
}
}
}
| apache-2.0 |
SergeyI88/InduikovS | chapter_002/src/main/java/ru/job4j/start/Input.java | 811 | package ru.job4j.start;
import java.util.ArrayList;
/**
*
* class Input.
* auhtor IndyukovS
* version 0.1
*/
public interface Input {
/**
* method select ввод управл¤ющего числа пользователем.
* @return select
*/
int select();
/**
* method askName.
* @param question first
* @return String.
*/
String askName(String question);
/**
* method askId.
* @param question first
* @return String
*/
String askId(String question);
/**
* method askDescription.
* @param question first
* @return String
*/
String askDescription(String question);
/**
* method askCreate.
* @param question first
* @return long
*/
long askCreate(String question);
/**
* method ask.
* @param question first
* @param range second
* @return int
*/
int ask(String question, ArrayList<Integer> range);
} | apache-2.0 |
rohlfingt/blockly-android | blocklylib-core/src/main/java/com/google/blockly/model/FieldColor.java | 3470 | /*
* Copyright 2016 Google 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.google.blockly.model;
import android.graphics.Color;
import android.text.TextUtils;
import com.google.blockly.utils.BlockLoadingException;
import org.json.JSONObject;
import org.xmlpull.v1.XmlSerializer;
import java.io.IOException;
/**
* Adds a color picker to an Input.
*/
public final class FieldColor extends Field<FieldColor.Observer> {
public static final int DEFAULT_COLOR = 0xff0000; // Red
private int mColor;
public FieldColor(String name) {
this(name, DEFAULT_COLOR);
}
public FieldColor(String name, int color) {
super(name, TYPE_COLOR);
setColor(color);
}
public static FieldColor fromJson(JSONObject json) throws BlockLoadingException {
String name = json.optString("name");
if (TextUtils.isEmpty(name)) {
throw new BlockLoadingException("field_colour \"name\" attribute must not be empty.");
}
int color = DEFAULT_COLOR;
String colourString = json.optString("colour");
if (!TextUtils.isEmpty(colourString)) {
color = Color.parseColor(colourString);
}
return new FieldColor(name, color);
}
@Override
public FieldColor clone() {
return new FieldColor(getName(), mColor);
}
@Override
public boolean setFromString(String text) {
try {
setColor(Color.parseColor(text));
} catch (IllegalArgumentException e) {
return false;
}
return true;
}
/**
* @return The current color in this field.
*/
public int getColor() {
return mColor;
}
/**
* Sets the color stored in this field.
*
* @param color A color in the form 0xRRGGBB
*/
public void setColor(int color) {
final int newColor = 0xFFFFFF & color;
if (mColor != newColor) {
int oldColor = mColor;
mColor = newColor;
onColorChanged(oldColor, newColor);
}
}
@Override
protected void serializeInner(XmlSerializer serializer) throws IOException {
serializer.text(String.format("#%02x%02x%02x",
Color.red(mColor), Color.green(mColor), Color.blue(mColor)));
}
private void onColorChanged(int oldColor, int newColor) {
for (int i = 0; i < mObservers.size(); i++) {
mObservers.get(i).onColorChanged(this, oldColor, newColor);
}
}
/**
* Observer for listening to changes to a color field.
*/
public interface Observer {
/**
* Called when the field's color changed.
*
* @param field The field that changed.
* @param oldColor The field's previous color.
* @param newColor The field's new color.
*/
void onColorChanged(Field field, int oldColor, int newColor);
}
}
| apache-2.0 |
nafae/developer | modules/dfp_appengine/src/main/java/com/google/api/ads/dfp/jaxws/v201411/HasDestinationUrlCreative.java | 2781 |
package com.google.api.ads.dfp.jaxws.v201411;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlSeeAlso;
import javax.xml.bind.annotation.XmlType;
/**
*
* A {@code Creative} that has a destination url
*
*
* <p>Java class for HasDestinationUrlCreative complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="HasDestinationUrlCreative">
* <complexContent>
* <extension base="{https://www.google.com/apis/ads/publisher/v201411}Creative">
* <sequence>
* <element name="destinationUrl" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="destinationUrlType" type="{https://www.google.com/apis/ads/publisher/v201411}DestinationUrlType" minOccurs="0"/>
* </sequence>
* </extension>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "HasDestinationUrlCreative", propOrder = {
"destinationUrl",
"destinationUrlType"
})
@XmlSeeAlso({
CustomCreative.class,
VpaidLinearCreative.class,
AspectRatioImageCreative.class,
LegacyDfpMobileCreative.class,
VpaidLinearRedirectCreative.class,
BaseFlashCreative.class,
BaseFlashRedirectCreative.class,
BaseImageRedirectCreative.class,
BaseImageCreative.class,
BaseVideoCreative.class
})
public abstract class HasDestinationUrlCreative
extends Creative
{
protected String destinationUrl;
protected DestinationUrlType destinationUrlType;
/**
* Gets the value of the destinationUrl property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getDestinationUrl() {
return destinationUrl;
}
/**
* Sets the value of the destinationUrl property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDestinationUrl(String value) {
this.destinationUrl = value;
}
/**
* Gets the value of the destinationUrlType property.
*
* @return
* possible object is
* {@link DestinationUrlType }
*
*/
public DestinationUrlType getDestinationUrlType() {
return destinationUrlType;
}
/**
* Sets the value of the destinationUrlType property.
*
* @param value
* allowed object is
* {@link DestinationUrlType }
*
*/
public void setDestinationUrlType(DestinationUrlType value) {
this.destinationUrlType = value;
}
}
| apache-2.0 |
devdattakulkarni/Cassandra-KVAC | src/java/org/apache/cassandra/utils/BloomFilter.java | 5011 | /**
* 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.cassandra.utils;
import java.nio.ByteBuffer;
import org.apache.cassandra.io.ICompactSerializer2;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.cassandra.utils.obs.OpenBitSet;
public class BloomFilter extends Filter
{
private static final Logger logger = LoggerFactory.getLogger(BloomFilter.class);
private static final int EXCESS = 20;
static ICompactSerializer2<BloomFilter> serializer_ = new BloomFilterSerializer();
public OpenBitSet bitset;
BloomFilter(int hashes, OpenBitSet bs)
{
hashCount = hashes;
bitset = bs;
}
public static BloomFilter emptyFilter()
{
return new BloomFilter(0, bucketsFor(0, 0));
}
public static ICompactSerializer2<BloomFilter> serializer()
{
return serializer_;
}
private static OpenBitSet bucketsFor(long numElements, int bucketsPer)
{
return new OpenBitSet(numElements * bucketsPer + EXCESS);
}
/**
* @return A BloomFilter with the lowest practical false positive probability
* for the given number of elements.
*/
public static BloomFilter getFilter(long numElements, int targetBucketsPerElem)
{
int maxBucketsPerElement = Math.max(1, BloomCalculations.maxBucketsPerElement(numElements));
int bucketsPerElement = Math.min(targetBucketsPerElem, maxBucketsPerElement);
if (bucketsPerElement < targetBucketsPerElem)
{
logger.warn(String.format("Cannot provide an optimal BloomFilter for %d elements (%d/%d buckets per element).",
numElements, bucketsPerElement, targetBucketsPerElem));
}
BloomCalculations.BloomSpecification spec = BloomCalculations.computeBloomSpec(bucketsPerElement);
if (logger.isTraceEnabled())
logger.trace("Creating bloom filter for {} elements and spec {}", numElements, spec);
return new BloomFilter(spec.K, bucketsFor(numElements, spec.bucketsPerElement));
}
/**
* @return The smallest BloomFilter that can provide the given false positive
* probability rate for the given number of elements.
*
* Asserts that the given probability can be satisfied using this filter.
*/
public static BloomFilter getFilter(long numElements, double maxFalsePosProbability)
{
assert maxFalsePosProbability <= 1.0 : "Invalid probability";
int bucketsPerElement = BloomCalculations.maxBucketsPerElement(numElements);
BloomCalculations.BloomSpecification spec = BloomCalculations.computeBloomSpec(bucketsPerElement, maxFalsePosProbability);
return new BloomFilter(spec.K, bucketsFor(numElements, spec.bucketsPerElement));
}
private long buckets()
{
return bitset.size();
}
private long[] getHashBuckets(ByteBuffer key)
{
return BloomFilter.getHashBuckets(key, hashCount, buckets());
}
// Murmur is faster than an SHA-based approach and provides as-good collision
// resistance. The combinatorial generation approach described in
// https://www.eecs.harvard.edu/~michaelm/postscripts/tr-02-05.pdf
// does prove to work in actual tests, and is obviously faster
// than performing further iterations of murmur.
static long[] getHashBuckets(ByteBuffer b, int hashCount, long max)
{
long[] result = new long[hashCount];
long hash1 = MurmurHash.hash64(b, b.position(), b.remaining(), 0L);
long hash2 = MurmurHash.hash64(b, b.position(), b.remaining(), hash1);
for (int i = 0; i < hashCount; ++i)
{
result[i] = Math.abs((hash1 + (long)i * hash2) % max);
}
return result;
}
public void add(ByteBuffer key)
{
for (long bucketIndex : getHashBuckets(key))
{
bitset.set(bucketIndex);
}
}
public boolean isPresent(ByteBuffer key)
{
for (long bucketIndex : getHashBuckets(key))
{
if (!bitset.get(bucketIndex))
{
return false;
}
}
return true;
}
public void clear()
{
bitset.clear(0, bitset.size());
}
}
| apache-2.0 |
xBlackCat/sjpu-saver | src/java/org/xblackcat/sjpu/saver/ReusableSaver.java | 1919 | package org.xblackcat.sjpu.saver;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* 19.06.2014 11:22
*
* @author xBlackCat
*/
public class ReusableSaver implements ISaver {
private final Map<URI, ILocation> openSavers = new HashMap<>();
private final Lock lock = new ReentrantLock();
@Override
public void save(URI target, InputStream data, Compression compression) throws IOException {
ILocation location = openSaver(target);
location.save(target.getPath(), data, compression);
}
private ILocation openSaver(URI t) throws IOException {
try {
URI base = SaverUtils.getRootUri(t);
lock.lock();
try {
ILocation p = openSavers.get(base);
if (p != null) {
return p;
}
p = SaverUtils.openLocation(base);
openSavers.put(base, p);
return p;
} finally {
lock.unlock();
}
} catch (URISyntaxException e) {
throw new MalformedURLException(e.getMessage());
}
}
@Override
public void close() {
final ILocation[] locations;
lock.lock();
try {
locations = openSavers.values().stream().toArray(ILocation[]::new);
openSavers.clear();
} finally {
lock.unlock();
}
for (ILocation saver : locations) {
try {
saver.close();
} catch (IOException e) {
// ignore
}
}
}
}
| apache-2.0 |
codyer/CleanFramework | app/src/demo/java/com/cody/app/business/binding/DemoImageViewActivity.java | 2365 | package com.cody.app.business.binding;
import android.os.Bundle;
import android.view.View;
import com.cody.app.R;
import com.cody.app.databinding.ImageViewActivityBinding;
import com.cody.app.framework.activity.WithHeaderActivity;
import com.cody.handler.business.presenter.CasePresenter;
import com.cody.handler.business.viewmodel.CaseViewModel;
import com.cody.handler.framework.viewmodel.HeaderViewModel;
public class DemoImageViewActivity extends WithHeaderActivity<CasePresenter, CaseViewModel, ImageViewActivityBinding> {
private boolean flag = false;
/**
* 创建标题
* 返回空或者默认的HeaderViewModel不会显示头部,必须设置头部的visible
*
* @param header
* @see HeaderViewModel#setVisible
*/
@Override
protected void initHeader(HeaderViewModel header) {
header.setTitle("Case test");
}
/**
* 子类提供有binding的资源ID
*/
@Override
protected int getLayoutID() {
return R.layout.activity_image_view;
}
/**
* 每个view保证只有一个Presenter
*/
@Override
protected CasePresenter buildPresenter() {
return new CasePresenter();
}
/**
* 每个view保证只有一个ViewModel,当包含其他ViewModel时使用根ViewModel包含子ViewModel
* ViewModel可以在创建的时候进行初始化,也可以在正在进行绑定(#setBinding)的时候初始化
*
* @param savedInstanceState
*/
@Override
protected CaseViewModel buildViewModel(Bundle savedInstanceState) {
CaseViewModel viewModel = new CaseViewModel();
viewModel.setImageUrl("http://test2.mklimg.com/aa.jpg");
viewModel.setInfo("http://test2.mklimg.com/aa.jpg");
viewModel.setVisibility(true);
return viewModel;
}
/**
* Called when a view has been clicked.
*
* @param v The view that was clicked.
*/
@Override
public void onClick(View v) {
if (flag = !flag) {
getViewModel().setInfo("http://test2.mklimg.com/bb.jpg");
getViewModel().setImageUrl("http://test2.mklimg.com/bb.jpg");
} else {
getViewModel().setInfo("http://test2.mklimg.com/aa.jpg");
getViewModel().setImageUrl("http://test2.mklimg.com/aa.jpg");
}
onUpdate(TAG);
}
}
| apache-2.0 |
cs-au-dk/TAJS | test/src/dk/brics/tajs/test/stats/StatsScriptaculous.java | 1407 | package dk.brics.tajs.test.stats;
import dk.brics.tajs.options.OptionValues;
import org.kohsuke.args4j.CmdLineException;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.Optional;
public class StatsScriptaculous {
public static String[][] scriptaculousTestSuite = {
{"benchmarks/tajs/src/popular-libs/scriptaculous-modified/justload.html"}
};
public static void main(String[] args) throws IOException, CmdLineException {
OptionValues optionValues = new OptionValues();
optionValues.enableTest();
optionValues.getSoundnessTesterOptions().setRootDirFromMainDirectory(Paths.get("../../"));
optionValues.getSoundnessTesterOptions().setGenerateOnlyIncludeAutomaticallyForHTMLFiles(true);
optionValues.enableDeterminacy();
optionValues.enablePolyfillMDN();
optionValues.enablePolyfillTypedArrays();
optionValues.enablePolyfillES6Collections();
optionValues.enablePolyfillES6Promises();
optionValues.enableConsoleModel();
optionValues.enableNoMessages();
optionValues.enableIncludeDom();
optionValues.getUnsoundness().setUsePreciseFunctionToString(true);
optionValues.getSoundnessTesterOptions().setDoNotCheckAmbiguousNodeQueries(true);
Stats.run("scriptaculous", 600, 500000, Optional.of(optionValues), scriptaculousTestSuite);
}
}
| apache-2.0 |
ilscipio/scipio-erp | framework/webapp/src/com/ilscipio/scipio/ce/webapp/control/util/AccessTokenProvider.java | 17551 | package com.ilscipio.scipio.ce.webapp.control.util;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.WeakHashMap;
import java.util.concurrent.ConcurrentHashMap;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.commons.lang.StringUtils;
import org.ofbiz.base.util.UtilHttp;
/**
* Provides generalized LoginWorker-like externalLoginKey-like
* access token functionality.
* <p>
* Tokens are associated in the provider with a map of tokens to values.
* If caller doesn't need the values, simply use a dummy Object.
* <p>
* All the current implementations are thread-safe
* but differ on key weakness and performance.
* <p>
* Added 2018-05-05.
*/
public abstract class AccessTokenProvider<V> {
private final EventHandler<V> eventHandler;
protected AccessTokenProvider(EventHandler<V> eventHandler) {
this.eventHandler = (eventHandler != null) ? eventHandler : NoopEventHandler.getInstance();
}
/**
* Creates a new token string ID.
* By default, uses same UUID generation as {@link org.ofbiz.webapp.control.LoginWorker#getExternalLoginKey} except the dashes are removed.
* <p>
* NOTE: 2020-03-12: By default this now removes dashes so the string is exactly 32 bytes (multiple of 16) for compatibility and special purposes.
*/
public String newTokenString() {
return StringUtils.remove(UUID.randomUUID().toString(), '-');
}
/**
* Creates a new token.
* The token is NOT automatically stored in the provider (see {@link #put(AccessToken, Object)).
*/
public abstract AccessToken newToken();
public abstract AccessToken newToken(String tokenString);
public abstract V put(AccessToken token, V value);
public V put(String tokenString, V value) {
return put(newToken(tokenString), value);
}
public abstract V get(AccessToken token);
public V get(String tokenString) {
return get(newToken(tokenString));
}
public abstract V remove(AccessToken token);
public V remove(String tokenString) {
return remove(newToken(tokenString));
}
protected EventHandler<V> getEventHandler() {
return eventHandler;
}
/**
* Access token, whose {@link #toString()} method provides the string
* representation (for URLs).
*/
@SuppressWarnings("serial")
public static abstract class AccessToken implements Serializable {
@Override
public int hashCode() {
return toString().hashCode();
}
@Override
public boolean equals(Object other) {
if (this == other) return true;
if (other == null) return false;
return toString().equals(other.toString());
}
}
/**
* Simple access token equivalent to a single string.
* DEV NOTE: This wrapper is needed for weak hash map keys to work.
* WARN: does not support null tokenString; use {@link NullSimpleAccessToken} for null token.
*/
@SuppressWarnings("serial")
public static class SimpleAccessToken extends AccessToken {
protected final String tokenString;
protected SimpleAccessToken(String tokenString) {
this.tokenString = tokenString;
}
public static SimpleAccessToken newToken(String tokenString) {
return (tokenString != null) ? new SimpleAccessToken(tokenString) : NullSimpleAccessToken.INSTANCE;
}
@Override
public String toString() {
return tokenString;
}
}
@SuppressWarnings("serial")
public static class NullSimpleAccessToken extends SimpleAccessToken {
public static final NullSimpleAccessToken INSTANCE = new NullSimpleAccessToken();
private NullSimpleAccessToken() {
super(null);
}
@Override
public int hashCode() {
return 0;
}
@Override
public boolean equals(Object other) {
return (other == null) || (other.toString() == null);
}
}
/**
* Returns a new THREAD-SAFE token provider that does NOT have weak keys (may be faster).
* <p>
* WARN: Caller should ONLY use this if he knows he can always clear the keys himself.
*/
public static <V> AccessTokenProvider<V> newAccessTokenProvider(EventHandler<V> eventHandler) {
return new ConcurrentSimpleAccessTokenProvider<V>(eventHandler);
}
/**
* Returns a new THREAD-SAFE token provider that uses weak keys (less chance of memory leaks, but slower).
* <p>
* With this, caller does not need to clear keys manually (though can for faster gc).
* <p>
* NOTE: This may be a little slower than the others due to synchronization needed.
* <p>
* FIXME: This implementation is slow because it synchronizes around WeakHashMap get accesses!
* Needs a fast concurrent weak hash map implementation instead!
*/
public static <V> AccessTokenProvider<V> newWeakAccessTokenProvider(EventHandler<V> eventHandler) {
return new WeakSimpleAccessTokenProvider<V>(eventHandler);
}
/**
* Returns a new NON-THREAD-SAFE token provider that does NOT have weak keys.
*/
public static <V> AccessTokenProvider<V> newUnsafeAccessTokenProvider(EventHandler<V> eventHandler) {
return new HashMapSimpleAccessTokenProvider<V>(eventHandler);
}
/**
* Returns a new NON-THREAD-SAFE token provider with weak keys.
*/
public static <V> AccessTokenProvider<V> newUnsafeWeakAccessTokenProvider(EventHandler<V> eventHandler) {
return new UnsafeWeakSimpleAccessTokenProvider<V>(eventHandler);
}
public static abstract class SimpleAccessTokenProvider<V> extends AccessTokenProvider<V> {
protected SimpleAccessTokenProvider(EventHandler<V> eventHandler) {
super(eventHandler);
}
@Override
public AccessToken newToken() {
return new SimpleAccessToken(newTokenString());
}
@Override
public AccessToken newToken(String tokenString) {
return (tokenString != null) ? new SimpleAccessToken(tokenString) : NullSimpleAccessToken.INSTANCE;
}
}
public static abstract class MapSimpleAccessTokenProvider<V> extends SimpleAccessTokenProvider<V> {
protected final Map<AccessToken, V> tokens;
protected MapSimpleAccessTokenProvider(EventHandler<V> eventHandler, Map<AccessToken, V> tokens) {
super(eventHandler);
this.tokens = tokens;
}
@Override
public V get(AccessToken token) {
return tokens.get(token);
}
@Override
public V put(AccessToken token, V value) {
return tokens.put(token, value);
}
@Override
public V remove(AccessToken token) {
return tokens.remove(token);
}
}
/**
* Map token provider that synchronizes around the map.
* <p>
* WARN: get accesses are synchronized - relatively slow.
*/
public static abstract class SyncingMapSimpleAccessTokenProvider<V> extends MapSimpleAccessTokenProvider<V> {
protected SyncingMapSimpleAccessTokenProvider(EventHandler<V> eventHandler, Map<AccessToken, V> tokens) {
super(eventHandler, tokens);
}
@Override
public V get(AccessToken token) {
synchronized(tokens) {
return tokens.get(token);
}
}
@Override
public V put(AccessToken token, V value) {
synchronized(tokens) {
return tokens.put(token, value);
}
}
@Override
public V remove(AccessToken token) {
synchronized(tokens) {
return tokens.remove(token);
}
}
}
/**
* Thread-safe fast token provider with non-weak keys.
*/
public static class ConcurrentSimpleAccessTokenProvider<V> extends MapSimpleAccessTokenProvider<V> {
protected ConcurrentSimpleAccessTokenProvider(EventHandler<V> eventHandler) {
super(eventHandler, new ConcurrentHashMap<AccessToken, V>());
}
}
/**
* Thread-safe slow token provider with weak keys.
* <p>
* WARN: get accesses are synchronized - relatively slow.
*/
public static class WeakSimpleAccessTokenProvider<V> extends SyncingMapSimpleAccessTokenProvider<V> {
protected WeakSimpleAccessTokenProvider(EventHandler<V> eventHandler) {
super(eventHandler, new WeakHashMap<AccessToken, V>());
}
}
/**
* Non-thread-safe fast HashMap token provider with non-weak keys.
*/
public static class HashMapSimpleAccessTokenProvider<V> extends MapSimpleAccessTokenProvider<V> {
protected HashMapSimpleAccessTokenProvider(EventHandler<V> eventHandler) {
super(eventHandler, new HashMap<>());
}
}
/**
* Non-thread-safe fast WeakHashMap token provider with weak keys.
*/
public static class UnsafeWeakSimpleAccessTokenProvider<V> extends MapSimpleAccessTokenProvider<V> {
protected UnsafeWeakSimpleAccessTokenProvider(EventHandler<V> eventHandler) {
super(eventHandler, new WeakHashMap<AccessToken, V>());
}
}
/**
* Returns the request token - only if it's already set in session (no create).
* <p>
* NOTE: there is no value parameter, which indicates this cannot create token.
* <p>
* NOTE: Request-scoped tokens are for very specific implementations only! You probably want
* the session-based ones. If you do use this request-based one, you'll need either a weak-keys based
* provider or a try/finally block.
*/
public AccessToken getLocalRequestToken(HttpServletRequest request, String attrName) {
return (AccessToken) request.getAttribute(attrName);
}
/**
* Gets request token; if not yet created or registered in the provider for whatever reason, does so.
* <p>
* NOTE: there is no value parameter, which indicates this cannot create token.
* <p>
* NOTE: Request-scoped tokens are for very specific implementations only! You probably want
* the session-based ones. If you do use this request-based one, you'll need either a weak-keys based
* provider or a try/finally block.
*/
public AccessToken getRequestToken(HttpServletRequest request, String attrName, V initialValue) {
AccessToken token = getLocalRequestToken(request, attrName);
if (token != null) {
return token;
}
token = newToken();
put(token, initialValue);
request.setAttribute(attrName, token);
return token;
}
/**
* Returns the session token - only if it's already set in session (no create).
* <p>
* NOTE: there is no value parameter, which indicates this cannot create token.
* <p>
* WARN: Even if this returns non-null, it is not guaranteed the token is properly
* registered in the provider! Use {@link #getSessionToken} to guarantee that.
*/
public AccessToken getLocalSessionToken(HttpSession session, HttpServletRequest request, String attrName) {
AccessToken token;
if (request != null) {
token = (AccessToken) request.getAttribute(attrName);
if (token != null) return token;
}
token = (AccessToken) session.getAttribute(attrName);
if (token != null) {
request.setAttribute(attrName, token);
}
return token;
}
/**
* Gets session token; if not yet created or registered in the provider for whatever reason, does so, with optional specific token string.
* <p>
* If the token string is specified and does not match the existing token, the existing session token is replaced - in other words
* non-null tokenString "forces" the token to be a specific string.
* <p>
* After this call, the session is guaranteed to contain a token.
* <p>
* WARN: FIXME: Synchronization on session is not guaranteed due to servlet API -
* e.g. will fail for session replication.
* To prevent issues, only call this from controller after-login events or from
* {@link javax.servlet.http.HttpSessionListener#sessionCreated} implementations.
*/
public AccessToken getSessionToken(HttpSession session, HttpServletRequest request, String attrName, String tokenString, V initialValue) {
// the following is an optimization to skip synchronized block, at least for ConcurrentHashMap
AccessToken token = getLocalSessionToken(session, request, attrName);
if (token != null && (tokenString == null || tokenString.equals(token.toString()))) {
if (this.get(token) != null) {
return token;
}
}
synchronized (UtilHttp.getSessionSyncObject(session)) {
token = (AccessToken) session.getAttribute(attrName);
if (token != null && (tokenString == null || tokenString.equals(token.toString()))) {
if (this.get(token) != null) {
return token;
}
}
return createSessionToken(session, request, attrName, tokenString, initialValue);
}
}
/**
* Gets session token; if not yet created or registered in the provider for whatever reason, does so.
* <p>
* After this call, the session is guaranteed to contain a token.
* <p>
* WARN: FIXME: Synchronization on session is not guaranteed due to servlet API -
* e.g. will fail for session replication.
* To prevent issues, only call this from controller after-login events or from
* {@link javax.servlet.http.HttpSessionListener#sessionCreated} implementations.
*/
public AccessToken getSessionToken(HttpSession session, HttpServletRequest request, String attrName, V initialValue) {
return getSessionToken(session, request, attrName, null, initialValue);
}
/**
* Creates token in session with given value, removing any prior, with optional specific token string.
* <p>
* After this call, the session is guaranteed to contain a token.
* <p>
* WARN: FIXME: Synchronization on session is not guaranteed due to servlet API -
* e.g. will fail for session replication.
* To prevent issues, only call this from controller after-login events or from
* {@link javax.servlet.http.HttpSessionListener#sessionCreated} implementations.
*/
public AccessToken createSessionToken(HttpSession session, HttpServletRequest request, String attrName, String tokenString, V initialValue) {
synchronized(UtilHttp.getSessionSyncObject(session)) {
cleanupSessionToken(session, request, attrName);
AccessToken token = (tokenString != null) ? newToken(tokenString) : newToken();
put(token, initialValue);
session.setAttribute(attrName, token);
request.setAttribute(attrName, token);
getEventHandler().sessionTokenCreated(session, request, attrName, token, initialValue);
return token;
}
}
/**
* Creates token in session with given value, removing any prior
* <p>
* After this call, the session is guaranteed to contain a token.
* <p>
* WARN: FIXME: Synchronization on session is not guaranteed due to servlet API -
* e.g. will fail for session replication.
* To prevent issues, only call this from controller after-login events or from
* {@link javax.servlet.http.HttpSessionListener#sessionCreated} implementations.
*/
public AccessToken createSessionToken(HttpSession session, HttpServletRequest request, String attrName, V initialValue) {
return createSessionToken(session, request, attrName, null, initialValue);
}
public void cleanupSessionToken(HttpSession session, HttpServletRequest request, String attrName) {
synchronized(UtilHttp.getSessionSyncObject(session)) {
if (request != null) {
AccessToken token = (AccessToken) request.getAttribute(attrName);
if (token != null) {
request.removeAttribute(attrName);
remove(token);
}
}
AccessToken token = (AccessToken) session.getAttribute(attrName);
if (token != null) {
session.removeAttribute(attrName);
remove(token);
}
}
}
public interface EventHandler<V> {
default void sessionTokenCreated(HttpSession session, HttpServletRequest request,
String attrName, AccessToken token, V value) {}
}
public static class NoopEventHandler<V> implements EventHandler<V> {
private static final NoopEventHandler<?> INSTANCE = new NoopEventHandler<Object>();
@SuppressWarnings("unchecked")
public static <V> NoopEventHandler<V> getInstance() {
// implemented via type erasure to avoid needless extra objects
return (NoopEventHandler<V>) INSTANCE;
}
@Override
public void sessionTokenCreated(HttpSession session, HttpServletRequest request,
String attrName, AccessToken token, V value) {
}
}
}
| apache-2.0 |
lsimons/phloc-schematron-standalone | phloc-schematron/jing/src/main/java/com/thaiopensource/relaxng/edit/Component.java | 159 | package com.thaiopensource.relaxng.edit;
public abstract class Component extends Annotated
{
public abstract <T> T accept (ComponentVisitor <T> visitor);
}
| apache-2.0 |
kuujo/onos | protocols/grpc/api/src/main/java/org/onosproject/grpc/api/GrpcClientController.java | 2898 | /*
* Copyright 2018-present Open Networking 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.onosproject.grpc.api;
import com.google.common.annotations.Beta;
import org.onosproject.net.DeviceId;
/**
* Abstraction of a gRPC controller which controls specific gRPC client {@link
* C} with specific client key {@link K}.
*
* @param <K> the gRPC client key
* @param <C> the gRPC client type
*/
@Beta
public interface GrpcClientController<K extends GrpcClientKey, C extends GrpcClient> {
/**
* Instantiates a new client to operate on a gRPC server identified by the
* given information. As a result of this method, a client can be later
* obtained by invoking {@link #getClient(DeviceId)}.
* <p>
* Only one client can exist for the same device ID. Calls to this method
* are idempotent fot the same client key, i.e. returns true if such client
* already exists but a new one is not created. If there exists a client
* with same device ID but different address and port, removes old one and
* recreate new one.
*
* @param clientKey the client key
* @return true if the client was created and the channel to the server is
* open; false otherwise
*/
boolean createClient(K clientKey);
/**
* Retrieves the gRPC client to operate on the given device.
*
* @param deviceId the device identifier
* @return the gRPC client of the device if exists; null otherwise
*/
C getClient(DeviceId deviceId);
/**
* Removes the gRPC client for the given device. If no client exists for the
* given device, the result is a no-op.
*
* @param deviceId the device identifier
*/
void removeClient(DeviceId deviceId);
/**
* Check reachability of the gRPC server running on the given device.
* Reachability can be tested only if a client is previously created using
* {@link #createClient(GrpcClientKey)}. Note that this only checks the
* reachability instead of checking service availability, different
* service-specific gRPC clients might check service availability in a
* different way.
*
* @param deviceId the device identifier
* @return true if client was created and is able to contact the gNMI
* server; false otherwise
*/
boolean isReachable(DeviceId deviceId);
}
| apache-2.0 |
rndsolutions/hawkcd | Server/src/main/java/io/hawkcd/services/interfaces/IFileManagementService.java | 1591 | /*
* Copyright (C) 2016 R&D Solutions Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.hawkcd.services.interfaces;
import io.hawkcd.model.payload.JsTreeFile;
import java.io.File;
import java.io.InputStream;
import java.util.List;
public interface IFileManagementService {
String unzipFile(String filePath, String destination);
String streamToFile(InputStream stream, String filePath);
List<File> getFiles(String rootPath, String wildCardPattern);
String zipFiles(String zipFilePath, List<File> files, String filesRootPath, boolean includeRootPath);
File generateUniqueFile(String filePath, String fileExtension);
String deleteFile(String filePath);
String deleteDirectoryRecursively(String directoryPath);
String getRootPath(String fullPath);
String getPattern(String rootPath, String fullPath);
String pathCombine(String... args);
String normalizePath(String filePath);
String urlCombine(String... args);
String getAbsolutePath(String path);
JsTreeFile getFileNames(File parentDirectory);
}
| apache-2.0 |
bmwcarit/joynr | java/backend-services/capabilities-directory/src/test/java/io/joynr/capabilities/TestCapabilitiesProvisioning.java | 980 | /*
* #%L
* %%
* Copyright (C) 2011 - 2017 BMW Car IT GmbH
* %%
* 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 io.joynr.capabilities;
import java.util.Collection;
import java.util.Collections;
import joynr.types.GlobalDiscoveryEntry;
public class TestCapabilitiesProvisioning implements CapabilitiesProvisioning {
@Override
public Collection<GlobalDiscoveryEntry> getDiscoveryEntries() {
return Collections.emptyList();
}
}
| apache-2.0 |
vrkansagara/elasticsearch | src/main/java/org/elasticsearch/action/mlt/MoreLikeThisRequestBuilder.java | 8672 | /*
* 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.mlt;
import org.elasticsearch.action.ActionRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.client.ElasticsearchClient;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.search.Scroll;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import java.util.Map;
/**
*/
public class MoreLikeThisRequestBuilder extends ActionRequestBuilder<MoreLikeThisRequest, SearchResponse, MoreLikeThisRequestBuilder> {
public MoreLikeThisRequestBuilder(ElasticsearchClient client, MoreLikeThisAction action) {
super(client, action, new MoreLikeThisRequest());
}
public MoreLikeThisRequestBuilder(ElasticsearchClient client, MoreLikeThisAction action, String index, String type, String id) {
super(client, action, new MoreLikeThisRequest(index).type(type).id(id));
}
/**
* The fields of the document to use in order to find documents "like" this one. Defaults to run
* against all the document fields.
*/
public MoreLikeThisRequestBuilder setField(String... fields) {
request.fields(fields);
return this;
}
/**
* Sets the routing. Required if routing isn't id based.
*/
public MoreLikeThisRequestBuilder setRouting(String routing) {
request.routing(routing);
return this;
}
/**
* Number of terms that must match the generated query expressed in the
* common syntax for minimum should match. Defaults to <tt>30%</tt>.
*
* @see org.elasticsearch.common.lucene.search.Queries#calculateMinShouldMatch(int, String)
*/
public MoreLikeThisRequestBuilder setMinimumShouldMatch(String minimumShouldMatch) {
request.minimumShouldMatch(minimumShouldMatch);
return this;
}
/**
* The percent of the terms to match for each field. Defaults to <tt>0.3f</tt>.
*/
public MoreLikeThisRequestBuilder setPercentTermsToMatch(float percentTermsToMatch) {
return setMinimumShouldMatch(Math.round(percentTermsToMatch * 100) + "%");
}
/**
* The frequency below which terms will be ignored in the source doc. Defaults to <tt>2</tt>.
*/
public MoreLikeThisRequestBuilder setMinTermFreq(int minTermFreq) {
request.minTermFreq(minTermFreq);
return this;
}
/**
* The maximum number of query terms that will be included in any generated query. Defaults to <tt>25</tt>.
*/
public MoreLikeThisRequestBuilder maxQueryTerms(int maxQueryTerms) {
request.maxQueryTerms(maxQueryTerms);
return this;
}
/**
* Any word in this set is considered "uninteresting" and ignored.
* <p/>
* <p>Even if your Analyzer allows stopwords, you might want to tell the MoreLikeThis code to ignore them, as
* for the purposes of document similarity it seems reasonable to assume that "a stop word is never interesting".
* <p/>
* <p>Defaults to no stop words.
*/
public MoreLikeThisRequestBuilder setStopWords(String... stopWords) {
request.stopWords(stopWords);
return this;
}
/**
* The frequency at which words will be ignored which do not occur in at least this
* many docs. Defaults to <tt>5</tt>.
*/
public MoreLikeThisRequestBuilder setMinDocFreq(int minDocFreq) {
request.minDocFreq(minDocFreq);
return this;
}
/**
* The maximum frequency in which words may still appear. Words that appear
* in more than this many docs will be ignored. Defaults to unbounded.
*/
public MoreLikeThisRequestBuilder setMaxDocFreq(int maxDocFreq) {
request.maxDocFreq(maxDocFreq);
return this;
}
/**
* The minimum word length below which words will be ignored. Defaults to <tt>0</tt>.
*/
public MoreLikeThisRequestBuilder setMinWordLen(int minWordLen) {
request.minWordLength(minWordLen);
return this;
}
/**
* The maximum word length above which words will be ignored. Defaults to unbounded.
*/
public MoreLikeThisRequestBuilder setMaxWordLen(int maxWordLen) {
request().maxWordLength(maxWordLen);
return this;
}
/**
* The boost factor to use when boosting terms. Defaults to <tt>1</tt>.
*/
public MoreLikeThisRequestBuilder setBoostTerms(float boostTerms) {
request.boostTerms(boostTerms);
return this;
}
/**
* Whether to include the queried document. Defaults to <tt>false</tt>.
*/
public MoreLikeThisRequestBuilder setInclude(boolean include) {
request.include(include);
return this;
}
/**
* An optional search source request allowing to control the search request for the
* more like this documents.
*/
public MoreLikeThisRequestBuilder setSearchSource(SearchSourceBuilder sourceBuilder) {
request.searchSource(sourceBuilder);
return this;
}
/**
* An optional search source request allowing to control the search request for the
* more like this documents.
*/
public MoreLikeThisRequestBuilder setSearchSource(String searchSource) {
request.searchSource(searchSource);
return this;
}
/**
* An optional search source request allowing to control the search request for the
* more like this documents.
*/
public MoreLikeThisRequestBuilder setSearchSource(Map searchSource) {
request.searchSource(searchSource);
return this;
}
/**
* An optional search source request allowing to control the search request for the
* more like this documents.
*/
public MoreLikeThisRequestBuilder setSearchSource(XContentBuilder builder) {
request.searchSource(builder);
return this;
}
/**
* An optional search source request allowing to control the search request for the
* more like this documents.
*/
public MoreLikeThisRequestBuilder setSearchSource(byte[] searchSource) {
request.searchSource(searchSource);
return this;
}
/**
* The search type of the mlt search query.
*/
public MoreLikeThisRequestBuilder setSearchType(SearchType searchType) {
request.searchType(searchType);
return this;
}
/**
* The search type of the mlt search query.
*/
public MoreLikeThisRequestBuilder setSearchType(String searchType) {
request.searchType(searchType);
return this;
}
/**
* The indices the resulting mlt query will run against. If not set, will run
* against the index the document was fetched from.
*/
public MoreLikeThisRequestBuilder setSearchIndices(String... searchIndices) {
request.searchIndices(searchIndices);
return this;
}
/**
* The types the resulting mlt query will run against. If not set, will run
* against the type of the document fetched.
*/
public MoreLikeThisRequestBuilder setSearchTypes(String... searchTypes) {
request.searchTypes(searchTypes);
return this;
}
/**
* An optional search scroll request to be able to continue and scroll the search
* operation.
*/
public MoreLikeThisRequestBuilder setSearchScroll(Scroll searchScroll) {
request.searchScroll(searchScroll);
return this;
}
/**
* The number of documents to return, defaults to 10.
*/
public MoreLikeThisRequestBuilder setSearchSize(int size) {
request.searchSize(size);
return this;
}
/**
* From which search result set to return.
*/
public MoreLikeThisRequestBuilder setSearchFrom(int from) {
request.searchFrom(from);
return this;
}
}
| apache-2.0 |
logonmy/HeartBeat | app/src/main/java/com/maxiee/heartbeat/common/cloudview/CloudView.java | 7076 | package com.maxiee.heartbeat.common.cloudview;
import android.content.Context;
import android.graphics.Color;
import android.support.v4.view.NestedScrollingChild;
import android.support.v4.view.NestedScrollingChildHelper;
import android.util.AttributeSet;
import android.util.Pair;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RemoteViews;
import android.widget.TextView;
import com.maxiee.heartbeat.R;
import java.util.List;
/**
* Created by maxiee on 15-6-24.
*/
@RemoteViews.RemoteView
public class CloudView extends ViewGroup {
private static final int MAX_SIZE = 70;
private OnLabelClickListener mCallback;
public interface OnLabelClickListener {
void onClick(String label);
}
public CloudView(Context context) {
super(context);
}
public CloudView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CloudView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public void setOnLabelClickListener(OnLabelClickListener callback) {
mCallback = callback;
}
public void addLabels(List<Pair<String, Integer>> labels) {
removeAllViews();
if (labels == null) {
return;
}
float maxFreq = computeMaxFreq(labels);
final TypedValue accentValue = new TypedValue();
getContext().getTheme().resolveAttribute(R.attr.colorAccent, accentValue, true);
int accentColor = accentValue.data;
final TypedValue grayValue = new TypedValue();
getContext().getTheme().resolveAttribute(R.attr.colorPrimary, grayValue, true);
int grayColor = grayValue.data;
float redStep = (Color.red(accentColor) - Color.red(grayColor)) / maxFreq;
float greenStep = (Color.green(accentColor) - Color.green(grayColor)) / maxFreq;
float blueStep = (Color.blue(accentColor) - Color.blue(grayColor)) / maxFreq;
for (final Pair<String, Integer> label: labels) {
TextView tagView = new TextView(getContext());
tagView.setText(label.first);
tagView.setTextSize(label.second / maxFreq * MAX_SIZE);
tagView.setTextColor(
Color.rgb(
(int) (Color.red(grayColor) + redStep * label.second),
(int) (Color.green(grayColor) + greenStep * label.second),
(int) (Color.blue(grayColor) + blueStep * label.second)
)
);
LayoutParams layoutParams = new LayoutParams(
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT
);
layoutParams.setMargins(20, 5, 20, 5);
tagView.setLayoutParams(layoutParams);
tagView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (mCallback != null) {
mCallback.onClick(label.first);
}
}
});
addView(tagView);
}
}
private float computeMaxFreq(List<Pair<String, Integer>> labels) {
float maxFreq = 1;
for (Pair<String, Integer> label: labels) {
if (label.second > maxFreq) {
maxFreq = label.second;
}
}
return maxFreq;
}
@Override
public boolean shouldDelayChildPressedState() {
return false;
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
int mViewGroupWidth = getMeasuredWidth();
int mViewGroupHeight = getMeasuredHeight();
int heightMax = 0;
int mPainterPosX = l;
int mPainterPosY = t;
int childCount = getChildCount();
for (int i=0; i<childCount; i++) {
View childView = getChildAt(i);
int width = childView.getMeasuredWidth();
int height = childView.getMeasuredHeight();
LayoutParams layoutParams = (LayoutParams) childView.getLayoutParams();
if (mPainterPosX + layoutParams.leftMargin + width + layoutParams.rightMargin > mViewGroupWidth) {
mPainterPosX = l;
mPainterPosY += heightMax;
heightMax = 0;
}
childView.layout(
mPainterPosX + layoutParams.leftMargin,
mPainterPosY + layoutParams.topMargin,
mPainterPosX + width + layoutParams.rightMargin,
mPainterPosY + height + layoutParams.bottomMargin
);
mPainterPosX += width + layoutParams.leftMargin + layoutParams.rightMargin;
if (height > heightMax) {
heightMax = height;
}
}
}
@Override
public ViewGroup.LayoutParams generateLayoutParams(AttributeSet attrs) {
return new ViewGroup.LayoutParams(getContext(), attrs);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int count = getChildCount();
int start = 0;
int currentLineWidth = 0;
int currentLineHeight = 0;
int totalHeight = 0;
int totalWeight = 0;
for (int i=0; i<count; i++) {
final View child = getChildAt(i);
measureChildWithMargins(child, widthMeasureSpec, 0, heightMeasureSpec, 0);
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
if (i==0) { // first one
start = child.getLeft();
currentLineWidth = child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin;
currentLineHeight = child.getMeasuredHeight() + lp.topMargin + lp.bottomMargin;
} else if (child.getLeft() != start) { // not the last
currentLineHeight = Math.max(
currentLineHeight, child.getMeasuredHeight() + lp.topMargin + lp.bottomMargin);
currentLineWidth += child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin;
} else { // the last one
totalHeight += currentLineHeight;
totalWeight= Math.max(currentLineWidth, totalWeight);
currentLineWidth = child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin;
currentLineHeight = child.getMeasuredHeight() + lp.topMargin + lp.bottomMargin;
}
}
setMeasuredDimension(resolveSize(totalWeight, widthMeasureSpec), resolveSize(totalHeight, heightMeasureSpec));
}
public static class LayoutParams extends MarginLayoutParams {
public LayoutParams(Context c, AttributeSet attrs) {
super(c, attrs);
}
public LayoutParams(int width, int height) {
super(width, height);
}
public LayoutParams(MarginLayoutParams source) {
super(source);
}
}
}
| apache-2.0 |
CMPUT301F17T13/cat-is-a-dog | app/src/androidTest/java/cmput301f17t13/com/catisadog/HabitHistoryTest.java | 2147 | package cmput301f17t13.com.catisadog;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import org.joda.time.DateTime;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import cmput301f17t13.com.catisadog.activities.history.HabitHistoryActivity;
import cmput301f17t13.com.catisadog.mocks.MockAuthentication;
import static android.support.test.espresso.Espresso.onData;
import static android.support.test.espresso.assertion.ViewAssertions.matches;
import static android.support.test.espresso.matcher.ViewMatchers.withId;
import static android.support.test.espresso.matcher.ViewMatchers.withText;
import static org.hamcrest.Matchers.anything;
@RunWith(AndroidJUnit4.class)
public class HabitHistoryTest {
@Rule
public ActivityTestRule<HabitHistoryActivity> mActivityRule =
new ActivityTestRule<>(HabitHistoryActivity.class, false, false);
@Before
public void setUp() throws Exception {
MockAuthentication.signIn();
mActivityRule.launchActivity(null);
}
@Test
public void showHabitTitle() throws Exception {
onData(anything())
.inAdapterView(withId(R.id.list))
.atPosition(0)
.onChildView(withId(R.id.myHabitEventListItemTitle))
.check(matches(withText("Test Habit")));
}
@Test
public void showHabitEventReason() throws Exception {
onData(anything())
.inAdapterView(withId(R.id.list))
.atPosition(0)
.onChildView(withId(R.id.myHabitEventListItemReason))
.check(matches(withText("Did it")));
}
@Test
public void showHabitEventDate() throws Exception {
DateTime testDate = new DateTime(1512199000000l);
String dateString = testDate.toString("d MMM");
onData(anything())
.inAdapterView(withId(R.id.list))
.atPosition(0)
.onChildView(withId(R.id.myHabitEventListItemStartDate))
.check(matches(withText(dateString)));
}
} | apache-2.0 |
GhostRealms/Metropolis | src/main/java/net/ghostrealms/Register.java | 5305 | package net.ghostrealms;
import net.ghostrealms.plot.Plot;
import net.ghostrealms.resident.Resident;
import net.ghostrealms.town.Town;
import org.bukkit.Chunk;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
public class Register {
private static Register me;
private final JavaPlugin plugin;
private final Database database;
private Map<Integer, Town> loadedTowns = new HashMap<Integer, Town>();
private Map<UUID, Resident> onlineResidents = new HashMap<UUID, Resident>();
static String readFile(String path) throws IOException {
byte[] encoded = Files.readAllBytes(Paths.get(path));
return new String(encoded, Charset.defaultCharset());
}
public Register(JavaPlugin plugin, Database database) {
this.plugin = plugin;
this.database = database;
me = this;
}
public Plot registerPlot(Player p) {
return null;
}
public static Register getInstance() {
return me;
}
public void cachePlot(Plot plot) {
//TODO add a plot to the cache
}
public void cacheResident(Resident r) {
//TODO add a resident to the cache
}
public void cacheTown(Town t) {
//TODO add a town to the cache
}
public Plot getPlot(int x, int z) {
return null;
}
public Plot getPlot(Chunk c) {
return null;
}
public Town getTown(String name) {
ResultSet results = database.executeQuery("SELECT * FROM town_map WHERE name = " + name + ";");
try {
if(!results.next()) {
return null;
} else {
results.beforeFirst();
results.next();
int id = results.getInt("id");
return getTown(id);
}
} catch (SQLException ex) {
return null;
}
}
protected void loadTowns() {
for(File f : new File(plugin.getDataFolder() + File.separator + "towns").listFiles()) {
String name = f.getName();
String[] split = name.split(".");
int id = Integer.parseInt(split[0]);
try {
String xml = readFile(f.getPath());
loadedTowns.put(id, (Town) Metro.xstream().fromXML(xml));
} catch (IOException e) {
e.printStackTrace();
return;
}
}
}
protected void saveTowns() {
for (Town t : loadedTowns.values()) {
FileOutputStream out = null;
try {
String xml = Metro.xstream().toXML(t);
out = new FileOutputStream(getTownFile(t));
out.write("<?xml version=\"1.0\"?>".getBytes("UTF-8"));
byte[] bytes = xml.getBytes("UTF-8");
out.write(bytes);
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (UnsupportedEncodingException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if(out != null) {
try {
out.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
}
public Town getTown(int tID) {
if(loadedTowns.containsKey(tID)) {
return loadedTowns.get(tID);
}
File file = new File(getTownFolderPath() + tID + ".xml");
if(file.exists()) {
try {
String xml = readFile(file.getPath());
return (Town) Metro.xstream().fromXML(xml);
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
} else {
return null;
}
}
public File getTownFile(Town town) {
File file = new File(getTownFolderPath() + File.separator + town.getTID() + ".xml");
if(file.exists()) {
return file;
} else {
try {
file.createNewFile();
} catch (IOException ex) {
ex.printStackTrace();
}
return file;
}
}
public Resident getResident(Player p) {
if(p.isOnline()) {
if(onlineResidents.containsKey(p.getUniqueId())) {
return onlineResidents.get(p.getUniqueId());
} else {
return new Resident(p);
}
} else {
return new Resident(p);
}
}
public Resident getResident(UUID id) {
if(onlineResidents.containsKey(id)) {
return onlineResidents.get(id);
} else {
return new Resident(id);
}
}
/**
* Creates a resident object and adds that object to the online resident mapping cache
* @param player
*/
protected void loginResident(Player player) {
Resident res = new Resident(player);
onlineResidents.put(player.getUniqueId(), res);
}
/**
* Remove a resident from the logged in listing, called on the PlayerQuit and PlayerLogout events
* @param uuid
*/
protected void logoutResident(UUID uuid) {
if(onlineResidents.containsKey(uuid)) {
onlineResidents.remove(uuid);
}
}
public String getTownFolderPath() {
String data_folder = Metro.plugin().getDataFolder().getPath();
return data_folder + File.separator + "towns" + File.separator;
}
}
| apache-2.0 |
qtvbwfn/dubbo | dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/Constants.java | 2541 | /*
* 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.dubbo.registry;
public interface Constants {
String REGISTER_IP_KEY = "register.ip";
String REGISTER_KEY = "register";
String SUBSCRIBE_KEY = "subscribe";
String DEFAULT_REGISTRY = "dubbo";
String REGISTER = "register";
String UNREGISTER = "unregister";
String SUBSCRIBE = "subscribe";
String UNSUBSCRIBE = "unsubscribe";
String CONFIGURATORS_SUFFIX = ".configurators";
String ADMIN_PROTOCOL = "admin";
String PROVIDER_PROTOCOL = "provider";
String CONSUMER_PROTOCOL = "consumer";
String SCRIPT_PROTOCOL = "script";
String CONDITION_PROTOCOL = "condition";
String TRACE_PROTOCOL = "trace";
/**
* simple the registry for provider.
*
* @since 2.7.0
*/
String SIMPLIFIED_KEY = "simplified";
/**
* To decide whether register center saves file synchronously, the default value is asynchronously
*/
String REGISTRY_FILESAVE_SYNC_KEY = "save.file";
/**
* Reconnection period in milliseconds for register center
*/
String REGISTRY_RECONNECT_PERIOD_KEY = "reconnect.period";
int DEFAULT_SESSION_TIMEOUT = 60 * 1000;
/**
* Default value for the times of retry: 3
*/
int DEFAULT_REGISTRY_RETRY_TIMES = 3;
int DEFAULT_REGISTRY_RECONNECT_PERIOD = 3 * 1000;
/**
* Default value for the period of retry interval in milliseconds: 5000
*/
int DEFAULT_REGISTRY_RETRY_PERIOD = 5 * 1000;
/**
* Most retry times
*/
String REGISTRY_RETRY_TIMES_KEY = "retry.times";
/**
* Period of registry center's retry interval
*/
String REGISTRY_RETRY_PERIOD_KEY = "retry.period";
String SESSION_TIMEOUT_KEY = "session";
}
| apache-2.0 |
alexduch/grobid | grobid-core/src/main/java/org/grobid/core/engines/Segmentation.java | 50129 | package org.grobid.core.engines;
import eugfc.imageio.plugins.PNMRegistry;
import org.apache.commons.io.FileUtils;
import org.grobid.core.GrobidModels;
import org.grobid.core.document.BasicStructureBuilder;
import org.grobid.core.document.Document;
import org.grobid.core.document.DocumentSource;
import org.grobid.core.engines.config.GrobidAnalysisConfig;
import org.grobid.core.exceptions.GrobidException;
import org.grobid.core.exceptions.GrobidExceptionStatus;
import org.grobid.core.features.FeatureFactory;
import org.grobid.core.features.FeaturesVectorSegmentation;
import org.grobid.core.layout.*;
import org.grobid.core.utilities.GrobidProperties;
import org.grobid.core.utilities.LanguageUtilities;
import org.grobid.core.utilities.TextUtilities;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.*;
import java.util.regex.Matcher;
import static org.apache.commons.lang3.StringUtils.*;
// for image conversion we're using an ImageIO plugin for PPM format support
// see https://github.com/eug/imageio-pnm
// the jar for this plugin is located in the local repository
/**
* Realise a high level segmentation of a document into cover page, document header, page footer,
* page header, document body, bibliographical section, each bibliographical references in
* the biblio section and finally the possible annexes.
*
* @author Patrice Lopez
*/
public class Segmentation extends AbstractParser {
/*
10 labels for this model:
cover page <cover>,
document header <header>,
page footer <footnote>,
page header <headnote>,
note in margin <marginnote>,
document body <body>,
bibliographical section <references>,
page number <page>,
annexes <annex>,
acknowledgement <acknowledgement>,
other <other>,
toc <toc> -> not yet used because not yet training data for this
*/
private static final Logger LOGGER = LoggerFactory.getLogger(Segmentation.class);
// default bins for relative position
private static final int NBBINS_POSITION = 12;
// default bins for inter-block spacing
private static final int NBBINS_SPACE = 5;
// default bins for block character density
private static final int NBBINS_DENSITY = 5;
// projection scale for line length
private static final int LINESCALE = 10;
private LanguageUtilities languageUtilities = LanguageUtilities.getInstance();
private FeatureFactory featureFactory = FeatureFactory.getInstance();
/**
* TODO some documentation...
*/
public Segmentation() {
super(GrobidModels.SEGMENTATION);
}
/**
* Segment a PDF document into high level zones: cover page, document header,
* page footer, page header, body, page numbers, biblio section and annexes.
*
* @param documentSource document source
* @return Document object with segmentation information
*/
public Document processing(DocumentSource documentSource, GrobidAnalysisConfig config) {
try {
Document doc = new Document(documentSource);
if (config.getAnalyzer() != null)
doc.setAnalyzer(config.getAnalyzer());
doc.addTokenizedDocument(config);
doc = prepareDocument(doc);
// if assets is true, the images are still there under directory pathXML+"_data"
// we copy them to the assetPath directory
File assetFile = config.getPdfAssetPath();
if (assetFile != null) {
dealWithImages(documentSource, doc, assetFile, config);
}
return doc;
} finally {
// keep it clean when leaving...
/*if (config.getPdfAssetPath() == null) {
// remove the pdf2xml tmp file
DocumentSource.close(documentSource, false, true, true);
} else*/ {
// remove the pdf2xml tmp files, including the sub-directories
DocumentSource.close(documentSource, true, true, true);
}
}
}
public Document processing(String text) {
Document doc = Document.createFromText(text);
return prepareDocument(doc);
}
public Document prepareDocument(Document doc) {
List<LayoutToken> tokenizations = doc.getTokenizations();
if (tokenizations.size() > GrobidProperties.getPdfTokensMax()) {
throw new GrobidException("The document has " + tokenizations.size() + " tokens, but the limit is " + GrobidProperties.getPdfTokensMax(),
GrobidExceptionStatus.TOO_MANY_TOKENS);
}
doc.produceStatistics();
String content = getAllLinesFeatured(doc);
if (isNotEmpty(trim(content))) {
String labelledResult = label(content);
// set the different sections of the Document object
doc = BasicStructureBuilder.generalResultSegmentation(doc, labelledResult, tokenizations);
}
return doc;
}
private void dealWithImages(DocumentSource documentSource, Document doc, File assetFile, GrobidAnalysisConfig config) {
if (assetFile != null) {
// copy the files under the directory pathXML+"_data" (the asset files) into the path specified by assetPath
if (!assetFile.exists()) {
// we create it
if (assetFile.mkdir()) {
LOGGER.debug("Directory created: " + assetFile.getPath());
} else {
LOGGER.error("Failed to create directory: " + assetFile.getPath());
}
}
PNMRegistry.registerAllServicesProviders();
// filter all .jpg and .png files
File directoryPath = new File(documentSource.getXmlFile().getAbsolutePath() + "_data");
if (directoryPath.exists()) {
File[] files = directoryPath.listFiles();
if (files != null) {
int nbFiles = 0;
for (final File currFile : files) {
if (nbFiles > DocumentSource.PDFTOXML_FILES_AMOUNT_LIMIT)
break;
String toLowerCaseName = currFile.getName().toLowerCase();
if (toLowerCaseName.endsWith(".png") || !config.isPreprocessImages()) {
try {
if (toLowerCaseName.endsWith(".svg")) {
continue;
}
FileUtils.copyFileToDirectory(currFile, assetFile);
nbFiles++;
} catch (IOException e) {
LOGGER.error("Cannot copy file " + currFile.getAbsolutePath() + " to " + assetFile.getAbsolutePath(), e);
}
} else if (toLowerCaseName.endsWith(".jpg")
|| toLowerCaseName.endsWith(".ppm")
// || currFile.getName().toLowerCase().endsWith(".pbm")
) {
String outputFilePath = "";
try {
final BufferedImage bi = ImageIO.read(currFile);
if (toLowerCaseName.endsWith(".jpg")) {
outputFilePath = assetFile.getPath() + File.separator +
toLowerCaseName.replace(".jpg", ".png");
}
/*else if (currFile.getName().toLowerCase().endsWith(".pbm")) {
outputFilePath = assetFile.getPath() + File.separator +
currFile.getName().toLowerCase().replace(".pbm",".png");
}*/
else {
outputFilePath = assetFile.getPath() + File.separator +
toLowerCaseName.replace(".ppm", ".png");
}
ImageIO.write(bi, "png", new File(outputFilePath));
nbFiles++;
} catch (IOException e) {
LOGGER.error("Cannot convert file " + currFile.getAbsolutePath() + " to " + outputFilePath, e);
}
}
}
}
}
// update the path of the image description stored in Document
if (config.isPreprocessImages()) {
List<GraphicObject> images = doc.getImages();
if (images != null) {
String subPath = assetFile.getPath();
int ind = subPath.lastIndexOf("/");
if (ind != -1)
subPath = subPath.substring(ind + 1, subPath.length());
for (GraphicObject image : images) {
String fileImage = image.getFilePath();
if (fileImage == null) {
continue;
}
fileImage = fileImage.replace(".ppm", ".png")
.replace(".jpg", ".png");
ind = fileImage.indexOf("/");
image.setFilePath(subPath + fileImage.substring(ind, fileImage.length()));
}
}
}
}
}
/**
* Addition of the features at line level for the complete document.
* <p/>
* This is an alternative to the token level, where the unit for labeling is the line - so allowing faster
* processing and involving less features.
* Lexical features becomes line prefix and suffix, the feature text unit is the first 10 characters of the
* line without space.
* The dictionary flags are at line level (i.e. the line contains a name mention, a place mention, a year, etc.)
* Regarding layout features: font, size and style are the one associated to the first token of the line.
*/
public String getAllLinesFeatured(Document doc) {
List<Block> blocks = doc.getBlocks();
if ((blocks == null) || blocks.size() == 0) {
return null;
}
//guaranteeing quality of service. Otherwise, there are some PDF that may contain 300k blocks and thousands of extracted "images" that ruins the performance
if (blocks.size() > GrobidProperties.getPdfBlocksMax()) {
throw new GrobidException("Postprocessed document is too big, contains: " + blocks.size(), GrobidExceptionStatus.TOO_MANY_BLOCKS);
}
//boolean graphicVector = false;
//boolean graphicBitmap = false;
// list of textual patterns at the head and foot of pages which can be re-occur on several pages
// (typically indicating a publisher foot or head notes)
Map<String, Integer> patterns = new TreeMap<String, Integer>();
Map<String, Boolean> firstTimePattern = new TreeMap<String, Boolean>();
for (Page page : doc.getPages()) {
// we just look at the two first and last blocks of the page
if ((page.getBlocks() != null) && (page.getBlocks().size() > 0)) {
for(int blockIndex=0; blockIndex < page.getBlocks().size(); blockIndex++) {
if ( (blockIndex < 2) || (blockIndex > page.getBlocks().size()-2)) {
Block block = page.getBlocks().get(blockIndex);
String localText = block.getText();
if ((localText != null) && (localText.length() > 0)) {
String[] lines = localText.split("[\\n\\r]");
if (lines.length > 0) {
String line = lines[0];
String pattern = featureFactory.getPattern(line);
if (pattern.length() > 8) {
Integer nb = patterns.get(pattern);
if (nb == null) {
patterns.put(pattern, Integer.valueOf(1));
firstTimePattern.put(pattern, false);
}
else
patterns.put(pattern, Integer.valueOf(nb+1));
}
}
}
}
}
}
}
String featuresAsString = getFeatureVectorsAsString(doc,
patterns, firstTimePattern);
return featuresAsString;
}
private String getFeatureVectorsAsString(Document doc, Map<String, Integer> patterns,
Map<String, Boolean> firstTimePattern) {
StringBuilder fulltext = new StringBuilder();
int documentLength = doc.getDocumentLenghtChar();
String currentFont = null;
int currentFontSize = -1;
boolean newPage;
boolean start = true;
int mm = 0; // page position
int nn = 0; // document position
int pageLength = 0; // length of the current page
double pageHeight = 0.0;
// vector for features
FeaturesVectorSegmentation features;
FeaturesVectorSegmentation previousFeatures = null;
for (Page page : doc.getPages()) {
pageHeight = page.getHeight();
newPage = true;
double spacingPreviousBlock = 0.0; // discretized
double lowestPos = 0.0;
pageLength = page.getPageLengthChar();
BoundingBox pageBoundingBox = page.getMainArea();
mm = 0;
//endPage = true;
if ((page.getBlocks() == null) || (page.getBlocks().size() == 0))
continue;
for(int blockIndex=0; blockIndex < page.getBlocks().size(); blockIndex++) {
Block block = page.getBlocks().get(blockIndex);
/*if (start) {
newPage = true;
start = false;
}*/
boolean graphicVector = false;
boolean graphicBitmap = false;
boolean lastPageBlock = false;
boolean firstPageBlock = false;
if (blockIndex == page.getBlocks().size()-1) {
lastPageBlock = true;
}
if (blockIndex == 0) {
firstPageBlock = true;
}
//endblock = false;
/*if (endPage) {
newPage = true;
mm = 0;
}*/
// check if we have a graphical object connected to the current block
List<GraphicObject> localImages = Document.getConnectedGraphics(block, doc);
if (localImages != null) {
for(GraphicObject localImage : localImages) {
if (localImage.getType() == GraphicObjectType.BITMAP)
graphicBitmap = true;
if (localImage.getType() == GraphicObjectType.VECTOR)
graphicVector = true;
}
}
if (lowestPos > block.getY()) {
// we have a vertical shift, which can be due to a change of column or other particular layout formatting
spacingPreviousBlock = doc.getMaxBlockSpacing() / 5.0; // default
} else
spacingPreviousBlock = block.getY() - lowestPos;
String localText = block.getText();
if (localText == null)
continue;
// character density of the block
double density = 0.0;
if ( (block.getHeight() != 0.0) && (block.getWidth() != 0.0) &&
(block.getText() != null) && (!block.getText().contains("@PAGE")) &&
(!block.getText().contains("@IMAGE")) )
density = (double)block.getText().length() / (block.getHeight() * block.getWidth());
// is the current block in the main area of the page or not?
boolean inPageMainArea = true;
BoundingBox blockBoundingBox = BoundingBox.fromPointAndDimensions(page.getNumber(),
block.getX(), block.getY(), block.getWidth(), block.getHeight());
if (pageBoundingBox == null || (!pageBoundingBox.contains(blockBoundingBox) && !pageBoundingBox.intersect(blockBoundingBox)))
inPageMainArea = false;
String[] lines = localText.split("[\\n\\r]");
// set the max length of the lines in the block, in number of characters
int maxLineLength = 0;
for(int p=0; p<lines.length; p++) {
if (lines[p].length() > maxLineLength)
maxLineLength = lines[p].length();
}
List<LayoutToken> tokens = block.getTokens();
if ((tokens == null) || (tokens.size() == 0)) {
continue;
}
for (int li = 0; li < lines.length; li++) {
String line = lines[li];
/*boolean firstPageBlock = false;
boolean lastPageBlock = false;
if (newPage)
firstPageBlock = true;
if (endPage)
lastPageBlock = true;
*/
// for the layout information of the block, we take simply the first layout token
LayoutToken token = null;
if (tokens.size() > 0)
token = tokens.get(0);
double coordinateLineY = token.getY();
features = new FeaturesVectorSegmentation();
features.token = token;
features.line = line;
if ( (blockIndex < 2) || (blockIndex > page.getBlocks().size()-2)) {
String pattern = featureFactory.getPattern(line);
Integer nb = patterns.get(pattern);
if ((nb != null) && (nb > 1)) {
features.repetitivePattern = true;
Boolean firstTimeDone = firstTimePattern.get(pattern);
if ((firstTimeDone != null) && !firstTimeDone) {
features.firstRepetitivePattern = true;
firstTimePattern.put(pattern, true);
}
}
}
// we consider the first token of the line as usual lexical CRF token
// and the second token of the line as feature
StringTokenizer st2 = new StringTokenizer(line, " \t");
// alternatively, use a grobid analyser
String text = null;
String text2 = null;
if (st2.hasMoreTokens())
text = st2.nextToken();
if (st2.hasMoreTokens())
text2 = st2.nextToken();
if (text == null)
continue;
// final sanitisation and filtering
text = text.replaceAll("[ \n]", "");
text = text.trim();
if ( (text.length() == 0) ||
// (text.equals("\n")) ||
// (text.equals("\r")) ||
// (text.equals("\n\r")) ||
(TextUtilities.filterLine(line))) {
continue;
}
features.string = text;
features.secondString = text2;
features.firstPageBlock = firstPageBlock;
features.lastPageBlock = lastPageBlock;
//features.lineLength = line.length() / LINESCALE;
features.lineLength = featureFactory
.linearScaling(line.length(), maxLineLength, LINESCALE);
features.punctuationProfile = TextUtilities.punctuationProfile(line);
if (graphicBitmap) {
features.bitmapAround = true;
}
if (graphicVector) {
features.vectorAround = true;
}
features.lineStatus = null;
features.punctType = null;
if ((li == 0) ||
((previousFeatures != null) && previousFeatures.blockStatus.equals("BLOCKEND"))) {
features.blockStatus = "BLOCKSTART";
} else if (li == lines.length - 1) {
features.blockStatus = "BLOCKEND";
//endblock = true;
} else if (features.blockStatus == null) {
features.blockStatus = "BLOCKIN";
}
if (newPage) {
features.pageStatus = "PAGESTART";
newPage = false;
//endPage = false;
if (previousFeatures != null)
previousFeatures.pageStatus = "PAGEEND";
} else {
features.pageStatus = "PAGEIN";
newPage = false;
//endPage = false;
}
if (text.length() == 1) {
features.singleChar = true;
}
if (Character.isUpperCase(text.charAt(0))) {
features.capitalisation = "INITCAP";
}
if (featureFactory.test_all_capital(text)) {
features.capitalisation = "ALLCAP";
}
if (featureFactory.test_digit(text)) {
features.digit = "CONTAINSDIGITS";
}
if (featureFactory.test_common(text)) {
features.commonName = true;
}
if (featureFactory.test_names(text)) {
features.properName = true;
}
if (featureFactory.test_month(text)) {
features.month = true;
}
Matcher m = featureFactory.isDigit.matcher(text);
if (m.find()) {
features.digit = "ALLDIGIT";
}
Matcher m2 = featureFactory.year.matcher(text);
if (m2.find()) {
features.year = true;
}
Matcher m3 = featureFactory.email.matcher(text);
if (m3.find()) {
features.email = true;
}
Matcher m4 = featureFactory.http.matcher(text);
if (m4.find()) {
features.http = true;
}
if (currentFont == null) {
currentFont = token.getFont();
features.fontStatus = "NEWFONT";
} else if (!currentFont.equals(token.getFont())) {
currentFont = token.getFont();
features.fontStatus = "NEWFONT";
} else
features.fontStatus = "SAMEFONT";
int newFontSize = (int) token.getFontSize();
if (currentFontSize == -1) {
currentFontSize = newFontSize;
features.fontSize = "HIGHERFONT";
} else if (currentFontSize == newFontSize) {
features.fontSize = "SAMEFONTSIZE";
} else if (currentFontSize < newFontSize) {
features.fontSize = "HIGHERFONT";
currentFontSize = newFontSize;
} else if (currentFontSize > newFontSize) {
features.fontSize = "LOWERFONT";
currentFontSize = newFontSize;
}
if (token.getBold())
features.bold = true;
if (token.getItalic())
features.italic = true;
// HERE horizontal information
// CENTERED
// LEFTAJUSTED
// CENTERED
if (features.capitalisation == null)
features.capitalisation = "NOCAPS";
if (features.digit == null)
features.digit = "NODIGIT";
//if (features.punctType == null)
// features.punctType = "NOPUNCT";
features.relativeDocumentPosition = featureFactory
.linearScaling(nn, documentLength, NBBINS_POSITION);
//System.out.println(nn + " " + documentLength + " " + NBBINS_POSITION + " " + features.relativeDocumentPosition);
features.relativePagePositionChar = featureFactory
.linearScaling(mm, pageLength, NBBINS_POSITION);
//System.out.println(mm + " " + pageLength + " " + NBBINS_POSITION + " " + features.relativePagePositionChar);
int pagePos = featureFactory
.linearScaling(coordinateLineY, pageHeight, NBBINS_POSITION);
//System.out.println(coordinateLineY + " " + pageHeight + " " + NBBINS_POSITION + " " + pagePos);
if (pagePos > NBBINS_POSITION)
pagePos = NBBINS_POSITION;
features.relativePagePosition = pagePos;
//System.out.println(coordinateLineY + "\t" + pageHeight);
if (spacingPreviousBlock != 0.0) {
features.spacingWithPreviousBlock = featureFactory
.linearScaling(spacingPreviousBlock-doc.getMinBlockSpacing(), doc.getMaxBlockSpacing()-doc.getMinBlockSpacing(), NBBINS_SPACE);
}
features.inMainArea = inPageMainArea;
if (density != -1.0) {
features.characterDensity = featureFactory
.linearScaling(density-doc.getMinCharacterDensity(), doc.getMaxCharacterDensity()-doc.getMinCharacterDensity(), NBBINS_DENSITY);
//System.out.println((density-doc.getMinCharacterDensity()) + " " + (doc.getMaxCharacterDensity()-doc.getMinCharacterDensity()) + " " + NBBINS_DENSITY + " " + features.characterDensity);
}
if (previousFeatures != null) {
String vector = previousFeatures.printVector();
fulltext.append(vector);
}
previousFeatures = features;
}
//System.out.println((spacingPreviousBlock-doc.getMinBlockSpacing()) + " " + (doc.getMaxBlockSpacing()-doc.getMinBlockSpacing()) + " " + NBBINS_SPACE + " "
// + featureFactory.linearScaling(spacingPreviousBlock-doc.getMinBlockSpacing(), doc.getMaxBlockSpacing()-doc.getMinBlockSpacing(), NBBINS_SPACE));
// lowest position of the block
lowestPos = block.getY() + block.getHeight();
// update page-level and document-level positions
if (tokens != null) {
mm += tokens.size();
nn += tokens.size();
}
}
}
if (previousFeatures != null)
fulltext.append(previousFeatures.printVector());
return fulltext.toString();
}
/**
* Process the content of the specified pdf and format the result as training data.
*
* @param inputFile input file
* @param pathFullText path to fulltext
* @param pathTEI path to TEI
* @param id id
*/
public void createTrainingSegmentation(String inputFile,
String pathFullText,
String pathTEI,
int id) {
DocumentSource documentSource = null;
try {
File file = new File(inputFile);
//documentSource = DocumentSource.fromPdf(file);
documentSource = DocumentSource.fromPdf(file, -1, -1, true, true, true);
Document doc = new Document(documentSource);
String PDFFileName = file.getName();
doc.addTokenizedDocument(GrobidAnalysisConfig.defaultInstance());
if (doc.getBlocks() == null) {
throw new Exception("PDF parsing resulted in empty content");
}
doc.produceStatistics();
String fulltext = //getAllTextFeatured(doc, false);
getAllLinesFeatured(doc);
List<LayoutToken> tokenizations = doc.getTokenizationsFulltext();
// we write the full text untagged (but featurized)
String outPathFulltext = pathFullText + File.separator +
PDFFileName.replace(".pdf", ".training.segmentation");
Writer writer = new OutputStreamWriter(new FileOutputStream(new File(outPathFulltext), false), "UTF-8");
writer.write(fulltext + "\n");
writer.close();
// also write the raw text as seen before segmentation
StringBuffer rawtxt = new StringBuffer();
for(LayoutToken txtline : tokenizations) {
rawtxt.append(txtline.getText());
}
String outPathRawtext = pathFullText + File.separator +
PDFFileName.replace(".pdf", ".training.segmentation.rawtxt");
FileUtils.writeStringToFile(new File(outPathRawtext), rawtxt.toString(), "UTF-8");
if (isNotBlank(fulltext)) {
String rese = label(fulltext);
StringBuffer bufferFulltext = trainingExtraction(rese, tokenizations, doc);
// write the TEI file to reflect the extact layout of the text as extracted from the pdf
writer = new OutputStreamWriter(new FileOutputStream(new File(pathTEI +
File.separator +
PDFFileName.replace(".pdf", ".training.segmentation.tei.xml")), false), "UTF-8");
writer.write("<?xml version=\"1.0\" ?>\n<tei>\n\t<teiHeader>\n\t\t<fileDesc xml:id=\"" + id +
"\"/>\n\t</teiHeader>\n\t<text xml:lang=\"en\">\n");
writer.write(bufferFulltext.toString());
writer.write("\n\t</text>\n</tei>\n");
writer.close();
}
} catch (Exception e) {
throw new GrobidException("An exception occured while running Grobid training" +
" data generation for segmentation model.", e);
} finally {
DocumentSource.close(documentSource, true, true, true);
}
}
/**
* Get the content of the pdf and produce a blank training data TEI file, i.e. a text only TEI file
* without any tags. This is usefull to start from scratch the creation of training data at the same
* level as the segmentation parser.
*
* @param inputFile input file
* @param pathFullText path to fulltext
* @param pathTEI path to TEI
* @param id id
*/
public void createBlankTrainingData(File file,
String pathFullText,
String pathTEI,
int id) {
DocumentSource documentSource = null;
try {
//File file = new File(inputFile);
//documentSource = DocumentSource.fromPdf(file);
documentSource = DocumentSource.fromPdf(file, -1, -1, true, true, true);
Document doc = new Document(documentSource);
String PDFFileName = file.getName();
doc.addTokenizedDocument(GrobidAnalysisConfig.defaultInstance());
if (doc.getBlocks() == null) {
throw new Exception("PDF parsing resulted in empty content");
}
doc.produceStatistics();
String fulltext = //getAllTextFeatured(doc, false);
getAllLinesFeatured(doc);
List<LayoutToken> tokenizations = doc.getTokenizationsFulltext();
// we write the full text untagged (but featurized)
String outPathFulltext = pathFullText + File.separator +
PDFFileName.replace(".pdf", ".training.blank");
Writer writer = new OutputStreamWriter(new FileOutputStream(new File(outPathFulltext), false), "UTF-8");
writer.write(fulltext + "\n");
writer.close();
// also write the raw text as seen before segmentation
StringBuffer rawtxt = new StringBuffer();
for(LayoutToken txtline : tokenizations) {
rawtxt.append(TextUtilities.HTMLEncode(txtline.getText()));
}
fulltext = rawtxt.toString();
if (isNotBlank(fulltext)) {
// write the TEI file to reflect the extact layout of the text as extracted from the pdf
writer = new OutputStreamWriter(new FileOutputStream(new File(pathTEI +
File.separator +
PDFFileName.replace(".pdf", ".training.blank.tei.xml")), false), "UTF-8");
writer.write("<?xml version=\"1.0\" ?>\n<tei>\n\t<teiHeader>\n\t\t<fileDesc xml:id=\"" + id +
"\"/>\n\t</teiHeader>\n\t<text xml:lang=\"en\">\n");
writer.write(fulltext);
writer.write("\n\t</text>\n</tei>\n");
writer.close();
}
} catch (Exception e) {
throw new GrobidException("An exception occured while running Grobid training" +
" data generation for segmentation model.", e);
} finally {
DocumentSource.close(documentSource, true, true, true);
}
}
/**
* Extract results from a labelled full text in the training format without any string modification.
*
* @param result reult
* @param tokenizations toks
* @return extraction
*/
public StringBuffer trainingExtraction(String result,
List<LayoutToken> tokenizations,
Document doc) {
// this is the main buffer for the whole full text
StringBuffer buffer = new StringBuffer();
try {
List<Block> blocks = doc.getBlocks();
int currentBlockIndex = 0;
int indexLine = 0;
StringTokenizer st = new StringTokenizer(result, "\n");
String s1 = null; // current label/tag
String s2 = null; // current lexical token
String s3 = null; // current second lexical token
String lastTag = null;
// current token position
int p = 0;
boolean start = true;
while (st.hasMoreTokens()) {
boolean addSpace = false;
String tok = st.nextToken().trim();
String line = null; // current line
if (tok.length() == 0) {
continue;
}
StringTokenizer stt = new StringTokenizer(tok, " \t");
List<String> localFeatures = new ArrayList<String>();
int i = 0;
boolean newLine = true;
int ll = stt.countTokens();
while (stt.hasMoreTokens()) {
String s = stt.nextToken().trim();
if (i == 0) {
s2 = TextUtilities.HTMLEncode(s); // lexical token
} else if (i == 1) {
s3 = TextUtilities.HTMLEncode(s); // second lexical token
} else if (i == ll - 1) {
s1 = s; // current label
} else {
localFeatures.add(s); // we keep the feature values in case they appear useful
}
i++;
}
// as we process the document segmentation line by line, we don't use the usual
// tokenization to rebuild the text flow, but we get each line again from the
// text stored in the document blocks (similarly as when generating the features)
line = null;
while ((line == null) && (currentBlockIndex < blocks.size())) {
Block block = blocks.get(currentBlockIndex);
List<LayoutToken> tokens = block.getTokens();
if (tokens == null) {
currentBlockIndex++;
indexLine = 0;
continue;
}
String localText = block.getText();
if ((localText == null) || (localText.trim().length() == 0)) {
currentBlockIndex++;
indexLine = 0;
continue;
}
//String[] lines = localText.split("\n");
String[] lines = localText.split("[\\n\\r]");
if ((lines.length == 0) || (indexLine >= lines.length)) {
currentBlockIndex++;
indexLine = 0;
continue;
} else {
line = lines[indexLine];
indexLine++;
if (line.trim().length() == 0) {
line = null;
continue;
}
if (TextUtilities.filterLine(line)) {
line = null;
continue;
}
}
}
line = TextUtilities.HTMLEncode(line);
if (newLine && !start) {
buffer.append("<lb/>");
}
String lastTag0 = null;
if (lastTag != null) {
if (lastTag.startsWith("I-")) {
lastTag0 = lastTag.substring(2, lastTag.length());
} else {
lastTag0 = lastTag;
}
}
String currentTag0 = null;
if (s1 != null) {
if (s1.startsWith("I-")) {
currentTag0 = s1.substring(2, s1.length());
} else {
currentTag0 = s1;
}
}
//boolean closeParagraph = false;
if (lastTag != null) {
//closeParagraph =
testClosingTag(buffer, currentTag0, lastTag0, s1);
}
boolean output;
output = writeField(buffer, line, s1, lastTag0, s2, "<header>", "<front>", addSpace, 3);
/*if (!output) {
output = writeField(buffer, line, s1, lastTag0, s2, "<other>", "<note type=\"other\">", addSpace, 3);
}*/
if (!output) {
output = writeField(buffer, line, s1, lastTag0, s2, "<headnote>", "<note place=\"headnote\">",
addSpace, 3);
}
if (!output) {
output = writeField(buffer, line, s1, lastTag0, s2, "<footnote>", "<note place=\"footnote\">",
addSpace, 3);
}
if (!output) {
output = writeField(buffer, line, s1, lastTag0, s2, "<marginnote>", "<note place=\"margin\">",
addSpace, 3);
}
if (!output) {
output = writeField(buffer, line, s1, lastTag0, s2, "<page>", "<page>", addSpace, 3);
}
if (!output) {
//output = writeFieldBeginEnd(buffer, s1, lastTag0, s2, "<reference>", "<listBibl>", addSpace, 3);
output = writeField(buffer, line, s1, lastTag0, s2, "<references>", "<listBibl>", addSpace, 3);
}
if (!output) {
//output = writeFieldBeginEnd(buffer, s1, lastTag0, s2, "<body>", "<body>", addSpace, 3);
output = writeField(buffer, line, s1, lastTag0, s2, "<body>", "<body>", addSpace, 3);
}
if (!output) {
output = writeField(buffer, line, s1, lastTag0, s2, "<cover>", "<titlePage>", addSpace, 3);
}
if (!output) {
output = writeField(buffer, line, s1, lastTag0, s2, "<annex>", "<div type=\"annex\">", addSpace, 3);
}
if (!output) {
output = writeField(buffer, line, s1, lastTag0, s2, "<acknowledgement>", "<div type=\"acknowledgement\">", addSpace, 3);
}
/*if (!output) {
if (closeParagraph) {
output = writeField(buffer, s1, "", s2, "<reference_marker>", "<label>", addSpace, 3);
} else
output = writeField(buffer, s1, lastTag0, s2, "<reference_marker>", "<label>", addSpace, 3);
}*/
/*if (!output) {
output = writeField(buffer, s1, lastTag0, s2, "<citation_marker>", "<ref type=\"biblio\">",
addSpace, 3);
}*/
/*if (!output) {
output = writeField(buffer, s1, lastTag0, s2, "<figure_marker>", "<ref type=\"figure\">",
addSpace, 3);
}*/
lastTag = s1;
if (!st.hasMoreTokens()) {
if (lastTag != null) {
testClosingTag(buffer, "", currentTag0, s1);
}
}
if (start) {
start = false;
}
}
return buffer;
} catch (Exception e) {
throw new GrobidException("An exception occured while running Grobid.", e);
}
}
/**
* TODO some documentation...
*
* @param buffer
* @param s1
* @param lastTag0
* @param s2
* @param field
* @param outField
* @param addSpace
* @param nbIndent
* @return
*/
private boolean writeField(StringBuffer buffer,
String line,
String s1,
String lastTag0,
String s2,
String field,
String outField,
boolean addSpace,
int nbIndent) {
boolean result = false;
// filter the output path
if ((s1.equals(field)) || (s1.equals("I-" + field))) {
result = true;
line = line.replace("@BULLET", "\u2022");
// if previous and current tag are the same, we output the token
if (s1.equals(lastTag0) || s1.equals("I-" + lastTag0)) {
buffer.append(line);
}
/*else if (lastTag0 == null) {
for(int i=0; i<nbIndent; i++) {
buffer.append("\t");
}
buffer.append(outField+s2);
}*/
/*else if (field.equals("<citation_marker>")) {
if (addSpace)
buffer.append(" " + outField + s2);
else
buffer.append(outField + s2);
} else if (field.equals("<figure_marker>")) {
if (addSpace)
buffer.append(" " + outField + s2);
else
buffer.append(outField + s2);
} else if (field.equals("<reference_marker>")) {
if (!lastTag0.equals("<references>") && !lastTag0.equals("<reference_marker>")) {
for (int i = 0; i < nbIndent; i++) {
buffer.append("\t");
}
buffer.append("<bibl>");
}
if (addSpace)
buffer.append(" " + outField + s2);
else
buffer.append(outField + s2);
} */
else if (lastTag0 == null) {
// if previous tagname is null, we output the opening xml tag
for (int i = 0; i < nbIndent; i++) {
buffer.append("\t");
}
buffer.append(outField).append(line);
} else if (!lastTag0.equals("<titlePage>")) {
// if the previous tagname is not titlePage, we output the opening xml tag
for (int i = 0; i < nbIndent; i++) {
buffer.append("\t");
}
buffer.append(outField).append(line);
} else {
// otherwise we continue by ouputting the token
buffer.append(line);
}
}
return result;
}
/**
* This is for writing fields for fields where begin and end of field matter, like paragraph or item
*
* @param buffer
* @param s1
* @param lastTag0
* @param s2
* @param field
* @param outField
* @param addSpace
* @param nbIndent
* @return
*/
/*private boolean writeFieldBeginEnd(StringBuffer buffer,
String s1,
String lastTag0,
String s2,
String field,
String outField,
boolean addSpace,
int nbIndent) {
boolean result = false;
if ((s1.equals(field)) || (s1.equals("I-" + field))) {
result = true;
if (lastTag0.equals("I-" + field)) {
if (addSpace)
buffer.append(" " + s2);
else
buffer.append(s2);
} /*else if (lastTag0.equals(field) && s1.equals(field)) {
if (addSpace)
buffer.append(" " + s2);
else
buffer.append(s2);
} else if (!lastTag0.equals("<citation_marker>") && !lastTag0.equals("<figure_marker>")
&& !lastTag0.equals("<figure>") && !lastTag0.equals("<reference_marker>")) {
for (int i = 0; i < nbIndent; i++) {
buffer.append("\t");
}
buffer.append(outField + s2);
}
else {
if (addSpace)
buffer.append(" " + s2);
else
buffer.append(s2);
}
}
return result;
}*/
/**
* TODO some documentation
*
* @param buffer
* @param currentTag0
* @param lastTag0
* @param currentTag
* @return
*/
private boolean testClosingTag(StringBuffer buffer,
String currentTag0,
String lastTag0,
String currentTag) {
boolean res = false;
// reference_marker and citation_marker are two exceptions because they can be embedded
if (!currentTag0.equals(lastTag0)) {
/*if (currentTag0.equals("<citation_marker>") || currentTag0.equals("<figure_marker>")) {
return res;
}*/
res = false;
// we close the current tag
if (lastTag0.equals("<header>")) {
buffer.append("</front>\n\n");
} else if (lastTag0.equals("<body>")) {
buffer.append("</body>\n\n");
} else if (lastTag0.equals("<headnote>")) {
buffer.append("</note>\n\n");
} else if (lastTag0.equals("<footnote>")) {
buffer.append("</note>\n\n");
} else if (lastTag0.equals("<marginnote>")) {
buffer.append("</note>\n\n");
} else if (lastTag0.equals("<references>")) {
buffer.append("</listBibl>\n\n");
res = true;
} else if (lastTag0.equals("<page>")) {
buffer.append("</page>\n\n");
} else if (lastTag0.equals("<cover>")) {
buffer.append("</titlePage>\n\n");
} else if (lastTag0.equals("<annex>")) {
buffer.append("</div>\n\n");
} else if (lastTag0.equals("<acknowledgement>")) {
buffer.append("</div>\n\n");
} else {
res = false;
}
}
return res;
}
@Override
public void close() throws IOException {
super.close();
// ...
}
}
| apache-2.0 |
arnelandwehr/killbill-adyen-plugin | src/test/java/org/killbill/billing/plugin/adyen/recurring/RecurringPortRegistry.java | 842 | /*
* Copyright 2015 Groupon, Inc
*
* Groupon 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.killbill.billing.plugin.adyen.recurring;
import org.killbill.adyen.recurring.RecurringPortType;
public interface RecurringPortRegistry {
RecurringPortType getRecurringPort(String countryIsoCode);
}
| apache-2.0 |
google-ar/sceneform-android-sdk | sceneformsrc/sceneform/src/main/java/com/google/ar/sceneform/rendering/ViewRenderableHelpers.java | 899 | package com.google.ar.sceneform.rendering;
import android.content.res.Resources;
import android.util.DisplayMetrics;
import android.view.View;
/** Helper class for utility functions for a view rendered in world space. */
class ViewRenderableHelpers {
/** Returns the aspect ratio of a view (width / height). */
static float getAspectRatio(View view) {
float viewWidth = (float) view.getWidth();
float viewHeight = (float) view.getHeight();
if (viewWidth == 0.0f || viewHeight == 0.0f) {
return 0.0f;
}
return viewWidth / viewHeight;
}
/**
* Returns the number of density independent pixels that a given number of pixels is equal to on
* this device.
*/
static float convertPxToDp(int px) {
DisplayMetrics displayMetrics = Resources.getSystem().getDisplayMetrics();
return px / (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT);
}
}
| apache-2.0 |
blockaystudio/com | libgdx-cookbook-master/samples/core/src/com/cookbook/samples/MainMenuSample.java | 5920 | package com.cookbook.samples;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.InputListener;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Image;
import com.badlogic.gdx.scenes.scene2d.ui.Slider;
import com.badlogic.gdx.scenes.scene2d.ui.Table;
import com.badlogic.gdx.scenes.scene2d.ui.TextButton;
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener;
import com.badlogic.gdx.scenes.scene2d.utils.TextureRegionDrawable;
import com.badlogic.gdx.utils.viewport.FitViewport;
import com.badlogic.gdx.utils.viewport.Viewport;
import static com.badlogic.gdx.scenes.scene2d.actions.Actions.*;
public class MainMenuSample extends GdxSample {
private static final String TAG = "BasicMenuSample";
private static final int VIRTUAL_WIDTH = 1280;
private static final int VIRTUAL_HEIGHT = 720;
private Viewport viewport;
private Image gameTitle, hamsty1, hamsty2;
private TextButton btnPlay, btnSettings, btnExit;
private Slider slider;
private BitmapFont font;
private Table table;
private Stage stage;
private Texture gameTitleTex, hamsty1Tex, hamsty2Tex, buttonUpTex,
buttonDownTex, buttonOverTex, sliderBackgroundTex, sliderKnobTex;
@Override
public void create () {
super.create();
viewport = new FitViewport(VIRTUAL_WIDTH, VIRTUAL_HEIGHT);
stage = new Stage(viewport);
Gdx.input.setInputProcessor(stage);
font = new BitmapFont(Gdx.files.internal("data/font.fnt"));
// Title Image
gameTitleTex = new Texture(Gdx.files.internal("data/scene2d/gameTitle.png"));
gameTitle = new Image(new TextureRegionDrawable(new TextureRegion(gameTitleTex)));
// Hamster Image
hamsty1Tex = new Texture(Gdx.files.internal("data/scene2d/hamsty.png"));
hamsty2Tex = new Texture(Gdx.files.internal("data/scene2d/hamsty2.png"));
hamsty1 = new Image(new TextureRegionDrawable(new TextureRegion(hamsty1Tex)));
hamsty2 = new Image(new TextureRegionDrawable(new TextureRegion(hamsty2Tex)));
// Set buttons' style
buttonUpTex = new Texture(Gdx.files.internal("data/scene2d/myactor.png"));
buttonOverTex = new Texture(Gdx.files.internal("data/scene2d/myactorOver.png"));
buttonDownTex = new Texture(Gdx.files.internal("data/scene2d/myactorDown.png"));
TextButton.TextButtonStyle tbs = new TextButton.TextButtonStyle();
tbs.font = font;
tbs.up = new TextureRegionDrawable(new TextureRegion(buttonUpTex));
tbs.over = new TextureRegionDrawable(new TextureRegion(buttonOverTex));
tbs.down = new TextureRegionDrawable(new TextureRegion(buttonDownTex));
//Define buttons
btnPlay = new TextButton("PLAY", tbs);
btnSettings = new TextButton("SETTINGS", tbs);
btnExit = new TextButton("EXIT", tbs);
//Slider
sliderBackgroundTex =new Texture(Gdx.files.internal("data/scene2d/slider_background.png"));
sliderKnobTex = new Texture(Gdx.files.internal("data/scene2d/slider_knob.png"));
Slider.SliderStyle ss = new Slider.SliderStyle();
ss.background = new TextureRegionDrawable(new TextureRegion(sliderBackgroundTex));
ss.knob = new TextureRegionDrawable(new TextureRegion(sliderKnobTex));
slider = new Slider(0f, 100f, 1f, false, ss);
// Create table
table = new Table();
table.debug(); //Enables debug
// Set table structure
table.row();
table.add(gameTitle).padTop(30f).colspan(2).expand();
table.row();
table.add(hamsty1).padTop(10f).expandY().uniform();
table.add(hamsty2).padTop(10f).expandY().uniform();
table.row();
table.add(btnPlay).padTop(10f).colspan(2);
table.row();
table.add(btnSettings).padTop(10f).colspan(2);
table.row();
table.add(btnExit).padTop(10f).colspan(2);
table.row();
table.add(slider).bottom().colspan(2).expandY();
table.padBottom(30f);
// Pack table
table.setFillParent(true);
table.pack();
// Set table's alpha to 0
table.getColor().a = 0f;
// Play button listener
btnPlay.addListener( new ClickListener() {
@Override
public void clicked(InputEvent event, float x, float y) {
Gdx.app.log(TAG, "PLAY");
};
});
// Settings button listener
btnSettings.addListener( new ClickListener() {
@Override
public void clicked(InputEvent event, float x, float y) {
Gdx.app.log(TAG, "SETTINGS");
};
});
// Exit button listener
btnExit.addListener( new ClickListener() {
@Override
public void clicked(InputEvent event, float x, float y) {
Gdx.app.log(TAG, "EXIT");
Gdx.app.exit();
};
});
// Slider listener
slider.addListener(new InputListener() {
@Override
public void touchUp(InputEvent event, float x, float y, int pointer, int button) {
Gdx.app.log(TAG, "slider changed to: " + slider.getValue());
// Set volume to slider.getValue();
}
@Override
public boolean touchDown (InputEvent event, float x, float y, int pointer, int button) {
return true;
};
});
// Adds created table to stage
stage.addActor(table);
// To make the table appear smoothly
table.addAction(fadeIn(2f));
}
@Override
public void resize(int width, int height) {
viewport.update(width, height);
}
@Override
public void dispose() {
gameTitleTex.dispose();
hamsty1Tex.dispose();
hamsty2Tex.dispose();
buttonUpTex.dispose();
buttonDownTex.dispose();
buttonOverTex.dispose();
sliderBackgroundTex.dispose();
sliderKnobTex.dispose();
font.dispose();
stage.dispose();
}
@Override
public void render () {
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
stage.act(Math.min(Gdx.graphics.getDeltaTime(), 1 / 60f));
stage.draw();
}
}
| artistic-2.0 |
jpaulm/javafbp | src/main/java/com/jpaulmorrison/fbp/core/components/text/LineToWords.java | 2256 | /*
* JavaFBP - A Java Implementation of Flow-Based Programming (FBP)
* Copyright (C) 2009, 2016 J. Paul Morrison
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 3.0 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, see the GNU Library General Public License v3
* at https://www.gnu.org/licenses/lgpl-3.0.en.html for more details.
*/
package com.jpaulmorrison.fbp.core.components.text;
import com.jpaulmorrison.fbp.core.engine.Component;
import com.jpaulmorrison.fbp.core.engine.ComponentDescription;
import com.jpaulmorrison.fbp.core.engine.InPort;
import com.jpaulmorrison.fbp.core.engine.InPorts;
import com.jpaulmorrison.fbp.core.engine.InputPort;
import com.jpaulmorrison.fbp.core.engine.OutPort;
import com.jpaulmorrison.fbp.core.engine.OutPorts;
import com.jpaulmorrison.fbp.core.engine.OutputPort;
import com.jpaulmorrison.fbp.core.engine.Packet;
/**
* Provide words from a stream of space-separated records - essentially same as routing.DeCompose
* Bob Corrick December 2011
*/
@ComponentDescription("Take space-separated words in a record IN and deliver individual words OUT")
@OutPorts({ @OutPort(value = "OUT") })
@InPorts({ @InPort("IN") })
public class LineToWords extends Component {
private InputPort inport;
private OutputPort outport;
@Override
protected void execute() {
Packet pIn;
while ((pIn = inport.receive()) != null) {
String w = (String) pIn.getContent();
drop(pIn);
// Get words for this record
String[] words = w.split(" ");
// Send words as individual packets
for (String word : words) {
Packet pOut = create(word);
outport.send(pOut);
}
}
}
@Override
protected void openPorts() {
inport = openInput("IN");
outport = openOutput("OUT");
}
}
| artistic-2.0 |
tokuhirom/nqp | src/vm/jvm/runtime/org/perl6/nqp/jast2bc/AutosplitMethodWriter.java | 73557 | package org.perl6.nqp.jast2bc;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.Handle;
import org.objectweb.asm.Label;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import org.objectweb.asm.tree.AbstractInsnNode;
import org.objectweb.asm.tree.FieldInsnNode;
import org.objectweb.asm.tree.IincInsnNode;
import org.objectweb.asm.tree.InsnList;
import org.objectweb.asm.tree.InsnNode;
import org.objectweb.asm.tree.IntInsnNode;
import org.objectweb.asm.tree.InvokeDynamicInsnNode;
import org.objectweb.asm.tree.JumpInsnNode;
import org.objectweb.asm.tree.LabelNode;
import org.objectweb.asm.tree.LdcInsnNode;
import org.objectweb.asm.tree.LineNumberNode;
import org.objectweb.asm.tree.LookupSwitchInsnNode;
import org.objectweb.asm.tree.MethodInsnNode;
import org.objectweb.asm.tree.MethodNode;
import org.objectweb.asm.tree.MultiANewArrayInsnNode;
import org.objectweb.asm.tree.TableSwitchInsnNode;
import org.objectweb.asm.tree.TryCatchBlockNode;
import org.objectweb.asm.tree.TypeInsnNode;
import org.objectweb.asm.tree.VarInsnNode;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
@SuppressWarnings("unchecked") /* our asm is stripped */
class AutosplitMethodWriter extends MethodNode {
/** Maximum size of a method to leave alone. */
private static final int MAX_UNSPLIT_METHOD = 65535;
private static final int MAX_FRAGMENT = 65535;
private static final int MAX_SWITCH = 256;
/** True to dump control flow analysis. */
private static final boolean DEBUG_CONTROL = false;
private static final boolean DEBUG_FRAGMENT = false;
private static final boolean TYPE_TRACE = false;
/** The real instructions (not branches) in program order. Filled out by {@link getControlFlow()}. */
private AbstractInsnNode[] insnList;
private Map<AbstractInsnNode, Integer> insnMap;
private int[] lineNumbers;
/** Array of (source, target) pairs. Filled out by {@link getControlFlow()}. -1 means from-outside. */
private ControlEdge[] controlEdges;
private ControlEdge[][] successors;
private int[] depth;
private int[] baselineSize;
private Frame[] types;
private int nextJumpNo;
private int[] jumpNoMap;
private List<Integer> firstJump = new ArrayList< >();
private static class ControlEdge {
public final int from, to;
public final String exn; // if non-null, replace the stack with this
public ControlEdge(int f, int t, String e) { from = f; to = t; exn = e; }
}
private int nstack, nlocal;
private final ClassVisitor target;
private final String tgtype;
public AutosplitMethodWriter(ClassVisitor target, String tgtype, int access, String name, String desc, String sig, String[] exn) {
super(Opcodes.ASM4, access, name, desc, sig, exn);
this.target = target;
this.tgtype = tgtype;
}
@Override
public void visitEnd() {
super.visitEnd();
int maxsize = 0;
for (AbstractInsnNode ai = instructions.getFirst(); ai != null; ai = ai.getNext())
maxsize += insnSize(ai);
if (maxsize <= MAX_UNSPLIT_METHOD) {
// hey cool, we don't need to do anything fancy here
MethodVisitor mw = target.visitMethod(access, name, desc, signature, ((List<String>)exceptions).toArray(new String[0]));
accept(mw);
return;
}
/* we need to split this thing */
if (DEBUG_FRAGMENT) System.out.printf("method=%s max=%d\n", name, maxsize);
splitSwitches();
getInstructions();
getControlFlow();
if (DEBUG_CONTROL) printControlFlow();
getTypes();
getBaselineSize();
if (DEBUG_CONTROL) {
for (int i = 1; i <= insnList.length; i++)
System.out.printf("from=%d to=%d frag=%d\n", 0,i,calcFragmentSize(0, i));
}
jumpNoMap = new int[insnList.length];
Arrays.fill(jumpNoMap, -1);
List<Integer> fragmentSizes = new ArrayList< >();
int taken = 0;
while (taken < insnList.length) {
if (calcFragmentSize(taken, taken+1) > MAX_FRAGMENT)
throw new RuntimeException("cannot take even one more instruction at "+taken);
int takeable = bite(taken, 1, insnList.length - taken);
if (DEBUG_FRAGMENT) System.out.printf("fragment: %d - %d (max %d bytes)\n", taken, taken + takeable - 1, calcFragmentSize(taken, taken+takeable));
fragmentSizes.add(takeable);
allocateJumpNrs(taken, taken+takeable);
taken += takeable;
}
taken = 0;
int fno = 0;
for (int sz : fragmentSizes) {
emitFragment(fno++, taken, taken+sz);
taken += sz;
}
becomeWrapper();
accept(target);
}
private int bite(int from, int min_take, int max_take) { /* min_take is known good */
while (true) {
if (min_take == max_take) return min_take;
int mid_take = (min_take + max_take + 1) / 2;
if (calcFragmentSize(from, from+mid_take) <= MAX_FRAGMENT) {
min_take = mid_take;
} else {
max_take = mid_take-1;
}
}
}
private boolean isRealInsn(AbstractInsnNode node) {
switch (node.getType()) {
case AbstractInsnNode.LINE:
case AbstractInsnNode.LABEL:
case AbstractInsnNode.FRAME:
return false;
default:
return true;
}
}
/** Break apart large switch instructions so that they may fit in a fragment. Runs before {@link getInstructions} because it changes instruction sequence. */
private void splitSwitches() {
AbstractInsnNode ptr = instructions.getFirst();
while (ptr != null) {
int cutoff = 0;
AbstractInsnNode left = null, right = null;
switch (ptr.getType()) {
case AbstractInsnNode.LOOKUPSWITCH_INSN:
{
LookupSwitchInsnNode lsi = (LookupSwitchInsnNode) ptr;
if (lsi.labels.size() <= MAX_SWITCH) break;
LookupSwitchInsnNode lsl = new LookupSwitchInsnNode(lsi.dflt, new int[0], new LabelNode[0]);
LookupSwitchInsnNode lsr = new LookupSwitchInsnNode(lsi.dflt, new int[0], new LabelNode[0]);
int lsisz = lsi.labels.size();
lsl.keys.addAll(lsi.keys.subList(0, lsisz / 2));
lsr.keys.addAll(lsi.keys.subList(lsisz / 2, lsisz));
lsl.labels.addAll(lsi.labels.subList(0, lsisz / 2));
lsr.labels.addAll(lsi.labels.subList(lsisz / 2, lsisz));
left = lsl;
right = lsr;
cutoff = (Integer)lsr.keys.get(0);
}
break;
case AbstractInsnNode.TABLESWITCH_INSN:
{
TableSwitchInsnNode lsi = (TableSwitchInsnNode) ptr;
if (lsi.labels.size() <= MAX_SWITCH) break;
cutoff = (lsi.min + lsi.max) / 2;
TableSwitchInsnNode lsl = new TableSwitchInsnNode(lsi.min, cutoff-1, lsi.dflt);
TableSwitchInsnNode lsr = new TableSwitchInsnNode(cutoff, lsi.max, lsi.dflt);
int lsisz = lsi.labels.size();
lsl.labels.addAll(lsi.labels.subList(0, cutoff - lsi.min));
lsr.labels.addAll(lsi.labels.subList(cutoff - lsi.min, lsi.max + 1 - lsi.min));
left = lsl;
right = lsr;
}
break;
default: break;
}
if (left != null) {
if (DEBUG_FRAGMENT) System.out.printf("Breaking switch at %d\n", cutoff);
LabelNode high = new LabelNode();
instructions.insertBefore(ptr, new InsnNode(Opcodes.DUP));
instructions.insertBefore(ptr, intNode(cutoff));
instructions.insertBefore(ptr, new JumpInsnNode(Opcodes.IF_ICMPGE, high));
instructions.insertBefore(ptr, left);
instructions.insertBefore(ptr, high);
instructions.insertBefore(ptr, right);
instructions.remove(ptr);
ptr = left;
} else {
ptr = ptr.getNext();
}
}
}
private AbstractInsnNode intNode(int value) {
return (value >= -1 && value <= 5) ? new InsnNode(Opcodes.ICONST_0 + value) :
(value >= -128 && value <= 127) ? new IntInsnNode(Opcodes.BIPUSH, value) :
(value >= -32768 && value <= 32767) ? new IntInsnNode(Opcodes.SIPUSH, value) :
new LdcInsnNode(value);
}
/** Extract the real instructions from the instruction list. */
private void getInstructions() {
// munge the linked list of insns we got from ASM into something saner
ArrayList<AbstractInsnNode> tempInsnList = new ArrayList< >();
insnMap = new HashMap< >();
HashMap<AbstractInsnNode, Integer> linesMap = new HashMap< >();
for (AbstractInsnNode n = instructions.getFirst(); n != null; n = n.getNext()) {
insnMap.put(n, tempInsnList.size());
if (isRealInsn(n)) tempInsnList.add(n);
if (n.getType() == AbstractInsnNode.LINE) {
LineNumberNode nn = (LineNumberNode) n;
AbstractInsnNode start = nn.start;
while (start != null && !isRealInsn(start)) start = start.getNext();
linesMap.put(start, nn.line);
}
}
insnList = tempInsnList.toArray(new AbstractInsnNode[0]);
int curLine = 0;
lineNumbers = new int[insnList.length];
for (int i = 0; i < insnList.length; i++) {
Integer ll = linesMap.get(insnList[i]);
if (ll != null) curLine = ll.intValue();
lineNumbers[i] = curLine;
}
}
/** Build the control flow graph. */
private void getControlFlow() {
List<ControlEdge> controlTemp = new ArrayList< >();
List<ControlEdge>[] succTemps = new List[insnList.length];
successors = new ControlEdge[insnList.length][];
for (int insnNo = 0; insnNo < insnList.length; insnNo++) {
AbstractInsnNode node = insnList[insnNo];
List<ControlEdge> succTemp = new ArrayList< >();
succTemps[insnNo] = succTemp;
switch (node.getType()) {
case AbstractInsnNode.JUMP_INSN:
JumpInsnNode ji = (JumpInsnNode) node;
succTemp.add(new ControlEdge(insnNo, insnMap.get(ji.label), null));
if (node.getOpcode() != Opcodes.GOTO)
succTemp.add(new ControlEdge(insnNo, insnNo+1, null));
break;
case AbstractInsnNode.TABLESWITCH_INSN:
TableSwitchInsnNode tsi = (TableSwitchInsnNode) node;
succTemp.add(new ControlEdge(insnNo, insnMap.get(tsi.dflt), null));
for (int i = 0; i < tsi.labels.size(); i++)
succTemp.add(new ControlEdge(insnNo, insnMap.get(tsi.labels.get(i)), null));
break;
case AbstractInsnNode.LOOKUPSWITCH_INSN:
LookupSwitchInsnNode lsi = (LookupSwitchInsnNode) node;
succTemp.add(new ControlEdge(insnNo, insnMap.get(lsi.dflt), null));
for (int i = 0; i < lsi.labels.size(); i++)
succTemp.add(new ControlEdge(insnNo, insnMap.get(lsi.labels.get(i)), null));
break;
default:
int opcode = node.getOpcode();
if (! (opcode == Opcodes.ATHROW || opcode >= Opcodes.IRETURN && opcode <= Opcodes.RETURN))
succTemp.add(new ControlEdge(insnNo, insnNo+1, null));
break;
}
}
for (TryCatchBlockNode tcb : (List<TryCatchBlockNode>) tryCatchBlocks) {
int start = insnMap.get(tcb.start);
int end = insnMap.get(tcb.end);
int handler = insnMap.get(tcb.handler);
String type = tcb.type == null ? "java/lang/Throwable" : tcb.type;
for (int i = start; i < end; i++)
succTemps[i].add(new ControlEdge(i, handler, type));
}
for (int insnNo = 0; insnNo < insnList.length; insnNo++) {
successors[insnNo] = succTemps[insnNo].toArray(new ControlEdge[0]);
controlTemp.addAll(succTemps[insnNo]);
}
controlEdges = controlTemp.toArray(new ControlEdge[0]);
}
private static class StackEffect {
public final String[] pop;
public final String[] push;
public StackEffect(String... ops) {
int nul = 0;
while (!ops[nul].isEmpty()) nul++;
this.pop = Arrays.copyOfRange(ops, 0, nul);
this.push = Arrays.copyOfRange(ops, nul+1, ops.length);
}
}
private static final StackEffect[] simpleEffects;
static {
simpleEffects = new StackEffect[256];
simpleEffects[Opcodes.AASTORE] = new StackEffect("L", "I", "L", "");
simpleEffects[Opcodes.ACONST_NULL] = new StackEffect("", "0");
simpleEffects[Opcodes.ARETURN] = new StackEffect("");
simpleEffects[Opcodes.ARRAYLENGTH] = new StackEffect("L", "", "I");
simpleEffects[Opcodes.ATHROW] = new StackEffect("");
simpleEffects[Opcodes.BALOAD] = new StackEffect("L", "I", "", "I");
simpleEffects[Opcodes.BASTORE] = new StackEffect("L", "I", "I", "");
simpleEffects[Opcodes.BIPUSH] = new StackEffect("", "I");
simpleEffects[Opcodes.CALOAD] = new StackEffect("[C", "I", "", "I");
simpleEffects[Opcodes.CASTORE] = new StackEffect("[C", "I", "I", "");
simpleEffects[Opcodes.D2F] = new StackEffect("D", "", "F");
simpleEffects[Opcodes.D2I] = new StackEffect("D", "", "I");
simpleEffects[Opcodes.D2L] = new StackEffect("D", "", "J");
simpleEffects[Opcodes.DADD] = new StackEffect("D", "D", "", "D");
simpleEffects[Opcodes.DALOAD] = new StackEffect("[D", "I", "", "D");
simpleEffects[Opcodes.DASTORE] = new StackEffect("[D", "I", "D", "");
simpleEffects[Opcodes.DCMPG] = new StackEffect("D", "D", "", "I");
simpleEffects[Opcodes.DCMPL] = new StackEffect("D", "D", "", "I");
simpleEffects[Opcodes.DCONST_0] = new StackEffect("", "D");
simpleEffects[Opcodes.DCONST_1] = new StackEffect("", "D");
simpleEffects[Opcodes.DDIV] = new StackEffect("D", "D", "", "D");
simpleEffects[Opcodes.DLOAD] = new StackEffect("", "D");
simpleEffects[Opcodes.DMUL] = new StackEffect("D", "D", "", "D");
simpleEffects[Opcodes.DNEG] = new StackEffect("D", "", "D");
simpleEffects[Opcodes.DREM] = new StackEffect("D", "D", "", "D");
simpleEffects[Opcodes.DRETURN] = new StackEffect("");
simpleEffects[Opcodes.DSUB] = new StackEffect("D", "D", "", "D");
simpleEffects[Opcodes.F2D] = new StackEffect("F", "", "D");
simpleEffects[Opcodes.F2I] = new StackEffect("F", "", "I");
simpleEffects[Opcodes.F2L] = new StackEffect("F", "", "J");
simpleEffects[Opcodes.FADD] = new StackEffect("F", "F", "", "F");
simpleEffects[Opcodes.FALOAD] = new StackEffect("[F", "I", "", "F");
simpleEffects[Opcodes.FASTORE] = new StackEffect("[F", "I", "F", "");
simpleEffects[Opcodes.FCMPG] = new StackEffect("F", "F", "", "I");
simpleEffects[Opcodes.FCMPL] = new StackEffect("F", "F", "", "I");
simpleEffects[Opcodes.FCONST_0] = new StackEffect("", "F");
simpleEffects[Opcodes.FCONST_1] = new StackEffect("", "F");
simpleEffects[Opcodes.FCONST_2] = new StackEffect("", "F");
simpleEffects[Opcodes.FDIV] = new StackEffect("F", "F", "", "F");
simpleEffects[Opcodes.FLOAD] = new StackEffect("", "F");
simpleEffects[Opcodes.FMUL] = new StackEffect("F", "F", "", "F");
simpleEffects[Opcodes.FNEG] = new StackEffect("F", "", "F");
simpleEffects[Opcodes.FREM] = new StackEffect("F", "F", "", "F");
simpleEffects[Opcodes.FRETURN] = new StackEffect("");
simpleEffects[Opcodes.FSUB] = new StackEffect("F", "F", "", "F");
simpleEffects[Opcodes.GOTO] = new StackEffect("");
simpleEffects[Opcodes.I2B] = new StackEffect("I", "", "I");
simpleEffects[Opcodes.I2C] = new StackEffect("I", "", "I");
simpleEffects[Opcodes.I2D] = new StackEffect("I", "", "D");
simpleEffects[Opcodes.I2F] = new StackEffect("I", "", "F");
simpleEffects[Opcodes.I2L] = new StackEffect("I", "", "J");
simpleEffects[Opcodes.I2S] = new StackEffect("I", "", "I");
simpleEffects[Opcodes.IADD] = new StackEffect("I", "I", "", "I");
simpleEffects[Opcodes.IALOAD] = new StackEffect("[I", "I", "", "I");
simpleEffects[Opcodes.IAND] = new StackEffect("I", "I", "", "I");
simpleEffects[Opcodes.IASTORE] = new StackEffect("[I", "I", "I", "");
simpleEffects[Opcodes.ICONST_0] = new StackEffect("", "I");
simpleEffects[Opcodes.ICONST_1] = new StackEffect("", "I");
simpleEffects[Opcodes.ICONST_2] = new StackEffect("", "I");
simpleEffects[Opcodes.ICONST_3] = new StackEffect("", "I");
simpleEffects[Opcodes.ICONST_4] = new StackEffect("", "I");
simpleEffects[Opcodes.ICONST_5] = new StackEffect("", "I");
simpleEffects[Opcodes.ICONST_M1] = new StackEffect("", "I");
simpleEffects[Opcodes.IDIV] = new StackEffect("I", "I", "", "I");
simpleEffects[Opcodes.IFEQ] = new StackEffect("I", "");
simpleEffects[Opcodes.IFGE] = new StackEffect("I", "");
simpleEffects[Opcodes.IFGT] = new StackEffect("I", "");
simpleEffects[Opcodes.IFLE] = new StackEffect("I", "");
simpleEffects[Opcodes.IFLT] = new StackEffect("I", "");
simpleEffects[Opcodes.IFNE] = new StackEffect("I", "");
simpleEffects[Opcodes.IFNONNULL] = new StackEffect("L", "");
simpleEffects[Opcodes.IFNULL] = new StackEffect("L", "");
simpleEffects[Opcodes.IF_ACMPEQ] = new StackEffect("I", "I", "");
simpleEffects[Opcodes.IF_ACMPNE] = new StackEffect("I", "I", "");
simpleEffects[Opcodes.IF_ICMPEQ] = new StackEffect("I", "I", "");
simpleEffects[Opcodes.IF_ICMPGE] = new StackEffect("I", "I", "");
simpleEffects[Opcodes.IF_ICMPGT] = new StackEffect("I", "I", "");
simpleEffects[Opcodes.IF_ICMPLE] = new StackEffect("I", "I", "");
simpleEffects[Opcodes.IF_ICMPLT] = new StackEffect("I", "I", "");
simpleEffects[Opcodes.IF_ICMPNE] = new StackEffect("I", "I", "");
simpleEffects[Opcodes.IINC] = new StackEffect("");
simpleEffects[Opcodes.ILOAD] = new StackEffect("", "I");
simpleEffects[Opcodes.IMUL] = new StackEffect("I", "I", "", "I");
simpleEffects[Opcodes.INEG] = new StackEffect("I", "", "I");
simpleEffects[Opcodes.INSTANCEOF] = new StackEffect("L", "", "I");
simpleEffects[Opcodes.IOR] = new StackEffect("I", "I", "", "I");
simpleEffects[Opcodes.IREM] = new StackEffect("I", "I", "", "I");
simpleEffects[Opcodes.IRETURN] = new StackEffect("");
simpleEffects[Opcodes.ISHL] = new StackEffect("I", "I", "", "I");
simpleEffects[Opcodes.ISHR] = new StackEffect("I", "I", "", "I");
simpleEffects[Opcodes.ISUB] = new StackEffect("I", "I", "", "I");
simpleEffects[Opcodes.IUSHR] = new StackEffect("I", "I", "", "I");
simpleEffects[Opcodes.IXOR] = new StackEffect("I", "I", "", "I");
simpleEffects[Opcodes.L2D] = new StackEffect("J", "", "D");
simpleEffects[Opcodes.L2F] = new StackEffect("J", "", "F");
simpleEffects[Opcodes.L2I] = new StackEffect("J", "", "I");
simpleEffects[Opcodes.LADD] = new StackEffect("J", "J", "", "J");
simpleEffects[Opcodes.LALOAD] = new StackEffect("[J", "I", "", "J");
simpleEffects[Opcodes.LAND] = new StackEffect("J", "J", "", "J");
simpleEffects[Opcodes.LASTORE] = new StackEffect("[J", "I", "J", "");
simpleEffects[Opcodes.LCMP] = new StackEffect("J", "J", "", "I");
simpleEffects[Opcodes.LCONST_0] = new StackEffect("", "J");
simpleEffects[Opcodes.LCONST_1] = new StackEffect("", "J");
simpleEffects[Opcodes.LDIV] = new StackEffect("J", "J", "", "J");
simpleEffects[Opcodes.LLOAD] = new StackEffect("", "J");
simpleEffects[Opcodes.LMUL] = new StackEffect("J", "J", "", "J");
simpleEffects[Opcodes.LNEG] = new StackEffect("J", "", "J");
simpleEffects[Opcodes.LOOKUPSWITCH] = new StackEffect("I", "");
simpleEffects[Opcodes.LOR] = new StackEffect("J", "J", "", "J");
simpleEffects[Opcodes.LREM] = new StackEffect("J", "J", "", "J");
simpleEffects[Opcodes.LRETURN] = new StackEffect("");
simpleEffects[Opcodes.LSHL] = new StackEffect("J", "I", "", "J");
simpleEffects[Opcodes.LSHR] = new StackEffect("J", "I", "", "J");
simpleEffects[Opcodes.LSUB] = new StackEffect("J", "J", "", "J");
simpleEffects[Opcodes.LUSHR] = new StackEffect("J", "I", "", "J");
simpleEffects[Opcodes.LXOR] = new StackEffect("J", "J", "", "J");
simpleEffects[Opcodes.MONITORENTER] = new StackEffect("L", "");
simpleEffects[Opcodes.MONITOREXIT] = new StackEffect("L", "");
simpleEffects[Opcodes.NOP] = new StackEffect("");
simpleEffects[Opcodes.PUTFIELD] = new StackEffect("X", "");
simpleEffects[Opcodes.PUTSTATIC] = new StackEffect("X", "X", "");
simpleEffects[Opcodes.RETURN] = new StackEffect("");
simpleEffects[Opcodes.SALOAD] = new StackEffect("[S", "I", "", "I");
simpleEffects[Opcodes.SASTORE] = new StackEffect("[S", "I", "I", "");
simpleEffects[Opcodes.SIPUSH] = new StackEffect("", "I");
simpleEffects[Opcodes.TABLESWITCH] = new StackEffect("I", "");
}
private void printControlFlow() {
for (int i = 0; i < insnList.length; i++) {
System.out.printf("%5d: %s\n", i, insnList[i]);
for (ControlEdge ce : successors[i])
System.out.printf(" %5d -> %d %s\n", ce.from, ce.to, ce.exn == null ? "-" : ce.exn);
}
}
/** Infer types. */
private static class Frame {
public String[] stack;
public int sp;
public int sbase;
public Frame(String[] stack, int sp, int sbase) {
this.stack = stack.clone(); this.sp = sp; this.sbase = sbase;
}
public Frame clone() {
return new Frame(stack, sp, sbase);
}
public void grow(int len) {
if (len <= stack.length) return;
int olen = stack.length;
stack = Arrays.copyOf(stack, len);
Arrays.fill(stack, olen, len, "T");
}
public String describe() {
return String.format("locals=[%s] stack=[%s]", Arrays.toString(Arrays.copyOfRange(stack, 0, sbase)), Arrays.toString(Arrays.copyOfRange(stack, sbase, sp)));
}
public void thrown(String ex) {
sp = sbase;
stack[sp++] = ('L'+ex+';').intern();
}
private void pushReturn(String s) {
switch (s.charAt(0)) {
case 'V': break;
case 'B': case 'Z': case 'S': case 'C': stack[sp++] = "I"; break;
default: stack[sp++] = s; break;
}
}
public void execute(int index, AbstractInsnNode anode) {
StackEffect simp = simpleEffects[anode.getOpcode()];
if (stack.length < sp + 5) grow(sp+8);// room for all fixed effects and a bit to spare
if (simp != null) {
sp -= simp.pop.length;
if (sp < sbase) throw new RuntimeException("stack underflow");
if (stack.length < sp + simp.push.length)
stack = Arrays.copyOf(stack, sp + simp.push.length);
for (String s : simp.push)
stack[sp++] = s;
return;
}
VarInsnNode vi = null;
TypeInsnNode ti = null;
FieldInsnNode fi = null;
String tidesc = null;
MethodInsnNode mi = null;
Type midesc = null;
switch (anode.getType()) {
case AbstractInsnNode.VAR_INSN:
vi = (VarInsnNode) anode;
if (vi.var != 0 && ("D" == stack[vi.var-1] || "J" == stack[vi.var-1]))
stack[vi.var-1] = "T";
break;
case AbstractInsnNode.TYPE_INSN:
ti = (TypeInsnNode) anode;
tidesc = ti.desc.charAt(0) == '[' ? ti.desc : ("L" + ti.desc + ";");
break;
case AbstractInsnNode.METHOD_INSN:
mi = (MethodInsnNode) anode;
midesc = Type.getMethodType(mi.desc);
break;
case AbstractInsnNode.INVOKE_DYNAMIC_INSN:
midesc = Type.getMethodType(((InvokeDynamicInsnNode)anode).desc);
break;
case AbstractInsnNode.FIELD_INSN:
fi = (FieldInsnNode) anode;
break;
}
String a,b,c,d;
int opcode = anode.getOpcode();
switch (opcode) {
case Opcodes.AALOAD:
stack[sp-2] = stack[sp-2].substring(1);
sp--;
break;
case Opcodes.ALOAD:
stack[sp++] = stack[vi.var];
break;
case Opcodes.ANEWARRAY:
stack[sp-1] = ("[" + tidesc).intern();
break;
case Opcodes.ASTORE:
stack[vi.var] = stack[--sp];
break;
case Opcodes.CHECKCAST:
stack[sp-1] = tidesc.intern();
break;
case Opcodes.DSTORE:
stack[vi.var] = "D";
stack[vi.var+1] = "T";
sp--;
break;
case Opcodes.DUP2:
// [b] a -> [b] a [b] a
a = stack[--sp];
b = ("D" == a || "J" == a) ? "X" : stack[--sp];
if (!"X".equals(b)) stack[sp++] = b;
stack[sp++] = a;
if (!"X".equals(b)) stack[sp++] = b;
stack[sp++] = a;
break;
case Opcodes.DUP2_X1:
// c [b] a -> [b] a c [b] a
a = stack[--sp];
b = ("D" == a || "J" == a) ? "X" : stack[--sp];
c = stack[--sp];
if ("X" != b) stack[sp++] = b;
stack[sp++] = a;
stack[sp++] = c;
if ("X" != b) stack[sp++] = b;
stack[sp++] = a;
break;
case Opcodes.DUP2_X2:
// [d] c [b] a -> b a d c b a
a = stack[--sp];
b = ("D" == a || "J" == a) ? "X" : stack[--sp];
c = stack[--sp];
d = ("D" == c || "J" == c) ? "X" : stack[--sp];
if ("X" != b) stack[sp++] = b;
stack[sp++] = a;
if ("X" != d) stack[sp++] = d;
stack[sp++] = c;
if ("X" != b) stack[sp++] = b;
stack[sp++] = a;
break;
case Opcodes.DUP:
// D, J invalid...
stack[sp] = stack[sp-1];
sp++;
break;
case Opcodes.DUP_X1:
// b a -> a b a
a = stack[--sp];
b = stack[--sp];
stack[sp++] = a;
stack[sp++] = b;
stack[sp++] = a;
break;
case Opcodes.DUP_X2:
// [d] c a -> a [d] c a
a = stack[--sp];
c = stack[--sp];
d = ("D" == c || "J" == c) ? "X" : stack[--sp];
stack[sp++] = a;
if ("X" != d) stack[sp++] = d;
stack[sp++] = c;
stack[sp++] = a;
break;
case Opcodes.FSTORE:
stack[vi.var] = "F";
sp--;
break;
case Opcodes.GETFIELD:
sp--;
pushReturn(fi.desc.intern());
break;
case Opcodes.GETSTATIC:
pushReturn(fi.desc.intern());
break;
case Opcodes.INVOKEINTERFACE:
case Opcodes.INVOKESPECIAL:
case Opcodes.INVOKESTATIC:
case Opcodes.INVOKEVIRTUAL:
case Opcodes.INVOKEDYNAMIC:
sp -= midesc.getArgumentTypes().length; // pop arguments
if (opcode != Opcodes.INVOKESTATIC && opcode != Opcodes.INVOKEDYNAMIC) {
a = stack[--sp]; // pop this
// initialize
if (a.charAt(0) == 'U') {
b = a.substring(a.indexOf(':')+1).intern();
for (int i = 0; i < stack.length; i++)
if (a == stack[i]) stack[i] = b;
}
}
pushReturn(midesc.getReturnType().getDescriptor().intern());
break;
case Opcodes.ISTORE:
stack[vi.var] = "I";
sp--;
break;
//simpleEffects[Opcodes.JSR] = new StackEffect(null);
case Opcodes.LDC:
{
Object cst = ((LdcInsnNode)anode).cst;
if (cst instanceof Integer) { stack[sp++] = "I"; break; }
if (cst instanceof Byte) { stack[sp++] = "I"; break; }
if (cst instanceof Character) { stack[sp++] = "I"; break; }
if (cst instanceof Short) { stack[sp++] = "I"; break; }
if (cst instanceof Boolean) { stack[sp++] = "I"; break; }
if (cst instanceof Float) { stack[sp++] = "F"; break; }
if (cst instanceof Long) { stack[sp++] = "J"; break; }
if (cst instanceof Double) { stack[sp++] = "D"; break; }
if (cst instanceof String) { stack[sp++] = "Ljava/lang/String;"; break; }
if (cst instanceof Type) { stack[sp++] = ((Type)cst).getSort() == Type.METHOD ? "Ljava/lang/invoke/MethodType;" : "Ljava/lang/Class;"; break; }
if (cst instanceof Handle) { stack[sp++] = "Ljava/lang/invoke/MethodHandle;"; break; }
throw new RuntimeException("Unknown constant type "+cst);
}
case Opcodes.LSTORE:
stack[vi.var] = "J";
stack[vi.var+1] = "T";
sp--;
break;
case Opcodes.MULTIANEWARRAY:
{
MultiANewArrayInsnNode m = (MultiANewArrayInsnNode)anode;
sp -= m.dims;
stack[sp++] = m.desc;
}
break;
case Opcodes.NEWARRAY:
{
int type = ((IntInsnNode)anode).operand;
switch (type) {
case Opcodes.T_BOOLEAN: stack[sp++] = "[Z"; break;
case Opcodes.T_CHAR: stack[sp++] = "[C"; break;
case Opcodes.T_FLOAT: stack[sp++] = "[F"; break;
case Opcodes.T_DOUBLE: stack[sp++] = "[D"; break;
case Opcodes.T_BYTE: stack[sp++] = "[B"; break;
case Opcodes.T_SHORT: stack[sp++] = "[S"; break;
case Opcodes.T_INT: stack[sp++] = "[I"; break;
case Opcodes.T_LONG: stack[sp++] = "[J"; break;
default: throw new RuntimeException("NEWARRAY "+type);
}
break;
}
case Opcodes.NEW:
stack[sp++] = ("U"+index+':'+tidesc).intern();
break;
case Opcodes.POP2:
// [d] c ->
c = stack[--sp];
d = ("D".equals(c) || "J".equals(c)) ? "X" : stack[--sp];
break;
case Opcodes.POP:
sp--;
break;
//simpleEffects[Opcodes.RET] = new StackEffect(null);
case Opcodes.SWAP:
a = stack[--sp];
b = stack[--sp];
stack[sp++] = a;
stack[sp++] = b;
break;
default:
throw new RuntimeException("unimplemented opcode " + anode.getOpcode());
}
}
}
private static class TypeInference {
public Frame[] frames;
int[] changedQueue;
int changedHead;
int changedTail;
boolean[] changedVec;
public TypeInference(int size) {
frames = new Frame[size];
changedQueue = new int[size+1];
changedVec = new boolean[size];
}
public int next() {
if (changedHead == changedTail) return -1;
int n = changedQueue[changedTail++];
if (changedTail == changedQueue.length) changedTail = 0;
changedVec[n] = false;
return n;
}
public void merge(int index, Frame f) {
Frame slot = frames[index];
if (slot == null) {
frames[index] = f.clone();
mark(index);
return;
}
slot.grow(f.stack.length);
f.grow(slot.stack.length);
if (f.sp != slot.sp) throw new RuntimeException(String.format("Insn %d can be reached with stack sizes of %d and %d", index, f.sp-f.sbase, slot.sp-slot.sbase));
boolean changed = false;
if (TYPE_TRACE) System.out.printf("MERGE INSN=%d\nOLD= [%s]\nINPUT= [%s]\n", index, slot.describe(), f.describe());
for (int i = 0; i < f.sp; i++) {
String a = f.stack[i];
String b = slot.stack[i];
String c = lub(a,b);
if (b != c) {
//System.out.printf("%d.%d %s -> %s\n", index, i, b, c);
if (DEBUG_FRAGMENT && a != c && b != c) System.out.printf("%d.%d %s | %s => %s\n", index, i, a, b, c);
slot.stack[i] = c;
changed = true;
}
}
if (TYPE_TRACE) System.out.printf("OUTPUT=[%s]\n%s\n", slot.describe(), changed ? "CHANGED" : "");
if (changed) mark(index);
}
void mark(int index) {
if (changedVec[index]) return;
changedVec[index] = true;
changedQueue[changedHead++] = index;
if (changedHead == changedQueue.length) changedHead = 0;
}
// computes the least upper bound of two verification types; we use descriptors, but U44:Lbar; for uninitialized(44), 0 for null, and T for TOP
String lub(String a,String b) {
// same type? trivial
if (a == b) return a;
if (a == "T") return a;
if (b == "T") return b;
char a0 = a.charAt(0);
char b0 = b.charAt(0);
// types other than initialized references cannot validly merge with anything
if (a0 != '0' && a0 != 'L' && a0 != '[') return "T";
if (b0 != '0' && b0 != 'L' && b0 != '[') return "T";
// null is the bottom of what remains
if (a0 == '0') return b;
if (b0 == '0') return a;
// an array and a non-array can merge only to Object
if (a0 == '[') {
if (b0 != '[') return "Ljava/lang/Object;";
// array types are covariant
String cc = lub(a.substring(1), b.substring(1));
if (cc.charAt(0) == 'T') // children are not compatible, but we know we have *some* array, which is an object
return "Ljava/lang/Object;";
return ('['+cc).intern();
} else {
if (b0 != 'L') return "Ljava/lang/Object;";
// at this point in a real verifier we would load the named classes and use their common superclass
// lub(P6OpaqueInstance, CodeRef) = SixModelObject
// punt.
if (a == "Lorg/perl6/nqp/runtime/CodeRef;" && b == "Lorg/perl6/nqp/sixmodel/SixModelObject;") return b;
if (b == "Lorg/perl6/nqp/runtime/CodeRef;" && a == "Lorg/perl6/nqp/sixmodel/SixModelObject;") return a;
return "Ljava/lang/Object;";
}
}
}
private void getTypes() {
// first, establish a locals size so that we can merge locals and stacks
nlocal = Type.getArgumentsAndReturnSizes(desc) >> 2;
if ((access & Opcodes.ACC_STATIC) != 0) nlocal--;
for (AbstractInsnNode an : insnList) {
if (an.getType() != AbstractInsnNode.VAR_INSN) continue;
int size = (an.getOpcode() == Opcodes.DSTORE || an.getOpcode() == Opcodes.LSTORE) ? 2 : 1;
nlocal = Math.max(nlocal, ((VarInsnNode)an).var + size);
}
TypeInference state = new TypeInference(insnList.length);
Frame initial = new Frame(new String[0], 0, 0);
initial.grow(nlocal+10);
int locwp = 0;
if ((access & Opcodes.ACC_STATIC) == 0) {
initial.stack[locwp++] = ('L'+tgtype+';').intern();
}
for (Type arg : Type.getArgumentTypes(desc)) {
initial.stack[locwp] = arg.getDescriptor().intern();
locwp += arg.getSize();
}
initial.sp = initial.sbase = nlocal;
state.merge(0, initial);
int insn;
int step = 0;
while ((insn = state.next()) >= 0) {
Frame in = state.frames[insn].clone();
if (TYPE_TRACE) System.out.printf("INFERENCE STEP: insn=%d [%d] locals=[%s] stack=[%s]\n", insn, insnList[insn].getOpcode(), Arrays.toString(Arrays.copyOfRange(in.stack, 0, nlocal)), Arrays.toString(Arrays.copyOfRange(in.stack, in.sbase, in.sp)));
in.execute(insn, insnList[insn]);
for (ControlEdge ce : successors[insn]) {
// assume exceptions follow non-exceptions
if (ce.exn != null) in.thrown(ce.exn);
state.merge(ce.to, in);
}
step++;
if (DEBUG_FRAGMENT && (step % 10000) == 0) System.out.printf("Inference step %d\n", step);
}
types = state.frames;
if (DEBUG_FRAGMENT) {
Map<String,Integer> histog = new HashMap< >();
for (Frame fr : types) {
for (int i = 0; i < fr.sp; i++) {
Integer r = histog.get(fr.stack[i]);
histog.put(fr.stack[i], r == null ? 1 : 1+r);
}
}
for (Map.Entry<String,Integer> ent : histog.entrySet())
System.out.printf("%s : %d\n", ent.getKey(), ent.getValue());
}
}
private int insnSize(AbstractInsnNode ai) {
int opc = ai.getOpcode();
switch (ai.getType()) {
case AbstractInsnNode.INSN:
return 1;
case AbstractInsnNode.INT_INSN:
return (opc == Opcodes.SIPUSH) ? 3 : 2;
case AbstractInsnNode.VAR_INSN:
{
int var = ((VarInsnNode)ai).var;
return (var < 4 && opc != Opcodes.RET) ? 1 : (var >= 256) ? 4 : 2;
}
case AbstractInsnNode.TYPE_INSN:
return 3;
case AbstractInsnNode.FIELD_INSN:
return 3;
case AbstractInsnNode.METHOD_INSN:
return (opc == Opcodes.INVOKEINTERFACE) ? 5 : 3;
case AbstractInsnNode.INVOKE_DYNAMIC_INSN:
return 5;
case AbstractInsnNode.JUMP_INSN:
return (opc == Opcodes.GOTO || opc == Opcodes.JSR) ? 5 : 8;
case AbstractInsnNode.LDC_INSN:
return 3;
case AbstractInsnNode.IINC_INSN:
{
IincInsnNode ii = (IincInsnNode) ai;
return (ii.var >= 256 || ii.incr > 127 || ii.incr < -128) ? 6 : 3;
}
case AbstractInsnNode.TABLESWITCH_INSN:
{
TableSwitchInsnNode si = (TableSwitchInsnNode) ai;
return 16 + si.labels.size() * 4;
}
case AbstractInsnNode.LOOKUPSWITCH_INSN:
{
LookupSwitchInsnNode si = (LookupSwitchInsnNode) ai;
return 12 + si.labels.size() * 8;
}
case AbstractInsnNode.MULTIANEWARRAY_INSN:
return 4;
default:
return 0;
}
}
// loosely based on the codesizeevaluator;
private void getBaselineSize() {
baselineSize = new int[insnList.length+1];
int accum=0;
for (int i = 0; i < insnList.length; i++) {
AbstractInsnNode ai = insnList[i];
MethodInsnNode mi;
int size = insnSize(ai);
// some of these require special handling
switch (ai.getOpcode()) {
case Opcodes.RETURN:
// iconst_m1; ireturn
size = 2;
break;
case Opcodes.IRETURN:
case Opcodes.FRETURN:
case Opcodes.LRETURN:
case Opcodes.DRETURN:
case Opcodes.ARETURN:
// xstore tmp[0-2]; aload buf; iconst_0; new java/lang/Wrapper; dup; xload tmp; invokespecial; aastore; iconst_m1; ireturn
size = 1+(nlocal >= 254 ? 4 : 2)+1+3+1+1+3+1+1+1;
break;
// Opcodes.NEW may be rewritten into aconst_null if a spill is needed, but that doesn't affect the max
case Opcodes.INVOKESPECIAL:
mi = (MethodInsnNode) ai;
if ("<init>".equals(mi.name)) {
int skeep = 0;
Frame f1 = types[i];
Frame f2 = types[i+1];
String uninit = f1.stack[f2.sp];
while (skeep < f1.sp && !uninit.equals(f1.stack[skeep])) skeep++;
size = 0;
int ltmp = nlocal + 2; /*buf*/
// spill everything relevant above skeep into locals
for (int j = skeep; j < f1.sp; j++) {
if (uninit.equals(f1.stack[j])) continue;
size += (ltmp < 256) ? 2 : 4;
ltmp += 2;
}
ltmp++; // keep a copy of the value
int argc = Type.getArgumentTypes(mi.desc).length;
// newobj, dup, unspill, invokespecial
size += 3 + 1 + argc*(ltmp < 256 ? 2 : 4) + 3;
// store in locals, including <tmp>
for (int j = 0; j < nlocal; j++) {
if (uninit.equals(f1.stack[j]))
size += 1 + (j < 256 ? 2 : 4);
}
size += (ltmp < 256 ? 2 : 4);
// unspill
size += (ltmp < 256 ? 2 : 4) * (f2.sp - skeep);
}
break;
}
baselineSize[i] = accum;
accum += size;
}
baselineSize[insnList.length] = accum;
if (DEBUG_CONTROL) System.out.println(Arrays.toString(baselineSize));
}
private int[][] nonlocalEntryExit(int from, int to) {
// need to include entry trampolines and exit trampolines
int[] entryPts = new int[to-from];
int entryCt = 0;
boolean[] entryDedup = new boolean[to-from];
int[] exitPts = new int[insnList.length];
int exitCt = 0;
boolean[] exitDedup = new boolean[insnList.length];
for (ControlEdge ce : controlEdges) {
boolean from_this = (ce.from >= from && ce.from < to);
boolean to_this = (ce.to >= from && ce.to < to);
if (!from_this && to_this && !entryDedup[ce.to-from]) {
entryDedup[ce.to-from] = true;
entryPts[entryCt++] = ce.to;
}
if (from_this && !to_this && !exitDedup[ce.to]) {
exitDedup[ce.to] = true;
exitPts[exitCt++] = ce.to;
}
}
if (from == 0 && !entryDedup[0]) {
entryPts[entryCt++] = 0;
}
entryPts = Arrays.copyOf(entryPts, entryCt);
exitPts = Arrays.copyOf(exitPts, exitCt);
Arrays.sort(entryPts);
Arrays.sort(exitPts);
if (DEBUG_CONTROL) {
System.out.printf("NONLOCAL ENTRY: %s\n", Arrays.toString(entryPts));
System.out.printf("NONLOCAL EXIT: %s\n", Arrays.toString(exitPts));
}
return new int[][] { entryPts, exitPts };
}
private int calcFragmentSize(int from, int to) {
// we have to include the instructions
int base = baselineSize[to] - baselineSize[from];
int[][] ee = nonlocalEntryExit(from, to);
int[] entryPts = ee[0];
int[] exitPts = ee[1];
// factor out commonalities from the trampolines
String[] commonEntry = commonTrampoline(entryPts, null);
String[] commonExit = commonTrampoline(exitPts, null);
// common entry code
// iload; aload; {dup; ipush; aaload; UNBOX; xstore; }; swap; tableswitch
int centry = 2;
for (int i = 0; i < commonEntry.length; i++) {
centry += localEntrySize(i, commonEntry[i]);
}
centry += 13; // swap+tswitch
// uncommon entry code
int uentry = 0;
for (int ept : entryPts) {
uentry += 4; // dispatch vector
Frame f = types[ept];
for (int j = 0; j < f.sp; j++) {
if (j < commonEntry.length && commonEntry[j].equals(f.stack[j])) {
/* no action */
} else if (j < nlocal) {
uentry += localEntrySize(j, f.stack[j]);
} else {
uentry += stackEntrySize(j, f.stack[j]);
}
}
uentry += (nlocal <= 255 ? 2 : 4); // astore
uentry += 5; // final jump
}
// jump insertion
int uexit = 3;
// uncommon exit code
for (int pt : exitPts) {
Frame f = types[pt];
for (int j = 0; j < f.sp; j++) {
if (j < commonExit.length && commonExit[j].equals(f.stack[j])) {
/* no action */
} else if (j < nlocal) {
uexit += localExitSize(j, f.stack[j]);
} else {
uexit += stackExitSize(j, f.stack[j]);
}
}
uexit += (nlocal <= 255 ? 2 : 4); // aload in middle
uexit += 3; // ipush
uexit += 5; // jump to combiner
}
// common exit code
int cexit = 1; // swap
for (int i = 0; i < commonExit.length; i++) {
cexit += localExitSize(i, commonExit[i]);
}
cexit += 2; // pop; ireturn
int total = centry + uentry + base + uexit + cexit;
if (DEBUG_FRAGMENT) System.out.printf("calcSize: %d-%d : centry(%d) uentry(%d) base(%d) uexit(%d) cexit(%d) total(%d)\n", from, to, centry, uentry, base, uexit, cexit, total);
return total;
}
private int localEntrySize(int loc, String desc) {
char c0 = desc.charAt(0);
if (c0 == 'T') return 0; // not loaded
int sz;
switch (c0) {
case '0':
case 'U':
// just load as a null
sz = 1;
break;
case 'L':
case '[':
// dup, ipush, aaload, checkcast
sz = (loc < 128) ? 7 : 8;
break;
default:
// dup, ipush, aaload, checkcast, fooValue
sz = (loc < 128) ? 10 : 11;
break;
}
return sz + ((loc < 256) ? 2 : 4);
}
private int localExitSize(int loc, String desc) {
char c0 = desc.charAt(0);
if (c0 == 'T' || c0 == '0' || c0 == 'U') return 0; // not saved
int sz = (loc < 256) ? 2 : 4;
switch (c0) {
case 'L':
case '[':
// dup, ipush, xload, aastore
return sz + ((loc < 128) ? 4 : 5);
default:
// dup, ipush, new, dup, xload, invokespecial, aastore
return sz + ((loc < 128) ? 11 : 12);
}
}
private int stackEntrySize(int loc, String desc) {
char c0 = desc.charAt(0);
switch (c0) {
case '0':
case 'U':
// just load as a null
return 1;
case 'L':
case '[':
// aload, ipush, aaload, checkcast
return (loc < 128) ? 10 : 11;
default:
// aload, ipush, aaload, checkcast, fooValue
return (loc < 128) ? 13 : 14;
}
}
private int stackExitSize(int loc, String desc) {
char c0 = desc.charAt(0);
if (c0 == 'T' || c0 == '0' || c0 == 'U') return 1; // not saved
switch (c0) {
case 'L':
case '[':
// xstore, aload, ipush, xload, aastore
return (loc < 128) ? 15 : 16;
default:
// xstore, aload, ipush, new, dup, xload, invokespecial, aastore
return (loc < 128) ? 22 : 23;
}
}
private String[] commonTrampoline(int[] points, Set<String> spills) {
String[] common = null;
for (int i = 0; i < points.length; i++) {
Frame f = types[points[i]];
if (spills != null) {
for (int j = 0; j < f.sp; j++) spills.add(f.stack[j]);
}
if (common == null) {
common = Arrays.copyOf(f.stack, nlocal);
} else {
for (int j = 0; j < common.length; j++) {
if (j >= f.sp || !f.stack[j].equals(common[j]))
common[j] = "T";
}
}
}
return common == null ? new String[] { } : common;
}
private void allocateJumpNrs(int begin, int end) {
int[][] ee = nonlocalEntryExit(begin, end);
int firstEntry = nextJumpNo;
for (int entry : ee[0]) {
jumpNoMap[entry] = nextJumpNo++;
}
firstJump.add(firstEntry);
if (DEBUG_FRAGMENT) System.out.printf("Fragment %d-%d has jump numbers %d-%d\n", begin, end, firstEntry, nextJumpNo);
}
private void emitFragment(int fno, int begin, int end) {
MethodVisitor v = target.visitMethod(Opcodes.ACC_STATIC | Opcodes.ACC_PRIVATE | Opcodes.ACC_SYNTHETIC, name+"$f"+fno, "(I[Ljava/lang/Object;)I", null, null);
v.visitCode();
int[][] ee = nonlocalEntryExit(begin, end);
int[] entryPts = ee[0];
int[] exitPts = ee[1];
// factor out commonalities from the trampolines
Set<String> spilledUTypes = new HashSet< >();
String[] commonEntry = commonTrampoline(entryPts, spilledUTypes);
String[] commonExit = commonTrampoline(exitPts, spilledUTypes);
Label[] entryTrampolineLabels = new Label[entryPts.length];
for (int i = 0; i < entryPts.length; i++)
entryTrampolineLabels[i] = new Label();
Map<Integer, Label> exitTrampolineLabels = new HashMap< >();
for (int i = 0; i < exitPts.length; i++)
exitTrampolineLabels.put(exitPts[i], new Label());
Label[] insnLabels = new Label[end - begin + 1];
for (int i = 0; i < end - begin + 1; i++)
insnLabels[i] = new Label();
// common entry code
// aload; {dup; ipush; aaload; UNBOX; xstore; }; iload; tableswitch
v.visitVarInsn(Opcodes.ILOAD, 0);
v.visitVarInsn(Opcodes.ALOAD, 1);
for (int i = 0; i < commonEntry.length; i++) {
localEntryCode(v, i, commonEntry[i]);
}
v.visitInsn(Opcodes.SWAP);
int firstj = firstJump.get(fno);
v.visitTableSwitchInsn(firstj, firstj + entryPts.length - 1, entryTrampolineLabels[0] /*XXX*/, entryTrampolineLabels);
int stash = nlocal;
int scratch = nlocal+1;
// emit salient tryblocks
for (TryCatchBlockNode tcbn : (List<TryCatchBlockNode>) tryCatchBlocks) {
int nstart = Math.max(begin, insnMap.get(tcbn.start));
int nend = Math.min(end, insnMap.get(tcbn.end));
int nhndlr = insnMap.get(tcbn.handler);
if (nstart >= nend) continue;
v.visitTryCatchBlock(insnLabels[nstart - begin], insnLabels[nend - begin],
exitTrampolineLabels.containsKey(nhndlr) ? exitTrampolineLabels.get(nhndlr) : insnLabels[nhndlr - begin],
tcbn.type);
}
// uncommon entry code
for (int ept : entryPts) {
v.visitLabel(entryTrampolineLabels[jumpNoMap[ept]-firstj]);
Frame f = types[ept];
for (int j = 0; j < nlocal; j++) {
if (j < commonEntry.length && commonEntry[j].equals(f.stack[j]))
continue;
localEntryCode(v, j, f.stack[j]);
}
v.visitVarInsn(Opcodes.ASTORE, stash);
for (int j = nlocal; j < f.sp; j++) {
stackEntryCode(v, stash, j, f.stack[j]);
}
v.visitJumpInsn(Opcodes.GOTO, insnLabels[ept - begin]);
}
// we have to include the instructions
for (int iix = begin; iix < end; iix++) {
emitFragmentInsn(v, iix, begin, insnLabels, exitTrampolineLabels, spilledUTypes);
}
v.visitLabel(insnLabels[end - begin]);
boolean fallthru = false;
for (ControlEdge ce : successors[end-1]) {
if (ce.to == end) {
fallthru = true;
break;
}
}
if (fallthru)
v.visitJumpInsn(Opcodes.GOTO, exitTrampolineLabels.get(end));
int lineno = -1;
for (int i = begin; i < end; i++) {
if (lineNumbers[i] != lineno) {
lineno = lineNumbers[i];
v.visitLineNumber(lineno, insnLabels[i-begin]);
}
}
Label commonExitLabel = new Label();
// uncommon exit code
for (int pt : exitPts) {
v.visitLabel(exitTrampolineLabels.get(pt));
Frame f = types[pt];
for (int j = f.sp-1; j >= nlocal; j--) {
stackExitCode(v, stash, scratch, j, f.stack[j]);
}
v.visitVarInsn(Opcodes.ALOAD, stash);
for (int j = 0; j < nlocal; j++) {
if (j < commonExit.length && commonExit[j].equals(f.stack[j]))
continue;
localExitCode(v, j, f.stack[j]);
}
pushInt(v, jumpNoMap[pt]);
v.visitJumpInsn(Opcodes.GOTO, commonExitLabel);
}
// common exit code
if (exitPts.length > 0) {
v.visitLabel(commonExitLabel);
v.visitInsn(Opcodes.SWAP);
for (int i = 0; i < commonExit.length; i++) {
localExitCode(v, i, commonExit[i]);
}
v.visitInsn(Opcodes.POP);
v.visitInsn(Opcodes.IRETURN);
}
v.visitMaxs(0,0);
v.visitEnd();
}
private String[] box_types = new String[] { "java/lang/Integer", "java/lang/Long", "java/lang/Float", "java/lang/Double" };
private String[] box_descs = new String[] { "(I)V", "(J)V", "(F)V", "(D)V" };
private void emitFragmentInsn(MethodVisitor v, int iix, int begin, Label[] insnLabels, Map<Integer,Label> exitTrampolineLabels, Set<String> spilledUTypes) {
v.visitLabel(insnLabels[iix - begin]);
AbstractInsnNode ai = insnList[iix];
// some instructions require very special handling
int opc = ai.getOpcode();
if (opc == Opcodes.RETURN) {
v.visitInsn(Opcodes.ICONST_M1);
v.visitInsn(Opcodes.IRETURN);
return;
}
if (opc >= Opcodes.IRETURN && opc <= Opcodes.ARETURN) {
int t = opc - Opcodes.IRETURN;
v.visitVarInsn(Opcodes.ISTORE + t, nlocal+1);
v.visitVarInsn(Opcodes.ALOAD, nlocal);
v.visitInsn(Opcodes.ICONST_0);
if (opc != Opcodes.ARETURN) {
v.visitTypeInsn(Opcodes.NEW, box_types[t]);
v.visitInsn(Opcodes.DUP);
v.visitVarInsn(Opcodes.ILOAD + t, nlocal+1);
v.visitMethodInsn(Opcodes.INVOKESPECIAL, box_types[t], "<init>", box_descs[t]);
} else {
v.visitVarInsn(Opcodes.ILOAD + t, nlocal+1);
}
v.visitInsn(Opcodes.AASTORE);
v.visitInsn(Opcodes.ICONST_M1);
v.visitInsn(Opcodes.IRETURN);
return;
}
if (opc == Opcodes.NEW) {
Frame f = types[iix+1];
if (spilledUTypes.contains(f.stack[f.sp-1])) {
v.visitInsn(Opcodes.ACONST_NULL);
return;
}
}
if (opc == Opcodes.INVOKESPECIAL) {
MethodInsnNode mi = (MethodInsnNode)ai;
Frame f1 = types[iix];
Frame f2 = types[iix+1];
String uninit = f1.stack[f2.sp];
if (mi.name.equals("<init>") && spilledUTypes.contains(uninit)) {
if (!f2.stack[f2.sp-1].equals(uninit)) throw new RuntimeException("general case of INVOKESPECIAL spill not implemented");
for (int i = 0; i < f2.sp-1; i++) if (f2.stack[i].equals(uninit)) throw new RuntimeException("general case of INVOKESPECIAL spill not implemented");
int ltmp = nlocal+1;
int argc = Type.getArgumentTypes(mi.desc).length;
int[] spillarg = new int[argc];
for (int d = 0; d < argc; d++) {
char ty0 = f1.stack[f1.sp-d-1].charAt(0);
spillarg[d] = ltmp;
v.visitVarInsn(ty0 == 'D' ? Opcodes.DSTORE : ty0 == 'J' ? Opcodes.LSTORE : ty0 == 'I' ? Opcodes.ISTORE : ty0 == 'F' ? Opcodes.FSTORE : Opcodes.ASTORE, ltmp);
ltmp += (ty0 == 'D' || ty0 == 'J') ? 2 : 1;
}
v.visitInsn(Opcodes.POP2);
v.visitTypeInsn(Opcodes.NEW, mi.owner);
v.visitInsn(Opcodes.DUP);
for (int d = argc-1; d >= 0; d++) {
char ty0 = f1.stack[f1.sp-d-1].charAt(0);
v.visitVarInsn(ty0 == 'D' ? Opcodes.DLOAD : ty0 == 'J' ? Opcodes.LLOAD : ty0 == 'I' ? Opcodes.ILOAD : ty0 == 'F' ? Opcodes.FLOAD : Opcodes.ALOAD, spillarg[d]);
}
v.visitMethodInsn(Opcodes.INVOKESPECIAL, mi.owner, mi.name, mi.desc);
return;
}
}
// all other instructions can be processed normally, perhaps with some control-flow fudging
switch (ai.getType()) {
case AbstractInsnNode.JUMP_INSN:
{
JumpInsnNode ji = (JumpInsnNode)ai;
v.visitJumpInsn(opc, mapLabel(ji.label, begin, insnLabels, exitTrampolineLabels));
break;
}
case AbstractInsnNode.TABLESWITCH_INSN:
{
TableSwitchInsnNode si = (TableSwitchInsnNode)ai;
Label[] mapped = new Label[si.labels.size()];
for (int i = 0; i < mapped.length; i++)
mapped[i] = mapLabel((LabelNode)si.labels.get(i), begin, insnLabels, exitTrampolineLabels);
v.visitTableSwitchInsn(si.min, si.max, mapLabel(si.dflt, begin, insnLabels, exitTrampolineLabels), mapped);
break;
}
case AbstractInsnNode.LOOKUPSWITCH_INSN:
{
LookupSwitchInsnNode si = (LookupSwitchInsnNode)ai;
Label[] mapped = new Label[si.labels.size()];
for (int i = 0; i < mapped.length; i++)
mapped[i] = mapLabel((LabelNode)si.labels.get(i), begin, insnLabels, exitTrampolineLabels);
int[] keys = new int[si.keys.size()];
for (int i = 0; i < keys.length; i++)
keys[i] = (int)si.keys.get(i);
v.visitLookupSwitchInsn(mapLabel(si.dflt, begin, insnLabels, exitTrampolineLabels), keys, mapped);
break;
}
default:
ai.accept(v);
break;
}
}
private Label mapLabel(LabelNode ln, int begin, Label[] insnLabels, Map<Integer,Label> exitTrampolineLabels) {
int lni = insnMap.get(ln);
if (exitTrampolineLabels.containsKey(lni))
return exitTrampolineLabels.get(lni);
return insnLabels[lni - begin];
}
private void localEntryCode(MethodVisitor v, int loc, String desc) {
char c0 = desc.charAt(0);
if (c0 == 'T') return; // not loaded
int sz;
switch (c0) {
case '0':
case 'U':
// just load as a null
v.visitInsn(Opcodes.ACONST_NULL);
break;
case 'L':
case '[':
// dup, ipush, aaload, checkcast
v.visitInsn(Opcodes.DUP);
pushInt(v, loc);
v.visitInsn(Opcodes.AALOAD);
if (!desc.equals("Ljava/lang/Object;")) v.visitTypeInsn(Opcodes.CHECKCAST, c0 == '[' ? desc : desc.substring(1, desc.length()-1));
break;
default:
// dup, ipush, aaload, checkcast, fooValue
v.visitInsn(Opcodes.DUP);
pushInt(v, loc);
v.visitInsn(Opcodes.AALOAD);
unbox(v, c0);
v.visitVarInsn( c0=='I' ? Opcodes.ISTORE : c0=='J' ? Opcodes.LSTORE : c0=='F' ? Opcodes.FSTORE : Opcodes.DSTORE, loc );
return;
}
v.visitVarInsn(Opcodes.ASTORE, loc);
}
private void pushInt(MethodVisitor v, int value) {
if (value >= -1 && value <= 5)
v.visitInsn(Opcodes.ICONST_0 + value);
else if (value >= -128 && value <= 127)
v.visitIntInsn(Opcodes.BIPUSH, value);
else if (value >= -32768 && value <= 32767)
v.visitIntInsn(Opcodes.SIPUSH, value);
else
v.visitLdcInsn(value);
}
private void unbox(MethodVisitor v, char c0) {
String c,m,d;
switch (c0) {
case 'I': c = "java/lang/Integer"; m = "intValue"; d = "()I"; break;
case 'J': c = "java/lang/Long"; m = "longValue"; d = "()J"; break;
case 'F': c = "java/lang/Float"; m = "floatValue"; d = "()F"; break;
case 'D': c = "java/lang/Double"; m = "doubleValue"; d = "()D"; break;
default: throw new IllegalArgumentException();
}
v.visitTypeInsn(Opcodes.CHECKCAST, c);
v.visitMethodInsn(Opcodes.INVOKEVIRTUAL, c, m, d);
}
private void localExitCode(MethodVisitor v, int loc, String desc) {
char c0 = desc.charAt(0);
if (c0 == 'T' || c0 == '0' || c0 == 'U') return; // not saved
switch (c0) {
case 'L':
case '[':
v.visitInsn(Opcodes.DUP);
pushInt(v, loc);
v.visitVarInsn(Opcodes.ALOAD, loc);
v.visitInsn(Opcodes.AASTORE);
break;
default:
v.visitInsn(Opcodes.DUP);
pushInt(v, loc);
{
String ty;
int load;
switch (c0) {
case 'I': ty = "java/lang/Integer"; load = Opcodes.ILOAD; break;
case 'J': ty = "java/lang/Long"; load = Opcodes.LLOAD; break;
case 'F': ty = "java/lang/Float"; load = Opcodes.FLOAD; break;
case 'D': ty = "java/lang/Double"; load = Opcodes.DLOAD; break;
default: throw new IllegalArgumentException(desc);
}
v.visitTypeInsn(Opcodes.NEW, ty);
v.visitInsn(Opcodes.DUP);
v.visitVarInsn(load, loc);
v.visitMethodInsn(Opcodes.INVOKESPECIAL, ty, "<init>", "("+c0+")V");
}
v.visitInsn(Opcodes.AASTORE);
break;
}
}
private void stackEntryCode(MethodVisitor v, int stash, int loc, String desc) {
char c0 = desc.charAt(0);
switch (c0) {
case '0':
case 'U':
v.visitInsn(Opcodes.ACONST_NULL);
break;
case 'L':
case '[':
v.visitVarInsn(Opcodes.ALOAD, stash);
pushInt(v, loc);
v.visitInsn(Opcodes.AALOAD);
if (!desc.equals("Ljava/lang/Object;")) v.visitTypeInsn(Opcodes.CHECKCAST, c0 == '[' ? desc : desc.substring(1, desc.length()-1));
break;
default:
v.visitVarInsn(Opcodes.ALOAD, stash);
pushInt(v, loc);
v.visitInsn(Opcodes.AALOAD);
unbox(v, c0);
break;
}
}
private void stackExitCode(MethodVisitor v, int stash, int scratch, int loc, String desc) {
char c0 = desc.charAt(0);
if (c0 == 'T' || c0 == '0' || c0 == 'U') {
v.visitInsn(Opcodes.POP);
return;
}
String ty;
int load, store;
switch (c0) {
case 'L':
case '[':
v.visitVarInsn(Opcodes.ASTORE, scratch);
v.visitVarInsn(Opcodes.ALOAD, stash);
pushInt(v, loc);
v.visitVarInsn(Opcodes.ALOAD, scratch);
v.visitInsn(Opcodes.AASTORE);
return;
case 'I': ty = "java/lang/Integer"; load = Opcodes.ILOAD; store = Opcodes.ISTORE; break;
case 'J': ty = "java/lang/Long"; load = Opcodes.LLOAD; store = Opcodes.LSTORE; break;
case 'F': ty = "java/lang/Float"; load = Opcodes.FLOAD; store = Opcodes.FSTORE; break;
case 'D': ty = "java/lang/Double"; load = Opcodes.DLOAD; store = Opcodes.DSTORE; break;
default: throw new IllegalArgumentException(desc);
}
v.visitVarInsn(store, scratch);
v.visitVarInsn(Opcodes.ALOAD, stash);
pushInt(v, loc);
v.visitTypeInsn(Opcodes.NEW, ty);
v.visitInsn(Opcodes.DUP);
v.visitVarInsn(load, scratch);
v.visitMethodInsn(Opcodes.INVOKESPECIAL, ty, "<init>", "("+c0+")V");
v.visitInsn(Opcodes.AASTORE);
}
private void becomeWrapper() {
int maxStack = 0;
for (Frame f : types)
maxStack = Math.max(maxStack, f.sp);
tryCatchBlocks = null;
localVariables = null;
instructions.clear();
// allocate the scratchpad
instructions.add(intNode(maxStack));
instructions.add(new TypeInsnNode(Opcodes.ANEWARRAY, "java/lang/Object"));
// move the arguments onto the scratchpad
int ltmp = 0;
if ((access & Opcodes.ACC_STATIC) == 0) ltmp += saveArg(instructions, ltmp, Type.getType(Object.class));
for (Type at : Type.getArgumentTypes(desc)) ltmp += saveArg(instructions, ltmp, at);
instructions.add(new VarInsnNode(Opcodes.ASTORE, 0));
instructions.add(intNode(0));
instructions.add(new VarInsnNode(Opcodes.ISTORE, 1));
LabelNode loop = new LabelNode();
instructions.add(loop);
for (int i = firstJump.size() - 1; i >= 0; i--) {
LabelNode not_my_problem = new LabelNode();
instructions.add(new VarInsnNode(Opcodes.ILOAD, 1));
instructions.add(intNode(firstJump.get(i)));
instructions.add(new JumpInsnNode(Opcodes.IF_ICMPLT, not_my_problem));
instructions.add(new VarInsnNode(Opcodes.ILOAD, 1));
instructions.add(new VarInsnNode(Opcodes.ALOAD, 0));
instructions.add(new MethodInsnNode(Opcodes.INVOKESTATIC, tgtype, name + "$f" + i, "(I[Ljava/lang/Object;)I"));
instructions.add(new VarInsnNode(Opcodes.ISTORE, 1));
instructions.add(new JumpInsnNode(Opcodes.GOTO, loop));
instructions.add(not_my_problem);
}
// time for return
String rty = null, unboxName = null, unboxDesc = null;
int retinst;
Type rtyty = Type.getReturnType(desc);
switch (rtyty.getSort()) {
case Type.VOID:
retinst = Opcodes.RETURN; break;
case Type.BOOLEAN:
case Type.CHAR:
case Type.INT:
case Type.SHORT:
case Type.BYTE:
retinst = Opcodes.IRETURN; rty = "java/lang/Integer"; unboxName = "intValue"; unboxDesc = "()I"; break;
case Type.LONG:
retinst = Opcodes.LRETURN; rty = "java/lang/Long"; unboxName = "longValue"; unboxDesc = "()J"; break;
case Type.FLOAT:
retinst = Opcodes.FRETURN; rty = "java/lang/Float"; unboxName = "floatValue"; unboxDesc = "()F"; break;
case Type.DOUBLE:
retinst = Opcodes.DRETURN; rty = "java/lang/Double"; unboxName = "doubleValue"; unboxDesc = "()D"; break;
default:
retinst = Opcodes.ARETURN; rty = rtyty.getInternalName(); break;
}
if (rty != null) {
instructions.add(new VarInsnNode(Opcodes.ALOAD, 0));
instructions.add(new InsnNode(Opcodes.ICONST_0));
instructions.add(new InsnNode(Opcodes.AALOAD));
instructions.add(new TypeInsnNode(Opcodes.CHECKCAST, rty));
if (unboxName != null)
instructions.add(new MethodInsnNode(Opcodes.INVOKEVIRTUAL, rty, unboxName, unboxDesc));
}
instructions.add(new InsnNode(retinst));
}
private int saveArg(InsnList il, int ltmp, Type at) {
il.add(new InsnNode(Opcodes.DUP));
il.add(intNode(ltmp));
int opc;
String ty = null, desc = null;
switch (at.getSort()) {
case Type.BOOLEAN:
case Type.CHAR:
case Type.INT:
case Type.SHORT:
case Type.BYTE:
opc = Opcodes.ILOAD; ty = "java/lang/Integer"; desc = "(I)V"; break;
case Type.LONG:
opc = Opcodes.LLOAD; ty = "java/lang/Long"; desc = "(J)V"; break;
case Type.FLOAT:
opc = Opcodes.FLOAD; ty = "java/lang/Float"; desc = "(F)V"; break;
case Type.DOUBLE:
opc = Opcodes.DLOAD; ty = "java/lang/Double"; desc = "(D)V"; break;
default:
opc = Opcodes.ALOAD; break;
}
if (ty != null) {
il.add(new TypeInsnNode(Opcodes.NEW, ty));
il.add(new InsnNode(Opcodes.DUP));
}
il.add(new VarInsnNode(opc, ltmp));
if (ty != null) il.add(new MethodInsnNode(Opcodes.INVOKESPECIAL, ty, "<init>", desc));
il.add(new InsnNode(Opcodes.AASTORE));
return at.getSize();
}
}
| artistic-2.0 |
RealTimeGenomics/rtg-tools | src/com/rtg/tabix/VcfPositionReader.java | 2430 | /*
* Copyright (c) 2014. Real Time Genomics Limited.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.rtg.tabix;
import java.io.IOException;
/**
* Position reader for <code>VCF</code> files, used for TABIX index support
*/
class VcfPositionReader extends AbstractPositionReader {
private static final int NUM_COLUMNS = 4;
private static final int REF_NAME_COLUMN = 0;
private static final int START_POS_COLUMN = 1;
private static final int REF_COLUMN = 3;
/**
* Constructor
* @param reader source of SAM file
* @param skip number of lines to skip at beginning of file
*/
VcfPositionReader(BlockCompressedLineReader reader, int skip) {
super(reader, NUM_COLUMNS, '#', skip);
}
@Override
protected void setReferenceName() throws IOException {
mReferenceName = getColumn(REF_NAME_COLUMN);
}
@Override
protected void setStartAndLength() throws IOException {
mStartPosition = getIntColumn(START_POS_COLUMN) - 1;
if (mStartPosition < 0) {
mStartPosition = 0;
}
final String ref = getColumn(REF_COLUMN);
mLengthOnReference = ref.length();
}
}
| bsd-2-clause |
DFC-Incubator/base-service | base-service-impl/src/main/java/org/irods/jargon/rest/base/model/PathComponent.java | 1532 | package org.irods.jargon.rest.base.model;
import java.util.Objects;
import java.util.ArrayList;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonCreator;
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaResteasyServerCodegen", date = "2017-02-10T11:17:25.080-05:00")
public class PathComponent {
private String parthPart = null;
/**
* part of a path
**/
@JsonProperty("parthPart")
public String getParthPart() {
return parthPart;
}
public void setParthPart(String parthPart) {
this.parthPart = parthPart;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
PathComponent pathComponent = (PathComponent) o;
return Objects.equals(parthPart, pathComponent.parthPart);
}
@Override
public int hashCode() {
return Objects.hash(parthPart);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class PathComponent {\n");
sb.append(" parthPart: ").append(toIndentedString(parthPart)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
| bsd-2-clause |
fokus-llc/lenzenslijper | src/main/java/us/fok/lenzenslijper/views/UserView.java | 402 | package us.fok.lenzenslijper.views;
public class UserView {
public String username;
public String name;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
| bsd-2-clause |
ScottLiu0/QuickOpen | app/src/main/java/cn/imliu/quickopen/util/Code.java | 155 | package cn.imliu.quickopen.util;
/**
* Created by scott on 2017/2/26.
*/
public final class Code {
public final static Integer REQUEST_OVERLAY = 1;
}
| bsd-2-clause |
jbox2d/jbox2d | jbox2d-testbed/src/main/java/org/jbox2d/testbed/framework/j2d/TestPanelJ2D.java | 4286 | /*******************************************************************************
* Copyright (c) 2013, Daniel Murphy All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met: * Redistributions of source code must retain the
* above copyright notice, this list of conditions and the following disclaimer. * Redistributions
* in binary form must reproduce the above copyright notice, this list of conditions and the
* following disclaimer in the documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY
* WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
package org.jbox2d.testbed.framework.j2d;
import java.awt.AWTError;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import javax.swing.JPanel;
import org.jbox2d.testbed.framework.AbstractTestbedController;
import org.jbox2d.testbed.framework.TestbedModel;
import org.jbox2d.testbed.framework.TestbedPanel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Daniel Murphy
*/
@SuppressWarnings("serial")
public class TestPanelJ2D extends JPanel implements TestbedPanel {
private static final Logger log = LoggerFactory.getLogger(TestPanelJ2D.class);
public static final int SCREEN_DRAG_BUTTON = 3;
public static final int INIT_WIDTH = 600;
public static final int INIT_HEIGHT = 600;
private Graphics2D dbg = null;
private Image dbImage = null;
private int panelWidth;
private int panelHeight;
private final AbstractTestbedController controller;
public TestPanelJ2D(final TestbedModel model, final AbstractTestbedController controller) {
this.controller = controller;
setBackground(Color.black);
setPreferredSize(new Dimension(INIT_WIDTH, INIT_HEIGHT));
updateSize(INIT_WIDTH, INIT_HEIGHT);
AWTPanelHelper.addHelpAndPanelListeners(this, model, controller, SCREEN_DRAG_BUTTON);
addComponentListener(new ComponentAdapter() {
@Override
public void componentResized(ComponentEvent e) {
updateSize(getWidth(), getHeight());
dbImage = null;
}
});
}
public Graphics2D getDBGraphics() {
return dbg;
}
private void updateSize(int width, int height) {
panelWidth = width;
panelHeight = height;
controller.updateExtents(width / 2, height / 2);
}
public boolean render() {
if (dbImage == null) {
log.debug("dbImage is null, creating a new one");
if (panelWidth <= 0 || panelHeight <= 0) {
return false;
}
dbImage = createImage(panelWidth, panelHeight);
if (dbImage == null) {
log.error("dbImage is still null, ignoring render call");
return false;
}
dbg = (Graphics2D) dbImage.getGraphics();
dbg.setFont(new Font("Courier New", Font.PLAIN, 12));
}
dbg.setColor(Color.black);
dbg.fillRect(0, 0, panelWidth, panelHeight);
return true;
}
public void paintScreen() {
try {
Graphics g = this.getGraphics();
if ((g != null) && dbImage != null) {
g.drawImage(dbImage, 0, 0, null);
Toolkit.getDefaultToolkit().sync();
g.dispose();
}
} catch (AWTError e) {
log.error("Graphics context error", e);
}
}
}
| bsd-2-clause |