repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15
values |
|---|---|---|---|---|
awushensky/checkers | checkers/src/main/java/edu/unlv/sudo/checkers/service/impl/GameServiceLocalImpl.java | 1381 | package edu.unlv.sudo.checkers.service.impl;
import java.util.HashMap;
import java.util.Map;
import edu.unlv.sudo.checkers.model.Board;
import edu.unlv.sudo.checkers.model.Game;
import edu.unlv.sudo.checkers.model.Team;
import edu.unlv.sudo.checkers.service.GameService;
/**
* This {@link GameService} locally stores games and runs them.
*/
public class GameServiceLocalImpl implements GameService {
//TODO: this is a temporary placeholder - remove it?
final Map<String, Game> games = new HashMap<>();
int gameNum = 0;
@Override
public void move(final String gameId, final Board board, final Listener listener) {
final Game game = games.get(gameId);
final Team turn = game.getTurn() == Team.RED ? Team.BLACK : Team.RED;
listener.onGame(new Game(gameId, board, turn));
}
@Override
public void joinGame(final String gameId, final Team team, final Listener listener) {
listener.onGame(games.get(gameId));
}
@Override
public void newGame(final Team team, final Listener listener) {
final String gameId = "game" + gameNum++;
final Game game = new Game(gameId, Team.BLACK);
games.put(gameId, game);
listener.onGame(game);
}
@Override
public void update(final String gameId, final Listener listener) {
listener.onGame(games.get(gameId));
}
}
| apache-2.0 |
aws/aws-sdk-java | aws-java-sdk-iot/src/main/java/com/amazonaws/services/iot/model/transform/ListSecurityProfilesForTargetRequestProtocolMarshaller.java | 2832 | /*
* 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.iot.model.transform;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.Request;
import com.amazonaws.http.HttpMethodName;
import com.amazonaws.services.iot.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.protocol.*;
import com.amazonaws.protocol.Protocol;
import com.amazonaws.annotation.SdkInternalApi;
/**
* ListSecurityProfilesForTargetRequest Marshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class ListSecurityProfilesForTargetRequestProtocolMarshaller implements
Marshaller<Request<ListSecurityProfilesForTargetRequest>, ListSecurityProfilesForTargetRequest> {
private static final OperationInfo SDK_OPERATION_BINDING = OperationInfo.builder().protocol(Protocol.REST_JSON).requestUri("/security-profiles-for-target")
.httpMethodName(HttpMethodName.GET).hasExplicitPayloadMember(false).hasPayloadMembers(false).serviceName("AWSIot").build();
private final com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory;
public ListSecurityProfilesForTargetRequestProtocolMarshaller(com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory) {
this.protocolFactory = protocolFactory;
}
public Request<ListSecurityProfilesForTargetRequest> marshall(ListSecurityProfilesForTargetRequest listSecurityProfilesForTargetRequest) {
if (listSecurityProfilesForTargetRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
final ProtocolRequestMarshaller<ListSecurityProfilesForTargetRequest> protocolMarshaller = protocolFactory.createProtocolMarshaller(
SDK_OPERATION_BINDING, listSecurityProfilesForTargetRequest);
protocolMarshaller.startMarshalling();
ListSecurityProfilesForTargetRequestMarshaller.getInstance().marshall(listSecurityProfilesForTargetRequest, protocolMarshaller);
return protocolMarshaller.finishMarshalling();
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
}
}
| apache-2.0 |
kangaroo-server/kangaroo | kangaroo-common/src/test/java/net/krotscheck/kangaroo/common/status/PoweredByFilterTest.java | 2173 | /*
* Copyright (c) 2017 Michael Krotscheck
*
* 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 net.krotscheck.kangaroo.common.status;
import com.google.common.net.HttpHeaders;
import net.krotscheck.kangaroo.test.jersey.KangarooJerseyTest;
import org.glassfish.jersey.server.ResourceConfig;
import org.junit.Test;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import static org.junit.Assert.assertEquals;
/**
* Test the "Powered-By" filter.
*
* @author Michael Krotscheck
*/
public final class PoweredByFilterTest extends KangarooJerseyTest {
/**
* Build an application.
*
* @return A configured application.
*/
@Override
protected ResourceConfig createApplication() {
ResourceConfig config = new ResourceConfig();
config.register(PoweredByFilter.class);
config.register(MockService.class);
return config;
}
/**
* Assert that the jackson feature is available.
*/
@Test
public void testFilters() {
Response r = target("/").request().get();
assertEquals("Kangaroo",
r.getHeaderString(HttpHeaders.X_POWERED_BY));
}
/**
* A simple endpoint.
*
* @author Michael Krotscheck
*/
@Path("/")
public static final class MockService {
/**
* Return OK.
*
* @return Nothing, error thrown.
*/
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response modifyPojo() {
return Response.ok().build();
}
}
}
| apache-2.0 |
dump247/aws-sdk-java | aws-java-sdk-ec2/src/main/java/com/amazonaws/services/ec2/model/transform/PriceScheduleStaxUnmarshaller.java | 3162 | /*
* Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights
* Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.services.ec2.model.transform;
import java.util.Map;
import java.util.Map.Entry;
import javax.xml.stream.events.XMLEvent;
import com.amazonaws.services.ec2.model.*;
import com.amazonaws.transform.Unmarshaller;
import com.amazonaws.transform.MapEntry;
import com.amazonaws.transform.StaxUnmarshallerContext;
import com.amazonaws.transform.SimpleTypeStaxUnmarshallers.*;
/**
* PriceSchedule StAX Unmarshaller
*/
public class PriceScheduleStaxUnmarshaller implements
Unmarshaller<PriceSchedule, StaxUnmarshallerContext> {
public PriceSchedule unmarshall(StaxUnmarshallerContext context)
throws Exception {
PriceSchedule priceSchedule = new PriceSchedule();
int originalDepth = context.getCurrentDepth();
int targetDepth = originalDepth + 1;
if (context.isStartOfDocument())
targetDepth += 1;
while (true) {
XMLEvent xmlEvent = context.nextEvent();
if (xmlEvent.isEndDocument())
return priceSchedule;
if (xmlEvent.isAttribute() || xmlEvent.isStartElement()) {
if (context.testExpression("term", targetDepth)) {
priceSchedule.setTerm(LongStaxUnmarshaller.getInstance()
.unmarshall(context));
continue;
}
if (context.testExpression("price", targetDepth)) {
priceSchedule.setPrice(DoubleStaxUnmarshaller.getInstance()
.unmarshall(context));
continue;
}
if (context.testExpression("currencyCode", targetDepth)) {
priceSchedule.setCurrencyCode(StringStaxUnmarshaller
.getInstance().unmarshall(context));
continue;
}
if (context.testExpression("active", targetDepth)) {
priceSchedule.setActive(BooleanStaxUnmarshaller
.getInstance().unmarshall(context));
continue;
}
} else if (xmlEvent.isEndElement()) {
if (context.getCurrentDepth() < originalDepth) {
return priceSchedule;
}
}
}
}
private static PriceScheduleStaxUnmarshaller instance;
public static PriceScheduleStaxUnmarshaller getInstance() {
if (instance == null)
instance = new PriceScheduleStaxUnmarshaller();
return instance;
}
}
| apache-2.0 |
cstamas/krati | src/test/java/test/store/TestDynamicStoreChannel.java | 340 | package test.store;
import krati.core.segment.SegmentFactory;
/**
* TestDynamicStore using ChannleSegment.
*
* @author jwu
*
*/
public class TestDynamicStoreChannel extends TestDynamicStore
{
@Override
protected SegmentFactory getSegmentFactory()
{
return new krati.core.segment.ChannelSegmentFactory();
}
}
| apache-2.0 |
lucastheisen/mina-sshd | sshd-fs/src/main/java/org/apache/sftp/protocol/packetdata/Remove.java | 176 | package org.apache.sftp.protocol.packetdata;
import org.apache.sftp.protocol.Request;
public interface Remove extends BasePath<Remove>, Request<Remove, Status> {
}
| apache-2.0 |
googleapis/google-api-java-client-services | clients/google-api-services-documentai/v1/1.31.0/com/google/api/services/documentai/v1/model/GoogleTypeDateTime.java | 8908 | /*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
/*
* This code was generated by https://github.com/googleapis/google-api-java-client-services/
* Modify at your own risk.
*/
package com.google.api.services.documentai.v1.model;
/**
* Represents civil time (or occasionally physical time). This type can represent a civil time in
* one of a few possible ways: * When utc_offset is set and time_zone is unset: a civil time on a
* calendar day with a particular offset from UTC. * When time_zone is set and utc_offset is unset:
* a civil time on a calendar day in a particular time zone. * When neither time_zone nor utc_offset
* is set: a civil time on a calendar day in local time. The date is relative to the Proleptic
* Gregorian Calendar. If year is 0, the DateTime is considered not to have a specific year. month
* and day must have valid, non-zero values. This type may also be used to represent a physical time
* if all the date and time fields are set and either case of the `time_offset` oneof is set.
* Consider using `Timestamp` message for physical time instead. If your use case also would like to
* store the user's timezone, that can be done in another field. This type is more flexible than
* some applications may want. Make sure to document and validate your application's limitations.
*
* <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is
* transmitted over HTTP when working with the Cloud Document AI API. For a detailed explanation
* see:
* <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a>
* </p>
*
* @author Google, Inc.
*/
@SuppressWarnings("javadoc")
public final class GoogleTypeDateTime extends com.google.api.client.json.GenericJson {
/**
* Required. Day of month. Must be from 1 to 31 and valid for the year and month.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Integer day;
/**
* Required. Hours of day in 24 hour format. Should be from 0 to 23. An API may choose to allow
* the value "24:00:00" for scenarios like business closing time.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Integer hours;
/**
* Required. Minutes of hour of day. Must be from 0 to 59.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Integer minutes;
/**
* Required. Month of year. Must be from 1 to 12.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Integer month;
/**
* Required. Fractions of seconds in nanoseconds. Must be from 0 to 999,999,999.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Integer nanos;
/**
* Required. Seconds of minutes of the time. Must normally be from 0 to 59. An API may allow the
* value 60 if it allows leap-seconds.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Integer seconds;
/**
* Time zone.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private GoogleTypeTimeZone timeZone;
/**
* UTC offset. Must be whole seconds, between -18 hours and +18 hours. For example, a UTC offset
* of -4:00 would be represented as { seconds: -14400 }.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private String utcOffset;
/**
* Optional. Year of date. Must be from 1 to 9999, or 0 if specifying a datetime without a year.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Integer year;
/**
* Required. Day of month. Must be from 1 to 31 and valid for the year and month.
* @return value or {@code null} for none
*/
public java.lang.Integer getDay() {
return day;
}
/**
* Required. Day of month. Must be from 1 to 31 and valid for the year and month.
* @param day day or {@code null} for none
*/
public GoogleTypeDateTime setDay(java.lang.Integer day) {
this.day = day;
return this;
}
/**
* Required. Hours of day in 24 hour format. Should be from 0 to 23. An API may choose to allow
* the value "24:00:00" for scenarios like business closing time.
* @return value or {@code null} for none
*/
public java.lang.Integer getHours() {
return hours;
}
/**
* Required. Hours of day in 24 hour format. Should be from 0 to 23. An API may choose to allow
* the value "24:00:00" for scenarios like business closing time.
* @param hours hours or {@code null} for none
*/
public GoogleTypeDateTime setHours(java.lang.Integer hours) {
this.hours = hours;
return this;
}
/**
* Required. Minutes of hour of day. Must be from 0 to 59.
* @return value or {@code null} for none
*/
public java.lang.Integer getMinutes() {
return minutes;
}
/**
* Required. Minutes of hour of day. Must be from 0 to 59.
* @param minutes minutes or {@code null} for none
*/
public GoogleTypeDateTime setMinutes(java.lang.Integer minutes) {
this.minutes = minutes;
return this;
}
/**
* Required. Month of year. Must be from 1 to 12.
* @return value or {@code null} for none
*/
public java.lang.Integer getMonth() {
return month;
}
/**
* Required. Month of year. Must be from 1 to 12.
* @param month month or {@code null} for none
*/
public GoogleTypeDateTime setMonth(java.lang.Integer month) {
this.month = month;
return this;
}
/**
* Required. Fractions of seconds in nanoseconds. Must be from 0 to 999,999,999.
* @return value or {@code null} for none
*/
public java.lang.Integer getNanos() {
return nanos;
}
/**
* Required. Fractions of seconds in nanoseconds. Must be from 0 to 999,999,999.
* @param nanos nanos or {@code null} for none
*/
public GoogleTypeDateTime setNanos(java.lang.Integer nanos) {
this.nanos = nanos;
return this;
}
/**
* Required. Seconds of minutes of the time. Must normally be from 0 to 59. An API may allow the
* value 60 if it allows leap-seconds.
* @return value or {@code null} for none
*/
public java.lang.Integer getSeconds() {
return seconds;
}
/**
* Required. Seconds of minutes of the time. Must normally be from 0 to 59. An API may allow the
* value 60 if it allows leap-seconds.
* @param seconds seconds or {@code null} for none
*/
public GoogleTypeDateTime setSeconds(java.lang.Integer seconds) {
this.seconds = seconds;
return this;
}
/**
* Time zone.
* @return value or {@code null} for none
*/
public GoogleTypeTimeZone getTimeZone() {
return timeZone;
}
/**
* Time zone.
* @param timeZone timeZone or {@code null} for none
*/
public GoogleTypeDateTime setTimeZone(GoogleTypeTimeZone timeZone) {
this.timeZone = timeZone;
return this;
}
/**
* UTC offset. Must be whole seconds, between -18 hours and +18 hours. For example, a UTC offset
* of -4:00 would be represented as { seconds: -14400 }.
* @return value or {@code null} for none
*/
public String getUtcOffset() {
return utcOffset;
}
/**
* UTC offset. Must be whole seconds, between -18 hours and +18 hours. For example, a UTC offset
* of -4:00 would be represented as { seconds: -14400 }.
* @param utcOffset utcOffset or {@code null} for none
*/
public GoogleTypeDateTime setUtcOffset(String utcOffset) {
this.utcOffset = utcOffset;
return this;
}
/**
* Optional. Year of date. Must be from 1 to 9999, or 0 if specifying a datetime without a year.
* @return value or {@code null} for none
*/
public java.lang.Integer getYear() {
return year;
}
/**
* Optional. Year of date. Must be from 1 to 9999, or 0 if specifying a datetime without a year.
* @param year year or {@code null} for none
*/
public GoogleTypeDateTime setYear(java.lang.Integer year) {
this.year = year;
return this;
}
@Override
public GoogleTypeDateTime set(String fieldName, Object value) {
return (GoogleTypeDateTime) super.set(fieldName, value);
}
@Override
public GoogleTypeDateTime clone() {
return (GoogleTypeDateTime) super.clone();
}
}
| apache-2.0 |
SharedHealth/openmrs-module-bdshrclient | fhirmapper/src/test/java/org/openmrs/module/fhir/mapper/model/EntityReferenceTest.java | 6612 | package org.openmrs.module.fhir.mapper.model;
import org.hl7.fhir.dstu3.model.BaseResource;
import org.junit.Test;
import org.openmrs.Encounter;
import org.openmrs.Location;
import org.openmrs.Patient;
import org.openmrs.Provider;
import org.openmrs.module.fhir.utils.PropertyKeyConstants;
import org.openmrs.module.shrclient.util.SystemProperties;
import java.util.HashMap;
import java.util.Properties;
import static org.junit.Assert.assertEquals;
import static org.openmrs.module.fhir.utils.PropertyKeyConstants.FACILITY_URL_FORMAT;
import static org.openmrs.module.fhir.utils.PropertyKeyConstants.PROVIDER_REFERENCE_PATH;
public class EntityReferenceTest {
@Test
public void shouldDefaultToIdForTypesNotDefined() {
EntityReference entityReference = new EntityReference();
assertEquals("urn:uuid:1", entityReference.build(Integer.class, getSystemProperties(), "1"));
}
/**
* NOTE: while communicating with the SHR and building encounter document, the public url should be used.
* Because it is possible that an internal application may use SHR using IP address or url not exposed to public http
*/
@Test
public void shouldCreatePatientReference() {
EntityReference entityReference = new EntityReference();
assertEquals("http://mci.com/api/default/patients/1", entityReference.build(Patient.class, getSystemProperties(), "1"));
}
@Test
public void shouldParseMciPatientUrl() throws Exception {
EntityReference entityReference = new EntityReference();
String hid = "hid";
assertEquals(hid, entityReference.parse(Patient.class, "http://mci.com/api/v1/patient/" + hid));
}
@Test
public void shouldParseEncounterUrl() {
EntityReference entityReference = new EntityReference();
assertEquals("enc1", entityReference.parse(Encounter.class, "http://shr.com/patients/hid1/encounters/enc1"));
}
@Test
public void shouldGetEncounterIdFromResourceUrl() {
EntityReference entityReference = new EntityReference();
assertEquals("enc1", entityReference.parse(Encounter.class, "http://shr.com/patients/hid1/encounters/enc1#MedicationRequest/order1"));
}
@Test(expected = RuntimeException.class)
public void shouldNotCreateEncounterReferenceWithOnlyId() {
EntityReference entityReference = new EntityReference();
entityReference.build(Encounter.class, getSystemProperties(), "1");
}
@Test
public void shouldCreateEncounterReferenceFromHealthIdAndEncounterId() {
EntityReference entityReference = new EntityReference();
String encounterUrl = entityReference.build(Encounter.class, getSystemProperties(), new HashMap<String, String>() {{
put(EntityReference.HEALTH_ID_REFERENCE, "hid1");
put(EntityReference.REFERENCE_ID, "enc1");
}});
assertEquals("http://shr.com/patients/hid1/encounters/enc1", encounterUrl);
}
/**
* NOTE: while communicating with the SHR and building encounter document, the public url should be used.
* Because it is possible that an internal application may use SHR using IP address or url not exposed to public http
*/
@Test
public void shouldCreateFacilityLocationReference() {
EntityReference entityReference = new EntityReference();
assertEquals("http://fr.com/api/1.0/facilities/1234.json", entityReference.build(Location.class, getSystemProperties(), "1234"));
}
@Test
public void shouldParseFacilityLocationReference() throws Exception {
EntityReference entityReference = new EntityReference();
String facilityId = "1013101";
assertEquals(facilityId, entityReference.parse(Location.class, "http://public.com/api/1.0/facilities/1013101.json" + facilityId + ".json"));
}
@Test
public void shouldCreateProviderReference() {
EntityReference entityReference = new EntityReference();
assertEquals("http://example.com/api/1.0/providers/1234.json", entityReference.build(Provider.class, getSystemProperties(), "1234"));
}
@Test
public void shouldParseProviderUrl() {
EntityReference entityReference = new EntityReference();
assertEquals("1234", entityReference.parse(Provider.class, "http://example.com/api/1.0/providers/1234.json"));
}
@Test(expected = RuntimeException.class)
public void shouldNotCreateFHIRResourceReferenceWithOnlyId() {
EntityReference entityReference = new EntityReference();
entityReference.build(BaseResource.class, getSystemProperties(), "1234");
}
@Test
public void shouldCreateFHIRResourceUrl() {
EntityReference entityReference = new EntityReference();
String resourceUrl = entityReference.build(BaseResource.class, getSystemProperties(), new HashMap<String, String>() {{
put(EntityReference.HEALTH_ID_REFERENCE, "hid1");
put(EntityReference.ENCOUNTER_ID_REFERENCE, "enc1");
put(EntityReference.REFERENCE_RESOURCE_NAME, "MedicationRequest");
put(EntityReference.REFERENCE_ID, "resource-1");
}});
assertEquals("http://shr.com/patients/hid1/encounters/enc1#MedicationRequest/resource-1", resourceUrl);
}
private SystemProperties getSystemProperties() {
Properties shrProperties = new Properties();
shrProperties.put(PropertyKeyConstants.SHR_REFERENCE_PATH, "http://shr.com/");
shrProperties.put(PropertyKeyConstants.SHR_PATIENT_ENC_PATH_PATTERN, "patients/%s/encounters");
Properties trProperties = new Properties();
Properties frProperties = new Properties();
frProperties.setProperty(FACILITY_URL_FORMAT, "foo-bar/%s.json");
frProperties.setProperty(PropertyKeyConstants.FACILITY_REFERENCE_PATH, "http://fr.com/api/1.0/facilities");
Properties prPoperties = new Properties();
prPoperties.setProperty(PROVIDER_REFERENCE_PATH, "http://example.com/api/1.0/providers");
Properties facilityInstanceProperties = new Properties();
HashMap<String, String> baseUrls = new HashMap<>();
baseUrls.put("mci", "http://mci");
baseUrls.put("fr", "http://fr");
Properties mciProperties = new Properties();
mciProperties.put(PropertyKeyConstants.MCI_REFERENCE_PATH, "http://mci.com/");
mciProperties.put(PropertyKeyConstants.MCI_PATIENT_CONTEXT, "/api/default/patients");
return new SystemProperties(frProperties, trProperties, prPoperties, facilityInstanceProperties, mciProperties, shrProperties, null);
}
} | apache-2.0 |
robertamarton/incubator-trafodion | core/sql/src/main/java/org/trafodion/sql/udr/OrderInfo.java | 6989 | // @@@ START COPYRIGHT @@@
//
// 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.
//
// @@@ END COPYRIGHT @@@
package org.trafodion.sql.udr;
import org.trafodion.sql.udr.UDRException;
import java.util.Vector;
/**
* Ordering of a table by some ascending or descending columns
*
* <p> A list of columns, represented by column numbers, with an
* ascending/descending indicator for each column.
*/
public class OrderInfo
{
/**
* Ascending/descending order of columns
*
* <p> For outputs, the ordering of values from the first row out to the
* last. Note that this ordering applies within a parallel instance
* of the UDF at runtime, but it does not guarantee a total
* order. For example, two parallel instances may get these ordered
* values: instance 0 gets 1,3,5,7 instance 1 gets 2,4,6,8
*/
public enum OrderTypeCode
{
/**
* Unspecified order
*/
NO_ORDER, ///< Unspecified order
/**
* Ascending order
*/
ASCENDING, ///< Ascending order
/**
* Descending order
*/
DESCENDING; ///< Descending order
private static OrderTypeCode[] allValues = values();
public static OrderTypeCode fromOrdinal(int n) {return allValues[n];}
};
// const Functions for use by UDR writer, both at compile and at run time
/**
* Default constructor.
*/
public OrderInfo() {
columnNumbers_ = new Vector<Integer>();
orderTypes_ = new Vector<OrderTypeCode>();
}
public OrderInfo(OrderInfo o) {
columnNumbers_ = new Vector<Integer>(o.columnNumbers_);
orderTypes_ = new Vector<OrderTypeCode>(o.orderTypes_);
}
/**
* Get the number of entries (columns) in the ordering.
* @return Number of entries/columns that make up the ordering.
*/
public int getNumEntries() {
return columnNumbers_.size();
}
/**
* Get the column number of an entry of the ordering.
* @param i the position (0-based) of the ordering, 0 meaning the leading position.
* @return The column number of the n-th entry of the ordering (both are 0-based).
* @throws UDRException
*/
public int getColumnNum(int i) throws UDRException {
if (i < 0 || i >= columnNumbers_.size())
throw new UDRException(
38900,
"Trying to access colnum entry %d of an OrderInfo object with %d entries",
i, columnNumbers_.size());
return columnNumbers_.get(i).intValue();
}
/**
* Get the order type of an entry of the ordering.
* @param i the position (0-based) of the ordering, 0 meaning the leading position.
* @return The order type of the n-th entry of the ordering (0-based).
* @throws UDRException
*/
public OrderTypeCode getOrderType(int i) throws UDRException {
if (i < 0 || i >= orderTypes_.size())
throw new UDRException(
38900,
"Trying to access order type entry %d of an OrderInfo object with %d entries",
i, orderTypes_.size());
return orderTypes_.get(i);
}
// Functions available at compile time only
/**
* Append an entry to the ordering.
* @param colNum Column number to append to the ordering.
* @param orderType Order type (ascending or descending) to use.
*/
public void addEntry(int colNum, OrderTypeCode orderType){
columnNumbers_.add(Integer.valueOf(colNum));
orderTypes_.add(orderType);
}
/**
* Append an entry to the ordering with ASCENDING orderType.
* @param colNum Column number to append to the ordering.
*/
public void addEntry(int colNum){
addEntry(colNum, OrderTypeCode.ASCENDING);
}
/**
* Insert an entry at any position of the ordering.
*
* <p> A quick example to illustrate this: Let's say we have a table
* with columns (a,b,c). Their column numbers are 0, 1, and 2.
* We produce an ordering (C ASCENDING):
*
* @code OrderInfo myorder;
*
* myorder.addEntryAt(0, 2); @endcode
*
* Next, we want to make this into (B DESCENDING, C ASCENDING):
*
* @code myorder.addEntryAt(0, 1, DESCENDING); @endcode
*
* @param pos Position (0-based) at which we want to insert. The new
* entry will be position "pos" after the insertion, any
* existing entries will be moved up.
* @param colNum Number of the column by which we want to order
* @param orderType Order type (ascending or descending) to use
* @throws UDRException
*/
public void addEntryAt(int pos,
int colNum,
OrderTypeCode orderType) throws UDRException {
if (pos > columnNumbers_.size())
throw new UDRException(
38900,
"OrderInfo::addEntryAt at position %d with a list of %d entries",
pos, columnNumbers_.size());
columnNumbers_.add(pos, Integer.valueOf(colNum));
orderTypes_.add(pos, orderType);
}
/**
* Insert an entry at any position of the ordering with orderType ASCENDING.
*
* <p> A quick example to illustrate this: Let's say we have a table
* with columns (a,b,c). Their column numbers are 0, 1, and 2.
* We produce an ordering (C ASCENDING):
*
* @code OrderInfo myorder;
*
* myorder.addEntryAt(0, 2); @endcode
*
* @param pos Position (0-based) at which we want to insert. The new
* entry will be position "pos" after the insertion, any
* existing entries will be moved up.
* @param colNum Number of the column by which we want to order
* @throws UDRException
*/
public void addEntryAt(int pos,
int colNum) throws UDRException {
addEntryAt(pos, colNum, OrderTypeCode.ASCENDING);
}
// UDR writers can ignore these methods
void clear()
{
columnNumbers_.clear();
orderTypes_.clear();
}
private Vector<Integer> columnNumbers_;
private Vector<OrderTypeCode> orderTypes_;
}
| apache-2.0 |
0359xiaodong/android-materialshadowninepatch | example/src/main/java/com/h6ah4i/android/example/materialshadowninepatch/MainContentsFragment.java | 6475 | /*
* Copyright (C) 2015 Haruki Hasegawa
*
* 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.h6ah4i.android.example.materialshadowninepatch;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.SeekBar;
import com.h6ah4i.android.materialshadowninepatch.MaterialShadowContainerView;
public class MainContentsFragment
extends Fragment
implements View.OnClickListener,
CheckBox.OnCheckedChangeListener,
SeekBar.OnSeekBarChangeListener {
private static final int SEEKBAR_MAX = 1000;
private static final float MAX_ELEVATION = 9;
private static final int[] mNativeShadowItemIds = new int[]{
R.id.native_shadow_item_z0,
R.id.native_shadow_item_z1,
R.id.native_shadow_item_z2,
R.id.native_shadow_item_z3,
R.id.native_shadow_item_z4,
R.id.native_shadow_item_z5,
R.id.native_shadow_item_z6,
R.id.native_shadow_item_z7,
R.id.native_shadow_item_z8,
R.id.native_shadow_item_z9,
};
private static final int[] mCompatShadowItemIds = new int[]{
R.id.compat_shadow_item_z0,
R.id.compat_shadow_item_z1,
R.id.compat_shadow_item_z2,
R.id.compat_shadow_item_z3,
R.id.compat_shadow_item_z4,
R.id.compat_shadow_item_z5,
R.id.compat_shadow_item_z6,
R.id.compat_shadow_item_z7,
R.id.compat_shadow_item_z8,
R.id.compat_shadow_item_z9,
};
private static final int[] mCompatShadowItemContainerIds = new int[]{
R.id.compat_shadow_item_container_z0,
R.id.compat_shadow_item_container_z1,
R.id.compat_shadow_item_container_z2,
R.id.compat_shadow_item_container_z3,
R.id.compat_shadow_item_container_z4,
R.id.compat_shadow_item_container_z5,
R.id.compat_shadow_item_container_z6,
R.id.compat_shadow_item_container_z7,
R.id.compat_shadow_item_container_z8,
R.id.compat_shadow_item_container_z9,
};
private View[] mNativeShadowItems;
private View[] mCompatShadowItems;
private MaterialShadowContainerView[] mCompatShadowItemContainers;
private SeekBar mSeekBarElevation;
private CheckBox mCheckBoxForceUseCompatMode;
private float mDisplayDensity;
public MainContentsFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.fragment_main, container, false);
mDisplayDensity = getResources().getDisplayMetrics().density;
mSeekBarElevation = (SeekBar) rootView.findViewById(R.id.seekbar_elevation);
mSeekBarElevation.setOnSeekBarChangeListener(this);
mSeekBarElevation.setMax(SEEKBAR_MAX);
mCheckBoxForceUseCompatMode = (CheckBox) (rootView.findViewById(R.id.checkbox_force_use_compat_mode));
mCheckBoxForceUseCompatMode.setOnCheckedChangeListener(this);
mNativeShadowItems = new View[mNativeShadowItemIds.length];
for (int i = 0; i < mNativeShadowItemIds.length; i++) {
mNativeShadowItems[i] = rootView.findViewById(mNativeShadowItemIds[i]);
}
mCompatShadowItems = new View[mCompatShadowItemIds.length];
for (int i = 0; i < mCompatShadowItemIds.length; i++) {
mCompatShadowItems[i] = rootView.findViewById(mCompatShadowItemIds[i]);
}
mCompatShadowItemContainers = new MaterialShadowContainerView[mCompatShadowItemContainerIds.length];
for (int i = 0; i < mCompatShadowItemContainerIds.length; i++) {
mCompatShadowItemContainers[i] = (MaterialShadowContainerView) rootView.findViewById(mCompatShadowItemContainerIds[i]);
}
return rootView;
}
@Override
public void onViewStateRestored(@Nullable Bundle savedInstanceState) {
super.onViewStateRestored(savedInstanceState);
setForceCompatMode(mCheckBoxForceUseCompatMode.isChecked());
setItemElevation(progressToElevation(mSeekBarElevation.getProgress()));
}
@Override
public void onClick(View v) {
}
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
switch (buttonView.getId()) {
case R.id.checkbox_force_use_compat_mode:
setForceCompatMode(isChecked);
break;
}
}
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
switch (seekBar.getId()) {
case R.id.seekbar_elevation:
if (fromUser) {
setItemElevation(progressToElevation(progress));
}
break;
}
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
private float progressToElevation(int progress) {
return MAX_ELEVATION * mDisplayDensity * progress / SEEKBAR_MAX;
}
public void setItemElevation(float elevation) {
for (View v : mNativeShadowItems) {
ViewCompat.setElevation(v, elevation);
}
for (MaterialShadowContainerView v : mCompatShadowItemContainers) {
v.setShadowElevation(elevation);
}
}
public void setForceCompatMode(boolean forceCompatMode) {
for (MaterialShadowContainerView v : mCompatShadowItemContainers) {
v.setForceUseCompatShadow(forceCompatMode);
}
}
}
| apache-2.0 |
zegerhoogeboom/hu-demo-appengine | src/test/java/org/hu/zegerhoogeboom/demo/GuestbookServletTest.java | 2378 | /**
* Copyright 2012 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.hu.zegerhoogeboom.demo;
import static junit.framework.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.appengine.tools.development.testing.LocalServiceTestHelper;
import com.google.appengine.tools.development.testing.LocalUserServiceTestConfig;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class GuestbookServletTest {
private GuestbookServlet guestbookServlet;
private final LocalServiceTestHelper helper =
new LocalServiceTestHelper(new LocalUserServiceTestConfig())
.setEnvIsLoggedIn(true)
.setEnvAuthDomain("localhost")
.setEnvEmail("test@localhost");
@Before
public void setupGuestBookServlet() {
helper.setUp();
guestbookServlet = new GuestbookServlet();
}
@After
public void tearDownHelper() {
helper.tearDown();
}
@Test
public void testDoGet() throws IOException {
HttpServletRequest request = mock(HttpServletRequest.class);
HttpServletResponse response = mock(HttpServletResponse.class);
StringWriter stringWriter = new StringWriter();
when(response.getWriter()).thenReturn(new PrintWriter(stringWriter));
guestbookServlet.doGet(request, response);
User currentUser = UserServiceFactory.getUserService().getCurrentUser();
assertEquals("Hello, " + currentUser.getNickname() + System.getProperty("line.separator"), stringWriter.toString());
}
}
| apache-2.0 |
zjyww/admin-demo | src/com/jfinal/ext/utils/BooleanUtil.java | 2338 | package com.jfinal.ext.utils;
/**
* 描述:是非判断工具类
*
*/
public class BooleanUtil {
public static String trim(String arg) {
return (arg == null) ? arg : arg.trim();
}
// public static String trim(HttpServletRequest request, String key)
// {
// String value = request.getParameter(key);
// return (value == null) ? value : value.trim();
// }
public static boolean isNull(Object[] args) {
Object[] arrayOfObject = args;
int j = args.length;
for (int i = 0; i < j; ++i) {
Object arg = arrayOfObject[i];
if (arg == null)
return true;
}
return false;
}
public static boolean isNullAll(Object[] args) {
int total = 0;
Object[] arrayOfObject = args;
int j = args.length;
for (int i = 0; i < j; ++i) {
Object arg = arrayOfObject[i];
if (arg != null)
continue;
++i;
}
return total == args.length;
}
public static boolean isEmptyAll(String[] args) {
int total = 0;
String[] arrayOfString = args;
int j = args.length;
for (int i = 0; i < j; ++i) {
String arg = arrayOfString[i];
if ((arg != null) && (!arg.trim().equals("")))
continue;
++i;
}
return total == args.length;
}
public static boolean isEmpty(String... args) {
String[] arrayOfString = args;
if (args == null)
return true;
int j = args.length;
for (int i = 0; i < j; ++i) {
String arg = arrayOfString[i];
if ((arg == null) || (arg.trim().equals("")))
return true;
}
return false;
}
public static boolean equals(String s1, String s2) {
if ((s1 == null) || (s2 == null))
return false;
return s1.equals(s2);
}
public static boolean trimAndEquals(String s1, String s2) {
return (!isEmpty(new String[] { s1 })) && (s1.trim().equals(s2));
}
public static boolean trimAndEquals(String url, String[] params) {
for (String param : params) {
if (trimAndEquals(url, param))
return true;
}
return false;
}
}
| apache-2.0 |
liweidev/coolweather | app/src/main/java/com/example/coolweather/bean/bmob_bean/Comment.java | 1008 | package com.example.coolweather.bean.bmob_bean;
import java.io.Serializable;
import cn.bmob.v3.BmobObject;
/**
* Created by liwei on 2017/3/13.
* 评论表
*/
public class Comment extends BmobObject implements Serializable{
/**
* 内容
*/
private String content;
/**
* 用户
*/
private MyUser user;
/**
* 帖子
*/
private Post post;
/**
* 赞
*/
private Integer favour;
public void setContent(String content) {
this.content = content;
}
public void setUser(MyUser user) {
this.user = user;
}
public void setPost(Post post) {
this.post = post;
}
public void setFavour(Integer favour) {
this.favour = favour;
}
public String getContent() {
return content;
}
public MyUser getUser() {
return user;
}
public Post getPost() {
return post;
}
public Integer getFavour() {
return favour;
}
}
| apache-2.0 |
Adgillmore/CaveMan | src/uk/co/atgsoft/caveman/wine/record/QuantityEntry.java | 490 | /*
* 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 uk.co.atgsoft.caveman.wine.record;
import uk.co.atgsoft.caveman.wine.BottleSize;
/**
*
* @author adam
*/
public interface QuantityEntry {
void setQuantity(int quantity);
int getQuantity();
void setBottleSize(BottleSize size);
BottleSize getBottleSize();
}
| apache-2.0 |
lburgazzoli/apache-activemq-artemis | artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/SharedStoreBackupActivation.java | 10604 | /*
* 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.activemq.artemis.core.server.impl;
import java.nio.channels.ClosedChannelException;
import java.util.concurrent.TimeUnit;
import org.apache.activemq.artemis.api.core.ActiveMQException;
import org.apache.activemq.artemis.api.core.TransportConfiguration;
import org.apache.activemq.artemis.core.config.Configuration;
import org.apache.activemq.artemis.core.paging.PagingManager;
import org.apache.activemq.artemis.core.persistence.StorageManager;
import org.apache.activemq.artemis.core.postoffice.PostOffice;
import org.apache.activemq.artemis.core.server.ActiveMQServer;
import org.apache.activemq.artemis.core.server.ActiveMQServerLogger;
import org.apache.activemq.artemis.core.server.NodeManager;
import org.apache.activemq.artemis.core.server.QueueFactory;
import org.apache.activemq.artemis.core.server.cluster.ha.ScaleDownPolicy;
import org.apache.activemq.artemis.core.server.cluster.ha.SharedStoreSlavePolicy;
import org.apache.activemq.artemis.core.server.group.GroupingHandler;
import org.apache.activemq.artemis.core.server.management.ManagementService;
import org.jboss.logging.Logger;
public final class SharedStoreBackupActivation extends Activation {
private static final Logger logger = Logger.getLogger(SharedStoreBackupActivation.class);
//this is how we act as a backup
private SharedStoreSlavePolicy sharedStoreSlavePolicy;
private ActiveMQServerImpl activeMQServer;
private final Object failbackCheckerGuard = new Object();
private boolean cancelFailBackChecker;
public SharedStoreBackupActivation(ActiveMQServerImpl server, SharedStoreSlavePolicy sharedStoreSlavePolicy) {
this.activeMQServer = server;
this.sharedStoreSlavePolicy = sharedStoreSlavePolicy;
synchronized (failbackCheckerGuard) {
cancelFailBackChecker = false;
}
}
@Override
public void run() {
try {
activeMQServer.getNodeManager().startBackup();
ScaleDownPolicy scaleDownPolicy = sharedStoreSlavePolicy.getScaleDownPolicy();
boolean scalingDown = scaleDownPolicy != null && scaleDownPolicy.isEnabled();
if (!activeMQServer.initialisePart1(scalingDown))
return;
activeMQServer.getBackupManager().start();
activeMQServer.setState(ActiveMQServerImpl.SERVER_STATE.STARTED);
ActiveMQServerLogger.LOGGER.backupServerStarted(activeMQServer.getVersion().getFullVersion(), activeMQServer.getNodeManager().getNodeId());
activeMQServer.getNodeManager().awaitLiveNode();
sharedStoreSlavePolicy.getSharedStoreMasterPolicy().setSharedStoreSlavePolicy(sharedStoreSlavePolicy);
activeMQServer.setHAPolicy(sharedStoreSlavePolicy.getSharedStoreMasterPolicy());
//activeMQServer.configuration.getHAPolicy().setPolicyType(HAPolicy.POLICY_TYPE.SHARED_STORE);
activeMQServer.getBackupManager().activated();
if (activeMQServer.getState() != ActiveMQServerImpl.SERVER_STATE.STARTED) {
return;
}
activeMQServer.initialisePart2(scalingDown);
activeMQServer.completeActivation();
if (scalingDown) {
ActiveMQServerLogger.LOGGER.backupServerScaledDown();
Thread t = new Thread(new Runnable() {
@Override
public void run() {
try {
activeMQServer.stop();
//we are shared store but if we were started by a parent server then we shouldn't restart
if (sharedStoreSlavePolicy.isRestartBackup()) {
activeMQServer.start();
}
}
catch (Exception e) {
ActiveMQServerLogger.LOGGER.serverRestartWarning();
}
}
});
t.start();
return;
}
else {
ActiveMQServerLogger.LOGGER.backupServerIsLive();
activeMQServer.getNodeManager().releaseBackup();
}
if (sharedStoreSlavePolicy.isAllowAutoFailBack()) {
startFailbackChecker();
}
}
catch (ClosedChannelException | InterruptedException e) {
// these are ok, we are being stopped
}
catch (Exception e) {
if (!(e.getCause() instanceof InterruptedException)) {
ActiveMQServerLogger.LOGGER.initializationError(e);
}
}
catch (Throwable e) {
ActiveMQServerLogger.LOGGER.initializationError(e);
}
}
@Override
public void close(boolean permanently, boolean restarting) throws Exception {
if (!restarting) {
synchronized (failbackCheckerGuard) {
cancelFailBackChecker = true;
}
}
// To avoid a NPE cause by the stop
NodeManager nodeManagerInUse = activeMQServer.getNodeManager();
//we need to check as the servers policy may have changed
if (activeMQServer.getHAPolicy().isBackup()) {
activeMQServer.interrupBackupThread(nodeManagerInUse);
if (nodeManagerInUse != null) {
nodeManagerInUse.stopBackup();
}
}
else {
if (nodeManagerInUse != null) {
// if we are now live, behave as live
// We need to delete the file too, otherwise the backup will failover when we shutdown or if the backup is
// started before the live
if (sharedStoreSlavePolicy.isFailoverOnServerShutdown() || permanently) {
nodeManagerInUse.crashLiveServer();
}
else {
nodeManagerInUse.pauseLiveServer();
}
}
}
}
@Override
public JournalLoader createJournalLoader(PostOffice postOffice,
PagingManager pagingManager,
StorageManager storageManager,
QueueFactory queueFactory,
NodeManager nodeManager,
ManagementService managementService,
GroupingHandler groupingHandler,
Configuration configuration,
ActiveMQServer parentServer) throws ActiveMQException {
if (sharedStoreSlavePolicy.getScaleDownPolicy() != null && sharedStoreSlavePolicy.getScaleDownPolicy().isEnabled()) {
return new BackupRecoveryJournalLoader(postOffice, pagingManager, storageManager, queueFactory, nodeManager, managementService, groupingHandler, configuration, parentServer, ScaleDownPolicy.getScaleDownConnector(sharedStoreSlavePolicy.getScaleDownPolicy(), activeMQServer), activeMQServer.getClusterManager().getClusterController());
}
else {
return super.createJournalLoader(postOffice, pagingManager, storageManager, queueFactory, nodeManager, managementService, groupingHandler, configuration, parentServer);
}
}
/**
* To be called by backup trying to fail back the server
*/
private void startFailbackChecker() {
activeMQServer.getScheduledPool().scheduleAtFixedRate(new FailbackChecker(), 1000L, 1000L, TimeUnit.MILLISECONDS);
}
private class FailbackChecker implements Runnable {
BackupTopologyListener backupListener;
FailbackChecker() {
TransportConfiguration connector = activeMQServer.getClusterManager().getDefaultConnection(null).getConnector();
backupListener = new BackupTopologyListener(activeMQServer.getNodeID().toString(), connector);
activeMQServer.getClusterManager().getDefaultConnection(null).addClusterTopologyListener(backupListener);
}
private boolean restarting = false;
@Override
public void run() {
try {
if (!restarting && activeMQServer.getNodeManager().isAwaitingFailback()) {
if (backupListener.waitForBackup()) {
ActiveMQServerLogger.LOGGER.awaitFailBack();
restarting = true;
Thread t = new Thread(new Runnable() {
@Override
public void run() {
try {
logger.debug(activeMQServer + "::Stopping live node in favor of failback");
NodeManager nodeManager = activeMQServer.getNodeManager();
activeMQServer.stop(true, false, true);
// ensure that the server to which we are failing back actually starts fully before we restart
nodeManager.start();
nodeManager.awaitLiveStatus();
nodeManager.stop();
synchronized (failbackCheckerGuard) {
if (cancelFailBackChecker || !sharedStoreSlavePolicy.isRestartBackup())
return;
activeMQServer.setHAPolicy(sharedStoreSlavePolicy);
logger.debug(activeMQServer + "::Starting backup node now after failback");
activeMQServer.start();
}
}
catch (Exception e) {
ActiveMQServerLogger.LOGGER.warn(e.getMessage(),e);
ActiveMQServerLogger.LOGGER.serverRestartWarning();
}
}
});
t.start();
}
}
}
catch (Exception e) {
ActiveMQServerLogger.LOGGER.serverRestartWarning(e);
}
}
}
}
| apache-2.0 |
jaikherajani/Capstone-Project | app/src/main/java/com/example/jaikh/movies/model/Genre.java | 1078 | package com.example.jaikh.movies.model;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import java.io.Serializable;
public class Genre implements Serializable {
private final static long serialVersionUID = -1057746908705631288L;
@SerializedName("id")
@Expose
private Long id;
@SerializedName("name")
@Expose
private String name;
/**
* No args constructor for use in serialization
*/
public Genre() {
}
/**
* @param id
* @param name
*/
public Genre(Long id, String name) {
super();
this.id = id;
this.name = name;
}
/**
* @return The id
*/
public Long getId() {
return id;
}
/**
* @param id The id
*/
public void setId(Long id) {
this.id = id;
}
/**
* @return The name
*/
public String getName() {
return name;
}
/**
* @param name The name
*/
public void setName(String name) {
this.name = name;
}
}
| apache-2.0 |
Netflix/hollow | hollow-diff-ui/src/main/java/com/netflix/hollow/diff/ui/jetty/OptionalDependencyHelper.java | 1230 | /*
* Copyright 2016-2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.hollow.diff.ui.jetty;
import com.netflix.hollow.ui.jetty.AbstractOptionalDependencyHelper;
final class OptionalDependencyHelper extends AbstractOptionalDependencyHelper {
HollowDiffUIServer.UIServer.Factory uiServerFactory() {
return (HollowDiffUIServer.UIServer.Factory)newFactory(
"com.netflix.hollow.diff.ui.jetty.JettyBasedUIServer$Factory",
"org.eclipse.jetty.server.Server",
"please add jetty-server (org.eclipse.jetty:jetty-server) to your dependencies");
}
OptionalDependencyHelper() {}
}
| apache-2.0 |
agustinmiura/footballBets | src/main/java/depoi/austral/model/other/Result.java | 1621 | /*
* Copyright (C) 2010 Miura Agustín
* Rozanec Jose
*
* 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 depoi.austral.model.other;
import java.util.Random;
public enum Result {
WIN(1), DRAW(0), LOSS(-1), NOT_BET(-2);
private Integer id;
private Result(Integer id) {
this.id = id;
}
public int getId() {
return id;
}
public String toString() {
switch (id) {
case 0:
return "Draw";
case 1:
return "Win";
case -1:
return "Lose";
default:
return "Not bet";
}
}
public static Result getRandom() {
Random random = new Random();
Integer number = random.nextInt(2);
number = Math.abs(number);
Integer answer = BetFactory.indexArr[number];
return Result.getResult(answer);
}
public static Result getResult(int type) {
switch (type) {
case 0:
return Result.DRAW;
case 1:
return Result.WIN;
case -1:
return Result.LOSS;
case -2:
return Result.NOT_BET;
default:
throw new IllegalArgumentException(
"Invalid number to create the enum");
}
}
}
| apache-2.0 |
jeremylong/DependencyCheck | core/src/main/java/org/owasp/dependencycheck/analyzer/ComposerLockAnalyzer.java | 6904 | /*
* This file is part of dependency-check-core.
*
* 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.
*
* Copyright (c) 2015 The OWASP Foundation. All Rights Reserved.
*/
package org.owasp.dependencycheck.analyzer;
import com.github.packageurl.MalformedPackageURLException;
import com.github.packageurl.PackageURL;
import com.github.packageurl.PackageURLBuilder;
import org.owasp.dependencycheck.Engine;
import org.owasp.dependencycheck.analyzer.exception.AnalysisException;
import org.owasp.dependencycheck.data.composer.ComposerException;
import org.owasp.dependencycheck.data.composer.ComposerLockParser;
import org.owasp.dependencycheck.dependency.Confidence;
import org.owasp.dependencycheck.dependency.Dependency;
import org.owasp.dependencycheck.exception.InitializationException;
import org.owasp.dependencycheck.utils.Checksum;
import org.owasp.dependencycheck.utils.FileFilterBuilder;
import org.owasp.dependencycheck.utils.Settings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.IOException;
import org.owasp.dependencycheck.data.nvd.ecosystem.Ecosystem;
import org.owasp.dependencycheck.dependency.EvidenceType;
import org.owasp.dependencycheck.dependency.naming.GenericIdentifier;
import org.owasp.dependencycheck.dependency.naming.PurlIdentifier;
/**
* Used to analyze a composer.lock file for a composer PHP app.
*
* @author colezlaw
*/
@Experimental
public class ComposerLockAnalyzer extends AbstractFileTypeAnalyzer {
/**
* A descriptor for the type of dependencies processed or added by this
* analyzer.
*/
public static final String DEPENDENCY_ECOSYSTEM = Ecosystem.PHP;
/**
* The logger.
*/
private static final Logger LOGGER = LoggerFactory.getLogger(ComposerLockAnalyzer.class);
/**
* The analyzer name.
*/
private static final String ANALYZER_NAME = "Composer.lock analyzer";
/**
* composer.json.
*/
private static final String COMPOSER_LOCK = "composer.lock";
/**
* The FileFilter.
*/
private static final FileFilter FILE_FILTER = FileFilterBuilder.newInstance().addFilenames(COMPOSER_LOCK).build();
/**
* Returns the FileFilter.
*
* @return the FileFilter
*/
@Override
protected FileFilter getFileFilter() {
return FILE_FILTER;
}
/**
* Initializes the analyzer.
*
* @param engine a reference to the dependency-check engine
* @throws InitializationException thrown if an exception occurs getting an
* instance of SHA1
*/
@Override
protected void prepareFileTypeAnalyzer(Engine engine) throws InitializationException {
// do nothing
}
/**
* Entry point for the analyzer.
*
* @param dependency the dependency to analyze
* @param engine the engine scanning
* @throws AnalysisException if there's a failure during analysis
*/
@Override
protected void analyzeDependency(Dependency dependency, Engine engine) throws AnalysisException {
engine.removeDependency(dependency);
try (FileInputStream fis = new FileInputStream(dependency.getActualFile())) {
final ComposerLockParser clp = new ComposerLockParser(fis);
LOGGER.debug("Checking composer.lock file {}", dependency.getActualFilePath());
clp.process();
clp.getDependencies().stream().map((dep) -> {
final Dependency d = new Dependency(dependency.getActualFile(), true);
final String filePath = String.format("%s:%s/%s/%s", dependency.getFilePath(), dep.getGroup(), dep.getProject(), dep.getVersion());
d.setName(dep.getProject());
d.setVersion(dep.getVersion());
try {
final PackageURL purl = PackageURLBuilder.aPackageURL().withType("composer").withNamespace(dep.getGroup())
.withName(dep.getProject()).withVersion(dep.getVersion()).build();
d.addSoftwareIdentifier(new PurlIdentifier(purl, Confidence.HIGHEST));
} catch (MalformedPackageURLException ex) {
LOGGER.debug("Unable to build package url for composer", ex);
d.addSoftwareIdentifier(new GenericIdentifier("cocoapods:" + dep.getGroup() + "/" + dep.getProject()
+ "@" + dep.getVersion(), Confidence.HIGHEST));
}
d.setPackagePath(String.format("%s:%s", dep.getProject(), dep.getVersion()));
d.setEcosystem(DEPENDENCY_ECOSYSTEM);
d.setFilePath(filePath);
d.setSha1sum(Checksum.getSHA1Checksum(filePath));
d.setSha256sum(Checksum.getSHA256Checksum(filePath));
d.setMd5sum(Checksum.getMD5Checksum(filePath));
d.addEvidence(EvidenceType.VENDOR, COMPOSER_LOCK, "vendor", dep.getGroup(), Confidence.HIGHEST);
d.addEvidence(EvidenceType.PRODUCT, COMPOSER_LOCK, "product", dep.getProject(), Confidence.HIGHEST);
d.addEvidence(EvidenceType.VERSION, COMPOSER_LOCK, "version", dep.getVersion(), Confidence.HIGHEST);
return d;
}).forEach((d) -> {
LOGGER.debug("Adding dependency {}", d.getDisplayFileName());
engine.addDependency(d);
});
} catch (IOException ex) {
LOGGER.warn("Error opening dependency {}", dependency.getActualFilePath());
} catch (ComposerException ce) {
LOGGER.warn("Error parsing composer.json {}", dependency.getActualFilePath(), ce);
}
}
/**
* Gets the key to determine whether the analyzer is enabled.
*
* @return the key specifying whether the analyzer is enabled
*/
@Override
protected String getAnalyzerEnabledSettingKey() {
return Settings.KEYS.ANALYZER_COMPOSER_LOCK_ENABLED;
}
/**
* Returns the analyzer's name.
*
* @return the analyzer's name
*/
@Override
public String getName() {
return ANALYZER_NAME;
}
/**
* Returns the phase this analyzer should run under.
*
* @return the analysis phase
*/
@Override
public AnalysisPhase getAnalysisPhase() {
return AnalysisPhase.INFORMATION_COLLECTION;
}
}
| apache-2.0 |
Squarespace/less-compiler | src/test/java/com/squarespace/less/LessImporterTest.java | 3114 | /**
* Copyright (c) 2014 SQUARESPACE, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.squarespace.less;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
import static org.testng.Assert.fail;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import org.testng.annotations.Test;
import com.squarespace.less.core.LessTestBase;
public class LessImporterTest extends LessTestBase {
private static final LessCompiler COMPILER = new LessCompiler();
@Test
public void testImporter() throws LessException {
LessLoader loader = new HashMapLessLoader(buildMap());
LessOptions opts = buildOptions();
LessContext ctx = new LessContext(opts, loader);
ctx.setCompiler(COMPILER);
String source = "@import 'base.less'; .ruleset { color: @color; font-size: @size; }";
String result = COMPILER.compile(source, ctx, Paths.get("."), null, true);
assertEquals(result, ".child{font-size:12px}.ruleset{color:#abc;font-size:12px}");
}
@Test
public void testImporterRecursionLimit() throws LessException {
int imports = 100;
Map<Path, String> map = new HashMap<>();
for (int i = 0; i < imports; i++) {
map.put(path(i + ".less"), "@import '" + (i + 1) + ".less';\n");
}
map.put(path(imports + ".less"), ".parent { color: red; }\n");
int recursionLimit = 90;
LessLoader loader = new HashMapLessLoader(map);
LessOptions opts = buildOptions();
opts.importRecursionLimit(recursionLimit);
LessContext ctx = new LessContext(opts, loader);
ctx.setCompiler(COMPILER);
String source = "@import '1.less';";
try {
COMPILER.compile(source, ctx, path("."), path("foo.less"), true);
fail("Expected import recursion limit exception");
} catch (LessException e) {
assertTrue(e.getMessage().contains("limit of " + recursionLimit + " exceeded"), e.getMessage());
}
}
private static Path path(String path) {
return Paths.get(path).toAbsolutePath().normalize();
}
private static Map<Path, String> buildMap() {
Map<Path, String> map = new HashMap<>();
map.put(path("base.less"), "@color: #abc; @import 'child.less';");
map.put(path("child.less"), ".child { font-size: 12px; }\n@size: 12px;");
return map;
}
private static LessOptions buildOptions() {
LessOptions opts = new LessOptions();
opts.compress(true);
opts.tracing(false);
opts.indent(4);
opts.importOnce(true);
opts.strict(false);
opts.hideWarnings(false);
return opts;
}
}
| apache-2.0 |
nafae/developer | modules/dfp_axis/src/main/java/com/google/api/ads/dfp/axis/v201308/LineItemError.java | 4321 | /**
* LineItemError.java
*
* This file was auto-generated from WSDL
* by the Apache Axis 1.4 Mar 02, 2009 (07:08:06 PST) WSDL2Java emitter.
*/
package com.google.api.ads.dfp.axis.v201308;
/**
* A catch-all error that lists all generic errors associated with
* LineItem.
*/
public class LineItemError extends com.google.api.ads.dfp.axis.v201308.ApiError implements java.io.Serializable {
/* The error reason represented by an enum. */
private com.google.api.ads.dfp.axis.v201308.LineItemErrorReason reason;
public LineItemError() {
}
public LineItemError(
java.lang.String fieldPath,
java.lang.String trigger,
java.lang.String errorString,
java.lang.String apiErrorType,
com.google.api.ads.dfp.axis.v201308.LineItemErrorReason reason) {
super(
fieldPath,
trigger,
errorString,
apiErrorType);
this.reason = reason;
}
/**
* Gets the reason value for this LineItemError.
*
* @return reason * The error reason represented by an enum.
*/
public com.google.api.ads.dfp.axis.v201308.LineItemErrorReason getReason() {
return reason;
}
/**
* Sets the reason value for this LineItemError.
*
* @param reason * The error reason represented by an enum.
*/
public void setReason(com.google.api.ads.dfp.axis.v201308.LineItemErrorReason reason) {
this.reason = reason;
}
private java.lang.Object __equalsCalc = null;
public synchronized boolean equals(java.lang.Object obj) {
if (!(obj instanceof LineItemError)) return false;
LineItemError other = (LineItemError) obj;
if (obj == null) return false;
if (this == obj) return true;
if (__equalsCalc != null) {
return (__equalsCalc == obj);
}
__equalsCalc = obj;
boolean _equals;
_equals = super.equals(obj) &&
((this.reason==null && other.getReason()==null) ||
(this.reason!=null &&
this.reason.equals(other.getReason())));
__equalsCalc = null;
return _equals;
}
private boolean __hashCodeCalc = false;
public synchronized int hashCode() {
if (__hashCodeCalc) {
return 0;
}
__hashCodeCalc = true;
int _hashCode = super.hashCode();
if (getReason() != null) {
_hashCode += getReason().hashCode();
}
__hashCodeCalc = false;
return _hashCode;
}
// Type metadata
private static org.apache.axis.description.TypeDesc typeDesc =
new org.apache.axis.description.TypeDesc(LineItemError.class, true);
static {
typeDesc.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201308", "LineItemError"));
org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("reason");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201308", "reason"));
elemField.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201308", "LineItemError.Reason"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
}
/**
* Return type metadata object
*/
public static org.apache.axis.description.TypeDesc getTypeDesc() {
return typeDesc;
}
/**
* Get Custom Serializer
*/
public static org.apache.axis.encoding.Serializer getSerializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanSerializer(
_javaType, _xmlType, typeDesc);
}
/**
* Get Custom Deserializer
*/
public static org.apache.axis.encoding.Deserializer getDeserializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanDeserializer(
_javaType, _xmlType, typeDesc);
}
}
| apache-2.0 |
namioka/spring-boot-multiple-modules-example | xyz-domain/src/main/java/xxxxx/yyyyy/zzzzz/op/domain/shared/_experimental/specification/Specification.java | 1002 | package xxxxx.yyyyy.zzzzz.op.domain.shared._experimental.specification;
import java.util.Optional;
public interface Specification<T> {
boolean isSatisfiedBy(T candidate);
boolean isGeneralizationOf(Specification<T> specification);
default Specification<T> and(Specification<T> specification) {
return new ConjunctionSpecification<T>().with(this).with(specification);
}
default Specification<T> or(Specification<T> specification) {
return new DisjunctionSpecification<T>().with(this).with(specification);
}
default Optional<Specification<T>> remainderUnsatisfiedBy(T candidate) {
return (isSatisfiedBy(candidate)) ? Optional.empty() : Optional.of(this);
}
default boolean isSpecialCaseOf(Specification<T> specification) {
if (specification == null) {
return false;
}
if (specification.equals(this)) {
return true;
}
return specification.isGeneralizationOf(this);
}
}
| apache-2.0 |
mread/buck | test/com/facebook/buck/apple/xcode/ProjectGeneratorTestUtils.java | 8106 | /*
* Copyright 2012-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.facebook.buck.apple.xcode;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import com.facebook.buck.apple.xcode.xcodeproj.PBXBuildFile;
import com.facebook.buck.apple.xcode.xcodeproj.PBXBuildPhase;
import com.facebook.buck.apple.xcode.xcodeproj.PBXCopyFilesBuildPhase;
import com.facebook.buck.apple.xcode.xcodeproj.PBXFrameworksBuildPhase;
import com.facebook.buck.apple.xcode.xcodeproj.PBXProject;
import com.facebook.buck.apple.xcode.xcodeproj.PBXReference;
import com.facebook.buck.apple.xcode.xcodeproj.PBXTarget;
import com.facebook.buck.model.BuildTarget;
import com.facebook.buck.parser.PartialGraph;
import com.facebook.buck.parser.PartialGraphFactory;
import com.facebook.buck.rules.ActionGraph;
import com.facebook.buck.rules.BuildRule;
import com.facebook.buck.rules.BuildRuleParams;
import com.facebook.buck.rules.BuildRuleResolver;
import com.facebook.buck.rules.Description;
import com.facebook.buck.rules.FakeBuildRuleParamsBuilder;
import com.facebook.buck.rules.PathSourcePath;
import com.facebook.buck.rules.SourcePath;
import com.facebook.buck.rules.coercer.TypeCoercer;
import com.facebook.buck.rules.coercer.TypeCoercerFactory;
import com.facebook.buck.testutil.RuleMap;
import com.facebook.buck.util.Types;
import com.google.common.base.Function;
import com.google.common.base.Functions;
import com.google.common.base.Optional;
import com.google.common.base.Predicate;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSortedSet;
import com.google.common.collect.Iterables;
import java.lang.reflect.Field;
import java.lang.reflect.Type;
import java.nio.file.Path;
import java.nio.file.Paths;
final class ProjectGeneratorTestUtils {
/**
* Utility class should not be instantiated.
*/
private ProjectGeneratorTestUtils() {}
public static <T> BuildRule createBuildRuleWithDefaults(
BuildTarget target,
ImmutableSortedSet<BuildRule> deps,
Description<T> description,
BuildRuleResolver resolver) {
return createBuildRuleWithDefaults(
target,
resolver,
deps,
description,
Functions.<T>identity());
}
/**
* Helper function to create a build rule for a description, initializing fields to empty values,
* and allowing a user to override specific fields.
*/
public static <T> BuildRule createBuildRuleWithDefaults(
BuildTarget target,
BuildRuleResolver resolver,
ImmutableSortedSet<BuildRule> deps,
Description<T> description,
Function<T, T> overrides) {
T arg = description.createUnpopulatedConstructorArg();
for (Field field : arg.getClass().getFields()) {
Object value;
if (field.getType().isAssignableFrom(ImmutableSortedSet.class)) {
value = ImmutableSortedSet.of();
} else if (field.getType().isAssignableFrom(ImmutableList.class)) {
value = ImmutableList.of();
} else if (field.getType().isAssignableFrom(ImmutableMap.class)) {
value = ImmutableMap.of();
} else if (field.getType().isAssignableFrom(Optional.class)) {
Type nonOptionalType = Types.getFirstNonOptionalType(field);
TypeCoercerFactory typeCoercerFactory = new TypeCoercerFactory();
TypeCoercer<?> typeCoercer = typeCoercerFactory.typeCoercerForType(nonOptionalType);
value = typeCoercer.getOptionalValue();
} else if (field.getType().isAssignableFrom(String.class)) {
value = "";
} else if (field.getType().isAssignableFrom(Path.class)) {
value = Paths.get("");
} else if (field.getType().isAssignableFrom(SourcePath.class)) {
value = new PathSourcePath(Paths.get(""));
} else if (field.getType().isPrimitive()) {
// do nothing, these are initialized with a zero value
continue;
} else {
// user should provide
continue;
}
try {
field.set(arg, value);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
BuildRuleParams buildRuleParams = new FakeBuildRuleParamsBuilder(target)
.setDeps(deps)
.setType(description.getBuildRuleType())
.build();
return description.createBuildRule(
buildRuleParams,
resolver,
overrides.apply(arg));
}
public static PartialGraph createPartialGraphFromBuildRuleResolver(BuildRuleResolver resolver) {
ActionGraph graph = RuleMap.createGraphFromBuildRules(resolver);
ImmutableSet.Builder<BuildTarget> targets = ImmutableSet.builder();
for (BuildRule rule : graph.getNodes()) {
targets.add(rule.getBuildTarget());
}
return PartialGraphFactory.newInstance(graph, targets.build());
}
public static PartialGraph createPartialGraphFromBuildRules(ImmutableSet<BuildRule> rules) {
return createPartialGraphFromBuildRuleResolver(new BuildRuleResolver(rules));
}
static PBXTarget assertTargetExistsAndReturnTarget(
PBXProject generatedProject,
String name) {
for (PBXTarget target : generatedProject.getTargets()) {
if (target.getName().equals(name)) {
return target;
}
}
fail("No generated target with name: " + name);
return null;
}
public static void assertHasSingletonFrameworksPhaseWithFrameworkEntries(
PBXTarget target, ImmutableList<String> frameworks) {
assertHasSingletonPhaseWithEntries(target, PBXFrameworksBuildPhase.class, frameworks);
}
public static void assertHasSingletonCopyFilesPhaseWithFileEntries(
PBXTarget target, ImmutableList<String>files) {
assertHasSingletonPhaseWithEntries(target, PBXCopyFilesBuildPhase.class, files);
}
public static <T extends PBXBuildPhase> void assertHasSingletonPhaseWithEntries(
PBXTarget target,
final Class<T> cls,
ImmutableList<String> entries) {
PBXBuildPhase buildPhase = getSingletonPhaseByType(target, cls);
assertEquals(
"Phase should have right number of entries",
entries.size(),
buildPhase.getFiles().size());
for (PBXBuildFile file : buildPhase.getFiles()) {
PBXReference.SourceTree sourceTree = file.getFileRef().getSourceTree();
switch (sourceTree) {
case GROUP:
fail("Should not emit entries with sourceTree <group>");
break;
case ABSOLUTE:
fail("Should not emit entries with sourceTree <absolute>");
break;
// $CASES-OMITTED$
default:
String serialized = "$" + sourceTree + "/" + file.getFileRef().getPath();
assertTrue(
"Framework should be listed in list of expected entries: " + serialized,
entries.contains(serialized));
break;
}
}
}
public static <T extends PBXBuildPhase> T getSingletonPhaseByType(
PBXTarget target, final Class<T> cls) {
Iterable<PBXBuildPhase> buildPhases =
Iterables.filter(
target.getBuildPhases(), new Predicate<PBXBuildPhase>() {
@Override
public boolean apply(PBXBuildPhase input) {
return cls.isInstance(input);
}
});
assertEquals("Build phase should be singleton", 1, Iterables.size(buildPhases));
@SuppressWarnings("unchecked")
T element = (T) Iterables.getOnlyElement(buildPhases);
return element;
}
}
| apache-2.0 |
dvilchez/logback2rollbar | test/com/xuaps/RollbarAppendderTest.java | 1267 | package com.xuaps;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.spi.LoggingEvent;
import org.junit.Before;
import org.junit.Test;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
/**
* Created by david.vilchez on 14/04/14.
*/
public class RollbarAppendderTest {
private Properties props;
@Before
public void setUp(){
props=new Properties();
try {
props.load(new FileInputStream("tests.properties"));
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
public void exception_occurs(){
RollbarAppender app=new RollbarAppender();
app.setAccessToken(props.getProperty("access_token"));
app.setEnvironment("test");
StackTraceElement[] context=new StackTraceElement[1];
context[0]=new StackTraceElement("tachan","juas", "C:\\", 10);
LoggingEvent event= new LoggingEvent();
event.setCallerData(context);
event.setLevel(Level.ERROR);
event.setTimeStamp(System.currentTimeMillis() / 1000L);
event.setMessage("ERRORRRRRRRRR!!!!");
app.start();
app.append(event);
//assert. go to rollbar panel to check it :)
}
}
| apache-2.0 |
Jason-Gew/Java_Modules | MqttPubSubClient/src/main/java/gew/PubSub/service/DataReceiving.java | 2453 | package gew.pubsub.service;
import gew.pubsub.mqtt.MQTTMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Queue;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* @author Jason/GeW
*/
public class DataReceiving implements Runnable {
private Queue<MQTTMessage> messageQ;
private AtomicBoolean controlBit;
private static final String FILE_PREFIX = "files";
private static final String FILE_TOPIC = "/File";
private static final Logger logger = LoggerFactory.getLogger(DataReceiving.class);
public DataReceiving(Queue<MQTTMessage> messageQ) {
this.messageQ = messageQ;
controlBit = new AtomicBoolean(true);
}
public void stop() {
controlBit.set(false);
}
@Override
public void run() {
while (controlBit.get()) {
while (!messageQ.isEmpty()) {
try {
// MQTTMessage message = messageQ.take(); // Use for BlockingQueue Only
MQTTMessage message = messageQ.poll();
if (message.getTopic().contains(FILE_TOPIC)) {
String fileName = message.getTopic().substring(message.getTopic().lastIndexOf("/") + 1);
try (FileOutputStream outputStream = new FileOutputStream(FILE_PREFIX + "/" + fileName)) {
outputStream.write(message.getMessage());
logger.info("-> File [ {} ] Has Been Stored Success", fileName);
} catch (IOException err) {
logger.error("-> Store File [ {} ] Failed: {}", fileName, err.getMessage());
}
} else {
logger.info("-> Received Message From Topic [{}]: {}", message.getTopic(),
new String(message.getMessage(), StandardCharsets.UTF_8));
}
} catch (Exception e) {
logger.error("-> Reading Data Exception: {}", e.getMessage());
}
}
try {
Thread.sleep(100);
} catch (InterruptedException err) {
logger.error("-> Data Receiving Got Interrupted...");
}
}
logger.info("-> Data Receiving Terminated...");
}
}
| apache-2.0 |
ggeorg/chillverse | async-http-client/src/test/java/com/ning/http/client/async/ComplexClientTest.java | 2280 | /*
* Copyright 2010 Ning, Inc.
*
* Ning licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.ning.http.client.async;
import com.ning.http.client.AsyncHttpClient;
import com.ning.http.client.Response;
import org.testng.annotations.Test;
import java.util.concurrent.TimeUnit;
import static org.testng.Assert.assertEquals;
public abstract class ComplexClientTest extends AbstractBasicTest {
@Test(groups = { "standalone", "default_provider" })
public void multipleRequestsTest() throws Throwable {
AsyncHttpClient client = getAsyncHttpClient(null);
try {
String body = "hello there";
// once
Response response = client.preparePost(getTargetUrl()).setBody(body).setHeader("Content-Type", "text/html").execute().get(TIMEOUT, TimeUnit.SECONDS);
assertEquals(response.getResponseBody(), body);
// twice
response = client.preparePost(getTargetUrl()).setBody(body).setHeader("Content-Type", "text/html").execute().get(TIMEOUT, TimeUnit.SECONDS);
assertEquals(response.getResponseBody(), body);
} finally {
client.close();
}
}
@Test(groups = { "standalone", "default_provider" })
public void urlWithoutSlashTest() throws Throwable {
AsyncHttpClient client = getAsyncHttpClient(null);
try {
String body = "hello there";
// once
Response response = client.preparePost(String.format("http://127.0.0.1:%d/foo/test", port1)).setBody(body).setHeader("Content-Type", "text/html").execute().get(TIMEOUT, TimeUnit.SECONDS);
assertEquals(response.getResponseBody(), body);
} finally {
client.close();
}
}
}
| apache-2.0 |
noikiy/binnavi | src/main/java/com/google/security/zynamics/binnavi/Database/PostgreSQL/Functions/PostgresSQLDebuggerFunctions.java | 10212 | /*
Copyright 2015 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.google.security.zynamics.binnavi.Database.PostgreSQL.Functions;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.google.common.base.Preconditions;
import com.google.security.zynamics.binnavi.Database.AbstractSQLProvider;
import com.google.security.zynamics.binnavi.Database.CConnection;
import com.google.security.zynamics.binnavi.Database.CTableNames;
import com.google.security.zynamics.binnavi.Database.Exceptions.CouldntDeleteException;
import com.google.security.zynamics.binnavi.Database.Exceptions.CouldntLoadDataException;
import com.google.security.zynamics.binnavi.Database.Exceptions.CouldntSaveDataException;
import com.google.security.zynamics.binnavi.Database.PostgreSQL.PostgreSQLHelpers;
import com.google.security.zynamics.binnavi.Log.NaviLogger;
import com.google.security.zynamics.binnavi.debug.debugger.DebuggerTemplate;
import com.google.security.zynamics.binnavi.debug.debugger.DebuggerTemplateManager;
import com.google.security.zynamics.zylib.net.NetHelpers;
/**
* This class contains PostgreSQL queries for working with debuggers.
*/
public final class PostgresSQLDebuggerFunctions {
/**
* Do not instantiate this class.
*/
private PostgresSQLDebuggerFunctions() {
// You are not supposed to instantiate this class
}
/**
* Creates a new debugger template in the database.
*
* @param provider SQL provider of the new debugger template.
* @param name Name of the new debugger template. This argument must be non-empty.
* @param host Host of the new debugger template. This argument must be non-empty.
* @param port Port of the new debugger template. This argument must be a valid port number.
*
* @return The new debugger template.
*
* @throws CouldntSaveDataException Thrown if the new debugger template could not be written to
* the database.
*/
public static DebuggerTemplate createDebuggerTemplate(final AbstractSQLProvider provider,
final String name, final String host, final int port) throws CouldntSaveDataException {
Preconditions.checkNotNull(name, "IE00417: Debugger names can not be null");
Preconditions.checkArgument(!name.isEmpty(), "IE00418: Debugger names can not be empty");
Preconditions.checkNotNull(host, "IE00419: Debugger host can not be null");
Preconditions.checkArgument(!host.isEmpty(), "IE00418: Debugger host can not be empty");
Preconditions.checkArgument((port > 0) && (port <= 65535),
"IE00421: Debugger port is out of bounds");
NaviLogger.info("Creating new debugger %s (%s:%d)", name, host, port);
final CConnection connection = provider.getConnection();
final String query =
"INSERT INTO " + CTableNames.DEBUGGERS_TABLE
+ "(name, host, port) VALUES(?, ?, ?) RETURNING id";
try (PreparedStatement statement = connection.getConnection().prepareStatement(query);
ResultSet resultSet = statement.executeQuery()) {
statement.setString(1, name);
statement.setString(2, host);
statement.setInt(3, port);
int id = -1;
while (resultSet.next()) {
id = resultSet.getInt("id");
}
return new DebuggerTemplate(id, name, host, port, provider);
} catch (final SQLException e) {
throw new CouldntSaveDataException(e);
}
}
/**
* Deletes a debugger template from the database.
*
* The given debugger template must be stored in the database connected to by the provider
* argument.
*
* @param provider The connection to the database.
* @param debugger The debugger template to delete.
*
* @throws CouldntDeleteException Thrown if the debugger template could not be deleted.
*/
public static void deleteDebugger(final AbstractSQLProvider provider,
final DebuggerTemplate debugger) throws CouldntDeleteException {
Preconditions.checkNotNull(debugger, "IE00709: Debugger template argument can not be null");
Preconditions.checkArgument(debugger.inSameDatabase(provider),
"IE00710: Debugger template is not part of this database");
NaviLogger.info("Deleting debugger %d", debugger.getId());
PostgreSQLHelpers.deleteById(provider.getConnection(), CTableNames.DEBUGGERS_TABLE,
debugger.getId());
}
/**
* Loads all debugger templates of a database.
*
* The debugger template manager must belong to the database connected to by the provider
* argument.
*
* @param provider The connection to the database.
* @param manager Debugger template manager where the loaded debuggers are added to.
*
* @throws CouldntLoadDataException Thrown if the debugger templates could not be loaded.
*/
public static void loadDebuggers(final AbstractSQLProvider provider,
final DebuggerTemplateManager manager) throws CouldntLoadDataException {
final CConnection connection = provider.getConnection();
final String query = "SELECT * FROM " + CTableNames.DEBUGGERS_TABLE;
try (ResultSet resultSet = connection.executeQuery(query, true)) {
while (resultSet.next()) {
final DebuggerTemplate debugger =
new DebuggerTemplate(resultSet.getInt("id"), PostgreSQLHelpers.readString(resultSet,
"name"), PostgreSQLHelpers.readString(resultSet, "host"),
resultSet.getInt("port"), provider);
manager.addDebugger(debugger);
}
} catch (final SQLException e) {
throw new CouldntLoadDataException(e);
}
}
/**
* Changes the host of an existing debugger template.
*
* The debugger must be stored in the database the provider argument is connected to.
*
* @param provider The connection to the database.
* @param debugger The debugger whose host value is changed.
* @param host The new host value of the debugger template.
*
* @throws CouldntSaveDataException Thrown if the host value could not be updated.
*/
public static void setHost(final AbstractSQLProvider provider, final DebuggerTemplate debugger,
final String host) throws CouldntSaveDataException {
Preconditions.checkNotNull(debugger, "IE00422: Debugger argument can not be null");
Preconditions.checkNotNull(host, "IE00423: Host argument can not be null");
Preconditions.checkArgument(debugger.inSameDatabase(provider),
"IE00424: Debugger is not part of this database");
final String query = "UPDATE " + CTableNames.DEBUGGERS_TABLE + " SET host = ? WHERE id = ?";
try (PreparedStatement statement =
provider.getConnection().getConnection().prepareStatement(query)) {
statement.setString(1, host);
statement.setInt(2, debugger.getId());
statement.executeUpdate();
} catch (final SQLException e) {
throw new CouldntSaveDataException(e);
}
}
/**
* Changes the name of an existing debugger template.
*
* The debugger must be stored in the database the provider argument is connected to.
*
* @param provider The connection to the database.
* @param debugger The debugger whose name value is changed.
* @param name The new name value of the debugger template.
*
* @throws CouldntSaveDataException Thrown if the name value could not be updated.
*/
public static void setName(final AbstractSQLProvider provider, final DebuggerTemplate debugger,
final String name) throws CouldntSaveDataException {
Preconditions.checkNotNull(debugger, "IE00425: Debugger argument can not be null");
Preconditions.checkNotNull(name, "IE00426: Name argument can not be null");
Preconditions.checkArgument(debugger.inSameDatabase(provider),
"IE00427: Debugger is not part of this database");
final String query = "UPDATE " + CTableNames.DEBUGGERS_TABLE + " SET name = ? WHERE id = ?";
try (PreparedStatement statement =
provider.getConnection().getConnection().prepareStatement(query)) {
statement.setString(1, name);
statement.setInt(2, debugger.getId());
statement.executeUpdate();
} catch (final SQLException e) {
throw new CouldntSaveDataException(e);
}
}
/**
* Changes the port of an existing debugger template.
*
* The debugger must be stored in the database the provider argument is connected to.
*
* @param provider The connection to the database.
* @param debugger The debugger whose port value is changed.
* @param port The new port value of the debugger template. This argument must be a valid port
* number.
*
* @throws CouldntSaveDataException Thrown if the port value could not be updated.
*/
public static void setPort(final AbstractSQLProvider provider, final DebuggerTemplate debugger,
final int port) throws CouldntSaveDataException {
Preconditions.checkNotNull(debugger, "IE00428: Debugger argument can not be null");
Preconditions.checkArgument(NetHelpers.isValidPort(port), "IE00429: Invalid port argument");
Preconditions.checkArgument(debugger.inSameDatabase(provider),
"IE00430: Debugger is not part of this database");
final String query = "UPDATE " + CTableNames.DEBUGGERS_TABLE + " SET port = ? WHERE id = ?";
try (PreparedStatement statement =
provider.getConnection().getConnection().prepareStatement(query)) {
statement.setInt(1, port);
statement.setInt(2, debugger.getId());
statement.executeUpdate();
} catch (final SQLException e) {
throw new CouldntSaveDataException(e);
}
}
}
| apache-2.0 |
apache/tapestry4 | framework/src/java/org/apache/tapestry/engine/encoders/DirectServiceEncoder.java | 3758 | // Copyright 2005 The Apache Software Foundation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.apache.tapestry.engine.encoders;
import org.apache.tapestry.INamespace;
import org.apache.tapestry.Tapestry;
import org.apache.tapestry.engine.ServiceEncoder;
import org.apache.tapestry.engine.ServiceEncoding;
import org.apache.tapestry.services.ServiceConstants;
/**
* A specialized encoder for the {@link org.apache.tapestry.engine.DirectService direct service}
* that encodes the page name and component id path into the servlet path, and encodes the
* stateful flag by choosing one of two extensions.
*
* @author Howard M. Lewis Ship
* @since 4.0
*/
public class DirectServiceEncoder implements ServiceEncoder
{
private String _statelessExtension;
private String _statefulExtension;
public void encode(ServiceEncoding encoding)
{
String service = encoding.getParameterValue(ServiceConstants.SERVICE);
if (!service.equals(Tapestry.DIRECT_SERVICE))
return;
String pageName = encoding.getParameterValue(ServiceConstants.PAGE);
// Only handle pages in the application namespace (not from a library).
if (pageName.indexOf(INamespace.SEPARATOR) >= 0)
return;
String stateful = encoding.getParameterValue(ServiceConstants.SESSION);
String componentIdPath = encoding.getParameterValue(ServiceConstants.COMPONENT);
StringBuffer buffer = new StringBuffer("/");
buffer.append(pageName);
buffer.append(",");
buffer.append(componentIdPath);
buffer.append(".");
buffer.append(stateful != null ? _statefulExtension : _statelessExtension);
encoding.setServletPath(buffer.toString());
encoding.setParameterValue(ServiceConstants.SERVICE, null);
encoding.setParameterValue(ServiceConstants.PAGE, null);
encoding.setParameterValue(ServiceConstants.SESSION, null);
encoding.setParameterValue(ServiceConstants.COMPONENT, null);
}
public void decode(ServiceEncoding encoding)
{
String servletPath = encoding.getServletPath();
int dotx = servletPath.lastIndexOf('.');
if (dotx < 0)
return;
String extension = servletPath.substring(dotx + 1);
if (!(extension.equals(_statefulExtension) || extension.equals(_statelessExtension)))
return;
int commax = servletPath.lastIndexOf(',');
String pageName = servletPath.substring(1, commax);
String componentIdPath = servletPath.substring(commax + 1, dotx);
encoding.setParameterValue(ServiceConstants.SERVICE, Tapestry.DIRECT_SERVICE);
encoding.setParameterValue(ServiceConstants.PAGE, pageName);
encoding.setParameterValue(
ServiceConstants.SESSION,
extension.equals(_statefulExtension) ? "T" : null);
encoding.setParameterValue(ServiceConstants.COMPONENT, componentIdPath);
}
public void setStatefulExtension(String statefulExtension)
{
_statefulExtension = statefulExtension;
}
public void setStatelessExtension(String statelessExtension)
{
_statelessExtension = statelessExtension;
}
} | apache-2.0 |
analyst47/Ibobrov | chapter_002/src/test/java/ru/job4j/CoffeMachineTest.java | 661 | package ru.job4j;
import org.junit.Test;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
public class CoffeMachineTest {
@Test
public void whenValueIsFiftydAndPriceIsThirtyTwo() {
CoffeMachine test = new CoffeMachine();
int[] result = test.charge(50, 32);
int[] expect = {1, 1, 1, 1};
assertThat(result, is(expect));
}
@Test
public void whenValueIsThousandAndPriceIsSevenHundredThirtyTwo() {
CoffeMachine test = new CoffeMachine();
int[] result = test.charge(1000, 732);
int[] expect = {26, 1, 1, 1};
assertThat(result, is(expect));
}
} | apache-2.0 |
eric-stanley/cgeo | tests/src/cgeo/geocaching/StaticMapsProviderTest.java | 3287 | package cgeo.geocaching;
import static org.assertj.core.api.Assertions.assertThat;
import cgeo.geocaching.enumerations.WaypointType;
import cgeo.geocaching.files.LocalStorage;
import cgeo.geocaching.geopoint.Geopoint;
import cgeo.geocaching.settings.Settings;
import cgeo.geocaching.settings.TestSettings;
import cgeo.geocaching.utils.RxUtils;
import junit.framework.TestCase;
import android.test.suitebuilder.annotation.Suppress;
import java.io.File;
@Suppress
public class StaticMapsProviderTest extends TestCase {
public static void testDownloadStaticMaps() {
final double lat = 52.354176d;
final double lon = 9.745685d;
String geocode = "GCTEST1";
boolean backupStore = Settings.isStoreOfflineMaps();
boolean backupStoreWP = Settings.isStoreOfflineWpMaps();
TestSettings.setStoreOfflineMaps(true);
TestSettings.setStoreOfflineWpMaps(true);
try {
Geopoint gp = new Geopoint(lat + 0.25d, lon + 0.25d);
Geocache cache = new Geocache();
cache.setGeocode(geocode);
cache.setCoords(gp);
cache.setCacheId(String.valueOf(1));
Waypoint theFinal = new Waypoint("Final", WaypointType.FINAL, false);
Geopoint finalGp = new Geopoint(lat + 0.25d + 1, lon + 0.25d + 1);
theFinal.setCoords(finalGp);
theFinal.setId(1);
cache.addOrChangeWaypoint(theFinal, false);
Waypoint trailhead = new Waypoint("Trail head", WaypointType.TRAILHEAD, false);
Geopoint trailheadGp = new Geopoint(lat + 0.25d + 2, lon + 0.25d + 2);
trailhead.setCoords(trailheadGp);
trailhead.setId(2);
cache.addOrChangeWaypoint(trailhead, false);
// make sure we don't have stale downloads
deleteCacheDirectory(geocode);
assertThat(StaticMapsProvider.hasStaticMap(cache)).isFalse();
assertThat(StaticMapsProvider.hasStaticMapForWaypoint(geocode, theFinal)).isFalse();
assertThat(StaticMapsProvider.hasStaticMapForWaypoint(geocode, trailhead)).isFalse();
// download
RxUtils.waitForCompletion(StaticMapsProvider.downloadMaps(cache));
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
fail();
}
// check download
assertThat(StaticMapsProvider.hasStaticMap(cache)).isTrue();
assertThat(StaticMapsProvider.hasStaticMapForWaypoint(geocode, theFinal)).isTrue();
assertThat(StaticMapsProvider.hasStaticMapForWaypoint(geocode, trailhead)).isTrue();
// waypoint static maps hashcode dependent
trailhead.setCoords(new Geopoint(lat + 0.24d + 2, lon + 0.25d + 2));
assertThat(StaticMapsProvider.hasStaticMapForWaypoint(geocode, trailhead)).isFalse();
} finally {
TestSettings.setStoreOfflineWpMaps(backupStoreWP);
TestSettings.setStoreOfflineMaps(backupStore);
deleteCacheDirectory(geocode);
}
}
private static void deleteCacheDirectory(String geocode) {
File cacheDir = LocalStorage.getStorageDir(geocode);
LocalStorage.deleteDirectory(cacheDir);
}
}
| apache-2.0 |
googleapis/java-language | proto-google-cloud-language-v1/src/main/java/com/google/cloud/language/v1/Sentence.java | 32501 | /*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/language/v1/language_service.proto
package com.google.cloud.language.v1;
/**
*
*
* <pre>
* Represents a sentence in the input document.
* </pre>
*
* Protobuf type {@code google.cloud.language.v1.Sentence}
*/
public final class Sentence extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.language.v1.Sentence)
SentenceOrBuilder {
private static final long serialVersionUID = 0L;
// Use Sentence.newBuilder() to construct.
private Sentence(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private Sentence() {}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new Sentence();
}
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet getUnknownFields() {
return this.unknownFields;
}
private Sentence(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
this();
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
com.google.protobuf.UnknownFieldSet.Builder unknownFields =
com.google.protobuf.UnknownFieldSet.newBuilder();
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
com.google.cloud.language.v1.TextSpan.Builder subBuilder = null;
if (text_ != null) {
subBuilder = text_.toBuilder();
}
text_ =
input.readMessage(
com.google.cloud.language.v1.TextSpan.parser(), extensionRegistry);
if (subBuilder != null) {
subBuilder.mergeFrom(text_);
text_ = subBuilder.buildPartial();
}
break;
}
case 18:
{
com.google.cloud.language.v1.Sentiment.Builder subBuilder = null;
if (sentiment_ != null) {
subBuilder = sentiment_.toBuilder();
}
sentiment_ =
input.readMessage(
com.google.cloud.language.v1.Sentiment.parser(), extensionRegistry);
if (subBuilder != null) {
subBuilder.mergeFrom(sentiment_);
sentiment_ = subBuilder.buildPartial();
}
break;
}
default:
{
if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) {
done = true;
}
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this);
} finally {
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.language.v1.LanguageServiceProto
.internal_static_google_cloud_language_v1_Sentence_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.language.v1.LanguageServiceProto
.internal_static_google_cloud_language_v1_Sentence_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.language.v1.Sentence.class,
com.google.cloud.language.v1.Sentence.Builder.class);
}
public static final int TEXT_FIELD_NUMBER = 1;
private com.google.cloud.language.v1.TextSpan text_;
/**
*
*
* <pre>
* The sentence text.
* </pre>
*
* <code>.google.cloud.language.v1.TextSpan text = 1;</code>
*
* @return Whether the text field is set.
*/
@java.lang.Override
public boolean hasText() {
return text_ != null;
}
/**
*
*
* <pre>
* The sentence text.
* </pre>
*
* <code>.google.cloud.language.v1.TextSpan text = 1;</code>
*
* @return The text.
*/
@java.lang.Override
public com.google.cloud.language.v1.TextSpan getText() {
return text_ == null ? com.google.cloud.language.v1.TextSpan.getDefaultInstance() : text_;
}
/**
*
*
* <pre>
* The sentence text.
* </pre>
*
* <code>.google.cloud.language.v1.TextSpan text = 1;</code>
*/
@java.lang.Override
public com.google.cloud.language.v1.TextSpanOrBuilder getTextOrBuilder() {
return getText();
}
public static final int SENTIMENT_FIELD_NUMBER = 2;
private com.google.cloud.language.v1.Sentiment sentiment_;
/**
*
*
* <pre>
* For calls to [AnalyzeSentiment][] or if
* [AnnotateTextRequest.Features.extract_document_sentiment][google.cloud.language.v1.AnnotateTextRequest.Features.extract_document_sentiment] is set to
* true, this field will contain the sentiment for the sentence.
* </pre>
*
* <code>.google.cloud.language.v1.Sentiment sentiment = 2;</code>
*
* @return Whether the sentiment field is set.
*/
@java.lang.Override
public boolean hasSentiment() {
return sentiment_ != null;
}
/**
*
*
* <pre>
* For calls to [AnalyzeSentiment][] or if
* [AnnotateTextRequest.Features.extract_document_sentiment][google.cloud.language.v1.AnnotateTextRequest.Features.extract_document_sentiment] is set to
* true, this field will contain the sentiment for the sentence.
* </pre>
*
* <code>.google.cloud.language.v1.Sentiment sentiment = 2;</code>
*
* @return The sentiment.
*/
@java.lang.Override
public com.google.cloud.language.v1.Sentiment getSentiment() {
return sentiment_ == null
? com.google.cloud.language.v1.Sentiment.getDefaultInstance()
: sentiment_;
}
/**
*
*
* <pre>
* For calls to [AnalyzeSentiment][] or if
* [AnnotateTextRequest.Features.extract_document_sentiment][google.cloud.language.v1.AnnotateTextRequest.Features.extract_document_sentiment] is set to
* true, this field will contain the sentiment for the sentence.
* </pre>
*
* <code>.google.cloud.language.v1.Sentiment sentiment = 2;</code>
*/
@java.lang.Override
public com.google.cloud.language.v1.SentimentOrBuilder getSentimentOrBuilder() {
return getSentiment();
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (text_ != null) {
output.writeMessage(1, getText());
}
if (sentiment_ != null) {
output.writeMessage(2, getSentiment());
}
unknownFields.writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (text_ != null) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, getText());
}
if (sentiment_ != null) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(2, getSentiment());
}
size += unknownFields.getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.language.v1.Sentence)) {
return super.equals(obj);
}
com.google.cloud.language.v1.Sentence other = (com.google.cloud.language.v1.Sentence) obj;
if (hasText() != other.hasText()) return false;
if (hasText()) {
if (!getText().equals(other.getText())) return false;
}
if (hasSentiment() != other.hasSentiment()) return false;
if (hasSentiment()) {
if (!getSentiment().equals(other.getSentiment())) return false;
}
if (!unknownFields.equals(other.unknownFields)) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
if (hasText()) {
hash = (37 * hash) + TEXT_FIELD_NUMBER;
hash = (53 * hash) + getText().hashCode();
}
if (hasSentiment()) {
hash = (37 * hash) + SENTIMENT_FIELD_NUMBER;
hash = (53 * hash) + getSentiment().hashCode();
}
hash = (29 * hash) + unknownFields.hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.language.v1.Sentence parseFrom(java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.language.v1.Sentence parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.language.v1.Sentence parseFrom(com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.language.v1.Sentence parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.language.v1.Sentence parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.language.v1.Sentence parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.language.v1.Sentence parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.language.v1.Sentence parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.language.v1.Sentence parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.language.v1.Sentence parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.language.v1.Sentence parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.language.v1.Sentence parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(com.google.cloud.language.v1.Sentence prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* Represents a sentence in the input document.
* </pre>
*
* Protobuf type {@code google.cloud.language.v1.Sentence}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.language.v1.Sentence)
com.google.cloud.language.v1.SentenceOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.language.v1.LanguageServiceProto
.internal_static_google_cloud_language_v1_Sentence_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.language.v1.LanguageServiceProto
.internal_static_google_cloud_language_v1_Sentence_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.language.v1.Sentence.class,
com.google.cloud.language.v1.Sentence.Builder.class);
}
// Construct using com.google.cloud.language.v1.Sentence.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {}
}
@java.lang.Override
public Builder clear() {
super.clear();
if (textBuilder_ == null) {
text_ = null;
} else {
text_ = null;
textBuilder_ = null;
}
if (sentimentBuilder_ == null) {
sentiment_ = null;
} else {
sentiment_ = null;
sentimentBuilder_ = null;
}
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.language.v1.LanguageServiceProto
.internal_static_google_cloud_language_v1_Sentence_descriptor;
}
@java.lang.Override
public com.google.cloud.language.v1.Sentence getDefaultInstanceForType() {
return com.google.cloud.language.v1.Sentence.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.language.v1.Sentence build() {
com.google.cloud.language.v1.Sentence result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.language.v1.Sentence buildPartial() {
com.google.cloud.language.v1.Sentence result =
new com.google.cloud.language.v1.Sentence(this);
if (textBuilder_ == null) {
result.text_ = text_;
} else {
result.text_ = textBuilder_.build();
}
if (sentimentBuilder_ == null) {
result.sentiment_ = sentiment_;
} else {
result.sentiment_ = sentimentBuilder_.build();
}
onBuilt();
return result;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.language.v1.Sentence) {
return mergeFrom((com.google.cloud.language.v1.Sentence) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.language.v1.Sentence other) {
if (other == com.google.cloud.language.v1.Sentence.getDefaultInstance()) return this;
if (other.hasText()) {
mergeText(other.getText());
}
if (other.hasSentiment()) {
mergeSentiment(other.getSentiment());
}
this.mergeUnknownFields(other.unknownFields);
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
com.google.cloud.language.v1.Sentence parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (com.google.cloud.language.v1.Sentence) e.getUnfinishedMessage();
throw e.unwrapIOException();
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private com.google.cloud.language.v1.TextSpan text_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.language.v1.TextSpan,
com.google.cloud.language.v1.TextSpan.Builder,
com.google.cloud.language.v1.TextSpanOrBuilder>
textBuilder_;
/**
*
*
* <pre>
* The sentence text.
* </pre>
*
* <code>.google.cloud.language.v1.TextSpan text = 1;</code>
*
* @return Whether the text field is set.
*/
public boolean hasText() {
return textBuilder_ != null || text_ != null;
}
/**
*
*
* <pre>
* The sentence text.
* </pre>
*
* <code>.google.cloud.language.v1.TextSpan text = 1;</code>
*
* @return The text.
*/
public com.google.cloud.language.v1.TextSpan getText() {
if (textBuilder_ == null) {
return text_ == null ? com.google.cloud.language.v1.TextSpan.getDefaultInstance() : text_;
} else {
return textBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* The sentence text.
* </pre>
*
* <code>.google.cloud.language.v1.TextSpan text = 1;</code>
*/
public Builder setText(com.google.cloud.language.v1.TextSpan value) {
if (textBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
text_ = value;
onChanged();
} else {
textBuilder_.setMessage(value);
}
return this;
}
/**
*
*
* <pre>
* The sentence text.
* </pre>
*
* <code>.google.cloud.language.v1.TextSpan text = 1;</code>
*/
public Builder setText(com.google.cloud.language.v1.TextSpan.Builder builderForValue) {
if (textBuilder_ == null) {
text_ = builderForValue.build();
onChanged();
} else {
textBuilder_.setMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The sentence text.
* </pre>
*
* <code>.google.cloud.language.v1.TextSpan text = 1;</code>
*/
public Builder mergeText(com.google.cloud.language.v1.TextSpan value) {
if (textBuilder_ == null) {
if (text_ != null) {
text_ =
com.google.cloud.language.v1.TextSpan.newBuilder(text_)
.mergeFrom(value)
.buildPartial();
} else {
text_ = value;
}
onChanged();
} else {
textBuilder_.mergeFrom(value);
}
return this;
}
/**
*
*
* <pre>
* The sentence text.
* </pre>
*
* <code>.google.cloud.language.v1.TextSpan text = 1;</code>
*/
public Builder clearText() {
if (textBuilder_ == null) {
text_ = null;
onChanged();
} else {
text_ = null;
textBuilder_ = null;
}
return this;
}
/**
*
*
* <pre>
* The sentence text.
* </pre>
*
* <code>.google.cloud.language.v1.TextSpan text = 1;</code>
*/
public com.google.cloud.language.v1.TextSpan.Builder getTextBuilder() {
onChanged();
return getTextFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* The sentence text.
* </pre>
*
* <code>.google.cloud.language.v1.TextSpan text = 1;</code>
*/
public com.google.cloud.language.v1.TextSpanOrBuilder getTextOrBuilder() {
if (textBuilder_ != null) {
return textBuilder_.getMessageOrBuilder();
} else {
return text_ == null ? com.google.cloud.language.v1.TextSpan.getDefaultInstance() : text_;
}
}
/**
*
*
* <pre>
* The sentence text.
* </pre>
*
* <code>.google.cloud.language.v1.TextSpan text = 1;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.language.v1.TextSpan,
com.google.cloud.language.v1.TextSpan.Builder,
com.google.cloud.language.v1.TextSpanOrBuilder>
getTextFieldBuilder() {
if (textBuilder_ == null) {
textBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.language.v1.TextSpan,
com.google.cloud.language.v1.TextSpan.Builder,
com.google.cloud.language.v1.TextSpanOrBuilder>(
getText(), getParentForChildren(), isClean());
text_ = null;
}
return textBuilder_;
}
private com.google.cloud.language.v1.Sentiment sentiment_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.language.v1.Sentiment,
com.google.cloud.language.v1.Sentiment.Builder,
com.google.cloud.language.v1.SentimentOrBuilder>
sentimentBuilder_;
/**
*
*
* <pre>
* For calls to [AnalyzeSentiment][] or if
* [AnnotateTextRequest.Features.extract_document_sentiment][google.cloud.language.v1.AnnotateTextRequest.Features.extract_document_sentiment] is set to
* true, this field will contain the sentiment for the sentence.
* </pre>
*
* <code>.google.cloud.language.v1.Sentiment sentiment = 2;</code>
*
* @return Whether the sentiment field is set.
*/
public boolean hasSentiment() {
return sentimentBuilder_ != null || sentiment_ != null;
}
/**
*
*
* <pre>
* For calls to [AnalyzeSentiment][] or if
* [AnnotateTextRequest.Features.extract_document_sentiment][google.cloud.language.v1.AnnotateTextRequest.Features.extract_document_sentiment] is set to
* true, this field will contain the sentiment for the sentence.
* </pre>
*
* <code>.google.cloud.language.v1.Sentiment sentiment = 2;</code>
*
* @return The sentiment.
*/
public com.google.cloud.language.v1.Sentiment getSentiment() {
if (sentimentBuilder_ == null) {
return sentiment_ == null
? com.google.cloud.language.v1.Sentiment.getDefaultInstance()
: sentiment_;
} else {
return sentimentBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* For calls to [AnalyzeSentiment][] or if
* [AnnotateTextRequest.Features.extract_document_sentiment][google.cloud.language.v1.AnnotateTextRequest.Features.extract_document_sentiment] is set to
* true, this field will contain the sentiment for the sentence.
* </pre>
*
* <code>.google.cloud.language.v1.Sentiment sentiment = 2;</code>
*/
public Builder setSentiment(com.google.cloud.language.v1.Sentiment value) {
if (sentimentBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
sentiment_ = value;
onChanged();
} else {
sentimentBuilder_.setMessage(value);
}
return this;
}
/**
*
*
* <pre>
* For calls to [AnalyzeSentiment][] or if
* [AnnotateTextRequest.Features.extract_document_sentiment][google.cloud.language.v1.AnnotateTextRequest.Features.extract_document_sentiment] is set to
* true, this field will contain the sentiment for the sentence.
* </pre>
*
* <code>.google.cloud.language.v1.Sentiment sentiment = 2;</code>
*/
public Builder setSentiment(com.google.cloud.language.v1.Sentiment.Builder builderForValue) {
if (sentimentBuilder_ == null) {
sentiment_ = builderForValue.build();
onChanged();
} else {
sentimentBuilder_.setMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* For calls to [AnalyzeSentiment][] or if
* [AnnotateTextRequest.Features.extract_document_sentiment][google.cloud.language.v1.AnnotateTextRequest.Features.extract_document_sentiment] is set to
* true, this field will contain the sentiment for the sentence.
* </pre>
*
* <code>.google.cloud.language.v1.Sentiment sentiment = 2;</code>
*/
public Builder mergeSentiment(com.google.cloud.language.v1.Sentiment value) {
if (sentimentBuilder_ == null) {
if (sentiment_ != null) {
sentiment_ =
com.google.cloud.language.v1.Sentiment.newBuilder(sentiment_)
.mergeFrom(value)
.buildPartial();
} else {
sentiment_ = value;
}
onChanged();
} else {
sentimentBuilder_.mergeFrom(value);
}
return this;
}
/**
*
*
* <pre>
* For calls to [AnalyzeSentiment][] or if
* [AnnotateTextRequest.Features.extract_document_sentiment][google.cloud.language.v1.AnnotateTextRequest.Features.extract_document_sentiment] is set to
* true, this field will contain the sentiment for the sentence.
* </pre>
*
* <code>.google.cloud.language.v1.Sentiment sentiment = 2;</code>
*/
public Builder clearSentiment() {
if (sentimentBuilder_ == null) {
sentiment_ = null;
onChanged();
} else {
sentiment_ = null;
sentimentBuilder_ = null;
}
return this;
}
/**
*
*
* <pre>
* For calls to [AnalyzeSentiment][] or if
* [AnnotateTextRequest.Features.extract_document_sentiment][google.cloud.language.v1.AnnotateTextRequest.Features.extract_document_sentiment] is set to
* true, this field will contain the sentiment for the sentence.
* </pre>
*
* <code>.google.cloud.language.v1.Sentiment sentiment = 2;</code>
*/
public com.google.cloud.language.v1.Sentiment.Builder getSentimentBuilder() {
onChanged();
return getSentimentFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* For calls to [AnalyzeSentiment][] or if
* [AnnotateTextRequest.Features.extract_document_sentiment][google.cloud.language.v1.AnnotateTextRequest.Features.extract_document_sentiment] is set to
* true, this field will contain the sentiment for the sentence.
* </pre>
*
* <code>.google.cloud.language.v1.Sentiment sentiment = 2;</code>
*/
public com.google.cloud.language.v1.SentimentOrBuilder getSentimentOrBuilder() {
if (sentimentBuilder_ != null) {
return sentimentBuilder_.getMessageOrBuilder();
} else {
return sentiment_ == null
? com.google.cloud.language.v1.Sentiment.getDefaultInstance()
: sentiment_;
}
}
/**
*
*
* <pre>
* For calls to [AnalyzeSentiment][] or if
* [AnnotateTextRequest.Features.extract_document_sentiment][google.cloud.language.v1.AnnotateTextRequest.Features.extract_document_sentiment] is set to
* true, this field will contain the sentiment for the sentence.
* </pre>
*
* <code>.google.cloud.language.v1.Sentiment sentiment = 2;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.language.v1.Sentiment,
com.google.cloud.language.v1.Sentiment.Builder,
com.google.cloud.language.v1.SentimentOrBuilder>
getSentimentFieldBuilder() {
if (sentimentBuilder_ == null) {
sentimentBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.language.v1.Sentiment,
com.google.cloud.language.v1.Sentiment.Builder,
com.google.cloud.language.v1.SentimentOrBuilder>(
getSentiment(), getParentForChildren(), isClean());
sentiment_ = null;
}
return sentimentBuilder_;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.language.v1.Sentence)
}
// @@protoc_insertion_point(class_scope:google.cloud.language.v1.Sentence)
private static final com.google.cloud.language.v1.Sentence DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.language.v1.Sentence();
}
public static com.google.cloud.language.v1.Sentence getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<Sentence> PARSER =
new com.google.protobuf.AbstractParser<Sentence>() {
@java.lang.Override
public Sentence parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new Sentence(input, extensionRegistry);
}
};
public static com.google.protobuf.Parser<Sentence> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<Sentence> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.language.v1.Sentence getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
| apache-2.0 |
KirillMakarov/edx-app-android | VideoLocker/src/main/java/org/edx/mobile/view/adapters/MyCourseAdapter.java | 6137 | package org.edx.mobile.view.adapters;
import android.annotation.SuppressLint;
import android.content.Context;
import android.os.SystemClock;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import org.edx.mobile.R;
import org.edx.mobile.core.IEdxEnvironment;
import org.edx.mobile.model.api.CourseEntry;
import org.edx.mobile.model.api.EnrolledCoursesResponse;
import org.edx.mobile.social.SocialMember;
import org.edx.mobile.util.images.TopAnchorFillWidthTransformation;
import org.edx.mobile.view.custom.SocialFacePileView;
import java.util.List;
public abstract class MyCourseAdapter extends BaseListAdapter<EnrolledCoursesResponse> {
private long lastClickTime;
private boolean showSocial;
private CourseFriendsListener courseFriendsListener;
public interface CourseFriendsListener {
public void fetchCourseFriends(EnrolledCoursesResponse course);
}
public int getPositionForCourseId(String courseId){
for(int i = 0; i < getCount(); i++){
if(getItem(i).getCourse() != null && TextUtils.equals(getItem(i).getCourse().getId(), courseId))
return i;
}
return -1;
}
public MyCourseAdapter(Context context, boolean showSocial, CourseFriendsListener courseFriendsListener,IEdxEnvironment environment ) {
super(context, R.layout.row_course_list, environment);
this.courseFriendsListener = courseFriendsListener;
this.showSocial = showSocial;
lastClickTime = 0;
}
@SuppressLint("SimpleDateFormat")
@Override
public void render(BaseViewHolder tag, final EnrolledCoursesResponse enrollment) {
ViewHolder holder = (ViewHolder) tag;
CourseEntry courseData = enrollment.getCourse();
holder.courseTitle.setText(courseData.getName());
if (enrollment.getCourse().hasUpdates()) {
holder.startingFrom.setVisibility(View.GONE);
holder.newCourseContent.setVisibility(View.VISIBLE);
holder.newCourseContent.setTag(courseData);
holder.newCourseContent
.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
onAnnouncementClicked(enrollment);
}
});
} else {
holder.newCourseContent.setVisibility(View.GONE);
holder.startingFrom.setVisibility(View.VISIBLE);
holder.courseRun.setText(courseData.getDescription(getContext(), false));
holder.startingFrom.setText(courseData.getFormattedStartDate(getContext()));
}
if(enrollment.isCertificateEarned()){
holder.certificateBanner.setVisibility(View.VISIBLE);
} else {
holder.certificateBanner.setVisibility(View.GONE);
}
Glide.with(getContext())
.load(courseData.getCourse_image(environment.getConfig()))
.placeholder(R.drawable.edx_map)
.transform(new TopAnchorFillWidthTransformation(getContext()))
.into(holder.courseImage);
if (showSocial) {
holder.facePileContainer.setVisibility(View.INVISIBLE);
List<SocialMember> membersList = enrollment.getCourse().getMembers_list();
if (membersList == null) {
courseFriendsListener.fetchCourseFriends(enrollment);
} else if (membersList.size() > 0){
holder.facePileContainer.setVisibility(View.VISIBLE);
holder.facePileView.setMemberList(membersList);
}
} else {
holder.facePileContainer.setVisibility(View.GONE);
}
}
@Override
public BaseViewHolder getTag(View convertView) {
ViewHolder holder = new ViewHolder();
holder.courseTitle = (TextView) convertView
.findViewById(R.id.course_name);
holder.courseRun = (TextView) convertView
.findViewById(R.id.course_run);
holder.startingFrom = (TextView) convertView
.findViewById(R.id.starting_from);
holder.courseImage = (ImageView) convertView
.findViewById(R.id.course_image);
holder.newCourseContent = convertView
.findViewById(R.id.new_course_content_layout);
holder.certificateBanner = convertView
.findViewById(R.id.course_certified_banner);
holder.facePileView = (SocialFacePileView) convertView
.findViewById(R.id.course_item_facepileview);
holder.facePileContainer = (ViewGroup) convertView
.findViewById(R.id.course_item_facepile_container);
return holder;
}
private static class ViewHolder extends BaseViewHolder {
ImageView courseImage;
TextView courseTitle;
TextView courseRun;
TextView startingFrom;
View certificateBanner;
View newCourseContent;
ViewGroup facePileContainer;
SocialFacePileView facePileView;
}
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
//This time is checked to avoid taps in quick succession
long currentTime = SystemClock.elapsedRealtime();
if (currentTime - lastClickTime > MIN_CLICK_INTERVAL) {
lastClickTime = currentTime;
EnrolledCoursesResponse model = getItem(position);
if(model!=null) onItemClicked(model);
}
}
public abstract void onItemClicked(EnrolledCoursesResponse model);
public abstract void onAnnouncementClicked(EnrolledCoursesResponse model);
public boolean isShowSocial() {
return showSocial;
}
public void setShowSocial(boolean showSocial) {
if (showSocial != this.showSocial){
this.showSocial = showSocial;
this.notifyDataSetChanged();
}
}
}
| apache-2.0 |
degauhta/dgagarsky | chapter_009/lesson_3/src/test/java/ru/dega/servlets/CreateUserTest.java | 2998 | package ru.dega.servlets;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;
import ru.dega.DBManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import java.io.IOException;
import java.io.StringWriter;
import java.io.PrintWriter;
import java.sql.SQLException;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.atLeast;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
/**
* CreateUserTest class.
*
* @author Denis
* @since 10.08.2017
*/
@RunWith(MockitoJUnitRunner.class)
public class CreateUserTest {
/**
* Http servlet request.
*/
private HttpServletRequest request;
/**
* Http servlet response.
*/
private HttpServletResponse response;
/**
* Datasource mock.
*/
@Mock
private DataSource ds;
/**
* Database manager mock.
*/
@Mock
private DBManager dbManager;
/**
* Users servlet.
*/
@InjectMocks
private CreateUser createUserServlet = new CreateUser();
/**
* Initialization.
*/
@Before
public void init() {
request = mock(HttpServletRequest.class);
response = mock(HttpServletResponse.class);
}
/**
* Test.
*
* @throws IOException error
* @throws ServletException error
*/
@Test
public void testGet() throws IOException, ServletException {
StringWriter sw = new StringWriter();
Mockito.when(response.getWriter()).thenReturn(new PrintWriter(sw));
Mockito.when(request.getContextPath()).thenReturn("http://localhost:8080/html/");
createUserServlet.doGet(request, response);
verify(response, atLeast(1)).getWriter();
verify(request, atLeast(1)).getContextPath();
}
/**
* Test post.
*
* @throws ServletException error
* @throws IOException error
* @throws SQLException error
*/
@Test
public void testPost() throws ServletException, IOException, SQLException {
StringWriter sw = new StringWriter();
Mockito.when(response.getWriter()).thenReturn(new PrintWriter(sw));
Mockito.when(request.getParameter("name")).thenReturn("test-name");
Mockito.when(request.getParameter("login")).thenReturn("test-login");
Mockito.when(request.getParameter("email")).thenReturn("test-email");
Mockito.when(ds.getConnection()).thenReturn(null);
Mockito.when(dbManager.addEntry(any(), any())).thenReturn(true);
createUserServlet.doPost(request, response);
assertThat(sw.toString(), is("create user test-login"));
}
} | apache-2.0 |
drapp/TaskMob | src/com/stackmob/taskmob/TaskActivity.java | 2326 | package com.stackmob.taskmob;
import com.stackmob.sdk.exception.StackMobException;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.Toast;
public class TaskActivity extends ListActivity {
private TaskList taskList;
private Button addTaskButton;
private TaskAdapter adapter;
private int index;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tasks);
taskList = new TaskList();
try {
taskList.fillFromJson(getIntent().getExtras().getString(TaskMob.TASKLIST_KEY));
} catch (StackMobException e) {
Toast.makeText(getApplicationContext(), "Error deserializing " + e.getMessage(), Toast.LENGTH_LONG);
}
index = getIntent().getIntExtra(TaskMob.TASKLIST_INDEX, 0);
adapter = new TaskAdapter(getApplicationContext(), R.layout.taskrow, taskList.getTasks());
setListAdapter(adapter);
addTaskButton = (Button) this.findViewById(R.id.add_task_button);
addTaskButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
startActivityForResult(new Intent(getApplicationContext(), AddTaskActivity.class),0);
}
});
getListView().setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> av, View v, int pos, long id) {
Task t = adapter.getItem(pos);
CheckBox cb = (CheckBox) v.findViewById(R.id.task_done_checkbox);
cb.setChecked(!cb.isChecked());
t.setDone(cb.isChecked());
t.save();
}
});
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
try {
Task t = new Task();
t.fillFromJson(data.getStringExtra("new_task"));
taskList.getTasks().add(t);
taskList.saveWithDepth(1);
adapter.notifyDataSetChanged();
} catch (StackMobException e) {
}
}
@Override
public void onBackPressed() {
Intent i = getIntent();
i.putExtra(TaskMob.TASKLIST_INDEX, index);
i.putExtra(TaskMob.TASKLIST_RETURN_KEY, taskList.toJson());
setResult(RESULT_OK, i);
super.onBackPressed();
}
} | apache-2.0 |
milg0/onvif-java-lib | src/org/onvif/ver10/media/wsdl/GetOSDOptionsResponse.java | 2955 | //
// Diese Datei wurde mit der JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.5-2 generiert
// Siehe <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// �nderungen an dieser Datei gehen bei einer Neukompilierung des Quellschemas verloren.
// Generiert: 2014.02.19 um 02:35:56 PM CET
//
package org.onvif.ver10.media.wsdl;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAnyElement;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import org.onvif.ver10.schema.OSDConfigurationOptions;
import org.w3c.dom.Element;
/**
* <p>
* Java-Klasse f�r anonymous complex type.
*
* <p>
* Das folgende Schemafragment gibt den erwarteten Content an, der in dieser Klasse enthalten ist.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="OSDOptions" type="{http://www.onvif.org/ver10/schema}OSDConfigurationOptions"/>
* <any processContents='lax' maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = { "osdOptions", "any" })
@XmlRootElement(name = "GetOSDOptionsResponse")
public class GetOSDOptionsResponse {
@XmlElement(name = "OSDOptions", required = true)
protected OSDConfigurationOptions osdOptions;
@XmlAnyElement(lax = true)
protected List<Object> any;
/**
* Ruft den Wert der osdOptions-Eigenschaft ab.
*
* @return possible object is {@link OSDConfigurationOptions }
*
*/
public OSDConfigurationOptions getOSDOptions() {
return osdOptions;
}
/**
* Legt den Wert der osdOptions-Eigenschaft fest.
*
* @param value
* allowed object is {@link OSDConfigurationOptions }
*
*/
public void setOSDOptions(OSDConfigurationOptions value) {
this.osdOptions = value;
}
/**
* Gets the value of the any property.
*
* <p>
* This accessor method returns a reference to the live list, not a snapshot. Therefore any modification you make to the returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the any property.
*
* <p>
* For example, to add a new item, do as follows:
*
* <pre>
* getAny().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list {@link Object } {@link Element }
*
*
*/
public List<Object> getAny() {
if (any == null) {
any = new ArrayList<Object>();
}
return this.any;
}
}
| apache-2.0 |
daima/solo-spring | src/main/java/org/b3log/solo/dao/repository/Blob.java | 1231 | /*
* Copyright (c) 2017, cxy7.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.b3log.solo.dao.repository;
import java.io.Serializable;
/**
* Blob.
*
* @author <a href="http://cxy7.com">XyCai</a>
* @version 1.0.0.2, Jan 18, 2011
*/
public final class Blob implements Serializable {
/**
* Default serial version uid.
*/
private static final long serialVersionUID = 1L;
/**
* Bytes.
*/
private byte[] bytes;
/**
* Constructs a blob with the specified bytes.
*
* @param bytes
* the specified bytes
*/
public Blob(final byte[] bytes) {
this.bytes = bytes;
}
/**
* Gets bytes.
*
* @return bytes
*/
public byte[] getBytes() {
return bytes;
}
}
| apache-2.0 |
VHAINNOVATIONS/Telepathology | Source/Java/ImagingCommon/main/test/java/gov/va/med/imaging/BhieStudyURNTest.java | 5570 | package gov.va.med.imaging;
import gov.va.med.SERIALIZATION_FORMAT;
import gov.va.med.URN;
import gov.va.med.URNFactory;
import gov.va.med.imaging.exceptions.URNFormatException;
import junit.framework.TestCase;
public class BhieStudyURNTest
extends TestCase
{
private String[] VALID_URN_EXAMPLES = new String[]
{
"urn:bhiestudy:rp02-UJBJUYGBHCGFDUGGUYGUY",
"urn:vastudy:200-ABFFG-1-1234",
"urn:bhiestudy:655321-111DFEA-44456",
"urn:bhiestudy:000000000000000111111111111111999999999999999-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA-ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ" };
public void testStudyUrnBuilding() throws URNFormatException
{
BhieStudyURN studyURN1 = null;
BhieStudyURN studyURN2 = null;
studyURN1 = BhieStudyURN.create("42", "655321");
}
public void testToStringVariations()
throws URNFormatException
{
BhieStudyURN urn;
BhieStudyURN cloneUrn;
String ts;
String tsCDTP;
String tsNative;
urn = URNFactory.create("urn:bhiestudy:nss?42*19-a");
assertTrue(urn instanceof BhieStudyURN);
ts = urn.toString();
tsCDTP = urn.toStringCDTP();
tsNative = urn.toStringNative();
//System.out.println("RFC2141 = " + ts);
//System.out.println("Internal = " + tsInternal);
//System.out.println("Native = " + tsNative);
assertEquals("urn:bhiestudy:nss%3f42*19-a", ts);
assertEquals("urn:vastudy:200-nss%3f42%2a19%2da", tsCDTP);
assertEquals("urn:bhiestudy:nss?42*19-a", tsNative);
urn = URNFactory.create("urn:bhiestudy:4219-a-b-c");
ts = urn.toString();
tsCDTP = urn.toString(SERIALIZATION_FORMAT.CDTP);
tsNative = urn.toString(SERIALIZATION_FORMAT.NATIVE);
//System.out.println("RFC2141 = " + ts);
//System.out.println("Internal = " + tsInternal);
//System.out.println("Native = " + tsNative);
assertEquals("urn:bhiestudy:4219-a-b-c", ts);
assertEquals("urn:vastudy:200-4219%2da%2db%2dc", tsCDTP);
assertEquals("urn:bhiestudy:4219-a-b-c", tsNative);
cloneUrn = URNFactory.create(ts);
assertEquals(urn, cloneUrn);
cloneUrn = URNFactory.create(tsCDTP, SERIALIZATION_FORMAT.CDTP);
assertEquals(urn, cloneUrn);
cloneUrn = URNFactory.create(tsNative, SERIALIZATION_FORMAT.NATIVE);
assertEquals(urn, cloneUrn);
urn = URNFactory.create("urn:bhiestudy:nss?42*19-a-b-c");
ts = urn.toString();
tsCDTP = urn.toStringCDTP();
tsNative = urn.toStringNative();
//System.out.println("RFC2141 = " + ts);
//System.out.println("Internal = " + tsInternal);
//System.out.println("Native = " + tsNative);
assertEquals("urn:bhiestudy:nss%3f42*19-a-b-c", ts);
assertEquals("urn:vastudy:200-nss%3f42%2a19%2da%2db%2dc", tsCDTP);
assertEquals("urn:bhiestudy:nss?42*19-a-b-c", tsNative);
cloneUrn = URNFactory.create(ts);
assertEquals(urn, cloneUrn);
cloneUrn = URNFactory.create(tsCDTP, SERIALIZATION_FORMAT.CDTP);
assertEquals(urn, cloneUrn);
cloneUrn = URNFactory.create(tsNative);
assertEquals(urn, cloneUrn);
}
public void testToStringVariationsWithAdditionalIdentifiers()
throws URNFormatException
{
BhieStudyURN urn;
BhieStudyURN cloneUrn;
String ts;
String tsCDTP;
String tsNative;
urn = URNFactory.create("urn:bhiestudy:nss?42*19-a-b-c[id1]");
ts = urn.toString();
tsCDTP = urn.toString(SERIALIZATION_FORMAT.CDTP);
tsNative = urn.toString(SERIALIZATION_FORMAT.NATIVE);
//System.out.println("RFC2141 = " + ts);
//System.out.println("Internal = " + tsInternal);
//System.out.println("Native = " + tsNative);
assertEquals("urn:bhiestudy:nss%3f42*19-a-b-c", ts);
assertEquals("urn:vastudy:200-nss%3f42%2a19%2da%2db%2dc[id1]", tsCDTP);
assertEquals("urn:bhiestudy:nss?42*19-a-b-c", tsNative);
cloneUrn = URNFactory.create(tsCDTP, SERIALIZATION_FORMAT.CDTP);
assertEquals(urn, cloneUrn);
}
public void testStringifaction() throws URNFormatException
{
BhieStudyURN bhieStudyUrn = URNFactory.create(
"urn:bhiestudy:rp02_0108_rg01-67d2445e-4997-423b-9efb-3642e276c153",
BhieStudyURN.class
);
bhieStudyUrn.setPatientId("1008861107V475740");
String stringified = bhieStudyUrn.toString();
String stringifiedAsVAInternal = bhieStudyUrn.toString(SERIALIZATION_FORMAT.CDTP);
String stringifiedPatch83VFTP = bhieStudyUrn.toString(SERIALIZATION_FORMAT.PATCH83_VFTP);
String stringifiedAsNative = bhieStudyUrn.toString(SERIALIZATION_FORMAT.NATIVE);
//System.out.println("bhieStudyUrn.toString(): " + stringified);
//System.out.println("bhieStudyUrn.toStringAsVAInternal(): " + stringifiedAsVAInternal);
//System.out.println("bhieStudyUrn.toStringPatch83(): " + stringifiedPatch83VFTP);
//System.out.println("bhieStudyUrn.toStringAsNative(): " + stringifiedAsNative);
URN base32CreatedStudyUrn = URNFactory.create(stringifiedPatch83VFTP, SERIALIZATION_FORMAT.PATCH83_VFTP);
//System.out.println("base32CreatedStudyUrn.getClass(): " + base32CreatedStudyUrn.getClass());
//System.out.println("base32CreatedStudyUrn.toString(): " + base32CreatedStudyUrn.toString());
//System.out.println("base32CreatedStudyUrn.toStringAsNative(): " + base32CreatedStudyUrn.toString(SERIALIZATION_FORMAT.NATIVE));
assertEquals(bhieStudyUrn, base32CreatedStudyUrn);
URN nativeCreatedUrn = URNFactory.create(stringifiedAsNative, SERIALIZATION_FORMAT.NATIVE);
//System.out.println("nativeCreatedUrn.getClass(): " + nativeCreatedUrn.getClass());
//System.out.println("nativeCreatedUrn.toString(): " + nativeCreatedUrn.toString());
//System.out.println("nativeCreatedUrn.toStringAsNative(): " + nativeCreatedUrn.toString(SERIALIZATION_FORMAT.NATIVE));
assertEquals(bhieStudyUrn, nativeCreatedUrn);
}
}
| apache-2.0 |
terrancesnyder/solr-analytics | lucene/suggest/src/java/org/apache/lucene/search/spell/HighFrequencyDictionary.java | 3359 | /*
* 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.lucene.search.spell;
import java.io.IOException;
import java.util.Comparator;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.TermsEnum;
import org.apache.lucene.index.Terms;
import org.apache.lucene.index.MultiFields;
import org.apache.lucene.util.BytesRefIterator;
import org.apache.lucene.util.BytesRef;
/**
* HighFrequencyDictionary: terms taken from the given field
* of a Lucene index, which appear in a number of documents
* above a given threshold.
*
* Threshold is a value in [0..1] representing the minimum
* number of documents (of the total) where a term should appear.
*
* Based on LuceneDictionary.
*/
public class HighFrequencyDictionary implements Dictionary {
private IndexReader reader;
private String field;
private float thresh;
/**
* Creates a new Dictionary, pulling source terms from
* the specified <code>field</code> in the provided <code>reader</code>.
* <p>
* Terms appearing in less than <code>thresh</code> percentage of documents
* will be excluded.
*/
public HighFrequencyDictionary(IndexReader reader, String field, float thresh) {
this.reader = reader;
this.field = field;
this.thresh = thresh;
}
public final BytesRefIterator getWordsIterator() throws IOException {
return new HighFrequencyIterator();
}
final class HighFrequencyIterator implements TermFreqIterator {
private final BytesRef spare = new BytesRef();
private final TermsEnum termsEnum;
private int minNumDocs;
private long freq;
HighFrequencyIterator() throws IOException {
Terms terms = MultiFields.getTerms(reader, field);
if (terms != null) {
termsEnum = terms.iterator(null);
} else {
termsEnum = null;
}
minNumDocs = (int)(thresh * (float)reader.numDocs());
}
private boolean isFrequent(int freq) {
return freq >= minNumDocs;
}
public long weight() {
return freq;
}
@Override
public BytesRef next() throws IOException {
if (termsEnum != null) {
BytesRef next;
while((next = termsEnum.next()) != null) {
if (isFrequent(termsEnum.docFreq())) {
freq = termsEnum.docFreq();
spare.copyBytes(next);
return spare;
}
}
}
return null;
}
@Override
public Comparator<BytesRef> getComparator() {
if (termsEnum == null) {
return null;
} else {
return termsEnum.getComparator();
}
}
}
}
| apache-2.0 |
Thirteam/CMPUT301W16T13 | TextbookHub/app/src/main/java/cmput301/textbookhub/Controllers/MyBorrowsActivityController.java | 1104 | package cmput301.textbookhub.Controllers;
import java.util.ArrayList;
import java.util.concurrent.ExecutionException;
import cmput301.textbookhub.Models.DataHelper;
import cmput301.textbookhub.Models.Textbook;
import cmput301.textbookhub.Views.Activity_MyBorrows;
/**
* <code>MainActivityController</code> the controller of <code>Activity_MyBorrows</code>
* @author Thirteam
* @version 1.0
* @since 2016/03/10
* @see ActivityController
* @see DataHelper
* @see Activity_MyBorrows
*
* Created by Fred on 2016/3/10.
*/
public class MyBorrowsActivityController extends ActivityController {
public MyBorrowsActivityController() {}
public ArrayList<Textbook> getBooksIBorrowed(String me){
DataHelper.GetTextbookByBorrowerTask t = new DataHelper.GetTextbookByBorrowerTask();
ArrayList<Textbook> rv = new ArrayList<>();
t.execute(me);
try{
rv.addAll(t.get());
}catch(ExecutionException e){
e.printStackTrace();
}catch (InterruptedException e){
e.printStackTrace();
}
return rv;
}
}
| apache-2.0 |
andy-goryachev/FxEditor | src/goryachev/fxeditor/FxEditorStyles.java | 626 | // Copyright © 2019-2022 Andy Goryachev <andy@goryachev.com>
package goryachev.fxeditor;
import goryachev.fx.FxStyleSheet;
import goryachev.fx.Theme;
/**
* FxEditorStyles.
*/
public class FxEditorStyles
extends FxStyleSheet
{
public Object fxEditor(Theme theme)
{
return selector(FxEditor.PANE).defines
(
backgroundColor(commas(theme.textBG, theme.textBG)),
backgroundInsets(commas(0, 1)),
backgroundRadius(0),
// FIX does not work
selector(FOCUSED).defines
(
backgroundColor(commas(theme.focus, theme.textBG)),
backgroundInsets(commas(0, 1))
)
);
}
}
| apache-2.0 |
BlueBrain/bluima | modules/bluima_xml/src/main/java/ch/epfl/bbp/uima/xml/archivearticle3/MomentType.java | 6546 | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2011.12.14 at 03:30:44 PM CET
//
package ch.epfl.bbp.uima.xml.archivearticle3;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAnyAttribute;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlID;
import javax.xml.bind.annotation.XmlIDREF;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.adapters.CollapsedStringAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import javax.xml.namespace.QName;
/**
* <p>Java class for moment.type complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="moment.type">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <attGroup ref="{http://www.w3.org/1998/Math/MathML}moment.attlist"/>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "moment.type", namespace = "http://www.w3.org/1998/Math/MathML")
public class MomentType {
@XmlAttribute(name = "class")
@XmlSchemaType(name = "NMTOKENS")
protected List<String> clazz;
@XmlAttribute(name = "style")
protected String style;
@XmlAttribute(name = "xref")
@XmlIDREF
@XmlSchemaType(name = "IDREF")
protected Object xref;
@XmlAttribute(name = "id")
@XmlJavaTypeAdapter(CollapsedStringAdapter.class)
@XmlID
@XmlSchemaType(name = "ID")
protected String id;
@XmlAttribute(name = "href", namespace = "http://www.w3.org/1999/xlink")
@XmlSchemaType(name = "anySimpleType")
protected String href;
@XmlAttribute(name = "encoding")
protected String encoding;
@XmlAttribute(name = "definitionURL")
@XmlSchemaType(name = "anyURI")
protected String definitionURL;
@XmlAnyAttribute
private Map<QName, String> otherAttributes = new HashMap<QName, String>();
/**
* Gets the value of the clazz property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the clazz property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getClazz().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link String }
*
*
*/
public List<String> getClazz() {
if (clazz == null) {
clazz = new ArrayList<String>();
}
return this.clazz;
}
/**
* Gets the value of the style property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getStyle() {
return style;
}
/**
* Sets the value of the style property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setStyle(String value) {
this.style = value;
}
/**
* Gets the value of the xref property.
*
* @return
* possible object is
* {@link Object }
*
*/
public Object getXref() {
return xref;
}
/**
* Sets the value of the xref property.
*
* @param value
* allowed object is
* {@link Object }
*
*/
public void setXref(Object value) {
this.xref = value;
}
/**
* Gets the value of the id property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getId() {
return id;
}
/**
* Sets the value of the id property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setId(String value) {
this.id = value;
}
/**
* Gets the value of the href property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getHref() {
return href;
}
/**
* Sets the value of the href property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setHref(String value) {
this.href = value;
}
/**
* Gets the value of the encoding property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getEncoding() {
return encoding;
}
/**
* Sets the value of the encoding property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setEncoding(String value) {
this.encoding = value;
}
/**
* Gets the value of the definitionURL property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getDefinitionURL() {
return definitionURL;
}
/**
* Sets the value of the definitionURL property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDefinitionURL(String value) {
this.definitionURL = value;
}
/**
* Gets a map that contains attributes that aren't bound to any typed property on this class.
*
* <p>
* the map is keyed by the name of the attribute and
* the value is the string value of the attribute.
*
* the map returned by this method is live, and you can add new attribute
* by updating the map directly. Because of this design, there's no setter.
*
*
* @return
* always non-null
*/
public Map<QName, String> getOtherAttributes() {
return otherAttributes;
}
}
| apache-2.0 |
joewalnes/idea-community | java/openapi/src/com/intellij/util/xml/ClassMappingNameConverter.java | 2603 | /*
* Copyright 2000-2010 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.util.xml;
import com.intellij.openapi.util.Condition;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiClassType;
import com.intellij.psi.PsiElement;
import com.intellij.psi.codeStyle.JavaCodeStyleManager;
import com.intellij.psi.codeStyle.SuggestedNameInfo;
import com.intellij.psi.codeStyle.VariableKind;
import com.intellij.psi.util.PsiTypesUtil;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NotNull;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
/**
* @see com.intellij.util.xml.MappingClass
* @author Dmitry Avdeev
*/
public class ClassMappingNameConverter extends ResolvingConverter.StringConverter {
@NotNull
@Override
public Collection<? extends String> getVariants(ConvertContext context) {
DomElement parent = context.getInvocationElement().getParent();
assert parent != null;
List<DomElement> children = DomUtil.getDefinedChildren(parent, true, true);
DomElement classElement = ContainerUtil.find(children, new Condition<DomElement>() {
@Override
public boolean value(DomElement domElement) {
return domElement.getAnnotation(MappingClass.class) != null;
}
});
if (classElement == null) return Collections.emptyList();
PsiClass psiClass = (PsiClass)((GenericDomValue)classElement).getValue();
if (psiClass == null) return Collections.emptyList();
JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance(context.getProject());
PsiClassType classType = PsiTypesUtil.getClassType(psiClass);
SuggestedNameInfo info = codeStyleManager.suggestVariableName(VariableKind.LOCAL_VARIABLE, null, null, classType);
return Arrays.asList(info.names);
}
@Override
public PsiElement resolve(String o, ConvertContext context) {
DomElement parent = context.getInvocationElement().getParent();
assert parent != null;
return parent.getXmlElement();
}
}
| apache-2.0 |
sdeleuze/reactor-core | reactor-core/src/main/java/reactor/core/publisher/FluxDematerialize.java | 4510 | /*
* Copyright (c) 2011-2017 Pivotal Software Inc, All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package reactor.core.publisher;
import java.util.AbstractQueue;
import java.util.Iterator;
import java.util.concurrent.atomic.AtomicLongFieldUpdater;
import java.util.function.BooleanSupplier;
import org.reactivestreams.Subscription;
import reactor.core.CoreSubscriber;
import reactor.util.annotation.Nullable;
/**
* @author Stephane Maldini
*/
final class FluxDematerialize<T> extends FluxOperator<Signal<T>, T> {
FluxDematerialize(Flux<Signal<T>> source) {
super(source);
}
@Override
public void subscribe(CoreSubscriber<? super T> actual) {
source.subscribe(new DematerializeSubscriber<>(actual));
}
static final class DematerializeSubscriber<T> extends AbstractQueue<T>
implements InnerOperator<Signal<T>, T>,
BooleanSupplier {
final CoreSubscriber<? super T> actual;
Subscription s;
T value;
boolean done;
long produced;
volatile long requested;
@SuppressWarnings("rawtypes")
static final AtomicLongFieldUpdater<DematerializeSubscriber> REQUESTED =
AtomicLongFieldUpdater.newUpdater(DematerializeSubscriber.class,
"requested");
volatile boolean cancelled;
Throwable error;
DematerializeSubscriber(CoreSubscriber<? super T> subscriber) {
this.actual = subscriber;
}
@Override
@Nullable
public Object scanUnsafe(Attr key) {
if (key == Attr.PARENT) return s;
if (key == Attr.TERMINATED) return done;
if (key == Attr.REQUESTED_FROM_DOWNSTREAM) return requested;
if (key == Attr.ERROR) return error;
if (key == Attr.CANCELLED) return cancelled;
if (key == Attr.BUFFERED) return size();
return InnerOperator.super.scanUnsafe(key);
}
@Override
public void onSubscribe(Subscription s) {
if (Operators.validate(this.s, s)) {
this.s = s;
actual.onSubscribe(this);
s.request(1);
}
}
@Override
public void onNext(Signal<T> t) {
if (done) {
Operators.onNextDropped(t, actual.currentContext());
return;
}
if (t.isOnComplete()) {
s.cancel();
onComplete();
}
else if (t.isOnError()) {
s.cancel();
onError(t.getThrowable());
}
else if (t.isOnNext()) {
T v = value;
value = t.get();
if (v != null) {
produced++;
actual.onNext(v);
}
}
}
@Override
public void onError(Throwable t) {
if (done) {
Operators.onErrorDropped(t, actual.currentContext());
return;
}
done = true;
error = t;
long p = produced;
if (p != 0L) {
Operators.addCap(REQUESTED, this, -p);
}
DrainUtils.postCompleteDelayError(actual, this, REQUESTED, this, this, error);
}
@Override
public void onComplete() {
if (done) {
return;
}
done = true;
long p = produced;
if (p != 0L) {
Operators.addCap(REQUESTED, this, -p);
}
DrainUtils.postCompleteDelayError(actual, this, REQUESTED, this, this, error);
}
@Override
public void request(long n) {
if (Operators.validate(n)) {
if (!DrainUtils.postCompleteRequestDelayError(n,
actual,
this,
REQUESTED,
this,
this,
error)) {
s.request(n);
}
}
}
@Override
public void cancel() {
cancelled = true;
s.cancel();
}
@Override
public CoreSubscriber<? super T> actual() {
return actual;
}
@Override
public boolean getAsBoolean() {
return cancelled;
}
@Override
public int size() {
return value == null ? 0 : 1;
}
@Override
public boolean isEmpty() {
return value == null;
}
@Override
public boolean offer(T e) {
throw new UnsupportedOperationException();
}
@Override
@Nullable
public T peek() {
return value;
}
@Override
@Nullable
public T poll() {
T v = value;
if (v != null) {
value = null;
return v;
}
return null;
}
@Override
public Iterator<T> iterator() {
throw new UnsupportedOperationException();
}
}
}
| apache-2.0 |
venusdrogon/feilong-core | src/main/java/com/feilong/core/bean/PropertyUtil.java | 26170 | /*
* Copyright (C) 2008 feilong
*
* 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.feilong.core.bean;
import static com.feilong.core.Validator.isNotNullOrEmpty;
import static com.feilong.core.Validator.isNullOrEmpty;
import static com.feilong.core.util.MapUtil.newLinkedHashMap;
import java.util.Collection;
import java.util.Map;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.beanutils.PropertyUtilsBean;
import org.apache.commons.lang3.ClassUtils;
import org.apache.commons.lang3.Validate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.feilong.core.lang.ClassUtil;
import com.feilong.tools.slf4j.Slf4jUtil;
/**
* 对 {@link org.apache.commons.beanutils.PropertyUtils}的再次封装.
*
* <h3>说明:</h3>
* <blockquote>
* <ol>
* <li>目的是将原来的 checkedException 异常 转换成 {@link BeanOperationException}</li>
* </ol>
* </blockquote>
*
* <h3>{@link PropertyUtils}与 {@link BeanUtils}:</h3>
*
* <blockquote>
* <p>
* {@link PropertyUtils}类和{@link BeanUtils}类很多的方法在参数上都是相同的,但返回值不同.<br>
* {@link BeanUtils}着重于"Bean",返回值通常是{@link String},<br>
* 而{@link PropertyUtils}着重于属性,它的返回值通常是{@link Object}.
* </p>
* </blockquote>
*
* @author <a href="http://feitianbenyue.iteye.com/">feilong</a>
* @see org.apache.commons.beanutils.PropertyUtils
* @see com.feilong.core.bean.BeanUtil
* @since 1.0.0
*/
public final class PropertyUtil{
/** The Constant LOGGER. */
private static final Logger LOGGER = LoggerFactory.getLogger(PropertyUtil.class);
/**
* 传入的bean 是null 的消息提示.
*
* @since 2.1.0
*/
private static final String MESSAGE_BEAN_IS_NULL = "bean can't be null!";
/**
* 传入的propertyName 是blank 的消息提示.
*
* @since 2.1.0
*/
private static final String MESSAGE_PROPERTYNAME_IS_BLANK = "propertyName can't be blank!";
//---------------------------------------------------------------
/** Don't let anyone instantiate this class. */
private PropertyUtil(){
//AssertionError不是必须的. 但它可以避免不小心在类的内部调用构造器. 保证该类在任何情况下都不会被实例化.
//see 《Effective Java》 2nd
throw new AssertionError("No " + getClass().getName() + " instances for you!");
}
//---------------------------------------------------------------
/**
* 将 <code>fromObj</code> 中的全部或者一组属性的值,复制到 <code>toObj</code> 对象中.
*
* <h3>注意点:</h3>
*
* <blockquote>
*
* <ol>
* <li>如果 <code>toObj</code> 是null,抛出 {@link NullPointerException}</li>
* <li>如果 <code>fromObj</code> 是null,抛出 {@link NullPointerException}</li>
* <li>对于Date类型,<span style="color:red">不需要先注册converter</span></li>
* <li>这种copy都是 <span style="color:red">浅拷贝</span>,复制后的2个Bean的同一个属性可能拥有同一个对象的ref,这个在使用时要小心,特别是对于属性为自定义类的情况 .</li>
* </ol>
* </blockquote>
*
* <h3>使用示例:</h3>
*
* <blockquote>
*
* <pre class="code">
* User oldUser = new User();
* oldUser.setId(5L);
* oldUser.setMoney(new BigDecimal(500000));
* oldUser.setDate(now());
* oldUser.setNickName(ConvertUtil.toArray("feilong", "飞天奔月", "venusdrogon"));
*
* User newUser = new User();
* PropertyUtil.copyProperties(newUser, oldUser, "date", "money", "nickName");
* LOGGER.debug(JsonUtil.format(newUser));
* </pre>
*
* <b>返回:</b>
*
* <pre class="code">
* {
* "date": "2015-09-06 13:27:43",
* "id": 0,
* "nickName": [
* "feilong",
* "飞天奔月",
* "venusdrogon"
* ],
* "age": 0,
* "name": "feilong",
* "money": 500000,
* "userInfo": {"age": 0}
* }
* </pre>
*
* </blockquote>
*
* <h3>重构:</h3>
*
* <blockquote>
*
* <p>
* 对于以下代码:
* </p>
*
* <pre class="code">
*
* private ContactCommand toContactCommand(ShippingInfoSubForm shippingInfoSubForm){
* ContactCommand contactCommand = new ContactCommand();
* contactCommand.setCountryId(shippingInfoSubForm.getCountryId());
* contactCommand.setProvinceId(shippingInfoSubForm.getProvinceId());
* contactCommand.setCityId(shippingInfoSubForm.getCityId());
* contactCommand.setAreaId(shippingInfoSubForm.getAreaId());
* contactCommand.setTownId(shippingInfoSubForm.getTownId());
* return contactCommand;
* }
*
* </pre>
*
* <b>可以重构成:</b>
*
* <pre class="code">
*
* private ContactCommand toContactCommand(ShippingInfoSubForm shippingInfoSubForm){
* ContactCommand contactCommand = new ContactCommand();
* PropertyUtil.copyProperties(contactCommand, shippingInfoSubForm, "countryId", "provinceId", "cityId", "areaId", "townId");
* return contactCommand;
* }
* </pre>
*
* <p>
* 可以看出,代码更精简,目的性更明确
* </p>
*
* </blockquote>
*
* <h3>{@link BeanUtils#copyProperties(Object, Object)}与 {@link PropertyUtils#copyProperties(Object, Object)}区别</h3>
*
* <blockquote>
* <ul>
* <li>{@link BeanUtils#copyProperties(Object, Object) BeanUtils} 提供类型转换功能,即发现两个JavaBean的同名属性为不同类型时,在支持的数据类型范围内进行转换,<br>
* 而 {@link PropertyUtils#copyProperties(Object, Object) PropertyUtils}不支持这个功能,但是速度会更快一些.</li>
* <li>commons-beanutils v1.9.0以前的版本 BeanUtils不允许对象的属性值为 null,PropertyUtils可以拷贝属性值 null的对象.<br>
* (<b>注:</b>commons-beanutils v1.9.0+修复了这个情况,BeanUtilsBean.copyProperties() no longer throws a ConversionException for null properties
* of certain data types),具体参阅commons-beanutils的
* <a href="http://commons.apache.org/proper/commons-beanutils/javadocs/v1.9.2/RELEASE-NOTES.txt">RELEASE-NOTES.txt</a></li>
* </ul>
* </blockquote>
*
* <h3>相比较直接调用 {@link PropertyUtils#copyProperties(Object, Object)}的优点:</h3>
* <blockquote>
* <ol>
* <li>将 checkedException 异常转成了 {@link BeanOperationException} RuntimeException,因为通常copy的时候出现了checkedException,也是普普通通记录下log,没有更好的处理方式
* </li>
* <li>支持 includePropertyNames 参数,允许针对性copy 个别属性</li>
* <li>更多,更容易理解的的javadoc</li>
* </ol>
* </blockquote>
*
* @param toObj
* 目标对象
* @param fromObj
* 原始对象
* @param includePropertyNames
* 包含的属性数组名字数组,(can be nested/indexed/mapped/combo)<br>
* 如果是null或者empty,将会调用 {@link PropertyUtils#copyProperties(Object, Object)}<br>
* <ol>
* <li>如果没有传入<code>includePropertyNames</code>参数,那么直接调用{@link PropertyUtils#copyProperties(Object, Object)},否则循环调用
* {@link #getProperty(Object, String)}再{@link #setProperty(Object, String, Object)}到<code>toObj</code>对象中</li>
* <li>如果传入的<code>includePropertyNames</code>,含有 <code>fromObj</code>没有的属性名字,将会抛出异常</li>
* <li>如果传入的<code>includePropertyNames</code>,含有 <code>fromObj</code>有,但是 <code>toObj</code>没有的属性名字,会抛出异常,see
* {@link PropertyUtilsBean#setSimpleProperty(Object, String, Object) copyProperties} Line2078</li>
* </ol>
* @throws NullPointerException
* 如果 <code>toObj</code> 是null,或者 <code>fromObj</code> 是null
* @throws BeanOperationException
* 如果在copy的过程中,有任何的checkedException,将会被转成该异常返回
* @see #setProperty(Object, String, Object)
* @see BeanUtil#copyProperties(Object, Object, String...)
* @see org.apache.commons.beanutils.PropertyUtilsBean#copyProperties(Object, Object)
* @see <a href="http://www.cnblogs.com/kaka/archive/2013/03/06/2945514.html">Bean复制的几种框架性能比较(Apache BeanUtils、PropertyUtils,Spring
* BeanUtils,Cglib BeanCopier)</a>
* @since 1.4.1
*/
public static void copyProperties(Object toObj,Object fromObj,String...includePropertyNames){
Validate.notNull(toObj, "toObj [destination bean] not specified!");
Validate.notNull(fromObj, "fromObj [origin bean] not specified!");
//---------------------------------------------------------------
if (isNullOrEmpty(includePropertyNames)){
try{
PropertyUtils.copyProperties(toObj, fromObj);
return;
}catch (Exception e){
String pattern = "copyProperties exception,toObj:[{}],fromObj:[{}],includePropertyNames:[{}]";
throw new BeanOperationException(Slf4jUtil.format(pattern, toObj, fromObj, includePropertyNames), e);
}
}
//---------------------------------------------------------------
for (String propertyName : includePropertyNames){
Object value = getProperty(fromObj, propertyName);
setProperty(toObj, propertyName, value);
}
}
//---------------------------------------------------------------
/**
* 返回一个 <code>bean</code>中指定属性 <code>propertyNames</code><span style="color:green">可读属性</span>,并将属性名/属性值放入一个
* {@link java.util.LinkedHashMap LinkedHashMap} 中.
*
* <h3>示例:</h3>
*
* <blockquote>
*
* <p>
* <b>场景:</b> 取到user bean里面所有的属性成map
* </p>
*
* <pre class="code">
* User user = new User();
* user.setId(5L);
* user.setDate(now());
*
* LOGGER.debug(JsonUtil.format(PropertyUtil.describe(user));
* </pre>
*
* <b>返回:</b>
*
* <pre class="code">
* {
* "id": 5,
* "name": "feilong",
* "age": null,
* "date": "2016-07-13 22:18:26"
* }
* </pre>
*
* <hr>
*
* <p>
* <b>场景:</b> 提取user bean "date"和 "id"属性:
* </p>
*
* <pre class="code">
* User user = new User();
* user.setId(5L);
* user.setDate(now());
*
* LOGGER.debug(JsonUtil.format(PropertyUtil.describe(user, "date", "id"));
* </pre>
*
* 返回的结果,按照指定参数名称顺序:
*
* <pre class="code">
* {
* "date": "2016-07-13 22:21:24",
* "id": 5
* }
* </pre>
*
* </blockquote>
*
* <h3>说明:</h3>
* <blockquote>
* <ol>
* <li>另外还有一个名为class的属性,属性值是Object的类名,事实上class是java.lang.Object的一个属性</li>
* <li>如果 <code>propertyNames</code>是null或者 empty,那么获取所有属性的值</li>
* <li>map的key按照 <code>propertyNames</code> 的顺序</li>
* </ol>
* </blockquote>
*
* <h3>原理:</h3>
*
* <blockquote>
* <ol>
* <li>取到bean class的 {@link java.beans.PropertyDescriptor}数组</li>
* <li>循环,找到 {@link java.beans.PropertyDescriptor#getReadMethod()}</li>
* <li>将 name and {@link org.apache.commons.beanutils.PropertyUtilsBean#getProperty(Object, String)} 设置到map中</li>
* </ol>
* </blockquote>
*
* @param bean
* Bean whose properties are to be extracted
* @param propertyNames
* 属性名称 (can be nested/indexed/mapped/combo),参见 <a href="../BeanUtil.html#propertyName">propertyName</a>
* @return 如果 <code>propertyNames</code> 是null或者empty,返回 {@link PropertyUtils#describe(Object)}<br>
* @throws NullPointerException
* 如果 <code>bean</code> 是null,或者<code>propertyNames</code> 包含 null的元素
* @throws IllegalArgumentException
* 如果 <code>propertyNames</code> 包含 blank的元素
* @see org.apache.commons.beanutils.BeanUtils#describe(Object)
* @see org.apache.commons.beanutils.PropertyUtils#describe(Object)
* @since 1.8.0
*/
public static Map<String, Object> describe(Object bean,String...propertyNames){
Validate.notNull(bean, MESSAGE_BEAN_IS_NULL);
//---------------------------------------------------------------
if (isNullOrEmpty(propertyNames)){
try{
return PropertyUtils.describe(bean);
}catch (Exception e){
String pattern = "describe exception,bean:[{}],propertyNames:[{}]";
throw new BeanOperationException(Slf4jUtil.format(pattern, bean, propertyNames), e);
}
}
//---------------------------------------------------------------
Map<String, Object> map = newLinkedHashMap(propertyNames.length);
for (String propertyName : propertyNames){
map.put(propertyName, getProperty(bean, propertyName));
}
return map;
}
//---------------------------------------------------------------
/**
* 使用 {@link PropertyUtils#setProperty(Object, String, Object)} 来设置指定bean对象中的指定属性的值.
*
* <h3>说明:</h3>
* <blockquote>
* <ol>
* <li>不会进行类型转换</li>
* </ol>
* </blockquote>
*
* <h3>示例:</h3>
*
* <blockquote>
*
* <pre class="code">
* User newUser = new User();
* PropertyUtil.setProperty(newUser, "name", "feilong");
* LOGGER.info(JsonUtil.format(newUser));
* </pre>
*
* <b>返回:</b>
*
* <pre class="code">
* {
* "age": 0,
* "name": "feilong"
* }
* </pre>
*
* </blockquote>
*
* <h3>注意点:</h3>
*
* <blockquote>
*
* <ol>
* <li>如果 <code>bean</code> 是null,抛出 {@link NullPointerException}</li>
* <li>如果 <code>propertyName</code> 是null,抛出 {@link NullPointerException}</li>
* <li>如果 <code>propertyName</code> 是blank,抛出 {@link IllegalArgumentException}</li>
* <li>如果<code>bean</code>没有传入的 <code>propertyName</code>属性名字,会抛出异常,see
* {@link PropertyUtilsBean#setSimpleProperty(Object, String, Object) setSimpleProperty} Line2078,转成 {@link BeanOperationException}</li>
* <li>对于Date类型,<span style="color:red">不需要先注册converter</span></li>
* </ol>
* </blockquote>
*
* @param bean
* Bean whose property is to be modified
* @param propertyName
* 属性名称 (can be nested/indexed/mapped/combo),参见 <a href="../BeanUtil.html#propertyName">propertyName</a>
* @param value
* Value to which this property is to be set
* @see org.apache.commons.beanutils.BeanUtils#setProperty(Object, String, Object)
* @see org.apache.commons.beanutils.PropertyUtils#setProperty(Object, String, Object)
* @see BeanUtil#setProperty(Object, String, Object)
*/
public static void setProperty(Object bean,String propertyName,Object value){
Validate.notNull(bean, MESSAGE_BEAN_IS_NULL);
Validate.notBlank(propertyName, MESSAGE_PROPERTYNAME_IS_BLANK);
//---------------------------------------------------------------
try{
PropertyUtils.setProperty(bean, propertyName, value);
}catch (Exception e){
String pattern = "setProperty exception,bean:[{}],propertyName:[{}],value:[{}]";
throw new BeanOperationException(Slf4jUtil.format(pattern, bean, propertyName, value), e);
}
}
//---------------------------------------------------------------
/**
* 如果 <code>value</code> isNotNullOrEmpty,那么才调用 {@link #setProperty(Object, String, Object)}.
*
* <h3>注意点:</h3>
*
* <blockquote>
* <ol>
* <li>如果 <code>bean</code> 是null,抛出 {@link NullPointerException}</li>
* <li>如果 <code>propertyName</code> 是null,抛出 {@link NullPointerException}</li>
* <li>如果 <code>propertyName</code> 是blank,抛出 {@link IllegalArgumentException}</li>
* <li>如果<code>bean</code>没有传入的 <code>propertyName</code>属性名字,会抛出异常,see
* {@link PropertyUtilsBean#setSimpleProperty(Object, String, Object)} Line2078</li>
* <li>对于Date类型,<span style="color:red">不需要先注册converter</span></li>
* </ol>
* </blockquote>
*
* @param bean
* Bean whose property is to be modified
* @param propertyName
* 属性名称 (can be nested/indexed/mapped/combo),参见 <a href="../BeanUtil.html#propertyName">propertyName</a>
* @param value
* Value to which this property is to be set
* @since 1.5.3
*/
public static void setPropertyIfValueNotNullOrEmpty(Object bean,String propertyName,Object value){
if (isNotNullOrEmpty(value)){
setProperty(bean, propertyName, value);
}
}
/**
* 如果 <code>null != value</code>,那么才调用 {@link #setProperty(Object, String, Object)}.
*
* <h3>注意点:</h3>
*
* <blockquote>
*
* <ol>
* <li>如果 <code>bean</code> 是null,抛出 {@link NullPointerException}</li>
* <li>如果 <code>propertyName</code> 是null,抛出 {@link NullPointerException}</li>
* <li>如果 <code>propertyName</code> 是blank,抛出 {@link IllegalArgumentException}</li>
* <li>如果<code>bean</code>没有传入的 <code>propertyName</code>属性名字,会抛出异常,see
* {@link PropertyUtilsBean#setSimpleProperty(Object, String, Object)} Line2078</li>
* <li>对于Date类型,<span style="color:red">不需要先注册converter</span></li>
* </ol>
* </blockquote>
*
* @param bean
* Bean whose property is to be modified
* @param propertyName
* 属性名称 (can be nested/indexed/mapped/combo),参见 <a href="../BeanUtil.html#propertyName">propertyName</a>
* @param value
* Value to which this property is to be set
* @see #setProperty(Object, String, Object)
* @since 1.5.3
*/
public static void setPropertyIfValueNotNull(Object bean,String propertyName,Object value){
if (null != value){
setProperty(bean, propertyName, value);
}
}
//---------------------------------------------------------------
// [start] getProperty
/**
* 使用 {@link PropertyUtils#getProperty(Object, String)} 从指定bean对象中取得指定属性名称的值.
*
* <h3>说明:</h3>
* <blockquote>
* <ol>
* <li>原样取出值,不会进行类型转换.</li>
* </ol>
* </blockquote>
*
* <h3>示例:</h3>
* <blockquote>
* <p>
* <b>场景:</b> 取list中第一个元素的id
* </p>
*
* <pre class="code">
* User user = new User();
* user.setId(5L);
* user.setDate(now());
*
* List{@code <User>} list = toList(user, user, user);
*
* Long id = PropertyUtil.getProperty(list, "[0].id");
* </pre>
*
* <b>返回:</b>
*
* <pre class="code">
* 5
* </pre>
*
* </blockquote>
*
* @param <T>
* the generic type
* @param bean
* Bean whose property is to be extracted
* @param propertyName
* 属性名称 (can be nested/indexed/mapped/combo),参见 <a href="../BeanUtil.html#propertyName">propertyName</a>
* @return 如果 <code>bean</code> 是null,抛出 {@link NullPointerException}<br>
* 如果 <code>propertyName</code> 是null,抛出 {@link NullPointerException}<br>
* 如果 <code>propertyName</code> 是blank,抛出 {@link IllegalArgumentException}<br>
* 否则 使用{@link PropertyUtils#getProperty(Object, String)} 从对象中取得属性值
* @see BeanUtil#getProperty(Object, String)
* @see org.apache.commons.beanutils.BeanUtils#getProperty(Object, String)
* @see org.apache.commons.beanutils.PropertyUtils#getProperty(Object, String)
* @see org.apache.commons.beanutils.PropertyUtilsBean
*/
public static <T> T getProperty(Object bean,String propertyName){
Validate.notNull(bean, MESSAGE_BEAN_IS_NULL);
Validate.notBlank(propertyName, MESSAGE_PROPERTYNAME_IS_BLANK);
return PropertyValueObtainer.obtain(bean, propertyName);
}
//---------------------------------------------------------------
// [end]
/**
* 从指定的 <code>obj</code>中,查找指定类型 <code>toBeFindedClassType</code> 的值.
*
* <h3>说明:</h3>
*
* <blockquote>
* <ol>
* <li>如果 <code>ClassUtil.isInstance(obj, toBeFindedClassType)</code> 直接返回 findValue</li>
* <li>不支持obj是<code>isPrimitiveOrWrapper</code>,<code>CharSequence</code>,<code>Collection</code>,<code>Map</code>类型,自动过滤</li>
* <li>调用 {@link PropertyUtil#describe(Object, String...)} 再递归查找</li>
* <li>目前暂不支持从集合里面找到指定类型的值,如果你有相关需求,可以调用 "org.springframework.util.CollectionUtils#findValueOfType(Collection, Class)"</li>
* </ol>
* </blockquote>
*
* <h3>示例:</h3>
* <blockquote>
*
* <p>
* <b>场景:</b> 从User中找到UserInfo类型的值
* </p>
*
* <pre class="code">
* User user = new User();
* user.setId(5L);
* user.setDate(now());
* user.getUserInfo().setAge(28);
*
* LOGGER.info(JsonUtil.format(PropertyUtil.findValueOfType(user, UserInfo.class)));
* </pre>
*
* <b>返回:</b>
*
* <pre class="code">
* {"age": 28}
* </pre>
*
* </blockquote>
*
* @param <T>
* the generic type
* @param obj
* 要被查找的对象
* @param toBeFindedClassType
* the to be finded class type
* @return 如果 <code>obj</code> 是null或者是empty,返回null<br>
* 如果 <code>toBeFindedClassType</code> 是null,抛出 {@link NullPointerException}<br>
* 如果 <code>ClassUtil.isInstance(obj, toBeFindedClassType)</code>,直接返回 <code>obj</code><br>
* 从对象中查找匹配的类型,如果找不到返回 <code>null</code><br>
* @see "org.springframework.util.CollectionUtils#findValueOfType(Collection, Class)"
* @since 1.4.1
*/
@SuppressWarnings("unchecked")
public static <T> T findValueOfType(Object obj,Class<T> toBeFindedClassType){
if (isNullOrEmpty(obj)){
return null;
}
Validate.notNull(toBeFindedClassType, "toBeFindedClassType can't be null/empty!");
//---------------------------------------------------------------
if (ClassUtil.isInstance(obj, toBeFindedClassType)){
return (T) obj;
}
//---------------------------------------------------------------
if (isDonotSupportFindType(obj)){
LOGGER.trace("obj:[{}] not support find toBeFindedClassType:[{}]", obj.getClass().getName(), toBeFindedClassType.getName());
return null;
}
//---------------------------------------------------------------
Map<String, Object> describe = describe(obj);
for (Map.Entry<String, Object> entry : describe.entrySet()){
String key = entry.getKey();
Object value = entry.getValue();
if (null != value && !"class".equals(key)){
//级联查询
T t = findValueOfType(value, toBeFindedClassType);
if (null != t){
return t;
}
}
}
return null;
}
//---------------------------------------------------------------
/**
* 一般自定义的command 里面 就是些 string int,list map等对象.
*
* <p>
* 这些我们过滤掉,只取类型是 findedClassType的
* </p>
*
* @param obj
* the obj
* @return true, if checks if is can find type
* @since 1.6.3
*/
private static boolean isDonotSupportFindType(Object obj){
//一般自定义的command 里面 就是些 string int,list map等对象
//这些我们过滤掉,只取类型是 findedClassType的
return ClassUtils.isPrimitiveOrWrapper(obj.getClass())//
|| ClassUtil.isInstanceAnyClass(obj, CharSequence.class, Collection.class, Map.class);
}
} | apache-2.0 |
vivantech/kc_fixes | src/main/java/org/kuali/kra/award/budget/document/authorizer/PostAwardBudgetAuthorizer.java | 3160 | /*
* Copyright 2005-2014 The Kuali Foundation
*
* Licensed under the Educational Community 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.osedu.org/licenses/ECL-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.kuali.kra.award.budget.document.authorizer;
import org.kuali.kra.authorization.Task;
import org.kuali.kra.award.budget.document.AwardBudgetDocument;
import org.kuali.kra.award.budget.document.authorization.AwardBudgetTask;
import org.kuali.kra.award.document.AwardDocument;
import org.kuali.kra.budget.document.authorizer.BudgetAuthorizer;
import org.kuali.kra.infrastructure.AwardPermissionConstants;
import org.kuali.kra.infrastructure.Constants;
import org.kuali.kra.infrastructure.KeyConstants;
import org.kuali.rice.coreservice.framework.CoreFrameworkServiceLocator;
import org.kuali.rice.coreservice.framework.parameter.ParameterService;
import org.kuali.rice.kew.api.WorkflowDocument;
/**
* The AwardBudget Modify Authorizer checks to see if the user has
* the necessary permission to modify a specific budget.
*
* @author Kuali Research Administration Team (kualidev@oncourse.iu.edu)
*/
public class PostAwardBudgetAuthorizer extends BudgetAuthorizer {
private static final String POST_ENABLED_PARAM_VALUE_1 = "1";
public boolean isAuthorized(String userId, Task task) {
AwardBudgetTask budgetTask = (AwardBudgetTask) task;
AwardBudgetDocument budgetDocument = budgetTask.getAwardBudgetDocument();
AwardDocument doc = (AwardDocument) budgetDocument.getParentDocument();
WorkflowDocument workflowDoc = getWorkflowDocument(budgetDocument);
return workflowDoc.isFinal() && isAwardBudgetToBePosted(budgetDocument) && canPost() &&
hasUnitPermission(userId, doc.getLeadUnitNumber(), Constants.MODULE_NAMESPACE_AWARD_BUDGET,
AwardPermissionConstants.POST_AWARD_BUDGET.getAwardPermission());
}
private boolean canPost() {
String postEnabled = getParameterService().getParameterValueAsString(AwardBudgetDocument.class, KeyConstants.AWARD_BUDGET_POST_ENABLED);
return postEnabled.equals(POST_ENABLED_PARAM_VALUE_1);
}
private boolean isAwardBudgetToBePosted(AwardBudgetDocument budgetDocument) {
String toBePostedStatusCode = getParameterService().getParameterValueAsString(AwardBudgetDocument.class, KeyConstants.AWARD_BUDGET_STATUS_TO_BE_POSTED);
return budgetDocument.getAwardBudget().getAwardBudgetStatusCode().equals(toBePostedStatusCode);
}
/**
* Gets the parameterService attribute.
* @return Returns the parameterService.
*/
public ParameterService getParameterService() {
return CoreFrameworkServiceLocator.getParameterService();
}
}
| apache-2.0 |
kisueht/KHTUI | source/src/com/kisueht/view/roundlist/RoundListAdapter.java | 1080 | package com.kisueht.view.roundlist;
import android.view.View;
public abstract class RoundListAdapter {
/**
*
* @param sectionNo
*/
public void didItemSectionClickEvent(int sectionNo){};
/**
*
* @param sectionNo
* @param rowNo
*/
public void didItemRowClickEvent(int sectionNo, int rowNo){};
/**
*
* @return
*/
public abstract int getSectionCount();
/**
*
* @param sectionNo
* @return
*/
public abstract int getSectionHeight(int sectionNo);
/**
*
* @param sectionNo
* @return
*/
public abstract String getSectionTitle(int sectionNo);
/**
*
* @param sectionNo
* @return
*/
public abstract int getSectionTitleSize(int sectionNo);
/**
*
* @param sectionNo
* @return
*/
public abstract View getSectionView(int sectionNo);
/**
*
* @return
*/
public abstract int getRowCount(int sectionNo);
/**
*
* @param rowNo
* @return
*/
public abstract int getRowHeight(int sectionNo, int rowNo);
/**
*
* @param rowNo
* @return
*/
public abstract View getRowView(int sectionNo, int rowNo);
}
| apache-2.0 |
pupnewfster/Lavasurvival | lavasurvival/src/main/java/me/eddiep/minecraft/ls/game/items/impl/Generosity.java | 2807 | package me.eddiep.minecraft.ls.game.items.impl;
import com.crossge.necessities.Necessities;
import me.eddiep.minecraft.ls.Lavasurvival;
import me.eddiep.minecraft.ls.game.Gamemode;
import me.eddiep.minecraft.ls.game.items.LavaItem;
import me.eddiep.minecraft.ls.ranks.UserInfo;
import net.minecraft.server.v1_12_R1.NBTTagCompound;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.craftbukkit.v1_12_R1.inventory.CraftItemStack;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
public class Generosity extends LavaItem {
@Override
public boolean consume(Player owner) {
UserInfo info = Lavasurvival.INSTANCE.getUserManager().getUser(owner.getUniqueId());
if (info.wasGenerous()) {
owner.sendMessage("" + ChatColor.BOLD + ChatColor.RED + "You can only use this item once per round !");
return false;
}
Gamemode gamemode = Gamemode.getCurrentGame();
if (gamemode.isEndGame()) {
owner.sendMessage("" + ChatColor.BOLD + ChatColor.RED + "You can't use this item during end-game !");
return false;
}
info.usedGenerosity();
double bal = Necessities.getEconomy().getBalance(owner.getUniqueId());
double cost = Math.round(bal * 0.07);
double bonus = Math.round(bal * 0.05);
Lavasurvival.INSTANCE.withdrawAndUpdate(owner, cost);
gamemode.addToBonus(bonus);
owner.sendMessage("" + ChatColor.ITALIC + ChatColor.RED + cost + "ggs were taken out of your balance!");
Lavasurvival.globalMessage(ChatColor.GREEN + "+ " + ChatColor.RESET + ChatColor.BOLD + owner.getDisplayName() + ChatColor.RESET + " used the Generosity item to add " + ChatColor.BOLD + bonus + ChatColor.RESET + " to the RoundBonus!");
return true;
}
@SuppressWarnings("ConstantConditions")
@Override
protected ItemStack displayItem() {
net.minecraft.server.v1_12_R1.ItemStack nmsStack = CraftItemStack.asNMSCopy(new ItemStack(Material.POTION));
NBTTagCompound tag = null;
if (!nmsStack.hasTag()) {
tag = new NBTTagCompound();
nmsStack.setTag(tag);
}
if (tag == null)
tag = nmsStack.getTag();
tag.setInt("HideFlags", 63);
tag.setString("Potion", "minecraft:leaping");
nmsStack.setTag(tag);
return CraftItemStack.asCraftMirror(nmsStack);
}
@Override
public String name() {
return "Generosity";
}
@Override
public String description() {
return "Take 7% of your total money and add\n5% of it to the current Round Bonus!";
}
@Override
public int getPrice() {
return 500;
}
} | apache-2.0 |
Mishiranu/Dashchan | src/com/mishiranu/dashchan/ui/DialogMenu.java | 10952 | package com.mishiranu.dashchan.ui;
import android.app.AlertDialog;
import android.content.Context;
import android.content.res.ColorStateList;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.core.view.ViewCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.mishiranu.dashchan.C;
import com.mishiranu.dashchan.graphics.BaseDrawable;
import com.mishiranu.dashchan.util.ConcurrentUtils;
import com.mishiranu.dashchan.util.ListViewUtils;
import com.mishiranu.dashchan.util.ResourceUtils;
import com.mishiranu.dashchan.util.ViewUtils;
import com.mishiranu.dashchan.widget.DividerItemDecoration;
import com.mishiranu.dashchan.widget.PaddedRecyclerView;
import com.mishiranu.dashchan.widget.ThemeEngine;
import java.util.ArrayList;
import java.util.List;
public class DialogMenu {
private final Context context;
private final ArrayList<ListItem> listItems = new ArrayList<>();
private CharSequence title;
private enum ViewType {ITEM, MORE, CHECK}
private static class ListItem {
public final ViewType viewType;
public final String title;
public final boolean checked;
public final Runnable runnable;
public ListItem(ViewType viewType, String title, boolean checked, Runnable runnable) {
this.viewType = viewType;
this.title = title;
this.checked = checked;
this.runnable = runnable;
}
}
public DialogMenu(Context context) {
this.context = context;
}
public DialogMenu setTitle(CharSequence title) {
this.title = title;
return this;
}
private DialogMenu add(ViewType viewType, String title, boolean checked, Runnable callback) {
listItems.add(new ListItem(viewType, title, checked, callback));
return this;
}
public DialogMenu add(int titleRes, Runnable runnable) {
return add(ViewType.ITEM, context.getString(titleRes), false, runnable);
}
public DialogMenu add(String title, Runnable runnable) {
return add(ViewType.ITEM, title, false, runnable);
}
public DialogMenu addMore(int titleRes, Runnable runnable) {
return add(ViewType.MORE, context.getString(titleRes), false, runnable);
}
public DialogMenu addCheck(int titleRes, boolean checked, Runnable runnable) {
return add(ViewType.CHECK, context.getString(titleRes), checked, runnable);
}
private RecyclerView getRecyclerView(AlertDialog dialog) {
FrameLayout custom = dialog.findViewById(android.R.id.custom);
return (RecyclerView) custom.getChildAt(0);
}
private void setAdapter(AlertDialog dialog, RecyclerView recyclerView) {
recyclerView.setAdapter(new Adapter(dialog.getContext(), dialog::dismiss, new ArrayList<>(listItems)));
}
private void updateInternal(AlertDialog dialog, RecyclerView recyclerView) {
dialog.setTitle(title);
if (dialog.isShowing()) {
setAdapter(dialog, recyclerView != null ? recyclerView : getRecyclerView(dialog));
} else if (recyclerView != null) {
dialog.setOnShowListener(ViewUtils.ALERT_DIALOG_LONGER_TITLE);
setAdapter(dialog, recyclerView);
} else {
dialog.setOnShowListener(d -> {
ViewUtils.ALERT_DIALOG_LONGER_TITLE.onShow(d);
setAdapter(dialog, getRecyclerView(dialog));
});
}
}
public void update(AlertDialog dialog) {
updateInternal(dialog, null);
}
public AlertDialog create() {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
RecyclerView recyclerView = new PaddedRecyclerView(builder.getContext());
recyclerView.setMotionEventSplittingEnabled(false);
recyclerView.setVerticalScrollBarEnabled(true);
recyclerView.setLayoutManager(new LinearLayoutManager(recyclerView.getContext()));
if (C.API_LOLLIPOP) {
float density = ResourceUtils.obtainDensity(recyclerView);
recyclerView.setClipToPadding(false);
recyclerView.setPadding(0, (int) (8f * density), 0, (int) (8f * density));
} else {
recyclerView.addItemDecoration(new DividerItemDecoration(recyclerView.getContext(),
(c, position) -> c.need(true)));
}
AlertDialog dialog = builder.setView(recyclerView).create();
updateInternal(dialog, recyclerView);
return dialog;
}
private static class Adapter extends RecyclerView.Adapter<ViewHolder>
implements ListViewUtils.ClickCallback<ListItem, ViewHolder> {
private final Runnable dismiss;
private final int layoutResId;
private final List<ListItem> listItems;
public Adapter(Context context, Runnable dismiss, List<ListItem> listItems) {
this.dismiss = dismiss;
layoutResId = ResourceUtils.obtainAlertDialogLayoutResId(context, ResourceUtils.DialogLayout.SIMPLE);
this.listItems = listItems;
}
@Override
public int getItemViewType(int position) {
return listItems.get(position).viewType.ordinal();
}
@Override
public int getItemCount() {
return listItems.size();
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
ViewHolder holder = new ViewHolder(parent, layoutResId, ViewType.values()[viewType]);
ListViewUtils.bind(holder, false, listItems::get, this);
return holder;
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
ListItem listItem = listItems.get(position);
holder.textView.setText(listItem.title);
if (holder.checkBox != null) {
holder.checkBox.setChecked(listItem.checked);
}
}
@Override
public boolean onItemClick(ViewHolder holder, int position, ListItem listItem, boolean longClick) {
dismiss.run();
ConcurrentUtils.HANDLER.post(listItem.runnable);
return true;
}
}
private static class ViewHolder extends RecyclerView.ViewHolder {
public final TextView textView;
public final CheckBox checkBox;
public ViewHolder(ViewGroup parent, int layoutResId, ViewType viewType) {
super(viewType != ViewType.ITEM ? new LinearLayout(parent.getContext())
: LayoutInflater.from(parent.getContext()).inflate(layoutResId, parent, false));
if (viewType != ViewType.ITEM) {
LinearLayout linearLayout = (LinearLayout) itemView;
linearLayout.setLayoutParams(new RecyclerView.LayoutParams(RecyclerView.LayoutParams.MATCH_PARENT,
RecyclerView.LayoutParams.WRAP_CONTENT));
linearLayout.setOrientation(LinearLayout.HORIZONTAL);
linearLayout.setGravity(Gravity.CENTER_VERTICAL);
View view = LayoutInflater.from(parent.getContext()).inflate(layoutResId, linearLayout, false);
linearLayout.addView(view, new LinearLayout.LayoutParams(0,
LinearLayout.LayoutParams.WRAP_CONTENT, 1f));
float density = ResourceUtils.obtainDensity(view);
// Align to checkbox inner padding
int padding = ViewCompat.getPaddingEnd(view) - (int) (2f * density);
ViewCompat.setPaddingRelative(view, ViewCompat.getPaddingStart(view),
view.getPaddingTop(), 0, view.getPaddingBottom());
int contentSize = (int) (24f * density);
FrameLayout contentLayout = new FrameLayout(parent.getContext());
linearLayout.addView(contentLayout, padding + contentSize + padding,
LinearLayout.LayoutParams.MATCH_PARENT);
if (viewType == ViewType.MORE) {
Drawable drawable = null;
if (C.API_NOUGAT) {
int[] attrs = {android.R.attr.subMenuArrow};
TypedArray typedArray = parent.getContext().obtainStyledAttributes(null,
attrs, android.R.attr.listMenuViewStyle, 0);
try {
drawable = typedArray.getDrawable(0);
} finally {
typedArray.recycle();
}
}
if (drawable == null) {
drawable = new SubMenuArrowDrawable(parent);
}
ImageView imageView = new ImageView(parent.getContext());
imageView.setScaleType(ImageView.ScaleType.CENTER);
imageView.setImageDrawable(drawable);
contentLayout.addView(imageView, FrameLayout.LayoutParams.WRAP_CONTENT,
FrameLayout.LayoutParams.WRAP_CONTENT);
((FrameLayout.LayoutParams) imageView.getLayoutParams()).gravity = Gravity.CENTER;
}
if (viewType == ViewType.CHECK) {
checkBox = new CheckBox(parent.getContext());
ThemeEngine.applyStyle(checkBox);
checkBox.setClickable(false);
checkBox.setFocusable(false);
contentLayout.addView(checkBox, LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
((FrameLayout.LayoutParams) checkBox.getLayoutParams()).gravity = Gravity.CENTER;
} else {
checkBox = null;
}
} else {
checkBox = null;
}
textView = itemView.findViewById(android.R.id.text1);
ViewUtils.setSelectableItemBackground(itemView);
}
}
private static class SubMenuArrowDrawable extends BaseDrawable {
private static final int SIZE_DP = 24;
private final Paint paint = new Paint();
private final Path path = new Path();
private final ColorStateList color;
private final boolean rtl;
private final int size;
public SubMenuArrowDrawable(View view) {
float density = ResourceUtils.obtainDensity(view);
color = ResourceUtils.getColorStateList(view.getContext(), android.R.attr.textColorSecondary);
rtl = ViewCompat.getLayoutDirection(view) == ViewCompat.LAYOUT_DIRECTION_RTL;
size = (int) (SIZE_DP * density);
}
@Override
public int getIntrinsicWidth() {
return size;
}
@Override
public int getIntrinsicHeight() {
return size;
}
@Override
public void setBounds(int left, int top, int right, int bottom) {
super.setBounds(left, top, right, bottom);
int size = Math.min(right - left, bottom - top);
float scale = (float) size / SIZE_DP;
path.rewind();
if (rtl) {
path.moveTo(14 * scale, 7 * scale);
path.rLineTo(-5 * scale, 5 * scale);
path.rLineTo(5 * scale, 5 * scale);
} else {
path.moveTo(10 * scale, 7 * scale);
path.rLineTo(5 * scale, 5 * scale);
path.rLineTo(-5 * scale, 5 * scale);
}
path.close();
}
@Override
public boolean isStateful() {
return true;
}
@Override
protected boolean onStateChange(int[] state) {
invalidateSelf();
return true;
}
@Override
public void draw(@NonNull Canvas canvas) {
canvas.save();
int left;
int top;
Rect bounds = getBounds();
int width = bounds.width();
int height = bounds.height();
if (width > height) {
left = bounds.left + (width - height) / 2;
top = bounds.top;
} else {
left = bounds.left;
top = bounds.top + (height - width) / 2;
}
canvas.translate(left, top);
paint.setColor(color.getColorForState(getState(), color.getDefaultColor()));
canvas.drawPath(path, paint);
canvas.restore();
}
}
}
| apache-2.0 |
thompsct/VPRKB | src/semsimKB/model/physical/CustomPhysicalEntity.java | 516 | package semsimKB.model.physical;
import semsimKB.definitions.SemSimTypes;
public class CustomPhysicalEntity extends PhysicalModelComponent implements PhysicalEntity{
public CustomPhysicalEntity(String name, String description){
super(SemSimTypes.CUSTOM_PHYSICAL_ENTITY);
setName(name);
setDescription(description);
}
public String getFullName() {
return getName();
}
@Override
protected boolean isEquivalent(Object obj) {
return ((CustomPhysicalEntity)obj).getName().equals(getName());
}
}
| apache-2.0 |
VibyJocke/gocd | config/config-api/src/com/thoughtworks/go/config/PartialsProvider.java | 196 | package com.thoughtworks.go.config;
import com.thoughtworks.go.config.remote.PartialConfig;
import java.util.List;
public interface PartialsProvider {
List<PartialConfig> lastPartials();
}
| apache-2.0 |
arrahtec/osdq-desktop | src/main/java/org/arrah/gui/swing/OrdinalPanel.java | 9242 | package org.arrah.gui.swing;
/***********************************************
* Copyright to Arrah Technology 2016 *
* *
* Any part of code or file can be changed, *
* redistributed, modified with the copyright *
* information intact *
* *
* Author$ : Vivek Singh *
* *
***********************************************/
/* This file is uses to create
* ordinal panel in data prepatation so that
* strings can be mapped to number for analysis
*
*/
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFormattedTextField;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.SpringLayout;
import javax.swing.border.Border;
import javax.swing.border.EtchedBorder;
import org.arrah.framework.util.DiscreetRange;
public class OrdinalPanel implements ActionListener, ItemListener {
private ReportTable _rt;
private int _rowC = 0;
private int _colIndex = 0;
private JDialog d_f;
private JFormattedTextField jrn_low, jrn_high;
private JComboBox<String> colSel;
private Border line_b;
private int beginIndex, endIndex;
private JLabel colType;
private JPanel cps;
private Vector<JTextField> grpName_v;
private ArrayList<Object> key;
private boolean onehot = false;
public OrdinalPanel(ReportTable rt, int colIndex,int ordinaltype) {
if (ordinaltype == 1) onehot = true;
_rt = rt;
_colIndex = colIndex;
_rowC = rt.table.getRowCount();
createDialog();
}; // Constructor
private void createDialog() {
JPanel jp = new JPanel(new BorderLayout());
line_b = BorderFactory.createEtchedBorder(EtchedBorder.RAISED);
jp.add(createSelectionPanel(),BorderLayout.NORTH);
if (cps == null) {
cps = new JPanel();
cps.setPreferredSize(new Dimension(475,325));
}
JScrollPane jscrollpane1 = new JScrollPane(cps);
jscrollpane1.setPreferredSize(new Dimension(500, 300));
jp.add(jscrollpane1,BorderLayout.CENTER);
JPanel bp = new JPanel();
JButton ok = new JButton("OK");
ok.addKeyListener(new KeyBoardListener());
ok.setActionCommand("ok");
ok.addActionListener(this);
bp.add(ok);
JButton can = new JButton("Cancel");
can.addKeyListener(new KeyBoardListener());
can.setActionCommand("cancel");
can.addActionListener(this);
bp.add(can);
JPanel bottom = new JPanel(new GridLayout(2,1));
bottom.add(createRowNumPanel());bottom.add(bp);
jp.add(bottom,BorderLayout.SOUTH);
d_f = new JDialog();
d_f.setModal(true);
d_f.setTitle("Ordinal Panel Dialog");
d_f.setLocation(300, 250);
d_f.setPreferredSize(new Dimension(625,415));
d_f.getContentPane().add(jp);
d_f.pack();
d_f.setVisible(true);
}
private JPanel createRowNumPanel() {
JPanel rownnumjp = new JPanel(new FlowLayout(FlowLayout.LEADING));
JLabel lrange = new JLabel(" Row Numbers to Populate : From (Inclusive)", JLabel.LEADING);
jrn_low = new JFormattedTextField();
jrn_low.setValue(new Long(1));
jrn_low.setColumns(8);
JLabel torange = new JLabel(" To(Exclusive):", JLabel.LEADING);
jrn_high = new JFormattedTextField();
jrn_high.setValue(new Long(_rowC+1));
jrn_high.setColumns(8);
rownnumjp.add(lrange);
rownnumjp.add(jrn_low);
rownnumjp.add(torange);
rownnumjp.add(jrn_high);
rownnumjp.setBorder(line_b);
return rownnumjp;
}
private JPanel createSelectionPanel() {
JPanel selectionjp = new JPanel(new FlowLayout(FlowLayout.LEADING));
JLabel selL = new JLabel("Choose Column to Apply Function on: ");
int colC = _rt.getModel().getColumnCount();
String[] colName = new String[colC+2]; // prompt to select column
colName[0] = "Select Column";
colName[1] = "--------------";
for (int i = 0; i < colC; i++)
colName[i+2] = _rt.getModel().getColumnName(i);
selectionjp.add(selL);
colSel = new JComboBox<String>(colName);
colSel.addItemListener(this);
selectionjp.add(colSel);
colType=new JLabel(" ");
selectionjp.add(colType);
return selectionjp;
}
public void actionPerformed(ActionEvent e) {
String action = e.getActionCommand();
if (action.equals("cancel")) {
d_f.dispose();
return;
}
if (action.equals("ok")) {
// d_f.dispose(); do not dispose now
if (_rt.isSorting() || _rt.table.isEditing()) {
JOptionPane.showMessageDialog(null, "Table is in Sorting or Editing State");
return;
}
beginIndex = ((Long) jrn_low.getValue()).intValue();
endIndex = ((Long) jrn_high.getValue()).intValue();
if (beginIndex <= 0 || beginIndex > _rowC)
beginIndex = 1;
if (endIndex <= 0 || endIndex > (_rowC + 1))
endIndex = _rowC +1;
int numGenerate = endIndex - beginIndex;
if ( numGenerate <= 0 || numGenerate > _rowC) {
numGenerate = _rowC; // default behavior for Invalid number
beginIndex = 1;endIndex = _rowC+1;
}
try {
d_f.setCursor(java.awt.Cursor.getPredefinedCursor(java.awt.Cursor.WAIT_CURSOR));
int selColIndex = colSel.getSelectedIndex(); // Take value from col on which grouping will be done
if (selColIndex < 2 ) {
JOptionPane.showMessageDialog(null, "Select the column to make ordinal");
return;
} else selColIndex = selColIndex -2;
for (int i = (beginIndex -1) ; i < ( endIndex -1 ); i++) {
Object colObject = _rt.getModel().getValueAt(i, selColIndex);
if (colObject == null) continue;
int index = key.indexOf(colObject);
if (index < 0) continue;
String grpString= grpName_v.get(index).getText();
_rt.getModel().setValueAt(grpString, i, _colIndex);
}
d_f.dispose(); // in case it is not disposed yet if all the filed null condition
return;
} finally {
d_f.setCursor(java.awt.Cursor.getPredefinedCursor(java.awt.Cursor.DEFAULT_CURSOR));
}
} // Ok action
} // End of actionPerformed
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED ) {
if (e.getSource() == colSel) {
int index = colSel.getSelectedIndex();
if (index < 2 ) { colType.setText(" "); return ; }
else index = index -2; // first two are for selection
colType.setText(" "+_rt.getModel().getColumnClass(index).getName());
try {
d_f.setCursor(java.awt.Cursor.getPredefinedCursor(java.awt.Cursor.WAIT_CURSOR));
addOrdinalRow(index);
} catch (Exception exp) {
ConsoleFrame.addText("\n Exception:" + exp.getLocalizedMessage());
return;
} finally {
d_f.setCursor(java.awt.Cursor.getPredefinedCursor(java.awt.Cursor.DEFAULT_CURSOR));
}
}
}
} // End of ItemStateChange
/* This function will be used to add row to ordinal grouping feature */
private void addOrdinalRow(int colIndex) {
if (cps == null)
cps = new JPanel();
cps.setPreferredSize(new Dimension(475,325));
grpName_v = new Vector<JTextField> ();
// remove all then rebuilt
cps.removeAll();
Vector<Object> vc = _rt.getRTMModel().getColDataV(colIndex);
Hashtable<Object,Integer> ordinalData= DiscreetRange.getUnique(vc);
int carSize = ordinalData.size();
key = new ArrayList<Object>();
if (carSize > 10000)
ConsoleFrame.addText("\n Warning: Cardinality very high, may not render:"+ carSize);
for (Enumeration <Object> keyEnum = ordinalData.keys(); keyEnum.hasMoreElements();)
key.add( keyEnum.nextElement().toString());
key.sort(null);
// for one hot key
Hashtable<Object,String> ht = null;
if (onehot == true)
ht= DiscreetRange.getOneHotEncoding(null,ordinalData);
for (int i=0; i < carSize; i++ ) {
JLabel ordinalName = new JLabel(" Nominal String:"+key.get(i).toString());
JLabel ordinalCount = new JLabel(" Repeat Count:"+ ordinalData.get(key.get(i)).toString());
JTextField ordgrp = new JTextField(15);
// for one hot key
if (onehot == true)
ordgrp.setText(""+ht.get(key.get(i)));
else
ordgrp.setText(""+i);
ordgrp.setToolTipText("Enter Ordinal value");
grpName_v.add(i,ordgrp);
/* Add value to Panel */
cps.add(ordinalName);
cps.add(ordinalCount);
cps.add(ordgrp);
}
cps.setLayout(new SpringLayout());
if (carSize > 10 ) // till ten it is default value
cps.setPreferredSize(new Dimension(475,carSize*30));
SpringUtilities.makeCompactGrid(cps, carSize, 3, 3, 3, 3, 3);
cps.revalidate();
}
}
| apache-2.0 |
PavelLazarchik/lpv_rep | sandbox/src/test/java/ru/stqa/pft/sandbox/PointTest.java | 905 | package ru.stqa.pft.sandbox;
//Создать тестовый класс
//Создать тестовый метод вида public void внутри класса, который будет проверять совпадение фактического и ожидаемого результатов
//Использовать для этого метод assertEquals класса Assert
//для проведения расчетов создать объект через конструктор и задать координаты точек А и Б
//задать аннотацию Test
import org.testng.Assert;
import org.testng.annotations.Test;
@Test
public class PointTest {
public void testDistanceBetweenPoints(){
Point pointA = new Point(4,6);
Point pointB = new Point(8,12);
Assert.assertEquals(Point.distanceBetweenDots(pointA,pointB),7.211102550927978);
}
}
| apache-2.0 |
oehme/analysing-gradle-performance | my-app/src/test/java/org/gradle/test/performance/mediummonolithicjavaproject/p289/Test5799.java | 2174 | package org.gradle.test.performance.mediummonolithicjavaproject.p289;
import org.junit.Test;
import static org.junit.Assert.*;
public class Test5799 {
Production5799 objectUnderTest = new Production5799();
@Test
public void testProperty0() {
Production5796 value = new Production5796();
objectUnderTest.setProperty0(value);
assertEquals(value, objectUnderTest.getProperty0());
}
@Test
public void testProperty1() {
Production5797 value = new Production5797();
objectUnderTest.setProperty1(value);
assertEquals(value, objectUnderTest.getProperty1());
}
@Test
public void testProperty2() {
Production5798 value = new Production5798();
objectUnderTest.setProperty2(value);
assertEquals(value, objectUnderTest.getProperty2());
}
@Test
public void testProperty3() {
String value = "value";
objectUnderTest.setProperty3(value);
assertEquals(value, objectUnderTest.getProperty3());
}
@Test
public void testProperty4() {
String value = "value";
objectUnderTest.setProperty4(value);
assertEquals(value, objectUnderTest.getProperty4());
}
@Test
public void testProperty5() {
String value = "value";
objectUnderTest.setProperty5(value);
assertEquals(value, objectUnderTest.getProperty5());
}
@Test
public void testProperty6() {
String value = "value";
objectUnderTest.setProperty6(value);
assertEquals(value, objectUnderTest.getProperty6());
}
@Test
public void testProperty7() {
String value = "value";
objectUnderTest.setProperty7(value);
assertEquals(value, objectUnderTest.getProperty7());
}
@Test
public void testProperty8() {
String value = "value";
objectUnderTest.setProperty8(value);
assertEquals(value, objectUnderTest.getProperty8());
}
@Test
public void testProperty9() {
String value = "value";
objectUnderTest.setProperty9(value);
assertEquals(value, objectUnderTest.getProperty9());
}
} | apache-2.0 |
smilezhoujl/smileweather | app/src/main/java/cn/com/smileweather/MainActivity.java | 853 | package cn.com.smileweather;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
/**
* GitHub : https://github.com/smilezhoujl/smileweather.git
* weather api_key : aacd0e37ac5e41e9a431f0e819a44306
**/
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
if (prefs.getString("weather", null) != null) {
Intent intent = new Intent(this, WeatherActivity.class);
startActivity(intent);
finish();
}
}
}
| apache-2.0 |
quarkusio/quarkus | extensions/vertx-http/deployment/src/main/java/io/quarkus/vertx/http/deployment/webjar/InMemoryTargetVisitor.java | 584 | package io.quarkus.vertx.http.deployment.webjar;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
/**
* Visitor which holds all web jar resources in memory.
*/
public class InMemoryTargetVisitor implements WebJarResourcesTargetVisitor {
private Map<String, byte[]> content = new HashMap<>();
public Map<String, byte[]> getContent() {
return content;
}
@Override
public void visitFile(String path, InputStream stream) throws IOException {
content.put(path, stream.readAllBytes());
}
} | apache-2.0 |
oehme/analysing-gradle-performance | commons/src/test/java/org/gradle/test/performance/mediummonolithicjavaproject/p0/Test12.java | 2150 | package org.gradle.test.performance.mediummonolithicjavaproject.p0;
import org.junit.Test;
import static org.junit.Assert.*;
public class Test12 {
Production12 objectUnderTest = new Production12();
@Test
public void testProperty0() {
Production3 value = new Production3();
objectUnderTest.setProperty0(value);
assertEquals(value, objectUnderTest.getProperty0());
}
@Test
public void testProperty1() {
Production7 value = new Production7();
objectUnderTest.setProperty1(value);
assertEquals(value, objectUnderTest.getProperty1());
}
@Test
public void testProperty2() {
Production11 value = new Production11();
objectUnderTest.setProperty2(value);
assertEquals(value, objectUnderTest.getProperty2());
}
@Test
public void testProperty3() {
String value = "value";
objectUnderTest.setProperty3(value);
assertEquals(value, objectUnderTest.getProperty3());
}
@Test
public void testProperty4() {
String value = "value";
objectUnderTest.setProperty4(value);
assertEquals(value, objectUnderTest.getProperty4());
}
@Test
public void testProperty5() {
String value = "value";
objectUnderTest.setProperty5(value);
assertEquals(value, objectUnderTest.getProperty5());
}
@Test
public void testProperty6() {
String value = "value";
objectUnderTest.setProperty6(value);
assertEquals(value, objectUnderTest.getProperty6());
}
@Test
public void testProperty7() {
String value = "value";
objectUnderTest.setProperty7(value);
assertEquals(value, objectUnderTest.getProperty7());
}
@Test
public void testProperty8() {
String value = "value";
objectUnderTest.setProperty8(value);
assertEquals(value, objectUnderTest.getProperty8());
}
@Test
public void testProperty9() {
String value = "value";
objectUnderTest.setProperty9(value);
assertEquals(value, objectUnderTest.getProperty9());
}
} | apache-2.0 |
jexp/idea2 | java/java-tests/testSrc/com/intellij/refactoring/convertToInstanceMethod/ConvertToInstanceMethodTest.java | 1644 | package com.intellij.refactoring.convertToInstanceMethod;
import com.intellij.codeInsight.TargetElementUtilBase;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiMethod;
import com.intellij.testFramework.LightCodeInsightTestCase;
import com.intellij.JavaTestUtil;
/**
* @author dsl
*/
public class ConvertToInstanceMethodTest extends LightCodeInsightTestCase {
@Override
protected String getTestDataPath() {
return JavaTestUtil.getJavaTestDataPath();
}
public void testSimple() throws Exception { doTest(0); }
public void testInterface() throws Exception { doTest(1); }
public void testInterfacePrivate() throws Exception { doTest(1); }
public void testInterface2() throws Exception { doTest(0); }
public void testInterface3() throws Exception { doTest(0); }
public void testTypeParameter() throws Exception { doTest(0); }
public void testInterfaceTypeParameter() throws Exception { doTest(0); }
private void doTest(final int targetParameter) throws Exception {
final String filePath = "/refactoring/convertToInstanceMethod/" + getTestName(false) + ".java";
configureByFile(filePath);
final PsiElement targetElement = TargetElementUtilBase.findTargetElement(getEditor(), TargetElementUtilBase.ELEMENT_NAME_ACCEPTED);
assertTrue("<caret> is not on method name", targetElement instanceof PsiMethod);
PsiMethod method = (PsiMethod) targetElement;
new ConvertToInstanceMethodProcessor(getProject(),
method, method.getParameterList().getParameters()[targetParameter], null).run();
checkResultByFile(filePath + ".after");
}
}
| apache-2.0 |
adrienfb/dejavu-stringmetrics | src/test/java/ch/ethz/student/dejavu/strings/HammingMetricTest.java | 5810 | /*
* Copyright 2013 Adrien Favre-Bully, Florian Froese, Adrian Schmidmeister
* 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 ch.ethz.student.dejavu.strings;
import org.junit.Assert;
import org.junit.Test;
import java.util.Random;
import ch.ethz.student.dejavu.AbstractDistanceAndSimilarityMetricTest;
import ch.ethz.student.dejavu.DistanceMetric;
import ch.ethz.student.dejavu.SimilarityMetric;
import ch.ethz.student.dejavu.TestUtils;
import ch.ethz.student.dejavu.utilities.Utilities;
public class HammingMetricTest extends AbstractDistanceAndSimilarityMetricTest {
private static final Random rnd = new Random();
private static final HammingMetric metric = HammingMetric.getInstance();
private static final TestInput[] testInput = {
new TestInput("Hello world!", "Hello mamma!", 5, 0.5833),
new TestInput("Hello world!", "Hello mamma?", 6, 0.5),
new TestInput("Hello world!", "Hello world?", 1, 0.9167),
};
@Override
protected TestInput[] getTestInput() {
return testInput;
}
@Override
protected DistanceMetric getDistanceMetric() {
return metric;
}
@Override
protected SimilarityMetric getSimilarityMetric() {
return metric;
}
// ===== Equal Length Constraints =====
public void testEqualLenghtConstraints() {
try {
getDistanceMetric().computeDistance("some length", "other length");
Assert.fail();
} catch (IllegalArgumentException e) {
// success
}
}
@Override
@Test
public void testDistanceEmptyArguments() {
double dist = getDistanceMetric().computeDistance("", "");
Assert.assertEquals(Utilities.DISTANCE_EMPTY_EMPTY, dist, TestUtils.DELTA);
}
@Override
@Test
public void testSimilarityEmptyArguments() {
double dist = getSimilarityMetric().computeSimilarity("", "");
Assert.assertEquals(Utilities.SIMILARITY_EMPTY_EMPTY, dist, TestUtils.DELTA);
}
@Override
@Test
public void testDistanceCommutativity() {
// run test on manually specified test input
for (TestInput ti : getTestInput()) {
double dist1 = getDistanceMetric().computeDistance(ti.s1, ti.s2);
double dist2 = getDistanceMetric().computeDistance(ti.s2, ti.s1);
Assert.assertEquals("Commutativity Test failed on strings " + ti.s1 + " and " + ti.s2, dist1, dist2, TestUtils.DELTA);
}
// run test on randomly generated strings
for (int i = 0; i < TestUtils.N; i++) {
int length = rnd.nextInt(TestUtils.MAX_LEN+1-TestUtils.MIN_LEN) + TestUtils.MIN_LEN;
String s1 = TestUtils.getRandomString(length);
String s2 = TestUtils.getRandomString(length);
double dist1 = getDistanceMetric().computeDistance(s1, s2);
double dist2 = getDistanceMetric().computeDistance(s2, s1);
Assert.assertEquals(dist1, dist2, TestUtils.DELTA);
}
}
@Override
@Test
public void testSimilarityCommutativity() {
// run test on manually specified test input
for (TestInput ti : getTestInput()) {
double dist1 = getDistanceMetric().computeDistance(ti.s1, ti.s2);
double dist2 = getDistanceMetric().computeDistance(ti.s2, ti.s1);
Assert.assertEquals("Commutativity Test failed on strings " + ti.s1 + " and " + ti.s2, dist1, dist2, TestUtils.DELTA);
}
// run test on randomly generated strings
for (int i = 0; i < TestUtils.N; i++) {
int length = rnd.nextInt(TestUtils.MAX_LEN+1-TestUtils.MIN_LEN) + TestUtils.MIN_LEN;
String s1 = TestUtils.getRandomString(length);
String s2 = TestUtils.getRandomString(length);
double dist1 = getDistanceMetric().computeDistance(s1, s2);
double dist2 = getDistanceMetric().computeDistance(s2, s1);
Assert.assertEquals(dist1, dist2, TestUtils.DELTA);
}
}
@Override
public void testSimilarityBounds() {
for (int i = 0; i < TestUtils.N; i++) {
int length = rnd.nextInt(TestUtils.MAX_LEN+1-TestUtils.MIN_LEN) + TestUtils.MIN_LEN;
String s1 = TestUtils.getRandomString(length);
String s2 = TestUtils.getRandomString(length);
double s = getSimilarityMetric().computeSimilarity(s1, s2);
Assert.assertTrue(
"Similarity s=" + s + " not in bounds [0,1] for input s1='" + s1 + "' and s2='" + s2
+ "'", s >= 0 && s <= 1);
}
}
@Override
public void testDistanceRobustness() {
for (int i = 0; i < TestUtils.N; i++) {
int length = rnd.nextInt(TestUtils.MAX_LEN+1-TestUtils.MIN_LEN) + TestUtils.MIN_LEN;
String s1 = TestUtils.getRandomString(length);
String s2 = TestUtils.getRandomString(length);
try {
getDistanceMetric().computeDistance(s1, s2);
} catch (Exception e) {
Assert.fail("Excpection is thrown for input s1='" + s1 + "' and s2='" + s2 + "'");
}
}
}
@Override
public void testSimilarityRobustness() {
for (int i = 0; i < TestUtils.N; i++) {
int length = rnd.nextInt(TestUtils.MAX_LEN+1-TestUtils.MIN_LEN) + TestUtils.MIN_LEN;
String s1 = TestUtils.getRandomString(length);
String s2 = TestUtils.getRandomString(length);
try {
getDistanceMetric().computeDistance(s1, s2);
} catch (Exception e) {
Assert.fail("Excpection is thrown for input s1='" + s1 + "' and s2='" + s2 + "'");
}
}
}
}
| apache-2.0 |
lisaglendenning/zookeeper-lite | zkserver/src/main/java/edu/uw/zookeeper/server/SessionParametersPolicy.java | 349 | package edu.uw.zookeeper.server;
import edu.uw.zookeeper.common.TimeValue;
public interface SessionParametersPolicy {
byte[] newPassword(long seed);
boolean validatePassword(long seed, byte[] password);
TimeValue boundTimeout(TimeValue timeOut);
long newSessionId();
TimeValue maxTimeout();
TimeValue minTimeout();
}
| apache-2.0 |
mp911de/spring-vault | spring-vault-core/src/test/java/org/springframework/vault/annotation/VaultPropertySourceMultipleIntegrationTests.java | 2691 | /*
* 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.vault.annotation;
import java.util.Collections;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.core.env.Environment;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.vault.core.VaultIntegrationTestConfiguration;
import org.springframework.vault.core.VaultOperations;
import org.springframework.vault.util.VaultExtension;
import org.springframework.vault.util.VaultInitializer;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Integration test for {@link VaultPropertySource} using multiple annotations.
*
* @author Mark Paluch
*/
@ExtendWith(SpringExtension.class)
@ExtendWith(VaultExtension.class)
@ContextConfiguration
class VaultPropertySourceMultipleIntegrationTests {
@VaultPropertySource(value = "secret/myapp/profile", propertyNamePrefix = "database.")
@VaultPropertySource("secret/myapp")
static class Config extends VaultIntegrationTestConfiguration {
}
@Autowired
Environment env;
@Autowired
ApplicationContext context;
@Value("${myapp}")
String myapp;
@BeforeAll
static void beforeClass(VaultInitializer initializer) {
VaultOperations vaultOperations = initializer.prepare().getVaultOperations();
vaultOperations.write("secret/myapp",
Collections.singletonMap("myapp", "myvalue"));
vaultOperations.write("secret/myapp/profile",
Collections.singletonMap("myprofile", "myprofilevalue"));
}
@Test
void environmentShouldResolveProperties() {
assertThat(env.getProperty("myapp")).isEqualTo("myvalue");
assertThat(env.getProperty("database.myprofile")).isEqualTo("myprofilevalue");
}
@Test
void valueShouldInjectProperty() {
assertThat(myapp).isEqualTo("myvalue");
}
}
| apache-2.0 |
KarloKnezevic/Ferko | src/java/hr/fer/zemris/jcms/web/actions/data/ConfPreloadScoreEditData.java | 700 | package hr.fer.zemris.jcms.web.actions.data;
import hr.fer.zemris.jcms.web.actions.data.support.IMessageLogger;
import java.util.List;
/**
* Podatkovna struktura za akciju {@link AdminAssessmentEdit}.
*
* @author marcupic
*
*/
public class ConfPreloadScoreEditData extends BaseAssessment {
private List<String> availableLetters;
/**
* Konstruktor.
* @param messageLogger lokalizirane poruke
*/
public ConfPreloadScoreEditData(IMessageLogger messageLogger) {
super(messageLogger);
}
public List<String> getAvailableLetters() {
return availableLetters;
}
public void setAvailableLetters(List<String> availableLetters) {
this.availableLetters = availableLetters;
}
}
| apache-2.0 |
consulo/consulo-unity3d | plugin/src/main/java/consulo/unity3d/module/Unity3dModuleExtension.java | 866 | /*
* Copyright 2013-2016 consulo.io
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package consulo.unity3d.module;
import consulo.dotnet.module.extension.DotNetSimpleModuleExtension;
/**
* @author VISTALL
* @since 29.03.2015
*/
public interface Unity3dModuleExtension<T extends Unity3dModuleExtension<T>> extends DotNetSimpleModuleExtension<T>
{
}
| apache-2.0 |
gilesjb/copalis.sql | src/test/java/org/copalis/sql/common/NameTest.java | 1048 | /*
* Copyright 2011 Giles Burgess
*
* 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.copalis.sql.common;
import java.io.IOException;
import junit.framework.TestCase;
/**
* @author gilesjb
*
*/
public class NameTest extends TestCase {
public interface Iface {
void a() throws IOException;
}
public void testMethodName() throws SecurityException, NoSuchMethodException {
assertEquals("org.copalis.sql.common.NameTest$Iface.a()", Name.of(Iface.class.getMethod("a")));
}
}
| apache-2.0 |
rwitzel/streamflyer | streamflyer-core/src/main/java/com/github/rwitzel/streamflyer/internal/thirdparty/ZzzValidate.java | 5419 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.rwitzel.streamflyer.internal.thirdparty;
import java.util.Collection;
/**
* The code of this class is copied from <code>org.apache.commons.lang.Validate</code>
* in order to avoid additional dependencies to other projects.
* <p>
* The name is prefixed with <code>Zzz</code> to avoid confusion in case the
* original classes are also available in classpath.
*/
/**
* <p>
* This class assists in validating arguments.
* </p>
* <p>
* The class is based along the lines of JUnit. If an argument value is deemed invalid, an IllegalArgumentException is
* thrown. For example:
* </p>
*
* <pre>
* Validate.isTrue(i > 0, "The value must be greater than zero: ", i);
* Validate.notNull(surname, "The surname must not be null");
* </pre>
*
* @author Apache Software Foundation
* @author <a href="mailto:ola.berg@arkitema.se">Ola Berg</a>
* @author Gary Gregory
* @author Norm Deane
* @since 2.0
* @version $Id: Validate.java 905636 2010-02-02 14:03:32Z niallp $
*/
public class ZzzValidate {
// Validate has no dependencies on other classes in Commons Lang at present
/**
* Constructor. This class should not normally be instantiated.
*/
public ZzzValidate() {
super();
}
// notNull
// ---------------------------------------------------------------------------------
/**
* <p>
* Validate that the specified argument is not <code>null</code>; otherwise throwing an exception.
*
* <pre>
* Validate.notNull(myObject);
* </pre>
* <p>
* The message of the exception is "The validated object is null".
* </p>
*
* @param object
* the object to check
* @throws IllegalArgumentException
* if the object is <code>null</code>
*/
public static void notNull(Object object) {
notNull(object, "The validated object is null");
}
/**
* <p>
* Validate that the specified argument is not <code>null</code>; otherwise throwing an exception with the specified
* message.
*
* <pre>
* Validate.notNull(myObject, "The object must not be null");
* </pre>
*
* @param object
* the object to check
* @param message
* the exception message if invalid
*/
public static void notNull(Object object, String message) {
if (object == null) {
throw new IllegalArgumentException(message);
}
}
/**
* <p>
* Validate that the argument condition is <code>true</code>; otherwise throwing an exception with the specified
* message. This method is useful when validating according to an arbitrary boolean expression, such as validating a
* primitive number or using your own custom validation expression.
* </p>
*
* <pre>
* Validate.isTrue((i > 0), "The value must be greater than zero");
* Validate.isTrue(myObject.isOk(), "The object is not OK");
* </pre>
*
* @param expression
* the boolean expression to check
* @param message
* the exception message if invalid
* @throws IllegalArgumentException
* if expression is <code>false</code>
*/
public static void isTrue(boolean expression, String message) {
if (expression == false) {
throw new IllegalArgumentException(message);
}
}
/**
* Validates that the given collection is not empty.
*
* @param collection
* @param collectionName
*/
public static void isNotEmpty(Collection<?> collection, String collectionName) {
notNull(collection, collectionName + " must not be null");
isTrue(!collection.isEmpty(), collectionName + " must not be empty");
}
//
// extensions of the third-party code (not part of the third-party code)
//
public static void isZeroOrPositiveNumber(double number, String variableName) {
if (number < 0) {
throw new IllegalArgumentException(variableName + " must be a zero or a positive number but was " + number);
}
}
public static void isGreaterThanZero(double number, String variableName) {
if (number <= 0) {
throw new IllegalArgumentException(variableName + " must be greather than zero but was " + number);
}
}
}
| apache-2.0 |
fidesmo/free-otp | app/src/main/java/org/fedorahosted/freeotp/MainActivity.java | 4302 | /*
* FreeOTP
*
* Authors: Nathaniel McCallum <npmccallum@redhat.com>
*
* Copyright (C) 2013 Nathaniel McCallum, Red Hat
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Portions Copyright 2009 ZXing 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.fedorahosted.freeotp;
import java.io.IOException;
import org.fedorahosted.freeotp.add.ScanActivity;
import org.fedorahosted.freeotp.add.AddActivity;
import org.fedorahosted.freeotp.add.BaseActivity;
import org.fedorahosted.freeotp.edit.DeleteActivity;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.WindowManager.LayoutParams;
import android.widget.Toast;
public abstract class MainActivity extends Activity implements OnMenuItemClickListener {
public static final int DELETE_REQUEST_CODE = 1;
public static final int SCAN_REQUEST_CODE = 2;
public static final int ADD_REQUEST_CODE = 3;
public static final int EDIT_REQUEST_CODE = 4;
protected abstract void deleteToken(int position);
protected abstract void addToken(String tokenUri);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Don't permit screenshots since these might contain OTP codes.
getWindow().setFlags(LayoutParams.FLAG_SECURE, LayoutParams.FLAG_SECURE);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
menu.findItem(R.id.action_scan).setVisible(ScanActivity.haveCamera());
menu.findItem(R.id.action_scan).setOnMenuItemClickListener(this);
menu.findItem(R.id.action_add).setOnMenuItemClickListener(this);
menu.findItem(R.id.action_about).setOnMenuItemClickListener(this);
return true;
}
@Override
public boolean onMenuItemClick(MenuItem item) {
Intent i;
switch (item.getItemId()) {
case R.id.action_scan:
i = new Intent(this, ScanActivity.class);
startActivityForResult(i, SCAN_REQUEST_CODE);
overridePendingTransition(R.anim.fadein, R.anim.fadeout);
return true;
case R.id.action_add:
startActivityForResult(new Intent(this, AddActivity.class), ADD_REQUEST_CODE);
return true;
case R.id.action_about:
startActivity(new Intent(this, AboutActivity.class));
return true;
}
return false;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(resultCode == RESULT_OK) {
switch(requestCode) {
case DELETE_REQUEST_CODE:
int position = data.getIntExtra(DeleteActivity.EXTRA_POSITION, -1);
deleteToken(position);
break;
case ADD_REQUEST_CODE:
case SCAN_REQUEST_CODE:
String tokenUri = data.getStringExtra(BaseActivity.EXTRA_TOKEN_URI);
addToken(tokenUri);
break;
}
}
}
}
| apache-2.0 |
zarub2k/moviedroid | app/src/main/java/com/cloudskol/moviedroid/details/MovieDetailsAsyncTask.java | 1613 | package com.cloudskol.moviedroid.details;
import android.net.Uri;
import android.os.AsyncTask;
import android.util.Log;
import com.cloudskol.moviedroid.common.MoviedroidException;
import com.cloudskol.moviedroid.common.MoviedroidUrlConnector;
import com.cloudskol.moviedroid.model.Movie;
import com.cloudskol.moviedroid.list.MovieJsonParser;
/**
* @author tham
*
* Async task handler for fetching the movie details from the movie API
*/
public class MovieDetailsAsyncTask extends AsyncTask<Uri, Void, Movie> {
private static final String LOG_TAG = MovieDetailsAsyncTask.class.getSimpleName();
private DetailFragment detailFragment_;
public MovieDetailsAsyncTask(DetailFragment detailFragment) {
detailFragment_ = detailFragment;
}
@Override
protected Movie doInBackground(Uri... uris) {
if (uris.length <= 0) {
return null;
}
String movieDetailsJsonString;
final Uri movieDetailsUri = uris[0];
final MoviedroidUrlConnector moviedroidUrlConnector = new MoviedroidUrlConnector();
try {
movieDetailsJsonString = moviedroidUrlConnector.getJson(movieDetailsUri);
} catch (MoviedroidException e) {
Log.e(LOG_TAG, "Error while fetching movie details", e);
return null;
}
Log.v(LOG_TAG, movieDetailsJsonString);
return MovieJsonParser.getInstance().getMovie(movieDetailsJsonString);
}
@Override
protected void onPostExecute(Movie movie) {
super.onPostExecute(movie);
detailFragment_.onMovieDataReceived(movie);
}
}
| apache-2.0 |
apereo/cas | support/cas-server-support-aup-mongo/src/main/java/org/apereo/cas/config/CasAcceptableUsagePolicyMongoDbConfiguration.java | 3767 | package org.apereo.cas.config;
import org.apereo.cas.aup.AcceptableUsagePolicyRepository;
import org.apereo.cas.aup.MongoDbAcceptableUsagePolicyRepository;
import org.apereo.cas.authentication.CasSSLContext;
import org.apereo.cas.configuration.CasConfigurationProperties;
import org.apereo.cas.configuration.support.CasFeatureModule;
import org.apereo.cas.mongo.MongoDbConnectionFactory;
import org.apereo.cas.ticket.registry.TicketRegistrySupport;
import org.apereo.cas.util.spring.beans.BeanSupplier;
import org.apereo.cas.util.spring.boot.ConditionalOnFeature;
import lombok.val;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.data.mongodb.core.MongoOperations;
/**
* This is {@link CasAcceptableUsagePolicyMongoDbConfiguration} that stores AUP decisions in a mongo database.
*
* @author Misagh Moayyed
* @since 5.2.0
*/
@EnableConfigurationProperties(CasConfigurationProperties.class)
@Configuration(value = "CasAcceptableUsagePolicyMongoDbConfiguration", proxyBeanMethods = false)
@ConditionalOnFeature(feature = CasFeatureModule.FeatureCatalog.AcceptableUsagePolicy, module = "mongo")
public class CasAcceptableUsagePolicyMongoDbConfiguration {
@RefreshScope(proxyMode = ScopedProxyMode.DEFAULT)
@Bean
@ConditionalOnMissingBean(name = "mongoAcceptableUsagePolicyTemplate")
public MongoOperations mongoAcceptableUsagePolicyTemplate(
final ConfigurableApplicationContext applicationContext,
final CasConfigurationProperties casProperties,
@Qualifier(CasSSLContext.BEAN_NAME)
final CasSSLContext casSslContext) throws Exception {
return BeanSupplier.of(MongoOperations.class)
.when(AcceptableUsagePolicyRepository.CONDITION_AUP_ENABLED.given(applicationContext.getEnvironment()))
.supply(() -> {
val mongo = casProperties.getAcceptableUsagePolicy().getMongo();
val factory = new MongoDbConnectionFactory(casSslContext.getSslContext());
val mongoTemplate = factory.buildMongoTemplate(mongo);
MongoDbConnectionFactory.createCollection(mongoTemplate, mongo.getCollection(), mongo.isDropCollection());
return mongoTemplate;
})
.otherwiseProxy()
.get();
}
@RefreshScope(proxyMode = ScopedProxyMode.DEFAULT)
@Bean
public AcceptableUsagePolicyRepository acceptableUsagePolicyRepository(
final ConfigurableApplicationContext applicationContext,
final CasConfigurationProperties casProperties,
@Qualifier("mongoAcceptableUsagePolicyTemplate")
final MongoOperations mongoAcceptableUsagePolicyTemplate,
@Qualifier(TicketRegistrySupport.BEAN_NAME)
final TicketRegistrySupport ticketRegistrySupport) throws Exception {
return BeanSupplier.of(AcceptableUsagePolicyRepository.class)
.when(AcceptableUsagePolicyRepository.CONDITION_AUP_ENABLED.given(applicationContext.getEnvironment()))
.supply(() -> new MongoDbAcceptableUsagePolicyRepository(ticketRegistrySupport,
casProperties.getAcceptableUsagePolicy(), mongoAcceptableUsagePolicyTemplate))
.otherwise(AcceptableUsagePolicyRepository::noOp)
.get();
}
}
| apache-2.0 |
myshzzx/mlib | core/src/main/java/mysh/sql/sqlite/SqliteDB.java | 17095 | package mysh.sql.sqlite;
import com.alibaba.fastjson.JSON;
import com.google.common.base.Joiner;
import lombok.Getter;
import mysh.collect.Colls;
import mysh.os.Oss;
import mysh.sql.PooledDataSource;
import mysh.util.*;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.sqlite.SQLiteConfig;
import org.sqlite.SQLiteDataSource;
import javax.annotation.Nullable;
import java.io.Closeable;
import java.nio.file.Path;
import java.sql.Connection;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.stream.Collectors;
/**
* @since 2019-07-08
*/
public class SqliteDB implements Closeable {
private static final Logger log = LoggerFactory.getLogger(SqliteDB.class);
private static final Serializer SERIALIZER = Serializer.BUILD_IN;
private final PooledDataSource ds;
private final Path dbFile;
@Getter
private final NamedParameterJdbcTemplate jdbcTemplate;
private final Set<String> existTables = Collections.newSetFromMap(new ConcurrentHashMap<>());
@Getter
public static class Item<V> {
private String key;
private LocalDateTime writeTime, readTime;
private V value;
public V getValue() {
return value;
}
}
public interface DAO {
String getTableName();
boolean tableExists();
JdbcTemplate getJdbcTemplate();
int update(String namedSql, Map<String, ?> params);
int insertOrReplace(Map<String, Object> tableColValues);
List<Map<String, Object>> byRawSql(
@Nullable String cols, @Nullable String conditions, @Nullable String clauses, @Nullable Map<String, ?> params);
}
public interface KvDAO<V> extends DAO {
boolean containsKey(String key);
V byKey(String key);
V byKey(String key, V defaultValue);
List<Item<V>> itemsByRawSql(
@Nullable String cols, @Nullable String conditions, @Nullable String clauses, @Nullable Map<String, ?> params);
Item<V> itemByKey(String key, boolean queryValue, boolean queryTime);
Item<V> timeByKey(String key);
default Item<V> itemByKey(String key) {
return itemByKey(key, true, true);
}
List<Item<V>> items();
V byKeyRemoveOnWriteExpired(String key, LocalDateTime validAfter);
void removeReadExpired(LocalDateTime validAfter);
void remove(String key);
int save(String key, V value);
int save(String key, V value, @Nullable LocalDateTime writeTime);
boolean exists(String key);
}
public interface KvConfigDAO<V> extends KvDAO<String> {
/**
* read old value and convert it to new value by doing some biz,
* guarded by key.intern() locking.
*
* @return new value
*/
V readAndWrite(String key, Function<V, V> biz);
/**
* read old value and convert it to new value by doing some biz,
* guarded by key.intern() locking.
*
* @return new value
*/
V readAndWrite(String key, Function<V, V> biz, @Nullable LocalDateTime writeTime);
V configByKey(String key);
V configByKey(String key, V defaultConfig);
List<Item<V>> configsByRawSql(
@Nullable String cols, @Nullable String conditions, @Nullable String clauses, @Nullable Map<String, ?> params);
int saveConfig(String key, V value);
int saveConfig(String key, V value, @Nullable LocalDateTime writeTime);
}
public SqliteDB(Path file) {
this(file, false, 0);
}
/**
* @see #newSqliteConfig
*/
public SqliteDB(Path file, boolean useLock, int mmapSize) {
this(file, newSqliteConfig(useLock ? SQLiteConfig.LockingMode.EXCLUSIVE : SQLiteConfig.LockingMode.NORMAL,
mmapSize, SQLiteConfig.SynchronousMode.NORMAL, SQLiteConfig.JournalMode.OFF));
}
/**
* @see #newSqliteConfig
*/
public SqliteDB(Path file, SQLiteConfig config) {
if (!file.toFile().getParentFile().exists())
file.toFile().getParentFile().mkdirs();
dbFile = file;
log.debug("init-sqliteDB, file={}, config={}", file, config.toProperties());
GenericObjectPoolConfig<Connection> poolConfig = new GenericObjectPoolConfig<>();
poolConfig.setMinIdle(1);
poolConfig.setMaxTotal(5);
poolConfig.setMaxWaitMillis(1000);
poolConfig.setTimeBetweenEvictionRunsMillis(600_000);
if (Oss.isAndroid())
poolConfig.setJmxEnabled(false);
SQLiteDataSource sqliteDs = new SQLiteDataSource(config);
sqliteDs.setUrl("jdbc:sqlite:" + file);
ds = new PooledDataSource(poolConfig, sqliteDs);
jdbcTemplate = new NamedParameterJdbcTemplate(ds);
}
/**
* PRAGMA 配置: <a href='https://www.runoob.com/sqlite/sqlite-pragma.html'>pragma 说明</a>
* <p>
* locking: default NORMAL. use lock to gain 10 times speed up IO performance,
* but lock will prevent db file from being accessed by other processes.
* see <a href='https://www.sqlite.org/pragma.html#pragma_locking_mode'>locking_mode</a>
* <p>
* mmap_size: Memory-Mapped file size(byte), 0 to disable. usually 268435456 or more.
* see <a href='https://cloud.tencent.com/developer/section/1420023'>Memory-Mapped I/O</a'>
* <p>
* synchronous: 0 | OFF | 1 | NORMAL | 2 | FULL | 3 | EXTRA
* <a href='https://www.sqlite.org/pragma.html#pragma_synchronous'>official</a>
* <p>
* journal: DELETE | TRUNCATE | PERSIST | MEMORY | WAL | OFF
* <a href='https://www.cnblogs.com/cchust/p/4754619.html'>日志模式</a>,
* <a href='https://www.sqlite.org/pragma.html#pragma_journal_mode'>official</a>
* <p>
*/
public static SQLiteConfig newSqliteConfig(SQLiteConfig.LockingMode lockingMode, int mmapSize,
SQLiteConfig.SynchronousMode synchronousMode, SQLiteConfig.JournalMode journalMode) {
SQLiteConfig config = new SQLiteConfig();
if (lockingMode != null)
config.setLockingMode(lockingMode);
if (mmapSize > 0)
config.setPragma(SQLiteConfig.Pragma.MMAP_SIZE, String.valueOf(mmapSize));
if (synchronousMode != null)
config.setSynchronous(synchronousMode);
if (journalMode != null)
config.setJournalMode(journalMode);
return config;
}
@Override
public void close() {
try {
log.debug("closing-sqlite-DS: {}", dbFile);
ds.close();
} catch (Exception e) {
log.error("close-sqlite-DS-fail", e);
}
}
private class DAOImpl<V> implements KvDAO<V> {
final String table;
final boolean suggestCompressValue;
final boolean updateReadTime;
/**
* {@link DAO} implementation
*
* @param table snake_case_group
*/
DAOImpl(String table) {
this.table = table;
this.suggestCompressValue = false;
this.updateReadTime = false;
}
/**
* {@link KvDAO} implementation
*
* @param table snake_case_group
* @param suggestCompressValue value may be zip compress before save, depends on reducing size or not
* @param updateReadTime update rt on each read
*/
DAOImpl(String table, boolean suggestCompressValue, boolean updateReadTime) {
this.table = table;
this.suggestCompressValue = suggestCompressValue;
this.updateReadTime = updateReadTime;
this.ensureKvTable();
}
public boolean tableExists() {
if (existTables.contains(table))
return true;
Integer tableCount = jdbcTemplate.queryForObject(
"select count(1) from sqlite_master where type='table' and tbl_name=:name",
Colls.ofHashMap("name", table), Integer.class
);
if (tableCount != null && tableCount > 0) {
existTables.add(table);
return true;
} else
return false;
}
@Override
public JdbcTemplate getJdbcTemplate() {
return jdbcTemplate.getJdbcTemplate();
}
private void ensureKvTable() {
if (!tableExists()) {
synchronized (table.intern()) {
if (tableExists())
return;
String sql = "create table " + table +
"(\n" +
"k text not null constraint " + table + "_pk primary key,\n" +
"v blob,\n" +
"wt text default (datetime(CURRENT_TIMESTAMP,'localtime')),\n" +
"rt text default (datetime(CURRENT_TIMESTAMP,'localtime'))\n" +
")";
jdbcTemplate.update(sql, Collections.emptyMap());
existTables.add(table);
}
}
}
@Override
public String getTableName() {
return this.table;
}
@Override
public int update(final String namedSql, final Map<String, ?> params) {
return jdbcTemplate.update(namedSql, params);
}
@Override
public int insertOrReplace(Map<String, Object> tableColValues) {
Set<String> cols = tableColValues.keySet();
Joiner cj = Joiner.on(",");
Joiner vj = Joiner.on(",:");
return jdbcTemplate.update(
"insert or replace into " + table
+ "(" + cj.join(cols) + ") values(:" + vj.join(cols) + ")",
tableColValues
);
}
@Override
public List<Map<String, Object>> byRawSql(String cols, String conditions, String clauses, Map<String, ?> params) {
String sql = "select " + ObjectUtils.firstNonNull(cols, "*") + " from " + table
+ (conditions != null ? (" where " + conditions + " ") : " ")
+ ObjectUtils.firstNonNull(clauses, "");
params = params == null ? Collections.emptyMap() : params;
Tick tick = Tick.tick();
List<Map<String, Object>> lst = jdbcTemplate.queryForList(sql, params);
if (tick.nip() > 30) {
log.warn("sql-need-optimize,cost={}ms, sql={}, params={}", tick.lastNip(), sql, params);
}
return lst;
}
@Override
public boolean containsKey(String key) {
Integer count = jdbcTemplate.queryForObject(
"select count(1) from " + table + " where k=:key",
Colls.ofHashMap("key", key), Integer.class);
return count > 0;
}
@Override
public V byKey(String key) {
return byKey(key, null);
}
@Override
public V byKey(String key, V defaultValue) {
Item<V> item = itemByKey(key, true, false);
return item == null ? defaultValue : item.getValue();
}
@Override
public Item<V> timeByKey(String key) {
return itemByKey(key, false, true);
}
@Override
public List<Item<V>> items() {
return itemsByRawSql(null, null, null, null);
}
@Override
public List<Item<V>> itemsByRawSql(String cols, String conditions, String clauses, Map<String, ?> params) {
List<Map<String, Object>> lst = this.byRawSql(cols, conditions, clauses, params);
List<Item<V>> items = new ArrayList<>();
for (Map<String, Object> mi : lst) {
Item<V> item = new Item<>();
item.key = (String) mi.get("k");
this.assembleItem(mi, item, true, true);
items.add(item);
}
return items;
}
@Override
public Item<V> itemByKey(String key, boolean queryValue, boolean queryTime) {
List<Map<String, Object>> lst = jdbcTemplate.queryForList(
"select " + (queryValue ? "v," : "") + (queryTime ? "wt,rt," : "") + "1 from " + table + " where k=:key",
Colls.ofHashMap("key", key));
if (Colls.isEmpty(lst))
return null;
else {
Map<String, Object> r = lst.get(0);
Item<V> item = new Item<>();
item.key = key;
assembleItem(r, item, queryValue, queryTime);
if (updateReadTime) {
jdbcTemplate.update(
"update " + table + " set rt=:now where k=:key",
Colls.ofHashMap("key", key, "now", Times.formatNow(Times.Formats.DayTime)));
}
return item;
}
}
private void assembleItem(Map<String, Object> r, Item<V> item, boolean queryValue, boolean queryTime) {
Object v = r.get("v");
if (queryValue && v != null) {
if (v instanceof String) {
item.value = (V) v;
} else {
byte[] blob = (byte[]) v;
if (Compresses.isZip(blob)) {
item.value = SERIALIZER.deserialize(Compresses.decompressZip(blob));
} else if (Compresses.isXz(blob)) {
item.value = SERIALIZER.deserialize(Compresses.decompressXz(blob));
} else if (Serializer.isBuildInStream(blob))
item.value = SERIALIZER.deserialize(blob);
else
item.value = (V) new String(blob);
}
}
if (queryTime) {
String wt = (String) r.get("wt");
if (wt != null)
item.writeTime = Times.parseDayTime(Times.Formats.DayTime, wt)
.atZone(ZoneId.systemDefault()).toLocalDateTime();
String rt = (String) r.get("rt");
if (rt != null)
item.readTime = Times.parseDayTime(Times.Formats.DayTime, rt)
.atZone(ZoneId.systemDefault()).toLocalDateTime();
}
}
@Override
public V byKeyRemoveOnWriteExpired(String key, LocalDateTime validAfter) {
Item<V> item = itemByKey(key, true, true);
if (item != null) {
if (item.writeTime.compareTo(validAfter) < 0) {
remove(key);
return null;
} else
return item.getValue();
} else
return null;
}
@Override
public void removeReadExpired(LocalDateTime validAfter) {
jdbcTemplate.update(
"delete from " + table + " where rt<:va",
Colls.ofHashMap("va", Times.format(Times.Formats.DayTime, validAfter)));
}
@Override
public void remove(String key) {
jdbcTemplate.update(
"delete from " + table + " where k=:key",
Colls.ofHashMap("key", key));
}
@Override
public int save(String key, V value) {
return save(key, value, LocalDateTime.now());
}
@Override
public int save(String key, V value, @Nullable LocalDateTime writeTime) {
byte[] buf = SERIALIZER.serialize(value);
Object saveValue = value instanceof String ? value : buf;
if (suggestCompressValue && buf.length > 256) {
byte[] cb = Compresses.compressXz(buf);
if (cb.length < buf.length)
saveValue = cb;
}
return jdbcTemplate.update(
"insert into " + table + "(k,v,wt,rt) values(:key,:value,:wt,:wt) " +
"on conflict(k) do update set v=:value,wt=:wt"
+ (updateReadTime ? ",rt=(datetime(CURRENT_TIMESTAMP,'localtime'))" : "")
, Colls.ofHashMap(
"key", key,
"value", saveValue,
"wt", Times.format(Times.Formats.DayTime, ObjectUtils.firstNonNull(writeTime, LocalDateTime.now())))
);
}
@Override
public boolean exists(String key) {
return jdbcTemplate.queryForObject("select count(1) from " + table + " where k=:key",
Colls.ofHashMap("key", key), Integer.class) > 0;
}
}
private class KvConfigDAOImpl<V> extends DAOImpl<String> implements KvConfigDAO<V> {
private final Class<V> valueClass;
KvConfigDAOImpl(String table, Class<V> valueClass, boolean updateReadTime) {
super(table, false, updateReadTime);
this.valueClass = Objects.requireNonNull(valueClass);
}
@Override
public V readAndWrite(String key, Function<V, V> biz) {
return readAndWrite(key, biz, LocalDateTime.now());
}
@Override
public V readAndWrite(String key, Function<V, V> biz, LocalDateTime writeTime) {
synchronized (key.intern()) {
Item<String> old = itemByKey(key, true, false);
String s = old != null ? old.getValue() : null;
V newV = biz.apply(s != null ? JSON.parseObject(s, valueClass) : null);
String v = JSON.toJSONString(newV);
save(key, v, writeTime);
return newV;
}
}
@Override
public V configByKey(String key) {
return configByKey(key, null);
}
@Override
public V configByKey(String key, V defaultConfig) {
Item<String> old = itemByKey(key, true, false);
return old != null && Strings.isNotBlank(old.getValue()) ?
JSON.parseObject(old.getValue(), valueClass) : defaultConfig;
}
@Override
public List<Item<V>> configsByRawSql(
@Nullable String cols, @Nullable String conditions, @Nullable String clauses, @Nullable Map<String, ?> params) {
List items = itemsByRawSql(cols, conditions, clauses, params);
items.stream()
.peek(i -> {
Item item = (Item) i;
item.value = JSON.parseObject((String) item.getValue(), valueClass);
})
.collect(Collectors.toList());
return items;
}
@Override
public int saveConfig(String key, V value) {
return saveConfig(key, value, LocalDateTime.now());
}
@Override
public int saveConfig(String key, V value, @Nullable LocalDateTime writeTime) {
return save(key, JSON.toJSONString(value), writeTime);
}
}
/**
* @param table snake_case_group style
*/
public DAO genDAO(String table) {
return new DAOImpl<>(table);
}
/**
* @param table snake_case_group style
*/
public <V> KvDAO<V> genKvDAO(String table, boolean suggestCompressValue, boolean updateReadTime) {
return new DAOImpl<>(table, suggestCompressValue, updateReadTime);
}
/**
* @param table snake_case_group style
* @param valueClass value class will be converted to json string before saving to db.
*/
public <V> KvConfigDAO<V> genKvConfigDAO(String table, Class<V> valueClass, boolean updateReadTime) {
return new KvConfigDAOImpl<>(table, valueClass, updateReadTime);
}
/**
* @see <a href='http://www.sqlitetutorial.net/sqlite-vacuum/'>clear and rebuild db</a>
*/
public void maintain() {
jdbcTemplate.update("VACUUM", Collections.emptyMap());
}
}
| apache-2.0 |
Contargo/contargo-types | src/test/java/net/contargo/types/contactinfo/validation/InternalUserCompletenessValidatorTest.java | 1831 | package net.contargo.types.contactinfo.validation;
import net.contargo.types.contactinfo.ContactInformation;
import org.junit.Before;
import org.junit.Test;
import java.util.List;
import java.util.UUID;
import static org.junit.Assert.assertTrue;
public class InternalUserCompletenessValidatorTest {
private InternalUserCompletenessValidator internalUserCompletenessValidator;
@Before
public void init() {
this.internalUserCompletenessValidator = new InternalUserCompletenessValidator();
}
@Test
public void ensureThatContactInfoWithoutMailIsInvalid() {
ContactInformation incompleteContactInformation = new ContactInformation(UUID.randomUUID().toString(),
"mobile", "phone", "");
List<ValidationResult> results = internalUserCompletenessValidator.checkCompleteness(
incompleteContactInformation);
assertTrue(results.size() == 1);
assertTrue(results.get(0).equals(ValidationResult.MISSING_EMAIL));
}
@Test
public void ensureThatCompleteContactInfoIsValid() {
ContactInformation incompleteContactInformation = new ContactInformation(UUID.randomUUID().toString(),
"mobile", "phone", "email");
List<ValidationResult> results = internalUserCompletenessValidator.checkCompleteness(
incompleteContactInformation);
assertTrue(results.isEmpty());
}
@Test
public void ensureThatContactInfoWithJustEMailIsValid() {
ContactInformation incompleteContactInformation = new ContactInformation(UUID.randomUUID().toString(), "", "",
"email");
List<ValidationResult> results = internalUserCompletenessValidator.checkCompleteness(
incompleteContactInformation);
assertTrue(results.isEmpty());
}
}
| apache-2.0 |
leoleegit/jetty-8.0.4.v20111024 | jetty-servlets/src/test/java/org/eclipse/jetty/servlets/CloseableDoSFilterTest.java | 1789 | // ========================================================================
// Copyright (c) 2009 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
package org.eclipse.jetty.servlets;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger;
import org.junit.BeforeClass;
public class CloseableDoSFilterTest extends AbstractDoSFilterTest
{
private static final Logger LOG = Log.getLogger(CloseableDoSFilterTest.class);
@BeforeClass
public static void setUp() throws Exception
{
startServer(CloseableDoSFilter2.class);
}
public static class CloseableDoSFilter2 extends CloseableDoSFilter
{
public void closeConnection(HttpServletRequest request, HttpServletResponse response, Thread thread)
{
try
{
response.getWriter().append("DoSFilter: timeout");
response.flushBuffer();
super.closeConnection(request, response, thread);
}
catch (Exception e)
{
LOG.warn(e);
}
}
}
}
| apache-2.0 |
91085004/TeachingKidsProgramming | src/org/teachingkidsprogramming/section05recursion/SpiderWeb.java | 2500 | package org.teachingkidsprogramming.section05recursion;
import org.teachingextensions.logo.Tortoise;
import org.teachingextensions.logo.Turtle.Animals;
import org.teachingextensions.logo.utils.ColorUtils.PenColors;
import org.teachingextensions.logo.utils.ColorUtils.PenColors.Reds;
public class SpiderWeb
{
public static void main(String[] args)
{
Tortoise.show();
// Make the tortoise go as fast as possible --#6
Tortoise.setSpeed(10);
// Change the width of the line the tortoise draws to 1 pixel --#12
Tortoise.setPenWidth(1);
// Change the Tortoise to a Spider --#14
Tortoise.setAnimal(Animals.Spider);
// Change the pen color of the line the tortoise draws to red --#13.1
Tortoise.setPenColor(Reds.Red);
// Set the color of the background window to black (HINT: use the Tortoise to get the background window) --#13.2
Tortoise.getBackgroundWindow().setBackground(PenColors.Grays.Black);
// The current length of a line is 10.5 pixels --#1.2
double length = 10.5;
// The current zoom is 1.1 --#8.2
double zoom = 1.1;
// Do the following 10 times --#10.1
for (int i = 0; i < 10; i++)
{
// weaveOneLayer (recipe below) --#9.1
//
// ------------- Recipe for weaveOneLayer --#9.2
// Do the following 6 times --#5.1
for (int j = 0; j < 6; j++)
{
// drawTriangle (recipe below) --#4.1
//
// ------------- Recipe for drawTriangle --#4.2
// Do the following 3 times --#3.1
for (int j2 = 0; j2 < 3; j2++)
{
// Move the tortoise the current length (of the line) --#1.1
Tortoise.move(length);
// Turn the tortoise 1/3rd of 360 degrees --#2
Tortoise.turn(360 / 3);
// End Repeat --#3.2
}
// ------------- End of drawTriangle recipe --#4.3
//
// Turn the tortoise 1/6th of 360 degrees to the right --#7
Tortoise.turn(360 / 6);
// Increase the current length (of the line) by the current zoom --#8.1
length = length * zoom;
// End Repeat --#5.2
}
// ------------- End of weaveOneLayer recipe --#9.3
//
// Change the current zoom so it is multiplied by 1.3 --#11
zoom = zoom * 1.3;
// End Repeat --#10.2
}
}
}
| apache-2.0 |
gstevey/gradle | subprojects/platform-play/src/main/java/org/gradle/play/plugins/PlayTwirlPlugin.java | 7270 | /*
* Copyright 2015 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.play.plugins;
import org.gradle.api.Action;
import org.gradle.api.DefaultTask;
import org.gradle.api.Incubating;
import org.gradle.api.Task;
import org.gradle.api.internal.file.SourceDirectorySetFactory;
import org.gradle.api.specs.Spec;
import org.gradle.internal.service.ServiceRegistry;
import org.gradle.language.base.LanguageSourceSet;
import org.gradle.language.base.internal.SourceTransformTaskConfig;
import org.gradle.language.base.internal.registry.LanguageTransform;
import org.gradle.language.base.internal.registry.LanguageTransformContainer;
import org.gradle.language.scala.ScalaLanguageSourceSet;
import org.gradle.language.twirl.TwirlImports;
import org.gradle.language.twirl.TwirlSourceSet;
import org.gradle.language.twirl.internal.DefaultTwirlSourceSet;
import org.gradle.model.ModelMap;
import org.gradle.model.Mutate;
import org.gradle.model.Path;
import org.gradle.model.RuleSource;
import org.gradle.platform.base.BinarySpec;
import org.gradle.platform.base.ComponentType;
import org.gradle.platform.base.TypeBuilder;
import org.gradle.platform.base.internal.PlatformResolvers;
import org.gradle.play.PlayApplicationSpec;
import org.gradle.play.internal.PlayApplicationBinarySpecInternal;
import org.gradle.play.internal.ScalaSourceCode;
import org.gradle.play.internal.platform.PlayPlatformInternal;
import org.gradle.play.platform.PlayPlatform;
import org.gradle.play.tasks.TwirlCompile;
import org.gradle.util.CollectionUtils;
import java.io.File;
import java.util.Collections;
import java.util.Map;
/**
* Plugin for compiling Twirl sources in a Play application.
*/
@SuppressWarnings("UnusedDeclaration")
@Incubating
public class PlayTwirlPlugin extends RuleSource {
@ComponentType
void registerTwirlLanguageType(TypeBuilder<TwirlSourceSet> builder) {
builder.defaultImplementation(DefaultTwirlSourceSet.class);
}
@Mutate
void createGeneratedScalaSourceSets(@Path("binaries") ModelMap<PlayApplicationBinarySpecInternal> binaries, final SourceDirectorySetFactory sourceDirectorySetFactory) {
binaries.all(new Action<PlayApplicationBinarySpecInternal>() {
@Override
public void execute(PlayApplicationBinarySpecInternal playApplicationBinarySpec) {
for (LanguageSourceSet languageSourceSet : playApplicationBinarySpec.getInputs().withType(TwirlSourceSet.class)) {
playApplicationBinarySpec.addGeneratedScala(languageSourceSet, sourceDirectorySetFactory);
}
}
});
}
@Mutate
// TODO:LPTR This should be @Defaults @Each PlayApplicationBinarySpecInternal
void addPlayJavaDependencyIfNeeded(@Path("binaries") ModelMap<PlayApplicationBinarySpecInternal> binaries, final PlayPluginConfigurations configurations, final PlatformResolvers platforms) {
binaries.beforeEach(new Action<PlayApplicationBinarySpecInternal>() {
@Override
public void execute(PlayApplicationBinarySpecInternal binary) {
if (hasTwirlSourceSetsWithJavaImports(binary.getApplication())) {
PlayPlatform targetPlatform = binary.getTargetPlatform();
configurations.getPlay().addDependency(((PlayPlatformInternal) targetPlatform).getDependencyNotation("play-java"));
}
}
});
}
@Mutate
void registerLanguageTransform(LanguageTransformContainer languages) {
languages.add(new Twirl());
}
private static boolean hasTwirlSourceSetsWithJavaImports(PlayApplicationSpec playApplicationSpec) {
return CollectionUtils.any(playApplicationSpec.getSources().withType(TwirlSourceSet.class).values(), new Spec<TwirlSourceSet>() {
@Override
public boolean isSatisfiedBy(TwirlSourceSet twirlSourceSet) {
return twirlSourceSet.getDefaultImports() == TwirlImports.JAVA;
}
});
}
private static class Twirl implements LanguageTransform<TwirlSourceSet, ScalaSourceCode> {
@Override
public String getLanguageName() {
return "twirl";
}
@Override
public Class<TwirlSourceSet> getSourceSetType() {
return TwirlSourceSet.class;
}
@Override
public Class<ScalaSourceCode> getOutputType() {
return ScalaSourceCode.class;
}
@Override
public Map<String, Class<?>> getBinaryTools() {
return Collections.emptyMap();
}
@Override
public SourceTransformTaskConfig getTransformTask() {
return new SourceTransformTaskConfig() {
public String getTaskPrefix() {
return "compile";
}
public Class<? extends DefaultTask> getTaskType() {
return TwirlCompile.class;
}
public void configureTask(Task task, BinarySpec binarySpec, LanguageSourceSet sourceSet, ServiceRegistry serviceRegistry) {
PlayApplicationBinarySpecInternal binary = (PlayApplicationBinarySpecInternal) binarySpec;
TwirlSourceSet twirlSourceSet = (TwirlSourceSet) sourceSet;
TwirlCompile twirlCompile = (TwirlCompile) task;
ScalaLanguageSourceSet twirlScalaSources = binary.getGeneratedScala().get(twirlSourceSet);
File generatedSourceDir = binary.getNamingScheme().getOutputDirectory(task.getProject().getBuildDir(), "src");
File twirlCompileOutputDirectory = new File(generatedSourceDir, twirlScalaSources.getName());
twirlCompile.setDescription("Compiles Twirl templates for the '" + twirlSourceSet.getName() + "' source set.");
twirlCompile.setPlatform(binary.getTargetPlatform());
twirlCompile.setSource(twirlSourceSet.getSource());
twirlCompile.setOutputDirectory(twirlCompileOutputDirectory);
twirlCompile.setDefaultImports(twirlSourceSet.getDefaultImports());
twirlCompile.setUserTemplateFormats(twirlSourceSet.getUserTemplateFormats());
twirlCompile.setAdditionalImports(twirlSourceSet.getAdditionalImports());
twirlScalaSources.getSource().srcDir(twirlCompileOutputDirectory);
twirlScalaSources.builtBy(twirlCompile);
}
};
}
@Override
public boolean applyToBinary(BinarySpec binary) {
return binary instanceof PlayApplicationBinarySpecInternal;
}
}
}
| apache-2.0 |
kostaskougios/javaflow | lib/src/test/java/org/apache/commons/javaflow/helper/ClassTransformerClassLoader.java | 4048 | /*
* 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.javaflow.helper;
import org.apache.commons.io.IOUtils;
import org.apache.commons.javaflow.bytecode.transformation.ResourceTransformer;
import org.apache.commons.javaflow.classloaders.BytecodeClassLoader;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.util.ASMifier;
import org.objectweb.asm.util.CheckClassAdapter;
import org.objectweb.asm.util.TraceClassVisitor;
import java.io.*;
import java.util.HashSet;
import java.util.Set;
public final class ClassTransformerClassLoader extends BytecodeClassLoader {
private final ResourceTransformer transformer;
private final Set<String> instrument;
private final Set<String> load;
public ClassTransformerClassLoader(final ResourceTransformer pTransformer, final Class<?>[] pInstrument, final Class<?>[] pLoad) {
instrument = new HashSet<>(pInstrument.length);
for (int i = 0; i < pInstrument.length; i++) {
instrument.add(pInstrument[i].getName());
}
load = new HashSet<>(pLoad.length);
for (int i = 0; i < pLoad.length; i++) {
load.add(pLoad[i].getName());
}
transformer = pTransformer;
}
protected byte[] transform(final String pName, final InputStream pClassStream) throws IOException {
final byte[] oldClass = IOUtils.toByteArray(pClassStream);
final byte[] newClass = transformer.transform(oldClass);
// CheckClassAdapter.verify(new ClassReader(newClass), true);
// Test case output has been moved to target/test-instrumentation to reduce clutter in main directory
new File("target/test-instrumentation").mkdirs();
CheckClassAdapter.verify(new ClassReader(newClass), true, new PrintWriter(
new FileOutputStream("target/test-instrumentation/" + transformer.getClass().getSimpleName()
+ "_" + pName + ".new.check")));
new ClassReader(oldClass).accept(new TraceClassVisitor(null, new ASMifier(), new PrintWriter(
new FileOutputStream("target/test-instrumentation/" + transformer.getClass().getSimpleName()
+ "_" + pName + ".old"))), 0);
new ClassReader(newClass).accept(new TraceClassVisitor(null, new ASMifier(), new PrintWriter(
new FileOutputStream("target/test-instrumentation/" + transformer.getClass().getSimpleName()
+ "_" + pName + ".new"))), 0);
return newClass;
}
public Class<?> loadClass(final String name) throws ClassNotFoundException {
final int i = name.indexOf('$');
final String key;
if (i == -1) {
key = name;
} else {
key = name.substring(0, i);
}
if (instrument.contains(key) || load.contains(key)) {
try {
final InputStream is = getClass().getResourceAsStream("/" + name.replace('.', '/') + ".class");
final byte[] bytecode;
if (instrument.contains(key)) {
// System.err.println("Instrumenting: " + name);
bytecode = transform(name, is);
} else {
// System.err.println("Loading: " + name);
bytecode = new ClassReader(is).b;
}
return super.defineClass(name, bytecode, 0, bytecode.length);
} catch (Throwable ex) {
// System.err.println("Load error: " + ex.toString());
ex.printStackTrace();
throw new ClassNotFoundException(name + " " + ex.getMessage(), ex);
}
}
// System.err.println("Delegating: " + name);
return super.loadClass(name);
}
}
| apache-2.0 |
watson-developer-cloud/java-sdk | natural-language-understanding/src/test/java/com/ibm/watson/natural_language_understanding/v1/model/ListModelsOptionsTest.java | 1421 | /*
* (C) Copyright IBM Corp. 2020.
*
* 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.ibm.watson.natural_language_understanding.v1.model;
import static org.testng.Assert.*;
import com.ibm.cloud.sdk.core.service.model.FileWithMetadata;
import com.ibm.watson.natural_language_understanding.v1.utils.TestUtilities;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import org.testng.annotations.Test;
/** Unit test class for the ListModelsOptions model. */
public class ListModelsOptionsTest {
final HashMap<String, InputStream> mockStreamMap = TestUtilities.createMockStreamMap();
final List<FileWithMetadata> mockListFileWithMetadata =
TestUtilities.creatMockListFileWithMetadata();
@Test
public void testListModelsOptions() throws Throwable {
ListModelsOptions listModelsOptionsModel = new ListModelsOptions();
assertNotNull(listModelsOptionsModel);
}
}
| apache-2.0 |
color-coding/ibas.initialfantasy | ibas.initialfantasy/src/main/java/org/colorcoding/ibas/initialfantasy/bo/privilege/IdentityPrivilege.java | 18411 | package org.colorcoding.ibas.initialfantasy.bo.privilege;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import org.colorcoding.ibas.bobas.bo.BusinessObject;
import org.colorcoding.ibas.bobas.core.IPropertyInfo;
import org.colorcoding.ibas.bobas.data.DateTime;
import org.colorcoding.ibas.bobas.data.emAuthoriseType;
import org.colorcoding.ibas.bobas.data.emYesNo;
import org.colorcoding.ibas.bobas.mapping.BusinessObjectUnit;
import org.colorcoding.ibas.bobas.mapping.DbField;
import org.colorcoding.ibas.bobas.mapping.DbFieldType;
import org.colorcoding.ibas.initialfantasy.MyConfiguration;
/**
* 身份权限
*
*/
@XmlAccessorType(XmlAccessType.NONE)
@XmlType(name = IdentityPrivilege.BUSINESS_OBJECT_NAME, namespace = MyConfiguration.NAMESPACE_BO)
@XmlRootElement(name = IdentityPrivilege.BUSINESS_OBJECT_NAME, namespace = MyConfiguration.NAMESPACE_BO)
@BusinessObjectUnit(code = IdentityPrivilege.BUSINESS_OBJECT_CODE)
public class IdentityPrivilege extends BusinessObject<IdentityPrivilege> implements IIdentityPrivilege {
/**
* 序列化版本标记
*/
private static final long serialVersionUID = -4271974320866895679L;
/**
* 当前类型
*/
private static final Class<?> MY_CLASS = IdentityPrivilege.class;
/**
* 数据库表
*/
public static final String DB_TABLE_NAME = "${Company}_SYS_PRIVILEGE1";
/**
* 业务对象编码
*/
public static final String BUSINESS_OBJECT_CODE = "${Company}_SYS_IDENTPRIVILEGE";
/**
* 业务对象名称
*/
public static final String BUSINESS_OBJECT_NAME = "IdentityPrivilege";
/**
* 属性名称-角色标识
*/
private static final String PROPERTY_ROLECODE_NAME = "RoleCode";
/**
* 角色标识 属性
*/
@DbField(name = "RoleCode", type = DbFieldType.ALPHANUMERIC, table = DB_TABLE_NAME, uniqueKey = true)
public static final IPropertyInfo<String> PROPERTY_ROLECODE = registerProperty(PROPERTY_ROLECODE_NAME, String.class,
MY_CLASS);
/**
* 获取-角色标识
*
* @return 值
*/
@XmlElement(name = PROPERTY_ROLECODE_NAME)
public final String getRoleCode() {
return this.getProperty(PROPERTY_ROLECODE);
}
/**
* 设置-角色标识
*
* @param value 值
*/
public final void setRoleCode(String value) {
this.setProperty(PROPERTY_ROLECODE, value);
}
/**
* 属性名称-平台标识
*/
private static final String PROPERTY_PLATFORMID_NAME = "PlatformId";
/**
* 平台标识 属性
*/
@DbField(name = "PlatformId", type = DbFieldType.ALPHANUMERIC, table = DB_TABLE_NAME, uniqueKey = true)
public static final IPropertyInfo<String> PROPERTY_PLATFORMID = registerProperty(PROPERTY_PLATFORMID_NAME,
String.class, MY_CLASS);
/**
* 获取-平台标识
*
* @return 值
*/
@XmlElement(name = PROPERTY_PLATFORMID_NAME)
public final String getPlatformId() {
return this.getProperty(PROPERTY_PLATFORMID);
}
/**
* 设置-平台标识
*
* @param value 值
*/
public final void setPlatformId(String value) {
this.setProperty(PROPERTY_PLATFORMID, value);
}
/**
* 属性名称-模块标识
*/
private static final String PROPERTY_MODULEID_NAME = "ModuleId";
/**
* 模块标识 属性
*/
@DbField(name = "ModuleId", type = DbFieldType.ALPHANUMERIC, table = DB_TABLE_NAME, uniqueKey = true)
public static final IPropertyInfo<String> PROPERTY_MODULEID = registerProperty(PROPERTY_MODULEID_NAME, String.class,
MY_CLASS);
/**
* 获取-模块标识
*
* @return 值
*/
@XmlElement(name = PROPERTY_MODULEID_NAME)
public final String getModuleId() {
return this.getProperty(PROPERTY_MODULEID);
}
/**
* 设置-模块标识
*
* @param value 值
*/
public final void setModuleId(String value) {
this.setProperty(PROPERTY_MODULEID, value);
}
/**
* 属性名称-目标标识
*/
private static final String PROPERTY_TARGET_NAME = "Target";
/**
* 目标标识 属性
*/
@DbField(name = "Target", type = DbFieldType.ALPHANUMERIC, table = DB_TABLE_NAME, uniqueKey = true)
public static final IPropertyInfo<String> PROPERTY_TARGET = registerProperty(PROPERTY_TARGET_NAME, String.class,
MY_CLASS);
/**
* 获取-目标标识
*
* @return 值
*/
@XmlElement(name = PROPERTY_TARGET_NAME)
public final String getTarget() {
return this.getProperty(PROPERTY_TARGET);
}
/**
* 设置-目标标识
*
* @param value 值
*/
public final void setTarget(String value) {
this.setProperty(PROPERTY_TARGET, value);
}
/**
* 属性名称-是否可用
*/
private static final String PROPERTY_ACTIVATED_NAME = "Activated";
/**
* 是否可用 属性
*/
@DbField(name = "Activated", type = DbFieldType.ALPHANUMERIC, table = DB_TABLE_NAME, primaryKey = false)
public static final IPropertyInfo<emYesNo> PROPERTY_ACTIVATED = registerProperty(PROPERTY_ACTIVATED_NAME,
emYesNo.class, MY_CLASS);
/**
* 获取-是否可用
*
* @return 值
*/
@XmlElement(name = PROPERTY_ACTIVATED_NAME)
public final emYesNo getActivated() {
return this.getProperty(PROPERTY_ACTIVATED);
}
/**
* 设置-是否可用
*
* @param value 值
*/
public final void setActivated(emYesNo value) {
this.setProperty(PROPERTY_ACTIVATED, value);
}
/**
* 属性名称-身份标识
*/
private static final String PROPERTY_IDENTITYCODE_NAME = "IdentityCode";
/**
* 身份标识 属性
*/
@DbField(name = "IdentityCode", type = DbFieldType.ALPHANUMERIC, table = DB_TABLE_NAME, uniqueKey = true)
public static final IPropertyInfo<String> PROPERTY_IDENTITYCODE = registerProperty(PROPERTY_IDENTITYCODE_NAME,
String.class, MY_CLASS);
/**
* 获取-身份标识
*
* @return 值
*/
@XmlElement(name = PROPERTY_IDENTITYCODE_NAME)
public final String getIdentityCode() {
return this.getProperty(PROPERTY_IDENTITYCODE);
}
/**
* 设置-身份标识
*
* @param value 值
*/
public final void setIdentityCode(String value) {
this.setProperty(PROPERTY_IDENTITYCODE, value);
}
/**
* 属性名称-权限类型
*/
private static final String PROPERTY_AUTHORISEVALUE_NAME = "AuthoriseValue";
/**
* 权限类型 属性
*/
@DbField(name = "AuthValue", type = DbFieldType.ALPHANUMERIC, table = DB_TABLE_NAME, primaryKey = false)
public static final IPropertyInfo<emAuthoriseType> PROPERTY_AUTHORISEVALUE = registerProperty(
PROPERTY_AUTHORISEVALUE_NAME, emAuthoriseType.class, MY_CLASS);
/**
* 获取-权限类型
*
* @return 值
*/
@XmlElement(name = PROPERTY_AUTHORISEVALUE_NAME)
public final emAuthoriseType getAuthoriseValue() {
return this.getProperty(PROPERTY_AUTHORISEVALUE);
}
/**
* 设置-权限类型
*
* @param value 值
*/
public final void setAuthoriseValue(emAuthoriseType value) {
this.setProperty(PROPERTY_AUTHORISEVALUE, value);
}
/**
* 属性名称-自动运行
*/
private static final String PROPERTY_AUTOMATIC_NAME = "Automatic";
/**
* 自动运行 属性
*/
@DbField(name = "Automatic", type = DbFieldType.ALPHANUMERIC, table = DB_TABLE_NAME, primaryKey = false)
public static final IPropertyInfo<emYesNo> PROPERTY_AUTOMATIC = registerProperty(PROPERTY_AUTOMATIC_NAME,
emYesNo.class, MY_CLASS);
/**
* 获取-自动运行
*
* @return 值
*/
@XmlElement(name = PROPERTY_AUTOMATIC_NAME)
public final emYesNo getAutomatic() {
return this.getProperty(PROPERTY_AUTOMATIC);
}
/**
* 设置-自动运行
*
* @param value 值
*/
public final void setAutomatic(emYesNo value) {
this.setProperty(PROPERTY_AUTOMATIC, value);
}
/**
* 属性名称-对象编号
*/
private static final String PROPERTY_OBJECTKEY_NAME = "ObjectKey";
/**
* 对象编号 属性
*/
@DbField(name = "ObjectKey", type = DbFieldType.NUMERIC, table = DB_TABLE_NAME, primaryKey = true)
public static final IPropertyInfo<Integer> PROPERTY_OBJECTKEY = registerProperty(PROPERTY_OBJECTKEY_NAME,
Integer.class, MY_CLASS);
/**
* 获取-对象编号
*
* @return 值
*/
@XmlElement(name = PROPERTY_OBJECTKEY_NAME)
public final Integer getObjectKey() {
return this.getProperty(PROPERTY_OBJECTKEY);
}
/**
* 设置-对象编号
*
* @param value 值
*/
public final void setObjectKey(Integer value) {
this.setProperty(PROPERTY_OBJECTKEY, value);
}
/**
* 属性名称-对象类型
*/
private static final String PROPERTY_OBJECTCODE_NAME = "ObjectCode";
/**
* 对象类型 属性
*/
@DbField(name = "ObjectCode", type = DbFieldType.ALPHANUMERIC, table = DB_TABLE_NAME, primaryKey = false)
public static final IPropertyInfo<String> PROPERTY_OBJECTCODE = registerProperty(PROPERTY_OBJECTCODE_NAME,
String.class, MY_CLASS);
/**
* 获取-对象类型
*
* @return 值
*/
@XmlElement(name = PROPERTY_OBJECTCODE_NAME)
public final String getObjectCode() {
return this.getProperty(PROPERTY_OBJECTCODE);
}
/**
* 设置-对象类型
*
* @param value 值
*/
public final void setObjectCode(String value) {
this.setProperty(PROPERTY_OBJECTCODE, value);
}
/**
* 属性名称-创建日期
*/
private static final String PROPERTY_CREATEDATE_NAME = "CreateDate";
/**
* 创建日期 属性
*/
@DbField(name = "CreateDate", type = DbFieldType.DATE, table = DB_TABLE_NAME, primaryKey = false)
public static final IPropertyInfo<DateTime> PROPERTY_CREATEDATE = registerProperty(PROPERTY_CREATEDATE_NAME,
DateTime.class, MY_CLASS);
/**
* 获取-创建日期
*
* @return 值
*/
@XmlElement(name = PROPERTY_CREATEDATE_NAME)
public final DateTime getCreateDate() {
return this.getProperty(PROPERTY_CREATEDATE);
}
/**
* 设置-创建日期
*
* @param value 值
*/
public final void setCreateDate(DateTime value) {
this.setProperty(PROPERTY_CREATEDATE, value);
}
/**
* 属性名称-创建时间
*/
private static final String PROPERTY_CREATETIME_NAME = "CreateTime";
/**
* 创建时间 属性
*/
@DbField(name = "CreateTime", type = DbFieldType.NUMERIC, table = DB_TABLE_NAME, primaryKey = false)
public static final IPropertyInfo<Short> PROPERTY_CREATETIME = registerProperty(PROPERTY_CREATETIME_NAME,
Short.class, MY_CLASS);
/**
* 获取-创建时间
*
* @return 值
*/
@XmlElement(name = PROPERTY_CREATETIME_NAME)
public final Short getCreateTime() {
return this.getProperty(PROPERTY_CREATETIME);
}
/**
* 设置-创建时间
*
* @param value 值
*/
public final void setCreateTime(Short value) {
this.setProperty(PROPERTY_CREATETIME, value);
}
/**
* 属性名称-修改日期
*/
private static final String PROPERTY_UPDATEDATE_NAME = "UpdateDate";
/**
* 修改日期 属性
*/
@DbField(name = "UpdateDate", type = DbFieldType.DATE, table = DB_TABLE_NAME, primaryKey = false)
public static final IPropertyInfo<DateTime> PROPERTY_UPDATEDATE = registerProperty(PROPERTY_UPDATEDATE_NAME,
DateTime.class, MY_CLASS);
/**
* 获取-修改日期
*
* @return 值
*/
@XmlElement(name = PROPERTY_UPDATEDATE_NAME)
public final DateTime getUpdateDate() {
return this.getProperty(PROPERTY_UPDATEDATE);
}
/**
* 设置-修改日期
*
* @param value 值
*/
public final void setUpdateDate(DateTime value) {
this.setProperty(PROPERTY_UPDATEDATE, value);
}
/**
* 属性名称-修改时间
*/
private static final String PROPERTY_UPDATETIME_NAME = "UpdateTime";
/**
* 修改时间 属性
*/
@DbField(name = "UpdateTime", type = DbFieldType.NUMERIC, table = DB_TABLE_NAME, primaryKey = false)
public static final IPropertyInfo<Short> PROPERTY_UPDATETIME = registerProperty(PROPERTY_UPDATETIME_NAME,
Short.class, MY_CLASS);
/**
* 获取-修改时间
*
* @return 值
*/
@XmlElement(name = PROPERTY_UPDATETIME_NAME)
public final Short getUpdateTime() {
return this.getProperty(PROPERTY_UPDATETIME);
}
/**
* 设置-修改时间
*
* @param value 值
*/
public final void setUpdateTime(Short value) {
this.setProperty(PROPERTY_UPDATETIME, value);
}
/**
* 属性名称-实例号(版本)
*/
private static final String PROPERTY_LOGINST_NAME = "LogInst";
/**
* 实例号(版本) 属性
*/
@DbField(name = "LogInst", type = DbFieldType.NUMERIC, table = DB_TABLE_NAME, primaryKey = false)
public static final IPropertyInfo<Integer> PROPERTY_LOGINST = registerProperty(PROPERTY_LOGINST_NAME, Integer.class,
MY_CLASS);
/**
* 获取-实例号(版本)
*
* @return 值
*/
@XmlElement(name = PROPERTY_LOGINST_NAME)
public final Integer getLogInst() {
return this.getProperty(PROPERTY_LOGINST);
}
/**
* 设置-实例号(版本)
*
* @param value 值
*/
public final void setLogInst(Integer value) {
this.setProperty(PROPERTY_LOGINST, value);
}
/**
* 属性名称-服务系列
*/
private static final String PROPERTY_SERIES_NAME = "Series";
/**
* 服务系列 属性
*/
@DbField(name = "Series", type = DbFieldType.NUMERIC, table = DB_TABLE_NAME, primaryKey = false)
public static final IPropertyInfo<Integer> PROPERTY_SERIES = registerProperty(PROPERTY_SERIES_NAME, Integer.class,
MY_CLASS);
/**
* 获取-服务系列
*
* @return 值
*/
@XmlElement(name = PROPERTY_SERIES_NAME)
public final Integer getSeries() {
return this.getProperty(PROPERTY_SERIES);
}
/**
* 设置-服务系列
*
* @param value 值
*/
public final void setSeries(Integer value) {
this.setProperty(PROPERTY_SERIES, value);
}
/**
* 属性名称-数据源
*/
private static final String PROPERTY_DATASOURCE_NAME = "DataSource";
/**
* 数据源 属性
*/
@DbField(name = "DataSource", type = DbFieldType.ALPHANUMERIC, table = DB_TABLE_NAME, primaryKey = false)
public static final IPropertyInfo<String> PROPERTY_DATASOURCE = registerProperty(PROPERTY_DATASOURCE_NAME,
String.class, MY_CLASS);
/**
* 获取-数据源
*
* @return 值
*/
@XmlElement(name = PROPERTY_DATASOURCE_NAME)
public final String getDataSource() {
return this.getProperty(PROPERTY_DATASOURCE);
}
/**
* 设置-数据源
*
* @param value 值
*/
public final void setDataSource(String value) {
this.setProperty(PROPERTY_DATASOURCE, value);
}
/**
* 属性名称-创建用户
*/
private static final String PROPERTY_CREATEUSERSIGN_NAME = "CreateUserSign";
/**
* 创建用户 属性
*/
@DbField(name = "Creator", type = DbFieldType.NUMERIC, table = DB_TABLE_NAME, primaryKey = false)
public static final IPropertyInfo<Integer> PROPERTY_CREATEUSERSIGN = registerProperty(PROPERTY_CREATEUSERSIGN_NAME,
Integer.class, MY_CLASS);
/**
* 获取-创建用户
*
* @return 值
*/
@XmlElement(name = PROPERTY_CREATEUSERSIGN_NAME)
public final Integer getCreateUserSign() {
return this.getProperty(PROPERTY_CREATEUSERSIGN);
}
/**
* 设置-创建用户
*
* @param value 值
*/
public final void setCreateUserSign(Integer value) {
this.setProperty(PROPERTY_CREATEUSERSIGN, value);
}
/**
* 属性名称-修改用户
*/
private static final String PROPERTY_UPDATEUSERSIGN_NAME = "UpdateUserSign";
/**
* 修改用户 属性
*/
@DbField(name = "Updator", type = DbFieldType.NUMERIC, table = DB_TABLE_NAME, primaryKey = false)
public static final IPropertyInfo<Integer> PROPERTY_UPDATEUSERSIGN = registerProperty(PROPERTY_UPDATEUSERSIGN_NAME,
Integer.class, MY_CLASS);
/**
* 获取-修改用户
*
* @return 值
*/
@XmlElement(name = PROPERTY_UPDATEUSERSIGN_NAME)
public final Integer getUpdateUserSign() {
return this.getProperty(PROPERTY_UPDATEUSERSIGN);
}
/**
* 设置-修改用户
*
* @param value 值
*/
public final void setUpdateUserSign(Integer value) {
this.setProperty(PROPERTY_UPDATEUSERSIGN, value);
}
/**
* 属性名称-创建动作标识
*/
private static final String PROPERTY_CREATEACTIONID_NAME = "CreateActionId";
/**
* 创建动作标识 属性
*/
@DbField(name = "CreateActId", type = DbFieldType.ALPHANUMERIC, table = DB_TABLE_NAME, primaryKey = false)
public static final IPropertyInfo<String> PROPERTY_CREATEACTIONID = registerProperty(PROPERTY_CREATEACTIONID_NAME,
String.class, MY_CLASS);
/**
* 获取-创建动作标识
*
* @return 值
*/
@XmlElement(name = PROPERTY_CREATEACTIONID_NAME)
public final String getCreateActionId() {
return this.getProperty(PROPERTY_CREATEACTIONID);
}
/**
* 设置-创建动作标识
*
* @param value 值
*/
public final void setCreateActionId(String value) {
this.setProperty(PROPERTY_CREATEACTIONID, value);
}
/**
* 属性名称-更新动作标识
*/
private static final String PROPERTY_UPDATEACTIONID_NAME = "UpdateActionId";
/**
* 更新动作标识 属性
*/
@DbField(name = "UpdateActId", type = DbFieldType.ALPHANUMERIC, table = DB_TABLE_NAME, primaryKey = false)
public static final IPropertyInfo<String> PROPERTY_UPDATEACTIONID = registerProperty(PROPERTY_UPDATEACTIONID_NAME,
String.class, MY_CLASS);
/**
* 获取-更新动作标识
*
* @return 值
*/
@XmlElement(name = PROPERTY_UPDATEACTIONID_NAME)
public final String getUpdateActionId() {
return this.getProperty(PROPERTY_UPDATEACTIONID);
}
/**
* 设置-更新动作标识
*
* @param value 值
*/
public final void setUpdateActionId(String value) {
this.setProperty(PROPERTY_UPDATEACTIONID, value);
}
/**
* 初始化数据
*/
@Override
protected void initialize() {
super.initialize();// 基类初始化,不可去除
this.setObjectCode(MyConfiguration.applyVariables(BUSINESS_OBJECT_CODE));
this.setActivated(emYesNo.YES);
this.setTarget("");
}
}
| apache-2.0 |
nafae/developer | modules/dfp_appengine/src/main/java/com/google/api/ads/dfp/jaxws/v201308/OrderServiceInterfaceupdateOrderResponse.java | 1524 |
package com.google.api.ads.dfp.jaxws.v201308;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for updateOrderResponse element declaration.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <element name="updateOrderResponse">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="rval" type="{https://www.google.com/apis/ads/publisher/v201308}Order" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"rval"
})
@XmlRootElement(name = "updateOrderResponse")
public class OrderServiceInterfaceupdateOrderResponse {
protected Order rval;
/**
* Gets the value of the rval property.
*
* @return
* possible object is
* {@link Order }
*
*/
public Order getRval() {
return rval;
}
/**
* Sets the value of the rval property.
*
* @param value
* allowed object is
* {@link Order }
*
*/
public void setRval(Order value) {
this.rval = value;
}
}
| apache-2.0 |
sdw2330976/Research-spring-data-jpa | spring-data-jpa-1.7.1.RELEASE/src/test/java/org/springframework/data/jpa/repository/JavaConfigUserRepositoryTests.java | 4707 | /*
* Copyright 2012-2013 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.springframework.data.jpa.repository;
import java.io.IOException;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.junit.Test;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.PropertiesFactoryBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.jpa.domain.sample.User;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.data.jpa.repository.sample.SampleEvaluationContextExtension;
import org.springframework.data.jpa.repository.sample.UserRepository;
import org.springframework.data.jpa.repository.sample.UserRepositoryImpl;
import org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean;
import org.springframework.data.repository.core.NamedQueries;
import org.springframework.data.repository.core.support.PropertiesBasedNamedQueries;
import org.springframework.data.repository.query.ExtensionAwareEvaluationContextProvider;
import org.springframework.data.repository.query.spi.EvaluationContextExtension;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
/**
* Integration test for {@link UserRepository} using JavaConfig.
*
* @author Oliver Gierke
* @author Thomas Darimont
*/
@ContextConfiguration(inheritLocations = false, loader = AnnotationConfigContextLoader.class)
public class JavaConfigUserRepositoryTests extends UserRepositoryTests {
@Configuration
@ImportResource("classpath:infrastructure.xml")
static class Config {
@PersistenceContext EntityManager entityManager;
@Autowired ApplicationContext applicationContext;
@Autowired List<EvaluationContextExtension> extensions;
@Bean
public EvaluationContextExtension sampleEvaluationContextExtension() {
return new SampleEvaluationContextExtension();
}
@Bean
public UserRepository userRepository() throws Exception {
ExtensionAwareEvaluationContextProvider evaluationContextProvider = new ExtensionAwareEvaluationContextProvider(
extensions);
evaluationContextProvider.setApplicationContext(applicationContext);
JpaRepositoryFactoryBean<UserRepository, User, Integer> factory = new JpaRepositoryFactoryBean<UserRepository, User, Integer>();
factory.setEntityManager(entityManager);
factory.setBeanFactory(applicationContext);
factory.setRepositoryInterface(UserRepository.class);
factory.setCustomImplementation(new UserRepositoryImpl());
factory.setNamedQueries(namedQueries());
factory.setEvaluationContextProvider(evaluationContextProvider);
factory.afterPropertiesSet();
return factory.getObject();
}
private NamedQueries namedQueries() throws IOException {
PropertiesFactoryBean factory = new PropertiesFactoryBean();
factory.setLocation(new ClassPathResource("META-INF/jpa-named-queries.properties"));
factory.afterPropertiesSet();
return new PropertiesBasedNamedQueries(factory.getObject());
}
}
/**
* @see DATAJPA-317
*/
@Test(expected = NoSuchBeanDefinitionException.class)
public void doesNotPickUpJpaRepository() {
ConfigurableApplicationContext context = new AnnotationConfigApplicationContext(JpaRepositoryConfig.class);
context.getBean("jpaRepository");
context.close();
}
@Configuration
@EnableJpaRepositories(basePackageClasses = UserRepository.class)
@ImportResource("classpath:infrastructure.xml")
static class JpaRepositoryConfig {
}
}
| apache-2.0 |
ryandcarter/hybris-connector | src/main/java/org/mule/modules/hybris/model/ConsignmentEntriesDTO.java | 2239 | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2013.11.29 at 12:35:53 PM GMT
//
package org.mule.modules.hybris.model;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for consignmentEntriesDTO complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="consignmentEntriesDTO">
* <complexContent>
* <extension base="{}abstractCollectionDTO">
* <sequence>
* <element ref="{}consignmententry" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </extension>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "consignmentEntriesDTO", propOrder = {
"consignmententry"
})
public class ConsignmentEntriesDTO
extends AbstractCollectionDTO
{
protected List<ConsignmentEntryDTO> consignmententry;
/**
* Gets the value of the consignmententry property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the consignmententry property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getConsignmententry().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link ConsignmentEntryDTO }
*
*
*/
public List<ConsignmentEntryDTO> getConsignmententry() {
if (consignmententry == null) {
consignmententry = new ArrayList<ConsignmentEntryDTO>();
}
return this.consignmententry;
}
}
| apache-2.0 |
tbroyer/gwt-maven-plugin | src/main/java/net/ltgt/gwt/maven/GenerateModuleMetadataMojo.java | 2465 | package net.ltgt.gwt.maven;
import java.io.File;
import java.io.IOException;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.Component;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.codehaus.plexus.util.FileUtils;
import org.codehaus.plexus.util.StringUtils;
import org.sonatype.plexus.build.incremental.BuildContext;
/**
* Generates the {@code META-INF/gwt/mainModule} file used by {@code gwt:generate-module} in downstream projects.
*/
@Mojo(name = "generate-module-metadata", threadSafe = true, defaultPhase = LifecyclePhase.GENERATE_RESOURCES)
public class GenerateModuleMetadataMojo extends AbstractMojo {
/**
* The main GWT module of the project.
*/
@Parameter
private String moduleName;
/**
* The directory where the generated {@code mainModule} file will be put.
*/
@Parameter(defaultValue = "${project.build.outputDirectory}/META-INF/gwt", required = true)
private File outputDirectory;
/**
* A flag to disable generation of the {@code mainModule}.
*/
@Parameter(defaultValue = "false")
private boolean skipModuleMetadata;
@Component
private BuildContext buildContext;
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
if (skipModuleMetadata) {
return;
}
if (StringUtils.isBlank(moduleName)) {
throw new MojoExecutionException("Missing moduleName");
}
// if (!ModuleDef.isValidModuleName(moduleName)) {
// throw new MojoExecutionException("Invalid module name: " + moduleName);
// }
File outputFile = new File(outputDirectory, "mainModule");
if (outputFile.isFile()) {
try {
String content = FileUtils.fileRead(outputFile, "UTF-8");
if (content.trim().equals(moduleName)) {
getLog().info(outputFile.getAbsolutePath() + " up to date - skipping.");
return;
}
} catch (IOException e) {
// fall-through; let's try writing.
}
}
outputDirectory.mkdirs();
try {
FileUtils.fileWrite(outputFile, "UTF-8", moduleName);
} catch (IOException e) {
throw new MojoExecutionException(e.getMessage(), e);
}
buildContext.refresh(outputFile);
}
}
| apache-2.0 |
bgould/thriftee | core/src/main/java/org/thriftee/core/ProtocolTypeAlias.java | 837 | /*
* Copyright (C) 2013-2016 Benjamin Gould, and others
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.thriftee.core;
import org.apache.thrift.protocol.TProtocolFactory;
public interface ProtocolTypeAlias {
String getName();
TProtocolFactory getInFactory();
TProtocolFactory getOutFactory();
} | apache-2.0 |
lokit/android-jhlabs-filters | src/main/java/com/jhlabs/image/SparkleFilter.java | 3243 | /*
Copyright 2006 Jerry Huxtable
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.jhlabs.image;
import java.util.Random;
public class SparkleFilter extends PointFilter {
private int rays = 50;
private int radius = 25;
private int amount = 50;
private int color = 0xffffffff;
private int randomness = 25;
private int width, height;
private int centreX, centreY;
private long seed = 371;
private float[] rayLengths;
private Random randomNumbers = new Random();
public SparkleFilter() {
}
public void setColor(int color) {
this.color = color;
}
public int getColor() {
return color;
}
public void setRandomness(int randomness) {
this.randomness = randomness;
}
public int getRandomness() {
return randomness;
}
/**
* Set the amount of sparkle.
*
* @param amount the amount
* @min-value 0
* @max-value 1
* @see #getAmount
*/
public void setAmount(int amount) {
this.amount = amount;
}
/**
* Get the amount of sparkle.
*
* @return the amount
* @see #setAmount
*/
public int getAmount() {
return amount;
}
public void setRays(int rays) {
this.rays = rays;
}
public int getRays() {
return rays;
}
/**
* Set the radius of the effect.
*
* @param radius the radius
* @min-value 0
* @see #getRadius
*/
public void setRadius(int radius) {
this.radius = radius;
}
/**
* Get the radius of the effect.
*
* @return the radius
* @see #setRadius
*/
public int getRadius() {
return radius;
}
@Override
public void setDimensions(int width, int height) {
this.width = width;
this.height = height;
centreX = width / 2;
centreY = height / 2;
super.setDimensions(width, height);
randomNumbers.setSeed(seed);
rayLengths = new float[rays];
for (int i = 0; i < rays; i++)
rayLengths[i] = radius + randomness / 100.0f * radius * (float) randomNumbers.nextGaussian();
}
@Override
public int filterRGB(int x, int y, int rgb) {
float dx = x - centreX;
float dy = y - centreY;
float distance = dx * dx + dy * dy;
float angle = (float) Math.atan2(dy, dx);
float d = (angle + ImageMath.PI) / (ImageMath.TWO_PI) * rays;
int i = (int) d;
float f = d - i;
if (radius != 0) {
float length = ImageMath.lerp(f, rayLengths[i % rays], rayLengths[(i + 1) % rays]);
float g = length * length / (distance + 0.0001f);
g = (float) Math.pow(g, (100 - amount) / 50.0);
f -= 0.5f;
// f *= amount/50.0f;
f = 1 - f * f;
f *= g;
}
f = ImageMath.clamp(f, 0, 1);
return ImageMath.mixColors(f, rgb, color);
}
public String toString() {
return "Stylize/Sparkle...";
}
}
| apache-2.0 |
sandeep-n/incubator-apex-malhar | contrib/src/test/java/com/datatorrent/contrib/enrich/JDBCLoaderTest.java | 7113 | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.datatorrent.contrib.enrich;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestWatcher;
import org.junit.runner.Description;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.datatorrent.lib.util.FieldInfo;
import com.datatorrent.netlet.util.DTThrowable;
public class JDBCLoaderTest
{
static final Logger logger = LoggerFactory.getLogger(JDBCLoaderTest.class);
public static class TestMeta extends TestWatcher
{
JDBCLoader dbloader;
int[] id = {1, 2, 3, 4};
String[] name = {"Paul", "Allen", "Teddy", "Mark"};
int[] age = {32, 25, 23, 25};
String[] address = {"California", "Texas", "Norway", "Rich-Mond"};
double[] salary = {20000.00, 15000.00, 20000.00, 65000.00};
@Override
protected void starting(Description description)
{
try {
dbloader = new JDBCLoader();
dbloader.setDatabaseDriver("org.hsqldb.jdbcDriver");
dbloader.setDatabaseUrl("jdbc:hsqldb:mem:test;sql.syntax_mys=true");
dbloader.setTableName("COMPANY");
dbloader.connect();
createTable();
insertRecordsInTable();
} catch (Throwable e) {
DTThrowable.rethrow(e);
}
}
private void createTable()
{
try {
Statement stmt = dbloader.getConnection().createStatement();
String createTable = "CREATE TABLE " + dbloader.getTableName() + " " +
"(ID INT PRIMARY KEY, " +
"NAME CHAR(50), " +
"AGE INT, " +
"ADDRESS CHAR(50), " +
"SALARY REAL)";
logger.debug(createTable);
stmt.executeUpdate(createTable);
logger.debug("Table created successfully...");
} catch (Throwable e) {
DTThrowable.rethrow(e);
}
}
private void insertRecordsInTable()
{
try {
Statement stmt = dbloader.getConnection().createStatement();
String tbName = dbloader.getTableName();
for (int i = 0; i < id.length; i++) {
String sql = "INSERT INTO " + tbName + " (ID,NAME,AGE,ADDRESS,SALARY) " +
"VALUES (" + id[i] + ", '" + name[i] + "', " + age[i] + ", '" + address[i] + "', " + salary[i] + " );";
stmt.executeUpdate(sql);
}
} catch (Throwable e) {
DTThrowable.rethrow(e);
}
}
private void cleanTable()
{
String sql = "DROP TABLE " + dbloader.tableName;
try {
Statement stmt = dbloader.getConnection().createStatement();
stmt.executeUpdate(sql);
logger.debug("Table deleted successfully...");
} catch (SQLException e) {
DTThrowable.rethrow(e);
}
}
@Override
protected void finished(Description description)
{
cleanTable();
}
}
@Rule
public TestMeta testMeta = new TestMeta();
@Test
public void testMysqlDBLookup() throws Exception
{
CountDownLatch latch = new CountDownLatch(1);
ArrayList<FieldInfo> lookupKeys = new ArrayList<>();
lookupKeys.add(new FieldInfo("ID", "ID", FieldInfo.SupportType.INTEGER));
ArrayList<FieldInfo> includeKeys = new ArrayList<>();
includeKeys.add(new FieldInfo("NAME", "NAME", FieldInfo.SupportType.STRING));
includeKeys.add(new FieldInfo("AGE", "AGE", FieldInfo.SupportType.INTEGER));
includeKeys.add(new FieldInfo("ADDRESS", "ADDRESS", FieldInfo.SupportType.STRING));
testMeta.dbloader.setFieldInfo(lookupKeys, includeKeys);
latch.await(1000, TimeUnit.MILLISECONDS);
ArrayList<Object> keys = new ArrayList<>();
keys.add(4);
ArrayList<Object> columnInfo = (ArrayList<Object>)testMeta.dbloader.get(keys);
Assert.assertEquals("NAME", "Mark", columnInfo.get(0).toString().trim());
Assert.assertEquals("AGE", 25, columnInfo.get(1));
Assert.assertEquals("ADDRESS", "Rich-Mond", columnInfo.get(2).toString().trim());
}
@Test
public void testMysqlDBLookupIncludeAllKeys() throws Exception
{
CountDownLatch latch = new CountDownLatch(1);
ArrayList<FieldInfo> lookupKeys = new ArrayList<>();
lookupKeys.add(new FieldInfo("ID", "ID", FieldInfo.SupportType.INTEGER));
ArrayList<FieldInfo> includeKeys = new ArrayList<>();
includeKeys.add(new FieldInfo("ID", "ID", FieldInfo.SupportType.INTEGER));
includeKeys.add(new FieldInfo("NAME", "NAME", FieldInfo.SupportType.STRING));
includeKeys.add(new FieldInfo("AGE", "AGE", FieldInfo.SupportType.INTEGER));
includeKeys.add(new FieldInfo("ADDRESS", "ADDRESS", FieldInfo.SupportType.STRING));
includeKeys.add(new FieldInfo("SALARY", "SALARY", FieldInfo.SupportType.DOUBLE));
testMeta.dbloader.setFieldInfo(lookupKeys, includeKeys);
latch.await(1000, TimeUnit.MILLISECONDS);
ArrayList<Object> keys = new ArrayList<Object>();
keys.add(4);
ArrayList<Object> columnInfo = (ArrayList<Object>)testMeta.dbloader.get(keys);
Assert.assertEquals("ID", 4, columnInfo.get(0));
Assert.assertEquals("NAME", "Mark", columnInfo.get(1).toString().trim());
Assert.assertEquals("AGE", 25, columnInfo.get(2));
Assert.assertEquals("ADDRESS", "Rich-Mond", columnInfo.get(3).toString().trim());
Assert.assertEquals("SALARY", 65000.0, columnInfo.get(4));
}
@Test
public void testMysqlDBQuery() throws Exception
{
CountDownLatch latch = new CountDownLatch(1);
testMeta.dbloader
.setQueryStmt("Select id, name from " + testMeta.dbloader.getTableName() + " where AGE = ? and ADDRESS = ?");
latch.await(1000, TimeUnit.MILLISECONDS);
ArrayList<FieldInfo> includeKeys = new ArrayList<>();
includeKeys.add(new FieldInfo("ID", "ID", FieldInfo.SupportType.INTEGER));
includeKeys.add(new FieldInfo("NAME", "NAME", FieldInfo.SupportType.STRING));
testMeta.dbloader.setFieldInfo(null, includeKeys);
ArrayList<Object> keys = new ArrayList<Object>();
keys.add(25);
keys.add("Texas");
ArrayList<Object> columnInfo = (ArrayList<Object>)testMeta.dbloader.get(keys);
Assert.assertEquals("ID", 2, columnInfo.get(0));
Assert.assertEquals("NAME", "Allen", columnInfo.get(1).toString().trim());
}
}
| apache-2.0 |
jruesga/rview | app/src/main/java/com/ruesga/rview/misc/ExceptionHelper.java | 9410 | /*
* Copyright (C) 2016 Jorge Ruesga
*
* 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.ruesga.rview.misc;
import android.content.Context;
import android.util.Log;
import com.ruesga.rview.R;
import com.ruesga.rview.attachments.EmptyMetadataException;
import com.ruesga.rview.exceptions.IllegalQueryExpressionException;
import com.ruesga.rview.exceptions.OperationFailedException;
import com.ruesga.rview.model.Account;
import com.ruesga.rview.model.EmptyState;
import com.ruesga.rview.preferences.Preferences;
import java.net.ConnectException;
import java.net.NoRouteToHostException;
import java.net.PortUnreachableException;
import java.net.SocketTimeoutException;
import java.util.HashSet;
import java.util.Set;
import androidx.annotation.StringRes;
public class ExceptionHelper {
private static final Set<String> sPreviousAccountAuthenticationFailures = new HashSet<>();
public static final String EXTRA_AUTHENTICATION_FAILURE = "authentication_failure";
@SuppressWarnings("SimplifiableIfStatement")
public static <T extends Throwable> boolean isException(Throwable cause, Class<T> c) {
if (c.isInstance(cause)) {
return true;
}
return cause.getCause() != null && isException(cause.getCause(), c);
}
@SuppressWarnings("SimplifiableIfStatement")
public static <T extends Throwable> boolean isExceptionPkg(Throwable cause, String pkg) {
if (cause.getClass().getName().startsWith(pkg)) {
return true;
}
return cause.getCause() != null && isExceptionPkg(cause.getCause(), pkg);
}
public static <T extends Throwable> Throwable getCause(Throwable cause, Class<T> c) {
if (c.isInstance(cause)) {
return cause;
}
if (cause.getCause() != null) {
return getCause(cause.getCause(), c);
}
return null;
}
@SuppressWarnings({"ThrowableResultOfMethodCallIgnored", "ConstantConditions", "deprecation"})
public static @StringRes int exceptionToMessage(Context context, String tag, Throwable cause) {
int message;
if (isException(cause, retrofit2.HttpException.class)) {
retrofit2.HttpException httpException =
(retrofit2.HttpException)
getCause(cause, retrofit2.HttpException.class);
message = httpCode2MessageResource(httpException.code());
} else if (isException(cause, retrofit2.adapter.rxjava2.HttpException.class)) {
retrofit2.adapter.rxjava2.HttpException httpException =
(retrofit2.adapter.rxjava2.HttpException)
getCause(cause, retrofit2.adapter.rxjava2.HttpException.class);
message = httpCode2MessageResource(httpException.code());
} else if (isException(cause, OperationFailedException.class)) {
message = R.string.exception_operation_failed;
} else if (isException(cause, com.ruesga.rview.gerrit.NoConnectivityException.class)
|| isException(cause, com.ruesga.rview.attachments.NoConnectivityException.class)) {
message = R.string.exception_no_network_available;
} else if (isException(cause, EmptyMetadataException.class)) {
message = R.string.exception_data_not_available;
} else if (isException(cause, com.ruesga.rview.attachments.AuthenticationException.class)) {
message = R.string.exception_attachment_provider_not_logged;
} else if (isException(cause, ConnectException.class)
|| isException(cause, NoRouteToHostException.class)
|| isException(cause, PortUnreachableException.class)
|| isException(cause, SocketTimeoutException.class)) {
message = R.string.exception_server_cannot_be_reached;
} else if (isException(cause, IllegalQueryExpressionException.class)) {
message = R.string.exception_invalid_request;
} else {
message = R.string.exception_request_error;
}
// Log an return the translated message
if (exceptionToLevel(cause) == 0) {
Log.e(tag, context.getString(message), cause);
} else {
Log.w(tag, context.getString(message));
}
return message;
}
private static int httpCode2MessageResource(int code) {
switch (code) {
case 400: //Bad request
return R.string.exception_invalid_request;
case 401: //Unauthorized
return R.string.exception_invalid_user_password;
case 403: //Forbidden
return R.string.exception_insufficient_permissions;
case 404: //Not found
return R.string.exception_request_data_not_found;
case 409: //Conflict
return R.string.exception_conflict;
default:
return R.string.exception_bad_request;
}
}
public static int exceptionToLevel(Throwable cause) {
if (isException(cause, com.ruesga.rview.gerrit.NoConnectivityException.class)
|| isException(cause, com.ruesga.rview.attachments.NoConnectivityException.class)
|| isHttpException(cause, 409)
|| isException(cause, IllegalQueryExpressionException.class)
|| isException(cause, EmptyMetadataException.class)) {
return 1;
}
return 0;
}
public static boolean hasConnectivity(Throwable cause) {
return !(isException(cause, com.ruesga.rview.gerrit.NoConnectivityException.class)
|| isException(cause, com.ruesga.rview.attachments.NoConnectivityException.class));
}
public static boolean hasServerConnectivity(Throwable cause) {
return !(isException(cause, ConnectException.class)
|| isException(cause, NoRouteToHostException.class)
|| isException(cause, PortUnreachableException.class)
|| isException(cause, SocketTimeoutException.class));
}
public static boolean isAuthenticationException(Throwable cause) {
return isHttpException(cause, 401);
}
public static boolean isResourceNotFoundException(Throwable cause) {
return isHttpException(cause, 404);
}
public static boolean isServerUnavailableException(Throwable cause) {
return isHttpException(cause, 503) ||
(isException(cause, ConnectException.class)
|| isException(cause, NoRouteToHostException.class)
|| isException(cause, PortUnreachableException.class)
|| isException(cause, SocketTimeoutException.class));
}
public static boolean isSSLException(Throwable cause) {
return isExceptionPkg(cause, "javax.net.ssl");
}
@SuppressWarnings({"ThrowableResultOfMethodCallIgnored", "ConstantConditions", "deprecation"})
private static boolean isHttpException(Throwable cause, int httpCode) {
if (isException(cause, retrofit2.HttpException.class)) {
retrofit2.HttpException httpException =
(retrofit2.HttpException)
getCause(cause, retrofit2.HttpException.class);
return httpCode == httpException.code();
}
if (isException(cause, retrofit2.adapter.rxjava2.HttpException.class)) {
retrofit2.adapter.rxjava2.HttpException httpException =
(retrofit2.adapter.rxjava2.HttpException)
getCause(cause, retrofit2.adapter.rxjava2.HttpException.class);
return httpCode == httpException.code();
}
return false;
}
public static int resolveEmptyState(Throwable error) {
if (!ExceptionHelper.hasConnectivity(error)) {
return EmptyState.NOT_CONNECTIVITY_STATE;
}
if (!ExceptionHelper.hasServerConnectivity(error)) {
return EmptyState.SERVER_CANNOT_BE_REACHED;
}
return EmptyState.ERROR_STATE;
}
public static synchronized boolean hasPreviousAuthenticationFailure(Context context) {
Account account = Preferences.getAccount(context);
return account != null &&
sPreviousAccountAuthenticationFailures.contains(account.getAccountHash());
}
public static synchronized void markAsAuthenticationFailure(Context context) {
Account account = Preferences.getAccount(context);
if (account != null) {
sPreviousAccountAuthenticationFailures.add(account.getAccountHash());
}
}
public static synchronized void clearAuthenticationFailure(Context context) {
Account account = Preferences.getAccount(context);
if (account != null) {
sPreviousAccountAuthenticationFailures.remove(account.getAccountHash());
}
}
}
| apache-2.0 |
weiwenqiang/GitHub | expert/glide/library/src/test/java/com/bumptech/glide/util/ContentLengthInputStreamTest.java | 5468 | package com.bumptech.glide.util;
import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.fail;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Mockito.when;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
@RunWith(RobolectricTestRunner.class)
@Config(manifest = Config.NONE, sdk = 18)
public class ContentLengthInputStreamTest {
@Mock private InputStream wrapped;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
}
@Test
public void testAvailable_withZeroReadsAndValidContentLength_returnsContentLength()
throws IOException {
int value = 123356;
InputStream is = ContentLengthInputStream.obtain(wrapped, String.valueOf(value));
assertThat(is.available()).isEqualTo(value);
}
@Test
public void testAvailable_withNullContentLength_returnsWrappedAvailable()
throws IOException {
InputStream is = ContentLengthInputStream.obtain(wrapped, null /*contentLengthHeader*/);
int expected = 1234;
when(wrapped.available()).thenReturn(expected);
assertThat(is.available()).isEqualTo(expected);
}
@Test
public void testAvailable_withInvalidContentLength_returnsWrappedAvailable() throws IOException {
InputStream is = ContentLengthInputStream.obtain(wrapped, "invalid_length");
int expected = 567;
when(wrapped.available()).thenReturn(expected);
assertThat(is.available()).isEqualTo(expected);
}
@Test
public void testAvailable_withRead_returnsContentLengthOffsetByRead() throws IOException {
int contentLength = 999;
InputStream is = ContentLengthInputStream.obtain(wrapped, String.valueOf(contentLength));
when(wrapped.read()).thenReturn(1);
assertThat(is.read()).isEqualTo(1);
assertThat(is.available()).isEqualTo(contentLength - 1);
}
@Test
public void testAvailable_handlesReadValueOfZero() throws IOException {
int contentLength = 999;
InputStream is = ContentLengthInputStream.obtain(wrapped, String.valueOf(contentLength));
when(wrapped.read()).thenReturn(0);
assertThat(is.read()).isEqualTo(0);
assertThat(is.available()).isEqualTo(contentLength - 1);
}
@Test
public void testAvailable_withReadBytes_returnsContentLengthOffsetByNumberOfBytes()
throws IOException {
int contentLength = 678;
InputStream is = ContentLengthInputStream.obtain(wrapped, String.valueOf(contentLength));
int read = 100;
when(wrapped.read(any(byte[].class), anyInt(), anyInt())).thenReturn(read);
assertThat(is.read(new byte[500], 0, 0)).isEqualTo(read);
assertThat(is.available()).isEqualTo(contentLength - read);
}
@Test
public void testRead_whenReturnsLessThanZeroWithoutReadingAllContent_throwsIOException()
throws IOException {
int contentLength = 1;
InputStream is = ContentLengthInputStream.obtain(wrapped, String.valueOf(contentLength));
when(wrapped.read()).thenReturn(-1);
try {
//noinspection ResultOfMethodCallIgnored
is.read();
fail("Failed to throw expected exception");
} catch (IOException e) {
// Expected.
}
}
@Test
public void testReadBytes_whenReturnsLessThanZeroWithoutReadingAllContent_throwsIOException()
throws IOException {
int contentLength = 2;
InputStream is = ContentLengthInputStream.obtain(wrapped, String.valueOf(contentLength));
when(wrapped.read(any(byte[].class), anyInt(), anyInt())).thenReturn(-1);
try {
//noinspection ResultOfMethodCallIgnored
is.read(new byte[10], 0, 0);
fail("Failed to throw expected exception");
} catch (IOException e) {
// Expected.
}
}
@Test
public void testRead_whenReturnsLessThanZeroWithInvalidLength_doesNotThrow() throws IOException {
InputStream is = ContentLengthInputStream.obtain(wrapped, "invalid_length");
when(wrapped.read()).thenReturn(-1);
//noinspection ResultOfMethodCallIgnored
is.read();
}
@Test
public void testReadBytes_whenReturnsLessThanZeroWithInvalidLength_doesNotThrow()
throws IOException {
InputStream is = ContentLengthInputStream.obtain(wrapped, "invalid_length");
when(wrapped.read(any(byte[].class), anyInt(), anyInt())).thenReturn(-1);
//noinspection ResultOfMethodCallIgnored
is.read(new byte[10], 0, 0);
}
@Test
public void testRead_readWithZeroes_doesNotThrow() throws IOException {
ByteArrayInputStream inner = new ByteArrayInputStream(new byte[] {0, 0, 0});
InputStream is = ContentLengthInputStream.obtain(inner, 3);
assertThat(is.read()).isEqualTo(0);
assertThat(is.read()).isEqualTo(0);
assertThat(is.read()).isEqualTo(0);
assertThat(is.read()).isEqualTo(-1);
}
@Test
public void testRead_readWithHighValues_doesNotThrow() throws IOException {
ByteArrayInputStream inner =
new ByteArrayInputStream(new byte[] {(byte) 0xF0, (byte) 0xA0, (byte) 0xFF});
InputStream is = ContentLengthInputStream.obtain(inner, 3);
assertThat(is.read()).isEqualTo(0xF0);
assertThat(is.read()).isEqualTo(0xA0);
assertThat(is.read()).isEqualTo(0xFF);
assertThat(is.read()).isEqualTo(-1);
}
}
| apache-2.0 |
nafae/developer | modules/dfp_appengine/src/main/java/com/google/api/ads/dfp/jaxws/v201311/CreativeErrorReason.java | 4480 |
package com.google.api.ads.dfp.jaxws.v201311;
import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for CreativeError.Reason.
*
* <p>The following schema fragment specifies the expected content contained within this class.
* <p>
* <pre>
* <simpleType name="CreativeError.Reason">
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <enumeration value="FLASH_AND_FALLBACK_URL_ARE_SAME"/>
* <enumeration value="INVALID_INTERNAL_REDIRECT_URL"/>
* <enumeration value="DESTINATION_URL_REQUIRED"/>
* <enumeration value="CANNOT_CREATE_OR_UPDATE_LEGACY_DFP_CREATIVE"/>
* <enumeration value="CANNOT_CREATE_OR_UPDATE_LEGACY_DFP_MOBILE_CREATIVE"/>
* <enumeration value="MISSING_FEATURE"/>
* <enumeration value="INVALID_COMPANY_TYPE"/>
* <enumeration value="INVALID_ADSENSE_CREATIVE_SIZE"/>
* <enumeration value="INVALID_AD_EXCHANGE_CREATIVE_SIZE"/>
* <enumeration value="DUPLICATE_ASSET_IN_CREATIVE"/>
* <enumeration value="CREATIVE_ASSET_CANNOT_HAVE_ID_AND_BYTE_ARRAY"/>
* <enumeration value="CANNOT_CREATE_OR_UPDATE_UNSUPPORTED_CREATIVE"/>
* <enumeration value="CANNOT_COPY_VIDEO_CREATIVE_ACROSS_ADVERTISERS"/>
* <enumeration value="UNKNOWN"/>
* </restriction>
* </simpleType>
* </pre>
*
*/
@XmlType(name = "CreativeError.Reason")
@XmlEnum
public enum CreativeErrorReason {
/**
*
* {@link FlashRedirectCreative#flashUrl} and
* {@link FlashRedirectCreative#fallbackUrl} are the same. The fallback URL
* is used when the flash URL does not work and must be different from it.
*
*
*/
FLASH_AND_FALLBACK_URL_ARE_SAME,
/**
*
* The internal redirect URL was invalid. The URL must have the following
* syntax http://ad.doubleclick.net/ad/sitename/;sz=size.
*
*
*/
INVALID_INTERNAL_REDIRECT_URL,
/**
*
* {@link HasDestinationUrlCreative#destinationUrl} is required.
*
*
*/
DESTINATION_URL_REQUIRED,
/**
*
* Cannot create or update legacy DART For Publishers creative.
*
*
*/
CANNOT_CREATE_OR_UPDATE_LEGACY_DFP_CREATIVE,
/**
*
* Cannot create or update legacy mobile creative.
*
*
*/
CANNOT_CREATE_OR_UPDATE_LEGACY_DFP_MOBILE_CREATIVE,
/**
*
* The user is missing a necessary feature.
*
*
*/
MISSING_FEATURE,
/**
*
* Company type should be one of Advertisers, House Advertisers and
* Ad Networks.
*
*
*/
INVALID_COMPANY_TYPE,
/**
*
* Invalid size for AdSense dynamic allocation creative.
* Only valid AFC sizes are allowed.
*
*
*/
INVALID_ADSENSE_CREATIVE_SIZE,
/**
*
* Invalid size for Ad Exchange dynamic allocation creative.
* Only valid Ad Exchange sizes are allowed.
*
*
*/
INVALID_AD_EXCHANGE_CREATIVE_SIZE,
/**
*
* Assets associated with the same creative must be unique.
*
*
*/
DUPLICATE_ASSET_IN_CREATIVE,
/**
*
* A creative asset cannot contain an asset ID and a byte array.
*
*
*/
CREATIVE_ASSET_CANNOT_HAVE_ID_AND_BYTE_ARRAY,
/**
*
* Cannot create or update unsupported creative.
*
*
*/
CANNOT_CREATE_OR_UPDATE_UNSUPPORTED_CREATIVE,
/**
*
* Video creatives cannot be copied across advertisers.
*
*
*/
CANNOT_COPY_VIDEO_CREATIVE_ACROSS_ADVERTISERS,
/**
*
* The value returned if the actual value is not exposed by the requested API version.
*
*
*/
UNKNOWN;
public String value() {
return name();
}
public static CreativeErrorReason fromValue(String v) {
return valueOf(v);
}
}
| apache-2.0 |
paplorinc/intellij-community | java/debugger/impl/src/com/intellij/debugger/settings/DebuggerSettings.java | 12891 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.debugger.settings;
import com.intellij.debugger.impl.DebuggerUtilsEx;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.components.PersistentStateComponent;
import com.intellij.openapi.components.ServiceManager;
import com.intellij.openapi.components.State;
import com.intellij.openapi.components.Storage;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.ui.classFilter.ClassFilter;
import com.intellij.util.EventDispatcher;
import com.intellij.util.containers.hash.LinkedHashMap;
import com.intellij.util.xmlb.SkipDefaultsSerializationFilter;
import com.intellij.util.xmlb.XmlSerializer;
import com.intellij.util.xmlb.annotations.OptionTag;
import com.intellij.util.xmlb.annotations.Transient;
import com.intellij.util.xmlb.annotations.XCollection;
import org.jdom.Element;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.*;
@State(name = "DebuggerSettings", storages = @Storage("debugger.xml"))
public class DebuggerSettings implements Cloneable, PersistentStateComponent<Element> {
private static final Logger LOG = Logger.getInstance(DebuggerSettings.class);
public static final int SOCKET_TRANSPORT = 0;
public static final int SHMEM_TRANSPORT = 1;
@NonNls public static final String SUSPEND_ALL = "SuspendAll";
@NonNls public static final String SUSPEND_THREAD = "SuspendThread";
@NonNls public static final String SUSPEND_NONE = "SuspendNone";
@NonNls public static final String RUN_HOTSWAP_ALWAYS = "RunHotswapAlways";
@NonNls public static final String RUN_HOTSWAP_NEVER = "RunHotswapNever";
@NonNls public static final String RUN_HOTSWAP_ASK = "RunHotswapAsk";
@NonNls public static final String EVALUATE_FINALLY_ALWAYS = "EvaluateFinallyAlways";
@NonNls public static final String EVALUATE_FINALLY_NEVER = "EvaluateFinallyNever";
@NonNls public static final String EVALUATE_FINALLY_ASK = "EvaluateFinallyAsk";
private static final ClassFilter[] DEFAULT_STEPPING_FILTERS = new ClassFilter[]{
new ClassFilter("com.sun.*"),
new ClassFilter("java.*"),
new ClassFilter("javax.*"),
new ClassFilter("org.omg.*"),
new ClassFilter("sun.*"),
new ClassFilter("jdk.internal.*"),
new ClassFilter("junit.*"),
new ClassFilter("com.intellij.rt.*"),
new ClassFilter("com.yourkit.runtime.*"),
new ClassFilter("com.springsource.loaded.*"),
new ClassFilter("org.springsource.loaded.*"),
new ClassFilter("javassist.*"),
new ClassFilter("org.apache.webbeans.*"),
new ClassFilter("com.ibm.ws.*"),
};
public boolean TRACING_FILTERS_ENABLED = true;
@OptionTag("DEBUGGER_TRANSPORT")
private int DEBUGGER_TRANSPORT;
public boolean FORCE_CLASSIC_VM = true;
public boolean DISABLE_JIT;
public boolean SHOW_ALTERNATIVE_SOURCE = true;
public boolean HOTSWAP_IN_BACKGROUND = true;
public volatile boolean ENABLE_MEMORY_AGENT =
ApplicationManager.getApplication().isEAP() && !ApplicationManager.getApplication().isUnitTestMode();
public boolean ALWAYS_SMART_STEP_INTO = true;
public boolean SKIP_SYNTHETIC_METHODS = true;
public boolean SKIP_CONSTRUCTORS;
public boolean SKIP_GETTERS;
public boolean SKIP_CLASSLOADERS = true;
public String RUN_HOTSWAP_AFTER_COMPILE = RUN_HOTSWAP_ASK;
public boolean COMPILE_BEFORE_HOTSWAP = true;
public boolean HOTSWAP_HANG_WARNING_ENABLED = false;
public volatile boolean WATCH_RETURN_VALUES = false;
public volatile boolean AUTO_VARIABLES_MODE = false;
public volatile boolean KILL_PROCESS_IMMEDIATELY = false;
public volatile boolean ALWAYS_DEBUG = true;
public String EVALUATE_FINALLY_ON_POP_FRAME = EVALUATE_FINALLY_ASK;
public boolean RESUME_ONLY_CURRENT_THREAD = false;
private ClassFilter[] mySteppingFilters = DEFAULT_STEPPING_FILTERS;
public boolean INSTRUMENTING_AGENT = true;
private List<CapturePoint> myCapturePoints = new ArrayList<>();
public boolean CAPTURE_VARIABLES;
private final EventDispatcher<CapturePointsSettingsListener> myDispatcher = EventDispatcher.create(CapturePointsSettingsListener.class);
private Map<String, ContentState> myContentStates = new LinkedHashMap<>();
// transient - custom serialization
@Transient
public ClassFilter[] getSteppingFilters() {
final ClassFilter[] rv = new ClassFilter[mySteppingFilters.length];
for (int idx = 0; idx < rv.length; idx++) {
rv[idx] = mySteppingFilters[idx].clone();
}
return rv;
}
public static DebuggerSettings getInstance() {
return ServiceManager.getService(DebuggerSettings.class);
}
public void setSteppingFilters(ClassFilter[] steppingFilters) {
mySteppingFilters = steppingFilters != null ? steppingFilters : ClassFilter.EMPTY_ARRAY;
}
@Nullable
@Override
public Element getState() {
Element state = XmlSerializer.serialize(this, new SkipDefaultsSerializationFilter());
if (!Arrays.equals(DEFAULT_STEPPING_FILTERS, mySteppingFilters)) {
DebuggerUtilsEx.writeFilters(state, "filter", mySteppingFilters);
}
for (ContentState eachState : myContentStates.values()) {
final Element content = new Element("content");
if (eachState.write(content)) {
state.addContent(content);
}
}
return state;
}
@Override
public void loadState(@NotNull Element state) {
XmlSerializer.deserializeInto(this, state);
List<Element> steppingFiltersElement = state.getChildren("filter");
if (steppingFiltersElement.isEmpty()) {
setSteppingFilters(DEFAULT_STEPPING_FILTERS);
}
else {
setSteppingFilters(DebuggerUtilsEx.readFilters(steppingFiltersElement));
}
myContentStates.clear();
for (Element content : state.getChildren("content")) {
ContentState contentState = new ContentState(content);
myContentStates.put(contentState.getType(), contentState);
}
}
public boolean equals(Object obj) {
if (!(obj instanceof DebuggerSettings)) return false;
DebuggerSettings secondSettings = (DebuggerSettings)obj;
return
TRACING_FILTERS_ENABLED == secondSettings.TRACING_FILTERS_ENABLED &&
DEBUGGER_TRANSPORT == secondSettings.DEBUGGER_TRANSPORT &&
StringUtil.equals(EVALUATE_FINALLY_ON_POP_FRAME, secondSettings.EVALUATE_FINALLY_ON_POP_FRAME) &&
FORCE_CLASSIC_VM == secondSettings.FORCE_CLASSIC_VM &&
DISABLE_JIT == secondSettings.DISABLE_JIT &&
SHOW_ALTERNATIVE_SOURCE == secondSettings.SHOW_ALTERNATIVE_SOURCE &&
KILL_PROCESS_IMMEDIATELY == secondSettings.KILL_PROCESS_IMMEDIATELY &&
ALWAYS_DEBUG == secondSettings.ALWAYS_DEBUG &&
HOTSWAP_IN_BACKGROUND == secondSettings.HOTSWAP_IN_BACKGROUND &&
ENABLE_MEMORY_AGENT == secondSettings.ENABLE_MEMORY_AGENT &&
ALWAYS_SMART_STEP_INTO == secondSettings.ALWAYS_SMART_STEP_INTO &&
SKIP_SYNTHETIC_METHODS == secondSettings.SKIP_SYNTHETIC_METHODS &&
SKIP_CLASSLOADERS == secondSettings.SKIP_CLASSLOADERS &&
SKIP_CONSTRUCTORS == secondSettings.SKIP_CONSTRUCTORS &&
SKIP_GETTERS == secondSettings.SKIP_GETTERS &&
RESUME_ONLY_CURRENT_THREAD == secondSettings.RESUME_ONLY_CURRENT_THREAD &&
COMPILE_BEFORE_HOTSWAP == secondSettings.COMPILE_BEFORE_HOTSWAP &&
HOTSWAP_HANG_WARNING_ENABLED == secondSettings.HOTSWAP_HANG_WARNING_ENABLED &&
(Objects.equals(RUN_HOTSWAP_AFTER_COMPILE, secondSettings.RUN_HOTSWAP_AFTER_COMPILE)) &&
DebuggerUtilsEx.filterEquals(mySteppingFilters, secondSettings.mySteppingFilters) &&
myCapturePoints.equals(((DebuggerSettings)obj).myCapturePoints);
}
@Override
public DebuggerSettings clone() {
try {
final DebuggerSettings cloned = (DebuggerSettings)super.clone();
cloned.myContentStates = new HashMap<>();
for (Map.Entry<String, ContentState> entry : myContentStates.entrySet()) {
cloned.myContentStates.put(entry.getKey(), entry.getValue().clone());
}
cloned.mySteppingFilters = new ClassFilter[mySteppingFilters.length];
for (int idx = 0; idx < mySteppingFilters.length; idx++) {
cloned.mySteppingFilters[idx] = mySteppingFilters[idx].clone();
}
cloned.myCapturePoints = cloneCapturePoints();
return cloned;
}
catch (CloneNotSupportedException e) {
LOG.error(e);
}
return null;
}
List<CapturePoint> cloneCapturePoints() {
try {
ArrayList<CapturePoint> res = new ArrayList<>(myCapturePoints.size());
for (CapturePoint point : myCapturePoints) {
res.add(point.clone());
}
return res;
}
catch (CloneNotSupportedException e) {
LOG.error(e);
}
return Collections.emptyList();
}
@XCollection(propertyElementName = "capture-points")
public List<CapturePoint> getCapturePoints() {
return myCapturePoints;
}
// for serialization, do not remove
@SuppressWarnings("unused")
public void setCapturePoints(List<CapturePoint> capturePoints) {
myCapturePoints = capturePoints;
myDispatcher.getMulticaster().capturePointsChanged();
}
public void addCapturePointsSettingsListener(CapturePointsSettingsListener listener, Disposable disposable) {
myDispatcher.addListener(listener, disposable);
}
public static class ContentState implements Cloneable {
private final String myType;
private boolean myMinimized;
private String mySelectedTab;
private double mySplitProportion;
private boolean myDetached;
private boolean myHorizontalToolbar;
private boolean myMaximized;
public ContentState(final String type) {
myType = type;
}
public ContentState(Element element) {
myType = element.getAttributeValue("type");
myMinimized = Boolean.parseBoolean(element.getAttributeValue("minimized"));
myMaximized = Boolean.parseBoolean(element.getAttributeValue("maximized"));
mySelectedTab = element.getAttributeValue("selected");
final String split = element.getAttributeValue("split");
if (split != null) {
mySplitProportion = Double.valueOf(split);
}
myDetached = Boolean.parseBoolean(element.getAttributeValue("detached"));
myHorizontalToolbar = !"false".equalsIgnoreCase(element.getAttributeValue("horizontal"));
}
public boolean write(final Element element) {
element.setAttribute("type", myType);
element.setAttribute("minimized", Boolean.valueOf(myMinimized).toString());
element.setAttribute("maximized", Boolean.valueOf(myMaximized).toString());
if (mySelectedTab != null) {
element.setAttribute("selected", mySelectedTab);
}
element.setAttribute("split", Double.toString(mySplitProportion));
element.setAttribute("detached", Boolean.valueOf(myDetached).toString());
element.setAttribute("horizontal", Boolean.valueOf(myHorizontalToolbar).toString());
return true;
}
public String getType() {
return myType;
}
public String getSelectedTab() {
return mySelectedTab;
}
public boolean isMinimized() {
return myMinimized;
}
public void setMinimized(final boolean minimized) {
myMinimized = minimized;
}
public void setMaximized(final boolean maximized) {
myMaximized = maximized;
}
public boolean isMaximized() {
return myMaximized;
}
public void setSelectedTab(final String selectedTab) {
mySelectedTab = selectedTab;
}
public void setSplitProportion(double splitProportion) {
mySplitProportion = splitProportion;
}
public double getSplitProportion(double defaultValue) {
return mySplitProportion <= 0 || mySplitProportion >= 1 ? defaultValue : mySplitProportion;
}
public void setDetached(final boolean detached) {
myDetached = detached;
}
public boolean isDetached() {
return myDetached;
}
public boolean isHorizontalToolbar() {
return myHorizontalToolbar;
}
public void setHorizontalToolbar(final boolean horizontalToolbar) {
myHorizontalToolbar = horizontalToolbar;
}
@Override
public ContentState clone() throws CloneNotSupportedException {
return (ContentState)super.clone();
}
}
public interface CapturePointsSettingsListener extends EventListener{
void capturePointsChanged();
}
@Transient
public int getTransport() {
if (!SystemInfo.isWindows) {
return SOCKET_TRANSPORT;
}
return DEBUGGER_TRANSPORT;
}
@Transient
public void setTransport(int transport) {
DEBUGGER_TRANSPORT = transport;
}
}
| apache-2.0 |
xcjava/ymWaterWeb | manager_ws_client/com/ymsino/water/service/manager/manager/GetByManagerId.java | 1335 | package com.ymsino.water.service.manager.manager;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;
/**
* <p>
* Java class for getByManagerId complex type.
*
* <p>
* The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="getByManagerId">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="mangerId" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "getByManagerId", propOrder = { "mangerId" })
public class GetByManagerId {
protected String mangerId;
/**
* Gets the value of the mangerId property.
*
* @return possible object is {@link String }
*
*/
public String getMangerId() {
return mangerId;
}
/**
* Sets the value of the mangerId property.
*
* @param value
* allowed object is {@link String }
*
*/
public void setMangerId(String value) {
this.mangerId = value;
}
}
| apache-2.0 |
Wechat-Group/WxJava | weixin-java-pay/src/main/java/com/github/binarywang/wxpay/bean/marketing/BusiFavorStocksUserGetResult.java | 7029 | package com.github.binarywang.wxpay.bean.marketing;
import com.github.binarywang.wxpay.bean.marketing.busifavor.*;
import com.github.binarywang.wxpay.bean.marketing.enums.StockTypeEnum;
import com.google.gson.annotations.SerializedName;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
/**
* 用户单张券详情返回对象
* <pre>
* 文档地址:https://pay.weixin.qq.com/wiki/doc/apiv3/apis/chapter9_2_5.shtml
* </pre>
* TODO:
*
* @author yujam
*/
@Data
@NoArgsConstructor
public class BusiFavorStocksUserGetResult {
private static final long serialVersionUID = 1L;
/**
* <pre>
* 字段名:批次名称
* 变量名:stock_name
* 是否必填:是
* 类型:string[1,21]
* 描述:
* 批次名称
* 校验规则:
* 1、批次名称最多9个中文汉字
* 2、批次名称最多20个字母
* 3、批次名称中不能包含不当内容和特殊字符 _ , ; |
* 示例值:微信支付代金券批次
* </pre>
*/
@SerializedName(value = "stock_name")
private String stockName;
/**
* <pre>
* 字段名:归属商户号
* 变量名:belong_merchant
* 是否必填:是
* 类型:string[8,15]
* 描述:
* 批次归属商户号
* 该字段暂未开放
* 示例值:98568865
* </pre>
*/
@SerializedName(value = "belong_merchant")
private String belongMerchant;
/**
* <pre>
* 字段名:批次备注
* 变量名:comment
* 是否必填:否
* 类型:string[1,20]
* 描述:
* 仅制券商户可见,用于自定义信息。
* 校验规则:批次备注最多60个UTF8字符数
* 示例值:零售批次
* </pre>
*/
@SerializedName(value = "comment")
private String comment;
/**
* <pre>
* 字段名:适用商品范围
* 变量名:goods_name
* 是否必填:是
* 类型:string[1,15]
* 描述:
* 用来描述批次在哪些商品可用,会显示在微信卡包中。字数上限为15个,一个中文汉字/英文字母/数字均占用一个字数。
* 示例值:xxx商品使用
* </pre>
*/
@SerializedName(value = "goods_name")
private String goodsName;
/**
* <pre>
* 字段名:批次类型
* 变量名:stock_type
* 是否必填:是
* 类型:string[1,32]
* 描述:
* 批次类型
* NORMAL:固定面额满减券批次
* DISCOUNT:折扣券批次
* EXCHANGE:换购券批次
* 示例值:NORMAL
* </pre>
*/
@SerializedName(value = "stock_type")
private StockTypeEnum stockType;
/**
* <pre>
* 字段名:核销规则
* 变量名:coupon_use_rule
* 是否必填:是
* 类型:object
* 描述:核销规则
* </pre>
*/
@SerializedName(value = "coupon_use_rule")
private CouponUseRule couponUseRule;
/**
* <pre>
* 字段名:券发放相关规则
* 变量名:stock_send_rule
* 是否必填:是
* 类型:object
* 描述:券发放相关规则
* </pre>
*/
@SerializedName(value = "stock_send_rule")
private StockSendRule stockSendRule;
/**
* <pre>
* 字段名:商户单据号
* 变量名:out_request_no
* 是否必填:是
* 类型:string[1,128]
* 描述:
* 商户创建批次凭据号(格式:商户id+日期+流水号),可包含英文字母,数字,|,_,*,-等内容,不允许出现其他不合法符号,商户侧需保持商户单据号全局唯一。
* </pre>
*/
@SerializedName(value = "out_request_no")
private String outRequestNo;
/**
* <pre>
* 字段名:自定义入口
* 变量名:custom_entrance
* 是否必填:否
* 类型:object
* 描述:卡详情页面,可选择多种入口引导用户。
* </pre>
*/
@SerializedName(value = "custom_entrance")
private CustomEntrance customEntrance;
/**
* <pre>
* 字段名:样式信息
* 变量名:display_pattern_info
* 是否必填:否
* 类型:object
* 描述:创建批次时的样式信息。
* </pre>
*/
@SerializedName(value = "display_pattern_info")
private DisplayPatternInfo displayPatternInfo;
/**
* <pre>
* 字段名:券code模式
* 变量名:coupon_code_mode
* 是否必填:是
* 类型:string[1,128]
* 描述:枚举值:
* WECHATPAY_MODE:系统分配券code。(固定22位纯数字)
* MERCHANT_API:商户发放时接口指定券code。
* MERCHANT_UPLOAD:商户上传自定义code,发券时系统随机选取上传的券code。
* </pre>
*/
@SerializedName(value = "coupon_code_mode")
private String couponCodeMode;
/**
* <pre>
* 字段名:事件通知配置
* 变量名:notify_config
* 是否必填:否
* 类型:object
* 描述:事件回调通知商户的配置
* </pre>
*/
@SerializedName(value = "notify_config")
private NotifyConfig notifyConfig;
/**
* <pre>
* 字段名:批次发放情况
* 变量名:send_count_information
* 是否必填:否
* 类型:object
* 描述:批次发放情况
* </pre>
*/
@SerializedName(value = "send_count_information")
private SendCountInformation sendCountInformation;
@Data
@NoArgsConstructor
public static class SendCountInformation implements Serializable {
private static final long serialVersionUID = 1L;
/**
* <pre>
* 字段名:已发放券张数
* 变量名:total_send_num
* 是否必填:否
* 类型:uint64
* 描述:
* 批次已发放的券数量,满减、折扣、换购类型会返回该字段
* 示例值:1
* </pre>
*/
@SerializedName(value = "total_send_num")
private Integer totalSendNum;
/**
* <pre>
* 字段名:已发放券金额
* 变量名:total_send_amount
* 是否必填:否
* 类型:uint64
* 描述:
* 批次已发放的预算金额,满减券类型会返回该字段
* 示例值:34
* </pre>
*/
@SerializedName(value = "total_send_amount")
private Integer totalSendAmount;
/**
* <pre>
* 字段名:单天已发放券张数
* 变量名:today_send_num
* 是否必填:否
* 类型:uint64
* 描述:
* 批次当天已发放的券数量,设置了单天发放上限的满减、折扣、换购类型返回该字段
* 示例值:1
* </pre>
*/
@SerializedName(value = "today_send_num")
private String todaySendNum;
/**
* <pre>
* 字段名:单天已发放券金额
* 变量名:today_send_amount
* 是否必填:否
* 类型:uint64
* 描述:
* 批次当天已发放的预算金额,设置了当天发放上限的满减券类型返回该字段
* 示例值:34
* </pre>
*/
@SerializedName(value = "today_send_amount")
private String todaySendAmount;
}
}
| apache-2.0 |
ShenghanGao/GoogleCloudPlatformProject | hiring/hiring/src/main/java/cs263w16/BlobstoreEnqueue.java | 4526 | package cs263w16;
import java.util.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import com.google.appengine.api.taskqueue.Queue;
import com.google.appengine.api.taskqueue.QueueFactory;
import com.google.appengine.api.taskqueue.TaskOptions;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PUT;
import javax.ws.rs.Produces;
import javax.ws.rs.FormParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Request;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import javax.xml.bind.JAXBElement;
@Path("/blobstoreenqueue")
public class BlobstoreEnqueue {
/*
@POST
@Path("/newprofilephoto")
@Consumes("application/x-www-form-urlencoded")
public Response newProfilePhoto(
@FormParam("profileName") String profileName,
@Context HttpServletRequest request,
@Context HttpServletResponse response
) throws Exception {
System.out.println("Ready to enqueue the profile photo!!!");
UserService userService = UserServiceFactory.getUserService();
User user = userService.getCurrentUser();
String userId = user.getUserId();
if (user != null) {
System.out.println("The user is not null!!! User Id is " + userId);
}
else
System.out.println("The user is NULL!!!NULLNULLNULLNULLNULLNULLNULLNULLNULLNULLNULLNULLNULLNULLNULL");
BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();
Map<String, List<BlobKey>> blobs = blobstoreService.getUploads(request);
List<BlobKey> blobKeys = blobs.get("myFile");
String des;
System.out.println("I am about to upload to Blobstore!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
if (blobKeys == null || blobKeys.isEmpty()) {
des = "/";
}
else {
des = "/profileaction.jsp?profileName=" + URLEncoder.encode(profileName, "UTF-8");
String blobKey = blobKeys.get(0).getKeyString();
Queue queue = QueueFactory.getDefaultQueue();
queue.add(
TaskOptions.Builder.withUrl("/rest/blobstoreworker/profilephotoworker").param("userId", userId).param("profileName", profileName).param("blobKey", blobKey)
);
}
return Response.temporaryRedirect(new URI(des)).build();
}
*/
@POST
@Path("/newprofilephoto")
@Consumes("application/x-www-form-urlencoded")
public void newProfilePhoto(
@Context HttpServletRequest request,
@Context HttpServletResponse response
) throws Exception {
System.out.println("Ready to enqueue the profile photo!!!");
String profileName = request.getParameter("profileName");
UserService userService = UserServiceFactory.getUserService();
User user = userService.getCurrentUser();
String userId = user.getUserId();
if (user != null) {
System.out.println("The user is not null!!! User Id is " + userId);
}
else
System.out.println("The user is NULL!!!NULLNULLNULLNULLNULLNULLNULLNULLNULLNULLNULLNULLNULLNULLNULL");
BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();
Map<String, List<BlobKey>> blobs = blobstoreService.getUploads(request);
List<BlobKey> blobKeys = blobs.get("myFile");
String des;
System.out.println("I am about to upload to Blobstore!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
if (blobKeys == null || blobKeys.isEmpty()) {
des = "/";
}
else {
des = "/profileaction.jsp?profileName=" + URLEncoder.encode(profileName, "UTF-8");
String blobKey = blobKeys.get(0).getKeyString();
Queue queue = QueueFactory.getDefaultQueue();
queue.add(
TaskOptions.Builder.withUrl("/rest/blobstoreworker/profilephotoworker").param("userId", userId).param("profileName", profileName).param("blobKey", blobKey)
);
}
//return Response.temporaryRedirect(new URI(des)).build();
response.sendRedirect(des);
}
}
| apache-2.0 |
fine1021/library | support/src/main/java/com/yxkang/android/util/Factory.java | 134 | package com.yxkang.android.util;
/**
* Created by yexiaokang on 2016/11/3.
*/
public interface Factory<T> extends Provider<T> {
}
| apache-2.0 |
math4youbyusgroupillinois/junto | src/main/java/junto/util/Defaults.java | 1073 | package junto.util;
import java.util.Hashtable;
public class Defaults {
public static String GetValueOrDie(Hashtable config, String key) {
if (!config.containsKey(key)) {
MessagePrinter.PrintAndDie("Must specify " + key + "");
}
return ((String) config.get(key));
}
public static String GetValueOrDefault(String valStr, String defaultVal) {
String res = defaultVal;
if (valStr != null) {
res = valStr;
}
return (res);
}
public static double GetValueOrDefault(String valStr, double defaultVal) {
double res = defaultVal;
if (valStr != null) {
res = Double.parseDouble(valStr);
}
return (res);
}
public static boolean GetValueOrDefault(String valStr, boolean defaultVal) {
boolean res = defaultVal;
if (valStr != null) {
res = Boolean.parseBoolean(valStr);
}
return (res);
}
public static int GetValueOrDefault(String valStr, int defaultVal) {
int res = defaultVal;
if (valStr != null) {
res = Integer.parseInt(valStr);
}
return (res);
}
}
| apache-2.0 |
macielbombonato/apolo | apolo-api/src/main/java/apolo/api/controller/UserController.java | 17484 | package apolo.api.controller;
import apolo.api.apimodel.FileDTO;
import apolo.api.apimodel.ModelList;
import apolo.api.apimodel.UserDTO;
import apolo.api.controller.base.BaseAPIController;
import apolo.api.helper.ApoloHelper;
import apolo.business.model.FileContent;
import apolo.business.service.FileService;
import apolo.business.service.PermissionGroupService;
import apolo.business.service.UserService;
import apolo.common.exception.AccessDeniedException;
import apolo.common.util.MessageBundle;
import apolo.data.enums.UserStatus;
import apolo.data.model.PermissionGroup;
import apolo.data.model.Tenant;
import apolo.data.model.User;
import apolo.security.Permission;
import org.springframework.core.io.FileSystemResource;
import org.springframework.data.domain.Page;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
@RestController
@RequestMapping(value = "/{tenant-url}/user")
public class UserController extends BaseAPIController<User> {
@Inject
private UserService userService;
@Inject
private PermissionGroupService permissionGroupService;
@Inject
private ApoloHelper<User, UserDTO> userHelper;
@Inject
private FileService<User> fileService;
@CrossOrigin(origins = "*")
@PreAuthorize("permitAll")
@RequestMapping(
value = "",
produces = MediaType.APPLICATION_JSON_VALUE,
method = RequestMethod.GET
)
public @ResponseBody
ModelList<UserDTO> list(
@PathVariable("tenant-url") String tenantUrl,
@RequestParam(required = false) Integer pageNumber,
HttpServletRequest request,
HttpServletResponse response
) {
ModelList<UserDTO> result = new ModelList<UserDTO>();
if (checkAccess(result, tenantUrl, request, Permission.USER_LIST)) {
Page<User> page = userService.list(getDBTenant(tenantUrl), pageNumber);
if (page != null) {
result.setTotalPages(page.getTotalPages());
result.setTotalElements(page.getTotalElements());
if (page.getContent() != null
&& !page.getContent().isEmpty()) {
result.setList(userHelper.toDTOList(page.getContent()));
response.setStatus(200);
} else {
response.setStatus(404);
}
}
} else {
response.setStatus(401);
}
return result;
}
@CrossOrigin(origins = "*")
@PreAuthorize("permitAll")
@RequestMapping(
value = "list-all",
produces = MediaType.APPLICATION_JSON_VALUE,
method = RequestMethod.GET
)
public @ResponseBody
ModelList<UserDTO> listFromAllTenants(
@PathVariable("tenant-url") String tenantUrl,
@RequestParam(required = false) Integer pageNumber,
HttpServletRequest request,
HttpServletResponse response
) {
ModelList<UserDTO> result = new ModelList<UserDTO>();
if (checkAccess(result, tenantUrl, request, Permission.ADMIN)) {
Page<User> page = userService.listAll(pageNumber);
if (page != null) {
result.setTotalPages(page.getTotalPages());
result.setTotalElements(page.getTotalElements());
if (page.getContent() != null
&& !page.getContent().isEmpty()) {
result.setList(userHelper.toDTOList(page.getContent()));
response.setStatus(200);
} else {
response.setStatus(404);
}
}
} else {
response.setStatus(401);
}
return result;
}
@CrossOrigin(origins = "*")
@PreAuthorize("permitAll")
@RequestMapping(
produces = MediaType.APPLICATION_JSON_VALUE,
value = "{id}",
method = RequestMethod.GET
)
public @ResponseBody
UserDTO find(
@PathVariable("tenant-url") String tenantUrl,
@PathVariable Long id,
HttpServletRequest request,
HttpServletResponse response
) {
UserDTO result = new UserDTO();
if (checkAccess(result, tenantUrl, request, Permission.ADMIN, Permission.USER_LIST)) {
User requestUser = getUserFromRequest(request);
User user = null;
if (requestUser.getPermissions().contains(Permission.ADMIN)) {
user = userService.find(id);
} else if (requestUser.getPermissions().contains(Permission.USER_LIST)) {
user = userService.find(getDBTenant(tenantUrl), id);
}
if (user != null) {
result = userHelper.toDTO(user);
response.setStatus(200);
} else {
response.setStatus(404);
}
} else {
response.setStatus(401);
}
return result;
}
@CrossOrigin(origins = "*")
@PreAuthorize("permitAll")
@RequestMapping(
produces = MediaType.APPLICATION_JSON_VALUE,
consumes = MediaType.APPLICATION_JSON_VALUE,
value = "",
method = RequestMethod.POST
)
public @ResponseBody
UserDTO create(
@PathVariable("tenant-url") String tenantUrl,
@RequestBody UserDTO dto,
HttpServletRequest request,
HttpServletResponse response
) {
UserDTO result = new UserDTO();
if (checkAccess(result, tenantUrl, request, Permission.USER_CREATE)) {
if (dto != null
&& dto.getEmail() != null) {
User user = userService.findByLogin(getDBTenant(tenantUrl), dto.getEmail());
User requestUser = getUserFromRequest(request);
if (user != null) {
result.setMessage("User account already exist.");
response.setStatus(403);
} else {
user = userHelper.toEntity(dto);
user.setStatus(UserStatus.ACTIVE);
user.setCreatedAt(new Date());
user.setCreatedBy(requestUser);
user.setEnabled(true);
if (dto.getPassword() == null
|| "".equals(dto.getPassword())) {
user.setPassword("newUser-this-password-need-to-be-changed-!!!!!");
}
Tenant tenant = getDBTenant(tenantUrl);
user.setTenant(tenant);
if (user.getPermissions().contains(Permission.ADMIN)) {
if (!requestUser.getPermissions().contains(Permission.ADMIN)) {
throw new AccessDeniedException(8, MessageBundle.getMessageBundle("error.403.8"));
}
}
user = userService.save(
getServerUrl(request),
user,
true
);
result = userHelper.toDTO(user);
response.setStatus(201);
}
} else {
response.setStatus(404);
}
} else {
response.setStatus(401);
}
return result;
}
@CrossOrigin(origins = "*")
@PreAuthorize("permitAll")
@RequestMapping(
produces = MediaType.APPLICATION_JSON_VALUE,
consumes = MediaType.APPLICATION_JSON_VALUE,
value = "",
method = RequestMethod.PUT
)
public @ResponseBody
UserDTO update(
@PathVariable("tenant-url") String tenantUrl,
@RequestBody UserDTO dto,
HttpServletRequest request,
HttpServletResponse response
) {
UserDTO result = new UserDTO();
User user = getUserFromRequest(request);
if ((user != null && user.getId().equals(dto.getId())) ||
checkAccess(result, tenantUrl, request, Permission.USER_EDIT)) {
Tenant tenant = getDBTenant(tenantUrl);
boolean hasChangePassword = false;
if (dto.getPassword() != null
&& !"".equals(dto.getPassword())) {
hasChangePassword = true;
}
if (dto != null
&& dto.getId() != null) {
User dbEntity = userService.find(dto.getId());
if (dbEntity != null) {
dbEntity = userHelper.toEntity(dto);
if (hasChangePassword) {
dbEntity.setPassword(dto.getPassword());
}
User requestUser = getUserFromRequest(request);
if (requestUser.getPermissions().contains(Permission.ADMIN)
|| requestUser.getPermissions().contains(Permission.TENANT_MANAGER)) {
dbEntity.setTenant(tenant);
}
if (dto.getGroupIds() != null
&& !dto.getGroupIds().isEmpty()) {
for (Long groupId : dto.getGroupIds()) {
if (!dbEntity.getGroupIds().contains(groupId)) {
PermissionGroup permissionGroup = permissionGroupService.find(groupId);
dbEntity.getGroups().add(permissionGroup);
}
}
}
if (dbEntity.getPermissions().contains(Permission.ADMIN)) {
if (!requestUser.getPermissions().contains(Permission.ADMIN)) {
throw new AccessDeniedException(8, MessageBundle.getMessageBundle("error.403.8"));
}
}
if (dbEntity != null
&& dbEntity.getId().equals(dto.getId())) {
dbEntity.setSessionId(request.getSession().getId());
}
dbEntity = userService.save(
getServerUrl(request, tenantUrl),
dbEntity,
hasChangePassword
);
if (dbEntity != null) {
result = userHelper.toDTO(dbEntity);
response.setStatus(200);
} else {
response.setStatus(404);
}
} else {
response.setStatus(404);
}
} else {
response.setStatus(404);
}
} else {
response.setStatus(401);
}
return result;
}
@CrossOrigin(origins = "*")
@PreAuthorize("permitAll")
@RequestMapping(
produces = MediaType.APPLICATION_JSON_VALUE,
value = "{id}",
method = RequestMethod.DELETE
)
public @ResponseBody
UserDTO delete(
@PathVariable("tenant-url") String tenantUrl,
@PathVariable Long id,
HttpServletRequest request,
HttpServletResponse response
) {
UserDTO result = new UserDTO();
if (checkAccess(result, tenantUrl, request, Permission.USER_REMOVE)) {
User user = userService.find(id);
if (user != null) {
if (UserStatus.ADMIN.equals(user.getStatus())) {
throw new AccessDeniedException(9, MessageBundle.getMessageBundle("error.403.9"));
} else if (user.getPermissions().contains(Permission.ADMIN)) {
User requestUser = getUserFromRequest(request);
if (!requestUser.getPermissions().contains(Permission.ADMIN)) {
throw new AccessDeniedException(10, MessageBundle.getMessageBundle("error.403.10"));
}
}
userService.remove(user);
result = null;
response.setStatus(200);
} else {
response.setStatus(404);
}
} else {
response.setStatus(401);
}
return result;
}
@CrossOrigin(origins = "*")
@PreAuthorize("permitAll")
@RequestMapping(
produces = MediaType.APPLICATION_JSON_VALUE,
consumes = MediaType.APPLICATION_JSON_VALUE,
value = "{id}/lock",
method = RequestMethod.PATCH
)
public @ResponseBody
UserDTO lock(
@PathVariable("tenant-url") String tenantUrl,
@PathVariable Long id,
HttpServletRequest request,
HttpServletResponse response
) {
UserDTO result = new UserDTO();
if (checkAccess(result, tenantUrl, request, Permission.USER_MANAGER)) {
User requestUser = getUserFromRequest(request);
User user = null;
if (requestUser.getPermissions().contains(Permission.ADMIN)) {
user = userService.find(id);
} else {
user = userService.find(getDBTenant(tenantUrl), id);
}
if (user != null) {
user = userService.lock(user);
result = userHelper.toDTO(user);
response.setStatus(200);
} else {
response.setStatus(404);
}
} else {
response.setStatus(401);
}
return result;
}
@CrossOrigin(origins = "*")
@PreAuthorize("permitAll")
@RequestMapping(
produces = MediaType.APPLICATION_JSON_VALUE,
consumes = MediaType.APPLICATION_JSON_VALUE,
value = "{id}/unlock",
method = RequestMethod.PATCH
)
public @ResponseBody
UserDTO unlock(
@PathVariable("tenant-url") String tenantUrl,
@PathVariable Long id,
HttpServletRequest request,
HttpServletResponse response
) {
UserDTO result = new UserDTO();
if (checkAccess(result, tenantUrl, request, Permission.USER_MANAGER)) {
User requestUser = getUserFromRequest(request);
User user = null;
if (requestUser.getPermissions().contains(Permission.ADMIN)) {
user = userService.find(id);
} else {
user = userService.find(getDBTenant(tenantUrl), id);
}
if (user != null) {
user = userService.unlock(user);
result = userHelper.toDTO(user);
response.setStatus(200);
} else {
response.setStatus(404);
}
} else {
response.setStatus(401);
}
return result;
}
@CrossOrigin(origins = "*")
@SuppressWarnings("rawtypes")
@PreAuthorize("permitAll")
@RequestMapping(value = "{id}/picture" , method = RequestMethod.POST)
public ResponseEntity<FileSystemResource> putFile(
@PathVariable("tenant-url") String tenantUrl,
@PathVariable Long id,
FileDTO dto,
HttpServletRequest request,
HttpServletResponse response
) {
if (isAutheticated(request)) {
User entity = userService.find(id);
if (entity != null
&& dto != null
&& dto.getFile() != null) {
try {
FileContent file = null;
if (dto != null
&& dto.getFile() != null) {
file = new FileContent();
file.setFile(dto.getFile());
}
String fileName = fileService.uploadFile(
getDBTenant(tenantUrl),
entity,
file,
"picture",
file.getFile().getInputStream()
);
if (dto.getFile() != null
&& dto.getFile().getOriginalFilename() != null
&& !dto.getFile().getOriginalFilename().isEmpty()) {
entity.setAvatarFileName(fileName);
entity.setAvatarContentType(file.getFile().getContentType());
entity.setAvatarOriginalName(file.getName());
entity.setAvatarFileSize(file.getFile().getSize());
entity.setAvatarUpdatedAt(new Date());
userService.save(entity);
}
response.setStatus(200);
} catch (IOException e) {
log.error(e.getMessage(), e);
}
}
return null;
} else {
response.setStatus(403);
throw new AccessDeniedException(MessageBundle.getMessageBundle("error.403"));
}
}
}
| apache-2.0 |
weld/core | tests-arquillian/src/test/java/org/jboss/weld/tests/decorators/abstractDecorator/FrameWithInitializerMethodInjectedDelegate.java | 1342 | /*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat, Inc., and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* 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.jboss.weld.tests.decorators.abstractDecorator;
import jakarta.decorator.Decorator;
import jakarta.decorator.Delegate;
import jakarta.inject.Inject;
/**
* @author <a href="mailto:mariusb@redhat.com">Marius Bogoevici</a>
*/
@Decorator
public abstract class FrameWithInitializerMethodInjectedDelegate implements Window {
static boolean drawn;
private Window window;
@Inject
void initWindow(@Delegate Window window) {
this.window = window;
}
public void draw() {
drawn = true;
window.draw();
}
}
| apache-2.0 |
torrances/swtk-commons | commons-dict-wordnet-indexbyid/src/main/java/org/swtk/commons/dict/wordnet/indexbyid/instance/p0/p9/WordnetNounIndexIdInstance0970.java | 9607 | package org.swtk.commons.dict.wordnet.indexbyid.instance.p0.p9; import java.util.ArrayList; import java.util.Collection; import java.util.Map; import java.util.TreeMap; import org.swtk.common.dict.dto.wordnet.IndexNoun; import com.trimc.blogger.commons.utils.GsonUtils; public final class WordnetNounIndexIdInstance0970 { private static Map<String, Collection<IndexNoun>> map = new TreeMap<String, Collection<IndexNoun>>(); static { add("09700053", "{\"term\":\"papist\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"09700053\"]}");
add("09700304", "{\"term\":\"old catholic\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"09700304\"]}");
add("09700503", "{\"term\":\"uniat\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"09700503\"]}");
add("09700503", "{\"term\":\"uniate\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"09700503\"]}");
add("09700503", "{\"term\":\"uniate christian\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"09700503\"]}");
add("09700630", "{\"term\":\"copt\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"09700630\", \"09720102\"]}");
add("09700747", "{\"term\":\"hebrew\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"09700747\", \"06999784\"]}");
add("09700747", "{\"term\":\"israelite\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"09700747\", \"09735081\"]}");
add("09700747", "{\"term\":\"jew\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"09700747\"]}");
add("09701369", "{\"term\":\"jewess\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"09701369\"]}");
add("09701518", "{\"term\":\"hymie\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"09701518\"]}");
add("09701518", "{\"term\":\"kike\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"09701518\"]}");
add("09701518", "{\"term\":\"sheeny\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"09701518\"]}");
add("09701518", "{\"term\":\"yid\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"09701518\"]}");
add("09701687", "{\"term\":\"moslem\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"09701687\"]}");
add("09701687", "{\"term\":\"muslim\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"09701687\"]}");
add("09702199", "{\"term\":\"islamist\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"09702199\", \"10237005\"]}");
add("09702363", "{\"term\":\"almoravid\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"09702363\"]}");
add("09702576", "{\"term\":\"jihadist\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"09702576\"]}");
add("09702684", "{\"term\":\"shi\u0027ite\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"09702684\"]}");
add("09702684", "{\"term\":\"shi\u0027ite muslim\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"09702684\"]}");
add("09702684", "{\"term\":\"shia muslim\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"09702684\"]}");
add("09702684", "{\"term\":\"shiite\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"09702684\"]}");
add("09702684", "{\"term\":\"shiite muslim\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"09702684\"]}");
add("09702937", "{\"term\":\"sunni\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"08113440\", \"09702937\"]}");
add("09702937", "{\"term\":\"sunni muslim\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"09702937\"]}");
add("09702937", "{\"term\":\"sunnite\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"09702937\"]}");
add("09703135", "{\"term\":\"buddhist\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"09703135\"]}");
add("09703302", "{\"term\":\"zen buddhist\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"09703302\"]}");
add("09703460", "{\"term\":\"mahayanist\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"09703460\"]}");
add("09703604", "{\"term\":\"hinayanist\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"09703604\"]}");
add("09703730", "{\"term\":\"lamaist\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"09703730\"]}");
add("09703854", "{\"term\":\"tantrist\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"09703854\"]}");
add("09703987", "{\"term\":\"hindoo\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"09703987\", \"09732897\"]}");
add("09703987", "{\"term\":\"hindu\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"09703987\", \"09732897\"]}");
add("09704279", "{\"term\":\"swami\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"09704279\"]}");
add("09704384", "{\"term\":\"chela\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"02159184\", \"09704384\"]}");
add("09704463", "{\"term\":\"jainist\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"09704463\"]}");
add("09704611", "{\"term\":\"hare krishna\", \"synsetCount\":3, \"upperType\":\"NOUN\", \"ids\":[\"07048566\", \"08114732\", \"09704611\"]}");
add("09704776", "{\"term\":\"shaktist\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"09704776\"]}");
add("09704942", "{\"term\":\"shivaist\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"09704942\"]}");
add("09705089", "{\"term\":\"vaishnava\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"09705089\"]}");
add("09705184", "{\"term\":\"shintoist\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"09705184\"]}");
add("09705300", "{\"term\":\"rasta\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"09705300\"]}");
add("09705300", "{\"term\":\"rastafarian\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"08169350\", \"09705300\"]}");
add("09705429", "{\"term\":\"mithraist\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"09705429\"]}");
add("09705524", "{\"term\":\"zoroastrian\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"09705524\"]}");
add("09705640", "{\"term\":\"eurafrican\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"09705640\"]}");
add("09705779", "{\"term\":\"eurasian\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"09705779\"]}");
add("09705914", "{\"term\":\"european\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"09705914\"]}");
add("09707171", "{\"term\":\"sahib\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"09707171\"]}");
add("09707336", "{\"term\":\"memsahib\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"09707336\"]}");
add("09707404", "{\"term\":\"celt\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"09707404\"]}");
add("09707404", "{\"term\":\"kelt\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"09707404\"]}");
add("09707629", "{\"term\":\"gael\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"09707629\"]}");
add("09707762", "{\"term\":\"briton\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"09707762\", \"09720360\"]}");
add("09707883", "{\"term\":\"gaul\", \"synsetCount\":3, \"upperType\":\"NOUN\", \"ids\":[\"08949495\", \"09707883\", \"09728044\"]}");
add("09707992", "{\"term\":\"galatian\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"09707992\"]}");
add("09708200", "{\"term\":\"frank\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"07692347\", \"09708200\"]}");
add("09708396", "{\"term\":\"salian\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"09708396\"]}");
add("09708396", "{\"term\":\"salian frank\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"09708396\"]}");
add("09708548", "{\"term\":\"teuton\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"09708548\", \"09767300\"]}");
add("09708831", "{\"term\":\"afghan\", \"synsetCount\":5, \"upperType\":\"NOUN\", \"ids\":[\"02090746\", \"04195013\", \"06987792\", \"09708831\", \"02686177\"]}");
add("09708831", "{\"term\":\"afghanistani\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"09708831\"]}");
add("09709027", "{\"term\":\"kafir\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"09709027\", \"10248534\"]}");
add("09709135", "{\"term\":\"pashtoon\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"09709135\"]}");
add("09709135", "{\"term\":\"pashtun\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"08501658\", \"09709135\"]}");
add("09709135", "{\"term\":\"pathan\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"08501658\", \"09709135\"]}");
add("09709135", "{\"term\":\"pushtun\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"09709135\"]}");
add("09709354", "{\"term\":\"albanian\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"06955014\", \"09709354\"]}");
add("09709479", "{\"term\":\"algerian\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"09709479\"]}");
add("09709604", "{\"term\":\"altaic\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"06938989\", \"09709604\"]}");
add("09709767", "{\"term\":\"armenian\", \"synsetCount\":3, \"upperType\":\"NOUN\", \"ids\":[\"06363524\", \"06955461\", \"09709767\"]}");
add("09709892", "{\"term\":\"andorran\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"09709892\"]}");
} private static void add(final String ID, final String JSON) { IndexNoun indexNoun = GsonUtils.toObject(JSON, IndexNoun.class); Collection<IndexNoun> list = (map.containsKey(ID)) ? map.get(ID) : new ArrayList<IndexNoun>(); list.add(indexNoun); map.put(ID, list); } public static Collection<IndexNoun> get(final String TERM) { return map.get(TERM); } public static boolean has(final String TERM) { return map.containsKey(TERM); } public static Collection<String> ids() { return map.keySet(); } } | apache-2.0 |
huunghiapn/giaitriviet | app/src/main/java/com/nghianh/giaitriviet/providers/soundcloud/helpers/EndlessRecyclerOnScrollListener.java | 2014 | package com.nghianh.giaitriviet.providers.soundcloud.helpers;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
//https://gist.github.com/ssinss/e06f12ef66c51252563e
public abstract class EndlessRecyclerOnScrollListener extends RecyclerView.OnScrollListener {
public static String TAG = EndlessRecyclerOnScrollListener.class.getSimpleName();
private int previousTotal = 0; // The total number of items in the dataset after the last load
private boolean loading = true; // True if we are still waiting for the last set of data to load.
private int visibleThreshold = 5; // The minimum amount of items to have below your current scroll position before loading more.
int firstVisibleItem, visibleItemCount, totalItemCount;
private int current_page = 0;
private LinearLayoutManager mLinearLayoutManager;
public EndlessRecyclerOnScrollListener(LinearLayoutManager linearLayoutManager) {
this.mLinearLayoutManager = linearLayoutManager;
}
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
visibleItemCount = recyclerView.getChildCount();
totalItemCount = mLinearLayoutManager.getItemCount();
firstVisibleItem = mLinearLayoutManager.findFirstVisibleItemPosition();
if (loading) {
if (totalItemCount > previousTotal) {
loading = false;
previousTotal = totalItemCount;
}
}
if (!loading && (totalItemCount - visibleItemCount)
<= (firstVisibleItem + visibleThreshold)) {
// End has been reached
// Do something
current_page++;
onLoadMore(current_page);
loading = true;
}
}
public void reset() {
current_page = 0;
loading = false;
previousTotal = 0;
}
public abstract void onLoadMore(int current_page);
}
| apache-2.0 |
minijax/minijax | minijax-components/minijax-dao/src/main/java/org/minijax/dao/DefaultNamedEntity.java | 2385 | package org.minijax.dao;
import java.util.UUID;
import jakarta.persistence.Column;
import jakarta.persistence.Embedded;
import jakarta.persistence.MappedSuperclass;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Pattern;
import jakarta.validation.constraints.Size;
/**
* The NamedEntity class is a base class for web entities with names.
*/
@MappedSuperclass
@SuppressWarnings({ "squid:S2160", "squid:S2637" })
public abstract class DefaultNamedEntity extends DefaultBaseEntity implements NamedEntity {
private static final long serialVersionUID = 1L;
public static final String HANDLE_SPECIAL_CHARS = "!#$%&'()*+,/:;=?@[\\]^`{|}~";
public static final String HANDLE_SPECIAL_CHARS_REGEX = java.util.regex.Pattern.quote(HANDLE_SPECIAL_CHARS);
public static final String HANDLE_REGEX = "[^\\." + HANDLE_SPECIAL_CHARS_REGEX + "][^" + HANDLE_SPECIAL_CHARS_REGEX + "]*";
@Column(length = 32, unique = true)
@Size(min = 1, max = 32)
@Pattern(regexp = "[^\\.\\Q!#$%&'()*+,/:;=?@[\\]^`{|}~\\E][^\\Q!#$%&'()*+,/:;=?@[\\]^`{|}~\\E]*")
private String handle;
@NotNull
@Size(min = 1, max = 128)
private String name = "";
@Embedded
private Avatar avatar;
protected DefaultNamedEntity() {
super();
}
protected DefaultNamedEntity(final String name) {
setName(name);
}
@Override
public String getHandle() {
return handle;
}
public void setHandle(final String handle) {
if (handle != null) {
this.handle = handle.trim();
} else {
this.handle = null;
}
}
@Override
public String getName() {
return name;
}
@Override
public void setName(final String name) {
if (name != null) {
this.name = name.trim();
} else {
this.name = "";
}
}
@Override
public Avatar getAvatar() {
return avatar;
}
@Override
public void setAvatar(final Avatar avatar) {
this.avatar = avatar;
}
public void generateHandle() {
final String uuid = UUID.randomUUID().toString();
if (name == null) {
handle = uuid.substring(0, 16);
} else {
handle = (name.replaceAll("[^A-Za-z0-9]", "") + "-" + uuid.substring(0, 6)).toLowerCase();
}
}
}
| apache-2.0 |
Fuusio/fuusio-app | fuusio.api/src/main/java/org/fuusio/api/graphics/TextDrawable.java | 17379 | // ============================================================================
// Floxp.com : Java Class Source File
// ============================================================================
//
// Class: TextDrawable
// Package: FloXP.com Android APIs (com.floxp.api) -
// Graphics API (com.floxp.api.graphics)
//
// Author: Marko Salmela
//
// Copyright (C) Marko Salmela, 2009-2011. All Rights Reserved.
//
// This software is the proprietary information of Marko Salmela.
// Use is subject to license terms. This software is protected by
// copyright and distributed under licenses restricting its use,
// copying, distribution, and decompilation. No part of this software
// or associated documentation may be reproduced in any form by any
// means without prior written authorization of Marko Salmela.
//
// Disclaimer:
// -----------
//
// This software is provided by the author 'as is' and any express or implied
// warranties, including, but not limited to, the implied warranties of
// merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the author be liable for any direct, indirect,
// incidental, special, exemplary, or consequential damages (including, but
// not limited to, procurement of substitute goods or services, loss of use,
// data, or profits; or business interruption) however caused and on any
// theory of liability, whether in contract, strict liability, or tort
// (including negligence or otherwise) arising in any way out of the use of
// this software, even if advised of the possibility of such damage.
// ============================================================================
package org.fuusio.api.graphics;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
/**
* {@link TextDrawable} extends {@link Drawable} to implements TODO
*
* @author Marko Salmela
*/
public class TextDrawable extends Drawable {
/**
* A {@code boolean} value specifying whether drawing is antialiazed.
*/
protected boolean mAntialized;
/**
* A {@code boolean} flag specifying whether the background of this {@link TextDrawable} is
* drawn.
*/
protected boolean mBackgroundDrawn;
/**
* The {@link Paint} used for drawing the background of this {@link TextDrawable}.
*/
protected Paint mBackgroundPaint;
/**
* The {@link Paint} used for filling the displayed font glyphs.
*/
protected Paint mFillPaint;
/**
* The horizontal alignment of the display text.
*/
protected HorizontalAlignment mHorizontalAlignment;
/**
* The opacity value of this {@link TextDrawable}.
*/
protected int mOpacity;
/**
* A {@code boolean} flag indicating whether the stroke of the outlines of the font glyphs
* displayed by this {@code TextNode} are drawn.
*/
protected boolean mStroked;
/**
* The {@link Paint} used for drawing the stroke that outlines the displayed font glyphs.
*/
protected Paint mStrokePaint;
/**
* The {@link String} to be displayed.
*/
protected String mText;
/**
* The bounding box for the set text content.
*/
protected Rect mTextBounds;
/**
* The vertical alignment of the display text.
*/
protected VerticalAlignment mVerticalAlignment;
/**
* Constructs a new instance of {@link TextDrawable}.
*/
public TextDrawable() {
mAntialized = false;
mBackgroundDrawn = false;
mBackgroundPaint = createDefaultBackgroundPaint();
mFillPaint = createDefaultFillPaint();
mHorizontalAlignment = HorizontalAlignment.LEFT;
mOpacity = 0xff; // TODO
mStroked = false;
mStrokePaint = createDefaultStrokePaint();
mText = new String();
mTextBounds = new Rect();
mVerticalAlignment = VerticalAlignment.CENTER;
}
/**
* Tests whether the drawing of this (@link TextDrawable) is set to be antialized.
*
* @return {@code boolean} value.
*/
public boolean isAntialized() {
return mAntialized;
}
/**
* Sets the drawing of this (@link TextDrawable) to be antialized depending on the given
* {@code boolean} value.
*
* @param antialized A {@code boolean} value.
*/
public void setAntialized(final boolean antialized) {
mAntialized = antialized;
}
/**
* Gets the {@link Paint} used for drawing the background of this {@link TextDrawable}.
*
* @return A {@link Paint}.
*/
public Paint getBackgroundPaint() {
return mBackgroundPaint;
}
/**
* Sets the {@link Paint} used for drawing the background of this {@link TextDrawable}.
*
* @param paint A {@link Paint}.
*/
public void setBackgroundPaint(final Paint paint) {
assert (paint != null); // TODO
mBackgroundPaint = paint;
mBackgroundPaint.setStyle(Paint.Style.FILL);
}
/**
* Sets the alpha value of the {@link Color} of the {@link Paint} used for drawing the
* background of this {@link TextDrawable}.
*
* @param alpha The alpha value as an {@code int}.
*/
public void setBackgroundAlpha(final int alpha) {
mBackgroundPaint.setAlpha(alpha);
}
/**
* Sets the {@link Color} of {@link Paint} used for drawing the background of this
* {@link TextDrawable}.
*
* @param color A {@link Paint}.
*/
public void setBackgroundColor(final int color) {
mBackgroundPaint.setColor(color);
}
/**
* Tests whether the background of this {@link TextDrawable} is drawn.
*
* @return A {@code boolean} value.
*/
public boolean isBackgroundDrawn() {
return mBackgroundDrawn;
}
/**
* Sets the background of this {@link TextDrawable} to be drawn depending on the given
* {@code boolean} value.
*
* @param isDrawn A {@code boolean} value.
*/
public void setBackgroundDrawn(final boolean isDrawn) {
mBackgroundDrawn = isDrawn;
}
/**
* Gets the {@link Paint} used for filling the displayed font glyphs.
*
* @return A {@link Paint}.
*/
public Paint getFillPaint() {
return mFillPaint;
}
/**
* Sets the {@link Paint} used for filling the displayed font glyphs.
*
* @param paint A {@link Paint}.
*/
public void setFillPaint(final Paint paint) {
assert (paint != null); // TODO
mFillPaint = paint;
mFillPaint.setStyle(Paint.Style.FILL);
}
/**
* Sets the alpha value of the {@link Color} of the {@link Paint} used filling the displayed
* font glyphs.
*
* @param alpha The alpha value as an {@code int}.
*/
public void setFillAlpha(final int alpha) {
mFillPaint.setAlpha(alpha);
}
/**
* Sets the {@link Color} of {@link Paint} used for filling the displayed font glyphs.
*
* @param color the color as an {@code int} value.
*/
public void setFillColor(final int color) {
mFillPaint.setColor(color);
}
/**
* Gets the horizontal alignment.
*
* @return The alignment value as a {@link HorizontalAlignment}.
*/
public HorizontalAlignment getHorizontalAlignment() {
return mHorizontalAlignment;
}
/**
* Sets the horizontal alignment.
*
* @param alignment The alignment value as a {@link HorizontalAlignment}.
*/
public void setHorizontalAlignment(final HorizontalAlignment alignment) {
mHorizontalAlignment = alignment;
}
/**
* Gets the the intrinsic height of the underlying drawable object. Returns -1 if it has no
* intrinsic height, such as with a solid color.
*
* @return The intrinsic height as an {@code int} value.
*/
@Override
public int getIntrinsicHeight() {
if (mText != null && mFillPaint != null) {
mFillPaint.getTextBounds(mText, 0, mText.length(), mTextBounds);
return mTextBounds.height();
}
return super.getIntrinsicHeight();
}
/**
* Gets the the intrinsic width of the underlying drawable object. Returns -1 if it has no
* intrinsic width, such as with a solid color.
*
* @return The intrinsic width as an {@code int} value.
*/
@Override
public int getIntrinsicWidth() {
if (mText != null && mFillPaint != null) {
mFillPaint.getTextBounds(mText, 0, mText.length(), mTextBounds);
return mTextBounds.width();
}
return super.getIntrinsicWidth();
}
@Override
public void setAlpha(final int alpha) // TODo
{
// TODO Auto-generated method stub
}
@Override
public void setColorFilter(final ColorFilter colorFilter) // TODO
{
// TODO Auto-generated method stub
}
/**
* Gets the opacity value.
*
* @return The opacity value as an {@code int}.
*/
@Override
public int getOpacity() {
return mOpacity;
}
/**
* Sets the opacity value.
*
* @param opacity The opacity value as an {@code int}.
*/
public void setOpacity(final int opacity) {
mOpacity = opacity;
}
/**
* Gets the {@link Paint} used for drawing the stroke that outlines the displayed font glyphs.
*
* @return A {@link Paint}.
*/
public Paint getStrokePaint() {
return mStrokePaint;
}
/**
* Sets the {@link Paint} used for drawing the stroke that outlines the displayed font glyphs.
*
* @param paint A {@link Paint}.
*/
public void setStrokePaint(final Paint paint) {
assert (paint != null); // TODO
mStrokePaint = paint;
mStrokePaint.setStyle(Paint.Style.STROKE);
}
/**
* Sets the cap parameter of {@link Paint} used for drawing the stroke that outlines the
* displayed font glyphs.
*
* @param cap A {@link Paint.Cap} value.
*/
public void setStrokeCap(final Paint.Cap cap) {
mStrokePaint.setStrokeCap(cap);
}
/**
* Sets the alpha value of the {@link Color} of the {@link Paint} used for drawing the stroke
* the displayed font glyphs.
*
* @param alpha The alpha value as an {@code int}.
*/
public void setStrokeAlpha(final int alpha) {
mStrokePaint.setAlpha(alpha);
}
/**
* Sets the {@link Color} of {@link Paint} used for drawing the stroke that outlines the
* displayed font glyphs.
*
* @param color the color as a {@link int} value.
*/
public void setStrokeColor(final int color) {
mStrokePaint.setColor(color);
}
public void setStroked(final boolean stroked) {
mStroked = stroked;
}
/**
* Sets the join parameter of {@link Paint} used for drawing the stroke that outlines the
* displayed font glyphs.
*
* @param join A {@link Paint.Join} value.
*/
public void setStrokeJoin(final Paint.Join join) {
mStrokePaint.setStrokeJoin(join);
}
/**
* Sets the miter parameter of {@link Paint} used for drawing the stroke that outlines the
* displayed font glyphs.
*
* @param miter A {@code float} value.
*/
public void setStrokeMiter(final float miter) {
mStrokePaint.setStrokeMiter(miter);
}
/**
* Sets the width parameter of {@link Paint} used for drawing the stroke that outlines the
* displayed font glyphs.
*
* @param width A {@code float} value.
*/
public void setStrokeWidth(final float width) {
mStrokePaint.setStrokeWidth(width);
}
/**
* Gets the {@link String} to be displayed.
*
* @return A {@link String}.
*/
public String getText() {
return mText;
}
/**
* Sets the {@link String} to be displayed.
*
* @param text A {@link String}.
*/
public void setText(final String text) {
mText = text;
}
/**
* Gets the text size.
*
* @return The size as a {@link float}.
*/
public float getTextSize() {
return mFillPaint.getTextSize();
}
/**
* Sets the text size.
*
* @param size The size as a {@link float}.
*/
public void setTextSize(final float size) {
mFillPaint.setTextSize(size);
mStrokePaint.setTextSize(size);
}
/**
* Gets the used {@link Typeface}.
*
* @return A {@link Typeface}. May be {@link null} if not set.
*/
public Typeface getTypeface() {
return mFillPaint.getTypeface();
}
/**
* Sets the used {@link Typeface}.
*
* @param typeface A {@link Typeface}. May be {@link null}.
*/
public void setTypeface(final Typeface typeface) {
mFillPaint.setTypeface(typeface);
mStrokePaint.setTypeface(typeface);
}
/**
* Gets the vertical alignment.
*
* @return The alignment value as a {@link VerticalAlignment}.
*/
public VerticalAlignment getVerticalAlignment() {
return mVerticalAlignment;
}
/**
* Sets the vertical alignment.
*
* @param alignment The alignment value as a {@link VerticalAlignment}.
*/
public void setVerticalAlignment(final VerticalAlignment alignment) {
mVerticalAlignment = alignment;
}
/**
* Creates an appropriate instance of {@link Paint} to be used as a default background paint to
* draw the background of a {@link TextDrawable}.
*
* @return The created {@link Paint} instance.
*/
protected Paint createDefaultBackgroundPaint() {
final Paint paint = new Paint();
paint.setColor(Color.WHITE);
paint.setStyle(Paint.Style.FILL);
return paint;
}
/**
* Creates an appropriate instance of {@link Paint} to be used as a default fillPaint to fill
* the interior of a {@link TextDrawable}.
*
* @return The created {@link Paint} instance.
*/
protected Paint createDefaultFillPaint() {
final Paint paint = new Paint();
paint.setColor(Color.BLACK);
paint.setStyle(Paint.Style.FILL_AND_STROKE);
return paint;
}
/**
* Creates an appropriate instance of {@link Paint} to be used as a default fillPaint of a
* stroke drawn around the outline of a {@link TextDrawable}.
*
* @return The created {@link Paint} instance.
*/
protected Paint createDefaultStrokePaint() {
final Paint paint = new Paint();
paint.setColor(Color.BLACK);
paint.setStyle(Paint.Style.STROKE);
return paint;
}
/**
* Clears the contents of the drawn {@code String}.
*/
public void clearText() {
mText = "";
}
/**
* Applies the rendering parameters defined for this {@link TextDrawable}.
*/
protected void applyRenderingParameters() {
if (mOpacity < 1.0f) {
float alphaValue = mBackgroundPaint.getAlpha();
int alpha = (int) (alphaValue * mOpacity);
mBackgroundPaint.setAlpha(alpha);
alphaValue = mFillPaint.getAlpha();
alpha = (int) (alphaValue * mOpacity);
mFillPaint.setAlpha(alpha);
alphaValue = mStrokePaint.getAlpha();
alpha = (int) (alphaValue * mOpacity);
mStrokePaint.setAlpha(alpha);
}
}
/**
* Draws this {@link TextDrawable} on the given {@link Canvas}.
*
* @param canvas A {@link Canvas}.
*/
@Override
public void draw(final Canvas canvas) {
if (mText != null) {
final Rect bounds = getBounds();
int x = bounds.left;
int y = bounds.top;
mFillPaint.getTextBounds(mText, 0, mText.length(), mTextBounds);
switch (mHorizontalAlignment) {
case LEFT: {
break;
}
case CENTER: {
x += (bounds.width() - mTextBounds.width()) / 2;
break;
}
case RIGHT: {
x = bounds.right - mTextBounds.width();
break;
}
}
switch (mVerticalAlignment) {
case TOP: {
y += mTextBounds.height();
break;
}
case CENTER: {
y += (bounds.height() + mTextBounds.height()) / 2;
break;
}
case BOTTOM: {
y = bounds.bottom;
break;
}
}
mFillPaint.setAntiAlias(mAntialized);
mFillPaint.setTextAlign(mHorizontalAlignment.getPaintAlign());
canvas.drawText(mText, x, y, mFillPaint);
if (mStroked) {
mStrokePaint.setAntiAlias(mAntialized);
mStrokePaint.setTextAlign(mHorizontalAlignment.getPaintAlign());
canvas.drawText(mText, x, y, mStrokePaint);
}
}
}
}
| apache-2.0 |
glahiru/airavata | modules/orchestrator/orchestrator-core/src/test/java/org/apache/airavata/orchestrator/core/BaseOrchestratorTest.java | 3436 | /*
*
* 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.airavata.orchestrator.core;
import org.apache.airavata.api.Airavata;
import org.apache.airavata.api.client.AiravataClientFactory;
//import org.apache.airavata.client.tools.DocumentCreatorNew;
import org.apache.airavata.common.utils.ServerSettings;
import org.apache.airavata.model.error.AiravataClientConnectException;
import org.apache.airavata.orchestrator.core.util.Initialize;
import org.apache.airavata.persistance.registry.jpa.ResourceUtils;
import org.apache.airavata.persistance.registry.jpa.resources.GatewayResource;
import org.apache.airavata.persistance.registry.jpa.resources.UserResource;
import org.apache.airavata.persistance.registry.jpa.resources.WorkerResource;
public class BaseOrchestratorTest {
/* private GatewayResource gatewayResource;
private WorkerResource workerResource;
private UserResource userResource;
private Initialize initialize;
private DocumentCreatorNew documentCreator;
public void setUp() throws Exception {
initialize = new Initialize("registry-derby.sql");
initialize.initializeDB();
gatewayResource = (GatewayResource) ResourceUtils.getGateway(ServerSettings.getSystemUserGateway());
workerResource = (WorkerResource) ResourceUtils.getWorker(gatewayResource.getGatewayName(), ServerSettings.getDefaultUser());
userResource = new UserResource();
userResource.setUserName(ServerSettings.getDefaultUser());
userResource.setPassword(ServerSettings.getDefaultUser());
documentCreator = new DocumentCreatorNew(getAiravataClient());
documentCreator.createLocalHostDocs();
documentCreator.createPBSDocsForOGCE_Echo();
}
public void tearDown() throws Exception {
initialize.stopDerbyServer();
}
public GatewayResource getGatewayResource() {
return gatewayResource;
}
public WorkerResource getWorkerResource() {
return workerResource;
}
public UserResource getUserResource() {
return userResource;
}
private Airavata.Client getAiravataClient() {
Airavata.Client client = null;
try {
client = AiravataClientFactory.createAiravataClient("localhost", 8930);
} catch (AiravataClientConnectException e) {
e.printStackTrace();
}
return client;
}
public DocumentCreatorNew getDocumentCreator() {
return documentCreator;
}
public void setDocumentCreator(DocumentCreatorNew documentCreator) {
this.documentCreator = documentCreator;
}
private void settingServerProperties(){
}*/
}
| apache-2.0 |
spring-projects/spring-security | oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/userinfo/ReactiveOAuth2UserService.java | 2060 | /*
* Copyright 2002-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.oauth2.client.userinfo;
import reactor.core.publisher.Mono;
import org.springframework.security.core.AuthenticatedPrincipal;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.core.user.OAuth2User;
/**
* Implementations of this interface are responsible for obtaining the user attributes of
* the End-User (Resource Owner) from the UserInfo Endpoint using the
* {@link OAuth2UserRequest#getAccessToken() Access Token} granted to the
* {@link OAuth2UserRequest#getClientRegistration() Client} and returning an
* {@link AuthenticatedPrincipal} in the form of an {@link OAuth2User}.
*
* @param <R> The type of OAuth 2.0 User Request
* @param <U> The type of OAuth 2.0 User
* @author Rob Winch
* @since 5.1
* @see OAuth2UserRequest
* @see OAuth2User
* @see AuthenticatedPrincipal
*/
@FunctionalInterface
public interface ReactiveOAuth2UserService<R extends OAuth2UserRequest, U extends OAuth2User> {
/**
* Returns an {@link OAuth2User} after obtaining the user attributes of the End-User
* from the UserInfo Endpoint.
* @param userRequest the user request
* @return an {@link OAuth2User}
* @throws OAuth2AuthenticationException if an error occurs while attempting to obtain
* the user attributes from the UserInfo Endpoint
*/
Mono<U> loadUser(R userRequest) throws OAuth2AuthenticationException;
}
| apache-2.0 |
sacjaya/siddhi | modules/siddhi-core/src/main/java/org/wso2/siddhi/core/query/output/ratelimit/snapshot/WindowedPerSnapshotOutputRateLimiter.java | 5132 | /*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. 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.wso2.siddhi.core.query.output.ratelimit.snapshot;
import org.wso2.siddhi.core.event.ComplexEvent;
import org.wso2.siddhi.core.event.ComplexEventChunk;
import org.wso2.siddhi.core.event.GroupedComplexEvent;
import org.wso2.siddhi.core.event.stream.StreamEventPool;
import org.wso2.siddhi.core.util.Scheduler;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class WindowedPerSnapshotOutputRateLimiter extends SnapshotOutputRateLimiter {
private String id;
private final Long value;
private final ScheduledExecutorService scheduledExecutorService;
private LinkedList<ComplexEvent> eventList;
private Comparator comparator;
private Scheduler scheduler;
private long scheduledTime;
private Lock lock;
public WindowedPerSnapshotOutputRateLimiter(String id, Long value, ScheduledExecutorService scheduledExecutorService, WrappedSnapshotOutputRateLimiter wrappedSnapshotOutputRateLimiter) {
super(wrappedSnapshotOutputRateLimiter);
this.id = id;
this.value = value;
this.scheduledExecutorService = scheduledExecutorService;
this.eventList = new LinkedList<ComplexEvent>();
lock = new ReentrantLock();
this.comparator = new Comparator<ComplexEvent>() {
@Override
public int compare(ComplexEvent event1, ComplexEvent event2) {
if (Arrays.equals(event1.getOutputData(), event2.getOutputData())) {
return 0;
} else {
return 1;
}
}
};
}
@Override
public void process(ComplexEventChunk complexEventChunk) {
try {
lock.lock();
complexEventChunk.reset();
while (complexEventChunk.hasNext()) {
ComplexEvent event = complexEventChunk.next();
if (event instanceof GroupedComplexEvent) {
event = ((GroupedComplexEvent) event).getComplexEvent();
}
if (event.getType() == ComplexEvent.Type.TIMER) {
if (event.getTimestamp() >= scheduledTime) {
sendEvents();
scheduledTime = scheduledTime + value;
scheduler.notifyAt(scheduledTime);
}
} else if (event.getType() == ComplexEvent.Type.CURRENT) {
complexEventChunk.remove();
eventList.add(event);
} else if (event.getType() == ComplexEvent.Type.EXPIRED) {
for (Iterator<ComplexEvent> iterator = eventList.iterator(); iterator.hasNext(); ) {
ComplexEvent currentEvent = iterator.next();
if (comparator.compare(currentEvent, event) == 0) {
iterator.remove();
break;
}
}
}
}
} finally {
lock.unlock();
}
}
@Override
public SnapshotOutputRateLimiter clone(String key, WrappedSnapshotOutputRateLimiter wrappedSnapshotOutputRateLimiter) {
return new WindowedPerSnapshotOutputRateLimiter(id + key, value, scheduledExecutorService, wrappedSnapshotOutputRateLimiter);
}
@Override
public void start() {
scheduler = new Scheduler(scheduledExecutorService, this);
scheduler.setStreamEventPool(new StreamEventPool(0, 0, 0, 5));
long currentTime = System.currentTimeMillis();
scheduler.notifyAt(currentTime);
scheduledTime = currentTime;
}
@Override
public void stop() {
//Nothing to stop
}
@Override
public Object[] currentState() {
return new Object[]{eventList};
}
@Override
public void restoreState(Object[] state) {
eventList = (LinkedList<ComplexEvent>) state[0];
}
private synchronized void sendEvents() {
ComplexEventChunk<ComplexEvent> complexEventChunk = new ComplexEventChunk<ComplexEvent>();
for (ComplexEvent complexEvent : eventList) {
complexEventChunk.add(cloneComplexEvent(complexEvent));
}
sendToCallBacks(complexEventChunk);
}
}
| apache-2.0 |