hexsha stringlengths 40 40 | size int64 8 1.04M | content stringlengths 8 1.04M | avg_line_length float64 2.24 100 | max_line_length int64 4 1k | alphanum_fraction float64 0.25 0.97 |
|---|---|---|---|---|---|
2e8a5afa52691d942a6663939bb07caafadba2ad | 1,093 | /*
* Copyright 2015 Dmitry Ovchinnikov.
*
* 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.dimitrovchi.enumlike.base;
import java.util.List;
import javax.annotation.Nonnull;
/**
* Typed key container.
*
* @param <E> Key type.
*
* @author Dmitry Ovchinnikov
*/
public interface TypedKeyContainer<E extends TypedKey> {
/**
* Get elements.
* @return Typed key elements.
*/
@Nonnull
List<E> getElements();
/**
* Get element class.
* @return Element class.
*/
@Nonnull
Class<E> getElementClass();
}
| 24.840909 | 75 | 0.67978 |
1a7ad2fea592bbe3e4340caad1d145edfa88fb84 | 464 | package datastruct;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.Stack;
public class StackNMap2 {
public static void main(String[] args) {
Map<String, String> envs = System.getenv();
System.out.println(envs);
Set<String> stringKeyset = envs.keySet();
String envValue;
for(String key : stringKeyset) {
envValue = envs.get(key);
System.out.println(key + " : " + envValue);
}
}
}
| 20.173913 | 45 | 0.713362 |
18aa2cba981e6f71804cee9e068b108ade0699bf | 1,803 | /**
* 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.pulsar.functions.runtime;
import org.testng.Assert;
import org.testng.annotations.Test;
public class RuntimeUtilsTest {
@Test
public void testSplitRuntimeArgs() {
String str1 = "-Xms314572800";
String[] result = RuntimeUtils.splitRuntimeArgs(str1);
Assert.assertEquals(result.length,1);
Assert.assertEquals(result[0], str1);
String str2 = "-Xms314572800 -Dbar=foo";
result = RuntimeUtils.splitRuntimeArgs(str2);
Assert.assertEquals(result.length,2);
Assert.assertEquals(result[0], "-Xms314572800");
Assert.assertEquals(result[1], "-Dbar=foo");
String str3 = "-Xms314572800 -Dbar=foo -Dfoo=\"bar foo\"";
result = RuntimeUtils.splitRuntimeArgs(str3);
Assert.assertEquals(result.length,3);
Assert.assertEquals(result[0], "-Xms314572800");
Assert.assertEquals(result[1], "-Dbar=foo");
Assert.assertEquals(result[2], "-Dfoo=\"bar foo\"");
}
}
| 38.361702 | 66 | 0.699945 |
90c72c9a8a9d4055a0111f2e6e3979839bf69aae | 2,690 | /*
* 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.bval.constraints;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.constraints.Digits;
import java.math.BigDecimal;
/**
* Validates that the <code>Number</code> being validates matches the pattern
* defined in the constraint.
*/
public class DigitsValidatorForNumber implements ConstraintValidator<Digits, Number> {
private int integral;
private int fractional;
public int getIntegral() {
return integral;
}
public void setIntegral(int integral) {
this.integral = integral;
}
public int getFractional() {
return fractional;
}
public void setFractional(int fractional) {
this.fractional = fractional;
}
public void initialize(Digits annotation) {
this.integral = annotation.integer();
this.fractional = annotation.fraction();
if (integral < 0) {
throw new IllegalArgumentException("The length of the integer part cannot be negative.");
}
if (fractional < 0) {
throw new IllegalArgumentException("The length of the fraction part cannot be negative.");
}
}
public boolean isValid(Number num, ConstraintValidatorContext context) {
if (num == null) {
return true;
}
BigDecimal bigDecimal;
if (num instanceof BigDecimal) {
bigDecimal = (BigDecimal) num;
} else {
bigDecimal = new BigDecimal(num.toString());
}
bigDecimal = bigDecimal.stripTrailingZeros();
final int intLength = bigDecimal.precision() - bigDecimal.scale();
if (integral >= intLength) {
int factionLength = bigDecimal.scale() < 0 ? 0 : bigDecimal.scale();
return fractional >= factionLength;
}
return false;
}
}
| 32.409639 | 102 | 0.676208 |
1e5e9a738e7c86dd84bfa7ad7b6bd4f96980d38b | 21,303 | /*
* 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.location.model;
import java.io.Serializable;
import javax.annotation.Generated;
/**
* <p>
* Returns the result of the route calculation. Metadata includes legs and route summary.
* </p>
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/location-2020-11-19/CalculateRoute" target="_top">AWS API
* Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class CalculateRouteResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable {
/**
* <p>
* Contains details about each path between a pair of positions included along a route such as:
* <code>StartPosition</code>, <code>EndPosition</code>, <code>Distance</code>, <code>DurationSeconds</code>,
* <code>Geometry</code>, and <code>Steps</code>. The number of legs returned corresponds to one fewer than the
* total number of positions in the request.
* </p>
* <p>
* For example, a route with a departure position and destination position returns one leg with the positions <a
* href
* ="https://docs.aws.amazon.com/location/latest/developerguide/calculate-route.html#snap-to-nearby-road">snapped to
* a nearby road</a>:
* </p>
* <ul>
* <li>
* <p>
* The <code>StartPosition</code> is the departure position.
* </p>
* </li>
* <li>
* <p>
* The <code>EndPosition</code> is the destination position.
* </p>
* </li>
* </ul>
* <p>
* A route with a waypoint between the departure and destination position returns two legs with the positions
* snapped to a nearby road:
* </p>
* <ul>
* <li>
* <p>
* Leg 1: The <code>StartPosition</code> is the departure position . The <code>EndPosition</code> is the waypoint
* positon.
* </p>
* </li>
* <li>
* <p>
* Leg 2: The <code>StartPosition</code> is the waypoint position. The <code>EndPosition</code> is the destination
* position.
* </p>
* </li>
* </ul>
*/
private java.util.List<Leg> legs;
/**
* <p>
* Contains information about the whole route, such as: <code>RouteBBox</code>, <code>DataSource</code>,
* <code>Distance</code>, <code>DistanceUnit</code>, and <code>DurationSeconds</code>.
* </p>
*/
private CalculateRouteSummary summary;
/**
* <p>
* Contains details about each path between a pair of positions included along a route such as:
* <code>StartPosition</code>, <code>EndPosition</code>, <code>Distance</code>, <code>DurationSeconds</code>,
* <code>Geometry</code>, and <code>Steps</code>. The number of legs returned corresponds to one fewer than the
* total number of positions in the request.
* </p>
* <p>
* For example, a route with a departure position and destination position returns one leg with the positions <a
* href
* ="https://docs.aws.amazon.com/location/latest/developerguide/calculate-route.html#snap-to-nearby-road">snapped to
* a nearby road</a>:
* </p>
* <ul>
* <li>
* <p>
* The <code>StartPosition</code> is the departure position.
* </p>
* </li>
* <li>
* <p>
* The <code>EndPosition</code> is the destination position.
* </p>
* </li>
* </ul>
* <p>
* A route with a waypoint between the departure and destination position returns two legs with the positions
* snapped to a nearby road:
* </p>
* <ul>
* <li>
* <p>
* Leg 1: The <code>StartPosition</code> is the departure position . The <code>EndPosition</code> is the waypoint
* positon.
* </p>
* </li>
* <li>
* <p>
* Leg 2: The <code>StartPosition</code> is the waypoint position. The <code>EndPosition</code> is the destination
* position.
* </p>
* </li>
* </ul>
*
* @return Contains details about each path between a pair of positions included along a route such as:
* <code>StartPosition</code>, <code>EndPosition</code>, <code>Distance</code>, <code>DurationSeconds</code>
* , <code>Geometry</code>, and <code>Steps</code>. The number of legs returned corresponds to one fewer
* than the total number of positions in the request. </p>
* <p>
* For example, a route with a departure position and destination position returns one leg with the
* positions <a href=
* "https://docs.aws.amazon.com/location/latest/developerguide/calculate-route.html#snap-to-nearby-road"
* >snapped to a nearby road</a>:
* </p>
* <ul>
* <li>
* <p>
* The <code>StartPosition</code> is the departure position.
* </p>
* </li>
* <li>
* <p>
* The <code>EndPosition</code> is the destination position.
* </p>
* </li>
* </ul>
* <p>
* A route with a waypoint between the departure and destination position returns two legs with the
* positions snapped to a nearby road:
* </p>
* <ul>
* <li>
* <p>
* Leg 1: The <code>StartPosition</code> is the departure position . The <code>EndPosition</code> is the
* waypoint positon.
* </p>
* </li>
* <li>
* <p>
* Leg 2: The <code>StartPosition</code> is the waypoint position. The <code>EndPosition</code> is the
* destination position.
* </p>
* </li>
*/
public java.util.List<Leg> getLegs() {
return legs;
}
/**
* <p>
* Contains details about each path between a pair of positions included along a route such as:
* <code>StartPosition</code>, <code>EndPosition</code>, <code>Distance</code>, <code>DurationSeconds</code>,
* <code>Geometry</code>, and <code>Steps</code>. The number of legs returned corresponds to one fewer than the
* total number of positions in the request.
* </p>
* <p>
* For example, a route with a departure position and destination position returns one leg with the positions <a
* href
* ="https://docs.aws.amazon.com/location/latest/developerguide/calculate-route.html#snap-to-nearby-road">snapped to
* a nearby road</a>:
* </p>
* <ul>
* <li>
* <p>
* The <code>StartPosition</code> is the departure position.
* </p>
* </li>
* <li>
* <p>
* The <code>EndPosition</code> is the destination position.
* </p>
* </li>
* </ul>
* <p>
* A route with a waypoint between the departure and destination position returns two legs with the positions
* snapped to a nearby road:
* </p>
* <ul>
* <li>
* <p>
* Leg 1: The <code>StartPosition</code> is the departure position . The <code>EndPosition</code> is the waypoint
* positon.
* </p>
* </li>
* <li>
* <p>
* Leg 2: The <code>StartPosition</code> is the waypoint position. The <code>EndPosition</code> is the destination
* position.
* </p>
* </li>
* </ul>
*
* @param legs
* Contains details about each path between a pair of positions included along a route such as:
* <code>StartPosition</code>, <code>EndPosition</code>, <code>Distance</code>, <code>DurationSeconds</code>,
* <code>Geometry</code>, and <code>Steps</code>. The number of legs returned corresponds to one fewer than
* the total number of positions in the request. </p>
* <p>
* For example, a route with a departure position and destination position returns one leg with the positions
* <a href=
* "https://docs.aws.amazon.com/location/latest/developerguide/calculate-route.html#snap-to-nearby-road"
* >snapped to a nearby road</a>:
* </p>
* <ul>
* <li>
* <p>
* The <code>StartPosition</code> is the departure position.
* </p>
* </li>
* <li>
* <p>
* The <code>EndPosition</code> is the destination position.
* </p>
* </li>
* </ul>
* <p>
* A route with a waypoint between the departure and destination position returns two legs with the positions
* snapped to a nearby road:
* </p>
* <ul>
* <li>
* <p>
* Leg 1: The <code>StartPosition</code> is the departure position . The <code>EndPosition</code> is the
* waypoint positon.
* </p>
* </li>
* <li>
* <p>
* Leg 2: The <code>StartPosition</code> is the waypoint position. The <code>EndPosition</code> is the
* destination position.
* </p>
* </li>
*/
public void setLegs(java.util.Collection<Leg> legs) {
if (legs == null) {
this.legs = null;
return;
}
this.legs = new java.util.ArrayList<Leg>(legs);
}
/**
* <p>
* Contains details about each path between a pair of positions included along a route such as:
* <code>StartPosition</code>, <code>EndPosition</code>, <code>Distance</code>, <code>DurationSeconds</code>,
* <code>Geometry</code>, and <code>Steps</code>. The number of legs returned corresponds to one fewer than the
* total number of positions in the request.
* </p>
* <p>
* For example, a route with a departure position and destination position returns one leg with the positions <a
* href
* ="https://docs.aws.amazon.com/location/latest/developerguide/calculate-route.html#snap-to-nearby-road">snapped to
* a nearby road</a>:
* </p>
* <ul>
* <li>
* <p>
* The <code>StartPosition</code> is the departure position.
* </p>
* </li>
* <li>
* <p>
* The <code>EndPosition</code> is the destination position.
* </p>
* </li>
* </ul>
* <p>
* A route with a waypoint between the departure and destination position returns two legs with the positions
* snapped to a nearby road:
* </p>
* <ul>
* <li>
* <p>
* Leg 1: The <code>StartPosition</code> is the departure position . The <code>EndPosition</code> is the waypoint
* positon.
* </p>
* </li>
* <li>
* <p>
* Leg 2: The <code>StartPosition</code> is the waypoint position. The <code>EndPosition</code> is the destination
* position.
* </p>
* </li>
* </ul>
* <p>
* <b>NOTE:</b> This method appends the values to the existing list (if any). Use
* {@link #setLegs(java.util.Collection)} or {@link #withLegs(java.util.Collection)} if you want to override the
* existing values.
* </p>
*
* @param legs
* Contains details about each path between a pair of positions included along a route such as:
* <code>StartPosition</code>, <code>EndPosition</code>, <code>Distance</code>, <code>DurationSeconds</code>,
* <code>Geometry</code>, and <code>Steps</code>. The number of legs returned corresponds to one fewer than
* the total number of positions in the request. </p>
* <p>
* For example, a route with a departure position and destination position returns one leg with the positions
* <a href=
* "https://docs.aws.amazon.com/location/latest/developerguide/calculate-route.html#snap-to-nearby-road"
* >snapped to a nearby road</a>:
* </p>
* <ul>
* <li>
* <p>
* The <code>StartPosition</code> is the departure position.
* </p>
* </li>
* <li>
* <p>
* The <code>EndPosition</code> is the destination position.
* </p>
* </li>
* </ul>
* <p>
* A route with a waypoint between the departure and destination position returns two legs with the positions
* snapped to a nearby road:
* </p>
* <ul>
* <li>
* <p>
* Leg 1: The <code>StartPosition</code> is the departure position . The <code>EndPosition</code> is the
* waypoint positon.
* </p>
* </li>
* <li>
* <p>
* Leg 2: The <code>StartPosition</code> is the waypoint position. The <code>EndPosition</code> is the
* destination position.
* </p>
* </li>
* @return Returns a reference to this object so that method calls can be chained together.
*/
public CalculateRouteResult withLegs(Leg... legs) {
if (this.legs == null) {
setLegs(new java.util.ArrayList<Leg>(legs.length));
}
for (Leg ele : legs) {
this.legs.add(ele);
}
return this;
}
/**
* <p>
* Contains details about each path between a pair of positions included along a route such as:
* <code>StartPosition</code>, <code>EndPosition</code>, <code>Distance</code>, <code>DurationSeconds</code>,
* <code>Geometry</code>, and <code>Steps</code>. The number of legs returned corresponds to one fewer than the
* total number of positions in the request.
* </p>
* <p>
* For example, a route with a departure position and destination position returns one leg with the positions <a
* href
* ="https://docs.aws.amazon.com/location/latest/developerguide/calculate-route.html#snap-to-nearby-road">snapped to
* a nearby road</a>:
* </p>
* <ul>
* <li>
* <p>
* The <code>StartPosition</code> is the departure position.
* </p>
* </li>
* <li>
* <p>
* The <code>EndPosition</code> is the destination position.
* </p>
* </li>
* </ul>
* <p>
* A route with a waypoint between the departure and destination position returns two legs with the positions
* snapped to a nearby road:
* </p>
* <ul>
* <li>
* <p>
* Leg 1: The <code>StartPosition</code> is the departure position . The <code>EndPosition</code> is the waypoint
* positon.
* </p>
* </li>
* <li>
* <p>
* Leg 2: The <code>StartPosition</code> is the waypoint position. The <code>EndPosition</code> is the destination
* position.
* </p>
* </li>
* </ul>
*
* @param legs
* Contains details about each path between a pair of positions included along a route such as:
* <code>StartPosition</code>, <code>EndPosition</code>, <code>Distance</code>, <code>DurationSeconds</code>,
* <code>Geometry</code>, and <code>Steps</code>. The number of legs returned corresponds to one fewer than
* the total number of positions in the request. </p>
* <p>
* For example, a route with a departure position and destination position returns one leg with the positions
* <a href=
* "https://docs.aws.amazon.com/location/latest/developerguide/calculate-route.html#snap-to-nearby-road"
* >snapped to a nearby road</a>:
* </p>
* <ul>
* <li>
* <p>
* The <code>StartPosition</code> is the departure position.
* </p>
* </li>
* <li>
* <p>
* The <code>EndPosition</code> is the destination position.
* </p>
* </li>
* </ul>
* <p>
* A route with a waypoint between the departure and destination position returns two legs with the positions
* snapped to a nearby road:
* </p>
* <ul>
* <li>
* <p>
* Leg 1: The <code>StartPosition</code> is the departure position . The <code>EndPosition</code> is the
* waypoint positon.
* </p>
* </li>
* <li>
* <p>
* Leg 2: The <code>StartPosition</code> is the waypoint position. The <code>EndPosition</code> is the
* destination position.
* </p>
* </li>
* @return Returns a reference to this object so that method calls can be chained together.
*/
public CalculateRouteResult withLegs(java.util.Collection<Leg> legs) {
setLegs(legs);
return this;
}
/**
* <p>
* Contains information about the whole route, such as: <code>RouteBBox</code>, <code>DataSource</code>,
* <code>Distance</code>, <code>DistanceUnit</code>, and <code>DurationSeconds</code>.
* </p>
*
* @param summary
* Contains information about the whole route, such as: <code>RouteBBox</code>, <code>DataSource</code>,
* <code>Distance</code>, <code>DistanceUnit</code>, and <code>DurationSeconds</code>.
*/
public void setSummary(CalculateRouteSummary summary) {
this.summary = summary;
}
/**
* <p>
* Contains information about the whole route, such as: <code>RouteBBox</code>, <code>DataSource</code>,
* <code>Distance</code>, <code>DistanceUnit</code>, and <code>DurationSeconds</code>.
* </p>
*
* @return Contains information about the whole route, such as: <code>RouteBBox</code>, <code>DataSource</code>,
* <code>Distance</code>, <code>DistanceUnit</code>, and <code>DurationSeconds</code>.
*/
public CalculateRouteSummary getSummary() {
return this.summary;
}
/**
* <p>
* Contains information about the whole route, such as: <code>RouteBBox</code>, <code>DataSource</code>,
* <code>Distance</code>, <code>DistanceUnit</code>, and <code>DurationSeconds</code>.
* </p>
*
* @param summary
* Contains information about the whole route, such as: <code>RouteBBox</code>, <code>DataSource</code>,
* <code>Distance</code>, <code>DistanceUnit</code>, and <code>DurationSeconds</code>.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public CalculateRouteResult withSummary(CalculateRouteSummary summary) {
setSummary(summary);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getLegs() != null)
sb.append("Legs: ").append(getLegs()).append(",");
if (getSummary() != null)
sb.append("Summary: ").append(getSummary());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof CalculateRouteResult == false)
return false;
CalculateRouteResult other = (CalculateRouteResult) obj;
if (other.getLegs() == null ^ this.getLegs() == null)
return false;
if (other.getLegs() != null && other.getLegs().equals(this.getLegs()) == false)
return false;
if (other.getSummary() == null ^ this.getSummary() == null)
return false;
if (other.getSummary() != null && other.getSummary().equals(this.getSummary()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getLegs() == null) ? 0 : getLegs().hashCode());
hashCode = prime * hashCode + ((getSummary() == null) ? 0 : getSummary().hashCode());
return hashCode;
}
@Override
public CalculateRouteResult clone() {
try {
return (CalculateRouteResult) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
}
| 37.571429 | 147 | 0.57053 |
09e3264e59688f5afc041bc35ba161a719e7a204 | 1,084 | /**
*
*/
package com.co.app.auth.configuration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.expression.method.MethodSecurityExpressionHandler;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration;
import com.co.app.auth.authorize.CustomMethodSecurityExpressionHandler;
import com.co.app.auth.services.AuthUserService;
/**
* @author alobaton
*
*/
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class MethodSecurityConfig extends GlobalMethodSecurityConfiguration {
@Autowired
private AuthUserService userService;
/**
* Creates an expression handler for the method security context.
*/
@Override
protected MethodSecurityExpressionHandler createExpressionHandler() {
return new CustomMethodSecurityExpressionHandler(userService);
}
} | 32.848485 | 109 | 0.836716 |
da1b56acb42a4672b2782f545a8f2cea3b29f088 | 5,634 | package org.maptalks.geojson.json;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.maptalks.geojson.*;
import java.util.HashMap;
import java.util.Map;
public class GeoJSONFactory {
static Map<String, Class> geoJsonTypeMap = new HashMap<String, Class>();
static {
geoJsonTypeMap.put(GeoJSONTypes.TYPE_POINT,Point.class);
geoJsonTypeMap.put(GeoJSONTypes.TYPE_LINESTRING,LineString.class);
geoJsonTypeMap.put(GeoJSONTypes.TYPE_POLYGON,Polygon.class);
geoJsonTypeMap.put(GeoJSONTypes.TYPE_MULTIPOINT,MultiPoint.class);
geoJsonTypeMap.put(GeoJSONTypes.TYPE_MULTILINESTRING,MultiLineString.class);
geoJsonTypeMap.put(GeoJSONTypes.TYPE_MULTIPOLYGON,MultiPolygon.class);
geoJsonTypeMap.put(GeoJSONTypes.TYPE_GEOMETRYCOLLECTION,GeometryCollection.class);
}
public static GeoJSON create(String json) {
JSONObject node = JSON.parseObject(json);
return create(node);
}
/**
* 将json解析为FeatureCollection数组
* @param json
* @return
*/
public static FeatureCollection[] createFeatureCollectionArray(String json) {
JSONArray node = JSON.parseArray(json);
int size = node.size();
FeatureCollection[] result = new FeatureCollection[size];
for (int i = 0; i < size; i++) {
if (node.get(i) == null) {
result[i] = null;
continue;
}
result[i] = ((FeatureCollection) create(((JSONObject) node.get(i))));
}
return result;
}
/**
* 将json解析为Feature数组
* @param json
* @return
*/
public static Feature[] createFeatureArray(String json) {
JSONArray node = JSON.parseArray(json);
int size = node.size();
Feature[] result = new Feature[size];
for (int i = 0; i < size; i++) {
if (node.get(i) == null) {
result[i] = null;
continue;
}
GeoJSON geojson = create(((JSONObject) node.get(i)));
if (geojson instanceof Geometry) {
result[i] = new Feature(((Geometry) geojson));
} else {
result[i] = ((Feature) geojson);
}
}
return result;
}
/**
* 将json解析为Geometry数组
* @param json
* @return
*/
public static Geometry[] createGeometryArray(String json) {
JSONArray node = JSON.parseArray(json);
int size = node.size();
Geometry[] result = new Geometry[size];
for (int i = 0; i < size; i++) {
if (node.get(i) == null) {
result[i] = null;
continue;
}
GeoJSON geojson = create(((JSONObject) node.get(i)));
if (geojson instanceof Feature) {
result[i] = ((Feature) geojson).getGeometry();
} else {
result[i] = ((Geometry) geojson);
}
}
return result;
}
public static GeoJSON create(JSONObject node) {
String type = node.getString("type");
if ("FeatureCollection".equals(type)) {
return readFeatureCollection(node);
} else if ("Feature".equals(type)) {
return readFeature(node);
} else {
return readGeometry(node, type);
}
}
private static FeatureCollection readFeatureCollection(JSONObject node) {
JSONArray jFeatures = node.getJSONArray("features");
if (jFeatures == null) {
//return a empty FeatureCollection
FeatureCollection result = new FeatureCollection();
result.setFeatures(new Feature[0]);
return result;
}
int size = jFeatures.size();
Feature[] features = new Feature[size];
for (int i=0;i<size;i++) {
features[i] = readFeature(jFeatures.getJSONObject(i));
}
FeatureCollection result = new FeatureCollection();
result.setFeatures(features);
return result;
}
private static Feature readFeature(JSONObject node) {
JSONObject geoJ = node.getJSONObject("geometry");
Geometry geo = null;
if (geoJ != null) {
geo = readGeometry(geoJ, geoJ.getString("type"));
}
node.remove("geometry");
Feature result = JSON.toJavaObject(node, Feature.class);
result.setGeometry(geo);
return result;
}
private static Geometry readGeometry(JSONObject node, String type) {
if (GeoJSONTypes.TYPE_GEOMETRYCOLLECTION.equals(type)) {
GeometryCollection result = new GeometryCollection(new Geometry[0]);
JSONArray jGeos = node.getJSONArray("geometries");
if (jGeos != null) {
int size = jGeos.size();
Geometry[] geometries = new Geometry[size];
for (int i=0;i<size;i++) {
JSONObject jgeo = jGeos.getJSONObject(i);
geometries[i] = readGeometry(jgeo, jgeo.getString("type"));
}
result.setGeometries(geometries);
} else {
//return a empty GeometryCollection
result.setGeometries(new Geometry[0]);
}
return result;
}
Class clazz = getGeoJsonType(type);
Object obj = JSON.toJavaObject(node, clazz);
return ((Geometry) obj);
}
public static Class getGeoJsonType(String type) {
Class clazz = geoJsonTypeMap.get(type);
return clazz;
}
}
| 33.535714 | 90 | 0.575612 |
62c256897143d81e476feb3c05695b68627512b1 | 949 | /*
* 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 com.docuware.dev.Extensions;
import java.io.Closeable;
import java.io.InputStream;
/**
*
* @author Patrick
*/
public class EasyCheckoutResult implements Closeable {
private String EncodedFileName;
public String getEncodedFileName() {
return EncodedFileName;
}
void setEncodedFileName(String data) {
EncodedFileName = data;
}
private DeserializedHttpResponseGen<InputStream> response;
public DeserializedHttpResponseGen<InputStream> getResponse() {
return response;
}
void setResponse(DeserializedHttpResponseGen<InputStream> data) {
response = data;
}
@Override
public void close() {
this.response.close();
}
}
| 22.595238 | 80 | 0.668072 |
68c57545308e227e9d0993586e4e7db4ee1c2d23 | 2,016 | package org.talend.librariesmanager.nexus.utils;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
public class RestAPIUtil {
public static String[] doRequest(String uri, String httpmethod, String user, String password, String data)
throws Exception {
String[] ret = new String[2];
StringBuffer response = new StringBuffer();
URL url = new URL(uri);
String auth = user + ":" + password;
try {
byte[] encodedAuth = Base64.getEncoder().encode((auth.getBytes(StandardCharsets.UTF_8)));
String authHeaderValue = "Basic " + new String(encodedAuth);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("Authorization", authHeaderValue);
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Accept", "application/json");
conn.setRequestMethod(httpmethod);
if (data != null) {
conn.setDoOutput(true);
conn.setDoInput(true);
conn.connect();
try (OutputStreamWriter streamWriter = new OutputStreamWriter(conn.getOutputStream());) {
streamWriter.write(data);
streamWriter.flush();
}
}
int responsecode = conn.getResponseCode();
debug(responsecode + " is returned for " + httpmethod + " on the endpoint:" + uri);
ret[0] = Integer.toString(responsecode);
try (BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"))) {
String responseLine = null;
while ((responseLine = br.readLine()) != null) {
response.append(responseLine.trim());
}
}
ret[1] = response.toString();
conn.disconnect();
} catch (Exception ex) {
debug(ex.getMessage());
throw ex;
}
return ret;
}
private static void debug(String message) {
System.out.println("[DEBUG]:" + message);
}
}
| 34.758621 | 108 | 0.687004 |
b331a5862751356c62071d174c897072f4150fec | 2,899 | /*
* Copyright (C) 2013 Paragon Software Group
* Author: Andrey Tumanov <Andrey_Tumanov@penreader.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
package com.paragon.dictionary.fbreader;
import java.util.HashSet;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import com.paragon.open.dictionary.api.*;
import org.geometerplus.android.fbreader.dict.DictionaryUtil;
public class OpenDictionaryFlyout {
private final Direction myDirection;
private final String myPackageName;
public OpenDictionaryFlyout(Dictionary dictionary) {
myDirection = dictionary.getDirection();
myPackageName = dictionary.getApplicationPackageName();
}
private Dictionary getDictionary(final Context context) {
if (myPackageName == null) {
return null;
}
final OpenDictionaryAPI api = new OpenDictionaryAPI(context);
HashSet<Dictionary> dictionaries = api.getDictionaries(myDirection);
for (Dictionary dictionary : dictionaries) {
if (myPackageName.equalsIgnoreCase(dictionary.getApplicationPackageName())) {
return dictionary;
}
}
Log.e("FBReader", "OpenDictionaryFlyout:getDictionary - Dictionary with direction [" +
myDirection.toString() + "] and package name [" + myPackageName + "] not found");
return null;
}
public void showTranslation(final Activity activity, final String text, DictionaryUtil.PopupFrameMetric frameMetrics) {
Log.d("FBReader", "OpenDictionaryFlyout:showTranslation");
final Dictionary dictionary = getDictionary(activity);
if (dictionary == null) {
Log.e("FBReader", "OpenDictionaryFlyout:showTranslation - null dictionary received");
return;
}
if (!dictionary.isTranslationAsTextSupported()) {
dictionary.showTranslation(text);
} else {
OpenDictionaryActivity.setDictionary(dictionary);
Intent intent = new Intent(activity, OpenDictionaryActivity.class);
intent.putExtra(OpenDictionaryActivity.OPEN_DICTIONARY_QUERY_KEY, text);
intent.putExtra(OpenDictionaryActivity.OPEN_DICTIONARY_HEIGHT_KEY, frameMetrics.Height);
intent.putExtra(OpenDictionaryActivity.OPEN_DICTIONARY_GRAVITY_KEY, frameMetrics.Gravity);
activity.startActivity(intent);
}
}
}
| 36.696203 | 120 | 0.770956 |
a81f31041ef8b6dc11c584b0e6768e06e11f726a | 2,788 | package martin.app.bagoftask.ns;
import java.io.File;
import java.util.Vector;
import martin.mogrid.entity.dispatcher.globus.ProxyCollaboratorDispatcherFactory;
import martin.mogrid.p2pdl.api.MogridApplicationFacade;
import martin.mogrid.p2pdl.api.RequestIdentifier;
import martin.mogrid.tl.asl.simulation.NSAdaptationSublayer;
public class NSMaster implements MogridApplicationFacade {
private static final File RUN_ROUNDS_SCRIPT;
private static final File NS_WORKER;
//private NSScriptProperties[] nsProperties;
private NSScriptProperties nsScriptProperties;
private NSAdaptationSublayer gridJobDiscovery;
private int numOfJobs;
static {
RUN_ROUNDS_SCRIPT = new File ( "NSFiles/run_rounds.sh" );
NS_WORKER = new File( "NSFiles/worker.jar" );
}
public NSMaster(NSScriptProperties nsScriptProperties) {
numOfJobs = NSScriptSender.getNumOfJobs( nsScriptProperties );
this.nsScriptProperties = nsScriptProperties;
//nsProperties = new NSScriptProperties[ numOfJobs ];
//initNSProperties( nsProperties );
gridJobDiscovery = new NSAdaptationSublayer(this);
gridJobDiscovery.registerTaskDispatcherFactory(new ProxyCollaboratorDispatcherFactory());
gridJobDiscovery.setCollaborationLevel(1);
gridJobDiscovery.setTransferDelay(10);
}
/*private void initNSProperties( NSScriptProperties[] nsProperties ) {
for( int i = 0; i < numOfJobs; i++ ) {
nsProperties[i] = NSScriptProperties.generateScriptSingleRoundProperties( nsScriptProperties, ( i + 1 ) );
}
}*/
private Vector getFiles( ) {
//File[] files = new File[2];
Vector vec = new Vector();
for( int i = 0; i < numOfJobs; i ++ ) {
vec.addElement( new File[] { nsScriptProperties.getSimScriptPath(), RUN_ROUNDS_SCRIPT, NS_WORKER } );
}
//files[0] = nsProperties[0].getSimScriptPath();
//files[1] = RUN_ROUNDS_SCRIPT;
//vec.addElement ( files );
return vec;
}
/*private String[] getArgs() {
String[] args = new String[numOfJobs];
for( int i = 0; i < numOfJobs; i ++ ) {
args[i] = nsScriptProperties.getArguments();
}
return args;
}*/
public void runRounds() {
//String query = "ns";
//String[] nsArgs = new String[1];
//nsArgs[0] = nsProperties[0].getArguments();
new NSResultListener( numOfJobs, nsScriptProperties ).start();
gridJobDiscovery.submitJobRequest(new String[] { "ns", "java" }, numOfJobs, getFiles() , RUN_ROUNDS_SCRIPT.getName(), NSScriptSender.getArguments( nsScriptProperties ));
}
public void handleMogridResource(RequestIdentifier reqID, Object resource) {
}
}
| 35.291139 | 175 | 0.676471 |
5f44c30c43ef6b9096e68d282cd22975218e7ccd | 1,094 | package org.example.utils.vaadinbridge.internal;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.osgi.service.http.HttpService;
import org.osgi.service.http.NamespaceException;
import org.osgi.util.tracker.ServiceTracker;
class HttpServiceTracker extends ServiceTracker {
HttpServiceTracker(BundleContext context) {
super(context, HttpService.class.getName(), null);
}
@Override
public Object addingService(ServiceReference reference) {
HttpService httpService = (HttpService) context.getService(reference);
try {
httpService.registerResources("/VAADIN", "/VAADIN", new TargetBundleHttpContext(context, "com.vaadin"));
} catch (NamespaceException e) {
e.printStackTrace();
}
ApplicationFactoryTracker bridge = new ApplicationFactoryTracker(httpService, context);
bridge.open();
return bridge;
}
@Override
public void removedService(ServiceReference reference, Object service) {
ApplicationFactoryTracker bridge = (ApplicationFactoryTracker) service;
bridge.close();
context.ungetService(reference);
}
}
| 31.257143 | 107 | 0.789762 |
b263c366607c05869d24d86c9e15fb8c16b7c47c | 1,115 | package subsectionexecutor;
import java.util.List;
import java.util.Set;
/**
* @author shenlw
* @date 9/20/2019 5:19 PM
*/
public interface Compose<E> {
void put(E o);
E get();
void reset();
class ListCompose<T> implements Compose<List<T>> {
private List<T> data;
@Override
public void put(List<T> o) {
if (data == null) {
data = o;
} else {
data.addAll(o);
}
}
@Override
public List<T> get() {
return data;
}
@Override
public void reset() {
data = null;
}
}
class SetCompose<T> implements Compose<Set<T>> {
private Set<T> data;
@Override
public void put(Set<T> o) {
if (data == null) {
data = o;
} else {
data.addAll(o);
}
}
@Override
public Set<T> get() {
return data;
}
@Override
public void reset() {
data = null;
}
}
}
| 16.641791 | 54 | 0.4287 |
b0d0740c0f55b822e87286649e56b4d542d0d045 | 8,309 | package betterquesting.client.toolbox.tools;
import betterquesting.api.client.toolbox.IToolboxTool;
import betterquesting.api.enums.EnumPacketAction;
import betterquesting.api.network.QuestingPacket;
import betterquesting.api.questing.IQuest;
import betterquesting.api.questing.IQuestLine;
import betterquesting.api2.client.gui.controls.PanelButtonQuest;
import betterquesting.api2.client.gui.misc.GuiRectangle;
import betterquesting.api2.storage.DBEntry;
import betterquesting.api2.client.gui.panels.lists.CanvasQuestLine;
import betterquesting.client.gui2.editors.designer.PanelToolController;
import betterquesting.client.toolbox.ToolboxTabMain;
import betterquesting.network.PacketSender;
import betterquesting.network.PacketTypeNative;
import betterquesting.questing.QuestDatabase;
import betterquesting.questing.QuestLineDatabase;
import betterquesting.questing.QuestLineEntry;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.util.NonNullList;
import java.util.*;
public class ToolboxToolCopy implements IToolboxTool
{
private CanvasQuestLine gui = null;
private final NonNullList<GrabEntry> grabList = NonNullList.create();
@Override
public void initTool(CanvasQuestLine gui)
{
this.gui = gui;
grabList.clear();
}
@Override
public void disableTool()
{
grabList.clear();
}
@Override
public void refresh(CanvasQuestLine gui)
{
if(grabList.size() <= 0) return;
List<GrabEntry> tmp = new ArrayList<>();
for(GrabEntry grab : grabList)
{
for(PanelButtonQuest btn : PanelToolController.selected)
{
if(btn.getStoredValue().getID() == grab.btn.getStoredValue().getID())
{
tmp.add(new GrabEntry(btn, grab.offX, grab.offY));
break;
}
}
}
grabList.clear();
grabList.addAll(tmp);
}
@Override
public void drawCanvas(int mx, int my, float partialTick)
{
if(grabList.size() <= 0) return;
int snap = Math.max(1, ToolboxTabMain.INSTANCE.getSnapValue());
int dx = mx;
int dy = my;
dx = ((dx%snap) + snap)%snap;
dy = ((dy%snap) + snap)%snap;
dx = mx - dx;
dy = my - dy;
for(GrabEntry grab : grabList)
{
grab.btn.rect.x = dx + grab.offX;
grab.btn.rect.y = dy + grab.offY;
grab.btn.drawPanel(dx, dy, partialTick);
}
}
@Override
public void drawOverlay(int mx, int my, float partialTick)
{
if(grabList.size() > 0) ToolboxTabMain.INSTANCE.drawGrid(gui);
}
@Override
public List<String> getTooltip(int mx, int my)
{
return grabList.size() <= 0 ? null : Collections.emptyList();
}
@Override
public boolean onMouseClick(int mx, int my, int click)
{
if(click == 1 && grabList.size() > 0)
{
grabList.clear();
return true;
} else if(click != 0 || !gui.getTransform().contains(mx, my))
{
return false;
}
if(grabList.size() <= 0)
{
PanelButtonQuest btnClicked = gui.getButtonAt(mx, my);
if(btnClicked != null) // Pickup the group or the single one if none are selected
{
if(PanelToolController.selected.size() > 0)
{
if(!PanelToolController.selected.contains(btnClicked)) return false;
for(PanelButtonQuest btn : PanelToolController.selected)
{
GuiRectangle rect = new GuiRectangle(btn.rect);
grabList.add(new GrabEntry(new PanelButtonQuest(rect, -1, "", btn.getStoredValue()), rect.x - btnClicked.rect.x, rect.y - btnClicked.rect.y));
}
} else
{
grabList.add(new GrabEntry(new PanelButtonQuest(new GuiRectangle(btnClicked.rect), -1, "", btnClicked.getStoredValue()), 0, 0));
}
return true;
}
return false;
}
// Pre-sync
IQuestLine qLine = gui.getQuestLine();
int lID = QuestLineDatabase.INSTANCE.getID(qLine);
NBTTagList bulkTags = new NBTTagList();
int[] nextIDs = getNextIDs(grabList.size());
HashMap<Integer, Integer> remappedIDs = new HashMap<>();
for(int i = 0; i < grabList.size(); i++) remappedIDs.put(grabList.get(i).btn.getStoredValue().getID(), nextIDs[i]);
for(int i = 0; i < grabList.size(); i++)
{
GrabEntry grab = grabList.get(i);
IQuest quest = grab.btn.getStoredValue().getValue();
int qID = nextIDs[i];
if(qLine.getValue(qID) == null) qLine.add(qID, new QuestLineEntry(grab.btn.rect.x, grab.btn.rect.y, grab.btn.rect.w, grab.btn.rect.h));
NBTTagCompound questTags = quest.writeToNBT(new NBTTagCompound());
int[] oldIDs = Arrays.copyOf(quest.getRequirements(), quest.getRequirements().length);
for(int n = 0; n < oldIDs.length; n++)
{
if(remappedIDs.containsKey(oldIDs[n]))
{
oldIDs[n] = remappedIDs.get(oldIDs[n]);
}
}
questTags.setIntArray("preRequisites", oldIDs);
// Sync Quest
NBTTagCompound tag1 = new NBTTagCompound();
NBTTagCompound base1 = new NBTTagCompound();
base1.setTag("config", questTags);
tag1.setTag("data", base1);
tag1.setInteger("action", EnumPacketAction.ADD.ordinal());
tag1.setInteger("questID", qID);
tag1.setString("ID", PacketTypeNative.QUEST_EDIT.GetLocation().toString());
bulkTags.appendTag(tag1);
}
grabList.clear();
// Sync Line
NBTTagCompound tag2 = new NBTTagCompound();
NBTTagCompound base2 = new NBTTagCompound();
base2.setTag("line", qLine.writeToNBT(new NBTTagCompound(), null));
tag2.setTag("data", base2);
tag2.setInteger("action", EnumPacketAction.EDIT.ordinal());
tag2.setInteger("lineID", lID);
tag2.setString("ID", PacketTypeNative.LINE_EDIT.GetLocation().toString());
bulkTags.appendTag(tag2);
NBTTagCompound tagBase = new NBTTagCompound();
tagBase.setTag("bulk", bulkTags);
PacketSender.INSTANCE.sendToServer(new QuestingPacket(PacketTypeNative.BULK.GetLocation(), tagBase));
return true;
}
private int[] getNextIDs(int num)
{
DBEntry<IQuest>[] listDB = QuestDatabase.INSTANCE.getEntries();
int[] nxtIDs = new int[num];
if(listDB.length <= 0 || listDB[listDB.length - 1].getID() == listDB.length - 1)
{
for(int i = 0; i < num; i++) nxtIDs[i] = listDB.length + i;
return nxtIDs;
}
int n1 = 0;
int n2 = 0;
for(int i = 0; i < num; i++)
{
while(n2 < listDB.length && listDB[n2].getID() == n1)
{
n1++;
n2++;
}
nxtIDs[i] = n1++;
}
return nxtIDs;
}
@Override
public boolean onMouseRelease(int mx, int my, int click)
{
return false;
}
@Override
public boolean onMouseScroll(int mx, int my, int scroll)
{
return false;
}
@Override
public boolean onKeyPressed(char c, int keyCode)
{
return grabList.size() > 0;
}
@Override
public boolean clampScrolling()
{
return grabList.size() <= 0;
}
@Override
public void onSelection(NonNullList<PanelButtonQuest> buttons)
{
}
@Override
public boolean useSelection()
{
return grabList.size() <= 0;
}
private class GrabEntry
{
private final PanelButtonQuest btn;
private final int offX;
private final int offY;
private GrabEntry(PanelButtonQuest btn, int offX, int offY)
{
this.btn = btn;
this.offX = offX;
this.offY = offY;
}
}
}
| 30.105072 | 166 | 0.580575 |
60cf72a707505c73eeac86833bf6f2efb59ba644 | 4,464 | /*
* 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.netbeans.api.debugger;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
/**
* Abstract definition of watch. Each watch is created for
* one String which contains the name of variable or some expression.
*
* @author Jan Jancura
*/
public final class Watch {
/** Name of the property for the watched expression. */
public static final String PROP_EXPRESSION = "expression"; // NOI18N
/** Name of the property for the value of the watched expression. This constant is not used at all. */
public static final String PROP_VALUE = "value"; // NOI18N
/** Name of the property for the enabled status of the watch.
* @since 1.36 */
public static final String PROP_ENABLED = "enabled"; // NOI18N
private String expression;
private boolean enabled = true;
private PropertyChangeSupport pcs;
private final Pin pin;
Watch (String expr) {
this(expr, null);
}
Watch (String expr, Pin pin) {
this.expression = expr;
this.pin = pin;
pcs = new PropertyChangeSupport (this);
}
/**
* Test whether the watch is enabled.
*
* @return <code>true</code> if the watch is enabled,
* <code>false</code> otherwise.
* @since 1.36
*/
public synchronized boolean isEnabled () {
return enabled;
}
/**
* Set enabled state of the watch.
* @param enabled <code>true</code> if this watch should be enabled,
* <code>false</code> otherwise
* @since 1.36
*/
public void setEnabled(boolean enabled) {
synchronized(this) {
if (enabled == this.enabled) return ;
this.enabled = enabled;
}
pcs.firePropertyChange (PROP_ENABLED, !enabled, enabled);
}
/**
* Return expression this watch is created for.
*
* @return expression this watch is created for
*/
public synchronized String getExpression () {
return expression;
}
/**
* Set the expression to watch.
*
* @param expression expression to watch
*/
public void setExpression (String expression) {
String old;
synchronized(this) {
old = this.expression;
this.expression = expression;
}
pcs.firePropertyChange (PROP_EXPRESSION, old, expression);
}
/**
* Get a pin location, where the watch is pinned at, if any.
* @return The watch pin, or <code>null</code>.
* @since 1.54
*/
public Pin getPin() {
return pin;
}
/**
* Remove the watch from the list of all watches in the system.
*/
public void remove () {
DebuggerManager dm = DebuggerManager.getDebuggerManager ();
dm.removeWatch (this);
}
/**
* Add a property change listener.
*
* @param l the listener to add
*/
public void addPropertyChangeListener (PropertyChangeListener l) {
pcs.addPropertyChangeListener (l);
}
/**
* Remove a property change listener.
*
* @param l the listener to remove
*/
public void removePropertyChangeListener (PropertyChangeListener l) {
pcs.removePropertyChangeListener (l);
}
/**
* A base interface for a watch pin location. Implemented by specific
* platform-dependent and location-dependent implementation.
* See <code>org.netbeans.spi.debugger.ui.EditorPin</code> for the NetBeans
* editor pin implementation.
* @since 1.54
*/
public static interface Pin {
}
}
| 29.368421 | 106 | 0.633737 |
6bda0b13c8b4621c6c10eaced3686bf7989e6fe9 | 3,142 | /*
* 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.nbandroid.netbeans.gradle.v2.project.template.freemarker.converters;
import freemarker.template.SimpleNumber;
import freemarker.template.TemplateMethodModelEx;
import freemarker.template.TemplateModelException;
import freemarker.template.TemplateScalarModel;
import java.util.List;
import org.jetbrains.annotations.NotNull;
/**
*
* @author arsi
*/
public class FmCompareVersionsIgnoringQualifiers implements TemplateMethodModelEx {
@Override
public Object exec(List args) throws TemplateModelException {
if (args.size() != 2) {
throw new TemplateModelException("Wrong arguments");
}
String string1 = ((TemplateScalarModel) args.get(0)).getAsString();
String string2 = ((TemplateScalarModel) args.get(1)).getAsString();
return new SimpleNumber(compare(string1, string2));
}
public static int compare(@NotNull String left, @NotNull String right) {
if (left.equals(right)) {
return 0;
}
int leftStart = 0, rightStart = 0, result;
do {
int leftEnd = left.indexOf('.', leftStart);
int rightEnd = right.indexOf('.', rightStart);
Integer leftValue = Integer.parseInt(leftEnd < 0
? left.substring(leftStart)
: left.substring(leftStart, leftEnd));
Integer rightValue = Integer.parseInt(rightEnd < 0
? right.substring(rightStart)
: right.substring(rightStart, rightEnd));
result = leftValue.compareTo(rightValue);
leftStart = leftEnd + 1;
rightStart = rightEnd + 1;
} while (result == 0 && leftStart > 0 && rightStart > 0);
if (result == 0) {
if (leftStart > rightStart) {
return containsNonZeroValue(left, leftStart) ? 1 : 0;
}
if (leftStart < rightStart) {
return containsNonZeroValue(right, rightStart) ? -1 : 0;
}
}
return result;
}
private static boolean containsNonZeroValue(String str, int beginIndex) {
for (int i = beginIndex; i < str.length(); i++) {
char c = str.charAt(i);
if (c != '0' && c != '.') {
return true;
}
}
return false;
}
}
| 37.404762 | 83 | 0.633673 |
6213165cfb2c01ff7ce4cbce6a28f5a91369a3e2 | 533 | package com.yoyiyi.soleil.mvp.contract.search;
import com.yoyiyi.soleil.bean.search.Movie;
/**
* @author zzq 作者 E-mail: soleilyoyiyi@gmail.com
* @date 创建时间:2017/5/12 10:09
* 描述:发现Contract
*/
public interface MovieContract {
interface View extends BaseSearchContract.View {
void showSearchMovie(Movie movie);
}
interface Presenter<T> extends BaseSearchContract.Presenter<T> {
// void getSearchArchiveData(String keyword, int page, int pagesize);
void getSearchMovieData();
}
}
| 19.740741 | 77 | 0.697936 |
e468a6a3e0af48fe5018cae55320f4f51acfd311 | 7,174 | package tv.mapper.embellishcraft.rocks.data.gen;
import net.minecraft.data.DataGenerator;
import net.minecraftforge.common.data.ExistingFileHelper;
import tv.mapper.embellishcraft.core.data.gen.ECBlockModels;
public class RockBlockModels extends ECBlockModels
{
public RockBlockModels(DataGenerator generator, String modid, ExistingFileHelper existingFileHelper)
{
super(generator, modid, existingFileHelper);
}
@Override
protected void registerModels()
{
buildAllStone("basalt");
buildRooftilesStairs("basalt_rooftiles");
buildAllStone("slate");
buildRooftilesStairs("slate_rooftiles");
buildAllStone("marble");
buildRooftilesStairs("marble_rooftiles");
buildAllStone("gneiss");
buildRooftilesStairs("gneiss_rooftiles");
buildAllStone("jade");
buildRooftilesStairs("jade_rooftiles");
buildAllStone("larvikite");
buildRooftilesStairs("larvikite_rooftiles");
buildWall("paving_stones", modLoc("block/paving_stones"));
buildPressure("paving_stones", modLoc("block/paving_stones"));
buildMcStone("andesite");
buildRooftilesStairs("andesite_rooftiles");
buildMcStone("diorite");
buildRooftilesStairs("diorite_rooftiles");
buildMcStone("granite");
buildRooftilesStairs("granite_rooftiles");
buildMcSandstone("sandstone");
buildRooftilesStairs("sandstone_rooftiles");
buildMcSandstone("red_sandstone");
buildRooftilesStairs("red_sandstone_rooftiles");
// Terracotta
buildWall("terracotta", mcLoc("block/terracotta"));
buildWall("polished_terracotta", modLoc("block/polished_terracotta"));
buildWall("terracotta_paving", modLoc("block/terracotta_paving"));
buildWall("terracotta_tiles", modLoc("block/terracotta_tiles"));
buildWall("terracotta_bricks", modLoc("block/terracotta_bricks"));
buildWall("terracotta_large_bricks", modLoc("block/terracotta_large_bricks"));
buildWall("terracotta_paving_stones", modLoc("block/terracotta_paving_stones"));
buildButton("terracotta", mcLoc("block/terracotta"));
buildPressure("terracotta", mcLoc("block/terracotta"));
buildPressure("polished_terracotta", modLoc("block/polished_terracotta"));
buildPressure("terracotta_paving", modLoc("block/terracotta_paving"));
buildPressure("terracotta_tiles", modLoc("block/terracotta_tiles"));
buildPressure("terracotta_bricks", modLoc("block/terracotta_bricks"));
buildPressure("terracotta_large_bricks", modLoc("block/terracotta_large_bricks"));
buildPressure("terracotta_paving_stones", modLoc("block/terracotta_paving_stones"));
buildRooftilesStairs("terracotta_rooftiles");
}
protected void buildAllStoneWall(String name)
{
buildWall(name, modLoc("block/" + name));
buildWall(name + "_cobblestone", modLoc("block/" + name + "_cobblestone"));
buildWall(name + "_cobblestone_bricks", modLoc("block/" + name + "_cobblestone_bricks"));
buildWall("smooth_" + name, modLoc("block/smooth_" + name));
buildWall("polished_" + name, modLoc("block/polished_" + name));
buildWall(name + "_paving", modLoc("block/" + name + "_paving"));
buildWall(name + "_tiles", modLoc("block/" + name + "_tiles"));
buildWall(name + "_bricks", modLoc("block/" + name + "_bricks"));
buildWall(name + "_large_bricks", modLoc("block/" + name + "_large_bricks"));
buildWall(name + "_paving_stones", modLoc("block/" + name + "_paving_stones"));
}
protected void buildAllStonePressure(String name)
{
buildPressure(name, modLoc("block/" + name));
buildPressure(name + "_cobblestone", modLoc("block/" + name + "_cobblestone"));
buildPressure(name + "_cobblestone_bricks", modLoc("block/" + name + "_cobblestone_bricks"));
buildPressure("smooth_" + name, modLoc("block/smooth_" + name));
buildPressure("polished_" + name, modLoc("block/polished_" + name));
buildPressure(name + "_paving", modLoc("block/" + name + "_paving"));
buildPressure(name + "_tiles", modLoc("block/" + name + "_tiles"));
buildPressure(name + "_bricks", modLoc("block/" + name + "_bricks"));
buildPressure(name + "_large_bricks", modLoc("block/" + name + "_large_bricks"));
buildPressure(name + "_paving_stones", modLoc("block/" + name + "_paving_stones"));
buildPressure(name + "_ornament", modLoc("block/" + name + "_ornament"));
}
protected void buildAllStone(String name)
{
buildAllStoneWall(name);
buildAllStonePressure(name);
buildButton(name, modLoc("block/" + name));
}
protected void buildMcStone(String name)
{
buildWall("smooth_" + name, modLoc("block/smooth_" + name));
buildPressure("smooth_" + name, modLoc("block/smooth_" + name));
buildButton(name, mcLoc("block/" + name));
buildWall(name + "_paving", modLoc("block/" + name + "_paving"));
buildPressure(name + "_paving", modLoc("block/" + name + "_paving"));
buildWall(name + "_tiles", modLoc("block/" + name + "_tiles"));
buildPressure(name + "_tiles", modLoc("block/" + name + "_tiles"));
buildWall(name + "_bricks", modLoc("block/" + name + "_bricks"));
buildPressure(name + "_bricks", modLoc("block/" + name + "_bricks"));
buildWall(name + "_large_bricks", modLoc("block/" + name + "_large_bricks"));
buildPressure(name + "_large_bricks", modLoc("block/" + name + "_large_bricks"));
buildWall(name + "_paving_stones", modLoc("block/" + name + "_paving_stones"));
buildPressure(name + "_paving_stones", modLoc("block/" + name + "_paving_stones"));
buildPressure(name + "_ornament", modLoc("block/" + name + "_ornament"));
}
protected void buildMcSandstone(String name)
{
buildButton(name, mcLoc("block/" + name));
buildWall("smooth_" + name, mcLoc("block/" + name + "_top"));
buildPressure("smooth_" + name, mcLoc("block/" + name + "_top"));
buildWall("polished_" + name, modLoc("block/polished_" + name));
buildPressure("polished_" + name, modLoc("block/polished_" + name));
buildWall(name + "_paving", modLoc("block/" + name + "_paving"));
buildPressure(name + "_paving", modLoc("block/" + name + "_paving"));
buildWall(name + "_tiles", modLoc("block/" + name + "_tiles"));
buildPressure(name + "_tiles", modLoc("block/" + name + "_tiles"));
buildWall(name + "_bricks", modLoc("block/" + name + "_bricks"));
buildPressure(name + "_bricks", modLoc("block/" + name + "_bricks"));
buildWall(name + "_large_bricks", modLoc("block/" + name + "_large_bricks"));
buildPressure(name + "_large_bricks", modLoc("block/" + name + "_large_bricks"));
buildWall(name + "_paving_stones", modLoc("block/" + name + "_paving_stones"));
buildPressure(name + "_paving_stones", modLoc("block/" + name + "_paving_stones"));
}
} | 45.119497 | 104 | 0.650125 |
228516810a9457b1018499ce277966e04f943999 | 6,684 | /*
* Copyright (C) 2018 Seoul National University
*
* 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 edu.snu.mist.examples;
import edu.snu.mist.client.APIQueryControlResult;
import edu.snu.mist.client.MISTQueryBuilder;
import edu.snu.mist.client.rulebased.*;
import edu.snu.mist.client.rulebased.conditions.ComparisonCondition;
import edu.snu.mist.client.rulebased.conditions.UnionCondition;
import edu.snu.mist.examples.parameters.NettySourceAddress;
import org.apache.reef.tang.Configuration;
import org.apache.reef.tang.JavaConfigurationBuilder;
import org.apache.reef.tang.Tang;
import org.apache.reef.tang.exceptions.InjectionException;
import org.apache.reef.tang.formats.CommandLine;
import java.io.IOException;
import java.net.URISyntaxException;
/**
* Example client which submits a rule-based stateful query.
*/
public final class RuleBasedStatefulExample {
/**
* Submit a stateless query.
* The query reads location and temperature from a source server.
* First, the query only accept INSIDE event to go INSIDE.
* When the location is changed, the state would be changed and send the mode to a sink server.
* After the state is changed into INSIDE,
* the state is changed only with the temperature value, ignoring the location value.
* If the temperature is not in the appropriate range, alarmed message would be sent to a sink server.
* The appropriate temperature of INSIDE is 5~25.
* @return result of the submission
* @throws IOException
* @throws InjectionException
*/
public static APIQueryControlResult submitQuery(final Configuration configuration)
throws IOException, InjectionException, URISyntaxException {
final String sourceSocket =
Tang.Factory.getTang().newInjector(configuration).getNamedInstance(NettySourceAddress.class);
final String[] source = sourceSocket.split(":");
final String sourceHostname = source[0];
final int sourcePort = Integer.parseInt(source[1]);
final String firstField = "Location";
final String secondField = "Temperature";
final RuleBasedValueType firstFieldType = RuleBasedValueType.STRING;
final RuleBasedValueType secondFieldType = RuleBasedValueType.INTEGER;
final String sourceSeparator = ",";
/**
* Make RuleBasedInput with sourceConfiguration.
*/
final RuleBasedInput input = new RuleBasedInput.TextSocketBuilder()
.setSocketAddress(sourceHostname)
.setSocketPort(sourcePort)
.addField(firstField, firstFieldType)
.addField(secondField, secondFieldType)
.setSeparator(sourceSeparator)
.build();
/**
* Make RuleBasedSink with sinkConfiguration.
*/
final RuleBasedSink sink = new RuleBasedSink.TextSocketBuilder()
.setSocketAddress(MISTExampleUtils.SINK_HOSTNAME)
.setSocketPort(MISTExampleUtils.SINK_PORT)
.build();
/**
* Make a StatefulQuery.
*/
final MISTStatefulQuery ruleBasedQuery = new MISTStatefulQuery.Builder("example-group", "user1")
.input(input)
.initialState("OUTSIDE")
.addStatefulRule(new StatefulRule.Builder()
.setCurrentState("OUTSIDE")
.addTransition(ComparisonCondition.eq("Location", "INSIDE"),
"INSIDE")
.build())
.addStatefulRule(new StatefulRule.Builder()
.setCurrentState("INSIDE")
.addTransition(UnionCondition.or(
ComparisonCondition.lt("Temperature", 5),
ComparisonCondition.gt("Temperature", 25)),
"INSIDE(ALARM)")
.addTransition(UnionCondition.and(
ComparisonCondition.ge("Temperature", 5),
ComparisonCondition.le("Temperature", 25)),
"INSIDE(0)")
.build())
.addStatefulRule(new StatefulRule.Builder()
.setCurrentState("INSIDE(ALARM)")
.addTransition(UnionCondition.and(
ComparisonCondition.ge("Temperature", 5),
ComparisonCondition.le("Temperature", 25)),
"INSIDE(0)")
.build())
.addStatefulRule(new StatefulRule.Builder()
.setCurrentState("INSIDE(0)")
.addTransition(UnionCondition.or(
ComparisonCondition.lt("Temperature", 5),
ComparisonCondition.gt("Temperature", 25)),
"INSIDE(ALARM)")
.build())
.addFinalState("INSIDE",
new RuleBasedAction.Builder()
.setActionType(RuleBasedActionType.TEXT_WRITE)
.setSink(sink)
.setParams("GO INSIDE")
.build())
.addFinalState("INSIDE(ALARM)",
new RuleBasedAction.Builder()
.setActionType(RuleBasedActionType.TEXT_WRITE)
.setSink(sink)
.setParams("INSIDE ALARM!(Temperature: $Temperature)")
.build())
.build();
/**
* Translate statelessQuery into MISTQuery
*/
final MISTQueryBuilder queryBuilder = RuleBasedTranslator.statefulTranslator(ruleBasedQuery);
return MISTExampleUtils.submit(queryBuilder, configuration);
}
/**
* Set the environment(Hostname and port of driver, source, and sink) and submit a query.
* @param args command line parameters
* @throws Exception
*/
public static void main(final String[] args) throws Exception {
final JavaConfigurationBuilder jcb = Tang.Factory.getTang().newConfigurationBuilder();
final CommandLine commandLine = MISTExampleUtils.getDefaultCommandLine(jcb)
.registerShortNameOfClass(NettySourceAddress.class) // Additional parameter
.processCommandLine(args);
if (commandLine == null) { // Option '?' was entered and processCommandLine printed the help.
return;
}
Thread sinkServer = new Thread(MISTExampleUtils.getSinkServer());
sinkServer.start();
final APIQueryControlResult result = submitQuery(jcb.build());
System.out.println("Query submission result: " + result.getQueryId());
}
/**
* Must not be instantiated.
*/
private RuleBasedStatefulExample() {
}
}
| 39.087719 | 104 | 0.681628 |
6b506ba0b895a24681617462f1e409cae1a7d83b | 285 | package com.v1project.MyDrugs.repositories;
import com.v1project.MyDrugs.models.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface UserRepository extends JpaRepository<User, Integer> {
}
| 28.5 | 70 | 0.845614 |
fb8423dee20981aa247ecbd296606ea5846b958e | 1,599 | package com.client.core.resttrigger.model.api;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* Created by john.sullivan on 10/2/2016.
*/
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
public class RestTriggerMeta {
private Integer userId;
private Integer entityId;
@JsonProperty("userId")
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
@JsonProperty("entityId")
public Integer getEntityId() {
return entityId;
}
public void setEntityId(Integer entityId) {
this.entityId = entityId;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof RestTriggerMeta)) return false;
RestTriggerMeta that = (RestTriggerMeta) o;
if (userId != null ? !userId.equals(that.userId) : that.userId != null) return false;
return !(entityId != null ? !entityId.equals(that.entityId) : that.entityId != null);
}
@Override
public int hashCode() {
int result = userId != null ? userId.hashCode() : 0;
result = 31 * result + (entityId != null ? entityId.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "RestTriggerMeta{" +
"userId=" + userId +
", entityId=" + entityId +
'}';
}
} | 26.65 | 93 | 0.630394 |
7bf10f88b22c7fa420b2e12e96ae47a12280b4dd | 528 | package org.onetwo.ext.ons.producer;
import org.onetwo.ext.alimq.OnsMessage;
import com.aliyun.openservices.ons.api.SendResult;
import com.aliyun.openservices.ons.api.transaction.LocalTransactionExecuter;
/**
* @author wayshall
* <br/>
*/
public interface TransactionProducerService extends TraceableProducer {
SendResult sendMessage(OnsMessage onsMessage,
LocalTransactionExecuter executer, Object arg);
/***
* 伪装一个非事务producer,简化调用
* @author wayshall
* @return
*/
ProducerService fakeProducerService();
} | 22 | 76 | 0.776515 |
ac6ba077586aca0c1a45f4744d06711173dda7bb | 8,585 | /*
* Copyright 2011-2019 B2i Healthcare Pte Ltd, http://b2i.sg
*
* 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.b2international.snowowl.snomed.api.rest;
import static com.b2international.snowowl.snomed.api.rest.domain.SnomedImportStatus.getImportStatus;
import static com.google.common.base.Preconditions.checkNotNull;
import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo;
import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collections;
import java.util.UUID;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.b2international.snowowl.snomed.api.ISnomedRf2ImportService;
import com.b2international.snowowl.snomed.api.rest.domain.RestApiError;
import com.b2international.snowowl.snomed.api.rest.domain.SnomedImportDetails;
import com.b2international.snowowl.snomed.api.rest.domain.SnomedReleasePatchImportRestConfiguration;
import com.b2international.snowowl.snomed.api.rest.domain.SnomedStandardImportRestConfiguration;
import com.b2international.snowowl.snomed.api.rest.util.Responses;
import com.b2international.snowowl.snomed.core.domain.ISnomedImportConfiguration;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
/**
* @since 1.0
*/
@Api(value = "Imports", description="Imports", tags = { "imports" })
@RestController
@RequestMapping(
value="/imports",
produces={ AbstractRestService.SO_MEDIA_TYPE, MediaType.APPLICATION_JSON_VALUE })
public class SnomedImportRestService extends AbstractRestService {
@Autowired
private ISnomedRf2ImportService delegate;
public SnomedImportRestService() {
super(Collections.emptySet());
}
@ApiOperation(
value="Import SNOMED CT content",
notes="Configures processes to import RF2 based archives. The configured process will wait until the archive actually uploaded via the <em>/archive</em> endpoint. "
+ "The actual import process will start after the file upload completed. Note: unpublished components (with no value entered in the 'effectiveTime' column) are "
+ "only allowed in DELTA import mode.")
@ApiResponses({
@ApiResponse(code = 201, message = "Created"),
@ApiResponse(code = 404, message = "Code system version not found"),
@ApiResponse(code = 404, message = "Task not found", response = RestApiError.class),
})
@RequestMapping(method=RequestMethod.POST,
consumes={ AbstractRestService.SO_MEDIA_TYPE, MediaType.APPLICATION_JSON_VALUE })
@ResponseStatus(HttpStatus.CREATED)
public ResponseEntity<Void> create(
@ApiParam(value="Import parameters")
@RequestBody
final SnomedStandardImportRestConfiguration importConfiguration) {
final UUID importId = delegate.create(importConfiguration.toConfig());
return Responses.created(linkTo(methodOn(SnomedImportRestService.class).getImportDetails(importId)).toUri()).build();
}
@ApiOperation(
value="Patch a SNOMED CT Release",
notes="Configures processes to import RF2 based archives in order to patch 'Released' SNOMED CT content. This is useful for making content changes during a beta feedback period. The configured process will wait until the archive actually uploaded via the <em>/archive</em> endpoint. "
+ "The actual import process will start after the file upload completed. Note: the patchReleaseVersion must match the effective-time of the release you are patching and takes the format 'yyyy-mm-dd'.")
@ApiResponses({
@ApiResponse(code = 201, message = "Created"),
@ApiResponse(code = 404, message = "Code system version not found"),
@ApiResponse(code = 404, message = "Task not found", response = RestApiError.class),
})
@RequestMapping(value="/release-patch", method=RequestMethod.POST,
consumes={ AbstractRestService.SO_MEDIA_TYPE, MediaType.APPLICATION_JSON_VALUE })
@ResponseStatus(HttpStatus.CREATED)
public ResponseEntity<Void> createReleaseHotfix(
@ApiParam(value="Import parameters")
@RequestBody
final SnomedReleasePatchImportRestConfiguration importConfiguration) {
checkNotNull(importConfiguration.getPatchReleaseVersion(), "patchReleaseVersion must be specified.");
final UUID importId = delegate.create(importConfiguration.toConfig());
return Responses.created(linkTo(methodOn(SnomedImportRestService.class).getImportDetails(importId)).toUri()).build();
}
@ApiOperation(
value="Retrieve import run details",
notes="Returns the specified import run's configuration and status.")
@ApiResponses({
@ApiResponse(code = 200, message = "OK"),
@ApiResponse(code = 404, message = "Code system version or import not found", response = RestApiError.class),
})
@RequestMapping(value="/{importId}", method=RequestMethod.GET)
public SnomedImportDetails getImportDetails(
@ApiParam(value="The import identifier")
@PathVariable(value="importId")
final UUID importId) {
return convertToDetails(importId, delegate.getImportDetails(importId));
}
@ApiOperation(
value="Delete import run",
notes="Removes a pending or finished import configuration from the server.")
@ApiResponses({
@ApiResponse(code = 204, message = "Delete successful"),
@ApiResponse(code = 404, message = "Code system version or import not found", response = RestApiError.class),
})
@RequestMapping(value="/{importId}", method=RequestMethod.DELETE)
@ResponseStatus(HttpStatus.NO_CONTENT)
public void deleteImportDetails(
@ApiParam(value="The import identifier")
@PathVariable(value="importId")
final UUID importId) {
delegate.deleteImportDetails(importId);
}
@ApiOperation(
value="Upload archive file and start the import",
notes="Removes a pending or finished import configuration from the server.")
@ApiResponses({
@ApiResponse(code = 204, message = "No content"),
@ApiResponse(code = 404, message = "Code system version or import not found", response = RestApiError.class),
})
@RequestMapping(value="/{importId}/archive",
method=RequestMethod.POST,
consumes={ MediaType.MULTIPART_FORM_DATA_VALUE })
@ResponseStatus(HttpStatus.NO_CONTENT)
public void startImport(
@ApiParam(value="The import identifier")
@PathVariable(value="importId")
final UUID importId,
@ApiParam(value="RF2 import archive")
@RequestPart("file")
final MultipartFile file) {
checkNotNull(file, "SNOMED CT RF2 release archive should be specified.");
try (final InputStream is = file.getInputStream()) {
delegate.startImport(importId, is);
} catch (final IOException e) {
throw new RuntimeException("Error while reading SNOMED CT RF2 release archive content.");
}
}
private SnomedImportDetails convertToDetails(final UUID importId,
final ISnomedImportConfiguration configuration) {
final SnomedImportDetails details = new SnomedImportDetails();
details.setCompletionDate(configuration.getCompletionDate());
details.setCreateVersions(configuration.shouldCreateVersion());
details.setId(importId);
details.setStartDate(configuration.getStartDate());
details.setStatus(getImportStatus(configuration.getStatus()));
details.setType(configuration.getRf2ReleaseType());
details.setBranchPath(configuration.getBranchPath());
details.setCodeSystemShortName(configuration.getCodeSystemShortName());
return details;
}
}
| 44.025641 | 287 | 0.782411 |
65d6d019789a1d0615a2044d1ee00bec96ded498 | 1,084 | package chat;
import chat.server.ChatRoomServer;
public class ServerMain {
public static void main(String[] args) throws Exception {
ClockThread clockThread = new ClockThread();
clockThread.start();
// 开启服务端
final ChatRoomServer chatRoomserver = new ChatRoomServer();
chatRoomserver.bind(8086);
}
static class ClockThread extends Thread {
@Override
public void run() {
super.run();
while (true) {
try {
// int s1 = GlobalChannel.chatOnline.keySet().size();
// int s2 = GlobalChannel.adminOnline.keySet().size();
int s3 = GlobalChannel.userOnline.keySet().size();
int s4 = GlobalChannel.online.keySet().size();
System.out.println(String.format("房间数量:%s,客服数量:%s,用户数量:%s,所有用户数量:%s",s3,s4));
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
| 28.526316 | 97 | 0.527675 |
6ab5459ad1d8279d30504d7001dd811f16c7933d | 2,355 | /*
*
* Copyright 2018 EMBL - European Bioinformatics Institute
*
* 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 uk.ac.ebi.ampt2d.metadata.persistence.repositories;
import io.swagger.annotations.ApiOperation;
import org.springframework.data.querydsl.QueryDslPredicateExecutor;
import org.springframework.data.querydsl.binding.QuerydslBinderCustomizer;
import org.springframework.data.querydsl.binding.QuerydslBindings;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
import org.springframework.data.rest.core.annotation.RestResource;
import uk.ac.ebi.ampt2d.metadata.persistence.entities.QProject;
import uk.ac.ebi.ampt2d.metadata.persistence.entities.Project;
import java.util.List;
@RepositoryRestResource
public interface ProjectRepository extends PagingAndSortingRepository<Project, Long>,
QueryDslPredicateExecutor<Project>, QuerydslBinderCustomizer<QProject> {
/**
* Custom bindings define how queries should be performed when a simple "field-by-field equals" is not adequate.
* In our case we want reference sequence queries to be ignoreCase equals.
*/
default void customize(QuerydslBindings bindings, QProject project) {
bindings.bind(project.study.analyses.any().referenceSequences.any().name,
project.study.analyses.any().referenceSequences.any().patch)
.first((path, value) -> path.equalsIgnoreCase(value));
}
@ApiOperation(value = "Get the latest version of Project based on accession")
@RestResource(path = "/accession")
List<Project> findFirstByAccessionVersionId_AccessionOrderByAccessionVersionId_VersionDesc
(@Param("accession") String accession);
}
| 44.433962 | 116 | 0.773673 |
06eeb9d7df4eb95681dcd9816eb9809f6dffd8e1 | 43,596 | /*
* Copyright 2022 the original author or authors.
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* https://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated from /Users/yoshi/Development/Repos/openrewrite/rewrite/rewrite-xml/src/main/antlr/XMLParser.g4 by ANTLR 4.10.1
package org.openrewrite.xml.internal.grammar;
import org.antlr.v4.runtime.atn.*;
import org.antlr.v4.runtime.dfa.DFA;
import org.antlr.v4.runtime.*;
import org.antlr.v4.runtime.misc.*;
import org.antlr.v4.runtime.tree.*;
import java.util.List;
import java.util.Iterator;
import java.util.ArrayList;
@SuppressWarnings({"all", "warnings", "unchecked", "unused", "cast"})
public class XMLParser extends Parser {
static { RuntimeMetaData.checkVersion("4.10.1", RuntimeMetaData.VERSION); }
protected static final DFA[] _decisionToDFA;
protected static final PredictionContextCache _sharedContextCache =
new PredictionContextCache();
public static final int
COMMENT=1, CDATA=2, ParamEntityRef=3, EntityRef=4, CharRef=5, SEA_WS=6,
UTF_ENCODING_BOM=7, SPECIAL_OPEN_XML=8, OPEN=9, SPECIAL_OPEN=10, DTD_OPEN=11,
TEXT=12, DTD_CLOSE=13, DTD_SUBSET_OPEN=14, DTD_S=15, DOCTYPE=16, DTD_SUBSET_CLOSE=17,
MARKUP_OPEN=18, DTS_SUBSET_S=19, MARK_UP_CLOSE=20, MARKUP_S=21, MARKUP_TEXT=22,
MARKUP_SUBSET=23, PI_S=24, PI_TEXT=25, CLOSE=26, SPECIAL_CLOSE=27, SLASH_CLOSE=28,
S=29, SLASH=30, EQUALS=31, STRING=32, Name=33;
public static final int
RULE_document = 0, RULE_prolog = 1, RULE_xmldecl = 2, RULE_misc = 3, RULE_doctypedecl = 4,
RULE_intsubset = 5, RULE_markupdecl = 6, RULE_declSep = 7, RULE_externalid = 8,
RULE_processinginstruction = 9, RULE_content = 10, RULE_element = 11,
RULE_reference = 12, RULE_attribute = 13, RULE_chardata = 14;
private static String[] makeRuleNames() {
return new String[] {
"document", "prolog", "xmldecl", "misc", "doctypedecl", "intsubset",
"markupdecl", "declSep", "externalid", "processinginstruction", "content",
"element", "reference", "attribute", "chardata"
};
}
public static final String[] ruleNames = makeRuleNames();
private static String[] makeLiteralNames() {
return new String[] {
null, null, null, null, null, null, null, null, "'<?xml'", "'<'", null,
null, null, null, null, null, "'DOCTYPE'", null, null, null, null, null,
null, null, null, null, null, "'?>'", "'/>'", null, "'/'", "'='"
};
}
private static final String[] _LITERAL_NAMES = makeLiteralNames();
private static String[] makeSymbolicNames() {
return new String[] {
null, "COMMENT", "CDATA", "ParamEntityRef", "EntityRef", "CharRef", "SEA_WS",
"UTF_ENCODING_BOM", "SPECIAL_OPEN_XML", "OPEN", "SPECIAL_OPEN", "DTD_OPEN",
"TEXT", "DTD_CLOSE", "DTD_SUBSET_OPEN", "DTD_S", "DOCTYPE", "DTD_SUBSET_CLOSE",
"MARKUP_OPEN", "DTS_SUBSET_S", "MARK_UP_CLOSE", "MARKUP_S", "MARKUP_TEXT",
"MARKUP_SUBSET", "PI_S", "PI_TEXT", "CLOSE", "SPECIAL_CLOSE", "SLASH_CLOSE",
"S", "SLASH", "EQUALS", "STRING", "Name"
};
}
private static final String[] _SYMBOLIC_NAMES = makeSymbolicNames();
public static final Vocabulary VOCABULARY = new VocabularyImpl(_LITERAL_NAMES, _SYMBOLIC_NAMES);
/**
* @deprecated Use {@link #VOCABULARY} instead.
*/
@Deprecated
public static final String[] tokenNames;
static {
tokenNames = new String[_SYMBOLIC_NAMES.length];
for (int i = 0; i < tokenNames.length; i++) {
tokenNames[i] = VOCABULARY.getLiteralName(i);
if (tokenNames[i] == null) {
tokenNames[i] = VOCABULARY.getSymbolicName(i);
}
if (tokenNames[i] == null) {
tokenNames[i] = "<INVALID>";
}
}
}
@Override
@Deprecated
public String[] getTokenNames() {
return tokenNames;
}
@Override
public Vocabulary getVocabulary() {
return VOCABULARY;
}
@Override
public String getGrammarFileName() { return "XMLParser.g4"; }
@Override
public String[] getRuleNames() { return ruleNames; }
@Override
public String getSerializedATN() { return _serializedATN; }
@Override
public ATN getATN() { return _ATN; }
public XMLParser(TokenStream input) {
super(input);
_interp = new ParserATNSimulator(this,_ATN,_decisionToDFA,_sharedContextCache);
}
public static class DocumentContext extends ParserRuleContext {
public PrologContext prolog() {
return getRuleContext(PrologContext.class,0);
}
public ElementContext element() {
return getRuleContext(ElementContext.class,0);
}
public TerminalNode UTF_ENCODING_BOM() { return getToken(XMLParser.UTF_ENCODING_BOM, 0); }
public DocumentContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_document; }
@Override
public void enterRule(ParseTreeListener listener) {
if ( listener instanceof XMLParserListener ) ((XMLParserListener)listener).enterDocument(this);
}
@Override
public void exitRule(ParseTreeListener listener) {
if ( listener instanceof XMLParserListener ) ((XMLParserListener)listener).exitDocument(this);
}
@Override
public <T> T accept(ParseTreeVisitor<? extends T> visitor) {
if ( visitor instanceof XMLParserVisitor ) return ((XMLParserVisitor<? extends T>)visitor).visitDocument(this);
else return visitor.visitChildren(this);
}
}
public final DocumentContext document() throws RecognitionException {
DocumentContext _localctx = new DocumentContext(_ctx, getState());
enterRule(_localctx, 0, RULE_document);
int _la;
try {
enterOuterAlt(_localctx, 1);
{
setState(31);
_errHandler.sync(this);
_la = _input.LA(1);
if (_la==UTF_ENCODING_BOM) {
{
setState(30);
match(UTF_ENCODING_BOM);
}
}
setState(33);
prolog();
setState(34);
element();
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static class PrologContext extends ParserRuleContext {
public XmldeclContext xmldecl() {
return getRuleContext(XmldeclContext.class,0);
}
public List<MiscContext> misc() {
return getRuleContexts(MiscContext.class);
}
public MiscContext misc(int i) {
return getRuleContext(MiscContext.class,i);
}
public PrologContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_prolog; }
@Override
public void enterRule(ParseTreeListener listener) {
if ( listener instanceof XMLParserListener ) ((XMLParserListener)listener).enterProlog(this);
}
@Override
public void exitRule(ParseTreeListener listener) {
if ( listener instanceof XMLParserListener ) ((XMLParserListener)listener).exitProlog(this);
}
@Override
public <T> T accept(ParseTreeVisitor<? extends T> visitor) {
if ( visitor instanceof XMLParserVisitor ) return ((XMLParserVisitor<? extends T>)visitor).visitProlog(this);
else return visitor.visitChildren(this);
}
}
public final PrologContext prolog() throws RecognitionException {
PrologContext _localctx = new PrologContext(_ctx, getState());
enterRule(_localctx, 2, RULE_prolog);
int _la;
try {
enterOuterAlt(_localctx, 1);
{
setState(37);
_errHandler.sync(this);
_la = _input.LA(1);
if (_la==SPECIAL_OPEN_XML) {
{
setState(36);
xmldecl();
}
}
setState(42);
_errHandler.sync(this);
_la = _input.LA(1);
while ((((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << COMMENT) | (1L << SPECIAL_OPEN) | (1L << DTD_OPEN))) != 0)) {
{
{
setState(39);
misc();
}
}
setState(44);
_errHandler.sync(this);
_la = _input.LA(1);
}
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static class XmldeclContext extends ParserRuleContext {
public TerminalNode SPECIAL_OPEN_XML() { return getToken(XMLParser.SPECIAL_OPEN_XML, 0); }
public TerminalNode SPECIAL_CLOSE() { return getToken(XMLParser.SPECIAL_CLOSE, 0); }
public List<AttributeContext> attribute() {
return getRuleContexts(AttributeContext.class);
}
public AttributeContext attribute(int i) {
return getRuleContext(AttributeContext.class,i);
}
public XmldeclContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_xmldecl; }
@Override
public void enterRule(ParseTreeListener listener) {
if ( listener instanceof XMLParserListener ) ((XMLParserListener)listener).enterXmldecl(this);
}
@Override
public void exitRule(ParseTreeListener listener) {
if ( listener instanceof XMLParserListener ) ((XMLParserListener)listener).exitXmldecl(this);
}
@Override
public <T> T accept(ParseTreeVisitor<? extends T> visitor) {
if ( visitor instanceof XMLParserVisitor ) return ((XMLParserVisitor<? extends T>)visitor).visitXmldecl(this);
else return visitor.visitChildren(this);
}
}
public final XmldeclContext xmldecl() throws RecognitionException {
XmldeclContext _localctx = new XmldeclContext(_ctx, getState());
enterRule(_localctx, 4, RULE_xmldecl);
int _la;
try {
enterOuterAlt(_localctx, 1);
{
setState(45);
match(SPECIAL_OPEN_XML);
setState(49);
_errHandler.sync(this);
_la = _input.LA(1);
while (_la==Name) {
{
{
setState(46);
attribute();
}
}
setState(51);
_errHandler.sync(this);
_la = _input.LA(1);
}
setState(52);
match(SPECIAL_CLOSE);
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static class MiscContext extends ParserRuleContext {
public TerminalNode COMMENT() { return getToken(XMLParser.COMMENT, 0); }
public DoctypedeclContext doctypedecl() {
return getRuleContext(DoctypedeclContext.class,0);
}
public ProcessinginstructionContext processinginstruction() {
return getRuleContext(ProcessinginstructionContext.class,0);
}
public MiscContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_misc; }
@Override
public void enterRule(ParseTreeListener listener) {
if ( listener instanceof XMLParserListener ) ((XMLParserListener)listener).enterMisc(this);
}
@Override
public void exitRule(ParseTreeListener listener) {
if ( listener instanceof XMLParserListener ) ((XMLParserListener)listener).exitMisc(this);
}
@Override
public <T> T accept(ParseTreeVisitor<? extends T> visitor) {
if ( visitor instanceof XMLParserVisitor ) return ((XMLParserVisitor<? extends T>)visitor).visitMisc(this);
else return visitor.visitChildren(this);
}
}
public final MiscContext misc() throws RecognitionException {
MiscContext _localctx = new MiscContext(_ctx, getState());
enterRule(_localctx, 6, RULE_misc);
try {
enterOuterAlt(_localctx, 1);
{
setState(57);
_errHandler.sync(this);
switch (_input.LA(1)) {
case COMMENT:
{
setState(54);
match(COMMENT);
}
break;
case DTD_OPEN:
{
setState(55);
doctypedecl();
}
break;
case SPECIAL_OPEN:
{
setState(56);
processinginstruction();
}
break;
default:
throw new NoViableAltException(this);
}
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static class DoctypedeclContext extends ParserRuleContext {
public TerminalNode DTD_OPEN() { return getToken(XMLParser.DTD_OPEN, 0); }
public TerminalNode DOCTYPE() { return getToken(XMLParser.DOCTYPE, 0); }
public TerminalNode Name() { return getToken(XMLParser.Name, 0); }
public ExternalidContext externalid() {
return getRuleContext(ExternalidContext.class,0);
}
public TerminalNode DTD_CLOSE() { return getToken(XMLParser.DTD_CLOSE, 0); }
public List<TerminalNode> STRING() { return getTokens(XMLParser.STRING); }
public TerminalNode STRING(int i) {
return getToken(XMLParser.STRING, i);
}
public TerminalNode DTD_SUBSET_OPEN() { return getToken(XMLParser.DTD_SUBSET_OPEN, 0); }
public IntsubsetContext intsubset() {
return getRuleContext(IntsubsetContext.class,0);
}
public TerminalNode DTD_SUBSET_CLOSE() { return getToken(XMLParser.DTD_SUBSET_CLOSE, 0); }
public DoctypedeclContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_doctypedecl; }
@Override
public void enterRule(ParseTreeListener listener) {
if ( listener instanceof XMLParserListener ) ((XMLParserListener)listener).enterDoctypedecl(this);
}
@Override
public void exitRule(ParseTreeListener listener) {
if ( listener instanceof XMLParserListener ) ((XMLParserListener)listener).exitDoctypedecl(this);
}
@Override
public <T> T accept(ParseTreeVisitor<? extends T> visitor) {
if ( visitor instanceof XMLParserVisitor ) return ((XMLParserVisitor<? extends T>)visitor).visitDoctypedecl(this);
else return visitor.visitChildren(this);
}
}
public final DoctypedeclContext doctypedecl() throws RecognitionException {
DoctypedeclContext _localctx = new DoctypedeclContext(_ctx, getState());
enterRule(_localctx, 8, RULE_doctypedecl);
int _la;
try {
enterOuterAlt(_localctx, 1);
{
setState(59);
match(DTD_OPEN);
setState(60);
match(DOCTYPE);
setState(61);
match(Name);
setState(62);
externalid();
setState(66);
_errHandler.sync(this);
_la = _input.LA(1);
while (_la==STRING) {
{
{
setState(63);
match(STRING);
}
}
setState(68);
_errHandler.sync(this);
_la = _input.LA(1);
}
setState(73);
_errHandler.sync(this);
_la = _input.LA(1);
if (_la==DTD_SUBSET_OPEN) {
{
setState(69);
match(DTD_SUBSET_OPEN);
setState(70);
intsubset();
setState(71);
match(DTD_SUBSET_CLOSE);
}
}
setState(75);
match(DTD_CLOSE);
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static class IntsubsetContext extends ParserRuleContext {
public List<MarkupdeclContext> markupdecl() {
return getRuleContexts(MarkupdeclContext.class);
}
public MarkupdeclContext markupdecl(int i) {
return getRuleContext(MarkupdeclContext.class,i);
}
public List<DeclSepContext> declSep() {
return getRuleContexts(DeclSepContext.class);
}
public DeclSepContext declSep(int i) {
return getRuleContext(DeclSepContext.class,i);
}
public IntsubsetContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_intsubset; }
@Override
public void enterRule(ParseTreeListener listener) {
if ( listener instanceof XMLParserListener ) ((XMLParserListener)listener).enterIntsubset(this);
}
@Override
public void exitRule(ParseTreeListener listener) {
if ( listener instanceof XMLParserListener ) ((XMLParserListener)listener).exitIntsubset(this);
}
@Override
public <T> T accept(ParseTreeVisitor<? extends T> visitor) {
if ( visitor instanceof XMLParserVisitor ) return ((XMLParserVisitor<? extends T>)visitor).visitIntsubset(this);
else return visitor.visitChildren(this);
}
}
public final IntsubsetContext intsubset() throws RecognitionException {
IntsubsetContext _localctx = new IntsubsetContext(_ctx, getState());
enterRule(_localctx, 10, RULE_intsubset);
int _la;
try {
enterOuterAlt(_localctx, 1);
{
setState(81);
_errHandler.sync(this);
_la = _input.LA(1);
while ((((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << COMMENT) | (1L << ParamEntityRef) | (1L << SPECIAL_OPEN) | (1L << MARKUP_OPEN))) != 0)) {
{
setState(79);
_errHandler.sync(this);
switch (_input.LA(1)) {
case COMMENT:
case SPECIAL_OPEN:
case MARKUP_OPEN:
{
setState(77);
markupdecl();
}
break;
case ParamEntityRef:
{
setState(78);
declSep();
}
break;
default:
throw new NoViableAltException(this);
}
}
setState(83);
_errHandler.sync(this);
_la = _input.LA(1);
}
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static class MarkupdeclContext extends ParserRuleContext {
public TerminalNode MARKUP_OPEN() { return getToken(XMLParser.MARKUP_OPEN, 0); }
public TerminalNode MARK_UP_CLOSE() { return getToken(XMLParser.MARK_UP_CLOSE, 0); }
public List<TerminalNode> MARKUP_TEXT() { return getTokens(XMLParser.MARKUP_TEXT); }
public TerminalNode MARKUP_TEXT(int i) {
return getToken(XMLParser.MARKUP_TEXT, i);
}
public List<TerminalNode> MARKUP_SUBSET() { return getTokens(XMLParser.MARKUP_SUBSET); }
public TerminalNode MARKUP_SUBSET(int i) {
return getToken(XMLParser.MARKUP_SUBSET, i);
}
public ProcessinginstructionContext processinginstruction() {
return getRuleContext(ProcessinginstructionContext.class,0);
}
public TerminalNode COMMENT() { return getToken(XMLParser.COMMENT, 0); }
public MarkupdeclContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_markupdecl; }
@Override
public void enterRule(ParseTreeListener listener) {
if ( listener instanceof XMLParserListener ) ((XMLParserListener)listener).enterMarkupdecl(this);
}
@Override
public void exitRule(ParseTreeListener listener) {
if ( listener instanceof XMLParserListener ) ((XMLParserListener)listener).exitMarkupdecl(this);
}
@Override
public <T> T accept(ParseTreeVisitor<? extends T> visitor) {
if ( visitor instanceof XMLParserVisitor ) return ((XMLParserVisitor<? extends T>)visitor).visitMarkupdecl(this);
else return visitor.visitChildren(this);
}
}
public final MarkupdeclContext markupdecl() throws RecognitionException {
MarkupdeclContext _localctx = new MarkupdeclContext(_ctx, getState());
enterRule(_localctx, 12, RULE_markupdecl);
int _la;
try {
setState(100);
_errHandler.sync(this);
switch (_input.LA(1)) {
case MARKUP_OPEN:
enterOuterAlt(_localctx, 1);
{
{
setState(84);
match(MARKUP_OPEN);
setState(86);
_errHandler.sync(this);
switch ( getInterpreter().adaptivePredict(_input,9,_ctx) ) {
case 1:
{
setState(85);
match(MARKUP_TEXT);
}
break;
}
setState(91);
_errHandler.sync(this);
_la = _input.LA(1);
while (_la==MARKUP_SUBSET) {
{
{
setState(88);
match(MARKUP_SUBSET);
}
}
setState(93);
_errHandler.sync(this);
_la = _input.LA(1);
}
setState(95);
_errHandler.sync(this);
_la = _input.LA(1);
if (_la==MARKUP_TEXT) {
{
setState(94);
match(MARKUP_TEXT);
}
}
setState(97);
match(MARK_UP_CLOSE);
}
}
break;
case SPECIAL_OPEN:
enterOuterAlt(_localctx, 2);
{
setState(98);
processinginstruction();
}
break;
case COMMENT:
enterOuterAlt(_localctx, 3);
{
setState(99);
match(COMMENT);
}
break;
default:
throw new NoViableAltException(this);
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static class DeclSepContext extends ParserRuleContext {
public TerminalNode ParamEntityRef() { return getToken(XMLParser.ParamEntityRef, 0); }
public DeclSepContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_declSep; }
@Override
public void enterRule(ParseTreeListener listener) {
if ( listener instanceof XMLParserListener ) ((XMLParserListener)listener).enterDeclSep(this);
}
@Override
public void exitRule(ParseTreeListener listener) {
if ( listener instanceof XMLParserListener ) ((XMLParserListener)listener).exitDeclSep(this);
}
@Override
public <T> T accept(ParseTreeVisitor<? extends T> visitor) {
if ( visitor instanceof XMLParserVisitor ) return ((XMLParserVisitor<? extends T>)visitor).visitDeclSep(this);
else return visitor.visitChildren(this);
}
}
public final DeclSepContext declSep() throws RecognitionException {
DeclSepContext _localctx = new DeclSepContext(_ctx, getState());
enterRule(_localctx, 14, RULE_declSep);
try {
enterOuterAlt(_localctx, 1);
{
setState(102);
match(ParamEntityRef);
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static class ExternalidContext extends ParserRuleContext {
public TerminalNode Name() { return getToken(XMLParser.Name, 0); }
public ExternalidContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_externalid; }
@Override
public void enterRule(ParseTreeListener listener) {
if ( listener instanceof XMLParserListener ) ((XMLParserListener)listener).enterExternalid(this);
}
@Override
public void exitRule(ParseTreeListener listener) {
if ( listener instanceof XMLParserListener ) ((XMLParserListener)listener).exitExternalid(this);
}
@Override
public <T> T accept(ParseTreeVisitor<? extends T> visitor) {
if ( visitor instanceof XMLParserVisitor ) return ((XMLParserVisitor<? extends T>)visitor).visitExternalid(this);
else return visitor.visitChildren(this);
}
}
public final ExternalidContext externalid() throws RecognitionException {
ExternalidContext _localctx = new ExternalidContext(_ctx, getState());
enterRule(_localctx, 16, RULE_externalid);
int _la;
try {
enterOuterAlt(_localctx, 1);
{
setState(105);
_errHandler.sync(this);
_la = _input.LA(1);
if (_la==Name) {
{
setState(104);
match(Name);
}
}
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static class ProcessinginstructionContext extends ParserRuleContext {
public TerminalNode SPECIAL_OPEN() { return getToken(XMLParser.SPECIAL_OPEN, 0); }
public TerminalNode PI_TEXT() { return getToken(XMLParser.PI_TEXT, 0); }
public TerminalNode SPECIAL_CLOSE() { return getToken(XMLParser.SPECIAL_CLOSE, 0); }
public ProcessinginstructionContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_processinginstruction; }
@Override
public void enterRule(ParseTreeListener listener) {
if ( listener instanceof XMLParserListener ) ((XMLParserListener)listener).enterProcessinginstruction(this);
}
@Override
public void exitRule(ParseTreeListener listener) {
if ( listener instanceof XMLParserListener ) ((XMLParserListener)listener).exitProcessinginstruction(this);
}
@Override
public <T> T accept(ParseTreeVisitor<? extends T> visitor) {
if ( visitor instanceof XMLParserVisitor ) return ((XMLParserVisitor<? extends T>)visitor).visitProcessinginstruction(this);
else return visitor.visitChildren(this);
}
}
public final ProcessinginstructionContext processinginstruction() throws RecognitionException {
ProcessinginstructionContext _localctx = new ProcessinginstructionContext(_ctx, getState());
enterRule(_localctx, 18, RULE_processinginstruction);
try {
enterOuterAlt(_localctx, 1);
{
setState(107);
match(SPECIAL_OPEN);
setState(108);
match(PI_TEXT);
setState(109);
match(SPECIAL_CLOSE);
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static class ContentContext extends ParserRuleContext {
public ElementContext element() {
return getRuleContext(ElementContext.class,0);
}
public ReferenceContext reference() {
return getRuleContext(ReferenceContext.class,0);
}
public ProcessinginstructionContext processinginstruction() {
return getRuleContext(ProcessinginstructionContext.class,0);
}
public TerminalNode CDATA() { return getToken(XMLParser.CDATA, 0); }
public TerminalNode COMMENT() { return getToken(XMLParser.COMMENT, 0); }
public ChardataContext chardata() {
return getRuleContext(ChardataContext.class,0);
}
public ContentContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_content; }
@Override
public void enterRule(ParseTreeListener listener) {
if ( listener instanceof XMLParserListener ) ((XMLParserListener)listener).enterContent(this);
}
@Override
public void exitRule(ParseTreeListener listener) {
if ( listener instanceof XMLParserListener ) ((XMLParserListener)listener).exitContent(this);
}
@Override
public <T> T accept(ParseTreeVisitor<? extends T> visitor) {
if ( visitor instanceof XMLParserVisitor ) return ((XMLParserVisitor<? extends T>)visitor).visitContent(this);
else return visitor.visitChildren(this);
}
}
public final ContentContext content() throws RecognitionException {
ContentContext _localctx = new ContentContext(_ctx, getState());
enterRule(_localctx, 20, RULE_content);
try {
enterOuterAlt(_localctx, 1);
{
setState(117);
_errHandler.sync(this);
switch (_input.LA(1)) {
case OPEN:
{
setState(111);
element();
}
break;
case EntityRef:
case CharRef:
{
setState(112);
reference();
}
break;
case SPECIAL_OPEN:
{
setState(113);
processinginstruction();
}
break;
case CDATA:
{
setState(114);
match(CDATA);
}
break;
case COMMENT:
{
setState(115);
match(COMMENT);
}
break;
case SEA_WS:
case TEXT:
{
setState(116);
chardata();
}
break;
default:
throw new NoViableAltException(this);
}
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static class ElementContext extends ParserRuleContext {
public List<TerminalNode> OPEN() { return getTokens(XMLParser.OPEN); }
public TerminalNode OPEN(int i) {
return getToken(XMLParser.OPEN, i);
}
public List<TerminalNode> Name() { return getTokens(XMLParser.Name); }
public TerminalNode Name(int i) {
return getToken(XMLParser.Name, i);
}
public List<TerminalNode> CLOSE() { return getTokens(XMLParser.CLOSE); }
public TerminalNode CLOSE(int i) {
return getToken(XMLParser.CLOSE, i);
}
public TerminalNode SLASH() { return getToken(XMLParser.SLASH, 0); }
public List<AttributeContext> attribute() {
return getRuleContexts(AttributeContext.class);
}
public AttributeContext attribute(int i) {
return getRuleContext(AttributeContext.class,i);
}
public List<ContentContext> content() {
return getRuleContexts(ContentContext.class);
}
public ContentContext content(int i) {
return getRuleContext(ContentContext.class,i);
}
public TerminalNode SLASH_CLOSE() { return getToken(XMLParser.SLASH_CLOSE, 0); }
public ElementContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_element; }
@Override
public void enterRule(ParseTreeListener listener) {
if ( listener instanceof XMLParserListener ) ((XMLParserListener)listener).enterElement(this);
}
@Override
public void exitRule(ParseTreeListener listener) {
if ( listener instanceof XMLParserListener ) ((XMLParserListener)listener).exitElement(this);
}
@Override
public <T> T accept(ParseTreeVisitor<? extends T> visitor) {
if ( visitor instanceof XMLParserVisitor ) return ((XMLParserVisitor<? extends T>)visitor).visitElement(this);
else return visitor.visitChildren(this);
}
}
public final ElementContext element() throws RecognitionException {
ElementContext _localctx = new ElementContext(_ctx, getState());
enterRule(_localctx, 22, RULE_element);
int _la;
try {
int _alt;
setState(147);
_errHandler.sync(this);
switch ( getInterpreter().adaptivePredict(_input,18,_ctx) ) {
case 1:
enterOuterAlt(_localctx, 1);
{
setState(119);
match(OPEN);
setState(120);
match(Name);
setState(124);
_errHandler.sync(this);
_la = _input.LA(1);
while (_la==Name) {
{
{
setState(121);
attribute();
}
}
setState(126);
_errHandler.sync(this);
_la = _input.LA(1);
}
setState(127);
match(CLOSE);
setState(131);
_errHandler.sync(this);
_alt = getInterpreter().adaptivePredict(_input,16,_ctx);
while ( _alt!=2 && _alt!=org.antlr.v4.runtime.atn.ATN.INVALID_ALT_NUMBER ) {
if ( _alt==1 ) {
{
{
setState(128);
content();
}
}
}
setState(133);
_errHandler.sync(this);
_alt = getInterpreter().adaptivePredict(_input,16,_ctx);
}
setState(134);
match(OPEN);
setState(135);
match(SLASH);
setState(136);
match(Name);
setState(137);
match(CLOSE);
}
break;
case 2:
enterOuterAlt(_localctx, 2);
{
setState(138);
match(OPEN);
setState(139);
match(Name);
setState(143);
_errHandler.sync(this);
_la = _input.LA(1);
while (_la==Name) {
{
{
setState(140);
attribute();
}
}
setState(145);
_errHandler.sync(this);
_la = _input.LA(1);
}
setState(146);
match(SLASH_CLOSE);
}
break;
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static class ReferenceContext extends ParserRuleContext {
public TerminalNode EntityRef() { return getToken(XMLParser.EntityRef, 0); }
public TerminalNode CharRef() { return getToken(XMLParser.CharRef, 0); }
public ReferenceContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_reference; }
@Override
public void enterRule(ParseTreeListener listener) {
if ( listener instanceof XMLParserListener ) ((XMLParserListener)listener).enterReference(this);
}
@Override
public void exitRule(ParseTreeListener listener) {
if ( listener instanceof XMLParserListener ) ((XMLParserListener)listener).exitReference(this);
}
@Override
public <T> T accept(ParseTreeVisitor<? extends T> visitor) {
if ( visitor instanceof XMLParserVisitor ) return ((XMLParserVisitor<? extends T>)visitor).visitReference(this);
else return visitor.visitChildren(this);
}
}
public final ReferenceContext reference() throws RecognitionException {
ReferenceContext _localctx = new ReferenceContext(_ctx, getState());
enterRule(_localctx, 24, RULE_reference);
int _la;
try {
enterOuterAlt(_localctx, 1);
{
setState(149);
_la = _input.LA(1);
if ( !(_la==EntityRef || _la==CharRef) ) {
_errHandler.recoverInline(this);
}
else {
if ( _input.LA(1)==Token.EOF ) matchedEOF = true;
_errHandler.reportMatch(this);
consume();
}
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static class AttributeContext extends ParserRuleContext {
public TerminalNode Name() { return getToken(XMLParser.Name, 0); }
public TerminalNode EQUALS() { return getToken(XMLParser.EQUALS, 0); }
public TerminalNode STRING() { return getToken(XMLParser.STRING, 0); }
public AttributeContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_attribute; }
@Override
public void enterRule(ParseTreeListener listener) {
if ( listener instanceof XMLParserListener ) ((XMLParserListener)listener).enterAttribute(this);
}
@Override
public void exitRule(ParseTreeListener listener) {
if ( listener instanceof XMLParserListener ) ((XMLParserListener)listener).exitAttribute(this);
}
@Override
public <T> T accept(ParseTreeVisitor<? extends T> visitor) {
if ( visitor instanceof XMLParserVisitor ) return ((XMLParserVisitor<? extends T>)visitor).visitAttribute(this);
else return visitor.visitChildren(this);
}
}
public final AttributeContext attribute() throws RecognitionException {
AttributeContext _localctx = new AttributeContext(_ctx, getState());
enterRule(_localctx, 26, RULE_attribute);
try {
enterOuterAlt(_localctx, 1);
{
setState(151);
match(Name);
setState(152);
match(EQUALS);
setState(153);
match(STRING);
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static class ChardataContext extends ParserRuleContext {
public TerminalNode TEXT() { return getToken(XMLParser.TEXT, 0); }
public TerminalNode SEA_WS() { return getToken(XMLParser.SEA_WS, 0); }
public ChardataContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_chardata; }
@Override
public void enterRule(ParseTreeListener listener) {
if ( listener instanceof XMLParserListener ) ((XMLParserListener)listener).enterChardata(this);
}
@Override
public void exitRule(ParseTreeListener listener) {
if ( listener instanceof XMLParserListener ) ((XMLParserListener)listener).exitChardata(this);
}
@Override
public <T> T accept(ParseTreeVisitor<? extends T> visitor) {
if ( visitor instanceof XMLParserVisitor ) return ((XMLParserVisitor<? extends T>)visitor).visitChardata(this);
else return visitor.visitChildren(this);
}
}
public final ChardataContext chardata() throws RecognitionException {
ChardataContext _localctx = new ChardataContext(_ctx, getState());
enterRule(_localctx, 28, RULE_chardata);
int _la;
try {
enterOuterAlt(_localctx, 1);
{
setState(155);
_la = _input.LA(1);
if ( !(_la==SEA_WS || _la==TEXT) ) {
_errHandler.recoverInline(this);
}
else {
if ( _input.LA(1)==Token.EOF ) matchedEOF = true;
_errHandler.reportMatch(this);
consume();
}
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static final String _serializedATN =
"\u0004\u0001!\u009e\u0002\u0000\u0007\u0000\u0002\u0001\u0007\u0001\u0002"+
"\u0002\u0007\u0002\u0002\u0003\u0007\u0003\u0002\u0004\u0007\u0004\u0002"+
"\u0005\u0007\u0005\u0002\u0006\u0007\u0006\u0002\u0007\u0007\u0007\u0002"+
"\b\u0007\b\u0002\t\u0007\t\u0002\n\u0007\n\u0002\u000b\u0007\u000b\u0002"+
"\f\u0007\f\u0002\r\u0007\r\u0002\u000e\u0007\u000e\u0001\u0000\u0003\u0000"+
" \b\u0000\u0001\u0000\u0001\u0000\u0001\u0000\u0001\u0001\u0003\u0001"+
"&\b\u0001\u0001\u0001\u0005\u0001)\b\u0001\n\u0001\f\u0001,\t\u0001\u0001"+
"\u0002\u0001\u0002\u0005\u00020\b\u0002\n\u0002\f\u00023\t\u0002\u0001"+
"\u0002\u0001\u0002\u0001\u0003\u0001\u0003\u0001\u0003\u0003\u0003:\b"+
"\u0003\u0001\u0004\u0001\u0004\u0001\u0004\u0001\u0004\u0001\u0004\u0005"+
"\u0004A\b\u0004\n\u0004\f\u0004D\t\u0004\u0001\u0004\u0001\u0004\u0001"+
"\u0004\u0001\u0004\u0003\u0004J\b\u0004\u0001\u0004\u0001\u0004\u0001"+
"\u0005\u0001\u0005\u0005\u0005P\b\u0005\n\u0005\f\u0005S\t\u0005\u0001"+
"\u0006\u0001\u0006\u0003\u0006W\b\u0006\u0001\u0006\u0005\u0006Z\b\u0006"+
"\n\u0006\f\u0006]\t\u0006\u0001\u0006\u0003\u0006`\b\u0006\u0001\u0006"+
"\u0001\u0006\u0001\u0006\u0003\u0006e\b\u0006\u0001\u0007\u0001\u0007"+
"\u0001\b\u0003\bj\b\b\u0001\t\u0001\t\u0001\t\u0001\t\u0001\n\u0001\n"+
"\u0001\n\u0001\n\u0001\n\u0001\n\u0003\nv\b\n\u0001\u000b\u0001\u000b"+
"\u0001\u000b\u0005\u000b{\b\u000b\n\u000b\f\u000b~\t\u000b\u0001\u000b"+
"\u0001\u000b\u0005\u000b\u0082\b\u000b\n\u000b\f\u000b\u0085\t\u000b\u0001"+
"\u000b\u0001\u000b\u0001\u000b\u0001\u000b\u0001\u000b\u0001\u000b\u0001"+
"\u000b\u0005\u000b\u008e\b\u000b\n\u000b\f\u000b\u0091\t\u000b\u0001\u000b"+
"\u0003\u000b\u0094\b\u000b\u0001\f\u0001\f\u0001\r\u0001\r\u0001\r\u0001"+
"\r\u0001\u000e\u0001\u000e\u0001\u000e\u0000\u0000\u000f\u0000\u0002\u0004"+
"\u0006\b\n\f\u000e\u0010\u0012\u0014\u0016\u0018\u001a\u001c\u0000\u0002"+
"\u0001\u0000\u0004\u0005\u0002\u0000\u0006\u0006\f\f\u00a7\u0000\u001f"+
"\u0001\u0000\u0000\u0000\u0002%\u0001\u0000\u0000\u0000\u0004-\u0001\u0000"+
"\u0000\u0000\u00069\u0001\u0000\u0000\u0000\b;\u0001\u0000\u0000\u0000"+
"\nQ\u0001\u0000\u0000\u0000\fd\u0001\u0000\u0000\u0000\u000ef\u0001\u0000"+
"\u0000\u0000\u0010i\u0001\u0000\u0000\u0000\u0012k\u0001\u0000\u0000\u0000"+
"\u0014u\u0001\u0000\u0000\u0000\u0016\u0093\u0001\u0000\u0000\u0000\u0018"+
"\u0095\u0001\u0000\u0000\u0000\u001a\u0097\u0001\u0000\u0000\u0000\u001c"+
"\u009b\u0001\u0000\u0000\u0000\u001e \u0005\u0007\u0000\u0000\u001f\u001e"+
"\u0001\u0000\u0000\u0000\u001f \u0001\u0000\u0000\u0000 !\u0001\u0000"+
"\u0000\u0000!\"\u0003\u0002\u0001\u0000\"#\u0003\u0016\u000b\u0000#\u0001"+
"\u0001\u0000\u0000\u0000$&\u0003\u0004\u0002\u0000%$\u0001\u0000\u0000"+
"\u0000%&\u0001\u0000\u0000\u0000&*\u0001\u0000\u0000\u0000\')\u0003\u0006"+
"\u0003\u0000(\'\u0001\u0000\u0000\u0000),\u0001\u0000\u0000\u0000*(\u0001"+
"\u0000\u0000\u0000*+\u0001\u0000\u0000\u0000+\u0003\u0001\u0000\u0000"+
"\u0000,*\u0001\u0000\u0000\u0000-1\u0005\b\u0000\u0000.0\u0003\u001a\r"+
"\u0000/.\u0001\u0000\u0000\u000003\u0001\u0000\u0000\u00001/\u0001\u0000"+
"\u0000\u000012\u0001\u0000\u0000\u000024\u0001\u0000\u0000\u000031\u0001"+
"\u0000\u0000\u000045\u0005\u001b\u0000\u00005\u0005\u0001\u0000\u0000"+
"\u00006:\u0005\u0001\u0000\u00007:\u0003\b\u0004\u00008:\u0003\u0012\t"+
"\u000096\u0001\u0000\u0000\u000097\u0001\u0000\u0000\u000098\u0001\u0000"+
"\u0000\u0000:\u0007\u0001\u0000\u0000\u0000;<\u0005\u000b\u0000\u0000"+
"<=\u0005\u0010\u0000\u0000=>\u0005!\u0000\u0000>B\u0003\u0010\b\u0000"+
"?A\u0005 \u0000\u0000@?\u0001\u0000\u0000\u0000AD\u0001\u0000\u0000\u0000"+
"B@\u0001\u0000\u0000\u0000BC\u0001\u0000\u0000\u0000CI\u0001\u0000\u0000"+
"\u0000DB\u0001\u0000\u0000\u0000EF\u0005\u000e\u0000\u0000FG\u0003\n\u0005"+
"\u0000GH\u0005\u0011\u0000\u0000HJ\u0001\u0000\u0000\u0000IE\u0001\u0000"+
"\u0000\u0000IJ\u0001\u0000\u0000\u0000JK\u0001\u0000\u0000\u0000KL\u0005"+
"\r\u0000\u0000L\t\u0001\u0000\u0000\u0000MP\u0003\f\u0006\u0000NP\u0003"+
"\u000e\u0007\u0000OM\u0001\u0000\u0000\u0000ON\u0001\u0000\u0000\u0000"+
"PS\u0001\u0000\u0000\u0000QO\u0001\u0000\u0000\u0000QR\u0001\u0000\u0000"+
"\u0000R\u000b\u0001\u0000\u0000\u0000SQ\u0001\u0000\u0000\u0000TV\u0005"+
"\u0012\u0000\u0000UW\u0005\u0016\u0000\u0000VU\u0001\u0000\u0000\u0000"+
"VW\u0001\u0000\u0000\u0000W[\u0001\u0000\u0000\u0000XZ\u0005\u0017\u0000"+
"\u0000YX\u0001\u0000\u0000\u0000Z]\u0001\u0000\u0000\u0000[Y\u0001\u0000"+
"\u0000\u0000[\\\u0001\u0000\u0000\u0000\\_\u0001\u0000\u0000\u0000][\u0001"+
"\u0000\u0000\u0000^`\u0005\u0016\u0000\u0000_^\u0001\u0000\u0000\u0000"+
"_`\u0001\u0000\u0000\u0000`a\u0001\u0000\u0000\u0000ae\u0005\u0014\u0000"+
"\u0000be\u0003\u0012\t\u0000ce\u0005\u0001\u0000\u0000dT\u0001\u0000\u0000"+
"\u0000db\u0001\u0000\u0000\u0000dc\u0001\u0000\u0000\u0000e\r\u0001\u0000"+
"\u0000\u0000fg\u0005\u0003\u0000\u0000g\u000f\u0001\u0000\u0000\u0000"+
"hj\u0005!\u0000\u0000ih\u0001\u0000\u0000\u0000ij\u0001\u0000\u0000\u0000"+
"j\u0011\u0001\u0000\u0000\u0000kl\u0005\n\u0000\u0000lm\u0005\u0019\u0000"+
"\u0000mn\u0005\u001b\u0000\u0000n\u0013\u0001\u0000\u0000\u0000ov\u0003"+
"\u0016\u000b\u0000pv\u0003\u0018\f\u0000qv\u0003\u0012\t\u0000rv\u0005"+
"\u0002\u0000\u0000sv\u0005\u0001\u0000\u0000tv\u0003\u001c\u000e\u0000"+
"uo\u0001\u0000\u0000\u0000up\u0001\u0000\u0000\u0000uq\u0001\u0000\u0000"+
"\u0000ur\u0001\u0000\u0000\u0000us\u0001\u0000\u0000\u0000ut\u0001\u0000"+
"\u0000\u0000v\u0015\u0001\u0000\u0000\u0000wx\u0005\t\u0000\u0000x|\u0005"+
"!\u0000\u0000y{\u0003\u001a\r\u0000zy\u0001\u0000\u0000\u0000{~\u0001"+
"\u0000\u0000\u0000|z\u0001\u0000\u0000\u0000|}\u0001\u0000\u0000\u0000"+
"}\u007f\u0001\u0000\u0000\u0000~|\u0001\u0000\u0000\u0000\u007f\u0083"+
"\u0005\u001a\u0000\u0000\u0080\u0082\u0003\u0014\n\u0000\u0081\u0080\u0001"+
"\u0000\u0000\u0000\u0082\u0085\u0001\u0000\u0000\u0000\u0083\u0081\u0001"+
"\u0000\u0000\u0000\u0083\u0084\u0001\u0000\u0000\u0000\u0084\u0086\u0001"+
"\u0000\u0000\u0000\u0085\u0083\u0001\u0000\u0000\u0000\u0086\u0087\u0005"+
"\t\u0000\u0000\u0087\u0088\u0005\u001e\u0000\u0000\u0088\u0089\u0005!"+
"\u0000\u0000\u0089\u0094\u0005\u001a\u0000\u0000\u008a\u008b\u0005\t\u0000"+
"\u0000\u008b\u008f\u0005!\u0000\u0000\u008c\u008e\u0003\u001a\r\u0000"+
"\u008d\u008c\u0001\u0000\u0000\u0000\u008e\u0091\u0001\u0000\u0000\u0000"+
"\u008f\u008d\u0001\u0000\u0000\u0000\u008f\u0090\u0001\u0000\u0000\u0000"+
"\u0090\u0092\u0001\u0000\u0000\u0000\u0091\u008f\u0001\u0000\u0000\u0000"+
"\u0092\u0094\u0005\u001c\u0000\u0000\u0093w\u0001\u0000\u0000\u0000\u0093"+
"\u008a\u0001\u0000\u0000\u0000\u0094\u0017\u0001\u0000\u0000\u0000\u0095"+
"\u0096\u0007\u0000\u0000\u0000\u0096\u0019\u0001\u0000\u0000\u0000\u0097"+
"\u0098\u0005!\u0000\u0000\u0098\u0099\u0005\u001f\u0000\u0000\u0099\u009a"+
"\u0005 \u0000\u0000\u009a\u001b\u0001\u0000\u0000\u0000\u009b\u009c\u0007"+
"\u0001\u0000\u0000\u009c\u001d\u0001\u0000\u0000\u0000\u0013\u001f%*1"+
"9BIOQV[_diu|\u0083\u008f\u0093";
public static final ATN _ATN =
new ATNDeserializer().deserialize(_serializedATN.toCharArray());
static {
_decisionToDFA = new DFA[_ATN.getNumberOfDecisions()];
for (int i = 0; i < _ATN.getNumberOfDecisions(); i++) {
_decisionToDFA[i] = new DFA(_ATN.getDecisionState(i), i);
}
}
} | 33.027273 | 147 | 0.711556 |
5113494716cf7c4e88f3f46cbc707cc43a73b5bc | 1,354 | package com.blackwater.Models;
import javax.persistence.*;
import java.util.Calendar;
@Entity
public class Client {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String email;
private String password;
private Calendar birthDate;
@OneToOne
private Adress adress;
public Client(String name, String email, String password, Calendar birthDate) {
this.name = name;
this.email = email;
this.password = password;
this.birthDate = birthDate;
}
public Adress getAdress() {
return adress;
}
public void setAdress(Adress adress) {
this.adress = adress;
}
public Long getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Calendar getBirthDate() {
return birthDate;
}
public void setBirthDate(Calendar birthDate) {
this.birthDate = birthDate;
}
}
| 18.805556 | 83 | 0.612999 |
5530a4b1f98c647e011eaa52870f40bab9a2c16c | 2,403 | /* Copyright 2004-2019 Jim Voris
*
* 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.qumasoft.server;
import java.util.Collections;
import java.util.Map;
import java.util.TreeMap;
/**
* Directory Contents manager factory. A factory class to create directory contents managers.
*
* @author Jim Voris
*/
public final class DirectoryContentsManagerFactory {
/**
* This is a singleton
*/
private static final DirectoryContentsManagerFactory DIRECTORY_CONTENTS_MANAGER_FACTORY = new DirectoryContentsManagerFactory();
/**
* Map for the DirectoryContentsManager objects. One per project
*/
private final Map<String, DirectoryContentsManager> directoryContentsManagerMap = Collections.synchronizedMap(new TreeMap<>());
/**
* Creates a new instance of DirectoryContentsManagerFactory.
*/
private DirectoryContentsManagerFactory() {
}
/**
* Get the Directory contents manager factory singleton.
*
* @return the Directory contents manager factory singleton.
*/
public static DirectoryContentsManagerFactory getInstance() {
return DIRECTORY_CONTENTS_MANAGER_FACTORY;
}
/**
* Get the directory contents manager for a given project.
*
* @param projectName the project name.
* @return the directory contents manager for the given project.
*/
public DirectoryContentsManager getDirectoryContentsManager(final String projectName) {
if (directoryContentsManagerMap.containsKey(projectName)) {
return directoryContentsManagerMap.get(projectName);
} else {
DirectoryContentsManager directoryContentsManager = new DirectoryContentsManager(projectName);
directoryContentsManagerMap.put(projectName, directoryContentsManager);
return directoryContentsManager;
}
}
}
| 35.338235 | 132 | 0.719101 |
310537ad2c3c3211e1919165d2d8a7b3cca28b95 | 3,990 | package io.prime.sse.client;
import java.net.URI;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.DefaultHttpRequest;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;
public class SseClientBuilder implements GenericFutureListener<Future<Void>>
{
private Logger logger = LoggerFactory.getLogger(this.getClass());
// @Value("${event.sse.url}")
private URI uri;
private EventLoopGroup group;
private Channel channel;
@PreDestroy
public void preDestroy()
{
this.logger.info("Shutting down Gateway Http Server (Netty) channel");
this.channel.close();
}
private HttpRequest createRequest(String lastEventId)
{
HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, this.uri.toString());
String hostHeader = this.uri.getHost();
String portString = "";
if (80==this.uri.getPort() && this.uri.getScheme().equals("http") ) {
// do nothing
} else if (443==this.uri.getPort() && this.uri.getScheme().equals("https")) {
// do nothing
} else {
portString = ":" + this.uri.getPort();
}
request.headers()
.add(HttpHeaderNames.ACCEPT, "text/event-stream")
.add(HttpHeaderNames.HOST, hostHeader + portString)
.add(HttpHeaderNames.ORIGIN, this.uri.getScheme() + "://" + this.uri.getHost() + portString)
.add(HttpHeaderNames.CACHE_CONTROL, "no-cache")
;
if (false == StringUtils.isEmpty(lastEventId)) {
request.headers().add("Last-Event-ID", lastEventId);
}
return request;
}
@PostConstruct
public void createChannel() throws Exception
{
this.logger.info("Starting Gateway Http Server (Netty)");
final SslContext sslCtx;
if ("https".equals(this.uri.getScheme())) {
sslCtx = SslContextBuilder.forClient().build();
} else {
sslCtx = null;
}
group = new NioEventLoopGroup(1);
Bootstrap b = new Bootstrap();
b.group(group)
.channel(NioSocketChannel.class)
.handler(new SseClientInitializer(sslCtx))
;
HttpRequest request = this.createRequest(null);
channel = b.connect(this.uri.getHost(), this.uri.getPort()).sync().channel();
this.channel.closeFuture().addListener(this);
this.channel
.writeAndFlush(request)
.addListener(new ChannelFutureListener()
{
@Override
public void operationComplete(ChannelFuture future) throws Exception {
System.out.println("$$$$ OPERATION_COMPLETE: " + future.isSuccess());
}
});
}
@Override
public void operationComplete(Future<Void> future) throws Exception {
this.logger.info("Shutting down workgroup of Gateway Http Server (Netty) gracefully");
this.group.shutdownGracefully();
}
public static void main(String[] args) throws Exception
{
SseClientBuilder client = new SseClientBuilder();
client.uri = new URI("http://localhost:28080/map/internal/event/sse");
client.createChannel();
}
}
| 32.177419 | 110 | 0.679198 |
9820f1d7d324bc21a90cb5f7eb38985a7e952084 | 11,108 | package dao;
import model.AreaEstacionamento;
import model.Proprietario;
import model.Veiculo;
import java.sql.*;
public class DataCadastro implements DataClass {
private static Connection conn;
private static DataCadastro instance = new DataCadastro();
private PreparedStatement dropPropTable;
private PreparedStatement createPropTable;
private PreparedStatement dropVeicTable;
private PreparedStatement createVeicTable;
private PreparedStatement dropAreaTable;
private PreparedStatement createAreaTable;
private PreparedStatement dropUsuariosTable;
private PreparedStatement createUsuariosTable;
private PreparedStatement queryPropByName;
private PreparedStatement queryPropById;
private PreparedStatement insertProp;
private PreparedStatement queryVeicByPlaca;
private PreparedStatement queryVeicById;
private PreparedStatement insertVeic;
private PreparedStatement queryAreaByName;
private PreparedStatement queryAreaById;
private PreparedStatement insertArea;
private PreparedStatement insertUsuario;
private DataCadastro() {
}
public static DataCadastro getInstance() {
return instance;
}
@Override
public boolean open() {
try {
conn = DriverManager.getConnection(Constants.CONECTION_STR);
dropPropTable = conn.prepareStatement(Constants.DROP_PROPRIETARIOS_TABLE);
createPropTable = conn.prepareStatement(Constants.CREATE_PROPRIETARIOS_TABLE);
dropVeicTable = conn.prepareStatement(Constants.DROP_VEICULOS_TABLE);
createVeicTable = conn.prepareStatement(Constants.CREATE_VEICULOS_TABLE);
dropAreaTable = conn.prepareStatement(Constants.DROP_AREAS_TABLE);
createAreaTable = conn.prepareStatement(Constants.CREATE_AREAS_TABLE);
dropUsuariosTable = conn.prepareStatement(Constants.DROP_USUARIOS_TABLE);
queryPropByName = conn.prepareStatement(Constants.QUERY_PROPRIETARIO_BY_NAME);
queryPropById = conn.prepareStatement(Constants.QUERY_PROPRIETARIO_BY_ID);
insertProp = conn.prepareStatement(Constants.INSERT_PROPRIETARIO);
queryVeicByPlaca = conn.prepareStatement(Constants.QUERY_VEICULO_BY_PLACA);
queryVeicById = conn.prepareStatement(Constants.QUERY_VEICULO_BY_ID);
insertVeic = conn.prepareStatement(Constants.INSERT_VEICULO);
queryAreaByName = conn.prepareStatement(Constants.QUERY_AREA_BY_NAME);
queryAreaById = conn.prepareStatement(Constants.QUERY_AREA_BY_ID);
insertArea = conn.prepareStatement(Constants.INSERT_AREA);
insertUsuario = conn.prepareStatement(Constants.INSERT_USUARIO);
dropPropTable.execute();
createPropTable.execute();
dropVeicTable.execute();
createVeicTable.execute();
dropAreaTable.execute();
createAreaTable.execute();
dropUsuariosTable.execute();
createUsuariosTable.execute();
return true;
} catch (SQLException e) {
System.out.println("SQLException: " + e.getMessage());
return false;
}
}
@Override
public void close() {
try {
if (dropPropTable != null) {
dropPropTable.close();
}
if (dropVeicTable != null) {
dropVeicTable.close();
}
if (dropAreaTable != null) {
dropAreaTable.close();
}
if (dropUsuariosTable != null) {
dropUsuariosTable.close();
}
if (createPropTable != null) {
createPropTable.close();
}
if (createVeicTable != null) {
createVeicTable.close();
}
if (createAreaTable != null) {
createAreaTable.close();
}
if (createUsuariosTable != null) {
createUsuariosTable.close();
}
if (queryPropByName != null) {
queryPropByName.close();
}
if (queryPropById != null) {
queryPropById.close();
}
if (queryVeicByPlaca != null) {
queryVeicByPlaca.close();
}
if (queryVeicById != null) {
queryVeicById.close();
}
if (queryAreaByName != null) {
queryAreaByName.close();
}
if (queryAreaById != null) {
queryAreaById.close();
}
if (insertProp != null) {
insertProp.close();
}
if (insertVeic != null) {
insertProp.close();
}
if (insertArea != null) {
insertProp.close();
}
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
System.out.println("SQLException: " + e.getMessage());
}
}
public Proprietario queryProprietarioByName(String nome) {
try {
queryPropByName.setString(1, nome.toUpperCase());
ResultSet results = queryPropByName.executeQuery();
if (results.next()) {
int currId = (results.getInt(1));
String currNome = (results.getString(2));
long currMat = (results.getLong(3));
String currCurso = (results.getString(4));
Proprietario proprietario = new Proprietario(currId, currNome, currMat, currCurso);
return proprietario;
}
return null;
} catch (SQLException e) {
System.out.println("SQLException: " + e.getMessage());
return null;
}
}
public Proprietario queryProprietarioById(int id) {
try {
queryPropById.setInt(1, id);
ResultSet results = queryPropById.executeQuery();
if (results.next()) {
int currId = (results.getInt(1));
String currNome = (results.getString(2));
long currMat = (results.getLong(3));
String currCurso = (results.getString(4));
Proprietario proprietario = new Proprietario(currId, currNome, currMat, currCurso);
return proprietario;
}
return null;
} catch (SQLException e) {
System.out.println("SQLException: " + e.getMessage());
return null;
}
}
public boolean insertProprietario(String nome, long matricula, String curso) {
nome = nome.toUpperCase();
curso = curso.toUpperCase();
// Proprietario proprietario = queryProprietario(nome);
// if (proprietario != null) {
// return false;
// }
try {
insertProp.setString(1, nome);
insertProp.setLong(2, matricula);
insertProp.setString(3, curso);
insertProp.executeUpdate();
return true;
} catch (SQLException e) {
System.out.println("SQLException: " + e.getMessage());
return false;
}
}
// public AreaEstacionamento queryAreaByName(String nome) {
// try {
// queryAreaByName.setString(1, nome.toUpperCase());
// ResultSet results = queryAreaByName.executeQuery();
// if (results.next()) {
// int currId = (results.getInt(1));
// String currNome = (results.getString(2));
// int currCap = (results.getInt(3));
// AreaEstacionamento area = new AreaEstacionamento(currId, currNome, currCap);
// return area;
// }
// return null;
// } catch (SQLException e) {
// System.out.println("SQLException: " + e.getMessage());
// return null;
// }
// }
// public AreaEstacionamento queryAreaById(int id) {
// try {
// queryAreaById.setInt(1, id);
// ResultSet results = queryAreaById.executeQuery();
// if (results.next()) {
// int currId = (results.getInt(1));
// String currNome = (results.getString(2));
// int currCap = (results.getInt(3));
// AreaEstacionamento area = new AreaEstacionamento(currId, currNome, currCap);
// return area;
// }
// return null;
// } catch (SQLException e) {
// System.out.println("SQLException: " + e.getMessage());
// return null;
// }
// }
// public boolean insertArea(String nome, int capacidade) {
// nome = nome.toUpperCase();
//// AreaEstacionamento area = queryArea(nome);
//// if (area != null) {
//// return false;
//// }
// try {
// insertArea.setString(1, nome);
// insertArea.setLong(2, capacidade);
// insertArea.executeUpdate();
// return true;
// } catch (SQLException e) {
// System.out.println("SQLException: " + e.getMessage());
// return false;
// }
// }
// public Veiculo queryVeiculo(String placa) {
// try {
// queryVeicByPlaca.setString(1, placa.toUpperCase());
// ResultSet results = queryVeicByPlaca.executeQuery();
// if (results.next()) {
// int currId = (results.getInt(1));
// String currPlaca = (results.getString(2));
// int currPropId = (results.getInt(3));
// String currModelo = (results.getString(4));
// String currCor = (results.getString(5));
// int currAreaId = (results.getInt(6));
// Proprietario currProp = queryProprietarioById(currPropId);
// String currAreaName = queryAreaById(currId).getNome();
// Veiculo veiculo = new Veiculo(currId, currPlaca, currProp, currModelo, currCor, currAreaName);
// return veiculo;
// }
// return null;
// } catch (SQLException e) {
// System.out.println("SQLException: " + e.getMessage());
// return null;
// }
// }
//
// public boolean insertVeiculo(String placa, String nome, long matricula, String curso, String modelo, String cor, String area) {
// nome = nome.toUpperCase();
// curso = curso.toUpperCase();
//// Proprietario proprietario = queryProprietario(nome);
//// if (proprietario != null) {
//// return false;
//// }
// try {
// insertProp.setString(1, nome);
// insertProp.setLong(2, matricula);
// insertProp.setString(3, curso);
// insertProp.executeUpdate();
// return true;
// } catch (SQLException e) {
// System.out.println("SQLException: " + e.getMessage());
// return false;
// }
//
// }
}
| 36.539474 | 133 | 0.563018 |
af8c981a210c98db48862fce1ad511c09f598ea1 | 1,256 | package com.example.friends_friends.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="friends_details")
public class Details {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String name;
private int age;
private String job;
public Details() {
super();
}
public Details(int id,
String name,
int age,
String job) {
super();
this.id = id;
this.name = name;
this.age = age;
this.job = job;
}
public Details(String name,
int age,
String job) {
super();
this.name = name;
this.age = age;
this.job = job;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getJob() {
return job;
}
public void setJob(String job) {
this.job = job;
}
@Override
public String toString() {
return "Details [id=" + id + ", name=" + name + ", age=" + age + ", job=" + job + "]";
}
}
| 16.972973 | 88 | 0.651274 |
5d73780f130322821408e80395ff4c3671dbec78 | 6,838 | /*
* All content copyright Terracotta, Inc., unless otherwise indicated. 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 org.quartz;
import java.util.Calendar;
import java.util.TimeZone;
/**
* The public interface for inspecting settings specific to a CronTrigger, .
* which is used to fire a <code>{@link org.quartz.Job}</code>
* at given moments in time, defined with Unix 'cron-like' schedule definitions.
*
* <p>
* For those unfamiliar with "cron", this means being able to create a firing
* schedule such as: "At 8:00am every Monday through Friday" or "At 1:30am
* every last Friday of the month".
* </p>
*
* <p>
* The format of a "Cron-Expression" string is documented on the
* {@link org.quartz.CronExpression} class.
* </p>
*
* <p>
* Here are some full examples: <br><table cellspacing="8">
* <tr>
* <th align="left">Expression</th>
* <th align="left"> </th>
* <th align="left">Meaning</th>
* </tr>
* <tr>
* <td align="left"><code>"0 0 12 * * ?"</code></td>
* <td align="left"> </th>
* <td align="left"><code>Fire at 12pm (noon) every day</code></td>
* </tr>
* <tr>
* <td align="left"><code>"0 15 10 ? * *"</code></td>
* <td align="left"> </th>
* <td align="left"><code>Fire at 10:15am every day</code></td>
* </tr>
* <tr>
* <td align="left"><code>"0 15 10 * * ?"</code></td>
* <td align="left"> </th>
* <td align="left"><code>Fire at 10:15am every day</code></td>
* </tr>
* <tr>
* <td align="left"><code>"0 15 10 * * ? *"</code></td>
* <td align="left"> </th>
* <td align="left"><code>Fire at 10:15am every day</code></td>
* </tr>
* <tr>
* <td align="left"><code>"0 15 10 * * ? 2005"</code></td>
* <td align="left"> </th>
* <td align="left"><code>Fire at 10:15am every day during the year 2005</code>
* </td>
* </tr>
* <tr>
* <td align="left"><code>"0 * 14 * * ?"</code></td>
* <td align="left"> </th>
* <td align="left"><code>Fire every minute starting at 2pm and ending at 2:59pm, every day</code>
* </td>
* </tr>
* <tr>
* <td align="left"><code>"0 0/5 14 * * ?"</code></td>
* <td align="left"> </th>
* <td align="left"><code>Fire every 5 minutes starting at 2pm and ending at 2:55pm, every day</code>
* </td>
* </tr>
* <tr>
* <td align="left"><code>"0 0/5 14,18 * * ?"</code></td>
* <td align="left"> </th>
* <td align="left"><code>Fire every 5 minutes starting at 2pm and ending at 2:55pm, AND fire every 5 minutes starting at 6pm and ending at 6:55pm, every day</code>
* </td>
* </tr>
* <tr>
* <td align="left"><code>"0 0-5 14 * * ?"</code></td>
* <td align="left"> </th>
* <td align="left"><code>Fire every minute starting at 2pm and ending at 2:05pm, every day</code>
* </td>
* </tr>
* <tr>
* <td align="left"><code>"0 10,44 14 ? 3 WED"</code></td>
* <td align="left"> </th>
* <td align="left"><code>Fire at 2:10pm and at 2:44pm every Wednesday in the month of March.</code>
* </td>
* </tr>
* <tr>
* <td align="left"><code>"0 15 10 ? * MON-FRI"</code></td>
* <td align="left"> </th>
* <td align="left"><code>Fire at 10:15am every Monday, Tuesday, Wednesday, Thursday and Friday</code>
* </td>
* </tr>
* <tr>
* <td align="left"><code>"0 15 10 15 * ?"</code></td>
* <td align="left"> </th>
* <td align="left"><code>Fire at 10:15am on the 15th day of every month</code>
* </td>
* </tr>
* <tr>
* <td align="left"><code>"0 15 10 L * ?"</code></td>
* <td align="left"> </th>
* <td align="left"><code>Fire at 10:15am on the last day of every month</code>
* </td>
* </tr>
* <tr>
* <td align="left"><code>"0 15 10 ? * 6L"</code></td>
* <td align="left"> </th>
* <td align="left"><code>Fire at 10:15am on the last Friday of every month</code>
* </td>
* </tr>
* <tr>
* <td align="left"><code>"0 15 10 ? * 6L"</code></td>
* <td align="left"> </th>
* <td align="left"><code>Fire at 10:15am on the last Friday of every month</code>
* </td>
* </tr>
* <tr>
* <td align="left"><code>"0 15 10 ? * 6L 2002-2005"</code></td>
* <td align="left"> </th>
* <td align="left"><code>Fire at 10:15am on every last Friday of every month during the years 2002, 2003, 2004 and 2005</code>
* </td>
* </tr>
* <tr>
* <td align="left"><code>"0 15 10 ? * 6#3"</code></td>
* <td align="left"> </th>
* <td align="left"><code>Fire at 10:15am on the third Friday of every month</code>
* </td>
* </tr>
* </table>
* </p>
*
* <p>
* Pay attention to the effects of '?' and '*' in the day-of-week and
* day-of-month fields!
* </p>
*
* <p>
* <b>NOTES:</b>
* <ul>
* <li>Support for specifying both a day-of-week and a day-of-month value is
* not complete (you'll need to use the '?' character in on of these fields).
* </li>
* <li>Be careful when setting fire times between mid-night and 1:00 AM -
* "daylight savings" can cause a skip or a repeat depending on whether the
* time moves back or jumps forward.</li>
* </ul>
* </p>
*
* @see CronScheduleBuilder
* @see TriggerBuilder
*
* @author jhouse
* @author Contributions from Mads Henderson
*/
public interface CronTrigger extends Trigger {
public static final long serialVersionUID = -8644953146451592766L;
/**
* <p>
* Instructs the <code>{@link Scheduler}</code> that upon a mis-fire
* situation, the <code>{@link CronTrigger}</code> wants to be fired now
* by <code>Scheduler</code>.
* </p>
*/
public static final int MISFIRE_INSTRUCTION_FIRE_ONCE_NOW = 1;
/**
* <p>
* Instructs the <code>{@link Scheduler}</code> that upon a mis-fire
* situation, the <code>{@link CronTrigger}</code> wants to have it's
* next-fire-time updated to the next time in the schedule after the
* current time (taking into account any associated <code>{@link Calendar}</code>,
* but it does not want to be fired now.
* </p>
*/
public static final int MISFIRE_INSTRUCTION_DO_NOTHING = 2;
public String getCronExpression();
/**
* <p>
* Returns the time zone for which the <code>cronExpression</code> of
* this <code>CronTrigger</code> will be resolved.
* </p>
*/
public TimeZone getTimeZone();
public String getExpressionSummary();
TriggerBuilder<CronTrigger> getTriggerBuilder();
}
| 32.875 | 164 | 0.61363 |
96e18d6b8dae1432c64652bc5e4531a1c156d6b5 | 624 | package com.sequenceiq.freeipa.flow.stack.upgrade.ccm.selector;
import com.sequenceiq.common.api.type.Tunnel;
import com.sequenceiq.flow.core.FlowEvent;
import com.sequenceiq.freeipa.flow.stack.upgrade.ccm.event.UpgradeCcmEvent;
public interface UpgradeCcmFlowEvent extends FlowEvent {
default UpgradeCcmEvent create(Long stackId, Tunnel oldTunnel) {
return new UpgradeCcmEvent(event(), stackId, oldTunnel);
}
default UpgradeCcmEvent createBasedOn(UpgradeCcmEvent upgradeCcmEvent) {
return new UpgradeCcmEvent(event(), upgradeCcmEvent.getResourceId(), upgradeCcmEvent.getOldTunnel());
}
}
| 39 | 109 | 0.786859 |
6e3ccafb1048c30441ae36bb4cb1435a1cc84d2c | 3,274 | package net.meisen.dissertation.impl.parser.query.select.evaluator;
import net.meisen.dissertation.impl.parser.query.Interval;
import net.meisen.dissertation.impl.parser.query.select.IntervalRelation;
import net.meisen.dissertation.impl.parser.query.select.SelectQuery;
import net.meisen.dissertation.impl.parser.query.select.SelectResultRecords;
import net.meisen.dissertation.model.data.IntervalModel;
import net.meisen.dissertation.model.data.TidaModel;
import net.meisen.dissertation.model.indexes.BaseIndexFactory;
import net.meisen.dissertation.model.indexes.datarecord.TidaIndex;
import net.meisen.dissertation.model.indexes.datarecord.slices.Bitmap;
/**
* Evaluator used to evaluate the selected records of a {@code SelectResult}.
*
* @author pmeisen
*
*/
public class RecordsEvaluator {
private final TidaIndex index;
private final BaseIndexFactory indexFactory;
private final IntervalModel intervalModel;
/**
* Default constructor specifying for which {@code model} the evaluation
* takes place.
*
* @param model
* the model the evaluation takes place for
*/
public RecordsEvaluator(final TidaModel model) {
this.intervalModel = model.getIntervalModel();
this.index = model.getIndex();
this.indexFactory = model.getIndexFactory();
}
/**
* Evaluates the result for the specified {@code interval}.
*
* @param query
* the {@code SelectQuery} to evaluate
* @param filteredBitmap
* the bitmap defining all the filtered bitmaps
*
* @return the selected records
*
* @see SelectResultRecords
*/
public Bitmap evaluateInterval(final SelectQuery query,
final Bitmap filteredBitmap) {
final Interval<?> interval = query.getInterval();
final IntervalRelation relation = query.getIntervalRelation();
// get the relation or use a default one if none is defined
final IntervalRelation intervalRelation = relation == null ? IntervalRelation.WITHIN
: relation;
// the result bitmap
final Bitmap result;
// check if there is a limit
if (!query.hasLimit() || query.getLimit() != 0) {
// combine the time with it
if (filteredBitmap == null || filteredBitmap.isBitSet()) {
final Bitmap timeBitmap = intervalRelation.determine(
intervalModel, index, interval);
result = combine(filteredBitmap, timeBitmap);
} else {
result = null;
}
} else {
result = null;
}
// if we don't have any result return null
if (result == null) {
return indexFactory.createBitmap();
} else {
return result;
}
}
/**
* Helper method to and-combine the {@code resBitmap} and the
* {@code andBitmap}.
*
* @param resBitmap
* the result bitmap, can be {@code null} if so it is ignored in
* combination
* @param andBitmap
* the and-bitmap to be and-combined, can be {@code null} if so
* it is ignored in combination
*
* @return the combination of the {@code resBitmap} and the
* {@code andBitmap}
*/
protected Bitmap combine(final Bitmap resBitmap, final Bitmap andBitmap) {
if (andBitmap == null) {
return resBitmap;
} else if (resBitmap == null) {
return andBitmap;
} else {
return Bitmap.and(indexFactory, resBitmap, andBitmap);
}
}
}
| 30.036697 | 86 | 0.704032 |
56c225bdffd503f18589aef4c30b8b61ec50ec58 | 1,914 | /*
* Copyright 2015-2021 Alejandro Sánchez <alex@nexttypes.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.nexttypes.datatypes;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import com.nexttypes.system.KeyWords;
@JsonPropertyOrder({ KeyWords.REFERENCED_TYPE, KeyWords.REFERENCING_TYPE, KeyWords.REFERENCING_FIELD })
public class Reference {
protected String referencedType;
protected String referencingType;
protected String referencingField;
public Reference(String referencedType, String referencingType, String referencingField) {
this.referencedType = referencedType;
this.referencingType = referencingType;
this.referencingField = referencingField;
}
@JsonProperty(KeyWords.REFERENCED_TYPE)
public String getReferencedType() {
return referencedType;
}
@JsonProperty(KeyWords.REFERENCING_TYPE)
public String getReferencingType() {
return referencingType;
}
@JsonProperty(KeyWords.REFERENCING_FIELD)
public String getReferencingField() {
return referencingField;
}
public void setReferencedType(String referencedType) {
this.referencedType = referencedType;
}
public void setReferencingType(String referencingType) {
this.referencingType = referencingType;
}
public void setReferencingField(String referencingField) {
this.referencingField = referencingField;
}
} | 30.870968 | 103 | 0.790491 |
b066a4cbd9289a192f0f72b673d39fb5448da5db | 455 | package ink.ikx.rt.api.mods.contenttweaker.function.mana;
import crafttweaker.api.item.IItemStack;
import ink.ikx.rt.impl.mods.crafttweaker.ModTotal;
import ink.ikx.rt.impl.mods.crafttweaker.RTRegister;
import stanhebben.zenscript.annotations.ZenClass;
@RTRegister
@FunctionalInterface
@ModTotal({"contenttweaker", "botania"})
@ZenClass("mods.randomtweaker.cote.IGetBaubleType")
public interface IGetBaubleType {
String call(IItemStack stack);
}
| 25.277778 | 57 | 0.808791 |
9f45f517a26ee47ca31a87804d602ae537acacc3 | 1,400 | /*
* Copyright 2021 DataCanvas
*
* 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.dingodb.common.table;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonValue;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import java.io.IOException;
import java.util.Base64;
import javax.annotation.Nonnull;
@EqualsAndHashCode
public class TableId {
@Getter
private final byte[] value;
public TableId(byte[] value) {
this.value = value;
}
@JsonCreator
@Nonnull
public static TableId fromBase64(String encoded) throws IOException {
return new TableId(Base64.getDecoder().decode(encoded));
}
@JsonValue
public String toBase64() {
return Base64.getEncoder().encodeToString(value);
}
@Override
public String toString() {
return toBase64();
}
}
| 26.415094 | 75 | 0.718571 |
2e9a07acbf5d7314913a09c58389dc0fa3dc6141 | 3,152 | /*
* 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.commons.compress;
import static org.junit.Assert.assertTrue;
import static org.ops4j.pax.exam.CoreOptions.bundle;
import static org.ops4j.pax.exam.CoreOptions.composite;
import static org.ops4j.pax.exam.CoreOptions.mavenBundle;
import static org.ops4j.pax.exam.CoreOptions.systemProperty;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.ops4j.pax.exam.Configuration;
import org.ops4j.pax.exam.Option;
import org.ops4j.pax.exam.junit.PaxExam;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import javax.inject.Inject;
@RunWith(PaxExam.class)
public class OsgiITest {
private static final String EXPECTED_BUNDLE_NAME = "org.apache.commons.commons-compress";
@Inject
private BundleContext ctx;
@Configuration
public Option[] config() {
return new Option[] {
systemProperty("pax.exam.osgi.unresolved.fail").value("true"),
mavenBundle().groupId("org.apache.felix").artifactId("org.apache.felix.scr")
.version("2.0.14"),
mavenBundle().groupId("org.apache.felix").artifactId("org.apache.felix.configadmin")
.version("1.8.16"),
composite(systemProperty("pax.exam.invoker").value("junit"),
bundle("link:classpath:META-INF/links/org.ops4j.pax.tipi.junit.link"),
bundle("link:classpath:META-INF/links/org.ops4j.pax.exam.invoker.junit.link"),
mavenBundle().groupId("org.apache.servicemix.bundles")
.artifactId("org.apache.servicemix.bundles.hamcrest").version("1.3_1")),
bundle("reference:file:target/classes/").start()
};
}
@Test
public void loadBundle() {
final StringBuilder bundles = new StringBuilder();
boolean foundCompressBundle = false, first = true;
for (final Bundle b : ctx.getBundles()) {
final String symbolicName = b.getSymbolicName();
foundCompressBundle |= EXPECTED_BUNDLE_NAME.equals(symbolicName);
if (!first) {
bundles.append(", ");
}
first = false;
bundles.append(symbolicName);
}
assertTrue("Expected to find bundle " + EXPECTED_BUNDLE_NAME + " in " + bundles,
foundCompressBundle);
}
}
| 39.898734 | 100 | 0.678299 |
732a26cf8e19ed1aecf5604f58922f472f8ac550 | 2,956 | /*
* 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.beam.runners.dataflow.worker;
import com.google.api.services.dataflow.model.CounterUpdate;
import java.util.Collections;
import java.util.List;
import org.apache.beam.runners.dataflow.worker.counters.CounterSet;
import org.apache.beam.runners.dataflow.worker.util.common.worker.ExecutionStateTracker;
import org.apache.beam.runners.dataflow.worker.util.common.worker.Operation;
/**
* Class for executing a MapTask via intrinsic Java function invocation in Dataflow.
*
* <p>Also known as the "legacy" or "pre-portability" method
*/
public class IntrinsicMapTaskExecutor extends DataflowMapTaskExecutor {
/**
* @deprecated subclasses should move to composition instead of inheritance, making this private
*/
@Deprecated
protected IntrinsicMapTaskExecutor(
List<Operation> operations,
CounterSet counterSet,
ExecutionStateTracker executionStateTracker) {
super(operations, counterSet, executionStateTracker);
}
/**
* Creates a new MapTaskExecutor.
*
* @param operations the operations of the map task, in order of execution
*/
public static IntrinsicMapTaskExecutor forOperations(
List<Operation> operations, ExecutionStateTracker executionStateTracker) {
return new IntrinsicMapTaskExecutor(operations, new CounterSet(), executionStateTracker);
}
/**
* Creates a new MapTaskExecutor with a shared set of counters with its creator.
*
* @param operations the operations of the map task, in order of execution
* @param counters a set of system counters associated with operations, which may get extended
* during execution
*/
public static IntrinsicMapTaskExecutor withSharedCounterSet(
List<Operation> operations,
CounterSet counters,
ExecutionStateTracker executionStateTracker) {
return new IntrinsicMapTaskExecutor(operations, counters, executionStateTracker);
}
/**
* {@inheritDoc}
*
* @return nothing; pre-portability Dataflow extracts Beam metrics via the execution context.
*/
@Override
public Iterable<CounterUpdate> extractMetricUpdates() {
return Collections.emptyList();
}
}
| 36.95 | 98 | 0.757781 |
69d7dfb07cf53cde120c1c759387fa8dd2f311a0 | 1,076 | package com.api.parkingcontrol.dtos.input;
import com.api.parkingcontrol.services.validations.annotations.ParkingSpotInsert;
import lombok.Data;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
@Data
@ParkingSpotInsert
public class ParkingSpotInsertDto {
@NotBlank(message = "parkingSpotNumber não pode ser nullo")
private String parkingSpotNumber;
@NotBlank(message = "licensePlateCar não pode ser nullo")
@Size(max = 7, message = "Máximo de 7 caracteres")
private String licensePlateCar;
@NotBlank(message = "brandCar não pode ser nullo")
private String brandCar;
@NotBlank(message = "modelCar não pode ser nullo")
private String modelCar;
@NotBlank(message = "colorCar não pode ser nullo")
private String colorCar;
@NotBlank(message = "responsibleName não pode ser nullo")
private String responsibleName;
@NotBlank(message = "apartment não pode ser nullo")
private String apartment;
@NotBlank(message = "block não pode ser nullo")
private String block;
}
| 28.315789 | 81 | 0.744424 |
74de4e998ede52f171e11fad2b79ac71c21dc649 | 918 | package com.example.faculty.database.entity.base;
import com.example.faculty.database.entity.Subject;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import lombok.experimental.SuperBuilder;
import javax.persistence.Column;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.MappedSuperclass;
import javax.validation.constraints.NotBlank;
@Data
@MappedSuperclass
@EqualsAndHashCode(callSuper = true)
@SuperBuilder
@NoArgsConstructor
@AllArgsConstructor
public class EventData extends BaseEntity {
@NotBlank
@Column(name = "group_name")
private String group;
@NotBlank
@Column(name = "name")
private String name;
@NotBlank
@Column(name = "auditory")
private String auditory;
@ManyToOne
@JoinColumn(name = "subject_id")
private Subject subject;
}
| 23.538462 | 51 | 0.778867 |
609aa147f6d65da14a1c8f1a1c8bc570d38fa58a | 4,283 | /*
* Copyright 2010 Aalto University, ComNet
* Released under GPLv3. See LICENSE.txt for details.
*/
package gui;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Vector;
import javax.swing.BorderFactory;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
/**
* Control panel for event log
*
*/
public class EventLogControlPanel extends JPanel implements ActionListener {
private static final String TITLE_TEXT = "Event log controls";
private static final String SHOW_TEXT = "show";
private static final String PAUSE_TEXT = "pause";
private static final int PADDING = 5;
private Font smallFont = new Font("sans",Font.PLAIN,11);
private Font headingFont = new Font("sans",Font.BOLD,11);
private Vector<EventLogControl> logControls;
private JCheckBox showAllCheck;
private JCheckBox pauseAllCheck;
private GridBagLayout layout;
private GridBagConstraints c;
/**
* Constructor. Creates a new control panel.
*/
public EventLogControlPanel() {
layout = new GridBagLayout();
c = new GridBagConstraints();
logControls = new Vector<EventLogControl>();
c.ipadx = PADDING;
setLayout(layout);
this.setBorder(BorderFactory.createTitledBorder(
getBorder(), TITLE_TEXT));
c.fill = GridBagConstraints.BOTH;
addLabel(" ");
addLabel(SHOW_TEXT + "");
c.gridwidth = GridBagConstraints.REMAINDER; //end row
addLabel(PAUSE_TEXT);
// create "show/pause on all selections
c.gridwidth = 1;
addLabel("all");
showAllCheck = addCheckBox(true,false);
pauseAllCheck = addCheckBox(false,true);
showAllCheck.addActionListener(this);
pauseAllCheck.addActionListener(this);
this.setMinimumSize(new Dimension(0,0));
}
/**
* Adds a new filter&pause control
* @param name Name of the control
* @param showOn Is "show" initially selected
* @param pauseOn Is "pause" initially selected
* @return Event log control object that can be queried for status
*/
public EventLogControl addControl(String name, boolean showOn,
boolean pauseOn) {
JCheckBox filterCheck;
JCheckBox pauseCheck;
EventLogControl control;
c.gridwidth = 1; // one component/cell
addLabel(name);
filterCheck = addCheckBox(showOn, false);
pauseCheck = addCheckBox(pauseOn, true);
control = new EventLogControl(filterCheck, pauseCheck);
this.logControls.add(control);
return control;
}
/**
* Creates and adds a new checkbox to this panel
* @param selected Is the checkbox initially selected
* @param endOfRow Is the box last in the row in the layout
* @return The created checkbox
*/
private JCheckBox addCheckBox(boolean selected, boolean endOfRow) {
JCheckBox box = new JCheckBox();
box.setSelected(selected);
if (endOfRow) {
c.gridwidth = GridBagConstraints.REMAINDER; // use rest of the line
}
else {
c.gridwidth = 1; // default
}
layout.setConstraints(box, c);
add(box);
return box;
}
/**
* Adds a new filter&pause control with initially "show" checked
* but "pause" unchecked
* @param name Name of the control
* @return Event log control object that can be queried for status
* @see #addControl(String name, boolean showOn, boolean pauseOn)
*/
public EventLogControl addControl(String name) {
return addControl(name, true, false);
}
/**
* Adds a new heading in the control panel. Subsequent addControl
* controls will be under this heading
* @param name The heading text
*/
public void addHeading(String name) {
c.gridwidth = GridBagConstraints.REMAINDER;
addLabel(name).setFont(this.headingFont);
}
private JLabel addLabel(String txt) {
JLabel label = new JLabel(txt);
label.setFont(this.smallFont);
layout.setConstraints(label, c);
add(label);
return label;
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == this.showAllCheck) {
for (EventLogControl elc : logControls) {
elc.setShowEvent(this.showAllCheck.isSelected());
}
}
else if (e.getSource() == this.pauseAllCheck) {
for (EventLogControl elc : logControls) {
elc.setPauseOnEvent(this.pauseAllCheck.isSelected());
}
}
}
}
| 26.76875 | 76 | 0.724726 |
5adee95a8a368178ab0ae34699946a387b337ec5 | 2,143 | package org.knowm.xchange.luno.dto.marketdata;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.Collections;
import java.util.Date;
import java.util.Map;
import java.util.TreeMap;
public class LunoOrderBook {
public final long timestamp;
private final TreeMap<Double, Double> bids = new TreeMap<>((k1, k2) -> -k1.compareTo(k2));
private final TreeMap<Double, Double> asks = new TreeMap<>();
public LunoOrderBook(
@JsonProperty(value = "timestamp", required = true) long timestamp,
@JsonProperty(value = "asks") Order[] asks,
@JsonProperty(value = "bids") Order[] bids) {
this.timestamp = timestamp;
// we merge the orders with the same price together bei adding the volumes
// java8 style:
// this.asks = Stream.of(asks).collect(Collectors.toMap(o -> o.price, o -> o.volume, (v1, v2) ->
// v1.add(v2), () -> new TreeMap<Double, Double>()));
// this.bids = Stream.of(bids).collect(Collectors.toMap(o -> o.price, o -> o.volume, (v1, v2) ->
// v1.add(v2), () -> new TreeMap<Double, Double>((k1, k2) -> -k1.compareTo(k2))));
// without java8:
addOrdersToMap(asks, this.asks);
addOrdersToMap(bids, this.bids);
}
private static void addOrdersToMap(Order[] orders, Map<Double, Double> map) {
for (Order o : orders) {
Double v = map.get(o.price);
map.put(o.price, v == null ? o.volume : o.volume + (v));
}
}
public Date getTimestamp() {
return new Date(timestamp);
}
public Map<Double, Double> getBids() {
return Collections.unmodifiableMap(bids);
}
public Map<Double, Double> getAsks() {
return Collections.unmodifiableMap(asks);
}
@Override
public String toString() {
return "LunoOrderBook [timestamp=" + getTimestamp() + ", bids=" + bids + ", asks=" + asks + "]";
}
public static class Order {
public final Double price;
public final Double volume;
public Order(
@JsonProperty(value = "price", required = true) Double price,
@JsonProperty(value = "volume", required = true) Double volume) {
this.price = price;
this.volume = volume;
}
}
}
| 31.057971 | 100 | 0.646757 |
f97429141a4524cc456280cb491c25d52eb69892 | 320 | package com.maxith.postDownload.service;
/**
* post下载数据接口service
* Description:
* Copyright: Maxith
* Date: 2016年8月16日
* Time: 下午3:44:20
* @author Maxith
* @version 1.0
*/
public interface IPostDownloadService {
/**
* 创建文件字节数组
* @param param
* @return
*/
public byte[] createFileByte(Object param);
}
| 16 | 44 | 0.68125 |
1b4fc1311678c159bcf8bee9aad7ed7f48ba83a7 | 2,028 | /*
* Copyright (c) 2011, Paul Merlin. 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 org.qipki.testsupport;
import java.io.File;
import java.io.IOException;
import org.codeartisans.java.toolbox.Strings;
import org.qi4j.library.fileconfig.FileConfigurationOverride;
public class QiPkiTestSupport
{
public static File ensureTestDirectory( String subdir )
throws IOException
{
File testDir = new File( "target/" + System.getProperty( "test" ) );
if ( !Strings.isEmpty( subdir ) ) {
testDir = new File( testDir, subdir );
}
if ( !testDir.exists() ) {
if ( !testDir.mkdirs() ) {
throw new IOException( "Unable to create directory: " + testDir );
}
}
return testDir;
}
public static File ensureTestDirectory()
throws IOException
{
return ensureTestDirectory( null );
}
public static FileConfigurationOverride fileConfigTestOverride( String testCodeName )
{
return new FileConfigurationOverride().withConfiguration( new File( "target/" + testCodeName + "-qi4j-configuration" ) ).
withData( new File( "target/" + testCodeName + "-qi4j-data" ) ).
withCache( new File( "target/" + testCodeName + "-qi4j-cache" ) ).
withTemporary( new File( "target/" + testCodeName + "-qi4j-temporary" ) ).
withLog( new File( "target/" + testCodeName + "-qi4j-log" ) );
}
}
| 36.872727 | 129 | 0.649901 |
46f29234aa8e6e245976419a043a84b4bf390eeb | 4,611 | /******************************************************************************
* Copyright AllSeen Alliance. All rights reserved.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
******************************************************************************/
package org.allseen.timeservice.sample.server.logic;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;
import org.allseen.timeservice.Date;
import org.allseen.timeservice.DateTime;
import org.allseen.timeservice.Time;
/**
* Singleton to manage time offsets. Manages notifications of {@link TimeChangeListener} Utilities to convert from {@link DateTime} to {@link Calendar} and vice versa
*
*/
public class TimeOffsetManager {
/**
* stores the time difference between the system time and the server time.
*/
private long timeDifference = 0;
/**
* List of TimeChangeListener registered.
*/
private final List<TimeChangeListener> timeChangeListenerList = new ArrayList<TimeChangeListener>();
private static final TimeOffsetManager instance = new TimeOffsetManager();
private TimeOffsetManager() {
}
public static TimeOffsetManager getInstance() {
return instance;
}
public synchronized void setTimeDifference(long diff) {
timeDifference = diff;
for (TimeChangeListener timeChangeListener : timeChangeListenerList) {
timeChangeListener.timeHasChanged(timeDifference);
}
}
public synchronized long getTimeDifference() {
return timeDifference;
}
public synchronized void registerTimeChangeListener(TimeChangeListener listener) {
if (!timeChangeListenerList.contains(listener)) {
timeChangeListenerList.add(listener);
}
}
public synchronized void unRegisterTimeChangeListener(TimeChangeListener listener) {
if (timeChangeListenerList.contains(listener)) {
timeChangeListenerList.remove(listener);
}
}
public SimpleDateFormat getDateAndTimeDisplayFormat() {
return new SimpleDateFormat("HH:mm:ss dd/MM/yyyy",Locale.US);
}
public SimpleDateFormat getTimeDisplayFormat() {
return new SimpleDateFormat("HH:mm:ss",Locale.US);
}
public Calendar getCurrentServerTime() {
Calendar c = Calendar.getInstance();
c.setTimeInMillis(c.getTimeInMillis() - timeDifference);
return c;
}
public Calendar convertDateTimeToCalendar(DateTime dt) {
Calendar newCalendar = Calendar.getInstance();
newCalendar.set(Calendar.HOUR_OF_DAY, dt.getTime().getHour());
newCalendar.set(Calendar.MINUTE, dt.getTime().getMinute());
newCalendar.set(Calendar.SECOND, dt.getTime().getSeconds());
newCalendar.set(Calendar.MILLISECOND, dt.getTime().getMilliseconds());
newCalendar.set(Calendar.MONTH, dt.getDate().getMonth() - 1);
newCalendar.set(Calendar.YEAR, dt.getDate().getYear());
newCalendar.set(Calendar.DAY_OF_MONTH, dt.getDate().getDay());
return newCalendar;
}
public DateTime convertCalendarToDateTime(Calendar currentCalendar) {
Time ts = new org.allseen.timeservice.Time((byte) currentCalendar.get(Calendar.HOUR_OF_DAY),
(byte) currentCalendar.get(Calendar.MINUTE),
(byte) currentCalendar.get(Calendar.SECOND),
(short) currentCalendar.get(Calendar.MILLISECOND));
Date ds = new Date((short) currentCalendar.get(Calendar.YEAR),
(byte) (currentCalendar.get(Calendar.MONTH) + 1),
(byte) currentCalendar.get(Calendar.DAY_OF_MONTH));
return new DateTime(ds, ts, (short) 0);
}
}
| 38.425 | 166 | 0.658209 |
1ec6fa5691fae2f8cc2eaa2c935a77e81ed78071 | 510 | /*
* 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 com.mycompany.part01_03.onceuponatime;
/**
*
* @author Harrison
*/
public class OnceUponATime {
public static void main(String[] args) {
// Write your program here
System.out.println("Once upon a time");
System.out.println("there was");
System.out.println("a program");
}
}
| 22.173913 | 80 | 0.672549 |
aa0f7d27030b4fa0aefa8e9ee4a9f689c350cf19 | 6,547 | /*
* Copyright 2016-2019 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.cloud.stream.reactive;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.junit.Test;
import reactor.core.publisher.Flux;
import reactor.test.StepVerifier;
import org.springframework.cloud.stream.converter.TestApplicationJsonMessageMarshallingConverter;
import org.springframework.core.MethodParameter;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.messaging.Message;
import org.springframework.messaging.converter.CompositeMessageConverter;
import org.springframework.messaging.converter.MappingJackson2MessageConverter;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.util.ReflectionUtils;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Marius Bogoevici
* @author Ryan Dunckel
*/
public class MessageChannelToInputFluxParameterAdapterTests {
@Test
public void testWrapperFluxSupportsMultipleSubscriptions() throws Exception {
List<String> results = Collections.synchronizedList(new ArrayList<>());
CountDownLatch latch = new CountDownLatch(4);
final MessageChannelToInputFluxParameterAdapter messageChannelToInputFluxParameterAdapter;
messageChannelToInputFluxParameterAdapter = new MessageChannelToInputFluxParameterAdapter(
new CompositeMessageConverter(
Collections.singleton(new MappingJackson2MessageConverter())));
final Method processMethod = ReflectionUtils.findMethod(
MessageChannelToInputFluxParameterAdapterTests.class, "process",
Flux.class);
final DirectChannel adaptedChannel = new DirectChannel();
@SuppressWarnings("unchecked")
final Flux<Message<?>> adapterFlux = (Flux<Message<?>>) messageChannelToInputFluxParameterAdapter
.adapt(adaptedChannel, new MethodParameter(processMethod, 0));
String uuid1 = UUID.randomUUID().toString();
String uuid2 = UUID.randomUUID().toString();
adapterFlux.map(m -> m.getPayload() + uuid1).subscribe(s -> {
results.add(s);
latch.countDown();
});
adapterFlux.map(m -> m.getPayload() + uuid2).subscribe(s -> {
results.add(s);
latch.countDown();
});
adaptedChannel.send(MessageBuilder.withPayload("A").build());
adaptedChannel.send(MessageBuilder.withPayload("B").build());
assertThat(latch.await(5000, TimeUnit.MILLISECONDS)).isTrue();
assertThat(results).containsExactlyInAnyOrder("A" + uuid1, "B" + uuid1,
"A" + uuid2, "B" + uuid2);
}
@Test
public void testAdapterConvertsUsingConversionHint() {
CompositeMessageConverter messageConverter = new CompositeMessageConverter(
Collections
.singleton(new TestApplicationJsonMessageMarshallingConverter()));
MessageChannelToInputFluxParameterAdapter adapter = new MessageChannelToInputFluxParameterAdapter(
messageConverter);
Method processMethod = ReflectionUtils.findMethod(
MessageChannelToInputFluxParameterAdapterTests.class, "processNestedGenericFlux",
Flux.class);
DirectChannel adaptedChannel = new DirectChannel();
@SuppressWarnings("unchecked")
Flux<FirstLevelWrapper<SecondLevelWrapper<String>>> adapterFlux = (Flux<FirstLevelWrapper<SecondLevelWrapper<String>>>) adapter
.adapt(adaptedChannel, new MethodParameter(processMethod, 0));
SecondLevelWrapper<String> expected2 = new SecondLevelWrapper<>();
expected2.setName("name");
expected2.setData("data");
FirstLevelWrapper<SecondLevelWrapper<String>> expected1 = new FirstLevelWrapper<>();
expected1.setId(1);
expected1.setData(expected2);
StepVerifier.create(adapterFlux).then(() -> {
adaptedChannel.send(MessageBuilder.withPayload(
"{ \"id\": 1, \"data\": { \"name\": \"name\", \"data\": \"data\" } }")
.build());
}).expectNext(expected1).thenCancel().verify();
}
public void process(Flux<Message<?>> message) {
// do nothing - we just reference this method from the test
}
public void processNestedGenericFlux(Flux<FirstLevelWrapper<SecondLevelWrapper<String>>> items) {
// do nothing - we just reference this method from the test
}
static class FirstLevelWrapper<T> {
private long id;
private T data;
long getId() {
return id;
}
void setId(long id) {
this.id = id;
}
T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
@Override
public int hashCode() {
return Objects.hash(data, id);
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof FirstLevelWrapper)) {
return false;
}
@SuppressWarnings("unchecked")
FirstLevelWrapper<T> other = (FirstLevelWrapper<T>) obj;
return Objects.equals(data, other.data) && id == other.id;
}
@Override
public String toString() {
return "FirstLevelWrapper [id=" + id + ", data=" + data + "]";
}
}
static class SecondLevelWrapper<T> {
private String name;
private T data;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
@Override
public int hashCode() {
return Objects.hash(data, name);
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof SecondLevelWrapper)) {
return false;
}
@SuppressWarnings("unchecked")
SecondLevelWrapper<T> other = (SecondLevelWrapper<T>) obj;
return Objects.equals(data, other.data) && Objects.equals(name, other.name);
}
@Override
public String toString() {
return "SecondLevelWrapper [name=" + name + ", data=" + data + "]";
}
}
}
| 27.978632 | 129 | 0.730716 |
f872db16474af33792335f9549d0ddfd060a3195 | 50,903 | /*
*
* Copyright (c) Microsoft. All rights reserved.
* Licensed under the MIT license. See LICENSE file in the project root for full license information.
*
*/
package com.microsoft.azure.sdk.iot.provisioning.device.internal.task;
import com.microsoft.azure.sdk.iot.provisioning.device.internal.ProvisioningDeviceClientConfig;
import com.microsoft.azure.sdk.iot.provisioning.device.internal.contract.ProvisioningDeviceClientContract;
import com.microsoft.azure.sdk.iot.provisioning.device.internal.contract.ResponseCallback;
import com.microsoft.azure.sdk.iot.provisioning.device.internal.contract.UrlPathBuilder;
import com.microsoft.azure.sdk.iot.provisioning.device.internal.exceptions.*;
import com.microsoft.azure.sdk.iot.provisioning.device.internal.parser.DeviceRegistrationParser;
import com.microsoft.azure.sdk.iot.provisioning.device.internal.parser.ProvisioningErrorParser;
import com.microsoft.azure.sdk.iot.provisioning.device.internal.parser.RegistrationOperationStatusParser;
import com.microsoft.azure.sdk.iot.provisioning.device.internal.parser.TpmRegistrationResultParser;
import com.microsoft.azure.sdk.iot.provisioning.device.internal.task.Authorization;
import com.microsoft.azure.sdk.iot.provisioning.device.internal.task.RegisterTask;
import com.microsoft.azure.sdk.iot.provisioning.device.internal.task.RequestData;
import com.microsoft.azure.sdk.iot.provisioning.device.internal.task.ResponseData;
import com.microsoft.azure.sdk.iot.provisioning.security.SecurityProvider;
import com.microsoft.azure.sdk.iot.provisioning.security.SecurityProviderSymmetricKey;
import com.microsoft.azure.sdk.iot.provisioning.security.SecurityProviderTpm;
import com.microsoft.azure.sdk.iot.provisioning.security.SecurityProviderX509;
import mockit.*;
import mockit.integration.junit4.JMockit;
import org.junit.Test;
import org.junit.runner.RunWith;
import javax.net.ssl.SSLContext;
import java.net.MalformedURLException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import static com.microsoft.azure.sdk.iot.provisioning.device.internal.task.ContractState.DPS_REGISTRATION_RECEIVED;
import static com.microsoft.azure.sdk.iot.provisioning.device.internal.task.ContractState.DPS_REGISTRATION_UNKNOWN;
import static org.junit.Assert.assertNotNull;
/*
Unit Test for Register Task
Coverage : 88% Method, 92% Line (private classes are non testable)
*/
@RunWith(JMockit.class)
public class RegisterTaskTest
{
private static final String TEST_REGISTRATION_ID = "testRegistrationId";
private static final String TEST_EK = "testEK";
private static final String TEST_SRK = "testSRK";
private static final String TEST_AUTH_KEY = "testAuthKey";
@Mocked
SecurityProvider mockedSecurityProvider;
@Mocked
SecurityProviderSymmetricKey mockedSecurityProviderSymmetricKey;
@Mocked
SecurityProviderTpm mockedSecurityProviderTpm;
@Mocked
SecurityProviderX509 mockedDpsSecurityProviderX509;
@Mocked
ProvisioningDeviceClientContract mockedProvisioningDeviceClientContract;
@Mocked
ProvisioningDeviceClientConfig mockedProvisioningDeviceClientConfig;
@Mocked
Authorization mockedAuthorization;
@Mocked
DeviceRegistrationParser mockedDeviceRegistrationParser;
@Mocked
UrlPathBuilder mockedUrlPathBuilder;
@Mocked
URLEncoder mockedUrlEncoder;
@Mocked
TpmRegistrationResultParser mockedTpmRegistrationResultParser;
@Mocked
SSLContext mockedSslContext;
@Mocked
RegistrationOperationStatusParser mockedRegistrationOperationStatusParser;
@Mocked
ResponseCallback mockedResponseCallback;
@Mocked
ResponseData mockedResponseData;
@Mocked
RequestData mockedRequestData;
//Tests_SRS_RegisterTask_25_001: [ Constructor shall save provisioningDeviceClientConfig , securityProvider, provisioningDeviceClientContract and authorization.]
@Test
public void constructorSucceeds() throws ProvisioningDeviceClientException
{
//arrange
//act
RegisterTask registerTask = Deencapsulation.newInstance(RegisterTask.class, mockedProvisioningDeviceClientConfig, mockedSecurityProvider,
mockedProvisioningDeviceClientContract, mockedAuthorization);
//assert
assertNotNull(Deencapsulation.getField(registerTask, "provisioningDeviceClientConfig"));
assertNotNull(Deencapsulation.getField(registerTask, "securityProvider"));
assertNotNull(Deencapsulation.getField(registerTask, "provisioningDeviceClientContract"));
assertNotNull(Deencapsulation.getField(registerTask, "authorization"));
assertNotNull(Deencapsulation.getField(registerTask, "responseCallback"));
}
//Tests_SRS_RegisterTask_25_002: [ Constructor throw ProvisioningDeviceClientException if provisioningDeviceClientConfig , securityProvider, authorization or provisioningDeviceClientContract is null.]
@Test (expected = ProvisioningDeviceClientException.class)
public void constructorThrowsOnNullConfig() throws ProvisioningDeviceClientException
{
//arrange
//act
RegisterTask registerTask = Deencapsulation.newInstance(RegisterTask.class, new Class[]{ProvisioningDeviceClientConfig.class,
SecurityProvider.class, ProvisioningDeviceClientContract.class,
Authorization.class},
null, mockedSecurityProvider,
mockedProvisioningDeviceClientContract, mockedAuthorization);
//assert
}
@Test (expected = ProvisioningDeviceClientException.class)
public void constructorThrowsOnNullSecurityProvider() throws ProvisioningDeviceClientException
{
//arrange
//act
RegisterTask registerTask = Deencapsulation.newInstance(RegisterTask.class, new Class[]{ProvisioningDeviceClientConfig.class,
SecurityProvider.class, ProvisioningDeviceClientContract.class,
Authorization.class},
mockedProvisioningDeviceClientConfig, null,
mockedProvisioningDeviceClientContract, mockedAuthorization);
//assert
}
@Test (expected = ProvisioningDeviceClientException.class)
public void constructorThrowsOnNullContract() throws ProvisioningDeviceClientException
{
//act
RegisterTask registerTask = Deencapsulation.newInstance(RegisterTask.class, new Class[]{ProvisioningDeviceClientConfig.class,
SecurityProvider.class, ProvisioningDeviceClientContract.class,
Authorization.class},
mockedProvisioningDeviceClientConfig, mockedSecurityProvider,
null, mockedAuthorization);
}
@Test (expected = ProvisioningDeviceClientException.class)
public void constructorThrowsOnNullAuthorization() throws ProvisioningDeviceClientException
{
//act
RegisterTask registerTask = Deencapsulation.newInstance(RegisterTask.class, new Class[]{ProvisioningDeviceClientConfig.class,
SecurityProvider.class, ProvisioningDeviceClientContract.class,
Authorization.class},
mockedProvisioningDeviceClientConfig, mockedSecurityProvider,
mockedProvisioningDeviceClientContract, null);
}
//Tests_SRS_RegisterTask_25_006: [ If the provided security client is for X509 then, this method shall trigger authenticateWithProvisioningService on the contract API and wait for response and return it. ]
@Test
public void authenticateWithX509Succeeds() throws Exception
{
//arrange
RegisterTask registerTask = Deencapsulation.newInstance(RegisterTask.class, mockedProvisioningDeviceClientConfig,
mockedDpsSecurityProviderX509, mockedProvisioningDeviceClientContract,
mockedAuthorization);
new NonStrictExpectations()
{
{
mockedDpsSecurityProviderX509.getRegistrationId();
result = TEST_REGISTRATION_ID;
mockedDeviceRegistrationParser.toJson();
result = "testJson";
mockedDpsSecurityProviderX509.getSSLContext();
result = mockedSslContext;
Deencapsulation.invoke(mockedResponseData, "getResponseData");
result = "NonNullValue".getBytes(StandardCharsets.UTF_8);
Deencapsulation.invoke(mockedResponseData, "getContractState");
result = DPS_REGISTRATION_RECEIVED;
}
};
//act
registerTask.call();
//assert
new Verifications()
{
{
Deencapsulation.invoke(mockedAuthorization, "setSslContext", mockedSslContext);
times = 1;
mockedProvisioningDeviceClientContract.authenticateWithProvisioningService((RequestData) any,
(ResponseCallback)any, any);
times = 1;
}
};
}
@Test (expected = ProvisioningDeviceClientException.class)
public void authenticateWithX509ThrowsOnNonExistentType() throws Exception
{
//arrange
RegisterTask registerTask = Deencapsulation.newInstance(RegisterTask.class, mockedProvisioningDeviceClientConfig,
mockedSecurityProvider, mockedProvisioningDeviceClientContract,
mockedAuthorization);
//act
registerTask.call();
}
//Tests_SRS_RegisterTask_25_003: [ If the provided security client is for X509 then, this method shall throw ProvisioningDeviceClientException if registration id is null. ]
@Test (expected = ProvisioningDeviceClientException.class)
public void authenticateWithX509ThrowsOnNullRegId() throws Exception
{
//arrange
RegisterTask registerTask = Deencapsulation.newInstance(RegisterTask.class, mockedProvisioningDeviceClientConfig,
mockedDpsSecurityProviderX509, mockedProvisioningDeviceClientContract,
mockedAuthorization);
new NonStrictExpectations()
{
{
mockedDpsSecurityProviderX509.getRegistrationId();
result = null;
}
};
//act
registerTask.call();
}
//Tests_SRS_RegisterTask_25_004: [ If the provided security client is for X509 then, this method shall save the SSL context to Authorization if it is not null and throw ProvisioningDeviceClientException otherwise. ]
@Test (expected = ProvisioningDeviceSecurityException.class)
public void authenticateWithX509ThrowsOnNullSSLContext() throws Exception
{
//arrange
RegisterTask registerTask = Deencapsulation.newInstance(RegisterTask.class, mockedProvisioningDeviceClientConfig,
mockedDpsSecurityProviderX509, mockedProvisioningDeviceClientContract,
mockedAuthorization);
new NonStrictExpectations()
{
{
mockedDpsSecurityProviderX509.getRegistrationId();
result = TEST_REGISTRATION_ID;
mockedDeviceRegistrationParser.toJson();
result = "testJson";
mockedDpsSecurityProviderX509.getSSLContext();
result = null;
}
};
//act
registerTask.call();
}
//Tests_SRS_RegisterTask_25_007: [ If the provided security client is for X509 then, this method shall throw ProvisioningDeviceClientException if null response is received. ]
@Test (expected = ProvisioningDeviceTransportException.class)
public void authenticateWithX509ThrowsOnAuthenticateWithDPSFail() throws Exception
{
//arrange
RegisterTask registerTask = Deencapsulation.newInstance(RegisterTask.class, mockedProvisioningDeviceClientConfig,
mockedDpsSecurityProviderX509, mockedProvisioningDeviceClientContract,
mockedAuthorization);
new NonStrictExpectations()
{
{
mockedDpsSecurityProviderX509.getRegistrationId();
result = TEST_REGISTRATION_ID;
mockedDeviceRegistrationParser.toJson();
result = "testJson";
mockedDpsSecurityProviderX509.getSSLContext();
result = mockedSslContext;
mockedProvisioningDeviceClientContract.authenticateWithProvisioningService((RequestData) any,
(ResponseCallback)any, any);
result = new ProvisioningDeviceTransportException("test transport exception");
}
};
//act
registerTask.call();
}
@Test (expected = ProvisioningDeviceClientException.class)
public void authenticateWithX509ThrowsOnThreadInterruptedException() throws Exception
{
//arrange
RegisterTask registerTask = Deencapsulation.newInstance(RegisterTask.class, mockedProvisioningDeviceClientConfig,
mockedDpsSecurityProviderX509, mockedProvisioningDeviceClientContract,
mockedAuthorization);
new NonStrictExpectations()
{
{
mockedDpsSecurityProviderX509.getRegistrationId();
result = TEST_REGISTRATION_ID;
mockedDeviceRegistrationParser.toJson();
result = "testJson";
mockedDpsSecurityProviderX509.getSSLContext();
result = new InterruptedException();
}
};
//act
registerTask.call();
}
@Test
public void authenticateWithSasTokenTpmSucceeds() throws Exception
{
//arrange
RegisterTask registerTask = Deencapsulation.newInstance(RegisterTask.class, mockedProvisioningDeviceClientConfig,
mockedSecurityProviderTpm, mockedProvisioningDeviceClientContract,
mockedAuthorization);
new NonStrictExpectations()
{
{
mockedSecurityProviderTpm.getRegistrationId();
result = TEST_REGISTRATION_ID;
mockedSecurityProviderTpm.getEndorsementKey();
result = TEST_EK.getBytes(StandardCharsets.UTF_8);
mockedSecurityProviderTpm.getStorageRootKey();
result = TEST_SRK.getBytes(StandardCharsets.UTF_8);
mockedDeviceRegistrationParser.toJson();
result = "testJson";
mockedSecurityProviderTpm.getSSLContext();
result = mockedSslContext;
Deencapsulation.invoke(mockedResponseData, "getResponseData");
result = "NonNullValue".getBytes(StandardCharsets.UTF_8);
Deencapsulation.invoke(mockedResponseData, "getContractState");
result = DPS_REGISTRATION_RECEIVED;
mockedTpmRegistrationResultParser.getAuthenticationKey();
result = TEST_AUTH_KEY;
mockedUrlPathBuilder.generateSasTokenUrl(TEST_REGISTRATION_ID);
result = "testUrl";
mockedSecurityProviderTpm.signWithIdentity((byte[])any);
result = "testToken".getBytes(StandardCharsets.UTF_8);
}
};
//act
registerTask.call();
//assert
new Verifications()
{
{
Deencapsulation.invoke(mockedAuthorization, "setSslContext", mockedSslContext);
times = 1;
Deencapsulation.invoke(mockedAuthorization, "setSasToken", anyString);
times = 1;
mockedProvisioningDeviceClientContract.requestNonceForTPM((RequestData) any,
(ResponseCallback)any, any);
times = 1;
mockedSecurityProviderTpm.activateIdentityKey((byte[])any);
times = 1;
mockedProvisioningDeviceClientContract.authenticateWithProvisioningService((RequestData) any,
(ResponseCallback)any, any);
times = 1;
}
};
}
@Test
public void authenticateWithSasTokenSymKeySucceeds() throws Exception
{
//arrange
RegisterTask registerTask = Deencapsulation.newInstance(RegisterTask.class, mockedProvisioningDeviceClientConfig,
mockedSecurityProviderSymmetricKey, mockedProvisioningDeviceClientContract,
mockedAuthorization);
new NonStrictExpectations()
{
{
mockedSecurityProviderSymmetricKey.getRegistrationId();
result = TEST_REGISTRATION_ID;
mockedDeviceRegistrationParser.toJson();
result = "testJson";
mockedSecurityProviderSymmetricKey.getSSLContext();
result = mockedSslContext;
Deencapsulation.invoke(mockedResponseData, "getResponseData");
result = "NonNullValue".getBytes(StandardCharsets.UTF_8);
Deencapsulation.invoke(mockedResponseData, "getContractState");
result = DPS_REGISTRATION_RECEIVED;
mockedTpmRegistrationResultParser.getAuthenticationKey();
result = TEST_AUTH_KEY;
mockedUrlPathBuilder.generateSasTokenUrl(TEST_REGISTRATION_ID);
result = "testUrl";
mockedSecurityProviderSymmetricKey.HMACSignData((byte[])any, (byte[]) any);
result = "testToken".getBytes(StandardCharsets.UTF_8);
}
};
//act
registerTask.call();
//assert
new Verifications()
{
{
Deencapsulation.invoke(mockedAuthorization, "setSslContext", mockedSslContext);
times = 1;
Deencapsulation.invoke(mockedAuthorization, "setSasToken", anyString);
times = 1;
mockedProvisioningDeviceClientContract.requestNonceForTPM((RequestData) any,
(ResponseCallback)any, any);
times = 0;
mockedSecurityProviderTpm.activateIdentityKey((byte[])any);
times = 0;
mockedProvisioningDeviceClientContract.authenticateWithProvisioningService((RequestData) any,
(ResponseCallback)any, any);
times = 1;
}
};
}
//Tests_SRS_RegisterTask_25_008: [ If the provided security client is for Key then, this method shall throw ProvisioningDeviceClientException if registration id or endorsement key or storage root key are null. ]
@Test (expected = ProvisioningDeviceClientException.class)
public void authenticateWithSasTokenNonceThrowsOnNullRegId() throws Exception
{
//arrange
RegisterTask registerTask = Deencapsulation.newInstance(RegisterTask.class, mockedProvisioningDeviceClientConfig,
mockedSecurityProviderTpm, mockedProvisioningDeviceClientContract,
mockedAuthorization);
new NonStrictExpectations()
{
{
mockedSecurityProviderTpm.getRegistrationId();
result = null;
}
};
//act
registerTask.call();
}
@Test (expected = ProvisioningDeviceSecurityException.class)
public void authenticateWithSasTokenNonceThrowsOnNullEk() throws Exception
{
//arrange
RegisterTask registerTask = Deencapsulation.newInstance(RegisterTask.class, mockedProvisioningDeviceClientConfig,
mockedSecurityProviderTpm, mockedProvisioningDeviceClientContract,
mockedAuthorization);
new NonStrictExpectations()
{
{
mockedSecurityProviderTpm.getRegistrationId();
result = TEST_REGISTRATION_ID;
mockedSecurityProviderTpm.getEndorsementKey();
result = null;
}
};
//act
registerTask.call();
}
@Test (expected = ProvisioningDeviceSecurityException.class)
public void authenticateWithSasTokenNonceThrowsOnNullSRK() throws Exception
{
//arrange
RegisterTask registerTask = Deencapsulation.newInstance(RegisterTask.class, mockedProvisioningDeviceClientConfig,
mockedSecurityProviderTpm, mockedProvisioningDeviceClientContract,
mockedAuthorization);
new NonStrictExpectations()
{
{
mockedSecurityProviderTpm.getRegistrationId();
result = TEST_REGISTRATION_ID;
mockedSecurityProviderTpm.getEndorsementKey();
result = TEST_EK.getBytes(StandardCharsets.UTF_8);
mockedSecurityProviderTpm.getStorageRootKey();
result = null;
}
};
//act
registerTask.call();
}
//Tests_SRS_RegisterTask_25_009: [ If the provided security client is for Key then, this method shall save the SSL context to Authorization if it is not null and throw ProvisioningDeviceClientException otherwise. ]
@Test (expected = ProvisioningDeviceSecurityException.class)
public void authenticateWithSasTokenNonceThrowsOnNullSSLContext() throws Exception
{
//arrange
RegisterTask registerTask = Deencapsulation.newInstance(RegisterTask.class, mockedProvisioningDeviceClientConfig,
mockedSecurityProviderTpm, mockedProvisioningDeviceClientContract,
mockedAuthorization);
new NonStrictExpectations()
{
{
mockedSecurityProviderTpm.getRegistrationId();
result = TEST_REGISTRATION_ID;
mockedSecurityProviderTpm.getEndorsementKey();
result = TEST_EK.getBytes(StandardCharsets.UTF_8);
mockedSecurityProviderTpm.getStorageRootKey();
result = TEST_SRK.getBytes(StandardCharsets.UTF_8);
mockedDeviceRegistrationParser.toJson();
result = "testJson";
mockedSecurityProviderTpm.getSSLContext();
result = null;
}
};
//act
registerTask.call();
}
//Tests_SRS_RegisterTask_25_011: [ If the provided security client is for Key then, this method shall trigger requestNonceForTPM on the contract API and wait for Authentication Key and decode it from Base64. Also this method shall pass the exception back to the user if it fails. ]
@Test (expected = ProvisioningDeviceHubException.class)
public void authenticateWithSasTokenNonceThrowsOnRequestNonceFail() throws Exception
{
//arrange
RegisterTask registerTask = Deencapsulation.newInstance(RegisterTask.class, mockedProvisioningDeviceClientConfig,
mockedSecurityProviderTpm, mockedProvisioningDeviceClientContract,
mockedAuthorization);
new NonStrictExpectations()
{
{
mockedSecurityProviderTpm.getRegistrationId();
result = TEST_REGISTRATION_ID;
mockedSecurityProviderTpm.getEndorsementKey();
result = TEST_EK.getBytes(StandardCharsets.UTF_8);
mockedSecurityProviderTpm.getStorageRootKey();
result = TEST_SRK.getBytes(StandardCharsets.UTF_8);
mockedDeviceRegistrationParser.toJson();
result = "testJson";
mockedSecurityProviderTpm.getSSLContext();
result = mockedSslContext;
mockedProvisioningDeviceClientContract.requestNonceForTPM((RequestData) any,
(ResponseCallback)any, any);
result = new ProvisioningDeviceHubException("test exception");
}
};
//act
registerTask.call();
}
@Test (expected = ProvisioningDeviceClientException.class)
public void authenticateWithSasTokenThrowsOnThreadInterruptedException() throws Exception
{
//arrange
RegisterTask registerTask = Deencapsulation.newInstance(RegisterTask.class, mockedProvisioningDeviceClientConfig,
mockedSecurityProviderTpm, mockedProvisioningDeviceClientContract,
mockedAuthorization);
new NonStrictExpectations()
{
{
mockedSecurityProviderTpm.getRegistrationId();
result = TEST_REGISTRATION_ID;
mockedSecurityProviderTpm.getEndorsementKey();
result = TEST_EK.getBytes(StandardCharsets.UTF_8);
mockedSecurityProviderTpm.getStorageRootKey();
result = TEST_SRK.getBytes(StandardCharsets.UTF_8);
mockedDeviceRegistrationParser.toJson();
result = "testJson";
mockedSecurityProviderTpm.getSSLContext();
result = new InterruptedException();
}
};
//act
registerTask.call();
}
//Tests_SRS_RegisterTask_25_013: [ If the provided security client is for Key then, this method shall throw ProvisioningDeviceClientException if Authentication Key received is null. ]
@Test (expected = ProvisioningDeviceClientAuthenticationException.class)
public void authenticateWithSasTokenThrowsOnNullAuthKey() throws Exception
{
//arrange
RegisterTask registerTask = Deencapsulation.newInstance(RegisterTask.class, mockedProvisioningDeviceClientConfig,
mockedSecurityProviderTpm, mockedProvisioningDeviceClientContract,
mockedAuthorization);
new NonStrictExpectations()
{
{
mockedSecurityProviderTpm.getRegistrationId();
result = TEST_REGISTRATION_ID;
mockedSecurityProviderTpm.getEndorsementKey();
result = TEST_EK.getBytes(StandardCharsets.UTF_8);
mockedSecurityProviderTpm.getStorageRootKey();
result = TEST_SRK.getBytes(StandardCharsets.UTF_8);
mockedDeviceRegistrationParser.toJson();
result = "testJson";
mockedSecurityProviderTpm.getSSLContext();
result = mockedSslContext;
Deencapsulation.invoke(mockedResponseData, "getContractState");
result = DPS_REGISTRATION_RECEIVED;
Deencapsulation.invoke(mockedResponseData, "getResponseData");
result = null;
}
};
//act
registerTask.call();
}
//Tests_SRS_RegisterTask_25_018: [ If the provided security client is for Key then, this method shall import the Base 64 encoded Authentication Key into the HSM using the security client and pass the exception to the user on failure. ]
@Test (expected = ProvisioningDeviceClientException.class)
public void authenticateWithSasTokenThrowsImportKeyFailure() throws Exception
{
//arrange
RegisterTask registerTask = Deencapsulation.newInstance(RegisterTask.class, mockedProvisioningDeviceClientConfig,
mockedSecurityProviderTpm, mockedProvisioningDeviceClientContract,
mockedAuthorization);
new NonStrictExpectations()
{
{
mockedSecurityProviderTpm.getRegistrationId();
result = TEST_REGISTRATION_ID;
mockedSecurityProviderTpm.getEndorsementKey();
result = TEST_EK.getBytes(StandardCharsets.UTF_8);
mockedSecurityProviderTpm.getStorageRootKey();
result = TEST_SRK.getBytes(StandardCharsets.UTF_8);
mockedDeviceRegistrationParser.toJson();
result = "testJson";
mockedSecurityProviderTpm.getSSLContext();
result = mockedSslContext;
Deencapsulation.invoke(mockedResponseData, "getResponseData");
result = "NonNullValue".getBytes(StandardCharsets.UTF_8);
Deencapsulation.invoke(mockedResponseData, "getContractState");
result = DPS_REGISTRATION_RECEIVED;
mockedTpmRegistrationResultParser.getAuthenticationKey();
result = TEST_AUTH_KEY;
mockedSecurityProviderTpm.activateIdentityKey((byte[])any);
result = new ProvisioningDeviceClientException("test exception");
}
};
//act
registerTask.call();
}
/*SRS_RegisterTask_25_014: [ If the provided security client is for Key then, this method shall construct SasToken by doing the following
1. Build a tokenScope of format <scopeid>/registrations/<registrationId>
2. Sign the HSM with the string of format <tokenScope>/n<expiryTime> and receive a token
3. Encode the token to Base64 format and UrlEncode it to generate the signature. ]*/
@Test (expected = ProvisioningDeviceClientException.class)
public void authenticateWithSasTokenThrowsConstructTokenFailure() throws Exception
{
//arrange
RegisterTask registerTask = Deencapsulation.newInstance(RegisterTask.class, mockedProvisioningDeviceClientConfig,
mockedSecurityProviderTpm, mockedProvisioningDeviceClientContract,
mockedAuthorization);
new NonStrictExpectations()
{
{
mockedSecurityProviderTpm.getRegistrationId();
result = TEST_REGISTRATION_ID;
mockedSecurityProviderTpm.getEndorsementKey();
result = TEST_EK.getBytes(StandardCharsets.UTF_8);
mockedSecurityProviderTpm.getStorageRootKey();
result = TEST_SRK.getBytes(StandardCharsets.UTF_8);
mockedDeviceRegistrationParser.toJson();
result = "testJson";
mockedSecurityProviderTpm.getSSLContext();
result = mockedSslContext;
Deencapsulation.invoke(mockedResponseData, "getResponseData");
result = "NonNullValue".getBytes(StandardCharsets.UTF_8);
Deencapsulation.invoke(mockedResponseData, "getContractState");
result = DPS_REGISTRATION_RECEIVED;
mockedTpmRegistrationResultParser.getAuthenticationKey();
result = TEST_AUTH_KEY;
mockedUrlPathBuilder.generateSasTokenUrl(TEST_REGISTRATION_ID);
result = new MalformedURLException("test exception");
}
};
//act
registerTask.call();
}
@Test (expected = ProvisioningDeviceClientException.class)
public void authenticateWithSasTokenThrowsUrlBuilderReturnsNull() throws Exception
{
//arrange
RegisterTask registerTask = Deencapsulation.newInstance(RegisterTask.class, mockedProvisioningDeviceClientConfig,
mockedSecurityProviderTpm, mockedProvisioningDeviceClientContract,
mockedAuthorization);
new NonStrictExpectations()
{
{
mockedSecurityProviderTpm.getRegistrationId();
result = TEST_REGISTRATION_ID;
mockedSecurityProviderTpm.getEndorsementKey();
result = TEST_EK.getBytes(StandardCharsets.UTF_8);
mockedSecurityProviderTpm.getStorageRootKey();
result = TEST_SRK.getBytes(StandardCharsets.UTF_8);
mockedDeviceRegistrationParser.toJson();
result = "testJson";
mockedSecurityProviderTpm.getSSLContext();
result = mockedSslContext;
Deencapsulation.invoke(mockedResponseData, "getResponseData");
result = "NonNullValue".getBytes(StandardCharsets.UTF_8);
Deencapsulation.invoke(mockedResponseData, "getContractState");
result = DPS_REGISTRATION_RECEIVED;
mockedTpmRegistrationResultParser.getAuthenticationKey();
result = TEST_AUTH_KEY;
mockedUrlPathBuilder.generateSasTokenUrl(TEST_REGISTRATION_ID);
result = null;
}
};
//act
registerTask.call();
}
@Test (expected = ProvisioningDeviceClientException.class)
public void authenticateWithSasTokenThrowsUrlBuilderReturnsEmpty() throws Exception
{
//arrange
RegisterTask registerTask = Deencapsulation.newInstance(RegisterTask.class, mockedProvisioningDeviceClientConfig,
mockedSecurityProviderTpm, mockedProvisioningDeviceClientContract,
mockedAuthorization);
new NonStrictExpectations()
{
{
mockedSecurityProviderTpm.getRegistrationId();
result = TEST_REGISTRATION_ID;
mockedSecurityProviderTpm.getEndorsementKey();
result = TEST_EK.getBytes(StandardCharsets.UTF_8);
mockedSecurityProviderTpm.getStorageRootKey();
result = TEST_SRK.getBytes(StandardCharsets.UTF_8);
mockedDeviceRegistrationParser.toJson();
result = "testJson";
mockedSecurityProviderTpm.getSSLContext();
result = mockedSslContext;
Deencapsulation.invoke(mockedResponseData, "getResponseData");
result = "NonNullValue".getBytes(StandardCharsets.UTF_8);
Deencapsulation.invoke(mockedResponseData, "getContractState");
result = DPS_REGISTRATION_RECEIVED;
mockedTpmRegistrationResultParser.getAuthenticationKey();
result = TEST_AUTH_KEY;
mockedUrlPathBuilder.generateSasTokenUrl(TEST_REGISTRATION_ID);
result = "";
}
};
//act
registerTask.call();
}
@Test (expected = ProvisioningDeviceClientException.class)
public void authenticateWithSasTokenTpmThrowsConstructTokenSignDataFailure() throws Exception
{
//arrange
RegisterTask registerTask = Deencapsulation.newInstance(RegisterTask.class, mockedProvisioningDeviceClientConfig,
mockedSecurityProviderTpm, mockedProvisioningDeviceClientContract,
mockedAuthorization);
new NonStrictExpectations()
{
{
mockedSecurityProviderTpm.getRegistrationId();
result = TEST_REGISTRATION_ID;
mockedSecurityProviderTpm.getEndorsementKey();
result = TEST_EK.getBytes(StandardCharsets.UTF_8);
mockedSecurityProviderTpm.getStorageRootKey();
result = TEST_SRK.getBytes(StandardCharsets.UTF_8);
mockedDeviceRegistrationParser.toJson();
result = "testJson";
mockedSecurityProviderTpm.getSSLContext();
result = mockedSslContext;
Deencapsulation.invoke(mockedResponseData, "getResponseData");
result = "NonNullValue".getBytes(StandardCharsets.UTF_8);
Deencapsulation.invoke(mockedResponseData, "getContractState");
result = DPS_REGISTRATION_RECEIVED;
mockedTpmRegistrationResultParser.getAuthenticationKey();
result = TEST_AUTH_KEY;
mockedUrlPathBuilder.generateSasTokenUrl(TEST_REGISTRATION_ID);
result = "testUrl";
mockedSecurityProviderTpm.signWithIdentity((byte[])any);
result = new ProvisioningDeviceClientException("test Exception");
}
};
//act
registerTask.call();
}
@Test (expected = ProvisioningDeviceClientException.class)
public void authenticateWithSasTokenSymKeyThrowsConstructTokenSignDataFailure() throws Exception
{
//arrange
RegisterTask registerTask = Deencapsulation.newInstance(RegisterTask.class, mockedProvisioningDeviceClientConfig,
mockedSecurityProviderSymmetricKey, mockedProvisioningDeviceClientContract,
mockedAuthorization);
new NonStrictExpectations()
{
{
mockedSecurityProviderSymmetricKey.getRegistrationId();
result = TEST_REGISTRATION_ID;
mockedDeviceRegistrationParser.toJson();
result = "testJson";
mockedSecurityProviderSymmetricKey.getSSLContext();
result = mockedSslContext;
Deencapsulation.invoke(mockedResponseData, "getResponseData");
result = "NonNullValue".getBytes(StandardCharsets.UTF_8);
Deencapsulation.invoke(mockedResponseData, "getContractState");
result = DPS_REGISTRATION_RECEIVED;
mockedTpmRegistrationResultParser.getAuthenticationKey();
result = TEST_AUTH_KEY;
mockedUrlPathBuilder.generateSasTokenUrl(TEST_REGISTRATION_ID);
result = "testUrl";
mockedSecurityProviderSymmetricKey.HMACSignData((byte[])any, (byte[]) any);
result = new ProvisioningDeviceClientException("test Exception");
}
};
//act
registerTask.call();
}
@Test (expected = ProvisioningDeviceClientException.class)
public void authenticateWithSasTokenThrowsConstructTokenSignDataReturnsNull() throws Exception
{
//arrange
RegisterTask registerTask = Deencapsulation.newInstance(RegisterTask.class, mockedProvisioningDeviceClientConfig,
mockedSecurityProviderTpm, mockedProvisioningDeviceClientContract,
mockedAuthorization);
new NonStrictExpectations()
{
{
mockedSecurityProviderTpm.getRegistrationId();
result = TEST_REGISTRATION_ID;
mockedSecurityProviderTpm.getEndorsementKey();
result = TEST_EK.getBytes(StandardCharsets.UTF_8);
mockedSecurityProviderTpm.getStorageRootKey();
result = TEST_SRK.getBytes(StandardCharsets.UTF_8);
mockedDeviceRegistrationParser.toJson();
result = "testJson";
mockedSecurityProviderTpm.getSSLContext();
result = mockedSslContext;
Deencapsulation.invoke(mockedResponseData, "getResponseData");
result = "NonNullValue".getBytes(StandardCharsets.UTF_8);
Deencapsulation.invoke(mockedResponseData, "getContractState");
result = DPS_REGISTRATION_RECEIVED;
mockedTpmRegistrationResultParser.getAuthenticationKey();
result = TEST_AUTH_KEY;
mockedUrlPathBuilder.generateSasTokenUrl(TEST_REGISTRATION_ID);
result = "testUrl";
mockedSecurityProviderTpm.signWithIdentity((byte[])any);
result = null;
}
};
//act
registerTask.call();
}
@Test (expected = ProvisioningDeviceClientException.class)
public void authenticateWithSasTokenThrowsConstructTokenSignDataReturnsEmpty() throws Exception
{
//arrange
RegisterTask registerTask = Deencapsulation.newInstance(RegisterTask.class, mockedProvisioningDeviceClientConfig,
mockedSecurityProviderTpm, mockedProvisioningDeviceClientContract,
mockedAuthorization);
new NonStrictExpectations()
{
{
mockedSecurityProviderTpm.getRegistrationId();
result = TEST_REGISTRATION_ID;
mockedSecurityProviderTpm.getEndorsementKey();
result = TEST_EK.getBytes(StandardCharsets.UTF_8);
mockedSecurityProviderTpm.getStorageRootKey();
result = TEST_SRK.getBytes(StandardCharsets.UTF_8);
mockedDeviceRegistrationParser.toJson();
result = "testJson";
mockedSecurityProviderTpm.getSSLContext();
result = mockedSslContext;
Deencapsulation.invoke(mockedResponseData, "getResponseData");
result = "NonNullValue".getBytes(StandardCharsets.UTF_8);
Deencapsulation.invoke(mockedResponseData, "getContractState");
result = DPS_REGISTRATION_RECEIVED;
mockedTpmRegistrationResultParser.getAuthenticationKey();
result = TEST_AUTH_KEY;
mockedUrlPathBuilder.generateSasTokenUrl(TEST_REGISTRATION_ID);
result = "testUrl";
mockedSecurityProviderTpm.signWithIdentity((byte[])any);
result = "".getBytes(StandardCharsets.UTF_8);
}
};
//act
registerTask.call();
}
//Tests_SRS_RegisterTask_25_016: [ If the provided security client is for Key then, this method shall trigger authenticateWithProvisioningService on the contract API using the sasToken generated and wait for response and return it. ]
@Test (expected = ProvisioningDeviceTransportException.class)
public void authenticateWithSasTokenThrowsOnAuthenticateWithDPSFail() throws Exception
{
//arrange
RegisterTask registerTask = Deencapsulation.newInstance(RegisterTask.class, mockedProvisioningDeviceClientConfig,
mockedSecurityProviderTpm, mockedProvisioningDeviceClientContract,
mockedAuthorization);
new NonStrictExpectations()
{
{
mockedSecurityProviderTpm.getRegistrationId();
result = TEST_REGISTRATION_ID;
mockedSecurityProviderTpm.getEndorsementKey();
result = TEST_EK.getBytes(StandardCharsets.UTF_8);
mockedSecurityProviderTpm.getStorageRootKey();
result = TEST_SRK.getBytes(StandardCharsets.UTF_8);
mockedDeviceRegistrationParser.toJson();
result = "testJson";
mockedSecurityProviderTpm.getSSLContext();
result = mockedSslContext;
Deencapsulation.invoke(mockedResponseData, "getResponseData");
result = "NonNullValue".getBytes(StandardCharsets.UTF_8);
Deencapsulation.invoke(mockedResponseData, "getContractState");
result = DPS_REGISTRATION_RECEIVED;
mockedTpmRegistrationResultParser.getAuthenticationKey();
result = TEST_AUTH_KEY;
mockedUrlPathBuilder.generateSasTokenUrl(TEST_REGISTRATION_ID);
result = "testUrl";
mockedSecurityProviderTpm.signWithIdentity((byte[])any);
result = "testToken".getBytes(StandardCharsets.UTF_8);
mockedProvisioningDeviceClientContract.authenticateWithProvisioningService((RequestData) any,
(ResponseCallback)any, any);
result = new ProvisioningDeviceTransportException("test transport exception");
}
};
//act
registerTask.call();
}
//Tests_SRS_StatusTask_34_010: [ If the response data cannot be parsed into a RegistrationOperationStatusParser,
// this function shall parse it into a ProvisioningErrorParser and throw a ProvisioningDeviceClientException with the parsed message. ]
@Test (expected = ProvisioningDeviceClientException.class)
public void authenticateWithX509FallsBackToErrorParserIfRegistrationOperationStatusParsingFails(@Mocked final ProvisioningErrorParser mockedProvisioningErrorParser) throws Exception
{
//arrange
RegisterTask registerTask = Deencapsulation.newInstance(RegisterTask.class, mockedProvisioningDeviceClientConfig,
mockedDpsSecurityProviderX509, mockedProvisioningDeviceClientContract,
mockedAuthorization);
new NonStrictExpectations()
{
{
mockedDpsSecurityProviderX509.getRegistrationId();
result = TEST_REGISTRATION_ID;
mockedDeviceRegistrationParser.toJson();
result = "testJson";
mockedDpsSecurityProviderX509.getSSLContext();
result = mockedSslContext;
Deencapsulation.invoke(mockedResponseData, "getResponseData");
result = "NonNullValue".getBytes(StandardCharsets.UTF_8);
Deencapsulation.invoke(mockedResponseData, "getContractState");
result = DPS_REGISTRATION_RECEIVED;
RegistrationOperationStatusParser.createFromJson("NonNullValue");
result = new IllegalArgumentException("this is an error");
ProvisioningErrorParser.createFromJson("NonNullValue");
result = mockedProvisioningErrorParser;
mockedProvisioningErrorParser.getExceptionMessage();
result = "some new exception";
}
};
//act
registerTask.call();
//assert
new Verifications()
{
{
ProvisioningErrorParser.createFromJson("NonNullValue");
times = 1;
mockedProvisioningErrorParser.getExceptionMessage();
times = 1;
}
};
}
@Test (expected = ProvisioningDeviceClientException.class)
public void authenticateWithSasTokenFallsBackToErrorParserIfRegistrationOperationStatusParsingFails(@Mocked final ProvisioningErrorParser mockedProvisioningErrorParser) throws Exception
{
//arrange
RegisterTask registerTask = Deencapsulation.newInstance(RegisterTask.class, mockedProvisioningDeviceClientConfig,
mockedSecurityProviderTpm, mockedProvisioningDeviceClientContract,
mockedAuthorization);
new NonStrictExpectations()
{
{
mockedSecurityProviderTpm.getRegistrationId();
result = TEST_REGISTRATION_ID;
mockedSecurityProviderTpm.getEndorsementKey();
result = TEST_EK.getBytes(StandardCharsets.UTF_8);
mockedSecurityProviderTpm.getStorageRootKey();
result = TEST_SRK.getBytes(StandardCharsets.UTF_8);
mockedDeviceRegistrationParser.toJson();
result = "testJson";
mockedSecurityProviderTpm.getSSLContext();
result = mockedSslContext;
Deencapsulation.invoke(mockedResponseData, "getResponseData");
result = "NonNullValue".getBytes(StandardCharsets.UTF_8);
Deencapsulation.invoke(mockedResponseData, "getContractState");
result = DPS_REGISTRATION_RECEIVED;
RegistrationOperationStatusParser.createFromJson("NonNullValue");
result = new IllegalArgumentException("this is an error");
ProvisioningErrorParser.createFromJson("NonNullValue");
result = mockedProvisioningErrorParser;
mockedProvisioningErrorParser.getExceptionMessage();
result = "some new exception";
}
};
//act
registerTask.call();
//assert
new Verifications()
{
{
ProvisioningErrorParser.createFromJson("NonNullValue");
times = 1;
mockedProvisioningErrorParser.getExceptionMessage();
times = 1;
}
};
}
}
| 49.807241 | 285 | 0.617115 |
36ddc15f6c46c71f879c672ee9d1c608bb66d421 | 277 | package io.sentry.protocol;
import org.jetbrains.annotations.ApiStatus;
@ApiStatus.Internal
public final class MeasurementValue {
@SuppressWarnings("UnusedVariable")
private final float value;
public MeasurementValue(final float value) {
this.value = value;
}
}
| 19.785714 | 46 | 0.768953 |
4c1b09088834704c99b1234fba41fbdfa3a9860c | 8,949 | package game;
import game.pieces.Type;
import java.util.ArrayList;
//import java.util.Random;
/**
* Authors: Serge Anan && Abideen Hamisu
*/
public class GameHelper{
/**
* Function that creates an arrayList holding all legal moves
* @param game game variable that stores the piece positions, accessed with game class getPiece()
* @return ArrayList of all legal moves of the current board
*/
public static ArrayList<Move> allValidMoves(Game game){
ArrayList<Move> moves = new ArrayList<Move>();
Cord from;
ArrayList<Cord> current;
for(int i = 0; i < game.getRankSize(); i++)
for(int j = 0; j < game.getFileSize(); j++){
from = new Cord(i, j);
current = game.getPiece(from).validMoves(game, from);
for(Cord to : current)
moves.add(new Move(from, to));
}
return moves;
}
/**
* Creates a list of all legal moves
*
* @param game game variable that stores the piece positions, accessed with game class getPiece()
* @return ArrayList of all legal moves of the current board
*/
public static ArrayList<Move> allLegalMoves(Game game){
ArrayList<Move> moves = new ArrayList<Move>();
Cord from;
ArrayList<Cord> current;
for(int i = 0; i < game.getRankSize(); i++)
for(int j = 0; j < game.getFileSize(); j++){
from = new Cord(i, j);
current = game.getPiece(from).legalMoves(game, from);
for(Cord to : current)
moves.add(new Move(from, to));
}
return moves;
}
/**
* if Constant.WHITE return "white" otherwise
* @param white a boolean for the current turn
* @return Returns "white" if current turn is true and "black" if it is false
*/
public static String turnToString(boolean white){return white? "white" : "black";}
/**
* checks if a king of a color is alive in a game
* @param game game variable that sotres the piece positions
* @param color the current player whose turn it is
* @return True if the King is still alive, false otherwise
*/
public static boolean kingAlive(Game game, boolean color){
for(int i = 0; i < game.getRankSize(); i++)
for(int j = 0; j < game.getFileSize(); j++)
if(game.getBoard()[i][j].getType() == Type.King && game.getBoard()[i][j].getColor() == color)
return true;
return false;
}
/**
* the color of the coordinate
* @param at the square being tested
* @return whether the square is black or white
*/
public static boolean cordColor(Cord at){
return (at.rank() + at.file()) % 2 == 0? Constant.BLACK : Constant.WHITE;
}
/**
* Checks if a piece is in check. 0 for not in mate, 1 for checkmate, 2 for stale mate
* @param game the object that stores the position of the pieces
* @return the state of the king's positin (Check, stalemate, or not in mate/stalemate)
*/
public static int inMate(Game game){
ArrayList<Move> moves = allLegalMoves(game);
if(moves.size() == 0){
if(inCheck(game)) return Constant.CHECK;
else return Constant.STALE;
}
return Constant.NO;
}
/**
* checks if the move is sucide/puting it self in check
* @param game the game object that stores the state of the board
* @param move the move to be checked
* @return True if the King is moving into check, false otherwise
*/
public static boolean sucide(Game game, Move move){
Game tempGame = new Game(game);
tempGame.simpleMove(move);
tempGame.changeTurn();
ArrayList<Move> moves = GameHelper.allValidMoves(tempGame);
for(Move nextMove : moves){
if(tempGame.getPiece(nextMove.to()).getType() == Type.King)
return true;
}
return false;
}
/**
* checks if the game is in check
* @param game the game object that stores the state of the board
* @return true if the King is in check, false otherwise
*/
public static boolean inCheck(Game game){
Game tempGame = new Game(game);
tempGame.changeTurn();
ArrayList<Move> moves = allValidMoves(tempGame);
for(Move nextMove : moves){
if(tempGame.getPiece(nextMove.to()).getType() == Type.King)
return true;
}
return false;
}
/**
* Checks a pieces move rules to decide if a move is allowed.
* @param from Take a coordinate value that the piece starts on
* @param to Takes a coordinate value that the piece wants to move to
* @return Invokes the .is_legal() method from the piece, which contains the pieces
* move rules that are evaluated based on the x,y coordinates that the piece is on and can move to.
* .is_legal() returns true if the piece is allowed to make that move, false otherwise
*/
public static boolean legalMove(Game game, Move move){//!!!!!!!!!!!!someone make isLegal() throw errors for the human plaer class to catch. betther then this way
if(game.getEnd() != Constant.ONGOING){
System.out.println("Error: Game's Over");
return false;
}
if(game.getPiece(move.from()).getType() == Type.Empty){
System.out.println("Error: Can't move an Empty Piece.");
return false;
}
if(game.getPiece(move.from()).getColor() != game.getWhiteTurn()){
System.out.println("Error: It's not " + turnToString(!game.getWhiteTurn()) + "'s turn.");
return false;
}
if(game.getPiece(move.to()).getType() != Type.Empty && game.getPiece(move.from()).getColor() == game.getPiece(move.to()).getColor()){
System.out.println("Error: Friendly Fire"); //example. white cant capture white, white can only capture black
return false;
}
if(sucide(game, move)){
System.out.println("Error: Can't put self in check.");
return false;
}
return game.getPiece(move.from()).isLegal(game, move);
}
/**
* checks if any board state has occured three times (Threefold Repetition)
* records boardstate as FEN and stores it into an arraylist
* iterates through the arraylist and checks if there are three identiacal board states
* @param game the game object that stores the location of the pieces
* @return true if a board state has occured more then three times, else false
*/
public static boolean threefoldRepetition(Game game){return repetition(game) >= 3;}
public static int repetition(Game game){
ArrayList<String> history = game.getHistory();
String current = GameInfo.FENBoard(game);
int repetition = 0;
for(String position: history)
if(position.equals(current))
repetition++;
return repetition;
}
/**
* if a piece is to the left of a king, used for casteling
* @param game the game object that stores the location of the pieces
* @param at The position to be checked
* @return true if a piece is left of the King, false otherwise
*/
public static boolean leftOfKing(Game game, Cord at){
for(int i = at.file() + 1; i < game.getFileSize(); i++)
if(game.getPiece(new Cord(at.rank(), i)).getType() == Type.King)
return true;
return false;
}
/**
* if a piece is to the right of a king, used for casteling
* @param game the game object that stores the location of the pieces
* @param at The position to be checked
* @return true if a piece is left of the King, false otherwise
*/
public static boolean rightOfKing(Game game, Cord at){
for(int i = at.file() - 1; i >=0; i--)
if(game.getPiece(new Cord(at.rank(), i)).getType() == Type.King)
return true;
return false;
}
public static boolean FENFormat(String FEN){
if(FEN.length() < 10) return false;
return true;
}
/**
* Used to re-arrange the pieces for a Fischer random game
* @return a string of the new Fischer random setup
*/
public static String newFischerRandom(){
String original = "RNBQKANR";
ArrayList<Character> characters = new ArrayList<Character>();
for(char c:original.toCharArray()){
characters.add(c);
}
String shuffle = "";
while(characters.size()!=0){
int randPicker = (int)(Math.random() * characters.size());
shuffle = shuffle + characters.remove(randPicker);
}
return shuffle.toLowerCase() + "/pppppppp/8/8/8/8/PPPPPPPP/" + shuffle + " w - - 0 1";
}
} | 38.407725 | 165 | 0.601073 |
c665cb93c0df91c1ce9c43d867066d2b12079502 | 2,531 | package me.aleiv.core.blocks.listeners;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.block.BlockPhysicsEvent;
import org.bukkit.event.block.NotePlayEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import me.aleiv.core.blocks.CoreBlocks;
public class BlockerListener implements Listener{
CoreBlocks instance;
public BlockerListener(CoreBlocks instance){
this.instance = instance;
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onBlockPhysics(BlockPhysicsEvent e) {
var block = e.getBlock();
var aboveBlock = block.getLocation().add(0, 1, 0).getBlock();
if (aboveBlock.getType() == Material.NOTE_BLOCK) {
updateAndCheck(block.getLocation());
e.setCancelled(true);
}
if (block.getType() == Material.NOTE_BLOCK)
e.setCancelled(true);
if (block.getType().toString().toLowerCase().contains("sign"))
return;
block.getState().update(true, false);
}
public void updateAndCheck(Location loc) {
Block b = loc.add(0, 1, 0).getBlock();
if (b.getType() == Material.NOTE_BLOCK)
b.getState().update(true, true);
Location nextBlock = b.getLocation().add(0, 1, 0);
if (nextBlock.getBlock().getType() == Material.NOTE_BLOCK)
updateAndCheck(b.getLocation());
}
@EventHandler
public void onClick(PlayerInteractEvent e) {
var hand = e.getHand();
var player = e.getPlayer();
var equip = player.getEquipment();
if(hand == null) return;
var item = equip.getItem(hand);
var block = e.getClickedBlock();
var action = e.getAction();
if (action == Action.RIGHT_CLICK_BLOCK && block != null && block.getType() == Material.NOTE_BLOCK) {
if(player.isSneaking() && item.getType() != Material.AIR) return;
e.setCancelled(true);
var tool = instance.getNoteBlockManager();
if (tool.isDefaultNoteBlock(block)) {
//TODO: vanilla noteblock
//player.sendMessage("VANILLA BLOCK");
}
}
}
@EventHandler
public void onNote(NotePlayEvent e) {
e.setCancelled(true);
}
}
| 30.493976 | 108 | 0.627815 |
bcf39b6008a975d9866fa71ba64b98cafa25a068 | 237 |
package com.roomstogo.rtgorder.dto;
import lombok.Data;
@Data
public class Contact {
private String firstName;
private String lastName;
private String email;
private String phone;
private String altPhone;
}
| 14.8125 | 35 | 0.708861 |
ff8d48aebb220e00f56d78be984347854f798915 | 603 | package ir.asparsa.hobbytaste.core.observer;
import rx.Observable;
import rx.subjects.PublishSubject;
import rx.subjects.SerializedSubject;
import rx.subjects.Subject;
import javax.inject.Inject;
import javax.inject.Singleton;
/**
* @author hadi
* @since 7/5/2016 AD
*/
@Singleton
public class RxBusManager {
@Inject
public RxBusManager() {
}
private final Subject<Object, Object> mBus = new SerializedSubject<>(PublishSubject.create());
public void send(Object o) {
mBus.onNext(o);
}
public Observable<Object> toObservable() {
return mBus;
}
}
| 18.84375 | 98 | 0.698176 |
8496cfa1573fde05db9b8a3434bb7f5bb09c0075 | 2,480 | //
// Decompiled by Procyon v0.5.36
//
package org.mudebug.prapr.reloc.commons.collections.map;
import java.io.ObjectInputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.Map;
import java.io.Serializable;
public class IdentityMap extends AbstractHashedMap implements Serializable, Cloneable
{
private static final long serialVersionUID = 2028493495224302329L;
public IdentityMap() {
super(16, 0.75f, 12);
}
public IdentityMap(final int initialCapacity) {
super(initialCapacity);
}
public IdentityMap(final int initialCapacity, final float loadFactor) {
super(initialCapacity, loadFactor);
}
public IdentityMap(final Map map) {
super(map);
}
protected int hash(final Object key) {
return System.identityHashCode(key);
}
protected boolean isEqualKey(final Object key1, final Object key2) {
return key1 == key2;
}
protected boolean isEqualValue(final Object value1, final Object value2) {
return value1 == value2;
}
protected HashEntry createEntry(final HashEntry next, final int hashCode, final Object key, final Object value) {
return new IdentityEntry(next, hashCode, key, value);
}
public Object clone() {
return super.clone();
}
private void writeObject(final ObjectOutputStream out) throws IOException {
out.defaultWriteObject();
this.doWriteObject(out);
}
private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException {
in.defaultReadObject();
this.doReadObject(in);
}
protected static class IdentityEntry extends HashEntry
{
protected IdentityEntry(final HashEntry next, final int hashCode, final Object key, final Object value) {
super(next, hashCode, key, value);
}
public boolean equals(final Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof Map.Entry)) {
return false;
}
final Map.Entry other = (Map.Entry)obj;
return this.getKey() == other.getKey() && this.getValue() == other.getValue();
}
public int hashCode() {
return System.identityHashCode(this.getKey()) ^ System.identityHashCode(this.getValue());
}
}
}
| 29.176471 | 117 | 0.632258 |
a3824af05e4ab32d8de5199dc849209c3dc54fab | 8,262 | /*
* Jexer - Java Text User Interface
*
* The MIT License (MIT)
*
* Copyright (C) 2021 Autumn Lamonte
*
* 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.
*
* @author Autumn Lamonte [AutumnWalksTheLake@gmail.com] ⚧ Trans Liberation Now
* @version 1
*/
package jexer;
import jexer.bits.CellAttributes;
import jexer.bits.StringUtils;
/**
* TRadioGroup is a collection of TRadioButtons with a box and label.
*/
public class TRadioGroup extends TWidget {
// ------------------------------------------------------------------------
// Variables --------------------------------------------------------------
// ------------------------------------------------------------------------
/**
* Label for this radio button group.
*/
private String label;
/**
* Only one of my children can be selected.
*/
private TRadioButton selectedButton = null;
/**
* If true, one of the children MUST be selected. Note package private
* access.
*/
boolean requiresSelection = false;
// ------------------------------------------------------------------------
// Constructors -----------------------------------------------------------
// ------------------------------------------------------------------------
/**
* Public constructor.
*
* @param parent parent widget
* @param x column relative to parent
* @param y row relative to parent
* @param width width of group
* @param label label to display on the group box
*/
public TRadioGroup(final TWidget parent, final int x, final int y,
final int width, final String label) {
// Set parent and window
super(parent, x, y, width, 2);
this.label = label;
}
/**
* Public constructor.
*
* @param parent parent widget
* @param x column relative to parent
* @param y row relative to parent
* @param label label to display on the group box
*/
public TRadioGroup(final TWidget parent, final int x, final int y,
final String label) {
// Set parent and window
super(parent, x, y, StringUtils.width(label) + 4, 2);
this.label = label;
}
// ------------------------------------------------------------------------
// TWidget ----------------------------------------------------------------
// ------------------------------------------------------------------------
/**
* Override TWidget's width: we can only set width at construction time.
*
* @param width new widget width (ignored)
*/
@Override
public void setWidth(final int width) {
// Do nothing
}
/**
* Override TWidget's height: we can only set height at construction
* time.
*
* @param height new widget height (ignored)
*/
@Override
public void setHeight(final int height) {
// Do nothing
}
/**
* Draw a radio button with label.
*/
@Override
public void draw() {
CellAttributes radioGroupColor;
if (isAbsoluteActive()) {
radioGroupColor = getTheme().getColor("tradiogroup.active");
} else {
radioGroupColor = getTheme().getColor("tradiogroup.inactive");
}
drawBox(0, 0, getWidth(), getHeight(), radioGroupColor, radioGroupColor,
3, false);
hLineXY(1, 0, StringUtils.width(label) + 2, ' ', radioGroupColor);
putStringXY(2, 0, label, radioGroupColor);
}
// ------------------------------------------------------------------------
// TRadioGroup ------------------------------------------------------------
// ------------------------------------------------------------------------
/**
* Get the radio button ID that was selected.
*
* @return ID of the selected button, or 0 if no button is selected
*/
public int getSelected() {
if (selectedButton == null) {
return 0;
}
return selectedButton.getId();
}
/**
* Set the new selected radio button. 1-based.
*
* @param id ID of the selected button, or 0 to unselect
*/
public void setSelected(final int id) {
if ((id < 0) || (id > getChildren().size())) {
return;
}
for (TWidget widget: getChildren()) {
((TRadioButton) widget).selected = false;
}
if (id == 0) {
selectedButton = null;
return;
}
assert ((id > 0) && (id <= getChildren().size()));
TRadioButton button = (TRadioButton) (getChildren().get(id - 1));
button.selected = true;
selectedButton = button;
}
/**
* Get the radio button that was selected.
*
* @return the selected button, or null if no button is selected
*/
public TRadioButton getSelectedButton() {
return selectedButton;
}
/**
* Convenience function to add a radio button to this group.
*
* @param label label to display next to (right of) the radiobutton
* @param selected if true, this will be the selected radiobutton
* @return the new radio button
*/
public TRadioButton addRadioButton(final String label,
final boolean selected) {
TRadioButton button = addRadioButton(label);
setSelected(button.id);
return button;
}
/**
* Convenience function to add a radio button to this group.
*
* @param label label to display next to (right of) the radiobutton
* @return the new radio button
*/
public TRadioButton addRadioButton(final String label) {
return new TRadioButton(this, 0, 0, label, 0);
}
/**
* Package private method for RadioButton to add itself to a RadioGroup
* container.
*
* @param button the button to add
*/
void addRadioButton(final TRadioButton button) {
super.setHeight(getChildren().size() + 2);
button.setX(1);
button.setY(getChildren().size());
button.id = getChildren().size();
String label = button.getMnemonic().getRawLabel();
if (StringUtils.width(label) + 4 > getWidth()) {
super.setWidth(StringUtils.width(label) + 7);
}
if (getParent().getLayoutManager() != null) {
getParent().getLayoutManager().resetSize(this);
}
// Default to the first item on the list.
activate(getChildren().get(0));
}
/**
* Get the requires selection flag.
*
* @return true if this radiogroup requires that one of the buttons be
* selected
*/
public boolean getRequiresSelection() {
return requiresSelection;
}
/**
* Set the requires selection flag.
*
* @param requiresSelection if true, then this radiogroup requires that
* one of the buttons be selected
*/
public void setRequiresSelection(final boolean requiresSelection) {
this.requiresSelection = requiresSelection;
if (requiresSelection) {
if ((getChildren().size() > 0) && (selectedButton == null)) {
setSelected(1);
}
}
}
}
| 30.94382 | 80 | 0.54902 |
d11c9d80f781b60639179103cbe4477733ca52b9 | 87,006 | /**
*/
package at.fhj.gaar.androidapp.appDsl;
import org.eclipse.emf.ecore.EAttribute;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EPackage;
import org.eclipse.emf.ecore.EReference;
/**
* <!-- begin-user-doc -->
* The <b>Package</b> for the model.
* It contains accessors for the meta objects to represent
* <ul>
* <li>each class,</li>
* <li>each feature of each class,</li>
* <li>each enum,</li>
* <li>and each data type</li>
* </ul>
* <!-- end-user-doc -->
* @see at.fhj.gaar.androidapp.appDsl.AppDslFactory
* @model kind="package"
* @generated
*/
public interface AppDslPackage extends EPackage
{
/**
* The package name.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
String eNAME = "appDsl";
/**
* The package namespace URI.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
String eNS_URI = "http://www.fhj.at/gaar/androidapp/AppDsl";
/**
* The package namespace name.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
String eNS_PREFIX = "appDsl";
/**
* The singleton instance of the package.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
AppDslPackage eINSTANCE = at.fhj.gaar.androidapp.appDsl.impl.AppDslPackageImpl.init();
/**
* The meta object id for the '{@link at.fhj.gaar.androidapp.appDsl.impl.AndroidAppProjectImpl <em>Android App Project</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see at.fhj.gaar.androidapp.appDsl.impl.AndroidAppProjectImpl
* @see at.fhj.gaar.androidapp.appDsl.impl.AppDslPackageImpl#getAndroidAppProject()
* @generated
*/
int ANDROID_APP_PROJECT = 0;
/**
* The feature id for the '<em><b>Applications</b></em>' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ANDROID_APP_PROJECT__APPLICATIONS = 0;
/**
* The number of structural features of the '<em>Android App Project</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ANDROID_APP_PROJECT_FEATURE_COUNT = 1;
/**
* The meta object id for the '{@link at.fhj.gaar.androidapp.appDsl.impl.ApplicationImpl <em>Application</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see at.fhj.gaar.androidapp.appDsl.impl.ApplicationImpl
* @see at.fhj.gaar.androidapp.appDsl.impl.AppDslPackageImpl#getApplication()
* @generated
*/
int APPLICATION = 1;
/**
* The feature id for the '<em><b>Name</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int APPLICATION__NAME = 0;
/**
* The feature id for the '<em><b>Attributes</b></em>' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int APPLICATION__ATTRIBUTES = 1;
/**
* The number of structural features of the '<em>Application</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int APPLICATION_FEATURE_COUNT = 2;
/**
* The meta object id for the '{@link at.fhj.gaar.androidapp.appDsl.impl.ApplicationAttributeImpl <em>Application Attribute</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see at.fhj.gaar.androidapp.appDsl.impl.ApplicationAttributeImpl
* @see at.fhj.gaar.androidapp.appDsl.impl.AppDslPackageImpl#getApplicationAttribute()
* @generated
*/
int APPLICATION_ATTRIBUTE = 2;
/**
* The number of structural features of the '<em>Application Attribute</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int APPLICATION_ATTRIBUTE_FEATURE_COUNT = 0;
/**
* The meta object id for the '{@link at.fhj.gaar.androidapp.appDsl.impl.ApplicationMinSdkImpl <em>Application Min Sdk</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see at.fhj.gaar.androidapp.appDsl.impl.ApplicationMinSdkImpl
* @see at.fhj.gaar.androidapp.appDsl.impl.AppDslPackageImpl#getApplicationMinSdk()
* @generated
*/
int APPLICATION_MIN_SDK = 3;
/**
* The feature id for the '<em><b>Min Sdk</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int APPLICATION_MIN_SDK__MIN_SDK = APPLICATION_ATTRIBUTE_FEATURE_COUNT + 0;
/**
* The number of structural features of the '<em>Application Min Sdk</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int APPLICATION_MIN_SDK_FEATURE_COUNT = APPLICATION_ATTRIBUTE_FEATURE_COUNT + 1;
/**
* The meta object id for the '{@link at.fhj.gaar.androidapp.appDsl.impl.ApplicationTargetSdkImpl <em>Application Target Sdk</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see at.fhj.gaar.androidapp.appDsl.impl.ApplicationTargetSdkImpl
* @see at.fhj.gaar.androidapp.appDsl.impl.AppDslPackageImpl#getApplicationTargetSdk()
* @generated
*/
int APPLICATION_TARGET_SDK = 4;
/**
* The feature id for the '<em><b>Target Sdk</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int APPLICATION_TARGET_SDK__TARGET_SDK = APPLICATION_ATTRIBUTE_FEATURE_COUNT + 0;
/**
* The number of structural features of the '<em>Application Target Sdk</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int APPLICATION_TARGET_SDK_FEATURE_COUNT = APPLICATION_ATTRIBUTE_FEATURE_COUNT + 1;
/**
* The meta object id for the '{@link at.fhj.gaar.androidapp.appDsl.impl.ApplicationCompileSdkImpl <em>Application Compile Sdk</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see at.fhj.gaar.androidapp.appDsl.impl.ApplicationCompileSdkImpl
* @see at.fhj.gaar.androidapp.appDsl.impl.AppDslPackageImpl#getApplicationCompileSdk()
* @generated
*/
int APPLICATION_COMPILE_SDK = 5;
/**
* The feature id for the '<em><b>Compile Sdk</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int APPLICATION_COMPILE_SDK__COMPILE_SDK = APPLICATION_ATTRIBUTE_FEATURE_COUNT + 0;
/**
* The number of structural features of the '<em>Application Compile Sdk</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int APPLICATION_COMPILE_SDK_FEATURE_COUNT = APPLICATION_ATTRIBUTE_FEATURE_COUNT + 1;
/**
* The meta object id for the '{@link at.fhj.gaar.androidapp.appDsl.impl.ApplicationPermissionListImpl <em>Application Permission List</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see at.fhj.gaar.androidapp.appDsl.impl.ApplicationPermissionListImpl
* @see at.fhj.gaar.androidapp.appDsl.impl.AppDslPackageImpl#getApplicationPermissionList()
* @generated
*/
int APPLICATION_PERMISSION_LIST = 6;
/**
* The feature id for the '<em><b>Permissions</b></em>' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int APPLICATION_PERMISSION_LIST__PERMISSIONS = APPLICATION_ATTRIBUTE_FEATURE_COUNT + 0;
/**
* The number of structural features of the '<em>Application Permission List</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int APPLICATION_PERMISSION_LIST_FEATURE_COUNT = APPLICATION_ATTRIBUTE_FEATURE_COUNT + 1;
/**
* The meta object id for the '{@link at.fhj.gaar.androidapp.appDsl.impl.ApplicationElementListImpl <em>Application Element List</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see at.fhj.gaar.androidapp.appDsl.impl.ApplicationElementListImpl
* @see at.fhj.gaar.androidapp.appDsl.impl.AppDslPackageImpl#getApplicationElementList()
* @generated
*/
int APPLICATION_ELEMENT_LIST = 7;
/**
* The feature id for the '<em><b>Elements</b></em>' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int APPLICATION_ELEMENT_LIST__ELEMENTS = APPLICATION_ATTRIBUTE_FEATURE_COUNT + 0;
/**
* The number of structural features of the '<em>Application Element List</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int APPLICATION_ELEMENT_LIST_FEATURE_COUNT = APPLICATION_ATTRIBUTE_FEATURE_COUNT + 1;
/**
* The meta object id for the '{@link at.fhj.gaar.androidapp.appDsl.impl.ApplicationMainActivityImpl <em>Application Main Activity</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see at.fhj.gaar.androidapp.appDsl.impl.ApplicationMainActivityImpl
* @see at.fhj.gaar.androidapp.appDsl.impl.AppDslPackageImpl#getApplicationMainActivity()
* @generated
*/
int APPLICATION_MAIN_ACTIVITY = 8;
/**
* The feature id for the '<em><b>Launcher Activity</b></em>' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int APPLICATION_MAIN_ACTIVITY__LAUNCHER_ACTIVITY = APPLICATION_ATTRIBUTE_FEATURE_COUNT + 0;
/**
* The number of structural features of the '<em>Application Main Activity</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int APPLICATION_MAIN_ACTIVITY_FEATURE_COUNT = APPLICATION_ATTRIBUTE_FEATURE_COUNT + 1;
/**
* The meta object id for the '{@link at.fhj.gaar.androidapp.appDsl.impl.PermissionImpl <em>Permission</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see at.fhj.gaar.androidapp.appDsl.impl.PermissionImpl
* @see at.fhj.gaar.androidapp.appDsl.impl.AppDslPackageImpl#getPermission()
* @generated
*/
int PERMISSION = 9;
/**
* The feature id for the '<em><b>Name</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int PERMISSION__NAME = 0;
/**
* The number of structural features of the '<em>Permission</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int PERMISSION_FEATURE_COUNT = 1;
/**
* The meta object id for the '{@link at.fhj.gaar.androidapp.appDsl.impl.ApplicationElementImpl <em>Application Element</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see at.fhj.gaar.androidapp.appDsl.impl.ApplicationElementImpl
* @see at.fhj.gaar.androidapp.appDsl.impl.AppDslPackageImpl#getApplicationElement()
* @generated
*/
int APPLICATION_ELEMENT = 10;
/**
* The feature id for the '<em><b>Name</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int APPLICATION_ELEMENT__NAME = 0;
/**
* The number of structural features of the '<em>Application Element</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int APPLICATION_ELEMENT_FEATURE_COUNT = 1;
/**
* The meta object id for the '{@link at.fhj.gaar.androidapp.appDsl.impl.ActivityImpl <em>Activity</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see at.fhj.gaar.androidapp.appDsl.impl.ActivityImpl
* @see at.fhj.gaar.androidapp.appDsl.impl.AppDslPackageImpl#getActivity()
* @generated
*/
int ACTIVITY = 11;
/**
* The feature id for the '<em><b>Name</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ACTIVITY__NAME = APPLICATION_ELEMENT__NAME;
/**
* The feature id for the '<em><b>Attributes</b></em>' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ACTIVITY__ATTRIBUTES = APPLICATION_ELEMENT_FEATURE_COUNT + 0;
/**
* The number of structural features of the '<em>Activity</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ACTIVITY_FEATURE_COUNT = APPLICATION_ELEMENT_FEATURE_COUNT + 1;
/**
* The meta object id for the '{@link at.fhj.gaar.androidapp.appDsl.impl.BroadcastReceiverImpl <em>Broadcast Receiver</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see at.fhj.gaar.androidapp.appDsl.impl.BroadcastReceiverImpl
* @see at.fhj.gaar.androidapp.appDsl.impl.AppDslPackageImpl#getBroadcastReceiver()
* @generated
*/
int BROADCAST_RECEIVER = 12;
/**
* The feature id for the '<em><b>Name</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int BROADCAST_RECEIVER__NAME = APPLICATION_ELEMENT__NAME;
/**
* The feature id for the '<em><b>Attributes</b></em>' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int BROADCAST_RECEIVER__ATTRIBUTES = APPLICATION_ELEMENT_FEATURE_COUNT + 0;
/**
* The number of structural features of the '<em>Broadcast Receiver</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int BROADCAST_RECEIVER_FEATURE_COUNT = APPLICATION_ELEMENT_FEATURE_COUNT + 1;
/**
* The meta object id for the '{@link at.fhj.gaar.androidapp.appDsl.impl.ServiceImpl <em>Service</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see at.fhj.gaar.androidapp.appDsl.impl.ServiceImpl
* @see at.fhj.gaar.androidapp.appDsl.impl.AppDslPackageImpl#getService()
* @generated
*/
int SERVICE = 13;
/**
* The feature id for the '<em><b>Name</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int SERVICE__NAME = APPLICATION_ELEMENT__NAME;
/**
* The feature id for the '<em><b>Attributes</b></em>' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int SERVICE__ATTRIBUTES = APPLICATION_ELEMENT_FEATURE_COUNT + 0;
/**
* The number of structural features of the '<em>Service</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int SERVICE_FEATURE_COUNT = APPLICATION_ELEMENT_FEATURE_COUNT + 1;
/**
* The meta object id for the '{@link at.fhj.gaar.androidapp.appDsl.impl.ActivityAttributeImpl <em>Activity Attribute</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see at.fhj.gaar.androidapp.appDsl.impl.ActivityAttributeImpl
* @see at.fhj.gaar.androidapp.appDsl.impl.AppDslPackageImpl#getActivityAttribute()
* @generated
*/
int ACTIVITY_ATTRIBUTE = 14;
/**
* The number of structural features of the '<em>Activity Attribute</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ACTIVITY_ATTRIBUTE_FEATURE_COUNT = 0;
/**
* The meta object id for the '{@link at.fhj.gaar.androidapp.appDsl.impl.BroadcastReceiverAttributeImpl <em>Broadcast Receiver Attribute</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see at.fhj.gaar.androidapp.appDsl.impl.BroadcastReceiverAttributeImpl
* @see at.fhj.gaar.androidapp.appDsl.impl.AppDslPackageImpl#getBroadcastReceiverAttribute()
* @generated
*/
int BROADCAST_RECEIVER_ATTRIBUTE = 15;
/**
* The number of structural features of the '<em>Broadcast Receiver Attribute</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int BROADCAST_RECEIVER_ATTRIBUTE_FEATURE_COUNT = 0;
/**
* The meta object id for the '{@link at.fhj.gaar.androidapp.appDsl.impl.ServiceAttributeImpl <em>Service Attribute</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see at.fhj.gaar.androidapp.appDsl.impl.ServiceAttributeImpl
* @see at.fhj.gaar.androidapp.appDsl.impl.AppDslPackageImpl#getServiceAttribute()
* @generated
*/
int SERVICE_ATTRIBUTE = 16;
/**
* The number of structural features of the '<em>Service Attribute</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int SERVICE_ATTRIBUTE_FEATURE_COUNT = 0;
/**
* The meta object id for the '{@link at.fhj.gaar.androidapp.appDsl.impl.ElementEnabledAttributeImpl <em>Element Enabled Attribute</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see at.fhj.gaar.androidapp.appDsl.impl.ElementEnabledAttributeImpl
* @see at.fhj.gaar.androidapp.appDsl.impl.AppDslPackageImpl#getElementEnabledAttribute()
* @generated
*/
int ELEMENT_ENABLED_ATTRIBUTE = 17;
/**
* The feature id for the '<em><b>Enabled</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ELEMENT_ENABLED_ATTRIBUTE__ENABLED = ACTIVITY_ATTRIBUTE_FEATURE_COUNT + 0;
/**
* The number of structural features of the '<em>Element Enabled Attribute</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ELEMENT_ENABLED_ATTRIBUTE_FEATURE_COUNT = ACTIVITY_ATTRIBUTE_FEATURE_COUNT + 1;
/**
* The meta object id for the '{@link at.fhj.gaar.androidapp.appDsl.impl.ElementExportedAttributeImpl <em>Element Exported Attribute</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see at.fhj.gaar.androidapp.appDsl.impl.ElementExportedAttributeImpl
* @see at.fhj.gaar.androidapp.appDsl.impl.AppDslPackageImpl#getElementExportedAttribute()
* @generated
*/
int ELEMENT_EXPORTED_ATTRIBUTE = 18;
/**
* The feature id for the '<em><b>Exported</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ELEMENT_EXPORTED_ATTRIBUTE__EXPORTED = ACTIVITY_ATTRIBUTE_FEATURE_COUNT + 0;
/**
* The number of structural features of the '<em>Element Exported Attribute</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ELEMENT_EXPORTED_ATTRIBUTE_FEATURE_COUNT = ACTIVITY_ATTRIBUTE_FEATURE_COUNT + 1;
/**
* The meta object id for the '{@link at.fhj.gaar.androidapp.appDsl.impl.ElementLabelAttributeImpl <em>Element Label Attribute</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see at.fhj.gaar.androidapp.appDsl.impl.ElementLabelAttributeImpl
* @see at.fhj.gaar.androidapp.appDsl.impl.AppDslPackageImpl#getElementLabelAttribute()
* @generated
*/
int ELEMENT_LABEL_ATTRIBUTE = 19;
/**
* The feature id for the '<em><b>Title</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ELEMENT_LABEL_ATTRIBUTE__TITLE = APPLICATION_ATTRIBUTE_FEATURE_COUNT + 0;
/**
* The number of structural features of the '<em>Element Label Attribute</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ELEMENT_LABEL_ATTRIBUTE_FEATURE_COUNT = APPLICATION_ATTRIBUTE_FEATURE_COUNT + 1;
/**
* The meta object id for the '{@link at.fhj.gaar.androidapp.appDsl.impl.ElementIntentListImpl <em>Element Intent List</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see at.fhj.gaar.androidapp.appDsl.impl.ElementIntentListImpl
* @see at.fhj.gaar.androidapp.appDsl.impl.AppDslPackageImpl#getElementIntentList()
* @generated
*/
int ELEMENT_INTENT_LIST = 20;
/**
* The feature id for the '<em><b>Intents</b></em>' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ELEMENT_INTENT_LIST__INTENTS = ACTIVITY_ATTRIBUTE_FEATURE_COUNT + 0;
/**
* The number of structural features of the '<em>Element Intent List</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ELEMENT_INTENT_LIST_FEATURE_COUNT = ACTIVITY_ATTRIBUTE_FEATURE_COUNT + 1;
/**
* The meta object id for the '{@link at.fhj.gaar.androidapp.appDsl.impl.IntentImpl <em>Intent</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see at.fhj.gaar.androidapp.appDsl.impl.IntentImpl
* @see at.fhj.gaar.androidapp.appDsl.impl.AppDslPackageImpl#getIntent()
* @generated
*/
int INTENT = 21;
/**
* The feature id for the '<em><b>Name</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int INTENT__NAME = 0;
/**
* The number of structural features of the '<em>Intent</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int INTENT_FEATURE_COUNT = 1;
/**
* The meta object id for the '{@link at.fhj.gaar.androidapp.appDsl.impl.ActivityParentAttributeImpl <em>Activity Parent Attribute</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see at.fhj.gaar.androidapp.appDsl.impl.ActivityParentAttributeImpl
* @see at.fhj.gaar.androidapp.appDsl.impl.AppDslPackageImpl#getActivityParentAttribute()
* @generated
*/
int ACTIVITY_PARENT_ATTRIBUTE = 22;
/**
* The feature id for the '<em><b>Parent</b></em>' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ACTIVITY_PARENT_ATTRIBUTE__PARENT = ACTIVITY_ATTRIBUTE_FEATURE_COUNT + 0;
/**
* The number of structural features of the '<em>Activity Parent Attribute</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ACTIVITY_PARENT_ATTRIBUTE_FEATURE_COUNT = ACTIVITY_ATTRIBUTE_FEATURE_COUNT + 1;
/**
* The meta object id for the '{@link at.fhj.gaar.androidapp.appDsl.impl.ActivityLayoutAttributeImpl <em>Activity Layout Attribute</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see at.fhj.gaar.androidapp.appDsl.impl.ActivityLayoutAttributeImpl
* @see at.fhj.gaar.androidapp.appDsl.impl.AppDslPackageImpl#getActivityLayoutAttribute()
* @generated
*/
int ACTIVITY_LAYOUT_ATTRIBUTE = 23;
/**
* The feature id for the '<em><b>Layout Elements</b></em>' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ACTIVITY_LAYOUT_ATTRIBUTE__LAYOUT_ELEMENTS = ACTIVITY_ATTRIBUTE_FEATURE_COUNT + 0;
/**
* The number of structural features of the '<em>Activity Layout Attribute</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ACTIVITY_LAYOUT_ATTRIBUTE_FEATURE_COUNT = ACTIVITY_ATTRIBUTE_FEATURE_COUNT + 1;
/**
* The meta object id for the '{@link at.fhj.gaar.androidapp.appDsl.impl.LayoutElementImpl <em>Layout Element</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see at.fhj.gaar.androidapp.appDsl.impl.LayoutElementImpl
* @see at.fhj.gaar.androidapp.appDsl.impl.AppDslPackageImpl#getLayoutElement()
* @generated
*/
int LAYOUT_ELEMENT = 24;
/**
* The number of structural features of the '<em>Layout Element</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int LAYOUT_ELEMENT_FEATURE_COUNT = 0;
/**
* The meta object id for the '{@link at.fhj.gaar.androidapp.appDsl.impl.ButtonImpl <em>Button</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see at.fhj.gaar.androidapp.appDsl.impl.ButtonImpl
* @see at.fhj.gaar.androidapp.appDsl.impl.AppDslPackageImpl#getButton()
* @generated
*/
int BUTTON = 25;
/**
* The feature id for the '<em><b>Name</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int BUTTON__NAME = LAYOUT_ELEMENT_FEATURE_COUNT + 0;
/**
* The feature id for the '<em><b>Attributes</b></em>' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int BUTTON__ATTRIBUTES = LAYOUT_ELEMENT_FEATURE_COUNT + 1;
/**
* The number of structural features of the '<em>Button</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int BUTTON_FEATURE_COUNT = LAYOUT_ELEMENT_FEATURE_COUNT + 2;
/**
* The meta object id for the '{@link at.fhj.gaar.androidapp.appDsl.impl.ButtonAttributeImpl <em>Button Attribute</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see at.fhj.gaar.androidapp.appDsl.impl.ButtonAttributeImpl
* @see at.fhj.gaar.androidapp.appDsl.impl.AppDslPackageImpl#getButtonAttribute()
* @generated
*/
int BUTTON_ATTRIBUTE = 26;
/**
* The number of structural features of the '<em>Button Attribute</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int BUTTON_ATTRIBUTE_FEATURE_COUNT = 0;
/**
* The meta object id for the '{@link at.fhj.gaar.androidapp.appDsl.impl.ButtonLabelAttributeImpl <em>Button Label Attribute</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see at.fhj.gaar.androidapp.appDsl.impl.ButtonLabelAttributeImpl
* @see at.fhj.gaar.androidapp.appDsl.impl.AppDslPackageImpl#getButtonLabelAttribute()
* @generated
*/
int BUTTON_LABEL_ATTRIBUTE = 27;
/**
* The feature id for the '<em><b>Title</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int BUTTON_LABEL_ATTRIBUTE__TITLE = BUTTON_ATTRIBUTE_FEATURE_COUNT + 0;
/**
* The number of structural features of the '<em>Button Label Attribute</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int BUTTON_LABEL_ATTRIBUTE_FEATURE_COUNT = BUTTON_ATTRIBUTE_FEATURE_COUNT + 1;
/**
* The meta object id for the '{@link at.fhj.gaar.androidapp.appDsl.impl.ButtonActionAttributeImpl <em>Button Action Attribute</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see at.fhj.gaar.androidapp.appDsl.impl.ButtonActionAttributeImpl
* @see at.fhj.gaar.androidapp.appDsl.impl.AppDslPackageImpl#getButtonActionAttribute()
* @generated
*/
int BUTTON_ACTION_ATTRIBUTE = 28;
/**
* The feature id for the '<em><b>Action</b></em>' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int BUTTON_ACTION_ATTRIBUTE__ACTION = BUTTON_ATTRIBUTE_FEATURE_COUNT + 0;
/**
* The number of structural features of the '<em>Button Action Attribute</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int BUTTON_ACTION_ATTRIBUTE_FEATURE_COUNT = BUTTON_ATTRIBUTE_FEATURE_COUNT + 1;
/**
* The meta object id for the '{@link at.fhj.gaar.androidapp.appDsl.impl.SpacerImpl <em>Spacer</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see at.fhj.gaar.androidapp.appDsl.impl.SpacerImpl
* @see at.fhj.gaar.androidapp.appDsl.impl.AppDslPackageImpl#getSpacer()
* @generated
*/
int SPACER = 29;
/**
* The number of structural features of the '<em>Spacer</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int SPACER_FEATURE_COUNT = LAYOUT_ELEMENT_FEATURE_COUNT + 0;
/**
* The meta object id for the '{@link at.fhj.gaar.androidapp.appDsl.impl.TextImpl <em>Text</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see at.fhj.gaar.androidapp.appDsl.impl.TextImpl
* @see at.fhj.gaar.androidapp.appDsl.impl.AppDslPackageImpl#getText()
* @generated
*/
int TEXT = 30;
/**
* The feature id for the '<em><b>Text</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int TEXT__TEXT = LAYOUT_ELEMENT_FEATURE_COUNT + 0;
/**
* The number of structural features of the '<em>Text</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int TEXT_FEATURE_COUNT = LAYOUT_ELEMENT_FEATURE_COUNT + 1;
/**
* The meta object id for the '{@link at.fhj.gaar.androidapp.appDsl.impl.LayoutElementClickActionImpl <em>Layout Element Click Action</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see at.fhj.gaar.androidapp.appDsl.impl.LayoutElementClickActionImpl
* @see at.fhj.gaar.androidapp.appDsl.impl.AppDslPackageImpl#getLayoutElementClickAction()
* @generated
*/
int LAYOUT_ELEMENT_CLICK_ACTION = 31;
/**
* The number of structural features of the '<em>Layout Element Click Action</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int LAYOUT_ELEMENT_CLICK_ACTION_FEATURE_COUNT = 0;
/**
* The meta object id for the '{@link at.fhj.gaar.androidapp.appDsl.impl.BroadcastReceiverActionAttributeImpl <em>Broadcast Receiver Action Attribute</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see at.fhj.gaar.androidapp.appDsl.impl.BroadcastReceiverActionAttributeImpl
* @see at.fhj.gaar.androidapp.appDsl.impl.AppDslPackageImpl#getBroadcastReceiverActionAttribute()
* @generated
*/
int BROADCAST_RECEIVER_ACTION_ATTRIBUTE = 32;
/**
* The feature id for the '<em><b>Action</b></em>' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int BROADCAST_RECEIVER_ACTION_ATTRIBUTE__ACTION = BROADCAST_RECEIVER_ATTRIBUTE_FEATURE_COUNT + 0;
/**
* The number of structural features of the '<em>Broadcast Receiver Action Attribute</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int BROADCAST_RECEIVER_ACTION_ATTRIBUTE_FEATURE_COUNT = BROADCAST_RECEIVER_ATTRIBUTE_FEATURE_COUNT + 1;
/**
* The meta object id for the '{@link at.fhj.gaar.androidapp.appDsl.impl.BroadcastReceiverActionImpl <em>Broadcast Receiver Action</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see at.fhj.gaar.androidapp.appDsl.impl.BroadcastReceiverActionImpl
* @see at.fhj.gaar.androidapp.appDsl.impl.AppDslPackageImpl#getBroadcastReceiverAction()
* @generated
*/
int BROADCAST_RECEIVER_ACTION = 33;
/**
* The number of structural features of the '<em>Broadcast Receiver Action</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int BROADCAST_RECEIVER_ACTION_FEATURE_COUNT = 0;
/**
* The meta object id for the '{@link at.fhj.gaar.androidapp.appDsl.impl.ActionShowToastImpl <em>Action Show Toast</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see at.fhj.gaar.androidapp.appDsl.impl.ActionShowToastImpl
* @see at.fhj.gaar.androidapp.appDsl.impl.AppDslPackageImpl#getActionShowToast()
* @generated
*/
int ACTION_SHOW_TOAST = 34;
/**
* The feature id for the '<em><b>Toast Text</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ACTION_SHOW_TOAST__TOAST_TEXT = LAYOUT_ELEMENT_CLICK_ACTION_FEATURE_COUNT + 0;
/**
* The number of structural features of the '<em>Action Show Toast</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ACTION_SHOW_TOAST_FEATURE_COUNT = LAYOUT_ELEMENT_CLICK_ACTION_FEATURE_COUNT + 1;
/**
* The meta object id for the '{@link at.fhj.gaar.androidapp.appDsl.impl.ActionStartActivityImpl <em>Action Start Activity</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see at.fhj.gaar.androidapp.appDsl.impl.ActionStartActivityImpl
* @see at.fhj.gaar.androidapp.appDsl.impl.AppDslPackageImpl#getActionStartActivity()
* @generated
*/
int ACTION_START_ACTIVITY = 35;
/**
* The feature id for the '<em><b>Activity</b></em>' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ACTION_START_ACTIVITY__ACTIVITY = LAYOUT_ELEMENT_CLICK_ACTION_FEATURE_COUNT + 0;
/**
* The number of structural features of the '<em>Action Start Activity</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ACTION_START_ACTIVITY_FEATURE_COUNT = LAYOUT_ELEMENT_CLICK_ACTION_FEATURE_COUNT + 1;
/**
* The meta object id for the '{@link at.fhj.gaar.androidapp.appDsl.impl.ActionStartServiceImpl <em>Action Start Service</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see at.fhj.gaar.androidapp.appDsl.impl.ActionStartServiceImpl
* @see at.fhj.gaar.androidapp.appDsl.impl.AppDslPackageImpl#getActionStartService()
* @generated
*/
int ACTION_START_SERVICE = 36;
/**
* The feature id for the '<em><b>Service</b></em>' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ACTION_START_SERVICE__SERVICE = LAYOUT_ELEMENT_CLICK_ACTION_FEATURE_COUNT + 0;
/**
* The number of structural features of the '<em>Action Start Service</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ACTION_START_SERVICE_FEATURE_COUNT = LAYOUT_ELEMENT_CLICK_ACTION_FEATURE_COUNT + 1;
/**
* Returns the meta object for class '{@link at.fhj.gaar.androidapp.appDsl.AndroidAppProject <em>Android App Project</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for class '<em>Android App Project</em>'.
* @see at.fhj.gaar.androidapp.appDsl.AndroidAppProject
* @generated
*/
EClass getAndroidAppProject();
/**
* Returns the meta object for the containment reference list '{@link at.fhj.gaar.androidapp.appDsl.AndroidAppProject#getApplications <em>Applications</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the containment reference list '<em>Applications</em>'.
* @see at.fhj.gaar.androidapp.appDsl.AndroidAppProject#getApplications()
* @see #getAndroidAppProject()
* @generated
*/
EReference getAndroidAppProject_Applications();
/**
* Returns the meta object for class '{@link at.fhj.gaar.androidapp.appDsl.Application <em>Application</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for class '<em>Application</em>'.
* @see at.fhj.gaar.androidapp.appDsl.Application
* @generated
*/
EClass getApplication();
/**
* Returns the meta object for the attribute '{@link at.fhj.gaar.androidapp.appDsl.Application#getName <em>Name</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Name</em>'.
* @see at.fhj.gaar.androidapp.appDsl.Application#getName()
* @see #getApplication()
* @generated
*/
EAttribute getApplication_Name();
/**
* Returns the meta object for the containment reference list '{@link at.fhj.gaar.androidapp.appDsl.Application#getAttributes <em>Attributes</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the containment reference list '<em>Attributes</em>'.
* @see at.fhj.gaar.androidapp.appDsl.Application#getAttributes()
* @see #getApplication()
* @generated
*/
EReference getApplication_Attributes();
/**
* Returns the meta object for class '{@link at.fhj.gaar.androidapp.appDsl.ApplicationAttribute <em>Application Attribute</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for class '<em>Application Attribute</em>'.
* @see at.fhj.gaar.androidapp.appDsl.ApplicationAttribute
* @generated
*/
EClass getApplicationAttribute();
/**
* Returns the meta object for class '{@link at.fhj.gaar.androidapp.appDsl.ApplicationMinSdk <em>Application Min Sdk</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for class '<em>Application Min Sdk</em>'.
* @see at.fhj.gaar.androidapp.appDsl.ApplicationMinSdk
* @generated
*/
EClass getApplicationMinSdk();
/**
* Returns the meta object for the attribute '{@link at.fhj.gaar.androidapp.appDsl.ApplicationMinSdk#getMinSdk <em>Min Sdk</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Min Sdk</em>'.
* @see at.fhj.gaar.androidapp.appDsl.ApplicationMinSdk#getMinSdk()
* @see #getApplicationMinSdk()
* @generated
*/
EAttribute getApplicationMinSdk_MinSdk();
/**
* Returns the meta object for class '{@link at.fhj.gaar.androidapp.appDsl.ApplicationTargetSdk <em>Application Target Sdk</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for class '<em>Application Target Sdk</em>'.
* @see at.fhj.gaar.androidapp.appDsl.ApplicationTargetSdk
* @generated
*/
EClass getApplicationTargetSdk();
/**
* Returns the meta object for the attribute '{@link at.fhj.gaar.androidapp.appDsl.ApplicationTargetSdk#getTargetSdk <em>Target Sdk</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Target Sdk</em>'.
* @see at.fhj.gaar.androidapp.appDsl.ApplicationTargetSdk#getTargetSdk()
* @see #getApplicationTargetSdk()
* @generated
*/
EAttribute getApplicationTargetSdk_TargetSdk();
/**
* Returns the meta object for class '{@link at.fhj.gaar.androidapp.appDsl.ApplicationCompileSdk <em>Application Compile Sdk</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for class '<em>Application Compile Sdk</em>'.
* @see at.fhj.gaar.androidapp.appDsl.ApplicationCompileSdk
* @generated
*/
EClass getApplicationCompileSdk();
/**
* Returns the meta object for the attribute '{@link at.fhj.gaar.androidapp.appDsl.ApplicationCompileSdk#getCompileSdk <em>Compile Sdk</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Compile Sdk</em>'.
* @see at.fhj.gaar.androidapp.appDsl.ApplicationCompileSdk#getCompileSdk()
* @see #getApplicationCompileSdk()
* @generated
*/
EAttribute getApplicationCompileSdk_CompileSdk();
/**
* Returns the meta object for class '{@link at.fhj.gaar.androidapp.appDsl.ApplicationPermissionList <em>Application Permission List</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for class '<em>Application Permission List</em>'.
* @see at.fhj.gaar.androidapp.appDsl.ApplicationPermissionList
* @generated
*/
EClass getApplicationPermissionList();
/**
* Returns the meta object for the containment reference list '{@link at.fhj.gaar.androidapp.appDsl.ApplicationPermissionList#getPermissions <em>Permissions</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the containment reference list '<em>Permissions</em>'.
* @see at.fhj.gaar.androidapp.appDsl.ApplicationPermissionList#getPermissions()
* @see #getApplicationPermissionList()
* @generated
*/
EReference getApplicationPermissionList_Permissions();
/**
* Returns the meta object for class '{@link at.fhj.gaar.androidapp.appDsl.ApplicationElementList <em>Application Element List</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for class '<em>Application Element List</em>'.
* @see at.fhj.gaar.androidapp.appDsl.ApplicationElementList
* @generated
*/
EClass getApplicationElementList();
/**
* Returns the meta object for the containment reference list '{@link at.fhj.gaar.androidapp.appDsl.ApplicationElementList#getElements <em>Elements</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the containment reference list '<em>Elements</em>'.
* @see at.fhj.gaar.androidapp.appDsl.ApplicationElementList#getElements()
* @see #getApplicationElementList()
* @generated
*/
EReference getApplicationElementList_Elements();
/**
* Returns the meta object for class '{@link at.fhj.gaar.androidapp.appDsl.ApplicationMainActivity <em>Application Main Activity</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for class '<em>Application Main Activity</em>'.
* @see at.fhj.gaar.androidapp.appDsl.ApplicationMainActivity
* @generated
*/
EClass getApplicationMainActivity();
/**
* Returns the meta object for the reference '{@link at.fhj.gaar.androidapp.appDsl.ApplicationMainActivity#getLauncherActivity <em>Launcher Activity</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the reference '<em>Launcher Activity</em>'.
* @see at.fhj.gaar.androidapp.appDsl.ApplicationMainActivity#getLauncherActivity()
* @see #getApplicationMainActivity()
* @generated
*/
EReference getApplicationMainActivity_LauncherActivity();
/**
* Returns the meta object for class '{@link at.fhj.gaar.androidapp.appDsl.Permission <em>Permission</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for class '<em>Permission</em>'.
* @see at.fhj.gaar.androidapp.appDsl.Permission
* @generated
*/
EClass getPermission();
/**
* Returns the meta object for the attribute '{@link at.fhj.gaar.androidapp.appDsl.Permission#getName <em>Name</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Name</em>'.
* @see at.fhj.gaar.androidapp.appDsl.Permission#getName()
* @see #getPermission()
* @generated
*/
EAttribute getPermission_Name();
/**
* Returns the meta object for class '{@link at.fhj.gaar.androidapp.appDsl.ApplicationElement <em>Application Element</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for class '<em>Application Element</em>'.
* @see at.fhj.gaar.androidapp.appDsl.ApplicationElement
* @generated
*/
EClass getApplicationElement();
/**
* Returns the meta object for the attribute '{@link at.fhj.gaar.androidapp.appDsl.ApplicationElement#getName <em>Name</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Name</em>'.
* @see at.fhj.gaar.androidapp.appDsl.ApplicationElement#getName()
* @see #getApplicationElement()
* @generated
*/
EAttribute getApplicationElement_Name();
/**
* Returns the meta object for class '{@link at.fhj.gaar.androidapp.appDsl.Activity <em>Activity</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for class '<em>Activity</em>'.
* @see at.fhj.gaar.androidapp.appDsl.Activity
* @generated
*/
EClass getActivity();
/**
* Returns the meta object for the containment reference list '{@link at.fhj.gaar.androidapp.appDsl.Activity#getAttributes <em>Attributes</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the containment reference list '<em>Attributes</em>'.
* @see at.fhj.gaar.androidapp.appDsl.Activity#getAttributes()
* @see #getActivity()
* @generated
*/
EReference getActivity_Attributes();
/**
* Returns the meta object for class '{@link at.fhj.gaar.androidapp.appDsl.BroadcastReceiver <em>Broadcast Receiver</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for class '<em>Broadcast Receiver</em>'.
* @see at.fhj.gaar.androidapp.appDsl.BroadcastReceiver
* @generated
*/
EClass getBroadcastReceiver();
/**
* Returns the meta object for the containment reference list '{@link at.fhj.gaar.androidapp.appDsl.BroadcastReceiver#getAttributes <em>Attributes</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the containment reference list '<em>Attributes</em>'.
* @see at.fhj.gaar.androidapp.appDsl.BroadcastReceiver#getAttributes()
* @see #getBroadcastReceiver()
* @generated
*/
EReference getBroadcastReceiver_Attributes();
/**
* Returns the meta object for class '{@link at.fhj.gaar.androidapp.appDsl.Service <em>Service</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for class '<em>Service</em>'.
* @see at.fhj.gaar.androidapp.appDsl.Service
* @generated
*/
EClass getService();
/**
* Returns the meta object for the containment reference list '{@link at.fhj.gaar.androidapp.appDsl.Service#getAttributes <em>Attributes</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the containment reference list '<em>Attributes</em>'.
* @see at.fhj.gaar.androidapp.appDsl.Service#getAttributes()
* @see #getService()
* @generated
*/
EReference getService_Attributes();
/**
* Returns the meta object for class '{@link at.fhj.gaar.androidapp.appDsl.ActivityAttribute <em>Activity Attribute</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for class '<em>Activity Attribute</em>'.
* @see at.fhj.gaar.androidapp.appDsl.ActivityAttribute
* @generated
*/
EClass getActivityAttribute();
/**
* Returns the meta object for class '{@link at.fhj.gaar.androidapp.appDsl.BroadcastReceiverAttribute <em>Broadcast Receiver Attribute</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for class '<em>Broadcast Receiver Attribute</em>'.
* @see at.fhj.gaar.androidapp.appDsl.BroadcastReceiverAttribute
* @generated
*/
EClass getBroadcastReceiverAttribute();
/**
* Returns the meta object for class '{@link at.fhj.gaar.androidapp.appDsl.ServiceAttribute <em>Service Attribute</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for class '<em>Service Attribute</em>'.
* @see at.fhj.gaar.androidapp.appDsl.ServiceAttribute
* @generated
*/
EClass getServiceAttribute();
/**
* Returns the meta object for class '{@link at.fhj.gaar.androidapp.appDsl.ElementEnabledAttribute <em>Element Enabled Attribute</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for class '<em>Element Enabled Attribute</em>'.
* @see at.fhj.gaar.androidapp.appDsl.ElementEnabledAttribute
* @generated
*/
EClass getElementEnabledAttribute();
/**
* Returns the meta object for the attribute '{@link at.fhj.gaar.androidapp.appDsl.ElementEnabledAttribute#isEnabled <em>Enabled</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Enabled</em>'.
* @see at.fhj.gaar.androidapp.appDsl.ElementEnabledAttribute#isEnabled()
* @see #getElementEnabledAttribute()
* @generated
*/
EAttribute getElementEnabledAttribute_Enabled();
/**
* Returns the meta object for class '{@link at.fhj.gaar.androidapp.appDsl.ElementExportedAttribute <em>Element Exported Attribute</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for class '<em>Element Exported Attribute</em>'.
* @see at.fhj.gaar.androidapp.appDsl.ElementExportedAttribute
* @generated
*/
EClass getElementExportedAttribute();
/**
* Returns the meta object for the attribute '{@link at.fhj.gaar.androidapp.appDsl.ElementExportedAttribute#isExported <em>Exported</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Exported</em>'.
* @see at.fhj.gaar.androidapp.appDsl.ElementExportedAttribute#isExported()
* @see #getElementExportedAttribute()
* @generated
*/
EAttribute getElementExportedAttribute_Exported();
/**
* Returns the meta object for class '{@link at.fhj.gaar.androidapp.appDsl.ElementLabelAttribute <em>Element Label Attribute</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for class '<em>Element Label Attribute</em>'.
* @see at.fhj.gaar.androidapp.appDsl.ElementLabelAttribute
* @generated
*/
EClass getElementLabelAttribute();
/**
* Returns the meta object for the attribute '{@link at.fhj.gaar.androidapp.appDsl.ElementLabelAttribute#getTitle <em>Title</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Title</em>'.
* @see at.fhj.gaar.androidapp.appDsl.ElementLabelAttribute#getTitle()
* @see #getElementLabelAttribute()
* @generated
*/
EAttribute getElementLabelAttribute_Title();
/**
* Returns the meta object for class '{@link at.fhj.gaar.androidapp.appDsl.ElementIntentList <em>Element Intent List</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for class '<em>Element Intent List</em>'.
* @see at.fhj.gaar.androidapp.appDsl.ElementIntentList
* @generated
*/
EClass getElementIntentList();
/**
* Returns the meta object for the containment reference list '{@link at.fhj.gaar.androidapp.appDsl.ElementIntentList#getIntents <em>Intents</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the containment reference list '<em>Intents</em>'.
* @see at.fhj.gaar.androidapp.appDsl.ElementIntentList#getIntents()
* @see #getElementIntentList()
* @generated
*/
EReference getElementIntentList_Intents();
/**
* Returns the meta object for class '{@link at.fhj.gaar.androidapp.appDsl.Intent <em>Intent</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for class '<em>Intent</em>'.
* @see at.fhj.gaar.androidapp.appDsl.Intent
* @generated
*/
EClass getIntent();
/**
* Returns the meta object for the attribute '{@link at.fhj.gaar.androidapp.appDsl.Intent#getName <em>Name</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Name</em>'.
* @see at.fhj.gaar.androidapp.appDsl.Intent#getName()
* @see #getIntent()
* @generated
*/
EAttribute getIntent_Name();
/**
* Returns the meta object for class '{@link at.fhj.gaar.androidapp.appDsl.ActivityParentAttribute <em>Activity Parent Attribute</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for class '<em>Activity Parent Attribute</em>'.
* @see at.fhj.gaar.androidapp.appDsl.ActivityParentAttribute
* @generated
*/
EClass getActivityParentAttribute();
/**
* Returns the meta object for the reference '{@link at.fhj.gaar.androidapp.appDsl.ActivityParentAttribute#getParent <em>Parent</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the reference '<em>Parent</em>'.
* @see at.fhj.gaar.androidapp.appDsl.ActivityParentAttribute#getParent()
* @see #getActivityParentAttribute()
* @generated
*/
EReference getActivityParentAttribute_Parent();
/**
* Returns the meta object for class '{@link at.fhj.gaar.androidapp.appDsl.ActivityLayoutAttribute <em>Activity Layout Attribute</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for class '<em>Activity Layout Attribute</em>'.
* @see at.fhj.gaar.androidapp.appDsl.ActivityLayoutAttribute
* @generated
*/
EClass getActivityLayoutAttribute();
/**
* Returns the meta object for the containment reference list '{@link at.fhj.gaar.androidapp.appDsl.ActivityLayoutAttribute#getLayoutElements <em>Layout Elements</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the containment reference list '<em>Layout Elements</em>'.
* @see at.fhj.gaar.androidapp.appDsl.ActivityLayoutAttribute#getLayoutElements()
* @see #getActivityLayoutAttribute()
* @generated
*/
EReference getActivityLayoutAttribute_LayoutElements();
/**
* Returns the meta object for class '{@link at.fhj.gaar.androidapp.appDsl.LayoutElement <em>Layout Element</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for class '<em>Layout Element</em>'.
* @see at.fhj.gaar.androidapp.appDsl.LayoutElement
* @generated
*/
EClass getLayoutElement();
/**
* Returns the meta object for class '{@link at.fhj.gaar.androidapp.appDsl.Button <em>Button</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for class '<em>Button</em>'.
* @see at.fhj.gaar.androidapp.appDsl.Button
* @generated
*/
EClass getButton();
/**
* Returns the meta object for the attribute '{@link at.fhj.gaar.androidapp.appDsl.Button#getName <em>Name</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Name</em>'.
* @see at.fhj.gaar.androidapp.appDsl.Button#getName()
* @see #getButton()
* @generated
*/
EAttribute getButton_Name();
/**
* Returns the meta object for the containment reference list '{@link at.fhj.gaar.androidapp.appDsl.Button#getAttributes <em>Attributes</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the containment reference list '<em>Attributes</em>'.
* @see at.fhj.gaar.androidapp.appDsl.Button#getAttributes()
* @see #getButton()
* @generated
*/
EReference getButton_Attributes();
/**
* Returns the meta object for class '{@link at.fhj.gaar.androidapp.appDsl.ButtonAttribute <em>Button Attribute</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for class '<em>Button Attribute</em>'.
* @see at.fhj.gaar.androidapp.appDsl.ButtonAttribute
* @generated
*/
EClass getButtonAttribute();
/**
* Returns the meta object for class '{@link at.fhj.gaar.androidapp.appDsl.ButtonLabelAttribute <em>Button Label Attribute</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for class '<em>Button Label Attribute</em>'.
* @see at.fhj.gaar.androidapp.appDsl.ButtonLabelAttribute
* @generated
*/
EClass getButtonLabelAttribute();
/**
* Returns the meta object for the attribute '{@link at.fhj.gaar.androidapp.appDsl.ButtonLabelAttribute#getTitle <em>Title</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Title</em>'.
* @see at.fhj.gaar.androidapp.appDsl.ButtonLabelAttribute#getTitle()
* @see #getButtonLabelAttribute()
* @generated
*/
EAttribute getButtonLabelAttribute_Title();
/**
* Returns the meta object for class '{@link at.fhj.gaar.androidapp.appDsl.ButtonActionAttribute <em>Button Action Attribute</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for class '<em>Button Action Attribute</em>'.
* @see at.fhj.gaar.androidapp.appDsl.ButtonActionAttribute
* @generated
*/
EClass getButtonActionAttribute();
/**
* Returns the meta object for the containment reference '{@link at.fhj.gaar.androidapp.appDsl.ButtonActionAttribute#getAction <em>Action</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the containment reference '<em>Action</em>'.
* @see at.fhj.gaar.androidapp.appDsl.ButtonActionAttribute#getAction()
* @see #getButtonActionAttribute()
* @generated
*/
EReference getButtonActionAttribute_Action();
/**
* Returns the meta object for class '{@link at.fhj.gaar.androidapp.appDsl.Spacer <em>Spacer</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for class '<em>Spacer</em>'.
* @see at.fhj.gaar.androidapp.appDsl.Spacer
* @generated
*/
EClass getSpacer();
/**
* Returns the meta object for class '{@link at.fhj.gaar.androidapp.appDsl.Text <em>Text</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for class '<em>Text</em>'.
* @see at.fhj.gaar.androidapp.appDsl.Text
* @generated
*/
EClass getText();
/**
* Returns the meta object for the attribute '{@link at.fhj.gaar.androidapp.appDsl.Text#getText <em>Text</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Text</em>'.
* @see at.fhj.gaar.androidapp.appDsl.Text#getText()
* @see #getText()
* @generated
*/
EAttribute getText_Text();
/**
* Returns the meta object for class '{@link at.fhj.gaar.androidapp.appDsl.LayoutElementClickAction <em>Layout Element Click Action</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for class '<em>Layout Element Click Action</em>'.
* @see at.fhj.gaar.androidapp.appDsl.LayoutElementClickAction
* @generated
*/
EClass getLayoutElementClickAction();
/**
* Returns the meta object for class '{@link at.fhj.gaar.androidapp.appDsl.BroadcastReceiverActionAttribute <em>Broadcast Receiver Action Attribute</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for class '<em>Broadcast Receiver Action Attribute</em>'.
* @see at.fhj.gaar.androidapp.appDsl.BroadcastReceiverActionAttribute
* @generated
*/
EClass getBroadcastReceiverActionAttribute();
/**
* Returns the meta object for the containment reference '{@link at.fhj.gaar.androidapp.appDsl.BroadcastReceiverActionAttribute#getAction <em>Action</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the containment reference '<em>Action</em>'.
* @see at.fhj.gaar.androidapp.appDsl.BroadcastReceiverActionAttribute#getAction()
* @see #getBroadcastReceiverActionAttribute()
* @generated
*/
EReference getBroadcastReceiverActionAttribute_Action();
/**
* Returns the meta object for class '{@link at.fhj.gaar.androidapp.appDsl.BroadcastReceiverAction <em>Broadcast Receiver Action</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for class '<em>Broadcast Receiver Action</em>'.
* @see at.fhj.gaar.androidapp.appDsl.BroadcastReceiverAction
* @generated
*/
EClass getBroadcastReceiverAction();
/**
* Returns the meta object for class '{@link at.fhj.gaar.androidapp.appDsl.ActionShowToast <em>Action Show Toast</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for class '<em>Action Show Toast</em>'.
* @see at.fhj.gaar.androidapp.appDsl.ActionShowToast
* @generated
*/
EClass getActionShowToast();
/**
* Returns the meta object for the attribute '{@link at.fhj.gaar.androidapp.appDsl.ActionShowToast#getToastText <em>Toast Text</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Toast Text</em>'.
* @see at.fhj.gaar.androidapp.appDsl.ActionShowToast#getToastText()
* @see #getActionShowToast()
* @generated
*/
EAttribute getActionShowToast_ToastText();
/**
* Returns the meta object for class '{@link at.fhj.gaar.androidapp.appDsl.ActionStartActivity <em>Action Start Activity</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for class '<em>Action Start Activity</em>'.
* @see at.fhj.gaar.androidapp.appDsl.ActionStartActivity
* @generated
*/
EClass getActionStartActivity();
/**
* Returns the meta object for the reference '{@link at.fhj.gaar.androidapp.appDsl.ActionStartActivity#getActivity <em>Activity</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the reference '<em>Activity</em>'.
* @see at.fhj.gaar.androidapp.appDsl.ActionStartActivity#getActivity()
* @see #getActionStartActivity()
* @generated
*/
EReference getActionStartActivity_Activity();
/**
* Returns the meta object for class '{@link at.fhj.gaar.androidapp.appDsl.ActionStartService <em>Action Start Service</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for class '<em>Action Start Service</em>'.
* @see at.fhj.gaar.androidapp.appDsl.ActionStartService
* @generated
*/
EClass getActionStartService();
/**
* Returns the meta object for the reference '{@link at.fhj.gaar.androidapp.appDsl.ActionStartService#getService <em>Service</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the reference '<em>Service</em>'.
* @see at.fhj.gaar.androidapp.appDsl.ActionStartService#getService()
* @see #getActionStartService()
* @generated
*/
EReference getActionStartService_Service();
/**
* Returns the factory that creates the instances of the model.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the factory that creates the instances of the model.
* @generated
*/
AppDslFactory getAppDslFactory();
/**
* <!-- begin-user-doc -->
* Defines literals for the meta objects that represent
* <ul>
* <li>each class,</li>
* <li>each feature of each class,</li>
* <li>each enum,</li>
* <li>and each data type</li>
* </ul>
* <!-- end-user-doc -->
* @generated
*/
interface Literals
{
/**
* The meta object literal for the '{@link at.fhj.gaar.androidapp.appDsl.impl.AndroidAppProjectImpl <em>Android App Project</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see at.fhj.gaar.androidapp.appDsl.impl.AndroidAppProjectImpl
* @see at.fhj.gaar.androidapp.appDsl.impl.AppDslPackageImpl#getAndroidAppProject()
* @generated
*/
EClass ANDROID_APP_PROJECT = eINSTANCE.getAndroidAppProject();
/**
* The meta object literal for the '<em><b>Applications</b></em>' containment reference list feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EReference ANDROID_APP_PROJECT__APPLICATIONS = eINSTANCE.getAndroidAppProject_Applications();
/**
* The meta object literal for the '{@link at.fhj.gaar.androidapp.appDsl.impl.ApplicationImpl <em>Application</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see at.fhj.gaar.androidapp.appDsl.impl.ApplicationImpl
* @see at.fhj.gaar.androidapp.appDsl.impl.AppDslPackageImpl#getApplication()
* @generated
*/
EClass APPLICATION = eINSTANCE.getApplication();
/**
* The meta object literal for the '<em><b>Name</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute APPLICATION__NAME = eINSTANCE.getApplication_Name();
/**
* The meta object literal for the '<em><b>Attributes</b></em>' containment reference list feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EReference APPLICATION__ATTRIBUTES = eINSTANCE.getApplication_Attributes();
/**
* The meta object literal for the '{@link at.fhj.gaar.androidapp.appDsl.impl.ApplicationAttributeImpl <em>Application Attribute</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see at.fhj.gaar.androidapp.appDsl.impl.ApplicationAttributeImpl
* @see at.fhj.gaar.androidapp.appDsl.impl.AppDslPackageImpl#getApplicationAttribute()
* @generated
*/
EClass APPLICATION_ATTRIBUTE = eINSTANCE.getApplicationAttribute();
/**
* The meta object literal for the '{@link at.fhj.gaar.androidapp.appDsl.impl.ApplicationMinSdkImpl <em>Application Min Sdk</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see at.fhj.gaar.androidapp.appDsl.impl.ApplicationMinSdkImpl
* @see at.fhj.gaar.androidapp.appDsl.impl.AppDslPackageImpl#getApplicationMinSdk()
* @generated
*/
EClass APPLICATION_MIN_SDK = eINSTANCE.getApplicationMinSdk();
/**
* The meta object literal for the '<em><b>Min Sdk</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute APPLICATION_MIN_SDK__MIN_SDK = eINSTANCE.getApplicationMinSdk_MinSdk();
/**
* The meta object literal for the '{@link at.fhj.gaar.androidapp.appDsl.impl.ApplicationTargetSdkImpl <em>Application Target Sdk</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see at.fhj.gaar.androidapp.appDsl.impl.ApplicationTargetSdkImpl
* @see at.fhj.gaar.androidapp.appDsl.impl.AppDslPackageImpl#getApplicationTargetSdk()
* @generated
*/
EClass APPLICATION_TARGET_SDK = eINSTANCE.getApplicationTargetSdk();
/**
* The meta object literal for the '<em><b>Target Sdk</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute APPLICATION_TARGET_SDK__TARGET_SDK = eINSTANCE.getApplicationTargetSdk_TargetSdk();
/**
* The meta object literal for the '{@link at.fhj.gaar.androidapp.appDsl.impl.ApplicationCompileSdkImpl <em>Application Compile Sdk</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see at.fhj.gaar.androidapp.appDsl.impl.ApplicationCompileSdkImpl
* @see at.fhj.gaar.androidapp.appDsl.impl.AppDslPackageImpl#getApplicationCompileSdk()
* @generated
*/
EClass APPLICATION_COMPILE_SDK = eINSTANCE.getApplicationCompileSdk();
/**
* The meta object literal for the '<em><b>Compile Sdk</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute APPLICATION_COMPILE_SDK__COMPILE_SDK = eINSTANCE.getApplicationCompileSdk_CompileSdk();
/**
* The meta object literal for the '{@link at.fhj.gaar.androidapp.appDsl.impl.ApplicationPermissionListImpl <em>Application Permission List</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see at.fhj.gaar.androidapp.appDsl.impl.ApplicationPermissionListImpl
* @see at.fhj.gaar.androidapp.appDsl.impl.AppDslPackageImpl#getApplicationPermissionList()
* @generated
*/
EClass APPLICATION_PERMISSION_LIST = eINSTANCE.getApplicationPermissionList();
/**
* The meta object literal for the '<em><b>Permissions</b></em>' containment reference list feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EReference APPLICATION_PERMISSION_LIST__PERMISSIONS = eINSTANCE.getApplicationPermissionList_Permissions();
/**
* The meta object literal for the '{@link at.fhj.gaar.androidapp.appDsl.impl.ApplicationElementListImpl <em>Application Element List</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see at.fhj.gaar.androidapp.appDsl.impl.ApplicationElementListImpl
* @see at.fhj.gaar.androidapp.appDsl.impl.AppDslPackageImpl#getApplicationElementList()
* @generated
*/
EClass APPLICATION_ELEMENT_LIST = eINSTANCE.getApplicationElementList();
/**
* The meta object literal for the '<em><b>Elements</b></em>' containment reference list feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EReference APPLICATION_ELEMENT_LIST__ELEMENTS = eINSTANCE.getApplicationElementList_Elements();
/**
* The meta object literal for the '{@link at.fhj.gaar.androidapp.appDsl.impl.ApplicationMainActivityImpl <em>Application Main Activity</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see at.fhj.gaar.androidapp.appDsl.impl.ApplicationMainActivityImpl
* @see at.fhj.gaar.androidapp.appDsl.impl.AppDslPackageImpl#getApplicationMainActivity()
* @generated
*/
EClass APPLICATION_MAIN_ACTIVITY = eINSTANCE.getApplicationMainActivity();
/**
* The meta object literal for the '<em><b>Launcher Activity</b></em>' reference feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EReference APPLICATION_MAIN_ACTIVITY__LAUNCHER_ACTIVITY = eINSTANCE.getApplicationMainActivity_LauncherActivity();
/**
* The meta object literal for the '{@link at.fhj.gaar.androidapp.appDsl.impl.PermissionImpl <em>Permission</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see at.fhj.gaar.androidapp.appDsl.impl.PermissionImpl
* @see at.fhj.gaar.androidapp.appDsl.impl.AppDslPackageImpl#getPermission()
* @generated
*/
EClass PERMISSION = eINSTANCE.getPermission();
/**
* The meta object literal for the '<em><b>Name</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute PERMISSION__NAME = eINSTANCE.getPermission_Name();
/**
* The meta object literal for the '{@link at.fhj.gaar.androidapp.appDsl.impl.ApplicationElementImpl <em>Application Element</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see at.fhj.gaar.androidapp.appDsl.impl.ApplicationElementImpl
* @see at.fhj.gaar.androidapp.appDsl.impl.AppDslPackageImpl#getApplicationElement()
* @generated
*/
EClass APPLICATION_ELEMENT = eINSTANCE.getApplicationElement();
/**
* The meta object literal for the '<em><b>Name</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute APPLICATION_ELEMENT__NAME = eINSTANCE.getApplicationElement_Name();
/**
* The meta object literal for the '{@link at.fhj.gaar.androidapp.appDsl.impl.ActivityImpl <em>Activity</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see at.fhj.gaar.androidapp.appDsl.impl.ActivityImpl
* @see at.fhj.gaar.androidapp.appDsl.impl.AppDslPackageImpl#getActivity()
* @generated
*/
EClass ACTIVITY = eINSTANCE.getActivity();
/**
* The meta object literal for the '<em><b>Attributes</b></em>' containment reference list feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EReference ACTIVITY__ATTRIBUTES = eINSTANCE.getActivity_Attributes();
/**
* The meta object literal for the '{@link at.fhj.gaar.androidapp.appDsl.impl.BroadcastReceiverImpl <em>Broadcast Receiver</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see at.fhj.gaar.androidapp.appDsl.impl.BroadcastReceiverImpl
* @see at.fhj.gaar.androidapp.appDsl.impl.AppDslPackageImpl#getBroadcastReceiver()
* @generated
*/
EClass BROADCAST_RECEIVER = eINSTANCE.getBroadcastReceiver();
/**
* The meta object literal for the '<em><b>Attributes</b></em>' containment reference list feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EReference BROADCAST_RECEIVER__ATTRIBUTES = eINSTANCE.getBroadcastReceiver_Attributes();
/**
* The meta object literal for the '{@link at.fhj.gaar.androidapp.appDsl.impl.ServiceImpl <em>Service</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see at.fhj.gaar.androidapp.appDsl.impl.ServiceImpl
* @see at.fhj.gaar.androidapp.appDsl.impl.AppDslPackageImpl#getService()
* @generated
*/
EClass SERVICE = eINSTANCE.getService();
/**
* The meta object literal for the '<em><b>Attributes</b></em>' containment reference list feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EReference SERVICE__ATTRIBUTES = eINSTANCE.getService_Attributes();
/**
* The meta object literal for the '{@link at.fhj.gaar.androidapp.appDsl.impl.ActivityAttributeImpl <em>Activity Attribute</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see at.fhj.gaar.androidapp.appDsl.impl.ActivityAttributeImpl
* @see at.fhj.gaar.androidapp.appDsl.impl.AppDslPackageImpl#getActivityAttribute()
* @generated
*/
EClass ACTIVITY_ATTRIBUTE = eINSTANCE.getActivityAttribute();
/**
* The meta object literal for the '{@link at.fhj.gaar.androidapp.appDsl.impl.BroadcastReceiverAttributeImpl <em>Broadcast Receiver Attribute</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see at.fhj.gaar.androidapp.appDsl.impl.BroadcastReceiverAttributeImpl
* @see at.fhj.gaar.androidapp.appDsl.impl.AppDslPackageImpl#getBroadcastReceiverAttribute()
* @generated
*/
EClass BROADCAST_RECEIVER_ATTRIBUTE = eINSTANCE.getBroadcastReceiverAttribute();
/**
* The meta object literal for the '{@link at.fhj.gaar.androidapp.appDsl.impl.ServiceAttributeImpl <em>Service Attribute</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see at.fhj.gaar.androidapp.appDsl.impl.ServiceAttributeImpl
* @see at.fhj.gaar.androidapp.appDsl.impl.AppDslPackageImpl#getServiceAttribute()
* @generated
*/
EClass SERVICE_ATTRIBUTE = eINSTANCE.getServiceAttribute();
/**
* The meta object literal for the '{@link at.fhj.gaar.androidapp.appDsl.impl.ElementEnabledAttributeImpl <em>Element Enabled Attribute</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see at.fhj.gaar.androidapp.appDsl.impl.ElementEnabledAttributeImpl
* @see at.fhj.gaar.androidapp.appDsl.impl.AppDslPackageImpl#getElementEnabledAttribute()
* @generated
*/
EClass ELEMENT_ENABLED_ATTRIBUTE = eINSTANCE.getElementEnabledAttribute();
/**
* The meta object literal for the '<em><b>Enabled</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute ELEMENT_ENABLED_ATTRIBUTE__ENABLED = eINSTANCE.getElementEnabledAttribute_Enabled();
/**
* The meta object literal for the '{@link at.fhj.gaar.androidapp.appDsl.impl.ElementExportedAttributeImpl <em>Element Exported Attribute</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see at.fhj.gaar.androidapp.appDsl.impl.ElementExportedAttributeImpl
* @see at.fhj.gaar.androidapp.appDsl.impl.AppDslPackageImpl#getElementExportedAttribute()
* @generated
*/
EClass ELEMENT_EXPORTED_ATTRIBUTE = eINSTANCE.getElementExportedAttribute();
/**
* The meta object literal for the '<em><b>Exported</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute ELEMENT_EXPORTED_ATTRIBUTE__EXPORTED = eINSTANCE.getElementExportedAttribute_Exported();
/**
* The meta object literal for the '{@link at.fhj.gaar.androidapp.appDsl.impl.ElementLabelAttributeImpl <em>Element Label Attribute</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see at.fhj.gaar.androidapp.appDsl.impl.ElementLabelAttributeImpl
* @see at.fhj.gaar.androidapp.appDsl.impl.AppDslPackageImpl#getElementLabelAttribute()
* @generated
*/
EClass ELEMENT_LABEL_ATTRIBUTE = eINSTANCE.getElementLabelAttribute();
/**
* The meta object literal for the '<em><b>Title</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute ELEMENT_LABEL_ATTRIBUTE__TITLE = eINSTANCE.getElementLabelAttribute_Title();
/**
* The meta object literal for the '{@link at.fhj.gaar.androidapp.appDsl.impl.ElementIntentListImpl <em>Element Intent List</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see at.fhj.gaar.androidapp.appDsl.impl.ElementIntentListImpl
* @see at.fhj.gaar.androidapp.appDsl.impl.AppDslPackageImpl#getElementIntentList()
* @generated
*/
EClass ELEMENT_INTENT_LIST = eINSTANCE.getElementIntentList();
/**
* The meta object literal for the '<em><b>Intents</b></em>' containment reference list feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EReference ELEMENT_INTENT_LIST__INTENTS = eINSTANCE.getElementIntentList_Intents();
/**
* The meta object literal for the '{@link at.fhj.gaar.androidapp.appDsl.impl.IntentImpl <em>Intent</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see at.fhj.gaar.androidapp.appDsl.impl.IntentImpl
* @see at.fhj.gaar.androidapp.appDsl.impl.AppDslPackageImpl#getIntent()
* @generated
*/
EClass INTENT = eINSTANCE.getIntent();
/**
* The meta object literal for the '<em><b>Name</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute INTENT__NAME = eINSTANCE.getIntent_Name();
/**
* The meta object literal for the '{@link at.fhj.gaar.androidapp.appDsl.impl.ActivityParentAttributeImpl <em>Activity Parent Attribute</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see at.fhj.gaar.androidapp.appDsl.impl.ActivityParentAttributeImpl
* @see at.fhj.gaar.androidapp.appDsl.impl.AppDslPackageImpl#getActivityParentAttribute()
* @generated
*/
EClass ACTIVITY_PARENT_ATTRIBUTE = eINSTANCE.getActivityParentAttribute();
/**
* The meta object literal for the '<em><b>Parent</b></em>' reference feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EReference ACTIVITY_PARENT_ATTRIBUTE__PARENT = eINSTANCE.getActivityParentAttribute_Parent();
/**
* The meta object literal for the '{@link at.fhj.gaar.androidapp.appDsl.impl.ActivityLayoutAttributeImpl <em>Activity Layout Attribute</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see at.fhj.gaar.androidapp.appDsl.impl.ActivityLayoutAttributeImpl
* @see at.fhj.gaar.androidapp.appDsl.impl.AppDslPackageImpl#getActivityLayoutAttribute()
* @generated
*/
EClass ACTIVITY_LAYOUT_ATTRIBUTE = eINSTANCE.getActivityLayoutAttribute();
/**
* The meta object literal for the '<em><b>Layout Elements</b></em>' containment reference list feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EReference ACTIVITY_LAYOUT_ATTRIBUTE__LAYOUT_ELEMENTS = eINSTANCE.getActivityLayoutAttribute_LayoutElements();
/**
* The meta object literal for the '{@link at.fhj.gaar.androidapp.appDsl.impl.LayoutElementImpl <em>Layout Element</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see at.fhj.gaar.androidapp.appDsl.impl.LayoutElementImpl
* @see at.fhj.gaar.androidapp.appDsl.impl.AppDslPackageImpl#getLayoutElement()
* @generated
*/
EClass LAYOUT_ELEMENT = eINSTANCE.getLayoutElement();
/**
* The meta object literal for the '{@link at.fhj.gaar.androidapp.appDsl.impl.ButtonImpl <em>Button</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see at.fhj.gaar.androidapp.appDsl.impl.ButtonImpl
* @see at.fhj.gaar.androidapp.appDsl.impl.AppDslPackageImpl#getButton()
* @generated
*/
EClass BUTTON = eINSTANCE.getButton();
/**
* The meta object literal for the '<em><b>Name</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute BUTTON__NAME = eINSTANCE.getButton_Name();
/**
* The meta object literal for the '<em><b>Attributes</b></em>' containment reference list feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EReference BUTTON__ATTRIBUTES = eINSTANCE.getButton_Attributes();
/**
* The meta object literal for the '{@link at.fhj.gaar.androidapp.appDsl.impl.ButtonAttributeImpl <em>Button Attribute</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see at.fhj.gaar.androidapp.appDsl.impl.ButtonAttributeImpl
* @see at.fhj.gaar.androidapp.appDsl.impl.AppDslPackageImpl#getButtonAttribute()
* @generated
*/
EClass BUTTON_ATTRIBUTE = eINSTANCE.getButtonAttribute();
/**
* The meta object literal for the '{@link at.fhj.gaar.androidapp.appDsl.impl.ButtonLabelAttributeImpl <em>Button Label Attribute</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see at.fhj.gaar.androidapp.appDsl.impl.ButtonLabelAttributeImpl
* @see at.fhj.gaar.androidapp.appDsl.impl.AppDslPackageImpl#getButtonLabelAttribute()
* @generated
*/
EClass BUTTON_LABEL_ATTRIBUTE = eINSTANCE.getButtonLabelAttribute();
/**
* The meta object literal for the '<em><b>Title</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute BUTTON_LABEL_ATTRIBUTE__TITLE = eINSTANCE.getButtonLabelAttribute_Title();
/**
* The meta object literal for the '{@link at.fhj.gaar.androidapp.appDsl.impl.ButtonActionAttributeImpl <em>Button Action Attribute</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see at.fhj.gaar.androidapp.appDsl.impl.ButtonActionAttributeImpl
* @see at.fhj.gaar.androidapp.appDsl.impl.AppDslPackageImpl#getButtonActionAttribute()
* @generated
*/
EClass BUTTON_ACTION_ATTRIBUTE = eINSTANCE.getButtonActionAttribute();
/**
* The meta object literal for the '<em><b>Action</b></em>' containment reference feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EReference BUTTON_ACTION_ATTRIBUTE__ACTION = eINSTANCE.getButtonActionAttribute_Action();
/**
* The meta object literal for the '{@link at.fhj.gaar.androidapp.appDsl.impl.SpacerImpl <em>Spacer</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see at.fhj.gaar.androidapp.appDsl.impl.SpacerImpl
* @see at.fhj.gaar.androidapp.appDsl.impl.AppDslPackageImpl#getSpacer()
* @generated
*/
EClass SPACER = eINSTANCE.getSpacer();
/**
* The meta object literal for the '{@link at.fhj.gaar.androidapp.appDsl.impl.TextImpl <em>Text</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see at.fhj.gaar.androidapp.appDsl.impl.TextImpl
* @see at.fhj.gaar.androidapp.appDsl.impl.AppDslPackageImpl#getText()
* @generated
*/
EClass TEXT = eINSTANCE.getText();
/**
* The meta object literal for the '<em><b>Text</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute TEXT__TEXT = eINSTANCE.getText_Text();
/**
* The meta object literal for the '{@link at.fhj.gaar.androidapp.appDsl.impl.LayoutElementClickActionImpl <em>Layout Element Click Action</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see at.fhj.gaar.androidapp.appDsl.impl.LayoutElementClickActionImpl
* @see at.fhj.gaar.androidapp.appDsl.impl.AppDslPackageImpl#getLayoutElementClickAction()
* @generated
*/
EClass LAYOUT_ELEMENT_CLICK_ACTION = eINSTANCE.getLayoutElementClickAction();
/**
* The meta object literal for the '{@link at.fhj.gaar.androidapp.appDsl.impl.BroadcastReceiverActionAttributeImpl <em>Broadcast Receiver Action Attribute</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see at.fhj.gaar.androidapp.appDsl.impl.BroadcastReceiverActionAttributeImpl
* @see at.fhj.gaar.androidapp.appDsl.impl.AppDslPackageImpl#getBroadcastReceiverActionAttribute()
* @generated
*/
EClass BROADCAST_RECEIVER_ACTION_ATTRIBUTE = eINSTANCE.getBroadcastReceiverActionAttribute();
/**
* The meta object literal for the '<em><b>Action</b></em>' containment reference feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EReference BROADCAST_RECEIVER_ACTION_ATTRIBUTE__ACTION = eINSTANCE.getBroadcastReceiverActionAttribute_Action();
/**
* The meta object literal for the '{@link at.fhj.gaar.androidapp.appDsl.impl.BroadcastReceiverActionImpl <em>Broadcast Receiver Action</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see at.fhj.gaar.androidapp.appDsl.impl.BroadcastReceiverActionImpl
* @see at.fhj.gaar.androidapp.appDsl.impl.AppDslPackageImpl#getBroadcastReceiverAction()
* @generated
*/
EClass BROADCAST_RECEIVER_ACTION = eINSTANCE.getBroadcastReceiverAction();
/**
* The meta object literal for the '{@link at.fhj.gaar.androidapp.appDsl.impl.ActionShowToastImpl <em>Action Show Toast</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see at.fhj.gaar.androidapp.appDsl.impl.ActionShowToastImpl
* @see at.fhj.gaar.androidapp.appDsl.impl.AppDslPackageImpl#getActionShowToast()
* @generated
*/
EClass ACTION_SHOW_TOAST = eINSTANCE.getActionShowToast();
/**
* The meta object literal for the '<em><b>Toast Text</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute ACTION_SHOW_TOAST__TOAST_TEXT = eINSTANCE.getActionShowToast_ToastText();
/**
* The meta object literal for the '{@link at.fhj.gaar.androidapp.appDsl.impl.ActionStartActivityImpl <em>Action Start Activity</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see at.fhj.gaar.androidapp.appDsl.impl.ActionStartActivityImpl
* @see at.fhj.gaar.androidapp.appDsl.impl.AppDslPackageImpl#getActionStartActivity()
* @generated
*/
EClass ACTION_START_ACTIVITY = eINSTANCE.getActionStartActivity();
/**
* The meta object literal for the '<em><b>Activity</b></em>' reference feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EReference ACTION_START_ACTIVITY__ACTIVITY = eINSTANCE.getActionStartActivity_Activity();
/**
* The meta object literal for the '{@link at.fhj.gaar.androidapp.appDsl.impl.ActionStartServiceImpl <em>Action Start Service</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see at.fhj.gaar.androidapp.appDsl.impl.ActionStartServiceImpl
* @see at.fhj.gaar.androidapp.appDsl.impl.AppDslPackageImpl#getActionStartService()
* @generated
*/
EClass ACTION_START_SERVICE = eINSTANCE.getActionStartService();
/**
* The meta object literal for the '<em><b>Service</b></em>' reference feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EReference ACTION_START_SERVICE__SERVICE = eINSTANCE.getActionStartService_Service();
}
} //AppDslPackage
| 36.313022 | 172 | 0.656759 |
b92d47cc6028dafe4634075e6eee5f0874be7728 | 451 | class Solution {
public boolean XXX(TreeNode root, int targetSum) {
if(root == null) return false;
if(root.left == null && root.right == null) return root.val == targetSum;
return XXX(root.left, targetSum-root.val) || XXX(root.right, targetSum-root.val);
}
}
undefined
for (i = 0; i < document.getElementsByTagName("code").length; i++) { console.log(document.getElementsByTagName("code")[i].innerText); }
| 30.066667 | 139 | 0.643016 |
17e13864bd6e0a70497070a91caf27a449ded782 | 3,165 | /*
* Copyright 2017 Beate Ottenwälder
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.ottenwbe.homedisplay.images;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringRunner;
import java.awt.image.BufferedImage;
import static org.junit.Assert.*;
@RunWith(SpringRunner.class)
@SpringBootTest
@ActiveProfiles("test")
@TestPropertySource(
properties = {
"images.sync.init.enabled=false"
}
)
public class SynchronizationServiceTest {
@Autowired
SynchronizationService synchronizationService;
@Autowired
ImageRepository imageRepository;
@Test
public void synchronizationTest() throws InterruptedException {
//Given:
imageRepository.deleteAll(); //An empty repository
// path is set to /resources/images in application-test.yml
//When:
synchronizationService.synchronizeImages();
synchronizationService.waitForSynchronization();
//Then:
assertEquals(1, imageRepository.count());
}
@Test
public void duplicatedSynchronizationTest() throws InterruptedException {
//Given:
imageRepository.deleteAll(); //An empty repository
// path is set to /resources/images in application-test.yml
//When:
synchronizationService.synchronizeImages();
synchronizationService.waitForSynchronization();
synchronizationService.synchronizeImages();
synchronizationService.waitForSynchronization();
//Then:
assertEquals(1, imageRepository.count());
}
@Test
public void getRandomImageTest() throws InterruptedException {
//Given:
synchronizationService.synchronizeImages(); // test image loaded
synchronizationService.waitForSynchronization();
// path is set to /resources/images in application-test.yml
//When:
BufferedImage testImage = synchronizationService.getRandomImage();
//Then:
assertNotNull(testImage);
}
@Test
public void getRandomImageInEmptyDBTest() {
//Given:
imageRepository.deleteAll();
// path is set to /resources/images in application-test.yml
//When:
BufferedImage testImage = synchronizationService.getRandomImage();
//Then:
assertNull(testImage);
}
} | 33.315789 | 78 | 0.702054 |
abb4281c5e287e5c6cde182b39c032a6d6cf7788 | 264 | package PizzaShop.Repositories;
import PizzaShop.Entities.Item;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface ItemRepository extends JpaRepository<Item, Integer> {
}
| 24 | 70 | 0.844697 |
b0fe881df5dce5b04537ef6138217fa8b8e06fe4 | 3,074 | /*
* Apache License
* Version 2.0, January 2004
*
* Copyright 2018 北有风雪 (yongjie.teng@qq.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.soraka.admin.service.impl;
import com.soraka.admin.dao.DeptDAO;
import com.soraka.common.model.domain.DeptDO;
import com.soraka.common.model.dto.Page;
import com.soraka.admin.model.dto.QueryParam;
import com.soraka.admin.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.List;
/**
* @author yongjie.teng
* @date 2018/8/16
* @package com.soraka.admin.service.impl
*/
@Transactional(rollbackFor = {RuntimeException.class})
@Service
public class DeptServiceImpl implements DeptService {
@Autowired
private DeptDAO deptDAO;
/**
* 通过主键获取部门
*
* @param id 主键
* @return {@link DeptDO}
*/
@Transactional(readOnly = true, rollbackFor = {RuntimeException.class})
@Override
public DeptDO get(Long id) {
return deptDAO.get(id);
}
/**
* 查询部门列表页
*
* @param queryParam 查询参数
* @return {@link Page}
*/
@Transactional(readOnly = true, rollbackFor = {RuntimeException.class})
@Override
public Page findPage(QueryParam queryParam) {
Page page = new Page();
List<DeptDO> depts;
int total = deptDAO.count(queryParam);
page.setTotal(total);
if (total > 0) {
depts = deptDAO.find(queryParam);
page.setRows(depts);
} else {
page.setRows(new ArrayList<>());
}
return page;
}
/**
* 新增部门
*
* @param deptDO
* @return true 成功 false 失败
*/
@Override
public boolean save(DeptDO deptDO) {
return deptDAO.save(deptDO) > 0;
}
/**
* 更新部门
*
* @param deptDO
* @return true 成功 false 失败
*/
@Override
public boolean update(DeptDO deptDO) {
return deptDAO.update(deptDO) > 0;
}
/**
* 删除部门
*
* @param id 部门ID
* @return true 成功 false 失败
*/
@Override
public boolean delete(Long id) {
return deptDAO.delete(id) > 0;
}
/**
* 获取所有部门
*
* @return List<DeptDO>
*/
@Transactional(readOnly = true, rollbackFor = {RuntimeException.class})
@Override
public List<DeptDO> findAll() {
return deptDAO.find(new QueryParam());
}
}
| 24.99187 | 78 | 0.63175 |
41d17d932f864f5352dd952fdfc242c5440bf7b0 | 7,671 | /*
* 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.sling.sitemap.impl;
import com.google.common.collect.ImmutableSet;
import org.apache.sling.api.resource.LoginException;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.event.jobs.JobManager;
import org.apache.sling.serviceusermapping.ServiceUserMapped;
import org.apache.sling.sitemap.SitemapException;
import org.apache.sling.sitemap.SitemapService;
import org.apache.sling.sitemap.builder.Sitemap;
import org.apache.sling.sitemap.spi.generator.SitemapGenerator;
import org.apache.sling.testing.mock.jcr.MockJcr;
import org.apache.sling.testing.mock.sling.ResourceResolverType;
import org.apache.sling.testing.mock.sling.junit5.SlingContext;
import org.apache.sling.testing.mock.sling.junit5.SlingContextExtension;
import org.jetbrains.annotations.NotNull;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Answers;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import javax.jcr.Node;
import javax.jcr.Session;
import javax.jcr.query.Query;
import java.util.Collections;
import java.util.Set;
import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.Mockito.*;
@ExtendWith({SlingContextExtension.class, MockitoExtension.class})
class SitemapServiceImplSchedulingTest {
final SlingContext context = new SlingContext(ResourceResolverType.JCR_MOCK);
private final SitemapServiceImpl subject = new SitemapServiceImpl();
private final SitemapStorage storage = new SitemapStorage();
private final SitemapGeneratorManagerImpl generatorManager = new SitemapGeneratorManagerImpl();
private final SitemapServiceConfiguration sitemapServiceConfiguration = new SitemapServiceConfiguration();
@Mock
private ServiceUserMapped serviceUser;
@Mock(answer = Answers.RETURNS_DEEP_STUBS)
private JobManager jobManager;
private SitemapGenerator generator1 = new SitemapGenerator() {
@Override
public @NotNull Set<String> getNames(@NotNull Resource sitemapRoot) {
return Collections.singleton(SitemapService.DEFAULT_SITEMAP_NAME);
}
@Override
public void generate(@NotNull Resource sitemapRoot, @NotNull String name, @NotNull Sitemap sitemap, @NotNull SitemapGenerator.Context context) throws SitemapException {
fail();
}
};
private SitemapGenerator generator2 = new SitemapGenerator() {
@Override
public @NotNull Set<String> getNames(@NotNull Resource sitemapRoot) {
return ImmutableSet.of("foo");
}
@Override
public void generate(@NotNull Resource sitemapRoot, @NotNull String name, @NotNull Sitemap sitemap, @NotNull SitemapGenerator.Context context) throws SitemapException {
fail();
}
};
private Resource siteRoot;
private Resource micrositeRoot;
private SitemapScheduler schedulerWithGenerator1OnSite;
private SitemapScheduler schedulerWithGenerator2OnMicrosite;
@BeforeEach
void setup() throws LoginException {
siteRoot = context.create().resource("/content/site/de", Collections.singletonMap(
SitemapService.PROPERTY_SITEMAP_ROOT, Boolean.TRUE
));
micrositeRoot = context.create().resource("/content/microsite/de", Collections.singletonMap(
SitemapService.PROPERTY_SITEMAP_ROOT, Boolean.TRUE
));
context.registerService(ServiceUserMapped.class, serviceUser, "subServiceName", "sitemap-writer");
context.registerService(ServiceUserMapped.class, serviceUser, "subServiceName", "sitemap-reader");
context.registerService(SitemapGenerator.class, generator1);
context.registerService(SitemapGenerator.class, generator2);
context.registerService(JobManager.class, jobManager);
context.registerInjectActivateService(sitemapServiceConfiguration);
context.registerInjectActivateService(generatorManager);
context.registerInjectActivateService(storage);
context.registerInjectActivateService(subject);
schedulerWithGenerator1OnSite = context.registerInjectActivateService(spy(new SitemapScheduler()),
"searchPath", "/content/site"
);
schedulerWithGenerator2OnMicrosite = context.registerInjectActivateService(spy(new SitemapScheduler()),
"searchPath", "/content/microsite"
);
SitemapSchedulerTest.initResourceResolver(context, schedulerWithGenerator1OnSite, this::setupResourceResolver);
SitemapSchedulerTest.initResourceResolver(context, schedulerWithGenerator2OnMicrosite, this::setupResourceResolver);
}
private void setupResourceResolver(ResourceResolver resolver) {
MockJcr.setQueryResult(
resolver.adaptTo(Session.class),
"/jcr:root/content/site//*[@sling:sitemapRoot=true]" +
" option(index tag slingSitemaps)",
Query.XPATH,
Collections.singletonList(siteRoot.adaptTo(Node.class))
);
MockJcr.setQueryResult(
resolver.adaptTo(Session.class),
"/jcr:root/content/microsite//*[@sling:sitemapRoot=true]" +
" option(index tag slingSitemaps)",
Query.XPATH,
Collections.singletonList(micrositeRoot.adaptTo(Node.class))
);
}
@Test
void testAllSchedulersCalled() {
// when
subject.scheduleGeneration();
// then
verify(schedulerWithGenerator1OnSite, atLeastOnce()).addJob(any(), any());
verify(schedulerWithGenerator2OnMicrosite, atLeastOnce()).addJob(any(), any());
}
@Test
void testSchedulersCalledForName() {
// when
subject.scheduleGeneration("<default>");
// then
verify(schedulerWithGenerator1OnSite, atLeastOnce()).addJob(any(), eq("<default>"));
verify(schedulerWithGenerator2OnMicrosite, atLeastOnce()).addJob(any(), eq("<default>"));
}
@Test
void testSchedulersCalledForPath() {
// when
subject.scheduleGeneration(siteRoot);
// then
verify(schedulerWithGenerator1OnSite, atLeastOnce()).addJob(eq(siteRoot.getPath()), any());
verify(schedulerWithGenerator2OnMicrosite, never()).addJob(any(), any());
}
@Test
void testSchedulersCalledForPathAndName() {
// when
subject.scheduleGeneration(siteRoot, "foo");
subject.scheduleGeneration(micrositeRoot, "foo");
// then
verify(schedulerWithGenerator1OnSite, times(1)).addJob(siteRoot.getPath(),"foo");
verify(schedulerWithGenerator2OnMicrosite, times(1)).addJob(micrositeRoot.getPath(),"foo");
}
}
| 42.148352 | 176 | 0.721027 |
09f4fae163effbb374dae8570d790e98c406f2fb | 361 | package cn.iflags.Mall.service;
import cn.iflags.Mall.common.ServerResponse;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
/**
* 描述:
*
* @author Vincent Vic
* create 2020-02-17 20:30
*/
public interface IFileService {
ServerResponse upload(MultipartFile file, String path, String suffix);
}
| 20.055556 | 74 | 0.764543 |
1d6b5812eed5e89b3a048f582e5bae6877df91d8 | 2,774 | /*
* Copyright (c) 2015, 2018, Oracle and/or its affiliates. All rights reserved.
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*/
package micro.benchmarks;
import java.util.Random;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Warmup;
import org.openjdk.jmh.infra.Blackhole;
/**
* Benchmarks cost of Math intrinsics.
*/
public class MathFunctionBenchmark extends BenchmarkBase {
@State(Scope.Benchmark)
public static class ThreadState {
double[] data = randomDoubles(100);
double[] result = new double[100];
double k = data[0];
static double[] randomDoubles(int len) {
double[] data = new double[len];
Random r = new Random();
for (int i = 0; i < data.length; i++) {
data[i] = r.nextDouble();
}
return data;
}
}
@Benchmark
@Warmup(iterations = 5)
public void mathLog(ThreadState state) {
double[] data = state.data;
for (int i = 0; i < data.length; i++) {
double[] result = state.result;
result[i] = Math.log(data[i]);
}
}
@Benchmark
@Warmup(iterations = 5)
public void mathLog10(ThreadState state) {
double[] data = state.data;
for (int i = 0; i < data.length; i++) {
double[] result = state.result;
result[i] = Math.log10(data[i]);
}
}
@Benchmark
@Warmup(iterations = 5)
public void mathSin(ThreadState state) {
double[] data = state.data;
for (int i = 0; i < data.length; i++) {
double[] result = state.result;
result[i] = Math.sin(data[i]);
}
}
@Benchmark
@Warmup(iterations = 5)
public void mathCos(ThreadState state) {
double[] data = state.data;
for (int i = 0; i < data.length; i++) {
double[] result = state.result;
result[i] = Math.cos(data[i]);
}
}
@Benchmark
@Warmup(iterations = 5)
public void mathTan(ThreadState state) {
double[] data = state.data;
for (int i = 0; i < data.length; i++) {
double[] result = state.result;
result[i] = Math.tan(data[i]);
}
}
@Benchmark
@Warmup(iterations = 1)
public void mathSqrt(ThreadState state, Blackhole blackhole) {
blackhole.consume(Math.sqrt(state.k));
}
@Benchmark
@Warmup(iterations = 1)
public void strictMathSqrt(ThreadState state, Blackhole blackhole) {
blackhole.consume(StrictMath.sqrt(state.k));
}
}
| 23.508475 | 79 | 0.566691 |
727a5b1ee8e5fe26d3eb0db67196bfcc0b45b452 | 9,596 | /*
* Copyright The Apache Software Foundation
*
* 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.flink.addons.hbase;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.logging.impl.Log4JLogger;
import org.apache.flink.util.TestLogger;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.HBaseTestingUtility;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HConstants;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.MasterNotRunningException;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.ZooKeeperConnectionException;
import org.apache.hadoop.hbase.client.HBaseAdmin;
import org.apache.hadoop.hbase.client.HTable;
import org.apache.hadoop.hbase.client.ScannerCallable;
import org.apache.hadoop.hbase.ipc.AbstractRpcClient;
import org.apache.hadoop.hbase.ipc.RpcServer;
import org.apache.log4j.Level;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* By using this class as the super class of a set of tests you will have a HBase testing
* cluster available that is very suitable for writing tests for scanning and filtering against.
* This is usable by any downstream application because the HBase cluster is 'injected' because
* a dynamically generated hbase-site.xml is added to the classpath.
* Because of this classpath manipulation it is not possible to start a second testing cluster in the same JVM.
* So if you have this you should either put all hbase related tests in a single class or force surefire to
* setup a new JVM for each testclass.
* See: http://maven.apache.org/surefire/maven-surefire-plugin/examples/fork-options-and-parallel-execution.html
*/
//
// NOTE: The code in this file is based on code from the
// Apache HBase project, licensed under the Apache License v 2.0
//
// https://github.com/apache/hbase/blob/master/hbase-server/src/test/java/org/apache/hadoop/hbase/filter/FilterTestingCluster.java
//
public class HBaseTestingClusterAutostarter extends TestLogger implements Serializable {
private static final Log LOG = LogFactory.getLog(HBaseTestingClusterAutostarter.class);
private static final HBaseTestingUtility TEST_UTIL = new HBaseTestingUtility();
private static HBaseAdmin admin = null;
private static List<TableName> createdTables = new ArrayList<>();
private static boolean alreadyRegisteredTestCluster = false;
private static Configuration conf;
protected static void createTable(TableName tableName, byte[][] columnFamilyName, byte[][] splitKeys) {
LOG.info("HBase minicluster: Creating table " + tableName.getNameAsString());
assertNotNull("HBaseAdmin is not initialized successfully.", admin);
HTableDescriptor desc = new HTableDescriptor(tableName);
for(byte[] fam : columnFamilyName) {
HColumnDescriptor colDef = new HColumnDescriptor(fam);
desc.addFamily(colDef);
}
try {
admin.createTable(desc, splitKeys);
createdTables.add(tableName);
assertTrue("Fail to create the table", admin.tableExists(tableName));
} catch (IOException e) {
assertNull("Exception found while creating table", e);
}
}
protected static HTable openTable(TableName tableName) throws IOException {
HTable table = (HTable) admin.getConnection().getTable(tableName);
assertTrue("Fail to create the table", admin.tableExists(tableName));
return table;
}
private static void deleteTables() {
if (admin != null) {
for (TableName tableName : createdTables) {
try {
if (admin.tableExists(tableName)) {
admin.disableTable(tableName);
admin.deleteTable(tableName);
}
} catch (IOException e) {
assertNull("Exception found deleting the table", e);
}
}
}
}
private static Configuration initialize(Configuration conf) {
conf = HBaseConfiguration.create(conf);
conf.setInt(HConstants.HBASE_CLIENT_RETRIES_NUMBER, 1);
try {
admin = TEST_UTIL.getHBaseAdmin();
} catch (MasterNotRunningException e) {
assertNull("Master is not running", e);
} catch (ZooKeeperConnectionException e) {
assertNull("Cannot connect to ZooKeeper", e);
} catch (IOException e) {
assertNull("IOException", e);
}
return conf;
}
@BeforeClass
public static void setUp() throws Exception {
LOG.info("HBase minicluster: Starting");
((Log4JLogger) RpcServer.LOG).getLogger().setLevel(Level.ALL);
((Log4JLogger) AbstractRpcClient.LOG).getLogger().setLevel(Level.ALL);
((Log4JLogger) ScannerCallable.LOG).getLogger().setLevel(Level.ALL);
TEST_UTIL.startMiniCluster(1);
// https://issues.apache.org/jira/browse/HBASE-11711
TEST_UTIL.getConfiguration().setInt("hbase.master.info.port", -1);
// Make sure the zookeeper quorum value contains the right port number (varies per run).
TEST_UTIL.getConfiguration().set("hbase.zookeeper.quorum", "localhost:" + TEST_UTIL.getZkCluster().getClientPort());
conf = initialize(TEST_UTIL.getConfiguration());
LOG.info("HBase minicluster: Running");
}
private static File hbaseSiteXmlDirectory;
private static File hbaseSiteXmlFile;
/**
* This dynamically generates a hbase-site.xml file that is added to the classpath.
* This way this HBaseMinicluster can be used by an unmodified application.
* The downside is that this cannot be 'unloaded' so you can have only one per JVM.
*/
public static void registerHBaseMiniClusterInClasspath() {
if (alreadyRegisteredTestCluster) {
fail("You CANNOT register a second HBase Testing cluster in the classpath of the SAME JVM");
}
File baseDir = new File(System.getProperty("java.io.tmpdir", "/tmp/"));
hbaseSiteXmlDirectory = new File(baseDir, "unittest-hbase-minicluster-" + Math.abs(new Random().nextLong()) + "/");
if (!hbaseSiteXmlDirectory.mkdirs()) {
fail("Unable to create output directory " + hbaseSiteXmlDirectory + " for the HBase minicluster");
}
assertNotNull("The ZooKeeper for the HBase minicluster is missing", TEST_UTIL.getZkCluster());
createHBaseSiteXml(hbaseSiteXmlDirectory, TEST_UTIL.getConfiguration().get("hbase.zookeeper.quorum"));
addDirectoryToClassPath(hbaseSiteXmlDirectory);
// Avoid starting it again.
alreadyRegisteredTestCluster = true;
}
public static Configuration getConf() {
return conf;
}
private static void createHBaseSiteXml(File hbaseSiteXmlDirectory, String zookeeperQuorum) {
hbaseSiteXmlFile = new File(hbaseSiteXmlDirectory, "hbase-site.xml");
// Create the hbase-site.xml file for this run.
try {
String hbaseSiteXml = "<?xml version=\"1.0\"?>\n" +
"<?xml-stylesheet type=\"text/xsl\" href=\"configuration.xsl\"?>\n" +
"<configuration>\n" +
" <property>\n" +
" <name>hbase.zookeeper.quorum</name>\n" +
" <value>" + zookeeperQuorum + "</value>\n" +
" </property>\n" +
"</configuration>";
OutputStream fos = new FileOutputStream(hbaseSiteXmlFile);
fos.write(hbaseSiteXml.getBytes(StandardCharsets.UTF_8));
fos.close();
} catch (IOException e) {
fail("Unable to create " + hbaseSiteXmlFile);
}
}
private static void addDirectoryToClassPath(File directory) {
try {
// Get the classloader actually used by HBaseConfiguration
ClassLoader classLoader = HBaseConfiguration.create().getClassLoader();
if (!(classLoader instanceof URLClassLoader)) {
fail("We should get a URLClassLoader");
}
// Make the addURL method accessible
Method method = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
method.setAccessible(true);
// Add the directory where we put the hbase-site.xml to the classpath
method.invoke(classLoader, directory.toURI().toURL());
} catch (MalformedURLException | NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
fail("Unable to add " + directory + " to classpath because of this exception: " + e.getMessage());
}
}
@AfterClass
public static void tearDown() throws Exception {
LOG.info("HBase minicluster: Shutting down");
deleteTables();
hbaseSiteXmlFile.delete();
hbaseSiteXmlDirectory.delete();
TEST_UTIL.shutdownMiniCluster();
LOG.info("HBase minicluster: Down");
}
}
| 38.693548 | 130 | 0.755732 |
f429cbed3364dc0cbbc2ae3c5017d6e819acb359 | 2,469 | package com.xiongxh.baking_app;
import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.action.ViewActions.click;
import static android.support.test.espresso.intent.Intents.intended;
import static android.support.test.espresso.intent.Intents.intending;
import static android.support.test.espresso.intent.matcher.IntentMatchers.hasComponent;
import static android.support.test.espresso.intent.matcher.IntentMatchers.isInternal;
import static org.hamcrest.Matchers.not;
import android.app.Activity;
import android.app.Instrumentation;
import android.support.test.espresso.Espresso;
import android.support.test.espresso.IdlingResource;
import android.support.test.espresso.contrib.RecyclerViewActions;
import android.support.test.espresso.intent.rule.IntentsTestRule;
import android.support.test.espresso.matcher.ViewMatchers;
import android.support.test.filters.LargeTest;
import android.support.test.runner.AndroidJUnit4;
import com.xiongxh.baking_app.recipes.RecipesActivity;
import com.xiongxh.baking_app.recipesteps.RecipeStepsActivity;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
@RunWith(AndroidJUnit4.class)
@LargeTest
public class RecipesActivityIntentTest {
@Rule
public IntentsTestRule<RecipesActivity> mIntentsTestRule =
new IntentsTestRule<>(RecipesActivity.class);
private IdlingResource idlingResource;
@Before
public void registerIdlingResource() {
idlingResource = mIntentsTestRule.getActivity().getIdlingResource();
Espresso.registerIdlingResources(idlingResource);
}
@Before
public void stubAllExternalIntents(){
intending(not(isInternal()))
.respondWith(new Instrumentation.ActivityResult(Activity.RESULT_OK, null));
}
@Test
public void onClickRecipeDetailActivity_checkIntent(){
onView(ViewMatchers.withId(R.id.rv_list_recipe))
.perform(RecyclerViewActions.actionOnItemAtPosition(0, click()));
onView(ViewMatchers.withId(R.id.rv_steps_recipe))
.perform(RecyclerViewActions.actionOnItemAtPosition(0, click()));
intended(hasComponent(RecipeStepsActivity.class.getName()));
}
@After
public void unregisterIdlingResource() {
if (idlingResource != null) {
Espresso.unregisterIdlingResources(idlingResource);
}
}
}
| 35.271429 | 91 | 0.771567 |
f739c15458c268896841ffa2c15c807d64236635 | 703 | package Atom.Annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MethodFuzzer {
byte maxByte() default Byte.MAX_VALUE;
byte minByte() default Byte.MIN_VALUE;
long maxLong() default Long.MAX_VALUE;
long minLong() default Long.MIN_VALUE;
int maxInteger() default Integer.MAX_VALUE;
int minInteger() default Integer.MIN_VALUE;
int minString() default 5;
int maxString() default 20;
boolean skip() default false;
}
| 21.96875 | 47 | 0.709815 |
ee17da87f106495377af99dbd6abce5a11534a2f | 1,655 | // $Id: BrickViewerEditor.java,v 1.1 2007/06/17 15:34:38 jim Exp $
package us.temerity.pipeline.plugin.BrickViewerEditor.v2_0_9;
import us.temerity.pipeline.*;
/*------------------------------------------------------------------------------------------*/
/* B R I C K V I E W E R E D I T O R */
/*------------------------------------------------------------------------------------------*/
/**
* Interactive viewer for examining Pixar's brick map format. <P>
*
* See the <A href="https://renderman.pixar.com/products/tools/rps.html">RenderMan
* ProServer</A> documentation for details about <B>brickviewer</B>(1). <P>
*/
public
class BrickViewerEditor
extends BaseEditor
{
/*----------------------------------------------------------------------------------------*/
/* C O N S T R U C T O R */
/*----------------------------------------------------------------------------------------*/
public
BrickViewerEditor()
{
super("BrickViewer", new VersionID("2.0.9"), "Temerity",
"Interactive viewer for examining Pixar's brick map file format.",
"brickviewer");
addSupport(OsType.Windows);
addSupport(OsType.MacOS);
}
/*----------------------------------------------------------------------------------------*/
/* S T A T I C I N T E R N A L S */
/*----------------------------------------------------------------------------------------*/
private static final long serialVersionUID = 1795580258226892536L;
}
| 35.978261 | 94 | 0.365559 |
327870c75759f1b47ced94af8b31e37fceec4b53 | 6,546 | package com.desmond.squarecamera;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import java.util.ArrayList;
import java.util.Arrays;
public class RuntimePermissionActivity extends AppCompatActivity {
public static final String REQUESTED_PERMISSION = "requested_permission";
private static final int REQUEST_CODE = 1;
public static void startActivity(@NonNull final Fragment fragment,
final int requestCode,
@NonNull final String requestedPermission,
final String... permissions) {
final Intent intent = new Intent(fragment.getActivity(), RuntimePermissionActivity.class);
final int capacity = 1 + (permissions != null ? permissions.length : 0);
final ArrayList<String> requestedPermissions = new ArrayList<>(capacity);
requestedPermissions.add(requestedPermission);
if (permissions != null) {
requestedPermissions.addAll(Arrays.asList(permissions));
}
intent.putStringArrayListExtra(REQUESTED_PERMISSION, requestedPermissions);
fragment.startActivityForResult(intent, requestCode);
}
/* https://code.google.com/p/android-developer-preview/issues/detail?id=2353 */
@Override
protected void onStart() {
super.onStart();
setVisible(true);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final ArrayList<String> reqPermissions = getIntent().getStringArrayListExtra(REQUESTED_PERMISSION);
final ArrayList<String> permissionsNeeded = getPermissionNeeded(reqPermissions);
final ArrayList<String> permissionRationaleNeeded = getPermissionRationaleNeeded(permissionsNeeded);
if (!permissionRationaleNeeded.isEmpty()) {
String message = getString(R.string.squarecamera__request_write_storage_permission_text);
for (int i = 1; i < permissionRationaleNeeded.size(); ++i) {
message += ", " + permissionRationaleNeeded.get(i);
}
showPermissionRationaleDialog(message, permissionsNeeded.toArray(new String[permissionsNeeded.size()]));
} else if (!permissionsNeeded.isEmpty()) {
requestForPermission(permissionsNeeded.toArray(new String[permissionsNeeded.size()]));
} else {
sendResult(true);
}
}
private ArrayList<String> getPermissionNeeded(@NonNull final ArrayList<String> reqPermissions) {
final ArrayList<String> permissionNeeded = new ArrayList<>(reqPermissions.size());
for (String reqPermission : reqPermissions) {
if (ContextCompat.checkSelfPermission(RuntimePermissionActivity.this, reqPermission)
!= PackageManager.PERMISSION_GRANTED) {
permissionNeeded.add(reqPermission);
}
}
return permissionNeeded;
}
private ArrayList<String> getPermissionRationaleNeeded(@NonNull final ArrayList<String> permissionsNeeded) {
final ArrayList<String> rationaleNeeded = new ArrayList<>(permissionsNeeded.size());
for (String permissionNeeded : permissionsNeeded) {
if (ActivityCompat.shouldShowRequestPermissionRationale(
RuntimePermissionActivity.this, permissionNeeded)) {
rationaleNeeded.add(permissionNeeded);
}
}
return rationaleNeeded;
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
switch (requestCode) {
case REQUEST_CODE:
final int numOfRequest = grantResults.length;
boolean isGranted = true;
for (int i = 0; i < numOfRequest; i++) {
if (PackageManager.PERMISSION_GRANTED != grantResults[i]) {
isGranted = false;
break;
}
}
sendResult(isGranted);
break;
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
private void showPermissionRationaleDialog(final String message, final String[] permissions) {
new AlertDialog.Builder(RuntimePermissionActivity.this)
.setMessage(message)
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
RuntimePermissionActivity.this.requestForPermission(permissions);
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
RuntimePermissionActivity.this.sendResult(false);
}
})
.setOnCancelListener(new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
RuntimePermissionActivity.this.sendResult(false);
}
})
.setOnDismissListener(new DialogInterface.OnDismissListener() {
@Override
public void onDismiss(DialogInterface dialog) {
RuntimePermissionActivity.this.sendResult(false);
}
})
.create()
.show();
}
private void requestForPermission(final String[] permissions) {
ActivityCompat.requestPermissions(RuntimePermissionActivity.this, permissions, REQUEST_CODE);
}
private void sendResult(final boolean isPermissionGranted) {
final Intent resultIntent = new Intent();
resultIntent.putExtra(REQUESTED_PERMISSION, isPermissionGranted);
setResult(Activity.RESULT_OK, resultIntent);
finish();
}
}
| 41.169811 | 121 | 0.635808 |
9c4d18731460afa471a14fd060dbb47f40af7bd8 | 4,986 | /**
* Copyright (C) 2008-2010 Matt Gumbley, DevZendo.org <http://devzendo.org>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.devzendo.minimiser.gui.wizard;
import java.awt.Dimension;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import javax.imageio.ImageIO;
import javax.swing.JFileChooser;
import javax.swing.JPanel;
import javax.swing.UIManager;
import org.apache.log4j.Logger;
import org.devzendo.minimiser.prefs.MiniMiserPrefs;
import org.netbeans.spi.wizard.WizardPage;
/**
* A Wizard Page of the largest size we use - that's big enough to contain a
* JFileChooser.
*
* @author matt
*
*/
public abstract class MiniMiserWizardPage extends WizardPage {
private static final long serialVersionUID = 8120003372114550270L;
private static final Logger LOGGER = Logger.getLogger(MiniMiserWizardPage.class);
private static Dimension pageDimension = null;
/**
* Construct the common wizard page
*/
public MiniMiserWizardPage() {
//getPanelDimension();
}
/**
* Set the left-hend graphic
*/
public static void setLHGraphic() {
final String key = "wizard.sidebar.image";
final InputStream resourceAsStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("WizardCoinsVeryLightGrey.jpg");
BufferedImage image;
try {
image = ImageIO.read(resourceAsStream);
UIManager.put(key, image);
try {
resourceAsStream.close();
} catch (final IOException e) {
}
} catch (final IOException e) {
LOGGER.warn("Couldn't read coins image: " + e.getMessage(), e);
}
}
/**
* @return a panel big enough to hold a JFileChooser, our largest component
*/
public final JPanel createNicelySizedPanel() {
final JPanel panel = new JPanel();
panel.setPreferredSize(pageDimension);
return panel;
}
/**
* Return the dimensions of the usual wizard page, calculating and storing
* these if they haven't been determined and stored before.
* @param prefs the prefs, to store the dimension in, for future runs
* @return the dimension of the panel
*/
public static Dimension getPanelDimension(final MiniMiserPrefs prefs) {
synchronized (MiniMiserWizardPage.class) {
if (pageDimension == null) {
final String wizardPanelSize = prefs.getWizardPanelSize();
if (wizardPanelSize.equals("")) {
LOGGER.debug("Wizard panel size is not yet stored; computing it");
final JPanel panel = new JPanel();
final JFileChooser fileChooser = new JFileChooser(getTempDir());
fileChooser.validate();
panel.add(fileChooser);
panel.validate();
pageDimension = panel.getPreferredSize();
final String size = String.format("%d,%d", pageDimension.width, pageDimension.height);
LOGGER.debug("Storing the wizard panel size as '" + size + "'");
prefs.setWizardPanelSize(size);
} else {
LOGGER.debug("Wizard panel size is stored as '" + wizardPanelSize + "'");
final String[] geomNumStrs = wizardPanelSize.split(",");
final int[] geomNums = new int[geomNumStrs.length];
for (int i = 0; i < geomNumStrs.length; i++) {
geomNums[i] = Integer.parseInt(geomNumStrs[i]);
}
pageDimension = new Dimension(geomNums[0], geomNums[1]);
}
}
return pageDimension;
}
}
@SuppressWarnings("finally")
private static String getTempDir() {
String tempDir = null;
try {
final File tempFile = File.createTempFile("minimiser", ".tmp");
tempDir = tempFile.getParent();
tempFile.deleteOnExit();
tempFile.delete();
LOGGER.info("temp dir is " + tempDir);
} catch (final IOException ioe) {
// nop
} finally {
return tempDir;
}
}
}
| 37.488722 | 145 | 0.598476 |
67a3cb41a8d5f0b147dfd0209a9d9dfeba9cefda | 5,199 |
package com.linkedin.restli.examples.groups.client;
import java.util.EnumSet;
import java.util.HashMap;
import javax.annotation.Generated;
import com.linkedin.data.template.DynamicRecordMetadata;
import com.linkedin.restli.client.OptionsRequestBuilder;
import com.linkedin.restli.client.RestliRequestOptions;
import com.linkedin.restli.client.base.BuilderBase;
import com.linkedin.restli.common.ComplexResourceKey;
import com.linkedin.restli.common.ResourceMethod;
import com.linkedin.restli.common.ResourceSpec;
import com.linkedin.restli.common.ResourceSpecImpl;
import com.linkedin.restli.examples.groups.api.ComplexKeyGroupMembership;
import com.linkedin.restli.examples.groups.api.GroupMembershipKey;
import com.linkedin.restli.examples.groups.api.GroupMembershipParam;
/**
* generated from: com.linkedin.restli.examples.groups.server.rest.impl.GroupMembershipsResource3
*
*/
@Generated(value = "com.linkedin.pegasus.generator.JavaCodeUtil", comments = "Rest.li Request Builder. Generated from /Users/jodzga/dev/pegasus_trunk/pegasus/restli-int-test-api/src/main/idl/com.linkedin.restli.examples.groups.client.groupMembershipsComplex.restspec.json.", date = "Thu Mar 31 14:16:24 PDT 2016")
public class GroupMembershipsComplexRequestBuilders
extends BuilderBase
{
private final static String ORIGINAL_RESOURCE_PATH = "groupMembershipsComplex";
private final static ResourceSpec _resourceSpec;
static {
HashMap<String, DynamicRecordMetadata> requestMetadataMap = new HashMap<String, DynamicRecordMetadata>();
HashMap<String, DynamicRecordMetadata> responseMetadataMap = new HashMap<String, DynamicRecordMetadata>();
HashMap<String, com.linkedin.restli.common.CompoundKey.TypeInfo> keyParts = new HashMap<String, com.linkedin.restli.common.CompoundKey.TypeInfo>();
_resourceSpec = new ResourceSpecImpl(EnumSet.of(ResourceMethod.GET, ResourceMethod.BATCH_GET, ResourceMethod.CREATE, ResourceMethod.BATCH_CREATE, ResourceMethod.PARTIAL_UPDATE, ResourceMethod.UPDATE, ResourceMethod.BATCH_UPDATE, ResourceMethod.DELETE, ResourceMethod.BATCH_PARTIAL_UPDATE, ResourceMethod.BATCH_DELETE), requestMetadataMap, responseMetadataMap, ComplexResourceKey.class, GroupMembershipKey.class, GroupMembershipParam.class, ComplexKeyGroupMembership.class, keyParts);
}
public GroupMembershipsComplexRequestBuilders() {
this(RestliRequestOptions.DEFAULT_OPTIONS);
}
public GroupMembershipsComplexRequestBuilders(RestliRequestOptions requestOptions) {
super(ORIGINAL_RESOURCE_PATH, requestOptions);
}
public GroupMembershipsComplexRequestBuilders(String primaryResourceName) {
this(primaryResourceName, RestliRequestOptions.DEFAULT_OPTIONS);
}
public GroupMembershipsComplexRequestBuilders(String primaryResourceName, RestliRequestOptions requestOptions) {
super(primaryResourceName, requestOptions);
}
public static String getPrimaryResource() {
return ORIGINAL_RESOURCE_PATH;
}
public OptionsRequestBuilder options() {
return new OptionsRequestBuilder(getBaseUriTemplate(), getRequestOptions());
}
public GroupMembershipsComplexBatchGetRequestBuilder batchGet() {
return new GroupMembershipsComplexBatchGetRequestBuilder(getBaseUriTemplate(), _resourceSpec, getRequestOptions());
}
public GroupMembershipsComplexBatchUpdateRequestBuilder batchUpdate() {
return new GroupMembershipsComplexBatchUpdateRequestBuilder(getBaseUriTemplate(), _resourceSpec, getRequestOptions());
}
public GroupMembershipsComplexBatchDeleteRequestBuilder batchDelete() {
return new GroupMembershipsComplexBatchDeleteRequestBuilder(getBaseUriTemplate(), _resourceSpec, getRequestOptions());
}
public GroupMembershipsComplexDeleteRequestBuilder delete() {
return new GroupMembershipsComplexDeleteRequestBuilder(getBaseUriTemplate(), _resourceSpec, getRequestOptions());
}
public GroupMembershipsComplexBatchCreateRequestBuilder batchCreate() {
return new GroupMembershipsComplexBatchCreateRequestBuilder(getBaseUriTemplate(), _resourceSpec, getRequestOptions());
}
public GroupMembershipsComplexCreateRequestBuilder create() {
return new GroupMembershipsComplexCreateRequestBuilder(getBaseUriTemplate(), _resourceSpec, getRequestOptions());
}
public GroupMembershipsComplexUpdateRequestBuilder update() {
return new GroupMembershipsComplexUpdateRequestBuilder(getBaseUriTemplate(), _resourceSpec, getRequestOptions());
}
public GroupMembershipsComplexGetRequestBuilder get() {
return new GroupMembershipsComplexGetRequestBuilder(getBaseUriTemplate(), _resourceSpec, getRequestOptions());
}
public GroupMembershipsComplexBatchPartialUpdateRequestBuilder batchPartialUpdate() {
return new GroupMembershipsComplexBatchPartialUpdateRequestBuilder(getBaseUriTemplate(), _resourceSpec, getRequestOptions());
}
public GroupMembershipsComplexPartialUpdateRequestBuilder partialUpdate() {
return new GroupMembershipsComplexPartialUpdateRequestBuilder(getBaseUriTemplate(), _resourceSpec, getRequestOptions());
}
}
| 49.990385 | 491 | 0.807078 |
67f2622e8fbf11d39edd0d8852261644d064dfb1 | 1,213 | import java.lang.System;
import java.lang.Math;
public class ArrayFunHouseTwo {
// goingUp() will return true if all numbers
// in numArray are in increasing order
// [1,2,6,9,23] returns true
// [9, 11, 13, 8] returns false
public static boolean goingUp(int[] numArray) {
for (int i = 0; i < numArray.length - 1; i++) {
if (!(numArray[i] < numArray[i + 1])) {
return false;
}
}
return true;
}
// goingDown() will return true if all numbers
// in numArray are in decreasing order
// [31,12,6,2,1] returns true
// [31, 20, 10, 15, 9] returns false
public static boolean goingDown(int[] numArray) {
for (int i = 0; i < numArray.length - 1; i++) {
if (numArray[i] < numArray[i + 1]) {
return false;
}
}
return true;
}
// getValuesBiggerThanX will return an array that contains
// count number of values that are larter than parameter x
// [1,2,3,4,5,6,7,8,9,10,11,6],3,5 would return [6,7,8]
public static int[] getCountValuesBiggerThanX(int[] numArray, int count, int x) {
int[] returnArray = new int[count];
int j = 0;
while (j < 3) {
for (int i : numArray) {
if (x < i) {
returnArray[j] = i;
j++;
}
}
}
return returnArray;
}
}
| 25.270833 | 82 | 0.619951 |
3ac6df990e556281b1823b42e1ed86c9f0d50458 | 889 | package com.ruoyi.project.module.perforer.service;
import com.ruoyi.project.module.perforer.domain.Perforer;
import java.util.List;
/**
* 演员 服务层
*
* @author ruoyi
* @date 2018-09-16
*/
public interface IPerforerService
{
/**
* 查询演员信息
*
* @param id 演员ID
* @return 演员信息
*/
public Perforer selectPerforerById(Long id);
/**
* 查询演员列表
*
* @param perforer 演员信息
* @return 演员集合
*/
public List<Perforer> selectPerforerList(Perforer perforer);
/**
* 新增演员
*
* @param perforer 演员信息
* @return 结果
*/
public int insertPerforer(Perforer perforer);
/**
* 修改演员
*
* @param perforer 演员信息
* @return 结果
*/
public int updatePerforer(Perforer perforer);
/**
* 删除演员信息
*
* @param ids 需要删除的数据ID
* @return 结果
*/
public int deletePerforerByIds(String ids);
}
| 16.163636 | 61 | 0.588301 |
2ac8b59072097911aa230f30a3ec7ccabb4234bc | 347 | package cn.com.warlock.wisp.router.rest.test.handler;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
@Path("/wisp")
public class EntryPointTestHandler {
@GET
@Path("get")
@Produces(MediaType.APPLICATION_JSON)
public String get() {
return "Test";
}
}
| 19.277778 | 53 | 0.691643 |
14c35a19710305093a2463159059729a95188f35 | 3,532 | /*
* Copyright (c) 2012-2014, John Campbell and other contributors. All rights reserved.
*
* This file is part of Tectonicus. It is subject to the license terms in the LICENSE file found in
* the top-level directory of this distribution. The full list of project contributors is contained
* in the AUTHORS file found in the same location.
*
*/
package tectonicus.cache.swap;
import java.io.File;
import java.io.FileFilter;
import java.util.ArrayList;
import java.util.Iterator;
import tectonicus.TileCoord;
public class HddTileListIterator implements Iterator<TileCoord>
{
private File[] xDirs;
private File[] yDirs;
private TileCoord[] tiles;
private int xPosition, yPosition, tilePosition;
private TileCoord next;
public HddTileListIterator(File baseDir)
{
xDirs = baseDir.listFiles( new DirectoryFilter() );
if (xDirs.length > 0)
yDirs = xDirs[0].listFiles( new DirectoryFilter() );
else
yDirs = new File[0] ;
if (yDirs.length > 0)
tiles = fetchTiles(yDirs[0]);
else
tiles = new TileCoord[0];
xPosition = 0;
yPosition = 0;
tilePosition = -1;
advance();
}
@Override
public boolean hasNext()
{
return next != null;
}
@Override
public TileCoord next()
{
if (!hasNext())
return null;
TileCoord actualNext = next;
advance();
return actualNext;
}
@Override
public void remove()
{
throw new RuntimeException("not implemented");
}
private void advance()
{
boolean finished = false;
// First try and find the next file in tileFiles
final boolean tileOk = advanceTile();
if (!tileOk)
{
// Finished in this tile dir? Advance the y dir
final boolean yOk = advanceYDir();
if (!yOk)
{
// Finished in the y dir? Advance the x dir
final boolean xOk = advanceXDir();
if (!xOk)
{
// Finished?
next = null;
finished = true;
}
if (!finished)
refreshYDir();
}
if (!finished)
{
refreshTiles();
advance();
}
}
}
private boolean advanceTile()
{
tilePosition++;
if (tiles == null || tiles.length <= tilePosition)
return false;
next = tiles[tilePosition];
return true;
}
private boolean advanceYDir()
{
yPosition++;
if (yDirs == null || yDirs.length <= yPosition)
return false;
return true;
}
private boolean advanceXDir()
{
xPosition++;
if (xDirs == null || xDirs.length <= xPosition)
return false;
return true;
}
private void refreshTiles()
{
// Refresh the tiles array
tiles = fetchTiles(yDirs[yPosition]);
tilePosition = -1;
}
private void refreshYDir()
{
// Refresh the y dir
yDirs = xDirs[xPosition].listFiles( new DirectoryFilter() );
yPosition = 0;
}
private static TileCoord[] fetchTiles(File dir)
{
File[] files = dir.listFiles( new TileCoordFilter() );
ArrayList<TileCoord> coords = new ArrayList<TileCoord>();
for (File f : files)
{
TileCoord coord = HddTileList.fileToTileCoord(f);
if (coord != null)
coords.add(coord);
}
return coords.toArray(new TileCoord[0]);
}
private static class DirectoryFilter implements FileFilter
{
@Override
public boolean accept(File pathname)
{
return pathname.isDirectory();
}
}
private static class TileCoordFilter implements FileFilter
{
@Override
public boolean accept(File pathname)
{
// TODO: More checking here - actually parse out tile coord
return pathname.isFile() && pathname.getName().endsWith(".tile");
}
}
}
| 18.300518 | 100 | 0.656569 |
e693843f3c37c519593a275a744da18a117dd8ee | 2,173 | /*
* 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.facebook.presto.type;
import com.facebook.presto.operator.scalar.AbstractTestFunctions;
import com.facebook.presto.spi.type.DecimalParseResult;
import com.facebook.presto.spi.type.Decimals;
import com.facebook.presto.spi.type.SqlDecimal;
import io.airlift.slice.Slice;
import java.math.BigInteger;
import static com.facebook.presto.spi.type.DecimalType.createDecimalType;
import static com.facebook.presto.spi.type.Decimals.MAX_PRECISION;
public abstract class AbstractTestDecimalFunctions
extends AbstractTestFunctions
{
protected void assertDecimalFunction(String statement, SqlDecimal expectedResult)
{
assertFunction(statement,
createDecimalType(expectedResult.getPrecision(), expectedResult.getScale()),
expectedResult);
}
protected SqlDecimal decimal(String decimalString)
{
DecimalParseResult parseResult = Decimals.parseIncludeLeadingZerosInPrecision(decimalString);
BigInteger unscaledValue;
if (parseResult.getType().isShort()) {
unscaledValue = BigInteger.valueOf((Long) parseResult.getObject());
}
else {
unscaledValue = Decimals.decodeUnscaledValue((Slice) parseResult.getObject());
}
return new SqlDecimal(unscaledValue, parseResult.getType().getPrecision(), parseResult.getType().getScale());
}
protected SqlDecimal maxPrecisionDecimal(long value)
{
final String maxPrecisionFormat = "%0" + (MAX_PRECISION + (value < 0 ? 1 : 0)) + "d";
return decimal(String.format(maxPrecisionFormat, value));
}
}
| 38.803571 | 117 | 0.729867 |
e9493ef8180f61b3c13b23266ef73730ca537eb9 | 8,788 | package org.codehaus.mojo.mrm.plugin;
/*
* Copyright 2011 Stephen Connolly
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import org.apache.maven.plugin.MojoExecutionException;
import org.codehaus.mojo.mrm.api.FileSystem;
import org.codehaus.mojo.mrm.servlet.FileSystemServlet;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import java.net.InetAddress;
import java.net.UnknownHostException;
/**
* A file system server.
*/
public class FileSystemServer
{
/**
* Guard for {@link #starting}, {@link #started}, {@link #finishing}, {@link #finished}, {@link #boundPort}
* and {@link #problem}.
*/
private final Object lock = new Object();
/**
* Flag to indicate that the thread is starting up.
* <p/>
* Guarded by {@link #lock}.
*/
private boolean starting = false;
/**
* Flag to indicate that the thread is ready to serve requests.
* <p/>
* Guarded by {@link #lock}.
*/
private boolean started = false;
/**
* Flag to indicate that the thread is terminated.
* <p/>
* Guarded by {@link #lock}.
*/
private boolean finished = false;
/**
* Flag to indicate that the thread should terminate.
* <p/>
* Guarded by {@link #lock}.
*/
private boolean finishing = false;
/**
* The port that the server is bound to.
* <p/>
* Guarded by {@link #lock}.
*/
private int boundPort = 0;
/**
* The port that the server is bound to.
* <p/>
* Guarded by {@link #lock}.
*/
private Exception problem = null;
/**
* The name of the file system (used to name the thread).
*/
private final String name;
/**
* The file system to serve.
*/
private final FileSystem fileSystem;
/**
* The port to try and serve on.
*/
private final int requestedPort;
/**
* The path to settingsFile containing the configuration to connect to this repository manager.
*/
private final String settingsServletPath;
/**
* Creates a new file system server that will serve a {@link FileSystem} over HTTP on the specified port.
*
* @param name The name of the file system server thread.
* @param port The port to server on or <code>0</code> to pick a random, but available, port.
* @param fileSystem the file system to serve.
*/
public FileSystemServer( String name, int port, FileSystem fileSystem, String settingsServletPath )
{
this.name = name;
this.fileSystem = fileSystem;
this.requestedPort = port;
this.settingsServletPath = settingsServletPath;
}
/**
* Ensures that the file system server is started (if already starting, will block until started, otherwise starts
* the file system server and blocks until started)
*
* @throws MojoExecutionException if the file system server could not be started.
*/
public void ensureStarted()
throws MojoExecutionException
{
synchronized ( lock )
{
if ( started || starting )
{
return;
}
starting = true;
started = false;
finished = false;
finishing = false;
}
Thread worker = new Thread( new Worker(), "FileSystemServer[" + name + "]" );
worker.setDaemon( true );
worker.start();
try
{
synchronized ( lock )
{
while ( starting && !started && !finished && !finishing )
{
lock.wait();
}
if ( problem != null )
{
throw problem;
}
}
}
catch ( Exception e )
{
throw new MojoExecutionException( e.getMessage(), e );
}
}
/**
* Returns <code>true</code> if and only if the file system server is finished.
*
* @return <code>true</code> if and only if the file system server is finished.
*/
public boolean isFinished()
{
synchronized ( lock )
{
return finished;
}
}
/**
* Returns <code>true</code> if and only if the file system server is started.
*
* @return <code>true</code> if and only if the file system server is started.
*/
public boolean isStarted()
{
synchronized ( lock )
{
return finished;
}
}
/**
* Signal the file system server to shut down.
*/
public void finish()
{
synchronized ( lock )
{
finishing = true;
lock.notifyAll();
}
}
/**
* Blocks until the file system server has actually shut down.
*
* @throws InterruptedException if interrupted.
*/
public void waitForFinished()
throws InterruptedException
{
synchronized ( lock )
{
while ( !finished )
{
lock.wait();
}
}
}
/**
* Gets the port that the file system server is/will server on.
*
* @return the port that the file system server is/will server on.
*/
public int getPort()
{
synchronized ( lock )
{
return started ? boundPort : requestedPort;
}
}
/**
* Gets the root url that the file system server is/will server on.
*
* @return the root url that the file system server is/will server on.
*/
public String getUrl()
{
return "http://localhost:" + getPort();
}
/**
* Same as {@link #getUrl()}, but now for remote users
*
* @return the scheme + raw IP address + port
* @throws UnknownHostException if the local host name could not be resolved into an address.
*/
public String getRemoteUrl() throws UnknownHostException
{
return "http://" + InetAddress.getLocalHost().getHostAddress() + ":" + getPort();
}
/**
* The work to monitor and control the Jetty instance that hosts the file system.
*/
private final class Worker
implements Runnable
{
/**
* {@inheritDoc}
*/
public void run()
{
try {
Server server = new Server(requestedPort);
try {
ServletContextHandler context = new ServletContextHandler();
context.setContextPath("/");
context.addServlet(new ServletHolder(new FileSystemServlet(fileSystem, settingsServletPath)), "/*");
server.setHandler(context);
server.start();
synchronized (lock) {
boundPort = ((ServerConnector)server.getConnectors()[0]).getLocalPort();
starting = false;
started = true;
lock.notifyAll();
}
} catch (Exception e) {
synchronized (lock) {
problem = e;
}
e.printStackTrace();
throw e;
}
synchronized (lock) {
while (!finishing) {
try {
lock.wait(500);
} catch (InterruptedException e) {
// ignore
}
}
}
server.stop();
server.join();
}
catch ( Exception e )
{
// ignore
}
finally
{
synchronized ( lock )
{
started = false;
starting = false;
finishing = false;
finished = true;
boundPort = 0;
lock.notifyAll();
}
}
}
}
}
| 27.810127 | 120 | 0.527765 |
368c6b28cf6cce10e3a454b9608e192dec983377 | 660 | package com.gemsrobotics.commands;
import com.gemsrobotics.subsystems.lift.Lift;
import edu.wpi.first.wpilibj.command.Command;
@SuppressWarnings("WeakerAccess")
public class LiftMovement extends Command {
private int m_runs;
private final Lift m_lift;
private final Lift.Position m_position;
public LiftMovement(
final Lift lift,
final Lift.Position position
) {
m_lift = lift;
m_position = position;
}
@Override
public void initialize() {
m_lift.setPosition(m_position);
m_runs = 0;
}
@Override
public void execute() {
m_runs++;
}
@Override
public boolean isFinished() {
return m_runs > 1 && m_lift.isAtSetpoint();
}
}
| 17.837838 | 45 | 0.731818 |
7e039e2c796de631222a3d4d5ef646c58f7d3558 | 432 | package io.beekeeper.gradle.security;
import org.cyclonedx.gradle.CycloneDxPlugin;
import org.gradle.api.Plugin;
import org.gradle.api.Project;
public class BeekeeperCycloneDxPlugin implements Plugin<Project> {
public static String IDENTIFIER = "io.beekeeper.gradle.plugins.security.cyclonedx";
@Override
public void apply(Project project) {
project.getPluginManager().apply(CycloneDxPlugin.class);
}
}
| 25.411765 | 87 | 0.768519 |
f7032f9690d63e82d76d3c7ad80522ee66f06471 | 2,634 | /**
* Copyright © 2018 The Lambico Datatest Team (lucio.benfante@gmail.com)
*
* This file is part of lambico-datatest-jpa.
*
* 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.lambico.datatest.example1;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
import java.util.Collection;
import org.junit.ClassRule;
import org.junit.Test;
import org.lambico.datatest.DataAggregator;
import org.lambico.datatest.annotation.TestData;
import org.lambico.datatest.example1.model.Entity1;
import org.lambico.datatest.example1.model.Entity2;
import org.lambico.datatest.junit.Dataset;
@TestData(resources = "org/lambico/datatest/example1/dataset/dataset.json")
public class InMemoryRuleTest {
@ClassRule
public static Dataset dataset = Dataset.builder().build();
@Test
public void testEntity1() {
DataAggregator dataAggregator = dataset.getDataAggregator();
Collection<?> entities1 = dataAggregator.getObjects().get("org.lambico.datatest.example1.model.Entity1");
Entity1 entity1 = ((Entity1)entities1.iterator().next());
assertEquals("test1", entity1.getStringField());
}
@Test
public void testEntity2() {
DataAggregator dataAggregator = dataset.getDataAggregator();
Collection<?> entities2 = dataAggregator.getObjects().get("org.lambico.datatest.example1.model.Entity2");
Entity2 entity2 = ((Entity2)entities2.iterator().next());
assertEquals("test2", entity2.getStringField());
}
@Test
public void testCircularReferences() {
DataAggregator dataAggregator = dataset.getDataAggregator();
Collection<?> entities1 = dataAggregator.getObjects().get("org.lambico.datatest.example1.model.Entity1");
Entity1 entity1 = ((Entity1)entities1.iterator().next());
Collection<?> entities2 = dataAggregator.getObjects().get("org.lambico.datatest.example1.model.Entity2");
Entity2 entity2 = ((Entity2)entities2.iterator().next());
assertSame(entity2, entity1.getEntity2());
assertSame(entity1, entity2.getEntity1());
}
}
| 39.313433 | 113 | 0.726651 |
dbb89e8541bca40575d440a04f264fd34a769edb | 2,672 | /*
* Copyright 2018 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.gradle.internal.execution.impl.steps;
import org.gradle.api.GradleException;
import org.gradle.api.InvalidUserDataException;
import org.gradle.internal.execution.Result;
import org.gradle.internal.execution.UnitOfWork;
import org.gradle.internal.execution.timeout.Timeout;
import org.gradle.internal.execution.timeout.TimeoutHandler;
import java.time.Duration;
import java.util.Optional;
public class TimeoutStep<C extends Context> implements Step<C, Result> {
private final TimeoutHandler timeoutHandler;
private final Step<? super C, ? extends Result> delegate;
public TimeoutStep(TimeoutHandler timeoutHandler, Step<? super C, ? extends Result> delegate) {
this.timeoutHandler = timeoutHandler;
this.delegate = delegate;
}
@Override
public Result execute(C context) {
UnitOfWork work = context.getWork();
Optional<Duration> timeoutProperty = work.getTimeout();
if (timeoutProperty.isPresent()) {
Duration timeout = timeoutProperty.get();
if (timeout.isNegative()) {
throw new InvalidUserDataException("Timeout of " + work.getDisplayName() + " must be positive, but was " + timeout.toString().substring(2));
}
return executeWithTimeout(context, timeout);
} else {
return executeWithoutTimeout(context);
}
}
private Result executeWithTimeout(C context, Duration timeout) {
Timeout taskTimeout = timeoutHandler.start(Thread.currentThread(), timeout);
try {
return executeWithoutTimeout(context);
} finally {
taskTimeout.stop();
if (taskTimeout.timedOut()) {
//noinspection ResultOfMethodCallIgnored
Thread.interrupted();
//noinspection ThrowFromFinallyBlock
throw new GradleException("Timeout has been exceeded");
}
}
}
private Result executeWithoutTimeout(C context) {
return delegate.execute(context);
}
}
| 37.111111 | 156 | 0.684506 |
6fdb6f852cc2927a3a96e9545255425d7041e729 | 1,867 | package be.stijnhooft.portal.recurringtasks.mappers.event;
import be.stijnhooft.portal.model.domain.Event;
import be.stijnhooft.portal.model.domain.FlowAction;
import be.stijnhooft.portal.recurringtasks.dtos.RecurringTaskDto;
import be.stijnhooft.portal.recurringtasks.mappers.Mapper;
import lombok.NonNull;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
@Component
public class ReminderEventMapper extends Mapper<RecurringTaskDto, Event> {
private final String deploymentName;
public ReminderEventMapper(@Value("${deployment-name}") String deploymentName) {
this.deploymentName = deploymentName;
}
@Override
public Event map(@NonNull RecurringTaskDto recurringTask) {
LocalDate lastExecution = recurringTask.getLastExecution();
LocalDate lastAcceptableDayOfExecution = lastExecution.plusDays(recurringTask.getMaxNumberOfDaysBetweenExecutions());
var isLastAcceptableDateOfExecution = LocalDate.now().isEqual(lastAcceptableDayOfExecution);
Map<String, String> data = new HashMap<>();
data.put("type", "reminder");
data.put("urgent", Boolean.toString(isLastAcceptableDateOfExecution));
data.put("task", recurringTask.getName());
data.put("lastExecution", recurringTask.getLastExecution().toString());
data.put("minDueDate", lastExecution.plusDays(recurringTask.getMinNumberOfDaysBetweenExecutions()).toString());
data.put("maxDueDate", lastAcceptableDayOfExecution.toString());
return new Event(deploymentName,
deploymentName + "-" + recurringTask.getId(),
FlowAction.START,
LocalDateTime.now(),
data);
}
}
| 40.586957 | 125 | 0.739154 |
e342994a7200e503a5fc0755a1074ec12700b89b | 1,840 | package com.itsmeyaw.werewolfbot.command;
import discord4j.common.util.Snowflake;
import discord4j.core.object.VoiceState;
import discord4j.core.object.entity.Guild;
import discord4j.core.object.entity.Member;
import discord4j.core.object.entity.Message;
import discord4j.core.object.entity.channel.VoiceChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Flux;
import java.util.Optional;
@Component
public class Mute implements Command{
private final Logger LOGGER = LoggerFactory.getLogger(Mute.class);
@Override
public String getCommand() {
return "mute";
}
@Override
public void execute(Message m) {
m.getAuthorAsMember().map(Member::getDisplayName).subscribe(name -> LOGGER.info(String.format("Mute received! [From:%s]", name)));
Optional<Snowflake> channel = m.getAuthorAsMember()
.flatMap(Member::getVoiceState)
.map(VoiceState::getChannelId)
.block();
if (channel != null) {
long snowflake = channel.get().asLong();
Flux.from(m.getGuild())
.flatMap(Guild::getMembers)
.filter(me -> me.getVoiceState()
.flatMap(VoiceState::getChannel)
.map(VoiceChannel::getId)
.map(e -> e.asLong() == snowflake)
.blockOptional()
.orElse(false))
.flatMap(me -> me.edit(g -> g.setMute(true)))
.subscribe();
} else {
m.getChannel()
.flatMap(c -> c.createMessage("You have to be connected to a voice channel!"))
.subscribe();
}
}
}
| 34.074074 | 138 | 0.589674 |
76a1761e65a1d9b6277af1801ea871c69f4ad408 | 1,003 | package GNM;
import Lattice.Maze;
import Lattice.Module;
import Search.*;
public class Main {
public static void main(String[] args) {
//P.seed=1;
//DebugTests.Random();
System.out.println("*****The simulation begins*****");
/*Maze ma = new Maze(10,10);
ma.showMaze();*/
/*Maze ma = new Maze(10,10, 5);
ma.showMaze();*/
Maze ma = new Maze(10, 10, 5, 0, 0, 5, 5);
ma.showMaze();
/*QLearning ql = new QLearning(ma);
ql.findPath();
ma.showMaze();
/*LRTA lrta = new LRTA(ma);
lrta.findPath();
ma.showMaze();*/
/* Backtrack bt = new Backtrack(ma);
bt.findPath();
ma.showMaze();*/
/*IDDFS iddfs = new IDDFS(ma);
iddfs.findPath();
ma.showMaze();*/
/**/
System.out.println();
Module mo = new Module(10);
GNMSearch hs = new GNMSearch(ma,mo,0);
hs.findPath();
ma.showMaze();
mo.showModule();
}
}
| 19.666667 | 62 | 0.512463 |
08f2ae3e55d2f418d99ea950a7acd0d902152010 | 2,902 | package com.anandsankritya.sikhoindia;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
/**
* A simple {@link Fragment} subclass.
*/
public class IOSFragment extends Fragment {
private ArrayList<VideoItemModel> videoItemModels;
private RecyclerView recyclerView;
private ArrayList<String> playListTitles;
public IOSFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
getActivity().setTitle("IOS Development");
View view = inflater.inflate(R.layout.fragment_ios, container, false);
recyclerView = view.findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
videoItemModels = new ArrayList<>();
playListTitles = new ArrayList<>();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
Query query = reference.orderByChild("category").equalTo("IOS");
query.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
// dataSnapshot returns all children with category General
videoItemModels.clear();
playListTitles.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
Video v = snapshot.getValue(Video.class);
if(!playListTitles.contains(v.getPlaylistTitle())){
playListTitles.add(v.getPlaylistTitle());
videoItemModels.add(new VideoItemModel(v.getVideoId(), v.getPlaylistTitle()));
}
}
VideoRecyclerViewAdapter adapter=new VideoRecyclerViewAdapter(videoItemModels, getActivity().getApplicationContext(), Common.API_KEY, Common.COURSE_GENERAL);
recyclerView.setAdapter(adapter);
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
return view;
}
}
| 33.744186 | 177 | 0.660234 |
869fd8f035f8f73afcc4c75fc8fba3a2e8cf5dde | 3,935 | package com.test.openvpn;
/* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 3.0.8
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
public class ClientAPI_ConnectionInfo {
private transient long swigCPtr;
protected transient boolean swigCMemOwn;
protected ClientAPI_ConnectionInfo(long cPtr, boolean cMemoryOwn) {
swigCMemOwn = cMemoryOwn;
swigCPtr = cPtr;
}
protected static long getCPtr(ClientAPI_ConnectionInfo obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
protected void finalize() {
delete();
}
public synchronized void delete() {
if (swigCPtr != 0) {
if (swigCMemOwn) {
swigCMemOwn = false;
ovpncliJNI.delete_ClientAPI_ConnectionInfo(swigCPtr);
}
swigCPtr = 0;
}
}
public void setDefined(boolean value) {
ovpncliJNI.ClientAPI_ConnectionInfo_defined_set(swigCPtr, this, value);
}
public boolean getDefined() {
return ovpncliJNI.ClientAPI_ConnectionInfo_defined_get(swigCPtr, this);
}
public void setUser(String value) {
ovpncliJNI.ClientAPI_ConnectionInfo_user_set(swigCPtr, this, value);
}
public String getUser() {
return ovpncliJNI.ClientAPI_ConnectionInfo_user_get(swigCPtr, this);
}
public void setServerHost(String value) {
ovpncliJNI.ClientAPI_ConnectionInfo_serverHost_set(swigCPtr, this, value);
}
public String getServerHost() {
return ovpncliJNI.ClientAPI_ConnectionInfo_serverHost_get(swigCPtr, this);
}
public void setServerPort(String value) {
ovpncliJNI.ClientAPI_ConnectionInfo_serverPort_set(swigCPtr, this, value);
}
public String getServerPort() {
return ovpncliJNI.ClientAPI_ConnectionInfo_serverPort_get(swigCPtr, this);
}
public void setServerProto(String value) {
ovpncliJNI.ClientAPI_ConnectionInfo_serverProto_set(swigCPtr, this, value);
}
public String getServerProto() {
return ovpncliJNI.ClientAPI_ConnectionInfo_serverProto_get(swigCPtr, this);
}
public void setServerIp(String value) {
ovpncliJNI.ClientAPI_ConnectionInfo_serverIp_set(swigCPtr, this, value);
}
public String getServerIp() {
return ovpncliJNI.ClientAPI_ConnectionInfo_serverIp_get(swigCPtr, this);
}
public void setVpnIp4(String value) {
ovpncliJNI.ClientAPI_ConnectionInfo_vpnIp4_set(swigCPtr, this, value);
}
public String getVpnIp4() {
return ovpncliJNI.ClientAPI_ConnectionInfo_vpnIp4_get(swigCPtr, this);
}
public void setVpnIp6(String value) {
ovpncliJNI.ClientAPI_ConnectionInfo_vpnIp6_set(swigCPtr, this, value);
}
public String getVpnIp6() {
return ovpncliJNI.ClientAPI_ConnectionInfo_vpnIp6_get(swigCPtr, this);
}
public void setGw4(String value) {
ovpncliJNI.ClientAPI_ConnectionInfo_gw4_set(swigCPtr, this, value);
}
public String getGw4() {
return ovpncliJNI.ClientAPI_ConnectionInfo_gw4_get(swigCPtr, this);
}
public void setGw6(String value) {
ovpncliJNI.ClientAPI_ConnectionInfo_gw6_set(swigCPtr, this, value);
}
public String getGw6() {
return ovpncliJNI.ClientAPI_ConnectionInfo_gw6_get(swigCPtr, this);
}
public void setClientIp(String value) {
ovpncliJNI.ClientAPI_ConnectionInfo_clientIp_set(swigCPtr, this, value);
}
public String getClientIp() {
return ovpncliJNI.ClientAPI_ConnectionInfo_clientIp_get(swigCPtr, this);
}
public void setTunName(String value) {
ovpncliJNI.ClientAPI_ConnectionInfo_tunName_set(swigCPtr, this, value);
}
public String getTunName() {
return ovpncliJNI.ClientAPI_ConnectionInfo_tunName_get(swigCPtr, this);
}
public ClientAPI_ConnectionInfo() {
this(ovpncliJNI.new_ClientAPI_ConnectionInfo(), true);
}
}
| 28.309353 | 83 | 0.71817 |
f6e39f4ea3ddfc05b859e5c2e9dc352764644a11 | 25,975 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.cosmos.benchmark;
import com.azure.cosmos.ConnectionMode;
import com.azure.cosmos.ConsistencyLevel;
import com.beust.jcommander.IStringConverter;
import com.beust.jcommander.Parameter;
import com.beust.jcommander.ParameterException;
import com.google.common.base.Strings;
import com.google.common.net.HostAndPort;
import com.google.common.net.PercentEscaper;
import io.micrometer.azuremonitor.AzureMonitorConfig;
import io.micrometer.azuremonitor.AzureMonitorMeterRegistry;
import io.micrometer.core.instrument.Clock;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.config.NamingConvention;
import io.micrometer.core.lang.Nullable;
import io.micrometer.graphite.GraphiteConfig;
import io.micrometer.graphite.GraphiteMeterRegistry;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import java.io.File;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Configuration {
public final static String DEFAULT_PARTITION_KEY_PATH = "/pk";
private final static int DEFAULT_GRAPHITE_SERVER_PORT = 2003;
private MeterRegistry azureMonitorMeterRegistry;
private MeterRegistry graphiteMeterRegistry;
@Parameter(names = "-serviceEndpoint", description = "Service Endpoint")
private String serviceEndpoint;
@Parameter(names = "-masterKey", description = "Master Key")
private String masterKey;
@Parameter(names = "-databaseId", description = "Database ID")
private String databaseId;
@Parameter(names = "-collectionId", description = "Collection ID")
private String collectionId;
@Parameter(names = "-useNameLink", description = "Use name Link")
private boolean useNameLink = false;
@Parameter(names = "-documentDataFieldSize", description = "Length of a document data field in characters (16-bit)")
private int documentDataFieldSize = 20;
@Parameter(names = "-documentDataFieldCount", description = "Number of data fields in document")
private int documentDataFieldCount = 5;
@Parameter(names = "-maxConnectionPoolSize", description = "Max Connection Pool Size")
private Integer maxConnectionPoolSize = 1000;
@Parameter(names = "-diagnosticsThresholdDuration", description = "Latency threshold for printing diagnostics", converter = DurationConverter.class)
private Duration diagnosticsThresholdDuration = Duration.ofSeconds(60);
@Parameter(names = "-disablePassingPartitionKeyAsOptionOnWrite", description = "Disables passing partition in request options for write operation;" +
" in this case, json will be parsed and partition key will be extracted (this requires more computational overhead).")
private boolean disablePassingPartitionKeyAsOptionOnWrite = false;
@Parameter(names = "-consistencyLevel", description = "Consistency Level", converter = ConsistencyLevelConverter.class)
private ConsistencyLevel consistencyLevel = ConsistencyLevel.SESSION;
@Parameter(names = "-connectionMode", description = "Connection Mode")
private ConnectionMode connectionMode = ConnectionMode.DIRECT;
@Parameter(names = "-graphiteEndpoint", description = "Graphite endpoint")
private String graphiteEndpoint;
@Parameter(names = "-enableJvmStats", description = "Enables JVM Stats")
private boolean enableJvmStats;
@Parameter(names = "-throughput", description = "provisioned throughput for test container")
private int throughput = 100000;
@Parameter(names = "-numberOfCollectionForCtl", description = "Number of collections for ctl load")
private int numberOfCollectionForCtl = 4;
@Parameter(names = "-readWriteQueryPct", description = "Comma separated read write query workload percent")
private String readWriteQueryPct = "90,9,1";
@Parameter(names = "-manageDatabase", description = "Control switch for creating/deleting underlying database resource")
private boolean manageDatabase = false;
@Parameter(names = "-preferredRegionsList", description = "Comma separated preferred regions list")
private String preferredRegionsList;
@Parameter(names = "-encryptedStringFieldCount", description = "Number of string field that need to be encrypted")
private int encryptedStringFieldCount = 1;
@Parameter(names = "-encryptedLongFieldCount", description = "Number of long field that need to be encrypted")
private int encryptedLongFieldCount = 0;
@Parameter(names = "-encryptedDoubleFieldCount", description = "Number of double field that need to be encrypted")
private int encryptedDoubleFieldCount = 0;
@Parameter(names = "-encryptionEnabled", description = "Control switch to enable the encryption operation")
private boolean encryptionEnabled = false;
@Parameter(names = "-operation", description = "Type of Workload:\n"
+ "\tReadThroughput- run a READ workload that prints only throughput *\n"
+ "\tReadThroughputWithMultipleClients - run a READ workload that prints throughput and latency for multiple client read.*\n"
+ "\tWriteThroughput - run a Write workload that prints only throughput\n"
+ "\tReadLatency - run a READ workload that prints both throughput and latency *\n"
+ "\tWriteLatency - run a Write workload that prints both throughput and latency\n"
+ "\tQueryInClauseParallel - run a 'Select * from c where c.pk in (....)' workload that prints latency\n"
+ "\tQueryCross - run a 'Select * from c where c._rid = SOME_RID' workload that prints throughput\n"
+ "\tQuerySingle - run a 'Select * from c where c.pk = SOME_PK' workload that prints throughput\n"
+ "\tQuerySingleMany - run a 'Select * from c where c.pk = \"pk\"' workload that prints throughput\n"
+ "\tQueryParallel - run a 'Select * from c' workload that prints throughput\n"
+ "\tQueryOrderby - run a 'Select * from c order by c._ts' workload that prints throughput\n"
+ "\tQueryAggregate - run a 'Select value max(c._ts) from c' workload that prints throughput\n"
+ "\tQueryAggregateTopOrderby - run a 'Select top 1 value count(c) from c order by c._ts' workload that prints throughput\n"
+ "\tQueryTopOrderby - run a 'Select top 1000 * from c order by c._ts' workload that prints throughput\n"
+ "\tMixed - runa workload of 90 reads, 9 writes and 1 QueryTopOrderby per 100 operations *\n"
+ "\tReadMyWrites - run a workflow of writes followed by reads and queries attempting to read the write.*\n"
+ "\tCtlWorkload - run a ctl workflow.*\n"
+ "\tReadAllItemsOfLogicalPartition - run a workload that uses readAllItems for a logical partition and prints throughput\n"
+ "\n\t* writes 10k documents initially, which are used in the reads"
+ "\tLinkedInCtlWorkload - ctl for LinkedIn workload.*\n",
converter = Operation.OperationTypeConverter.class)
private Operation operation = Operation.WriteThroughput;
@Parameter(names = "-concurrency", description = "Degree of Concurrency in Inserting Documents."
+ " If this value is not specified, the max connection pool size will be used as the concurrency level.")
private Integer concurrency;
@Parameter(names = "-numberOfOperations", description = "Total NUMBER Of Documents To Insert")
private int numberOfOperations = 100000;
static class DurationConverter implements IStringConverter<Duration> {
@Override
public Duration convert(String value) {
if (value == null) {
return null;
}
return Duration.parse(value);
}
}
@Parameter(names = "-maxRunningTimeDuration", description = "Max Running Time Duration", converter = DurationConverter.class)
private Duration maxRunningTimeDuration;
@Parameter(names = "-printingInterval", description = "Interval of time after which Metrics should be printed (seconds)")
private int printingInterval = 10;
@Parameter(names = "-reportingDirectory", description = "Location of a directory to which metrics should be printed as comma-separated values")
private String reportingDirectory = null;
@Parameter(names = "-numberOfPreCreatedDocuments", description = "Total NUMBER Of Documents To pre create for a read workload to use")
private int numberOfPreCreatedDocuments = 1000;
@Parameter(names = "-sparsityWaitTime", description = "Sleep time before making each request. Default is no sleep time."
+ " NOTE: For now only ReadLatency and ReadThroughput support this."
+ " Format: A string representation of this duration using ISO-8601 seconds based representation, such as "
+ "PT20.345S (20.345 seconds), PT15M (15 minutes)", converter = DurationConverter.class)
private Duration sparsityWaitTime = null;
@Parameter(names = "-skipWarmUpOperations", description = "the number of operations to be skipped before starting perf numbers.")
private int skipWarmUpOperations = 0;
@Parameter(names = "-useSync", description = "Uses Sync API")
private boolean useSync = false;
@Parameter(names = "-contentResponseOnWriteEnabled", description = "if set to false, does not returns content response on document write operations")
private String contentResponseOnWriteEnabled = String.valueOf(true);
@Parameter(names = "-bulkloadBatchSize", description = "Control the number of documents uploaded in each BulkExecutor load iteration (Only supported for the LinkedInCtlWorkload)")
private int bulkloadBatchSize = 200000;
@Parameter(names = "-testScenario", description = "The test scenario (GET, QUERY) for the LinkedInCtlWorkload")
private String testScenario = "GET";
@Parameter(names = "-accountNameInGraphiteReporter", description = "if set, account name with be appended in graphite reporter")
private boolean accountNameInGraphiteReporter = false;
public enum Environment {
Daily, // This is the CTL environment where we run the workload for a fixed number of hours
Staging; // This is the CTL environment where the worload runs as a long running job
static class EnvironmentConverter implements IStringConverter<Environment> {
@Override
public Environment convert(String value) {
if (value == null) {
return Environment.Daily;
}
return Environment.valueOf(value);
}
}
}
@Parameter(names = "-environment", description = "The CTL Environment we are validating the workload",
converter = Environment.EnvironmentConverter.class)
private Environment environment = Environment.Daily;
@Parameter(names = {"-h", "-help", "--help"}, description = "Help", help = true)
private boolean help = false;
public enum Operation {
ReadThroughput,
WriteThroughput,
ReadLatency,
WriteLatency,
QueryInClauseParallel,
QueryCross,
QuerySingle,
QuerySingleMany,
QueryParallel,
QueryOrderby,
QueryAggregate,
QueryAggregateTopOrderby,
QueryTopOrderby,
Mixed,
ReadMyWrites,
ReadThroughputWithMultipleClients,
CtlWorkload,
ReadAllItemsOfLogicalPartition,
LinkedInCtlWorkload;
static Operation fromString(String code) {
for (Operation output : Operation.values()) {
if (output.toString().equalsIgnoreCase(code)) {
return output;
}
}
return null;
}
static class OperationTypeConverter implements IStringConverter<Operation> {
/*
* (non-Javadoc)
*
* @see com.beust.jcommander.IStringConverter#convert(java.lang.STRING)
*/
@Override
public Operation convert(String value) {
Operation ret = fromString(value);
if (ret == null) {
throw new ParameterException("Value " + value + " can not be converted to ClientType. "
+ "Available values are: " + Arrays.toString(Operation.values()));
}
return ret;
}
}
}
private static ConsistencyLevel fromString(String code) {
for (ConsistencyLevel output : ConsistencyLevel.values()) {
if (output.toString().equalsIgnoreCase(code)) {
return output;
}
}
return null;
}
static class ConsistencyLevelConverter implements IStringConverter<ConsistencyLevel> {
/*
* (non-Javadoc)
*
* @see com.beust.jcommander.IStringConverter#convert(java.lang.STRING)
*/
@Override
public ConsistencyLevel convert(String value) {
ConsistencyLevel ret = fromString(value);
if (ret == null) {
throw new ParameterException("Value " + value + " can not be converted to ClientType. "
+ "Available values are: " + Arrays.toString(Operation.values()));
}
return ret;
}
}
public int getSkipWarmUpOperations() {
return skipWarmUpOperations;
}
public Duration getSparsityWaitTime() {
return sparsityWaitTime;
}
public boolean isDisablePassingPartitionKeyAsOptionOnWrite() {
return disablePassingPartitionKeyAsOptionOnWrite;
}
public boolean isSync() {
return useSync;
}
public boolean isAccountNameInGraphiteReporter() {
return accountNameInGraphiteReporter;
}
public Duration getMaxRunningTimeDuration() {
return maxRunningTimeDuration;
}
public Operation getOperationType() {
return operation;
}
public int getNumberOfOperations() {
return numberOfOperations;
}
public int getThroughput() {
return throughput;
}
public String getServiceEndpoint() {
return serviceEndpoint;
}
public String getMasterKey() {
return masterKey;
}
public boolean isHelp() {
return help;
}
public int getDocumentDataFieldSize() {
return documentDataFieldSize;
}
public int getDocumentDataFieldCount() {
return documentDataFieldCount;
}
public Integer getMaxConnectionPoolSize() {
return maxConnectionPoolSize;
}
public ConnectionMode getConnectionMode() {
return connectionMode;
}
public ConsistencyLevel getConsistencyLevel() {
return consistencyLevel;
}
public String isContentResponseOnWriteEnabled() {
return contentResponseOnWriteEnabled;
}
public String getDatabaseId() {
return databaseId;
}
public String getCollectionId() {
return collectionId;
}
public int getNumberOfPreCreatedDocuments() {
return numberOfPreCreatedDocuments;
}
public int getPrintingInterval() {
return printingInterval;
}
public Duration getDiagnosticsThresholdDuration() {
return diagnosticsThresholdDuration;
}
public File getReportingDirectory() {
return reportingDirectory == null ? null : new File(reportingDirectory);
}
public int getConcurrency() {
if (this.concurrency != null) {
return concurrency;
} else {
return this.maxConnectionPoolSize;
}
}
public boolean isUseNameLink() {
return useNameLink;
}
public boolean isEnableJvmStats() {
return enableJvmStats;
}
public MeterRegistry getAzureMonitorMeterRegistry() {
String instrumentationKey = System.getProperty("azure.cosmos.monitoring.azureMonitor.instrumentationKey",
StringUtils.defaultString(Strings.emptyToNull(
System.getenv().get("AZURE_INSTRUMENTATION_KEY")), null));
return instrumentationKey == null ? null : this.azureMonitorMeterRegistry(instrumentationKey);
}
public MeterRegistry getGraphiteMeterRegistry() {
String serviceAddress = System.getProperty("azure.cosmos.monitoring.graphite.serviceAddress",
StringUtils.defaultString(Strings.emptyToNull(
System.getenv().get("GRAPHITE_SERVICE_ADDRESS")), null));
return serviceAddress == null ? null : this.graphiteMeterRegistry(serviceAddress);
}
public String getGraphiteEndpoint() {
if (graphiteEndpoint == null) {
return null;
}
return StringUtils.substringBeforeLast(graphiteEndpoint, ":");
}
public int getGraphiteEndpointPort() {
if (graphiteEndpoint == null) {
return -1;
}
String portAsString = Strings.emptyToNull(StringUtils.substringAfterLast(graphiteEndpoint, ":"));
if (portAsString == null) {
return DEFAULT_GRAPHITE_SERVER_PORT;
} else {
return Integer.parseInt(portAsString);
}
}
public int getNumberOfCollectionForCtl(){
return this.numberOfCollectionForCtl;
}
public String getReadWriteQueryPct() {
return this.readWriteQueryPct;
}
public boolean shouldManageDatabase() {
return this.manageDatabase;
}
public int getBulkloadBatchSize() {
return this.bulkloadBatchSize;
}
public String getTestScenario() {
return this.testScenario;
}
public Environment getEnvironment() {
return this.environment;
}
public String toString() {
return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE);
}
public List<String> getPreferredRegionsList() {
List<String> preferredRegions = null;
if (StringUtils.isNotEmpty(preferredRegionsList)) {
String[] preferredArray = preferredRegionsList.split(",");
if (preferredArray != null && preferredArray.length > 0) {
preferredRegions = new ArrayList<>(Arrays.asList(preferredArray));
}
}
return preferredRegions;
}
public int getEncryptedStringFieldCount() {
return encryptedStringFieldCount;
}
public int getEncryptedLongFieldCount() {
return encryptedLongFieldCount;
}
public int getEncryptedDoubleFieldCount() {
return encryptedDoubleFieldCount;
}
public boolean isEncryptionEnabled() {
return encryptionEnabled;
}
public void tryGetValuesFromSystem() {
serviceEndpoint = StringUtils.defaultString(Strings.emptyToNull(System.getenv().get("SERVICE_END_POINT")),
serviceEndpoint);
masterKey = StringUtils.defaultString(Strings.emptyToNull(System.getenv().get("MASTER_KEY")), masterKey);
databaseId = StringUtils.defaultString(Strings.emptyToNull(System.getenv().get("DATABASE_ID")), databaseId);
collectionId = StringUtils.defaultString(Strings.emptyToNull(System.getenv().get("COLLECTION_ID")),
collectionId);
documentDataFieldSize = Integer.parseInt(
StringUtils.defaultString(Strings.emptyToNull(System.getenv().get("DOCUMENT_DATA_FIELD_SIZE")),
Integer.toString(documentDataFieldSize)));
maxConnectionPoolSize = Integer.parseInt(
StringUtils.defaultString(Strings.emptyToNull(System.getenv().get("MAX_CONNECTION_POOL_SIZE")),
Integer.toString(maxConnectionPoolSize)));
ConsistencyLevelConverter consistencyLevelConverter = new ConsistencyLevelConverter();
consistencyLevel = consistencyLevelConverter.convert(StringUtils
.defaultString(Strings.emptyToNull(System.getenv().get("CONSISTENCY_LEVEL")), consistencyLevel.name()));
Operation.OperationTypeConverter operationTypeConverter = new Operation.OperationTypeConverter();
operation = operationTypeConverter.convert(
StringUtils.defaultString(Strings.emptyToNull(System.getenv().get("OPERATION")), operation.name()));
String concurrencyValue = StringUtils.defaultString(Strings.emptyToNull(System.getenv().get("CONCURRENCY")),
concurrency == null ? null : Integer.toString(concurrency));
concurrency = concurrencyValue == null ? null : Integer.parseInt(concurrencyValue);
String numberOfOperationsValue = StringUtils.defaultString(
Strings.emptyToNull(System.getenv().get("NUMBER_OF_OPERATIONS")), Integer.toString(numberOfOperations));
numberOfOperations = Integer.parseInt(numberOfOperationsValue);
String throughputValue = StringUtils.defaultString(
Strings.emptyToNull(System.getenv().get("THROUGHPUT")), Integer.toString(throughput));
throughput = Integer.parseInt(throughputValue);
preferredRegionsList = StringUtils.defaultString(Strings.emptyToNull(System.getenv().get(
"PREFERRED_REGIONS_LIST")), preferredRegionsList);
encryptedStringFieldCount = Integer.parseInt(
StringUtils.defaultString(Strings.emptyToNull(System.getenv().get("ENCRYPTED_STRING_FIELD_COUNT")),
Integer.toString(encryptedStringFieldCount)));
encryptedLongFieldCount = Integer.parseInt(
StringUtils.defaultString(Strings.emptyToNull(System.getenv().get("ENCRYPTED_LONG_FIELD_COUNT")),
Integer.toString(encryptedLongFieldCount)));
encryptedDoubleFieldCount = Integer.parseInt(
StringUtils.defaultString(Strings.emptyToNull(System.getenv().get("ENCRYPTED_DOUBLE_FIELD_COUNT")),
Integer.toString(encryptedDoubleFieldCount)));
encryptionEnabled = Boolean.parseBoolean(StringUtils.defaultString(Strings.emptyToNull(System.getenv().get(
"ENCRYPTED_ENABLED")),
Boolean.toString(encryptionEnabled)));
}
private synchronized MeterRegistry azureMonitorMeterRegistry(String instrumentationKey) {
if (this.azureMonitorMeterRegistry == null) {
Duration step = Duration.ofSeconds(Integer.getInteger("azure.cosmos.monitoring.azureMonitor.step", this.printingInterval));
boolean enabled = !Boolean.getBoolean("azure.cosmos.monitoring.azureMonitor.disabled");
final AzureMonitorConfig config = new AzureMonitorConfig() {
@Override
@Nullable
public String get(@Nullable String key) {
return null;
}
@Override
@Nullable
public String instrumentationKey() {
return instrumentationKey;
}
@Override
public Duration step() {
return step;
}
@Override
public boolean enabled() {
return enabled;
}
};
this.azureMonitorMeterRegistry = new AzureMonitorMeterRegistry(config, Clock.SYSTEM);
}
return this.azureMonitorMeterRegistry;
}
@SuppressWarnings("UnstableApiUsage")
private synchronized MeterRegistry graphiteMeterRegistry(String serviceAddress) {
if (this.graphiteMeterRegistry == null) {
HostAndPort address = HostAndPort.fromString(serviceAddress);
String host = address.getHost();
int port = address.getPortOrDefault(DEFAULT_GRAPHITE_SERVER_PORT);
boolean enabled = !Boolean.getBoolean("azure.cosmos.monitoring.graphite.disabled");
Duration step = Duration.ofSeconds(Integer.getInteger("azure.cosmos.monitoring.graphite.step", this.printingInterval));
final GraphiteConfig config = new GraphiteConfig() {
private String[] tagNames = { "source" };
@Override
@Nullable
public String get(@Nullable String key) {
return null;
}
@Override
public boolean enabled() {
return enabled;
}
@Override
@Nullable
public String host() {
return host;
}
@Override
@Nullable
public int port() {
return port;
}
@Override
@Nullable
public Duration step() {
return step;
}
@Override
@Nullable
public String[] tagsAsPrefix() {
return this.tagNames;
}
};
this.graphiteMeterRegistry = new GraphiteMeterRegistry(config, Clock.SYSTEM);
String source;
try {
PercentEscaper escaper = new PercentEscaper("_-", false);
source = escaper.escape(InetAddress.getLocalHost().getHostName());
} catch (UnknownHostException error) {
source = "unknown-host";
}
this.graphiteMeterRegistry.config()
.namingConvention(NamingConvention.dot)
.commonTags("source", source);
}
return this.graphiteMeterRegistry;
}
}
| 39.415781 | 183 | 0.660173 |
db7daa1c42633f353b8785a4b4672773dfdfb162 | 5,119 | package bwfdm.sara.transfer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.eclipse.jgit.lib.ProgressMonitor;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.annotation.JsonProperty;
import bwfdm.sara.api.Error.ErrorInfo;
public abstract class Task implements ProgressMonitor, Runnable {
protected static final Log logger = LogFactory.getLog(Task.class);
private final List<Step> steps = new ArrayList<>();
private int lastCompletedIndex = -1;
private Map<String, Step> declaredSteps;
private Step currentStep;
private boolean started, done, cancelled;
private Exception exception;
private Step failedStep;
private Thread thread;
protected void declareSteps(final List<String> steps) {
if (declaredSteps == null)
declaredSteps = new HashMap<>();
for (final String t : steps) {
final Step s = new Step(t);
this.steps.add(s);
declaredSteps.put(t, s);
}
}
protected void declareSteps(final String... steps) {
declareSteps(Arrays.asList(steps));
}
public synchronized Exception getException() {
if (!done)
throw new IllegalStateException(
"getException while task still running");
return exception;
}
public synchronized void start() {
// start at most once
if (started)
return;
thread = new Thread(this);
thread.start();
started = true;
}
@Override
public void start(final int totalTasks) {
return;
}
@Override
public void endTask() {
// ignored. users tend to get confused when a step is completed but the
// next step hasn't started yet. thus we lie to them and delay ending
// the step until the next one has already started.
}
@Override
public void beginTask(final String title, final int totalWork) {
// ending steps here instead of endTask(), see above
endStep();
currentStep = findTask(title, totalWork);
currentStep.start(totalWork);
}
private void endStep() {
if (currentStep != null)
currentStep.end();
currentStep = null;
}
private Step findTask(final String title, final int totalWork) {
final Step step;
if (declaredSteps != null && declaredSteps.containsKey(title)) {
step = declaredSteps.get(title);
lastCompletedIndex = steps.indexOf(step);
} else {
step = new Step(title);
lastCompletedIndex++;
steps.add(lastCompletedIndex, step);
}
return step;
}
@Override
public void update(final int completed) {
currentStep.update(completed);
}
/** @return <code>true</code> if the task has finished successfully */
public boolean isDone() {
return done && !cancelled;
}
/** @return <code>true</code> if the task has been cancelled or has crashed */
@Override
public boolean isCancelled() {
return cancelled;
}
public void cancel() {
if (thread != null)
thread.interrupt();
synchronized (this) {
cancelled = true;
if (!done)
return; // thread will do it
}
// perform cleanup here if the thread has already exited
cleanup();
}
@Override
public final void run() {
try {
execute();
} catch (final Exception e) {
synchronized (this) {
cancelled = true;
exception = e;
failedStep = currentStep;
}
logger.debug(e);
} finally {
synchronized (this) {
// end the last step, finally setting checkmarks on everything
endStep();
done = true;
if (!cancelled)
return;
}
// if the task was cancelled while the thread was running, perform
// cleanup here
cleanup();
}
}
protected abstract void cleanup();
protected abstract void execute() throws Exception;
public List<Step> getSteps() {
return Collections.unmodifiableList(steps);
}
public TaskStatus getStatus() {
return new TaskStatus();
}
@JsonInclude(Include.NON_NULL)
public class TaskStatus {
@JsonProperty
private final StatusCode status;
@JsonProperty
private final List<Step> steps;
@JsonProperty
private final TaskErrorInfo error;
private TaskStatus() {
if (cancelled) {
status = StatusCode.ERROR;
if (exception != null) {
logger.warn("exception in "
+ Task.this.getClass().getSimpleName() + ": "
+ exception.getClass().getSimpleName() + ": "
+ exception.getMessage(), exception);
final String fail = failedStep != null ? failedStep.text
: null;
error = new TaskErrorInfo(exception, fail);
} else
error = null;
} else {
error = null;
status = done ? StatusCode.SUCCESS : StatusCode.ACTIVE;
}
steps = Task.this.steps;
}
}
public enum StatusCode {
@JsonProperty("active")
ACTIVE, //
@JsonProperty("success")
SUCCESS, //
@JsonProperty("error")
ERROR
}
@JsonInclude(Include.NON_NULL)
public static class TaskErrorInfo extends ErrorInfo {
@JsonProperty
public final String step;
public TaskErrorInfo(final Exception e, final String step) {
super(e);
this.step = step;
}
}
}
| 23.699074 | 79 | 0.695839 |
97600849811b17d0093fde3750e8b1eb3187d4c2 | 6,164 | /*
************************************************************************************
* Copyright (C) 2001-2011 encuestame: system online surveys Copyright (C) 2011
* encuestame Development Team.
* Licensed under the Apache Software License version 2.0
* 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.encuestame.mvc.test.json;
import junit.framework.Assert;
import org.encuestame.core.config.EnMePlaceHolderConfigurer;
import org.encuestame.mvc.controller.json.v1.search.QuickSearchJsonController;
import org.encuestame.mvc.test.config.AbstractJsonV1MvcUnitBeans;
import org.encuestame.persistence.domain.security.Account;
import org.encuestame.persistence.domain.security.UserAccount;
import org.encuestame.utils.categories.test.DefaultTest;
import org.encuestame.utils.enums.MethodJson;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.categories.Category;
/**
* Test case for {@link QuickSearchJsonController}.
* @author Picado, Juan juanATencuestame.org
* @since Apr 10, 2011
*/
@Category(DefaultTest.class)
public class QuickSearchJsonControllerTestCase extends AbstractJsonV1MvcUnitBeans{
/** {@link Account} **/
private Account account;
/** {@link UserAccount} **/
private UserAccount userAccount;
/**
* Init Test.
*/
@Before
public void initTest() {
this.account = createAccount();
createFakesQuestions(this.account);
createHashTag("Nicaragua");
createHashTag("Spain");
createHashTag("Java");
createHashTag("Condega");
createQuestion("testing 1 question", getSpringSecurityLoggedUserAccount().getAccount());
createQuestion("alabama", getSpringSecurityLoggedUserAccount().getAccount());
flushIndexes();
}
/**
* Test api/search/quick-suggest.json.
* @throws Exception
*/
@Test
public void quickSearchTest() throws Exception {
flushIndexes();
logPrint("datasource.hibernate.search.provider" +EnMePlaceHolderConfigurer.getProperty("datasource.hibernate.search.provider"));
initService("/api/search/quick-suggest.json", MethodJson.GET);
setParameter("keyword", "S");
final JSONObject response = callJsonService();
Assert.assertEquals(this.getSearchRestuls(response, "tags").size(), 0);
Assert.assertEquals(this.getSearchRestuls(response, "questions").size(), 0);
Assert.assertEquals(this.getSearchRestuls(response, "profiles").size(), 0);
Assert.assertEquals(this.getSearchRestuls(response, "attachments").size(), 0);
initService("/api/search/quick-suggest.json", MethodJson.GET);
setParameter("keyword", "a*");
final JSONObject response2 = callJsonService();
Assert.assertEquals(this.getSearchRestuls(response2, "tags").size(), 0);
Assert.assertEquals(this.getSearchRestuls(response2, "questions").size(), 3);
Assert.assertEquals(this.getSearchRestuls(response2, "profiles").size(), 0);
Assert.assertEquals(this.getSearchRestuls(response2, "attachments").size(), 0);
initService("/api/search/quick-suggest.json", MethodJson.GET);
setParameter("keyword", "Nicaragua");
final JSONObject response3 = callJsonService();
Assert.assertEquals(this.getSearchRestuls(response3, "tags").size(), 0);
Assert.assertEquals(this.getSearchRestuls(response3, "questions").size(), 0);
Assert.assertEquals(this.getSearchRestuls(response3, "profiles").size(), 0);
Assert.assertEquals(this.getSearchRestuls(response3, "attachments").size(), 0);
}
/**
*
* @param response
* @param property
* @return
*/
private JSONArray getSearchRestuls(JSONObject response, final String property){
final JSONObject sucess = getSucess(response);
Assert.assertNotNull(sucess.get("items"));
final JSONObject items = (JSONObject) sucess.get("items");
return (JSONArray) items.get(property);
}
@Test
public void testadvancedSearch() throws Exception {
flushIndexes();
initService("/api/search/quick-suggest.json", MethodJson.GET);
setParameter("keyword", "S");
final JSONObject response = callJsonService();
Assert.assertEquals(this.getSearchRestuls(response, "tags").size(), 0);
Assert.assertEquals(this.getSearchRestuls(response, "questions").size(), 0);
Assert.assertEquals(this.getSearchRestuls(response, "profiles").size(), 0);
Assert.assertEquals(this.getSearchRestuls(response, "attachments").size(), 0);
initService("/api/search/quick-suggest.json", MethodJson.GET);
setParameter("keyword", "a*");
final JSONObject response2 = callJsonService();
Assert.assertEquals(this.getSearchRestuls(response2, "tags").size(), 0);
Assert.assertEquals(this.getSearchRestuls(response2, "questions").size(), 3);
Assert.assertEquals(this.getSearchRestuls(response2, "profiles").size(), 0);
Assert.assertEquals(this.getSearchRestuls(response2, "attachments").size(), 0);
initService("/api/search/quick-suggest.json", MethodJson.GET);
setParameter("keyword", "Nicaragua");
final JSONObject response3 = callJsonService();
Assert.assertEquals(this.getSearchRestuls(response3, "tags").size(), 0);
Assert.assertEquals(this.getSearchRestuls(response3, "questions").size(), 0);
Assert.assertEquals(this.getSearchRestuls(response3, "profiles").size(), 0);
Assert.assertEquals(this.getSearchRestuls(response3, "attachments").size(), 0);
}
} | 47.415385 | 136 | 0.682998 |
6901f49bc0311bbee67c471f0ef354b7e3eb3205 | 809 | package pl.tkowalcz.tjahzi.protobuf;
import io.netty.buffer.ByteBuf;
import static pl.tkowalcz.tjahzi.protobuf.Protobuf.VARINT_TYPE;
import static pl.tkowalcz.tjahzi.protobuf.Protobuf.writeUnsignedVarint;
public class TimestampSerializer {
public static void serialize(
long timestamp,
ByteBuf target
) {
long timestampSeconds = timestamp / 1000;
int timestampNanos = (int) (timestamp % 1000) * 1000_000;
int messageStartIndex = target.writerIndex();
target.writeInt(0);
target.writeByte(1 << 3 | VARINT_TYPE);
writeUnsignedVarint(timestampSeconds, target);
target.writeByte(2 << 3 | VARINT_TYPE);
writeUnsignedVarint(timestampNanos, target);
Protobuf.writeSize(target, messageStartIndex);
}
}
| 28.892857 | 71 | 0.68974 |
abf04576ee0044d3b290a8883b3c29dd7e0e2304 | 1,091 | package js.tiny.container.stub;
import js.tiny.container.core.AppFactory;
public class AppFactoryStub implements AppFactory {
@Override
public <T> T getInstance(Class<? super T> interfaceClass, Object... args) {
throw new UnsupportedOperationException("getInstance(Class<? super T>, Object...)");
}
@Override
public <T> T getInstance(String instanceName, Class<? super T> interfaceClass, Object... args) {
throw new UnsupportedOperationException("getInstance(String, Class<? super T>, Object...)");
}
@Override
public <T> T getOptionalInstance(Class<? super T> interfaceClass, Object... args) {
throw new UnsupportedOperationException("getOptionalInstance(Class<? super T>, Object...)");
}
@Override
public <T> T getRemoteInstance(String implementationURL, Class<? super T> interfaceClass) {
throw new UnsupportedOperationException("getRemoteInstance(URL, Class<? super T>)");
}
@Override
public <T> T loadService(Class<T> serviceInterface) {
throw new UnsupportedOperationException("loadService(Class<T> serviceInterface)");
}
}
| 35.193548 | 98 | 0.728689 |
64c30a10085c8eb834517dc0dfeb1dff7c618adc | 436 | package com.gsc.service.impl;
import com.gsc.dao.UserDao;
import com.gsc.pojo.Users;
import com.gsc.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userDao;
@Override
public void saveUser(Users users) {
userDao.addUser(users);
}
}
| 21.8 | 62 | 0.761468 |
319c9ceb82b71f8135ac3c426ccd1bb1eb11fc06 | 17,049 | package cn.xnatural.http;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.lang.reflect.Array;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.nio.ByteBuffer;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Function;
import java.util.function.Supplier;
import static cn.xnatural.http.HttpServer.log;
/**
* http 请求 处理上下文
*/
public class HttpContext {
public final HttpRequest request;
public final HttpResponse response = new HttpResponse();
protected final HttpAioSession aioStream;
protected final HttpServer server;
/**
* 路径变量值映射
*/
protected final Map<String, Object> pathToken = new LinkedHashMap<>(7);
/**
* 动态变化的 路径块, 用于路径匹配 /test/p1/p2 -> test,p1,p2
* 去除 {@link Ctrl#prefix()} 剩下的分片
*/
public final LinkedList<String> pieces = new LinkedList<>();
/**
* 是否已关闭
*/
protected final AtomicBoolean closed = new AtomicBoolean(false);
/**
* 请求属性集
*/
protected final Map<String, Object> attrs = new ConcurrentHashMap<>();
/**
* session 数据操作委托
*/
protected final Lazies<Map<String, Object>> sessionSupplier;
/**
* 执行的 {@link Handler}
*/
protected final List<Handler> passedHandler = new LinkedList<>();
/**
* 结束回调函数
*/
protected final List<Runnable> finishedFns = new LinkedList<>();
/**
* 请求执行上下文
* @param request 请求
* @param server {@link HttpServer}
* @param sessionDelegate session 委托映射
*/
HttpContext(HttpRequest request, HttpServer server, Function<HttpContext, Map<String, Object>> sessionDelegate) {
if (request == null) throw new NullPointerException("Param request required");
this.request = request;
this.aioStream = request.session;
this.server = server;
this.sessionSupplier = new Lazies<>(() -> sessionDelegate.apply(this));
if ("/".equals(request.getPath())) this.pieces.add("/");
else {
for (String piece : Handler.extract(request.getPath()).split("/")) {
pieces.add(piece);
}
if (request.getPath().endsWith("/")) this.pieces.add("/");
}
}
/**
* 关闭
*/
public void close() {
if (closed.compareAndSet(false, true)) {
aioStream.close();
}
}
/**
* 从cookie中取session 标识
* @return session id(会话id)
*/
public String getSessionId() {
Map<String, Object> data = sessionSupplier.get();
if (data == null) return null;
return (String) data.get("id");
}
/**
* 设置请求属性
* @param key 属性key
* @param value 属性值
* @return {@link HttpContext}
*/
public HttpContext setAttr(String key, Object value) { attrs.put(key, value); return this; }
/**
* 设置请求 懒计算 属性
* @param key 属性key
* @param supplier 属性值计算器
* @return {@link HttpContext}
*/
public <T> HttpContext setAttr(String key, Supplier<T> supplier) { attrs.put(key, supplier); return this; }
/**
* 获取请求属性
* @param aName 属性名
* @param aType 属性类型
* @return 属性值
*/
public <T> T getAttr(String aName, Class<T> aType) {
Object v = attrs.get(aName);
if (v instanceof Supplier) v = ((Supplier<?>) v).get();
if (aType != null) return aType.cast(v);
return (T) v;
}
/**
* 设置 session 属性
* @param aName 属性名
* @param value 属性值
* @return {@link HttpContext}
*/
public HttpContext setSessionAttr(String aName, Object value) {
if (sessionSupplier.get() == null) return this;
if (value == null) sessionSupplier.get().remove(aName);
else sessionSupplier.get().put(aName, value);
return this;
}
/**
* 设置 session 懒计算属性
* @param aName 属性名
* @param value 属性值
* @return {@link HttpContext}
*/
public <T> HttpContext setSessionAttr(String aName, Supplier<T> value) {
if (sessionSupplier.get() == null) return this;
if (value == null) sessionSupplier.get().remove(aName);
else sessionSupplier.get().put(aName, value);
return this;
}
/**
* 删除 session 属性
* @param aName 属性名
* @return 属性值
*/
public Object removeSessionAttr(String aName) {
if (sessionSupplier.get() == null) return null;
return sessionSupplier.get().remove(aName);
}
/**
* 获取 session 属性
* @param aName 属性名
* @return 属性值
*/
public Object getSessionAttr(String aName) {
if (sessionSupplier.get() == null) return null;
Object v = sessionSupplier.get().get(aName);
return v instanceof Supplier ? ((Supplier<?>) v).get() : v;
}
/**
* 注册结束时回调函数
*/
public HttpContext regFinishedFn(Runnable fn) {
finishedFns.add(fn);
return this;
}
/**
* 权限验证
* @param permissions 权限名 验证用户是否有此权限
* @return true: 验证通过
*/
public boolean auth(String... permissions) { return server.auth(this, permissions); }
/**
* 是否存在权限
* @param permissions 多个权限标识
* @return true: 存在
*/
public boolean hasAuth(String... permissions) { return server.hasAuth(this, permissions); }
/**
* 响应请求
*/
public void render() { render(null); }
/**
* 响应请求
* @param body 响应内容
*/
public void render(Object body) {
if (!response.commit.compareAndSet(false, true)) {
throw new RuntimeException("Already submit response");
}
long spend = System.currentTimeMillis() - request.createTime.getTime();
if (spend > server.getInteger("logWarnTimeout", 5000)) { // 请求超时警告单位ms
log.warn("Request timeout '" + request.getId() + "', path: " + request.getPath() + " , spend: " + spend + "ms");
}
try {
if (body == null) { //无内容返回
response.statusIfNotSet(204);
response.contentLengthIfNotSet(0);
aioStream.write(ByteBuffer.wrap(preRespBytes()));
return;
} else {
response.statusIfNotSet(200);
// HttpResponseEncoder
if (body instanceof String) { //回写字符串
response.contentTypeIfNotSet("text/plain;charset=" + server.getCharset());
renderBytes(((String) body).getBytes(server.getCharset()));
} else if (body instanceof ApiResp) {
response.contentTypeIfNotSet("application/json;charset=" + server.getCharset());
((ApiResp) body).setMark((String) param("mark"));
((ApiResp) body).setTraceNo(request.getId());
renderBytes(JSON.toJSONString(body, SerializerFeature.WriteMapNullValue).getBytes(server.getCharset()));
} else if (body instanceof byte[]) {
renderBytes((byte[]) body);
} else if (body instanceof File) {
renderFile((File) body);
} else if (response.getContentType() != null) {
String ct = response.getContentType();
if (ct.contains("application/json")) {
renderBytes(JSON.toJSONString(body, SerializerFeature.WriteMapNullValue).getBytes(server.getCharset()));
} else if (ct.contains("text/plain")) {
renderBytes(body.toString().getBytes(server.getCharset()));
} else throw new Exception("Not support response Content-Type: " + ct);
} else throw new Exception("Not support response type: " + body.getClass().getName());
}
determineClose();
} catch (Exception ex) {
log.error("Http response error", ex);
close();
} finally {
for (Runnable fn : finishedFns) {
fn.run();
}
}
}
/**
* 发送字节
* @param bodyBs body
* @throws Exception
*/
protected void renderBytes(byte[] bodyBs) throws Exception {
int chunkedSize = server.chunkedSize(this, bodyBs.length, byte[].class);
if (chunkedSize < 0) { // 不分块, 文件整块传送
response.contentLengthIfNotSet(bodyBs.length);
aioStream.write(ByteBuffer.wrap(preRespBytes())); //1. 先写header
aioStream.write(ByteBuffer.wrap(bodyBs)); //2. 再写body
} else {
response.transferEncoding("chunked");
aioStream.write(ByteBuffer.wrap(preRespBytes())); // 1. 先写公共header
try (InputStream is = new ByteArrayInputStream(bodyBs)) { // 2. 再写body内容
chunked(chunkedSize, is);
}
}
}
/**
* 渲染文件
* 分块传送. js 加载不全, 可能是网速限制的原因
* @param file 文件
* @throws Exception
*/
protected void renderFile(File file) throws Exception {
if (!file.exists()) {
response.status(404);
log.warn("Request {}({}). id: {}, url: {}", HttpResponse.statusMsg.get(response.status), response.status, request.getId(), request.getRowUrl());
response.contentLengthIfNotSet(0);
aioStream.write(ByteBuffer.wrap(preRespBytes()));
close(); return;
}
if (file.getName().endsWith(".html")) {
response.contentTypeIfNotSet("text/html");
} else if (file.getName().endsWith(".css")) {
response.contentTypeIfNotSet("text/css");
} else if (file.getName().endsWith(".js")) {
response.contentTypeIfNotSet("application/javascript");
}
int chunkedSize = server.chunkedSize(this, (int) file.length(), File.class);
if (chunkedSize < 0) { // 不分块, 文件整块传送
byte[] content = new byte[(int) file.length()]; // 一次性读出来, 减少IO
try (InputStream fis = new FileInputStream(file)) { fis.read(content); }
response.contentLengthIfNotSet(content.length);
aioStream.write(ByteBuffer.wrap(preRespBytes())); //1. 先写header
aioStream.write(ByteBuffer.wrap(content)); //2. 再写body
} else { // 文件分块传送
// response.contentLengthIfNotSet((int) file.length());
response.transferEncoding("chunked");
response.contentTypeIfNotSet("application/octet-stream");
aioStream.write(ByteBuffer.wrap(preRespBytes())); // 1. 先写公共header
try (InputStream fis = new FileInputStream(file)) { // 2. 再写文件内容
chunked(chunkedSize, fis);
}
}
}
/**
* 分批发送数据 chunked
* @param chunkedSize 分批大小
* @param is 输入数据流
* @throws Exception
*/
protected void chunked(int chunkedSize, InputStream is) throws Exception {
byte[] buf = new byte[chunkedSize]; // 数据缓存buf
boolean end;
do {
int length = is.read(buf); // 一批一批的读, 减少IO
end = length < chunkedSize; // 是否已结束(当读出来的数据少于chunkedSize)
if (length > 0) {
aioStream.write(ByteBuffer.wrap((Integer.toHexString(length) + "\r\n").getBytes(server.getCharset()))); //1. 写chunked: header
aioStream.write(ByteBuffer.wrap(buf, 0, length)); //2. 写chunked: body
aioStream.write(ByteBuffer.wrap("\r\n".getBytes(server.getCharset()))); //2. 写chunked: end
}
// Thread.sleep(450L); // 阿里云网速限制, chunkedSize = 1024 * 20
} while (!end);
//3. 结束chunk
aioStream.write(ByteBuffer.wrap("0\r\n\r\n".getBytes(server.getCharset())));
}
/**
* http 响应的前半部分
* 包含: 起始行, 公共 header
* @return byte[]
*/
protected byte[] preRespBytes() throws Exception {
StringBuilder sb = new StringBuilder();
sb.append("HTTP/").append(request.getVersion()).append(" ").append(response.status).append(" ").append(HttpResponse.statusMsg.get(response.status)).append("\r\n"); // 起始行
response.headers.forEach((key, value) -> sb.append(key).append(": ").append(value).append("\r\n"));
response.cookies.forEach((key, value) -> sb.append("Set-Cookie: ").append(key).append("=").append(value).append("\r\n"));
return sb.append("\r\n").toString().getBytes(server.getCharset());
}
/**
* 判断是否应该关闭此次Http连接会话
*/
protected void determineClose() {
String connection = request.getConnection();
if (connection != null && connection.toLowerCase().contains("close")) {
// http/1.1 规定 只有显示 connection:close 才关闭连接
close();
}
}
/**
* 所有参数(有序): 路径参数, query参数, 表单, json
* @return map
*/
public Map<String, Object> params() {
Map<String, Object> params = new LinkedHashMap<>();
params.putAll(request.getJsonParams());
params.putAll(request.getFormParams());
params.putAll(request.getQueryParams());
params.putAll(pathToken);
return params;
}
/**
* {@link #param(String, Class)}
* @param pName 参数名
* @return 参数值
*/
public Object param(String pName) { return param(pName, null); }
/**
* 取请求参数值
* @param pName 参数名
* @param type 结果类型
* @return 参数值
*/
public <T> T param(String pName, Class<T> type) {
if (type != null && HttpContext.class.isAssignableFrom(type)) return (T) this;
if (type != null && HttpServer.class.isAssignableFrom(type)) return (T) server;
Object v = pathToken.get(pName);
if (v == null) v = request.getQueryParams().get(pName);
if (v == null) v = request.getFormParams().get(pName);
if (v == null) v = request.getJsonParams().get(pName);
if (v == null && type != null && type.isArray()) { // 数组参数名后边加个[]
pName = pName + "[]";
v = pathToken.get(pName);
if (v == null) v = request.getQueryParams().get(pName);
if (v == null) v = request.getFormParams().get(pName);
if (v == null) v = request.getJsonParams().get(pName);
}
if (type == null) return (T) v;
else if (v == null) return null;
else if (FileData.class.isAssignableFrom(type)) return (T) (v instanceof List ? (((List) v).get(0)) : v);
else if (FileData[].class.equals(type)) return v instanceof List ? (T) ((List) v).toArray() : (T) new FileData[]{(FileData) v};
else if (type.isArray()) {
List ls = new LinkedList();
if (v instanceof List) {
for (Object o : ((List) v)) { ls.add(to(o, type.getComponentType())); }
return (T) ls.toArray((T[]) Array.newInstance(type.getComponentType(), ((List) v).size()));
} else {
ls.add(to(v, type.getComponentType()));
return (T) ls.toArray((T[]) Array.newInstance(type.getComponentType(), 1));
}
} else return to(v, type);
}
/**
* 类型转换
* @param v 值
* @param type 转换的类型
* @return 转换后的结果
*/
public static <T> T to(Object v, Class<T> type) {
if (type == null) return (T) v;
if (v == null) return null;
else if (type.isAssignableFrom(v.getClass())) return (T) v;
else if (String.class.equals(type)) return (T) v.toString();
else if (Boolean.class.equals(type) || boolean.class.equals(type)) return (T) Boolean.valueOf(v.toString());
else if (Short.class.equals(type) || short.class.equals(type)) return (T) Short.valueOf(v.toString());
else if (Byte.class.equals(type) || byte.class.equals(type)) return (T) Byte.valueOf(v.toString());
else if (Integer.class.equals(type) || int.class.equals(type)) return (T) Integer.valueOf(v.toString());
else if (BigInteger.class.equals(type)) return (T) new BigInteger(v.toString());
else if (Long.class.equals(type) || long.class.equals(type)) return (T) Long.valueOf(v.toString());
else if (Double.class.equals(type) || double.class.equals(type)) return (T) Double.valueOf(v.toString());
else if (Float.class.equals(type) || float.class.equals(type)) return (T) Float.valueOf(v.toString());
else if (BigDecimal.class.equals(type)) return (T) new BigDecimal(v.toString());
else if (URI.class.equals(type)) return (T) URI.create(v.toString());
else if (URL.class.equals(type)) {
try {
return (T) URI.create(v.toString()).toURL();
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
}
else if (type.isEnum()) return Arrays.stream(type.getEnumConstants()).filter((o) -> v.equals(((Enum) o).name())).findFirst().orElse(null);
return (T) v;
}
}
| 35.667364 | 178 | 0.577336 |
0138d1730b46e9a67438cf4d7fa09c22bf25ac2e | 460 | //https://leetcode.com/problems/car-pooling/submissions/
public class CarPooling {
public boolean carPooling(int[][] trips, int capacity) {
int[] people = new int[1001];
for(int i=0; i<trips.length; i++){
people[trips[i][1]]+=trips[i][0];
people[trips[i][2]]-=trips[i][0];
}
for(int v: people){
capacity-=v;
if(capacity<0) return false;
}
return true;
}
}
| 28.75 | 60 | 0.526087 |
353be8724d107451349c6641d1a15bd666b881b4 | 247 | package edu.nju.bl.vo;
import lombok.AllArgsConstructor;
import lombok.Data;
/**
* Created by cuihao on 2017/3/13.
*/
@Data
@AllArgsConstructor
public class LineVo {
private String name;
private long reserve;
private long check;
}
| 15.4375 | 34 | 0.716599 |
615fcc4eaf900b477f80d0bbe0fbe97f2bded00a | 1,368 | /*
* Copyright 2018 Aleksander Jagiełło
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package pl.themolka.arcade.config;
import pl.themolka.arcade.dom.Child;
import pl.themolka.arcade.util.StringId;
public class SimpleConfig<T extends SimpleConfig<T>> implements Child<T>, IConfig, StringId {
protected final String id;
protected final T parent;
public SimpleConfig(String id) {
this(id, null);
}
public SimpleConfig(String id, T parent) {
this.id = id;
this.parent = parent;
}
@Override
public final boolean detach() {
return false;
}
@Override
public String getId() {
return this.id;
}
@Override
public T getParent() {
return this.parent;
}
@Override
public boolean hasParent() {
return this.parent != null;
}
}
| 24.872727 | 93 | 0.673246 |
2695f28095952d5c619103d63d2f6403254c84a8 | 2,522 | /*
* Copyright (c) 2016 simplity.org
*
* 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, OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package org.simplity.core.app;
import java.io.InputStream;
import org.simplity.core.ApplicationError;
/**
* An assistant to AttachmentManager who can store/retrieve file/media in a permanent way. We
* provide a simple assistant who uses a designated folder on the file system for this.
*
* @author simplity.org
*/
public interface IAttachmentAssistant {
/**
* store a file into corporate storage area. IMP : we DO NOT close stream. We believe the creator
* has to destroy it.
*
* @param inStream stream to read he media from. Kept open on return. Caller need to close it.
* @return key/token that can be used to retrieve this attachment any time.
*/
public String store(InputStream inStream);
/**
* store a file into corporate storage area from its temp-area
*
* @param tempKey key to temp-storage area
* @return key/token that can be used to retrieve this attachment any time.
*/
public String store(String tempKey);
/**
* retrieve a media file from central storage
*
* @param storageKey
* @return file-token that is to be used to access the retrieved content for sending to client or
* re-storage
* @throws ApplicationError if storageKey is not valid
*/
public String retrieve(String storageKey);
/**
* remove a media file from central storage
*
* @param storageKey
*/
public void remove(String storageKey);
}
| 36.028571 | 99 | 0.732355 |
b6b00622bdc87bb12f8f2d3b8d58851b17678ba1 | 8,566 | package com.cz3002.shopfunding.API;
import android.content.Context;
import com.cz3002.shopfunding.Model.Contribution;
import com.cz3002.shopfunding.Model.FundingRequest;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class FundRequest {
public static int createRequest(
Context context, String productName, String description, String url, float goal
) {
RequestManager requestManager = RequestManager.getInstance(context.getApplicationContext());
JSONObject product = new JSONObject();
try {
product.put("name", productName);
product.put("description", description);
product.put("original_url", url);
} catch (JSONException e) {
e.printStackTrace();
}
JSONObject payload = new JSONObject();
try {
payload.put("product", product);
payload.put("goal", goal);
} catch (JSONException e) {
e.printStackTrace();
}
JSONObject json_response = requestManager.postRequest(context, ENDPOINTS.FUND_REQUEST, payload);
try {
return json_response.getInt("id");
} catch (JSONException e) {
e.printStackTrace();
return -1;
}
}
public static FundingRequest fetchFundRequest(Context context, int id) {
RequestManager requestManager = RequestManager.getInstance(context.getApplicationContext());
JSONObject jsonObject = requestManager.getRequest(context, ENDPOINTS.FUND_REQUEST + id);
try {
String author = jsonObject.getJSONObject("author").getString("username");
String creationDate = jsonObject.getString("creation_date");
JSONObject product = jsonObject.getJSONObject("product");
String productName = product.getString("name");
String description = product.getString("description");
String url = product.getString("original_url");
float goal = (float) jsonObject.getDouble("goal");
float remaining = (float) jsonObject.getDouble("remaining_fund_needed");
FundingRequest fundingRequest = new FundingRequest(
id, author, productName, description, creationDate, url, goal, remaining
);
return fundingRequest;
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
public static ArrayList<FundingRequest> fetchFundRequests(Context context) {
RequestManager requestManager = RequestManager.getInstance(context.getApplicationContext());
JSONArray json_response = requestManager.getRequest_JSONArray(context, ENDPOINTS.FUND_REQUEST + "mine");
if (json_response != null) {
ArrayList<FundingRequest> fundRequests = new ArrayList<>();
try {
for (int i=0; i < json_response.length(); i++) {
JSONObject jsonObject = json_response.getJSONObject(i);
int id = jsonObject.getInt("id");
String author = jsonObject.getJSONObject("author").getString("username");
String creationDate = jsonObject.getString("creation_date");
JSONObject product = jsonObject.getJSONObject("product");
String productName = product.getString("name");
String description = product.getString("description");
String url = product.getString("original_url");
float goal = (float) jsonObject.getDouble("goal");
float remaining = (float) jsonObject.getDouble("remaining_fund_needed");
fundRequests.add(new FundingRequest(
id, author, productName, description, creationDate, url, goal, remaining
));
}
} catch (JSONException e) {
e.printStackTrace();
}
return fundRequests;
}
return null;
}
public static ArrayList<FundingRequest> fetchFriendFundRequests(Context context, int userID) {
RequestManager requestManager = RequestManager.getInstance(context.getApplicationContext());
JSONArray json_response = requestManager.getRequest_JSONArray(
context, ENDPOINTS.FUND_REQUEST + userID + ENDPOINTS.FRIEND_FUND_REQUEST);
if (json_response != null) {
ArrayList<FundingRequest> fundRequests = new ArrayList<>();
try {
for (int i=0; i < json_response.length(); i++) {
JSONObject jsonObject = json_response.getJSONObject(i);
int id = jsonObject.getInt("id");
String author = jsonObject.getJSONObject("author").getString("username");
String creationDate = jsonObject.getString("creation_date");
JSONObject product = jsonObject.getJSONObject("product");
String productName = product.getString("name");
String description = product.getString("description");
String url = product.getString("original_url");
float goal = (float) jsonObject.getDouble("goal");
float remaining = (float) jsonObject.getDouble("remaining_fund_needed");
fundRequests.add(new FundingRequest(
id, author, productName, description, creationDate, url, goal, remaining
));
}
} catch (JSONException e) {
e.printStackTrace();
}
return fundRequests;
}
return null;
}
public static boolean addContributors(
Context context, int requestID, String[] usernames) {
RequestManager requestManager = RequestManager.getInstance(context.getApplicationContext());
for (String username: usernames) {
JSONObject payload = new JSONObject();
try {
payload.put("username", username);
} catch (JSONException e) {
e.printStackTrace();
}
JSONObject json_response = requestManager.postRequest(
context, ENDPOINTS.FUND_REQUEST + requestID + ENDPOINTS.ADD_FRIEND, payload);
try {
json_response.getInt("id");
} catch (JSONException e) {
e.printStackTrace();
return false;
}
}
return true;
}
public static Contribution[] fetchContributions(Context context, int requestID) {
RequestManager requestManager = RequestManager.getInstance(context.getApplicationContext());
JSONArray json_response = requestManager.getRequest_JSONArray(
context, ENDPOINTS.FUND_REQUEST + requestID + ENDPOINTS.CONTRIBUTIONS);
if (json_response != null) {
ArrayList<Contribution> contributions = new ArrayList<>();
try {
for (int i=0; i < json_response.length(); i++) {
JSONObject jsonObject = json_response.getJSONObject(i);
int id = jsonObject.getInt("id");
String contributor = jsonObject.getJSONObject("user").getString("username");
float amount = (float) jsonObject.getDouble("amount");
contributions.add(new Contribution(id, contributor, amount));
}
} catch (JSONException e) {
e.printStackTrace();
}
return contributions.toArray(new Contribution[contributions.size()]);
}
return null;
}
public static Float updateContribution(Context context, int contributionID, float amount) {
RequestManager requestManager = RequestManager.getInstance(context.getApplicationContext());
JSONObject payload = new JSONObject();
try {
payload.put("amount", amount);
} catch (JSONException e) {
e.printStackTrace();
}
JSONObject json_response = requestManager.patchRequest(
context, ENDPOINTS.CONTRIBUTION + contributionID, payload);
if (json_response != null) {
try {
return (float) json_response.getDouble("amount");
} catch (JSONException e) {
e.printStackTrace();
}
}
return null;
}
}
| 43.482234 | 112 | 0.596194 |
0a3e0995aab54c7bf747363602d38bff74248ecd | 3,730 | /*
* Copyright 2019 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 androidx.camera.extensions;
import static org.junit.Assume.assumeTrue;
import android.content.Context;
import android.hardware.camera2.CameraAccessException;
import androidx.camera.camera2.Camera2Config;
import androidx.camera.core.CameraInfoUnavailableException;
import androidx.camera.core.CameraSelector;
import androidx.camera.core.CameraX;
import androidx.camera.extensions.impl.ImageCaptureExtenderImpl;
import androidx.camera.extensions.util.ExtensionsTestUtil;
import androidx.camera.testing.CameraUtil;
import androidx.test.core.app.ApplicationProvider;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import androidx.test.filters.LargeTest;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestRule;
import org.junit.runner.RunWith;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
@RunWith(AndroidJUnit4.class)
public class ImageCaptureExtenderValidationTest {
@Rule
public TestRule mUseCamera = CameraUtil.grantCameraPermissionAndPreTest();
private final Context mContext = ApplicationProvider.getApplicationContext();
@Before
public void setUp() throws InterruptedException, ExecutionException, TimeoutException {
assumeTrue(CameraUtil.deviceHasCamera());
CameraX.initialize(mContext, Camera2Config.defaultConfig());
assumeTrue(ExtensionsTestUtil.initExtensions(mContext));
}
@After
public void tearDown() throws ExecutionException, InterruptedException, TimeoutException {
CameraX.shutdown().get(10000, TimeUnit.MILLISECONDS);
ExtensionsManager.deinit().get();
}
@Test
@LargeTest
public void getSupportedResolutionsImplementationTest()
throws CameraInfoUnavailableException, CameraAccessException {
// getSupportedResolutions supported since version 1.1
assumeTrue(ExtensionVersion.getRuntimeVersion().compareTo(Version.VERSION_1_1) >= 0);
// Uses for-loop to check all possible effect/lens facing combinations
for (Object[] EffectLensFacingPair :
ExtensionsTestUtil.getAllEffectLensFacingCombinations()) {
ExtensionsManager.EffectMode effectMode =
(ExtensionsManager.EffectMode) EffectLensFacingPair[0];
@CameraSelector.LensFacing int lensFacing = (int) EffectLensFacingPair[1];
assumeTrue(CameraUtil.hasCameraWithLensFacing(lensFacing));
assumeTrue(ExtensionsManager.isExtensionAvailable(effectMode, lensFacing));
// Retrieves the target format/resolutions pair list from vendor library for the
// target effect mode.
ImageCaptureExtenderImpl impl = ExtensionsTestUtil.createImageCaptureExtenderImpl(
effectMode, lensFacing);
// NoSuchMethodError will be thrown if getSupportedResolutions is not
// implemented in vendor library, and then the test will fail.
impl.getSupportedResolutions();
}
}
}
| 39.680851 | 94 | 0.752011 |
f7be299207ad06a089daba84ce4a2cbb4b2a0c79 | 20,000 | package io.deephaven.grpc_api.flight;
import dagger.BindsInstance;
import dagger.Component;
import dagger.Module;
import dagger.Provides;
import dagger.multibindings.IntoSet;
import io.deephaven.base.verify.Assert;
import io.deephaven.db.tables.Table;
import io.deephaven.db.tables.live.LiveTableMonitor;
import io.deephaven.db.tables.utils.TableDiff;
import io.deephaven.db.tables.utils.TableTools;
import io.deephaven.db.util.AbstractScriptSession;
import io.deephaven.db.util.NoLanguageDeephavenSession;
import io.deephaven.db.util.liveness.LivenessScopeStack;
import io.deephaven.grpc_api.arrow.FlightServiceGrpcBinding;
import io.deephaven.grpc_api.auth.AuthContextModule;
import io.deephaven.extensions.barrage.util.BarrageUtil;
import io.deephaven.grpc_api.console.GlobalSessionProvider;
import io.deephaven.grpc_api.console.ScopeTicketResolver;
import io.deephaven.grpc_api.arrow.ArrowModule;
import io.deephaven.grpc_api.session.SessionModule;
import io.deephaven.grpc_api.session.SessionService;
import io.deephaven.grpc_api.session.SessionServiceGrpcImpl;
import io.deephaven.grpc_api.session.SessionState;
import io.deephaven.grpc_api.session.TicketResolver;
import io.deephaven.grpc_api.util.FlightExportTicketHelper;
import io.deephaven.grpc_api.util.Scheduler;
import io.deephaven.proto.backplane.grpc.HandshakeRequest;
import io.deephaven.proto.backplane.grpc.HandshakeResponse;
import io.deephaven.proto.backplane.grpc.SessionServiceGrpc;
import io.deephaven.util.SafeCloseable;
import io.grpc.*;
import io.grpc.netty.NettyServerBuilder;
import org.apache.arrow.flight.*;
import org.apache.arrow.flight.impl.Flight;
import org.apache.arrow.memory.RootAllocator;
import org.apache.arrow.vector.VectorSchemaRoot;
import org.apache.arrow.vector.types.pojo.ArrowType;
import org.apache.arrow.vector.types.pojo.Field;
import org.apache.arrow.vector.types.pojo.Schema;
import org.apache.commons.lang3.mutable.MutableInt;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExternalResource;
import javax.inject.Named;
import javax.inject.Singleton;
import java.io.IOException;
import java.util.EnumSet;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import static org.junit.Assert.*;
/**
* Deliberately much lower in scope (and running time) than BarrageMessageRoundTripTest, the only purpose of this test
* is to verify that we can round trip
*/
public class FlightMessageRoundTripTest {
@Module
public static class FlightTestModule {
@IntoSet
@Provides
TicketResolver ticketResolver(ScopeTicketResolver resolver) {
return resolver;
}
@Provides
AbstractScriptSession createGlobalScriptSession(GlobalSessionProvider sessionProvider) {
final AbstractScriptSession scriptSession = new NoLanguageDeephavenSession("non-script-session");
sessionProvider.initializeGlobalScriptSession(scriptSession);
return scriptSession;
}
}
@Singleton
@Component(modules = {
FlightTestModule.class,
ArrowModule.class,
SessionModule.class,
AuthContextModule.class
})
public interface TestComponent {
Set<ServerInterceptor> interceptors();
FlightServiceGrpcBinding flightService();
SessionServiceGrpcImpl sessionGrpcService();
SessionService sessionService();
AbstractScriptSession scriptSession();
@Component.Builder
interface Builder {
@BindsInstance
Builder withScheduler(final Scheduler scheduler);
@BindsInstance
Builder withSessionTokenExpireTmMs(@Named("session.tokenExpireMs") long tokenExpireMs);
TestComponent build();
}
}
private Server server;
private ManagedChannel channel;
private FlightClient client;
private UUID sessionToken;
private SessionState currentSession;
private AbstractScriptSession scriptSession;
@Before
public void setup() throws IOException {
TestComponent component = DaggerFlightMessageRoundTripTest_TestComponent
.builder()
.withScheduler(new Scheduler.DelegatingImpl(Executors.newSingleThreadExecutor(),
Executors.newScheduledThreadPool(1)))
.withSessionTokenExpireTmMs(60_000_000)
.build();
NettyServerBuilder serverBuilder = NettyServerBuilder.forPort(0);
component.interceptors().forEach(serverBuilder::intercept);
serverBuilder.addService(component.sessionGrpcService());
serverBuilder.addService(component.flightService());
server = serverBuilder.build().start();
int actualPort = server.getPort();
scriptSession = component.scriptSession();
client = FlightClient.builder().location(Location.forGrpcInsecure("localhost", actualPort))
.allocator(new RootAllocator()).intercept(info -> new FlightClientMiddleware() {
@Override
public void onBeforeSendingHeaders(CallHeaders outgoingHeaders) {
final UUID currSession = sessionToken;
if (currSession != null) {
outgoingHeaders.insert(SessionServiceGrpcImpl.DEEPHAVEN_SESSION_ID, currSession.toString());
}
}
@Override
public void onHeadersReceived(CallHeaders incomingHeaders) {}
@Override
public void onCallCompleted(CallStatus status) {}
}).build();
channel = ManagedChannelBuilder.forTarget("localhost:" + actualPort)
.usePlaintext()
.build();
SessionServiceGrpc.SessionServiceBlockingStub sessionServiceClient =
SessionServiceGrpc.newBlockingStub(channel);
HandshakeResponse response =
sessionServiceClient.newSession(HandshakeRequest.newBuilder().setAuthProtocol(1).build());
assertNotNull(response.getSessionToken());
sessionToken = UUID.fromString(response.getSessionToken().toStringUtf8());
currentSession = component.sessionService().getSessionForToken(sessionToken);
}
@After
public void teardown() {
scriptSession.release();
channel.shutdown();
server.shutdown();
try {
channel.awaitTermination(1, TimeUnit.MINUTES);
server.awaitTermination(1, TimeUnit.MINUTES);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException(e);
} finally {
channel.shutdownNow();
channel = null;
server.shutdownNow();
server = null;
}
}
@Rule
public final ExternalResource livenessRule = new ExternalResource() {
SafeCloseable scope;
@Override
protected void before() {
scope = LivenessScopeStack.open();
}
@Override
protected void after() {
if (scope != null) {
scope.close();
scope = null;
}
}
};
@Test
public void testSimpleEmptyTableDoGet() {
Flight.Ticket simpleTableTicket = FlightExportTicketHelper.exportIdToFlightTicket(1);
currentSession.newExport(simpleTableTicket, "test")
.submit(() -> TableTools.emptyTable(10).update("I=i"));
FlightStream stream = client.getStream(new Ticket(simpleTableTicket.getTicket().toByteArray()));
assertTrue(stream.next());
VectorSchemaRoot root = stream.getRoot();
// row count should match what we expect
assertEquals(10, root.getRowCount());
// only one column was sent
assertEquals(1, root.getFieldVectors().size());
Field i = root.getSchema().findField("I");
// all DH columns are nullable, even primitives
assertTrue(i.getFieldType().isNullable());
// verify it is a java int type, which is an arrow 32bit int
assertEquals(ArrowType.ArrowTypeID.Int, i.getFieldType().getType().getTypeID());
assertEquals(32, ((ArrowType.Int) i.getFieldType().getType()).getBitWidth());
assertEquals("int", i.getMetadata().get("deephaven:type"));
// verify that the server didn't send more data after the first payload
assertFalse(stream.next());
}
@Test
public void testRoundTripData() throws InterruptedException, ExecutionException {
// tables without columns, as flight-based way of doing emptyTable
assertRoundTripDataEqual(TableTools.emptyTable(0));
assertRoundTripDataEqual(TableTools.emptyTable(10));
// simple values, no nulls
assertRoundTripDataEqual(TableTools.emptyTable(10).update("empty=String.valueOf(i)"));
assertRoundTripDataEqual(TableTools.emptyTable(10).update("empty=(int)i"));
assertRoundTripDataEqual(TableTools.emptyTable(10).update("empty=\"\""));
assertRoundTripDataEqual(TableTools.emptyTable(10).update("empty=0"));
// non-flat index
assertRoundTripDataEqual(TableTools.emptyTable(10).where("i % 2 == 0").update("I=i"));
// all null values in columns
assertRoundTripDataEqual(TableTools.emptyTable(10).update("empty=(int)null"));
assertRoundTripDataEqual(TableTools.emptyTable(10).update("empty=(String)null"));
// some nulls in columns
assertRoundTripDataEqual(TableTools.emptyTable(10).update("empty= ((i % 2) == 0) ? i : (int)null"));
assertRoundTripDataEqual(
TableTools.emptyTable(10).update("empty= ((i % 2) == 0) ? String.valueOf(i) : (String)null"));
// list columns TODO(#755): support for DBArray
// assertRoundTripDataEqual(TableTools.emptyTable(5).update("A=i").by().join(TableTools.emptyTable(5)));
}
@Test
public void testTimestampColumn() throws InterruptedException, ExecutionException {
assertRoundTripDataEqual(TableTools.emptyTable(10).update("tm = DBDateTime.now()"));
}
@Test
public void testStringCol() throws InterruptedException, ExecutionException {
assertRoundTripDataEqual(TableTools.emptyTable(10).update("S = \"test\""));
assertRoundTripDataEqual(TableTools.emptyTable(10).update("S = new String[] {\"test\", \"42\"}"));
assertRoundTripDataEqual(TableTools.emptyTable(10).update("S = new String[][] {new String[] {\"t1\"}}"));
assertRoundTripDataEqual(TableTools.emptyTable(10).update("S = new String[][][] {" +
"null, new String[][] {" +
" null, " +
" new String[] {" +
" null, \"elem_1_1_1\"" +
"}}, new String[][] {" +
" null, " +
" new String[] {" +
" null, \"elem_2_1_1\"" +
" }, new String[] {" +
" null, \"elem_2_2_1\", \"elem_2_2_2\"" +
"}}, new String[][] {" +
" null, " +
" new String[] {" +
" null, \"elem_3_1_1\"" +
" }, new String[] {" +
" null, \"elem_3_2_1\", \"elem_3_2_2\"" +
" }, new String[] {" +
" null, \"elem_3_3_1\", \"elem_3_3_2\", \"elem_3_3_3\"" +
"}}}"));
}
@Test
public void testLongCol() throws InterruptedException, ExecutionException {
assertRoundTripDataEqual(TableTools.emptyTable(10).update("L = ii"));
assertRoundTripDataEqual(TableTools.emptyTable(10).update("L = new long[] {ii}"));
assertRoundTripDataEqual(TableTools.emptyTable(10).update("L = new long[][] {new long[] {ii}}"));
assertRoundTripDataEqual(TableTools.emptyTable(10).update("L = (Long)ii"));
assertRoundTripDataEqual(TableTools.emptyTable(10).update("L = new Long[] {ii}"));
assertRoundTripDataEqual(TableTools.emptyTable(10).update("L = new Long[] {ii, null}"));
assertRoundTripDataEqual(TableTools.emptyTable(10).update("L = new Long[][] {new Long[] {ii}}"));
assertRoundTripDataEqual(TableTools.emptyTable(10).update("L = new Long[][] {null, new Long[] {null, ii}}"));
assertRoundTripDataEqual(TableTools.emptyTable(10).update("L = io.deephaven.util.QueryConstants.NULL_LONG"));
assertRoundTripDataEqual(
TableTools.emptyTable(10).update("L = new long[] {0, -1, io.deephaven.util.QueryConstants.NULL_LONG}"));
}
@Test
public void testFlightInfo() {
final String staticTableName = "flightInfoTest";
final String tickingTableName = "flightInfoTestTicking";
final Table table = TableTools.emptyTable(10).update("I = i");
final Table tickingTable = LiveTableMonitor.DEFAULT.sharedLock()
.computeLocked(() -> TableTools.timeTable(1_000_000).update("I = i"));
// stuff table into the scope
scriptSession.setVariable(staticTableName, table);
scriptSession.setVariable(tickingTableName, tickingTable);
// test fetch info from scoped ticket
assertInfoMatchesTable(client.getInfo(arrowFlightDescriptorForName(staticTableName)), table);
assertInfoMatchesTable(client.getInfo(arrowFlightDescriptorForName(tickingTableName)), tickingTable);
// test list flights which runs through scoped tickets
final MutableInt seenTables = new MutableInt();
client.listFlights(Criteria.ALL).forEach(fi -> {
seenTables.increment();
if (fi.getDescriptor().equals(arrowFlightDescriptorForName(staticTableName))) {
assertInfoMatchesTable(fi, table);
} else {
assertInfoMatchesTable(fi, tickingTable);
}
});
Assert.eq(seenTables.intValue(), "seenTables.intValue()", 2);
}
@Test
public void testGetSchema() {
final String staticTableName = "flightInfoTest";
final String tickingTableName = "flightInfoTestTicking";
final Table table = TableTools.emptyTable(10).update("I = i");
final Table tickingTable = LiveTableMonitor.DEFAULT.sharedLock()
.computeLocked(() -> TableTools.timeTable(1_000_000).update("I = i"));
try (final SafeCloseable ignored = LivenessScopeStack.open(scriptSession, false)) {
// stuff table into the scope
scriptSession.setVariable(staticTableName, table);
scriptSession.setVariable(tickingTableName, tickingTable);
// test fetch info from scoped ticket
assertSchemaMatchesTable(client.getSchema(arrowFlightDescriptorForName(staticTableName)).getSchema(),
table);
assertSchemaMatchesTable(client.getSchema(arrowFlightDescriptorForName(tickingTableName)).getSchema(),
tickingTable);
// test list flights which runs through scoped tickets
final MutableInt seenTables = new MutableInt();
client.listFlights(Criteria.ALL).forEach(fi -> {
seenTables.increment();
if (fi.getDescriptor().equals(arrowFlightDescriptorForName(staticTableName))) {
assertInfoMatchesTable(fi, table);
} else {
assertInfoMatchesTable(fi, tickingTable);
}
});
Assert.eq(seenTables.intValue(), "seenTables.intValue()", 2);
}
}
private static FlightDescriptor arrowFlightDescriptorForName(String name) {
return FlightDescriptor.path(ScopeTicketResolver.descriptorForName(name).getPathList());
}
@Test
public void testExportTicketVisibility() {
// we have decided that if an api client creates export tickets, that they probably gain no value from
// seeing them via Flight's listFlights but we do want them to work with getFlightInfo (or anywhere else a
// flight ticket can be resolved).
final Flight.Ticket ticket = FlightExportTicketHelper.exportIdToFlightTicket(1);
final Table table = TableTools.emptyTable(10).update("I = i");
currentSession.newExport(ticket, "test").submit(() -> table);
// test fetch info from export ticket
final FlightInfo info = client.getInfo(FlightDescriptor.path("export", "1"));
assertInfoMatchesTable(info, table);
// test list flights which runs through scoped tickets
client.listFlights(Criteria.ALL).forEach(fi -> {
throw new IllegalStateException("should not be included in list flights");
});
}
private void assertInfoMatchesTable(FlightInfo info, Table table) {
if (table.isLive()) {
Assert.eq(info.getRecords(), "info.getRecords()", -1);
} else {
Assert.eq(info.getRecords(), "info.getRecords()", table.size(), "table.size()");
}
// we don't try to compute this for the user; verify we are sending UNKNOWN instead of 0
Assert.eq(info.getBytes(), "info.getBytes()", -1L);
assertSchemaMatchesTable(info.getSchema(), table);
}
private void assertSchemaMatchesTable(Schema schema, Table table) {
Assert.eq(schema.getFields().size(), "schema.getFields().size()", table.getColumns().length,
"table.getColumns().length");
Assert.equals(BarrageUtil.convertArrowSchema(schema).tableDef,
"BarrageUtil.convertArrowSchema(schema)",
table.getDefinition(), "table.getDefinition()");
}
private static int nextTicket = 1;
private void assertRoundTripDataEqual(Table deephavenTable) throws InterruptedException, ExecutionException {
// bind the table in the session
Flight.Ticket dhTableTicket = FlightExportTicketHelper.exportIdToFlightTicket(nextTicket++);
currentSession.newExport(dhTableTicket, "test").submit(() -> deephavenTable);
// fetch with DoGet
FlightStream stream = client.getStream(new Ticket(dhTableTicket.getTicket().toByteArray()));
VectorSchemaRoot root = stream.getRoot();
// start the DoPut and send the schema
int flightDescriptorTicketValue = nextTicket++;
FlightDescriptor descriptor = FlightDescriptor.path("export", flightDescriptorTicketValue + "");
FlightClient.ClientStreamListener putStream = client.startPut(descriptor, root, new AsyncPutListener());
// send the body of the table
while (stream.next()) {
putStream.putNext();
}
// tell the server we are finished sending data
putStream.completed();
// get the table that was uploaded, and confirm it matches what we originally sent
CompletableFuture<Table> tableFuture = new CompletableFuture<>();
SessionState.ExportObject<Table> tableExport = currentSession.getExport(flightDescriptorTicketValue);
currentSession.nonExport()
.onErrorHandler(exception -> tableFuture.cancel(true))
.require(tableExport)
.submit(() -> tableFuture.complete(tableExport.get()));
// block until we're done, so we can get the table and see what is inside
putStream.getResult();
Table uploadedTable = tableFuture.get();
// check that contents match
assertEquals(deephavenTable.size(), uploadedTable.size());
assertEquals(deephavenTable.getDefinition(), uploadedTable.getDefinition());
assertEquals(0, (long) TableTools
.diffPair(deephavenTable, uploadedTable, 0, EnumSet.noneOf(TableDiff.DiffItems.class)).getSecond());
}
}
| 42.918455 | 120 | 0.6594 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.