text
stringlengths 7
1.01M
|
|---|
/*
* Copyright 2015-2018 _floragunn_ 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.
*/
/*
* Portions Copyright 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://www.apache.org/licenses/LICENSE-2.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.amazon.opendistroforelasticsearch.security.action.configupdate;
import java.io.IOException;
import java.util.List;
import org.opensearch.action.FailedNodeException;
import org.opensearch.action.support.nodes.BaseNodesResponse;
import org.opensearch.cluster.ClusterName;
import org.opensearch.common.io.stream.StreamInput;
import org.opensearch.common.io.stream.StreamOutput;
public class ConfigUpdateResponse extends BaseNodesResponse<ConfigUpdateNodeResponse> {
public ConfigUpdateResponse(StreamInput in) throws IOException {
super(in);
}
public ConfigUpdateResponse(final ClusterName clusterName, List<ConfigUpdateNodeResponse> nodes, List<FailedNodeException> failures) {
super(clusterName, nodes, failures);
}
@Override
public List<ConfigUpdateNodeResponse> readNodesFrom(final StreamInput in) throws IOException {
return in.readList(ConfigUpdateNodeResponse::readNodeResponse);
}
@Override
public void writeNodesTo(final StreamOutput out, List<ConfigUpdateNodeResponse> nodes) throws IOException {
out.writeList(nodes);
}
}
|
package com.xdroid.rxjava.model;
/**
* 类描述:GitHub API 中的User
* 创建人:launcher.myemail@gmail.com
* 创建时间:16-1-24
* 备注:使用:http://www.jsonschema2pojo.org/这个网站就Json自动转换为POJO
*/
public class User {
public String login;
public Integer id;
public String avatarUrl;
public String gravatarId;
public String url;
public String htmlUrl;
public String followersUrl;
public String followingUrl;
public String gistsUrl;
public String starredUrl;
public String subscriptionsUrl;
public String organizationsUrl;
public String reposUrl;
public String eventsUrl;
public String receivedEventsUrl;
public String type;
public Boolean siteAdmin;
public String name;
public String company;
public String blog;
public String location;
public String email;
public Boolean hireable;
public Object bio;
public Integer publicRepos;
public Integer publicGists;
public Integer followers;
public Integer following;
public String createdAt;
public String updatedAt;
@Override
public String toString() {
return "User{" +
"login='" + login + '\'' +
", id=" + id +
", avatarUrl='" + avatarUrl + '\'' +
", gravatarId='" + gravatarId + '\'' +
", url='" + url + '\'' +
", htmlUrl='" + htmlUrl + '\'' +
", followersUrl='" + followersUrl + '\'' +
", followingUrl='" + followingUrl + '\'' +
", gistsUrl='" + gistsUrl + '\'' +
", starredUrl='" + starredUrl + '\'' +
", subscriptionsUrl='" + subscriptionsUrl + '\'' +
", organizationsUrl='" + organizationsUrl + '\'' +
", reposUrl='" + reposUrl + '\'' +
", eventsUrl='" + eventsUrl + '\'' +
", receivedEventsUrl='" + receivedEventsUrl + '\'' +
", type='" + type + '\'' +
", siteAdmin=" + siteAdmin +
", name='" + name + '\'' +
", company='" + company + '\'' +
", blog='" + blog + '\'' +
", location='" + location + '\'' +
", email='" + email + '\'' +
", hireable=" + hireable +
", bio=" + bio +
", publicRepos=" + publicRepos +
", publicGists=" + publicGists +
", followers=" + followers +
", following=" + following +
", createdAt='" + createdAt + '\'' +
", updatedAt='" + updatedAt + '\'' +
'}';
}
}
|
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.location;
import android.os.Bundle;
import android.os.Parcel;
import android.os.Parcelable;
import android.os.SystemClock;
import android.util.Printer;
import android.util.TimeUtils;
import java.text.DecimalFormat;
import java.util.StringTokenizer;
/**
* A data class representing a geographic location.
*
* <p>A location can consist of a latitude, longitude, timestamp,
* and other information such as bearing, altitude and velocity.
*
* <p>All locations generated by the {@link LocationManager} are
* guaranteed to have a valid latitude, longitude, and timestamp
* (both UTC time and elapsed real-time since boot), all other
* parameters are optional.
*/
public class Location implements Parcelable {
/**
* Constant used to specify formatting of a latitude or longitude
* in the form "[+-]DDD.DDDDD where D indicates degrees.
*/
public static final int FORMAT_DEGREES = 0;
/**
* Constant used to specify formatting of a latitude or longitude
* in the form "[+-]DDD:MM.MMMMM" where D indicates degrees and
* M indicates minutes of arc (1 minute = 1/60th of a degree).
*/
public static final int FORMAT_MINUTES = 1;
/**
* Constant used to specify formatting of a latitude or longitude
* in the form "DDD:MM:SS.SSSSS" where D indicates degrees, M
* indicates minutes of arc, and S indicates seconds of arc (1
* minute = 1/60th of a degree, 1 second = 1/3600th of a degree).
*/
public static final int FORMAT_SECONDS = 2;
/**
* Bundle key for a version of the location that has been fed through
* LocationFudger. Allows location providers to flag locations as being
* safe for use with ACCESS_COARSE_LOCATION permission.
*
* @hide
*/
public static final String EXTRA_COARSE_LOCATION = "coarseLocation";
/**
* Bundle key for a version of the location containing no GPS data.
* Allows location providers to flag locations as being safe to
* feed to LocationFudger.
*
* @hide
*/
public static final String EXTRA_NO_GPS_LOCATION = "noGPSLocation";
private String mProvider;
private long mTime = 0;
private long mElapsedRealtimeNanos = 0;
private double mLatitude = 0.0;
private double mLongitude = 0.0;
private boolean mHasAltitude = false;
private double mAltitude = 0.0f;
private boolean mHasSpeed = false;
private float mSpeed = 0.0f;
private boolean mHasBearing = false;
private float mBearing = 0.0f;
private boolean mHasAccuracy = false;
private float mAccuracy = 0.0f;
private Bundle mExtras = null;
private boolean mIsFromMockProvider = false;
// Cache the inputs and outputs of computeDistanceAndBearing
// so calls to distanceTo() and bearingTo() can share work
private double mLat1 = 0.0;
private double mLon1 = 0.0;
private double mLat2 = 0.0;
private double mLon2 = 0.0;
private float mDistance = 0.0f;
private float mInitialBearing = 0.0f;
// Scratchpad
private final float[] mResults = new float[2];
/**
* Construct a new Location with a named provider.
*
* <p>By default time, latitude and longitude are 0, and the location
* has no bearing, altitude, speed, accuracy or extras.
*
* @param provider the name of the provider that generated this location
*/
public Location(String provider) {
mProvider = provider;
}
/**
* Construct a new Location object that is copied from an existing one.
*/
public Location(Location l) {
set(l);
}
/**
* Sets the contents of the location to the values from the given location.
*/
public void set(Location l) {
mProvider = l.mProvider;
mTime = l.mTime;
mElapsedRealtimeNanos = l.mElapsedRealtimeNanos;
mLatitude = l.mLatitude;
mLongitude = l.mLongitude;
mHasAltitude = l.mHasAltitude;
mAltitude = l.mAltitude;
mHasSpeed = l.mHasSpeed;
mSpeed = l.mSpeed;
mHasBearing = l.mHasBearing;
mBearing = l.mBearing;
mHasAccuracy = l.mHasAccuracy;
mAccuracy = l.mAccuracy;
mExtras = (l.mExtras == null) ? null : new Bundle(l.mExtras);
mIsFromMockProvider = l.mIsFromMockProvider;
}
/**
* Clears the contents of the location.
*/
public void reset() {
mProvider = null;
mTime = 0;
mElapsedRealtimeNanos = 0;
mLatitude = 0;
mLongitude = 0;
mHasAltitude = false;
mAltitude = 0;
mHasSpeed = false;
mSpeed = 0;
mHasBearing = false;
mBearing = 0;
mHasAccuracy = false;
mAccuracy = 0;
mExtras = null;
mIsFromMockProvider = false;
}
/**
* Converts a coordinate to a String representation. The outputType
* may be one of FORMAT_DEGREES, FORMAT_MINUTES, or FORMAT_SECONDS.
* The coordinate must be a valid double between -180.0 and 180.0.
*
* @throws IllegalArgumentException if coordinate is less than
* -180.0, greater than 180.0, or is not a number.
* @throws IllegalArgumentException if outputType is not one of
* FORMAT_DEGREES, FORMAT_MINUTES, or FORMAT_SECONDS.
*/
public static String convert(double coordinate, int outputType) {
if (coordinate < -180.0 || coordinate > 180.0 ||
Double.isNaN(coordinate)) {
throw new IllegalArgumentException("coordinate=" + coordinate);
}
if ((outputType != FORMAT_DEGREES) &&
(outputType != FORMAT_MINUTES) &&
(outputType != FORMAT_SECONDS)) {
throw new IllegalArgumentException("outputType=" + outputType);
}
StringBuilder sb = new StringBuilder();
// Handle negative values
if (coordinate < 0) {
sb.append('-');
coordinate = -coordinate;
}
DecimalFormat df = new DecimalFormat("###.#####");
if (outputType == FORMAT_MINUTES || outputType == FORMAT_SECONDS) {
int degrees = (int) Math.floor(coordinate);
sb.append(degrees);
sb.append(':');
coordinate -= degrees;
coordinate *= 60.0;
if (outputType == FORMAT_SECONDS) {
int minutes = (int) Math.floor(coordinate);
sb.append(minutes);
sb.append(':');
coordinate -= minutes;
coordinate *= 60.0;
}
}
sb.append(df.format(coordinate));
return sb.toString();
}
/**
* Converts a String in one of the formats described by
* FORMAT_DEGREES, FORMAT_MINUTES, or FORMAT_SECONDS into a
* double.
*
* @throws NullPointerException if coordinate is null
* @throws IllegalArgumentException if the coordinate is not
* in one of the valid formats.
*/
public static double convert(String coordinate) {
// IllegalArgumentException if bad syntax
if (coordinate == null) {
throw new NullPointerException("coordinate");
}
boolean negative = false;
if (coordinate.charAt(0) == '-') {
coordinate = coordinate.substring(1);
negative = true;
}
StringTokenizer st = new StringTokenizer(coordinate, ":");
int tokens = st.countTokens();
if (tokens < 1) {
throw new IllegalArgumentException("coordinate=" + coordinate);
}
try {
String degrees = st.nextToken();
double val;
if (tokens == 1) {
val = Double.parseDouble(degrees);
return negative ? -val : val;
}
String minutes = st.nextToken();
int deg = Integer.parseInt(degrees);
double min;
double sec = 0.0;
if (st.hasMoreTokens()) {
min = Integer.parseInt(minutes);
String seconds = st.nextToken();
sec = Double.parseDouble(seconds);
} else {
min = Double.parseDouble(minutes);
}
boolean isNegative180 = negative && (deg == 180) &&
(min == 0) && (sec == 0);
// deg must be in [0, 179] except for the case of -180 degrees
if ((deg < 0.0) || (deg > 179 && !isNegative180)) {
throw new IllegalArgumentException("coordinate=" + coordinate);
}
if (min < 0 || min > 59) {
throw new IllegalArgumentException("coordinate=" +
coordinate);
}
if (sec < 0 || sec > 59) {
throw new IllegalArgumentException("coordinate=" +
coordinate);
}
val = deg*3600.0 + min*60.0 + sec;
val /= 3600.0;
return negative ? -val : val;
} catch (NumberFormatException nfe) {
throw new IllegalArgumentException("coordinate=" + coordinate);
}
}
private static void computeDistanceAndBearing(double lat1, double lon1,
double lat2, double lon2, float[] results) {
// Based on http://www.ngs.noaa.gov/PUBS_LIB/inverse.pdf
// using the "Inverse Formula" (section 4)
int MAXITERS = 20;
// Convert lat/long to radians
lat1 *= Math.PI / 180.0;
lat2 *= Math.PI / 180.0;
lon1 *= Math.PI / 180.0;
lon2 *= Math.PI / 180.0;
double a = 6378137.0; // WGS84 major axis
double b = 6356752.3142; // WGS84 semi-major axis
double f = (a - b) / a;
double aSqMinusBSqOverBSq = (a * a - b * b) / (b * b);
double L = lon2 - lon1;
double A = 0.0;
double U1 = Math.atan((1.0 - f) * Math.tan(lat1));
double U2 = Math.atan((1.0 - f) * Math.tan(lat2));
double cosU1 = Math.cos(U1);
double cosU2 = Math.cos(U2);
double sinU1 = Math.sin(U1);
double sinU2 = Math.sin(U2);
double cosU1cosU2 = cosU1 * cosU2;
double sinU1sinU2 = sinU1 * sinU2;
double sigma = 0.0;
double deltaSigma = 0.0;
double cosSqAlpha = 0.0;
double cos2SM = 0.0;
double cosSigma = 0.0;
double sinSigma = 0.0;
double cosLambda = 0.0;
double sinLambda = 0.0;
double lambda = L; // initial guess
for (int iter = 0; iter < MAXITERS; iter++) {
double lambdaOrig = lambda;
cosLambda = Math.cos(lambda);
sinLambda = Math.sin(lambda);
double t1 = cosU2 * sinLambda;
double t2 = cosU1 * sinU2 - sinU1 * cosU2 * cosLambda;
double sinSqSigma = t1 * t1 + t2 * t2; // (14)
sinSigma = Math.sqrt(sinSqSigma);
cosSigma = sinU1sinU2 + cosU1cosU2 * cosLambda; // (15)
sigma = Math.atan2(sinSigma, cosSigma); // (16)
double sinAlpha = (sinSigma == 0) ? 0.0 :
cosU1cosU2 * sinLambda / sinSigma; // (17)
cosSqAlpha = 1.0 - sinAlpha * sinAlpha;
cos2SM = (cosSqAlpha == 0) ? 0.0 :
cosSigma - 2.0 * sinU1sinU2 / cosSqAlpha; // (18)
double uSquared = cosSqAlpha * aSqMinusBSqOverBSq; // defn
A = 1 + (uSquared / 16384.0) * // (3)
(4096.0 + uSquared *
(-768 + uSquared * (320.0 - 175.0 * uSquared)));
double B = (uSquared / 1024.0) * // (4)
(256.0 + uSquared *
(-128.0 + uSquared * (74.0 - 47.0 * uSquared)));
double C = (f / 16.0) *
cosSqAlpha *
(4.0 + f * (4.0 - 3.0 * cosSqAlpha)); // (10)
double cos2SMSq = cos2SM * cos2SM;
deltaSigma = B * sinSigma * // (6)
(cos2SM + (B / 4.0) *
(cosSigma * (-1.0 + 2.0 * cos2SMSq) -
(B / 6.0) * cos2SM *
(-3.0 + 4.0 * sinSigma * sinSigma) *
(-3.0 + 4.0 * cos2SMSq)));
lambda = L +
(1.0 - C) * f * sinAlpha *
(sigma + C * sinSigma *
(cos2SM + C * cosSigma *
(-1.0 + 2.0 * cos2SM * cos2SM))); // (11)
double delta = (lambda - lambdaOrig) / lambda;
if (Math.abs(delta) < 1.0e-12) {
break;
}
}
float distance = (float) (b * A * (sigma - deltaSigma));
results[0] = distance;
if (results.length > 1) {
float initialBearing = (float) Math.atan2(cosU2 * sinLambda,
cosU1 * sinU2 - sinU1 * cosU2 * cosLambda);
initialBearing *= 180.0 / Math.PI;
results[1] = initialBearing;
if (results.length > 2) {
float finalBearing = (float) Math.atan2(cosU1 * sinLambda,
-sinU1 * cosU2 + cosU1 * sinU2 * cosLambda);
finalBearing *= 180.0 / Math.PI;
results[2] = finalBearing;
}
}
}
/**
* Computes the approximate distance in meters between two
* locations, and optionally the initial and final bearings of the
* shortest path between them. Distance and bearing are defined using the
* WGS84 ellipsoid.
*
* <p> The computed distance is stored in results[0]. If results has length
* 2 or greater, the initial bearing is stored in results[1]. If results has
* length 3 or greater, the final bearing is stored in results[2].
*
* @param startLatitude the starting latitude
* @param startLongitude the starting longitude
* @param endLatitude the ending latitude
* @param endLongitude the ending longitude
* @param results an array of floats to hold the results
*
* @throws IllegalArgumentException if results is null or has length < 1
*/
public static void distanceBetween(double startLatitude, double startLongitude,
double endLatitude, double endLongitude, float[] results) {
if (results == null || results.length < 1) {
throw new IllegalArgumentException("results is null or has length < 1");
}
computeDistanceAndBearing(startLatitude, startLongitude,
endLatitude, endLongitude, results);
}
/**
* Returns the approximate distance in meters between this
* location and the given location. Distance is defined using
* the WGS84 ellipsoid.
*
* @param dest the destination location
* @return the approximate distance in meters
*/
public float distanceTo(Location dest) {
// See if we already have the result
synchronized (mResults) {
if (mLatitude != mLat1 || mLongitude != mLon1 ||
dest.mLatitude != mLat2 || dest.mLongitude != mLon2) {
computeDistanceAndBearing(mLatitude, mLongitude,
dest.mLatitude, dest.mLongitude, mResults);
mLat1 = mLatitude;
mLon1 = mLongitude;
mLat2 = dest.mLatitude;
mLon2 = dest.mLongitude;
mDistance = mResults[0];
mInitialBearing = mResults[1];
}
return mDistance;
}
}
/**
* Returns the approximate initial bearing in degrees East of true
* North when traveling along the shortest path between this
* location and the given location. The shortest path is defined
* using the WGS84 ellipsoid. Locations that are (nearly)
* antipodal may produce meaningless results.
*
* @param dest the destination location
* @return the initial bearing in degrees
*/
public float bearingTo(Location dest) {
synchronized (mResults) {
// See if we already have the result
if (mLatitude != mLat1 || mLongitude != mLon1 ||
dest.mLatitude != mLat2 || dest.mLongitude != mLon2) {
computeDistanceAndBearing(mLatitude, mLongitude,
dest.mLatitude, dest.mLongitude, mResults);
mLat1 = mLatitude;
mLon1 = mLongitude;
mLat2 = dest.mLatitude;
mLon2 = dest.mLongitude;
mDistance = mResults[0];
mInitialBearing = mResults[1];
}
return mInitialBearing;
}
}
/**
* Returns the name of the provider that generated this fix.
*
* @return the provider, or null if it has not been set
*/
public String getProvider() {
return mProvider;
}
/**
* Sets the name of the provider that generated this fix.
*/
public void setProvider(String provider) {
mProvider = provider;
}
/**
* Return the UTC time of this fix, in milliseconds since January 1, 1970.
*
* <p>Note that the UTC time on a device is not monotonic: it
* can jump forwards or backwards unpredictably. So always use
* {@link #getElapsedRealtimeNanos} when calculating time deltas.
*
* <p>On the other hand, {@link #getTime} is useful for presenting
* a human readable time to the user, or for carefully comparing
* location fixes across reboot or across devices.
*
* <p>All locations generated by the {@link LocationManager}
* are guaranteed to have a valid UTC time, however remember that
* the system time may have changed since the location was generated.
*
* @return time of fix, in milliseconds since January 1, 1970.
*/
public long getTime() {
return mTime;
}
/**
* Set the UTC time of this fix, in milliseconds since January 1,
* 1970.
*
* @param time UTC time of this fix, in milliseconds since January 1, 1970
*/
public void setTime(long time) {
mTime = time;
}
/**
* Return the time of this fix, in elapsed real-time since system boot.
*
* <p>This value can be reliably compared to
* {@link android.os.SystemClock#elapsedRealtimeNanos},
* to calculate the age of a fix and to compare Location fixes. This
* is reliable because elapsed real-time is guaranteed monotonic for
* each system boot and continues to increment even when the system
* is in deep sleep (unlike {@link #getTime}.
*
* <p>All locations generated by the {@link LocationManager}
* are guaranteed to have a valid elapsed real-time.
*
* @return elapsed real-time of fix, in nanoseconds since system boot.
*/
public long getElapsedRealtimeNanos() {
return mElapsedRealtimeNanos;
}
/**
* Set the time of this fix, in elapsed real-time since system boot.
*
* @param time elapsed real-time of fix, in nanoseconds since system boot.
*/
public void setElapsedRealtimeNanos(long time) {
mElapsedRealtimeNanos = time;
}
/**
* Get the latitude, in degrees.
*
* <p>All locations generated by the {@link LocationManager}
* will have a valid latitude.
*/
public double getLatitude() {
return mLatitude;
}
/**
* Set the latitude, in degrees.
*/
public void setLatitude(double latitude) {
mLatitude = latitude;
}
/**
* Get the longitude, in degrees.
*
* <p>All locations generated by the {@link LocationManager}
* will have a valid longitude.
*/
public double getLongitude() {
return mLongitude;
}
/**
* Set the longitude, in degrees.
*/
public void setLongitude(double longitude) {
mLongitude = longitude;
}
/**
* True if this location has an altitude.
*/
public boolean hasAltitude() {
return mHasAltitude;
}
/**
* Get the altitude if available, in meters above sea level.
*
* <p>If this location does not have an altitude then 0.0 is returned.
*/
public double getAltitude() {
return mAltitude;
}
/**
* Set the altitude, in meters above sea level.
*
* <p>Following this call {@link #hasAltitude} will return true.
*/
public void setAltitude(double altitude) {
mAltitude = altitude;
mHasAltitude = true;
}
/**
* Remove the altitude from this location.
*
* <p>Following this call {@link #hasAltitude} will return false,
* and {@link #getAltitude} will return 0.0.
*/
public void removeAltitude() {
mAltitude = 0.0f;
mHasAltitude = false;
}
/**
* True if this location has a speed.
*/
public boolean hasSpeed() {
return mHasSpeed;
}
/**
* Get the speed if it is available, in meters/second over ground.
*
* <p>If this location does not have a speed then 0.0 is returned.
*/
public float getSpeed() {
return mSpeed;
}
/**
* Set the speed, in meters/second over ground.
*
* <p>Following this call {@link #hasSpeed} will return true.
*/
public void setSpeed(float speed) {
mSpeed = speed;
mHasSpeed = true;
}
/**
* Remove the speed from this location.
*
* <p>Following this call {@link #hasSpeed} will return false,
* and {@link #getSpeed} will return 0.0.
*/
public void removeSpeed() {
mSpeed = 0.0f;
mHasSpeed = false;
}
/**
* True if this location has a bearing.
*/
public boolean hasBearing() {
return mHasBearing;
}
/**
* Get the bearing, in degrees.
*
* <p>Bearing is the horizontal direction of travel of this device,
* and is not related to the device orientation. It is guaranteed to
* be in the range (0.0, 360.0] if the device has a bearing.
*
* <p>If this location does not have a bearing then 0.0 is returned.
*/
public float getBearing() {
return mBearing;
}
/**
* Set the bearing, in degrees.
*
* <p>Bearing is the horizontal direction of travel of this device,
* and is not related to the device orientation.
*
* <p>The input will be wrapped into the range (0.0, 360.0].
*/
public void setBearing(float bearing) {
while (bearing < 0.0f) {
bearing += 360.0f;
}
while (bearing >= 360.0f) {
bearing -= 360.0f;
}
mBearing = bearing;
mHasBearing = true;
}
/**
* Remove the bearing from this location.
*
* <p>Following this call {@link #hasBearing} will return false,
* and {@link #getBearing} will return 0.0.
*/
public void removeBearing() {
mBearing = 0.0f;
mHasBearing = false;
}
/**
* True if this location has an accuracy.
*
* <p>All locations generated by the {@link LocationManager} have an
* accuracy.
*/
public boolean hasAccuracy() {
return mHasAccuracy;
}
/**
* Get the estimated accuracy of this location, in meters.
*
* <p>We define accuracy as the radius of 68% confidence. In other
* words, if you draw a circle centered at this location's
* latitude and longitude, and with a radius equal to the accuracy,
* then there is a 68% probability that the true location is inside
* the circle.
*
* <p>In statistical terms, it is assumed that location errors
* are random with a normal distribution, so the 68% confidence circle
* represents one standard deviation. Note that in practice, location
* errors do not always follow such a simple distribution.
*
* <p>This accuracy estimation is only concerned with horizontal
* accuracy, and does not indicate the accuracy of bearing,
* velocity or altitude if those are included in this Location.
*
* <p>If this location does not have an accuracy, then 0.0 is returned.
* All locations generated by the {@link LocationManager} include
* an accuracy.
*/
public float getAccuracy() {
return mAccuracy;
}
/**
* Set the estimated accuracy of this location, meters.
*
* <p>See {@link #getAccuracy} for the definition of accuracy.
*
* <p>Following this call {@link #hasAccuracy} will return true.
*/
public void setAccuracy(float accuracy) {
mAccuracy = accuracy;
mHasAccuracy = true;
}
/**
* Remove the accuracy from this location.
*
* <p>Following this call {@link #hasAccuracy} will return false, and
* {@link #getAccuracy} will return 0.0.
*/
public void removeAccuracy() {
mAccuracy = 0.0f;
mHasAccuracy = false;
}
/**
* Return true if this Location object is complete.
*
* <p>A location object is currently considered complete if it has
* a valid provider, accuracy, wall-clock time and elapsed real-time.
*
* <p>All locations supplied by the {@link LocationManager} to
* applications must be complete.
*
* @see #makeComplete
* @hide
*/
public boolean isComplete() {
if (mProvider == null) return false;
if (!mHasAccuracy) return false;
if (mTime == 0) return false;
if (mElapsedRealtimeNanos == 0) return false;
return true;
}
/**
* Helper to fill incomplete fields.
*
* <p>Used to assist in backwards compatibility with
* Location objects received from applications.
*
* @see #isComplete
* @hide
*/
public void makeComplete() {
if (mProvider == null) mProvider = "?";
if (!mHasAccuracy) {
mHasAccuracy = true;
mAccuracy = 100.0f;
}
if (mTime == 0) mTime = System.currentTimeMillis();
if (mElapsedRealtimeNanos == 0) mElapsedRealtimeNanos = SystemClock.elapsedRealtimeNanos();
}
/**
* Returns additional provider-specific information about the
* location fix as a Bundle. The keys and values are determined
* by the provider. If no additional information is available,
* null is returned.
*
* <p> A number of common key/value pairs are listed
* below. Providers that use any of the keys on this list must
* provide the corresponding value as described below.
*
* <ul>
* <li> satellites - the number of satellites used to derive the fix
* </ul>
*/
public Bundle getExtras() {
return mExtras;
}
/**
* Sets the extra information associated with this fix to the
* given Bundle.
*/
public void setExtras(Bundle extras) {
mExtras = (extras == null) ? null : new Bundle(extras);
}
@Override
public String toString() {
StringBuilder s = new StringBuilder();
s.append("Location[");
s.append(mProvider);
s.append(String.format(" %.6f,%.6f", mLatitude, mLongitude));
if (mHasAccuracy) s.append(String.format(" acc=%.0f", mAccuracy));
else s.append(" acc=???");
if (mTime == 0) {
s.append(" t=?!?");
}
if (mElapsedRealtimeNanos == 0) {
s.append(" et=?!?");
} else {
s.append(" et=");
TimeUtils.formatDuration(mElapsedRealtimeNanos / 1000000L, s);
}
if (mHasAltitude) s.append(" alt=").append(mAltitude);
if (mHasSpeed) s.append(" vel=").append(mSpeed);
if (mHasBearing) s.append(" bear=").append(mBearing);
if (mIsFromMockProvider) s.append(" mock");
if (mExtras != null) {
s.append(" {").append(mExtras).append('}');
}
s.append(']');
return s.toString();
}
public void dump(Printer pw, String prefix) {
pw.println(prefix + toString());
}
public static final Parcelable.Creator<Location> CREATOR =
new Parcelable.Creator<Location>() {
@Override
public Location createFromParcel(Parcel in) {
String provider = in.readString();
Location l = new Location(provider);
l.mTime = in.readLong();
l.mElapsedRealtimeNanos = in.readLong();
l.mLatitude = in.readDouble();
l.mLongitude = in.readDouble();
l.mHasAltitude = in.readInt() != 0;
l.mAltitude = in.readDouble();
l.mHasSpeed = in.readInt() != 0;
l.mSpeed = in.readFloat();
l.mHasBearing = in.readInt() != 0;
l.mBearing = in.readFloat();
l.mHasAccuracy = in.readInt() != 0;
l.mAccuracy = in.readFloat();
l.mExtras = in.readBundle();
l.mIsFromMockProvider = in.readInt() != 0;
return l;
}
@Override
public Location[] newArray(int size) {
return new Location[size];
}
};
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel parcel, int flags) {
parcel.writeString(mProvider);
parcel.writeLong(mTime);
parcel.writeLong(mElapsedRealtimeNanos);
parcel.writeDouble(mLatitude);
parcel.writeDouble(mLongitude);
parcel.writeInt(mHasAltitude ? 1 : 0);
parcel.writeDouble(mAltitude);
parcel.writeInt(mHasSpeed ? 1 : 0);
parcel.writeFloat(mSpeed);
parcel.writeInt(mHasBearing ? 1 : 0);
parcel.writeFloat(mBearing);
parcel.writeInt(mHasAccuracy ? 1 : 0);
parcel.writeFloat(mAccuracy);
parcel.writeBundle(mExtras);
parcel.writeInt(mIsFromMockProvider? 1 : 0);
}
/**
* Returns one of the optional extra {@link Location}s that can be attached
* to this Location.
*
* @param key the key associated with the desired extra Location
* @return the extra Location, or null if unavailable
* @hide
*/
public Location getExtraLocation(String key) {
if (mExtras != null) {
Parcelable value = mExtras.getParcelable(key);
if (value instanceof Location) {
return (Location) value;
}
}
return null;
}
/**
* Attaches an extra {@link Location} to this Location.
*
* @param key the key associated with the Location extra
* @param location the Location to attach
* @hide
*/
public void setExtraLocation(String key, Location value) {
if (mExtras == null) {
mExtras = new Bundle();
}
mExtras.putParcelable(key, value);
}
/**
* Returns true if the Location came from a mock provider.
*
* @return true if this Location came from a mock provider, false otherwise
*/
public boolean isFromMockProvider() {
return mIsFromMockProvider;
}
/**
* Flag this Location as having come from a mock provider or not.
*
* @param isFromMockProvider true if this Location came from a mock provider, false otherwise
* @hide
*/
public void setIsFromMockProvider(boolean isFromMockProvider) {
mIsFromMockProvider = isFromMockProvider;
}
}
|
package com.github.amlcurran.showcaseview.targets;
import android.app.Activity;
import android.view.View;
import android.view.ViewParent;
/**
* Created by Alex on 27/10/13.
*/
class AppCompatReflector implements Reflector {
private Activity mActivity;
public AppCompatReflector(Activity activity) {
mActivity = activity;
}
@Override
public ViewParent getActionBarView() {
return getHomeButton().getParent().getParent();
}
@Override
public View getHomeButton() {
View homeButton = mActivity.findViewById(android.R.id.home);
if (homeButton != null) {
return homeButton;
}
int homeId = mActivity.getResources().getIdentifier("home", "id", mActivity.getPackageName());
homeButton = mActivity.findViewById(homeId);
if (homeButton == null) {
throw new RuntimeException(
"insertShowcaseViewWithType cannot be used when the theme " +
"has no ActionBar");
}
return homeButton;
}
@Override
public void showcaseActionItem(int itemId) {
}
}
|
package cc.sylar.elasticsearch.proxy.beans.search.request.fuction;
import cc.sylar.elasticsearch.proxy.beans.common.ScriptParamsConverter;
import com.sun.tools.javac.util.Assert;
import java.util.Map;
/**
* @author sylar
* @Description:
* @date 2020/5/4 11:08 下午
*/
public interface ScriptSetter {
/**
*
* @param parameterMap
* @return
*/
ScriptSetter parameter(Map<String, Object> parameterMap);
/**
*
* @param scriptParamsConverter
* @return
*/
default ScriptSetter parameter(ScriptParamsConverter scriptParamsConverter) {
Assert.checkNonNull(scriptParamsConverter, "ScriptParamsConverter must not be null!");
return this.parameter(scriptParamsConverter.get());
}
}
|
package com.lei.stu.jvm.abstracttest;
import java.lang.ref.WeakReference;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
/**
* @Description
* @Author leihaoyuan
* @Date 2020/12/11 13:17
*/
public abstract class AbstractClassTest {
private static final List<WeakReference<AbstractClassTest>> LISTENERS = Collections.synchronizedList(new LinkedList<>());
public AbstractClassTest(){
LISTENERS.add(new WeakReference<>(this));
}
public static void main(String[] args) {
System.out.println(LISTENERS.size());
}
private void test(){
System.out.println("test....");
}
abstract void aTtest();
}
|
/*
* 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.test.common.unit;
import org.elasticsearch.ElasticsearchParseException;
import org.elasticsearch.common.io.stream.BytesStreamOutput;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.unit.Fuzziness;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.testframework.ESTestCase;
import java.io.IOException;
import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;
import static org.hamcrest.CoreMatchers.anyOf;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.sameInstance;
public class FuzzinessTests extends ESTestCase {
public void testNumerics() {
String[] options = new String[]{"1.0", "1", "1.000000"};
assertThat(Fuzziness.build(randomFrom(options)).asFloat(), equalTo(1f));
}
public void testParseFromXContent() throws IOException {
final int iters = randomIntBetween(10, 50);
for (int i = 0; i < iters; i++) {
{
float floatValue = randomFloat();
XContentBuilder json = jsonBuilder().startObject()
.field(Fuzziness.X_FIELD_NAME, floatValue)
.endObject();
XContentParser parser = createParser(json);
assertThat(parser.nextToken(), equalTo(XContentParser.Token.START_OBJECT));
assertThat(parser.nextToken(), equalTo(XContentParser.Token.FIELD_NAME));
assertThat(parser.nextToken(), equalTo(XContentParser.Token.VALUE_NUMBER));
Fuzziness fuzziness = Fuzziness.parse(parser);
assertThat(fuzziness.asFloat(), equalTo(floatValue));
assertThat(parser.nextToken(), equalTo(XContentParser.Token.END_OBJECT));
}
{
Integer intValue = frequently() ? randomIntBetween(0, 2) : randomIntBetween(0, 100);
Float floatRep = randomFloat();
Number value = intValue;
if (randomBoolean()) {
value = new Float(floatRep += intValue);
}
XContentBuilder json = jsonBuilder().startObject()
.field(Fuzziness.X_FIELD_NAME, randomBoolean() ? value.toString() : value)
.endObject();
XContentParser parser = createParser(json);
assertThat(parser.nextToken(), equalTo(XContentParser.Token.START_OBJECT));
assertThat(parser.nextToken(), equalTo(XContentParser.Token.FIELD_NAME));
assertThat(parser.nextToken(), anyOf(equalTo(XContentParser.Token.VALUE_NUMBER), equalTo(XContentParser.Token.VALUE_STRING)));
Fuzziness fuzziness = Fuzziness.parse(parser);
if (value.intValue() >= 1) {
assertThat(fuzziness.asDistance(), equalTo(Math.min(2, value.intValue())));
}
assertThat(parser.nextToken(), equalTo(XContentParser.Token.END_OBJECT));
if (intValue.equals(value)) {
switch (intValue) {
case 1:
assertThat(fuzziness, sameInstance(Fuzziness.ONE));
break;
case 2:
assertThat(fuzziness, sameInstance(Fuzziness.TWO));
break;
case 0:
assertThat(fuzziness, sameInstance(Fuzziness.ZERO));
break;
default:
break;
}
}
}
{
XContentBuilder json;
boolean isDefaultAutoFuzzinessTested = randomBoolean();
if (isDefaultAutoFuzzinessTested) {
json = Fuzziness.AUTO.toXContent(jsonBuilder().startObject(), null).endObject();
} else {
String auto = randomBoolean() ? "AUTO" : "auto";
if (randomBoolean()) {
auto += ":" + randomIntBetween(1, 3) + "," + randomIntBetween(4, 10);
}
json = jsonBuilder().startObject()
.field(Fuzziness.X_FIELD_NAME, auto)
.endObject();
}
XContentParser parser = createParser(json);
assertThat(parser.nextToken(), equalTo(XContentParser.Token.START_OBJECT));
assertThat(parser.nextToken(), equalTo(XContentParser.Token.FIELD_NAME));
assertThat(parser.nextToken(), equalTo(XContentParser.Token.VALUE_STRING));
Fuzziness fuzziness = Fuzziness.parse(parser);
if (isDefaultAutoFuzzinessTested) {
assertThat(fuzziness, sameInstance(Fuzziness.AUTO));
}
assertThat(parser.nextToken(), equalTo(XContentParser.Token.END_OBJECT));
}
}
}
public void testAuto() {
assertThat(Fuzziness.AUTO.asFloat(), equalTo(1f));
}
public void testAsDistance() {
final int iters = randomIntBetween(10, 50);
for (int i = 0; i < iters; i++) {
Integer integer = Integer.valueOf(randomIntBetween(0, 10));
String value = "" + (randomBoolean() ? integer.intValue() : integer.floatValue());
assertThat(Fuzziness.build(value).asDistance(), equalTo(Math.min(2, integer.intValue())));
}
}
public void testSerialization() throws IOException {
Fuzziness fuzziness = Fuzziness.AUTO;
Fuzziness deserializedFuzziness = doSerializeRoundtrip(fuzziness);
assertEquals(fuzziness, deserializedFuzziness);
fuzziness = Fuzziness.fromEdits(randomIntBetween(0, 2));
deserializedFuzziness = doSerializeRoundtrip(fuzziness);
assertEquals(fuzziness, deserializedFuzziness);
}
public void testSerializationDefaultAuto() throws IOException {
Fuzziness fuzziness = Fuzziness.AUTO;
Fuzziness deserializedFuzziness = doSerializeRoundtrip(fuzziness);
assertEquals(fuzziness, deserializedFuzziness);
assertEquals(fuzziness.asFloat(), deserializedFuzziness.asFloat(), 0f);
}
public void testSerializationCustomAuto() throws IOException {
String auto = "AUTO:4,7";
XContentBuilder json = jsonBuilder().startObject()
.field(Fuzziness.X_FIELD_NAME, auto)
.endObject();
XContentParser parser = createParser(json);
assertThat(parser.nextToken(), equalTo(XContentParser.Token.START_OBJECT));
assertThat(parser.nextToken(), equalTo(XContentParser.Token.FIELD_NAME));
assertThat(parser.nextToken(), equalTo(XContentParser.Token.VALUE_STRING));
Fuzziness fuzziness = Fuzziness.parse(parser);
Fuzziness deserializedFuzziness = doSerializeRoundtrip(fuzziness);
assertEquals(fuzziness, deserializedFuzziness);
assertEquals(fuzziness.asString(), deserializedFuzziness.asString());
}
private static Fuzziness doSerializeRoundtrip(Fuzziness in) throws IOException {
BytesStreamOutput output = new BytesStreamOutput();
in.writeTo(output);
StreamInput streamInput = output.bytes().streamInput();
return new Fuzziness(streamInput);
}
}
|
/*
* Copyright (c) 2008-2021, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.jet.pipeline;
import com.hazelcast.config.Config;
import com.hazelcast.jet.JetInstance;
import com.hazelcast.jet.Traversers;
import com.hazelcast.jet.core.JetTestSupport;
import com.hazelcast.jet.pipeline.test.TestSources;
import com.hazelcast.test.HazelcastSerialClassRunner;
import com.hazelcast.test.annotation.NightlyTest;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import java.util.Map;
import java.util.Random;
import java.util.function.Function;
import static com.hazelcast.jet.Util.entry;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
@RunWith(HazelcastSerialClassRunner.class)
@Category(NightlyTest.class)
public class StatefulMappingStressTest extends JetTestSupport {
private static final Random RANDOM = new Random();
private static final long TTL = SECONDS.toMillis(2);
private static final String MAP_SINK_NAME = StatefulMappingStressTest.class.getSimpleName() + "_sink";
private JetInstance instance;
@Before
public void setup() {
instance = createJetMembers(new Config(), 2)[0];
}
@Test
public void mapStateful_stressTest() {
stressTest(
streamStageWithKey -> streamStageWithKey.mapStateful(TTL,
Object::new,
(state, key, input) -> {
return entry(0, 1);
},
(state, key, wm) -> {
return entry(1, 1);
}));
}
@Test
public void flatMapStateful_stressTest() {
stressTest(
streamStageWithKey -> streamStageWithKey.flatMapStateful(TTL,
Object::new,
(state, key, input) -> {
return Traversers.singleton(entry(0, 1));
},
(state, key, wm) -> {
return Traversers.singleton(entry(1, 1));
}));
}
private void stressTest(
Function<StreamStageWithKey<Integer, Integer>, StreamStage<Map.Entry<Integer, Integer>>> statefulFn
) {
int emitItemsCount = 2_000_000;
Pipeline p = Pipeline.create();
StreamStageWithKey<Integer, Integer> streamStageWithKey = p.readFrom(TestSources.itemStream(100_000))
.withIngestionTimestamps()
.filter(f -> f.sequence() < emitItemsCount)
.map(t -> RANDOM.nextInt(100_000))
.groupingKey(k -> k % 100_000);
StreamStage<Map.Entry<Integer, Integer>> statefulStage = statefulFn.apply(streamStageWithKey);
statefulStage.writeTo(Sinks.mapWithMerging(MAP_SINK_NAME, (oldValue, newValue) -> oldValue + newValue));
instance.newJob(p);
Map<Integer, Integer> map = instance.getMap(MAP_SINK_NAME);
assertTrueEventually(() -> {
assertNotNull(map.get(0));
assertNotNull(map.get(1));
assertEquals(emitItemsCount, map.get(0).intValue());
assertTrue(map.get(1) > 0);
});
}
}
|
package org.semanticweb.elk.owl.managers;
/*
* #%L
* ELK Reasoner
*
* $Id$
* $HeadURL$
* %%
* Copyright (C) 2011 Department of Computer Science, University of Oxford
* %%
* 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.semanticweb.elk.owl.interfaces.ElkObject;
/**
* An {@link ElkObjectRecycler} that does not recycle anything and simply
* returns the input {@link ElkObject}.
*
* @author Markus Kroetzsch
* @author "Yevgeny Kazakov"
*/
public class DummyElkObjectRecycler implements ElkObjectRecycler {
@Override
public ElkObject recycle(ElkObject object) {
return object;
}
}
|
import java.util.Comparator;
import java.util.PriorityQueue;
public class RunningMedian {
private PriorityQueue<Integer> maxHeap;
private PriorityQueue<Integer> minHeap;
public RunningMedian(int size) {
minHeap = new PriorityQueue<>(size / 2, Comparator.naturalOrder());
maxHeap = new PriorityQueue<>(size / 2, Comparator.reverseOrder());
}
public void add(int value) {
if (maxHeap.size() == minHeap.size()) {
if (minHeap.peek() != null && value > minHeap.peek()) {
maxHeap.offer(minHeap.poll());
minHeap.offer(value);
} else {
maxHeap.offer(value);
}
} else {
if (value < maxHeap.peek()) {
minHeap.offer(maxHeap.poll());
maxHeap.offer(value);
} else {
minHeap.offer(value);
}
}
}
public double getMedian() {
if (maxHeap.size() == 0) return 0.0;
if (minHeap.size() == maxHeap.size()) {
return ((double) minHeap.peek() + (double) maxHeap.peek()) / 2;
} else {
return (double) maxHeap.peek();
}
}
}
|
/*
* The MIT License (MIT)
*
* Copyright (c) 2020-2030 The XdagJ Developers
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/package io.xdag.rpc.jsonrpc;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonPropertyOrder({"jsonrpc", "id", "method", "result", "params", "error"})
public abstract class JsonRpcMessage {
private final JsonRpcVersion version;
public JsonRpcMessage(JsonRpcVersion version) {
this.version = verifyVersion(version);
}
@JsonProperty("jsonrpc")
@JsonInclude(JsonInclude.Include.ALWAYS)
public JsonRpcVersion getVersion() {
return version;
}
private static JsonRpcVersion verifyVersion(JsonRpcVersion version) {
if (version != JsonRpcVersion.V2_0) {
throw new IllegalArgumentException(
String.format("JSON-RPC version should always be %s, but was %s.", JsonRpcVersion.V2_0, version)
);
}
return version;
}
}
|
/*
* Copyright 2002-2020 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.xml.config;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import java.util.List;
import java.util.Locale;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.w3c.dom.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.SmartLifecycle;
import org.springframework.integration.MessageRejectedException;
import org.springframework.integration.endpoint.EventDrivenConsumer;
import org.springframework.integration.support.SmartLifecycleRoleController;
import org.springframework.integration.test.util.TestUtils;
import org.springframework.integration.xml.AggregatedXmlMessageValidationException;
import org.springframework.integration.xml.util.XmlTestUtil;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.PollableChannel;
import org.springframework.messaging.support.GenericMessage;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.util.MultiValueMap;
/**
* @author Jonas Partner
* @author Oleg Zhurakousky
* @author Gunnar Hillert
* @author Artem Bilan
* @author Gary Russell
*/
@ContextConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
@DirtiesContext
public class XmlPayloadValidatingFilterParserTests {
private Locale localeBeforeTest;
@Before
public void setUp() {
localeBeforeTest = Locale.getDefault();
Locale.setDefault(new Locale("en", "US"));
}
@After
public void tearDown() {
Locale.setDefault(localeBeforeTest);
}
public static final DocumentBuilderFactory DOCUMENT_BUILDER_FACTORY = DocumentBuilderFactory.newInstance();
static {
DOCUMENT_BUILDER_FACTORY.setNamespaceAware(true);
try {
DOCUMENT_BUILDER_FACTORY.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
DOCUMENT_BUILDER_FACTORY.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
}
catch (ParserConfigurationException e) {
throw new RuntimeException(e);
}
}
@Autowired
private ApplicationContext ac;
@Test
public void testParse() throws Exception {
EventDrivenConsumer consumer = (EventDrivenConsumer) ac.getBean("parseOnly");
assertThat(TestUtils.getPropertyValue(consumer, "handler.order")).isEqualTo(2);
assertThat(TestUtils.getPropertyValue(consumer, "handler.messagingTemplate.sendTimeout")).isEqualTo(123L);
assertThat(TestUtils.getPropertyValue(consumer, "phase")).isEqualTo(-1);
assertThat(TestUtils.getPropertyValue(consumer, "autoStartup", Boolean.class)).isFalse();
SmartLifecycleRoleController roleController = ac.getBean(SmartLifecycleRoleController.class);
@SuppressWarnings("unchecked")
List<SmartLifecycle> list = (List<SmartLifecycle>) TestUtils.getPropertyValue(roleController, "lifecycles",
MultiValueMap.class).get("foo");
assertThat(list).containsExactly((SmartLifecycle) consumer);
}
@Test
public void testValidMessage() throws Exception {
Message<String> docMessage =
new GenericMessage<>("<!DOCTYPE greeting SYSTEM \"greeting.dtd\"><greeting>hello</greeting>");
PollableChannel validChannel = this.ac.getBean("validOutputChannel", PollableChannel.class);
MessageChannel inputChannel = this.ac.getBean("inputChannelA", MessageChannel.class);
inputChannel.send(docMessage);
assertThat(validChannel.receive(100)).isNotNull();
}
@Test
public void testInvalidMessageWithDiscardChannel() throws Exception {
Document doc = XmlTestUtil.getDocumentForString("<greeting><other/></greeting>");
GenericMessage<Document> docMessage = new GenericMessage<Document>(doc);
PollableChannel validChannel = ac.getBean("validOutputChannel", PollableChannel.class);
PollableChannel invalidChannel = ac.getBean("invalidOutputChannel", PollableChannel.class);
MessageChannel inputChannel = ac.getBean("inputChannelA", MessageChannel.class);
inputChannel.send(docMessage);
assertThat(invalidChannel.receive(100)).isNotNull();
assertThat(validChannel.receive(100)).isNull();
}
@Test
public void testInvalidMessageWithThrowException() throws Exception {
Document doc = XmlTestUtil.getDocumentForString("<greeting ping=\"pong\"><other/></greeting>");
GenericMessage<Document> docMessage = new GenericMessage<Document>(doc);
MessageChannel inputChannel = ac.getBean("inputChannelB", MessageChannel.class);
try {
inputChannel.send(docMessage);
fail("MessageRejectedException expected");
}
catch (Exception e) {
assertThat(e).isInstanceOf(MessageRejectedException.class);
Throwable cause = e.getCause();
assertThat(cause).isInstanceOf(AggregatedXmlMessageValidationException.class);
assertThat(cause.getMessage())
.contains(
"Element 'greeting' is a simple type, so it must have no element information item [children].");
assertThat(cause.getMessage())
.contains("Element 'greeting' is a simple type, so it cannot have attributes,");
}
}
@Test
public void testValidMessageWithValidator() throws Exception {
Document doc = XmlTestUtil.getDocumentForString("<greeting>hello</greeting>");
GenericMessage<Document> docMessage = new GenericMessage<Document>(doc);
PollableChannel validChannel = ac.getBean("validOutputChannel", PollableChannel.class);
MessageChannel inputChannel = ac.getBean("inputChannelC", MessageChannel.class);
inputChannel.send(docMessage);
assertThat(validChannel.receive(100)).isNotNull();
}
@Test
public void testInvalidMessageWithValidatorAndDiscardChannel() throws Exception {
Document doc = XmlTestUtil.getDocumentForString("<greeting><other/></greeting>");
GenericMessage<Document> docMessage = new GenericMessage<Document>(doc);
PollableChannel invalidChannel = ac.getBean("invalidOutputChannel", PollableChannel.class);
MessageChannel inputChannel = ac.getBean("inputChannelC", MessageChannel.class);
inputChannel.send(docMessage);
assertThat(invalidChannel.receive(100)).isNotNull();
}
}
|
package com.pakio.loudsTrie;
import java.util.ArrayDeque;
import java.util.Map.Entry;
import java.util.Queue;
public class Converter {
/**
* convert tree to LOUDS
*/
public static LOUDS convert(Node rootNode) {
LOUDS louds = new LOUDS();
Queue<Node> queue = new ArrayDeque<>();
queue.add(rootNode);
while(!queue.isEmpty()) {
processQueue(queue, louds);
}
return louds;
}
public static void processQueue(Queue<Node> queue, LOUDS louds) {
Node node = queue.poll();
if (node.hasChild()) {
for(Entry<Character, Node> characterNodeMap : node.getChildNodes().entrySet()) {
queue.add(characterNodeMap.getValue());
louds.LBS.add(true);
louds.labels.add(characterNodeMap.getKey());
louds.isLeaf.add(characterNodeMap.getValue().isLeaf());
}
}
// end of node
louds.LBS.add(false);
louds.isLeaf.add(false);
}
}
|
import tio.*;
class opgave13_3 {
public static void main(String[] args) {
int input[] = new int [6];
boolean []generated = new boolean[42];
boolean []inputTable = new boolean[42];
int i, amount = 0, simAmount, n = 0, k;
double profit = 0;
simAmount = Console.in.readInt();
while(profit <= 0){
//for(k = 0; k < 3120; k++) {
generated = genLotto();
amount = 0;
for(k = 0; k < simAmount; k++) {
inputTable = genLotto();
for (i = 0; i < generated.length; i++) {
if ((generated[i] == true) && (inputTable[i] == true)) {
amount++;
}
}
}
if(amount == 3)
profit += 2.5;
if(amount == 4)
profit += 35;
if(amount == 5)
profit += 850;
if(amount == 6)
profit += 1000000;
//}
n++;
profit -= (simAmount);
System.out.println(profit);
}
System.out.println(n);
}
static boolean[] genLotto() {
boolean []generated = new boolean [42];
int i, amount = 0;
int randomNum;
while (amount != 6) {
randomNum = (int)(Math.random() * 42.0);
if (generated[randomNum] != true) {
generated[randomNum] = true;
amount++;
}
}
return(generated);
}
}
|
package org.bouncycastle.jcajce.provider;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Writer;
import java.security.Provider;
import java.security.cert.CertPath;
import java.security.cert.Certificate;
import java.security.cert.CertificateEncodingException;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import javax.security.auth.x500.X500Principal;
import org.bouncycastle.asn1.ASN1Encodable;
import org.bouncycastle.asn1.ASN1EncodableVector;
import org.bouncycastle.asn1.ASN1Encoding;
import org.bouncycastle.asn1.ASN1InputStream;
import org.bouncycastle.asn1.ASN1Integer;
import org.bouncycastle.asn1.ASN1Primitive;
import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.asn1.DERSequence;
import org.bouncycastle.asn1.DERSet;
import org.bouncycastle.asn1.pkcs.ContentInfo;
import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers;
import org.bouncycastle.asn1.pkcs.SignedData;
import org.bouncycastle.util.io.pem.PemObject;
import org.bouncycastle.util.io.pem.PemWriter;
/**
* CertPath implementation for X.509 certificates.
* <br />
**/
class PKIXCertPath
extends CertPath
{
static final List certPathEncodings;
static
{
List encodings = new ArrayList();
encodings.add("PkiPath");
encodings.add("PEM");
encodings.add("PKCS7");
certPathEncodings = Collections.unmodifiableList(encodings);
}
private final Provider fipsProvider;
private List certificates;
/**
* @param certs
*/
private List sortCerts(
List certs)
{
if (certs.size() < 2)
{
return certs;
}
X500Principal issuer = ((X509Certificate)certs.get(0)).getIssuerX500Principal();
boolean okay = true;
for (int i = 1; i != certs.size(); i++)
{
X509Certificate cert = (X509Certificate)certs.get(i);
if (issuer.equals(cert.getSubjectX500Principal()))
{
issuer = ((X509Certificate)certs.get(i)).getIssuerX500Principal();
}
else
{
okay = false;
break;
}
}
if (okay)
{
return certs;
}
// find end-entity cert
List retList = new ArrayList(certs.size());
List orig = new ArrayList(certs);
for (int i = 0; i < certs.size(); i++)
{
X509Certificate cert = (X509Certificate)certs.get(i);
boolean found = false;
X500Principal subject = cert.getSubjectX500Principal();
for (int j = 0; j != certs.size(); j++)
{
X509Certificate c = (X509Certificate)certs.get(j);
if (c.getIssuerX500Principal().equals(subject))
{
found = true;
break;
}
}
if (!found)
{
retList.add(cert);
certs.remove(i);
}
}
// can only have one end entity cert - something's wrong, give up.
if (retList.size() > 1)
{
return orig;
}
for (int i = 0; i != retList.size(); i++)
{
issuer = ((X509Certificate)retList.get(i)).getIssuerX500Principal();
for (int j = 0; j < certs.size(); j++)
{
X509Certificate c = (X509Certificate)certs.get(j);
if (issuer.equals(c.getSubjectX500Principal()))
{
retList.add(c);
certs.remove(j);
break;
}
}
}
// make sure all certificates are accounted for.
if (certs.size() > 0)
{
return orig;
}
return retList;
}
PKIXCertPath(Provider fipsProvider, List certificates)
{
super("X.509");
this.fipsProvider = fipsProvider;
this.certificates = sortCerts(new ArrayList(certificates));
}
/**
* Creates a CertPath of the specified type.
* This constructor is protected because most users should use
* a CertificateFactory to create CertPaths.
**/
PKIXCertPath(
Provider fipsProvider,
InputStream inStream,
String encoding)
throws CertificateException
{
super("X.509");
this.fipsProvider = fipsProvider;
try
{
if (encoding.equalsIgnoreCase("PkiPath"))
{
ASN1InputStream derInStream = new ASN1InputStream(inStream);
ASN1Primitive derObject = derInStream.readObject();
if (!(derObject instanceof ASN1Sequence))
{
throw new CertificateException("input stream does not contain a ASN1 SEQUENCE while reading PkiPath encoded data to load CertPath");
}
Enumeration e = ((ASN1Sequence)derObject).getObjects();
certificates = new ArrayList();
CertificateFactory certFactory = CertificateFactory.getInstance("X.509", fipsProvider);
while (e.hasMoreElements())
{
ASN1Encodable element = (ASN1Encodable)e.nextElement();
byte[] encoded = element.toASN1Primitive().getEncoded(ASN1Encoding.DER);
certificates.add(0, certFactory.generateCertificate(
new ByteArrayInputStream(encoded)));
}
}
else if (encoding.equalsIgnoreCase("PKCS7") || encoding.equalsIgnoreCase("PEM"))
{
inStream = new BufferedInputStream(inStream);
certificates = new ArrayList();
CertificateFactory certFactory= CertificateFactory.getInstance("X.509", fipsProvider);
Certificate cert;
while (inStream.available() > 0)
{
certificates.add(certFactory.generateCertificate(inStream));
}
}
else
{
throw new CertificateException("unsupported encoding: " + encoding);
}
}
catch (IOException ex)
{
throw new CertificateException("IOException throw while decoding CertPath:\n" + ex.toString());
}
this.certificates = sortCerts(certificates);
}
/**
* Returns an iteration of the encodings supported by this
* certification path, with the default encoding
* first. Attempts to modify the returned Iterator via its
* remove method result in an UnsupportedOperationException.
*
* @return an Iterator over the names of the supported encodings (as Strings)
**/
public Iterator getEncodings()
{
return certPathEncodings.iterator();
}
/**
* Returns the encoded form of this certification path, using
* the default encoding.
*
* @return the encoded bytes
* @exception java.security.cert.CertificateEncodingException if an encoding error occurs
**/
public byte[] getEncoded()
throws CertificateEncodingException
{
Iterator iter = getEncodings();
if (iter.hasNext())
{
Object enc = iter.next();
if (enc instanceof String)
{
return getEncoded((String)enc);
}
}
return null;
}
/**
* Returns the encoded form of this certification path, using
* the specified encoding.
*
* @param encoding the name of the encoding to use
* @return the encoded bytes
* @exception java.security.cert.CertificateEncodingException if an encoding error
* occurs or the encoding requested is not supported
*
**/
public byte[] getEncoded(String encoding)
throws CertificateEncodingException
{
if (encoding.equalsIgnoreCase("PkiPath"))
{
ASN1EncodableVector v = new ASN1EncodableVector();
ListIterator iter = certificates.listIterator(certificates.size());
while (iter.hasPrevious())
{
v.add(toASN1Object((X509Certificate)iter.previous()));
}
return toDEREncoded(new DERSequence(v));
}
else if (encoding.equalsIgnoreCase("PKCS7"))
{
ContentInfo encInfo = new ContentInfo(PKCSObjectIdentifiers.data, null);
ASN1EncodableVector v = new ASN1EncodableVector();
for (int i = 0; i != certificates.size(); i++)
{
v.add(toASN1Object((X509Certificate)certificates.get(i)));
}
SignedData sd = new SignedData(
new ASN1Integer(1),
new DERSet(),
encInfo,
new DERSet(v),
null,
new DERSet());
return toDEREncoded(new ContentInfo(
PKCSObjectIdentifiers.signedData, sd));
}
else if (encoding.equalsIgnoreCase("PEM"))
{
ByteArrayOutputStream bOut = new ByteArrayOutputStream();
PemWriter pWrt = new PemWriter(new ByteArrayWriter(bOut));
try
{
for (int i = 0; i != certificates.size(); i++)
{
pWrt.writeObject(new PemObject("CERTIFICATE", ((X509Certificate)certificates.get(i)).getEncoded()));
}
pWrt.close();
}
catch (Exception e)
{
throw new CertificateEncodingException("can't encode certificate for PEM encoded path");
}
return bOut.toByteArray();
}
else
{
throw new CertificateEncodingException("unsupported encoding: " + encoding);
}
}
/**
* Returns the list of certificates in this certification
* path. The List returned must be immutable and thread-safe.
*
* @return an immutable List of Certificates (may be empty, but not null)
**/
public List getCertificates()
{
return Collections.unmodifiableList(new ArrayList(certificates));
}
/**
* Return a DERObject containing the encoded certificate.
*
* @param cert the X509Certificate object to be encoded
*
* @return the DERObject
**/
private ASN1Primitive toASN1Object(
X509Certificate cert)
throws CertificateEncodingException
{
try
{
return ASN1Primitive.fromByteArray(cert.getEncoded());
}
catch (Exception e)
{
throw new CertificateEncodingException("Exception while encoding certificate: " + e.toString());
}
}
private byte[] toDEREncoded(ASN1Encodable obj)
throws CertificateEncodingException
{
try
{
return obj.toASN1Primitive().getEncoded(ASN1Encoding.DER);
}
catch (IOException e)
{
throw new CertificateEncodingException("Exception thrown: " + e);
}
}
private class ByteArrayWriter
extends Writer
{
private final ByteArrayOutputStream bOut;
ByteArrayWriter(ByteArrayOutputStream bOut)
{
this.bOut = bOut;
}
@Override
public void write(char[] chars, int offSet, int length)
throws IOException
{
for (int i = offSet; i != offSet + length; i++)
{
bOut.write(chars[i]);
}
}
@Override
public void flush()
throws IOException
{
bOut.flush();
}
@Override
public void close()
throws IOException
{
bOut.close();
}
}
}
|
package infobip.api.model.omni;
/**
* This is a generated class and is not intended for modification!
*/
public class Error {
private Integer groupId;
private String groupName;
private Integer id;
private String name;
private String description;
private Boolean permanent;
public Error() {
}
public Integer getGroupId() {
return this.groupId;
}
public Error setGroupId(Integer groupId) {
this.groupId = groupId;
return this;
}
public String getGroupName() {
return this.groupName;
}
public Error setGroupName(String groupName) {
this.groupName = groupName;
return this;
}
public Integer getId() {
return this.id;
}
public Error setId(Integer id) {
this.id = id;
return this;
}
public String getName() {
return this.name;
}
public Error setName(String name) {
this.name = name;
return this;
}
public String getDescription() {
return this.description;
}
public Error setDescription(String description) {
this.description = description;
return this;
}
public Boolean getPermanent() {
return this.permanent;
}
public Error setPermanent(Boolean permanent) {
this.permanent = permanent;
return this;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
Error o = (Error)obj;
if (this.groupId == null) {
if (o.groupId != null){
return false;
}
} else if (!this.groupId.equals(o.groupId)) {
return false;
}
if (this.groupName == null) {
if (o.groupName != null){
return false;
}
} else if (!this.groupName.equals(o.groupName)) {
return false;
}
if (this.id == null) {
if (o.id != null){
return false;
}
} else if (!this.id.equals(o.id)) {
return false;
}
if (this.name == null) {
if (o.name != null){
return false;
}
} else if (!this.name.equals(o.name)) {
return false;
}
if (this.description == null) {
if (o.description != null){
return false;
}
} else if (!this.description.equals(o.description)) {
return false;
}
if (this.permanent == null) {
if (o.permanent != null){
return false;
}
} else if (!this.permanent.equals(o.permanent)) {
return false;
}
return true;
}
@Override
public String toString() {
return "Error{" +
"groupId='" + groupId + "'" +
", groupName='" + groupName + "'" +
", id='" + id + "'" +
", name='" + name + "'" +
", description='" + description + "'" +
", permanent='" + permanent + "'" +
'}';
}
}
|
package uk.nhs.adaptors.gp2gp.gpc;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.experimental.SuperBuilder;
import lombok.extern.jackson.Jacksonized;
import org.apache.commons.lang3.StringUtils;
import uk.nhs.adaptors.gp2gp.common.task.TaskType;
import uk.nhs.adaptors.gp2gp.ehr.DocumentTaskDefinition;
import static uk.nhs.adaptors.gp2gp.common.task.TaskType.GET_GPC_DOCUMENT;
/**
* Task definition for downloading binaries from GCP
*/
@Jacksonized
@SuperBuilder
@Getter
@EqualsAndHashCode(callSuper = true)
public class GetGpcDocumentTaskDefinition extends DocumentTaskDefinition {
private static final String PATH_DELIMITER = "/";
/**
* URl pointing to the FHIR Binary resource hosted by GPC
*/
private final String accessDocumentUrl;
@Override
public TaskType getTaskType() {
return GET_GPC_DOCUMENT;
}
public static String extractIdFromUrl(String url) {
return StringUtils.substring(url, StringUtils.lastIndexOf(url, PATH_DELIMITER) + 1);
}
}
|
package ru.job4j.tracker;
import org.junit.Test;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.util.StringJoiner;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
public class ShowAllItemsTest {
@Test
public void whenCheckOutput() {
ByteArrayOutputStream out = new ByteArrayOutputStream();
PrintStream def = System.out;
System.setOut(new PrintStream(out));
Tracker tracker = new Tracker();
Item item = new Item("fix bug");
tracker.add(item);
ShowAllItems show = new ShowAllItems();
show.execute(new StubInput(new String[]{}), tracker);
String expect = new StringJoiner(System.lineSeparator(), "", System.lineSeparator())
.add("Name: " + item.getName() + " Id: " + item.getId())
.toString();
assertThat(new String(out.toByteArray()), is(expect));
System.setOut(def);
}
}
|
package net.somethingdreadful.MAL.dialog;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import net.somethingdreadful.MAL.DetailView;
import net.somethingdreadful.MAL.R;
import net.somethingdreadful.MAL.SearchActivity;
import net.somethingdreadful.MAL.api.MALApi;
public class SearchIdDialogFragment extends DialogFragment {
private int query;
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
query = Integer.parseInt(((SearchActivity) activity).query);
}
@Override
public AlertDialog onCreateDialog(Bundle state) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(R.string.dialog_title_id_search);
builder.setMessage(R.string.dialog_message_id_search);
builder.setPositiveButton(R.string.dialog_label_anime, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent startDetails = new Intent(getActivity(), DetailView.class);
startDetails.putExtra("recordID", query);
startDetails.putExtra("recordType", MALApi.ListType.ANIME);
startActivity(startDetails);
dismiss();
getActivity().finish();
}
});
builder.setNeutralButton(R.string.dialog_label_cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dismiss();
getActivity().finish();
}
});
builder.setNegativeButton(R.string.dialog_label_manga, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent startDetails = new Intent(getActivity(), DetailView.class);
startDetails.putExtra("recordID", query);
startDetails.putExtra("recordType", MALApi.ListType.MANGA);
startActivity(startDetails);
dismiss();
getActivity().finish();
}
});
return builder.create();
}
}
|
package com.kangec.client.view.common;
import javafx.scene.Cursor;
import javafx.scene.Parent;
import javafx.scene.control.ListView;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;
/**
* @Author Ardien
* @Date 9/22/2020 7:17 PM
* @Email ardien@126.com
* @Version 1.0
**/
public abstract class UIBinding extends Stage {
protected Parent root;
private double xOffset;
private double yOffset;
/**
* FXML属性绑定
* @param id 控件id
* @param clazz 控件类型
* @param <T> 控件类型
* @return 类型实例
*/
public <T> T binding(String id, Class<T> clazz) {
return (T) root.lookup("#" + id);
}
/**
* 清除所有选定索引的选择
* @param views ListView视图
*/
public void clearViews(ListView<Pane>... views) {
for (ListView<Pane> listView : views) {
listView.getSelectionModel().clearSelection();
}
}
/**
* 窗体移动
*/
public void move() {
root.setOnMousePressed(event -> {
xOffset = getX() - event.getScreenX();
yOffset = getY() - event.getScreenY();
root.setCursor(Cursor.CLOSED_HAND);
});
root.setOnMouseDragged(event -> {
setX(event.getScreenX() + xOffset);
setY(event.getScreenY() + yOffset);
});
root.setOnMouseReleased(event -> {
root.setCursor(Cursor.DEFAULT);
});
}
/**
* 初始化视图
*/
public abstract void initView();
/**
* 初始化事件
*/
//public abstract void initEventDefine();
}
|
/* file: CpuTypeEnable.java */
/*******************************************************************************
* Copyright 2014-2017 Intel Corporation
*
* 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.
*******************************************************************************/
/**
* @ingroup services
* @{
*/
package com.intel.daal.services;
/**
* <a name="DAAL-CLASS-SERVICES__CPUTYPEENABLE"></a>
* @brief CPU types
*/
public final class CpuTypeEnable{
private int _value;
/**
* Constructs the CPU type object using the provided value
* @param value Value corresponding to the CPU type object
*/
public CpuTypeEnable(int value) {
_value = value;
}
/**
* Returns the value corresponding to the CPU type object
* @return Value corresponding to the CPU type object
*/
public int getValue() {
return _value;
}
private static final int _cpu_default = 0;
private static final int _avx512_mic = 1;
private static final int _avx512 = 2;
private static final int _avx512_mic_e1 = 4;
public static final CpuTypeEnable cpu_default = new CpuTypeEnable(_cpu_default); /*!< Default processor type */
public static final CpuTypeEnable avx512_mic = new CpuTypeEnable(_avx512_mic); /*!< Intel(R) Xeon Phi(TM) processors/coprocessors based on Intel(R) Advanced Vector Extensions 512 (Intel(R) AVX-512) */
public static final CpuTypeEnable avx512 = new CpuTypeEnable(_avx512); /*!< Intel(R) Xeon(R) processors based on Intel(R) Advanced Vector Extensions 512 (Intel(R) AVX-512) */
public static final CpuTypeEnable avx512_mic_e1 = new CpuTypeEnable(_avx512_mic_e1); /*!< Intel(R) Xeon Phi(TM) processors based on Intel(R) Advanced Vector Extensions 512 (Intel(R) AVX-512) with support of AVX512_4FMAPS and AVX512_4VNNIW instruction groups */
}
/** @} */
|
package com.cloud.gateway;
import com.cloud.common.cache.annotation.EnableProCache;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
/**
* 网关模块
* @author Aijm
* @since 2019/5/8
*/
@EnableDiscoveryClient
@SpringBootApplication
@EnableProCache
public class CloudGatewayApplication {
public static void main(String[] args) {
SpringApplication.run(CloudGatewayApplication.class, args);
}
}
|
/**
* Copyright 2011-2019 Asakusa Framework Team.
*
* 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.asakusafw.vocabulary.model;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Annotation for joined models.
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Joined {
/**
* Each source term using join.
*/
Term[] terms();
/**
* Source term.
*/
@Target({ })
public @interface Term {
/**
* The class of source model.
*/
Class<?> source();
/**
* The mapping specifications from source properties to destination properties.
*/
Mapping[] mappings();
/**
* Shuffling specification.
* <p>
* The all properties must be declared in the joined model.
* </p>
*/
Key shuffle();
}
/**
* Property mapping.
*/
@Target({ })
public @interface Mapping {
/**
* The property name of source property in the source model.
*/
String source();
/**
* The property name of destination property in the joined model.
*/
String destination();
}
}
|
package com.microsoft.bingads.v11.api.test.entities.ad_group_product_partition.write;
import com.microsoft.bingads.v11.api.test.entities.ad_group_product_partition.BulkAdGroupProductPartitionTest;
import com.microsoft.bingads.v11.bulk.entities.BulkAdGroupProductPartition;
import com.microsoft.bingads.v11.campaignmanagement.AdGroupCriterion;
import com.microsoft.bingads.v11.campaignmanagement.BiddableAdGroupCriterion;
import com.microsoft.bingads.v11.campaignmanagement.NegativeAdGroupCriterion;
import com.microsoft.bingads.v11.campaignmanagement.ProductPartition;
import com.microsoft.bingads.internal.functionalinterfaces.BiConsumer;
import org.junit.Test;
import org.junit.runners.Parameterized;
import java.util.Arrays;
import java.util.Collection;
public class WriteParentCriterionIdTest extends BulkAdGroupProductPartitionTest {
@Parameterized.Parameter(value = 1)
public Long propertyValue;
@Parameterized.Parameters
public static Collection<Object[]> data() {
return Arrays.asList(
new Object[][]{
{"123", 123L},
{"9223372036854775807", 9223372036854775807L},
{null, null}
}
);
}
@Test
public void testWriteExcluded() {
testWriteProperty(
"Parent Criterion Id",
datum,
propertyValue,
new BiConsumer<BulkAdGroupProductPartition, Long>() {
@Override
public void accept(BulkAdGroupProductPartition c, Long v) {
ProductPartition criterion = new ProductPartition();
AdGroupCriterion adGroupCriterion = new NegativeAdGroupCriterion();
adGroupCriterion.setCriterion(criterion);
c.setAdGroupCriterion(adGroupCriterion);
criterion.setParentCriterionId(v);
}
}
);
}
@Test
public void testWriteNotExcluded() {
testWriteProperty(
"Parent Criterion Id",
datum,
propertyValue,
new BiConsumer<BulkAdGroupProductPartition, Long>() {
@Override
public void accept(BulkAdGroupProductPartition c, Long v) {
ProductPartition criterion = new ProductPartition();
AdGroupCriterion adGroupCriterion = new BiddableAdGroupCriterion();
adGroupCriterion.setCriterion(criterion);
c.setAdGroupCriterion(adGroupCriterion);
criterion.setParentCriterionId(v);
}
}
);
}
}
|
package org.checkerframework.framework.type;
// The imports from com.sun are all @jdk.Exported and therefore somewhat safe to use.
// Try to avoid using non-@jdk.Exported classes.
import com.sun.source.tree.AnnotationTree;
import com.sun.source.tree.AssignmentTree;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.CompilationUnitTree;
import com.sun.source.tree.ConditionalExpressionTree;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.IdentifierTree;
import com.sun.source.tree.LambdaExpressionTree;
import com.sun.source.tree.MemberReferenceTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.NewArrayTree;
import com.sun.source.tree.NewClassTree;
import com.sun.source.tree.ReturnTree;
import com.sun.source.tree.Tree;
import com.sun.source.tree.Tree.Kind;
import com.sun.source.tree.TypeCastTree;
import com.sun.source.tree.VariableTree;
import com.sun.source.util.TreePath;
import com.sun.source.util.Trees;
import com.sun.tools.javac.code.Type;
import java.lang.annotation.Annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Target;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.annotation.processing.ProcessingEnvironment;
import javax.lang.model.element.AnnotationMirror;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.Name;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.type.DeclaredType;
import javax.lang.model.type.IntersectionType;
import javax.lang.model.type.PrimitiveType;
import javax.lang.model.type.TypeKind;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.type.TypeVariable;
import javax.lang.model.type.WildcardType;
import javax.lang.model.util.Elements;
import javax.lang.model.util.Types;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.checkerframework.common.basetype.BaseTypeChecker;
import org.checkerframework.common.basetype.BaseTypeVisitor;
import org.checkerframework.common.reflection.DefaultReflectionResolver;
import org.checkerframework.common.reflection.MethodValAnnotatedTypeFactory;
import org.checkerframework.common.reflection.MethodValChecker;
import org.checkerframework.common.reflection.ReflectionResolver;
import org.checkerframework.common.wholeprograminference.WholeProgramInference;
import org.checkerframework.common.wholeprograminference.WholeProgramInferenceScenes;
import org.checkerframework.dataflow.qual.SideEffectFree;
import org.checkerframework.framework.qual.FieldInvariant;
import org.checkerframework.framework.qual.FromStubFile;
import org.checkerframework.framework.qual.InheritedAnnotation;
import org.checkerframework.framework.qual.PolymorphicQualifier;
import org.checkerframework.framework.qual.SubtypeOf;
import org.checkerframework.framework.source.Result;
import org.checkerframework.framework.source.SourceChecker;
import org.checkerframework.framework.stub.StubTypes;
import org.checkerframework.framework.type.AnnotatedTypeMirror.AnnotatedArrayType;
import org.checkerframework.framework.type.AnnotatedTypeMirror.AnnotatedDeclaredType;
import org.checkerframework.framework.type.AnnotatedTypeMirror.AnnotatedExecutableType;
import org.checkerframework.framework.type.AnnotatedTypeMirror.AnnotatedIntersectionType;
import org.checkerframework.framework.type.AnnotatedTypeMirror.AnnotatedNullType;
import org.checkerframework.framework.type.AnnotatedTypeMirror.AnnotatedPrimitiveType;
import org.checkerframework.framework.type.AnnotatedTypeMirror.AnnotatedTypeVariable;
import org.checkerframework.framework.type.AnnotatedTypeMirror.AnnotatedWildcardType;
import org.checkerframework.framework.util.AnnotatedTypes;
import org.checkerframework.framework.util.AnnotationFormatter;
import org.checkerframework.framework.util.CFContext;
import org.checkerframework.framework.util.DefaultAnnotationFormatter;
import org.checkerframework.framework.util.FieldInvariants;
import org.checkerframework.framework.util.GraphQualifierHierarchy;
import org.checkerframework.framework.util.MultiGraphQualifierHierarchy;
import org.checkerframework.framework.util.MultiGraphQualifierHierarchy.MultiGraphFactory;
import org.checkerframework.framework.util.TreePathCacher;
import org.checkerframework.framework.util.typeinference.DefaultTypeArgumentInference;
import org.checkerframework.framework.util.typeinference.TypeArgInferenceUtil;
import org.checkerframework.framework.util.typeinference.TypeArgumentInference;
import org.checkerframework.javacutil.AnnotationBuilder;
import org.checkerframework.javacutil.AnnotationProvider;
import org.checkerframework.javacutil.AnnotationUtils;
import org.checkerframework.javacutil.BugInCF;
import org.checkerframework.javacutil.CollectionUtils;
import org.checkerframework.javacutil.ElementUtils;
import org.checkerframework.javacutil.Pair;
import org.checkerframework.javacutil.TreeUtils;
import org.checkerframework.javacutil.TypesUtils;
import org.checkerframework.javacutil.UserError;
import org.checkerframework.javacutil.trees.DetachedVarSymbol;
/**
* The methods of this class take an element or AST node, and return the annotated type as an {@link
* AnnotatedTypeMirror}. The methods are:
*
* <ul>
* <li>{@link #getAnnotatedType(ClassTree)}
* <li>{@link #getAnnotatedType(MethodTree)}
* <li>{@link #getAnnotatedType(Tree)}
* <li>{@link #getAnnotatedTypeFromTypeTree(Tree)}
* <li>{@link #getAnnotatedType(TypeElement)}
* <li>{@link #getAnnotatedType(ExecutableElement)}
* <li>{@link #getAnnotatedType(Element)}
* </ul>
*
* This implementation only adds qualifiers explicitly specified by the programmer. Subclasses
* override {@link #addComputedTypeAnnotations} to add defaults, flow-sensitive refinement, and
* type-system-specific rules.
*
* <p>Unless otherwise indicated, each public method in this class returns a "fully annotated" type,
* which is one that has an annotation in all positions.
*
* <p>Type system checker writers may need to subclass this class, to add default qualifiers
* according to the type system semantics. Subclasses should especially override {@link
* #addComputedTypeAnnotations(Element, AnnotatedTypeMirror)} and {@link
* #addComputedTypeAnnotations(Tree, AnnotatedTypeMirror)} to handle default annotations. (Also,
* {@link #addDefaultAnnotations(AnnotatedTypeMirror)} adds annotations, but that method is a
* workaround for <a href="https://github.com/typetools/checker-framework/issues/979">Issue
* 979</a>.)
*
* @checker_framework.manual #creating-a-checker How to write a checker plug-in
*/
public class AnnotatedTypeFactory implements AnnotationProvider {
/** The {@link Trees} instance to use for tree node path finding. */
protected final Trees trees;
/** Optional! The AST of the source file being operated on. */
// TODO: when should root be null? What are the use cases?
// None of the existing test checkers has a null root.
// Should not be modified between calls to "visit".
protected @Nullable CompilationUnitTree root;
/** The processing environment to use for accessing compiler internals. */
protected final ProcessingEnvironment processingEnv;
/** Utility class for working with {@link Element}s. */
protected final Elements elements;
/** Utility class for working with {@link TypeMirror}s. */
public final Types types;
/** The state of the visitor. */
protected final VisitorState visitorState;
/**
* ===== postInit initialized fields ==== Note: qualHierarchy and typeHierarchy are both
* initialized in the postInit.
*
* @see #postInit() This means, they cannot be final and cannot be referred to in any subclass
* constructor or method until after postInit is called
*/
/** Represent the annotation relations. */
protected QualifierHierarchy qualHierarchy;
/** Represent the type relations. */
protected TypeHierarchy typeHierarchy;
/** performs whole program inference. */
private WholeProgramInference wholeProgramInference;
/**
* This formatter is used for converting AnnotatedTypeMirrors to Strings. This formatter will be
* used by all AnnotatedTypeMirrors created by this factory in their toString methods.
*/
protected final AnnotatedTypeFormatter typeFormatter;
/**
* Annotation formatter is used to format AnnotationMirrors. It is primarily used by
* SourceChecker when generating error messages.
*/
private final AnnotationFormatter annotationFormatter;
/** Holds the qualifier upper bounds for type uses. */
protected QualifierUpperBounds qualifierUpperBounds;
/**
* Provides utility method to substitute arguments for their type variables. Field should be
* final, but can only be set in postInit, because subtypes might need other state to be
* initialized first.
*/
protected TypeVariableSubstitutor typeVarSubstitutor;
/** Provides utility method to infer type arguments. */
protected TypeArgumentInference typeArgumentInference;
/**
* Caches the supported type qualifier classes. Call {@link #getSupportedTypeQualifiers()}
* instead of using this field directly, as it may not have been initialized.
*/
private final Set<Class<? extends Annotation>> supportedQuals;
/**
* Caches the fully-qualified names of the classes in {@link #supportedQuals}. Call {@link
* #getSupportedTypeQualifierNames()} instead of using this field directly, as it may not have
* been initialized.
*/
private final Set<String> supportedQualNames;
/** Parses stub files and stores annotations from stub files. */
public final StubTypes stubTypes;
/**
* A cache used to store elements whose declaration annotations have already been stored by
* calling the method {@link #getDeclAnnotations(Element)}.
*/
private final Map<Element, Set<AnnotationMirror>> cacheDeclAnnos;
/**
* A set containing declaration annotations that should be inherited. A declaration annotation
* will be inherited if it is in this set, or if it has the
* meta-annotation @InheritedAnnotation.
*/
private final Set<AnnotationMirror> inheritedAnnotations =
AnnotationUtils.createAnnotationSet();
/** The checker to use for option handling and resource management. */
protected final BaseTypeChecker checker;
/** Map keys are canonical names of aliased annotations. */
private final Map<String, Alias> aliases = new HashMap<>();
/**
* Information about one annotation alias.
*
* <p>The information is either an AnotationMirror that can be used directly, or information for
* a builder (name and fields not to copy); see checkRep.
*/
private static class Alias {
/** The canonical annotation (or null if copyElements == true). */
AnnotationMirror canonical;
/** Whether elements should be copied over when translating to the canonical annotation. */
boolean copyElements;
/** The canonical annotation name (or null if copyElements == false). */
String canonicalName;
/** Which elements should not be copied over (or null if copyElements == false). */
String[] ignorableElements;
/**
* Create an Alias with the given components.
*
* @param aliasName the alias name; only used for debugging
* @param canonical the canonical annotation
* @param copyElements whether elements should be copied over when translating to the
* canonical annotation
* @param ignorableElements elements that should not be copied over
*/
Alias(
String aliasName,
AnnotationMirror canonical,
boolean copyElements,
String canonicalName,
String[] ignorableElements) {
this.canonical = canonical;
this.copyElements = copyElements;
this.canonicalName = canonicalName;
this.ignorableElements = ignorableElements;
checkRep(aliasName);
}
/**
* Throw an exception if this object is malformed.
*
* @param aliasName the alias name; only used for diagnostic messages
*/
void checkRep(String aliasName) {
if (copyElements) {
if (!(canonical == null && canonicalName != null && ignorableElements != null)) {
throw new BugInCF(
"Bad Alias for %s: [canonical=%s] copyElements=%s canonicalName=%s ignorableElements=%s",
aliasName, canonical, copyElements, canonicalName, ignorableElements);
}
} else {
if (!(canonical != null && canonicalName == null && ignorableElements == null)) {
throw new BugInCF(
"Bad Alias for %s: canonical=%s copyElements=%s [canonicalName=%s ignorableElements=%s]",
aliasName, canonical, copyElements, canonicalName, ignorableElements);
}
}
}
}
/**
* A map from the class of an annotation to the set of classes for annotations with the same
* meaning, as well as the annotation mirror that should be used.
*/
private final Map<
Class<? extends Annotation>,
Pair<AnnotationMirror, Set<Class<? extends Annotation>>>>
declAliases = new HashMap<>();
/** Unique ID counter; for debugging purposes. */
private static int uidCounter = 0;
/** Unique ID of the current object; for debugging purposes. */
public final int uid;
/**
* Object that is used to resolve reflective method calls, if reflection resolution is turned
* on.
*/
protected ReflectionResolver reflectionResolver;
/** AnnotationClassLoader used to load type annotation classes via reflective lookup. */
protected AnnotationClassLoader loader;
/** Indicates that the whole-program inference is on. */
private final boolean infer;
/**
* Should results be cached? This means that ATM.deepCopy() will be called. ATM.deepCopy() used
* to (and perhaps still does) side effect the ATM being copied. So setting this to false is not
* equivalent to setting shouldReadCache to false.
*/
public boolean shouldCache;
/** Size of LRU cache if one isn't specified using the atfCacheSize option. */
private static final int DEFAULT_CACHE_SIZE = 300;
/** Mapping from a Tree to its annotated type; defaults have been applied. */
private final Map<Tree, AnnotatedTypeMirror> classAndMethodTreeCache;
/**
* Mapping from an expression tree to its annotated type; before defaults are applied, just what
* the programmer wrote.
*/
protected final Map<Tree, AnnotatedTypeMirror> fromExpressionTreeCache;
/**
* Mapping from a member tree to its annotated type; before defaults are applied, just what the
* programmer wrote.
*/
protected final Map<Tree, AnnotatedTypeMirror> fromMemberTreeCache;
/**
* Mapping from a type tree to its annotated type; before defaults are applied, just what the
* programmer wrote.
*/
protected final Map<Tree, AnnotatedTypeMirror> fromTypeTreeCache;
/**
* Mapping from an Element to its annotated type; before defaults are applied, just what the
* programmer wrote.
*/
private final Map<Element, AnnotatedTypeMirror> elementCache;
/** Mapping from an Element to the source Tree of the declaration. */
private final Map<Element, Tree> elementToTreeCache;
/** Mapping from a Tree to its TreePath. Shared between all instances. */
private final TreePathCacher treePathCache;
/** Mapping from CFG generated trees to their enclosing elements. */
private final Map<Tree, Element> artificialTreeToEnclosingElementMap;
/**
* Whether to ignore uninferred type arguments. This is a temporary flag to work around Issue
* 979.
*/
public final boolean ignoreUninferredTypeArguments;
/** The Object.getClass method. */
protected final ExecutableElement objectGetClass;
/** Size of the annotationClassNames cache. */
private static final int ANNOTATION_CACHE_SIZE = 500;
/** Maps classes representing AnnotationMirrors to their canonical names. */
private final Map<Class<? extends Annotation>, String> annotationClassNames;
/**
* Constructs a factory from the given {@link ProcessingEnvironment} instance and syntax tree
* root. (These parameters are required so that the factory may conduct the appropriate
* annotation-gathering analyses on certain tree types.)
*
* <p>Root can be {@code null} if the factory does not operate on trees.
*
* <p>A subclass must call postInit at the end of its constructor. postInit must be the last
* call in the constructor or else types from stub files may not be created as expected.
*
* @param checker the {@link SourceChecker} to which this factory belongs
* @throws IllegalArgumentException if either argument is {@code null}
*/
public AnnotatedTypeFactory(BaseTypeChecker checker) {
uid = ++uidCounter;
this.processingEnv = checker.getProcessingEnvironment();
// this.root = root;
this.checker = checker;
this.trees = Trees.instance(processingEnv);
this.elements = processingEnv.getElementUtils();
this.types = processingEnv.getTypeUtils();
this.visitorState = new VisitorState();
this.supportedQuals = new HashSet<>();
this.supportedQualNames = new HashSet<>();
this.stubTypes = new StubTypes(this);
this.cacheDeclAnnos = new HashMap<>();
this.artificialTreeToEnclosingElementMap = new HashMap<>();
// get the shared instance from the checker
this.treePathCache = checker.getTreePathCacher();
this.shouldCache = !checker.hasOption("atfDoNotCache");
if (shouldCache) {
int cacheSize = getCacheSize();
this.classAndMethodTreeCache = CollectionUtils.createLRUCache(cacheSize);
this.fromExpressionTreeCache = CollectionUtils.createLRUCache(cacheSize);
this.fromMemberTreeCache = CollectionUtils.createLRUCache(cacheSize);
this.fromTypeTreeCache = CollectionUtils.createLRUCache(cacheSize);
this.elementCache = CollectionUtils.createLRUCache(cacheSize);
this.elementToTreeCache = CollectionUtils.createLRUCache(cacheSize);
this.annotationClassNames =
Collections.synchronizedMap(
CollectionUtils.createLRUCache(ANNOTATION_CACHE_SIZE));
} else {
this.classAndMethodTreeCache = null;
this.fromExpressionTreeCache = null;
this.fromMemberTreeCache = null;
this.fromTypeTreeCache = null;
this.elementCache = null;
this.elementToTreeCache = null;
this.annotationClassNames = null;
}
this.typeFormatter = createAnnotatedTypeFormatter();
this.annotationFormatter = createAnnotationFormatter();
infer = checker.hasOption("infer");
if (infer) {
checkInvalidOptionsInferSignatures();
wholeProgramInference =
new WholeProgramInferenceScenes(
!"NullnessAnnotatedTypeFactory"
.equals(this.getClass().getSimpleName()));
}
ignoreUninferredTypeArguments = !checker.hasOption("conservativeUninferredTypeArguments");
objectGetClass = TreeUtils.getMethod("java.lang.Object", "getClass", 0, processingEnv);
}
/**
* @throws BugInCF If supportedQuals is empty or if any of the support qualifiers has a @Target
* meta-annotation that contain something besides TYPE_USE or TYPE_PARAMETER. (@Target({})
* is allowed.)
*/
private void checkSupportedQuals() {
if (supportedQuals.isEmpty()) {
// This is throwing a CF bug, but it could also be a bug in the checker rather than in
// the framework itself.
throw new BugInCF("Found no supported qualifiers.");
}
for (Class<? extends Annotation> annotationClass : supportedQuals) {
// Check @Target values
ElementType[] elements = annotationClass.getAnnotation(Target.class).value();
List<ElementType> otherElementTypes = new ArrayList<>();
for (ElementType element : elements) {
if (!(element == ElementType.TYPE_USE || element == ElementType.TYPE_PARAMETER)) {
// if there's an ElementType with an enumerated value of something other
// than TYPE_USE or TYPE_PARAMETER then it isn't a valid qualifier
otherElementTypes.add(element);
}
}
if (!otherElementTypes.isEmpty()) {
StringBuilder buf =
new StringBuilder("The @Target meta-annotation on type qualifier ");
buf.append(annotationClass.toString());
buf.append(" must not contain ");
for (int i = 0; i < otherElementTypes.size(); i++) {
if (i == 1 && otherElementTypes.size() == 2) {
buf.append(" or ");
} else if (i == otherElementTypes.size() - 1) {
buf.append(", or ");
} else if (i != 0) {
buf.append(", ");
}
buf.append(otherElementTypes.get(i));
}
buf.append(".");
throw new BugInCF(buf.toString());
}
}
}
/**
* This method is called only when {@code -Ainfer} is passed as an option. It checks if another
* option that should not occur simultaneously with the whole-program inference is also passed
* as argument, and aborts the process if that is the case. For example, the whole-program
* inference process was not designed to work with unchecked code defaults.
*
* <p>Subclasses may override this method to add more options.
*/
protected void checkInvalidOptionsInferSignatures() {
// See Issue 683
// https://github.com/typetools/checker-framework/issues/683
if (checker.useUncheckedCodeDefault("source")
|| checker.useUncheckedCodeDefault("bytecode")) {
throw new UserError(
"The option -Ainfer cannot be"
+ " used together with unchecked code defaults.");
}
}
/**
* Actions that logically belong in the constructor, but need to run after the subclass
* constructor has completed. In particular, parseStubFiles() may try to do type resolution with
* this AnnotatedTypeFactory.
*/
protected void postInit() {
this.qualHierarchy = createQualifierHierarchy();
if (qualHierarchy == null) {
throw new BugInCF("AnnotatedTypeFactory with null qualifier hierarchy not supported.");
}
this.typeHierarchy = createTypeHierarchy();
this.typeVarSubstitutor = createTypeVariableSubstitutor();
this.typeArgumentInference = createTypeArgumentInference();
this.qualifierUpperBounds = createQualifierUpperBounds();
// TODO: is this the best location for declaring this alias?
addAliasedDeclAnnotation(
org.jmlspecs.annotation.Pure.class,
org.checkerframework.dataflow.qual.Pure.class,
AnnotationBuilder.fromClass(
elements, org.checkerframework.dataflow.qual.Pure.class));
addInheritedAnnotation(
AnnotationBuilder.fromClass(
elements, org.checkerframework.dataflow.qual.Pure.class));
addInheritedAnnotation(
AnnotationBuilder.fromClass(
elements, org.checkerframework.dataflow.qual.SideEffectFree.class));
addInheritedAnnotation(
AnnotationBuilder.fromClass(
elements, org.checkerframework.dataflow.qual.Deterministic.class));
addInheritedAnnotation(
AnnotationBuilder.fromClass(
elements, org.checkerframework.dataflow.qual.TerminatesExecution.class));
initializeReflectionResolution();
if (this.getClass() == AnnotatedTypeFactory.class) {
this.parseStubFiles();
}
}
/** Creates {@link QualifierUpperBounds} for this type factory. */
protected QualifierUpperBounds createQualifierUpperBounds() {
return new QualifierUpperBounds(this);
}
/** Returns the WholeProgramInference instance. */
public WholeProgramInference getWholeProgramInference() {
return wholeProgramInference;
}
protected void initializeReflectionResolution() {
if (checker.shouldResolveReflection()) {
boolean debug = "debug".equals(checker.getOption("resolveReflection"));
MethodValChecker methodValChecker = checker.getSubchecker(MethodValChecker.class);
assert methodValChecker != null
: "AnnotatedTypeFactory: reflection resolution was requested, but MethodValChecker isn't a subchecker.";
MethodValAnnotatedTypeFactory methodValATF =
(MethodValAnnotatedTypeFactory) methodValChecker.getAnnotationProvider();
reflectionResolver = new DefaultReflectionResolver(checker, methodValATF, debug);
}
}
/**
* Set the CompilationUnitTree that should be used.
*
* @param root the new compilation unit to use
*/
// What's a better name? Maybe "reset" or "restart"?
public void setRoot(@Nullable CompilationUnitTree root) {
this.root = root;
// Do not clear here. Only the primary checker should clear this cache.
// treePathCache.clear();
artificialTreeToEnclosingElementMap.clear();
if (shouldCache) {
// Clear the caches with trees because once the compilation unit changes,
// the trees may be modified and lose type arguments.
elementToTreeCache.clear();
fromExpressionTreeCache.clear();
fromMemberTreeCache.clear();
fromTypeTreeCache.clear();
classAndMethodTreeCache.clear();
// There is no need to clear the following cache, it is limited by cache size and it
// contents won't change between compilation units.
// elementCache.clear();
}
}
@SideEffectFree
@Override
public String toString() {
return getClass().getSimpleName() + "#" + uid;
}
/** Factory method to easily change what Factory is used to create a QualifierHierarchy. */
protected MultiGraphQualifierHierarchy.MultiGraphFactory createQualifierHierarchyFactory() {
return new MultiGraphQualifierHierarchy.MultiGraphFactory(this);
}
/**
* Factory method to easily change what QualifierHierarchy is created. Needs to be public only
* because the GraphFactory must be able to call this method. No external use of this method is
* necessary.
*/
public QualifierHierarchy createQualifierHierarchy(MultiGraphFactory factory) {
return new GraphQualifierHierarchy(factory, null);
}
/**
* Returns the type qualifier hierarchy graph to be used by this processor.
*
* <p>The implementation builds the type qualifier hierarchy for the {@link
* #getSupportedTypeQualifiers()} using the meta-annotations found in them. The current
* implementation returns an instance of {@code GraphQualifierHierarchy}.
*
* <p>Subclasses may override this method to express any relationships that cannot be inferred
* using meta-annotations (e.g. due to lack of meta-annotations).
*
* @return an annotation relation tree representing the supported qualifiers
*/
protected QualifierHierarchy createQualifierHierarchy() {
Set<Class<? extends Annotation>> supportedTypeQualifiers = getSupportedTypeQualifiers();
MultiGraphQualifierHierarchy.MultiGraphFactory factory =
this.createQualifierHierarchyFactory();
return createQualifierHierarchy(elements, supportedTypeQualifiers, factory);
}
/**
* Returns the type qualifier hierarchy graph for a given set of type qualifiers and a factory.
*
* <p>The implementation builds the type qualifier hierarchy for the {@code
* supportedTypeQualifiers}. The current implementation returns an instance of {@code
* GraphQualifierHierarchy}.
*
* @param elements the element utilities to use
* @param supportedTypeQualifiers the type qualifiers for this type system
* @param factory the type factory for this type system
* @return an annotation relation tree representing the supported qualifiers
*/
protected static QualifierHierarchy createQualifierHierarchy(
Elements elements,
Set<Class<? extends Annotation>> supportedTypeQualifiers,
MultiGraphFactory factory) {
for (Class<? extends Annotation> typeQualifier : supportedTypeQualifiers) {
AnnotationMirror typeQualifierAnno =
AnnotationBuilder.fromClass(elements, typeQualifier);
factory.addQualifier(typeQualifierAnno);
// Polymorphic qualifiers can't declare their supertypes.
// An error is raised if one is present.
if (typeQualifier.getAnnotation(PolymorphicQualifier.class) != null) {
if (typeQualifier.getAnnotation(SubtypeOf.class) != null) {
// This is currently not supported. At some point we might add
// polymorphic qualifiers with upper and lower bounds.
throw new BugInCF(
"AnnotatedTypeFactory: "
+ typeQualifier
+ " is polymorphic and specifies super qualifiers. "
+ "Remove the @org.checkerframework.framework.qual.SubtypeOf or @org.checkerframework.framework.qual.PolymorphicQualifier annotation from it.");
}
continue;
}
if (typeQualifier.getAnnotation(SubtypeOf.class) == null) {
throw new BugInCF(
"AnnotatedTypeFactory: %s does not specify its super qualifiers.%n"
+ "Add an @org.checkerframework.framework.qual.SubtypeOf annotation to it,%n"
+ "or if it is an alias, exclude it from `createSupportedTypeQualifiers()`.%n",
typeQualifier);
}
Class<? extends Annotation>[] superQualifiers =
typeQualifier.getAnnotation(SubtypeOf.class).value();
for (Class<? extends Annotation> superQualifier : superQualifiers) {
if (!supportedTypeQualifiers.contains(superQualifier)) {
throw new BugInCF(
"Found unsupported qualifier in SubTypeOf: %s on qualifier: %s",
superQualifier.getCanonicalName(), typeQualifier.getCanonicalName());
}
AnnotationMirror superAnno = AnnotationBuilder.fromClass(elements, superQualifier);
factory.addSubtype(typeQualifierAnno, superAnno);
}
}
QualifierHierarchy hierarchy = factory.build();
if (!hierarchy.isValid()) {
throw new BugInCF(
"AnnotatedTypeFactory: invalid qualifier hierarchy: "
+ hierarchy.getClass()
+ " "
+ hierarchy);
}
return hierarchy;
}
/**
* Returns the type qualifier hierarchy graph to be used by this processor.
*
* @see #createQualifierHierarchy()
* @return the {@link QualifierHierarchy} for this checker
*/
public final QualifierHierarchy getQualifierHierarchy() {
// if (qualHierarchy == null)
// qualHierarchy = createQualifierHierarchy();
return qualHierarchy;
}
/**
* Creates the type subtyping checker using the current type qualifier hierarchy.
*
* <p>Subclasses may override this method to specify new type-checking rules beyond the typical
* java subtyping rules.
*
* @return the type relations class to check type subtyping
*/
protected TypeHierarchy createTypeHierarchy() {
return new DefaultTypeHierarchy(
checker,
getQualifierHierarchy(),
checker.getBooleanOption("ignoreRawTypeArguments", true),
checker.hasOption("invariantArrays"));
}
public final TypeHierarchy getTypeHierarchy() {
return typeHierarchy;
}
/**
* TypeVariableSubstitutor provides a method to replace type parameters with their arguments.
*/
protected TypeVariableSubstitutor createTypeVariableSubstitutor() {
return new TypeVariableSubstitutor();
}
public TypeVariableSubstitutor getTypeVarSubstitutor() {
return typeVarSubstitutor;
}
/**
* TypeArgumentInference infers the method type arguments when they are not explicitly written.
*/
protected TypeArgumentInference createTypeArgumentInference() {
return new DefaultTypeArgumentInference(this);
}
public TypeArgumentInference getTypeArgumentInference() {
return typeArgumentInference;
}
/**
* Factory method to easily change what {@link AnnotationClassLoader} is created to load type
* annotation classes. Subclasses can override this method and return a custom
* AnnotationClassLoader subclass to customize loading logic.
*/
protected AnnotationClassLoader createAnnotationClassLoader() {
return new AnnotationClassLoader(checker);
}
/**
* Returns a mutable set of annotation classes that are supported by a checker.
*
* <p>Subclasses may override this method to return a mutable set of their supported type
* qualifiers through one of the 5 approaches shown below.
*
* <p>Subclasses should not call this method; they should call {@link
* #getSupportedTypeQualifiers} instead.
*
* <p>By default, a checker supports all annotations located in a subdirectory called {@literal
* qual} that's located in the same directory as the checker. Note that only annotations defined
* with the {@code @Target({ElementType.TYPE_USE})} meta-annotation (and optionally with the
* additional value of {@code ElementType.TYPE_PARAMETER}, but no other {@code ElementType}
* values) are automatically considered as supported annotations.
*
* <p>To support a different set of annotations than those in the {@literal qual} subdirectory,
* or that have other {@code ElementType} values, see examples below.
*
* <p>In total, there are 5 ways to indicate annotations that are supported by a checker:
*
* <ol>
* <li>Only support annotations located in a checker's {@literal qual} directory:
* <p>This is the default behavior. Simply place those annotations within the {@literal
* qual} directory.
* <li>Support annotations located in a checker's {@literal qual} directory and a list of
* other annotations:
* <p>Place those annotations within the {@literal qual} directory, and override {@link
* #createSupportedTypeQualifiers()} by calling {@link
* #getBundledTypeQualifiers(Class...)} with a varargs parameter list of the other
* annotations. Code example:
* <pre>
* {@code @Override protected Set<Class<? extends Annotation>> createSupportedTypeQualifiers() {
* return getBundledTypeQualifiers(Regex.class, PartialRegex.class, RegexBottom.class, UnknownRegex.class);
* } }
* </pre>
* <li>Supporting only annotations that are explicitly listed: Override {@link
* #createSupportedTypeQualifiers()} and return a mutable set of the supported
* annotations. Code example:
* <pre>
* {@code @Override protected Set<Class<? extends Annotation>> createSupportedTypeQualifiers() {
* return new HashSet<Class<? extends Annotation>>(
* Arrays.asList(A.class, B.class));
* } }
* </pre>
* The set of qualifiers returned by {@link #createSupportedTypeQualifiers()} must be a
* fresh, mutable set. The methods {@link #getBundledTypeQualifiers(Class...)} must return
* a fresh, mutable set
* </ol>
*
* @return the type qualifiers supported this processor, or an empty set if none
*/
protected Set<Class<? extends Annotation>> createSupportedTypeQualifiers() {
return getBundledTypeQualifiers();
}
/**
* Loads all annotations contained in the qual directory of a checker via reflection; if a
* polymorphic type qualifier exists, and an explicit array of annotations to the set of
* annotation classes.
*
* <p>This method can be called in the overridden versions of {@link
* #createSupportedTypeQualifiers()} in each checker.
*
* @param explicitlyListedAnnotations a varargs array of explicitly listed annotation classes to
* be added to the returned set. For example, it is used frequently to add Bottom
* qualifiers.
* @return a mutable set of the loaded and listed annotation classes
*/
@SafeVarargs
protected final Set<Class<? extends Annotation>> getBundledTypeQualifiers(
Class<? extends Annotation>... explicitlyListedAnnotations) {
return loadTypeAnnotationsFromQualDir(explicitlyListedAnnotations);
}
/**
* Instantiates the AnnotationClassLoader and loads all annotations contained in the qual
* directory of a checker via reflection, and has the option to include an explicitly stated
* list of annotations (eg ones found in a different directory than qual).
*
* <p>The annotations that are automatically loaded must have the {@link
* java.lang.annotation.Target Target} meta-annotation with the value of {@link
* ElementType#TYPE_USE} (and optionally {@link ElementType#TYPE_PARAMETER}). If it has other
* {@link ElementType} values, it won't be loaded. Other annotation classes must be explicitly
* listed even if they are in the same directory as the checker's qual directory.
*
* @param explicitlyListedAnnotations a set of explicitly listed annotation classes to be added
* to the returned set, for example, it is used frequently to add Bottom qualifiers
* @return a set of annotation class instances
*/
@SafeVarargs
@SuppressWarnings("varargs")
private final Set<Class<? extends Annotation>> loadTypeAnnotationsFromQualDir(
Class<? extends Annotation>... explicitlyListedAnnotations) {
loader = createAnnotationClassLoader();
Set<Class<? extends Annotation>> annotations = loader.getBundledAnnotationClasses();
// add in all explicitly Listed qualifiers
if (explicitlyListedAnnotations != null) {
annotations.addAll(Arrays.asList(explicitlyListedAnnotations));
}
return annotations;
}
/**
* Creates the AnnotatedTypeFormatter used by this type factory and all AnnotatedTypeMirrors it
* creates. The AnnotatedTypeFormatter is used in AnnotatedTypeMirror.toString and will affect
* the error messages printed for checkers that use this type factory.
*
* @return the AnnotatedTypeFormatter to pass to all instantiated AnnotatedTypeMirrors
*/
protected AnnotatedTypeFormatter createAnnotatedTypeFormatter() {
boolean printVerboseGenerics = checker.hasOption("printVerboseGenerics");
return new DefaultAnnotatedTypeFormatter(
printVerboseGenerics,
// -AprintVerboseGenerics implies -AprintAllQualifiers
printVerboseGenerics || checker.hasOption("printAllQualifiers"));
}
public AnnotatedTypeFormatter getAnnotatedTypeFormatter() {
return typeFormatter;
}
protected AnnotationFormatter createAnnotationFormatter() {
return new DefaultAnnotationFormatter();
}
public AnnotationFormatter getAnnotationFormatter() {
return annotationFormatter;
}
/**
* Returns an immutable set of the classes corresponding to the type qualifiers supported by
* this checker.
*
* <p>Subclasses cannot override this method; they should override {@link
* #createSupportedTypeQualifiers createSupportedTypeQualifiers} instead.
*
* @see #createSupportedTypeQualifiers()
* @return an immutable set of the supported type qualifiers, or an empty set if no qualifiers
* are supported
*/
public final Set<Class<? extends Annotation>> getSupportedTypeQualifiers() {
if (this.supportedQuals.isEmpty()) {
supportedQuals.addAll(createSupportedTypeQualifiers());
checkSupportedQuals();
}
return Collections.unmodifiableSet(supportedQuals);
}
/**
* Returns an immutable set of the fully qualified names of the type qualifiers supported by
* this checker.
*
* <p>Subclasses cannot override this method; they should override {@link
* #createSupportedTypeQualifiers createSupportedTypeQualifiers} instead.
*
* @see #createSupportedTypeQualifiers()
* @return an immutable set of the supported type qualifiers, or an empty set if no qualifiers
* are supported
*/
public final Set<String> getSupportedTypeQualifierNames() {
if (this.supportedQualNames.isEmpty()) {
for (Class<?> clazz : getSupportedTypeQualifiers()) {
supportedQualNames.add(clazz.getCanonicalName());
}
}
return Collections.unmodifiableSet(supportedQualNames);
}
// **********************************************************************
// Factories for annotated types that account for default qualifiers
// **********************************************************************
/**
* Returns the int supplied to the checker via the atfCacheSize option or the default cache
* size.
*
* @return cache size passed as argument to checker or DEFAULT_CACHE_SIZE
*/
protected int getCacheSize() {
String option = checker.getOption("atfCacheSize");
if (option == null) {
return DEFAULT_CACHE_SIZE;
}
try {
return Integer.valueOf(option);
} catch (NumberFormatException ex) {
throw new UserError("atfCacheSize was not an integer: " + option);
}
}
/**
* Returns an AnnotatedTypeMirror representing the annotated type of {@code elt}.
*
* @param elt the element
* @return the annotated type of {@code elt}
*/
public AnnotatedTypeMirror getAnnotatedType(Element elt) {
if (elt == null) {
throw new BugInCF("AnnotatedTypeFactory.getAnnotatedType: null element");
}
// Annotations explicitly written in the source code,
// or obtained from bytecode.
AnnotatedTypeMirror type = fromElement(elt);
addComputedTypeAnnotations(elt, type);
return type;
}
@Override
public @Nullable AnnotationMirror getAnnotationMirror(
Tree tree, Class<? extends Annotation> target) {
if (isSupportedQualifier(target)) {
AnnotatedTypeMirror atm = getAnnotatedType(tree);
return atm.getAnnotation(target);
}
return null;
}
/**
* Returns an AnnotatedTypeMirror representing the annotated type of {@code tree}.
*
* @param tree the AST node
* @return the annotated type of {@code tree}
*/
public AnnotatedTypeMirror getAnnotatedType(Tree tree) {
/// For debugging
// String treeString = tree.toString();
// if (treeString.length() > 63) {
// treeString = treeString.substring(0, 60) + "...";
// }
if (tree == null) {
throw new BugInCF("AnnotatedTypeFactory.getAnnotatedType: null tree");
}
if (shouldCache && classAndMethodTreeCache.containsKey(tree)) {
return classAndMethodTreeCache.get(tree).deepCopy();
}
AnnotatedTypeMirror type;
if (TreeUtils.isClassTree(tree)) {
type = fromClass((ClassTree) tree);
} else if (tree.getKind() == Tree.Kind.METHOD || tree.getKind() == Tree.Kind.VARIABLE) {
type = fromMember(tree);
} else if (TreeUtils.isExpressionTree(tree)) {
tree = TreeUtils.withoutParens((ExpressionTree) tree);
type = fromExpression((ExpressionTree) tree);
} else {
throw new BugInCF(
"AnnotatedTypeFactory.getAnnotatedType: query of annotated type for tree "
+ tree.getKind());
}
addComputedTypeAnnotations(tree, type);
if (TreeUtils.isClassTree(tree) || tree.getKind() == Tree.Kind.METHOD) {
// Don't cache VARIABLE
if (shouldCache) {
classAndMethodTreeCache.put(tree, type.deepCopy());
}
} else {
// No caching otherwise
}
// System.out.println("AnnotatedTypeFactory::getAnnotatedType(Tree) result: " + type);
return type;
}
/**
* Called by {@link BaseTypeVisitor#visitClass(ClassTree, Void)} before the classTree is type
* checked.
*
* @param classTree ClassTree on which to perform preprocessing
*/
public void preProcessClassTree(ClassTree classTree) {}
/**
* Called by {@link BaseTypeVisitor#visitClass(ClassTree, Void)} after the ClassTree has been
* type checked.
*
* <p>The default implementation uses this to store the defaulted AnnotatedTypeMirrors and
* inherited declaration annotations back into the corresponding Elements. Subclasses might want
* to override this method if storing defaulted types is not desirable.
*/
public void postProcessClassTree(ClassTree tree) {
TypesIntoElements.store(processingEnv, this, tree);
DeclarationsIntoElements.store(processingEnv, this, tree);
if (checker.hasOption("infer") && wholeProgramInference != null) {
// Write scenes into .jaif files. In order to perform the write
// operation only once for each .jaif file, the best location to
// do so is here.
wholeProgramInference.saveResults();
}
}
/**
* Determines the annotated type from a type in tree form.
*
* <p>Note that we cannot decide from a Tree whether it is a type use or an expression.
* TreeUtils.isTypeTree is only an under-approximation. For example, an identifier can be either
* a type or an expression.
*
* @param tree the type tree
* @return the annotated type of the type in the AST
*/
public AnnotatedTypeMirror getAnnotatedTypeFromTypeTree(Tree tree) {
if (tree == null) {
throw new BugInCF("AnnotatedTypeFactory.getAnnotatedTypeFromTypeTree: null tree");
}
AnnotatedTypeMirror type = fromTypeTree(tree);
addComputedTypeAnnotations(tree, type);
return type;
}
/**
* Returns the set of qualifiers that are the upper bounds for a use of the type.
*
* @param type
*/
public Set<AnnotationMirror> getTypeDeclarationBounds(TypeMirror type) {
return qualifierUpperBounds.getBoundQualifiers(type);
}
/**
* Returns the set of qualifiers that are the upper bound for a type use if no other bound is
* specified for the type.
*
* <p>This implementation returns the top qualifiers by default. Subclass may override to return
* different qualifiers.
*
* @return the set of qualifiers that are the upper bound for a type use if no other bound is
* specified for the type
*/
protected Set<? extends AnnotationMirror> getDefaultTypeDeclarationBounds() {
return qualHierarchy.getTopAnnotations();
}
/**
* Returns the type of the extends or implements clause.
*
* <p>The primary qualifier is either an explicit annotation on {@code clause}, or it is the
* qualifier upper bounds for uses of the type of the clause.
*
* @param clause tree that represents an extends or implements clause
* @return the type of the extends or implements clause
*/
public AnnotatedTypeMirror getTypeOfExtendsImplements(Tree clause) {
AnnotatedTypeMirror fromTypeTree = fromTypeTree(clause);
Set<AnnotationMirror> bound = getTypeDeclarationBounds(fromTypeTree.getUnderlyingType());
fromTypeTree.addMissingAnnotations(bound);
return fromTypeTree;
}
// **********************************************************************
// Factories for annotated types that do not account for default qualifiers.
// They only include qualifiers explicitly inserted by the user.
// **********************************************************************
/**
* Creates an AnnotatedTypeMirror for {@code elt} that includes: annotations explicitly written
* on the element and annotations from stub files.
*
* @param elt the element
* @return AnnotatedTypeMirror of the element with explicitly-written and stub file annotations
*/
public AnnotatedTypeMirror fromElement(Element elt) {
if (shouldCache && elementCache.containsKey(elt)) {
return elementCache.get(elt).deepCopy();
}
if (elt.getKind() == ElementKind.PACKAGE) {
return toAnnotatedType(elt.asType(), false);
}
AnnotatedTypeMirror type;
// Because of a bug in Java 8, annotations on type parameters are not stored in elements,
// so get explicit annotations from the tree. (This bug has been fixed in Java 9.)
// Also, since annotations computed by the AnnotatedTypeFactory are stored in the element,
// the annotations have to be retrieved from the tree so that only explicit annotations are
// returned.
Tree decl = declarationFromElement(elt);
if (decl == null) {
type = stubTypes.getAnnotatedTypeMirror(elt);
if (type == null) {
type = toAnnotatedType(elt.asType(), ElementUtils.isTypeDeclaration(elt));
ElementAnnotationApplier.apply(type, elt, this);
}
} else if (decl instanceof ClassTree) {
type = fromClass((ClassTree) decl);
} else if (decl instanceof VariableTree) {
type = fromMember(decl);
} else if (decl instanceof MethodTree) {
type = fromMember(decl);
} else if (decl.getKind() == Tree.Kind.TYPE_PARAMETER) {
type = fromTypeTree(decl);
} else {
throw new BugInCF(
"AnnotatedTypeFactory.fromElement: cannot be here. decl: "
+ decl.getKind()
+ " elt: "
+ elt);
}
// Caching is disabled if stub files are being parsed, because calls to this
// method before the stub files are fully read can return incorrect results.
if (shouldCache && !stubTypes.isParsing()) {
elementCache.put(elt, type.deepCopy());
}
return type;
}
/**
* Returns an AnnotatedDeclaredType with explicit annotations from the ClassTree {@code tree}.
*
* @param tree the class declaration
* @return AnnotatedDeclaredType with explicit annotations from {@code tree}
*/
private AnnotatedDeclaredType fromClass(ClassTree tree) {
return TypeFromTree.fromClassTree(this, tree);
}
/**
* Creates an AnnotatedTypeMirror for a variable or method declaration tree. The
* AnnotatedTypeMirror contains annotations explicitly written on the tree.
*
* <p>If a VariableTree is a parameter to a lambda, this method also adds annotations from the
* declared type of the functional interface and the executable type of its method.
*
* @param tree MethodTree or VariableTree
* @return AnnotatedTypeMirror with explicit annotations from {@code tree}.
*/
private final AnnotatedTypeMirror fromMember(Tree tree) {
if (!(tree instanceof MethodTree || tree instanceof VariableTree)) {
throw new BugInCF(
"AnnotatedTypeFactory.fromMember: not a method or variable declaration: "
+ tree);
}
if (shouldCache && fromMemberTreeCache.containsKey(tree)) {
return fromMemberTreeCache.get(tree).deepCopy();
}
AnnotatedTypeMirror result = TypeFromTree.fromMember(this, tree);
if (shouldCache) {
fromMemberTreeCache.put(tree, result.deepCopy());
}
return result;
}
/**
* Creates an AnnotatedTypeMirror for an ExpressionTree. The AnnotatedTypeMirror contains
* explicit annotations written on the expression and for some expressions, annotations from
* sub-expressions that could have been explicitly written, defaulted, refined, or otherwise
* computed. (Expression whose type include annotations from sub-expressions are:
* ArrayAccessTree, ConditionalExpressionTree, IdentifierTree, MemberSelectTree, and
* MethodInvocationTree.)
*
* <p>For example, the AnnotatedTypeMirror returned for an array access expression is the fully
* annotated type of the array component of the array being accessed.
*
* @param tree an expression
* @return AnnotatedTypeMirror of the expressions either fully-annotated or partially annotated
* depending on the kind of expression
* @see TypeFromExpressionVisitor
*/
private AnnotatedTypeMirror fromExpression(ExpressionTree tree) {
if (shouldCache && fromExpressionTreeCache.containsKey(tree)) {
return fromExpressionTreeCache.get(tree).deepCopy();
}
AnnotatedTypeMirror result = TypeFromTree.fromExpression(this, tree);
if (shouldCache && tree.getKind() != Tree.Kind.NEW_CLASS) {
// Don't cache the type of object creations, because incorrect
// annotations would be cached during dataflow analysis.
// See Issue #602.
fromExpressionTreeCache.put(tree, result.deepCopy());
}
return result;
}
/**
* Creates an AnnotatedTypeMirror for the tree. The AnnotatedTypeMirror contains annotations
* explicitly written on the tree. It also adds type arguments to raw types that include
* annotations from the element declaration of the type {@link #fromElement(Element)}.
*
* <p>Called on the following trees: AnnotatedTypeTree, ArrayTypeTree, ParameterizedTypeTree,
* PrimitiveTypeTree, TypeParameterTree, WildcardTree, UnionType, IntersectionTypeTree, and
* IdentifierTree, MemberSelectTree.
*
* @param tree the type tree
* @return the (partially) annotated type of the type in the AST
*/
/*package private*/ final AnnotatedTypeMirror fromTypeTree(Tree tree) {
if (shouldCache && fromTypeTreeCache.containsKey(tree)) {
return fromTypeTreeCache.get(tree).deepCopy();
}
AnnotatedTypeMirror result = TypeFromTree.fromTypeTree(this, tree);
if (shouldCache) {
fromTypeTreeCache.put(tree, result.deepCopy());
}
return result;
}
// **********************************************************************
// Customization methods meant to be overridden by subclasses to include
// defaulted annotations
// **********************************************************************
/**
* Changes annotations on a type obtained from a {@link Tree}. By default, this method does
* nothing. GenericAnnotatedTypeFactory uses this method to implement defaulting and inference
* (flow-sensitive type refinement). Its subclasses usually override it only to customize
* default annotations.
*
* <p>Subclasses that override this method should also override {@link
* #addComputedTypeAnnotations(Element, AnnotatedTypeMirror)}.
*
* <p>In classes that extend {@link GenericAnnotatedTypeFactory}, override {@link
* GenericAnnotatedTypeFactory#addComputedTypeAnnotations(Tree, AnnotatedTypeMirror, boolean)}
* instead of this method.
*
* @param tree an AST node
* @param type the type obtained from {@code tree}
*/
protected void addComputedTypeAnnotations(Tree tree, AnnotatedTypeMirror type) {
// Pass.
}
/**
* Changes annotations on a type obtained from an {@link Element}. By default, this method does
* nothing. GenericAnnotatedTypeFactory uses this method to implement defaulting.
*
* <p>Subclasses that override this method should also override {@link
* #addComputedTypeAnnotations(Tree, AnnotatedTypeMirror)}.
*
* @param elt an element
* @param type the type obtained from {@code elt}
*/
protected void addComputedTypeAnnotations(Element elt, AnnotatedTypeMirror type) {
// Pass.
}
/**
* Adds default annotations to {@code type}. This method should only be used in places where the
* correct annotations cannot be computed because of uninferred type arguments. (See {@link
* AnnotatedWildcardType#isUninferredTypeArgument()}.)
*
* @param type annotated type to which default annotations are added
*/
protected void addDefaultAnnotations(AnnotatedTypeMirror type) {
// Pass.
}
/**
* A callback method for the AnnotatedTypeFactory subtypes to customize directSuperTypes().
* Overriding methods should merely change the annotations on the supertypes, without adding or
* removing new types.
*
* <p>The default provided implementation adds {@code type} annotations to {@code supertypes}.
* This allows the {@code type} and its supertypes to have the qualifiers.
*
* @param type the type whose supertypes are desired
* @param supertypes the supertypes as specified by the base AnnotatedTypeFactory
*/
protected void postDirectSuperTypes(
AnnotatedTypeMirror type, List<? extends AnnotatedTypeMirror> supertypes) {
// Use the effective annotations here to get the correct annotations
// for type variables and wildcards.
Set<AnnotationMirror> annotations = type.getEffectiveAnnotations();
for (AnnotatedTypeMirror supertype : supertypes) {
if (!annotations.equals(supertype.getEffectiveAnnotations())) {
supertype.clearAnnotations();
// TODO: is this correct for type variables and wildcards?
supertype.addAnnotations(annotations);
}
}
}
/**
* A callback method for the AnnotatedTypeFactory subtypes to customize
* AnnotatedTypes.asMemberOf(). Overriding methods should merely change the annotations on the
* subtypes, without changing the types.
*
* @param type the annotated type of the element
* @param owner the annotated type of the receiver of the accessing tree
* @param element the element of the field or method
*/
public void postAsMemberOf(
AnnotatedTypeMirror type, AnnotatedTypeMirror owner, Element element) {
if (element.getKind() == ElementKind.FIELD) {
addAnnotationFromFieldInvariant(type, owner, (VariableElement) element);
}
addComputedTypeAnnotations(element, type);
}
/**
* Adds the qualifier specified by a field invariant for {@code field} to {@code type}.
*
* @param type annotated type to which the annotation is added
* @param accessedVia the annotated type of the receiver of the accessing tree. (Only used to
* get the type element of the underling type.)
* @param field element representing the field
*/
protected void addAnnotationFromFieldInvariant(
AnnotatedTypeMirror type, AnnotatedTypeMirror accessedVia, VariableElement field) {
TypeMirror declaringType = accessedVia.getUnderlyingType();
// Find the first upper bound that isn't a wildcard or type variable
while (declaringType.getKind() == TypeKind.WILDCARD
|| declaringType.getKind() == TypeKind.TYPEVAR) {
if (declaringType.getKind() == TypeKind.WILDCARD) {
declaringType = ((WildcardType) declaringType).getExtendsBound();
} else if (declaringType.getKind() == TypeKind.TYPEVAR) {
declaringType = ((TypeVariable) declaringType).getUpperBound();
}
}
TypeElement typeElement = TypesUtils.getTypeElement(declaringType);
if (ElementUtils.enclosingClass(field).equals(typeElement)) {
// If the field is declared in the accessedVia class, then the field in the invariant
// cannot be this field, even if the field has the same name.
return;
}
FieldInvariants invariants = getFieldInvariants(typeElement);
if (invariants == null) {
return;
}
List<AnnotationMirror> invariantAnnos = invariants.getQualifiersFor(field.getSimpleName());
type.replaceAnnotations(invariantAnnos);
}
/**
* Returns the field invariants for the given class, as expressed by the user in {@link
* FieldInvariant @FieldInvariant} method annotations.
*
* <p>Subclasses may implement their own field invariant annotations if {@link
* FieldInvariant @FieldInvariant} is not expressive enough. They must override this method to
* properly create AnnotationMirror and also override {@link
* #getFieldInvariantDeclarationAnnotations()} to return their field invariants.
*
* @param element class for which to get invariants
* @return fields invariants for {@code element}
*/
public FieldInvariants getFieldInvariants(TypeElement element) {
if (element == null) {
return null;
}
AnnotationMirror fieldInvarAnno = getDeclAnnotation(element, FieldInvariant.class);
if (fieldInvarAnno == null) {
return null;
}
List<String> fields =
AnnotationUtils.getElementValueArray(fieldInvarAnno, "field", String.class, true);
List<Name> classes =
AnnotationUtils.getElementValueClassNames(fieldInvarAnno, "qualifier", true);
List<AnnotationMirror> qualifiers = new ArrayList<>();
for (Name name : classes) {
// Calling AnnotationBuilder.fromName (which ignores elements/fields) is acceptable
// because @FieldInvariant does not handle classes with elements/fields.
qualifiers.add(AnnotationBuilder.fromName(elements, name));
}
if (qualifiers.size() == 1) {
while (fields.size() > qualifiers.size()) {
qualifiers.add(qualifiers.get(0));
}
}
if (fields.size() != qualifiers.size()) {
// The user wrote a malformed @FieldInvariant annotation, so just return a malformed
// FieldInvariants object. The BaseTypeVisitor will issue an error.
return new FieldInvariants(fields, qualifiers);
}
// Only keep qualifiers that are supported by this checker. (The other qualifiers cannot
// be checked by this checker, so they must be ignored.)
List<String> supportFields = new ArrayList<>();
List<AnnotationMirror> supportedQualifiers = new ArrayList<>();
for (int i = 0; i < fields.size(); i++) {
if (isSupportedQualifier(qualifiers.get(i))) {
supportedQualifiers.add(qualifiers.get(i));
supportFields.add(fields.get(i));
}
}
if (supportFields.isEmpty() && qualifiers.isEmpty()) {
return null;
}
return new FieldInvariants(supportFields, supportedQualifiers);
}
/**
* Returns the AnnotationTree which is a use of one of the field invariant annotations (as
* specified via {@link #getFieldInvariantDeclarationAnnotations()}. If one isn't found, null is
* returned.
*
* @param annoTrees trees to look
* @return returns the AnnotationTree which is a use of one of the field invariant annotations
* or null if one isn't found
*/
public AnnotationTree getFieldInvariantAnnotationTree(
List<? extends AnnotationTree> annoTrees) {
List<AnnotationMirror> annos = TreeUtils.annotationsFromTypeAnnotationTrees(annoTrees);
for (int i = 0; i < annos.size(); i++) {
for (Class<? extends Annotation> clazz : getFieldInvariantDeclarationAnnotations()) {
if (areSameByClass(annos.get(i), clazz)) {
return annoTrees.get(i);
}
}
}
return null;
}
/** Returns the set of classes of field invariant annotations. */
protected Set<Class<? extends Annotation>> getFieldInvariantDeclarationAnnotations() {
return Collections.singleton(FieldInvariant.class);
}
/**
* A callback method for the AnnotatedTypeFactory subtypes to customize
* AnnotatedTypeMirror.substitute().
*
* @param varDecl a declaration of a type variable
* @param varUse a use of the same type variable
* @param value the new type to substitute in for the type variable
*/
public void postTypeVarSubstitution(
AnnotatedTypeVariable varDecl,
AnnotatedTypeVariable varUse,
AnnotatedTypeMirror value) {
if (!varUse.getAnnotationsField().isEmpty()
&& !AnnotationUtils.areSame(
varUse.getAnnotationsField(), varDecl.getAnnotationsField())) {
value.replaceAnnotations(varUse.getAnnotationsField());
}
}
/**
* Adapt the upper bounds of the type variables of a class relative to the type instantiation.
* In some type systems, the upper bounds depend on the instantiation of the class. For example,
* in the Generic Universe Type system, consider a class declaration
*
* <pre>{@code class C<X extends @Peer Object> }</pre>
*
* then the instantiation
*
* <pre>{@code @Rep C<@Rep Object> }</pre>
*
* is legal. The upper bounds of class C have to be adapted by the main modifier.
*
* <p>An example of an adaptation follows. Suppose, I have a declaration:
*
* <pre>{@code class MyClass<E extends List<E>>}</pre>
*
* And an instantiation:
*
* <pre>{@code new MyClass<@NonNull String>()}</pre>
*
* <p>The upper bound of E adapted to the argument String, would be {@code List<@NonNull
* String>} and the lower bound would be an AnnotatedNullType.
*
* <p>TODO: ensure that this method is consistently used instead of directly querying the type
* variables.
*
* @param type the use of the type
* @param element the corresponding element
* @return the adapted bounds of the type parameters
*/
public List<AnnotatedTypeParameterBounds> typeVariablesFromUse(
AnnotatedDeclaredType type, TypeElement element) {
AnnotatedDeclaredType generic = getAnnotatedType(element);
List<AnnotatedTypeMirror> targs = type.getTypeArguments();
List<AnnotatedTypeMirror> tvars = generic.getTypeArguments();
assert targs.size() == tvars.size()
: "Mismatch in type argument size between " + type + " and " + generic;
// System.err.printf("TVFU\n type: %s\n generic: %s\n", type, generic);
Map<TypeVariable, AnnotatedTypeMirror> mapping = new HashMap<>();
AnnotatedDeclaredType enclosing = type;
while (enclosing != null) {
List<AnnotatedTypeMirror> enclosingTArgs = enclosing.getTypeArguments();
AnnotatedDeclaredType declaredType =
getAnnotatedType((TypeElement) enclosing.getUnderlyingType().asElement());
List<AnnotatedTypeMirror> enclosingTVars = declaredType.getTypeArguments();
for (int i = 0; i < enclosingTArgs.size(); i++) {
AnnotatedTypeVariable enclosingTVar = (AnnotatedTypeVariable) enclosingTVars.get(i);
mapping.put(enclosingTVar.getUnderlyingType(), enclosingTArgs.get(i));
}
enclosing = enclosing.getEnclosingType();
}
List<AnnotatedTypeParameterBounds> res = new ArrayList<>(tvars.size());
for (AnnotatedTypeMirror atm : tvars) {
AnnotatedTypeVariable atv = (AnnotatedTypeVariable) atm;
AnnotatedTypeMirror upper = typeVarSubstitutor.substitute(mapping, atv.getUpperBound());
AnnotatedTypeMirror lower = typeVarSubstitutor.substitute(mapping, atv.getLowerBound());
res.add(new AnnotatedTypeParameterBounds(upper, lower));
}
return res;
}
/**
* Creates and returns an AnnotatedNullType qualified with {@code annotations}.
*
* @param annotations set of AnnotationMirrors to qualify the returned type with
* @return AnnotatedNullType qualified with {@code annotations}
*/
public AnnotatedNullType getAnnotatedNullType(Set<? extends AnnotationMirror> annotations) {
final AnnotatedTypeMirror.AnnotatedNullType nullType =
(AnnotatedNullType)
toAnnotatedType(processingEnv.getTypeUtils().getNullType(), false);
nullType.addAnnotations(annotations);
return nullType;
}
// **********************************************************************
// Utilities method for getting specific types from trees or elements
// **********************************************************************
/**
* Return the implicit receiver type of an expression tree.
*
* <p>The result is null for expressions that don't have a receiver, e.g. for a local variable
* or method parameter access.
*
* <p>Clients should generally call {@link #getReceiverType}.
*
* @param tree the expression that might have an implicit receiver
* @return the type of the receiver
*/
/*
* TODO: receiver annotations on outer this.
* TODO: Better document the difference between getImplicitReceiverType and getSelfType?
* TODO: this method assumes that the tree is within the current
* Compilation Unit. This assumption fails in testcase Bug109_A/B, where
* a chain of dependencies leads into a different compilation unit.
* I didn't find a way how to handle this better and conservatively
* return null. See TODO comment below.
*
*/
protected AnnotatedDeclaredType getImplicitReceiverType(ExpressionTree tree) {
assert (tree.getKind() == Tree.Kind.IDENTIFIER
|| tree.getKind() == Tree.Kind.MEMBER_SELECT
|| tree.getKind() == Tree.Kind.METHOD_INVOCATION
|| tree.getKind() == Tree.Kind.NEW_CLASS)
: "Unexpected tree kind: " + tree.getKind();
Element element = TreeUtils.elementFromTree(tree);
assert element != null : "Unexpected null element for tree: " + tree;
// Return null if the element kind has no receiver.
if (!ElementUtils.hasReceiver(element)) {
return null;
}
ExpressionTree receiver = TreeUtils.getReceiverTree(tree);
if (receiver == null) {
if (isMostEnclosingThisDeref(tree)) {
// TODO: problem with ambiguity with implicit receivers.
// We need a way to find the correct class. We cannot use the
// element, as generics might have to be substituted in a subclass.
// See GenericsEnclosing test case.
// TODO: is this fixed?
return getSelfType(tree);
} else {
TreePath path = getPath(tree);
if (path == null) {
// The path is null if the field is in a compilation unit we haven't
// processed yet. TODO: is there a better way?
return null;
}
TypeElement typeElt = ElementUtils.enclosingClass(element);
if (typeElt == null) {
throw new BugInCF(
"AnnotatedTypeFactory.getImplicitReceiver: enclosingClass()==null for element: "
+ element);
}
if (tree.getKind() == Kind.NEW_CLASS) {
if (typeElt.getEnclosingElement() != null) {
typeElt = ElementUtils.enclosingClass(typeElt.getEnclosingElement());
} else {
typeElt = null;
}
if (typeElt == null) {
// If the typeElt does not have an enclosing class, then the NewClassTree
// does not have an implicit receiver.
return null;
}
}
// TODO: method receiver annotations on outer this
return getEnclosingType(typeElt, tree);
}
}
Element rcvelem = TreeUtils.elementFromTree(receiver);
assert rcvelem != null : "Unexpected null element for receiver: " + receiver;
if (!ElementUtils.hasReceiver(rcvelem)) {
return null;
}
if (receiver.getKind() == Tree.Kind.IDENTIFIER
&& ((IdentifierTree) receiver).getName().contentEquals("this")) {
// TODO: also "super"?
return this.getSelfType(tree);
}
TypeElement typeElt = ElementUtils.enclosingClass(rcvelem);
if (typeElt == null) {
throw new BugInCF(
"AnnotatedTypeFactory.getImplicitReceiver: enclosingClass()==null for element: "
+ rcvelem);
}
AnnotatedDeclaredType type = getAnnotatedType(typeElt);
// TODO: go through _all_ enclosing methods to see whether any of them has a
// receiver annotation of the correct type.
// TODO: Can we reuse getSelfType for outer this accesses?
AnnotatedDeclaredType methodReceiver = getCurrentMethodReceiver(tree);
if (shouldTakeFromReceiver(methodReceiver)) {
// TODO: this only takes the main annotations.
// What about other annotations (annotations on the type argument, outer types, ...)
type.clearAnnotations();
type.addAnnotations(methodReceiver.getAnnotations());
}
return type;
}
// Determine whether we should take annotations from the given method receiver.
private boolean shouldTakeFromReceiver(AnnotatedDeclaredType methodReceiver) {
return methodReceiver != null;
}
/**
* Determine whether the tree dereferences the most enclosing "this" object. That is, we have an
* expression like "f.g" and want to know whether it is an access "this.f.g" or whether e.g. f
* is a field of an outer class or e.g. f is a local variable.
*
* @param tree the tree to check
* @return true, iff the tree is an explicit or implicit reference to the most enclosing "this"
*/
public final boolean isMostEnclosingThisDeref(ExpressionTree tree) {
if (!isAnyEnclosingThisDeref(tree)) {
return false;
}
Element element = TreeUtils.elementFromUse(tree);
TypeElement typeElt = ElementUtils.enclosingClass(element);
ClassTree enclosingClass = getCurrentClassTree(tree);
if (enclosingClass != null
&& isSubtype(TreeUtils.elementFromDeclaration(enclosingClass), typeElt)) {
return true;
}
// ran out of options
return false;
}
/**
* Does this expression have (the innermost or an outer) "this" as receiver? Note that the
* receiver can be either explicit or implicit.
*
* @param tree the tree to test
* @return true, iff the expression uses (the innermost or an outer) "this" as receiver
*/
public final boolean isAnyEnclosingThisDeref(ExpressionTree tree) {
if (!TreeUtils.isUseOfElement(tree)) {
return false;
}
ExpressionTree recv = TreeUtils.getReceiverTree(tree);
if (recv == null) {
Element element = TreeUtils.elementFromUse(tree);
if (!ElementUtils.hasReceiver(element)) {
return false;
}
tree = TreeUtils.withoutParens(tree);
if (tree.getKind() == Tree.Kind.IDENTIFIER) {
Name n = ((IdentifierTree) tree).getName();
if ("this".contentEquals(n) || "super".contentEquals(n)) {
// An explicit reference to "this"/"super" has no receiver.
return false;
}
}
// Must be some access through this.
return true;
} else if (!TreeUtils.isUseOfElement(recv)) {
// The receiver is e.g. a String literal.
return false;
// TODO: I think this:
// (i==9 ? this : this).toString();
// is not a use of an element, as the receiver is an
// expression. How should this be handled?
}
Element element = TreeUtils.elementFromUse(recv);
if (!ElementUtils.hasReceiver(element)) {
return false;
}
return TreeUtils.isExplicitThisDereference(recv);
}
/**
* Returns the type of {@code this} in the given location, which can be used if {@code this} has
* a special semantics (e.g. {@code this} is non-null).
*
* <p>The parameter is an arbitrary tree and does not have to mention "this", neither explicitly
* nor implicitly. This method should be overridden for type-system specific behavior.
*
* <p>TODO: in 1.8.2, handle all receiver type annotations. TODO: handle enclosing classes
* correctly.
*/
public AnnotatedDeclaredType getSelfType(Tree tree) {
if (TreeUtils.isClassTree(tree)) {
return getAnnotatedType(TreeUtils.elementFromDeclaration((ClassTree) tree));
}
TreePath path = getPath(tree);
ClassTree enclosingClass = TreeUtils.enclosingClass(path);
if (enclosingClass == null) {
// I hope this only happens when tree is a fake tree that
// we created, e.g. when desugaring enhanced-for-loops.
enclosingClass = getCurrentClassTree(tree);
}
AnnotatedDeclaredType type = getAnnotatedType(enclosingClass);
MethodTree enclosingMethod = TreeUtils.enclosingMethod(path);
if (enclosingClass.getSimpleName().length() != 0 && enclosingMethod != null) {
AnnotatedDeclaredType methodReceiver;
if (TreeUtils.isConstructor(enclosingMethod)) {
// The type of `this` in a constructor is usually the constructor return type.
// Certain type systems, in particular the Initialization Checker, need custom
// logic.
methodReceiver =
(AnnotatedDeclaredType) getAnnotatedType(enclosingMethod).getReturnType();
} else {
methodReceiver = getAnnotatedType(enclosingMethod).getReceiverType();
}
if (shouldTakeFromReceiver(methodReceiver)) {
// TODO what about all annotations on the receiver?
// Code is also duplicated above.
type.clearAnnotations();
type.addAnnotations(methodReceiver.getAnnotations());
}
}
return type;
}
/**
* Determine the type of the most enclosing class of the given tree that is a subtype of the
* given element. Receiver type annotations of an enclosing method are considered, similarly
* return type annotations of an enclosing constructor.
*/
public AnnotatedDeclaredType getEnclosingType(TypeElement element, Tree tree) {
Element enclosingElt = getMostInnerClassOrMethod(tree);
while (enclosingElt != null) {
if (enclosingElt instanceof ExecutableElement) {
ExecutableElement method = (ExecutableElement) enclosingElt;
if (method.asType() != null // XXX: hack due to a compiler bug
&& isSubtype((TypeElement) method.getEnclosingElement(), element)) {
if (ElementUtils.isStatic(method)) {
// Static methods should use type of enclosing class,
// by simply taking another turn in the loop.
} else if (method.getKind() == ElementKind.CONSTRUCTOR) {
// return getSelfType(this.declarationFromElement(method));
return (AnnotatedDeclaredType) getAnnotatedType(method).getReturnType();
} else {
return getAnnotatedType(method).getReceiverType();
}
}
} else if (enclosingElt instanceof TypeElement) {
if (isSubtype((TypeElement) enclosingElt, element)) {
return (AnnotatedDeclaredType) getAnnotatedType(enclosingElt);
}
}
enclosingElt = enclosingElt.getEnclosingElement();
}
return null;
}
private boolean isSubtype(TypeElement a1, TypeElement a2) {
return (a1.equals(a2)
|| types.isSubtype(types.erasure(a1.asType()), types.erasure(a2.asType())));
}
/**
* Returns the receiver type of the expression tree, or null if it does not exist.
*
* <p>The only trees that could potentially have a receiver are:
*
* <ul>
* <li>Array Access
* <li>Identifiers (whose receivers are usually self type)
* <li>Method Invocation Trees
* <li>Member Select Trees
* </ul>
*
* @param expression the expression for which to determine the receiver type
* @return the type of the receiver of this expression
*/
public final AnnotatedTypeMirror getReceiverType(ExpressionTree expression) {
if (this.isAnyEnclosingThisDeref(expression)) {
return getImplicitReceiverType(expression);
}
ExpressionTree receiver = TreeUtils.getReceiverTree(expression);
if (receiver != null) {
return getAnnotatedType(receiver);
} else {
// E.g. local variables
return null;
}
}
/** The type for an instantiated generic method or constructor. */
public static class ParameterizedExecutableType {
/** The method's/constructor's type. */
public final AnnotatedExecutableType executableType;
/** The types of the generic type arguments. */
public final List<AnnotatedTypeMirror> typeArgs;
/** Create a ParameterizedExecutableType. */
public ParameterizedExecutableType(
AnnotatedExecutableType executableType, List<AnnotatedTypeMirror> typeArgs) {
this.executableType = executableType;
this.typeArgs = typeArgs;
}
}
/**
* Determines the type of the invoked method based on the passed method invocation tree.
*
* <p>The returned method type has all type variables resolved, whether based on receiver type,
* passed type parameters if any, and method invocation parameter.
*
* <p>Subclasses may override this method to customize inference of types or qualifiers based on
* method invocation parameters.
*
* <p>As an implementation detail, this method depends on {@link
* AnnotatedTypes#asMemberOf(Types, AnnotatedTypeFactory, AnnotatedTypeMirror, Element)}, and
* customization based on receiver type should be in accordance to its specification.
*
* <p>The return type is a pair of the type of the invoked method and the (inferred) type
* arguments. Note that neither the explicitly passed nor the inferred type arguments are
* guaranteed to be subtypes of the corresponding upper bounds. See method {@link
* org.checkerframework.common.basetype.BaseTypeVisitor#checkTypeArguments(Tree, List, List,
* List)} for the checks of type argument well-formedness.
*
* <p>Note that "this" and "super" constructor invocations are also handled by this method
* (explicit or implicit ones, at the beginning of a constructor). Method {@link
* #constructorFromUse(NewClassTree)} is only used for a constructor invocation in a "new"
* expression.
*
* @param tree the method invocation tree
* @return the method type being invoked with tree and the (inferred) type arguments
*/
public ParameterizedExecutableType methodFromUse(MethodInvocationTree tree) {
ExecutableElement methodElt = TreeUtils.elementFromUse(tree);
AnnotatedTypeMirror receiverType = getReceiverType(tree);
ParameterizedExecutableType mType = methodFromUse(tree, methodElt, receiverType);
if (checker.shouldResolveReflection()
&& reflectionResolver.isReflectiveMethodInvocation(tree)) {
mType = reflectionResolver.resolveReflectiveCall(this, tree, mType);
}
AnnotatedExecutableType method = mType.executableType;
if (method.getReturnType().getKind() == TypeKind.WILDCARD
&& ((AnnotatedWildcardType) method.getReturnType()).isUninferredTypeArgument()) {
// Get the correct Java type from the tree and use it as the upper bound of the
// wildcard.
TypeMirror tm = TreeUtils.typeOf(tree);
AnnotatedTypeMirror t = toAnnotatedType(tm, false);
AnnotatedWildcardType wildcard = (AnnotatedWildcardType) method.getReturnType();
if (ignoreUninferredTypeArguments) {
// remove the annotations so that default annotations are used instead.
// (See call to addDefaultAnnotations below.)
t.clearAnnotations();
} else {
t.replaceAnnotations(wildcard.getExtendsBound().getAnnotations());
}
wildcard.setExtendsBound(t);
addDefaultAnnotations(wildcard);
}
return mType;
}
/**
* Determines the type of the invoked method based on the passed expression tree, executable
* element, and receiver type.
*
* @param tree either a MethodInvocationTree or a MemberReferenceTree
* @param methodElt the element of the referenced method
* @param receiverType the type of the receiver
* @return the method type being invoked with tree and the (inferred) type arguments
* @see #methodFromUse(MethodInvocationTree)
*/
public ParameterizedExecutableType methodFromUse(
ExpressionTree tree, ExecutableElement methodElt, AnnotatedTypeMirror receiverType) {
AnnotatedExecutableType methodType =
AnnotatedTypes.asMemberOf(types, this, receiverType, methodElt);
List<AnnotatedTypeMirror> typeargs = new ArrayList<>(methodType.getTypeVariables().size());
Map<TypeVariable, AnnotatedTypeMirror> typeVarMapping =
AnnotatedTypes.findTypeArguments(processingEnv, this, tree, methodElt, methodType);
if (!typeVarMapping.isEmpty()) {
for (AnnotatedTypeVariable tv : methodType.getTypeVariables()) {
if (typeVarMapping.get(tv.getUnderlyingType()) == null) {
throw new BugInCF(
"AnnotatedTypeFactory.methodFromUse:"
+ "mismatch between declared method type variables and the inferred method type arguments. "
+ "Method type variables: "
+ methodType.getTypeVariables()
+ "; "
+ "Inferred method type arguments: "
+ typeVarMapping);
}
typeargs.add(typeVarMapping.get(tv.getUnderlyingType()));
}
methodType =
(AnnotatedExecutableType)
typeVarSubstitutor.substitute(typeVarMapping, methodType);
}
if (tree.getKind() == Tree.Kind.METHOD_INVOCATION
&& TreeUtils.isMethodInvocation(tree, objectGetClass, processingEnv)) {
adaptGetClassReturnTypeToReceiver(methodType, receiverType);
}
return new ParameterizedExecutableType(methodType, typeargs);
}
/**
* Java special-cases the return type of {@link java.lang.Class#getClass() getClass()}. Though
* the method has a return type of {@code Class<?>}, the compiler special cases this return-type
* and changes the bound of the type argument to the erasure of the receiver type. For example:
*
* <ul>
* <li>{@code x.getClass()} has the type {@code Class< ? extends erasure_of_x >}
* <li>{@code someInteger.getClass()} has the type {@code Class< ? extends Integer >}
* </ul>
*
* @param getClassType this must be a type representing a call to Object.getClass otherwise a
* runtime exception will be thrown. It is modified by side effect.
* @param receiverType the receiver type of the method invocation (not the declared receiver
* type)
*/
protected void adaptGetClassReturnTypeToReceiver(
final AnnotatedExecutableType getClassType, final AnnotatedTypeMirror receiverType) {
// TODO: should the receiver type ever be a declaration??
// Work on removing the asUse() call.
final AnnotatedTypeMirror newBound = receiverType.getErased().asUse();
final AnnotatedTypeMirror returnType = getClassType.getReturnType();
if (returnType == null
|| !(returnType.getKind() == TypeKind.DECLARED)
|| ((AnnotatedDeclaredType) returnType).getTypeArguments().size() != 1) {
throw new BugInCF(
"Unexpected type passed to AnnotatedTypes.adaptGetClassReturnTypeToReceiver\n"
+ "getClassType="
+ getClassType
+ "\n"
+ "receiverType="
+ receiverType);
}
final AnnotatedDeclaredType returnAdt =
(AnnotatedDeclaredType) getClassType.getReturnType();
final List<AnnotatedTypeMirror> typeArgs = returnAdt.getTypeArguments();
// Usually, the only locations that will add annotations to the return type are getClass in
// stub files defaults and propagation tree annotator. Since getClass is final they cannot
// come from source code. Also, since the newBound is an erased type we have no type
// arguments. So, we just copy the annotations from the bound of the declared type to the
// new bound.
final AnnotatedWildcardType classWildcardArg = (AnnotatedWildcardType) typeArgs.get(0);
Set<AnnotationMirror> newAnnos = AnnotationUtils.createAnnotationSet();
Set<AnnotationMirror> typeBoundAnnos =
getTypeDeclarationBounds(newBound.getUnderlyingType());
Set<AnnotationMirror> wildcardBoundAnnos =
classWildcardArg.getExtendsBound().getAnnotations();
for (AnnotationMirror typeBoundAnno : typeBoundAnnos) {
AnnotationMirror wildcardAnno =
qualHierarchy.findAnnotationInSameHierarchy(wildcardBoundAnnos, typeBoundAnno);
if (qualHierarchy.isSubtype(typeBoundAnno, wildcardAnno)) {
newAnnos.add(typeBoundAnno);
} else {
newAnnos.add(wildcardAnno);
}
}
newBound.replaceAnnotations(newAnnos);
classWildcardArg.setExtendsBound(newBound);
}
/**
* Determines the type of the invoked constructor based on the passed new class tree.
*
* <p>The returned method type has all type variables resolved, whether based on receiver type,
* passed type parameters if any, and constructor invocation parameter.
*
* <p>Subclasses may override this method to customize inference of types or qualifiers based on
* constructor invocation parameters.
*
* <p>As an implementation detail, this method depends on {@link
* AnnotatedTypes#asMemberOf(Types, AnnotatedTypeFactory, AnnotatedTypeMirror, Element)}, and
* customization based on receiver type should be in accordance with its specification.
*
* <p>The return type is a pair of the type of the invoked constructor and the (inferred) type
* arguments. Note that neither the explicitly passed nor the inferred type arguments are
* guaranteed to be subtypes of the corresponding upper bounds. See method {@link
* org.checkerframework.common.basetype.BaseTypeVisitor#checkTypeArguments(Tree, List, List,
* List)} for the checks of type argument well-formedness.
*
* <p>Note that "this" and "super" constructor invocations are handled by method {@link
* #methodFromUse}. This method only handles constructor invocations in a "new" expression.
*
* @param tree the constructor invocation tree
* @return the annotated type of the invoked constructor (as an executable type) and the
* (inferred) type arguments
*/
public ParameterizedExecutableType constructorFromUse(NewClassTree tree) {
ExecutableElement ctor = TreeUtils.constructor(tree);
AnnotatedTypeMirror type = fromNewClass(tree);
addComputedTypeAnnotations(tree, type);
AnnotatedExecutableType con = AnnotatedTypes.asMemberOf(types, this, type, ctor);
if (tree.getArguments().size() == con.getParameterTypes().size() + 1
&& isSyntheticArgument(tree.getArguments().get(0))) {
// happens for anonymous constructors of inner classes
List<AnnotatedTypeMirror> actualParams = new ArrayList<>();
actualParams.add(getAnnotatedType(tree.getArguments().get(0)));
actualParams.addAll(con.getParameterTypes());
con.setParameterTypes(actualParams);
}
List<AnnotatedTypeMirror> typeargs = new ArrayList<>(con.getTypeVariables().size());
Map<TypeVariable, AnnotatedTypeMirror> typeVarMapping =
AnnotatedTypes.findTypeArguments(processingEnv, this, tree, ctor, con);
if (!typeVarMapping.isEmpty()) {
for (AnnotatedTypeVariable tv : con.getTypeVariables()) {
typeargs.add(typeVarMapping.get(tv.getUnderlyingType()));
}
con = (AnnotatedExecutableType) typeVarSubstitutor.substitute(typeVarMapping, con);
}
return new ParameterizedExecutableType(con, typeargs);
}
/** Returns the return type of the method {@code m}. */
public AnnotatedTypeMirror getMethodReturnType(MethodTree m) {
AnnotatedExecutableType methodType = getAnnotatedType(m);
AnnotatedTypeMirror ret = methodType.getReturnType();
return ret;
}
/** Returns the return type of the method {@code m} at the return statement {@code r}. */
public AnnotatedTypeMirror getMethodReturnType(MethodTree m, ReturnTree r) {
AnnotatedExecutableType methodType = getAnnotatedType(m);
AnnotatedTypeMirror ret = methodType.getReturnType();
return ret;
}
private boolean isSyntheticArgument(Tree tree) {
return tree.toString().contains("<*nullchk*>");
}
/**
* Creates an AnnotatedDeclaredType for a NewClassTree. Only adds explicit annotations, unless
* newClassTree has a diamond operator. In that case, the annotations on the type arguments are
* inferred using the assignment context and contain defaults.
*
* <p>Also, fully annotates the enclosing type of the returned declared type.
*
* <p>(Subclass beside {@link GenericAnnotatedTypeFactory} should not override this method.)
*
* @param newClassTree NewClassTree
* @return AnnotatedDeclaredType
*/
public AnnotatedDeclaredType fromNewClass(NewClassTree newClassTree) {
AnnotatedDeclaredType enclosingType;
if (newClassTree.getEnclosingExpression() != null) {
enclosingType = (AnnotatedDeclaredType) getReceiverType(newClassTree);
} else {
enclosingType = getImplicitReceiverType(newClassTree);
}
// Diamond trees that are not anonymous classes.
if (TreeUtils.isDiamondTree(newClassTree) && newClassTree.getClassBody() == null) {
AnnotatedDeclaredType type =
(AnnotatedDeclaredType) toAnnotatedType(TreeUtils.typeOf(newClassTree), false);
if (((com.sun.tools.javac.code.Type) type.actualType)
.tsym
.getTypeParameters()
.nonEmpty()) {
Pair<Tree, AnnotatedTypeMirror> ctx = this.visitorState.getAssignmentContext();
if (ctx != null) {
AnnotatedTypeMirror ctxtype = ctx.second;
fromNewClassContextHelper(type, ctxtype);
} else {
TreePath p = getPath(newClassTree);
AnnotatedTypeMirror ctxtype = TypeArgInferenceUtil.assignedTo(this, p);
if (ctxtype != null) {
fromNewClassContextHelper(type, ctxtype);
} else {
// give up trying and set to raw.
type.setWasRaw();
}
}
}
AnnotatedDeclaredType fromTypeTree =
(AnnotatedDeclaredType)
TypeFromTree.fromTypeTree(this, newClassTree.getIdentifier());
type.replaceAnnotations(fromTypeTree.getAnnotations());
type.setEnclosingType(enclosingType);
return type;
} else if (newClassTree.getClassBody() != null) {
AnnotatedDeclaredType type =
(AnnotatedDeclaredType) toAnnotatedType(TreeUtils.typeOf(newClassTree), false);
// If newClassTree creates an anonymous class, then annotations in this location:
// new @HERE Class() {}
// are on not on the identifier newClassTree, but rather on the modifier newClassTree.
List<? extends AnnotationTree> annos =
newClassTree.getClassBody().getModifiers().getAnnotations();
type.addAnnotations(TreeUtils.annotationsFromTypeAnnotationTrees(annos));
type.setEnclosingType(enclosingType);
return type;
} else {
// If newClassTree does not create anonymous class,
// newClassTree.getIdentifier includes the explicit annotations in this location:
// new @HERE Class()
AnnotatedDeclaredType type =
(AnnotatedDeclaredType)
TypeFromTree.fromTypeTree(this, newClassTree.getIdentifier());
type.setEnclosingType(enclosingType);
return type;
}
}
// This method extracts the ugly hacky parts.
// This method should be rewritten and in particular diamonds should be
// implemented cleanly.
// See Issue 289.
private void fromNewClassContextHelper(
AnnotatedDeclaredType type, AnnotatedTypeMirror ctxtype) {
switch (ctxtype.getKind()) {
case DECLARED:
AnnotatedDeclaredType adctx = (AnnotatedDeclaredType) ctxtype;
if (type.getTypeArguments().size() == adctx.getTypeArguments().size()) {
// Try to simply take the type arguments from LHS.
List<AnnotatedTypeMirror> oldArgs = type.getTypeArguments();
List<AnnotatedTypeMirror> newArgs = adctx.getTypeArguments();
for (int i = 0; i < type.getTypeArguments().size(); ++i) {
if (!types.isSubtype(
newArgs.get(i).actualType, oldArgs.get(i).actualType)) {
// One of the underlying types doesn't match. Give up.
return;
}
}
type.setTypeArguments(newArgs);
/* It would be nice to call isSubtype for a basic sanity check.
* However, the type might not have been completely initialized yet,
* so isSubtype might fail.
*
if (!typeHierarchy.isSubtype(type, ctxtype)) {
// Simply taking the newArgs didn't result in a valid subtype.
// Give up and simply use the inferred types.
type.setTypeArguments(oldArgs);
}
*/
} else {
// TODO: Find a way to determine annotated type arguments.
// Look at what Attr and Resolve are doing and rework this whole method.
}
break;
case ARRAY:
// This new class is in the initializer of an array.
// The array being created can't have a generic component type,
// so nothing to be done.
break;
case TYPEVAR:
// TODO: this should NOT be necessary.
// org.checkerframework.dataflow.cfg.node.MethodAccessNode.MethodAccessNode(ExpressionTree, Node)
// Uses an ExecutableElement, which did not substitute type variables.
break;
case WILDCARD:
// TODO: look at bounds of wildcard and see whether we can improve.
break;
default:
if (ctxtype.getKind().isPrimitive()) {
// See Issue 438. Ignore primitive types for diamond inference - a primitive
// type is never a suitable context anyway.
} else {
throw new BugInCF(
"AnnotatedTypeFactory.fromNewClassContextHelper: unexpected context: "
+ ctxtype
+ " ("
+ ctxtype.getKind()
+ ")");
}
}
}
/**
* Returns the annotated boxed type of the given primitive type. The returned type would only
* have the annotations on the given type.
*
* <p>Subclasses may override this method safely to override this behavior.
*
* @param type the primitive type
* @return the boxed declared type of the passed primitive type
*/
public AnnotatedDeclaredType getBoxedType(AnnotatedPrimitiveType type) {
TypeElement typeElt = types.boxedClass(type.getUnderlyingType());
AnnotatedDeclaredType dt = fromElement(typeElt);
dt.addAnnotations(type.getAnnotations());
return dt;
}
/**
* returns the annotated primitive type of the given declared type if it is a boxed declared
* type. Otherwise, it throws <i>IllegalArgumentException</i> exception.
*
* <p>The returned type would have the annotations on the given type and nothing else.
*
* @param type the declared type
* @return the unboxed primitive type
* @throws IllegalArgumentException if the type given has no unbox conversion
*/
public AnnotatedPrimitiveType getUnboxedType(AnnotatedDeclaredType type)
throws IllegalArgumentException {
PrimitiveType primitiveType = types.unboxedType(type.getUnderlyingType());
AnnotatedPrimitiveType pt =
(AnnotatedPrimitiveType) AnnotatedTypeMirror.createType(primitiveType, this, false);
pt.addAnnotations(type.getAnnotations());
return pt;
}
/**
* Returns AnnotatedDeclaredType with underlying type String and annotations copied from type.
* Subclasses may change the annotations.
*
* @param type type to convert to String
* @return AnnotatedTypeMirror that results from converting type to a String type
*/
// TODO: Test that this is called in all the correct locations
// See Issue #715
// https://github.com/typetools/checker-framework/issues/715
public AnnotatedDeclaredType getStringType(AnnotatedTypeMirror type) {
TypeMirror stringTypeMirror = TypesUtils.typeFromClass(String.class, types, elements);
AnnotatedDeclaredType stringATM =
(AnnotatedDeclaredType)
AnnotatedTypeMirror.createType(
stringTypeMirror, this, type.isDeclaration());
stringATM.addAnnotations(type.getEffectiveAnnotations());
return stringATM;
}
/**
* Returns AnnotatedPrimitiveType with underlying type {@code narrowedTypeMirror} and
* annotations copied from {@code type}.
*
* <p>Currently this method is called only for primitives that are narrowed at assignments from
* literal ints, for example, {@code byte b = 1;}. All other narrowing conversions happen at
* typecasts.
*
* @param type type to narrow
* @param narrowedTypeMirror underlying type for the returned type mirror
* @return result of converting {@code type} to {@code narrowedTypeMirror}
*/
public AnnotatedPrimitiveType getNarrowedPrimitive(
AnnotatedPrimitiveType type, TypeMirror narrowedTypeMirror) {
AnnotatedPrimitiveType narrowed =
(AnnotatedPrimitiveType)
AnnotatedTypeMirror.createType(
narrowedTypeMirror, this, type.isDeclaration());
narrowed.addAnnotations(type.getAnnotations());
return narrowed;
}
/** Returns the VisitorState instance used by the factory to infer types. */
public VisitorState getVisitorState() {
return this.visitorState;
}
// **********************************************************************
// random methods wrapping #getAnnotatedType(Tree) and #fromElement(Tree)
// with appropriate casts to reduce casts on the client side
// **********************************************************************
/** @see #getAnnotatedType(Tree) */
public final AnnotatedDeclaredType getAnnotatedType(ClassTree tree) {
return (AnnotatedDeclaredType) getAnnotatedType((Tree) tree);
}
/** @see #getAnnotatedType(Tree) */
public final AnnotatedDeclaredType getAnnotatedType(NewClassTree tree) {
return (AnnotatedDeclaredType) getAnnotatedType((Tree) tree);
}
/** @see #getAnnotatedType(Tree) */
public final AnnotatedArrayType getAnnotatedType(NewArrayTree tree) {
return (AnnotatedArrayType) getAnnotatedType((Tree) tree);
}
/** @see #getAnnotatedType(Tree) */
public final AnnotatedExecutableType getAnnotatedType(MethodTree tree) {
return (AnnotatedExecutableType) getAnnotatedType((Tree) tree);
}
/** @see #getAnnotatedType(Element) */
public final AnnotatedDeclaredType getAnnotatedType(TypeElement elt) {
return (AnnotatedDeclaredType) getAnnotatedType((Element) elt);
}
/** @see #getAnnotatedType(Element) */
public final AnnotatedExecutableType getAnnotatedType(ExecutableElement elt) {
return (AnnotatedExecutableType) getAnnotatedType((Element) elt);
}
/** @see #fromElement(Element) */
public final AnnotatedDeclaredType fromElement(TypeElement elt) {
return (AnnotatedDeclaredType) fromElement((Element) elt);
}
/** @see #fromElement(Element) */
public final AnnotatedExecutableType fromElement(ExecutableElement elt) {
return (AnnotatedExecutableType) fromElement((Element) elt);
}
// **********************************************************************
// Helper methods for this classes
// **********************************************************************
/**
* Determines whether the given annotation is a part of the type system under which this type
* factory operates. Null is never a supported qualifier; the parameter is nullable to allow the
* result of canonicalAnnotation to be passed in directly.
*
* @param a any annotation
* @return true if that annotation is part of the type system under which this type factory
* operates, false otherwise
*/
public boolean isSupportedQualifier(@Nullable AnnotationMirror a) {
if (a == null) {
return false;
}
return isSupportedQualifier(AnnotationUtils.annotationName(a));
}
/**
* Determines whether the given class is a part of the type system under which this type factory
* operates.
*
* @param clazz annotation class
* @return true if that class is a type qualifier in the type system under which this type
* factory operates, false otherwise
*/
public boolean isSupportedQualifier(Class<? extends Annotation> clazz) {
return getSupportedTypeQualifiers().contains(clazz);
}
/**
* Determines whether the given class name is a part of the type system under which this type
* factory operates.
*
* @param className fully-qualified annotation class name
* @return true if that class name is a type qualifier in the type system under which this type
* factory operates, false otherwise
*/
public boolean isSupportedQualifier(String className) {
return getSupportedTypeQualifierNames().contains(className);
}
/**
* Adds the annotation {@code aliasClass} as an alias for the canonical annotation {@code type}
* that will be used by the Checker Framework in the alias's place.
*
* <p>By specifying the alias/canonical relationship using this method, the elements of the
* alias are not preserved when the canonical annotation to use is constructed from the alias.
* If you want the elements to be copied over as well, use {@link #addAliasedAnnotation(Class,
* Class, boolean, String...)}.
*
* @param aliasClass the class of the aliased annotation
* @param type the canonical annotation
*/
protected void addAliasedAnnotation(Class<?> aliasClass, AnnotationMirror type) {
if (getSupportedTypeQualifiers().contains(aliasClass)) {
throw new BugInCF(
"AnnotatedTypeFactory: alias %s should not be in type hierarchy for %s",
aliasClass, this.getClass().getSimpleName());
}
addAliasedAnnotation(aliasClass.getCanonicalName(), type);
}
/**
* Adds the annotation, whose fully-qualified name is given by {@code aliasName}, as an alias
* for the canonical annotation {@code type} that will be used by the Checker Framework in the
* alias's place.
*
* <p>Use this method if the alias class is not necessarily on the classpath at Checker
* Framework compile and run time. Otherwise, use {@link #addAliasedAnnotation(Class,
* AnnotationMirror)} which prevents the possibility of a typo in the class name.
*
* @param aliasName the fully-qualified name of the aliased annotation
* @param type the canonical annotation
*/
protected void addAliasedAnnotation(String aliasName, AnnotationMirror type) {
aliases.put(aliasName, new Alias(aliasName, type, false, null, null));
}
/**
* Adds the annotation {@code aliasClass} as an alias for the canonical annotation {@code type}
* that will be used by the Checker Framework in the alias's place.
*
* <p>You may specify the copyElements flag to indicate whether you want the elements of the
* alias to be copied over when the canonical annotation is constructed as a copy of {@code
* type}. Be careful that the framework will try to copy the elements by name matching, so make
* sure that names and types of the elements to be copied over are exactly the same as the ones
* in the canonical annotation. Otherwise, an 'Couldn't find element in annotation' error is
* raised.
*
* <p>To facilitate the cases where some of the elements is ignored on purpose when constructing
* the canonical annotation, this method also provides a varargs {@code ignorableElements} for
* you to explicitly specify the ignoring rules. For example, {@code
* org.checkerframework.checker.index.qual.IndexFor} is an alias of {@code
* org.checkerframework.checker.index.qual.NonNegative}, but the element "value" of
* {@code @IndexFor} should be ignored when constructing {@code @NonNegative}. In the cases
* where all elements are ignored, we can simply use {@link #addAliasedAnnotation(Class,
* AnnotationMirror)} instead.
*
* @param aliasClass the class of the aliased annotation
* @param canonical the canonical annotation
* @param copyElements a flag that indicates whether you want to copy the elements over when
* getting the alias from the canonical annotation
* @param ignorableElements a list of elements that can be safely dropped when the elements are
* being copied over
*/
protected void addAliasedAnnotation(
Class<?> aliasClass,
Class<?> canonical,
boolean copyElements,
String... ignorableElements) {
if (getSupportedTypeQualifiers().contains(aliasClass)) {
throw new BugInCF(
"AnnotatedTypeFactory: alias %s should not be in type hierarchy for %s",
aliasClass, this.getClass().getSimpleName());
}
addAliasedAnnotation(
aliasClass.getCanonicalName(), canonical, copyElements, ignorableElements);
}
/**
* Adds the annotation, whose fully-qualified name is given by {@code aliasName}, as an alias
* for the canonical annotation {@code type} that will be used by the Checker Framework in the
* alias's place.
*
* <p>Use this method if the alias class is not necessarily on the classpath at Checker
* Framework compile and run time. Otherwise, use {@link #addAliasedAnnotation(Class, Class,
* boolean, String[])} which prevents the possibility of a typo in the class name.
*
* @param aliasName the fully-qualified name of the aliased class
* @param canonicalName the canonical annotation name
* @param copyElements a flag that indicates whether we want to copy the elements over when
* getting the alias from the canonical annotation
* @param ignorableElements a list of elements that can be safely dropped when the elements are
* being copied over
*/
protected void addAliasedAnnotation(
String aliasName,
Class<?> canonicalName,
boolean copyElements,
String... ignorableElements) {
// The copyElements argument disambiguates overloading.
if (!copyElements) {
throw new BugInCF("Do not call with false");
}
aliases.put(
aliasName,
new Alias(
aliasName,
null,
copyElements,
canonicalName.getCanonicalName(),
ignorableElements));
}
/**
* Returns the canonical annotation for the passed annotation. Returns null if the passed
* annotation is not an alias of a canonical one in the framework.
*
* <p>A canonical annotation is the internal annotation that will be used by the Checker
* Framework in the aliased annotation's place.
*
* @param a the qualifier to check for an alias
* @return the canonical annotation, or null if none exists
*/
public @Nullable AnnotationMirror canonicalAnnotation(AnnotationMirror a) {
TypeElement elem = (TypeElement) a.getAnnotationType().asElement();
String qualName = elem.getQualifiedName().toString();
Alias alias = aliases.get(qualName);
if (alias == null) {
return null;
}
if (alias.copyElements) {
AnnotationBuilder builder = new AnnotationBuilder(processingEnv, alias.canonicalName);
builder.copyElementValuesFromAnnotation(a, alias.ignorableElements);
return builder.build();
} else {
return alias.canonical;
}
}
/**
* Add the annotation {@code alias} as an alias for the declaration annotation {@code
* annotation}, where the annotation mirror {@code annotationToUse} will be used instead. If
* multiple calls are made with the same {@code annotation}, then the {@code annotationToUse}
* must be the same.
*
* <p>The point of {@code annotationToUse} is that it may include elements/fields.
*/
protected void addAliasedDeclAnnotation(
Class<? extends Annotation> alias,
Class<? extends Annotation> annotation,
AnnotationMirror annotationToUse) {
Pair<AnnotationMirror, Set<Class<? extends Annotation>>> pair = declAliases.get(annotation);
if (pair != null) {
if (!AnnotationUtils.areSame(annotationToUse, pair.first)) {
throw new BugInCF(
"annotationToUse should be the same: %s %s", pair.first, annotationToUse);
}
} else {
pair = Pair.of(annotationToUse, new HashSet<>());
declAliases.put(annotation, pair);
}
Set<Class<? extends Annotation>> aliases = pair.second;
aliases.add(alias);
}
/**
* Adds the annotation {@code annotation} in the set of declaration annotations that should be
* inherited. A declaration annotation will be inherited if it is in this list, or if it has the
* meta-annotation @InheritedAnnotation. The meta-annotation @InheritedAnnotation should be used
* instead of this method, if possible.
*/
protected void addInheritedAnnotation(AnnotationMirror annotation) {
inheritedAnnotations.add(annotation);
}
/**
* A convenience method that converts a {@link TypeMirror} to an empty {@link
* AnnotatedTypeMirror} using {@link AnnotatedTypeMirror#createType}.
*
* @param t the {@link TypeMirror}
* @param declaration true if the result should be marked as a type declaration
* @return an {@link AnnotatedTypeMirror} that has {@code t} as its underlying type
*/
protected final AnnotatedTypeMirror toAnnotatedType(TypeMirror t, boolean declaration) {
return AnnotatedTypeMirror.createType(t, this, declaration);
}
/**
* Determines an empty annotated type of the given tree. In other words, finds the {@link
* TypeMirror} for the tree and converts that into an {@link AnnotatedTypeMirror}, but does not
* add any annotations to the result.
*
* <p>Most users will want to use {@link #getAnnotatedType(Tree)} instead; this method is mostly
* for internal use.
*
* @param node the tree to analyze
* @return the type of {@code node}, without any annotations
*/
protected final AnnotatedTypeMirror type(Tree node) {
boolean isDeclaration = TreeUtils.isTypeDeclaration(node);
// Attempt to obtain the type via JCTree.
if (TreeUtils.typeOf(node) != null) {
AnnotatedTypeMirror result = toAnnotatedType(TreeUtils.typeOf(node), isDeclaration);
return result;
}
// Attempt to obtain the type via TreePath (slower).
TreePath path = this.getPath(node);
assert path != null : "No path or type in tree: " + node;
TypeMirror t = trees.getTypeMirror(path);
assert validType(t) : "Invalid type " + t + " for node " + t;
return toAnnotatedType(t, isDeclaration);
}
/**
* Gets the declaration tree for the element, if the source is available.
*
* <p>TODO: would be nice to move this to InternalUtils/TreeUtils.
*
* @param elt an element
* @return the tree declaration of the element if found
*/
public final Tree declarationFromElement(Element elt) {
// if root is null, we cannot find any declaration
if (root == null) {
return null;
}
if (shouldCache && elementToTreeCache.containsKey(elt)) {
return elementToTreeCache.get(elt);
}
// Check for new declarations, outside of the AST.
if (elt instanceof DetachedVarSymbol) {
return ((DetachedVarSymbol) elt).getDeclaration();
}
// TODO: handle type parameter declarations?
Tree fromElt;
// Prevent calling declarationFor on elements we know we don't have
// the tree for
switch (elt.getKind()) {
case CLASS:
case ENUM:
case INTERFACE:
case ANNOTATION_TYPE:
case FIELD:
case ENUM_CONSTANT:
case METHOD:
case CONSTRUCTOR:
fromElt = trees.getTree(elt);
break;
default:
fromElt =
com.sun.tools.javac.tree.TreeInfo.declarationFor(
(com.sun.tools.javac.code.Symbol) elt,
(com.sun.tools.javac.tree.JCTree) root);
break;
}
if (shouldCache) {
elementToTreeCache.put(elt, fromElt);
}
return fromElt;
}
/**
* Returns the current class type being visited by the visitor. The method uses the parameter
* only if the most enclosing class cannot be found directly.
*
* @return type of the most enclosing class being visited
*/
// This method is used to wrap access to visitorState
protected final ClassTree getCurrentClassTree(Tree tree) {
if (visitorState.getClassTree() != null) {
return visitorState.getClassTree();
}
return TreeUtils.enclosingClass(getPath(tree));
}
protected final AnnotatedDeclaredType getCurrentClassType(Tree tree) {
return getAnnotatedType(getCurrentClassTree(tree));
}
/**
* Returns the receiver type of the current method being visited, and returns null if the
* visited tree is not within a method or if that method has no receiver (e.g. a static method).
*
* <p>The method uses the parameter only if the most enclosing method cannot be found directly.
*
* @return receiver type of the most enclosing method being visited
*/
protected final @Nullable AnnotatedDeclaredType getCurrentMethodReceiver(Tree tree) {
AnnotatedDeclaredType res = visitorState.getMethodReceiver();
if (res == null) {
TreePath path = getPath(tree);
if (path != null) {
MethodTree enclosingMethod = TreeUtils.enclosingMethod(path);
ClassTree enclosingClass = TreeUtils.enclosingClass(path);
boolean found = false;
for (Tree member : enclosingClass.getMembers()) {
if (member.getKind() == Tree.Kind.METHOD) {
if (member == enclosingMethod) {
found = true;
}
}
}
if (found && enclosingMethod != null) {
AnnotatedExecutableType method = getAnnotatedType(enclosingMethod);
res = method.getReceiverType();
// TODO: three tests fail if one adds the following, which would make
// sense, or not?
// visitorState.setMethodReceiver(res);
} else {
// We are within an anonymous class or field initializer
res = this.getAnnotatedType(enclosingClass);
}
}
}
return res;
}
protected final boolean isWithinConstructor(Tree tree) {
if (visitorState.getClassType() != null) {
return visitorState.getMethodTree() != null
&& TreeUtils.isConstructor(visitorState.getMethodTree());
}
MethodTree enclosingMethod = TreeUtils.enclosingMethod(getPath(tree));
return enclosingMethod != null && TreeUtils.isConstructor(enclosingMethod);
}
private final Element getMostInnerClassOrMethod(Tree tree) {
if (visitorState.getMethodTree() != null) {
return TreeUtils.elementFromDeclaration(visitorState.getMethodTree());
}
if (visitorState.getClassTree() != null) {
return TreeUtils.elementFromDeclaration(visitorState.getClassTree());
}
TreePath path = getPath(tree);
if (path == null) {
throw new BugInCF(
String.format(
"AnnotatedTypeFactory.getMostInnerClassOrMethod: getPath(tree)=>null%n TreePath.getPath(root, tree)=>%s\n for tree (%s) = %s%n root=%s",
TreePath.getPath(root, tree), tree.getClass(), tree, root));
}
for (Tree pathTree : path) {
if (pathTree instanceof MethodTree) {
return TreeUtils.elementFromDeclaration((MethodTree) pathTree);
} else if (pathTree instanceof ClassTree) {
return TreeUtils.elementFromDeclaration((ClassTree) pathTree);
}
}
throw new BugInCF("AnnotatedTypeFactory.getMostInnerClassOrMethod: cannot be here");
}
/**
* Gets the path for the given {@link Tree} under the current root by checking from the
* visitor's current path, and only using {@link Trees#getPath(CompilationUnitTree, Tree)}
* (which is much slower) only if {@code node} is not found on the current path.
*
* <p>Note that the given Tree has to be within the current compilation unit, otherwise null
* will be returned.
*
* @param node the {@link Tree} to get the path for
* @return the path for {@code node} under the current root
*/
public final TreePath getPath(Tree node) {
assert root != null
: "AnnotatedTypeFactory.getPath: root needs to be set when used on trees; factory: "
+ this.getClass();
if (node == null) {
return null;
}
if (treePathCache.isCached(node)) {
return treePathCache.getPath(root, node);
}
TreePath currentPath = visitorState.getPath();
if (currentPath == null) {
TreePath path = TreePath.getPath(root, node);
treePathCache.addPath(node, path);
return path;
}
// This method uses multiple heuristics to avoid calling
// TreePath.getPath()
// If the current path you are visiting is for this node we are done
if (currentPath.getLeaf() == node) {
treePathCache.addPath(node, currentPath);
return currentPath;
}
// When running on Daikon, we noticed that a lot of calls happened
// within a small subtree containing the node we are currently visiting
// When testing on Daikon, two steps resulted in the best performance
if (currentPath.getParentPath() != null) {
currentPath = currentPath.getParentPath();
treePathCache.addPath(currentPath.getLeaf(), currentPath);
if (currentPath.getLeaf() == node) {
return currentPath;
}
if (currentPath.getParentPath() != null) {
currentPath = currentPath.getParentPath();
treePathCache.addPath(currentPath.getLeaf(), currentPath);
if (currentPath.getLeaf() == node) {
return currentPath;
}
}
}
final TreePath pathWithinSubtree = TreePath.getPath(currentPath, node);
if (pathWithinSubtree != null) {
treePathCache.addPath(node, pathWithinSubtree);
return pathWithinSubtree;
}
// climb the current path till we see that
// Works when getPath called on the enclosing method, enclosing
// class
TreePath current = currentPath;
while (current != null) {
treePathCache.addPath(current.getLeaf(), current);
if (current.getLeaf() == node) {
return current;
}
current = current.getParentPath();
}
// OK, we give up. Use the cache to look up.
return treePathCache.getPath(root, node);
}
/**
* Gets the {@link Element} representing the declaration of the method enclosing a tree node.
* This feature is used to record the enclosing methods of {@link Tree}s that are created
* internally by the checker.
*
* <p>TODO: Find a better way to store information about enclosing Trees.
*
* @param node the {@link Tree} to get the enclosing method for
* @return the method {@link Element} enclosing the argument, or null if none has been recorded
*/
public final Element getEnclosingElementForArtificialTree(Tree node) {
return artificialTreeToEnclosingElementMap.get(node);
}
/**
* Handle an artificial tree by mapping it to the enclosing element.
*
* <p>See {@code
* org.checkerframework.framework.flow.CFCFGBuilder.CFCFGTranslationPhaseOne.handleArtificialTree(Tree)}.
*/
public final void setEnclosingElementForArtificialTree(Tree node, Element enclosing) {
artificialTreeToEnclosingElementMap.put(node, enclosing);
}
/**
* Assert that the type is a type of valid type mirror, i.e. not an ERROR or OTHER type.
*
* @param type an annotated type
* @return true if the type is a valid annotated type, false otherwise
*/
static final boolean validAnnotatedType(AnnotatedTypeMirror type) {
if (type == null) {
return false;
}
return validType(type.getUnderlyingType());
}
/**
* Used for asserting that a type is valid for converting to an annotated type.
*
* @return true if {@code type} can be converted to an annotated type, false otherwise
*/
private static final boolean validType(TypeMirror type) {
if (type == null) {
return false;
}
switch (type.getKind()) {
case ERROR:
case OTHER:
case PACKAGE:
return false;
default:
return true;
}
}
/**
* Parses the stub files in the following order:
*
* <ol>
* <li>jdk.astub in the same directory as the checker, if it exists and ignorejdkastub option
* is not supplied <br>
* <li>jdkN.astub, where N is the Java version in the same directory as the checker, if it
* exists and ignorejdkastub option is not supplied <br>
* <li>Stub files listed in @StubFiles annotation on the checker; must be in same directory as
* the checker<br>
* <li>Stub files provide via stubs system property <br>
* <li>Stub files provide via stubs environment variable <br>
* <li>Stub files provide via stubs compiler option
* </ol>
*
* <p>If a type is annotated with a qualifier from the same hierarchy in more than one stub
* file, the qualifier in the last stub file is applied.
*
* <p>Sets typesFromStubFiles and declAnnosFromStubFiles by side effect, just before returning.
*/
protected void parseStubFiles() {
stubTypes.parseStubFiles();
}
/**
* Returns the actual annotation mirror used to annotate this element, whose name equals the
* passed annotation class (or is an alias for it). Returns null if none exists.
*
* @see #getDeclAnnotationNoAliases
* @param elt the element to retrieve the declaration annotation from
* @param anno annotation class
* @return the annotation mirror for anno
*/
@Override
public final AnnotationMirror getDeclAnnotation(Element elt, Class<? extends Annotation> anno) {
return getDeclAnnotation(elt, anno, true);
}
/**
* Returns the actual annotation mirror used to annotate this element, whose name equals the
* passed annotation class. Returns null if none exists. Does not check for aliases of the
* annotation class.
*
* <p>Call this method from a checker that needs to alias annotations for one purpose and not
* for another. For example, in the Lock Checker, {@code @LockingFree} and
* {@code @ReleasesNoLocks} are both aliases of {@code @SideEffectFree} since they are all
* considered side-effect-free with regard to the set of locks held before and after the method
* call. However, a {@code synchronized} block is permitted inside a {@code @ReleasesNoLocks}
* method but not inside a {@code @LockingFree} or {@code @SideEffectFree} method.
*
* @see #getDeclAnnotation
* @param elt the element to retrieve the declaration annotation from
* @param anno annotation class
* @return the annotation mirror for anno
*/
public final AnnotationMirror getDeclAnnotationNoAliases(
Element elt, Class<? extends Annotation> anno) {
return getDeclAnnotation(elt, anno, false);
}
/**
* Returns true if the element appears in a stub file (Currently only works for methods,
* constructors, and fields).
*/
public boolean isFromStubFile(Element element) {
return this.getDeclAnnotation(element, FromStubFile.class) != null;
}
/**
* Returns true if the element is from bytecode and the if the element did not appear in a stub
* file. Currently only works for methods, constructors, and fields.
*/
public boolean isFromByteCode(Element element) {
if (isFromStubFile(element)) {
return false;
}
return ElementUtils.isElementFromByteCode(element);
}
/**
* Returns true if redundancy between a stub file and bytecode should be reported.
*
* <p>For most type systems the default behavior of returning true is correct. For subcheckers,
* redundancy in one of the type hierarchies can be ok. Such implementations should return
* false.
*
* @return whether to warn about redundancy between a stub file and bytecode
*/
public boolean shouldWarnIfStubRedundantWithBytecode() {
return true;
}
/**
* Returns the actual annotation mirror used to annotate this element, whose name equals the
* passed annotation class (or is an alias for it). Returns null if none exists. May return the
* canonical annotation that annotationName is an alias for.
*
* <p>This is the private implementation of the same-named, public method.
*
* <p>An option is provided to not to check for aliases of annotations. For example, an
* annotated type factory may use aliasing for a pair of annotations for convenience while
* needing in some cases to determine a strict ordering between them, such as when determining
* whether the annotations on an overrider method are more specific than the annotations of an
* overridden method.
*
* @param elt the element to retrieve the annotation from
* @param annoClass the class the annotation to retrieve
* @param checkAliases whether to return an annotation mirror for an alias of the requested
* annotation class name
* @return the annotation mirror for the requested annotation, or null if not found
*/
private AnnotationMirror getDeclAnnotation(
Element elt, Class<? extends Annotation> annoClass, boolean checkAliases) {
Set<AnnotationMirror> declAnnos = getDeclAnnotations(elt);
for (AnnotationMirror am : declAnnos) {
if (areSameByClass(am, annoClass)) {
return am;
}
}
// Look through aliases.
if (checkAliases) {
Pair<AnnotationMirror, Set<Class<? extends Annotation>>> aliases =
declAliases.get(annoClass);
if (aliases != null) {
for (Class<? extends Annotation> alias : aliases.second) {
for (AnnotationMirror am : declAnnos) {
if (areSameByClass(am, alias)) {
// TODO: need to copy over elements/fields
return aliases.first;
}
}
}
}
}
// Not found.
return null;
}
/**
* Returns all of the actual annotation mirrors used to annotate this element (includes stub
* files and declaration annotations from overridden methods).
*
* @param elt the element for which to determine annotations
* @return declaration annotations on this element
*/
public Set<AnnotationMirror> getDeclAnnotations(Element elt) {
Set<AnnotationMirror> cachedValue = cacheDeclAnnos.get(elt);
if (cachedValue != null) {
// Found in cache, return result.
return cachedValue;
}
Set<AnnotationMirror> results = AnnotationUtils.createAnnotationSet();
// Retrieving the annotations from the element.
List<? extends AnnotationMirror> fromEle = elements.getAllAnnotationMirrors(elt);
for (AnnotationMirror annotation : fromEle) {
try {
results.add(annotation);
} catch (com.sun.tools.javac.code.Symbol.CompletionFailure cf) {
// If a CompletionFailure occurs, issue a warning.
checker.report(
Result.warning(
"annotation.not.completed",
ElementUtils.getVerboseName(elt),
annotation),
annotation.getAnnotationType().asElement());
}
}
// If parsing stub files, return the annotations in the element.
if (!stubTypes.isParsing()) {
// Retrieving annotations from stub files.
Set<AnnotationMirror> stubAnnos = stubTypes.getDeclAnnotation(elt);
results.addAll(stubAnnos);
if (elt.getKind() == ElementKind.METHOD) {
// Retrieve the annotations from the overridden method's element.
inheritOverriddenDeclAnnos((ExecutableElement) elt, results);
}
// Add the element and its annotations to the cache.
cacheDeclAnnos.put(elt, results);
}
return results;
}
/**
* Adds into {@code results} the declaration annotations found in all elements that the method
* element {@code elt} overrides.
*
* @param elt method element
* @param results {@code elt} local declaration annotations. The ones found in stub files and in
* the element itself.
*/
private void inheritOverriddenDeclAnnos(ExecutableElement elt, Set<AnnotationMirror> results) {
Map<AnnotatedDeclaredType, ExecutableElement> overriddenMethods =
AnnotatedTypes.overriddenMethods(elements, this, elt);
if (overriddenMethods != null) {
for (ExecutableElement superElt : overriddenMethods.values()) {
Set<AnnotationMirror> superAnnos = getDeclAnnotations(superElt);
for (AnnotationMirror annotation : superAnnos) {
List<? extends AnnotationMirror> annotationsOnAnnotation;
try {
annotationsOnAnnotation =
annotation.getAnnotationType().asElement().getAnnotationMirrors();
} catch (com.sun.tools.javac.code.Symbol.CompletionFailure cf) {
// Fix for Issue 348: If a CompletionFailure occurs,
// issue a warning.
checker.report(
Result.warning(
"annotation.not.completed",
ElementUtils.getVerboseName(elt),
annotation),
annotation.getAnnotationType().asElement());
continue;
}
if (containsSameByClass(annotationsOnAnnotation, InheritedAnnotation.class)
|| AnnotationUtils.containsSameByName(
inheritedAnnotations, annotation)) {
addOrMerge(results, annotation);
}
}
}
}
}
private void addOrMerge(Set<AnnotationMirror> results, AnnotationMirror annotation) {
if (AnnotationUtils.containsSameByName(results, annotation)) {
/*
* TODO: feature request: figure out a way to merge multiple annotations
* of the same kind. For some annotations this might mean merging some
* arrays, for others it might mean converting a single annotation into a
* container annotation. We should define a protected method for subclasses
* to adapt the behavior.
* For now, do nothing and just take the first, most concrete, annotation.
AnnotationMirror prev = null;
for (AnnotationMirror an : results) {
if (AnnotationUtils.areSameByName(an, annotation)) {
prev = an;
break;
}
}
results.remove(prev);
AnnotationMirror merged = ...;
results.add(merged);
*/
} else {
results.add(annotation);
}
}
/**
* Returns a list of all declaration annotations used to annotate this element, which have a
* meta-annotation (i.e., an annotation on that annotation) with class {@code
* metaAnnotationClass}.
*
* @param element the element for which to determine annotations
* @param metaAnnotationClass the class of the meta-annotation that needs to be present
* @return a list of pairs {@code (anno, metaAnno)} where {@code anno} is the annotation mirror
* at {@code element}, and {@code metaAnno} is the annotation mirror (of type {@code
* metaAnnotationClass}) used to annotate {@code anno}.
*/
public List<Pair<AnnotationMirror, AnnotationMirror>> getDeclAnnotationWithMetaAnnotation(
Element element, Class<? extends Annotation> metaAnnotationClass) {
List<Pair<AnnotationMirror, AnnotationMirror>> result = new ArrayList<>();
Set<AnnotationMirror> annotationMirrors = getDeclAnnotations(element);
// Go through all annotations found.
for (AnnotationMirror annotation : annotationMirrors) {
List<? extends AnnotationMirror> annotationsOnAnnotation;
try {
annotationsOnAnnotation =
annotation.getAnnotationType().asElement().getAnnotationMirrors();
} catch (com.sun.tools.javac.code.Symbol.CompletionFailure cf) {
// Fix for Issue 309: If a CompletionFailure occurs, issue a warning.
// I didn't find a nicer alternative to check whether the Symbol can be completed.
// The completer field of a Symbol might be non-null also in successful cases.
// Issue a warning (exception only happens once) and continue.
checker.report(
Result.warning(
"annotation.not.completed",
ElementUtils.getVerboseName(element),
annotation),
annotation.getAnnotationType().asElement());
continue;
}
// First call copier, if exception, continue normal modula laws.
for (AnnotationMirror a : annotationsOnAnnotation) {
if (areSameByClass(a, metaAnnotationClass)) {
result.add(Pair.of(annotation, a));
}
}
}
return result;
}
/**
* Returns a list of all annotations used to annotate this element, which have a meta-annotation
* (i.e., an annotation on that annotation) with class {@code metaAnnotationClass}.
*
* @param element the element at which to look for annotations
* @param metaAnnotationClass the class of the meta-annotation that needs to be present
* @return a list of pairs {@code (anno, metaAnno)} where {@code anno} is the annotation mirror
* at {@code element}, and {@code metaAnno} is the annotation mirror used to annotate {@code
* anno}.
*/
public List<Pair<AnnotationMirror, AnnotationMirror>> getAnnotationWithMetaAnnotation(
Element element, Class<? extends Annotation> metaAnnotationClass) {
List<Pair<AnnotationMirror, AnnotationMirror>> result = new ArrayList<>();
Set<AnnotationMirror> annotationMirrors = AnnotationUtils.createAnnotationSet();
// Consider real annotations.
annotationMirrors.addAll(getAnnotatedType(element).getAnnotations());
// Consider declaration annotations
annotationMirrors.addAll(getDeclAnnotations(element));
// Go through all annotations found.
for (AnnotationMirror annotation : annotationMirrors) {
List<? extends AnnotationMirror> annotationsOnAnnotation =
annotation.getAnnotationType().asElement().getAnnotationMirrors();
for (AnnotationMirror a : annotationsOnAnnotation) {
if (areSameByClass(a, metaAnnotationClass)) {
result.add(Pair.of(annotation, a));
}
}
}
return result;
}
/**
* Returns a wildcard type to be used as a type argument when the correct type could not be
* inferred. The wildcard will be marked as an uninferred wildcard so that {@link
* AnnotatedWildcardType#isUninferredTypeArgument()} returns true.
*
* <p>This method should only be used by type argument inference.
* org.checkerframework.framework.util.AnnotatedTypes.inferTypeArguments(ProcessingEnvironment,
* AnnotatedTypeFactory, ExpressionTree, ExecutableElement)
*
* @param typeVar TypeVariable which could not be inferred
* @return a wildcard that is marked as an uninferred type argument
*/
public AnnotatedWildcardType getUninferredWildcardType(AnnotatedTypeVariable typeVar) {
final boolean intersectionType;
final TypeMirror boundType;
if (typeVar.getUpperBound().getKind() == TypeKind.INTERSECTION) {
boundType = typeVar.getUpperBound().directSuperTypes().get(0).getUnderlyingType();
intersectionType = true;
} else {
boundType = typeVar.getUnderlyingType().getUpperBound();
intersectionType = false;
}
WildcardType wc = types.getWildcardType(boundType, null);
AnnotatedWildcardType wctype =
(AnnotatedWildcardType) AnnotatedTypeMirror.createType(wc, this, false);
wctype.setTypeVariable(typeVar.getUnderlyingType());
if (!intersectionType) {
wctype.setExtendsBound(typeVar.getUpperBound().deepCopy());
} else {
wctype.getExtendsBound().addAnnotations(typeVar.getUpperBound().getAnnotations());
}
wctype.setSuperBound(typeVar.getLowerBound().deepCopy());
wctype.addAnnotations(typeVar.getAnnotations());
addDefaultAnnotations(wctype);
wctype.setUninferredTypeArgument();
return wctype;
}
/**
* If {@code wildcard}'s upper bound is a super type of {@code annotatedTypeMirror}, this method
* returns an AnnotatedTypeMirror with the same qualifiers as {@code annotatedTypeMirror}, but
* the underlying Java type is the most specific base type of {@code annotatedTypeMirror} whose
* erasure type is equivalent to the upper bound of {@code wildcard}.
*
* <p>Otherwise, returns {@code annotatedTypeMirror} unmodified.
*
* <p>For example:
*
* <pre>
* wildcard := @NonNull ? extends @NonNull Object
* annotatedTypeMirror := @Nullable String
*
* widenToUpperBound(annotatedTypeMirror, wildcard) returns @Nullable Object
* </pre>
*
* This method is needed because, the Java compiler allows wildcards to have upper bounds above
* the type variable upper bounds for which they are type arguments. For example, given the
* following parametric type:
*
* <pre>
* {@code class MyClass<T extends Number>}
* </pre>
*
* the following is legal:
*
* <pre>
* {@code MyClass<? extends Object>}
* </pre>
*
* This is sound because in Java the wildcard is capture converted to: {@code CAP#1 extends
* Number from capture of ? extends Object}.
*
* <p>Because the Checker Framework does not implement capture conversion, wildcard upper bounds
* may cause spurious errors in subtyping checks. This method prevents those errors by widening
* the upper bound of the type parameter.
*
* <p>This method widens the underlying Java type of the upper bound of the type parameter
* rather than narrowing the bound of the wildcard in order to avoid issuing an error with an
* upper bound that is not in source code.
*
* <p>The widened type should only be used for typing checks that require it. Using the widened
* type elsewhere would cause confusing error messages with types not in the source code.
*
* @param annotatedTypeMirror AnnotatedTypeMirror to widen
* @param wildcard AnnotatedWildcardType whose upper bound is used to widen
* @return {@code annotatedTypeMirror} widen to the upper bound of {@code wildcard}
*/
public AnnotatedTypeMirror widenToUpperBound(
final AnnotatedTypeMirror annotatedTypeMirror, final AnnotatedWildcardType wildcard) {
final TypeMirror toModifyTypeMirror = annotatedTypeMirror.getUnderlyingType();
final TypeMirror wildcardUBTypeMirror = wildcard.getExtendsBound().getUnderlyingType();
if (TypesUtils.isErasedSubtype(wildcardUBTypeMirror, toModifyTypeMirror, types)) {
return annotatedTypeMirror;
} else if (TypesUtils.isErasedSubtype(toModifyTypeMirror, wildcardUBTypeMirror, types)) {
return AnnotatedTypes.asSuper(this, annotatedTypeMirror, wildcard);
} else if (wildcardUBTypeMirror.getKind() == TypeKind.DECLARED
&& TypesUtils.getTypeElement(wildcardUBTypeMirror).getKind().isInterface()) {
// If the Checker Framework implemented capture conversion, then in this case, then
// the upper bound of the capture converted wildcard would be an intersection type.
// See JLS 15.1.10
// (https://docs.oracle.com/javase/specs/jls/se11/html/jls-5.html#jls-5.1.10)
// For example:
// class MyClass<@A T extends @B Number> {}
// MyClass<@C ? extends @D Serializable>
// The upper bound of the captured wildcard:
// glb(@B Number, @D Serializable) = @B Number & @D Serializable
// The about upper bound must be a subtype of the declared upper bound:
// @B Number & @D Serializable <: @B Number, which is always true.
// So, replace the upper bound at the declaration with the wildcard's upper bound so
// that the rest of the subtyping test pass.
return wildcard.getExtendsBound();
}
return annotatedTypeMirror;
}
/**
* Returns the function type that this member reference targets.
*
* <p>The function type is the type of the single method declared in the functional interface
* adapted as if it were invoked using the functional interface as the receiver expression.
*
* <p>The target type of a member reference is the type to which it is assigned or casted.
*
* @param tree member reference tree
* @return the function type that this method reference targets
*/
public AnnotatedExecutableType getFunctionTypeFromTree(MemberReferenceTree tree) {
return getFnInterfaceFromTree(tree).second;
}
/**
* Returns the function type that this lambda targets.
*
* <p>The function type is the type of the single method declared in the functional interface
* adapted as if it were invoked using the functional interface as the receiver expression.
*
* <p>The target type of a lambda is the type to which it is assigned or casted.
*
* @param tree lambda expression tree
* @return the function type that this lambda targets
*/
public AnnotatedExecutableType getFunctionTypeFromTree(LambdaExpressionTree tree) {
return getFnInterfaceFromTree(tree).second;
}
/**
* Returns the functional interface and the function type that this lambda or member references
* targets.
*
* <p>The function type is the type of the single method declared in the functional interface
* adapted as if it were invoked using the functional interface as the receiver expression.
*
* <p>The target type of a lambda or a method reference is the type to which it is assigned or
* casted.
*
* @param tree lambda expression tree or member reference tree
* @return the functional interface and the function type that this method reference or lambda
* targets
*/
public Pair<AnnotatedTypeMirror, AnnotatedExecutableType> getFnInterfaceFromTree(Tree tree) {
// Functional interface
AnnotatedTypeMirror functionalInterfaceType = getFunctionalInterfaceType(tree);
if (functionalInterfaceType.getKind() == TypeKind.DECLARED) {
makeGroundTargetType(
(AnnotatedDeclaredType) functionalInterfaceType,
(DeclaredType) TreeUtils.typeOf(tree));
}
// Functional method
Element fnElement = TreeUtils.findFunction(tree, processingEnv);
// Function type
AnnotatedExecutableType functionType =
(AnnotatedExecutableType)
AnnotatedTypes.asMemberOf(types, this, functionalInterfaceType, fnElement);
return Pair.of(functionalInterfaceType, functionType);
}
/**
* Get the AnnotatedDeclaredType for the FunctionalInterface from assignment context of the
* method reference or lambda expression which may be a variable assignment, a method call, or a
* cast.
*
* <p>The assignment context is not always correct, so we must search up the AST. It will
* recursively search for lambdas nested in lambdas.
*
* @param tree the tree of the lambda or method reference
* @return the functional interface type or an uninferred type argument
*/
private AnnotatedTypeMirror getFunctionalInterfaceType(Tree tree) {
Tree parentTree = getPath(tree).getParentPath().getLeaf();
switch (parentTree.getKind()) {
case PARENTHESIZED:
return getFunctionalInterfaceType(parentTree);
case TYPE_CAST:
TypeCastTree cast = (TypeCastTree) parentTree;
assert isFunctionalInterface(
trees.getTypeMirror(getPath(cast.getType())), parentTree, tree);
AnnotatedTypeMirror castATM = getAnnotatedType(cast.getType());
if (castATM.getKind() == TypeKind.INTERSECTION) {
AnnotatedIntersectionType itype = (AnnotatedIntersectionType) castATM;
for (AnnotatedTypeMirror t : itype.directSuperTypes()) {
if (TypesUtils.isFunctionalInterface(
t.getUnderlyingType(), getProcessingEnv())) {
return t;
}
}
// We should never reach here: isFunctionalInterface performs the same check
// and would have raised an error already.
throw new BugInCF(
String.format(
"Expected the type of a cast tree in an assignment context to contain a functional interface bound. "
+ "Found type: %s for tree: %s in lambda tree: %s",
castATM, cast, tree));
}
return castATM;
case NEW_CLASS:
NewClassTree newClass = (NewClassTree) parentTree;
int indexOfLambda = newClass.getArguments().indexOf(tree);
ParameterizedExecutableType con = this.constructorFromUse(newClass);
AnnotatedTypeMirror constructorParam =
AnnotatedTypes.getAnnotatedTypeMirrorOfParameter(
con.executableType, indexOfLambda);
assert isFunctionalInterface(
constructorParam.getUnderlyingType(), parentTree, tree);
return constructorParam;
case NEW_ARRAY:
NewArrayTree newArray = (NewArrayTree) parentTree;
AnnotatedArrayType newArrayATM = getAnnotatedType(newArray);
AnnotatedTypeMirror elementATM = newArrayATM.getComponentType();
assert isFunctionalInterface(elementATM.getUnderlyingType(), parentTree, tree);
return elementATM;
case METHOD_INVOCATION:
MethodInvocationTree method = (MethodInvocationTree) parentTree;
int index = method.getArguments().indexOf(tree);
ParameterizedExecutableType exe = this.methodFromUse(method);
AnnotatedTypeMirror param =
AnnotatedTypes.getAnnotatedTypeMirrorOfParameter(exe.executableType, index);
if (param.getKind() == TypeKind.WILDCARD) {
// param is an uninferred wildcard.
TypeMirror typeMirror = TreeUtils.typeOf(tree);
param = AnnotatedTypeMirror.createType(typeMirror, this, false);
addDefaultAnnotations(param);
}
assert isFunctionalInterface(param.getUnderlyingType(), parentTree, tree);
return param;
case VARIABLE:
VariableTree varTree = (VariableTree) parentTree;
assert isFunctionalInterface(TreeUtils.typeOf(varTree), parentTree, tree);
return getAnnotatedType(varTree.getType());
case ASSIGNMENT:
AssignmentTree assignmentTree = (AssignmentTree) parentTree;
assert isFunctionalInterface(TreeUtils.typeOf(assignmentTree), parentTree, tree);
return getAnnotatedType(assignmentTree.getVariable());
case RETURN:
Tree enclosing =
TreeUtils.enclosingOfKind(
getPath(parentTree),
new HashSet<>(
Arrays.asList(
Tree.Kind.METHOD, Tree.Kind.LAMBDA_EXPRESSION)));
if (enclosing.getKind() == Tree.Kind.METHOD) {
MethodTree enclosingMethod = (MethodTree) enclosing;
return getAnnotatedType(enclosingMethod.getReturnType());
} else {
LambdaExpressionTree enclosingLambda = (LambdaExpressionTree) enclosing;
AnnotatedExecutableType methodExe = getFunctionTypeFromTree(enclosingLambda);
return methodExe.getReturnType();
}
case LAMBDA_EXPRESSION:
LambdaExpressionTree enclosingLambda = (LambdaExpressionTree) parentTree;
AnnotatedExecutableType methodExe = getFunctionTypeFromTree(enclosingLambda);
return methodExe.getReturnType();
case CONDITIONAL_EXPRESSION:
ConditionalExpressionTree conditionalExpressionTree =
(ConditionalExpressionTree) parentTree;
final AnnotatedTypeMirror falseType =
getAnnotatedType(conditionalExpressionTree.getFalseExpression());
final AnnotatedTypeMirror trueType =
getAnnotatedType(conditionalExpressionTree.getTrueExpression());
// Known cases where we must use LUB because falseType/trueType will not be equal:
// a) when one of the types is a type variable that extends a functional interface
// or extends a type variable that extends a functional interface
// b) When one of the two sides of the expression is a reference to a sub-interface.
// e.g. interface ConsumeStr {
// public void consume(String s)
// }
// interface SubConsumer extends ConsumeStr {
// default void someOtherMethod() { ... }
// }
// SubConsumer s = ...;
// ConsumeStr stringConsumer = (someCondition) ? s : System.out::println;
AnnotatedTypeMirror conditionalType =
AnnotatedTypes.leastUpperBound(this, trueType, falseType);
assert isFunctionalInterface(conditionalType.getUnderlyingType(), parentTree, tree);
return conditionalType;
default:
throw new BugInCF(
"Could not find functional interface from assignment context. "
+ "Unexpected tree type: "
+ parentTree.getKind()
+ " For lambda tree: "
+ tree);
}
}
private boolean isFunctionalInterface(TypeMirror typeMirror, Tree contextTree, Tree tree) {
if (typeMirror.getKind() == TypeKind.WILDCARD) {
// Ignore wildcards, because they are uninferred type arguments.
return true;
}
Type type = (Type) typeMirror;
if (!TypesUtils.isFunctionalInterface(type, processingEnv)) {
if (type.getKind() == TypeKind.INTERSECTION) {
IntersectionType itype = (IntersectionType) type;
for (TypeMirror t : itype.getBounds()) {
if (TypesUtils.isFunctionalInterface(t, processingEnv)) {
// As long as any of the bounds is a functional interface
// we should be fine.
return true;
}
}
}
throw new BugInCF(
String.format(
"Expected the type of %s tree in assignment context to be a functional interface. "
+ "Found type: %s for tree: %s in lambda tree: %s",
contextTree.getKind(), type, contextTree, tree));
}
return true;
}
/**
* Create the ground target type of the functional interface.
*
* <p>Basically, it replaces the wildcards with their bounds doing a capture conversion like glb
* for extends bounds.
*
* @see "JLS 9.9"
* @param functionalType the functional interface type
* @param groundTargetJavaType the Java type as found by javac
*/
private void makeGroundTargetType(
AnnotatedDeclaredType functionalType, DeclaredType groundTargetJavaType) {
if (functionalType.getTypeArguments().isEmpty()) {
return;
}
List<AnnotatedTypeParameterBounds> bounds =
this.typeVariablesFromUse(
functionalType,
(TypeElement) functionalType.getUnderlyingType().asElement());
List<AnnotatedTypeMirror> newTypeArguments =
new ArrayList<>(functionalType.getTypeArguments());
boolean sizesDiffer =
functionalType.getTypeArguments().size()
!= groundTargetJavaType.getTypeArguments().size();
for (int i = 0; i < functionalType.getTypeArguments().size(); i++) {
AnnotatedTypeMirror argType = functionalType.getTypeArguments().get(i);
if (argType.getKind() == TypeKind.WILDCARD) {
AnnotatedWildcardType wildcardType = (AnnotatedWildcardType) argType;
TypeMirror wildcardUbType = wildcardType.getExtendsBound().getUnderlyingType();
if (wildcardType.isUninferredTypeArgument()) {
// Keep the uninferred type so that it is ignored by later subtyping and
// containment checks.
newTypeArguments.set(i, wildcardType);
} else if (isExtendsWildcard(wildcardType)) {
TypeMirror correctArgType;
if (sizesDiffer) {
// The java type is raw.
TypeMirror typeParamUbType =
bounds.get(i).getUpperBound().getUnderlyingType();
correctArgType =
TypesUtils.greatestLowerBound(
typeParamUbType,
wildcardUbType,
this.checker.getProcessingEnvironment());
} else {
correctArgType = groundTargetJavaType.getTypeArguments().get(i);
}
final AnnotatedTypeMirror newArg;
if (types.isSameType(wildcardUbType, correctArgType)) {
newArg = wildcardType.getExtendsBound().deepCopy();
} else if (correctArgType.getKind() == TypeKind.TYPEVAR) {
newArg = this.toAnnotatedType(correctArgType, false);
AnnotatedTypeVariable newArgAsTypeVar = (AnnotatedTypeVariable) newArg;
newArgAsTypeVar
.getUpperBound()
.replaceAnnotations(
wildcardType.getExtendsBound().getAnnotations());
newArgAsTypeVar
.getLowerBound()
.replaceAnnotations(wildcardType.getSuperBound().getAnnotations());
} else {
newArg = this.toAnnotatedType(correctArgType, false);
newArg.replaceAnnotations(wildcardType.getExtendsBound().getAnnotations());
}
newTypeArguments.set(i, newArg);
} else {
newTypeArguments.set(i, wildcardType.getSuperBound());
}
}
}
functionalType.setTypeArguments(newTypeArguments);
// When the groundTargetJavaType is different from the underlying type of functionalType,
// only the main annotations are copied. Add default annotations in places without
// annotations.
addDefaultAnnotations(functionalType);
}
/**
* Check that a wildcard is an extends wildcard.
*
* @param awt the wildcard type
* @return true if awt is an extends wildcard
*/
private boolean isExtendsWildcard(AnnotatedWildcardType awt) {
return awt.getUnderlyingType().getSuperBound() == null;
}
/** Accessor for the element utilities. */
public Elements getElementUtils() {
return this.elements;
}
/** Accessor for the tree utilities. */
public Trees getTreeUtils() {
return this.trees;
}
/** Accessor for the processing environment. */
public ProcessingEnvironment getProcessingEnv() {
return this.processingEnv;
}
/** Accessor for the {@link CFContext}. */
public CFContext getContext() {
return checker;
}
static final Pattern plusConstant = Pattern.compile(" *\\+ *(-?[0-9]+)$");
static final Pattern minusConstant = Pattern.compile(" *- *(-?[0-9]+)$");
/**
* Given an expression, split it into a subexpression and a constant offset. For example:
*
* <pre>{@code
* "a" => <"a", "0">
* "a + 5" => <"a", "5">
* "a + -5" => <"a", "-5">
* "a - 5" => <"a", "-5">
* }</pre>
*
* There are methods that can only take as input an expression that represents a Receiver. The
* purpose of this is to pre-process expressions to make those methods more likely to succeed.
*
* @param expression an expression to remove a constant offset from
* @return a sub-expression and a constant offset. The offset is "0" if this routine is unable
* to splite the given expression
*/
// TODO: generalize. There is no reason this couldn't handle arbitrary addition and subtraction
// expressions, given the Index Checker's support for OffsetEquation. That might even make its
// implementation simpler.
public static Pair<String, String> getExpressionAndOffset(String expression) {
String expr = expression;
String offset = "0";
// Is this normalization necessary?
// Remove surrrounding whitespace.
expr = expr.trim();
// Remove surrounding parentheses.
if (expr.matches("^\\([^()]\\)")) {
expr = expr.substring(1, expr.length() - 2).trim();
}
Matcher mPlus = plusConstant.matcher(expr);
Matcher mMinus = minusConstant.matcher(expr);
if (mPlus.find()) {
expr = expr.substring(0, mPlus.start());
offset = mPlus.group(1);
} else if (mMinus.find()) {
expr = expr.substring(0, mMinus.start());
offset = negateConstant(mMinus.group(1));
}
if (offset.equals("-0")) {
offset = "0";
}
expr = expr.intern();
offset = offset.intern();
return Pair.of(expr, offset);
}
/**
* Given an expression string, returns its negation.
*
* @param constantExpression a string representing an integer constant
* @return the negation of constantExpression
*/
// Also see Subsequence.negateString which is similar but more sophisticated.
public static String negateConstant(String constantExpression) {
if (constantExpression.startsWith("-")) {
return constantExpression.substring(1);
} else {
if (constantExpression.startsWith("+")) {
constantExpression = constantExpression.substring(1);
}
return "-" + constantExpression;
}
}
/**
* Returns {@code null} or an annotated type mirror that type argument inference should assume
* {@code expressionTree} is assigned to.
*
* <p>If {@code null} is returned, inference proceeds normally.
*
* <p>If a type is returned, then inference assumes that {@code expressionTree} was asigned to
* it. This biases the inference algorithm toward the annotations in the returned type. In
* particular, if the annotations on type variables in invariant positions are a super type of
* the annotations inferred, the super type annotations are chosen.
*
* <p>This implementation returns null, but subclasses may override this method to return a
* type.
*
* @param expressionTree an expression which has no assignment context and for which type
* arguments need to be inferred
* @return {@code null} or an annotated type mirror that inferrence should pretend {@code
* expressionTree} is assigned to
*/
public @Nullable AnnotatedTypeMirror getDummyAssignedTo(ExpressionTree expressionTree) {
return null;
}
/**
* Checks that the annotation {@code am} has the name of {@code annoClass}. Values are ignored.
*
* <p>This method is faster than {@link AnnotationUtils#areSameByClass(AnnotationMirror, Class)}
* because is caches the name of the class rather than computing it each time.
*
* @param am the AnnotationMirror whose class to compare
* @param annoClass the class to compare
* @return true if annoclass is the class of am
*/
public boolean areSameByClass(AnnotationMirror am, Class<? extends Annotation> annoClass) {
if (!shouldCache) {
return AnnotationUtils.areSameByName(am, annoClass.getCanonicalName());
}
String canonicalName = annotationClassNames.get(annoClass);
if (canonicalName == null) {
canonicalName = annoClass.getCanonicalName();
assert canonicalName != null : "@AssumeAssertion(nullness): assumption";
annotationClassNames.put(annoClass, canonicalName);
}
return AnnotationUtils.areSameByName(am, canonicalName);
}
/**
* Checks that the collection contains the annotation. Using Collection.contains does not always
* work, because it does not use areSame for comparison.
*
* <p>This method is faster than {@link AnnotationUtils#containsSameByClass(Collection, Class)}
* because is caches the name of the class rather than computing it each time.
*
* @param c a collection of AnnotationMirrors
* @param anno the annotation class to search for in c
* @return true iff c contains anno, according to areSameByClass
*/
public boolean containsSameByClass(
Collection<? extends AnnotationMirror> c, Class<? extends Annotation> anno) {
return getAnnotationByClass(c, anno) != null;
}
/**
* Returns the AnnotationMirror in {@code c} that has the same class as {@code anno}.
*
* <p>This method is faster than {@link AnnotationUtils#getAnnotationByClass(Collection, Class)}
* because is caches the name of the class rather than computing it each time.
*
* @param c a collection of AnnotationMirrors
* @param anno the class to search for in c
* @return AnnotationMirror with the same class as {@code anno} iff c contains anno, according
* to areSameByClass; otherwise, {@code null}
*/
public @Nullable AnnotationMirror getAnnotationByClass(
Collection<? extends AnnotationMirror> c, Class<? extends Annotation> anno) {
for (AnnotationMirror an : c) {
if (areSameByClass(an, anno)) {
return an;
}
}
return null;
}
}
|
package mage.cards.c;
import java.util.UUID;
import mage.MageInt;
import mage.abilities.TriggeredAbilityImpl;
import mage.abilities.effects.common.counter.AddCountersSourceEffect;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.constants.SubType;
import mage.constants.Zone;
import mage.counters.CounterType;
import mage.game.Game;
import mage.game.events.GameEvent;
import mage.game.events.GameEvent.EventType;
/**
*
* @author North
*/
public final class CosisTrickster extends CardImpl {
public CosisTrickster(UUID ownerId, CardSetInfo setInfo) {
super(ownerId,setInfo,new CardType[]{CardType.CREATURE},"{U}");
this.subtype.add(SubType.MERFOLK);
this.subtype.add(SubType.WIZARD);
this.power = new MageInt(1);
this.toughness = new MageInt(1);
this.addAbility(new CosisTricksterTriggeredAbility());
}
public CosisTrickster(final CosisTrickster card) {
super(card);
}
@Override
public CosisTrickster copy() {
return new CosisTrickster(this);
}
}
class CosisTricksterTriggeredAbility extends TriggeredAbilityImpl {
public CosisTricksterTriggeredAbility() {
super(Zone.BATTLEFIELD, new AddCountersSourceEffect(CounterType.P1P1.createInstance()), true);
}
public CosisTricksterTriggeredAbility(final CosisTricksterTriggeredAbility ability) {
super(ability);
}
@Override
public CosisTricksterTriggeredAbility copy() {
return new CosisTricksterTriggeredAbility(this);
}
@Override
public boolean checkEventType(GameEvent event, Game game) {
return event.getType() == GameEvent.EventType.LIBRARY_SHUFFLED;
}
@Override
public boolean checkTrigger(GameEvent event, Game game) {
return game.getOpponents(controllerId).contains(event.getPlayerId());
}
@Override
public String getRule() {
return "Whenever an opponent shuffles their library, you may put a +1/+1 counter on {this}.";
}
}
|
package org.ff4j.web.api.test.filter;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.io.IOException;
import javax.ws.rs.WebApplicationException;
import org.ff4j.utils.Util;
import org.ff4j.web.ApiConfig;
import org.ff4j.web.api.security.FF4jSecurityContextFilter;
import org.junit.Assert;
import org.junit.Test;
import com.sun.jersey.spi.container.ContainerRequest;
/*
* #%L
* ff4j-webapi-jersey1x
* %%
* Copyright (C) 2013 - 2016 FF4J
* %%
* 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%
*/
public class SecurityFilterTest {
@Test
public void testContextFilterGetWadl() {
FF4jSecurityContextFilter fscf = new FF4jSecurityContextFilter();
ContainerRequest mockRequest = mock(ContainerRequest.class);
when(mockRequest.getMethod()).thenReturn("GET");
when(mockRequest.getPath(true)).thenReturn("application.wadl");
fscf.filter(mockRequest);
}
@Test(expected = WebApplicationException.class)
public void testUnAuthorized1NoAuthorization() throws IOException {
// Given
FF4jSecurityContextFilter faf = new FF4jSecurityContextFilter();
ContainerRequest mockRequest = mock(ContainerRequest.class);
when(mockRequest.getMethod()).thenReturn("GET");
when(mockRequest.getPath(true)).thenReturn("someURLl");
Assert.assertNotNull(faf);
faf.filter(mockRequest);
}
@Test(expected = WebApplicationException.class)
public void testUnAuthorizedInvalidValue() throws IOException {
FF4jSecurityContextFilter faf = new FF4jSecurityContextFilter();
ContainerRequest mockRequest = mock(ContainerRequest.class);
when(mockRequest.getMethod()).thenReturn("GET");
when(mockRequest.getPath(true)).thenReturn("someURLl");
when(mockRequest.getHeaderValue("Authorization")).thenReturn("12");
Assert.assertNotNull(faf);
faf.filter(mockRequest);
}
@Test(expected = WebApplicationException.class)
public void testUnAuthorizedApiKey() throws IOException {
FF4jSecurityContextFilter faf = new FF4jSecurityContextFilter();
ContainerRequest mockRequest = mock(ContainerRequest.class);
when(mockRequest.getMethod()).thenReturn("GET");
when(mockRequest.getPath(true)).thenReturn("someURLl");
when(mockRequest.getHeaderValue("Authorization")).thenReturn("apiKey=12");
FF4jSecurityContextFilter.setSecurityConfig(new ApiConfig());
Assert.assertNotNull(faf);
faf.filter(mockRequest);
}
@Test(expected = WebApplicationException.class)
public void testNoAuthorizationAttributeInHeader() throws IOException {
FF4jSecurityContextFilter faf = new FF4jSecurityContextFilter();
ContainerRequest mockRequest = mock(ContainerRequest.class);
when(mockRequest.getMethod()).thenReturn("GET");
when(mockRequest.getPath(true)).thenReturn("someURLl");
when(mockRequest.getHeaderValue("Authorization")).thenReturn(null);
Assert.assertNotNull(faf);
faf.filter(mockRequest);
}
@Test
public void testAuthorizedApiKey() throws IOException {
// Define ApiConfig
FF4jSecurityContextFilter.setSecurityConfig(new ApiConfig().createApiKey("12", true, true, Util.set("USER")));
// Given
FF4jSecurityContextFilter faf = new FF4jSecurityContextFilter();
ContainerRequest mockRequest = mock(ContainerRequest.class);
when(mockRequest.getMethod()).thenReturn("GET");
when(mockRequest.getPath(true)).thenReturn("someURLl");
when(mockRequest.getHeaderValue("Authorization")).thenReturn("apiKey=12");
Assert.assertNotNull(faf);
faf.filter(mockRequest);
}
}
|
package onLoad;
import java.sql.*;
import java.io.*;
public class showAssg1
{
String aname,ques,id,info;
Date adate,ddate;
public showAssg1()
{
}
public showAssg1(String assgName)throws Exception
{
Class.forName("org.postgresql.Driver");
String assgId;
String s=null;
int i=0;
Connection connection=DriverManager.getConnection("jdbc:postgresql://localhost:5432/postgres","postgres"," ");
PreparedStatement preparedStatement = connection.prepareStatement("select * from assignmentmaster where assignmentname=?");
preparedStatement.setString(1, assgName);
ResultSet resultSet = preparedStatement.executeQuery();
while(resultSet.next())
{
System.out.println("rec found!!!!");
id=resultSet.getString(1);
aname=resultSet.getString(2);
ques=resultSet.getString(4);
info=resultSet.getString(5);
System.out.println("Id :"+id);
preparedStatement = connection.prepareStatement("select * from assignmentbatch,studentassignment where assignmentbatch.assignmentid= studentassignment.assignmentid and studentassignment.assignmentid=?");
preparedStatement.setString(1, id);
ResultSet resultSet1 = preparedStatement.executeQuery();
if(resultSet1.next())
{
adate=resultSet1.getDate(3);
ddate=resultSet1.getDate(4);
}
System.out.println("adate :"+adate);
}
}
public String getan()
{
return aname;
}
public String ques()
{
return ques;
}
public Date adate()
{
return adate;
}
public Date ddate()
{
return ddate;
}
public String info()
{
return info;
}
}
|
/*
* Copyright (c) 2020 GeekXYZ.
* All rights reserved.
*/
package io.geekshop.mapper;
import io.geekshop.entity.ProductVariantCollectionJoinEntity;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
/**
* Created on Nov, 2020 by @author bobo
*/
@Mapper
public interface ProductVariantCollectionJoinEntityMapper extends BaseMapper<ProductVariantCollectionJoinEntity> {
}
|
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.gwtproject.i18n.client.impl.cldr;
// DO NOT EDIT - GENERATED FROM CLDR AND ICU DATA
/**
* Implementation of DateTimeFormatInfo for the "mgo" locale.
*/
public class DateTimeFormatInfoImpl_mgo extends DateTimeFormatInfoImpl {
@Override
public String dateFormatFull() {
return "EEEE, y MMMM dd";
}
@Override
public String[] erasFull() {
return new String[] {
"BCE",
"CE"
};
}
@Override
public String[] erasShort() {
return new String[] {
"BCE",
"CE"
};
}
@Override
public String formatYearMonthNumDay() {
return "y-M-d";
}
@Override
public String[] monthsFull() {
return new String[] {
"iməg mbegtug",
"imeg àbùbì",
"imeg mbəŋchubi",
"iməg ngwə̀t",
"iməg fog",
"iməg ichiibɔd",
"iməg àdùmbə̀ŋ",
"iməg ichika",
"iməg kud",
"iməg tèsiʼe",
"iməg zò",
"iməg krizmed"
};
}
@Override
public String[] monthsNarrow() {
return new String[] {
"M1",
"A2",
"M3",
"N4",
"F5",
"I6",
"A7",
"I8",
"K9",
"10",
"11",
"12"
};
}
@Override
public String[] monthsShort() {
return new String[] {
"mbegtug",
"imeg àbùbì",
"imeg mbəŋchubi",
"iməg ngwə̀t",
"iməg fog",
"iməg ichiibɔd",
"iməg àdùmbə̀ŋ",
"iməg ichika",
"iməg kud",
"iməg tèsiʼe",
"iməg zò",
"iməg krizmed"
};
}
@Override
public String[] quartersFull() {
return new String[] {
"Q1",
"Q2",
"Q3",
"Q4"
};
}
@Override
public String[] weekdaysFull() {
return new String[] {
"Aneg 1",
"Aneg 2",
"Aneg 3",
"Aneg 4",
"Aneg 5",
"Aneg 6",
"Aneg 7"
};
}
@Override
public String[] weekdaysNarrow() {
return new String[] {
"A1",
"A2",
"A3",
"A4",
"A5",
"A6",
"A7"
};
}
@Override
public String[] weekdaysShort() {
return new String[] {
"Aneg 1",
"Aneg 2",
"Aneg 3",
"Aneg 4",
"Aneg 5",
"Aneg 6",
"Aneg 7"
};
}
}
|
package com.example.demo.rocketmq.Test;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.common.message.Message;
/**
* 消息发送者
* @author 一明哥
*
*/
public class Producer4 {
public static void main(String[] args)throws Exception {
DefaultMQProducer producer = new DefaultMQProducer("xoxogp");
// 设置nameserver地址
producer.setNamesrvAddr("192.168.150.113:9876");
producer.start();
// tag 是用来过滤消息,消息分组
Message message = new Message("myTopic003", "TAG-B","KEY-xx","xxooxx".getBytes());
// 单向消息
// p 网络不确定
producer.send(message);
producer.shutdown();
System.out.println("已经停机");
}
}
|
package org.kohsuke.github;
/**
* Search repositories.
*
* @see GitHub#searchRepositories() GitHub#searchRepositories()
*/
public class GHRepositorySearchBuilder extends GHSearchBuilder<GHRepository> {
GHRepositorySearchBuilder(GitHub root) {
super(root, RepositorySearchResult.class);
}
/**
* Search terms.
*/
public GHRepositorySearchBuilder q(String term) {
super.q(term);
return this;
}
/**
* In gh repository search builder.
*
* @param v
* the v
* @return the gh repository search builder
*/
public GHRepositorySearchBuilder in(String v) {
return q("in:" + v);
}
/**
* Size gh repository search builder.
*
* @param v
* the v
* @return the gh repository search builder
*/
public GHRepositorySearchBuilder size(String v) {
return q("size:" + v);
}
/**
* Forks gh repository search builder.
*
* @param v
* the v
* @return the gh repository search builder
*/
public GHRepositorySearchBuilder forks(String v) {
return q("forks:" + v);
}
/**
* Created gh repository search builder.
*
* @param v
* the v
* @return the gh repository search builder
*/
public GHRepositorySearchBuilder created(String v) {
return q("created:" + v);
}
/**
* Pushed gh repository search builder.
*
* @param v
* the v
* @return the gh repository search builder
*/
public GHRepositorySearchBuilder pushed(String v) {
return q("pushed:" + v);
}
/**
* User gh repository search builder.
*
* @param v
* the v
* @return the gh repository search builder
*/
public GHRepositorySearchBuilder user(String v) {
return q("user:" + v);
}
/**
* Repo gh repository search builder.
*
* @param v
* the v
* @return the gh repository search builder
*/
public GHRepositorySearchBuilder repo(String v) {
return q("repo:" + v);
}
/**
* Language gh repository search builder.
*
* @param v
* the v
* @return the gh repository search builder
*/
public GHRepositorySearchBuilder language(String v) {
return q("language:" + v);
}
/**
* Stars gh repository search builder.
*
* @param v
* the v
* @return the gh repository search builder
*/
public GHRepositorySearchBuilder stars(String v) {
return q("stars:" + v);
}
/**
* Topic gh repository search builder.
*
* @param v
* the v
* @return the gh repository search builder
*/
public GHRepositorySearchBuilder topic(String v) {
return q("topic:" + v);
}
/**
* Order gh repository search builder.
*
* @param v
* the v
* @return the gh repository search builder
*/
public GHRepositorySearchBuilder order(GHDirection v) {
req.with("order", v);
return this;
}
/**
* Sort gh repository search builder.
*
* @param sort
* the sort
* @return the gh repository search builder
*/
public GHRepositorySearchBuilder sort(Sort sort) {
req.with("sort", sort);
return this;
}
/**
* The enum Sort.
*/
public enum Sort {
STARS, FORKS, UPDATED
}
private static class RepositorySearchResult extends SearchResult<GHRepository> {
private GHRepository[] items;
@Override
GHRepository[] getItems(GitHub root) {
for (GHRepository item : items)
item.wrap(root);
return items;
}
}
@Override
protected String getApiUrl() {
return "/search/repositories";
}
}
|
package dev.lajoscseppento.ruthless.demo.springbootlibrary;
import static org.assertj.core.api.Assertions.assertThat;
import com.google.common.collect.ImmutableSet;
import dev.lajoscseppento.ruthless.demo.javalibrary.Item;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest(classes = ItemRepository.class)
class ItemRepositoryTest {
@Autowired private ItemRepository itemRepository;
@Test
void test() {
// Given
Item item1 = Item.builder().name("1").description("First").build();
Item item2 = Item.builder().name("2").description("Second").build();
// When
itemRepository.add(item1);
itemRepository.add(item2);
// Then
ImmutableSet<Item> items = itemRepository.getAll();
assertThat(items).containsExactlyInAnyOrder(item1, item2);
}
}
|
/*
* Copyright (C) 2021 即时通讯网(52im.net) & Jack Jiang.
* The MobileIMSDK4j_udp (MobileIMSDK4j v6.x UDP版) Project.
* All rights reserved.
*
* > Github地址:https://github.com/JackJiang2011/MobileIMSDK
* > 文档地址: http://www.52im.net/forum-89-1.html
* > 技术社区: http://www.52im.net/
* > 技术交流群:320837163 (http://www.52im.net/topic-qqgroup.html)
* > 作者公众号:“即时通讯技术圈】”,欢迎关注!
* > 联系作者: http://www.52im.net/thread-2792-1-1.html
*
* "即时通讯网(52im.net) - 即时通讯开发者社区!" 推荐开源工程。
*
* ClientCoreSDK.java at 2021-7-6 15:54:42, code by Jack Jiang.
*/
package net.x52im.mobileimsdk.java;
import net.x52im.mobileimsdk.java.core.AutoReLoginDaemon;
import net.x52im.mobileimsdk.java.core.KeepAliveDaemon;
import net.x52im.mobileimsdk.java.core.LocalDataReciever;
import net.x52im.mobileimsdk.java.core.LocalSocketProvider;
import net.x52im.mobileimsdk.java.core.QoS4ReciveDaemon;
import net.x52im.mobileimsdk.java.core.QoS4SendDaemon;
import net.x52im.mobileimsdk.java.event.ChatBaseEvent;
import net.x52im.mobileimsdk.java.event.ChatMessageEvent;
import net.x52im.mobileimsdk.java.event.MessageQoSEvent;
import net.x52im.mobileimsdk.server.protocal.c.PLoginInfo;
public class ClientCoreSDK {
public static boolean DEBUG = true;
public static boolean autoReLogin = true;
private static ClientCoreSDK instance = null;
private boolean _init = false;
private boolean connectedToServer = true;
private boolean loginHasInit = false;
private PLoginInfo currentLoginInfo = null;
private ChatBaseEvent chatBaseEvent = null;
private ChatMessageEvent chatMessageEvent = null;
private MessageQoSEvent messageQoSEvent = null;
public static ClientCoreSDK getInstance() {
if (instance == null)
instance = new ClientCoreSDK();
return instance;
}
private ClientCoreSDK() {
}
public void init() {
if (!_init) {
_init = true;
}
}
public void release() {
LocalSocketProvider.getInstance().closeLocalSocket();
AutoReLoginDaemon.getInstance().stop();
QoS4SendDaemon.getInstance().stop();
KeepAliveDaemon.getInstance().stop();
LocalDataReciever.getInstance().stop();
QoS4ReciveDaemon.getInstance().stop();
QoS4SendDaemon.getInstance().clear();
QoS4ReciveDaemon.getInstance().clear();
_init = false;
this.setLoginHasInit(false);
this.setConnectedToServer(false);
}
public void setCurrentLoginInfo(PLoginInfo currentLoginInfo)
{
this.currentLoginInfo = currentLoginInfo;
}
public PLoginInfo getCurrentLoginInfo()
{
return this.currentLoginInfo;
}
public void saveFirstLoginTime(long firstLoginTime)
{
if(this.currentLoginInfo != null)
this.currentLoginInfo.setFirstLoginTime(firstLoginTime);
}
@Deprecated
public String getCurrentLoginUserId()
{
return this.currentLoginInfo.getLoginUserId();
}
@Deprecated
public String getCurrentLoginToken()
{
return this.currentLoginInfo.getLoginToken();
}
@Deprecated
public String getCurrentLoginExtra()
{
return this.currentLoginInfo.getExtra();
}
public boolean isLoginHasInit() {
return loginHasInit;
}
public ClientCoreSDK setLoginHasInit(boolean loginHasInit) {
this.loginHasInit = loginHasInit;
return this;
}
public boolean isConnectedToServer() {
return connectedToServer;
}
public void setConnectedToServer(boolean connectedToServer) {
this.connectedToServer = connectedToServer;
}
public boolean isInitialed() {
return this._init;
}
public void setChatBaseEvent(ChatBaseEvent chatBaseEvent) {
this.chatBaseEvent = chatBaseEvent;
}
public ChatBaseEvent getChatBaseEvent() {
return chatBaseEvent;
}
public void setChatMessageEvent(ChatMessageEvent chatMessageEvent) {
this.chatMessageEvent = chatMessageEvent;
}
public ChatMessageEvent getChatMessageEvent() {
return chatMessageEvent;
}
public void setMessageQoSEvent(MessageQoSEvent messageQoSEvent) {
this.messageQoSEvent = messageQoSEvent;
}
public MessageQoSEvent getMessageQoSEvent() {
return messageQoSEvent;
}
}
|
/*
* This file was automatically generated by EvoSuite
* Sun Nov 08 05:49:25 GMT 2020
*/
package org.databene.jdbacl;
import org.junit.Test;
import static org.junit.Assert.*;
import static org.evosuite.shaded.org.mockito.Mockito.*;
import static org.evosuite.runtime.EvoAssertions.*;
import java.io.FileNotFoundException;
import java.lang.reflect.Proxy;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.SQLWarning;
import java.sql.Statement;
import java.util.List;
import java.util.regex.PatternSyntaxException;
import org.apache.derby.diag.ErrorMessages;
import org.databene.commons.ErrorHandler;
import org.databene.commons.Level;
import org.databene.jdbacl.DBExecutionResult;
import org.databene.jdbacl.DBUtil;
import org.databene.jdbacl.JDBCConnectData;
import org.databene.jdbacl.ResultsWithMetadata;
import org.databene.jdbacl.model.DBConstraint;
import org.databene.jdbacl.model.DBForeignKeyConstraint;
import org.databene.jdbacl.model.DBPrimaryKeyConstraint;
import org.databene.jdbacl.model.DBSchema;
import org.databene.jdbacl.model.DBTable;
import org.databene.jdbacl.model.DBUniqueConstraint;
import org.databene.jdbacl.model.DefaultDBColumn;
import org.databene.jdbacl.model.DefaultDBTable;
import org.databene.jdbacl.model.TableContainer;
import org.databene.jdbacl.model.TableHolder;
import org.evosuite.runtime.EvoRunner;
import org.evosuite.runtime.EvoRunnerParameters;
import org.evosuite.runtime.ViolatedAssumptionAnswer;
import org.evosuite.runtime.testdata.EvoSuiteFile;
import org.evosuite.runtime.testdata.EvoSuiteLocalAddress;
import org.evosuite.runtime.testdata.FileSystemHandling;
import org.evosuite.runtime.testdata.NetworkHandling;
import org.h2.engine.SessionRemote;
import org.h2.tools.Csv;
import org.h2.tools.SimpleResultSet;
import org.hsqldb.Result;
import org.hsqldb.Session;
import org.hsqldb.jdbc.jdbcConnection;
import org.junit.runner.RunWith;
import org.postgresql.xa.PGXAConnection;
@RunWith(EvoRunner.class) @EvoRunnerParameters(mockJVMNonDeterminism = true, useVFS = true, useVNET = true, resetStaticState = true, separateClassLoader = true, useJEE = true)
public class DBUtil_ESTest extends DBUtil_ESTest_scaffolding {
/**
//Test case number: 0
/*Coverage entropy=0.6931471805599453
*/
@Test(timeout = 4000)
public void test000() throws Throwable {
Session session0 = mock(Session.class, new ViolatedAssumptionAnswer());
jdbcConnection jdbcConnection0 = new jdbcConnection(session0);
// Undeclared exception!
try {
DBUtil.getMetaData((Connection) jdbcConnection0, "uF,pF5W", "uF,pF5W", true, true, false, false, "75Zf;+", true);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("org.hsqldb.jdbc.jdbcDatabaseMetaData", e);
}
}
/**
//Test case number: 1
/*Coverage entropy=0.6931471805599453
*/
@Test(timeout = 4000)
public void test001() throws Throwable {
boolean boolean0 = DBUtil.available("--i6NKua1Bihl#T,", "--i6NKua1Bihl#T,", "i6", "p");
assertFalse(boolean0);
}
/**
//Test case number: 2
/*Coverage entropy=0.6931471805599453
*/
@Test(timeout = 4000)
public void test002() throws Throwable {
boolean boolean0 = DBUtil.available((String) null, (String) null, "gZi{v%RK7", "gZi{v%RK7");
assertFalse(boolean0);
}
/**
//Test case number: 3
/*Coverage entropy=-0.0
*/
@Test(timeout = 4000)
public void test003() throws Throwable {
try {
DBUtil.connect("SQRT(-1)", "org.apache.derby.impl.store.access.conglomerate.OpenConglomerate", "org.apache.derby.impl.store.access.conglomerate.OpenConglomerate", "", false);
fail("Expecting exception: Exception");
} catch(Exception e) {
//
// Connecting SQRT(-1) failed:
//
verifyException("org.databene.jdbacl.DBUtil", e);
}
}
/**
//Test case number: 4
/*Coverage entropy=-0.0
*/
@Test(timeout = 4000)
public void test004() throws Throwable {
SimpleResultSet simpleResultSet0 = new SimpleResultSet();
Object[] objectArray0 = DBUtil.parseResultRow(simpleResultSet0);
assertEquals(0, objectArray0.length);
}
/**
//Test case number: 5
/*Coverage entropy=2.582424317350126
*/
@Test(timeout = 4000)
public void test005() throws Throwable {
SessionRemote sessionRemote0 = new SessionRemote();
FileSystemHandling.setPermissions((EvoSuiteFile) null, false, false, false);
Level level0 = Level.error;
ErrorHandler.setDefaultLevel(level0);
FileSystemHandling.createFolder((EvoSuiteFile) null);
NetworkHandling.sendMessageOnTcp((EvoSuiteLocalAddress) null, "--' found");
Result result0 = new Result(2448);
Session session0 = mock(Session.class, new ViolatedAssumptionAnswer());
doReturn(result0, (Result) null).when(session0).execute(any(org.hsqldb.Result.class));
jdbcConnection jdbcConnection0 = new jdbcConnection(session0);
Object[] objectArray0 = new Object[2];
objectArray0[0] = (Object) result0;
objectArray0[1] = (Object) result0;
result0.add(objectArray0);
ErrorHandler errorHandler0 = ErrorHandler.getDefault();
ErrorHandler.setDefaultLevel(level0);
ErrorHandler.getDefault();
errorHandler0.handleError("--' found");
DBUtil.runScript("--' found", '/', (Connection) jdbcConnection0, false, errorHandler0);
ErrorHandler.getDefault();
DBUtil.queryAndSimplify("--8LsMcR<}xO]I^FvZ*,", jdbcConnection0);
DBUtil.getOpenResultSetCount();
// Undeclared exception!
try {
DBUtil.prepareStatement((Connection) jdbcConnection0, "org.firebirdsql.jdbc.FBSavepoint", false);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("org.hsqldb.jdbc.jdbcPreparedStatement", e);
}
}
/**
//Test case number: 6
/*Coverage entropy=0.6365141682948128
*/
@Test(timeout = 4000)
public void test006() throws Throwable {
EvoSuiteFile evoSuiteFile0 = new EvoSuiteFile("/home/ubuntu/databene/org.apache.derby.impl.sql.execute.ValueRow.env.properties");
FileSystemHandling.appendStringToFile(evoSuiteFile0, "");
boolean boolean0 = DBUtil.existsEnvironment("org.apache.derby.impl.sql.execute.ValueRow");
assertTrue(boolean0);
}
/**
//Test case number: 7
/*Coverage entropy=0.5623351446188083
*/
@Test(timeout = 4000)
public void test007() throws Throwable {
Result result0 = Result.newReleaseSavepointRequest((String) null);
result0.setStatementType((-390));
Session session0 = mock(Session.class, new ViolatedAssumptionAnswer());
doReturn(result0).when(session0).execute(any(org.hsqldb.Result.class));
jdbcConnection jdbcConnection0 = new jdbcConnection(session0);
int int0 = DBUtil.executeUpdate("Wrczx%wvPl", jdbcConnection0);
assertEquals((-390), int0);
}
/**
//Test case number: 8
/*Coverage entropy=-0.0
*/
@Test(timeout = 4000)
public void test008() throws Throwable {
Result result0 = Result.newReleaseSavepointRequest((String) null);
Session session0 = mock(Session.class, new ViolatedAssumptionAnswer());
doReturn(result0).when(session0).execute(any(org.hsqldb.Result.class));
jdbcConnection jdbcConnection0 = new jdbcConnection(session0);
ResultSet resultSet0 = DBUtil.executeQuery("Wrczx%wvPl", jdbcConnection0);
assertFalse(resultSet0.wasNull());
}
/**
//Test case number: 9
/*Coverage entropy=-0.0
*/
@Test(timeout = 4000)
public void test009() throws Throwable {
String string0 = DBUtil.escape("checking primary key ");
assertEquals("checking primary key ", string0);
}
/**
//Test case number: 10
/*Coverage entropy=-0.0
*/
@Test(timeout = 4000)
public void test010() throws Throwable {
DefaultDBTable defaultDBTable0 = new DefaultDBTable("|I o(");
String[] stringArray0 = new String[0];
DBPrimaryKeyConstraint dBPrimaryKeyConstraint0 = new DBPrimaryKeyConstraint(defaultDBTable0, "Go+]c7-c", true, stringArray0);
boolean boolean0 = DBUtil.equivalent(dBPrimaryKeyConstraint0, dBPrimaryKeyConstraint0);
assertTrue(boolean0);
}
/**
//Test case number: 11
/*Coverage entropy=-0.0
*/
@Test(timeout = 4000)
public void test011() throws Throwable {
DefaultDBTable defaultDBTable0 = new DefaultDBTable();
String[] stringArray0 = new String[0];
DBUniqueConstraint dBUniqueConstraint0 = new DBUniqueConstraint(defaultDBTable0, "R8;", false, stringArray0);
String[] stringArray1 = new String[9];
DBPrimaryKeyConstraint dBPrimaryKeyConstraint0 = new DBPrimaryKeyConstraint(defaultDBTable0, "--XBCM3.S", false, stringArray1);
boolean boolean0 = DBUtil.equivalent(dBUniqueConstraint0, dBPrimaryKeyConstraint0);
assertFalse(boolean0);
}
/**
//Test case number: 12
/*Coverage entropy=0.6931471805599453
*/
@Test(timeout = 4000)
public void test012() throws Throwable {
SimpleResultSet simpleResultSet0 = new SimpleResultSet();
Object[] objectArray0 = DBUtil.currentLine(simpleResultSet0);
assertEquals(0, objectArray0.length);
}
/**
//Test case number: 13
/*Coverage entropy=0.6931471805599453
*/
@Test(timeout = 4000)
public void test013() throws Throwable {
jdbcConnection jdbcConnection0 = new jdbcConnection((Session) null);
ErrorHandler errorHandler0 = ErrorHandler.getDefault();
// Undeclared exception!
try {
DBUtil.runScript((String) null, (Connection) jdbcConnection0, false, errorHandler0);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("java.io.StringReader", e);
}
}
/**
//Test case number: 14
/*Coverage entropy=0.6931471805599453
*/
@Test(timeout = 4000)
public void test014() throws Throwable {
ErrorHandler errorHandler0 = ErrorHandler.getDefault();
// Undeclared exception!
try {
DBUtil.runScript((String) null, "--z$=8A|pH2^1jI", (Connection) null, false, errorHandler0);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("org.databene.commons.IOUtil", e);
}
}
/**
//Test case number: 15
/*Coverage entropy=0.6931471805599453
*/
@Test(timeout = 4000)
public void test015() throws Throwable {
ErrorHandler errorHandler0 = ErrorHandler.getDefault();
try {
DBUtil.runScript("", "There are unclosed database resources: ", (Connection) null, true, errorHandler0);
fail("Expecting exception: FileNotFoundException");
} catch(FileNotFoundException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("org.evosuite.runtime.mock.java.io.MockFileInputStream", e);
}
}
/**
//Test case number: 16
/*Coverage entropy=-0.0
*/
@Test(timeout = 4000)
public void test016() throws Throwable {
Session session0 = mock(Session.class, new ViolatedAssumptionAnswer());
jdbcConnection jdbcConnection0 = new jdbcConnection(session0);
// Undeclared exception!
try {
DBUtil.runScript("Connecting ", "", 'J', (Connection) jdbcConnection0, false, (ErrorHandler) null);
fail("Expecting exception: RuntimeException");
} catch(RuntimeException e) {
//
// Resource not found: Connecting
//
verifyException("org.databene.commons.IOUtil", e);
}
}
/**
//Test case number: 17
/*Coverage entropy=-0.0
*/
@Test(timeout = 4000)
public void test017() throws Throwable {
Session session0 = mock(Session.class, new ViolatedAssumptionAnswer());
jdbcConnection jdbcConnection0 = new jdbcConnection(session0);
// Undeclared exception!
try {
DBUtil.runScript((String) null, "fkHce!||1fN)lRx", 'J', (Connection) jdbcConnection0, false, (ErrorHandler) null);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("org.databene.commons.IOUtil", e);
}
}
/**
//Test case number: 18
/*Coverage entropy=-0.0
*/
@Test(timeout = 4000)
public void test018() throws Throwable {
ErrorHandler errorHandler0 = ErrorHandler.getDefault();
// Undeclared exception!
try {
DBUtil.runScript((String) null, '+', (Connection) null, false, errorHandler0);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("java.io.StringReader", e);
}
}
/**
//Test case number: 19
/*Coverage entropy=1.0986122886681096
*/
@Test(timeout = 4000)
public void test019() throws Throwable {
Result result0 = new Result(2);
Session session0 = mock(Session.class, new ViolatedAssumptionAnswer());
doReturn(result0).when(session0).execute(any(org.hsqldb.Result.class));
jdbcConnection jdbcConnection0 = new jdbcConnection(session0);
try {
DBUtil.queryWithMetadata("RkAKke", jdbcConnection0);
fail("Expecting exception: SQLException");
} catch(SQLException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("org.hsqldb.jdbc.Util", e);
}
}
/**
//Test case number: 20
/*Coverage entropy=-0.0
*/
@Test(timeout = 4000)
public void test020() throws Throwable {
// Undeclared exception!
try {
DBUtil.queryString((PreparedStatement) null);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("org.databene.jdbacl.DBUtil", e);
}
}
/**
//Test case number: 21
/*Coverage entropy=1.0986122886681096
*/
@Test(timeout = 4000)
public void test021() throws Throwable {
SQLWarning sQLWarning0 = new SQLWarning();
Result result0 = new Result(sQLWarning0, "OIIwiNd,8]iJ");
Session session0 = mock(Session.class, new ViolatedAssumptionAnswer());
doReturn(result0).when(session0).execute(any(org.hsqldb.Result.class));
jdbcConnection jdbcConnection0 = new jdbcConnection(session0);
Class<PGXAConnection> class0 = PGXAConnection.class;
try {
DBUtil.queryScalarArray("jC0 u-Ev+nU~-~", class0, (Connection) jdbcConnection0);
fail("Expecting exception: SQLException");
} catch(SQLException e) {
//
// null java.sql.SQLWarning in statement [OIIwiNd,8]iJ]
//
verifyException("org.hsqldb.jdbc.Util", e);
}
}
/**
//Test case number: 22
/*Coverage entropy=1.6094379124341005
*/
@Test(timeout = 4000)
public void test022() throws Throwable {
Session session0 = mock(Session.class, new ViolatedAssumptionAnswer());
doReturn((Result) null).when(session0).execute(any(org.hsqldb.Result.class));
jdbcConnection jdbcConnection0 = new jdbcConnection(session0);
Proxy proxy0 = (Proxy)DBUtil.wrapWithPooledConnection(jdbcConnection0, false);
// Undeclared exception!
try {
DBUtil.queryLong("Da", (Connection) proxy0);
fail("Expecting exception: RuntimeException");
} catch(RuntimeException e) {
//
// Internal exception in method: public java.sql.ResultSet org.databene.jdbacl.proxy.LoggingStatementHandler.executeQuery(java.lang.String) throws java.sql.SQLException
//
verifyException("org.databene.commons.ExceptionMapper", e);
}
}
/**
//Test case number: 23
/*Coverage entropy=0.6931471805599453
*/
@Test(timeout = 4000)
public void test023() throws Throwable {
Result result0 = Result.newReleaseSavepointRequest("Wrczx%wvPl");
Session session0 = mock(Session.class, new ViolatedAssumptionAnswer());
doReturn(result0).when(session0).execute(any(org.hsqldb.Result.class));
jdbcConnection jdbcConnection0 = new jdbcConnection(session0);
// Undeclared exception!
try {
DBUtil.queryLong("ES`bB", jdbcConnection0);
fail("Expecting exception: RuntimeException");
} catch(RuntimeException e) {
//
// Expected a row.
//
verifyException("org.databene.jdbacl.DBUtil", e);
}
}
/**
//Test case number: 24
/*Coverage entropy=0.6365141682948128
*/
@Test(timeout = 4000)
public void test024() throws Throwable {
SQLWarning sQLWarning0 = new SQLWarning();
Result result0 = new Result(sQLWarning0, "OIIwiNd,8]iJ");
Session session0 = mock(Session.class, new ViolatedAssumptionAnswer());
doReturn(result0).when(session0).execute(any(org.hsqldb.Result.class));
jdbcConnection jdbcConnection0 = new jdbcConnection(session0);
try {
DBUtil.query("OIIwiNd,8]iJ", jdbcConnection0);
fail("Expecting exception: SQLException");
} catch(SQLException e) {
//
// null java.sql.SQLWarning in statement [OIIwiNd,8]iJ]
//
verifyException("org.hsqldb.jdbc.Util", e);
}
}
/**
//Test case number: 25
/*Coverage entropy=0.6365141682948128
*/
@Test(timeout = 4000)
public void test025() throws Throwable {
// Undeclared exception!
try {
DBUtil.query("--2VaOBP?V", (Connection) null);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("org.databene.jdbacl.DBUtil", e);
}
}
/**
//Test case number: 26
/*Coverage entropy=0.6365141682948128
*/
@Test(timeout = 4000)
public void test026() throws Throwable {
Session session0 = mock(Session.class, new ViolatedAssumptionAnswer());
jdbcConnection jdbcConnection0 = new jdbcConnection(session0);
// Undeclared exception!
try {
DBUtil.prepareStatement((Connection) jdbcConnection0, "", true, 1473, 774, 44);
fail("Expecting exception: IllegalStateException");
} catch(IllegalStateException e) {
//
// Tried to mutate a database with read-only settings:
//
verifyException("org.databene.jdbacl.DBUtil", e);
}
}
/**
//Test case number: 27
/*Coverage entropy=1.0397207708399179
*/
@Test(timeout = 4000)
public void test027() throws Throwable {
// Undeclared exception!
try {
DBUtil.prepareStatement((Connection) null, "&T+^", true);
fail("Expecting exception: IllegalStateException");
} catch(IllegalStateException e) {
//
// Tried to mutate a database with read-only settings: &T+^
//
verifyException("org.databene.jdbacl.DBUtil", e);
}
}
/**
//Test case number: 28
/*Coverage entropy=-0.0
*/
@Test(timeout = 4000)
public void test028() throws Throwable {
// Undeclared exception!
try {
DBUtil.parseResultSet((ResultSet) null);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("org.databene.jdbacl.DBUtil", e);
}
}
/**
//Test case number: 29
/*Coverage entropy=-0.0
*/
@Test(timeout = 4000)
public void test029() throws Throwable {
// Undeclared exception!
try {
DBUtil.parseResultRow((ResultSet) null);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("org.databene.jdbacl.DBUtil", e);
}
}
/**
//Test case number: 30
/*Coverage entropy=1.0549201679861442
*/
@Test(timeout = 4000)
public void test030() throws Throwable {
ErrorMessages errorMessages0 = new ErrorMessages();
try {
DBUtil.parseAndSimplifyResultSet(errorMessages0);
fail("Expecting exception: SQLException");
} catch(SQLException e) {
//
// getObject
//
verifyException("org.apache.derby.vti.VTITemplate", e);
}
}
/**
//Test case number: 31
/*Coverage entropy=0.6931471805599453
*/
@Test(timeout = 4000)
public void test031() throws Throwable {
// Undeclared exception!
try {
DBUtil.parseAndSimplifyResultSet((ResultSet) null);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("org.databene.jdbacl.DBUtil", e);
}
}
/**
//Test case number: 32
/*Coverage entropy=-0.0
*/
@Test(timeout = 4000)
public void test032() throws Throwable {
// Undeclared exception!
try {
DBUtil.nextLine((ResultSet) null);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("org.databene.jdbacl.DBUtil", e);
}
}
/**
//Test case number: 33
/*Coverage entropy=-0.0
*/
@Test(timeout = 4000)
public void test033() throws Throwable {
// Undeclared exception!
try {
DBUtil.getStatement((ResultSet) null);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("org.databene.jdbacl.DBUtil", e);
}
}
/**
//Test case number: 34
/*Coverage entropy=0.6931471805599453
*/
@Test(timeout = 4000)
public void test034() throws Throwable {
// Undeclared exception!
try {
DBUtil.getMetaData((Connection) null, "nKA*}D", "Cannot cast an instance of {0} to type {1}", true, true, true, false, "&\"+iWrm{{hpO@Msd?^", true);
fail("Expecting exception: PatternSyntaxException");
} catch(PatternSyntaxException e) {
//
// Illegal repetition near index 6
// &\"+iWrm{{hpO@Msd?^
// ^
//
verifyException("java.util.regex.Pattern", e);
}
}
/**
//Test case number: 35
/*Coverage entropy=0.6931471805599453
*/
@Test(timeout = 4000)
public void test035() throws Throwable {
Session session0 = mock(Session.class, new ViolatedAssumptionAnswer());
jdbcConnection jdbcConnection0 = new jdbcConnection(session0);
// Undeclared exception!
try {
DBUtil.getMetaData((Connection) jdbcConnection0, "h,", "h,", false, false, false, true, "h,", true);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("org.hsqldb.jdbc.jdbcDatabaseMetaData", e);
}
}
/**
//Test case number: 36
/*Coverage entropy=0.5623351446188083
*/
@Test(timeout = 4000)
public void test036() throws Throwable {
// Undeclared exception!
try {
DBUtil.getMetaData("Could not create directory, because a file with the same name already exists: ", false, true, true, false, "2V", false, false);
fail("Expecting exception: RuntimeException");
} catch(RuntimeException e) {
//
// No environment definition 'Could not create directory, because a file with the same name already exists: .env.properties' found
//
verifyException("org.databene.jdbacl.DBUtil", e);
}
}
/**
//Test case number: 37
/*Coverage entropy=0.5004024235381879
*/
@Test(timeout = 4000)
public void test037() throws Throwable {
SQLWarning sQLWarning0 = new SQLWarning();
Result result0 = new Result(sQLWarning0, "OIIwiNd,8]iJ");
Session session0 = mock(Session.class, new ViolatedAssumptionAnswer());
doReturn((Result) null).when(session0).execute(any(org.hsqldb.Result.class));
jdbcConnection jdbcConnection0 = new jdbcConnection(session0);
// Undeclared exception!
try {
DBUtil.executeUpdate("R.<#v[BfPImm4", jdbcConnection0);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("org.hsqldb.jdbc.jdbcStatement", e);
}
}
/**
//Test case number: 38
/*Coverage entropy=-0.0
*/
@Test(timeout = 4000)
public void test038() throws Throwable {
// Undeclared exception!
try {
DBUtil.escape((String) null);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("org.databene.jdbacl.DBUtil", e);
}
}
/**
//Test case number: 39
/*Coverage entropy=-0.0
*/
@Test(timeout = 4000)
public void test039() throws Throwable {
// Undeclared exception!
try {
DBUtil.dependencyOrderedTables((TableHolder) null);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("org.databene.jdbacl.DBUtil", e);
}
}
/**
//Test case number: 40
/*Coverage entropy=0.6931471805599453
*/
@Test(timeout = 4000)
public void test040() throws Throwable {
// Undeclared exception!
try {
DBUtil.currentLine((ResultSet) null);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("org.databene.jdbacl.DBUtil", e);
}
}
/**
//Test case number: 41
/*Coverage entropy=-0.0
*/
@Test(timeout = 4000)
public void test041() throws Throwable {
DefaultDBTable defaultDBTable0 = new DefaultDBTable();
String[] stringArray0 = new String[1];
DBForeignKeyConstraint dBForeignKeyConstraint0 = new DBForeignKeyConstraint("mI o(", false, defaultDBTable0, stringArray0, defaultDBTable0, stringArray0);
// Undeclared exception!
try {
DBUtil.containsMandatoryColumn(dBForeignKeyConstraint0);
fail("Expecting exception: RuntimeException");
} catch(RuntimeException e) {
//
// Column 'null' not found in table 'null'
//
verifyException("org.databene.jdbacl.model.DefaultDBTable", e);
}
}
/**
//Test case number: 42
/*Coverage entropy=-0.0
*/
@Test(timeout = 4000)
public void test042() throws Throwable {
// Undeclared exception!
try {
DBUtil.containsMandatoryColumn((DBConstraint) null);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("org.databene.jdbacl.DBUtil", e);
}
}
/**
//Test case number: 43
/*Coverage entropy=-0.0
*/
@Test(timeout = 4000)
public void test043() throws Throwable {
// Undeclared exception!
try {
DBUtil.connect((JDBCConnectData) null, false);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("org.databene.jdbacl.DBUtil", e);
}
}
/**
//Test case number: 44
/*Coverage entropy=0.6931471805599453
*/
@Test(timeout = 4000)
public void test044() throws Throwable {
// Undeclared exception!
try {
DBUtil.closeResultSetAndStatement((ResultSet) null);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("org.databene.jdbacl.DBUtil", e);
}
}
/**
//Test case number: 45
/*Coverage entropy=-0.0
*/
@Test(timeout = 4000)
public void test045() throws Throwable {
// Undeclared exception!
try {
DBUtil.checkReadOnly((String) null, true);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("org.databene.jdbacl.SQLUtil", e);
}
}
/**
//Test case number: 46
/*Coverage entropy=-0.0
*/
@Test(timeout = 4000)
public void test046() throws Throwable {
// Undeclared exception!
try {
DBUtil.checkReadOnly("NE}6eYf", true);
fail("Expecting exception: IllegalStateException");
} catch(IllegalStateException e) {
//
// Tried to mutate a database with read-only settings: NE}6eYf
//
verifyException("org.databene.jdbacl.DBUtil", e);
}
}
/**
//Test case number: 47
/*Coverage entropy=-0.0
*/
@Test(timeout = 4000)
public void test047() throws Throwable {
DBUtil.checkReadOnly("*0<oXZV.8il'jWZyP;", false);
}
/**
//Test case number: 48
/*Coverage entropy=0.6365141682948128
*/
@Test(timeout = 4000)
public void test048() throws Throwable {
// Undeclared exception!
try {
DBUtil.queryAndSimplify("jC0 u-Ev+nU~-~", (Connection) null);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("org.databene.jdbacl.DBUtil", e);
}
}
/**
//Test case number: 49
/*Coverage entropy=0.5623351446188083
*/
@Test(timeout = 4000)
public void test049() throws Throwable {
Result result0 = Result.newReleaseSavepointRequest((String) null);
Session session0 = mock(Session.class, new ViolatedAssumptionAnswer());
doReturn(result0).when(session0).execute(any(org.hsqldb.Result.class));
jdbcConnection jdbcConnection0 = new jdbcConnection(session0);
int int0 = DBUtil.executeUpdate("Wrczx%wvPl", jdbcConnection0);
assertEquals(4, int0);
}
/**
//Test case number: 50
/*Coverage entropy=0.5004024235381879
*/
@Test(timeout = 4000)
public void test050() throws Throwable {
Session session0 = mock(Session.class, new ViolatedAssumptionAnswer());
doReturn((Result) null).when(session0).execute(any(org.hsqldb.Result.class));
jdbcConnection jdbcConnection0 = new jdbcConnection(session0);
// Undeclared exception!
try {
DBUtil.executeUpdate("Wrczx%wvPl", jdbcConnection0);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("org.hsqldb.jdbc.jdbcStatement", e);
}
}
/**
//Test case number: 51
/*Coverage entropy=-0.0
*/
@Test(timeout = 4000)
public void test051() throws Throwable {
// Undeclared exception!
try {
DBUtil.executeUpdate("-LefK6jIO)sr.y", (Connection) null);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("org.databene.jdbacl.DBUtil", e);
}
}
/**
//Test case number: 52
/*Coverage entropy=-0.0
*/
@Test(timeout = 4000)
public void test052() throws Throwable {
Result result0 = new Result(1326);
Session session0 = mock(Session.class, new ViolatedAssumptionAnswer());
doReturn(result0).when(session0).execute(any(org.hsqldb.Result.class));
jdbcConnection jdbcConnection0 = new jdbcConnection(session0);
// Undeclared exception!
try {
DBUtil.queryScalar("&*;", jdbcConnection0);
fail("Expecting exception: RuntimeException");
} catch(RuntimeException e) {
//
// Expected a row.
//
verifyException("org.databene.jdbacl.DBUtil", e);
}
}
/**
//Test case number: 53
/*Coverage entropy=0.6931471805599453
*/
@Test(timeout = 4000)
public void test053() throws Throwable {
ErrorMessages errorMessages0 = new ErrorMessages();
try {
DBUtil.parseResultSet(errorMessages0);
fail("Expecting exception: SQLException");
} catch(SQLException e) {
//
// getObject
//
verifyException("org.apache.derby.vti.VTITemplate", e);
}
}
/**
//Test case number: 54
/*Coverage entropy=0.6931471805599453
*/
@Test(timeout = 4000)
public void test054() throws Throwable {
SimpleResultSet simpleResultSet0 = new SimpleResultSet();
DBUtil.parseResultSet(simpleResultSet0);
// Undeclared exception!
try {
DBUtil.format(simpleResultSet0);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("org.h2.tools.SimpleResultSet", e);
}
}
/**
//Test case number: 55
/*Coverage entropy=-0.0
*/
@Test(timeout = 4000)
public void test055() throws Throwable {
DBUtil.close((ResultSet) null);
}
/**
//Test case number: 56
/*Coverage entropy=-0.0
*/
@Test(timeout = 4000)
public void test056() throws Throwable {
SimpleResultSet simpleResultSet0 = new SimpleResultSet();
DBUtil.close((ResultSet) simpleResultSet0);
assertTrue(simpleResultSet0.isClosed());
}
/**
//Test case number: 57
/*Coverage entropy=-0.0
*/
@Test(timeout = 4000)
public void test057() throws Throwable {
Session session0 = mock(Session.class, new ViolatedAssumptionAnswer());
jdbcConnection jdbcConnection0 = new jdbcConnection(session0);
Statement statement0 = jdbcConnection0.createStatement();
DBUtil.close(statement0);
assertEquals(1003, statement0.getResultSetType());
}
/**
//Test case number: 58
/*Coverage entropy=-0.0
*/
@Test(timeout = 4000)
public void test058() throws Throwable {
DBUtil.close((Statement) null);
}
/**
//Test case number: 59
/*Coverage entropy=0.6365141682948128
*/
@Test(timeout = 4000)
public void test059() throws Throwable {
Session session0 = mock(Session.class, new ViolatedAssumptionAnswer());
jdbcConnection jdbcConnection0 = new jdbcConnection(session0);
try {
DBUtil.prepareStatement((Connection) jdbcConnection0, "", false, (-377), (-1907), 1688);
fail("Expecting exception: SQLException");
} catch(SQLException e) {
//
// java.lang.String@0000000002
//
verifyException("org.hsqldb.jdbc.Util", e);
}
}
/**
//Test case number: 60
/*Coverage entropy=-0.0
*/
@Test(timeout = 4000)
public void test060() throws Throwable {
try {
DBUtil.connect("", (String) null, "", "", false);
fail("Expecting exception: Exception");
} catch(Exception e) {
//
// Connecting failed:
//
verifyException("org.databene.jdbacl.DBUtil", e);
}
}
/**
//Test case number: 61
/*Coverage entropy=-0.0
*/
@Test(timeout = 4000)
public void test061() throws Throwable {
JDBCConnectData jDBCConnectData0 = new JDBCConnectData("", (String) null, "--Wrczx%wvPl", "Wrczx%wvPl");
// Undeclared exception!
try {
DBUtil.connect(jDBCConnectData0, false);
fail("Expecting exception: RuntimeException");
} catch(RuntimeException e) {
//
// No JDBC URL specified
//
verifyException("org.databene.jdbacl.DBUtil", e);
}
}
/**
//Test case number: 62
/*Coverage entropy=-0.0
*/
@Test(timeout = 4000)
public void test062() throws Throwable {
// Undeclared exception!
try {
DBUtil.getConnectData("%r");
fail("Expecting exception: RuntimeException");
} catch(RuntimeException e) {
//
// No environment definition '%r.env.properties' found
//
verifyException("org.databene.jdbacl.DBUtil", e);
}
}
/**
//Test case number: 63
/*Coverage entropy=-0.0
*/
@Test(timeout = 4000)
public void test063() throws Throwable {
ErrorMessages errorMessages0 = new ErrorMessages();
// Undeclared exception!
try {
DBUtil.getStatement(errorMessages0);
fail("Expecting exception: RuntimeException");
} catch(RuntimeException e) {
//
// Error getting statement from result set
//
verifyException("org.databene.jdbacl.DBUtil", e);
}
}
/**
//Test case number: 64
/*Coverage entropy=-0.0
*/
@Test(timeout = 4000)
public void test064() throws Throwable {
int int0 = DBUtil.getOpenConnectionCount();
assertEquals(0, int0);
}
/**
//Test case number: 65
/*Coverage entropy=-0.0
*/
@Test(timeout = 4000)
public void test065() throws Throwable {
int int0 = DBUtil.getOpenPreparedStatementCount();
assertEquals(0, int0);
}
/**
//Test case number: 66
/*Coverage entropy=-0.0
*/
@Test(timeout = 4000)
public void test066() throws Throwable {
Session session0 = mock(Session.class, new ViolatedAssumptionAnswer());
jdbcConnection jdbcConnection0 = new jdbcConnection(session0);
try {
DBUtil.runScript("", "", 'J', (Connection) jdbcConnection0, false, (ErrorHandler) null);
fail("Expecting exception: FileNotFoundException");
} catch(FileNotFoundException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("org.evosuite.runtime.mock.java.io.MockFileInputStream", e);
}
}
/**
//Test case number: 67
/*Coverage entropy=-0.0
*/
@Test(timeout = 4000)
public void test067() throws Throwable {
int int0 = DBUtil.getOpenStatementCount();
assertEquals(14, int0);
}
/**
//Test case number: 68
/*Coverage entropy=-0.0
*/
@Test(timeout = 4000)
public void test068() throws Throwable {
Session session0 = mock(Session.class, new ViolatedAssumptionAnswer());
doReturn((Result) null).when(session0).execute(any(org.hsqldb.Result.class));
jdbcConnection jdbcConnection0 = new jdbcConnection(session0);
// Undeclared exception!
try {
DBUtil.executeQuery("", jdbcConnection0);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("org.hsqldb.jdbc.jdbcStatement", e);
}
}
/**
//Test case number: 69
/*Coverage entropy=-0.0
*/
@Test(timeout = 4000)
public void test069() throws Throwable {
DBSchema dBSchema0 = new DBSchema("--]dnIV0uYr:MT?bN&d%");
DefaultDBTable defaultDBTable0 = new DefaultDBTable("i6NKua1Bihl#T,", dBSchema0);
String[] stringArray0 = new String[1];
stringArray0[0] = "--]dnIV0uYr:MT?bN&d%";
DefaultDBColumn defaultDBColumn0 = new DefaultDBColumn("--]dnIV0uYr:MT?bN&d%", defaultDBTable0, (byte)38, "txY,A}}4~};I");
DBUniqueConstraint dBUniqueConstraint0 = new DBUniqueConstraint(defaultDBTable0, "--]dnIV0uYr:MT?bN&d%", false, stringArray0);
boolean boolean0 = DBUtil.containsMandatoryColumn(dBUniqueConstraint0);
assertFalse(boolean0);
}
/**
//Test case number: 70
/*Coverage entropy=0.908908734898781
*/
@Test(timeout = 4000)
public void test070() throws Throwable {
// Undeclared exception!
try {
DBUtil.assertAllDbResourcesClosed(true);
fail("Expecting exception: AssertionError");
} catch(AssertionError e) {
//
// There are unclosed database resources: 1 statement(s)
//
}
}
/**
//Test case number: 71
/*Coverage entropy=-0.0
*/
@Test(timeout = 4000)
public void test071() throws Throwable {
TableContainer tableContainer0 = new TableContainer("--' found");
DefaultDBTable defaultDBTable0 = new DefaultDBTable("--' found");
tableContainer0.addTable(defaultDBTable0);
List<DBTable> list0 = DBUtil.dependencyOrderedTables(tableContainer0);
assertFalse(list0.isEmpty());
}
/**
//Test case number: 72
/*Coverage entropy=-0.0
*/
@Test(timeout = 4000)
public void test072() throws Throwable {
TableContainer tableContainer0 = new TableContainer("--' found");
List<DBTable> list0 = DBUtil.dependencyOrderedTables(tableContainer0);
assertTrue(list0.isEmpty());
}
/**
//Test case number: 73
/*Coverage entropy=0.8675632284814612
*/
@Test(timeout = 4000)
public void test073() throws Throwable {
Result result0 = Result.newFreeStmtRequest(10);
Object[] objectArray0 = new Object[9];
result0.setParameterData(objectArray0);
Session session0 = mock(Session.class, new ViolatedAssumptionAnswer());
doReturn(result0).when(session0).execute(any(org.hsqldb.Result.class));
jdbcConnection jdbcConnection0 = new jdbcConnection(session0);
ResultsWithMetadata resultsWithMetadata0 = DBUtil.queryWithMetadata("RkAKke", jdbcConnection0);
assertNotNull(resultsWithMetadata0);
}
/**
//Test case number: 74
/*Coverage entropy=1.7478680974667573
*/
@Test(timeout = 4000)
public void test074() throws Throwable {
Result result0 = new Result(2521);
Session session0 = mock(Session.class, new ViolatedAssumptionAnswer());
doReturn(result0).when(session0).execute(any(org.hsqldb.Result.class));
jdbcConnection jdbcConnection0 = new jdbcConnection(session0);
// Undeclared exception!
try {
DBUtil.querySingleRow("$$", jdbcConnection0);
fail("Expecting exception: RuntimeException");
} catch(RuntimeException e) {
//
// Database query did not return a result: $$
//
verifyException("org.databene.jdbacl.DBUtil", e);
}
}
/**
//Test case number: 75
/*Coverage entropy=1.8310204811135165
*/
@Test(timeout = 4000)
public void test075() throws Throwable {
Result result0 = Result.newFreeStmtRequest(10);
Object[] objectArray0 = new Object[9];
result0.setParameterData(objectArray0);
Session session0 = mock(Session.class, new ViolatedAssumptionAnswer());
doReturn(result0).when(session0).execute(any(org.hsqldb.Result.class));
jdbcConnection jdbcConnection0 = new jdbcConnection(session0);
Object[] objectArray1 = DBUtil.querySingleRow("$$", jdbcConnection0);
assertEquals(0, objectArray1.length);
}
/**
//Test case number: 76
/*Coverage entropy=1.5498260458782016
*/
@Test(timeout = 4000)
public void test076() throws Throwable {
Session session0 = mock(Session.class, new ViolatedAssumptionAnswer());
jdbcConnection jdbcConnection0 = new jdbcConnection(session0);
Proxy proxy0 = (Proxy)DBUtil.wrapWithPooledConnection(jdbcConnection0, true);
// Undeclared exception!
try {
DBUtil.query("C[$0itioqGX=", (Connection) proxy0);
fail("Expecting exception: RuntimeException");
} catch(RuntimeException e) {
//
// Internal exception in method: public java.sql.ResultSet org.databene.jdbacl.proxy.LoggingStatementHandler.executeQuery(java.lang.String) throws java.sql.SQLException
//
verifyException("org.databene.commons.ExceptionMapper", e);
}
}
/**
//Test case number: 77
/*Coverage entropy=1.945910149055313
*/
@Test(timeout = 4000)
public void test077() throws Throwable {
Result result0 = Result.newFreeStmtRequest((-3490));
Session session0 = mock(Session.class, new ViolatedAssumptionAnswer());
doReturn(result0).when(session0).execute(any(org.hsqldb.Result.class));
jdbcConnection jdbcConnection0 = new jdbcConnection(session0);
List<Object[]> list0 = DBUtil.query("V1", jdbcConnection0);
assertEquals(0, list0.size());
}
/**
//Test case number: 78
/*Coverage entropy=1.0986122886681096
*/
@Test(timeout = 4000)
public void test078() throws Throwable {
Result result0 = new Result(2521);
Session session0 = mock(Session.class, new ViolatedAssumptionAnswer());
doReturn(result0).when(session0).execute(any(org.hsqldb.Result.class));
jdbcConnection jdbcConnection0 = new jdbcConnection(session0);
Object[] objectArray0 = new Object[7];
result0.add(objectArray0);
Class<PGXAConnection> class0 = PGXAConnection.class;
// Undeclared exception!
try {
DBUtil.queryScalarArray("}Gh.@VU27`%OH%3c", class0, (Connection) jdbcConnection0);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("org.hsqldb.jdbc.jdbcResultSet", e);
}
}
/**
//Test case number: 79
/*Coverage entropy=1.0986122886681096
*/
@Test(timeout = 4000)
public void test079() throws Throwable {
Result result0 = Result.newFreeStmtRequest((-540));
Session session0 = mock(Session.class, new ViolatedAssumptionAnswer());
doReturn(result0).when(session0).execute(any(org.hsqldb.Result.class));
jdbcConnection jdbcConnection0 = new jdbcConnection(session0);
Class<PGXAConnection> class0 = PGXAConnection.class;
PGXAConnection[] pGXAConnectionArray0 = DBUtil.queryScalarArray("Q<3x", class0, (Connection) jdbcConnection0);
assertEquals(0, pGXAConnectionArray0.length);
}
/**
//Test case number: 80
/*Coverage entropy=-0.0
*/
@Test(timeout = 4000)
public void test080() throws Throwable {
Session session0 = mock(Session.class, new ViolatedAssumptionAnswer());
jdbcConnection jdbcConnection0 = new jdbcConnection(session0);
int int0 = DBUtil.executeUpdate("", jdbcConnection0);
assertEquals(0, int0);
}
/**
//Test case number: 81
/*Coverage entropy=-0.0
*/
@Test(timeout = 4000)
public void test081() throws Throwable {
int int0 = DBUtil.executeUpdate((String) null, (Connection) null);
assertEquals(0, int0);
}
/**
//Test case number: 82
/*Coverage entropy=0.9656421724371469
*/
@Test(timeout = 4000)
public void test082() throws Throwable {
Level level0 = Level.error;
ErrorHandler.setDefaultLevel(level0);
SQLWarning sQLWarning0 = new SQLWarning();
Result result0 = new Result(sQLWarning0, "OIIwiNd,8]iJ");
Session session0 = mock(Session.class, new ViolatedAssumptionAnswer());
doReturn((Result) null).when(session0).execute(any(org.hsqldb.Result.class));
jdbcConnection jdbcConnection0 = new jdbcConnection(session0);
ErrorHandler errorHandler0 = ErrorHandler.getDefault();
// Undeclared exception!
try {
DBUtil.runScript("$$", (Connection) jdbcConnection0, true, errorHandler0);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("org.hsqldb.jdbc.jdbcStatement", e);
}
}
/**
//Test case number: 83
/*Coverage entropy=1.051256318980014
*/
@Test(timeout = 4000)
public void test083() throws Throwable {
SQLWarning sQLWarning0 = new SQLWarning();
Result result0 = new Result(sQLWarning0, "OIIwiNd,8]iJ");
Session session0 = mock(Session.class, new ViolatedAssumptionAnswer());
doReturn(result0).when(session0).execute(any(org.hsqldb.Result.class));
jdbcConnection jdbcConnection0 = new jdbcConnection(session0);
ErrorHandler errorHandler0 = ErrorHandler.getDefault();
// Undeclared exception!
try {
DBUtil.runScript("$$", (Connection) jdbcConnection0, true, errorHandler0);
fail("Expecting exception: RuntimeException");
} catch(RuntimeException e) {
//
// java.sql.SQLException: null java.sql.SQLWarning in statement [OIIwiNd,8]iJ]
//
verifyException("org.databene.commons.ErrorHandler", e);
}
}
/**
//Test case number: 84
/*Coverage entropy=0.7751292747786216
*/
@Test(timeout = 4000)
public void test084() throws Throwable {
Result result0 = new Result(2521);
Session session0 = mock(Session.class, new ViolatedAssumptionAnswer());
doReturn(result0).when(session0).execute(any(org.hsqldb.Result.class));
jdbcConnection jdbcConnection0 = new jdbcConnection(session0);
ErrorHandler errorHandler0 = ErrorHandler.getDefault();
DBExecutionResult dBExecutionResult0 = DBUtil.runScript(")", 'z', (Connection) jdbcConnection0, true, errorHandler0);
assertNotNull(dBExecutionResult0);
}
/**
//Test case number: 85
/*Coverage entropy=0.857174043642079
*/
@Test(timeout = 4000)
public void test085() throws Throwable {
ErrorHandler errorHandler0 = ErrorHandler.getDefault();
// Undeclared exception!
try {
DBUtil.runScript("SELECT ", 'I', (Connection) null, false, errorHandler0);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("org.databene.jdbacl.DBUtil", e);
}
}
/**
//Test case number: 86
/*Coverage entropy=0.9868994488385301
*/
@Test(timeout = 4000)
public void test086() throws Throwable {
Session session0 = mock(Session.class, new ViolatedAssumptionAnswer());
doReturn((Result) null).when(session0).execute(any(org.hsqldb.Result.class));
jdbcConnection jdbcConnection0 = new jdbcConnection(session0);
ErrorHandler errorHandler0 = ErrorHandler.getDefault();
// Undeclared exception!
try {
DBUtil.runScript("Connecting ", 'g', (Connection) jdbcConnection0, false, errorHandler0);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("org.hsqldb.jdbc.jdbcStatement", e);
}
}
/**
//Test case number: 87
/*Coverage entropy=1.0986122886681096
*/
@Test(timeout = 4000)
public void test087() throws Throwable {
Result result0 = new Result(10);
Session session0 = mock(Session.class, new ViolatedAssumptionAnswer());
doReturn(result0).when(session0).execute(any(org.hsqldb.Result.class));
jdbcConnection jdbcConnection0 = new jdbcConnection(session0);
Object[] objectArray0 = new Object[2];
result0.add(objectArray0);
// Undeclared exception!
try {
DBUtil.countRows("$$", jdbcConnection0);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("org.hsqldb.jdbc.jdbcResultSet", e);
}
}
/**
//Test case number: 88
/*Coverage entropy=-0.0
*/
@Test(timeout = 4000)
public void test088() throws Throwable {
Csv csv0 = Csv.getInstance();
SimpleResultSet simpleResultSet0 = new SimpleResultSet(csv0);
Object[] objectArray0 = DBUtil.nextLine(simpleResultSet0);
assertNull(objectArray0);
}
/**
//Test case number: 89
/*Coverage entropy=1.0397207708399179
*/
@Test(timeout = 4000)
public void test089() throws Throwable {
ErrorMessages errorMessages0 = new ErrorMessages();
try {
DBUtil.nextLine(errorMessages0);
fail("Expecting exception: SQLException");
} catch(SQLException e) {
//
// getObject
//
verifyException("org.apache.derby.vti.VTITemplate", e);
}
}
/**
//Test case number: 90
/*Coverage entropy=0.9502705392332347
*/
@Test(timeout = 4000)
public void test090() throws Throwable {
SimpleResultSet simpleResultSet0 = new SimpleResultSet();
String string0 = DBUtil.format(simpleResultSet0);
assertEquals("", string0);
}
/**
//Test case number: 91
/*Coverage entropy=1.0986122886681096
*/
@Test(timeout = 4000)
public void test091() throws Throwable {
Session session0 = mock(Session.class, new ViolatedAssumptionAnswer());
doReturn((Result) null).when(session0).execute(any(org.hsqldb.Result.class));
jdbcConnection jdbcConnection0 = new jdbcConnection(session0);
// Undeclared exception!
try {
DBUtil.queryWithMetadata("--nioMapped:", jdbcConnection0);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("org.hsqldb.jdbc.jdbcStatement", e);
}
}
/**
//Test case number: 92
/*Coverage entropy=-0.0
*/
@Test(timeout = 4000)
public void test092() throws Throwable {
DBUtil.close((Connection) null);
}
/**
//Test case number: 93
/*Coverage entropy=-0.0
*/
@Test(timeout = 4000)
public void test093() throws Throwable {
Session session0 = mock(Session.class, new ViolatedAssumptionAnswer());
jdbcConnection jdbcConnection0 = new jdbcConnection(session0);
DBUtil.close((Connection) jdbcConnection0);
assertFalse(jdbcConnection0.isClosed());
}
/**
//Test case number: 94
/*Coverage entropy=0.6365141682948128
*/
@Test(timeout = 4000)
public void test094() throws Throwable {
JDBCConnectData jDBCConnectData0 = new JDBCConnectData("Wrczx%wvPl", "--Wrczx%wvPl", "Wrczx%wvPl", "Wrczx%wvPl");
try {
DBUtil.connect(jDBCConnectData0, true);
fail("Expecting exception: Exception");
} catch(Exception e) {
//
// Connecting --Wrczx%wvPl failed:
//
verifyException("org.databene.jdbacl.DBUtil", e);
}
}
/**
//Test case number: 95
/*Coverage entropy=-0.0
*/
@Test(timeout = 4000)
public void test095() throws Throwable {
JDBCConnectData jDBCConnectData0 = new JDBCConnectData((String) null, "Wr", "Wr", "There are unclosed database resources");
// Undeclared exception!
try {
DBUtil.connect(jDBCConnectData0, false);
fail("Expecting exception: RuntimeException");
} catch(RuntimeException e) {
//
// No JDBC driver class name specified
//
verifyException("org.databene.jdbacl.DBUtil", e);
}
}
/**
//Test case number: 96
/*Coverage entropy=1.0397207708399179
*/
@Test(timeout = 4000)
public void test096() throws Throwable {
EvoSuiteFile evoSuiteFile0 = new EvoSuiteFile("Tried to mutate a database with read-only settings} .env.properties");
byte[] byteArray0 = new byte[1];
FileSystemHandling.appendDataToFile(evoSuiteFile0, byteArray0);
// Undeclared exception!
try {
DBUtil.connect("Tried to mutate a database with read-only settings} ", false);
fail("Expecting exception: RuntimeException");
} catch(RuntimeException e) {
//
// No JDBC URL specified
//
verifyException("org.databene.jdbacl.DBUtil", e);
}
}
/**
//Test case number: 97
/*Coverage entropy=1.0397207708399179
*/
@Test(timeout = 4000)
public void test097() throws Throwable {
Proxy proxy0 = (Proxy)DBUtil.wrapWithPooledConnection((Connection) null, true);
// Undeclared exception!
try {
DBUtil.prepareStatement((Connection) proxy0, "!Qf_9q}", false, 2528, (-391), 32);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("org.databene.jdbacl.DBUtil", e);
}
}
/**
//Test case number: 98
/*Coverage entropy=0.9257019111219665
*/
@Test(timeout = 4000)
public void test098() throws Throwable {
ErrorHandler errorHandler0 = ErrorHandler.getDefault();
// Undeclared exception!
try {
DBUtil.runScript("org.apache.derby.iapi.sql.dictionary.StatementPermission", (Connection) null, true, errorHandler0);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("org.databene.jdbacl.DBUtil", e);
}
}
/**
//Test case number: 99
/*Coverage entropy=-0.0
*/
@Test(timeout = 4000)
public void test099() throws Throwable {
DBUtil.resetMonitors();
}
/**
//Test case number: 100
/*Coverage entropy=-0.0
*/
@Test(timeout = 4000)
public void test100() throws Throwable {
SimpleResultSet simpleResultSet0 = new SimpleResultSet();
Proxy proxy0 = (Proxy)DBUtil.createLoggingResultSet(simpleResultSet0, (Statement) null);
assertNotNull(proxy0);
}
/**
//Test case number: 101
/*Coverage entropy=0.6365141682948128
*/
@Test(timeout = 4000)
public void test101() throws Throwable {
ErrorMessages errorMessages0 = new ErrorMessages();
try {
DBUtil.currentLine(errorMessages0);
fail("Expecting exception: SQLException");
} catch(SQLException e) {
//
// getObject
//
verifyException("org.apache.derby.vti.VTITemplate", e);
}
}
/**
//Test case number: 102
/*Coverage entropy=-0.0
*/
@Test(timeout = 4000)
public void test102() throws Throwable {
String string0 = DBUtil.escape("");
assertEquals("", string0);
}
/**
//Test case number: 103
/*Coverage entropy=0.6365141682948128
*/
@Test(timeout = 4000)
public void test103() throws Throwable {
// Undeclared exception!
try {
DBUtil.querySingleRow("ol", (Connection) null);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("org.databene.jdbacl.DBUtil", e);
}
}
/**
//Test case number: 104
/*Coverage entropy=0.6931471805599453
*/
@Test(timeout = 4000)
public void test104() throws Throwable {
Session session0 = mock(Session.class, new ViolatedAssumptionAnswer());
jdbcConnection jdbcConnection0 = new jdbcConnection(session0);
ErrorHandler errorHandler0 = ErrorHandler.getDefault();
// Undeclared exception!
try {
DBUtil.runScript("--org.apache.derby.iapi.sql.dictionary.StatementPermission", "--", (Connection) jdbcConnection0, true, errorHandler0);
fail("Expecting exception: RuntimeException");
} catch(RuntimeException e) {
//
// Resource not found: --org.apache.derby.iapi.sql.dictionary.StatementPermission
//
verifyException("org.databene.commons.IOUtil", e);
}
}
/**
//Test case number: 105
/*Coverage entropy=0.6931471805599453
*/
@Test(timeout = 4000)
public void test105() throws Throwable {
boolean boolean0 = DBUtil.available("MODE_RECORD", "%}_=Kl5=mbo", "%}_=Kl5=mbo", "%}_=Kl5=mbo");
assertFalse(boolean0);
}
/**
//Test case number: 106
/*Coverage entropy=1.0986122886681096
*/
@Test(timeout = 4000)
public void test106() throws Throwable {
Result result0 = Result.newFreeStmtRequest((-3490));
Session session0 = mock(Session.class, new ViolatedAssumptionAnswer());
doReturn(result0).when(session0).execute(any(org.hsqldb.Result.class));
jdbcConnection jdbcConnection0 = new jdbcConnection(session0);
// Undeclared exception!
try {
DBUtil.countRows("Da", jdbcConnection0);
fail("Expecting exception: RuntimeException");
} catch(RuntimeException e) {
//
// Expected a row.
//
verifyException("org.databene.jdbacl.DBUtil", e);
}
}
/**
//Test case number: 107
/*Coverage entropy=-0.0
*/
@Test(timeout = 4000)
public void test107() throws Throwable {
Session session0 = mock(Session.class, new ViolatedAssumptionAnswer());
jdbcConnection jdbcConnection0 = new jdbcConnection(session0);
// Undeclared exception!
try {
DBUtil.logMetaData(jdbcConnection0);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("org.hsqldb.jdbc.jdbcDatabaseMetaData", e);
}
}
/**
//Test case number: 108
/*Coverage entropy=-0.0
*/
@Test(timeout = 4000)
public void test108() throws Throwable {
Proxy proxy0 = (Proxy)DBUtil.createLoggingStatementHandler((Statement) null, false);
assertNotNull(proxy0);
}
/**
//Test case number: 109
/*Coverage entropy=0.6931471805599453
*/
@Test(timeout = 4000)
public void test109() throws Throwable {
Session session0 = mock(Session.class, new ViolatedAssumptionAnswer());
doReturn((Result) null).when(session0).execute(any(org.hsqldb.Result.class));
jdbcConnection jdbcConnection0 = new jdbcConnection(session0);
// Undeclared exception!
try {
DBUtil.queryLong("org.databene.JDBC", jdbcConnection0);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("org.hsqldb.jdbc.jdbcStatement", e);
}
}
/**
//Test case number: 110
/*Coverage entropy=0.5623351446188083
*/
@Test(timeout = 4000)
public void test110() throws Throwable {
boolean boolean0 = DBUtil.existsEnvironment("org.apache.derby.impl.sql.execute.ValueRow");
assertFalse(boolean0);
}
/**
//Test case number: 111
/*Coverage entropy=1.3862943611198906
*/
@Test(timeout = 4000)
public void test111() throws Throwable {
Csv csv0 = Csv.getInstance();
SimpleResultSet simpleResultSet0 = new SimpleResultSet(csv0);
DBUtil.closeResultSetAndStatement(simpleResultSet0);
assertEquals(1, simpleResultSet0.getHoldability());
}
/**
//Test case number: 112
/*Coverage entropy=1.0986122886681096
*/
@Test(timeout = 4000)
public void test112() throws Throwable {
try {
DBUtil.getMetaData((Connection) null, "*i^*wRGRCzF|h;", "\"Ri<5L", true, false, false, true, (String) null, false);
fail("Expecting exception: Exception");
} catch(Exception e) {
//
// Connecting null failed:
//
verifyException("org.databene.jdbacl.DBUtil", e);
}
}
/**
//Test case number: 113
/*Coverage entropy=-0.0
*/
@Test(timeout = 4000)
public void test113() throws Throwable {
// Undeclared exception!
try {
DBUtil.equivalent((DBUniqueConstraint) null, (DBPrimaryKeyConstraint) null);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("org.databene.jdbacl.DBUtil", e);
}
}
/**
//Test case number: 114
/*Coverage entropy=0.908908734898781
*/
@Test(timeout = 4000)
public void test114() throws Throwable {
DBUtil.assertAllDbResourcesClosed(false);
}
}
|
/*
* Copyright 2010-2011, Sikuli.org
* Released under the MIT License.
*
*/
package org.sikuli.script;
import java.util.*;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.imageio.ImageIO;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JWindow;
import java.util.List;
import org.python.util.PythonInterpreter;
import org.python.core.*;
public class Region {
final static float DEFAULT_HIGHLIGHT_TIME = 2f;
private IRobot _robot;
private IScreen _scr;
private ScreenHighlighter _overlay = null;
public int x, y, w, h;
protected FindFailedResponse _defaultFindFailedResponse =
FindFailedResponse.ABORT;
public void setFindFailedResponse(FindFailedResponse res){
_defaultFindFailedResponse = res;
}
public FindFailedResponse getFindFailedResponse(){
return _defaultFindFailedResponse;
}
protected boolean _throwException = true;
protected double _autoWaitTimeout = 3.0;
protected boolean _observing = false;
protected EventManager _evtMgr = null;
// the last captured screen image the last match or matches are based on
// TODO: consider moving this to Screen class
protected ScreenImage _lastScreenImage;
protected Match _lastMatch;
protected Iterator<Match> _lastMatches;
/**
* Create a region with the provided coordinate / size
*
* @deprecated Not for public use in Java. Use Region.create() instead.
*
* @param x_ X position
* @param y_ Y position
* @param w_ width
* @param h_ heigth
*/
@Deprecated
public Region(int x_, int y_, int w_, int h_) {
init(x_,y_,w_,h_, null);
}
/**
* Create a region from a Rectangle
*
* @deprecated Not for public use in Java. Use Region.create() instead.
*
* @param r the Rectangle
*/
@Deprecated
public Region(Rectangle r) {
init(r.x, r.y, r.width, r.height, null);
}
/**
* Create a region from an other region
*
* @deprecated Not for public use in Java. Use Region.create() instead.
*
* @param r the region
*/
@Deprecated
public Region(Region r) {
init(r.x, r.y, r.w, r.h, r.getScreen());
}
Region(Rectangle r, IScreen parentScreen) {
init(r.x, r.y, r.width, r.height, parentScreen);
}
/**
* Create a region from a Rectangle
*
* @param r the Rectangle
*/
public static Region create(Rectangle rect){
return create(new Region(rect));
}
/**
* Create a region with the provided coordinate / size
*
* @param x_ X position
* @param y_ Y position
* @param w_ width
* @param h_ heigth
*/
public static Region create(int x_, int y_, int w_, int h_) {
return create(new Region(x_, y_, w_, h_));
}
public static Region create(Rectangle r, IScreen parentScreen){
return create(new Region(r, parentScreen));
}
/**
* Create a region from an other region
*
* @param r the region
*/
public static Region create(Region r){
//TODO: determine if the caller is Jython
return toJythonRegion(r);
}
protected Region(){}
/////////////////////////////////////////////////////////////////
public String toString(){
return String.format("Region[%d,%d %dx%d]@%s E:%s, T:%.1f",
x, y, w, h, _scr.toString(),
_throwException?"Y":"N", _autoWaitTimeout);
}
protected void init(int x_, int y_, int w_, int h_, IScreen parentScreen) {
x = x_;
y = y_;
w = w_;
h = h_;
if(parentScreen != null)
_scr = parentScreen;
else
_scr = initScreen();
_robot = _scr.getRobot();
}
protected EventManager getEventManager(){
if(_evtMgr == null)
_evtMgr = new EventManager(this);
return _evtMgr;
}
private Screen initScreen(){
if(this instanceof Screen)
return (Screen)this;
Rectangle roi = new Rectangle(x, y, w, h);
for(int i=0;i<Screen.getNumberScreens();i++){
Rectangle scrBound = Screen.getBounds(i);
if(scrBound.contains(roi)){
return new Screen(i);
}
}
return new Screen();
}
protected void updateSelf(){
if(_overlay != null)
_overlay.highlight(this);
}
////////////////////////////////////////////////////////
public IScreen getScreen(){ return _scr; }
public int getX(){ return x; }
public int getY(){ return y; }
public int getW(){ return w; }
public int getH(){ return h; }
public void setX(int _x){ x = _x; }
public void setY(int _y){ y = _y; }
public void setW(int _w){ w = _w; }
public void setH(int _h){ h = _h; }
public Rectangle getROI(){ return new Rectangle(x,y,w,h); }
public void setROI(int X, int Y, int W, int H){
x = X; y = Y; w = W; h = H;
}
public void setROI(Region roi){
x = roi.x;
y = roi.y;
w = roi.w;
h = roi.h;
}
public void setROI(Rectangle roi){
x = (int)roi.getX();
y = (int)roi.getY();
w = (int)roi.getWidth();
h = (int)roi.getHeight();
}
public void highlight(){
if(_overlay==null)
highlight(true);
else
highlight(false);
}
protected void highlight(boolean toEnable){
Debug.history("toggle highlight " + toString() + ": " + toEnable);
if(!(_scr instanceof Screen)){
Debug.error("highlight only work on the physical desktop screens.");
return;
}
Screen scr = (Screen)getScreen();
if(toEnable){
_overlay = new ScreenHighlighter(scr);
_overlay.highlight(this);
}
else{
if(_overlay != null){
_overlay.close();
_overlay = null;
}
}
}
public void highlight(float secs){
Debug.history("highlight " + toString() + " for " + secs + " secs");
if(!(_scr instanceof Screen)){
Debug.error("highlight only work on the physical desktop screens.");
return;
}
Screen scr = (Screen)getScreen();
ScreenHighlighter overlay = new ScreenHighlighter(scr);
overlay.highlight(this, secs);
}
public Rectangle getRect(){ return getROI(); }
public void setRect(Rectangle roi){ setROI(roi); }
public void setRect(int X, int Y, int W, int H){ setROI(X, Y, W, H); }
public void setRect(Region roi){ setROI(roi); }
public Location getCenter(){
return new Location(x+w/2, y+h/2);
}
public Location getTopLeft(){
return new Location(x, y);
}
public Location getTopRight(){
return new Location(x+w, y);
}
public Location getBottomLeft(){
return new Location(x, y+h);
}
public Location getBottomRight(){
return new Location(x+w, y+h);
}
///// SPATIAL OPERATORS
public Region offset(Location loc){
return Region.create(x+loc.x, y+loc.y, w, h);
}
public Region moveTo(Location loc){
x = loc.x;
y = loc.y;
updateSelf();
return this;
}
public Region morphTo(Region r){
x = r.x;
y = r.y;
w = r.w;
h = r.h;
updateSelf();
return this;
}
public Region nearby(){
final int PADDING = 50;
return nearby(PADDING);
}
public Region nearby(int range){
Rectangle bounds = getScreen().getBounds();
Rectangle rect = new Rectangle(x-range,y-range,w+range*2,h+range*2);
rect = rect.intersection(bounds);
return Region.create(rect);
}
public Region right(){ return right(9999999); }
public Region right(int range){
Rectangle bounds = getScreen().getBounds();
Rectangle rect = new Rectangle(x+w,y,range,h);
rect = rect.intersection(bounds);
return Region.create(rect);
}
public Region left(){ return left(9999999); }
public Region left(int range){
Rectangle bounds = getScreen().getBounds();
Region r = Region.create(this);
r.x = x-range < bounds.x? bounds.x: x-range;
r.y = y;
r.w = x - r.x;
r.h = h;
return r;
}
public Region above(){ return above(9999999); }
public Region above(int range){
Rectangle bounds = getScreen().getBounds();
Region r = Region.create(this);
r.x = x;
r.y = y-range < bounds.y? bounds.y : y-range;
r.w = w;
r.h = y-r.y;
return r;
}
public Region below(){ return below(999999); }
public Region below(int range){
Rectangle bounds = getScreen().getBounds();
Rectangle rect = new Rectangle(x,y+h,w,range);
rect = rect.intersection(bounds);
return Region.create(rect);
}
public Region inside(){
return this;
}
//////////// Settings
public void setThrowException(boolean flag){
_throwException = flag;
if (_throwException){
_defaultFindFailedResponse = FindFailedResponse.ABORT;
}else{
_defaultFindFailedResponse = FindFailedResponse.SKIP;
}
}
public void setAutoWaitTimeout(double sec){ _autoWaitTimeout = sec; }
public boolean getThrowException(){ return _throwException; }
public double getAutoWaitTimeout(){ return _autoWaitTimeout; }
//////////// PUBLIC API
/**
* Match find( Pattern/String/PatternClass )
* finds the given pattern on the screen and returns the best match.
* If AutoWaitTimeout is set, this is equivalent to wait().
*
* @param target A search criteria
* @return If found, the element. null otherwise
* @throws FindFailed if the Find operation failed
*/
public <PSC> Match find(final PSC target) throws FindFailed{
if(_autoWaitTimeout > 0){
return wait(target, _autoWaitTimeout);
}
while (true){
try{
_lastMatch = doFind(target);
}catch (Exception e){
throw new FindFailed(e.getMessage());
}
if (_lastMatch != null){
return _lastMatch;
}
if (!handleFindFailed(target))
return null;
}
}
// return false to skip
// return true to try again
// throw FindFailed to abort
<PSC> boolean handleFindFailed(PSC target) throws FindFailed{
FindFailedResponse response;
if (_defaultFindFailedResponse == FindFailedResponse.PROMPT){
FindFailedDialog fd = new FindFailedDialog(target);
fd.setVisible(true);
response = fd.getResponse();
}else{
response = _defaultFindFailedResponse;
}
if (response == FindFailedResponse.SKIP){
return false;
}else if (response == FindFailedResponse.RETRY){
return true;
}else if (response == FindFailedResponse.ABORT){
throw new FindFailed("can not find " + target + " on the screen.");
}
return false;
}
/**
* Iterator<Match> findAll( Pattern/String/PatternClass )
* finds the given pattern on the screen and returns the best match.
* If AutoWaitTimeout is set, this is equivalent to wait().
*
* @param target A search criteria
* @return All elements matching
* @throws FindFailed if the Find operation failed
*/
public <PSC> Iterator<Match> findAll(PSC target)
throws FindFailed{
while (true){
try{
if(_autoWaitTimeout > 0){
RepeatableFindAll rf = new RepeatableFindAll(target);
rf.repeat(_autoWaitTimeout);
_lastMatches = rf.getMatches();
}
else{
_lastMatches = doFindAll(target);
}
}catch (Exception e){
throw new FindFailed(e.getMessage());
}
if (_lastMatches != null){
return _lastMatches;
}
if (!handleFindFailed(target))
return null;
}
}
//WARNING: wait(long timeout) is taken by Java Object
public void wait(double timeout) {
try{
Thread.sleep((long)(timeout*1000L));
}
catch(InterruptedException e){
e.printStackTrace();
}
}
public <PSC> Match wait(PSC target) throws FindFailed{
return wait(target, _autoWaitTimeout);
}
/**
* Match wait(Pattern/String/PatternClass target, timeout-sec)
* waits until target appears or timeout (in second) is passed
*
* @param target A search criteria
* @param timeout Timeout in seconds
* @return All elements matching
* @throws FindFailed if the Find operation failed
*/
public <PSC> Match wait(PSC target, double timeout) throws FindFailed{
while (true){
try {
Debug.log(2, "waiting for " + target + " to appear");
RepeatableFind rf = new RepeatableFind(target);
rf.repeat(timeout);
_lastMatch = rf.getMatch();
} catch (Exception e) {
throw new FindFailed(e.getMessage());
}
if (_lastMatch != null){
Debug.log(2, "" + target + " has appeared.");
break;
}
Debug.log(2, "" + target + " has not appeared.");
if (!handleFindFailed(target))
return null;
}
return _lastMatch;
}
/**
* Check if target exists (with the default autoWaitTimeout)
*
* @param target A search criteria
* @return The element matching
*/
public <PSC> Match exists(PSC target) {
return exists(target, _autoWaitTimeout);
}
/**
* Check if target exists with a specified timeout
*
* @param target A search criteria
* @param timeout Timeout in second
* @return The element matching
*/
public <PSC> Match exists(PSC target, double timeout) {
try{
RepeatableFind rf = new RepeatableFind(target);
if (rf.repeat(timeout)){
_lastMatch = rf.getMatch();
return _lastMatch;
}
}
catch(Exception ff){
// TODO: This should throw an exception since
// it is likely caused by not able to read the input
// image.
}
return null;
}
public <PSC> boolean waitVanish(PSC target) {
return waitVanish(target, _autoWaitTimeout);
}
/**
* boolean waitVanish(Pattern/String/PatternClass target, timeout-sec)
* waits until target vanishes or timeout (in second) is passed
* @return true if the target vanishes, otherwise returns false.
*/
public <PSC> boolean waitVanish(PSC target, double timeout) {
try {
Debug.log(2, "waiting for " + target + " to vanish");
RepeatableVanish r = new RepeatableVanish(target);
if (r.repeat(timeout)){
// target has vanished before timeout
Debug.log(2, "" + target + " has vanished");
return true;
}else{
// target has not vanished before timeout
Debug.log(2, "" + target + " has not vanished before timeout");
return false;
}
} catch (Exception e) {
// TODO: This should throw an error (IOException caused by target
// image not readable).
Debug.error(e.getMessage());
}
return false;
}
/**
* Click on the item provided by "target"
*
* @param target Where to click
* @return 1 if success, 0 otherwise
* @throws FindFailed if the Find operation failed
*/
public <PSRML> int click(PSRML target) throws FindFailed{
return click(target, 0);
}
/**
* Click on the item provided by "target"
*
* @param target Where to click
* @param modifiers Can be 0 (no modifier), K_SHIFT, K_CTRL, K_ALT or K_META
* @return 1 if success, 0 otherwise
* @throws FindFailed if the Find operation failed
*/
public <PSRML> int click(PSRML target, int modifiers)
throws FindFailed{
Location loc = getLocationFromPSRML(target);
int ret = _click(loc, InputEvent.BUTTON1_MASK, modifiers, false);
SikuliActionManager.getInstance().clickTarget(this, target, _lastScreenImage, _lastMatch);
return ret;
}
/**
* Double click on the item provided by "target"
*
* @param target Where to double click
* @return 1 if success, 0 otherwise
* @throws FindFailed if the Find operation failed
*/
public <PSRML> int doubleClick(PSRML target) throws FindFailed{
return doubleClick(target, 0);
}
/**
* Double click on the item provided by "target"
*
* @param target Where to double click
* @param modifiers Can be 0 (no modifier), K_SHIFT, K_CTRL, K_ALT or K_META
* @return 1 if success, 0 otherwise
* @throws FindFailed if the Find operation failed
*/
public <PSRML> int doubleClick(PSRML target, int modifiers)
throws FindFailed{
Location loc = getLocationFromPSRML(target);
int ret = _click(loc, InputEvent.BUTTON1_MASK, modifiers, true);
SikuliActionManager.getInstance().doubleClickTarget(this, target, _lastScreenImage, _lastMatch);
return ret;
}
/**
* Right click on the item provided by "target"
*
* @param target Where to right click
* @return 1 if success, 0 otherwise
* @throws FindFailed if the Find operation failed
*/
public <PSRML> int rightClick(PSRML target) throws FindFailed{
return rightClick(target, 0);
}
/**
* Right click on the item provided by "target"
*
* @param target Where to right click
* @param modifiers Can be 0 (no modifier), K_SHIFT, K_CTRL, K_ALT or K_META
* @return 1 if success, 0 otherwise
* @throws FindFailed if the Find operation failed
*/
public <PSRML> int rightClick(PSRML target, int modifiers)
throws FindFailed{
Location loc = getLocationFromPSRML(target);
int ret = _click(loc, InputEvent.BUTTON3_MASK, modifiers, false);
SikuliActionManager.getInstance().rightClickTarget(this, target, _lastScreenImage, _lastMatch);
return ret;
}
/**
* Move the wheel at the current position
*
* @param direction the direction applied
* @param steps the number of step
* @return 1 in any case
*/
public int wheel(int direction, int steps) throws FindFailed{
for(int i=0;i<steps;i++){
_robot.mouseWheel(direction);
_robot.delay(50);
}
return 1;
}
/**
* Move the wheel at the specified position
*
* @param target The specified position
* @param direction the direction applied
* @param steps the number of step
* @return 1 if success, 0 otherwise
* @throws FindFailed if the Find operation failed
*/
public <PSRML> int wheel(PSRML target, int direction, int steps) throws FindFailed{
if( target == null || hover(target) != 0){
return wheel(direction, steps);
}
return 0;
}
public <PSRML> int mouseMove(PSRML target) throws FindFailed{
return hover(target);
}
public <PSRML> int hover(PSRML target) throws FindFailed{
Location loc = getLocationFromPSRML(target);
if( loc != null){
_scr.showMove(loc);
_robot.smoothMove(loc);
_robot.waitForIdle();
return 1;
}
return 0;
}
/**
* Drag and drop from a position to the other
*
* @param t1 The specified source position
* @param t2 The specified destination position
* @return 1 if success, 0 otherwise
* @throws FindFailed if the Find operation failed
*/
public <PSRML> int dragDrop(PSRML t1, PSRML t2) throws FindFailed {
return dragDrop(t1, t2, 0);
}
/**
* Drag and drop from a position to the other
*
* @param t1 The specified source position
* @param t2 The specified destination position
* @param modifiers Can be 0 (no modifier), K_SHIFT, K_CTRL, K_ALT or K_META
* @return 1 if success, 0 otherwise
* @throws FindFailed if the Find operation failed
*/
public <PSRML> int dragDrop(PSRML t1, PSRML t2, int modifiers)
throws FindFailed {
int ret = 0;
Location loc1 = getLocationFromPSRML(t1);
Location loc2 = getLocationFromPSRML(t2);
Debug.history(
(modifiers!=0?KeyEvent.getKeyModifiersText(modifiers)+"+":"")+
"DRAG " + loc1 + " to " + loc2);
if(loc1 != null && loc2 != null){
_robot.pressModifiers(modifiers);
_robot.dragDrop(loc1, loc2, 10,
(long)(Settings.MoveMouseDelay*1000), InputEvent.BUTTON1_MASK);
_robot.releaseModifiers(modifiers);
return 1;
}
return 0;
}
public <PSRML> int drag(PSRML target) throws FindFailed{
Location loc = getLocationFromPSRML(target);
if(loc != null){
_robot.smoothMove(loc);
_scr.showTarget(loc);
_robot.mousePress(InputEvent.BUTTON1_MASK);
_robot.waitForIdle();
return 1;
}
return 0;
}
public <PSRML> int dropAt(PSRML target) throws FindFailed{
return dropAt(target, Settings.DelayBeforeDrop);
}
public <PSRML> int dropAt(PSRML target, double delay) throws FindFailed{
Location loc = getLocationFromPSRML(target);
if(loc != null){
_scr.showDropTarget(loc);
_robot.smoothMove(loc);
_robot.delay((int)(delay*1000));
_robot.mouseRelease(InputEvent.BUTTON1_MASK);
_robot.waitForIdle();
return 1;
}
return 0;
}
public <PSRML> int type(String text) throws FindFailed{
return type(null, text, 0);
}
public <PSRML> int type(String text, int modifiers) throws FindFailed{
return type(null, text, modifiers);
}
public <PSRML> int type(PSRML target, String text) throws FindFailed{
return type(target, text, 0);
}
public <PSRML> int type(PSRML target, String text, int modifiers)
throws FindFailed{
click(target, 0);
if(text != null){
Debug.history(
(modifiers!=0?KeyEvent.getKeyModifiersText(modifiers)+"+":"")+
"TYPE \"" + text + "\"");
for(int i=0; i < text.length(); i++){
_robot.pressModifiers(modifiers);
_robot.typeChar(text.charAt(i), IRobot.KeyMode.PRESS_RELEASE);
_robot.releaseModifiers(modifiers);
_robot.delay(20);
}
_robot.waitForIdle();
return 1;
}
return 0;
}
public int paste(String text) throws FindFailed{
return paste(null, text);
}
public <PSRML> int paste(PSRML target, String text)
throws FindFailed{
click(target, 0);
if(text != null){
Clipboard.putText(Clipboard.PLAIN, Clipboard.UTF8,
Clipboard.BYTE_BUFFER, text);
int mod = Env.getHotkeyModifier();
_robot.keyPress(mod);
_robot.keyPress(KeyEvent.VK_V);
_robot.keyRelease(KeyEvent.VK_V);
_robot.keyRelease(mod);
return 1;
}
return 0;
}
private int _hold_buttons = 0;
public void mouseDown(int buttons) {
_hold_buttons = buttons;
_robot.mousePress(buttons);
_robot.waitForIdle();
}
public void mouseUp() {
mouseUp(0);
}
public void mouseUp(int buttons) {
if(buttons==0)
_robot.mouseRelease(_hold_buttons);
else
_robot.mouseRelease(buttons);
_robot.waitForIdle();
}
/**
* press down the key (given by the key code) on the underlying device.
* The code depend on the type of the device.
*/
public void keyDown(int keycode){
_robot.keyPress(keycode);
}
/**
* release the key (given by the key code) on the underlying device.
* The code depend on the type of the device.
*/
public void keyUp(int keycode){
_robot.keyRelease(keycode);
}
private String _hold_keys = "";
public void keyDown(String keys){
if(keys != null){
for(int i=0; i < keys.length(); i++){
if(_hold_keys.indexOf(keys.charAt(i)) == -1){
Debug.log(5, "press: " + keys.charAt(i));
_robot.typeChar(keys.charAt(i), IRobot.KeyMode.PRESS_ONLY);
_hold_keys += keys.charAt(i);
}
}
_robot.waitForIdle();
return;
}
}
public void keyUp(){
keyUp(null);
}
public void keyUp(String keys){
if(keys == null)
keys = _hold_keys;
for(int i=0; i < keys.length(); i++){
int pos;
if( (pos=_hold_keys.indexOf(keys.charAt(i))) != -1 ){
Debug.log(5, "release: " + keys.charAt(i));
_robot.typeChar(keys.charAt(i), IRobot.KeyMode.RELEASE_ONLY);
_hold_keys = _hold_keys.substring(0,pos) +
_hold_keys.substring(pos+1);
}
}
_robot.waitForIdle();
}
public <PSC> void onAppear(PSC target, SikuliEventObserver observer){
getEventManager().addAppearObserver(target, observer);
}
public <PSC> void onVanish(PSC target, SikuliEventObserver observer){
getEventManager().addVanishObserver(target, observer);
}
public void onChange(int threshold, SikuliEventObserver observer){
getEventManager().addChangeObserver(threshold, observer);
}
public void onChange(SikuliEventObserver observer){
getEventManager().addChangeObserver(Settings.ObserveMinChangedPixels,
observer);
}
public void observe(){
observe(Float.POSITIVE_INFINITY);
}
public void observeInBackground(final double secs){
Thread th = new Thread(){
public void run(){
observe(secs);
}
};
th.start();
}
public void stopObserver(){
_observing = false;
}
public void observe(double secs){
if(_evtMgr == null)
return;
int MaxTimePerScan = (int)(1000.0/Settings.ObserveScanRate);
long begin_t = (new Date()).getTime();
_observing = true;
while( _observing && begin_t + secs*1000 > (new Date()).getTime() ){
long before_find = (new Date()).getTime();
ScreenImage simg = _scr.capture(x, y, w, h);
_lastScreenImage = simg;
_evtMgr.update(simg);
long after_find = (new Date()).getTime();
try{
if(after_find-before_find<MaxTimePerScan)
Thread.sleep((int)(MaxTimePerScan-(after_find-before_find)));
}
catch(Exception e){ }
}
}
public Match getLastMatch(){
return _lastMatch;
}
public Iterator<Match> getLastMatches(){
return _lastMatches;
}
public String text(){
ScreenImage simg = getScreen().capture(x, y, w, h);
_lastScreenImage = simg;
return TextRecognizer.getInstance().recognize(simg);
}
public List<Match> listText(){
ScreenImage simg = getScreen().capture(x, y, w, h);
return TextRecognizer.getInstance().listText(simg, this);
}
////////////////////////////////////////////////////////////////
// SPECIAL FUNCTIONS FOR JYTHON
////////////////////////////////////////////////////////////////
public static Region toJythonRegion(Region r){
if(r == null)
return null;
PythonInterpreter interpreter = new PythonInterpreter();
interpreter.exec("from sikuli import Region");
PyObject regionClass = interpreter.get("Region");
PyObject pyRegion = regionClass.__call__(Py.java2py(r));
return (Region)pyRegion.__tojava__(Region.class);
}
////////////////////////////////////////////////////////////////
// HELPER FUNCTIONS
////////////////////////////////////////////////////////////////
/**
* Match findNow( Pattern/String/PatternClass )
* finds the given pattern on the screen and returns the best match
* without waiting.
*/
public <PSC> Match findNow(PSC ptn) throws FindFailed{
Debug.log("capture: " + x + "," + y);
ScreenImage simg = _scr.capture(x, y, w, h);
Debug.log("ScreenImage: " + simg.getROI());
_lastScreenImage = simg;
Finder f = new Finder(simg, this);
Match ret = null;
try{
f.find(ptn);
if(f.hasNext())
ret = f.next();
f.destroy();
}
catch(IOException e){
throw new FindFailed(e.getMessage());
}
return ret;
}
<PSC> Match doFind(PSC ptn) throws IOException{
ScreenImage simg = getScreen().capture(x, y, w, h);
_lastScreenImage = simg;
Finder f = new Finder(simg, this);
f.find(ptn);
if(f.hasNext()){
return f.next();
}
return null;
}
<PSC> Iterator<Match> doFindAll(PSC ptn) throws IOException{
ScreenImage simg = getScreen().capture(x, y, w, h);
_lastScreenImage = simg;
Finder f = new Finder(simg, this);
f.findAll(ptn);
if(f.hasNext()){
return f;
}
return null;
}
/**
* Match findAllNow( Pattern/String/PatternClass )
* finds the given pattern on the screen and returns the best match
* without waiting.
*/
public <PSC> Iterator<Match> findAllNow(PSC ptn)
throws FindFailed{
ScreenImage simg = _scr.capture(x, y, w, h);
_lastScreenImage = simg;
Finder f = new Finder(simg, this);
try{
f.findAll(ptn);
if(f.hasNext()){
return f;
}
f.destroy();
}
catch(IOException e){
throw new FindFailed(e.getMessage());
}
return null;
}
/**
* Iterator<Match> waitAll(Pattern/String/PatternClass target, timeout-sec)
* waits until target appears or timeout (in second) is passed
*/
@Deprecated
public <PSC> Iterator<Match> waitAll(PSC target, double timeout)
throws FindFailed{
while (true){
try {
RepeatableFindAll rf = new RepeatableFindAll(target);
rf.repeat(timeout);
_lastMatches = rf.getMatches();
} catch (Exception e) {
throw new FindFailed(e.getMessage());
}
if (_lastMatches != null)
break;
if (!handleFindFailed(target))
return null;
}
return _lastMatches;
}
/**
* Figure out where is located target
*
* @param target The specified position
* @return The Region if found. null otherwise.
*/
public <PSRM> Region getRegionFromPSRM(PSRM target)
throws FindFailed {
if(target instanceof Pattern || target instanceof String){
Match m = find(target);
if(m!=null)
return m;
return null;
}
if(target instanceof Region)
return (Region)target;
return null;
}
/**
* Figure out where is located target
*
* @param target The specified position
* @return The Location if found. null otherwise.
*/
public <PSRML> Location getLocationFromPSRML(PSRML target)
throws FindFailed {
if(target instanceof Pattern || target instanceof String){
Match m = find(target);
if(m!=null)
return m.getTarget();
return null;
}
if(target instanceof Match) return ((Match)target).getTarget();
if(target instanceof Region) return ((Region)target).getCenter();
if(target instanceof Location) return (Location)target;
return null;
}
private String getClickMsg(Location loc, int buttons, int modifiers,
boolean dblClick){
String msg = "";
if(modifiers != 0)
msg += KeyEvent.getKeyModifiersText(modifiers) + "+";
if(buttons==InputEvent.BUTTON1_MASK && !dblClick)
msg += "CLICK";
if(buttons==InputEvent.BUTTON1_MASK && dblClick)
msg += "DOUBLE CLICK";
if(buttons==InputEvent.BUTTON3_MASK)
msg += "RIGHT CLICK";
else if(buttons==InputEvent.BUTTON2_MASK)
msg += "MID CLICK";
msg += " on " + loc;
return msg;
}
private int _click(Location loc, int buttons, int modifiers,
boolean dblClick) {
if(loc == null)
return 0;
Debug.history( getClickMsg(loc, buttons, modifiers, dblClick) );
_robot.pressModifiers(modifiers);
_robot.smoothMove(loc);
_scr.showClick(loc);
_robot.mousePress(buttons);
_robot.mouseRelease(buttons);
if( dblClick ){
_robot.mousePress(buttons);
_robot.mouseRelease(buttons);
}
_robot.releaseModifiers(modifiers);
_robot.waitForIdle();
return 1;
}
Location toRobotCoord(Location l){
return new Location(l.x-x, l.y-y);
}
Match toGlobalCoord(Match m){
m.x += x;
m.y += y;
return m;
}
abstract class Repeatable{
abstract void run() throws Exception;
abstract boolean ifSuccessful();
// return TRUE if successful before timeout
// return FALSE if otherwise
// throws Exception if any unexpected error occurs
boolean repeat(double timeout) throws Exception{
int MaxTimePerScan = (int)(1000.0/Settings.WaitScanRate);
long begin_t = (new Date()).getTime();
do{
long before_find = (new Date()).getTime();
run();
if (ifSuccessful())
return true;
long after_find = (new Date()).getTime();
if(after_find-before_find<MaxTimePerScan)
_robot.delay((int)(MaxTimePerScan-(after_find-before_find)));
else
_robot.delay(10);
}while( begin_t + timeout*1000 > (new Date()).getTime() );
return false;
}
}
class RepeatableFind extends Repeatable{
Object _target;
Match _match = null;
public <PSC> RepeatableFind(PSC target){
_target = target;
}
public Match getMatch() {
return _match;
}
@Override
public void run() throws IOException{
_match = doFind(_target);
}
@Override
boolean ifSuccessful() {
return _match != null;
}
}
class RepeatableVanish extends RepeatableFind{
public <PSC> RepeatableVanish(PSC target){
super(target);
}
@Override
boolean ifSuccessful() {
return _match == null;
}
}
class RepeatableFindAll extends Repeatable{
Object _target;
Iterator<Match> _matches = null;
public <PSC> RepeatableFindAll(PSC target){
_target = target;
}
public Iterator<Match> getMatches() {
return _matches;
}
@Override
public void run() throws IOException{
_matches = doFindAll(_target);
}
@Override
boolean ifSuccessful() {
return _matches != null;
}
}
}
|
package com.nmmoc7.polymercore.common.multiblock.unit;
import net.minecraft.block.BlockState;
import net.minecraft.fluid.FluidState;
import java.util.Collections;
public class UnitFluidState extends AbstractUnit {
private final FluidState fluidState;
public UnitFluidState(FluidState fluid) {
super(Collections.singletonList(fluid.getBlockState()));
this.fluidState = fluid;
}
@Override
public boolean test(BlockState block) {
return fluidState == block.getFluidState();
}
}
|
package br.com.cams7.siscom.jpa.domain.entity;
import java.util.Date;
import java.util.List;
import javax.persistence.AttributeOverride;
import javax.persistence.AttributeOverrides;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.UniqueConstraint;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import br.com.cams7.apps.jpa.domain.BaseEntity;
import br.com.cams7.siscom.jpa.domain.RegistroPessoal;
/**
* The persistent class for the cliente database table.
*
*/
@Entity
@Table(name = "cliente", uniqueConstraints = @UniqueConstraint(columnNames = {
"email", "cpf_cliente", "cnpj_cliente" }))
@AttributeOverrides({
@AttributeOverride(name = "id", column = @Column(name = "cod_cliente")),
@AttributeOverride(name = "nome", column = @Column(name = "nome_cliente")),
@AttributeOverride(name = "email", column = @Column(name = "email")),
@AttributeOverride(name = "cadastro", column = @Column(name = "desde_cliente")),
@AttributeOverride(name = "rg", column = @Column(name = "rg_cliente")),
@AttributeOverride(name = "orgaoExpedidor", column = @Column(name = "orgao_rg_cliente")),
@AttributeOverride(name = "cpf", column = @Column(name = "cpf_cliente")),
@AttributeOverride(name = "cnpj", column = @Column(name = "cnpj_cliente")) })
@SequenceGenerator(name = "USUARIO_GENERATOR", sequenceName = "cliente_seq", initialValue = BaseEntity.INITIAL_VALUE, allocationSize = BaseEntity.ALLOCATION_SIZE)
@NamedQuery(name = "Cliente.findAll", query = "SELECT c FROM ClienteEntity c")
public class ClienteEntity extends RegistroPessoal<Integer> {
private static final long serialVersionUID = 1L;
@NotNull
@Temporal(TemporalType.DATE)
@Column(name = "nascimento_cliente")
private Date nascimento;
@Size(min = 5, max = 40)
@Column(name = "profissao_cliente")
private String profissao;
@Column(name = "renda_cliente")
private Double rendaMensal;
@Size(min = 5, max = 50)
@Column(name = "empresa_cliente")
private String empresaNome;
@Size(min = 8, max = 15)
@Column(name = "fone_empresa")
private String empresaFone;
@Size(min = 5, max = 50)
@Column(name = "referencia_cliente")
private String referenciaNome;
@Size(min = 8, max = 15)
@Column(name = "fone_referencia_cliente")
private String referenciaFone;
@NotNull
@Enumerated(EnumType.ORDINAL)
@Column(name = "tipo_cliente", length = 1, columnDefinition = "char(1)")
private TipoCliente tipo;
// bi-directional many-to-one association to EnderecoEntity
@OneToMany(mappedBy = "cliente")
private List<ClienteEnderecoEntity> enderecos;
// bi-directional many-to-one association to TelefoneEntity
@OneToMany(mappedBy = "cliente")
private List<ClienteTelefoneEntity> telefones;
// bi-directional many-to-one association to CobrancaEntity
@OneToMany(mappedBy = "cliente")
private List<CobrancaEntity> cobrancas;
// bi-directional many-to-one association to OrcamentoCabecarioEntity
@OneToMany(mappedBy = "cliente")
private List<OrcamentoCabecarioEntity> orcamentos;
// bi-directional many-to-one association to RecebimentoEntity
@OneToMany(mappedBy = "cliente")
private List<RecebimentoEntity> recebimentos;
// bi-directional many-to-one association to VendaCabecarioEntity
@OneToMany(mappedBy = "cliente")
private List<VendaCabecarioEntity> vendas;
public ClienteEntity() {
super();
}
public ClienteEntity(Integer id) {
super(id);
}
public Date getNascimento() {
return this.nascimento;
}
public void setNascimento(Date nascimento) {
this.nascimento = nascimento;
}
public String getProfissao() {
return this.profissao;
}
public void setProfissao(String profissao) {
this.profissao = profissao;
}
public Double getRendaMensal() {
return this.rendaMensal;
}
public void setRendaMensal(Double rendaMensal) {
this.rendaMensal = rendaMensal;
}
public String getEmpresaNome() {
return this.empresaNome;
}
public void setEmpresaNome(String empresaNome) {
this.empresaNome = empresaNome;
}
public String getEmpresaFone() {
return this.empresaFone;
}
public void setEmpresaFone(String empresaFone) {
this.empresaFone = empresaFone;
}
public String getReferenciaNome() {
return this.referenciaNome;
}
public void setReferenciaNome(String referenciaNome) {
this.referenciaNome = referenciaNome;
}
public String getReferenciaFone() {
return this.referenciaFone;
}
public void setReferenciaFone(String referenciaFone) {
this.referenciaFone = referenciaFone;
}
public TipoCliente getTipo() {
return this.tipo;
}
public void setTipo(TipoCliente tipo) {
this.tipo = tipo;
}
public List<ClienteEnderecoEntity> getEnderecos() {
return this.enderecos;
}
public void setEnderecos(List<ClienteEnderecoEntity> enderecos) {
this.enderecos = enderecos;
}
public ClienteEnderecoEntity addEndereco(ClienteEnderecoEntity endereco) {
getEnderecos().add(endereco);
endereco.setCliente(this);
return endereco;
}
public ClienteEnderecoEntity removeEndereco(ClienteEnderecoEntity endereco) {
getEnderecos().remove(endereco);
endereco.setCliente(null);
return endereco;
}
public List<ClienteTelefoneEntity> getTelefones() {
return this.telefones;
}
public void setTelefones(List<ClienteTelefoneEntity> telefones) {
this.telefones = telefones;
}
public ClienteTelefoneEntity addTelefone(ClienteTelefoneEntity telefone) {
getTelefones().add(telefone);
telefone.setCliente(this);
return telefone;
}
public ClienteTelefoneEntity removeTelefone(ClienteTelefoneEntity telefone) {
getTelefones().remove(telefone);
telefone.setCliente(null);
return telefone;
}
public List<CobrancaEntity> getCobrancas() {
return this.cobrancas;
}
public void setCobrancas(List<CobrancaEntity> cobrancas) {
this.cobrancas = cobrancas;
}
public CobrancaEntity addCobranca(CobrancaEntity cobranca) {
getCobrancas().add(cobranca);
cobranca.setCliente(this);
return cobranca;
}
public CobrancaEntity removeCobranca(CobrancaEntity cobranca) {
getCobrancas().remove(cobranca);
cobranca.setCliente(null);
return cobranca;
}
public List<OrcamentoCabecarioEntity> getOrcamentos() {
return this.orcamentos;
}
public void setOrcamentos(List<OrcamentoCabecarioEntity> orcamentos) {
this.orcamentos = orcamentos;
}
public OrcamentoCabecarioEntity addOrcamento(
OrcamentoCabecarioEntity orcamento) {
getOrcamentos().add(orcamento);
orcamento.setCliente(this);
return orcamento;
}
public OrcamentoCabecarioEntity removeOrcamento(
OrcamentoCabecarioEntity orcamento) {
getOrcamentos().remove(orcamento);
orcamento.setCliente(null);
return orcamento;
}
public List<RecebimentoEntity> getRecebimentos() {
return this.recebimentos;
}
public void setRecebimentos(List<RecebimentoEntity> recebimentos) {
this.recebimentos = recebimentos;
}
public RecebimentoEntity addRecebimento(RecebimentoEntity recebimento) {
getRecebimentos().add(recebimento);
recebimento.setCliente(this);
return recebimento;
}
public RecebimentoEntity removeRecebimento(RecebimentoEntity recebimento) {
getRecebimentos().remove(recebimento);
recebimento.setCliente(null);
return recebimento;
}
public List<VendaCabecarioEntity> getVendas() {
return this.vendas;
}
public void setVendas(List<VendaCabecarioEntity> vendas) {
this.vendas = vendas;
}
public VendaCabecarioEntity addVenda(VendaCabecarioEntity venda) {
getVendas().add(venda);
venda.setCliente(this);
return venda;
}
public VendaCabecarioEntity removeVenda(VendaCabecarioEntity venda) {
getVendas().remove(venda);
venda.setCliente(null);
return venda;
}
public enum TipoCliente {
EMPRESA, PESSOA_FISICA
}
}
|
/*
* Copyright 2016-2021 Cisco Systems Inc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.ciscowebex.androidsdk.phone;
import com.ciscowebex.androidsdk.WebexError;
import me.helloworld.utils.Objects;
import me.helloworld.utils.annotation.StringPart;
/**
* An observer interface for {@link Call} event
*
* @since 0.1
*/
public interface CallObserver {
/**
* Callback when the call is waiting.
*
* @param call Call.
* @param reason The reason why the call is waiting.
* @since 2.4.0
*/
default void onWaiting(Call call, Call.WaitReason reason) {
}
/**
* Callback when remote participant(s) is ringing.
*
* @param call Call
* @since 0.1
*/
default void onRinging(Call call) {
}
/**
* Callback when remote participant(s) answered and the call is connected.
*
* @param call Call
* @since 0.1
*/
default void onConnected(Call call) {
}
/**
* Callback when the call is disconnected (hangup, cancelled, get declined or other self device pickup the call).
*
* @param event event
* @since 0.1
*/
default void onDisconnected(CallDisconnectedEvent event) {
}
/**
* Callback when the media types of the call have changed.
*
* @param event event
* @since 0.1
*/
default void onMediaChanged(MediaChangedEvent event) {
}
/**
* Callback when the memberships of this call have changed.
*
* @param event event
* @since 1.3.0
*/
default void onCallMembershipChanged(CallMembershipChangedEvent event) {
}
/**
* Callback when the `Call` is scheduled call and the schedules of the call has been changed.
*
* @param call Call
* @since 2.6.0
*/
default void onScheduleChanged(Call call) {
}
/**
* Base class for the event of a call
*
* @since 0.1
*/
interface CallEvent {
/**
* @return Call
* @since 0.1
*/
Call getCall();
}
/**
* Base class for the event of a call
*
* @since 0.1
*/
abstract class AbstractCallEvent implements CallEvent {
@StringPart
protected Call _call;
protected AbstractCallEvent(Call call) {
_call = call;
}
/**
* @see CallEvent
*/
public Call getCall() {
return _call;
}
@Override
public String toString() {
return Objects.toStringByAnnotation(this);
}
}
/**
* This event is fired when the call is disconnected.
*
* @since 0.1
*/
interface CallDisconnectedEvent extends CallEvent {
}
/**
* This event is fired when local party has left the call.
*
* @since 0.1
*/
class LocalLeft extends AbstractCallEvent implements CallDisconnectedEvent {
public LocalLeft(Call call) {
super(call);
}
}
/**
* This event is fired when the local party has declined the call.
* This is only applicable when the direction of the call is incoming.
*
* @since 0.1
*/
class LocalDecline extends AbstractCallEvent implements CallDisconnectedEvent {
public LocalDecline(Call call) {
super(call);
}
}
/**
* TThis event is fired when the local party has cancelled the call.
* This is only applicable when the direction of the call is outgoing.
*
* @since 0.1
*/
class LocalCancel extends AbstractCallEvent implements CallDisconnectedEvent {
public LocalCancel(Call call) {
super(call);
}
}
/**
* This event is fired when the remote party has left the call.
*
* @since 0.1
*/
class RemoteLeft extends AbstractCallEvent implements CallDisconnectedEvent {
public RemoteLeft(Call call) {
super(call);
}
}
/**
* This event is fired when the remote party has declined the call.
* This is only applicable when the direction of the call is outgoing.
*
* @since 0.1
*/
class RemoteDecline extends AbstractCallEvent implements CallDisconnectedEvent {
public RemoteDecline(Call call) {
super(call);
}
}
/**
* This event is fired when the remote party has cancelled the call.
* This is only applicable when the direction of the call is incoming.
*
* @since 0.1
*/
class RemoteCancel extends AbstractCallEvent implements CallDisconnectedEvent {
public RemoteCancel(Call call) {
super(call);
}
}
/**
* This event is fired when one of the other phones of the authenticated user has answered the call.
* This is only applicable when the direction of the call is incoming.
*
* @since 0.1
*/
class OtherConnected extends AbstractCallEvent implements CallDisconnectedEvent {
public OtherConnected(Call call) {
super(call);
}
}
/**
* One of the other phones of the authenticated user has declined the call. This is only applicable when the direction of the call is incoming.
*
* @since 0.1
*/
class OtherDeclined extends AbstractCallEvent implements CallDisconnectedEvent {
public OtherDeclined(Call call) {
super(call);
}
}
/**
* This event is fired when the call to be disconnected due to an error.
*
* @since 0.1
*/
class CallErrorEvent extends AbstractCallEvent implements CallDisconnectedEvent {
@StringPart
private WebexError _error;
public CallErrorEvent(Call call, WebexError error) {
super(call);
_error = error;
}
/**
* @return Error
* @since 0.1
*/
public WebexError getError() {
return _error;
}
@Override
public String toString() {
return Objects.toStringByAnnotation(this);
}
}
/**
* Media change event
*
* @since 0.1
*/
interface MediaChangedEvent extends CallEvent {
}
/**
* This might be triggered when the remote party muted or unmuted the video.
*
* @since 0.1
*/
class RemoteSendingVideoEvent extends AbstractCallEvent implements MediaChangedEvent {
@StringPart
private boolean _sending;
public RemoteSendingVideoEvent(Call call, boolean sending) {
super(call);
_sending = sending;
}
/**
* @return True if the remote party now is sending video. Otherwise false.
* @since 0.1
*/
public boolean isSending() {
return _sending;
}
@Override
public String toString() {
return Objects.toStringByAnnotation(this);
}
}
/**
* This might be triggered when the remote party muted or unmuted the audio.
*
* @since 0.1
*/
class RemoteSendingAudioEvent extends AbstractCallEvent implements MediaChangedEvent {
@StringPart
private boolean _sending;
public RemoteSendingAudioEvent(Call call, boolean sending) {
super(call);
_sending = sending;
}
/**
* @return True if the remote party now is sending audio. Otherwise false.
* @since 0.1
*/
public boolean isSending() {
return _sending;
}
@Override
public String toString() {
return Objects.toStringByAnnotation(this);
}
}
/**
* This might be triggered when the remote party muted or unmuted the content sharing.
*
* @since 1.3.0
*/
class RemoteSendingSharingEvent extends AbstractCallEvent implements MediaChangedEvent {
@StringPart
private boolean _sending;
public RemoteSendingSharingEvent(Call call, boolean sending) {
super(call);
_sending = sending;
}
/**
* @return True if the remote party now is sending content sharing. Otherwise false.
* @since 1.3.0
*/
public boolean isSending() {
return _sending;
}
@Override
public String toString() {
return Objects.toStringByAnnotation(this);
}
}
/**
* This might be triggered when the local party started or stopped the content sharing.
*
* @since 1.4.0
*/
class SendingSharingEvent extends AbstractCallEvent implements MediaChangedEvent {
@StringPart
private boolean _sending;
public SendingSharingEvent(Call call, boolean sending) {
super(call);
_sending = sending;
}
/**
* @return True if the local party now is sending content sharing. Otherwise false.
* @since 1.4.0
*/
public boolean isSending() {
return _sending;
}
@Override
public String toString() {
return Objects.toStringByAnnotation(this);
}
}
/**
* This might be triggered when the local party muted or unmuted the video.
*
* @since 0.1
*/
class SendingVideo extends AbstractCallEvent implements MediaChangedEvent {
@StringPart
private boolean _sending;
public SendingVideo(Call call, boolean sending) {
super(call);
_sending = sending;
}
/**
* @return True if the local party now is sending video. Otherwise false.
* @since 0.1
*/
public boolean isSending() {
return _sending;
}
@Override
public String toString() {
return Objects.toStringByAnnotation(this);
}
}
/**
* This might be triggered when the local party muted or unmuted the audio.
*
* @since 0.1
*/
class SendingAudio extends AbstractCallEvent implements MediaChangedEvent {
@StringPart
private boolean _sending;
public SendingAudio(Call call, boolean sending) {
super(call);
_sending = sending;
}
/**
* @return True if the local party now is sending aduio. Otherwise false.
* @since 0.1
*/
public boolean isSending() {
return _sending;
}
@Override
public String toString() {
return Objects.toStringByAnnotation(this);
}
}
/**
* This might be triggered when the local party muted or unmuted the video.
*
* @since 0.1
*/
class ReceivingVideo extends AbstractCallEvent implements MediaChangedEvent {
@StringPart
private boolean _receiving;
public ReceivingVideo(Call call, boolean receiving) {
super(call);
_receiving = receiving;
}
/**
* @return True if the local party now is receiving video. Otherwise false.
* @since 0.1
*/
public boolean isReceiving() {
return _receiving;
}
@Override
public String toString() {
return Objects.toStringByAnnotation(this);
}
}
/**
* This might be triggered when the local party muted or unmuted the audio.
*
* @since 0.1
*/
class ReceivingAudio extends AbstractCallEvent implements MediaChangedEvent {
@StringPart
private boolean _receiving;
public ReceivingAudio(Call call, boolean receiving) {
super(call);
_receiving = receiving;
}
/**
* @return True if the local party now is receiving audio. Otherwise false.
* @since 0.1
*/
public boolean isReceiving() {
return _receiving;
}
@Override
public String toString() {
return Objects.toStringByAnnotation(this);
}
}
/**
* This might be triggered when the local party muted or unmuted the remote content sharing.
*
* @since 1.3.0
*/
class ReceivingSharing extends AbstractCallEvent implements MediaChangedEvent {
@StringPart
private boolean _receiving;
public ReceivingSharing(Call call, boolean receiving) {
super(call);
_receiving = receiving;
}
/**
* @return True if the local party now is receiving content sharing. Otherwise false.
* @since 0.1
*/
public boolean isReceiving() {
return _receiving;
}
@Override
public String toString() {
return Objects.toStringByAnnotation(this);
}
}
/**
* Camera FacingMode on local device has switched.
*
* @since 0.1
*/
class CameraSwitched extends AbstractCallEvent implements MediaChangedEvent {
public CameraSwitched(Call call) {
super(call);
}
}
/**
* Local video rendering view size has changed.
*
* @since 0.1
*/
class LocalVideoViewSizeChanged extends AbstractCallEvent implements MediaChangedEvent {
public LocalVideoViewSizeChanged(Call call) {
super(call);
}
}
/**
* Local video rendering view size has changed.
*
* @since 2.5.0
*/
class LocalSharingViewSizeChanged extends AbstractCallEvent implements MediaChangedEvent {
public LocalSharingViewSizeChanged(Call call) {
super(call);
}
}
/**
* Remote video rendering view size has changed.
*
* @since 0.1
*/
class RemoteVideoViewSizeChanged extends AbstractCallEvent implements MediaChangedEvent {
public RemoteVideoViewSizeChanged(Call call) {
super(call);
}
}
/**
* Remote sharing rendering view size has changed.
*
* @since 1.3.0
*/
class RemoteSharingViewSizeChanged extends AbstractCallEvent implements MediaChangedEvent {
public RemoteSharingViewSizeChanged(Call call) {
super(call);
}
}
/**
* Remote sharing rendering view size has changed.
*
* @since 2.0.0
*/
class ActiveSpeakerChangedEvent extends AbstractCallEvent implements MediaChangedEvent {
@StringPart
private CallMembership _from;
@StringPart
private CallMembership _to;
public ActiveSpeakerChangedEvent(Call call, CallMembership from, CallMembership to) {
super(call);
_from = from;
_to = to;
}
public CallMembership from() {
return _from;
}
public CallMembership to() {
return _to;
}
@Override
public String toString() {
return Objects.toStringByAnnotation(this);
}
}
/**
* Call membership change event
*
* @since 1.3.0
*/
interface CallMembershipChangedEvent extends CallEvent {
CallMembership getCallMembership();
}
/**
* Base class for the event of a CallMembershipEvent
*
* @since 1.3.0
*/
abstract class AbstractCallMembershipChangedEvent extends AbstractCallEvent implements CallMembershipChangedEvent {
@StringPart
protected CallMembership _membership;
protected AbstractCallMembershipChangedEvent(Call call, CallMembership membership) {
super(call);
_membership = membership;
}
/**
* @see CallMembershipChangedEvent
*/
/**
* @return changed membership.
* @since 1.3.0
*/
public CallMembership getCallMembership() {
return _membership;
}
@Override
public String toString() {
return Objects.toStringByAnnotation(this);
}
}
/**
* This might be triggered when the person in the membership joined this call.
*
* @since 1.3.0
*/
class MembershipJoinedEvent extends AbstractCallMembershipChangedEvent {
public MembershipJoinedEvent(Call call, CallMembership membership) {
super(call, membership);
}
}
/**
* This might be triggered when the person in the membership left this call.
*
* @since 1.3.0
*/
class MembershipLeftEvent extends AbstractCallMembershipChangedEvent {
public MembershipLeftEvent(Call call, CallMembership membership) {
super(call, membership);
}
}
/**
* This might be triggered when the person in the membership declined this call.
*
* @since 1.3.0
*/
class MembershipDeclinedEvent extends AbstractCallMembershipChangedEvent {
public MembershipDeclinedEvent(Call call, CallMembership membership) {
super(call, membership);
}
}
/**
* This might be triggered when the person in the membership started sending video this call.
*
* @since 1.3.0
*/
class MembershipSendingVideoEvent extends AbstractCallMembershipChangedEvent {
public MembershipSendingVideoEvent(Call call, CallMembership membership) {
super(call, membership);
}
}
/**
* This might be triggered when the person in the membership started sending audio this call.
*
* @since 1.3.0
*/
class MembershipSendingAudioEvent extends AbstractCallMembershipChangedEvent {
public MembershipSendingAudioEvent(Call call, CallMembership membership) {
super(call, membership);
}
}
/**
* This might be triggered when the person in the membership started sharing this call.
*
* @since 1.3.0
*/
class MembershipSendingSharingEvent extends AbstractCallMembershipChangedEvent {
public MembershipSendingSharingEvent(Call call, CallMembership membership) {
super(call, membership);
}
}
/**
* This might be triggered when the person in the membership is waiting in the lobby.
*
* @since 2.4.0
*/
class MembershipWaitingEvent extends AbstractCallMembershipChangedEvent {
private Call.WaitReason waitReason;
public MembershipWaitingEvent(Call call, CallMembership membership, Call.WaitReason waitReason) {
super(call, membership);
this.waitReason = waitReason;
}
public Call.WaitReason getWaitReason() {
return waitReason;
}
}
/**
* This might be triggered when the person in the membership is muted by others in the meeting.
*
* @since 2.7.0
*/
class MembershipAudioMutedControlledEvent extends AbstractCallMembershipChangedEvent {
public MembershipAudioMutedControlledEvent(Call call, CallMembership membership) {
super(call, membership);
}
}
}
|
/**
* 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.github.liyue2008.rpc;
import com.github.liyue2008.rpc.spi.ServiceSupport;
import java.io.Closeable;
import java.net.URI;
import java.util.Collection;
/**
* RPC框架对外提供的服务接口
* @author LiYue
* Date: 2019/9/20
*/
public interface RpcAccessPoint extends Closeable{
/**
* 客户端获取远程服务的引用
* @param uri 远程服务地址
* @param serviceClass 服务的接口类的Class
* @param <T> 服务接口的类型
* @return 远程服务引用
*/
<T> T getRemoteService(URI uri, Class<T> serviceClass);
/**
* 服务端注册服务的实现实例
* @param service 实现实例
* @param serviceClass 服务的接口类的Class
* @param <T> 服务接口的类型
* @return 服务地址
*/
<T> URI addServiceProvider(T service, Class<T> serviceClass);
/**
* 获取注册中心的引用
* @param nameServiceUri 注册中心URI
* @return 注册中心引用
*/
default NameService getNameService(URI nameServiceUri) {
Collection<NameService> nameServices = ServiceSupport.loadAll(NameService.class);
for (NameService nameService : nameServices) {
if(nameService.supportedSchemes().contains(nameServiceUri.getScheme())) {
nameService.connect(nameServiceUri);
return nameService;
}
}
return null;
}
/**
* 服务端启动RPC框架,监听接口,开始提供远程服务。
* @return 服务实例,用于程序停止的时候安全关闭服务。
*/
Closeable startServer() throws Exception;
}
|
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package com.cloud.network.router;
import java.net.URI;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.inject.Inject;
import org.apache.cloudstack.framework.config.dao.ConfigurationDao;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import com.cloud.agent.api.SetupGuestNetworkCommand;
import com.cloud.agent.api.routing.CreateIpAliasCommand;
import com.cloud.agent.api.routing.DeleteIpAliasCommand;
import com.cloud.agent.api.routing.DhcpEntryCommand;
import com.cloud.agent.api.routing.DnsMasqConfigCommand;
import com.cloud.agent.api.routing.IpAliasTO;
import com.cloud.agent.api.routing.IpAssocCommand;
import com.cloud.agent.api.routing.IpAssocVpcCommand;
import com.cloud.agent.api.routing.LoadBalancerConfigCommand;
import com.cloud.agent.api.routing.NetworkElementCommand;
import com.cloud.agent.api.routing.RemoteAccessVpnCfgCommand;
import com.cloud.agent.api.routing.SavePasswordCommand;
import com.cloud.agent.api.routing.SetFirewallRulesCommand;
import com.cloud.agent.api.routing.SetNetworkACLCommand;
import com.cloud.agent.api.routing.SetPortForwardingRulesCommand;
import com.cloud.agent.api.routing.SetPortForwardingRulesVpcCommand;
import com.cloud.agent.api.routing.SetSourceNatCommand;
import com.cloud.agent.api.routing.SetStaticNatRulesCommand;
import com.cloud.agent.api.routing.SetStaticRouteCommand;
import com.cloud.agent.api.routing.Site2SiteVpnCfgCommand;
import com.cloud.agent.api.routing.VmDataCommand;
import com.cloud.agent.api.routing.VpnUsersCfgCommand;
import com.cloud.agent.api.to.DhcpTO;
import com.cloud.agent.api.to.FirewallRuleTO;
import com.cloud.agent.api.to.IpAddressTO;
import com.cloud.agent.api.to.LoadBalancerTO;
import com.cloud.agent.api.to.NetworkACLTO;
import com.cloud.agent.api.to.PortForwardingRuleTO;
import com.cloud.agent.api.to.StaticNatRuleTO;
import com.cloud.agent.manager.Commands;
import com.cloud.configuration.Config;
import com.cloud.dc.DataCenter;
import com.cloud.dc.DataCenter.NetworkType;
import com.cloud.dc.DataCenterVO;
import com.cloud.dc.dao.DataCenterDao;
import com.cloud.dc.dao.VlanDao;
import com.cloud.network.IpAddress;
import com.cloud.network.Network;
import com.cloud.network.Network.Provider;
import com.cloud.network.Network.Service;
import com.cloud.network.NetworkModel;
import com.cloud.network.Networks.BroadcastDomainType;
import com.cloud.network.Networks.TrafficType;
import com.cloud.network.PublicIpAddress;
import com.cloud.network.RemoteAccessVpn;
import com.cloud.network.Site2SiteVpnConnection;
import com.cloud.network.VpnUser;
import com.cloud.network.VpnUserVO;
import com.cloud.network.dao.FirewallRulesDao;
import com.cloud.network.dao.IPAddressDao;
import com.cloud.network.dao.NetworkDao;
import com.cloud.network.dao.NetworkVO;
import com.cloud.network.dao.Site2SiteCustomerGatewayDao;
import com.cloud.network.dao.Site2SiteCustomerGatewayVO;
import com.cloud.network.dao.Site2SiteVpnGatewayDao;
import com.cloud.network.dao.Site2SiteVpnGatewayVO;
import com.cloud.network.dao.VpnUserDao;
import com.cloud.network.lb.LoadBalancingRule;
import com.cloud.network.lb.LoadBalancingRule.LbDestination;
import com.cloud.network.lb.LoadBalancingRule.LbStickinessPolicy;
import com.cloud.network.rules.FirewallRule;
import com.cloud.network.rules.FirewallRule.Purpose;
import com.cloud.network.rules.FirewallRuleVO;
import com.cloud.network.rules.PortForwardingRule;
import com.cloud.network.rules.StaticNat;
import com.cloud.network.rules.StaticNatRule;
import com.cloud.network.vpc.NetworkACLItem;
import com.cloud.network.vpc.PrivateIpAddress;
import com.cloud.network.vpc.StaticRouteProfile;
import com.cloud.network.vpc.Vpc;
import com.cloud.network.vpc.VpcGateway;
import com.cloud.network.vpc.dao.VpcDao;
import com.cloud.offering.NetworkOffering;
import com.cloud.offerings.NetworkOfferingVO;
import com.cloud.offerings.dao.NetworkOfferingDao;
import com.cloud.service.dao.ServiceOfferingDao;
import com.cloud.storage.GuestOSVO;
import com.cloud.storage.dao.GuestOSDao;
import com.cloud.user.Account;
import com.cloud.uservm.UserVm;
import com.cloud.utils.Pair;
import com.cloud.utils.StringUtils;
import com.cloud.utils.db.EntityManager;
import com.cloud.utils.net.NetUtils;
import com.cloud.vm.DomainRouterVO;
import com.cloud.vm.Nic;
import com.cloud.vm.NicIpAlias;
import com.cloud.vm.NicProfile;
import com.cloud.vm.NicVO;
import com.cloud.vm.UserVmVO;
import com.cloud.vm.VirtualMachine;
import com.cloud.vm.VirtualMachine.State;
import com.cloud.vm.VirtualMachineManager;
import com.cloud.vm.VirtualMachineProfile;
import com.cloud.vm.dao.DomainRouterDao;
import com.cloud.vm.dao.NicDao;
import com.cloud.vm.dao.NicIpAliasDao;
import com.cloud.vm.dao.NicIpAliasVO;
import com.cloud.vm.dao.UserVmDao;
public class CommandSetupHelper {
private static final Logger s_logger = Logger.getLogger(CommandSetupHelper.class);
@Inject
private EntityManager _entityMgr;
@Inject
private NicDao _nicDao;
@Inject
private NetworkDao _networkDao;
@Inject
private DomainRouterDao _routerDao;
@Inject
private NetworkModel _networkModel;
@Inject
private VirtualMachineManager _itMgr;
@Inject
private DataCenterDao _dcDao;
@Inject
private NicIpAliasDao _nicIpAliasDao;
@Inject
private FirewallRulesDao _rulesDao;
@Inject
private NetworkOfferingDao _networkOfferingDao;
@Inject
private ConfigurationDao _configDao;
@Inject
private ServiceOfferingDao _serviceOfferingDao;
@Inject
private UserVmDao _userVmDao;
@Inject
private VpnUserDao _vpnUsersDao;
@Inject
private Site2SiteCustomerGatewayDao _s2sCustomerGatewayDao;
@Inject
private Site2SiteVpnGatewayDao _s2sVpnGatewayDao;
@Inject
private VpcDao _vpcDao;
@Inject
private VlanDao _vlanDao;
@Inject
private IPAddressDao _ipAddressDao;
@Inject
private GuestOSDao _guestOSDao;
@Inject
private RouterControlHelper _routerControlHelper;
@Autowired
@Qualifier("networkHelper")
protected NetworkHelper _networkHelper;
private final String _dnsBasicZoneUpdates = "all";
public void createVmDataCommand(final VirtualRouter router, final UserVm vm, final NicVO nic, final String publicKey, final Commands cmds) {
final String serviceOffering = _serviceOfferingDao.findByIdIncludingRemoved(vm.getId(), vm.getServiceOfferingId()).getDisplayText();
final String zoneName = _dcDao.findById(router.getDataCenterId()).getName();
cmds.addCommand(
"vmdata",
generateVmDataCommand(router, nic.getIPv4Address(), vm.getUserData(), serviceOffering, zoneName, nic.getIPv4Address(), vm.getHostName(), vm.getInstanceName(),
vm.getId(), vm.getUuid(), publicKey, nic.getNetworkId()));
}
public void createApplyVpnUsersCommand(final List<? extends VpnUser> users, final VirtualRouter router, final Commands cmds) {
final List<VpnUser> addUsers = new ArrayList<VpnUser>();
final List<VpnUser> removeUsers = new ArrayList<VpnUser>();
for (final VpnUser user : users) {
if (user.getState() == VpnUser.State.Add || user.getState() == VpnUser.State.Active) {
addUsers.add(user);
} else if (user.getState() == VpnUser.State.Revoke) {
removeUsers.add(user);
}
}
final VpnUsersCfgCommand cmd = new VpnUsersCfgCommand(addUsers, removeUsers);
cmd.setAccessDetail(NetworkElementCommand.ACCOUNT_ID, String.valueOf(router.getAccountId()));
cmd.setAccessDetail(NetworkElementCommand.ROUTER_IP, _routerControlHelper.getRouterControlIp(router.getId()));
cmd.setAccessDetail(NetworkElementCommand.ROUTER_NAME, router.getInstanceName());
final DataCenterVO dcVo = _dcDao.findById(router.getDataCenterId());
cmd.setAccessDetail(NetworkElementCommand.ZONE_NETWORK_TYPE, dcVo.getNetworkType().toString());
cmds.addCommand("users", cmd);
}
public void createDhcpEntryCommand(final VirtualRouter router, final UserVm vm, final NicVO nic, final Commands cmds) {
final DhcpEntryCommand dhcpCommand = new DhcpEntryCommand(nic.getMacAddress(), nic.getIPv4Address(), vm.getHostName(), nic.getIPv6Address(),
_networkModel.getExecuteInSeqNtwkElmtCmd());
String gatewayIp = nic.getIPv4Gateway();
if (!nic.isDefaultNic()) {
final GuestOSVO guestOS = _guestOSDao.findById(vm.getGuestOSId());
if (guestOS == null || !guestOS.getDisplayName().toLowerCase().contains("windows")) {
gatewayIp = "0.0.0.0";
}
}
final DataCenterVO dcVo = _dcDao.findById(router.getDataCenterId());
dhcpCommand.setDefaultRouter(gatewayIp);
dhcpCommand.setIp6Gateway(nic.getIPv6Gateway());
String ipaddress = null;
final NicVO domrDefaultNic = findDefaultDnsIp(vm.getId());
if (domrDefaultNic != null) {
ipaddress = domrDefaultNic.getIPv4Address();
}
dhcpCommand.setDefaultDns(ipaddress);
dhcpCommand.setDuid(NetUtils.getDuidLL(nic.getMacAddress()));
dhcpCommand.setDefault(nic.isDefaultNic());
dhcpCommand.setAccessDetail(NetworkElementCommand.ROUTER_IP, _routerControlHelper.getRouterControlIp(router.getId()));
dhcpCommand.setAccessDetail(NetworkElementCommand.ROUTER_NAME, router.getInstanceName());
dhcpCommand.setAccessDetail(NetworkElementCommand.ROUTER_GUEST_IP, _routerControlHelper.getRouterIpInNetwork(nic.getNetworkId(), router.getId()));
dhcpCommand.setAccessDetail(NetworkElementCommand.ZONE_NETWORK_TYPE, dcVo.getNetworkType().toString());
cmds.addCommand("dhcp", dhcpCommand);
}
public void createIpAlias(final VirtualRouter router, final List<IpAliasTO> ipAliasTOs, final Long networkid, final Commands cmds) {
final String routerip = _routerControlHelper.getRouterIpInNetwork(networkid, router.getId());
final DataCenterVO dcVo = _dcDao.findById(router.getDataCenterId());
final CreateIpAliasCommand ipaliasCmd = new CreateIpAliasCommand(routerip, ipAliasTOs);
ipaliasCmd.setAccessDetail(NetworkElementCommand.ROUTER_IP, _routerControlHelper.getRouterControlIp(router.getId()));
ipaliasCmd.setAccessDetail(NetworkElementCommand.ROUTER_NAME, router.getInstanceName());
ipaliasCmd.setAccessDetail(NetworkElementCommand.ROUTER_GUEST_IP, routerip);
ipaliasCmd.setAccessDetail(NetworkElementCommand.ZONE_NETWORK_TYPE, dcVo.getNetworkType().toString());
cmds.addCommand("ipalias", ipaliasCmd);
}
public void configDnsMasq(final VirtualRouter router, final Network network, final Commands cmds) {
final DataCenterVO dcVo = _dcDao.findById(router.getDataCenterId());
final List<NicIpAliasVO> ipAliasVOList = _nicIpAliasDao.listByNetworkIdAndState(network.getId(), NicIpAlias.state.active);
final List<DhcpTO> ipList = new ArrayList<DhcpTO>();
final NicVO router_guest_nic = _nicDao.findByNtwkIdAndInstanceId(network.getId(), router.getId());
final String cidr = NetUtils.getCidrFromGatewayAndNetmask(router_guest_nic.getIPv4Gateway(), router_guest_nic.getIPv4Netmask());
final String[] cidrPair = cidr.split("\\/");
final String cidrAddress = cidrPair[0];
final long cidrSize = Long.parseLong(cidrPair[1]);
final String startIpOfSubnet = NetUtils.getIpRangeStartIpFromCidr(cidrAddress, cidrSize);
ipList.add(new DhcpTO(router_guest_nic.getIPv4Address(), router_guest_nic.getIPv4Gateway(), router_guest_nic.getIPv4Netmask(), startIpOfSubnet));
for (final NicIpAliasVO ipAliasVO : ipAliasVOList) {
final DhcpTO DhcpTO = new DhcpTO(ipAliasVO.getIp4Address(), ipAliasVO.getGateway(), ipAliasVO.getNetmask(), ipAliasVO.getStartIpOfSubnet());
if (s_logger.isTraceEnabled()) {
s_logger.trace("configDnsMasq : adding ip {" + DhcpTO.getGateway() + ", " + DhcpTO.getNetmask() + ", " + DhcpTO.getRouterIp() + ", " + DhcpTO.getStartIpOfSubnet()
+ "}");
}
ipList.add(DhcpTO);
ipAliasVO.setVmId(router.getId());
}
_dcDao.findById(router.getDataCenterId());
final DnsMasqConfigCommand dnsMasqConfigCmd = new DnsMasqConfigCommand(ipList);
dnsMasqConfigCmd.setAccessDetail(NetworkElementCommand.ROUTER_IP, _routerControlHelper.getRouterControlIp(router.getId()));
dnsMasqConfigCmd.setAccessDetail(NetworkElementCommand.ROUTER_NAME, router.getInstanceName());
dnsMasqConfigCmd.setAccessDetail(NetworkElementCommand.ROUTER_GUEST_IP, _routerControlHelper.getRouterIpInNetwork(network.getId(), router.getId()));
dnsMasqConfigCmd.setAccessDetail(NetworkElementCommand.ZONE_NETWORK_TYPE, dcVo.getNetworkType().toString());
cmds.addCommand("dnsMasqConfig", dnsMasqConfigCmd);
}
public void createApplyLoadBalancingRulesCommands(final List<LoadBalancingRule> rules, final VirtualRouter router, final Commands cmds, final long guestNetworkId) {
final LoadBalancerTO[] lbs = new LoadBalancerTO[rules.size()];
int i = 0;
// We don't support VR to be inline currently
final boolean inline = false;
for (final LoadBalancingRule rule : rules) {
final boolean revoked = rule.getState().equals(FirewallRule.State.Revoke);
final String protocol = rule.getProtocol();
final String algorithm = rule.getAlgorithm();
final String uuid = rule.getUuid();
final String srcIp = rule.getSourceIp().addr();
final int srcPort = rule.getSourcePortStart();
final List<LbDestination> destinations = rule.getDestinations();
final List<LbStickinessPolicy> stickinessPolicies = rule.getStickinessPolicies();
final LoadBalancerTO lb = new LoadBalancerTO(uuid, srcIp, srcPort, protocol, algorithm, revoked, false, inline, destinations, stickinessPolicies);
lbs[i++] = lb;
}
String routerPublicIp = null;
if (router instanceof DomainRouterVO) {
final DomainRouterVO domr = _routerDao.findById(router.getId());
routerPublicIp = domr.getPublicIpAddress();
if (routerPublicIp == null) {
routerPublicIp = router.getPublicIpAddress();
}
}
final Network guestNetwork = _networkModel.getNetwork(guestNetworkId);
final Nic nic = _nicDao.findByNtwkIdAndInstanceId(guestNetwork.getId(), router.getId());
final NicProfile nicProfile = new NicProfile(nic, guestNetwork, nic.getBroadcastUri(), nic.getIsolationUri(), _networkModel.getNetworkRate(guestNetwork.getId(),
router.getId()), _networkModel.isSecurityGroupSupportedInNetwork(guestNetwork), _networkModel.getNetworkTag(router.getHypervisorType(), guestNetwork));
final NetworkOffering offering = _networkOfferingDao.findById(guestNetwork.getNetworkOfferingId());
String maxconn = null;
if (offering.getConcurrentConnections() == null) {
maxconn = _configDao.getValue(Config.NetworkLBHaproxyMaxConn.key());
} else {
maxconn = offering.getConcurrentConnections().toString();
}
final LoadBalancerConfigCommand cmd = new LoadBalancerConfigCommand(lbs, routerPublicIp, _routerControlHelper.getRouterIpInNetwork(guestNetworkId, router.getId()),
router.getPrivateIpAddress(), _itMgr.toNicTO(nicProfile, router.getHypervisorType()), router.getVpcId(), maxconn, offering.isKeepAliveEnabled());
cmd.lbStatsVisibility = _configDao.getValue(Config.NetworkLBHaproxyStatsVisbility.key());
cmd.lbStatsUri = _configDao.getValue(Config.NetworkLBHaproxyStatsUri.key());
cmd.lbStatsAuth = _configDao.getValue(Config.NetworkLBHaproxyStatsAuth.key());
cmd.lbStatsPort = _configDao.getValue(Config.NetworkLBHaproxyStatsPort.key());
cmd.setAccessDetail(NetworkElementCommand.ROUTER_IP, _routerControlHelper.getRouterControlIp(router.getId()));
cmd.setAccessDetail(NetworkElementCommand.ROUTER_GUEST_IP, _routerControlHelper.getRouterIpInNetwork(guestNetworkId, router.getId()));
cmd.setAccessDetail(NetworkElementCommand.ROUTER_NAME, router.getInstanceName());
final DataCenterVO dcVo = _dcDao.findById(router.getDataCenterId());
cmd.setAccessDetail(NetworkElementCommand.ZONE_NETWORK_TYPE, dcVo.getNetworkType().toString());
cmds.addCommand(cmd);
}
public void createApplyPortForwardingRulesCommands(final List<? extends PortForwardingRule> rules, final VirtualRouter router, final Commands cmds, final long guestNetworkId) {
final List<PortForwardingRuleTO> rulesTO = new ArrayList<PortForwardingRuleTO>();
if (rules != null) {
for (final PortForwardingRule rule : rules) {
final IpAddress sourceIp = _networkModel.getIp(rule.getSourceIpAddressId());
final PortForwardingRuleTO ruleTO = new PortForwardingRuleTO(rule, null, sourceIp.getAddress().addr());
rulesTO.add(ruleTO);
}
}
SetPortForwardingRulesCommand cmd = null;
if (router.getVpcId() != null) {
cmd = new SetPortForwardingRulesVpcCommand(rulesTO);
} else {
cmd = new SetPortForwardingRulesCommand(rulesTO);
}
cmd.setAccessDetail(NetworkElementCommand.ROUTER_IP, _routerControlHelper.getRouterControlIp(router.getId()));
cmd.setAccessDetail(NetworkElementCommand.ROUTER_GUEST_IP, _routerControlHelper.getRouterIpInNetwork(guestNetworkId, router.getId()));
cmd.setAccessDetail(NetworkElementCommand.ROUTER_NAME, router.getInstanceName());
final DataCenterVO dcVo = _dcDao.findById(router.getDataCenterId());
cmd.setAccessDetail(NetworkElementCommand.ZONE_NETWORK_TYPE, dcVo.getNetworkType().toString());
cmds.addCommand(cmd);
}
public void createApplyStaticNatRulesCommands(final List<? extends StaticNatRule> rules, final VirtualRouter router, final Commands cmds, final long guestNetworkId) {
final List<StaticNatRuleTO> rulesTO = new ArrayList<StaticNatRuleTO>();
if (rules != null) {
for (final StaticNatRule rule : rules) {
final IpAddress sourceIp = _networkModel.getIp(rule.getSourceIpAddressId());
final StaticNatRuleTO ruleTO = new StaticNatRuleTO(rule, null, sourceIp.getAddress().addr(), rule.getDestIpAddress());
rulesTO.add(ruleTO);
}
}
final SetStaticNatRulesCommand cmd = new SetStaticNatRulesCommand(rulesTO, router.getVpcId());
cmd.setAccessDetail(NetworkElementCommand.ROUTER_IP, _routerControlHelper.getRouterControlIp(router.getId()));
cmd.setAccessDetail(NetworkElementCommand.ROUTER_GUEST_IP, _routerControlHelper.getRouterIpInNetwork(guestNetworkId, router.getId()));
cmd.setAccessDetail(NetworkElementCommand.ROUTER_NAME, router.getInstanceName());
final DataCenterVO dcVo = _dcDao.findById(router.getDataCenterId());
cmd.setAccessDetail(NetworkElementCommand.ZONE_NETWORK_TYPE, dcVo.getNetworkType().toString());
cmds.addCommand(cmd);
}
public void createApplyFirewallRulesCommands(final List<? extends FirewallRule> rules, final VirtualRouter router, final Commands cmds, final long guestNetworkId) {
final List<FirewallRuleTO> rulesTO = new ArrayList<FirewallRuleTO>();
String systemRule = null;
Boolean defaultEgressPolicy = false;
if (rules != null) {
if (rules.size() > 0) {
if (rules.get(0).getTrafficType() == FirewallRule.TrafficType.Egress && rules.get(0).getType() == FirewallRule.FirewallRuleType.System) {
systemRule = String.valueOf(FirewallRule.FirewallRuleType.System);
}
}
for (final FirewallRule rule : rules) {
_rulesDao.loadSourceCidrs((FirewallRuleVO) rule);
final FirewallRule.TrafficType traffictype = rule.getTrafficType();
if (traffictype == FirewallRule.TrafficType.Ingress) {
final IpAddress sourceIp = _networkModel.getIp(rule.getSourceIpAddressId());
final FirewallRuleTO ruleTO = new FirewallRuleTO(rule, null, sourceIp.getAddress().addr(), Purpose.Firewall, traffictype);
rulesTO.add(ruleTO);
} else if (rule.getTrafficType() == FirewallRule.TrafficType.Egress) {
final NetworkVO network = _networkDao.findById(guestNetworkId);
final NetworkOfferingVO offering = _networkOfferingDao.findById(network.getNetworkOfferingId());
defaultEgressPolicy = offering.getEgressDefaultPolicy();
assert rule.getSourceIpAddressId() == null : "ipAddressId should be null for egress firewall rule. ";
final FirewallRuleTO ruleTO = new FirewallRuleTO(rule, null, "", Purpose.Firewall, traffictype, defaultEgressPolicy);
rulesTO.add(ruleTO);
}
}
}
final SetFirewallRulesCommand cmd = new SetFirewallRulesCommand(rulesTO);
cmd.setAccessDetail(NetworkElementCommand.ROUTER_IP, _routerControlHelper.getRouterControlIp(router.getId()));
cmd.setAccessDetail(NetworkElementCommand.ROUTER_GUEST_IP, _routerControlHelper.getRouterIpInNetwork(guestNetworkId, router.getId()));
cmd.setAccessDetail(NetworkElementCommand.ROUTER_NAME, router.getInstanceName());
final DataCenterVO dcVo = _dcDao.findById(router.getDataCenterId());
cmd.setAccessDetail(NetworkElementCommand.ZONE_NETWORK_TYPE, dcVo.getNetworkType().toString());
if (systemRule != null) {
cmd.setAccessDetail(NetworkElementCommand.FIREWALL_EGRESS_DEFAULT, systemRule);
} else {
cmd.setAccessDetail(NetworkElementCommand.FIREWALL_EGRESS_DEFAULT, String.valueOf(defaultEgressPolicy));
}
cmds.addCommand(cmd);
}
public void createFirewallRulesCommands(final List<? extends FirewallRule> rules, final VirtualRouter router, final Commands cmds, final long guestNetworkId) {
final List<FirewallRuleTO> rulesTO = new ArrayList<FirewallRuleTO>();
String systemRule = null;
Boolean defaultEgressPolicy = false;
if (rules != null) {
if (rules.size() > 0) {
if (rules.get(0).getTrafficType() == FirewallRule.TrafficType.Egress && rules.get(0).getType() == FirewallRule.FirewallRuleType.System) {
systemRule = String.valueOf(FirewallRule.FirewallRuleType.System);
}
}
for (final FirewallRule rule : rules) {
_rulesDao.loadSourceCidrs((FirewallRuleVO) rule);
final FirewallRule.TrafficType traffictype = rule.getTrafficType();
if (traffictype == FirewallRule.TrafficType.Ingress) {
final IpAddress sourceIp = _networkModel.getIp(rule.getSourceIpAddressId());
final FirewallRuleTO ruleTO = new FirewallRuleTO(rule, null, sourceIp.getAddress().addr(), Purpose.Firewall, traffictype);
rulesTO.add(ruleTO);
} else if (rule.getTrafficType() == FirewallRule.TrafficType.Egress) {
final NetworkVO network = _networkDao.findById(guestNetworkId);
final NetworkOfferingVO offering = _networkOfferingDao.findById(network.getNetworkOfferingId());
defaultEgressPolicy = offering.getEgressDefaultPolicy();
assert rule.getSourceIpAddressId() == null : "ipAddressId should be null for egress firewall rule. ";
final FirewallRuleTO ruleTO = new FirewallRuleTO(rule, null, "", Purpose.Firewall, traffictype, defaultEgressPolicy);
rulesTO.add(ruleTO);
}
}
}
final SetFirewallRulesCommand cmd = new SetFirewallRulesCommand(rulesTO);
cmd.setAccessDetail(NetworkElementCommand.ROUTER_IP, _routerControlHelper.getRouterControlIp(router.getId()));
cmd.setAccessDetail(NetworkElementCommand.ROUTER_GUEST_IP, _routerControlHelper.getRouterIpInNetwork(guestNetworkId, router.getId()));
cmd.setAccessDetail(NetworkElementCommand.ROUTER_NAME, router.getInstanceName());
final DataCenterVO dcVo = _dcDao.findById(router.getDataCenterId());
cmd.setAccessDetail(NetworkElementCommand.ZONE_NETWORK_TYPE, dcVo.getNetworkType().toString());
if (systemRule != null) {
cmd.setAccessDetail(NetworkElementCommand.FIREWALL_EGRESS_DEFAULT, systemRule);
} else {
cmd.setAccessDetail(NetworkElementCommand.FIREWALL_EGRESS_DEFAULT, String.valueOf(defaultEgressPolicy));
}
cmds.addCommand(cmd);
}
public void createAssociateIPCommands(final VirtualRouter router, final List<? extends PublicIpAddress> ips, final Commands cmds, final long vmId) {
final String ipAssocCommand = "IPAssocCommand";
createRedundantAssociateIPCommands(router, ips, cmds, ipAssocCommand, vmId);
}
public void createNetworkACLsCommands(final List<? extends NetworkACLItem> rules, final VirtualRouter router, final Commands cmds, final long guestNetworkId,
final boolean privateGateway) {
final List<NetworkACLTO> rulesTO = new ArrayList<NetworkACLTO>();
String guestVlan = null;
final Network guestNtwk = _networkDao.findById(guestNetworkId);
final URI uri = guestNtwk.getBroadcastUri();
if (uri != null) {
guestVlan = BroadcastDomainType.getValue(uri);
}
if (rules != null) {
for (final NetworkACLItem rule : rules) {
final NetworkACLTO ruleTO = new NetworkACLTO(rule, guestVlan, rule.getTrafficType());
rulesTO.add(ruleTO);
}
}
final SetNetworkACLCommand cmd = new SetNetworkACLCommand(rulesTO, _networkHelper.getNicTO(router, guestNetworkId, null));
cmd.setAccessDetail(NetworkElementCommand.ROUTER_IP, _routerControlHelper.getRouterControlIp(router.getId()));
cmd.setAccessDetail(NetworkElementCommand.ROUTER_GUEST_IP, _routerControlHelper.getRouterIpInNetwork(guestNetworkId, router.getId()));
cmd.setAccessDetail(NetworkElementCommand.GUEST_VLAN_TAG, guestVlan);
cmd.setAccessDetail(NetworkElementCommand.ROUTER_NAME, router.getInstanceName());
final DataCenterVO dcVo = _dcDao.findById(router.getDataCenterId());
cmd.setAccessDetail(NetworkElementCommand.ZONE_NETWORK_TYPE, dcVo.getNetworkType().toString());
if (privateGateway) {
cmd.setAccessDetail(NetworkElementCommand.VPC_PRIVATE_GATEWAY, String.valueOf(VpcGateway.Type.Private));
}
cmds.addCommand(cmd);
}
public void createPasswordCommand(final VirtualRouter router, final VirtualMachineProfile profile, final NicVO nic, final Commands cmds) {
final String password = (String) profile.getParameter(VirtualMachineProfile.Param.VmPassword);
final DataCenterVO dcVo = _dcDao.findById(router.getDataCenterId());
// password should be set only on default network element
if (password != null && nic.isDefaultNic()) {
final SavePasswordCommand cmd = new SavePasswordCommand(password, nic.getIPv4Address(), profile.getVirtualMachine().getHostName(),
_networkModel.getExecuteInSeqNtwkElmtCmd());
cmd.setAccessDetail(NetworkElementCommand.ROUTER_IP, _routerControlHelper.getRouterControlIp(router.getId()));
cmd.setAccessDetail(NetworkElementCommand.ROUTER_GUEST_IP, _routerControlHelper.getRouterIpInNetwork(nic.getNetworkId(), router.getId()));
cmd.setAccessDetail(NetworkElementCommand.ROUTER_NAME, router.getInstanceName());
cmd.setAccessDetail(NetworkElementCommand.ZONE_NETWORK_TYPE, dcVo.getNetworkType().toString());
cmds.addCommand("password", cmd);
}
}
public void createApplyStaticNatCommands(final List<? extends StaticNat> rules, final VirtualRouter router, final Commands cmds, final long guestNetworkId) {
final List<StaticNatRuleTO> rulesTO = new ArrayList<StaticNatRuleTO>();
if (rules != null) {
for (final StaticNat rule : rules) {
final IpAddress sourceIp = _networkModel.getIp(rule.getSourceIpAddressId());
final StaticNatRuleTO ruleTO = new StaticNatRuleTO(0, sourceIp.getAddress().addr(), null, null, rule.getDestIpAddress(), null, null, null, rule.isForRevoke(),
false);
rulesTO.add(ruleTO);
}
}
final SetStaticNatRulesCommand cmd = new SetStaticNatRulesCommand(rulesTO, router.getVpcId());
cmd.setAccessDetail(NetworkElementCommand.ROUTER_IP, _routerControlHelper.getRouterControlIp(router.getId()));
cmd.setAccessDetail(NetworkElementCommand.ROUTER_GUEST_IP, _routerControlHelper.getRouterIpInNetwork(guestNetworkId, router.getId()));
cmd.setAccessDetail(NetworkElementCommand.ROUTER_NAME, router.getInstanceName());
final DataCenterVO dcVo = _dcDao.findById(router.getDataCenterId());
cmd.setAccessDetail(NetworkElementCommand.ZONE_NETWORK_TYPE, dcVo.getNetworkType().toString());
cmds.addCommand(cmd);
}
public void createStaticRouteCommands(final List<StaticRouteProfile> staticRoutes, final VirtualRouter router, final Commands cmds) {
final SetStaticRouteCommand cmd = new SetStaticRouteCommand(staticRoutes);
cmd.setAccessDetail(NetworkElementCommand.ROUTER_IP, _routerControlHelper.getRouterControlIp(router.getId()));
cmd.setAccessDetail(NetworkElementCommand.ROUTER_NAME, router.getInstanceName());
final DataCenterVO dcVo = _dcDao.findById(router.getDataCenterId());
cmd.setAccessDetail(NetworkElementCommand.ZONE_NETWORK_TYPE, dcVo.getNetworkType().toString());
cmds.addCommand(cmd);
}
public void createApplyVpnCommands(final boolean isCreate, final RemoteAccessVpn vpn, final VirtualRouter router, final Commands cmds) {
final List<VpnUserVO> vpnUsers = _vpnUsersDao.listByAccount(vpn.getAccountId());
createApplyVpnUsersCommand(vpnUsers, router, cmds);
final IpAddress ip = _networkModel.getIp(vpn.getServerAddressId());
// This block is needed due to the line 206 of the
// RemoteAccessVpnManagenerImpl:
// TODO: assumes one virtual network / domr per account per zone
final String cidr;
final Network network = _networkDao.findById(vpn.getNetworkId());
if (network == null) {
final Vpc vpc = _vpcDao.findById(vpn.getVpcId());
cidr = vpc.getCidr();
} else {
cidr = network.getCidr();
}
final RemoteAccessVpnCfgCommand startVpnCmd = new RemoteAccessVpnCfgCommand(isCreate, ip.getAddress().addr(), vpn.getLocalIp(), vpn.getIpRange(),
vpn.getIpsecPresharedKey(), vpn.getVpcId() != null);
startVpnCmd.setLocalCidr(cidr);
startVpnCmd.setAccessDetail(NetworkElementCommand.ROUTER_IP, _routerControlHelper.getRouterControlIp(router.getId()));
startVpnCmd.setAccessDetail(NetworkElementCommand.ROUTER_NAME, router.getInstanceName());
final DataCenterVO dcVo = _dcDao.findById(router.getDataCenterId());
startVpnCmd.setAccessDetail(NetworkElementCommand.ZONE_NETWORK_TYPE, dcVo.getNetworkType().toString());
cmds.addCommand("startVpn", startVpnCmd);
}
public void createVmDataCommandForVMs(final DomainRouterVO router, final Commands cmds, final long guestNetworkId) {
final List<UserVmVO> vms = _userVmDao.listByNetworkIdAndStates(guestNetworkId, State.Running, State.Migrating, State.Stopping);
final DataCenterVO dc = _dcDao.findById(router.getDataCenterId());
for (final UserVmVO vm : vms) {
boolean createVmData = true;
if (dc.getNetworkType() == NetworkType.Basic && router.getPodIdToDeployIn().longValue() != vm.getPodIdToDeployIn().longValue()) {
createVmData = false;
}
if (createVmData) {
final NicVO nic = _nicDao.findByNtwkIdAndInstanceId(guestNetworkId, vm.getId());
if (nic != null) {
s_logger.debug("Creating user data entry for vm " + vm + " on domR " + router);
createVmDataCommand(router, vm, nic, null, cmds);
}
}
}
}
public void createDhcpEntryCommandsForVMs(final DomainRouterVO router, final Commands cmds, final long guestNetworkId) {
final List<UserVmVO> vms = _userVmDao.listByNetworkIdAndStates(guestNetworkId, State.Running, State.Migrating, State.Stopping);
final DataCenterVO dc = _dcDao.findById(router.getDataCenterId());
for (final UserVmVO vm : vms) {
boolean createDhcp = true;
if (dc.getNetworkType() == NetworkType.Basic && router.getPodIdToDeployIn().longValue() != vm.getPodIdToDeployIn().longValue()
&& _dnsBasicZoneUpdates.equalsIgnoreCase("pod")) {
createDhcp = false;
}
if (createDhcp) {
final NicVO nic = _nicDao.findByNtwkIdAndInstanceId(guestNetworkId, vm.getId());
if (nic != null) {
s_logger.debug("Creating dhcp entry for vm " + vm + " on domR " + router + ".");
createDhcpEntryCommand(router, vm, nic, cmds);
}
}
}
}
public void createDeleteIpAliasCommand(final DomainRouterVO router, final List<IpAliasTO> deleteIpAliasTOs, final List<IpAliasTO> createIpAliasTos, final long networkId,
final Commands cmds) {
final String routerip = _routerControlHelper.getRouterIpInNetwork(networkId, router.getId());
final DataCenterVO dcVo = _dcDao.findById(router.getDataCenterId());
final DeleteIpAliasCommand deleteIpaliasCmd = new DeleteIpAliasCommand(routerip, deleteIpAliasTOs, createIpAliasTos);
deleteIpaliasCmd.setAccessDetail(NetworkElementCommand.ROUTER_IP, _routerControlHelper.getRouterControlIp(router.getId()));
deleteIpaliasCmd.setAccessDetail(NetworkElementCommand.ROUTER_NAME, router.getInstanceName());
deleteIpaliasCmd.setAccessDetail(NetworkElementCommand.ROUTER_GUEST_IP, routerip);
deleteIpaliasCmd.setAccessDetail(NetworkElementCommand.ZONE_NETWORK_TYPE, dcVo.getNetworkType().toString());
cmds.addCommand("deleteIpalias", deleteIpaliasCmd);
}
public void createVpcAssociatePublicIPCommands(final VirtualRouter router, final List<? extends PublicIpAddress> ips, final Commands cmds,
final Map<String, String> vlanMacAddress) {
final String ipAssocCommand = "IPAssocVpcCommand";
if (router.getIsRedundantRouter()) {
createRedundantAssociateIPCommands(router, ips, cmds, ipAssocCommand, 0);
return;
}
Pair<IpAddressTO, Long> sourceNatIpAdd = null;
Boolean addSourceNat = null;
// Ensure that in multiple vlans case we first send all ip addresses of
// vlan1, then all ip addresses of vlan2, etc..
final Map<String, ArrayList<PublicIpAddress>> vlanIpMap = new HashMap<String, ArrayList<PublicIpAddress>>();
for (final PublicIpAddress ipAddress : ips) {
final String vlanTag = ipAddress.getVlanTag();
ArrayList<PublicIpAddress> ipList = vlanIpMap.get(vlanTag);
if (ipList == null) {
ipList = new ArrayList<PublicIpAddress>();
}
// VR doesn't support release for sourceNat IP address; so reset the
// state
if (ipAddress.isSourceNat() && ipAddress.getState() == IpAddress.State.Releasing) {
ipAddress.setState(IpAddress.State.Allocated);
}
ipList.add(ipAddress);
vlanIpMap.put(vlanTag, ipList);
}
for (final Map.Entry<String, ArrayList<PublicIpAddress>> vlanAndIp : vlanIpMap.entrySet()) {
final List<PublicIpAddress> ipAddrList = vlanAndIp.getValue();
// Get network rate - required for IpAssoc
final Integer networkRate = _networkModel.getNetworkRate(ipAddrList.get(0).getNetworkId(), router.getId());
final Network network = _networkModel.getNetwork(ipAddrList.get(0).getNetworkId());
final IpAddressTO[] ipsToSend = new IpAddressTO[ipAddrList.size()];
int i = 0;
for (final PublicIpAddress ipAddr : ipAddrList) {
final boolean add = ipAddr.getState() == IpAddress.State.Releasing ? false : true;
final String macAddress = vlanMacAddress.get(BroadcastDomainType.getValue(BroadcastDomainType.fromString(ipAddr.getVlanTag())));
final IpAddressTO ip = new IpAddressTO(ipAddr.getAccountId(), ipAddr.getAddress().addr(), add, false, ipAddr.isSourceNat(), BroadcastDomainType.fromString(ipAddr.getVlanTag()).toString(), ipAddr.getGateway(),
ipAddr.getNetmask(), macAddress, networkRate, ipAddr.isOneToOneNat());
ip.setTrafficType(network.getTrafficType());
ip.setNetworkName(_networkModel.getNetworkTag(router.getHypervisorType(), network));
ipsToSend[i++] = ip;
if (ipAddr.isSourceNat()) {
sourceNatIpAdd = new Pair<IpAddressTO, Long>(ip, ipAddr.getNetworkId());
addSourceNat = add;
}
}
final IpAssocVpcCommand cmd = new IpAssocVpcCommand(ipsToSend);
cmd.setAccessDetail(NetworkElementCommand.ROUTER_IP, _routerControlHelper.getRouterControlIp(router.getId()));
cmd.setAccessDetail(NetworkElementCommand.ROUTER_GUEST_IP, _routerControlHelper.getRouterIpInNetwork(ipAddrList.get(0).getNetworkId(), router.getId()));
cmd.setAccessDetail(NetworkElementCommand.ROUTER_NAME, router.getInstanceName());
final DataCenterVO dcVo = _dcDao.findById(router.getDataCenterId());
cmd.setAccessDetail(NetworkElementCommand.ZONE_NETWORK_TYPE, dcVo.getNetworkType().toString());
cmds.addCommand(ipAssocCommand, cmd);
}
// set source nat ip
if (sourceNatIpAdd != null) {
final IpAddressTO sourceNatIp = sourceNatIpAdd.first();
final SetSourceNatCommand cmd = new SetSourceNatCommand(sourceNatIp, addSourceNat);
cmd.setAccessDetail(NetworkElementCommand.ROUTER_IP, _routerControlHelper.getRouterControlIp(router.getId()));
cmd.setAccessDetail(NetworkElementCommand.ROUTER_NAME, router.getInstanceName());
final DataCenterVO dcVo = _dcDao.findById(router.getDataCenterId());
cmd.setAccessDetail(NetworkElementCommand.ZONE_NETWORK_TYPE, dcVo.getNetworkType().toString());
cmds.addCommand("SetSourceNatCommand", cmd);
}
}
public void createRedundantAssociateIPCommands(final VirtualRouter router, final List<? extends PublicIpAddress> ips, final Commands cmds, final String ipAssocCommand, final long vmId) {
// Ensure that in multiple vlans case we first send all ip addresses of
// vlan1, then all ip addresses of vlan2, etc..
final Map<String, ArrayList<PublicIpAddress>> vlanIpMap = new HashMap<String, ArrayList<PublicIpAddress>>();
for (final PublicIpAddress ipAddress : ips) {
final String vlanTag = ipAddress.getVlanTag();
ArrayList<PublicIpAddress> ipList = vlanIpMap.get(vlanTag);
if (ipList == null) {
ipList = new ArrayList<PublicIpAddress>();
}
// domR doesn't support release for sourceNat IP address; so reset
// the state
if (ipAddress.isSourceNat() && ipAddress.getState() == IpAddress.State.Releasing) {
ipAddress.setState(IpAddress.State.Allocated);
}
ipList.add(ipAddress);
vlanIpMap.put(vlanTag, ipList);
}
final List<NicVO> nics = _nicDao.listByVmId(router.getId());
String baseMac = null;
for (final NicVO nic : nics) {
final NetworkVO nw = _networkDao.findById(nic.getNetworkId());
if (nw.getTrafficType() == TrafficType.Public) {
baseMac = nic.getMacAddress();
break;
}
}
for (final Map.Entry<String, ArrayList<PublicIpAddress>> vlanAndIp : vlanIpMap.entrySet()) {
final List<PublicIpAddress> ipAddrList = vlanAndIp.getValue();
// Source nat ip address should always be sent first
Collections.sort(ipAddrList, new Comparator<PublicIpAddress>() {
@Override
public int compare(final PublicIpAddress o1, final PublicIpAddress o2) {
final boolean s1 = o1.isSourceNat();
final boolean s2 = o2.isSourceNat();
return s1 ^ s2 ? s1 ^ true ? 1 : -1 : 0;
}
});
// Get network rate - required for IpAssoc
final Integer networkRate = _networkModel.getNetworkRate(ipAddrList.get(0).getNetworkId(), router.getId());
final Network network = _networkModel.getNetwork(ipAddrList.get(0).getNetworkId());
final IpAddressTO[] ipsToSend = new IpAddressTO[ipAddrList.size()];
int i = 0;
boolean firstIP = true;
for (final PublicIpAddress ipAddr : ipAddrList) {
final boolean add = ipAddr.getState() == IpAddress.State.Releasing ? false : true;
boolean sourceNat = ipAddr.isSourceNat();
/* enable sourceNAT for the first ip of the public interface */
if (firstIP) {
sourceNat = true;
}
final String vlanId = ipAddr.getVlanTag();
final String vlanGateway = ipAddr.getGateway();
final String vlanNetmask = ipAddr.getNetmask();
String vifMacAddress = null;
// For non-source nat IP, set the mac to be something based on
// first public nic's MAC
// We cannot depend on first ip because we need to deal with
// first ip of other nics
if (router.getVpcId() != null) {
//vifMacAddress = NetUtils.generateMacOnIncrease(baseMac, ipAddr.getVlanId());
vifMacAddress = ipAddr.getMacAddress();
} else {
if (!sourceNat && ipAddr.getVlanId() != 0) {
vifMacAddress = NetUtils.generateMacOnIncrease(baseMac, ipAddr.getVlanId());
} else {
vifMacAddress = ipAddr.getMacAddress();
}
}
final IpAddressTO ip = new IpAddressTO(ipAddr.getAccountId(), ipAddr.getAddress().addr(), add, firstIP, sourceNat, vlanId, vlanGateway, vlanNetmask,
vifMacAddress, networkRate, ipAddr.isOneToOneNat());
ip.setTrafficType(network.getTrafficType());
ip.setNetworkName(_networkModel.getNetworkTag(router.getHypervisorType(), network));
ipsToSend[i++] = ip;
/*
* send the firstIP = true for the first Add, this is to create
* primary on interface
*/
if (!firstIP || add) {
firstIP = false;
}
}
Long associatedWithNetworkId = ipAddrList.get(0).getAssociatedWithNetworkId();
if (associatedWithNetworkId == null || associatedWithNetworkId == 0) {
associatedWithNetworkId = ipAddrList.get(0).getNetworkId();
}
final IpAssocCommand cmd = new IpAssocCommand(ipsToSend);
cmd.setAccessDetail(NetworkElementCommand.ROUTER_IP, _routerControlHelper.getRouterControlIp(router.getId()));
cmd.setAccessDetail(NetworkElementCommand.ROUTER_GUEST_IP, _routerControlHelper.getRouterIpInNetwork(associatedWithNetworkId, router.getId()));
cmd.setAccessDetail(NetworkElementCommand.ROUTER_NAME, router.getInstanceName());
final DataCenterVO dcVo = _dcDao.findById(router.getDataCenterId());
cmd.setAccessDetail(NetworkElementCommand.ZONE_NETWORK_TYPE, dcVo.getNetworkType().toString());
cmds.addCommand(ipAssocCommand, cmd);
}
}
public void createStaticRouteCommands(final List<StaticRouteProfile> staticRoutes, final DomainRouterVO router, final Commands cmds) {
final SetStaticRouteCommand cmd = new SetStaticRouteCommand(staticRoutes);
cmd.setAccessDetail(NetworkElementCommand.ROUTER_IP, _routerControlHelper.getRouterControlIp(router.getId()));
cmd.setAccessDetail(NetworkElementCommand.ROUTER_NAME, router.getInstanceName());
final DataCenterVO dcVo = _dcDao.findById(router.getDataCenterId());
cmd.setAccessDetail(NetworkElementCommand.ZONE_NETWORK_TYPE, dcVo.getNetworkType().toString());
cmds.addCommand(cmd);
}
public void createSite2SiteVpnCfgCommands(final Site2SiteVpnConnection conn, final boolean isCreate, final VirtualRouter router, final Commands cmds) {
final Site2SiteCustomerGatewayVO gw = _s2sCustomerGatewayDao.findById(conn.getCustomerGatewayId());
final Site2SiteVpnGatewayVO vpnGw = _s2sVpnGatewayDao.findById(conn.getVpnGatewayId());
final IpAddress ip = _ipAddressDao.findById(vpnGw.getAddrId());
final Vpc vpc = _vpcDao.findById(ip.getVpcId());
final String localPublicIp = ip.getAddress().toString();
final String localGuestCidr = vpc.getCidr();
final String localPublicGateway = _vlanDao.findById(ip.getVlanId()).getVlanGateway();
final String peerGatewayIp = gw.getGatewayIp();
final String peerGuestCidrList = gw.getGuestCidrList();
final String ipsecPsk = gw.getIpsecPsk();
final String ikePolicy = gw.getIkePolicy();
final String espPolicy = gw.getEspPolicy();
final Long ikeLifetime = gw.getIkeLifetime();
final Long espLifetime = gw.getEspLifetime();
final Boolean dpd = gw.getDpd();
final Site2SiteVpnCfgCommand cmd = new Site2SiteVpnCfgCommand(isCreate, localPublicIp, localPublicGateway, localGuestCidr, peerGatewayIp, peerGuestCidrList, ikePolicy,
espPolicy, ipsecPsk, ikeLifetime, espLifetime, dpd, conn.isPassive());
cmd.setAccessDetail(NetworkElementCommand.ROUTER_IP, _routerControlHelper.getRouterControlIp(router.getId()));
cmd.setAccessDetail(NetworkElementCommand.ROUTER_IP, _routerControlHelper.getRouterControlIp(router.getId()));
cmd.setAccessDetail(NetworkElementCommand.ROUTER_NAME, router.getInstanceName());
final DataCenterVO dcVo = _dcDao.findById(router.getDataCenterId());
cmd.setAccessDetail(NetworkElementCommand.ZONE_NETWORK_TYPE, dcVo.getNetworkType().toString());
cmds.addCommand("applyS2SVpn", cmd);
}
public void createVpcAssociatePrivateIPCommands(final VirtualRouter router, final List<PrivateIpAddress> ips, final Commands cmds, final boolean add) {
// Ensure that in multiple vlans case we first send all ip addresses of
// vlan1, then all ip addresses of vlan2, etc..
final Map<String, ArrayList<PrivateIpAddress>> vlanIpMap = new HashMap<String, ArrayList<PrivateIpAddress>>();
for (final PrivateIpAddress ipAddress : ips) {
final String vlanTag = ipAddress.getBroadcastUri();
ArrayList<PrivateIpAddress> ipList = vlanIpMap.get(vlanTag);
if (ipList == null) {
ipList = new ArrayList<PrivateIpAddress>();
}
ipList.add(ipAddress);
vlanIpMap.put(vlanTag, ipList);
}
for (final Map.Entry<String, ArrayList<PrivateIpAddress>> vlanAndIp : vlanIpMap.entrySet()) {
final List<PrivateIpAddress> ipAddrList = vlanAndIp.getValue();
final IpAddressTO[] ipsToSend = new IpAddressTO[ipAddrList.size()];
int i = 0;
for (final PrivateIpAddress ipAddr : ipAddrList) {
final Network network = _networkModel.getNetwork(ipAddr.getNetworkId());
final IpAddressTO ip = new IpAddressTO(Account.ACCOUNT_ID_SYSTEM, ipAddr.getIpAddress(), add, false, ipAddr.getSourceNat(), ipAddr.getBroadcastUri(),
ipAddr.getGateway(), ipAddr.getNetmask(), ipAddr.getMacAddress(), null, false);
ip.setTrafficType(network.getTrafficType());
ip.setNetworkName(_networkModel.getNetworkTag(router.getHypervisorType(), network));
ipsToSend[i++] = ip;
}
final IpAssocVpcCommand cmd = new IpAssocVpcCommand(ipsToSend);
cmd.setAccessDetail(NetworkElementCommand.ROUTER_IP, _routerControlHelper.getRouterControlIp(router.getId()));
cmd.setAccessDetail(NetworkElementCommand.ROUTER_GUEST_IP, _routerControlHelper.getRouterIpInNetwork(ipAddrList.get(0).getNetworkId(), router.getId()));
cmd.setAccessDetail(NetworkElementCommand.ROUTER_NAME, router.getInstanceName());
final DataCenterVO dcVo = _dcDao.findById(router.getDataCenterId());
cmd.setAccessDetail(NetworkElementCommand.ZONE_NETWORK_TYPE, dcVo.getNetworkType().toString());
cmds.addCommand("IPAssocVpcCommand", cmd);
}
}
public SetupGuestNetworkCommand createSetupGuestNetworkCommand(final DomainRouterVO router, final boolean add, final NicProfile guestNic) {
final Network network = _networkModel.getNetwork(guestNic.getNetworkId());
String defaultDns1 = null;
String defaultDns2 = null;
final boolean dnsProvided = _networkModel.isProviderSupportServiceInNetwork(network.getId(), Service.Dns, Provider.VPCVirtualRouter);
final boolean dhcpProvided = _networkModel.isProviderSupportServiceInNetwork(network.getId(), Service.Dhcp, Provider.VPCVirtualRouter);
final boolean setupDns = dnsProvided || dhcpProvided;
if (setupDns) {
defaultDns1 = guestNic.getIPv4Dns1();
defaultDns2 = guestNic.getIPv4Dns2();
}
final Nic nic = _nicDao.findByNtwkIdAndInstanceId(network.getId(), router.getId());
final String networkDomain = network.getNetworkDomain();
final String dhcpRange = getGuestDhcpRange(guestNic, network, _entityMgr.findById(DataCenter.class, network.getDataCenterId()));
final NicProfile nicProfile = _networkModel.getNicProfile(router, nic.getNetworkId(), null);
final SetupGuestNetworkCommand setupCmd = new SetupGuestNetworkCommand(dhcpRange, networkDomain, router.getIsRedundantRouter(), defaultDns1, defaultDns2, add, _itMgr.toNicTO(nicProfile,
router.getHypervisorType()));
final String brd = NetUtils.long2Ip(NetUtils.ip2Long(guestNic.getIPv4Address()) | ~NetUtils.ip2Long(guestNic.getIPv4Netmask()));
setupCmd.setAccessDetail(NetworkElementCommand.ROUTER_IP, _routerControlHelper.getRouterControlIp(router.getId()));
setupCmd.setAccessDetail(NetworkElementCommand.ROUTER_GUEST_IP, _routerControlHelper.getRouterIpInNetwork(network.getId(), router.getId()));
setupCmd.setAccessDetail(NetworkElementCommand.GUEST_NETWORK_GATEWAY, network.getGateway());
setupCmd.setAccessDetail(NetworkElementCommand.GUEST_BRIDGE, brd);
setupCmd.setAccessDetail(NetworkElementCommand.ROUTER_NAME, router.getInstanceName());
if (network.getBroadcastDomainType() == BroadcastDomainType.Vlan) {
final long guestVlanTag = Long.parseLong(BroadcastDomainType.Vlan.getValueFrom(network.getBroadcastUri()));
setupCmd.setAccessDetail(NetworkElementCommand.GUEST_VLAN_TAG, String.valueOf(guestVlanTag));
}
return setupCmd;
}
private VmDataCommand generateVmDataCommand(final VirtualRouter router, final String vmPrivateIpAddress, final String userData, final String serviceOffering,
final String zoneName, final String guestIpAddress, final String vmName, final String vmInstanceName, final long vmId, final String vmUuid, final String publicKey,
final long guestNetworkId) {
final VmDataCommand cmd = new VmDataCommand(vmPrivateIpAddress, vmName, _networkModel.getExecuteInSeqNtwkElmtCmd());
cmd.setAccessDetail(NetworkElementCommand.ROUTER_IP, _routerControlHelper.getRouterControlIp(router.getId()));
cmd.setAccessDetail(NetworkElementCommand.ROUTER_GUEST_IP, _routerControlHelper.getRouterIpInNetwork(guestNetworkId, router.getId()));
cmd.setAccessDetail(NetworkElementCommand.ROUTER_NAME, router.getInstanceName());
final DataCenterVO dcVo = _dcDao.findById(router.getDataCenterId());
cmd.setAccessDetail(NetworkElementCommand.ZONE_NETWORK_TYPE, dcVo.getNetworkType().toString());
cmd.addVmData("userdata", "user-data", userData);
cmd.addVmData("metadata", "service-offering", StringUtils.unicodeEscape(serviceOffering));
cmd.addVmData("metadata", "availability-zone", StringUtils.unicodeEscape(zoneName));
cmd.addVmData("metadata", "local-ipv4", guestIpAddress);
cmd.addVmData("metadata", "local-hostname", StringUtils.unicodeEscape(vmName));
if (dcVo.getNetworkType() == NetworkType.Basic) {
cmd.addVmData("metadata", "public-ipv4", guestIpAddress);
cmd.addVmData("metadata", "public-hostname", StringUtils.unicodeEscape(vmName));
} else {
if (router.getPublicIpAddress() == null) {
cmd.addVmData("metadata", "public-ipv4", guestIpAddress);
} else {
cmd.addVmData("metadata", "public-ipv4", router.getPublicIpAddress());
}
cmd.addVmData("metadata", "public-hostname", router.getPublicIpAddress());
}
if (vmUuid == null) {
cmd.addVmData("metadata", "instance-id", vmInstanceName);
cmd.addVmData("metadata", "vm-id", String.valueOf(vmId));
} else {
cmd.addVmData("metadata", "instance-id", vmUuid);
cmd.addVmData("metadata", "vm-id", vmUuid);
}
cmd.addVmData("metadata", "public-keys", publicKey);
String cloudIdentifier = _configDao.getValue("cloud.identifier");
if (cloudIdentifier == null) {
cloudIdentifier = "";
} else {
cloudIdentifier = "CloudStack-{" + cloudIdentifier + "}";
}
cmd.addVmData("metadata", "cloud-identifier", cloudIdentifier);
return cmd;
}
private NicVO findGatewayIp(final long userVmId) {
final NicVO defaultNic = _nicDao.findDefaultNicForVM(userVmId);
return defaultNic;
}
private NicVO findDefaultDnsIp(final long userVmId) {
final NicVO defaultNic = _nicDao.findDefaultNicForVM(userVmId);
// check if DNS provider is the domR
if (!_networkModel.isProviderSupportServiceInNetwork(defaultNic.getNetworkId(), Service.Dns, Provider.VirtualRouter)) {
return null;
}
final NetworkOffering offering = _networkOfferingDao.findById(_networkDao.findById(defaultNic.getNetworkId()).getNetworkOfferingId());
if (offering.getRedundantRouter()) {
return findGatewayIp(userVmId);
}
final DataCenter dc = _dcDao.findById(_networkModel.getNetwork(defaultNic.getNetworkId()).getDataCenterId());
final boolean isZoneBasic = dc.getNetworkType() == NetworkType.Basic;
// find domR's nic in the network
NicVO domrDefaultNic;
if (isZoneBasic) {
domrDefaultNic = _nicDao.findByNetworkIdTypeAndGateway(defaultNic.getNetworkId(), VirtualMachine.Type.DomainRouter, defaultNic.getIPv4Gateway());
} else {
domrDefaultNic = _nicDao.findByNetworkIdAndType(defaultNic.getNetworkId(), VirtualMachine.Type.DomainRouter);
}
return domrDefaultNic;
}
protected String getGuestDhcpRange(final NicProfile guestNic, final Network guestNetwork, final DataCenter dc) {
String dhcpRange = null;
// setup dhcp range
if (dc.getNetworkType() == NetworkType.Basic) {
final long cidrSize = NetUtils.getCidrSize(guestNic.getIPv4Netmask());
final String cidr = NetUtils.getCidrSubNet(guestNic.getIPv4Gateway(), cidrSize);
if (cidr != null) {
dhcpRange = NetUtils.getIpRangeStartIpFromCidr(cidr, cidrSize);
}
} else if (dc.getNetworkType() == NetworkType.Advanced) {
final String cidr = guestNetwork.getCidr();
if (cidr != null) {
dhcpRange = NetUtils.getDhcpRange(cidr);
}
}
return dhcpRange;
}
}
|
package org.ddx.algorithms.graph;
import org.ddx.algorithms.graph.model.Graph;
import org.ddx.algorithms.graph.model.Node;
import org.ddx.algorithms.graph.model.Path;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
/**
* Utility to print human-friendly debugging logs of graphs, nodes, edges and paths.
*/
public class GraphLogger {
private static final Logger LOGGER = LoggerFactory.getLogger(GraphLogger.class);
public static final void logPath(Graph graph, Path path) {
path.pathStream()
.map(nodeId -> graph.getNode(nodeId).toString())
.reduce((s1, s2) -> s1 + " -> " + s2);
StringBuilder pathLog = new StringBuilder("Path: ");
List<Long> nodePath = path.getNodeIds();
for (int i=0; i<(nodePath.size()-1); i++) {
long nodeId = nodePath.get(i);
Node node = graph.getNode(nodeId);
pathLog.append(node.toString());
LOGGER.debug(pathLog.toString());
pathLog.setLength(0);
// indent
pathLog.append(new String(new char[i]).replace('\0', ' '));
long nextNodeId = nodePath.get(i + 1);
node.edgeStream()
.filter(edge -> edge.getTargetNodeId()==nextNodeId)
.forEach(edge -> {
pathLog.append(" -");
if (edge.getCost() > 0) {
pathLog.append("($");
pathLog.append(edge.getCost());
pathLog.append(")");
}
pathLog.append("-> ");
});
}
Node node = graph.getNode(nodePath.get(nodePath.size()-1));
pathLog.append(node.toString());
LOGGER.debug(pathLog.toString());
}
}
|
package intensiveteamhslee.config.kafka;
import org.springframework.cloud.stream.annotation.Input;
import org.springframework.cloud.stream.annotation.Output;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.SubscribableChannel;
public interface KafkaProcessor {
String INPUT = "event-in";
String OUTPUT = "event-out";
@Input(INPUT)
SubscribableChannel inboundTopic();
@Output(OUTPUT)
MessageChannel outboundTopic();
}
|
package com.coolweather.android;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Build;
import android.preference.PreferenceManager;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.coolweather.android.gson.Forecast;
import com.coolweather.android.gson.Weather;
import com.coolweather.android.service.AutoUpdateService;
import com.coolweather.android.util.HttpUtil;
import com.coolweather.android.util.Utility;
import java.io.IOException;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
public class WeatherActivity extends AppCompatActivity {
public DrawerLayout drawerLayout;
private Button navButton;
public SwipeRefreshLayout swipeRefresh;
private String mWeatherId;
private ScrollView weatherLayout;
private TextView titleCity;
private TextView titleUpdateTime;
private TextView degreeText;
private TextView weatherInfoText;
private LinearLayout forecastLayout;
private TextView aqiText;
private TextView pm25Text;
private TextView comfortText;
private TextView carWashText;
private TextView sportText;
private ImageView bingPicImg;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (Build.VERSION.SDK_INT >=21){
View decorView = getWindow().getDecorView();
decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
getWindow().setStatusBarColor(Color.TRANSPARENT);
}
setContentView(R.layout.activity_weather);
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
navButton = (Button) findViewById(R.id.nav_button);
bingPicImg = (ImageView) findViewById(R.id.bing_pic_img);
weatherLayout = (ScrollView) findViewById(R.id.weather_layout);
titleCity = (TextView) findViewById(R.id.title_city);
titleUpdateTime = (TextView) findViewById(R.id.title_update_time);
degreeText = (TextView) findViewById(R.id.degree_text);
weatherInfoText = (TextView) findViewById(R.id.weather_info_text);
forecastLayout = (LinearLayout) findViewById(R.id.forecast_layout);
aqiText = (TextView) findViewById(R.id.aqi_text);
pm25Text = (TextView) findViewById(R.id.pm25_text);
comfortText = (TextView) findViewById(R.id.comfort_text);
carWashText = (TextView) findViewById(R.id.car_wash_text);
sportText = (TextView) findViewById(R.id.sport_text);
swipeRefresh = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh);
swipeRefresh.setColorSchemeResources(R.color.colorPrimary);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String weatherString = prefs.getString("weather", null);
if (weatherString != null){
Weather weather = Utility.handleWeatherResponse(weatherString);
mWeatherId = weather.basic.weatherId;
showWeatherInfo(weather);
} else {
// String weatherId = getIntent().getStringExtra("weather_id");
mWeatherId = getIntent().getStringExtra("weather_id");
weatherLayout.setVisibility(View.INVISIBLE);
// requestWeather(weatherId);
requestWeather(mWeatherId);
}
swipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
requestWeather(mWeatherId);
}
});
String bingPic = prefs.getString("bing_pic", null);
if (bingPic != null){
Glide.with(this).load(bingPic).into(bingPicImg);
} else {
loadBingPic();
}
navButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
drawerLayout.openDrawer(GravityCompat.START);
}
});
}
public void requestWeather(final String weatherId){
String weatherUrl = "http://guolin.tech/api/weather?cityid=" + weatherId
+ "&key=46616226e67d49dc9424ce7573ddccd0";
HttpUtil.sendOkHttpRquest(weatherUrl, new Callback() {
@Override
public void onResponse(Call call, Response response) throws IOException {
final String responseText = response.body().string();
final Weather weather = Utility.handleWeatherResponse(responseText);
runOnUiThread(new Runnable() {
@Override
public void run() {
if (weather != null && "ok".equals(weather.status)){
SharedPreferences.Editor editor = PreferenceManager
.getDefaultSharedPreferences(WeatherActivity.this).edit();
editor.putString("weather", responseText);
editor.apply();
mWeatherId = weather.basic.weatherId;
showWeatherInfo(weather);
} else {
Toast.makeText(WeatherActivity.this, "获取天气信息失败", Toast.LENGTH_SHORT).show();
}
swipeRefresh.setRefreshing(false);
}
});
loadBingPic();
}
@Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(WeatherActivity.this, "获取天气信息失败", Toast.LENGTH_SHORT).show();
swipeRefresh.setRefreshing(false);
}
});
}
});
}
private void loadBingPic(){
String requestBingPic = "http://guolin.tech/api/bing_pic";
HttpUtil.sendOkHttpRquest(requestBingPic, new Callback() {
@Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
final String bingPic = response.body().string();
SharedPreferences.Editor editor = PreferenceManager
.getDefaultSharedPreferences(WeatherActivity.this).edit();
editor.putString("bing_pic", bingPic);
editor.apply();
runOnUiThread(new Runnable() {
@Override
public void run() {
Glide.with(WeatherActivity.this).load(bingPic).into(bingPicImg);
}
});
}
});
}
private void showWeatherInfo(Weather weather){
String cityName = weather.basic.cityName;
String updateTime = weather.basic.update.updateTime.split(" ")[1];
String degree = weather.now.temperature + "℃";
String weatherInfo = weather.now.more.info;
titleCity.setText(cityName);
titleUpdateTime.setText(updateTime);
degreeText.setText(degree);
weatherInfoText.setText(weatherInfo);
forecastLayout.removeAllViews();
for (Forecast forecast : weather.forecastList){
View view = LayoutInflater.from(this).inflate(R.layout.forecast_item, forecastLayout, false);
TextView dateText = (TextView) view.findViewById(R.id.date_text);
TextView infoText = (TextView) view.findViewById(R.id.info_text);
TextView maxText = (TextView) view.findViewById(R.id.max_text);
TextView minText = (TextView) view.findViewById(R.id.min_text);
dateText.setText(forecast.date);
infoText.setText(forecast.more.info);
maxText.setText(forecast.temperature.max);
minText.setText(forecast.temperature.min);
forecastLayout.addView(view);
}
if (weather.aqi != null){
aqiText.setText(weather.aqi.city.aqi);
pm25Text.setText(weather.aqi.city.pm25);
}
String comfort = "舒适度:" + weather.suggestion.comfort.info;
String carWash = "洗车指数:" + weather.suggestion.carWash.info;
String sport = "运动建议:" + weather.suggestion.sport.info;
comfortText.setText(comfort);
carWashText.setText(carWash);
sportText.setText(sport);
weatherLayout.setVisibility(View.VISIBLE);
Intent intent = new Intent(this, AutoUpdateService.class);
startService(intent);
}
}
|
package DataStructures.Trees;// Java program to print top view of Binary tree
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Queue;
// 트리 노드 클래스
class TreeNode {
// 멤버 변수들
int key;
TreeNode left, right;
// 생성자
public TreeNode(int key) {
this.key = key;
left = right = null;
}
}
// 큐의 아이템을 나타내는 클래스. 큐는 레벨순 검색을 하기위해 사용(level order traversal queue를 참고)
// 모든 큐의 아이템들은 노드와 horizontal을 멤버 변수로 가지고 있다
// distance of node from root
class QItem {
TreeNode node;
int hd;
public QItem(TreeNode n, int h) {
node = n;
hd = h;
}
}
// 이진 트리 클래스
class Tree {
TreeNode root;
// 생성자
public Tree() {
root = null;
}
public Tree(TreeNode n) {
root = n;
}
// 이 메소드는 이진 트리의 노드들을 top view로 출력한다
public void printTopView() {
// 추가 안된 트리의 경우
if (root == null) {
return;
}
// 빈 해쉬집합을 만든다
HashSet<Integer> set = new HashSet<>();
// 큐를 만든 뒤 루트를 큐에 넣는다
Queue<QItem> Q = new LinkedList<QItem>();
Q.add(new QItem(root, 0)); // Horizontal distance of root is 0
// 너비 우선 탐색(BFS) or 레벨 순회(level order traversal)
while (!Q.isEmpty()) {
// 앞의 정보를 삭제한 뒤 멤버 변수의 값을 얻는다
QItem qi = Q.remove();
int hd = qi.hd;
TreeNode n = qi.node;
// 이것이 수평 거리의 첫번째 노드인 경우,
// 이 노드를 top view 로 한다
if (!set.contains(hd)) {
set.add(hd);
System.out.print(n.key + " ");
}
// 현재 노드의 왼쪽 자식과 오른쪽 자식을 큐에 넣는다
if (n.left != null)
Q.add(new QItem(n.left, hd - 1));
if (n.right != null)
Q.add(new QItem(n.right, hd + 1));
}
}
}
// 위의 메소드들을 테스트하기 위한 클래스
public class PrintTopViewofTree {
public static void main(String[] args) {
/* 위의 이진 트리를 만들어라
1
/ \
2 3
\
4
\
5
\
6*/
TreeNode root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
root.left.right = new TreeNode(4);
root.left.right.right = new TreeNode(5);
root.left.right.right.right = new TreeNode(6);
Tree t = new Tree(root);
System.out.println("Following are nodes in top view of Binary Tree");
t.printTopView();
}
}
|
package controllers;
import play.mvc.*;
import views.html.*;
public class HomeController extends Controller {
public Result index() {
return ok(index.render());
}
}
|
package com.github.housepower.jdbc;
import com.github.housepower.jdbc.connect.PhysicalConnection;
import com.github.housepower.jdbc.connect.PhysicalInfo;
import com.github.housepower.jdbc.data.Block;
import com.github.housepower.jdbc.misc.Validate;
import com.github.housepower.jdbc.protocol.HelloResponse;
import com.github.housepower.jdbc.protocol.QueryRequest;
import com.github.housepower.jdbc.protocol.QueryResponse;
import com.github.housepower.jdbc.settings.ClickHouseConfig;
import com.github.housepower.jdbc.settings.ClickHouseDefines;
import com.github.housepower.jdbc.statement.ClickHousePreparedInsertStatement;
import com.github.housepower.jdbc.statement.ClickHousePreparedQueryStatement;
import com.github.housepower.jdbc.statement.ClickHouseStatement;
import com.github.housepower.jdbc.wrapper.SQLConnection;
import java.net.InetSocketAddress;
import java.sql.Array;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLClientInfoException;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Struct;
import java.util.Locale;
import java.util.Properties;
import java.util.TimeZone;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ClickHouseConnection extends SQLConnection {
private static final Pattern VALUES_REGEX = Pattern.compile("[V|v][A|a][L|l][U|u][E|e][S|s]\\s*\\(");
// Just to be variable
private final AtomicBoolean isClosed;
private final ClickHouseConfig configure;
private final AtomicReference<PhysicalInfo> atomicInfo;
private ConnectionState state = ConnectionState.IDLE;
protected ClickHouseConnection(ClickHouseConfig configure, PhysicalInfo info) {
this.isClosed = new AtomicBoolean(false);
this.configure = configure;
this.atomicInfo = new AtomicReference<PhysicalInfo>(info);
}
@Override
public void close() throws SQLException {
if (!isClosed() && isClosed.compareAndSet(false, true)) {
PhysicalConnection connection = atomicInfo.get().connection();
connection.disPhysicalConnection();
}
}
@Override
public boolean isClosed() throws SQLException {
return isClosed.get();
}
@Override
public Statement createStatement() throws SQLException {
Validate.isTrue(!isClosed(), "Unable to create Statement, because the connection is closed.");
return new ClickHouseStatement(this);
}
@Override
public PreparedStatement prepareStatement(String query) throws SQLException {
Validate.isTrue(!isClosed(), "Unable to create PreparedStatement, because the connection is closed.");
Matcher matcher = VALUES_REGEX.matcher(query);
return matcher.find() ? new ClickHousePreparedInsertStatement(matcher.end() - 1, query, this) :
new ClickHousePreparedQueryStatement(this, query);
}
@Override
public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException {
return this.prepareStatement(sql);
}
@Override
public void setClientInfo(Properties properties) throws SQLClientInfoException {
configure.parseJDBCProperties(properties);
}
@Override
public void setClientInfo(String name, String value) throws SQLClientInfoException {
Properties properties = new Properties();
properties.put(name, value);
configure.parseJDBCProperties(properties);
}
@Override
public Array createArrayOf(String typeName, Object[] elements) throws SQLException {
Validate.isTrue(!isClosed(), "Unable to create Array, because the connection is closed.");
return new ClickHouseArray(elements);
}
@Override
public Struct createStruct(String typeName, Object[] attributes) throws SQLException {
Validate.isTrue(!isClosed(), "Unable to create Struct, because the connection is closed.");
return new ClickHouseStruct(typeName, attributes);
}
@Override
public boolean isValid(int timeout) throws SQLException {
ClickHouseConfig validConfigure = configure.copy();
validConfigure.setQueryTimeout(timeout * 1000);
Connection connection = null;
Statement statement = null;
try {
connection = new ClickHouseConnection(validConfigure, atomicInfo.get());
statement = connection.createStatement();
statement.execute("SELECT 1");
statement.close();
return true;
} finally {
if (statement != null)
statement.close();
if (connection != null)
connection.close();
}
}
public Block getSampleBlock(final String insertQuery) throws SQLException {
PhysicalConnection connection = getHealthyPhysicalConnection();
connection.sendQuery(insertQuery, atomicInfo.get().client(), configure.settings());
this.state=ConnectionState.WAITING_INSERT;
return connection.receiveSampleBlock(configure.queryTimeout(), atomicInfo.get().server());
}
public QueryResponse sendQueryRequest(final String query) throws SQLException {
if (this.state == ConnectionState.WAITING_INSERT) {
throw new RuntimeException("Connection is currently waiting for an insert operation, check your previous InsertStatement.");
}
PhysicalConnection connection = getHealthyPhysicalConnection();
connection.sendQuery(query, atomicInfo.get().client(), configure.settings());
return new QueryResponse(() -> connection.receiveResponse(configure.queryTimeout(), atomicInfo.get().server()));
}
// when sendInsertRequest we must ensure the connection is healthy
// the sampleblock mus be called before this method
public Integer sendInsertRequest(Block block)
throws SQLException {
if (this.state != ConnectionState.WAITING_INSERT) {
throw new RuntimeException("Call getSampleBlock before insert.");
}
PhysicalConnection connection = getPhysicalConnection();
connection.sendData(block);
connection.sendData(new Block());
connection.receiveEndOfStream(configure.queryTimeout(), atomicInfo.get().server());
this.state = ConnectionState.IDLE;
return block.rows();
}
private PhysicalConnection getHealthyPhysicalConnection() throws SQLException {
PhysicalInfo oldInfo = atomicInfo.get();
if (!oldInfo.connection().ping(configure.queryTimeout(), atomicInfo.get().server())) {
PhysicalInfo newInfo = createPhysicalInfo(configure);
PhysicalInfo closeableInfo = atomicInfo.compareAndSet(oldInfo, newInfo) ? oldInfo : newInfo;
closeableInfo.connection().disPhysicalConnection();
}
return atomicInfo.get().connection();
}
private PhysicalConnection getPhysicalConnection() throws SQLException {
return atomicInfo.get().connection();
}
public static ClickHouseConnection createClickHouseConnection(ClickHouseConfig configure) throws SQLException {
return new ClickHouseConnection(configure, createPhysicalInfo(configure));
}
private static PhysicalInfo createPhysicalInfo(ClickHouseConfig configure) throws SQLException {
PhysicalConnection physical = PhysicalConnection.openPhysicalConnection(configure);
return new PhysicalInfo(clientInfo(physical, configure), serverInfo(physical, configure), physical);
}
private static QueryRequest.ClientInfo clientInfo(PhysicalConnection physical, ClickHouseConfig configure) throws SQLException {
Validate.isTrue(physical.address() instanceof InetSocketAddress);
InetSocketAddress address = (InetSocketAddress) physical.address();
String clientName = String.format(Locale.ROOT, "%s %s", ClickHouseDefines.NAME, "client");
String initialAddress = "[::ffff:127.0.0.1]:0";
return new QueryRequest.ClientInfo(initialAddress, address.getHostName(), clientName);
}
private static PhysicalInfo.ServerInfo serverInfo(PhysicalConnection physical, ClickHouseConfig configure) throws SQLException {
try {
long reversion = ClickHouseDefines.CLIENT_REVERSION;
physical.sendHello("client", reversion, configure.database(), configure.username(), configure.password());
HelloResponse response = physical.receiveHello(configure.queryTimeout(), null);
TimeZone timeZone = TimeZone.getTimeZone(response.serverTimeZone());
return new PhysicalInfo.ServerInfo(configure, response.reversion(), timeZone, response.serverDisplayName());
} catch (SQLException rethrows) {
physical.disPhysicalConnection();
throw rethrows;
}
}
}
|
import java.io.*;
import java.lang.Math;
import vector.Vector2D;
class KiwiVectorMath {
//
// /\
// / \
// / \
// l / \ r
// / \
// / \
// ------------
// m
public static void main(String[] argv){
Vector2D middleWheelVec = new Vector2D(1.0, 0.0);
Vector2D rightWheelVec = new Vector2D(-1.0, 1.0);
Vector2D leftWheelVec = new Vector2D(1.0, 1.0);
double middleWheelOutput = 0.0;
double rightWheelOutput = 0.0;
double leftWheelOutput = 0.0;
double xOutput = Vector2D.add(Vector2D.add(Vector2D.multiply(rightWheelOutput, new Vector2D(rightWheelVec.magnitude()*Math.toDegrees(Math.cos(Vector2D.angleBetween(rightWheelVec, new Vector2D(1,0)))), 0).normalize()), Vector2D.multiply(leftWheelOutput, new Vector2D(leftWheelVec.magnitude()*Math.toDegrees(Math.cos(Vector2D.angleBetween(leftWheelVec, new Vector2D(1,0)))), 0).normalize())), Vector2D.multiply(middleWheelOutput, middleWheelVec)).normalize().x;
double yOutput = Vector2D.add(Vector2D.multiply(rightWheelOutput, new Vector2D(0,rightWheelVec.magnitude()*Math.toDegrees(Math.cos(Vector2D.angleBetween(rightWheelVec, new Vector2D(0,1))))).normalize()), Vector2D.multiply(leftWheelOutput, new Vector2D(0,leftWheelVec.magnitude()*Math.toDegrees(Math.cos(Vector2D.angleBetween(leftWheelVec, new Vector2D(0,1))))).normalize())).normalize().y;
System.out.println(String.format("[%1$.1f, %2$.1f]", xOutput, yOutput));
}
}
|
package com.cantinho.cms;
import com.cantinho.cms.controllers.Controller;
import org.apache.catalina.connector.Connector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.embedded.EmbeddedServletContainerFactory;
import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory;
import org.springframework.context.annotation.Bean;
import java.util.Arrays;
/**
* Copyright 2016 Cantinho. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* @author Samir Trajano Feitosa
* @author Jordão Ezequiel Serafim de Araújo
* @author Cantinho - Github https://github.com/Cantinho
* @since 2016
* @license Apache 2.0
*
* This file is 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. For additional information regarding
* copyright in this work, please see the NOTICE file in the top level
* directory of this distribution.
*
*/
@SpringBootApplication
public class InitialPoint {
private static Logger LOGGER = LoggerFactory.getLogger(InitialPoint.class);
@Value("${server.http.port}")
private Integer httpPort;
@Bean
public EmbeddedServletContainerFactory servletContainer() {
TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory();
tomcat.addAdditionalTomcatConnectors(createStandardConnector());
return tomcat;
}
private Connector createStandardConnector() {
Connector connector = new Connector(TomcatEmbeddedServletContainerFactory.DEFAULT_PROTOCOL);
connector.setPort(httpPort);
return connector;
}
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
LOGGER.debug("Calling method: " + String.format("protected SpringApplicationBuilder configure( %s )", application.toString()));
return application.sources(Controller.class);
}
public static void main(String[] args) throws Exception {
LOGGER.debug("Calling method: " + String.format("public static void main( %s ) throws Exception", Arrays.toString(args)));
SpringApplication.run(Controller.class, args);
}
}
|
package com.project.onthego.proxy;
import java.net.InetSocketAddress;
import java.net.Proxy;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
public class RealInternet implements Internet {
@Override
public Response connectTo(Request req) throws Exception {
Proxy webProxy
= new Proxy(Proxy.Type.HTTP, new InetSocketAddress("54.213.107.123", 3128));
OkHttpClient client = new OkHttpClient();
client.setProxy(webProxy);
return client.newCall(req).execute();
}
}
|
/*
* 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.tasks;
import org.junit.Test;
public final class GetTaskRequestTest {
@Test(expected = IllegalStateException.class)
public void noTaskId() {
GetTaskRequest.builder()
.build();
}
@Test
public void valid() {
GetTaskRequest.builder()
.taskId("test-task-id")
.build();
}
}
|
/*
* Copyright (C) 2011 Benoit GUEROUT <bguerout at gmail dot com> and Yves AMSELLEM <amsellem dot yves at gmail dot 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 org.jongo.marshall;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import org.bson.types.*;
import org.jongo.MongoCollection;
import org.jongo.model.Friend;
import org.jongo.util.JongoTestBase;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.util.*;
import java.util.regex.Pattern;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.data.MapEntry.entry;
public class DocumentMarshallingTest extends JongoTestBase {
private MongoCollection collection;
@Before
public void setUp() throws Exception {
collection = createEmptyCollection("marshalling");
}
@After
public void tearDown() throws Exception {
dropCollection("marshalling");
}
@Test
public void canHandleJavaTypes() throws Exception {
JavaNativeType type = new JavaNativeType();
type.number = 100L;
type.string = "value";
type.bool = false;
type.anEnum = Parameter.TEST;
collection.save(type);
assertHasBeenPersistedAs("{'number' : 100}");
assertHasBeenPersistedAs("{'string' : 'value'}");
assertHasBeenPersistedAs("{'bool' : false}");
assertHasBeenPersistedAs("{'anEnum' : 'TEST'}");
JavaNativeType result = collection.findOne("{}").as(JavaNativeType.class);
assertThat(result.bool).isFalse();
assertThat(result.string).isEqualTo("value");
assertThat(result.number).isEqualTo(100L);
assertThat(result.anEnum).isEqualTo(Parameter.TEST);
}
@Test
public void canHandleMinAndMaxKey() throws Exception {
BSONPrimitiveType type = new BSONPrimitiveType();
type.minKey = new MinKey();
type.maxKey = new MaxKey();
collection.save(type);
assertHasBeenPersistedAs("{'minKey' : { '$minKey' : 1}}");
assertHasBeenPersistedAs("{'maxKey' : { '$maxKey' : 1}}");
BSONPrimitiveType result = collection.findOne("{}").as(BSONPrimitiveType.class);
assertThat(result.minKey).isNotNull();
assertThat(result.maxKey).isNotNull();
}
@Test
public void canHandleObjectId() throws Exception {
BSONPrimitiveType type = new BSONPrimitiveType();
type.key = new ObjectId("4fe83969e4b042bbbca47c48");
collection.save(type);
assertHasBeenPersistedAs("{'key' : { '$oid' : '4fe83969e4b042bbbca47c48'}}");
BSONPrimitiveType result = collection.findOne("{}").as(BSONPrimitiveType.class);
assertThat(result.key).isEqualTo(new ObjectId("4fe83969e4b042bbbca47c48"));
}
@Test
public void canHandlePattern() throws Exception {
Pattern chars = Pattern.compile("[a-z]");
BSONPrimitiveType type = new BSONPrimitiveType();
type.pattern = chars;
collection.save(type);
assertHasBeenPersistedAs("{'pattern' : { '$regex' : '[a-z]'}}");//options is not longer generated since 2.8.0
BSONPrimitiveType result = collection.findOne("{}").as(BSONPrimitiveType.class);
assertThat(result.pattern.toString()).isEqualTo(chars.toString());
}
@Test
public void canHandleBSONTimestamp() throws Exception {
BSONPrimitiveType type = new BSONPrimitiveType();
type.timestamp = new BSONTimestamp(1, 2);
collection.save(type);
assertHasBeenPersistedAs("{'timestamp' : { '$timestamp' : { 't' : 1 , 'i' : 2}}}");
BSONPrimitiveType result = collection.findOne("{}").as(BSONPrimitiveType.class);
assertThat(result.timestamp).isEqualTo(new BSONTimestamp(1, 2));
}
@Test
public void canHandleISODate() throws Exception {
BSONPrimitiveType type = new BSONPrimitiveType();
type.date = new Date(123);
collection.save(type);
assertHasBeenPersistedAs("{'date' : { '$date' : 123}}");
BSONPrimitiveType result = collection.findOne("{}").as(BSONPrimitiveType.class);
assertThat(result.date).isEqualTo(new Date(123));
}
@Test
public void canHandleNonIsoDate() throws IOException {
collection.insert("{date:#}", 1340714101235L);
BSONPrimitiveType result = collection.findOne("{}").as(BSONPrimitiveType.class);
assertThat(result.date).isEqualTo(new Date(1340714101235L));
}
@Test
public void canHandleUUID() throws Exception {
BSONPrimitiveType type = new BSONPrimitiveType();
type.uuid = UUID.fromString("cf0eddfa-2670-4929-a581-eb263d839cab");
collection.save(type);
assertHasBeenPersistedAs("{'uuid' : { '$uuid' : 'cf0eddfa-2670-4929-a581-eb263d839cab'}}");
BSONPrimitiveType result = collection.findOne("{}").as(BSONPrimitiveType.class);
assertThat(result.uuid).isEqualTo(type.uuid);
}
@Test
public void canHandleDBObject() throws Exception {
BSONPrimitiveType type = new BSONPrimitiveType();
type.dbo = new BasicDBObject("key", "value");
collection.save(type);
BSONPrimitiveType result = collection.findOne("{}").as(BSONPrimitiveType.class);
assertThat(result.dbo).isEqualTo(type.dbo);
}
@Test
public void canHandleMapWithPrimitiveType() throws Exception {
Map<String, Date> strings = new HashMap<String, Date>();
strings.put("key", new Date(456));
BSONPrimitiveType type = new BSONPrimitiveType();
type.mapWithDates = strings;
collection.save(type);
assertHasBeenPersistedAs("{mapWithDates : { key : { $date : 456}}}");
BSONPrimitiveType result = collection.findOne("{}").as(BSONPrimitiveType.class);
assertThat(result.mapWithDates).contains(entry("key", new Date(456)));
}
@Test
public void canHandleMapWithComplexType() throws Exception {
Map<String, Friend> friends = new HashMap<String, Friend>();
Friend robert = new Friend("robert");
friends.put("key", robert);
BSONPrimitiveType type = new BSONPrimitiveType();
type.friends = friends;
collection.save(type);
assertHasBeenPersistedAs("{'friends' : { 'key' : { 'name' : 'robert'}}}");
BSONPrimitiveType result = collection.findOne("{}").as(BSONPrimitiveType.class);
assertThat(result.friends).contains(entry("key", robert));
}
@Test
public void canHandleArray() throws Exception {
BSONPrimitiveType type = new BSONPrimitiveType();
type.array = new int[]{1, 2, 3};
collection.save(type);
assertHasBeenPersistedAs("{'array' : [ 1 , 2 , 3]}");
BSONPrimitiveType result = collection.findOne("{}").as(BSONPrimitiveType.class);
assertThat(result.array).contains(1, 2, 3);
}
@Test
public void canHandleByteArray() throws Exception {
BSONPrimitiveType type = new BSONPrimitiveType();
type.bytes = "this is a byte array".getBytes();
collection.save(type);
BSONPrimitiveType result = collection.findOne("{}").as(BSONPrimitiveType.class);
assertThat(result.bytes).isEqualTo(type.bytes);
}
@Test
public void canHandleIterableWithPrimitiveType() throws Exception {
BSONPrimitiveType type = new BSONPrimitiveType();
List<Date> dates = new ArrayList<Date>();
dates.add(new Date(123));
type.dateList = dates;
collection.save(type);
assertHasBeenPersistedAs("{'dateList' : [ { '$date' : 123}]}");
BSONPrimitiveType result = collection.findOne("{}").as(BSONPrimitiveType.class);
assertThat(result.dateList).contains(new Date(123));
}
@Test
public void canHandleIterableWithComplexType() throws Exception {
BSONPrimitiveType type = new BSONPrimitiveType();
List<Friend> friends = new ArrayList<Friend>();
Friend robert = new Friend("robert");
friends.add(robert);
type.complexList = friends;
collection.save(type);
assertHasBeenPersistedAs("{'complexList' : [ { 'name' : 'robert'}]}");
BSONPrimitiveType result = collection.findOne("{}").as(BSONPrimitiveType.class);
assertThat(result.complexList).contains(robert);
}
private void assertHasBeenPersistedAs(String expectedPersistedJSON) {
assertThat(collection.count(expectedPersistedJSON)).isEqualTo(1);
}
private static class BSONPrimitiveType {
MinKey minKey;
MaxKey maxKey;
ObjectId key;
Pattern pattern;
BSONTimestamp timestamp;
Date date;
UUID uuid;
Code code;
DBObject dbo;
Map<String, Date> mapWithDates;
Map<String, Friend> friends;
int[] array;
List<Friend> complexList;
List<Date> dateList;
byte[] bytes;
}
private static class JavaNativeType {
long number;
String string;
boolean bool;
Parameter anEnum;
}
private static enum Parameter {
TEST
}
}
|
/*
* Copyright (c) Pawel Quver 2015.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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 pl.quver.sharepointmobileclient.components.activities;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.rest.RestService;
import org.androidannotations.api.BackgroundExecutor;
import java.util.Collections;
import java.util.List;
import pl.quver.sharepointmobileclient.BuildConfig;
import pl.quver.sharepointmobileclient.Configuration;
import pl.quver.sharepointmobileclient.R;
import pl.quver.sharepointmobileclient.components.adapters.TasksListAdapter;
import pl.quver.sharepointmobileclient.rest.models.TaskEntity;
import pl.quver.sharepointmobileclient.rest.services.TasksService;
/**
* Class Main of pl.quver.sharepointmobileclient.components.activities.
*
* Activite shows List of Tasks from Sharepoint REST API. This is start point of application.
*
* @author quver
* @version 1.0
* @since 19.04.15
* @see pl.quver.sharepointmobileclient.rest.services.TasksService
* @see pl.quver.sharepointmobileclient.rest.models.TaskEntity
*/
@EActivity(R.layout.activity_main)
public class MainActivity extends Activity {
protected Context mContext;
protected String mFedAuth;
protected String mRtfa;
protected boolean mIsLogged = false;
@ViewById(R.id.list_requests)
protected ListView mTasksList;
@Bean
protected TasksListAdapter mTasksAdapter;
@RestService
protected TasksService mTasksService;
@AfterViews
void bindAdapter() {
mTasksList.setAdapter(mTasksAdapter);
}
/**
* Method checks is SharedPreferences contains rfTa and FedAuth for REST API requests
*/
private void showLoginIfNeeded() {
SharedPreferences shared = getSharedPreferences("AUTHENTICATION_CREDENTIALS", Context.MODE_PRIVATE);
mFedAuth = shared.getString("FED_AUTH", "");
mRtfa = shared.getString("RFTA", "");
if(mRtfa.length() > 0 && mFedAuth.length() > 0) {
System.out.println("mRtfa " + mRtfa);
System.out.println("mFedAuth " + mFedAuth);
mIsLogged = true;
return;
}
mIsLogged = false;
LoginActivity_.intent(this).start();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(Configuration.SITE_URL.isEmpty() || Configuration.LIST_NAME.isEmpty() || Configuration.ENDPOINT_URL.isEmpty()) {
throw new AssertionError("Configuration cannot be empty");
}
mContext = this;
showLoginIfNeeded();
performRequest();
}
@Override
protected void onResume() {
super.onResume();
showLoginIfNeeded();
performRequest();
}
@Override
protected void onStop() {
super.onStop();
//Cancel all background requests when activity disappear top
BackgroundExecutor.cancelAll("restRequest", true);
}
@AfterViews
protected void click() {
mTasksList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> av, View view, int i, long l) {
System.out.println(mTasksAdapter.getItem(i));
DetailsActivity_.intent(mContext).taskEntity(mTasksAdapter.getItem(i)).start();
}
});
}
/**
* Method perform requests to Sharepoint REST API on background thread
*/
@Background(id="restRequest")
protected void performRequest() {
if(mIsLogged) {
/**
* Header "Cookie: rtFA=(String); FedAuth=(String)"
*/
mTasksService.setHeader("Cookie", "rtFa=" + mRtfa + "; FedAuth=" + mFedAuth);
List<TaskEntity> responseList = Collections.emptyList();
try {
responseList = mTasksService.getTasksList().getmValues();
} catch (Exception e) {
e.printStackTrace();
}
updateList(responseList);
if(BuildConfig.DEBUG) {
for (TaskEntity taskEntity : responseList) {
System.out.println(taskEntity.toString());
}
}
}
}
/**
* Method update Tasks List View on UI Thread
* @param updatedList list of <class>TaskEntity</class> objects
*/
@UiThread
protected void updateList(List<TaskEntity> updatedList) {
mTasksList.setAdapter(mTasksAdapter);
mTasksAdapter.setmTasksList(updatedList);
Toast.makeText(getApplicationContext(), updatedList.size() + " tasks recived", Toast.LENGTH_SHORT).show();
}
}
|
/*
* Copyright 2017-2022 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.iotwireless.model.transform;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.services.iotwireless.model.*;
import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;
/**
* LoRaWANGatewayCurrentVersionMarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class LoRaWANGatewayCurrentVersionMarshaller {
private static final MarshallingInfo<StructuredPojo> CURRENTVERSION_BINDING = MarshallingInfo.builder(MarshallingType.STRUCTURED)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("CurrentVersion").build();
private static final LoRaWANGatewayCurrentVersionMarshaller instance = new LoRaWANGatewayCurrentVersionMarshaller();
public static LoRaWANGatewayCurrentVersionMarshaller getInstance() {
return instance;
}
/**
* Marshall the given parameter object.
*/
public void marshall(LoRaWANGatewayCurrentVersion loRaWANGatewayCurrentVersion, ProtocolMarshaller protocolMarshaller) {
if (loRaWANGatewayCurrentVersion == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(loRaWANGatewayCurrentVersion.getCurrentVersion(), CURRENTVERSION_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
}
}
|
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 - 2018 Raja Vallée-Rai and others
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
class Helper {
public static void main(String [] args){
}
public void action(){
System.out.println("Helper");
}
}
public class Test93 {
public static void main(String [] args) {
Test93 t93 = new Test93();
t93.run();
}
public void run(){
new Helper(){
int x = 9;
{x=x+3;}
public void action(){
System.out.println("x: "+x);
}
}.action();
}
}
|
//Dstl (c) Crown Copyright 2017
package uk.gov.dstl.baleen.annotators.regex;
import org.junit.Test;
import uk.gov.dstl.baleen.annotators.regex.Email;
import uk.gov.dstl.baleen.annotators.testing.AbstractAnnotatorTest;
import uk.gov.dstl.baleen.annotators.testing.types.TestCommsIdentifier;
import uk.gov.dstl.baleen.types.common.CommsIdentifier;
/**
*
*/
public class EmailTest extends AbstractAnnotatorTest {
private static final String EMAIL = "email";
public EmailTest() {
super(Email.class);
}
@Test
public void test() throws Exception{
jCas.setDocumentText("John Smith has two work e-mail addresses, jsmith@example.com and john.smith@example.com. Joe Bloggs can be reached by e-mail too (j.bloggs@foo.com).");
processJCas();
assertAnnotations(3, CommsIdentifier.class,
new TestCommsIdentifier(0, "jsmith@example.com", EMAIL),
new TestCommsIdentifier(1, "john.smith@example.com", EMAIL),
new TestCommsIdentifier(2, "j.bloggs@foo.com", EMAIL));
}
}
|
// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3) annotate safe
package com.google.android.gms.dynamite;
// Referenced classes of package com.google.android.gms.dynamite:
// DynamiteModule, zza
public static class DynamiteModule$LoadingException extends Exception
{
private DynamiteModule$LoadingException(String s)
{
super(s);
// 0 0:aload_0
// 1 1:aload_1
// 2 2:invokespecial #11 <Method void Exception(String)>
// 3 5:return
}
DynamiteModule$LoadingException(String s, zza zza)
{
this(s);
// 0 0:aload_0
// 1 1:aload_1
// 2 2:invokespecial #14 <Method void DynamiteModule$LoadingException(String)>
// 3 5:return
}
private DynamiteModule$LoadingException(String s, Throwable throwable)
{
super(s, throwable);
// 0 0:aload_0
// 1 1:aload_1
// 2 2:aload_2
// 3 3:invokespecial #17 <Method void Exception(String, Throwable)>
// 4 6:return
}
DynamiteModule$LoadingException(String s, Throwable throwable, zza zza)
{
this(s, throwable);
// 0 0:aload_0
// 1 1:aload_1
// 2 2:aload_2
// 3 3:invokespecial #19 <Method void DynamiteModule$LoadingException(String, Throwable)>
// 4 6:return
}
}
|
package com.empdirectory.model.am.client;
import com.empdirectory.model.am.common.EmpDirectoryModule;
import oracle.jbo.client.remote.ApplicationModuleImpl;
// ---------------------------------------------------------------------
// --- File generated by Oracle ADF Business Components Design Time.
// --- Wed Oct 10 23:40:03 CDT 2012
// --- Custom code may be added to this class.
// --- Warning: Do not modify method signatures of generated methods.
// ---------------------------------------------------------------------
public class EmpDirectoryModuleClient extends ApplicationModuleImpl implements EmpDirectoryModule {
/**
* This is the default constructor (do not remove).
*/
public EmpDirectoryModuleClient() {
}
public String getHelloWorld() {
Object _ret = this.riInvokeExportedMethod(this,"getHelloWorld",null,null);
return (String)_ret;
}
}
|
package g2048.v3;
/**
* @author Xcl
* @date 2021/12/1 09:48
* @package g2048.v3
*/
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class Login extends JFrame implements Runnable, IData, ILogin {
static final long serialVersionUID = 3878971623272611814L;
static String stt1 = null;
JFrame jfmm = this;
JLabel l_name;
JLabel l_password;
JTextField t_name;
JPasswordField t_password;
JButton b_login;
JButton b_reset;
JButton b_register;
Register rf_1 = null;
Login() {
setTitle(getStt1() + "登录窗体");
setVisible(getStt1() != null);
init(getStt1());
setSize(380, 300);
setLocationRelativeTo(null);
}
public static long getSerialVersionUID() {
return serialVersionUID;
}
public static String getStt1() {
return stt1;
}
public static void setStt1(String stt1) {
Login.stt1 = stt1;
}
@Override
public void init(String st) {
setLayout(null);
setL_name(new JLabel("用户名", JLabel.CENTER));
setL_password(new JLabel("用户密码", JLabel.CENTER));
setT_name(new JTextField());
setT_password(new JPasswordField());
setB_login(new JButton("登录"));
getB_login().addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, "登录成功会跳转!", " ", -1);
if (st.equals("用户")) {
/*数据库结束*/
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection conn1 = DriverManager.getConnection(SqlMessage.Sqlmessage_URL,
SqlMessage.Sqlmessage_USER, SqlMessage.Sqlmessage_PASSWORD);
Statement stmt1 = conn1.createStatement();
ResultSet rs1 = stmt1.executeQuery("select Tname,Tpasswd from t_user ;");
while (rs1.next()) {
if (String.valueOf(getT_name().getText()).equals(rs1.getString(1))) {
if (String.valueOf(getT_password().getPassword()).equals(rs1.getString(2))) {
getJfmm().dispose();
new GView4(getT_name().getText()).showView();
break;
}
}
}
} catch (Exception e_1) {
JOptionPane.showMessageDialog(null, "数据库综合错误,如果你看到此弹窗,请立刻联系我。",
"ERROR!", JOptionPane.ERROR_MESSAGE);
e_1.printStackTrace();
}
/*数据库结束*/
} else if (st.equals("管理员")) {
if (String.valueOf(getT_name().getText()).equals("admin123")) {
if (String.valueOf(getT_password().getPassword()).equals("111111")) {
getJfmm().dispose();
new UserInfo(String.valueOf(getT_name().getText()));
}
}
} else {
System.out.println("不可能执行到这里...");
}
}
});
setB_reset(new JButton("重置"));
getB_reset().addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
getT_name().setText("");
getT_password().setText("");
}
});
setB_register(new JButton("点我注册"));
getB_register().addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (st.equals("管理员"))
JOptionPane.showMessageDialog(null, "注意:管理员模式登录禁止注册!",
"ERROR", JOptionPane.ERROR_MESSAGE);
else {
getJfmm().dispose();
if (getRf_1() != null) getRf_1().dispose();
Register rf = new Register();
setRf_1(rf);
rf.setVisible(true);
}
}
});
JPanel p = new JPanel();
p.setLayout(new GridLayout(2, 2, 5, 5));
p.add(getL_name());
p.add(getT_name());
p.add(getL_password());
p.add(getT_password());
p.setBounds(5, 5, 350, 185);
add(p);
p = new JPanel();
p.setLayout(new GridLayout(1, 3, 5, 5));
p.add(getB_login());
p.add(getB_reset());
p.add(getB_register());
p.setBounds(5, 205, 350, 50);
add(p);
}
@Override
public void run() {
new Login();
}
public JFrame getJfmm() {
return jfmm;
}
public void setJfmm(JFrame jfmm) {
this.jfmm = jfmm;
}
public JLabel getL_name() {
return l_name;
}
public void setL_name(JLabel l_name) {
this.l_name = l_name;
}
public JLabel getL_password() {
return l_password;
}
public void setL_password(JLabel l_password) {
this.l_password = l_password;
}
public JTextField getT_name() {
return t_name;
}
public void setT_name(JTextField t_name) {
this.t_name = t_name;
}
public JPasswordField getT_password() {
return t_password;
}
public void setT_password(JPasswordField t_password) {
this.t_password = t_password;
}
public JButton getB_login() {
return b_login;
}
public void setB_login(JButton b_login) {
this.b_login = b_login;
}
public JButton getB_reset() {
return b_reset;
}
public void setB_reset(JButton b_reset) {
this.b_reset = b_reset;
}
public JButton getB_register() {
return b_register;
}
public void setB_register(JButton b_register) {
this.b_register = b_register;
}
public Register getRf_1() {
return rf_1;
}
public void setRf_1(Register rf_1) {
this.rf_1 = rf_1;
}
}
|
package com.pj.offer.config.security;
import com.pj.offer.domain.model.User;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;
import java.util.Date;
@Service
public class TokenService {
@Value("${offer.jwt.expiration}")
private String expiration;
@Value("${offer.jwt.secret}")
private String secret;
public String gerarToken(Authentication authentication)
{
User logado = (User) authentication.getPrincipal();
Date hoje = new Date();
Date dateExpiration = new Date(hoje.getTime() + Long.parseLong(expiration));
return Jwts.builder()
.setIssuer("Offer").
setSubject(logado.getIdUser().toString())
.setIssuedAt(hoje)
.setExpiration(dateExpiration).
signWith(SignatureAlgorithm.HS256, secret)
.compact();
}
public boolean isValidToken(String token){
try{
Jwts.parser().setSigningKey(secret).parseClaimsJws(token);
return true;
} catch (Exception exception) {
return false;
}
}
public long getId(String token) {
Claims claims = Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
return Long.parseLong(claims.getSubject());
}
public boolean isValid(String token) {
try{
Jwts.parser().setSigningKey(this.secret).parseClaimsJws(token).getBody();
return true;
} catch (Exception exception) {
return false;
}
}
}
|
/*
* 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.component.crypto.cms;
import java.io.InputStream;
import org.apache.camel.CamelContext;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.crypto.cms.crypt.DefaultKeyTransRecipientInfo;
import org.apache.camel.component.crypto.cms.exception.CryptoCmsVerifierCertificateNotValidException;
import org.apache.camel.component.crypto.cms.sig.DefaultSignerInfo;
import org.apache.camel.component.crypto.cms.util.KeystoreUtil;
import org.apache.camel.component.crypto.cms.util.TestAttributesGeneratorProvider;
import org.apache.camel.component.crypto.cms.util.TestOriginatorInformationProvider;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.impl.DefaultCamelContext;
import org.apache.camel.support.SimpleRegistry;
import org.apache.camel.support.jsse.KeyStoreParameters;
import org.apache.camel.test.junit5.CamelTestSupport;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
public class ComponentTest extends CamelTestSupport {
private SimpleRegistry simpleReg;
@Test
public void execute() throws Exception {
String message = "Testmessage";
MockEndpoint mock = getMockEndpoint("mock:result");
mock.expectedBodiesReceived(message);
sendBody("direct:start", message.getBytes("UTF-8"));
assertMockEndpointsSatisfied();
}
@Test
public void signedWithOutdatedCert() throws Exception {
String message = "Testmessage";
MockEndpoint mock = getMockEndpoint("mock:result");
mock.expectedMessageCount(0);
MockEndpoint mockException = getMockEndpoint("mock:exception");
mockException.expectedMessageCount(1);
sendBody("direct:outdated", message.getBytes("UTF-8"));
assertMockEndpointsSatisfied();
}
@Test
public void decryptAndVerify() throws Exception {
InputStream input = this.getClass().getClassLoader().getResourceAsStream("signed_enveloped_other_CMS_vendor.binary");
assertNotNull(input);
MockEndpoint mock = getMockEndpoint("mock:result");
mock.expectedBodiesReceived("Testmessage");
sendBody("direct:decryptAndVerify", input);
assertMockEndpointsSatisfied();
input.close();
}
@Test
public void orignatorUnprotectedAttributes() throws Exception {
String message = "Testmessage";
MockEndpoint mock = getMockEndpoint("mock:result");
mock.expectedBodiesReceived(message);
sendBody("direct:encryptDecryptOriginatorAttributes", message.getBytes("UTF-8"));
assertMockEndpointsSatisfied();
}
@Override
protected CamelContext createCamelContext() throws Exception {
simpleReg = new SimpleRegistry();
CamelContext context = new DefaultCamelContext(simpleReg);
return context;
}
@Override
protected RouteBuilder createRouteBuilder() throws Exception {
return new RouteBuilder() {
@Override
public void configure() throws Exception {
context.setTracing(true);
context.setStreamCaching(true);
KeyStoreParameters keystore = KeystoreUtil.getKeyStoreParameters("system.jks");
DefaultKeyTransRecipientInfo recipient = new DefaultKeyTransRecipientInfo();
recipient.setCertificateAlias("rsa");
recipient.setKeyStoreParameters(keystore);
DefaultSignerInfo signerInfo = new DefaultSignerInfo();
signerInfo.setIncludeCertificates(true);
signerInfo.setSignatureAlgorithm("SHA256withRSA");
signerInfo.setPrivateKeyAlias("rsa");
signerInfo.setKeyStoreParameters(keystore);
DefaultSignerInfo signerInfo2 = new DefaultSignerInfo();
signerInfo2.setSignatureAlgorithm("SHA256withDSA"); // mandatory
signerInfo2.setPrivateKeyAlias("dsa");
signerInfo2.setKeyStoreParameters(keystore);
simpleReg.bind("keyStoreParameters", keystore);
simpleReg.bind("signer1", signerInfo);
simpleReg.bind("signer2", signerInfo2);
simpleReg.bind("recipient1", recipient);
onException(CryptoCmsVerifierCertificateNotValidException.class).handled(false).to("mock:exception");
from("direct:start").to("crypto-cms:sign://testsign?signer=#signer1,#signer2&includeContent=true")
.to("crypto-cms:encrypt://testencrpyt?toBase64=true&recipient=#recipient1&contentEncryptionAlgorithm=DESede/CBC/PKCS5Padding&secretKeyLength=128")
// .to("file:target/test_signed_encrypted.base64")
.to("crypto-cms:decrypt://testdecrypt?fromBase64=true&keyStoreParameters=#keyStoreParameters")
.to("crypto-cms:verify://testverify?keyStoreParameters=#keyStoreParameters").convertBodyTo(String.class).to("log:after").to("mock:result");
DefaultSignerInfo signerOutdated = new DefaultSignerInfo();
signerOutdated.setIncludeCertificates(false);
signerOutdated.setSignatureAlgorithm("SHA1withRSA");
signerOutdated.setPrivateKeyAlias("outdated");
signerOutdated.setKeyStoreParameters(keystore);
simpleReg.bind("signerOutdated", signerOutdated);
from("direct:outdated").to("crypto-cms:sign://outdated?signer=#signerOutdated&includeContent=true")
.to("crypto-cms:verify://outdated?keyStoreParameters=#keyStoreParameters").to("mock:result");
from("direct:decryptAndVerify").to("crypto-cms:decrypt://testdecrypt?fromBase64=true&keyStoreParameters=#keyStoreParameters")
.to("crypto-cms:verify://testverify?keyStoreParameters=#keyStoreParameters").to("mock:result");
TestOriginatorInformationProvider originatorInformationProvider = new TestOriginatorInformationProvider();
TestAttributesGeneratorProvider attributesGeneratorProvider = new TestAttributesGeneratorProvider();
simpleReg.bind("originatorInformationProvider1", originatorInformationProvider);
simpleReg.bind("attributesGeneratorProvider1", attributesGeneratorProvider);
from("direct:encryptDecryptOriginatorAttributes")
.to("crypto-cms:encrypt://testencrpyt?toBase64=true&recipient=#recipient1&contentEncryptionAlgorithm=DESede/CBC/PKCS5Padding&secretKeyLength=128&"
+ "originatorInformationProvider=#originatorInformationProvider1&unprotectedAttributesGeneratorProvider=#attributesGeneratorProvider1")
.to("crypto-cms:decrypt://testdecrypt?fromBase64=true&keyStoreParameters=#keyStoreParameters").to("mock:result");
}
};
}
@Test
public void wrongOperation() throws Exception {
CryptoCmsComponent c = new CryptoCmsComponent(new DefaultCamelContext());
assertThrows(IllegalStateException.class,
() -> c.createEndpoint("uri", "wrongoperation", null));
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package chapter08;
import com.jme3.bullet.collision.shapes.SphereCollisionShape;
import com.jme3.bullet.control.RigidBodyControl;
import com.jme3.math.Vector3f;
import com.jme3.scene.Geometry;
import com.jme3.scene.Node;
import com.jme3.scene.shape.Box;
import chapter08.control.ArrowFacingControl;
/**
*
* @author reden
*/
public class Arrow extends Node{
public Arrow(Vector3f location, Vector3f velocity) {
Box arrowBody = new Box(0.3f, 4f, 0.3f);
Geometry geometry = new Geometry("bullet", arrowBody);
geometry.setLocalTranslation(0f, -4f, 0f);
SphereCollisionShape arrowHeadCollision = new SphereCollisionShape(0.5f);
RigidBodyControl rigidBody = new RigidBodyControl(arrowHeadCollision, 1f);
rigidBody.setCcdMotionThreshold(0.01f);
rigidBody.setLinearVelocity(velocity);
setLocalTranslation(location);
addControl(rigidBody);
attachChild(geometry);
addControl(new ArrowFacingControl());
}
}
|
/*
* Created on Jun 8, 2006
*
* To change the template for this generated file go to
* Window>Preferences>Java>Code Generation>Code and Comments
*/
package biomight.chemistry;
import java.util.ArrayList;
import biomight.BioMightBase;
import biomight.Constants;
import biomight.chemistry.aminoacid.Alanine;
import biomight.chemistry.aminoacid.Arginine;
import biomight.chemistry.aminoacid.Asparagine;
import biomight.chemistry.aminoacid.AsparticAcid;
import biomight.chemistry.aminoacid.Cysteine;
import biomight.chemistry.aminoacid.GlutamicAcid;
import biomight.chemistry.aminoacid.Glutamine;
import biomight.chemistry.aminoacid.Glycine;
import biomight.chemistry.aminoacid.Histidine;
import biomight.chemistry.aminoacid.IsoLeucine;
import biomight.chemistry.aminoacid.Leucine;
import biomight.chemistry.aminoacid.Lysine;
import biomight.chemistry.aminoacid.Methionine;
import biomight.chemistry.aminoacid.Phenylalanine;
import biomight.chemistry.aminoacid.Proline;
import biomight.chemistry.compound.*;
import biomight.chemistry.elements.*;
import biomight.view.BioMightMethodView;
import biomight.view.BioMightPosition;
import biomight.view.BioMightScale;
/**
* @author SurferJim
*
* To change the template for this generated type comment go to
* Window>Preferences>Java>Code Generation>Code and Comments
*/
public class MoleculeBuilder extends BioMightBase {
private Carboxyl carboxyl;
private Amine amine;
private Calcium calcium;
private Carbon carbon;
private Hydrogen hydrogen;
private Nitrogen nitrogen;
private Oxygen oxygen;
private Sulfur sulfur;
private Object base;
public MoleculeBuilder()
{
}
public MoleculeBuilder(String formula, String parentID, ArrayList<BioMightMethodView> bioMightMethods){
// Run through the forumla string
// Use introspection to get the associated Java Object
// Store it in the chain. The chain is a mathematical probable relationship
// given the right soup
int localVP = Constants.VIEW_HAWKEYE;
int localLOD = Constants.MAG1X;
BioMightScale bioScale = new BioMightScale("0.00, 0.00, 0.00");
BioMightPosition bioPos = new BioMightPosition("0.00, 0.00, 0.00");
String bioTemplate="Molecules.x3d";
String[] myAtoms = formula.split("-");
for (int i=0; i<myAtoms.length; i++){
if (myAtoms[i].equals("C")) {
//carbon = new Carbon(parentID, bioMightMethods);
carbon = new Carbon(localVP, localLOD, null, null, bioMightMethods);
initProperty(Constants.CarbonRef, Constants.Carbon, Constants.CarbonRef, carbon.getComponentID(), bioPos, bioScale, Constants.SINGLE_COMPONENT, bioTemplate, false);
System.out.println("In Elements - Carbon is complete");
}
if (myAtoms[i].equals("Ca")) {
//Calcium calcium = new Calcium(parentID, bioMightMethods);
}
else if (myAtoms[i].equals("H")) {
//Hydrogen hydrogen = new Hydrogen(parentID, bioMightMethods);
}
else if (myAtoms[i].equals("N")) {
//Nitrogen nitrogen = new Nitrogen(parentID, bioMightMethods);
}
else if (myAtoms[i].equals("O")) {
//Oxygen oxygen = new Oxygen(parentID, bioMightMethods);
}
else
{}
}
}
}
|
// Automatically generated by xdrgen
// DO NOT EDIT or your changes may be overwritten
package io.digitalbits.sdk.xdr;
import java.io.IOException;
import com.google.common.base.Objects;
import java.util.Arrays;
// === xdr source ============================================================
// struct TransactionV0Envelope
// {
// TransactionV0 tx;
// /* Each decorated signature is a signature over the SHA256 hash of
// * a TransactionSignaturePayload */
// DecoratedSignature signatures<20>;
// };
// ===========================================================================
public class TransactionV0Envelope implements XdrElement {
public TransactionV0Envelope () {}
private TransactionV0 tx;
public TransactionV0 getTx() {
return this.tx;
}
public void setTx(TransactionV0 value) {
this.tx = value;
}
private DecoratedSignature[] signatures;
public DecoratedSignature[] getSignatures() {
return this.signatures;
}
public void setSignatures(DecoratedSignature[] value) {
this.signatures = value;
}
public static void encode(XdrDataOutputStream stream, TransactionV0Envelope encodedTransactionV0Envelope) throws IOException{
TransactionV0.encode(stream, encodedTransactionV0Envelope.tx);
int signaturessize = encodedTransactionV0Envelope.getSignatures().length;
stream.writeInt(signaturessize);
for (int i = 0; i < signaturessize; i++) {
DecoratedSignature.encode(stream, encodedTransactionV0Envelope.signatures[i]);
}
}
public void encode(XdrDataOutputStream stream) throws IOException {
encode(stream, this);
}
public static TransactionV0Envelope decode(XdrDataInputStream stream) throws IOException {
TransactionV0Envelope decodedTransactionV0Envelope = new TransactionV0Envelope();
decodedTransactionV0Envelope.tx = TransactionV0.decode(stream);
int signaturessize = stream.readInt();
decodedTransactionV0Envelope.signatures = new DecoratedSignature[signaturessize];
for (int i = 0; i < signaturessize; i++) {
decodedTransactionV0Envelope.signatures[i] = DecoratedSignature.decode(stream);
}
return decodedTransactionV0Envelope;
}
@Override
public int hashCode() {
return Objects.hashCode(this.tx, Arrays.hashCode(this.signatures));
}
@Override
public boolean equals(Object object) {
if (!(object instanceof TransactionV0Envelope)) {
return false;
}
TransactionV0Envelope other = (TransactionV0Envelope) object;
return Objects.equal(this.tx, other.tx) && Arrays.equals(this.signatures, other.signatures);
}
public static final class Builder {
private TransactionV0 tx;
private DecoratedSignature[] signatures;
public Builder tx(TransactionV0 tx) {
this.tx = tx;
return this;
}
public Builder signatures(DecoratedSignature[] signatures) {
this.signatures = signatures;
return this;
}
public TransactionV0Envelope build() {
TransactionV0Envelope val = new TransactionV0Envelope();
val.setTx(tx);
val.setSignatures(signatures);
return val;
}
}
}
|
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.documentapi.messagebus.protocol;
import com.yahoo.messagebus.EmptyReply;
import com.yahoo.messagebus.routing.RoutingContext;
/**
* This policy assigns an error supplied at constructor time to the routing context when {@link #select(RoutingContext)}
* is invoked. This is useful for returning error states to the client instead of those auto-generated by mbus when a
* routing policy can not be created.
*
* @author Simon Thoresen Hult
*/
public class ErrorPolicy implements DocumentProtocolRoutingPolicy {
private final String msg;
/**
* Creates a new policy that will assign an {@link EmptyReply} with the given error to all routing contexts that
* invoke {@link #select(RoutingContext)}.
*
* @param msg The message of the error to assign.
*/
public ErrorPolicy(String msg) {
this.msg = msg;
}
public void select(RoutingContext ctx) {
ctx.setError(DocumentProtocol.ERROR_POLICY_FAILURE, msg);
}
public void merge(RoutingContext ctx) {
throw new AssertionError("Routing should not pass terminated selection.");
}
public void destroy() {
}
}
|
/**
* Copyright 2015-2017 Boundless, http://boundlessgeo.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.boundlessgeo.spatialconnect.geometries;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.Polygon;
public class SCPolygon extends SCGeometry
{
public SCPolygon(Geometry geometry)
{
super(geometry);
}
@JsonIgnore
public Polygon getJTS()
{
return (Polygon)this.geometry;
}
@Override
public String toString()
{
return geometry.toText();
}
}
|
import java.util.Locale;
import java.util.Scanner;
public class Main_2 {
public static void main(String[] args) {
//EXERCICIO 02
Scanner sc = new Scanner(System.in);
Locale.setDefault(Locale.US);
double area , parame , raio ;
parame = 3.14159;
System.out.print("Digite o valor de Raio: ");
raio = sc.nextDouble();
area = parame * (raio * raio);
System.out.printf("Area e igual a ... %.4f %n" , area);
sc.close();
}
}
|
/**
* Copyright 2016 William Van Woensel
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.
*
*
* @author wvw
*
*/
package wvw.mobibench.service.preproc.ont.binarize;
import java.io.IOException;
import java.util.List;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.Property;
import com.hp.hpl.jena.rdf.model.RDFNode;
import com.hp.hpl.jena.rdf.model.Resource;
import com.hp.hpl.jena.rdf.model.Statement;
import wvw.mobibench.service.preproc.PreProcessConfig;
import wvw.mobibench.service.preproc.PreProcessConfig.Ontology;
import wvw.mobibench.service.preproc.PreProcessException;
import wvw.mobibench.service.preproc.PreProcessResults;
import wvw.mobibench.service.preproc.PreProcessTypes;
import wvw.mobibench.service.preproc.ont.OntologyBasedPreProcessor;
import wvw.mobibench.service.res.ServiceResources;
public class BinarizePreProcessor extends OntologyBasedPreProcessor {
private int newCtr = 0;
private int lstCtr = 0;
public BinarizePreProcessor(ServiceResources res) {
super(res);
}
public PreProcessResults doPreprocess(PreProcessConfig config)
throws PreProcessException {
Ontology ontology = config.getOntology();
try {
String ontologyStr = normalizeOntology(ontology.getContent(),
ontology.getSyntax());
String rulesStr = res.getContents(rootPath + "binary/rules.spin");
return new PreProcessResults(rulesStr, ontologyStr);
} catch (IOException e) {
throw new PreProcessException(e);
}
}
public PreProcessTypes getType() {
return PreProcessTypes.BINARIZE;
}
private String normalizeOntology(String ontology, String syntax)
throws IOException {
Model m = loadModel(ontology, syntax);
normalize(intersectionOf, m);
normalize(propertyChainAxiom, m);
// has-key not supported
return getData(m);
}
private void normalize(Property p, Model m) {
List<Statement> stmts = copyStmts(
m.listStatements(null, p, (RDFNode) null));
for (Statement stmt : stmts) {
Resource list = stmt.getObject().asResource();
List<Resource> chain = collectChain(list, m);
normalize(p, chain, m);
}
}
private void normalize(Property p, List<Resource> chain, Model m) {
normalize(p, chain, 0, m);
}
private void normalize(Property p, List<Resource> chain, int idx, Model m) {
if (chain.size() - 2 - idx == 0)
return;
Resource l1 = chain.get(idx);
Resource l2 = chain.get(idx + 1);
Resource nl = m.createResource(
"http://niche.cs.dal.ca/owl/normalize/L" + lstCtr++);
Resource ne = m.createResource(
"http://niche.cs.dal.ca/owl/normalize/N" + newCtr++);
l1.removeAll(rest);
l1.addProperty(rest, nl);
nl.addProperty(first, ne);
nl.addProperty(rest, nil);
ne.addProperty(p, l2);
normalize(p, chain, idx + 1, m);
}
}
|
package ru.taximaxim.codekeeper.apgdiff.sql;
import static ru.taximaxim.codekeeper.apgdiff.sql.Keyword.KeywordCategory.COL_NAME_KEYWORD;
import static ru.taximaxim.codekeeper.apgdiff.sql.Keyword.KeywordCategory.RESERVED_KEYWORD;
import static ru.taximaxim.codekeeper.apgdiff.sql.Keyword.KeywordCategory.TYPE_FUNC_NAME_KEYWORD;
import static ru.taximaxim.codekeeper.apgdiff.sql.Keyword.KeywordCategory.UNRESERVED_KEYWORD;
import java.util.Collections;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
/**
* {@link #KEYWORDS} list maintenance:<br><br>
* <ol>
* <li>Copy code from
* <a href='https://github.com/postgres/postgres/blob/REL9_6_STABLE/src/include/parser/kwlist.h'>
* kwlist.h</a>, use your desired stable branch.</li>
* <li>Paste it into {@link #addKeywords(Map)}, replacing the code there.</li>
* <li>In pasted code, replace <code>PG_KEYWORD\(("\w+"), \w+, (\w+)\)</code> by
* <code>keywords.put($1, new Keyword($1, $2));</code> using regular expressions.</li>
* </ol>
*
* @author levsha_aa
*/
public class Keyword {
public static final Map<String, Keyword> KEYWORDS;
/**
* <a href='https://github.com/postgres/postgres/blob/REL9_6_STABLE/src/include/common/keywords.h'>
* keywords.h</a>
*/
public enum KeywordCategory {
UNRESERVED_KEYWORD, COL_NAME_KEYWORD, TYPE_FUNC_NAME_KEYWORD, RESERVED_KEYWORD
}
/*
* Regex search and replacement strings for kwlist.h -> Java transformation:
*
* PG_KEYWORD\(("\w+"), \w+, (\w+)\)
* keywords.put($1, new Keyword($1, $2));
*/
private static void addKeywords(Map<String, Keyword> keywords) {
keywords.put("abort", new Keyword("abort", UNRESERVED_KEYWORD));
keywords.put("absolute", new Keyword("absolute", UNRESERVED_KEYWORD));
keywords.put("access", new Keyword("access", UNRESERVED_KEYWORD));
keywords.put("action", new Keyword("action", UNRESERVED_KEYWORD));
keywords.put("add", new Keyword("add", UNRESERVED_KEYWORD));
keywords.put("admin", new Keyword("admin", UNRESERVED_KEYWORD));
keywords.put("after", new Keyword("after", UNRESERVED_KEYWORD));
keywords.put("aggregate", new Keyword("aggregate", UNRESERVED_KEYWORD));
keywords.put("all", new Keyword("all", RESERVED_KEYWORD));
keywords.put("also", new Keyword("also", UNRESERVED_KEYWORD));
keywords.put("alter", new Keyword("alter", UNRESERVED_KEYWORD));
keywords.put("always", new Keyword("always", UNRESERVED_KEYWORD));
keywords.put("analyse", new Keyword("analyse", RESERVED_KEYWORD)); /* British spelling */
keywords.put("analyze", new Keyword("analyze", RESERVED_KEYWORD));
keywords.put("and", new Keyword("and", RESERVED_KEYWORD));
keywords.put("any", new Keyword("any", RESERVED_KEYWORD));
keywords.put("array", new Keyword("array", RESERVED_KEYWORD));
keywords.put("as", new Keyword("as", RESERVED_KEYWORD));
keywords.put("asc", new Keyword("asc", RESERVED_KEYWORD));
keywords.put("assertion", new Keyword("assertion", UNRESERVED_KEYWORD));
keywords.put("assignment", new Keyword("assignment", UNRESERVED_KEYWORD));
keywords.put("asymmetric", new Keyword("asymmetric", RESERVED_KEYWORD));
keywords.put("at", new Keyword("at", UNRESERVED_KEYWORD));
keywords.put("attach", new Keyword("attach", UNRESERVED_KEYWORD));
keywords.put("attribute", new Keyword("attribute", UNRESERVED_KEYWORD));
keywords.put("authorization", new Keyword("authorization", TYPE_FUNC_NAME_KEYWORD));
keywords.put("backward", new Keyword("backward", UNRESERVED_KEYWORD));
keywords.put("before", new Keyword("before", UNRESERVED_KEYWORD));
keywords.put("begin", new Keyword("begin", UNRESERVED_KEYWORD));
keywords.put("between", new Keyword("between", COL_NAME_KEYWORD));
keywords.put("bigint", new Keyword("bigint", COL_NAME_KEYWORD));
keywords.put("binary", new Keyword("binary", TYPE_FUNC_NAME_KEYWORD));
keywords.put("bit", new Keyword("bit", COL_NAME_KEYWORD));
keywords.put("boolean", new Keyword("boolean", COL_NAME_KEYWORD));
keywords.put("both", new Keyword("both", RESERVED_KEYWORD));
keywords.put("by", new Keyword("by", UNRESERVED_KEYWORD));
keywords.put("cache", new Keyword("cache", UNRESERVED_KEYWORD));
keywords.put("call", new Keyword("call", UNRESERVED_KEYWORD));
keywords.put("called", new Keyword("called", UNRESERVED_KEYWORD));
keywords.put("cascade", new Keyword("cascade", UNRESERVED_KEYWORD));
keywords.put("cascaded", new Keyword("cascaded", UNRESERVED_KEYWORD));
keywords.put("case", new Keyword("case", RESERVED_KEYWORD));
keywords.put("cast", new Keyword("cast", RESERVED_KEYWORD));
keywords.put("catalog", new Keyword("catalog", UNRESERVED_KEYWORD));
keywords.put("chain", new Keyword("chain", UNRESERVED_KEYWORD));
keywords.put("char", new Keyword("char", COL_NAME_KEYWORD));
keywords.put("character", new Keyword("character", COL_NAME_KEYWORD));
keywords.put("characteristics", new Keyword("characteristics", UNRESERVED_KEYWORD));
keywords.put("check", new Keyword("check", RESERVED_KEYWORD));
keywords.put("checkpoint", new Keyword("checkpoint", UNRESERVED_KEYWORD));
keywords.put("class", new Keyword("class", UNRESERVED_KEYWORD));
keywords.put("close", new Keyword("close", UNRESERVED_KEYWORD));
keywords.put("cluster", new Keyword("cluster", UNRESERVED_KEYWORD));
keywords.put("coalesce", new Keyword("coalesce", COL_NAME_KEYWORD));
keywords.put("collate", new Keyword("collate", RESERVED_KEYWORD));
keywords.put("collation", new Keyword("collation", TYPE_FUNC_NAME_KEYWORD));
keywords.put("column", new Keyword("column", RESERVED_KEYWORD));
keywords.put("columns", new Keyword("columns", UNRESERVED_KEYWORD));
keywords.put("comment", new Keyword("comment", UNRESERVED_KEYWORD));
keywords.put("comments", new Keyword("comments", UNRESERVED_KEYWORD));
keywords.put("commit", new Keyword("commit", UNRESERVED_KEYWORD));
keywords.put("committed", new Keyword("committed", UNRESERVED_KEYWORD));
keywords.put("concurrently", new Keyword("concurrently", TYPE_FUNC_NAME_KEYWORD));
keywords.put("configuration", new Keyword("configuration", UNRESERVED_KEYWORD));
keywords.put("conflict", new Keyword("conflict", UNRESERVED_KEYWORD));
keywords.put("connection", new Keyword("connection", UNRESERVED_KEYWORD));
keywords.put("constraint", new Keyword("constraint", RESERVED_KEYWORD));
keywords.put("constraints", new Keyword("constraints", UNRESERVED_KEYWORD));
keywords.put("content", new Keyword("content", UNRESERVED_KEYWORD));
keywords.put("continue", new Keyword("continue", UNRESERVED_KEYWORD));
keywords.put("conversion", new Keyword("conversion", UNRESERVED_KEYWORD));
keywords.put("copy", new Keyword("copy", UNRESERVED_KEYWORD));
keywords.put("cost", new Keyword("cost", UNRESERVED_KEYWORD));
keywords.put("create", new Keyword("create", RESERVED_KEYWORD));
keywords.put("cross", new Keyword("cross", TYPE_FUNC_NAME_KEYWORD));
keywords.put("csv", new Keyword("csv", UNRESERVED_KEYWORD));
keywords.put("cube", new Keyword("cube", UNRESERVED_KEYWORD));
keywords.put("current", new Keyword("current", UNRESERVED_KEYWORD));
keywords.put("current_catalog", new Keyword("current_catalog", RESERVED_KEYWORD));
keywords.put("current_date", new Keyword("current_date", RESERVED_KEYWORD));
keywords.put("current_role", new Keyword("current_role", RESERVED_KEYWORD));
keywords.put("current_schema", new Keyword("current_schema", TYPE_FUNC_NAME_KEYWORD));
keywords.put("current_time", new Keyword("current_time", RESERVED_KEYWORD));
keywords.put("current_timestamp", new Keyword("current_timestamp", RESERVED_KEYWORD));
keywords.put("current_user", new Keyword("current_user", RESERVED_KEYWORD));
keywords.put("cursor", new Keyword("cursor", UNRESERVED_KEYWORD));
keywords.put("cycle", new Keyword("cycle", UNRESERVED_KEYWORD));
keywords.put("data", new Keyword("data", UNRESERVED_KEYWORD));
keywords.put("database", new Keyword("database", UNRESERVED_KEYWORD));
keywords.put("day", new Keyword("day", UNRESERVED_KEYWORD));
keywords.put("deallocate", new Keyword("deallocate", UNRESERVED_KEYWORD));
keywords.put("dec", new Keyword("dec", COL_NAME_KEYWORD));
keywords.put("decimal", new Keyword("decimal", COL_NAME_KEYWORD));
keywords.put("declare", new Keyword("declare", UNRESERVED_KEYWORD));
keywords.put("default", new Keyword("default", RESERVED_KEYWORD));
keywords.put("defaults", new Keyword("defaults", UNRESERVED_KEYWORD));
keywords.put("deferrable", new Keyword("deferrable", RESERVED_KEYWORD));
keywords.put("deferred", new Keyword("deferred", UNRESERVED_KEYWORD));
keywords.put("definer", new Keyword("definer", UNRESERVED_KEYWORD));
keywords.put("delete", new Keyword("delete", UNRESERVED_KEYWORD));
keywords.put("delimiter", new Keyword("delimiter", UNRESERVED_KEYWORD));
keywords.put("delimiters", new Keyword("delimiters", UNRESERVED_KEYWORD));
keywords.put("depends", new Keyword("depends", UNRESERVED_KEYWORD));
keywords.put("desc", new Keyword("desc", RESERVED_KEYWORD));
keywords.put("detach", new Keyword("detach", UNRESERVED_KEYWORD));
keywords.put("dictionary", new Keyword("dictionary", UNRESERVED_KEYWORD));
keywords.put("disable", new Keyword("disable", UNRESERVED_KEYWORD));
keywords.put("discard", new Keyword("discard", UNRESERVED_KEYWORD));
keywords.put("distinct", new Keyword("distinct", RESERVED_KEYWORD));
keywords.put("do", new Keyword("do", RESERVED_KEYWORD));
keywords.put("document", new Keyword("document", UNRESERVED_KEYWORD));
keywords.put("domain", new Keyword("domain", UNRESERVED_KEYWORD));
keywords.put("double", new Keyword("double", UNRESERVED_KEYWORD));
keywords.put("drop", new Keyword("drop", UNRESERVED_KEYWORD));
keywords.put("each", new Keyword("each", UNRESERVED_KEYWORD));
keywords.put("else", new Keyword("else", RESERVED_KEYWORD));
keywords.put("enable", new Keyword("enable", UNRESERVED_KEYWORD));
keywords.put("encoding", new Keyword("encoding", UNRESERVED_KEYWORD));
keywords.put("encrypted", new Keyword("encrypted", UNRESERVED_KEYWORD));
keywords.put("end", new Keyword("end", RESERVED_KEYWORD));
keywords.put("enum", new Keyword("enum", UNRESERVED_KEYWORD));
keywords.put("escape", new Keyword("escape", UNRESERVED_KEYWORD));
keywords.put("event", new Keyword("event", UNRESERVED_KEYWORD));
keywords.put("except", new Keyword("except", RESERVED_KEYWORD));
keywords.put("exclude", new Keyword("exclude", UNRESERVED_KEYWORD));
keywords.put("excluding", new Keyword("excluding", UNRESERVED_KEYWORD));
keywords.put("exclusive", new Keyword("exclusive", UNRESERVED_KEYWORD));
keywords.put("execute", new Keyword("execute", UNRESERVED_KEYWORD));
keywords.put("exists", new Keyword("exists", COL_NAME_KEYWORD));
keywords.put("explain", new Keyword("explain", UNRESERVED_KEYWORD));
keywords.put("extension", new Keyword("extension", UNRESERVED_KEYWORD));
keywords.put("external", new Keyword("external", UNRESERVED_KEYWORD));
keywords.put("extract", new Keyword("extract", COL_NAME_KEYWORD));
keywords.put("false", new Keyword("false", RESERVED_KEYWORD));
keywords.put("family", new Keyword("family", UNRESERVED_KEYWORD));
keywords.put("fetch", new Keyword("fetch", RESERVED_KEYWORD));
keywords.put("filter", new Keyword("filter", UNRESERVED_KEYWORD));
keywords.put("first", new Keyword("first", UNRESERVED_KEYWORD));
keywords.put("float", new Keyword("float", COL_NAME_KEYWORD));
keywords.put("following", new Keyword("following", UNRESERVED_KEYWORD));
keywords.put("for", new Keyword("for", RESERVED_KEYWORD));
keywords.put("force", new Keyword("force", UNRESERVED_KEYWORD));
keywords.put("foreign", new Keyword("foreign", RESERVED_KEYWORD));
keywords.put("forward", new Keyword("forward", UNRESERVED_KEYWORD));
keywords.put("freeze", new Keyword("freeze", TYPE_FUNC_NAME_KEYWORD));
keywords.put("from", new Keyword("from", RESERVED_KEYWORD));
keywords.put("full", new Keyword("full", TYPE_FUNC_NAME_KEYWORD));
keywords.put("function", new Keyword("function", UNRESERVED_KEYWORD));
keywords.put("functions", new Keyword("functions", UNRESERVED_KEYWORD));
keywords.put("generated", new Keyword("generated", UNRESERVED_KEYWORD));
keywords.put("global", new Keyword("global", UNRESERVED_KEYWORD));
keywords.put("grant", new Keyword("grant", RESERVED_KEYWORD));
keywords.put("granted", new Keyword("granted", UNRESERVED_KEYWORD));
keywords.put("greatest", new Keyword("greatest", COL_NAME_KEYWORD));
keywords.put("group", new Keyword("group", RESERVED_KEYWORD));
keywords.put("grouping", new Keyword("grouping", COL_NAME_KEYWORD));
keywords.put("groups", new Keyword("groups", UNRESERVED_KEYWORD));
keywords.put("handler", new Keyword("handler", UNRESERVED_KEYWORD));
keywords.put("having", new Keyword("having", RESERVED_KEYWORD));
keywords.put("header", new Keyword("header", UNRESERVED_KEYWORD));
keywords.put("hold", new Keyword("hold", UNRESERVED_KEYWORD));
keywords.put("hour", new Keyword("hour", UNRESERVED_KEYWORD));
keywords.put("identity", new Keyword("identity", UNRESERVED_KEYWORD));
keywords.put("if", new Keyword("if", UNRESERVED_KEYWORD));
keywords.put("ilike", new Keyword("ilike", TYPE_FUNC_NAME_KEYWORD));
keywords.put("immediate", new Keyword("immediate", UNRESERVED_KEYWORD));
keywords.put("immutable", new Keyword("immutable", UNRESERVED_KEYWORD));
keywords.put("implicit", new Keyword("implicit", UNRESERVED_KEYWORD));
keywords.put("import", new Keyword("import", UNRESERVED_KEYWORD));
keywords.put("in", new Keyword("in", RESERVED_KEYWORD));
keywords.put("include", new Keyword("include", UNRESERVED_KEYWORD));
keywords.put("including", new Keyword("including", UNRESERVED_KEYWORD));
keywords.put("increment", new Keyword("increment", UNRESERVED_KEYWORD));
keywords.put("index", new Keyword("index", UNRESERVED_KEYWORD));
keywords.put("indexes", new Keyword("indexes", UNRESERVED_KEYWORD));
keywords.put("inherit", new Keyword("inherit", UNRESERVED_KEYWORD));
keywords.put("inherits", new Keyword("inherits", UNRESERVED_KEYWORD));
keywords.put("initially", new Keyword("initially", RESERVED_KEYWORD));
keywords.put("inline", new Keyword("inline", UNRESERVED_KEYWORD));
keywords.put("inner", new Keyword("inner", TYPE_FUNC_NAME_KEYWORD));
keywords.put("inout", new Keyword("inout", COL_NAME_KEYWORD));
keywords.put("input", new Keyword("input", UNRESERVED_KEYWORD));
keywords.put("insensitive", new Keyword("insensitive", UNRESERVED_KEYWORD));
keywords.put("insert", new Keyword("insert", UNRESERVED_KEYWORD));
keywords.put("instead", new Keyword("instead", UNRESERVED_KEYWORD));
keywords.put("int", new Keyword("int", COL_NAME_KEYWORD));
keywords.put("integer", new Keyword("integer", COL_NAME_KEYWORD));
keywords.put("intersect", new Keyword("intersect", RESERVED_KEYWORD));
keywords.put("interval", new Keyword("interval", COL_NAME_KEYWORD));
keywords.put("into", new Keyword("into", RESERVED_KEYWORD));
keywords.put("invoker", new Keyword("invoker", UNRESERVED_KEYWORD));
keywords.put("is", new Keyword("is", TYPE_FUNC_NAME_KEYWORD));
keywords.put("isnull", new Keyword("isnull", TYPE_FUNC_NAME_KEYWORD));
keywords.put("isolation", new Keyword("isolation", UNRESERVED_KEYWORD));
keywords.put("join", new Keyword("join", TYPE_FUNC_NAME_KEYWORD));
keywords.put("key", new Keyword("key", UNRESERVED_KEYWORD));
keywords.put("label", new Keyword("label", UNRESERVED_KEYWORD));
keywords.put("language", new Keyword("language", UNRESERVED_KEYWORD));
keywords.put("large", new Keyword("large", UNRESERVED_KEYWORD));
keywords.put("last", new Keyword("last", UNRESERVED_KEYWORD));
keywords.put("lateral", new Keyword("lateral", RESERVED_KEYWORD));
keywords.put("leading", new Keyword("leading", RESERVED_KEYWORD));
keywords.put("leakproof", new Keyword("leakproof", UNRESERVED_KEYWORD));
keywords.put("least", new Keyword("least", COL_NAME_KEYWORD));
keywords.put("left", new Keyword("left", TYPE_FUNC_NAME_KEYWORD));
keywords.put("level", new Keyword("level", UNRESERVED_KEYWORD));
keywords.put("like", new Keyword("like", TYPE_FUNC_NAME_KEYWORD));
keywords.put("limit", new Keyword("limit", RESERVED_KEYWORD));
keywords.put("listen", new Keyword("listen", UNRESERVED_KEYWORD));
keywords.put("load", new Keyword("load", UNRESERVED_KEYWORD));
keywords.put("local", new Keyword("local", UNRESERVED_KEYWORD));
keywords.put("localtime", new Keyword("localtime", RESERVED_KEYWORD));
keywords.put("localtimestamp", new Keyword("localtimestamp", RESERVED_KEYWORD));
keywords.put("location", new Keyword("location", UNRESERVED_KEYWORD));
keywords.put("lock", new Keyword("lock", UNRESERVED_KEYWORD));
keywords.put("locked", new Keyword("locked", UNRESERVED_KEYWORD));
keywords.put("logged", new Keyword("logged", UNRESERVED_KEYWORD));
keywords.put("mapping", new Keyword("mapping", UNRESERVED_KEYWORD));
keywords.put("match", new Keyword("match", UNRESERVED_KEYWORD));
keywords.put("materialized", new Keyword("materialized", UNRESERVED_KEYWORD));
keywords.put("maxvalue", new Keyword("maxvalue", UNRESERVED_KEYWORD));
keywords.put("method", new Keyword("method", UNRESERVED_KEYWORD));
keywords.put("minute", new Keyword("minute", UNRESERVED_KEYWORD));
keywords.put("minvalue", new Keyword("minvalue", UNRESERVED_KEYWORD));
keywords.put("mode", new Keyword("mode", UNRESERVED_KEYWORD));
keywords.put("month", new Keyword("month", UNRESERVED_KEYWORD));
keywords.put("move", new Keyword("move", UNRESERVED_KEYWORD));
keywords.put("name", new Keyword("name", UNRESERVED_KEYWORD));
keywords.put("names", new Keyword("names", UNRESERVED_KEYWORD));
keywords.put("national", new Keyword("national", COL_NAME_KEYWORD));
keywords.put("natural", new Keyword("natural", TYPE_FUNC_NAME_KEYWORD));
keywords.put("nchar", new Keyword("nchar", COL_NAME_KEYWORD));
keywords.put("new", new Keyword("new", UNRESERVED_KEYWORD));
keywords.put("next", new Keyword("next", UNRESERVED_KEYWORD));
keywords.put("no", new Keyword("no", UNRESERVED_KEYWORD));
keywords.put("none", new Keyword("none", COL_NAME_KEYWORD));
keywords.put("not", new Keyword("not", RESERVED_KEYWORD));
keywords.put("nothing", new Keyword("nothing", UNRESERVED_KEYWORD));
keywords.put("notify", new Keyword("notify", UNRESERVED_KEYWORD));
keywords.put("notnull", new Keyword("notnull", TYPE_FUNC_NAME_KEYWORD));
keywords.put("nowait", new Keyword("nowait", UNRESERVED_KEYWORD));
keywords.put("null", new Keyword("null", RESERVED_KEYWORD));
keywords.put("nullif", new Keyword("nullif", COL_NAME_KEYWORD));
keywords.put("nulls", new Keyword("nulls", UNRESERVED_KEYWORD));
keywords.put("numeric", new Keyword("numeric", COL_NAME_KEYWORD));
keywords.put("object", new Keyword("object", UNRESERVED_KEYWORD));
keywords.put("of", new Keyword("of", UNRESERVED_KEYWORD));
keywords.put("off", new Keyword("off", UNRESERVED_KEYWORD));
keywords.put("offset", new Keyword("offset", RESERVED_KEYWORD));
keywords.put("oids", new Keyword("oids", UNRESERVED_KEYWORD));
keywords.put("old", new Keyword("old", UNRESERVED_KEYWORD));
keywords.put("on", new Keyword("on", RESERVED_KEYWORD));
keywords.put("only", new Keyword("only", RESERVED_KEYWORD));
keywords.put("operator", new Keyword("operator", UNRESERVED_KEYWORD));
keywords.put("option", new Keyword("option", UNRESERVED_KEYWORD));
keywords.put("options", new Keyword("options", UNRESERVED_KEYWORD));
keywords.put("or", new Keyword("or", RESERVED_KEYWORD));
keywords.put("order", new Keyword("order", RESERVED_KEYWORD));
keywords.put("ordinality", new Keyword("ordinality", UNRESERVED_KEYWORD));
keywords.put("others", new Keyword("others", UNRESERVED_KEYWORD));
keywords.put("out", new Keyword("out", COL_NAME_KEYWORD));
keywords.put("outer", new Keyword("outer", TYPE_FUNC_NAME_KEYWORD));
keywords.put("over", new Keyword("over", UNRESERVED_KEYWORD));
keywords.put("overlaps", new Keyword("overlaps", TYPE_FUNC_NAME_KEYWORD));
keywords.put("overlay", new Keyword("overlay", COL_NAME_KEYWORD));
keywords.put("overriding", new Keyword("overriding", UNRESERVED_KEYWORD));
keywords.put("owned", new Keyword("owned", UNRESERVED_KEYWORD));
keywords.put("owner", new Keyword("owner", UNRESERVED_KEYWORD));
keywords.put("parallel", new Keyword("parallel", UNRESERVED_KEYWORD));
keywords.put("parser", new Keyword("parser", UNRESERVED_KEYWORD));
keywords.put("partial", new Keyword("partial", UNRESERVED_KEYWORD));
keywords.put("partition", new Keyword("partition", UNRESERVED_KEYWORD));
keywords.put("passing", new Keyword("passing", UNRESERVED_KEYWORD));
keywords.put("password", new Keyword("password", UNRESERVED_KEYWORD));
keywords.put("placing", new Keyword("placing", RESERVED_KEYWORD));
keywords.put("plans", new Keyword("plans", UNRESERVED_KEYWORD));
keywords.put("policy", new Keyword("policy", UNRESERVED_KEYWORD));
keywords.put("position", new Keyword("position", COL_NAME_KEYWORD));
keywords.put("preceding", new Keyword("preceding", UNRESERVED_KEYWORD));
keywords.put("precision", new Keyword("precision", COL_NAME_KEYWORD));
keywords.put("prepare", new Keyword("prepare", UNRESERVED_KEYWORD));
keywords.put("prepared", new Keyword("prepared", UNRESERVED_KEYWORD));
keywords.put("preserve", new Keyword("preserve", UNRESERVED_KEYWORD));
keywords.put("primary", new Keyword("primary", RESERVED_KEYWORD));
keywords.put("prior", new Keyword("prior", UNRESERVED_KEYWORD));
keywords.put("privileges", new Keyword("privileges", UNRESERVED_KEYWORD));
keywords.put("procedural", new Keyword("procedural", UNRESERVED_KEYWORD));
keywords.put("procedure", new Keyword("procedure", UNRESERVED_KEYWORD));
keywords.put("procedures", new Keyword("procedures", UNRESERVED_KEYWORD));
keywords.put("program", new Keyword("program", UNRESERVED_KEYWORD));
keywords.put("publication", new Keyword("publication", UNRESERVED_KEYWORD));
keywords.put("quote", new Keyword("quote", UNRESERVED_KEYWORD));
keywords.put("range", new Keyword("range", UNRESERVED_KEYWORD));
keywords.put("read", new Keyword("read", UNRESERVED_KEYWORD));
keywords.put("real", new Keyword("real", COL_NAME_KEYWORD));
keywords.put("reassign", new Keyword("reassign", UNRESERVED_KEYWORD));
keywords.put("recheck", new Keyword("recheck", UNRESERVED_KEYWORD));
keywords.put("recursive", new Keyword("recursive", UNRESERVED_KEYWORD));
keywords.put("ref", new Keyword("ref", UNRESERVED_KEYWORD));
keywords.put("references", new Keyword("references", RESERVED_KEYWORD));
keywords.put("referencing", new Keyword("referencing", UNRESERVED_KEYWORD));
keywords.put("refresh", new Keyword("refresh", UNRESERVED_KEYWORD));
keywords.put("reindex", new Keyword("reindex", UNRESERVED_KEYWORD));
keywords.put("relative", new Keyword("relative", UNRESERVED_KEYWORD));
keywords.put("release", new Keyword("release", UNRESERVED_KEYWORD));
keywords.put("rename", new Keyword("rename", UNRESERVED_KEYWORD));
keywords.put("repeatable", new Keyword("repeatable", UNRESERVED_KEYWORD));
keywords.put("replace", new Keyword("replace", UNRESERVED_KEYWORD));
keywords.put("replica", new Keyword("replica", UNRESERVED_KEYWORD));
keywords.put("reset", new Keyword("reset", UNRESERVED_KEYWORD));
keywords.put("restart", new Keyword("restart", UNRESERVED_KEYWORD));
keywords.put("restrict", new Keyword("restrict", UNRESERVED_KEYWORD));
keywords.put("returning", new Keyword("returning", RESERVED_KEYWORD));
keywords.put("returns", new Keyword("returns", UNRESERVED_KEYWORD));
keywords.put("revoke", new Keyword("revoke", UNRESERVED_KEYWORD));
keywords.put("right", new Keyword("right", TYPE_FUNC_NAME_KEYWORD));
keywords.put("role", new Keyword("role", UNRESERVED_KEYWORD));
keywords.put("rollback", new Keyword("rollback", UNRESERVED_KEYWORD));
keywords.put("rollup", new Keyword("rollup", UNRESERVED_KEYWORD));
keywords.put("routine", new Keyword("routine", UNRESERVED_KEYWORD));
keywords.put("routines", new Keyword("routines", UNRESERVED_KEYWORD));
keywords.put("row", new Keyword("row", COL_NAME_KEYWORD));
keywords.put("rows", new Keyword("rows", UNRESERVED_KEYWORD));
keywords.put("rule", new Keyword("rule", UNRESERVED_KEYWORD));
keywords.put("savepoint", new Keyword("savepoint", UNRESERVED_KEYWORD));
keywords.put("schema", new Keyword("schema", UNRESERVED_KEYWORD));
keywords.put("schemas", new Keyword("schemas", UNRESERVED_KEYWORD));
keywords.put("scroll", new Keyword("scroll", UNRESERVED_KEYWORD));
keywords.put("search", new Keyword("search", UNRESERVED_KEYWORD));
keywords.put("second", new Keyword("second", UNRESERVED_KEYWORD));
keywords.put("security", new Keyword("security", UNRESERVED_KEYWORD));
keywords.put("select", new Keyword("select", RESERVED_KEYWORD));
keywords.put("sequence", new Keyword("sequence", UNRESERVED_KEYWORD));
keywords.put("sequences", new Keyword("sequences", UNRESERVED_KEYWORD));
keywords.put("serializable", new Keyword("serializable", UNRESERVED_KEYWORD));
keywords.put("server", new Keyword("server", UNRESERVED_KEYWORD));
keywords.put("session", new Keyword("session", UNRESERVED_KEYWORD));
keywords.put("session_user", new Keyword("session_user", RESERVED_KEYWORD));
keywords.put("set", new Keyword("set", UNRESERVED_KEYWORD));
keywords.put("setof", new Keyword("setof", COL_NAME_KEYWORD));
keywords.put("sets", new Keyword("sets", UNRESERVED_KEYWORD));
keywords.put("share", new Keyword("share", UNRESERVED_KEYWORD));
keywords.put("show", new Keyword("show", UNRESERVED_KEYWORD));
keywords.put("similar", new Keyword("similar", TYPE_FUNC_NAME_KEYWORD));
keywords.put("simple", new Keyword("simple", UNRESERVED_KEYWORD));
keywords.put("skip", new Keyword("skip", UNRESERVED_KEYWORD));
keywords.put("smallint", new Keyword("smallint", COL_NAME_KEYWORD));
keywords.put("snapshot", new Keyword("snapshot", UNRESERVED_KEYWORD));
keywords.put("some", new Keyword("some", RESERVED_KEYWORD));
keywords.put("sql", new Keyword("sql", UNRESERVED_KEYWORD));
keywords.put("stable", new Keyword("stable", UNRESERVED_KEYWORD));
keywords.put("standalone", new Keyword("standalone", UNRESERVED_KEYWORD));
keywords.put("start", new Keyword("start", UNRESERVED_KEYWORD));
keywords.put("statement", new Keyword("statement", UNRESERVED_KEYWORD));
keywords.put("statistics", new Keyword("statistics", UNRESERVED_KEYWORD));
keywords.put("stdin", new Keyword("stdin", UNRESERVED_KEYWORD));
keywords.put("stdout", new Keyword("stdout", UNRESERVED_KEYWORD));
keywords.put("storage", new Keyword("storage", UNRESERVED_KEYWORD));
keywords.put("stored", new Keyword("stored", UNRESERVED_KEYWORD));
keywords.put("strict", new Keyword("strict", UNRESERVED_KEYWORD));
keywords.put("strip", new Keyword("strip", UNRESERVED_KEYWORD));
keywords.put("subscription", new Keyword("subscription", UNRESERVED_KEYWORD));
keywords.put("substring", new Keyword("substring", COL_NAME_KEYWORD));
keywords.put("support", new Keyword("support", UNRESERVED_KEYWORD));
keywords.put("symmetric", new Keyword("symmetric", RESERVED_KEYWORD));
keywords.put("sysid", new Keyword("sysid", UNRESERVED_KEYWORD));
keywords.put("system", new Keyword("system", UNRESERVED_KEYWORD));
keywords.put("table", new Keyword("table", RESERVED_KEYWORD));
keywords.put("tables", new Keyword("tables", UNRESERVED_KEYWORD));
keywords.put("tablesample", new Keyword("tablesample", TYPE_FUNC_NAME_KEYWORD));
keywords.put("tablespace", new Keyword("tablespace", UNRESERVED_KEYWORD));
keywords.put("temp", new Keyword("temp", UNRESERVED_KEYWORD));
keywords.put("template", new Keyword("template", UNRESERVED_KEYWORD));
keywords.put("temporary", new Keyword("temporary", UNRESERVED_KEYWORD));
keywords.put("text", new Keyword("text", UNRESERVED_KEYWORD));
keywords.put("then", new Keyword("then", RESERVED_KEYWORD));
keywords.put("ties", new Keyword("ties", UNRESERVED_KEYWORD));
keywords.put("time", new Keyword("time", COL_NAME_KEYWORD));
keywords.put("timestamp", new Keyword("timestamp", COL_NAME_KEYWORD));
keywords.put("to", new Keyword("to", RESERVED_KEYWORD));
keywords.put("trailing", new Keyword("trailing", RESERVED_KEYWORD));
keywords.put("transaction", new Keyword("transaction", UNRESERVED_KEYWORD));
keywords.put("transform", new Keyword("transform", UNRESERVED_KEYWORD));
keywords.put("treat", new Keyword("treat", COL_NAME_KEYWORD));
keywords.put("trigger", new Keyword("trigger", UNRESERVED_KEYWORD));
keywords.put("trim", new Keyword("trim", COL_NAME_KEYWORD));
keywords.put("true", new Keyword("true", RESERVED_KEYWORD));
keywords.put("truncate", new Keyword("truncate", UNRESERVED_KEYWORD));
keywords.put("trusted", new Keyword("trusted", UNRESERVED_KEYWORD));
keywords.put("type", new Keyword("type", UNRESERVED_KEYWORD));
keywords.put("types", new Keyword("types", UNRESERVED_KEYWORD));
keywords.put("unbounded", new Keyword("unbounded", UNRESERVED_KEYWORD));
keywords.put("uncommitted", new Keyword("uncommitted", UNRESERVED_KEYWORD));
keywords.put("unencrypted", new Keyword("unencrypted", UNRESERVED_KEYWORD));
keywords.put("union", new Keyword("union", RESERVED_KEYWORD));
keywords.put("unique", new Keyword("unique", RESERVED_KEYWORD));
keywords.put("unknown", new Keyword("unknown", UNRESERVED_KEYWORD));
keywords.put("unlisten", new Keyword("unlisten", UNRESERVED_KEYWORD));
keywords.put("unlogged", new Keyword("unlogged", UNRESERVED_KEYWORD));
keywords.put("until", new Keyword("until", UNRESERVED_KEYWORD));
keywords.put("update", new Keyword("update", UNRESERVED_KEYWORD));
keywords.put("user", new Keyword("user", RESERVED_KEYWORD));
keywords.put("using", new Keyword("using", RESERVED_KEYWORD));
keywords.put("vacuum", new Keyword("vacuum", UNRESERVED_KEYWORD));
keywords.put("valid", new Keyword("valid", UNRESERVED_KEYWORD));
keywords.put("validate", new Keyword("validate", UNRESERVED_KEYWORD));
keywords.put("validator", new Keyword("validator", UNRESERVED_KEYWORD));
keywords.put("value", new Keyword("value", UNRESERVED_KEYWORD));
keywords.put("values", new Keyword("values", COL_NAME_KEYWORD));
keywords.put("varchar", new Keyword("varchar", COL_NAME_KEYWORD));
keywords.put("variadic", new Keyword("variadic", RESERVED_KEYWORD));
keywords.put("varying", new Keyword("varying", UNRESERVED_KEYWORD));
keywords.put("verbose", new Keyword("verbose", TYPE_FUNC_NAME_KEYWORD));
keywords.put("version", new Keyword("version", UNRESERVED_KEYWORD));
keywords.put("view", new Keyword("view", UNRESERVED_KEYWORD));
keywords.put("views", new Keyword("views", UNRESERVED_KEYWORD));
keywords.put("volatile", new Keyword("volatile", UNRESERVED_KEYWORD));
keywords.put("when", new Keyword("when", RESERVED_KEYWORD));
keywords.put("where", new Keyword("where", RESERVED_KEYWORD));
keywords.put("whitespace", new Keyword("whitespace", UNRESERVED_KEYWORD));
keywords.put("window", new Keyword("window", RESERVED_KEYWORD));
keywords.put("with", new Keyword("with", RESERVED_KEYWORD));
keywords.put("within", new Keyword("within", UNRESERVED_KEYWORD));
keywords.put("without", new Keyword("without", UNRESERVED_KEYWORD));
keywords.put("work", new Keyword("work", UNRESERVED_KEYWORD));
keywords.put("wrapper", new Keyword("wrapper", UNRESERVED_KEYWORD));
keywords.put("write", new Keyword("write", UNRESERVED_KEYWORD));
keywords.put("xml", new Keyword("xml", UNRESERVED_KEYWORD));
keywords.put("xmlattributes", new Keyword("xmlattributes", COL_NAME_KEYWORD));
keywords.put("xmlconcat", new Keyword("xmlconcat", COL_NAME_KEYWORD));
keywords.put("xmlelement", new Keyword("xmlelement", COL_NAME_KEYWORD));
keywords.put("xmlexists", new Keyword("xmlexists", COL_NAME_KEYWORD));
keywords.put("xmlforest", new Keyword("xmlforest", COL_NAME_KEYWORD));
keywords.put("xmlnamespaces", new Keyword("xmlnamespaces", COL_NAME_KEYWORD));
keywords.put("xmlparse", new Keyword("xmlparse", COL_NAME_KEYWORD));
keywords.put("xmlpi", new Keyword("xmlpi", COL_NAME_KEYWORD));
keywords.put("xmlroot", new Keyword("xmlroot", COL_NAME_KEYWORD));
keywords.put("xmlserialize", new Keyword("xmlserialize", COL_NAME_KEYWORD));
keywords.put("xmltable", new Keyword("xmltable", COL_NAME_KEYWORD));
keywords.put("year", new Keyword("year", UNRESERVED_KEYWORD));
keywords.put("yes", new Keyword("yes", UNRESERVED_KEYWORD));
keywords.put("zone", new Keyword("zone", UNRESERVED_KEYWORD));
}
static {
Map<String, Keyword> keywords = new HashMap<>();
addKeywords(keywords);
KEYWORDS = Collections.unmodifiableMap(keywords);
}
private final String keyword;
private final KeywordCategory category;
public Keyword(String keyword, KeywordCategory category) {
this.keyword = keyword;
this.category = category;
}
public String getKeyword() {
return keyword;
}
public KeywordCategory getCategory() {
return category;
}
public static void getAllTokensByGroups () {
Map<KeywordCategory, StringBuilder> map = new EnumMap<>(KeywordCategory.class);
KEYWORDS.values().stream()
.sorted((v1,v2) -> v1.getKeyword().compareTo(v2.getKeyword()))
.forEach(v -> {
StringBuilder sb = map.get(v.getCategory());
if (sb == null) {
sb = new StringBuilder();
map.put(v.getCategory(), sb);
}
String k = v.getKeyword();
String kUpper = k.toUpperCase(Locale.ROOT);
sb.append(" ").append(kUpper).append(':');
for (int i = 0; i < k.length(); ++i){
char ch = k.charAt(i);
if (ch == '_'){
sb.append(" UNDERLINE ");
} else {
sb.append(" [").append(ch).append(kUpper.charAt(i)).append(']');
}
}
sb.append(";\n");
});
// SONAR-OFF
map.keySet().stream().sorted().forEach(k -> {
System.out.println("==================================================");
System.out.println(k);
System.out.println("==================================================");
System.out.println(map.get(k));
});
// SONAR-ON
}
public static void getAllWordsByGroups () {
Map<KeywordCategory, StringBuilder> map = new EnumMap<>(KeywordCategory.class);
KEYWORDS.values().stream()
.sorted((v1,v2) -> v1.getKeyword().compareTo(v2.getKeyword()))
.forEach(v -> {
StringBuilder sb = map.get(v.getCategory());
if (sb == null) {
sb = new StringBuilder();
map.put(v.getCategory(), sb);
}
sb.append(" | ").append(v.getKeyword().toUpperCase(Locale.ROOT)).append("\n");
});
// SONAR-OFF
map.keySet().stream().sorted().forEach(k -> {
System.out.println("==================================================");
System.out.println(k);
System.out.println("==================================================");
System.out.println(map.get(k));
});
// SONAR-ON
}
}
|
package schedulerscreens;
import io.appium.java_client.AppiumDriver;
import io.appium.java_client.MobileElement;
import models.Event;
import org.openqa.selenium.support.FindBy;
import org.testng.annotations.Test;
public class EditCreateEventScreen extends BaseScreen{
public EditCreateEventScreen(AppiumDriver<MobileElement> driver) {
super(driver);
}
@FindBy(xpath = "//*[@resource-id = 'com.example.svetlana.scheduler:id/info_title_input']")
MobileElement title;
@FindBy(xpath = "//*[@resource-id = 'com.example.svetlana.scheduler:id/info_type_input']")
MobileElement type;
@FindBy(xpath = "//*[@resource-id = 'com.example.svetlana.scheduler:id/info_break_plus_btn']")
MobileElement breaksPlusButton;
@FindBy(xpath = "//*[@resource-id = 'com.example.svetlana.scheduler:id/info_wage_edit']")
MobileElement wageEdit;
@FindBy(xpath = "//*[@resource-id = 'com.example.svetlana.scheduler:id/info_wage_input']")
MobileElement wageInput;
@FindBy(xpath = "//*[@resource-id = 'com.example.svetlana.scheduler:id/info_wage_save']")
MobileElement wageSave;
@FindBy(xpath = "//*[@resource-id = 'com.example.svetlana.scheduler:id/info_save_btn']")
MobileElement confirmCreation;
@FindBy (xpath = "//*[@resource-id='android:id/message']")
MobileElement errorMessage;
@FindBy (xpath = "//*[@resource-id='android:id/button1']")
MobileElement okBtn;
public HomeScreen createNewEvent(Event event){
should(title, 15);
type(title, event.getTitle());
type(type, event.getType());
hideKeyBoard();
int breaks = event.getBreaks();
if(breaks>0 && breaks<5 ) {
for (int i=0;i<breaks;i++){
breaksPlusButton.click();
}
}
wageEdit.click();
type(wageInput,String.valueOf(event.getWage()));
wageSave.click();
confirmCreation.click();
return new HomeScreen(driver);
}
}
|
import java.util.Comparator;
/**
* Client for a search library with a generic type.
*
* @author Dean Hendrix (dh@auburn.edu)
* @version 2010-08-20
*
*/
public class SearchLibraryGenericCompClient
{
/**
* Illustrates basic calls to search method.
*
* @param args Command line arguments not used.
*
*/
public static void main(String[] args)
{
Book[] a = {
new Book("Smith", "Smith Book", 123),
new Book("Jones", "Jones Book", 456),
new Book("Baker", "Baker Book", 789)
};
Book target = new Book("Wilson", "Jones Book", 543);
SearchLibraryGenericComp<Book> slgc = new SearchLibraryGenericComp<Book>();
System.out.println(slgc.search(a, target));
System.out.println(slgc.search(a, target, new CompareBooksByTitle()));
System.out.println(slgc.search(a, target, new CompareBooksByAuthor()));
}
/**
* Defines comparison of two books by title equality.
*
*/
public static class CompareBooksByTitle implements Comparator<Book>
{
/**
* Compares two books by title.
*
* @param o1 Object referencing the first Book
* @param o2 Object referencing the second Book.
* @return zero if o1 and o1 are logically equal,
* positive if o1 > o2
* negative if o1 < o2
*/
public int compare(Book b1, Book b2)
{
return b1.getTitle().compareTo(b2.getTitle());
}
}
/**
* Defines comparison of two books by author equality.
*
*/
public static class CompareBooksByAuthor implements Comparator<Book>
{
/**
* Compares two books by author.
*
* @param o1 Object referencing the first Book
* @param o2 Object referencing the second Book.
* @return zero if o1 and o1 are logically equal,
* positive if o1 > o2
* negative if o1 < o2
*/
public int compare(Book b1, Book b2)
{
return b1.getAuthor().compareTo(b2.getAuthor());
}
}
}
|
/*
* 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.aliyuncs.netana.model.v20201016;
import java.util.List;
import com.aliyuncs.AcsResponse;
import com.aliyuncs.netana.transform.v20201016.ListIpGeolocationsResponseUnmarshaller;
import com.aliyuncs.transform.UnmarshallerContext;
/**
* @author auto create
* @version
*/
public class ListIpGeolocationsResponse extends AcsResponse {
private String requestId;
private String nextToken;
private Integer totalCount;
private Integer maxResults;
private List<IpGeolocationModel> ipGeolocationModels;
public String getRequestId() {
return this.requestId;
}
public void setRequestId(String requestId) {
this.requestId = requestId;
}
public String getNextToken() {
return this.nextToken;
}
public void setNextToken(String nextToken) {
this.nextToken = nextToken;
}
public Integer getTotalCount() {
return this.totalCount;
}
public void setTotalCount(Integer totalCount) {
this.totalCount = totalCount;
}
public Integer getMaxResults() {
return this.maxResults;
}
public void setMaxResults(Integer maxResults) {
this.maxResults = maxResults;
}
public List<IpGeolocationModel> getIpGeolocationModels() {
return this.ipGeolocationModels;
}
public void setIpGeolocationModels(List<IpGeolocationModel> ipGeolocationModels) {
this.ipGeolocationModels = ipGeolocationModels;
}
public static class IpGeolocationModel {
private String ipv4Prefix;
private String countryCode;
private String cityCode;
private String resourcePoolName;
public String getIpv4Prefix() {
return this.ipv4Prefix;
}
public void setIpv4Prefix(String ipv4Prefix) {
this.ipv4Prefix = ipv4Prefix;
}
public String getCountryCode() {
return this.countryCode;
}
public void setCountryCode(String countryCode) {
this.countryCode = countryCode;
}
public String getCityCode() {
return this.cityCode;
}
public void setCityCode(String cityCode) {
this.cityCode = cityCode;
}
public String getResourcePoolName() {
return this.resourcePoolName;
}
public void setResourcePoolName(String resourcePoolName) {
this.resourcePoolName = resourcePoolName;
}
}
@Override
public ListIpGeolocationsResponse getInstance(UnmarshallerContext context) {
return ListIpGeolocationsResponseUnmarshaller.unmarshall(this, context);
}
}
|
package myservice.mynamespace.service.api;
import org.apache.olingo.server.api.processor.EntityProcessor;
public interface IEntityProcessor extends EntityProcessor, ICanHandleODataUri {
}
|
package core.ast.util;
import com.intellij.psi.PsiConditionalExpression;
import com.intellij.psi.PsiExpression;
public class InstanceOfConditionalExpression implements ExpressionInstanceChecker {
public boolean instanceOf(PsiExpression expression) {
return expression instanceof PsiConditionalExpression;
}
}
|
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.0-b52-fcs
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2012.09.06 at 09:23:00 오후 KST
//
package com.athena.chameleon.engine.entity.xml.ejbjar.weblogic.v9_0;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlID;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.XmlValue;
import javax.xml.bind.annotation.adapters.CollapsedStringAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
/**
* <p>Java class for initial-context-factoryType complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="initial-context-factoryType">
* <simpleContent>
* <extension base="<http://www.w3.org/2001/XMLSchema>string">
* <attribute name="id" type="{http://www.w3.org/2001/XMLSchema}ID" />
* </extension>
* </simpleContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "initial-context-factoryType", propOrder = {
"value"
})
public class InitialContextFactoryType {
@XmlValue
protected java.lang.String value;
@XmlAttribute
@XmlJavaTypeAdapter(CollapsedStringAdapter.class)
@XmlID
protected java.lang.String id;
/**
* Gets the value of the value property.
*
* @return
* possible object is
* {@link java.lang.String }
*
*/
public java.lang.String getValue() {
return value;
}
/**
* Sets the value of the value property.
*
* @param value
* allowed object is
* {@link java.lang.String }
*
*/
public void setValue(java.lang.String value) {
this.value = value;
}
/**
* Gets the value of the id property.
*
* @return
* possible object is
* {@link java.lang.String }
*
*/
public java.lang.String getId() {
return id;
}
/**
* Sets the value of the id property.
*
* @param value
* allowed object is
* {@link java.lang.String }
*
*/
public void setId(java.lang.String value) {
this.id = value;
}
}
|
/**
* Copyright 2018 The OpenTracing 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 io.opentracing.contrib.java.spring.jaeger.starter;
import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties("opentracing.jaeger")
public class JaegerConfigurationProperties {
private final RemoteReporter remoteReporter = new RemoteReporter();
private final HttpSender httpSender = new HttpSender();
private final UdpSender udpSender = new UdpSender();
private final ConstSampler constSampler = new ConstSampler();
private final ProbabilisticSampler probabilisticSampler = new ProbabilisticSampler();
private final RateLimitingSampler rateLimitingSampler = new RateLimitingSampler();
private final RemoteControlledSampler remoteControlledSampler = new RemoteControlledSampler();
/**
* Enable Jaeger Tracer
*/
private boolean enabled = true;
/**
* Whether spans should be logged to the console
*/
private boolean logSpans = true;
/**
* Enable the handling of B3 headers like "X-B3-TraceId" This setting should be used when it is
* desired for Jaeger to be able to join traces started by other Zipkin instrumented applications
*/
private boolean enableB3Propagation = false;
private boolean expandExceptionLogs = false;
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public boolean isLogSpans() {
return logSpans;
}
public void setLogSpans(boolean logSpans) {
this.logSpans = logSpans;
}
public boolean isEnableB3Propagation() {
return enableB3Propagation;
}
public void setEnableB3Propagation(boolean enableB3Propagation) {
this.enableB3Propagation = enableB3Propagation;
}
public boolean isExpandExceptionLogs() {
return expandExceptionLogs;
}
public void setExpandExceptionLogs(boolean expandExceptionLogs) {
this.expandExceptionLogs = expandExceptionLogs;
}
public HttpSender getHttpSender() {
return httpSender;
}
public RemoteReporter getRemoteReporter() {
return remoteReporter;
}
public UdpSender getUdpSender() {
return udpSender;
}
public ConstSampler getConstSampler() {
return constSampler;
}
public ProbabilisticSampler getProbabilisticSampler() {
return probabilisticSampler;
}
public RateLimitingSampler getRateLimitingSampler() {
return rateLimitingSampler;
}
public RemoteControlledSampler getRemoteControlledSampler() {
return remoteControlledSampler;
}
public static class RemoteReporter {
private Integer flushInterval;
private Integer maxQueueSize;
public Integer getFlushInterval() {
return flushInterval;
}
public void setFlushInterval(Integer flushInterval) {
this.flushInterval = flushInterval;
}
public Integer getMaxQueueSize() {
return maxQueueSize;
}
public void setMaxQueueSize(Integer maxQueueSize) {
this.maxQueueSize = maxQueueSize;
}
}
/**
* If the URL is set, then HttpSender is used regardless
* of the configuration in UdpSender
*/
public static class HttpSender {
private String url;
private Integer maxPayload = 0;
private String username;
private String password;
private String authToken;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public Integer getMaxPayload() {
return maxPayload;
}
public void setMaxPayload(Integer maxPayload) {
this.maxPayload = maxPayload;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getAuthToken() {
return authToken;
}
public void setAuthToken(String authToken) {
this.authToken = authToken;
}
}
public static class UdpSender {
private String host = "localhost";
private int port = 6831;
private int maxPacketSize = 0;
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public int getMaxPacketSize() {
return maxPacketSize;
}
public void setMaxPacketSize(int maxPacketSize) {
this.maxPacketSize = maxPacketSize;
}
}
public static class ConstSampler {
private Boolean decision;
public Boolean getDecision() {
return decision;
}
public void setDecision(Boolean decision) {
this.decision = decision;
}
}
public static class ProbabilisticSampler {
private Double samplingRate;
public Double getSamplingRate() {
return samplingRate;
}
public void setSamplingRate(Double samplingRate) {
this.samplingRate = samplingRate;
}
}
public static class RateLimitingSampler {
private Double maxTracesPerSecond;
public Double getMaxTracesPerSecond() {
return maxTracesPerSecond;
}
public void setMaxTracesPerSecond(Double maxTracesPerSecond) {
this.maxTracesPerSecond = maxTracesPerSecond;
}
}
public static class RemoteControlledSampler {
/**
* i.e. localhost:5778
*/
private String hostPort;
private Double samplingRate =
io.jaegertracing.internal.samplers.ProbabilisticSampler.DEFAULT_SAMPLING_PROBABILITY;
public String getHostPort() {
return hostPort;
}
public void setHostPort(String hostPort) {
this.hostPort = hostPort;
}
public Double getSamplingRate() {
return samplingRate;
}
public void setSamplingRate(Double samplingRate) {
this.samplingRate = samplingRate;
}
}
}
|
package com.atming.mingmall.product.service.impl;
import org.springframework.stereotype.Service;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atming.common.utils.PageUtils;
import com.atming.common.utils.Query;
import com.atming.mingmall.product.dao.PmsAttrGroupDao;
import com.atming.mingmall.product.entity.PmsAttrGroupEntity;
import com.atming.mingmall.product.service.PmsAttrGroupService;
@Service("pmsAttrGroupService")
public class PmsAttrGroupServiceImpl extends ServiceImpl<PmsAttrGroupDao, PmsAttrGroupEntity> implements PmsAttrGroupService {
@Override
public PageUtils queryPage(Map<String, Object> params) {
IPage<PmsAttrGroupEntity> page = this.page(
new Query<PmsAttrGroupEntity>().getPage(params),
new QueryWrapper<PmsAttrGroupEntity>()
);
return new PageUtils(page);
}
}
|
/*
* 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 aula_2020_05_25_noite;
/**
*
* @author sicsu
*/
public class Vetor4 {
public static void main(String[] args) {
int vetor[] = new int[10];
int auxiliar;
for(int i=0; i<10; i++) {
vetor[i]= (20- i*2);// cria na ordem descrescente
vetor[i]= (i*2);// cria na ordem crescente
}
System.out.println("Vetor antes da ordenação:");
for(int i=0; i<10; i++) {
System.out.println(vetor[i]);
}
for (int i=0; i<9; i++) {
for (int j=i+1; j<10; j++) {
//if(vetor[i] > vetor[j]) {// coloca na ordem crescente
if(vetor[i] < vetor[j]) {// coloca na ordem decrescente
auxiliar = vetor[i];
vetor[i] = vetor[j];
vetor[j] = auxiliar;
}
}
}
System.out.println("Vetor depois da ordenação:");
for(int i=0; i<10; i++) {
System.out.println(vetor[i]);
}
}
}
|
/*
* Copyright (C) 2017 优客服-多渠道客服系统
* Modifications copyright (C) 2018-2019 Chatopera Inc, <https://www.chatopera.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.cs.wit.persistence.repository;
import com.cs.wit.model.SystemConfig;
import org.springframework.data.jpa.repository.JpaRepository;
public interface SystemConfigRepository extends JpaRepository<SystemConfig, String>
{
SystemConfig findByOrgi(String orgi);
}
|
package com.jivesoftware.os.miru.reco.trending;
import com.jivesoftware.os.mlogger.core.MetricLogger;
import com.jivesoftware.os.mlogger.core.MetricLoggerFactory;
import java.nio.ByteBuffer;
import java.util.Arrays;
/**
* Supports storing a hits waveform. You can add hit @ time in any order.
* The Buffer will slide to accommodate hits.
*
* NOT thread safe any more, synchronize externally.
*
* @author jonathan
*/
public class SparseCircularHitsBucketBuffer {
private static final MetricLogger logger = MetricLoggerFactory.getLogger();
private long mostRecentTimeStamp = Long.MIN_VALUE;
private long oldestBucketNumber = Long.MIN_VALUE;
private long youngestBucketNumber;
private long utcOffset; // shifts alignment of buckets as offset from UTC, e.g. aligning with start of work day in PST
private long bucketWidthMillis;
private int cursor; // always points oldest bucket. cursor -1 is the newestBucket
private int numberOfBuckets;
private double[] hits;
public SparseCircularHitsBucketBuffer(int numberOfBuckets, long utcOffset, long bucketWidthMillis) {
this.numberOfBuckets = numberOfBuckets;
this.utcOffset = utcOffset;
this.bucketWidthMillis = bucketWidthMillis;
hits = new double[numberOfBuckets];
}
public long mostRecentTimestamp() {
return mostRecentTimeStamp;
}
public long duration() {
return bucketWidthMillis * numberOfBuckets;
}
public byte[] toBytes() throws Exception {
ByteBuffer bb = ByteBuffer.allocate((8 * 5) + (4 * 2) + (8 * numberOfBuckets));
bb.putLong(mostRecentTimeStamp);
bb.putLong(oldestBucketNumber);
bb.putLong(youngestBucketNumber);
bb.putLong(utcOffset);
bb.putLong(bucketWidthMillis);
bb.putInt(cursor);
bb.putInt(numberOfBuckets);
for (int i = 0; i < numberOfBuckets; i++) {
bb.putDouble(hits[i]);
}
return bb.array();
}
public void fromBytes(byte[] raw) throws Exception {
ByteBuffer bb = ByteBuffer.wrap(raw);
mostRecentTimeStamp = bb.getLong();
oldestBucketNumber = bb.getLong();
youngestBucketNumber = bb.getLong();
utcOffset = bb.getLong();
bucketWidthMillis = bb.getLong();
cursor = bb.getInt();
numberOfBuckets = bb.getInt();
hits = new double[numberOfBuckets];
for (int i = 0; i < numberOfBuckets; i++) {
hits[i] = bb.getDouble();
}
}
public void push(long time, double hit) {
if (time > mostRecentTimeStamp) {
mostRecentTimeStamp = time;
}
long absBucketNumber = absBucketNumber(time);
if (oldestBucketNumber == Long.MIN_VALUE) {
oldestBucketNumber = absBucketNumber - (numberOfBuckets - 1);
youngestBucketNumber = absBucketNumber;
} else {
if (absBucketNumber < oldestBucketNumber) {
logger.debug("Moving backwards is unsupported so we will simply drop the hit on the floor!");
return;
}
if (absBucketNumber > youngestBucketNumber) {
// we need to slide the buffer to accommodate younger values
long delta = absBucketNumber - youngestBucketNumber;
for (int i = 0; i < delta; i++) {
hits[cursor] = 0; // zero out oldest
cursor = nextCursor(cursor, 1); // move cursor
}
oldestBucketNumber += delta;
youngestBucketNumber = absBucketNumber;
}
}
int delta = (int) (absBucketNumber - oldestBucketNumber);
hits[nextCursor(cursor, delta)] += hit;
}
private long absBucketNumber(long time) {
long absBucketNumber = time / bucketWidthMillis;
long absNearestEdge = bucketWidthMillis * absBucketNumber;
long remainder = time - (absNearestEdge);
if (remainder < utcOffset) {
return absBucketNumber - 1;
} else {
return absBucketNumber;
}
}
private int nextCursor(int cursor, int move) {
cursor += move;
if (cursor >= numberOfBuckets) {
cursor -= numberOfBuckets;
}
return cursor;
}
public double[] rawSignal() {
double[] copy = new double[numberOfBuckets];
int c = cursor;
for (int i = 0; i < numberOfBuckets; i++) {
copy[i] = hits[c];
c = nextCursor(c, 1);
}
return copy;
}
public long[] bucketTimes() {
long[] times = new long[numberOfBuckets];
long t = mostRecentTimeStamp - (numberOfBuckets - 1) * bucketWidthMillis;
for (int i = cursor, j = 0; j < numberOfBuckets; i = (i + 1) % numberOfBuckets, j++) {
times[i] = t;
t += bucketWidthMillis;
}
return times;
}
@Override
public String toString() {
return "SparseCircularHitsBucketBuffer{" +
"mostRecentTimeStamp=" + mostRecentTimeStamp +
", oldestBucketNumber=" + oldestBucketNumber +
", youngestBucketNumber=" + youngestBucketNumber +
", utcOffset=" + utcOffset +
", bucketWidthMillis=" + bucketWidthMillis +
", cursor=" + cursor +
", numberOfBuckets=" + numberOfBuckets +
", hits=" + Arrays.toString(hits) +
'}';
}
}
|
package de.srendi.advancedperipherals.common.container.base;
import net.minecraft.network.chat.Component;
import net.minecraft.world.MenuProvider;
import net.minecraft.world.entity.player.Inventory;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.inventory.AbstractContainerMenu;
import net.minecraft.world.inventory.MenuConstructor;
import org.jetbrains.annotations.Nullable;
public class NamedContainerProvider implements MenuProvider {
protected Component component;
protected MenuConstructor containerProvider;
public NamedContainerProvider(Component component, MenuConstructor containerProvider) {
this.component = component;
this.containerProvider = containerProvider;
}
@Override
public Component getDisplayName() {
return component;
}
@Nullable
@Override
public AbstractContainerMenu createMenu(int id, Inventory playerInventory, Player playerEntity) {
return containerProvider.createMenu(id, playerInventory, playerEntity);
}
}
|
package com.cap.jumpthequeue.general.common.api.validation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import javax.validation.Constraint;
import javax.validation.Payload;
import javax.validation.constraints.Pattern;
import org.hibernate.validator.constraints.Email;
@Email
@Pattern(regexp = ".+@.+\\..+", message = "Email must specify a domain")
@Target({ ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = {})
@Documented
public @interface EmailExtended {
String message() default "Please provide a valid email address";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
|
package com.hubspot.singularity.auth;
import com.hubspot.singularity.auth.authenticator.SingularityAuthenticator;
import com.hubspot.singularity.auth.authenticator.SingularityDisabledAuthenticator;
import com.hubspot.singularity.auth.authenticator.SingularityTokenAuthenticator;
import com.hubspot.singularity.auth.authenticator.SingularityWebhookAuthenticator;
import com.hubspot.singularity.auth.authenticator.SingularityHeaderPassthroughAuthenticator;
import com.hubspot.singularity.auth.authenticator.SingularityQueryParamAuthenticator;
public enum SingularityAuthenticatorClass {
DISABLED(SingularityDisabledAuthenticator.class),
HEADER_PASSTHROUGH(SingularityHeaderPassthroughAuthenticator.class),
QUERYPARAM_PASSTHROUGH(SingularityQueryParamAuthenticator.class),
WEBHOOK(SingularityWebhookAuthenticator.class),
TOKEN(SingularityTokenAuthenticator.class);
private final Class<? extends SingularityAuthenticator> authenticatorClass;
SingularityAuthenticatorClass(Class<? extends SingularityAuthenticator> authenticatorClass) {
this.authenticatorClass = authenticatorClass;
}
public Class<? extends SingularityAuthenticator> getAuthenticatorClass() {
return authenticatorClass;
}
}
|
package com.xm.gulimall.product.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xm.common.utils.PageUtils;
import com.xm.common.utils.Query;
import com.xm.gulimall.product.dao.SpuInfoDao;
import com.xm.gulimall.product.entity.SpuInfoEntity;
import com.xm.gulimall.product.service.SpuInfoService;
import org.springframework.stereotype.Service;
import java.util.Map;
@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {
@Override
public PageUtils queryPage(Map<String, Object> params) {
IPage<SpuInfoEntity> page = this.page(
new Query<SpuInfoEntity>().getPage(params),
new QueryWrapper<SpuInfoEntity>()
);
return new PageUtils(page);
}
}
|
package org.daming.person.pojo.type.handler;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.daming.person.enums.Gender;
import org.springframework.util.StringUtils;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.EnumMap;
import java.util.Map;
@MappedJdbcTypes({JdbcType.VARCHAR})
@MappedTypes({Gender.class})
public class GenderTypeHandler extends BaseTypeHandler<Gender> {
private EnumMap<Gender, String> map;
@Override
public void setNonNullParameter(PreparedStatement preparedStatement, int i, Gender gender, JdbcType jdbcType) throws SQLException {
preparedStatement.setString(i, map.get(gender));
}
@Override
public Gender getNullableResult(ResultSet rs, String s) throws SQLException {
String value = rs.getString(s);
return this.getGender(value);
}
@Override
public Gender getNullableResult(ResultSet rs, int i) throws SQLException {
String value = rs.getString(i);
return this.getGender(value);
}
@Override
public Gender getNullableResult(CallableStatement cs, int i) throws SQLException {
String value = cs.getString(i);
return this.getGender(value);
}
private Gender getGender(String value) {
return this.map.entrySet().stream()
.filter(e -> value.equalsIgnoreCase(e.getValue()))
.map(Map.Entry::getKey).findFirst().orElse(Gender.N);
}
public GenderTypeHandler() {
super();
this.init();
}
private void init() {
this.map = new EnumMap<>(Gender.class);
this.map.put(Gender.F, "F");
this.map.put(Gender.M, "M");
this.map.put(Gender.N, "N");
}
}
|
/* AUTO-GENERATED FILE. DO NOT MODIFY.
*
* This class was automatically generated by the
* aapt tool from the resource data it found. It
* should not be modified by hand.
*/
package com.bgstation0.android.sample.sharedpreferences_;
public final class R {
public static final class attr {
}
public static final class drawable {
public static final int ic_launcher=0x7f020000;
}
public static final class id {
public static final int button_load_pref=0x7f060002;
public static final int button_save_pref=0x7f060001;
public static final int edit_pref=0x7f060000;
}
public static final class layout {
public static final int activity_main=0x7f030000;
}
public static final class string {
public static final int app_name=0x7f040000;
public static final int button_load_pref_text=0x7f040003;
public static final int button_save_pref_text=0x7f040002;
public static final int edit_pref_text=0x7f040001;
}
public static final class style {
/**
Base application theme, dependent on API level. This theme is replaced
by AppBaseTheme from res/values-vXX/styles.xml on newer devices.
Theme customizations available in newer API levels can go in
res/values-vXX/styles.xml, while customizations related to
backward-compatibility can go here.
Base application theme for API 11+. This theme completely replaces
AppBaseTheme from res/values/styles.xml on API 11+ devices.
API 11 theme customizations can go here.
Base application theme for API 14+. This theme completely replaces
AppBaseTheme from BOTH res/values/styles.xml and
res/values-v11/styles.xml on API 14+ devices.
API 14 theme customizations can go here.
*/
public static final int AppBaseTheme=0x7f050000;
/** Application theme.
All customizations that are NOT specific to a particular API-level can go here.
*/
public static final int AppTheme=0x7f050001;
}
}
|
package com.wqwy.zhnm.base.component.utils;
import java.math.BigDecimal;
public class Arith {
/**
* 由于Java的简单类型不能够精确的对浮点数进行运算,这个工具类提供精
* 确的浮点数运算,包括加减乘除和四舍五入。
*/
//默认除法运算精度
private static final int DEF_DIV_SCALE = 10;
//这个类不能实例化
private Arith(){
}
/**
* 提供精确的加法运算。
* @param v1 被加数
* @param v2 加数
* @return 两个参数的和
*/
public static double add(double v1,double v2){
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
return b1.add(b2).doubleValue();
}
/**
* 提供精确的减法运算。
* @param v1 被减数
* @param v2 减数
* @return 两个参数的差
*/
public static double sub(double v1,double v2){
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
return b1.subtract(b2).doubleValue();
}
/**
* 提供精确的乘法运算。
* @param v1 被乘数
* @param v2 乘数
* @return 两个参数的积
*/
public static double mul(double v1,double v2){
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
return b1.multiply(b2).doubleValue();
}
/**
* 提供(相对)精确的除法运算,当发生除不尽的情况时,精确到
* 小数点以后10位,以后的数字四舍五入。
* @param v1 被除数
* @param v2 除数
* @return 两个参数的商
*/
public static double div(double v1,double v2){
return div(v1,v2,DEF_DIV_SCALE);
}
/**
* 提供(相对)精确的除法运算。当发生除不尽的情况时,由scale参数指
* 定精度,以后的数字四舍五入。
* @param v1 被除数
* @param v2 除数
* @param scale 表示表示需要精确到小数点以后几位。
* @return 两个参数的商
*/
public static double div(double v1,double v2,int scale){
if(scale<0){
throw new IllegalArgumentException(
"The scale must be a positive integer or zero");
}
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
return b1.divide(b2,scale,BigDecimal.ROUND_HALF_UP).doubleValue();
}
/**
* 提供精确的小数位四舍五入处理。
* @param v 需要四舍五入的数字
* @param scale 小数点后保留几位
* @return 四舍五入后的结果
*/
public static double round(double v,int scale){
if(scale<0){
throw new IllegalArgumentException(
"The scale must be a positive integer or zero");
}
BigDecimal b = new BigDecimal(Double.toString(v));
BigDecimal one = new BigDecimal("1");
return b.divide(one,scale,BigDecimal.ROUND_HALF_UP).doubleValue();
}
/**
* 提供精确的类型转换(Float)
* @param v 需要被转换的数字
* @return 返回转换结果
*/
public static float convertsToFloat(double v){
BigDecimal b = new BigDecimal(v);
return b.floatValue();
}
/**
* 提供精确的类型转换(Int)不进行四舍五入
* @param v 需要被转换的数字
* @return 返回转换结果
*/
public static int convertsToInt(double v){
BigDecimal b = new BigDecimal(v);
return b.intValue();
}
/**
* 提供精确的类型转换(Long)
* @param v 需要被转换的数字
* @return 返回转换结果
*/
public static long convertsToLong(double v){
BigDecimal b = new BigDecimal(v);
return b.longValue();
}
/**
* 返回两个数中大的一个值
* @param v1 需要被对比的第一个数
* @param v2 需要被对比的第二个数
* @return 返回两个数中大的一个值
*/
public static double returnMax(double v1,double v2){
BigDecimal b1 = new BigDecimal(v1);
BigDecimal b2 = new BigDecimal(v2);
return b1.max(b2).doubleValue();
}
/**
* 返回两个数中小的一个值
* @param v1 需要被对比的第一个数
* @param v2 需要被对比的第二个数
* @return 返回两个数中小的一个值
*/
public static double returnMin(double v1,double v2){
BigDecimal b1 = new BigDecimal(v1);
BigDecimal b2 = new BigDecimal(v2);
return b1.min(b2).doubleValue();
}
/**
* 精确对比两个数字
* @param v1 需要被对比的第一个数
* @param v2 需要被对比的第二个数
* @return 如果两个数一样则返回0,如果第一个数比第二个数大则返回1,反之返回-1
*/
public static int compareTo(double v1,double v2){
BigDecimal b1 = new BigDecimal(v1);
BigDecimal b2 = new BigDecimal(v2);
return b1.compareTo(b2);
}
public static void main(String[] args) {
//0.79 0.92 1.05 1.18
double t1 = 0.79;
double t2 = 0.92;
double t3 = 1.05;
double t4 = 1.18;
double sum = add(t1, t2);
sum = add(sum, t3);
sum = add(sum, t4);
System.out.println("-->"+sum);
// BigDecimal t = new BigDecimal(0.00);
//
// BigDecimal t1 = new BigDecimal(0.79);
// BigDecimal t2 = new BigDecimal(0.92);
// BigDecimal t3 = new BigDecimal(1.05);
// BigDecimal t4 = new BigDecimal(1.18);
// t = t.add(t1);
// t = t.add(t2);
// t = t.add(t3);
// t = t.add(t4);
// System.out.println("t-->"+t);
}
}
|
/*
* Javolution - Java(TM) Solution for Real-Time and Embedded Systems
* Copyright (C) 2012 - Javolution (http://javolution.org/)
* All rights reserved.
*
* Permission to use, copy, modify, and distribute this software is
* freely granted, provided that this notice is preserved.
*/
package javolution.util.internal.table.sorted;
import javolution.util.internal.table.TableView;
import javolution.util.service.SortedTableService;
/**
* Sorted table view implementation; can be used as root class for implementations
* if target is {@code null}.
*/
public abstract class SortedTableView<E> extends TableView<E> implements
SortedTableService<E> {
private static final long serialVersionUID = 0x600L; // Version.
/**
* The view constructor or root class constructor if target is {@code null}.
*/
public SortedTableView(SortedTableService<E> target) {
super(target);
}
@Override
public boolean addIfAbsent(E element) {
if (!contains(element)) return add(element);
return false;
}
@SuppressWarnings("unchecked")
@Override
public int indexOf(Object o) {
int i = positionOf((E) o);
if ((i >= size()) || !comparator().areEqual((E) o, get(i))) return -1;
return i;
}
@SuppressWarnings("unchecked")
@Override
public int lastIndexOf(Object o) {
int i = positionOf((E) o);
int result = -1;
while ((i < size()) && comparator().areEqual((E) o, get(i))) {
result = i++;
}
return result;
}
@Override
public abstract int positionOf(E element);
/** Returns the actual target */
@Override
protected SortedTableService<E> target() {
return (SortedTableService<E>) super.target();
}
}
|
package com.shop.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.shop.bean.model.Area;
import java.util.List;
/**
* @author yzh
*/
public interface AreaService extends IService<Area> {
/**
* 通过pid 查找地址接口
*
* @param pid 父id
* @return
*/
List<Area> listByPid(Long pid);
/**
* 通过pid 清除地址缓存
*
* @param pid
*/
void removeAreaCacheByParentId(Long pid);
}
|
/*
* Copyright (c) 2017-2018 THL A29 Limited, a Tencent company. 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.tencentcloudapi.cdb.v20170320.models;
import com.tencentcloudapi.common.AbstractModel;
import com.google.gson.annotations.SerializedName;
import com.google.gson.annotations.Expose;
import java.util.HashMap;
public class OfflineIsolatedInstancesResponse extends AbstractModel{
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
@SerializedName("RequestId")
@Expose
private String RequestId;
/**
* Get 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
* @return RequestId 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
public String getRequestId() {
return this.RequestId;
}
/**
* Set 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
* @param RequestId 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
public void setRequestId(String RequestId) {
this.RequestId = RequestId;
}
/**
* Internal implementation, normal users should not use it.
*/
public void toMap(HashMap<String, String> map, String prefix) {
this.setParamSimple(map, prefix + "RequestId", this.RequestId);
}
}
|
package org.carlspring.strongbox.artifact.generator;
import org.carlspring.strongbox.artifact.coordinates.NugetArtifactCoordinates;
import org.carlspring.strongbox.artifact.coordinates.versioning.SemanticVersion;
import org.carlspring.strongbox.io.LayoutOutputStream;
import org.carlspring.strongbox.storage.metadata.nuget.Dependencies;
import org.carlspring.strongbox.storage.metadata.nuget.Dependency;
import org.carlspring.strongbox.storage.metadata.nuget.NugetFormatException;
import org.carlspring.strongbox.storage.metadata.nuget.Nuspec;
import org.carlspring.strongbox.testing.artifact.LicenseConfiguration;
import org.carlspring.strongbox.util.MessageDigestUtils;
import org.carlspring.strongbox.util.TestFileUtils;
import javax.xml.bind.JAXBException;
import java.io.*;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Random;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import org.apache.commons.codec.digest.MessageDigestAlgorithms;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Kate Novik.
* @author Pablo Tirado
*/
public class NugetArtifactGenerator
implements ArtifactGenerator
{
private static final Logger logger = LoggerFactory.getLogger(NugetArtifactGenerator.class);
private static final String PSMDCP_CONTENT = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n" +
"<coreProperties xmlns:dc=\"http://purl.org/dc/elements/1.1/\" xmlns:dcterms=\"http://purl.org/dc/terms/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=\"http://schemas.openxmlformats.org/package/2006/m\r\netadata/core-properties\">\r\n " +
"<dc:creator>Carlspring</dc:creator>\r\n " +
"<dc:description>Strongbox Nuget generated package for tests</dc:description>\r\n " +
"<dc:identifier>%s</dc:identifier>\r\n " +
"<version>%s</version>\r\n <keywords>mono strongbox nuget</keywords>\r\n " +
"<lastModifiedBy>org.carlspring.strongbox.artifact.generator.NugetArtifactGenerator</lastModifiedBy>\r\n" +
"</coreProperties>";
private static final String RELS_CONTENT = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n" +
"<Relationships xmlns=\"http://schemas.openxmlformats.org/package/2006/relationships\">\r\n " +
"<Relationship Type=\"http://schemas.microsoft.com/packaging/2010/07/manifest\" Target=\"/%s.nuspec\" Id=\"Rc20b205c579d4f85\" />\r\n " +
"<Relationship Type=\"http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties\" Target=\"/package/services/metadata/core-properties/metadata.psmdcp\" Id=\"R23f62\r\ne2778b3442e\" />\r\n" +
"</Relationships>";
private static final String PACKAGING_NUPKG = "nupkg";
private static final int DEFAULT_BYTE_SIZE = 1000000;
private Path basePath;
public NugetArtifactGenerator(String baseDir)
{
this(Paths.get(baseDir));
}
public NugetArtifactGenerator(Path basePath)
{
this.basePath = basePath.normalize().toAbsolutePath();
}
@Override
public Path generateArtifact(String id,
String version,
long bytesSize)
throws IOException
{
try
{
return generate(id, version, PACKAGING_NUPKG, bytesSize);
}
catch (NoSuchAlgorithmException | JAXBException | NugetFormatException e)
{
throw new IOException(e);
}
}
@Override
public Path generateArtifact(URI uri,
long bytesSize)
throws IOException
{
NugetArtifactCoordinates coordinates = NugetArtifactCoordinates.parse(uri.toString());
return generateArtifact(coordinates, bytesSize);
}
public Path generateArtifact(NugetArtifactCoordinates coordinates,
long bytesSize)
throws IOException
{
return generateArtifact(coordinates.getId(), coordinates.getVersion(), coordinates.getType(), bytesSize);
}
public Path generateArtifact(String id,
String version,
String packaging,
long bytesSize)
throws IOException
{
try
{
return generate(id, version, packaging, bytesSize);
}
catch (NoSuchAlgorithmException | JAXBException | NugetFormatException e)
{
throw new IOException(e);
}
}
public Path generate(String id,
String version,
String packaging,
String... dependencyList)
throws IOException, NoSuchAlgorithmException, JAXBException, NugetFormatException
{
return generate(id, version, packaging, new Random().nextInt(DEFAULT_BYTE_SIZE), dependencyList);
}
public Path generate(String id,
String version,
String packaging,
long bytesSize,
String... dependencyList)
throws IOException, NoSuchAlgorithmException, JAXBException, NugetFormatException
{
NugetArtifactCoordinates coordinates = new NugetArtifactCoordinates(id, version, packaging);
Path fullPath = basePath.resolve(coordinates.toPath()).normalize().toAbsolutePath();
Files.createDirectories(fullPath.getParent());
SemanticVersion semanticVersion = SemanticVersion.parse(version);
logger.debug("Version of the {} package: {}", packaging, semanticVersion.toString());
generate(fullPath, id, semanticVersion, bytesSize, dependencyList);
return fullPath;
}
public void generate(Path packagePath,
String id,
SemanticVersion version,
String... dependencyList)
throws IOException, JAXBException, NoSuchAlgorithmException, NugetFormatException
{
generate(packagePath, id, version, new Random().nextInt(DEFAULT_BYTE_SIZE), dependencyList);
}
public void generate(Path packagePath,
String id,
SemanticVersion version,
long bytesSize,
String... dependencyList)
throws IOException, JAXBException, NoSuchAlgorithmException, NugetFormatException
{
Nuspec nuspec = generateNuspec(id, version, dependencyList);
createArchive(nuspec, packagePath, bytesSize);
generateNuspecFile(nuspec);
}
public void createArchive(Nuspec nuspec,
Path packagePath,
long bytesSize)
throws IOException,
JAXBException,
NoSuchAlgorithmException
{
// Make sure the artifact's parent directory exists before writing the model.
Files.createDirectories(packagePath.getParent());
try (OutputStream fileOutputStream = Files.newOutputStream(packagePath))
{
try (LayoutOutputStream layoutOutputStream = new LayoutOutputStream(fileOutputStream))
{
layoutOutputStream.addAlgorithm(MessageDigestAlgorithms.SHA_512);
layoutOutputStream.setDigestStringifier(this::toBase64);
try (ZipOutputStream zos = new ZipOutputStream(layoutOutputStream))
{
addNugetNuspecFile(nuspec, zos);
TestFileUtils.generateFile(zos, bytesSize, "file-with-given-size");
String id = nuspec.getId();
SemanticVersion version = nuspec.getVersion();
createMetadata(id, version.toString(), zos);
createContentType(zos);
createRels(id, zos);
}
generateChecksum(packagePath, layoutOutputStream);
}
}
}
private void createRels(String id,
ZipOutputStream zos)
throws IOException
{
ZipEntry ze = new ZipEntry("_rels/.rels");
zos.putNextEntry(ze);
ByteArrayInputStream is = new ByteArrayInputStream(String.format(RELS_CONTENT, id).getBytes());
byte[] buffer = new byte[4096];
int len;
while ((len = is.read(buffer)) > 0)
{
zos.write(buffer, 0, len);
}
is.close();
zos.closeEntry();
}
private void createContentType(ZipOutputStream zos)
throws IOException
{
ZipEntry ze = new ZipEntry("[Content_Types].xml");
zos.putNextEntry(ze);
try (InputStream is = getClass().getResourceAsStream("[Content_Types].xml"))
{
byte[] buffer = new byte[4096];
int len;
while ((len = is.read(buffer)) > 0)
{
zos.write(buffer, 0, len);
}
}
zos.closeEntry();
}
private void createMetadata(String id,
String version,
ZipOutputStream zos)
throws IOException
{
ZipEntry ze = new ZipEntry("package/services/metadata/core-properties/metadata.psmdcp");
zos.putNextEntry(ze);
ByteArrayInputStream is = new ByteArrayInputStream(String.format(PSMDCP_CONTENT, id, version).getBytes());
byte[] buffer = new byte[4096];
int len;
while ((len = is.read(buffer)) > 0)
{
zos.write(buffer, 0, len);
}
is.close();
zos.closeEntry();
}
private void addNugetNuspecFile(Nuspec nuspec,
ZipOutputStream zos)
throws IOException, JAXBException
{
ZipEntry ze = new ZipEntry(nuspec.getId() + ".nuspec");
zos.putNextEntry(ze);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
nuspec.saveTo(baos);
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
byte[] buffer = new byte[4096];
int len;
while ((len = bais.read(buffer)) > 0)
{
zos.write(buffer, 0, len);
}
bais.close();
zos.closeEntry();
}
private Nuspec generateNuspec(String id,
SemanticVersion version,
String... dependencyList)
throws NugetFormatException
{
Nuspec nuspec = new Nuspec();
Nuspec.Metadata metadata = nuspec.getMetadata();
metadata.id = id;
metadata.version = version;
metadata.authors = "carlspring";
metadata.owners = "Carlspring Consulting & Development Ltd.";
metadata.licenseUrl = "https://www.apache.org/licenses/LICENSE-2.0";
metadata.description = "Strongbox Nuget package for tests";
if (dependencyList != null)
{
metadata.dependencies = new Dependencies();
metadata.dependencies.dependencies = new ArrayList<>();
for (String dependency : dependencyList)
{
metadata.dependencies.dependencies.add(Dependency.parseString(dependency));
}
}
return nuspec;
}
private void generateNuspecFile(Nuspec nuspec)
throws IOException, JAXBException, NoSuchAlgorithmException
{
String packageId = nuspec.getId();
String packageVersion = nuspec.getVersion().toString();
NugetArtifactCoordinates nac = new NugetArtifactCoordinates(packageId, packageVersion, "nuspec");
Path basePath = Paths.get(getBasedir()).normalize().toAbsolutePath();
Path nuspecPath = basePath.resolve(nac.toPath()).normalize().toAbsolutePath();
Files.createDirectories(nuspecPath.getParent());
try (OutputStream fileOutputStream = Files.newOutputStream(nuspecPath))
{
LayoutOutputStream layoutOutputStream = new LayoutOutputStream(fileOutputStream);
layoutOutputStream.addAlgorithm(MessageDigestAlgorithms.SHA_512);
layoutOutputStream.setDigestStringifier(this::toBase64);
try
{
nuspec.saveTo(layoutOutputStream);
}
finally
{
layoutOutputStream.close();
}
generateChecksum(nuspecPath, layoutOutputStream);
}
}
private String toBase64(byte[] digest)
{
byte[] encoded = Base64.getEncoder().encode(digest);
return new String(encoded, StandardCharsets.UTF_8);
}
private void generateChecksum(Path artifactPath,
LayoutOutputStream layoutOutputStream)
throws IOException
{
String sha512 = layoutOutputStream.getDigestMap().get(MessageDigestAlgorithms.SHA_512);
MessageDigestUtils.writeChecksum(artifactPath, ".sha512", sha512);
}
public String getBasedir()
{
return basePath.normalize().toAbsolutePath().toString();
}
@Override
public void setLicenses(LicenseConfiguration[] licenses)
{
// set Nuget licenses
}
}
|
package org.nutz.castor.castor;
import java.sql.Time;
import java.util.Date;
import org.nutz.castor.Castor;
import org.nutz.castor.FailToCastObjectException;
public class Datetime2SqlTime extends Castor<Date, Time> {
@Override
public Time cast(Date src, Class<?> toType, String... args) throws FailToCastObjectException {
return new Time(src.getTime());
}
}
|
/*
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.facebook.drawee.backends.pipeline.info;
import com.facebook.imagepipeline.listener.BaseRequestListener;
import javax.annotation.Nullable;
/**
* Image origin request listener that maps all image requests for a given Drawee controller to an
* {@link ImageOrigin} and corresponding {@link ImageOriginListener}.
*/
public class ImageOriginRequestListener extends BaseRequestListener {
private final String mControllerId;
private final @Nullable ImageOriginListener mImageOriginLister;
public ImageOriginRequestListener(
String controllerId, @Nullable ImageOriginListener imageOriginLister) {
mControllerId = controllerId;
mImageOriginLister = imageOriginLister;
}
@Override
public void onUltimateProducerReached(String requestId, String producerName, boolean successful) {
if (mImageOriginLister != null) {
mImageOriginLister.onImageLoaded(
mControllerId, ImageOriginUtils.mapProducerNameToImageOrigin(producerName), successful);
}
}
}
|
package module4;
import de.fhpotsdam.unfolding.UnfoldingMap;
import de.fhpotsdam.unfolding.data.Feature;
import de.fhpotsdam.unfolding.data.GeoJSONReader;
import de.fhpotsdam.unfolding.data.PointFeature;
import de.fhpotsdam.unfolding.geo.Location;
import de.fhpotsdam.unfolding.marker.AbstractShapeMarker;
import de.fhpotsdam.unfolding.marker.Marker;
import de.fhpotsdam.unfolding.marker.MultiMarker;
import de.fhpotsdam.unfolding.providers.MBTilesMapProvider;
import de.fhpotsdam.unfolding.providers.Microsoft;
import de.fhpotsdam.unfolding.utils.MapUtils;
import parsing.ParseFeed;
import processing.core.PApplet;
import java.util.ArrayList;
import java.util.List;
/** EarthquakeCityMap
* An application with an interactive map displaying earthquake data.
* Author: UC San Diego Intermediate Software Development MOOC team
* @author Aleksandr
* Date: July 17, 2015
* */
public class EarthquakeCityMap extends PApplet {
// We will use member variables, instead of local variables, to store the data
// that the setUp and draw methods will need to access (as well as other methods)
// You will use many of these variables, but the only one you should need to add
// code to modify is countryQuakes, where you will store the number of earthquakes
// per country.
// You can ignore this. It's to get rid of eclipse warnings
private static final long serialVersionUID = 1L;
// IF YOU ARE WORKING OFFILINE, change the value of this variable to true
private static final boolean offline = false;
/** This is where to find the local tiles, for working without an Internet connection */
private static String mbTilesString = "blankLight-1-3.mbtiles";
//feed with magnitude 2.5+ Earthquakes
private String earthquakesURL = "https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/2.5_week.atom";
// The files containing city names and info and country names and info
private String cityFile = "city-data.json";
private String countryFile = "countries.geo.json";
// The map
private UnfoldingMap map;
// Markers for each city
private List<Marker> cityMarkers;
// Markers for each earthquake
private List<Marker> quakeMarkers;
// A List of country markers
private List<Marker> countryMarkers;
// Colors
private int backgroundColor = color(102, 0, 17);
private int yellow = color(255, 255, 0);
private int blue = color(0, 0, 255);
private int red = color(255, 0, 0);
public void setup() {
//background(102, 0, 17);
// (1) Initializing canvas and map tiles
size(900, 700, OPENGL);
if (offline) {
map = new UnfoldingMap(this, 200, 50, 650, 600, new MBTilesMapProvider(mbTilesString));
earthquakesURL = "2.5_week.atom"; // The same feed, but saved August 7, 2015
}
else {
map = new UnfoldingMap(this, 200, 50, 650, 600, new Microsoft.RoadProvider());
// IF YOU WANT TO TEST WITH A LOCAL FILE, uncomment the next line
//earthquakesURL = "2.5_week.atom";
}
MapUtils.createDefaultEventDispatcher(this, map);
// FOR TESTING: Set earthquakesURL to be one of the testing files by uncommenting
// one of the lines below. This will work whether you are online or offline
//earthquakesURL = "/Users/aleksandrakhmatdianov/Documents/Coursera/UCSDUnfoldingMaps/data/test1.atom";
//earthquakesURL = "/Users/aleksandrakhmatdianov/Documents/Coursera/UCSDUnfoldingMaps/data/test2.atom";
// WHEN TAKING THIS QUIZ: Uncomment the next line
earthquakesURL = "quiz1.atom";
// (2) Reading in earthquake data and geometric properties
// STEP 1: load country features and markers
List<Feature> countries = GeoJSONReader.loadData(this, countryFile);
countryMarkers = MapUtils.createSimpleMarkers(countries);
// STEP 2: read in city data
List<Feature> cities = GeoJSONReader.loadData(this, cityFile);
cityMarkers = new ArrayList<Marker>();
for(Feature city : cities) {
cityMarkers.add(new CityMarker(city));
}
// STEP 3: read in earthquake RSS feed
List<PointFeature> earthquakes = ParseFeed.parseEarthquake(this, earthquakesURL);
quakeMarkers = new ArrayList<Marker>();
for(PointFeature feature : earthquakes) {
//check if LandQuake
if(isLand(feature)) {
quakeMarkers.add(new LandQuakeMarker(feature));
}
// OceanQuakes
else {
quakeMarkers.add(new OceanQuakeMarker(feature));
}
}
// could be used for debugging
printQuakes();
// (3) Add markers to map
// NOTE: Country markers are not added to the map. They are used
// for their geometric properties
map.addMarkers(quakeMarkers);
map.addMarkers(cityMarkers);
} // End setup
public void draw() {
background(backgroundColor);
map.draw();
addKey();
}
public void mouseReleased() {
if (mouseX > 30 && mouseX < 50 && mouseY > 480 && mouseY < 500) {
backgroundColor = color(102, 0, 17);
} else if (mouseX > 30 && mouseX < 50 && mouseY > 520 && mouseY < 540) {
backgroundColor = color(204, 255, 204);
}
}
// helper method to draw key in GUI
// TODO: Update this method as appropriate
private void addKey() {
// Remember you can use Processing's graphics methods here
fill(255, 234, 128);
rect(20, 50, 175, 600);
// Markers
fill(255, 0, 0);
triangle(30, 100, 50, 100, 40, 110);
fill(255);
ellipse(40, 150, 20, 20);
rect(30, 190, 20, 20);
// Texting
fill(0);
textSize(15);
text("Earthquake Keys", 50, 70);
text("City", 65, 110);
text("Land Quake", 65, 155);
text("Ocean Quake", 65, 205);
text("Size ~ magnitude", 50, 250);
// Markers
fill(yellow);
ellipse(40, 290, 20, 20);
fill(blue);
ellipse(40, 340, 20, 20);
fill(red);
ellipse(40, 390, 20, 20);
// Texting
fill(0);
text("Shallow", 65, 295);
text("Intermediate", 65, 345);
text("Deep", 65, 395);
// X on Past Day Quakes
fill(255);
ellipse(40, 440, 20, 20);
fill(0);
line(30, 430, 50, 450);
line (50, 430, 30, 450);
text("Past Day Quake", 65, 445);
// Adding background color setters
fill(102, 0, 17);
rect(30, 480, 20, 20);
fill (204, 255, 204);
rect(30, 520, 20, 20);
fill(0);
text("Background color", 65, 520);
}
// Checks whether this quake occurred on land. If it did, it sets the
// "country" property of its PointFeature to the country where it occurred
// and returns true. Notice that the helper method isInCountry will
// set this "country" property already. Otherwise it returns false.
private boolean isLand(PointFeature earthquake) {
// Loop over all the country markers.
// For each, check if the earthquake PointFeature is in the
// country in m. Notice that isInCountry takes a PointFeature
// and a Marker as input.
// If isInCountry ever returns true, isLand should return true.
for (Marker m : countryMarkers) {
// TODO: Finish this method using the helper method isInCountry
if (isInCountry(earthquake, m)) {
return true;
}
}
// not inside any country
return false;
}
/* prints countries with number of earthquakes as
* Country1: numQuakes1
* Country2: numQuakes2
* ...
* OCEAN QUAKES: numOceanQuakes
* */
private void printQuakes()
{
// TODO: Implement this method
int oceanQuakes = 0;
boolean isNumberOfOceanQuakesFetched = false;
int landQuakes = 0;
boolean isNumberOfLandQuakesFetched = false;
for (Marker marker : countryMarkers) {
String countryName = marker.getStringProperty("name");
int quakeCounter = 0;
for (Marker earthquakeMarker : quakeMarkers) {
if (earthquakeMarker instanceof LandQuakeMarker) {
if (!isNumberOfLandQuakesFetched) {
landQuakes++;
}
String earthquakeCountry = earthquakeMarker.getStringProperty("country");
if (countryName.equals(earthquakeCountry)) {
quakeCounter++;
}
} else if (!isNumberOfOceanQuakesFetched) {
oceanQuakes++;
}
}
isNumberOfOceanQuakesFetched = true;
isNumberOfLandQuakesFetched = true;
if (quakeCounter > 0) {
System.out.println(countryName + ": " + quakeCounter);
}
}
System.out.println("LAND QUAKES TOTAL: " + landQuakes);
System.out.println("OCEAN QUAKES: " + oceanQuakes);
// One (inefficient but correct) approach is to:
// Loop over all of the countries, e.g. using
// for (Marker cm : countryMarkers) { ... }
//
// Inside the loop, first initialize a quake counter.
// Then loop through all of the earthquake
// markers and check to see whether (1) that marker is on land
// and (2) if it is on land, that its country property matches
// the name property of the country marker. If so, increment
// the country's counter.
// Here is some code you will find useful:
//
// * To get the name of a country from a country marker in variable cm, use:
// String name = (String)cm.getProperty("name");
// * If you have a reference to a Marker m, but you know the underlying object
// is an EarthquakeMarker, you can cast it:
// EarthquakeMarker em = (EarthquakeMarker)m;
// Then em can access the methods of the EarthquakeMarker class
// (e.g. isOnLand)
// * If you know your Marker, m, is a LandQuakeMarker, then it has a "country"
// property set. You can get the country with:
// String country = (String)m.getProperty("country");
}
// helper method to test whether a given earthquake is in a given country
// This will also add the country property to the properties of the earthquake
// feature if it's in one of the countries.
// You should not have to modify this code
private boolean isInCountry(PointFeature earthquake, Marker country) {
// getting location of feature
Location checkLoc = earthquake.getLocation();
// some countries represented it as MultiMarker
// looping over SimplePolygonMarkers which make them up to use isInsideByLoc
if(country.getClass() == MultiMarker.class) {
// looping over markers making up MultiMarker
for(Marker marker : ((MultiMarker)country).getMarkers()) {
// checking if inside
if(((AbstractShapeMarker)marker).isInsideByLocation(checkLoc)) {
earthquake.addProperty("country", country.getProperty("name"));
// return if is inside one
return true;
}
}
}
// check if inside country represented by SimplePolygonMarker
else if(((AbstractShapeMarker)country).isInsideByLocation(checkLoc)) {
earthquake.addProperty("country", country.getProperty("name"));
return true;
}
return false;
}
}
|
package org.benf.cfr.tests;
/**
* Created by IntelliJ IDEA.
* User: lee
* Date: 05/05/2011
* Time: 18:48
*/
public class SyncTest6 {
private int x[];
/* This doesn't currently work, because we are
* incorrectly pushing intermediate expression computation
* past a monitorexit.
*
* This needs to be banned.
*
* public int test1();
Code:
0: aload_0
1: dup
2: astore_1
3: monitorenter
4: aload_0
5: getfield #2; //Field x:[I
8: iconst_2
9: iaload
10: aload_1
11: monitorexit
12: ireturn <<-- the return is after the exit, but we're pushing the computed value here.
13: astore_2
14: aload_1
15: monitorexit
16: aload_2
17: athrow
*/
public int test1() {
synchronized (this) {
return x[2];
}
}
}
|
package com.taskagile.domain.model.activity;
import com.taskagile.domain.model.board.events.BoardCreatedEvent;
import com.taskagile.domain.model.board.events.BoardMemberAddedEvent;
public class BoardActivities {
public static Activity from(BoardCreatedEvent event) {
String detail = ActivityDetail.blank()
.add("boardName", event.getBoardName())
.toJson();
return Activity.from(event.getUserId(), event.getBoardId(), ActivityType.ADD_BOARD,
detail, event.getIpAddress());
}
public static Activity from(BoardMemberAddedEvent event) {
String detail = ActivityDetail.blank()
.add("memberUserId", event.getMemberUserId().value())
.add("memberName", event.getMemberName())
.toJson();
return Activity.from(event.getUserId(), event.getBoardId(), ActivityType.ADD_BOARD_MEMBER,
detail, event.getIpAddress());
}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache license, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the license for the specific language governing permissions and
* limitations under the license.
*/
package org.apache.logging.log4j.plugins.convert;
/**
* Converts Strings to hex. This is used in place of java.xml.bind.DataTypeConverter which is not available by
* default in Java 9.
*
* @since 2.9
*/
public class HexConverter {
public static byte[] parseHexBinary(final String s) {
final int len = s.length();
final byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
+ Character.digit(s.charAt(i+1), 16));
}
return data;
}
}
|
// Copyright 2021 The Terasology Foundation
// SPDX-License-Identifier: Apache-2.0
package org.terasology.engine.audio;
import org.terasology.gestalt.assets.Asset;
import org.terasology.gestalt.assets.AssetData;
import org.terasology.gestalt.assets.AssetType;
import org.terasology.gestalt.assets.DisposableResource;
import org.terasology.gestalt.assets.ResourceUrn;
/**
* An abstract class
* @param <T> The asset type this asset belongs to
*/
public abstract class Sound<T extends AssetData> extends Asset<T> implements org.terasology.nui.asset.Sound {
/**
* The constructor for an asset.
* It is suggested that implementing classes provide a constructor taking both the urn, and an initial AssetData to load.
*
* @param urn The urn identifying the asset.
* @param assetType The asset type this asset belongs to.
*/
protected Sound(ResourceUrn urn, AssetType<?, T> assetType, DisposableResource resource) {
super(urn, assetType, resource);
}
/**
* The constructor for an asset.
* It is suggested that implementing classes provide a constructor taking both the urn, and an initial AssetData to load.
*
* @param urn The urn identifying the asset.
* @param assetType The asset type this asset belongs to.
*/
protected Sound(ResourceUrn urn, AssetType<?, T> assetType) {
super(urn, assetType);
}
/**
* @return channels amount of sound (1 - mono, 2 - stereo)
*/
public abstract int getChannels();
/**
* @return sampling rate of sound (example 44100)
*/
public abstract int getSamplingRate();
/**
* @return the size of the sound buffer
*/
public abstract int getBufferSize();
/**
* Plays the sound at full volume.
*/
public abstract void play();
/**
* Plays the sound at the given volume.
* @param volume
*/
public abstract void play(float volume);
}
|
package com.cdesigner.mgr.req;
import org.apache.commons.lang3.StringUtils;
/**
* @author 刘飞 E-mail:liufei_it@126.com
*
* @version 1.0.0
* @since 2015年7月4日 下午7:02:30
*/
public class IndustryListRequest extends PageRequest {
private Long id;
private String name;
private Integer listed = 1;
@Override
protected IndustryListRequest Q() {
StringBuilder sb = new StringBuilder();
boolean appended = false;
if (StringUtils.isNotBlank(name)) {
sb.append("name").append("=").append(name);
appended = true;
}
if (listed != null) {
if (appended) {
sb.append("&");
}
sb.append("listed").append("=").append(listed);
appended = true;
}
if (id != null && id > 0L) {
if (appended) {
sb.append("&");
}
sb.append("id").append("=").append(id);
appended = true;
}
getQuery().setQueryString(sb.toString());
return this;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getListed() {
return listed;
}
public void setListed(Integer listed) {
this.listed = listed;
}
}
|
package org.xtuml.bp.als.oal;
//====================================================================
//
// File: $RCSfile: OalPlugin.java,v $
// Version: $Revision: 1.13 $
// Modified: $Date: 2013/01/10 23:43:47 $
//
// (c) Copyright 2003-2014 Mentor Graphics Corporation All rights reserved.
//
//====================================================================
//
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.ui.plugin.AbstractUIPlugin;
/**
* The main plugin class to be used in the desktop.
*/
public class OalPlugin extends AbstractUIPlugin {
//The shared instance.
private static OalPlugin plugin;
//Resource bundle.
private ResourceBundle resourceBundle;
/**
* The constructor.
*/
public OalPlugin() {
super();
plugin = this;
try {
resourceBundle= ResourceBundle.getBundle("org.xtuml.bp.als.oal.OalPluginResources");
} catch (MissingResourceException x) {
resourceBundle = null;
}
}
/**
* Returns the shared instance.
*/
public static OalPlugin getDefault() {
return plugin;
}
/**
* Returns the workspace instance.
*/
public static IWorkspace getWorkspace() {
return ResourcesPlugin.getWorkspace();
}
/**
* Returns the string from the plugin's resource bundle,
* or 'key' if not found.
*/
public static String getResourceString(String key) {
ResourceBundle bundle= OalPlugin.getDefault().getResourceBundle();
try {
return bundle.getString(key);
} catch (MissingResourceException e) {
return key;
}
}
/**
* Returns the plugin's resource bundle,
*/
public ResourceBundle getResourceBundle() {
return resourceBundle;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.