repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15
values |
|---|---|---|---|---|
smanvi-pivotal/geode | geode-core/src/main/java/org/apache/geode/distributed/internal/membership/gms/GMSMember.java | 15738 | /*
* 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.geode.distributed.internal.membership.gms;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.EOFException;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import org.jgroups.util.UUID;
import org.apache.geode.DataSerializer;
import org.apache.geode.distributed.DurableClientAttributes;
import org.apache.geode.distributed.internal.DistributionConfig;
import org.apache.geode.distributed.internal.membership.MemberAttributes;
import org.apache.geode.distributed.internal.membership.NetMember;
import org.apache.geode.internal.DataSerializableFixedID;
import org.apache.geode.internal.InternalDataSerializer;
import org.apache.geode.internal.Version;
import org.apache.geode.internal.i18n.LocalizedStrings;
/**
* This is the fundamental representation of a member of a GemFire distributed system.
*
* Unfortunately, this class serves two distinct functions. First, it is the fundamental element of
* membership in the GemFire distributed system. As such, it is used in enumerations and properly
* responds to hashing and equals() comparisons.
*
* Second, it is used as a cheap way of representing an address. This is unfortunate, because as a
* NetMember, it holds two separate port numbers: the "membership" descriptor as well as a direct
* communication channel.
*
*/
public class GMSMember implements NetMember, DataSerializableFixedID {
// whether to show UUID info in toString()
private static final boolean SHOW_UUIDS =
Boolean.getBoolean(DistributionConfig.GEMFIRE_PREFIX + "show_UUIDs");
private int udpPort = 0;
private boolean preferredForCoordinator;
private boolean networkPartitionDetectionEnabled;
private byte memberWeight;
private InetAddress inetAddr;
private int processId;
private byte vmKind;
private int vmViewId = -1;
private int directPort;
private String name;
private DurableClientAttributes durableClientAttributes;
private String[] groups;
private short versionOrdinal = Version.CURRENT_ORDINAL;
private long uuidLSBs;
private long uuidMSBs;
// Used only by Externalization
public GMSMember() {}
public MemberAttributes getAttributes() {
return new MemberAttributes(directPort, processId, vmKind, vmViewId, name, groups,
durableClientAttributes);
}
public void setAttributes(MemberAttributes p_attr) {
MemberAttributes attr = p_attr;
if (attr == null) {
attr = MemberAttributes.INVALID;
}
processId = attr.getVmPid();
vmKind = (byte) attr.getVmKind();
directPort = attr.getPort();
vmViewId = attr.getVmViewId();
name = attr.getName();
groups = attr.getGroups();
durableClientAttributes = attr.getDurableClientAttributes();
}
/**
* Create a CacheMember referring to the current host (as defined by the given string).
*
* @param i the hostname, must be for the current host
* @param p the membership listening port
*/
public GMSMember(String i, int p) {
udpPort = p;
try {
inetAddr = InetAddress.getByName(i);
} catch (UnknownHostException e) {
// oops
}
}
/**
* Create a CacheMember referring to the current host (as defined by the given string).
*
* @param i the hostname, must be for the current host
* @param p the membership listening port
* @param networkPartitionDetectionEnabled whether the member has network partition detection
* enabled
* @param preferredForCoordinator whether the member can be group coordinator
* @param version the member's version ordinal
* @param msbs - most significant bytes of UUID
* @param lsbs - least significant bytes of UUID
*/
public GMSMember(MemberAttributes attr, InetAddress i, int p,
boolean networkPartitionDetectionEnabled, boolean preferredForCoordinator, short version,
long msbs, long lsbs) {
setAttributes(attr);
this.inetAddr = i;
this.udpPort = p;
this.networkPartitionDetectionEnabled = networkPartitionDetectionEnabled;
this.preferredForCoordinator = preferredForCoordinator;
this.versionOrdinal = version;
this.uuidMSBs = msbs;
this.uuidLSBs = lsbs;
}
public GMSMember(InetAddress i, int p, short version, long msbs, long lsbs, int viewId) {
this.inetAddr = i;
this.udpPort = p;
this.versionOrdinal = version;
this.uuidMSBs = msbs;
this.uuidLSBs = lsbs;
this.vmViewId = viewId;
}
/**
* Clone a GMSMember
*
* @param other the member to create a copy of
*/
public GMSMember(GMSMember other) {
this.udpPort = other.udpPort;
this.preferredForCoordinator = other.preferredForCoordinator;
this.networkPartitionDetectionEnabled = other.networkPartitionDetectionEnabled;
this.memberWeight = other.memberWeight;
this.inetAddr = other.inetAddr;
this.processId = other.processId;
this.vmKind = other.vmKind;
this.vmViewId = other.vmViewId;
this.directPort = other.directPort;
this.name = other.name;
this.durableClientAttributes = other.durableClientAttributes;
this.groups = other.groups;
this.versionOrdinal = other.versionOrdinal;
this.uuidLSBs = other.uuidLSBs;
this.uuidMSBs = other.uuidMSBs;
}
public int getPort() {
return this.udpPort;
}
public boolean isMulticastAddress() {
return false; // ipAddr.isMulticastAddress();
}
public boolean preferredForCoordinator() {
return this.preferredForCoordinator;
}
public void setPreferredForCoordinator(boolean preferred) {
this.preferredForCoordinator = preferred;
}
public InetAddress getInetAddress() {
return this.inetAddr;
}
public short getVersionOrdinal() {
return this.versionOrdinal;
}
public void setVersionOrdinal(short versionOrdinal) {
this.versionOrdinal = versionOrdinal;
}
public void setUUID(UUID u) {
this.uuidLSBs = u.getLeastSignificantBits();
this.uuidMSBs = u.getMostSignificantBits();
}
/**
* return the jgroups logical address for this member, if it's been established
*/
public UUID getUUID() {
if (this.uuidLSBs == 0 && this.uuidMSBs == 0) {
return null;
}
return new UUID(this.uuidMSBs, this.uuidLSBs);
}
public long getUuidMSBs() {
return this.uuidMSBs;
}
public long getUuidLSBs() {
return this.uuidLSBs;
}
/*
* implements the java.lang.Comparable interface
*
* @see java.lang.Comparable
*
* @param o - the Object to be compared
*
* @return a negative integer, zero, or a positive integer as this object is less than, equal to,
* or greater than the specified object.
*
* @exception java.lang.ClassCastException - if the specified object's type prevents it from being
* compared to this Object.
*/
public int compareTo(NetMember o) {
if (o == this) {
return 0;
}
// obligatory type check
if (o == null || !(o instanceof GMSMember)) {
throw new ClassCastException(
LocalizedStrings.Member_MEMBERCOMPARETO_COMPARISON_BETWEEN_DIFFERENT_CLASSES
.toLocalizedString());
}
byte[] myAddr = inetAddr.getAddress();
GMSMember his = (GMSMember) o;
byte[] hisAddr = his.inetAddr.getAddress();
if (myAddr != hisAddr) {
for (int idx = 0; idx < myAddr.length; idx++) {
if (idx >= hisAddr.length) {
return 1;
} else if (myAddr[idx] > hisAddr[idx]) {
return 1;
} else if (myAddr[idx] < hisAddr[idx]) {
return -1;
}
}
// After checking both addresses we have only gone up to myAddr.length, their address could be
// longer
if (hisAddr.length > myAddr.length) {
return -1;
}
}
if (udpPort < his.udpPort)
return -1;
if (his.udpPort < udpPort)
return 1;
int result = 0;
// bug #41983, address of kill-9'd member is reused
// before it can be ejected from membership
if (this.vmViewId >= 0 && his.vmViewId >= 0) {
if (this.vmViewId < his.vmViewId) {
result = -1;
} else if (his.vmViewId < this.vmViewId) {
result = 1;
}
}
if (result == 0 && this.uuidMSBs != 0 && his.uuidMSBs != 0) {
if (this.uuidMSBs < his.uuidMSBs) {
result = -1;
} else if (his.uuidMSBs < this.uuidMSBs) {
result = 1;
} else if (this.uuidLSBs < his.uuidLSBs) {
result = -1;
} else if (his.uuidLSBs < this.uuidLSBs) {
result = 1;
}
}
return result;
}
@Override
public int compareAdditionalData(NetMember other) {
GMSMember his = (GMSMember) other;
int result = 0;
if (this.uuidMSBs != 0 && his.uuidMSBs != 0) {
if (this.uuidMSBs < his.uuidMSBs) {
result = -1;
} else if (his.uuidMSBs < this.uuidMSBs) {
result = 1;
} else if (this.uuidLSBs < his.uuidLSBs) {
result = -1;
} else if (his.uuidLSBs < this.uuidLSBs) {
result = 1;
}
}
return result;
}
@Override
public boolean equals(Object obj) {
// GemStone fix for 29125
if ((obj == null) || !(obj instanceof GMSMember)) {
return false;
}
return compareTo((GMSMember) obj) == 0;
}
@Override
public int hashCode() {
if (this.inetAddr == null) {
return this.udpPort;
}
return this.udpPort + inetAddr.hashCode();
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder(100);
String uuid = SHOW_UUIDS ? (";uuid=" + getUUID().toStringLong())
: ((this.uuidLSBs == 0 && this.uuidMSBs == 0) ? "; no uuid" : "; uuid set");
sb.append("GMSMember[addr=").append(inetAddr).append(";port=").append(udpPort)
.append(";processId=").append(processId).append(";name=").append(name).append(uuid)
.append("]");
return sb.toString();
}
public int getUdpPort() {
return udpPort;
}
public boolean isNetworkPartitionDetectionEnabled() {
return networkPartitionDetectionEnabled;
}
public byte getMemberWeight() {
return memberWeight;
}
public InetAddress getInetAddr() {
return inetAddr;
}
public int getProcessId() {
return processId;
}
public byte getVmKind() {
return vmKind;
}
public int getVmViewId() {
return vmViewId;
}
@Override
public void setVmViewId(int id) {
this.vmViewId = id;
}
public int getDirectPort() {
return directPort;
}
public String getName() {
return name;
}
public DurableClientAttributes getDurableClientAttributes() {
return durableClientAttributes;
}
public String[] getRoles() {
return groups;
}
public void setUdpPort(int udpPort) {
this.udpPort = udpPort;
}
public void setNetworkPartitionDetectionEnabled(boolean networkPartitionDetectionEnabled) {
this.networkPartitionDetectionEnabled = networkPartitionDetectionEnabled;
}
public void setMemberWeight(byte memberWeight) {
this.memberWeight = memberWeight;
}
public void setInetAddr(InetAddress inetAddr) {
this.inetAddr = inetAddr;
}
public void setProcessId(int processId) {
this.processId = processId;
}
public void setVmKind(int vmKind) {
this.vmKind = (byte) vmKind;
}
public void setVersion(Version v) {
this.versionOrdinal = v.ordinal();
}
public void setBirthViewId(int birthViewId) {
this.vmViewId = birthViewId;
}
public void setDirectPort(int directPort) {
this.directPort = directPort;
}
public void setName(String name) {
this.name = name;
}
public void setDurableClientAttributes(DurableClientAttributes durableClientAttributes) {
this.durableClientAttributes = durableClientAttributes;
}
@Override
public String[] getGroups() {
return groups;
}
public void setGroups(String[] groups) {
this.groups = groups;
}
public void setPort(int p) {
this.udpPort = p;
}
/**
* checks to see if this address has UUID information needed to send messages via JGroups
*/
public boolean hasUUID() {
return !(this.uuidLSBs == 0 && this.uuidMSBs == 0);
}
@Override
public Version[] getSerializationVersions() {
return null;
}
@Override
public int getDSFID() {
return GMSMEMBER;
}
static final int NPD_ENABLED_BIT = 0x01;
static final int PREFERRED_FOR_COORD_BIT = 0x02;
@Override
public void toData(DataOutput out) throws IOException {
writeEssentialData(out);
out.writeInt(directPort);
out.writeByte(memberWeight);
out.writeByte(vmKind);
out.writeInt(processId);
DataSerializer.writeString(name, out);
DataSerializer.writeStringArray(groups, out);
}
public void writeEssentialData(DataOutput out) throws IOException {
Version.writeOrdinal(out, this.versionOrdinal, true);
int flags = 0;
if (networkPartitionDetectionEnabled)
flags |= NPD_ENABLED_BIT;
if (preferredForCoordinator)
flags |= PREFERRED_FOR_COORD_BIT;
out.writeShort(flags);
DataSerializer.writeInetAddress(inetAddr, out);
out.writeInt(udpPort);
out.writeInt(vmViewId);
out.writeLong(uuidMSBs);
out.writeLong(uuidLSBs);
if (InternalDataSerializer.getVersionForDataStream(out).compareTo(Version.GEODE_120) >= 0) {
out.writeByte(vmKind);
}
}
@Override
public void fromData(DataInput in) throws IOException, ClassNotFoundException {
readEssentialData(in);
this.directPort = in.readInt();
this.memberWeight = in.readByte();
this.vmKind = in.readByte();
this.processId = in.readInt();
this.name = DataSerializer.readString(in);
this.groups = DataSerializer.readStringArray(in);
}
public void readEssentialData(DataInput in) throws IOException, ClassNotFoundException {
this.versionOrdinal = Version.readOrdinal(in);
int flags = in.readShort();
this.networkPartitionDetectionEnabled = (flags & NPD_ENABLED_BIT) != 0;
this.preferredForCoordinator = (flags & PREFERRED_FOR_COORD_BIT) != 0;
this.inetAddr = DataSerializer.readInetAddress(in);
this.udpPort = in.readInt();
this.vmViewId = in.readInt();
this.uuidMSBs = in.readLong();
this.uuidLSBs = in.readLong();
if (InternalDataSerializer.getVersionForDataStream(in).compareTo(Version.GEODE_120) >= 0) {
this.vmKind = in.readByte();
}
}
@Override
public boolean hasAdditionalData() {
return uuidMSBs != 0 || uuidLSBs != 0 || memberWeight != 0;
}
@Override
public void writeAdditionalData(DataOutput out) throws IOException {
out.writeLong(uuidMSBs);
out.writeLong(uuidLSBs);
out.write(memberWeight);
}
@Override
public void readAdditionalData(DataInput in) throws ClassNotFoundException, IOException {
try {
this.uuidMSBs = in.readLong();
this.uuidLSBs = in.readLong();
memberWeight = (byte) (in.readByte() & 0xFF);
} catch (EOFException e) {
// some IDs do not have UUID or membership weight information
}
}
}
| apache-2.0 |
terrancesnyder/oozie-hadoop2 | core/src/main/java/org/apache/oozie/store/StoreException.java | 1485 | /**
* 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.oozie.store;
import org.apache.oozie.XException;
import org.apache.oozie.ErrorCode;
/**
* Exception thrown by the {@link WorkflowStore}
*/
public class StoreException extends XException {
/**
* Create an store exception from a XException.
*
* @param cause the XException cause.
*/
public StoreException(XException cause) {
super(cause);
}
/**
* Create a store exception.
*
* @param errorCode error code.
* @param params parameters for the error code message template.
*/
public StoreException(ErrorCode errorCode, Object... params) {
super(errorCode, params);
}
}
| apache-2.0 |
lyubomyr-shaydariv/ext-gson | src/main/java/lsh/ext/gson/ext/json/JsonApiModule.java | 1504 | package lsh.ext.gson.ext.json;
import java.util.Arrays;
import java.util.Collections;
import com.google.gson.TypeAdapterFactory;
import lombok.AccessLevel;
import lombok.RequiredArgsConstructor;
import lsh.ext.gson.adapters.AbstractModule;
import lsh.ext.gson.adapters.IModule;
/**
* Implements a Java JSON API module registering the following type adapter factories:
*
* <ul>
* <li>{@link JsonValueTypeAdapterFactory}</li>
* </ul>
*
* @author Lyubomyr Shaydariv
*/
public final class JsonApiModule
extends AbstractModule {
private static final IModule instance = build()
.done();
private JsonApiModule(final Iterable<? extends TypeAdapterFactory> typeAdapterFactories) {
super("Java JSON API", typeAdapterFactories);
}
/**
* @return The default instance of the module with the default type adapter factories settings.
*/
public static IModule getInstance() {
return instance;
}
/**
* @return A builder to build a new instance of the module.
*/
public static Builder build() {
return new Builder();
}
/**
* A builder to configure a new module instance.
*/
@RequiredArgsConstructor(access = AccessLevel.PRIVATE)
public static final class Builder {
/**
* @return A new module instance.
*/
public IModule done() {
final Iterable<? extends TypeAdapterFactory> typeAdapterFactories = Collections.unmodifiableList(Arrays.asList(
JsonValueTypeAdapterFactory.getInstance()
));
return new JsonApiModule(typeAdapterFactories);
}
}
}
| apache-2.0 |
gbif/checklistbank | checklistbank-mybatis-service/src/main/java/org/gbif/checklistbank/service/mybatis/persistence/mapper/NubRelMapper.java | 1163 | /*
* 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.gbif.checklistbank.service.mybatis.persistence.mapper;
import org.gbif.checklistbank.model.NubMapping;
import java.util.UUID;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.cursor.Cursor;
import org.springframework.stereotype.Repository;
@Repository
public interface NubRelMapper {
void insert(@Param("uuid") UUID datasetKey, @Param("usageKey") int usageKey, @Param("nubKey") int nubKey);
void delete(@Param("usageKey") int usageKey);
void deleteByDataset(@Param("uuid") UUID datasetKey);
Cursor<NubMapping> process(@Param("uuid") UUID datasetKey);
}
| apache-2.0 |
artikcloud/artikcloud-java | src/main/java/cloud/artik/model/UploadStatusEnvelope.java | 2078 | /*
* ARTIK Cloud API
* No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
*
* OpenAPI spec version: 2.0.0
*
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
package cloud.artik.model;
import java.util.Objects;
import com.google.gson.annotations.SerializedName;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
/**
*
*/
@ApiModel(description = "")
public class UploadStatusEnvelope {
@SerializedName("status")
private String status = null;
public UploadStatusEnvelope status(String status) {
this.status = status;
return this;
}
/**
* The uploaded CSV status, like 'Processing', 'Completed' or 'Failed'
* @return status
**/
@ApiModelProperty(example = "null", value = "The uploaded CSV status, like 'Processing', 'Completed' or 'Failed'")
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
UploadStatusEnvelope uploadStatusEnvelope = (UploadStatusEnvelope) o;
return Objects.equals(this.status, uploadStatusEnvelope.status);
}
@Override
public int hashCode() {
return Objects.hash(status);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class UploadStatusEnvelope {\n");
sb.append(" status: ").append(toIndentedString(status)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
| apache-2.0 |
scarabsoft/jrest | jrest-api/src/main/java/com/scarabsoft/jrest/Headers.java | 389 | package com.scarabsoft.jrest;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(value = {ElementType.METHOD, ElementType.TYPE, ElementType.PARAMETER, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface Headers {
Header[] value();
}
| apache-2.0 |
OpenConext/OpenConext-authorization-server | src/test/java/authzserver/AuthzServerApplicationTest.java | 6650 | package authzserver;
import com.github.tomakehurst.wiremock.junit.WireMockRule;
import com.github.tomakehurst.wiremock.verification.LoggedRequest;
import org.apache.commons.codec.binary.Base64;
import org.junit.Rule;
import org.junit.Test;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import static authzserver.shibboleth.ShibbolethPreAuthenticatedProcessingFilter.SHIB_AUTHENTICATING_AUTHORITY;
import static authzserver.shibboleth.ShibbolethPreAuthenticatedProcessingFilter.SHIB_DISPLAY_NAME;
import static authzserver.shibboleth.ShibbolethPreAuthenticatedProcessingFilter.SHIB_EDU_PERSON_PRINCIPAL_NAME;
import static authzserver.shibboleth.ShibbolethPreAuthenticatedProcessingFilter.SHIB_EMAIL;
import static authzserver.shibboleth.ShibbolethPreAuthenticatedProcessingFilter.SHIB_NAME_ID_HEADER_NAME;
import static authzserver.shibboleth.ShibbolethPreAuthenticatedProcessingFilter
.SHIB_SCHAC_HOME_ORGANIZATION_HEADER_NAME;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.findAll;
import static com.github.tomakehurst.wiremock.client.WireMock.get;
import static com.github.tomakehurst.wiremock.client.WireMock.getRequestedFor;
import static com.github.tomakehurst.wiremock.client.WireMock.matching;
import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
public class AuthzServerApplicationTest extends AbstractIntegrationTest{
private String callback = "http://localhost:8889/callback";
@Rule
public WireMockRule wireMockRule = new WireMockRule(8889);
@Test
public void test_skip_confirmation_autoapprove_true() throws InterruptedException {
String serverUrl = "http://localhost:" + this.port;
HttpHeaders headers = getShibHttpHeaders();
wireMockRule.stubFor(get(urlMatching("/callback.*")).withQueryParam("code", matching(".*")).willReturn(aResponse().withStatus(200)));
ResponseEntity<String> response = restTemplate.exchange(serverUrl + "/oauth/authorize?response_type=code&client_id=test_client&scope=read&redirect_uri={callback}",
HttpMethod.GET, new HttpEntity<>(headers), String.class, Collections.singletonMap("callback", callback));
assertEquals(200, response.getStatusCode().value());
List<LoggedRequest> requests = findAll(getRequestedFor(urlMatching("/callback.*")));
assertEquals(1, requests.size());
String authorizationCode = requests.get(0).queryParameter("code").firstValue();
addAuthorizationHeaders(headers);
MultiValueMap<String, String> bodyMap = getAuthorizationCodeFormParameters(authorizationCode);
Map body = restTemplate.exchange(serverUrl + "/oauth/token", HttpMethod.POST, new HttpEntity<>(bodyMap, headers), Map.class).getBody();
assertEquals("bearer", body.get("token_type"));
String accessToken = (String) body.get("access_token");
assertNotNull(accessToken);
// Now for the completeness of the scenario retrieve the Principal (e.g. impersonating a Resource Server) using the accessCode
MultiValueMap<String, String> formData = new LinkedMultiValueMap<>();
formData.add("token", accessToken);
Map principal = restTemplate.exchange(serverUrl + "/oauth/check_token", HttpMethod.POST, new HttpEntity<>(formData, headers), Map.class).getBody();
assertEquals("urn:collab:person:example.com:mock-user", principal.get("user_name"));
assertEquals("admin@example.com", principal.get("email"));
assertEquals("admin@example.com", principal.get("eduPersonPrincipalName"));
assertEquals("John Doe", principal.get("displayName"));
//resourceIds
assertEquals(Arrays.asList("groups", "whatever" ), principal.get("aud"));
}
@Test
public void testErrorPage() {
String url = "http://localhost:" + this.port + "/bogus";
Map map = testRestTemplate.getForObject(url, Map.class);
assertEquals(500, map.get("status"));
HttpHeaders headers = getShibHttpHeaders();
ResponseEntity<Map> response = testRestTemplate.exchange(url, HttpMethod.GET, new HttpEntity<>(headers), Map.class);
assertEquals(404, response.getBody().get("status"));
}
@Test
public void testOpenRedirectResourceServer() throws Exception {
HttpHeaders headers = getShibHttpHeaders();
String serverUrl = "http://localhost:" + this.port + "/oauth/authorize?response_type=code&client_id=test_resource_server&scope=read&redirect_uri=https://google.com";
ResponseEntity<String> response = testRestTemplate.exchange(serverUrl, HttpMethod.GET, new HttpEntity<>(headers), String.class, callback);
assertEquals(400, response.getStatusCode().value());
String body = response.getBody();
assertTrue(body.contains("A redirect_uri can only be used by implicit or authorization_code grant types"));
}
private MultiValueMap<String, String> getAuthorizationCodeFormParameters(String authorizationCode) {
MultiValueMap<String, String> bodyMap = new LinkedMultiValueMap<>();
bodyMap.add("grant_type", "authorization_code");
bodyMap.add("code", authorizationCode);
bodyMap.add("redirect_uri", callback);
return bodyMap;
}
private void addAuthorizationHeaders(HttpHeaders headers) {
String authenticationCredentials = "Basic " + new String(Base64.encodeBase64(new String("test_client" + ":" + "secret").getBytes(Charset.forName("UTF-8"))));
headers.add("Authorization", authenticationCredentials);
headers.add("Content-Type", "application/x-www-form-urlencoded");
headers.add("Accept", "application/json");
}
private HttpHeaders getShibHttpHeaders() {
HttpHeaders headers = new HttpHeaders();
headers.add(SHIB_NAME_ID_HEADER_NAME, "urn:collab:person:example.com:mock-user");
headers.add(SHIB_AUTHENTICATING_AUTHORITY, "my-university");
headers.add(SHIB_SCHAC_HOME_ORGANIZATION_HEADER_NAME, "example.com");
headers.add(SHIB_EMAIL, "admin@example.com");
headers.add(SHIB_EDU_PERSON_PRINCIPAL_NAME, "admin@example.com");
headers.add(SHIB_DISPLAY_NAME, "John Doe");
return headers;
}
}
| apache-2.0 |
jentfoo/aws-sdk-java | aws-java-sdk-mediaconvert/src/main/java/com/amazonaws/services/mediaconvert/model/ProresSlowPal.java | 1901 | /*
* Copyright 2014-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.mediaconvert.model;
import javax.annotation.Generated;
/**
* Enables Slow PAL rate conversion. 23.976fps and 24fps input is relabeled as 25fps, and audio is sped up
* correspondingly.
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public enum ProresSlowPal {
DISABLED("DISABLED"),
ENABLED("ENABLED");
private String value;
private ProresSlowPal(String value) {
this.value = value;
}
@Override
public String toString() {
return this.value;
}
/**
* Use this in place of valueOf.
*
* @param value
* real value
* @return ProresSlowPal corresponding to the value
*
* @throws IllegalArgumentException
* If the specified value does not map to one of the known values in this enum.
*/
public static ProresSlowPal fromValue(String value) {
if (value == null || "".equals(value)) {
throw new IllegalArgumentException("Value cannot be null or empty!");
}
for (ProresSlowPal enumEntry : ProresSlowPal.values()) {
if (enumEntry.toString().equals(value)) {
return enumEntry;
}
}
throw new IllegalArgumentException("Cannot create enum from " + value + " value!");
}
}
| apache-2.0 |
goodwinnk/intellij-community | java/java-impl/src/com/intellij/codeInspection/java19api/Java9CollectionFactoryInspection.java | 20325 | /*
* Copyright 2000-2017 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.codeInspection.java19api;
import com.intellij.codeInspection.*;
import com.intellij.codeInspection.ex.BaseLocalInspectionTool;
import com.intellij.codeInspection.ui.MultipleCheckboxOptionsPanel;
import com.intellij.openapi.project.Project;
import com.intellij.profile.codeInspection.InspectionProjectProfileManager;
import com.intellij.psi.*;
import com.intellij.psi.controlFlow.DefUseUtil;
import com.intellij.psi.impl.PsiDiamondTypeUtil;
import com.intellij.psi.search.searches.ReferencesSearch;
import com.intellij.psi.util.InheritanceUtil;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.PsiUtil;
import com.intellij.util.containers.ContainerUtil;
import com.siyeh.ig.callMatcher.CallMapper;
import com.siyeh.ig.callMatcher.CallMatcher;
import com.siyeh.ig.psiutils.*;
import one.util.streamex.IntStreamEx;
import one.util.streamex.StreamEx;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.util.*;
import java.util.function.Function;
import static com.intellij.psi.CommonClassNames.*;
import static com.intellij.util.ObjectUtils.tryCast;
import static com.siyeh.ig.callMatcher.CallMatcher.instanceCall;
import static com.siyeh.ig.callMatcher.CallMatcher.staticCall;
public class Java9CollectionFactoryInspection extends BaseLocalInspectionTool {
private static final CallMatcher UNMODIFIABLE_SET = staticCall(JAVA_UTIL_COLLECTIONS, "unmodifiableSet").parameterCount(1);
private static final CallMatcher UNMODIFIABLE_MAP = staticCall(JAVA_UTIL_COLLECTIONS, "unmodifiableMap").parameterCount(1);
private static final CallMatcher UNMODIFIABLE_LIST = staticCall(JAVA_UTIL_COLLECTIONS, "unmodifiableList").parameterCount(1);
private static final CallMatcher ARRAYS_AS_LIST = staticCall(JAVA_UTIL_ARRAYS, "asList");
private static final CallMatcher COLLECTION_ADD = instanceCall(JAVA_UTIL_COLLECTION, "add").parameterCount(1);
private static final CallMatcher MAP_PUT = instanceCall(JAVA_UTIL_MAP, "put").parameterCount(2);
private static final CallMatcher STREAM_COLLECT = instanceCall(JAVA_UTIL_STREAM_STREAM, "collect").parameterCount(1);
private static final CallMatcher STREAM_OF = staticCall(JAVA_UTIL_STREAM_STREAM, "of");
private static final CallMatcher COLLECTORS_TO_SET = staticCall(JAVA_UTIL_STREAM_COLLECTORS, "toSet").parameterCount(0);
private static final CallMatcher COLLECTORS_TO_LIST = staticCall(JAVA_UTIL_STREAM_COLLECTORS, "toList").parameterCount(0);
private static final CallMapper<PrepopulatedCollectionModel> MAPPER = new CallMapper<PrepopulatedCollectionModel>()
.register(UNMODIFIABLE_SET, call -> PrepopulatedCollectionModel.fromSet(call.getArgumentList().getExpressions()[0]))
.register(UNMODIFIABLE_MAP, call -> PrepopulatedCollectionModel.fromMap(call.getArgumentList().getExpressions()[0]))
.register(UNMODIFIABLE_LIST, call -> PrepopulatedCollectionModel.fromList(call.getArgumentList().getExpressions()[0]));
public boolean IGNORE_NON_CONSTANT = false;
public boolean SUGGEST_MAP_OF_ENTRIES = true;
@Nullable
@Override
public JComponent createOptionsPanel() {
MultipleCheckboxOptionsPanel panel = new MultipleCheckboxOptionsPanel(this);
panel.addCheckbox(InspectionsBundle.message("inspection.collection.factories.option.ignore.non.constant"), "IGNORE_NON_CONSTANT");
panel.addCheckbox(InspectionsBundle.message("inspection.collection.factories.option.suggest.ofentries"), "SUGGEST_MAP_OF_ENTRIES");
return panel;
}
@NotNull
@Override
public PsiElementVisitor buildVisitor(@NotNull ProblemsHolder holder, boolean isOnTheFly) {
if (!PsiUtil.isLanguageLevel9OrHigher(holder.getFile())) {
return PsiElementVisitor.EMPTY_VISITOR;
}
return new JavaElementVisitor() {
@Override
public void visitMethodCallExpression(PsiMethodCallExpression call) {
PrepopulatedCollectionModel model = MAPPER.mapFirst(call);
if (model != null && model.isValid(SUGGEST_MAP_OF_ENTRIES)) {
ProblemHighlightType type = model.myConstantContent || !IGNORE_NON_CONSTANT
? ProblemHighlightType.GENERIC_ERROR_OR_WARNING
: ProblemHighlightType.INFORMATION;
if (type == ProblemHighlightType.INFORMATION && !isOnTheFly) return;
boolean wholeStatement = isOnTheFly &&
(type == ProblemHighlightType.INFORMATION ||
InspectionProjectProfileManager.isInformationLevel(getShortName(), call));
PsiElement element = wholeStatement ? call : call.getMethodExpression().getReferenceNameElement();
if(element != null) {
String replacementMethod = model.hasTooManyMapEntries() ? "ofEntries" : model.myCopy ? "copyOf" : "of";
String fixMessage = InspectionsBundle.message("inspection.collection.factories.fix.name", model.myType, replacementMethod);
String inspectionMessage =
InspectionsBundle.message("inspection.collection.factories.message", model.myType, replacementMethod);
holder.registerProblem(element, inspectionMessage, type, new ReplaceWithCollectionFactoryFix(fixMessage));
}
}
}
};
}
static class PrepopulatedCollectionModel {
final List<PsiExpression> myContent;
final List<PsiElement> myElementsToDelete;
final String myType;
final boolean myCopy;
final boolean myConstantContent;
final boolean myRepeatingKeys;
final boolean myHasNulls;
PrepopulatedCollectionModel(List<PsiExpression> content, List<PsiElement> delete, String type) {
this(content, delete, type, false);
}
PrepopulatedCollectionModel(List<PsiExpression> content, List<PsiElement> delete, String type, boolean copy) {
myContent = content;
myElementsToDelete = delete;
myType = type;
myCopy = copy;
Map<PsiExpression, List<Object>> constants = StreamEx.of(myContent)
.cross(ExpressionUtils::nonStructuralChildren).mapValues(ExpressionUtils::computeConstantExpression).distinct().grouping();
myConstantContent = !copy && StreamEx.ofValues(constants).flatCollection(Function.identity()).allMatch(Objects::nonNull);
myRepeatingKeys = keyExpressions().flatCollection(constants::get).nonNull().distinct(2).findAny().isPresent();
myHasNulls = StreamEx.of(myContent).flatMap(ExpressionUtils::nonStructuralChildren).map(PsiExpression::getType).has(PsiType.NULL);
}
boolean isValid(boolean suggestMapOfEntries) {
return !myHasNulls && !myRepeatingKeys && (suggestMapOfEntries || !hasTooManyMapEntries());
}
private boolean hasTooManyMapEntries() {
return myType.equals("Map") && myContent.size() > 20;
}
private StreamEx<PsiExpression> keyExpressions() {
switch (myType) {
case "Set":
return StreamEx.of(myContent);
case "Map":
return IntStreamEx.range(0, myContent.size(), 2).elements(myContent);
default:
return StreamEx.empty();
}
}
public static PrepopulatedCollectionModel fromList(PsiExpression listDefinition) {
listDefinition = PsiUtil.skipParenthesizedExprDown(listDefinition);
if(listDefinition instanceof PsiMethodCallExpression) {
PsiMethodCallExpression call = (PsiMethodCallExpression)listDefinition;
if (ARRAYS_AS_LIST.test(call)) {
return new PrepopulatedCollectionModel(Arrays.asList(call.getArgumentList().getExpressions()), Collections.emptyList(), "List");
}
return fromCollect(call, "List", COLLECTORS_TO_LIST);
}
if(listDefinition instanceof PsiNewExpression) {
return fromNewExpression((PsiNewExpression)listDefinition, "List", JAVA_UTIL_ARRAY_LIST);
}
if (listDefinition instanceof PsiReferenceExpression) {
return fromVariable((PsiReferenceExpression)listDefinition, "List", JAVA_UTIL_ARRAY_LIST, COLLECTION_ADD);
}
return null;
}
public static PrepopulatedCollectionModel fromSet(PsiExpression setDefinition) {
setDefinition = PsiUtil.skipParenthesizedExprDown(setDefinition);
if (setDefinition instanceof PsiMethodCallExpression) {
return fromCollect((PsiMethodCallExpression)setDefinition, "Set", COLLECTORS_TO_SET);
}
if (setDefinition instanceof PsiNewExpression) {
return fromNewExpression((PsiNewExpression)setDefinition, "Set", JAVA_UTIL_HASH_SET);
}
if (setDefinition instanceof PsiReferenceExpression) {
return fromVariable((PsiReferenceExpression)setDefinition, "Set", JAVA_UTIL_HASH_SET, COLLECTION_ADD);
}
return null;
}
public static PrepopulatedCollectionModel fromMap(PsiExpression mapDefinition) {
mapDefinition = PsiUtil.skipParenthesizedExprDown(mapDefinition);
if (mapDefinition instanceof PsiReferenceExpression) {
return fromVariable((PsiReferenceExpression)mapDefinition, "Map", JAVA_UTIL_HASH_MAP, MAP_PUT);
}
if (mapDefinition instanceof PsiNewExpression) {
PsiNewExpression newExpression = (PsiNewExpression)mapDefinition;
PsiAnonymousClass anonymousClass = newExpression.getAnonymousClass();
PsiExpressionList argumentList = newExpression.getArgumentList();
if (argumentList != null) {
PsiExpression[] args = argumentList.getExpressions();
PsiJavaCodeReferenceElement classReference = newExpression.getClassReference();
if (classReference != null && PsiUtil.isLanguageLevel10OrHigher(mapDefinition) &&
JAVA_UTIL_HASH_MAP.equals(classReference.getQualifiedName()) && args.length == 1) {
PsiExpression arg = PsiUtil.skipParenthesizedExprDown(args[0]);
if (arg != null) {
PsiType sourceType = arg.getType();
PsiType targetType = newExpression.getType();
if (targetType != null && sourceType != null && sourceType.isAssignableFrom(targetType)) {
return new PrepopulatedCollectionModel(Collections.singletonList(arg), Collections.emptyList(), "Map", true);
}
}
}
if (anonymousClass != null && argumentList.isEmpty()) {
PsiJavaCodeReferenceElement baseClassReference = anonymousClass.getBaseClassReference();
if (JAVA_UTIL_HASH_MAP.equals(baseClassReference.getQualifiedName())) {
return fromInitializer(anonymousClass, "Map", MAP_PUT);
}
}
}
}
return null;
}
@Nullable
private static PrepopulatedCollectionModel fromCollect(PsiMethodCallExpression call, String typeName, CallMatcher collector) {
if (STREAM_COLLECT.test(call) && collector.matches(call.getArgumentList().getExpressions()[0])) {
PsiMethodCallExpression qualifier = MethodCallUtils.getQualifierMethodCall(call);
if (STREAM_OF.matches(qualifier)) {
return new PrepopulatedCollectionModel(Arrays.asList(qualifier.getArgumentList().getExpressions()), Collections.emptyList(),
typeName);
}
}
return null;
}
@Nullable
private static PrepopulatedCollectionModel fromVariable(PsiReferenceExpression expression,
String typeName, String collectionClass, CallMatcher addMethod) {
PsiLocalVariable variable = tryCast(expression.resolve(), PsiLocalVariable.class);
if (variable == null) return null;
PsiCodeBlock block = PsiTreeUtil.getParentOfType(variable, PsiCodeBlock.class);
PsiDeclarationStatement declaration = PsiTreeUtil.getParentOfType(variable, PsiDeclarationStatement.class);
if (block == null || declaration == null) return null;
PsiElement[] defs = DefUseUtil.getDefs(block, variable, expression);
if (defs.length == 1 && defs[0] == variable) {
PsiExpression initializer = variable.getInitializer();
if (!ConstructionUtils.isEmptyCollectionInitializer(initializer)) return null;
PsiClassType type = tryCast(initializer.getType(), PsiClassType.class);
if (type == null || !type.rawType().equalsToText(collectionClass)) return null;
Set<PsiElement> refs = ContainerUtil.set(DefUseUtil.getRefs(block, variable, initializer));
refs.remove(expression);
PsiStatement cur = declaration;
List<PsiExpression> contents = new ArrayList<>();
List<PsiElement> elementsToRemove = new ArrayList<>();
elementsToRemove.add(initializer);
while (true) {
cur = tryCast(PsiTreeUtil.skipWhitespacesAndCommentsForward(cur), PsiStatement.class);
if (PsiTreeUtil.isAncestor(cur, expression, false)) break;
if (!(cur instanceof PsiExpressionStatement)) return null;
PsiMethodCallExpression call = tryCast(((PsiExpressionStatement)cur).getExpression(), PsiMethodCallExpression.class);
if (!addMethod.test(call)) return null;
if (!refs.remove(call.getMethodExpression().getQualifierExpression())) return null;
contents.addAll(Arrays.asList(call.getArgumentList().getExpressions()));
elementsToRemove.add(cur);
}
if (!refs.isEmpty()) return null;
return new PrepopulatedCollectionModel(contents, elementsToRemove, typeName);
}
return null;
}
@Nullable
private static PrepopulatedCollectionModel fromNewExpression(PsiNewExpression newExpression, String type, String className) {
PsiExpressionList argumentList = newExpression.getArgumentList();
if (argumentList != null) {
PsiExpression[] args = argumentList.getExpressions();
PsiJavaCodeReferenceElement classReference = newExpression.getClassReference();
if (classReference != null && className.equals(classReference.getQualifiedName())) {
return fromCopyConstructor(args, type);
}
PsiAnonymousClass anonymousClass = newExpression.getAnonymousClass();
if (anonymousClass != null && args.length == 0) {
PsiJavaCodeReferenceElement baseClassReference = anonymousClass.getBaseClassReference();
if (className.equals(baseClassReference.getQualifiedName())) {
return fromInitializer(anonymousClass, type, COLLECTION_ADD);
}
}
}
return null;
}
@Nullable
private static PrepopulatedCollectionModel fromCopyConstructor(PsiExpression[] args, String type) {
if (args.length == 1) {
PsiExpression arg = PsiUtil.skipParenthesizedExprDown(args[0]);
PsiMethodCallExpression call = tryCast(arg, PsiMethodCallExpression.class);
if (ARRAYS_AS_LIST.test(call)) {
return new PrepopulatedCollectionModel(Arrays.asList(call.getArgumentList().getExpressions()), Collections.emptyList(), type);
}
if(arg != null && PsiUtil.isLanguageLevel10OrHigher(arg) && InheritanceUtil.isInheritor(arg.getType(), JAVA_UTIL_COLLECTION)) {
return new PrepopulatedCollectionModel(Collections.singletonList(arg), Collections.emptyList(), type, true);
}
}
return null;
}
@Nullable
private static PrepopulatedCollectionModel fromInitializer(PsiAnonymousClass anonymousClass, String type, CallMatcher addMethod) {
PsiClassInitializer initializer = ClassUtils.getDoubleBraceInitializer(anonymousClass);
if(initializer != null) {
List<PsiExpression> contents = new ArrayList<>();
for(PsiStatement statement : initializer.getBody().getStatements()) {
if(!(statement instanceof PsiExpressionStatement)) return null;
PsiMethodCallExpression call = tryCast(((PsiExpressionStatement)statement).getExpression(), PsiMethodCallExpression.class);
if(!addMethod.test(call)) return null;
PsiExpression qualifier = call.getMethodExpression().getQualifierExpression();
if(qualifier != null && !qualifier.getText().equals("this")) return null;
contents.addAll(Arrays.asList(call.getArgumentList().getExpressions()));
}
return new PrepopulatedCollectionModel(contents, Collections.emptyList(), type);
}
return null;
}
}
private static class ReplaceWithCollectionFactoryFix implements LocalQuickFix {
private final String myMessage;
ReplaceWithCollectionFactoryFix(String message) {
myMessage = message;
}
@Nls
@NotNull
@Override
public String getName() {
return myMessage;
}
@Nls
@NotNull
@Override
public String getFamilyName() {
return InspectionsBundle.message("inspection.collection.factories.fix.family.name");
}
@Override
public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) {
PsiMethodCallExpression call = PsiTreeUtil.getParentOfType(descriptor.getStartElement(), PsiMethodCallExpression.class, false);
if(call == null) return;
PrepopulatedCollectionModel model = MAPPER.mapFirst(call);
if(model == null) return;
String typeArgument = getTypeArguments(call.getType(), model.myType);
CommentTracker ct = new CommentTracker();
String replacementText;
if (model.myCopy) {
assert model.myContent.size() == 1;
replacementText = "java.util." + model.myType + "." + typeArgument + "copyOf(" + model.myContent.get(0).getText() + ")";
}
else if (model.hasTooManyMapEntries()) {
replacementText = StreamEx.ofSubLists(model.myContent, 2)
.prepend(Collections.<PsiExpression>emptyList())
.pairMap((prev, next) -> {
String prevComment = prev.isEmpty() ? "" : CommentTracker.commentsBetween(prev.get(1), next.get(0));
String midComment = CommentTracker.commentsBetween(next.get(0), next.get(1));
return prevComment + "java.util.Map.entry(" + ct.text(next.get(0)) + "," + midComment + ct.text(next.get(1)) + ")";
})
.joining(",", "java.util.Map." + typeArgument + "ofEntries(", ")");
}
else {
replacementText = StreamEx.of(model.myContent)
.prepend((PsiExpression)null)
.pairMap((prev, next) -> (prev == null ? "" : CommentTracker.commentsBetween(prev, next)) + ct.text(next))
.joining(",", "java.util." + model.myType + "." + typeArgument + "of(", ")");
}
List<PsiLocalVariable> vars =
StreamEx.of(model.myElementsToDelete).map(PsiElement::getParent).select(PsiLocalVariable.class).toList();
model.myElementsToDelete.forEach(ct::delete);
PsiElement replacement = ct.replaceAndRestoreComments(call, replacementText);
vars.stream().filter(var -> ReferencesSearch.search(var).findFirst() == null).forEach(PsiElement::delete);
PsiDiamondTypeUtil.removeRedundantTypeArguments(replacement);
}
@NotNull
private static String getTypeArguments(PsiType type, String typeName) {
if (typeName.equals("Map")) {
PsiType keyType = PsiUtil.substituteTypeParameter(type, JAVA_UTIL_MAP, 0, false);
PsiType valueType = PsiUtil.substituteTypeParameter(type, JAVA_UTIL_MAP, 1, false);
if (keyType != null && valueType != null) {
return "<" + keyType.getCanonicalText() + "," + valueType.getCanonicalText() + ">";
}
}
else {
PsiType elementType = PsiUtil.substituteTypeParameter(type, JAVA_UTIL_COLLECTION, 0, false);
if (elementType != null) {
return "<" + elementType.getCanonicalText() + ">";
}
}
return "";
}
}
}
| apache-2.0 |
wsad1239655/- | src/mp3fragment/NetFragment.java | 6538 | package mp3fragment;
import java.io.File;
import java.io.InputStream;
import java.io.Serializable;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import com.example.mp3player.MainActivity;
import com.example.mp3player.R;
import adapter.SearchResultListAdapter;
import android.app.Fragment;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;
import model.AppConstant;
import model.Mp3Info;
import utils.FileUtils;
import utils.ImageUtils;
import utils.OnLoadSearchFinishListener;
import utils.SearchUtils;
public class NetFragment extends Fragment{
private static View view;
private ListView lvSearchReasult;
private List<Mp3Info> listSearchResult;
private ProgressDialog dialog;
private MainActivity activity;
private ImageButton playButton;//²¥·Å
private TextView musicTitle;//¸èÃû
private ImageView musicAblum;//ר¼
private ImageView playerMusicAlbum;//²¥·Å½çÃæ×¨¼´óͼ
public static final String NET_MUSIC = "com.example.action.NET_MUSIC";//ÍøÂçÒôÀÖ
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// TODO Auto-generated method stub
view = inflater.inflate(R.layout.net_fragment, container, false);
//½ÓÊÕMainActivity
activity = (MainActivity)getActivity();
ImageUtils.initImageLoader(activity);// ImageLoader³õʼ»¯
init();
//»ñÈ¡¸¸¿Ø¼þ
musicTitle = (TextView)activity.findViewById(R.id.music_title);
playButton = (ImageButton)activity.findViewById(R.id.play_music);
musicAblum = (ImageView)activity.findViewById(R.id.music_album);
return view;
}
//ËÑË÷³õʼ»¯
private void init() {
listSearchResult = new ArrayList<Mp3Info>();
dialog = new ProgressDialog(activity);
dialog.setTitle("¼ÓÔØÖС£¡£¡£");
lvSearchReasult = (ListView)view.findViewById(R.id.lv_search_list);
Button btSearch = (Button)view.findViewById(R.id.bt_online_search);
final EditText edtKey = (EditText)view.findViewById(R.id.edt_search);
btSearch.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
dialog.show();// ½øÈë¼ÓÔØ×´Ì¬£¬ÏÔʾ½ø¶ÈÌõ
//Òþ²ØÈí¼üÅÌ
InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
new Thread(new Runnable() {
//ÊäÈëÎÄ×Ö£¬µÃµ½ËÑË÷½á¹û£¬jsoup»ñÈ¡¸èÇúID£¬Í¨¹ýID»ñÈ¡¸èÇúÐÅÏ¢£¬½«ÐÅÏ¢·ÅÈëmusicList
@Override
public void run() {
SearchUtils.getIds(edtKey.getText().toString(),
new OnLoadSearchFinishListener() {
@Override
public void onLoadSucess(
List<Mp3Info> musicList) {
dialog.dismiss();// ¼ÓÔØÍê³É£¬È¡Ïû½ø¶ÈÌõ
Message msg = new Message();
msg.what = 0;
mHandler.sendMessage(msg);
listSearchResult = musicList;
}
@Override
public void onLoadFiler() {
dialog.dismiss();// ¼ÓÔØÊ§°Ü£¬È¡Ïû½ø¶ÈÌõ
Toast.makeText(activity,
"¼ÓÔØÊ§°Ü", Toast.LENGTH_SHORT)
.show();
}
});
}
}).start();
}
});
//¼àÌýÁбí
lvSearchReasult.setOnItemClickListener(new LvSearchReasultListener());
}
private class LvSearchReasultListener implements OnItemClickListener{
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
play(position);
String url = listSearchResult.get(position).getLrcUrl();
String name = listSearchResult.get(position).getTitle();
DownloadLrc downloadLrc = new DownloadLrc(url,name);
Thread thread = new Thread(downloadLrc);
thread.start();
//·¢Ë͹㲥£¬½«µÃµ½µÄÒôÀÖÁбíËÑË÷½á¹ûÓëר¼·¢Ë͵½Ïß³Ì
Intent intent2 = new Intent();
intent2.setAction(NET_MUSIC);
intent2.putExtra("listSearchResult", (Serializable)listSearchResult);
intent2.putExtra("listPosition", position);
intent2.putExtra("albumUrl", listSearchResult.get(position).getBigAlumUrl());
activity.sendBroadcast(intent2);
}
}
class DownloadLrc implements Runnable{
private String url;
private String fileName;
public DownloadLrc(String url,String fileName) {
this.url = url;
this.fileName = fileName;
}
@Override
public void run() {
//ÏÂÔØ¸è´Ê
InputStream inputStream = null;
try {
FileUtils fileUtils = new FileUtils();
URL url1 = new URL(url);
HttpURLConnection urlConn = (HttpURLConnection)url1.openConnection();
inputStream = urlConn.getInputStream();
File resultFile = fileUtils.write2SDFromInput("/Download", fileName + ".lrc", inputStream);
} catch (Exception e) {
e.printStackTrace();
}
finally{
try {
inputStream.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
}
//²¥·Å
public void play(int position){
Mp3Info mp3Info = listSearchResult.get(position);
//¸ü¸Äͼ±ê
playButton.setImageResource(R.drawable.pause);
musicTitle.setText(mp3Info.getTitle());
// »ñȡר¼Î»Í¼¶ÔÏó£¬ÎªÐ¡Í¼
ImageUtils.disPlay(mp3Info.getSmallAlumUrl(), musicAblum);
Intent intent = new Intent();
intent.putExtra("url", mp3Info.getUrl());
intent.putExtra("MSG", AppConstant.PlayerMsg.NET_MSG);
intent.putExtra("listSearchResult", (Serializable)listSearchResult);
intent.putExtra("current", position);
intent.setPackage(activity.getPackageName());
activity.startService(intent);
}
//½«Ïß³ÌÖеõ½µÄËÑË÷½á¹ûÉèÖÃ×ÊÔ´ÊÊÅäÆ÷£¬²¢´«Ë͸øÖ÷Ï̴߳¦Àí
private Handler mHandler = new Handler() {
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case 0:
SearchResultListAdapter adapter = new SearchResultListAdapter(
listSearchResult,activity);
lvSearchReasult.setAdapter(adapter);
break;
}
};
};
}
| apache-2.0 |
flordan/COMPSs-Mobile | code/runtime/master/src/main/java/es/bsc/mobile/runtime/types/CEI.java | 5054 | /*
* Copyright 2008-2016 Barcelona Supercomputing Center (www.bsc.es)
*
* 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 es.bsc.mobile.runtime.types;
import es.bsc.mobile.annotations.JavaMethod;
import es.bsc.mobile.annotations.OpenCL;
import java.util.LinkedList;
import es.bsc.mobile.types.Constraints;
import java.io.Serializable;
import java.util.Arrays;
public class CEI implements Serializable {
private final String[] ceSignatures;
private final String[][] implSignatures;
private final LinkedList<Implementation>[] coreElements;
private final int[] coreParamsCount;
public CEI(Class<?> itf) {
int coreCount = itf.getDeclaredMethods().length;
ceSignatures = new String[coreCount];
coreElements = new LinkedList[coreCount];
coreParamsCount = new int[coreCount];
implSignatures = new String[coreCount][];
int ceId = 0;
for (java.lang.reflect.Method m : itf.getDeclaredMethods()) {
if (m.isAnnotationPresent(es.bsc.mobile.annotations.CoreElement.class)) {
coreElements[ceId] = loadCoreElement(m, ceId);
coreParamsCount[ceId] = m.getParameterAnnotations().length;
}
ceId++;
}
}
private LinkedList<Implementation> loadCoreElement(java.lang.reflect.Method m, int ceId) {
LinkedList<Implementation> impls = new LinkedList<>();
String methodName = m.getName();
String methodSignature = Method.getSignature(m);
ceSignatures[ceId] = methodSignature;
es.bsc.mobile.annotations.CoreElement ceAnnot = m.getAnnotation(es.bsc.mobile.annotations.CoreElement.class);
int implementationCount = ceAnnot.methods().length + ceAnnot.openclKernels().length;
implSignatures[ceId] = new String[implementationCount];
int implId = 0;
for (JavaMethod mAnnot : ceAnnot.methods()) {
String declaringClass = mAnnot.declaringClass();
Constraints ctrs = new Constraints(mAnnot.constraints());
if (ctrs.processorCoreCount() == 0) {
ctrs.setProcessorCoreCount(1);
}
Method method = new Method(ceId, implId, methodName, declaringClass, ctrs);
implSignatures[ceId][implId] = method.completeSignature(methodSignature);
impls.add(method);
implId++;
}
for (OpenCL oclAnnot : ceAnnot.openclKernels()) {
String program = oclAnnot.kernel();
Class<?> resultType = m.getReturnType();
String[] resultSize = oclAnnot.resultSize();
String[] workload = oclAnnot.workloadSize();
String[] localSize = oclAnnot.localSize();
String[] readOffset = oclAnnot.offset();
String[] offset;
if (readOffset.length == workload.length) {
offset = readOffset;
} else {
offset = new String[workload.length];
int i = 0;
for (; i < offset.length && i < readOffset.length; i++) {
offset[i] = readOffset[i];
}
for (; i < offset.length; i++) {
offset[i] = "0";
}
}
Kernel kernel = new Kernel(ceId, implId, program, methodName, resultType, resultSize, workload, localSize, offset);
implSignatures[ceId][implId] = kernel.completeSignature(methodSignature);
impls.add(kernel);
implId++;
}
return impls;
}
public int getCoreCount() {
return coreElements.length;
}
public String getCoreSignature(int coreIdx) {
return ceSignatures[coreIdx];
}
public LinkedList<Implementation> getCoreImplementations(int coreIdx) {
return coreElements[coreIdx];
}
public int getParamsCount(int ceiCE) {
return coreParamsCount[ceiCE];
}
public String[] getAllSignatures() {
LinkedList<String> signatures = new LinkedList<>();
signatures.addAll(Arrays.asList(ceSignatures));
for (String[] impls : implSignatures) {
for (String sign : impls) {
if (sign != null) {
signatures.addAll(Arrays.asList(impls));
}
}
}
String[] signArray = new String[signatures.size()];
int i = 0;
for (String signature : signatures) {
signArray[i++] = signature;
}
return signArray;
}
}
| apache-2.0 |
mikkokupsu/KantaCDA-API | KantaCDA-API/src/main/java/fi/kela/kanta/cda/validation/ReseptinMitatointiValidoija.java | 2828 | /*******************************************************************************
* Copyright 2017 Kansaneläkelaitos
*
* 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 fi.kela.kanta.cda.validation;
import fi.kela.kanta.to.LaakemaarayksenMitatointiTO;
import fi.kela.kanta.to.LaakemaaraysTO;
import fi.kela.kanta.util.KantaCDAUtil;
public class ReseptinMitatointiValidoija extends LaakemaaraysValidoija {
protected LaakemaarayksenMitatointiTO mitatointi;
public LaakemaarayksenMitatointiTO getMitatointi() {
return mitatointi;
}
public void setMitatointi(LaakemaarayksenMitatointiTO mitatointi) {
this.mitatointi = mitatointi;
}
public ReseptinMitatointiValidoija(LaakemaaraysTO alkuperainenLaakemaarays, LaakemaarayksenMitatointiTO laakemaarayksenMitatointi) {
super(alkuperainenLaakemaarays);
setMitatointi(laakemaarayksenMitatointi);
}
@Override
public void validoi() {
validoiMitatointi();
validoiAlkuperainenLaakemaarays();
}
protected void validoiMitatointi() {
if (null == getMitatointi()) {
throw new IllegalArgumentException("Laakemaarayksen mitatointi cannot be null.");
}
if (null == getMitatointi().getMitatoija()) {
throw new IllegalArgumentException("Laakemaarayksen mitatointi cannot be null.");
}
if (KantaCDAUtil.onkoNullTaiTyhja(getMitatointi().getMitatoinninSyyKoodi())) {
throw new IllegalArgumentException("Laakemaarayksen mitatoinnin syy koodi cannot be null.");
}
if (KantaCDAUtil.onkoNullTaiTyhja(getMitatointi().getMitatoinninPerustelu()) && "5".equals(getMitatointi().getMitatoinninSyyKoodi())) {
throw new IllegalArgumentException("Jos muutoksen syy on 'Muu syy' niin laakemaarayksen mitatoinnin perustelu ei voi olla null.");
}
validoiHenkilotiedot(getMitatointi().getPotilas());
}
/**
* Validoi alkuperaisen LaakemaraysTOn
*
* @param laakemaarays LaakemaaraysTO joka validoidaan
*/
private void validoiAlkuperainenLaakemaarays() {
if (null == getAlkuperainenLaakemaarays().getMaarayspaiva()) {
throw new IllegalArgumentException("Alkuperaisen laakemaarayksen maarayspaiva cannot be null.");
}
}
}
| apache-2.0 |
NationalSecurityAgency/ghidra | Ghidra/Debug/Debugger/src/main/java/ghidra/app/plugin/core/debug/gui/time/DebuggerTimeSelectionDialog.java | 5331 | /* ###
* IP: GHIDRA
*
* 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 ghidra.app.plugin.core.debug.gui.time;
import java.awt.BorderLayout;
import java.util.function.Function;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import docking.DialogComponentProvider;
import ghidra.app.plugin.core.debug.gui.DebuggerResources;
import ghidra.framework.plugintool.PluginTool;
import ghidra.trace.model.Trace;
import ghidra.trace.model.time.schedule.TraceSchedule;
import ghidra.util.MessageType;
import ghidra.util.Msg;
public class DebuggerTimeSelectionDialog extends DialogComponentProvider {
private final PluginTool tool;
DebuggerSnapshotTablePanel snapshotPanel;
JTextField scheduleText;
TraceSchedule schedule;
JButton tickStep;
JButton tickBack;
JButton opStep;
JButton opBack;
public DebuggerTimeSelectionDialog(PluginTool tool) {
super("Select Time", true, true, true, false);
this.tool = tool;
populateComponents();
}
protected void doStep(Function<TraceSchedule, TraceSchedule> stepper) {
try {
TraceSchedule stepped = stepper.apply(schedule);
if (stepped == null) {
return;
}
setScheduleText(stepped.toString());
}
catch (Throwable e) {
Msg.warn(this, e.getMessage());
}
}
protected void populateComponents() {
JPanel workPanel = new JPanel(new BorderLayout());
{
Box hbox = Box.createHorizontalBox();
hbox.setBorder(BorderFactory.createTitledBorder("Schedule"));
hbox.add(new JLabel("Expression: "));
scheduleText = new JTextField();
hbox.add(scheduleText);
hbox.add(new JLabel("Ticks: "));
hbox.add(tickBack = new JButton(DebuggerResources.ICON_STEP_BACK));
hbox.add(tickStep = new JButton(DebuggerResources.ICON_STEP_INTO));
hbox.add(new JLabel("Ops: "));
hbox.add(opBack = new JButton(DebuggerResources.ICON_STEP_BACK));
hbox.add(opStep = new JButton(DebuggerResources.ICON_STEP_INTO));
workPanel.add(hbox, BorderLayout.NORTH);
}
tickBack.addActionListener(evt -> doStep(s -> s.steppedBackward(getTrace(), 1)));
tickStep.addActionListener(evt -> doStep(s -> s.steppedForward(null, 1)));
opBack.addActionListener(evt -> doStep(s -> s.steppedPcodeBackward(1)));
opStep.addActionListener(evt -> doStep(s -> s.steppedPcodeForward(null, 1)));
{
snapshotPanel = new DebuggerSnapshotTablePanel();
workPanel.add(snapshotPanel, BorderLayout.CENTER);
}
snapshotPanel.getSelectionModel().addListSelectionListener(evt -> {
Long snap = snapshotPanel.getSelectedSnapshot();
if (snap == null) {
return;
}
if (schedule.getSnap() == snap.longValue()) {
return;
}
scheduleText.setText(snap.toString());
});
scheduleText.getDocument().addDocumentListener(new DocumentListener() {
@Override
public void insertUpdate(DocumentEvent e) {
scheduleTextChanged();
}
@Override
public void removeUpdate(DocumentEvent e) {
scheduleTextChanged();
}
@Override
public void changedUpdate(DocumentEvent e) {
scheduleTextChanged();
}
});
addWorkPanel(workPanel);
addOKButton();
addCancelButton();
setMinimumSize(600, 600);
}
protected void scheduleTextChanged() {
schedule = null;
try {
schedule = TraceSchedule.parse(scheduleText.getText());
snapshotPanel.setSelectedSnapshot(schedule.getSnap());
schedule.validate(getTrace());
setStatusText("");
setOkEnabled(true);
}
catch (Exception e) {
setStatusText(e.getMessage(), MessageType.ERROR);
setOkEnabled(false);
}
enableStepButtons(schedule != null);
}
protected void enableStepButtons(boolean enabled) {
tickBack.setEnabled(enabled);
tickStep.setEnabled(enabled);
opBack.setEnabled(enabled);
opStep.setEnabled(enabled);
}
@Override // Public for test access
public void okCallback() {
assert schedule != null;
super.okCallback();
close();
}
@Override // Public for test access
public void cancelCallback() {
this.schedule = null;
super.cancelCallback();
}
@Override
public void close() {
super.close();
snapshotPanel.setTrace(null);
snapshotPanel.setSelectedSnapshot(null);
}
/**
* Prompts the user to select a snapshot and optionally specify a full schedule
*
* @param trace the trace from whose snapshots to select
* @param defaultTime, optionally the time to select initially
* @return the schedule, likely specifying just the snapshot selection
*/
public TraceSchedule promptTime(Trace trace, TraceSchedule defaultTime) {
snapshotPanel.setTrace(trace);
schedule = defaultTime;
scheduleText.setText(defaultTime.toString());
tool.showDialog(this);
return schedule;
}
public Trace getTrace() {
return snapshotPanel.getTrace();
}
public void setScheduleText(String text) {
scheduleText.setText(text);
}
}
| apache-2.0 |
bjorndm/prebake | code/third_party/bdb/src/com/sleepycat/persist/model/NotPersistent.java | 1314 | /*-
* See the file LICENSE for redistribution information.
*
* Copyright (c) 2002-2010 Oracle. All rights reserved.
*
* $Id: NotPersistent.java,v 1.5 2010/01/04 15:50:57 cwl Exp $
*/
package com.sleepycat.persist.model;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
/**
* Overrides the default rules for field persistence and defines a field as
* being non-persistent even when it is not declared with the
* <code>transient</code> keyword.
*
* <p>By default, the persistent fields of a class are all declared instance
* fields that are non-transient (are not declared with the
* <code>transient</code> keyword). The default rules may be overridden by
* specifying the {@link NotPersistent} or {@link NotTransient} annotation.</p>
*
* <p>For example, the following field is non-transient (persistent) with
* respect to Java serialization but is transient with respect to the DPL.</p>
*
* <pre style="code">
* {@code @NotPersistent}
* int myField;
* }
* </pre>
*
* @see NotTransient
* @author Mark Hayes
*/
@Documented @Retention(RUNTIME) @Target(FIELD)
public @interface NotPersistent {
}
| apache-2.0 |
1147576679/findbest | app/src/main/java/com/example/zjy/bantang/SplashActivity.java | 741 | package com.example.zjy.bantang;
import android.content.Intent;
import android.widget.ImageView;
import com.example.zjy.niklauslibrary.base.BaseActivity;
import butterknife.Bind;
public class SplashActivity extends BaseActivity {
@Bind(R.id.splash_image)
ImageView splash_image;
@Override
public int getContentId() {
return R.layout.activity_splash;
}
//欢迎页的跳转
@Override
protected void onPostResume() {
super.onPostResume();
splash_image.postDelayed(new Runnable() {
@Override
public void run() {
startActivity(new Intent(SplashActivity.this,MainActivity.class));
finish();
}
},2000);
}
}
| apache-2.0 |
rlatkdgus500/UnityBluetoothPlugin | Assets/Scripts/Bluetooth/AndroidJavaFile/BluetoothPlugin.java | 11563 | package com.hyeon.bluetoothPlugin;
import java.util.ArrayList;
import java.util.Set;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;
import android.support.annotation.RequiresPermission;
import com.unity3d.player.UnityPlayer;
import com.unity3d.player.UnityPlayerActivity;
public class BluetoothPlugin extends UnityPlayerActivity {
public static final int MESSAGE_STATE_CHANGE = 1;
public static final int MESSAGE_READ = 2;
public static final int MESSAGE_WRITE = 3;
public static final int MESSAGE_DEVICE_NAME = 4;
public static final int MESSAGE_TOAST = 5;
private static final int REQUEST_CONNECT_DEVICE = 1;
private static final int REQUEST_ENABLE_BT = 2;
private static final String TAG = "BluetoothPlugin";
private static final String TARGET = "BluetoothModel";
private boolean IsScan = false;
private String mConnectedDeviceName = null;
private StringBuffer mOutStringBuffer;
private BluetoothAdapter mBtAdapter = null;
private BluetoothService mBtService = null;
private ArrayList<String> singleAddress = new ArrayList();
// Handler
private final Handler mHandler = new Handler() {
public void handleMessage(Message msg) {
switch(msg.what) {
case MESSAGE_STATE_CHANGE:
UnityPlayer.UnitySendMessage(TARGET, "OnStateChanged", String.valueOf(msg.arg1));
break;
case MESSAGE_READ:
byte[] readBuf = (byte[])msg.obj;
String readMessage = new String(readBuf, 0, msg.arg1);
UnityPlayer.UnitySendMessage(TARGET, "OnReadMessage", readMessage);
break;
case MESSAGE_WRITE:
byte[] writeBuf = (byte[])msg.obj;
String writeMessage = new String(writeBuf);
UnityPlayer.UnitySendMessage(TARGET, "OnSendMessage", writeMessage);
break;
case MESSAGE_DEVICE_NAME:
BluetoothPlugin.this.mConnectedDeviceName = msg.getData().getString("device_name");
Toast.makeText(BluetoothPlugin.this.getApplicationContext(), "Connected to " + BluetoothPlugin.this.mConnectedDeviceName, Toast.LENGTH_SHORT).show();
break;
case MESSAGE_TOAST:
Toast.makeText(BluetoothPlugin.this.getApplicationContext(), msg.getData().getString("toast"), Toast.LENGTH_SHORT).show();
break;
}
}
};
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
@RequiresPermission("android.permission.BLUETOOTH")
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if("android.bluetooth.device.action.FOUND".equals(action)) {
BluetoothDevice device = intent.getParcelableExtra("android.bluetooth.device.extra.DEVICE");
BluetoothPlugin.this.singleAddress.add(device.getName() + "\n" + device.getAddress());
UnityPlayer.UnitySendMessage(TARGET, "OnFoundDevice", device.getName() + ",\n" + device.getAddress());
} else if("android.bluetooth.adapter.action.DISCOVERY_FINISHED".equals(action)) {
if(BluetoothPlugin.this.IsScan) {
UnityPlayer.UnitySendMessage(TARGET, "OnScanFinish", "");
}
if(BluetoothPlugin.this.singleAddress.size() == 0) {
UnityPlayer.UnitySendMessage(TARGET, "OnFoundNoDevice", "");
}
}
}
};
// 1. Starting Point in Unity Script
@RequiresPermission("android.permission.BLUETOOTH")
public void StartPlugin() {
if(Looper.myLooper() == null) {
Looper.prepare();
}
this.SetupPlugin();
}
// 2. Setup Plugin
// Get Default Bluetooth Adapter and start Service
@RequiresPermission("android.permission.BLUETOOTH")
public String SetupPlugin() {
// Bluetooth Adapter
this.mBtAdapter = BluetoothAdapter.getDefaultAdapter();
// if Bluettoth Adapter is avaibale, start Service
if(this.mBtAdapter == null) {
return "Bluetooth is not available";
} else {
if(this.mBtService == null) {
this.startService();
}
return "SUCCESS";
}
}
// 3. Setup and Start Bluetooth Service
private void startService() {
Log.d(TAG, "setupService()");
this.mBtService = new BluetoothService(this, this.mHandler);
this.mOutStringBuffer = new StringBuffer("");
}
public String DeviceName() {
return this.mBtAdapter.getName();
}
@RequiresPermission("android.permission.BLUETOOTH")
public String GetDeviceConnectedName() {
return !this.mBtAdapter.isEnabled()?"You Must Enable The BlueTooth":(this.mBtService.getState() != 3?"Not Connected":this.mConnectedDeviceName);
}
@RequiresPermission("android.permission.BLUETOOTH")
public boolean IsEnabled() {
return this.mBtAdapter.isEnabled();
}
public boolean IsConnected() {
return this.mBtService.getState() == 3;
}
@RequiresPermission("android.permission.BLUETOOTH")
public void stopThread() {
Log.d(TAG, "stop");
if(this.mBtService != null) {
this.mBtService.stop();
this.mBtService = null;
}
if(this.mBtAdapter != null) {
this.mBtAdapter = null;
}
this.SetupPlugin();
}
@RequiresPermission(
allOf = {"android.permission.BLUETOOTH", "android.permission.BLUETOOTH_ADMIN"}
)
public void Connect(String TheAdrees) {
if(this.mBtAdapter.isDiscovering()) {
this.mBtAdapter.cancelDiscovery();
}
this.IsScan = false;
String address = TheAdrees.substring(TheAdrees.length() - 17);
this.mConnectedDeviceName = TheAdrees.split(",")[0];
BluetoothDevice device = this.mBtAdapter.getRemoteDevice(address);
this.mBtService.connect(device);
}
@RequiresPermission(
allOf = {"android.permission.BLUETOOTH", "android.permission.BLUETOOTH_ADMIN"}
)
String ScanDevice() {
Log.d(TAG, "Start - ScanDevice()");
if(!this.mBtAdapter.isEnabled()) {
return "You Must Enable The BlueTooth";
} else {
this.IsScan = true;
this.singleAddress.clear();
IntentFilter filter = new IntentFilter("android.bluetooth.device.action.FOUND");
this.registerReceiver(this.mReceiver, filter);
filter = new IntentFilter("android.bluetooth.adapter.action.DISCOVERY_FINISHED");
this.registerReceiver(this.mReceiver, filter);
this.mBtAdapter = BluetoothAdapter.getDefaultAdapter();
Set pairedDevices = this.mBtAdapter.getBondedDevices();
if(pairedDevices.size() > 0) {
}
this.doDiscovery();
return "SUCCESS";
}
}
@RequiresPermission(
allOf = {"android.permission.BLUETOOTH", "android.permission.BLUETOOTH_ADMIN"}
)
private void doDiscovery() {
Log.d(TAG, "doDiscovery()");
if(this.mBtAdapter.isDiscovering()) {
this.mBtAdapter.cancelDiscovery();
}
this.mBtAdapter.startDiscovery();
}
@RequiresPermission(
allOf = {"android.permission.BLUETOOTH", "android.permission.BLUETOOTH_ADMIN"}
)
String BluetoothSetName(String name) {
if(!this.mBtAdapter.isEnabled()) {
return "You Must Enable The BlueTooth";
} else if(this.mBtService.getState() != 3) {
return "Not Connected";
} else {
this.mBtAdapter.setName(name);
return "SUCCESS";
}
}
@RequiresPermission(
allOf = {"android.permission.BLUETOOTH", "android.permission.BLUETOOTH_ADMIN"}
)
String DisableBluetooth() {
if(!this.mBtAdapter.isEnabled()) {
return "You Must Enable The BlueTooth";
} else {
if(this.mBtAdapter != null) {
this.mBtAdapter.cancelDiscovery();
}
if(this.mBtAdapter.isEnabled()) {
this.mBtAdapter.disable();
}
return "SUCCESS";
}
}
@RequiresPermission("android.permission.BLUETOOTH")
public String BluetoothEnable() {
try {
if(!this.mBtAdapter.isEnabled()) {
Intent e = new Intent("android.bluetooth.adapter.action.REQUEST_ENABLE");
this.startActivityForResult(e, 2);
}
return "SUCCESS";
} catch (Exception e) {
return "Faild";
}
}
public void showMessage(final String message) {
this.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(BluetoothPlugin.this, message, Toast.LENGTH_SHORT).show();
}
});
}
// Android Life cycle method
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.e(TAG, "+++ ON CREATE +++");
}
public void onStart() {
super.onStart();
}
public synchronized void onPause() {
super.onPause();
Log.e(TAG, "- ON PAUSE -");
}
@RequiresPermission("android.permission.BLUETOOTH")
public synchronized void onResume() {
super.onResume();
Log.d(TAG, "+ ON RESUME +");
if(this.mBtService != null && this.mBtService.getState() == 0) {
this.mBtService.start();
}
}
public void onStop() {
super.onStop();
Log.e(TAG, "-- ON STOP --");
}
public void onDestroy() {
super.onDestroy();
if(this.mBtService != null) {
this.mBtService.stop();
}
Log.e(TAG, "--- ON DESTROY ---");
}
@RequiresPermission("android.permission.BLUETOOTH")
public String ensureDiscoverable() {
if(!this.mBtAdapter.isEnabled()) {
return "You Must Enable The BlueTooth";
} else {
if(this.mBtAdapter.getScanMode() != 23) {
Intent discoverableIntent = new Intent("android.bluetooth.adapter.action.REQUEST_DISCOVERABLE");
discoverableIntent.putExtra("android.bluetooth.adapter.extra.DISCOVERABLE_DURATION", 300);
this.startActivity(discoverableIntent);
}
return "SUCCESS";
}
}
@RequiresPermission("android.permission.BLUETOOTH")
public String sendMessage(String message) {
if(!this.mBtAdapter.isEnabled()) {
return "You Must Enable The BlueTooth";
} else if(this.mBtService.getState() != 3) {
return "Not Connected";
} else {
if(message.length() > 0) {
byte[] send = message.getBytes();
this.mBtService.write(send);
this.mOutStringBuffer.setLength(0);
}
return "SUCCESS";
}
}
} | apache-2.0 |
michpetrov/hal.next | app/src/main/java/org/jboss/hal/client/bootstrap/tasks/InitializedTask.java | 772 | /*
* Copyright 2022 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
*
* 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.jboss.hal.client.bootstrap.tasks;
/** A task executed after the console has been fully initialized. */
public interface InitializedTask extends Runnable {
}
| apache-2.0 |
shamim8888/SMSlib-ParallelPort | smslib-v3.5.3-MyBuild/NetBeansProjects/ioTest/src/ioTest.java | 94838 | import java.lang.Integer;
import java.lang.String;
import java.io.*;
import java.lang.System;
import java.util.StringTokenizer;
import java.util.logging.Logger;
import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.Properties;
import org.smslib.smsserver.SMSServer;
public class ioTest
{
static short datum;
static short Addr;
static pPort lpt;
static final int SQL_DELAY = 1000;
int sqlDelayMultiplier = 1;
private Connection dbCon = null;
static String do_read(short address)
{
short addnumber = 2;
short ContAddr=(short)(address+addnumber);
short Contdatanumber=0x50;
do_write(ContAddr,Contdatanumber);
// Read from the port
datum = (short) lpt.input(address);
// Notify the console
System.out.println("Read Port: " + Integer.toHexString(address) +
" = " + Integer.toHexString(datum)+" And Binary String is " + Integer.toBinaryString(datum));
return Integer.toBinaryString(datum);
}
static String do_read_register(short address)
{
// Read from the port
datum = (short) lpt.input(address);
// Notify the console
System.out.println("Read Port: " + Integer.toHexString(address) +
" = " + Integer.toHexString(datum)+" And Binary String is " + Integer.toBinaryString(datum));
return Integer.toBinaryString(datum);
}
static void do_write(short Address,short datanumber)
{
// Notify the console
System.out.println("Write to Port: " + Integer.toHexString(Address) +
" with data = " + Integer.toHexString(datanumber));
//Write to the port
lpt.output(Address,datanumber);
}
static void do_read_range()
{
// Try to read 0x378..0x37F, LPT1:
for (Addr=0x378; (Addr<0x380); Addr++)
{
//Read from the port
datum = (short) lpt.input(Addr);
// Notify the console
System.out.println("Port: " + Integer.toHexString(Addr) +
" = " + Integer.toHexString(datum));
}
}
public static String replaceCharAt(String s, int pos, char c)
{
return s.substring(0, pos) + c + s.substring(pos + 1);
}
public static String SendStatusMessage(String AreaName[][],String StatusCommand )
{
String SmsOut = "";
for (int j=0;j<2;j++)
{
Addr=0x378;
do_read(Addr);
String stat = do_read(Addr);
int statlength = stat.length();
System.out.println("Binary Number is "+stat+" And Stat Length is "+statlength);
if(statlength<8)
{
for (int i=0;i<(8-statlength);i++)
{
stat = "0".concat(stat);
}
}
System.out.println("Concatenated string "+stat);
char[] chars = stat.toCharArray();
for(int i = 7; i >=0; i--)
{
if("1".equals(String.valueOf(chars[i])))
{
// System.out.println(AreaName[j][9-i]+" is "+"ON");
if(i==7)
{
if ("OFF".equals(StatusCommand.trim().toUpperCase()))
{
}
else
{
SmsOut = SmsOut.concat(AreaName[j][9-i]+" is "+"ON");
}
}
else
{
if ("OFF".equals(StatusCommand.trim().toUpperCase()))
{
}
else
{
SmsOut = SmsOut.concat("\n"+AreaName[j][9-i]+" is "+"ON");
}
}
}
else
{
// System.out.println(AreaName[j][9-i]+" is "+"OFF");
if(i==7)
{
if ("ON".equals(StatusCommand.trim().toUpperCase()))
{
}
else
{
SmsOut = SmsOut.concat(AreaName[j][9-i]+" is "+"OFF");
}
}
else
{
if ("ON".equals(StatusCommand.trim().toUpperCase()))
{
}
else
{
SmsOut = SmsOut.concat("\n"+AreaName[j][9-i]+" is "+"OFF");
}
}
// System.out.println("SMS String Is: " + SmsOut);
}
}
}
return SmsOut;
}
public static void WriteDeviceAllCommand(String LPTDeviceName,String AreaName[][],String DeviceCommand )
{
char firstLetter;
String DeviceAllPinCommand;
DeviceAllPinCommand = "";
if ("ON".equals(DeviceCommand.trim().toUpperCase()))
{
System.out.println("AllCommandName is "+DeviceCommand);
DeviceAllPinCommand = "11111111";
System.out.println("Binary String Before replacement: "+DeviceAllPinCommand);
}
else if("OFF".equals(DeviceCommand.trim().toUpperCase()))
{
System.out.println("ThirdSpaceTokenSMSCommandName is "+DeviceCommand+" And StatusCommand is "+DeviceCommand);
DeviceAllPinCommand = "00000000";
System.out.println("Binary String Before replacement: "+DeviceAllPinCommand);
}
else if("TG".equals(DeviceCommand.trim().toUpperCase()))
{
Addr=0x378;
DeviceAllPinCommand = do_read_register(Addr);
int PinStatuslength = DeviceAllPinCommand.length();
System.out.println("Binary Number is "+DeviceAllPinCommand+" And DeviceAllPinStatus Length is "+PinStatuslength);
if(PinStatuslength<8)
{
for (int c=0;c<(8-PinStatuslength);c++)
{
DeviceAllPinCommand = "0".concat(DeviceAllPinCommand);
System.out.println("Concatenated string "+DeviceAllPinCommand);
}
}
for(int k=0;k<8;k++)
{
char CharPosForToggle = DeviceAllPinCommand.charAt(k);
if(CharPosForToggle=='0')
{
firstLetter = '1';
}
else
{
firstLetter = '0';
}
DeviceAllPinCommand = replaceCharAt(DeviceAllPinCommand, k, firstLetter);
}
}
String writedatum = Integer.toHexString(Integer.parseInt(DeviceAllPinCommand,2));
System.out.println("Check To See hexstring : "+writedatum);
datum = Short.parseShort(writedatum, 16) ;
do_write(Addr,datum);
DeviceAllPinCommand = do_read_register(Addr);
System.out.println("Check To See if we write properly: "+DeviceAllPinCommand);
}
public static void StatusCommand(String FirstSpaceTokenSMSCommandName,String SecondSpaceTokenSMSCommandName, String AreaName[][] )
{
if ("ON".equals(SecondSpaceTokenSMSCommandName.trim().toUpperCase()))
{
System.out.println("SecondSpaceTokenSMSCommandName is "+SecondSpaceTokenSMSCommandName+" And StatusCommand is "+SecondSpaceTokenSMSCommandName);
System.out.println("SMS String is : "+SendStatusMessage(AreaName,SecondSpaceTokenSMSCommandName)+" End Of SMS String");
}
else if("OFF".equals(SecondSpaceTokenSMSCommandName.trim().toUpperCase()))
{
System.out.println("SecondSpaceTokenSMSCommandName is "+SecondSpaceTokenSMSCommandName+" And StatusCommand is "+SecondSpaceTokenSMSCommandName);
System.out.println("SMS String is : "+SendStatusMessage(AreaName,SecondSpaceTokenSMSCommandName)+" End Of SMS STring");
}
else if("TG".equals(SecondSpaceTokenSMSCommandName.trim().toUpperCase()))
{
System.out.println("SecondSpaceTokenSMSCommandName is "+SecondSpaceTokenSMSCommandName+" And StatusCommand is "+SecondSpaceTokenSMSCommandName);
System.out.println("SMS String is : "+SendStatusMessage(AreaName,SecondSpaceTokenSMSCommandName)+" End Of SMS String");
}
else
{
System.out.println("SecondSpaceTokenSMSCommandName is "+SecondSpaceTokenSMSCommandName+" And StatusCommand Is : "+SecondSpaceTokenSMSCommandName +" And StatusCommand Is Not Supported");
// SendErrorMessage();
}
}
public static void AllCommand(String FirstSpaceTokenSMSCommandName,String SecondSpaceTokenSMSCommandName, String AreaName[][] )
{
if ("ON".equals(SecondSpaceTokenSMSCommandName.trim().toUpperCase()))
{
System.out.println("SecondSpaceTokenSMSCommandName is "+SecondSpaceTokenSMSCommandName+" And StatusCommand is "+SecondSpaceTokenSMSCommandName);
System.out.println("SMS String is : "+SendStatusMessage(AreaName,SecondSpaceTokenSMSCommandName)+" End Of SMS String");
}
else if("OFF".equals(SecondSpaceTokenSMSCommandName.trim().toUpperCase()))
{
System.out.println("SecondSpaceTokenSMSCommandName is "+SecondSpaceTokenSMSCommandName+" And StatusCommand is "+SecondSpaceTokenSMSCommandName);
System.out.println("SMS String is : "+SendStatusMessage(AreaName,SecondSpaceTokenSMSCommandName)+" End Of SMS STring");
}
else if("TG".equals(SecondSpaceTokenSMSCommandName.trim().toUpperCase()))
{
System.out.println("SecondSpaceTokenSMSCommandName is "+SecondSpaceTokenSMSCommandName+" And StatusCommand is "+SecondSpaceTokenSMSCommandName);
System.out.println("SMS String is : "+SendStatusMessage(AreaName,SecondSpaceTokenSMSCommandName)+" End Of SMS String");
}
else
{
System.out.println("SecondSpaceTokenSMSCommandName is "+SecondSpaceTokenSMSCommandName+" And StatusCommand Is : "+SecondSpaceTokenSMSCommandName +" And StatusCommand Is Not Supported");
// SendErrorMessage();
}
}
public static void main( String args[] )
{
lpt = new pPort();
System.out.print("Enter Your Message: ");
// open up standard input
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String msg = null;
int PinNumber = 0;
int DataBaseNotFound = 0;
int aPinNumberInt = 0;
String LPTDeviceName;
LPTDeviceName = "";
String PinCommand = "";
String StatusCommand;
StatusCommand = "";
String DeviceCommand;
int NumberOfSpaceToken=0;
String PinStatus = "";
char firstLetter;
int PinStatuslength;
Connection con = null;
Statement cmd;
// read the username from the command-line; need to use try/catch with the readLine() method
try
{
msg = br.readLine();
}
catch (IOException ioe)
{
System.out.println("IO error trying to read your Message!");
System.exit(1);
}
System.out.println("Thanks for the message: " + msg);
String[][] AreaName = new String[32][22];
try
{
String driver = "com.mysql.jdbc.Driver";
Class.forName(driver).newInstance();
Connection conn = null;
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/parallelport?autoReconnect=true","root","");
Statement s = conn.createStatement();
ResultSet rs = s.executeQuery("SELECT * FROM parallel_comm_port_view");
int i = 0;
while(rs.next())
{
int d = 0;
int e = 1;
System.out.println("Building_Name : "+ rs.getString(3));
AreaName[i][0] = rs.getString(3);
System.out.println("Floor_Name : "+ rs.getString(5));
AreaName[i][1] = rs.getString(5);
System.out.println("Flat_Name : "+ rs.getString(7));
AreaName[i][2] = rs.getString(7);
System.out.println("Room_Name : "+ rs.getString(9));
AreaName[i][3] = rs.getString(9);
System.out.println("Host_Address : "+ rs.getString(10));
AreaName[i][4] = rs.getString(10);
System.out.println("Device_Name : "+ rs.getString(12));
AreaName[i][5] = rs.getString(12);
for(int k=6;k<14;k++)
{
System.out.println("Equipment_ID : "+ rs.getString(k+7+d));
AreaName[i][k+d] = rs.getString(k+7+d);
System.out.println("Equipment_Name : "+ rs.getString(k+7+e));
AreaName[i][k+e] = rs.getString(k+7+e);
d++;
e++;
}
System.out.println();
i++;
}
rs.close();
s.close();
conn.close();
}
catch(Exception e)
{
System.out.println("Exception: "+ e);
e.printStackTrace();
}
//Start Check and tokenize the Message And Read and Write Lpt
StringTokenizer Entertokens = new StringTokenizer(msg, "\r",true);
if(Entertokens.countTokens() == 1)
{
System.out.println("Enter Token is "+Entertokens.countTokens());
StringTokenizer commatokens = new StringTokenizer(msg, ",", true);
if(commatokens.countTokens() == 1)
{
System.out.println("Comma Token in Enter Token is "+commatokens.countTokens()+" And It's a Single SMS Command");
StringTokenizer spacetokens = new StringTokenizer(msg, " ");
if(spacetokens.countTokens() == 1)
{
System.out.println("Space Token in Comma Token is "+spacetokens.countTokens());
if("STATUS".equals(msg.trim().toUpperCase()))
{
System.out.println("SMS Command is "+spacetokens.nextToken());
// pst.setString(11, "STATUS");
System.out.println("SMS String is : "+SendStatusMessage(AreaName,StatusCommand)+" End Of SMS String");
for(int i = 12; i <52; i++)
{
//pst.setString(i,null);
System.out.println("Field Number is "+i);
}
}
//This else is for command not status
else
{
System.out.println("Command is not Status, Command is "+spacetokens.nextToken()+"Command is not supported");
//SendErrorMessage();
}
}
//This else is for Space token not equal 1
else
{
//System.out.println("Comma Token in Enter Token is "+spacetokens.countTokens()+" And It's a Single SMS Command");
System.out.println("Space Token in Comma Token is "+spacetokens.countTokens()+" And It's a Single SMS Command And Total Words Are "+spacetokens.countTokens());
NumberOfSpaceToken = spacetokens.countTokens();
if(spacetokens.countTokens() >6)
{
System.out.println("SMS Command Is More Than "+spacetokens.countTokens());
// SendErrorMessage("You Have Write More Than Six Words");
}
// This else is for space token not greater than 6
else
{
// pst.setString(11, null);
int fieldnumber = 12;
char CharPosForToggle = '0';
while(spacetokens.hasMoreTokens())
{
if (fieldnumber==12)
{
// pst.setString(fieldnumber, (subtokens.nextToken().length() == 0 ? "" : subtokens.nextToken()));
String FirstSpaceTokenSMSCommandName = spacetokens.nextToken();
System.out.println("FieldNumber is "+fieldnumber+" and FirstSpaceTokenSMSCommandName Is "+FirstSpaceTokenSMSCommandName);
if ("STATUS".equals(FirstSpaceTokenSMSCommandName.trim().toUpperCase()))
{
System.out.println(FirstSpaceTokenSMSCommandName.trim().toUpperCase()+" FirstSpaceTokenSMSCommandName is found in database ");
String SecondSpaceTokenSMSCommandName = spacetokens.nextToken();
StatusCommand(FirstSpaceTokenSMSCommandName,SecondSpaceTokenSMSCommandName,AreaName);
}
//This elseif is for FirstSpaceTokenSMSCommend is not STATUS
else if ("ALL".equals(FirstSpaceTokenSMSCommandName.trim().toUpperCase()))
{
System.out.println(" Device Pin Number is ALL found in database And ");
aPinNumberInt = 10;
DataBaseNotFound = 1;
System.out.println(FirstSpaceTokenSMSCommandName.trim().toUpperCase()+" FirstSpaceTokenSMSCommandName is found in database ");
String SecondSpaceTokenSMSCommandName = spacetokens.nextToken();
AllCommand(FirstSpaceTokenSMSCommandName,SecondSpaceTokenSMSCommandName,AreaName);
}
//This else is for FirstSpaceTokenSMSCommend is not STATUS or ALL
else
{
for(int i=0;i<32;i++)
{
for(int j=0;j<22;j++)
{
if (AreaName[i][j].toUpperCase().equals(FirstSpaceTokenSMSCommandName.trim().toUpperCase()))
{
String FirstSpaceTokenSMSCommand = AreaName[i][j];
System.out.println("FieldNumber is "+fieldnumber+" and FirstSpaceTokenSMSCommandName Is "+FirstSpaceTokenSMSCommandName.trim().toUpperCase()+" FirstSpaceTokenSMSCommandName is found in database ");
String SecondSpaceTokenSMSCommandName = spacetokens.nextToken();
if ("STATUS".equals(SecondSpaceTokenSMSCommandName.trim().toUpperCase()))
{
System.out.println(SecondSpaceTokenSMSCommandName.trim().toUpperCase()+" SecondSpaceTokenSMSCommandName is found in database ");
String ThirdSpaceTokenSMSCommandName = spacetokens.nextToken();
StatusCommand(FirstSpaceTokenSMSCommand,ThirdSpaceTokenSMSCommandName,AreaName);
}
else if("ALL".equals(SecondSpaceTokenSMSCommandName.trim().toUpperCase()))
{
System.out.println(SecondSpaceTokenSMSCommandName.trim().toUpperCase()+" SecondSpaceTokenSMSCommandName is found in database ");
String ThirdSpaceTokenSMSCommandName = spacetokens.nextToken();
AllCommand(FirstSpaceTokenSMSCommand,ThirdSpaceTokenSMSCommandName,AreaName);
}
else
{
for(int k=0;k<32;k++)
{
for(int l=0;l<22;l++)
{
if (AreaName[k][l].toUpperCase().equals(SecondSpaceTokenSMSCommandName.trim().toUpperCase()))
{
String SecondSpaceTokenSMSCommand = AreaName[k][l];
System.out.println(SecondSpaceTokenSMSCommandName.trim().toUpperCase()+" SecondSpaceTokenSMSCommandName is found in database ");
String ThirdSpaceTokenSMSCommandName = spacetokens.nextToken();
if ("STATUS".equals(ThirdSpaceTokenSMSCommandName.trim().toUpperCase()))
{
System.out.println(ThirdSpaceTokenSMSCommandName.trim().toUpperCase()+" ThirdSpaceTokenSMSCommandName is found in database ");
String FourthSpaceTokenSMSCommandName = spacetokens.nextToken();
StatusCommand(FirstSpaceTokenSMSCommand,FourthSpaceTokenSMSCommandName,AreaName);
}
else if("ALL".equals(ThirdSpaceTokenSMSCommandName.trim().toUpperCase()))
{
System.out.println(ThirdSpaceTokenSMSCommandName.trim().toUpperCase()+" ThirdSpaceTokenSMSCommandName is found in database ");
String FourthSpaceTokenSMSCommandName = spacetokens.nextToken();
AllCommand(FirstSpaceTokenSMSCommand,FourthSpaceTokenSMSCommandName,AreaName);
}
else
{
for(int m=0;m<32;m++)
{
for(int n=0;n<22;n++)
{
if (AreaName[m][n].toUpperCase().equals(ThirdSpaceTokenSMSCommandName.trim().toUpperCase()))
{
String ThirdSpaceTokenSMSCommand = AreaName[m][n];
System.out.println(ThirdSpaceTokenSMSCommandName.trim().toUpperCase()+" ThirdSpaceTokenSMSCommandName is found in database ");
String FourthSpaceTokenSMSCommandName = spacetokens.nextToken();
if ("STATUS".equals(FourthSpaceTokenSMSCommandName.trim().toUpperCase()))
{
System.out.println(FourthSpaceTokenSMSCommandName.trim().toUpperCase()+" FourthSpaceTokenSMSCommandName is found in database ");
String FifthSpaceTokenSMSCommandName = spacetokens.nextToken();
StatusCommand(FirstSpaceTokenSMSCommand,FifthSpaceTokenSMSCommandName,AreaName);
}
else if("ALL".equals(FourthSpaceTokenSMSCommandName.trim().toUpperCase()))
{
System.out.println(FourthSpaceTokenSMSCommandName.trim().toUpperCase()+" FourthSpaceTokenSMSCommandName is found in database ");
String FifthSpaceTokenSMSCommandName = spacetokens.nextToken();
AllCommand(FirstSpaceTokenSMSCommand,FifthSpaceTokenSMSCommandName,AreaName);
}
else
{
for(int o=0;o<32;o++)
{
for(int p=0;p<22;p++)
{
if (AreaName[o][p].toUpperCase().equals(FourthSpaceTokenSMSCommandName.trim().toUpperCase()))
{
String FourthSpaceTokenSMSCommand = AreaName[o][p];
System.out.println(FourthSpaceTokenSMSCommandName.trim().toUpperCase()+" FourthSpaceTokenSMSCommandName is found in database ");
String FifthSpaceTokenSMSCommandName = spacetokens.nextToken();
if ("STATUS".equals(FifthSpaceTokenSMSCommandName.trim().toUpperCase()))
{
System.out.println(FifthSpaceTokenSMSCommandName.trim().toUpperCase()+" FifthSpaceTokenSMSCommandName is found in database ");
String SixthSpaceTokenSMSCommandName = spacetokens.nextToken();
StatusCommand(FirstSpaceTokenSMSCommand,SixthSpaceTokenSMSCommandName,AreaName);
}
else if("ALL".equals(FifthSpaceTokenSMSCommandName.trim().toUpperCase()))
{
System.out.println(FourthSpaceTokenSMSCommandName.trim().toUpperCase()+" FifthSpaceTokenSMSCommandName is found in database ");
String SixthSpaceTokenSMSCommandName = spacetokens.nextToken();
AllCommand(FirstSpaceTokenSMSCommand,SixthSpaceTokenSMSCommandName,AreaName);
}
else
{
for(int q=0;q<32;q++)
{
for(int r=0;r<22;r++)
{
if (AreaName[q][r].toUpperCase().equals(FifthSpaceTokenSMSCommandName.trim().toUpperCase()))
{
String FifthSpaceTokenSMSCommand = AreaName[o][p];
System.out.println(FifthSpaceTokenSMSCommandName.trim().toUpperCase()+" FifthSpaceTokenSMSCommandName is found in database ");
String SixthSpaceTokenSMSCommandName = spacetokens.nextToken();
if ("STATUS".equals(SixthSpaceTokenSMSCommandName.trim().toUpperCase()))
{
System.out.println(SixthSpaceTokenSMSCommandName.trim().toUpperCase()+" SixthSpaceTokenSMSCommandName is found in database ");
String SeventhSpaceTokenSMSCommandName = spacetokens.nextToken();
StatusCommand(FirstSpaceTokenSMSCommand,SixthSpaceTokenSMSCommandName,AreaName);
}
else if("ALL".equals(SixthSpaceTokenSMSCommandName.trim().toUpperCase()))
{
System.out.println(SixthSpaceTokenSMSCommandName.trim().toUpperCase()+" SixthSpaceTokenSMSCommandName is found in database ");
String SeventhSpaceTokenSMSCommandName = spacetokens.nextToken();
AllCommand(FirstSpaceTokenSMSCommand,SixthSpaceTokenSMSCommandName,AreaName);
}
else
{
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
//This Else is for Comma Token is More Than 1
else
{
System.out.println("Comma Token in Enter Token is "+commatokens.countTokens()+" And It's a Multiple SMS Command");
if(commatokens.countTokens() >16)
{
System.out.println("SMS Command Is More Than "+commatokens.countTokens());
// SendErrorMessage("You Have Write More Than Six Words");
}
// This else is for Comma token not greater than 16
else
{
// pst.setString(11, null);
int fieldnumber = 12;
char CharPosForToggle = '0';
while(commatokens.hasMoreTokens())
{
}
}
}
// aPinNumberInt = Integer.parseInt(PinNumber);
aPinNumberInt = PinNumber;
if (aPinNumberInt!=0)
{
switch (aPinNumberInt)
{
case 1:
aPinNumberInt =7;
break;
case 2:
aPinNumberInt =6;
break;
case 3:
aPinNumberInt =5;
break;
case 4:
aPinNumberInt =4;
break;
case 5:
aPinNumberInt =3;
break;
case 6:
aPinNumberInt =2;
break;
case 7:
aPinNumberInt =1;
break;
case 8:
aPinNumberInt =0;
break;
}
}
else if ("ALL".equals(SecondSpaceTokenSMSCommandName.trim().toUpperCase()))
{
System.out.println(" Device Pin Number is ALL found in database And ");
aPinNumberInt = 10;
DataBaseNotFound = 1;
}
else
{
System.out.println(" Device Pin Number not found in database ");
// SendErrorMessage();
}
}
if ("".equals(SecondSpaceTokenSMSCommandName.trim()))
{
System.out.println(SecondSpaceTokenSMSCommandName+" LPT_Device_Mobile_Name Not found in database");
// SendErrorMessage();
}
}
}
}
else
{
String TokenCommandName = spacetokens.nextToken();
System.out.println("fieldNumber is "+fieldnumber+" and Spacetoken Is "+TokenCommandName);
if ("ON".equals(TokenCommandName.trim().toUpperCase()))
{
PinCommand = "1";
System.out.println("Command is "+TokenCommandName+" And PinCommand is "+PinCommand);
// SendErrorMessage();
}
else if("OFF".equals(TokenCommandName.trim().toUpperCase()))
{
PinCommand = "0";
System.out.println("Command is "+TokenCommandName+" And PinCommand is "+PinCommand);
}
else if("TG".equals(TokenCommandName.trim().toUpperCase()))
{
PinCommand = "2";
System.out.println("Command is "+TokenCommandName+" And PinCommand is "+PinCommand);
}
else
{
System.out.println("Command is "+TokenCommandName+" And Command Is Not Supported");
}
}
fieldnumber++;
}
if(DataBaseNotFound!=0)
{
Addr=0x378;
// do_read(Addr);
String stat = do_read_register(Addr);
int statlength = stat.length();
System.out.println("Binary Number is "+stat+" And Stat Length is "+statlength);
if(statlength<8)
{
for (int i=0;i<(8-statlength);i++)
{
stat = "0".concat(stat);
System.out.println("Concatenated string "+stat);
}
}
char[] chars = stat.toCharArray();
System.out.println("Binary String Before replacement: "+stat);
//int aPinNumberInt = Integer.parseInt(PinNumber);
char firstLetterOfPinCommand = PinCommand.charAt(0);
if (aPinNumberInt<=7)
{
if ("2".equals(PinCommand.trim().toUpperCase()))
{
CharPosForToggle = stat.charAt(aPinNumberInt-1);
if(CharPosForToggle=='0')
{
firstLetter = '1';
}
else
{
firstLetter = '0';
}
stat = replaceCharAt(stat, aPinNumberInt, firstLetter);
System.out.println("Binary String After replacement: "+stat);
}
else
{
stat = replaceCharAt(stat, aPinNumberInt, firstLetter);
System.out.println("Binary String After replacement: "+stat);
}
}
else
{
if ("0".equals(PinCommand.trim().toUpperCase()))
{
stat = "00000000";
System.out.println("Binary String After replacement: "+stat);
}
else if ("1".equals(PinCommand.trim().toUpperCase()))
{
stat = "11111111";
System.out.println("Binary String After replacement: "+stat);
}
else
{
for(int k=0;k<8;k++)
{
CharPosForToggle = stat.charAt(k);
if(CharPosForToggle=='0')
{
firstLetter = '1';
}
else
{
firstLetter = '0';
}
stat = replaceCharAt(stat, k, firstLetter);
}
}
}
Addr=0x378;
String writedatum = Integer.toHexString(Integer.parseInt(stat,2));
System.out.println("Check To See hexstring : "+writedatum);
//datum = writedatum;
datum = Short.parseShort(writedatum, 16) ;
//Short sObj2 = Short.valueOf(str);
do_write(Addr,datum);
stat = do_read_register(Addr);
System.out.println("Check To See if we write properly: "+stat);
}
if(fieldnumber==14)
{
for(int i = 14; i <52; i++)
{
//pst.setString(i,null)
System.out.println("Field Number is "+i);
}
}
else
{
if(fieldnumber==15)
{
System.out.println("Unfinished command. Need another token");
// SendErrorMessage();
}
else
{
for(int i = 16; i <52; i++)
{
//pst.setString(i,null)
System.out.println("Field Number is "+i);
}
}
System.out.println("We are in tg mode. Field Number is ");
}
}
}
}
else
{
if(commatokens.countTokens() > 7)
{
// SendErrorMessage();
}
else
{
System.out.println("Comma Token is "+commatokens.countTokens());
int fieldnumber = 12;
int firstset = 1;
int separatorset = 1;
boolean ISItFirstComma = true;
while(commatokens.hasMoreTokens())
{
// System.out.println(commatokens.nextToken());
// pst.setString(fieldnumber, (tokens.nextToken().length() == 0 ? "" : "Enter"));
String FirstBlockLineCut = commatokens.nextToken().trim();
StringTokenizer FirstBlockSpacetokens = new StringTokenizer(FirstBlockLineCut, " ");
int FirstBlockHighestToken = FirstBlockSpacetokens.countTokens();
System.out.println("Highest First Block Space Token in a Comma Token is: "+FirstBlockHighestToken);
String FirstBlockFirstToken = FirstBlockSpacetokens.nextToken();
if(",".equals(FirstBlockFirstToken.trim()) & ISItFirstComma & fieldnumber==12)
{
ISItFirstComma = true;
//SendErrorMessage("You Put Comma First");
System.out.println("You Put a Comma before anything....Separator_"+separatorset+" : "+FirstBlockFirstToken);
separatorset++;
fieldnumber++;
System.out.println("FieldNumber is :"+fieldnumber);
}
else if(",".equals(FirstBlockFirstToken.trim()) & ISItFirstComma)
{
ISItFirstComma = true;
//SendErrorMessage("You Put Comma First");
System.out.println("You Put a Comma after a comma....Separator_"+separatorset+" : "+FirstBlockFirstToken);
separatorset++;
fieldnumber++;
System.out.println("FieldNumber is :"+fieldnumber);
}
else if(",".equals(FirstBlockFirstToken.trim()))
{
ISItFirstComma = true;
System.out.println("Separator_"+separatorset+" : "+FirstBlockFirstToken);
separatorset++;
fieldnumber++;
System.out.println("FieldNumber is :"+fieldnumber);
}
else
{
if(FirstBlockHighestToken==4)
{
}
else
{
ISItFirstComma = false;
while(FirstBlockSpacetokens.hasMoreTokens())
{
String FirstBlockMobileDeviceToken = FirstBlockSpacetokens.nextToken();
for (int m=0;m<2;m++)
{
if(AreaName[m][1].trim().toUpperCase().equals(FirstBlockMobileDeviceToken.trim().toUpperCase()))
{
System.out.println(FirstBlockMobileDeviceToken+" Device Mobile Name is found in database ");
System.out.println("LPT_Device_Mobile_name : " + FirstBlockMobileDeviceToken);
String FirstBlockTokenPinName = FirstBlockSpacetokens.nextToken();
for (int n=0;n<10;n++)
{
if(AreaName[m][n].trim().toUpperCase().equals(FirstBlockTokenPinName.trim().toUpperCase()))
{
System.out.println(FirstBlockTokenPinName+" First Block Device Name is found in database ");
PinNumber = n-1;
DataBaseNotFound = 1;
System.out.println(PinNumber+" is Pin Number of "+FirstBlockTokenPinName+" found in database ");
// aPinNumberInt = Integer.parseInt(PinNumber);
aPinNumberInt = PinNumber;
if (aPinNumberInt!=0)
{
switch (aPinNumberInt)
{
case 1:
aPinNumberInt =7;
break;
case 2:
aPinNumberInt =6;
break;
case 3:
aPinNumberInt =5;
break;
case 4:
aPinNumberInt =4;
break;
case 5:
aPinNumberInt =3;
break;
case 6:
aPinNumberInt =2;
break;
case 7:
aPinNumberInt =1;
break;
case 8:
aPinNumberInt =0;
break;
}
}
String FirstBlockTokenCommandName = FirstBlockSpacetokens.nextToken();
System.out.println("fieldNumber is "+fieldnumber+" and Spacetoken Is "+FirstBlockTokenCommandName);
if ("ON".equals(FirstBlockTokenCommandName.trim().toUpperCase()))
{
PinCommand = "1";
System.out.println("Command is "+FirstBlockTokenCommandName+" And PinCommand is "+PinCommand);
// SendErrorMessage();
}
else if("OFF".equals(FirstBlockTokenCommandName.trim().toUpperCase()))
{
PinCommand = "0";
System.out.println("Command is "+FirstBlockTokenCommandName+" And PinCommand is "+PinCommand);
}
else if("TG".equals(FirstBlockTokenCommandName.trim().toUpperCase()))
{
PinCommand = "2";
System.out.println("Command is "+FirstBlockTokenCommandName+" And PinCommand is "+PinCommand);
}
else
{
System.out.println("Command is "+FirstBlockTokenCommandName+" And Command Is Not Supported");
}
}
else if ("ALL".equals(FirstBlockTokenPinName.trim().toUpperCase()))
{
System.out.println(" Device Pin Number is ALL found in database And ");
aPinNumberInt = 10;
DataBaseNotFound = 1;
}
else
{
System.out.println(" Device Pin Number not found in database ");
// SendErrorMessage();
}
}
}
}
System.out.println("Device_name_"+firstset+" : "+FirstBlockMobileDeviceToken);
fieldnumber++;
System.out.println("FieldNumber is :"+fieldnumber);
System.out.println("Command_name_"+firstset+" : "+FirstBlockMobileDeviceToken);
fieldnumber++;
System.out.println("FieldNumber is :"+fieldnumber);
//pst.setString(i,null)
System.out.println("from_toggle_"+firstset+" : "+"//pst.setString("+fieldnumber+",null)");
fieldnumber++;
System.out.println("FieldNumber is :"+fieldnumber);
System.out.println("to_toggle_"+firstset+" : "+"//pst.setString("+fieldnumber+",null)");
fieldnumber++;
System.out.println("FieldNumber is :"+fieldnumber);
firstset++;
}
}
}
}
}
}
}
}
| apache-2.0 |
jamesnetherton/betamax-arquillian-wildfly | extension/src/main/java/com/github/jamesnetherton/betamax/arquillian/BetamaxAuxiliaryArchiveAppender.java | 4655 | /*
* #%L
* Betamax Arquillian Wildfly :: Extension
* %%
* Copyright (C) 2016 James Netherton
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package com.github.jamesnetherton.betamax.arquillian;
import com.github.jamesnetherton.betamax.arquillian.utils.ManifestBuilder;
import org.jboss.arquillian.container.test.spi.RemoteLoadableExtension;
import org.jboss.arquillian.container.test.spi.client.deployment.AuxiliaryArchiveAppender;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.jboss.shrinkwrap.resolver.api.maven.Maven;
import software.betamax.Configuration;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
/**
* A {@link AuxiliaryArchiveAppender} implementation that appends Betamax dependencies not provided by the WildFly
* container to an auxiliary deployment. If a betamax.properties configuration file is discovered on the classpath,
* this is also added to the deployment.
*/
public class BetamaxAuxiliaryArchiveAppender implements AuxiliaryArchiveAppender {
private static final Pattern BETAMAX_LIBS = Pattern.compile("(littleproxy-.*|betamax-.*|tika-.*|commons-lang3.*)");
private static final String BETAMAX_GROUP_ID = "software.betamax";
private static final String BETAMAX_ARTIFACT_ID = "betamax-junit";
public Archive<?> createAuxiliaryArchive() {
JavaArchive archive = ShrinkWrap.create(JavaArchive.class, "betamax-extension.jar")
// Add extension
.addPackage(BetamaxLoadableExtension.class.getPackage())
// Add utils
.addClass(ManifestBuilder.class)
// Add extensions
.addAsServiceProvider(RemoteLoadableExtension.class, BetamaxRemoteLoadableExtension.class);
// Add Betamax library dependencies
for (File file : collectBetamaxDependencies()) {
archive.merge(ShrinkWrap.createFromZipFile(JavaArchive.class, file));
}
// Add Betamax config file if it exists
InputStream stream = Configuration.class.getResourceAsStream("/betamax.properties");
if (stream != null) {
try {
archive.add(new StringAsset(convertStreamToString(stream)), "betamax.properties");
} catch (IOException e) {
e.printStackTrace();
}
}
return archive;
}
private File[] collectBetamaxDependencies() {
File[] dependencies = Maven.resolver().
resolve(getBetamaxGAV()).
withTransitivity().
asFile();
List<File> filtered = Arrays.stream(dependencies)
.filter((d) -> (BETAMAX_LIBS.matcher(d.getName()).matches()))
.collect(Collectors.toList());
return filtered.toArray(new File[0]);
}
private String convertStreamToString(InputStream inputStream) throws IOException {
try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
byte[] buffer = new byte[1024];
int len = inputStream.read(buffer);
while (len >= 0) {
outputStream.write(buffer, 0, len);
len = inputStream.read(buffer);
}
return new String(outputStream.toByteArray());
} finally {
inputStream.close();
}
}
private String getBetamaxGAV() {
try (InputStream input = BetamaxAuxiliaryArchiveAppender.class.getResourceAsStream("betamax.version")) {
BufferedReader br = new BufferedReader(new InputStreamReader(input));
return String.format("%s:%s:%s", BETAMAX_GROUP_ID, BETAMAX_ARTIFACT_ID, br.readLine());
} catch (IOException e) {
throw new IllegalStateException("Failed reading betamax version manifest", e);
}
}
}
| apache-2.0 |
orfjackal/dimdwarf | dimdwarf-core/src/main/java/net/orfjackal/dimdwarf/tasks/TaskScoped.java | 592 | // Copyright © 2008-2010 Esko Luontola <www.orfjackal.net>
// This software is released under the Apache License 2.0.
// The license text is at http://dimdwarf.sourceforge.net/LICENSE
package net.orfjackal.dimdwarf.tasks;
import javax.inject.Scope;
import java.lang.annotation.*;
/**
* Indicates that an object needs to be task scoped. Each task will run in a transaction
* which is automatically committed when the task ends.
*
* @see net.orfjackal.dimdwarf.tasks.TaskExecutor
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Scope
public @interface TaskScoped {
}
| apache-2.0 |
jentfoo/aws-sdk-java | aws-java-sdk-ssm/src/main/java/com/amazonaws/services/simplesystemsmanagement/model/transform/UpdateMaintenanceWindowTaskRequestProtocolMarshaller.java | 2911 | /*
* Copyright 2014-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.simplesystemsmanagement.model.transform;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.Request;
import com.amazonaws.http.HttpMethodName;
import com.amazonaws.services.simplesystemsmanagement.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.protocol.*;
import com.amazonaws.protocol.Protocol;
import com.amazonaws.annotation.SdkInternalApi;
/**
* UpdateMaintenanceWindowTaskRequest Marshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class UpdateMaintenanceWindowTaskRequestProtocolMarshaller implements
Marshaller<Request<UpdateMaintenanceWindowTaskRequest>, UpdateMaintenanceWindowTaskRequest> {
private static final OperationInfo SDK_OPERATION_BINDING = OperationInfo.builder().protocol(Protocol.AWS_JSON).requestUri("/")
.httpMethodName(HttpMethodName.POST).hasExplicitPayloadMember(false).hasPayloadMembers(true)
.operationIdentifier("AmazonSSM.UpdateMaintenanceWindowTask").serviceName("AWSSimpleSystemsManagement").build();
private final com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory;
public UpdateMaintenanceWindowTaskRequestProtocolMarshaller(com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory) {
this.protocolFactory = protocolFactory;
}
public Request<UpdateMaintenanceWindowTaskRequest> marshall(UpdateMaintenanceWindowTaskRequest updateMaintenanceWindowTaskRequest) {
if (updateMaintenanceWindowTaskRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
final ProtocolRequestMarshaller<UpdateMaintenanceWindowTaskRequest> protocolMarshaller = protocolFactory.createProtocolMarshaller(
SDK_OPERATION_BINDING, updateMaintenanceWindowTaskRequest);
protocolMarshaller.startMarshalling();
UpdateMaintenanceWindowTaskRequestMarshaller.getInstance().marshall(updateMaintenanceWindowTaskRequest, protocolMarshaller);
return protocolMarshaller.finishMarshalling();
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
}
}
| apache-2.0 |
lmjacksoniii/hazelcast | hazelcast/src/main/java/com/hazelcast/cache/impl/CacheEntryCountResolver.java | 1408 | /*
* Copyright (c) 2008-2016, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.cache.impl;
/**
* Contract point for tracking count of stored cache entries.
*/
public abstract class CacheEntryCountResolver {
public abstract long getEntryCount();
public static CacheEntryCountResolver createEntryCountResolver(CacheContext cacheContext) {
return new CacheContextBackedEntryCountResolver(cacheContext);
}
private static class CacheContextBackedEntryCountResolver extends CacheEntryCountResolver {
private final CacheContext cacheContext;
public CacheContextBackedEntryCountResolver(CacheContext cacheContext) {
this.cacheContext = cacheContext;
}
@Override
public long getEntryCount() {
return cacheContext.getEntryCount();
}
}
}
| apache-2.0 |
michaelliao/shici | web/src/main/java/com/itranswarp/shici/bean/Hit.java | 250 | package com.itranswarp.shici.bean;
/**
* JavaBean for search hits.
*
* @author liaoxuefeng
*/
public class Hit {
public final long id;
public final float score;
public Hit(long id, float score) {
this.id = id;
this.score = score;
}
}
| apache-2.0 |
dagnir/aws-sdk-java | aws-java-sdk-simpleworkflow/src/main/java/com/amazonaws/services/simpleworkflow/model/transform/DecisionMarshaller.java | 7787 | /*
* Copyright 2012-2017 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.simpleworkflow.model.transform;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.services.simpleworkflow.model.*;
import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;
/**
* DecisionMarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class DecisionMarshaller {
private static final MarshallingInfo<String> DECISIONTYPE_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("decisionType").build();
private static final MarshallingInfo<StructuredPojo> SCHEDULEACTIVITYTASKDECISIONATTRIBUTES_BINDING = MarshallingInfo.builder(MarshallingType.STRUCTURED)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("scheduleActivityTaskDecisionAttributes").build();
private static final MarshallingInfo<StructuredPojo> REQUESTCANCELACTIVITYTASKDECISIONATTRIBUTES_BINDING = MarshallingInfo
.builder(MarshallingType.STRUCTURED).marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("requestCancelActivityTaskDecisionAttributes")
.build();
private static final MarshallingInfo<StructuredPojo> COMPLETEWORKFLOWEXECUTIONDECISIONATTRIBUTES_BINDING = MarshallingInfo
.builder(MarshallingType.STRUCTURED).marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("completeWorkflowExecutionDecisionAttributes")
.build();
private static final MarshallingInfo<StructuredPojo> FAILWORKFLOWEXECUTIONDECISIONATTRIBUTES_BINDING = MarshallingInfo.builder(MarshallingType.STRUCTURED)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("failWorkflowExecutionDecisionAttributes").build();
private static final MarshallingInfo<StructuredPojo> CANCELWORKFLOWEXECUTIONDECISIONATTRIBUTES_BINDING = MarshallingInfo
.builder(MarshallingType.STRUCTURED).marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("cancelWorkflowExecutionDecisionAttributes")
.build();
private static final MarshallingInfo<StructuredPojo> CONTINUEASNEWWORKFLOWEXECUTIONDECISIONATTRIBUTES_BINDING = MarshallingInfo
.builder(MarshallingType.STRUCTURED).marshallLocation(MarshallLocation.PAYLOAD)
.marshallLocationName("continueAsNewWorkflowExecutionDecisionAttributes").build();
private static final MarshallingInfo<StructuredPojo> RECORDMARKERDECISIONATTRIBUTES_BINDING = MarshallingInfo.builder(MarshallingType.STRUCTURED)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("recordMarkerDecisionAttributes").build();
private static final MarshallingInfo<StructuredPojo> STARTTIMERDECISIONATTRIBUTES_BINDING = MarshallingInfo.builder(MarshallingType.STRUCTURED)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("startTimerDecisionAttributes").build();
private static final MarshallingInfo<StructuredPojo> CANCELTIMERDECISIONATTRIBUTES_BINDING = MarshallingInfo.builder(MarshallingType.STRUCTURED)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("cancelTimerDecisionAttributes").build();
private static final MarshallingInfo<StructuredPojo> SIGNALEXTERNALWORKFLOWEXECUTIONDECISIONATTRIBUTES_BINDING = MarshallingInfo
.builder(MarshallingType.STRUCTURED).marshallLocation(MarshallLocation.PAYLOAD)
.marshallLocationName("signalExternalWorkflowExecutionDecisionAttributes").build();
private static final MarshallingInfo<StructuredPojo> REQUESTCANCELEXTERNALWORKFLOWEXECUTIONDECISIONATTRIBUTES_BINDING = MarshallingInfo
.builder(MarshallingType.STRUCTURED).marshallLocation(MarshallLocation.PAYLOAD)
.marshallLocationName("requestCancelExternalWorkflowExecutionDecisionAttributes").build();
private static final MarshallingInfo<StructuredPojo> STARTCHILDWORKFLOWEXECUTIONDECISIONATTRIBUTES_BINDING = MarshallingInfo
.builder(MarshallingType.STRUCTURED).marshallLocation(MarshallLocation.PAYLOAD)
.marshallLocationName("startChildWorkflowExecutionDecisionAttributes").build();
private static final MarshallingInfo<StructuredPojo> SCHEDULELAMBDAFUNCTIONDECISIONATTRIBUTES_BINDING = MarshallingInfo.builder(MarshallingType.STRUCTURED)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("scheduleLambdaFunctionDecisionAttributes").build();
private static final DecisionMarshaller instance = new DecisionMarshaller();
public static DecisionMarshaller getInstance() {
return instance;
}
/**
* Marshall the given parameter object.
*/
public void marshall(Decision decision, ProtocolMarshaller protocolMarshaller) {
if (decision == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(decision.getDecisionType(), DECISIONTYPE_BINDING);
protocolMarshaller.marshall(decision.getScheduleActivityTaskDecisionAttributes(), SCHEDULEACTIVITYTASKDECISIONATTRIBUTES_BINDING);
protocolMarshaller.marshall(decision.getRequestCancelActivityTaskDecisionAttributes(), REQUESTCANCELACTIVITYTASKDECISIONATTRIBUTES_BINDING);
protocolMarshaller.marshall(decision.getCompleteWorkflowExecutionDecisionAttributes(), COMPLETEWORKFLOWEXECUTIONDECISIONATTRIBUTES_BINDING);
protocolMarshaller.marshall(decision.getFailWorkflowExecutionDecisionAttributes(), FAILWORKFLOWEXECUTIONDECISIONATTRIBUTES_BINDING);
protocolMarshaller.marshall(decision.getCancelWorkflowExecutionDecisionAttributes(), CANCELWORKFLOWEXECUTIONDECISIONATTRIBUTES_BINDING);
protocolMarshaller.marshall(decision.getContinueAsNewWorkflowExecutionDecisionAttributes(),
CONTINUEASNEWWORKFLOWEXECUTIONDECISIONATTRIBUTES_BINDING);
protocolMarshaller.marshall(decision.getRecordMarkerDecisionAttributes(), RECORDMARKERDECISIONATTRIBUTES_BINDING);
protocolMarshaller.marshall(decision.getStartTimerDecisionAttributes(), STARTTIMERDECISIONATTRIBUTES_BINDING);
protocolMarshaller.marshall(decision.getCancelTimerDecisionAttributes(), CANCELTIMERDECISIONATTRIBUTES_BINDING);
protocolMarshaller.marshall(decision.getSignalExternalWorkflowExecutionDecisionAttributes(),
SIGNALEXTERNALWORKFLOWEXECUTIONDECISIONATTRIBUTES_BINDING);
protocolMarshaller.marshall(decision.getRequestCancelExternalWorkflowExecutionDecisionAttributes(),
REQUESTCANCELEXTERNALWORKFLOWEXECUTIONDECISIONATTRIBUTES_BINDING);
protocolMarshaller.marshall(decision.getStartChildWorkflowExecutionDecisionAttributes(), STARTCHILDWORKFLOWEXECUTIONDECISIONATTRIBUTES_BINDING);
protocolMarshaller.marshall(decision.getScheduleLambdaFunctionDecisionAttributes(), SCHEDULELAMBDAFUNCTIONDECISIONATTRIBUTES_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
}
}
| apache-2.0 |
jenetics/jenetics | jenetics.ext/src/main/java/io/jenetics/ext/moea/GeneralObjectVec.java | 1604 | /*
* Java Genetic Algorithm Library (@__identifier__@).
* Copyright (c) @__year__@ Franz Wilhelmstötter
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Author:
* Franz Wilhelmstötter (franz.wilhelmstoetter@gmail.com)
*/
package io.jenetics.ext.moea;
import java.util.Arrays;
import java.util.Comparator;
/**
* @author <a href="mailto:franz.wilhelmstoetter@gmail.com">Franz Wilhelmstötter</a>
* @version 5.2
* @since 5.2
*/
final class GeneralObjectVec<T> extends GeneralVec<T[]> {
GeneralObjectVec(
final T[] data,
final ElementComparator<T[]> comparator,
final ElementDistance<T[]> distance,
final Comparator<T[]> dominance
) {
super(data, comparator, distance, dominance);
}
@Override
public int length() {
return _data.length;
}
@Override
public int hashCode() {
return Arrays.hashCode(_data);
}
@Override
public boolean equals(final Object obj) {
return obj == this ||
obj instanceof GeneralObjectVec<?> other &&
Arrays.equals(other._data, _data);
}
@Override
public String toString() {
return Arrays.toString(_data);
}
}
| apache-2.0 |
gurpreet-flipkart/KafkaSql | src/main/java/org/kafka/grep/kafka/ThreadPrintStream.java | 1165 | package org.kafka.grep.kafka;
import java.io.OutputStream;
import java.io.PrintStream;
public class ThreadPrintStream extends PrintStream {
private String last = "";
ThreadLocal<Integer> colorLocal = new ThreadLocal<Integer>() {
int color = 33;
@Override
protected Integer initialValue() {
if (color == 38) {
color = 31;
}
return color++;
}
};
public ThreadPrintStream(OutputStream out) {
super(out);
}
@Override
public void println(String msg) {
if (last.equals(".")) {
System.out.println();
}
last = msg;
int color = colorLocal.get();
String s = "[" + color + "m";
msg = (char) 27 + s + msg + (char) 27 + "[0m";
super.println(msg);
}
@Override
public void print(String msg) {
if (last.equals(".") && !msg.equals(".")) {
System.out.println();
}
last = msg;
int color = colorLocal.get();
String s = "[" + color + "m";
msg = (char) 27 + s + msg + (char) 27 + "[0m";
super.print(msg);
}
}
| apache-2.0 |
gavin2lee/incubator | docs/sourcecodes/OpenBridge-passos-ui/ob-monitor-web/src/main/java/com/harmazing/openbridge/alarm/controller/TeamController.java | 5137 | package com.harmazing.openbridge.alarm.controller;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.alibaba.fastjson.JSON;
import com.harmazing.framework.authorization.IUser;
import com.harmazing.framework.common.JsonResponse;
import com.harmazing.framework.common.Page;
import com.harmazing.framework.common.controller.AbstractController;
import com.harmazing.framework.util.ExceptionUtil;
import com.harmazing.framework.util.StringUtil;
import com.harmazing.framework.util.WebUtil;
import com.harmazing.openbridge.alarm.model.Team;
import com.harmazing.openbridge.alarm.service.ITeamService;
import com.harmazing.openbridge.sys.user.model.SysUser;
@Controller
@RequestMapping("/teams")
public class TeamController extends AbstractController {
private static final Log logger = LogFactory
.getLog(TeamController.class);
@Autowired
private ITeamService teamService;
@RequestMapping
public String list(HttpServletRequest request, HttpServletResponse response){
return "alarm/team/list";
}
@RequestMapping("/table")
public String list(HttpServletRequest request, HttpServletResponse response,
Integer pageNo,Integer pageSize) {
if(pageNo==null) pageNo = 1;
if(pageSize==null) pageSize = 10;
Page<Team> page = teamService.getPage(pageNo, pageSize);
request.setAttribute("page", page);
return "alarm/team/table";
}
/**
* 列表显示信息
*
* @param request
* @param response
* @return
*/
@RequestMapping("/page")
public String page(HttpServletRequest request,
HttpServletResponse response) {
try {
Map<String, Object> params = new HashMap<String, Object>();
String keyWord = request.getParameter("keyWords");
if (keyWord != null && !keyWord.trim().equals("")) {
params.put("keyword", keyWord);
request.setAttribute("keyWords", keyWord);
}
params.put("pageNo", StringUtil.getIntParam(request, "pageNo", 1));
params.put("pageSize",
StringUtil.getIntParam(request, "pageSize", 10));
// List<Map<String, Object>> pageData = teamService.getPage(pageNo,pageSize);
//request.setAttribute("pageData", pageData);
return getUrlPrefix() + "/page";
} catch (Exception e) {
logger.error("列表页面出错", e);
request.setAttribute("exception", e);
return forward(ERROR);
}
}
@RequestMapping("/add")
public String addTenant(HttpServletRequest request, HttpServletResponse response) {
String id = request.getParameter("id");
Team team = new Team();
if(StringUtil.isNotNull(id)){
team = teamService.get(id);
}
request.setAttribute("team", team);
return "alarm/team/add";
}
@RequestMapping("/saveOrUpdate")
@ResponseBody
public JsonResponse saveOrUpdate(String json,HttpServletRequest request) {
Team team = null;
IUser user = WebUtil.getUserByRequest(request);
JsonResponse jsonResponse = JsonResponse.success();
try{
if(StringUtil.isNotNull(json)){
team = JSON.parseObject(json, Team.class);
}
if(team!=null){
teamService.saveOrUpdate(team,user.getUserId());
}
}catch(Exception e){
jsonResponse = JsonResponse.failure(1, e.getMessage());
}
return jsonResponse;
}
@RequestMapping("/delete")
@ResponseBody
public JsonResponse delete(@RequestParam String id) {
JsonResponse jsonResponse = JsonResponse.success();
try{
teamService.delete(id);
}catch(Exception e){
jsonResponse = JsonResponse.failure(1, ExceptionUtil.getExceptionString(e));
}
return jsonResponse;
}
@RequestMapping("/detail")
public String detail(HttpServletRequest request, HttpServletResponse response) {
String userId = request.getParameter("userId");
SysUser user = teamService.getUserById(userId);
request.setAttribute("user", user);
return "alarm/team/detail";
}
@RequestMapping(value="/listTeam",method = RequestMethod.GET)
public String getTeamName(HttpServletRequest request, HttpServletResponse response){
Map<String, Object> params = new HashMap<String, Object>();
params.put("pageNo", StringUtil.getIntParam(request, "pageNo", 1));
params.put("pageSize",
StringUtil.getIntParam(request, "pageSize", 10));
String keyword = request.getParameter("keyword");
params.put("keyword", keyword);
List<Map<String, Object>> pageData = teamService.Page(params);
request.setAttribute("pageData", pageData);
request.setAttribute("keyword", keyword);
return "alarm/template/listTeam";
}
}
| apache-2.0 |
inbloom/secure-data-service | tools/csv2xml/src/org/slc/sli/sample/entitiesR1/SchoolCategoryItemType.java | 3090 | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2012.12.05 at 01:12:38 PM EST
//
package org.slc.sli.sample.entitiesR1;
import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlEnumValue;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for SchoolCategoryItemType.
*
* <p>The following schema fragment specifies the expected content contained within this class.
* <p>
* <pre>
* <simpleType name="SchoolCategoryItemType">
* <restriction base="{http://www.w3.org/2001/XMLSchema}token">
* <enumeration value="Elementary/Secondary School"/>
* <enumeration value="Elementary School"/>
* <enumeration value="High School"/>
* <enumeration value="Middle School"/>
* <enumeration value="Junior High School"/>
* <enumeration value="SecondarySchool"/>
* <enumeration value="Ungraded"/>
* <enumeration value="Adult School"/>
* <enumeration value="Infant/toddler School"/>
* <enumeration value="Preschool/early childhood"/>
* <enumeration value="Primary School"/>
* <enumeration value="Intermediate School"/>
* <enumeration value="All Levels"/>
* </restriction>
* </simpleType>
* </pre>
*
*/
@XmlType(name = "SchoolCategoryItemType")
@XmlEnum
public enum SchoolCategoryItemType {
@XmlEnumValue("Elementary/Secondary School")
ELEMENTARY_SECONDARY_SCHOOL("Elementary/Secondary School"),
@XmlEnumValue("Elementary School")
ELEMENTARY_SCHOOL("Elementary School"),
@XmlEnumValue("High School")
HIGH_SCHOOL("High School"),
@XmlEnumValue("Middle School")
MIDDLE_SCHOOL("Middle School"),
@XmlEnumValue("Junior High School")
JUNIOR_HIGH_SCHOOL("Junior High School"),
@XmlEnumValue("SecondarySchool")
SECONDARY_SCHOOL("SecondarySchool"),
@XmlEnumValue("Ungraded")
UNGRADED("Ungraded"),
@XmlEnumValue("Adult School")
ADULT_SCHOOL("Adult School"),
@XmlEnumValue("Infant/toddler School")
INFANT_TODDLER_SCHOOL("Infant/toddler School"),
@XmlEnumValue("Preschool/early childhood")
PRESCHOOL_EARLY_CHILDHOOD("Preschool/early childhood"),
@XmlEnumValue("Primary School")
PRIMARY_SCHOOL("Primary School"),
@XmlEnumValue("Intermediate School")
INTERMEDIATE_SCHOOL("Intermediate School"),
@XmlEnumValue("All Levels")
ALL_LEVELS("All Levels");
private final String value;
SchoolCategoryItemType(String v) {
value = v;
}
public String value() {
return value;
}
public static SchoolCategoryItemType fromValue(String v) {
for (SchoolCategoryItemType c: SchoolCategoryItemType.values()) {
if (c.value.equals(v)) {
return c;
}
}
throw new IllegalArgumentException(v);
}
}
| apache-2.0 |
m-m-m/client | ui/widget/impl-web-gwt/src/main/java/net/sf/mmm/client/ui/impl/gwt/widget/window/adapter/UiWidgetAdapterGwtAbstractWindow.java | 1770 | /* Copyright (c) The m-m-m Team, Licensed under the Apache License, Version 2.0
* http://www.apache.org/licenses/LICENSE-2.0 */
package net.sf.mmm.client.ui.impl.gwt.widget.window.adapter;
import net.sf.mmm.client.ui.api.widget.UiWidgetRegular;
import net.sf.mmm.client.ui.base.widget.window.adapter.UiWidgetAdapterAbstractWindow;
import net.sf.mmm.client.ui.gwt.widgets.VerticalFlowPanel;
import net.sf.mmm.client.ui.impl.gwt.widget.adapter.UiWidgetAdapterGwtDynamicComposite;
import com.google.gwt.dom.client.Element;
import com.google.gwt.user.client.ui.Panel;
/**
* This is the implementation of {@link UiWidgetAdapterAbstractWindow} using GWT based on {@link Panel}. <br>
*
* @author Joerg Hohwiller (hohwille at users.sourceforge.net)
* @since 1.0.0
* @param <WIDGET> is the generic type of {@link #getToplevelWidget()}.
*/
public abstract class UiWidgetAdapterGwtAbstractWindow<WIDGET extends Panel> extends
UiWidgetAdapterGwtDynamicComposite<WIDGET, UiWidgetRegular> implements UiWidgetAdapterAbstractWindow {
/**
* The constructor.
*/
public UiWidgetAdapterGwtAbstractWindow() {
super();
}
/**
* @return the content panel.
*/
protected abstract VerticalFlowPanel getContentPanel();
/**
* {@inheritDoc}
*/
@Override
public void setEnabled(boolean enabled) {
// TODO Auto-generated method stub
}
/**
* {@inheritDoc}
*/
@Override
public void addChild(UiWidgetRegular child, int index) {
if (index >= 0) {
getContentPanel().insert(getToplevelWidget(child), index);
} else {
getContentPanel().add(getToplevelWidget(child));
}
}
/**
* {@inheritDoc}
*/
@Override
protected Element getSizeElement() {
return getContentPanel().getElement();
}
}
| apache-2.0 |
roberthafner/flowable-engine | modules/flowable-ui-modeler/flowable-ui-modeler-logic/src/main/java/org/activiti/app/service/editor/ActivitiModelQueryService.java | 8804 | /* 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.activiti.app.service.editor;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamReader;
import org.activiti.app.domain.editor.AbstractModel;
import org.activiti.app.domain.editor.AppDefinition;
import org.activiti.app.domain.editor.Model;
import org.activiti.app.model.common.ResultListDataRepresentation;
import org.activiti.app.model.editor.AppDefinitionListModelRepresentation;
import org.activiti.app.model.editor.ModelRepresentation;
import org.activiti.app.repository.editor.ModelRepository;
import org.activiti.app.repository.editor.ModelSort;
import org.activiti.app.security.SecurityUtils;
import org.activiti.app.service.api.ModelService;
import org.activiti.app.service.exception.BadRequestException;
import org.activiti.app.service.exception.InternalServerErrorException;
import org.activiti.app.util.XmlUtil;
import org.activiti.bpmn.BpmnAutoLayout;
import org.activiti.bpmn.converter.BpmnXMLConverter;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.editor.language.json.converter.BpmnJsonConverter;
import org.activiti.editor.language.json.converter.util.CollectionUtils;
import org.activiti.idm.api.User;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URLEncodedUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
/**
* @author Tijs Rademakers
*/
@Service
@Transactional
public class ActivitiModelQueryService {
private static final Logger logger = LoggerFactory.getLogger(ActivitiModelQueryService.class);
protected static final String FILTER_SHARED_WITH_ME = "sharedWithMe";
protected static final String FILTER_SHARED_WITH_OTHERS = "sharedWithOthers";
protected static final String FILTER_FAVORITE = "favorite";
protected static final int MIN_FILTER_LENGTH = 1;
@Autowired
protected ModelRepository modelRepository;
@Autowired
protected ModelService modelService;
@Autowired
protected ObjectMapper objectMapper;
protected BpmnXMLConverter bpmnXmlConverter = new BpmnXMLConverter();
protected BpmnJsonConverter bpmnJsonConverter = new BpmnJsonConverter();
public ResultListDataRepresentation getModels(String filter, String sort, Integer modelType, HttpServletRequest request) {
// need to parse the filterText parameter ourselves, due to encoding issues with the default parsing.
String filterText = null;
List<NameValuePair> params = URLEncodedUtils.parse(request.getQueryString(), Charset.forName("UTF-8"));
if (params != null) {
for (NameValuePair nameValuePair : params) {
if ("filterText".equalsIgnoreCase(nameValuePair.getName())) {
filterText = nameValuePair.getValue();
}
}
}
List<ModelRepresentation> resultList = new ArrayList<ModelRepresentation>();
List<Model> models = null;
String validFilter = makeValidFilterText(filterText);
User user = SecurityUtils.getCurrentUserObject();
if (validFilter != null) {
models = modelRepository.findByModelTypeAndCreatedBy(user.getId(), modelType, validFilter, sort);
} else {
models = modelRepository.findByModelTypeAndCreatedBy(user.getId(), modelType, sort);
}
if (CollectionUtils.isNotEmpty(models)) {
List<String> addedModelIds = new ArrayList<String>();
for (Model model : models) {
if (addedModelIds.contains(model.getId()) == false) {
addedModelIds.add(model.getId());
ModelRepresentation representation = createModelRepresentation(model);
resultList.add(representation);
}
}
}
ResultListDataRepresentation result = new ResultListDataRepresentation(resultList);
return result;
}
public ResultListDataRepresentation getModelsToIncludeInAppDefinition() {
List<ModelRepresentation> resultList = new ArrayList<ModelRepresentation>();
User user = SecurityUtils.getCurrentUserObject();
List<String> addedModelIds = new ArrayList<String>();
List<Model> models = modelRepository.findByModelTypeAndCreatedBy(user.getId(), 0, ModelSort.MODIFIED_DESC);
if (CollectionUtils.isNotEmpty(models)) {
for (Model model : models) {
if (addedModelIds.contains(model.getId()) == false) {
addedModelIds.add(model.getId());
ModelRepresentation representation = createModelRepresentation(model);
resultList.add(representation);
}
}
}
ResultListDataRepresentation result = new ResultListDataRepresentation(resultList);
return result;
}
public ModelRepresentation importProcessModel(HttpServletRequest request, MultipartFile file) {
String fileName = file.getOriginalFilename();
if (fileName != null && (fileName.endsWith(".bpmn") || fileName.endsWith(".bpmn20.xml"))) {
try {
XMLInputFactory xif = XmlUtil.createSafeXmlInputFactory();
InputStreamReader xmlIn = new InputStreamReader(file.getInputStream(), "UTF-8");
XMLStreamReader xtr = xif.createXMLStreamReader(xmlIn);
BpmnModel bpmnModel = bpmnXmlConverter.convertToBpmnModel(xtr);
if (CollectionUtils.isEmpty(bpmnModel.getProcesses())) {
throw new BadRequestException("No process found in definition " + fileName);
}
if (bpmnModel.getLocationMap().size() == 0) {
BpmnAutoLayout bpmnLayout = new BpmnAutoLayout(bpmnModel);
bpmnLayout.execute();
}
ObjectNode modelNode = bpmnJsonConverter.convertToJson(bpmnModel);
org.activiti.bpmn.model.Process process = bpmnModel.getMainProcess();
String name = process.getId();
if (StringUtils.isNotEmpty(process.getName())) {
name = process.getName();
}
String description = process.getDocumentation();
ModelRepresentation model = new ModelRepresentation();
model.setKey(process.getId());
model.setName(name);
model.setDescription(description);
model.setModelType(AbstractModel.MODEL_TYPE_BPMN);
Model newModel = modelService.createModel(model, modelNode.toString(), SecurityUtils.getCurrentUserObject());
return new ModelRepresentation(newModel);
} catch (BadRequestException e) {
throw e;
} catch (Exception e) {
logger.error("Import failed for " + fileName, e);
throw new BadRequestException("Import failed for " + fileName + ", error message " + e.getMessage());
}
} else {
throw new BadRequestException("Invalid file name, only .bpmn and .bpmn20.xml files are supported not " + fileName);
}
}
protected ModelRepresentation createModelRepresentation(AbstractModel model) {
ModelRepresentation representation = null;
if (model.getModelType() != null && model.getModelType() == 3) {
representation = new AppDefinitionListModelRepresentation(model);
AppDefinition appDefinition = null;
try {
appDefinition = objectMapper.readValue(model.getModelEditorJson(), AppDefinition.class);
} catch (Exception e) {
logger.error("Error deserializing app " + model.getId(), e);
throw new InternalServerErrorException("Could not deserialize app definition");
}
((AppDefinitionListModelRepresentation) representation).setAppDefinition(appDefinition);
} else {
representation = new ModelRepresentation(model);
}
return representation;
}
protected String makeValidFilterText(String filterText) {
String validFilter = null;
if (filterText != null) {
String trimmed = StringUtils.trim(filterText);
if (trimmed.length() >= MIN_FILTER_LENGTH) {
validFilter = "%" + trimmed.toLowerCase() + "%";
}
}
return validFilter;
}
}
| apache-2.0 |
dadarom/dubbo | dubbo-remoting/dubbo-remoting-netty/src/test/java/com/alibaba/dubbo/remoting/transport/netty/NettyStringTest.java | 2346 | /*
* 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.alibaba.dubbo.remoting.transport.netty;
import com.alibaba.dubbo.common.URL;
import com.alibaba.dubbo.remoting.exchange.ExchangeChannel;
import com.alibaba.dubbo.remoting.exchange.ExchangeServer;
import com.alibaba.dubbo.remoting.exchange.Exchangers;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
/**
* Date: 4/26/11
* Time: 4:13 PM
*/
public class NettyStringTest {
static ExchangeServer server;
static ExchangeChannel client;
@BeforeClass
public static void setUp() throws Exception {
//int port = (int) (1000 * Math.random() + 10000);
int port = 10001;
System.out.println(port);
server = Exchangers.bind(URL.valueOf("telnet://0.0.0.0:" + port + "?server=netty"), new TelnetServerHandler());
client = Exchangers.connect(URL.valueOf("telnet://127.0.0.1:" + port + "?client=netty"), new TelnetClientHandler());
}
@AfterClass
public static void tearDown() throws Exception {
try {
if (server != null)
server.close();
} finally {
if (client != null)
client.close();
}
}
@Test
public void testHandler() throws Exception {
//Thread.sleep(20000);
/*client.request("world\r\n");
Future future = client.request("world", 10000);
String result = (String)future.get();
Assert.assertEquals("Did you say 'world'?\r\n",result);*/
}
} | apache-2.0 |
jasjisdo/spark-newsreel-recommender | metarecommender/src/main/java/de/dailab/newsreel/recommender/metarecommender/util/RequestUtils.java | 2166 | package de.dailab.newsreel.recommender.metarecommender.util;
import de.dailab.newsreel.recommender.common.item.Item;
import de.dailab.newsreel.recommender.metarecommender.delegate.RecommenderDelegate;
import org.apache.log4j.Logger;
/**
* Created by domann on 21.12.15.
*/
public class RequestUtils {
private static final Logger log = Logger.getLogger(RequestUtils.class);
// static {log.setLevel(org.apache.log4j.Level.DEBUG);}
/**
* Create a json response object for recommendation requests.
*
* @param itemsIDs The recommendation result
* @return The recommendation result as json
*/
public static final String getRecommendationResultJSON(String itemsIDs) {
// invalid recommendations result in empty result sets
if (itemsIDs == null || itemsIDs.length() == 0) {
itemsIDs = "[]";
}
// add brackets if needed
else if (!itemsIDs.trim().startsWith("[")) {
itemsIDs = "[" + itemsIDs + "]";
}
// build result as JSON according to formal requirements
String result = "{" + "\"recs\": {" + "\"ints\": {" + "\"3\": "
+ itemsIDs + "}" + "}}";
return result;
}
public static void handleUnknownMessageType(String typeValue, String propertyValue, String entityValue) {
log.error("unknown MessageType: " + typeValue);
log.error(propertyValue + "\n" + entityValue);
}
public static void handleErrorNotification(String propertyValue, String entityValue) {
log.error("error-notification: " + propertyValue + "\n" + entityValue);
}
/**
* Handles item impression by using delegate.
*
* @return response text.
*/
public static String handleUpdate(RecommenderDelegate delegate, Item recommenderItem, Long domainId) {
String response;
if (recommenderItem != null && recommenderItem.getItemID() != null) {
// handle update to all recommenders
delegate.update(recommenderItem, domainId);
}
response = ";item_update successfull";
return response;
}
}
| apache-2.0 |
fakereplace/fakereplace | testsuite/wildfly/src/test/java/a/org/fakereplace/integration/wildfly/resteasy/changepath/HelloWorldResource1.java | 987 | /*
* Copyright 2016, Stuart Douglas, and individual contributors as indicated
* by the @authors tag.
*
* 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 a.org.fakereplace.integration.wildfly.resteasy.changepath;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
@Path("helloworld")
@Produces({"application/xml"})
public class HelloWorldResource1 {
@GET
@Path("/sub")
public String sub() {
return "sub";
}
}
| apache-2.0 |
shawnsky/spring-boot-mybatis-shiro | src/main/java/com/xt/service/impl/UserRoleServiceImpl.java | 698 | package com.xt.service.impl;/**
* Created by Administrator on 2017/7/10.
*/
import com.xt.entity.UserRole;
import com.xt.mapper.UserRoleMapper;
import com.xt.service.UserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* 07-10 17:19
*
* @author xt
**/
@Service("userRoleService")
public class UserRoleServiceImpl implements UserRoleService {
@Autowired
private UserRoleMapper userRoleMapper;
@Override
public void add(UserRole userRole) {
userRoleMapper.add(userRole);
}
@Override
public void removeByRole(String role) {
userRoleMapper.removeByRole(role);
}
}
| apache-2.0 |
mitre-cyber-academy/2015-mobile-challenges | FlashingColorsChallenge/android/app/src/main/java/com/mitre/flashingcolors/ServerInterface.java | 1684 | package com.mitre.flashingcolors;
import android.util.Log;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
public class ServerInterface {
public static String SERVER_URL = "";
public static String sendMsg(String message){
String data = message;
return executeHttpRequest(data);
}
private static String executeHttpRequest(String data) {
String result = "";
try {
URL url = new URL(SERVER_URL+data);
//URL url = new URL(data);
URLConnection connection = url.openConnection();
connection.setDoInput(true);
connection.setUseCaches(false);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
DataInputStream dataIn = new DataInputStream(connection.getInputStream());
String inputLine;
while ((inputLine = dataIn.readLine()) != null) {
result += inputLine;
}
dataIn.close();
} catch (IOException e) {
/*
* In case of an error, we're going to return a null String. This
* can be changed to a specific error message format if the client
* wants to do some error handling. For our simple app, we're just
* going to use the null to communicate a general error in
* retrieving the data.
*/
e.printStackTrace();
result = null;
}
return result;
}
}
| apache-2.0 |
neykov/incubator-brooklyn | software/nosql/src/main/java/brooklyn/entity/nosql/elasticsearch/ElasticSearchNodeImpl.java | 4496 | package brooklyn.entity.nosql.elasticsearch;
import static com.google.common.base.Preconditions.checkNotNull;
import brooklyn.entity.basic.SoftwareProcessImpl;
import brooklyn.event.AttributeSensor;
import brooklyn.event.feed.http.HttpFeed;
import brooklyn.event.feed.http.HttpPollConfig;
import brooklyn.event.feed.http.HttpValueFunctions;
import brooklyn.event.feed.http.JsonFunctions;
import brooklyn.location.access.BrooklynAccessUtils;
import brooklyn.util.guava.Functionals;
import brooklyn.util.guava.Maybe;
import brooklyn.util.guava.MaybeFunctions;
import brooklyn.util.guava.TypeTokens;
import brooklyn.util.http.HttpToolResponse;
import com.google.common.base.Function;
import com.google.common.base.Functions;
import com.google.common.net.HostAndPort;
import com.google.gson.JsonElement;
public class ElasticSearchNodeImpl extends SoftwareProcessImpl implements ElasticSearchNode {
protected static final Function<Maybe<JsonElement>, Maybe<JsonElement>> GET_FIRST_NODE_FROM_NODES = new Function<Maybe<JsonElement>, Maybe<JsonElement>>() {
@Override public Maybe<JsonElement> apply(Maybe<JsonElement> input) {
if (input.isAbsent()) {
return input;
}
return Maybe.fromNullable(input.get().getAsJsonObject().entrySet().iterator().next().getValue());
}
};
protected static final Function<HttpToolResponse, Maybe<JsonElement>> GET_FIRST_NODE = Functionals.chain(HttpValueFunctions.jsonContents(),
MaybeFunctions.<JsonElement>wrap(), JsonFunctions.walkM("nodes"), GET_FIRST_NODE_FROM_NODES);
HttpFeed httpFeed;
@Override
public Class<ElasticSearchNodeDriver> getDriverInterface() {
return ElasticSearchNodeDriver.class;
}
protected static final <T> HttpPollConfig<T> getSensorFromNodeStat(AttributeSensor<T> sensor, String... jsonPath) {
return new HttpPollConfig<T>(sensor)
.onSuccess(Functionals.chain(GET_FIRST_NODE, JsonFunctions.walkM(jsonPath), JsonFunctions.castM(TypeTokens.getRawRawType(sensor.getTypeToken()), null)))
.onFailureOrException(Functions.<T>constant(null));
}
@Override
protected void connectSensors() {
super.connectSensors();
Integer rawPort = getAttribute(HTTP_PORT);
checkNotNull(rawPort, "HTTP_PORT sensors not set for %s; is an acceptable port available?", this);
HostAndPort hp = BrooklynAccessUtils.getBrooklynAccessibleAddress(this, rawPort);
Function<Maybe<JsonElement>, String> getNodeId = new Function<Maybe<JsonElement>, String>() {
@Override public String apply(Maybe<JsonElement> input) {
if (input.isAbsent()) {
return null;
}
return input.get().getAsJsonObject().entrySet().iterator().next().getKey();
}
};
httpFeed = HttpFeed.builder()
.entity(this)
.period(1000)
.baseUri(String.format("http://%s:%s/_nodes/_local/stats", hp.getHostText(), hp.getPort()))
.poll(new HttpPollConfig<Boolean>(SERVICE_UP)
.onSuccess(HttpValueFunctions.responseCodeEquals(200))
.onFailureOrException(Functions.constant(false)))
.poll(new HttpPollConfig<String>(NODE_ID)
.onSuccess(Functionals.chain(HttpValueFunctions.jsonContents(), MaybeFunctions.<JsonElement>wrap(), JsonFunctions.walkM("nodes"), getNodeId))
.onFailureOrException(Functions.constant("")))
.poll(getSensorFromNodeStat(NODE_NAME, "name"))
.poll(getSensorFromNodeStat(DOCUMENT_COUNT, "indices", "docs", "count"))
.poll(getSensorFromNodeStat(STORE_BYTES, "indices", "store", "size_in_bytes"))
.poll(getSensorFromNodeStat(GET_TOTAL, "indices", "get", "total"))
.poll(getSensorFromNodeStat(GET_TIME_IN_MILLIS, "indices", "get", "time_in_millis"))
.poll(getSensorFromNodeStat(SEARCH_QUERY_TOTAL, "indices", "search", "query_total"))
.poll(getSensorFromNodeStat(SEARCH_QUERY_TIME_IN_MILLIS, "indices", "search", "query_time_in_millis"))
.poll(new HttpPollConfig<String>(CLUSTER_NAME)
.onSuccess(HttpValueFunctions.jsonContents("cluster_name", String.class)))
.build();
}
@Override
protected void disconnectSensors() {
if (httpFeed != null) {
httpFeed.stop();
}
}
}
| apache-2.0 |
FAU-Inf2/AuDoscore | tests/forbidden_in_other_class/student/ToTest.java | 163 | public class ToTest {
public static int test() {
return Exploit.test();
}
}
class Exploit {
public static int test() {
return Integer.parseInt("0");
}
}
| apache-2.0 |
giuliojiang/WaterMarker | src/imageutil/Color.java | 1044 | package imageutil;
public class Color
{
private int red;
private int green;
private int blue;
private int alpha;
// public Color(int red, int green, int blue)
// {
// this.red = red;
// this.green = green;
// this.blue = blue;
// this.alpha = 255;
// }
public Color(int alpha, int red, int green, int blue)
{
this.alpha = alpha;
this.red = red;
this.green = green;
this.blue = blue;
}
public int getRed()
{
return red;
}
public int getGreen()
{
return green;
}
public int getBlue()
{
return blue;
}
public int getAlpha()
{
return alpha;
}
public void setRed(int red)
{
this.red = red;
}
public void setGreen(int green)
{
this.green = green;
}
public void setBlue(int blue)
{
this.blue = blue;
}
public void setAlpha(int alpha)
{
this.alpha = alpha;
}
}
| apache-2.0 |
nikelin/Redshape-AS | plugins/src/main/java/com/redshape/plugins/meta/IUpdateSource.java | 929 | /*
* Copyright 2012 Cyril A. Karpenko
*
* 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.redshape.plugins.meta;
import com.redshape.utils.config.IConfig;
/**
* @author Cyril A. Karpenko <self@nikelin.ru>
* @package com.redshape.plugins.meta
* @date 10/11/11 1:21 PM
*/
public interface IUpdateSource {
public String getId();
public String getMethod();
public IConfig getConnection();
}
| apache-2.0 |
dagnir/aws-sdk-java | aws-java-sdk-directory/src/main/java/com/amazonaws/services/directory/AbstractAWSDirectoryServiceAsync.java | 23405 | /*
* Copyright 2012-2017 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.directory;
import javax.annotation.Generated;
import com.amazonaws.services.directory.model.*;
/**
* Abstract implementation of {@code AWSDirectoryServiceAsync}. Convenient method forms pass through to the
* corresponding overload that takes a request object and an {@code AsyncHandler}, which throws an
* {@code UnsupportedOperationException}.
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class AbstractAWSDirectoryServiceAsync extends AbstractAWSDirectoryService implements AWSDirectoryServiceAsync {
protected AbstractAWSDirectoryServiceAsync() {
}
@Override
public java.util.concurrent.Future<AddIpRoutesResult> addIpRoutesAsync(AddIpRoutesRequest request) {
return addIpRoutesAsync(request, null);
}
@Override
public java.util.concurrent.Future<AddIpRoutesResult> addIpRoutesAsync(AddIpRoutesRequest request,
com.amazonaws.handlers.AsyncHandler<AddIpRoutesRequest, AddIpRoutesResult> asyncHandler) {
throw new java.lang.UnsupportedOperationException();
}
@Override
public java.util.concurrent.Future<AddTagsToResourceResult> addTagsToResourceAsync(AddTagsToResourceRequest request) {
return addTagsToResourceAsync(request, null);
}
@Override
public java.util.concurrent.Future<AddTagsToResourceResult> addTagsToResourceAsync(AddTagsToResourceRequest request,
com.amazonaws.handlers.AsyncHandler<AddTagsToResourceRequest, AddTagsToResourceResult> asyncHandler) {
throw new java.lang.UnsupportedOperationException();
}
@Override
public java.util.concurrent.Future<CancelSchemaExtensionResult> cancelSchemaExtensionAsync(CancelSchemaExtensionRequest request) {
return cancelSchemaExtensionAsync(request, null);
}
@Override
public java.util.concurrent.Future<CancelSchemaExtensionResult> cancelSchemaExtensionAsync(CancelSchemaExtensionRequest request,
com.amazonaws.handlers.AsyncHandler<CancelSchemaExtensionRequest, CancelSchemaExtensionResult> asyncHandler) {
throw new java.lang.UnsupportedOperationException();
}
@Override
public java.util.concurrent.Future<ConnectDirectoryResult> connectDirectoryAsync(ConnectDirectoryRequest request) {
return connectDirectoryAsync(request, null);
}
@Override
public java.util.concurrent.Future<ConnectDirectoryResult> connectDirectoryAsync(ConnectDirectoryRequest request,
com.amazonaws.handlers.AsyncHandler<ConnectDirectoryRequest, ConnectDirectoryResult> asyncHandler) {
throw new java.lang.UnsupportedOperationException();
}
@Override
public java.util.concurrent.Future<CreateAliasResult> createAliasAsync(CreateAliasRequest request) {
return createAliasAsync(request, null);
}
@Override
public java.util.concurrent.Future<CreateAliasResult> createAliasAsync(CreateAliasRequest request,
com.amazonaws.handlers.AsyncHandler<CreateAliasRequest, CreateAliasResult> asyncHandler) {
throw new java.lang.UnsupportedOperationException();
}
@Override
public java.util.concurrent.Future<CreateComputerResult> createComputerAsync(CreateComputerRequest request) {
return createComputerAsync(request, null);
}
@Override
public java.util.concurrent.Future<CreateComputerResult> createComputerAsync(CreateComputerRequest request,
com.amazonaws.handlers.AsyncHandler<CreateComputerRequest, CreateComputerResult> asyncHandler) {
throw new java.lang.UnsupportedOperationException();
}
@Override
public java.util.concurrent.Future<CreateConditionalForwarderResult> createConditionalForwarderAsync(CreateConditionalForwarderRequest request) {
return createConditionalForwarderAsync(request, null);
}
@Override
public java.util.concurrent.Future<CreateConditionalForwarderResult> createConditionalForwarderAsync(CreateConditionalForwarderRequest request,
com.amazonaws.handlers.AsyncHandler<CreateConditionalForwarderRequest, CreateConditionalForwarderResult> asyncHandler) {
throw new java.lang.UnsupportedOperationException();
}
@Override
public java.util.concurrent.Future<CreateDirectoryResult> createDirectoryAsync(CreateDirectoryRequest request) {
return createDirectoryAsync(request, null);
}
@Override
public java.util.concurrent.Future<CreateDirectoryResult> createDirectoryAsync(CreateDirectoryRequest request,
com.amazonaws.handlers.AsyncHandler<CreateDirectoryRequest, CreateDirectoryResult> asyncHandler) {
throw new java.lang.UnsupportedOperationException();
}
@Override
public java.util.concurrent.Future<CreateMicrosoftADResult> createMicrosoftADAsync(CreateMicrosoftADRequest request) {
return createMicrosoftADAsync(request, null);
}
@Override
public java.util.concurrent.Future<CreateMicrosoftADResult> createMicrosoftADAsync(CreateMicrosoftADRequest request,
com.amazonaws.handlers.AsyncHandler<CreateMicrosoftADRequest, CreateMicrosoftADResult> asyncHandler) {
throw new java.lang.UnsupportedOperationException();
}
@Override
public java.util.concurrent.Future<CreateSnapshotResult> createSnapshotAsync(CreateSnapshotRequest request) {
return createSnapshotAsync(request, null);
}
@Override
public java.util.concurrent.Future<CreateSnapshotResult> createSnapshotAsync(CreateSnapshotRequest request,
com.amazonaws.handlers.AsyncHandler<CreateSnapshotRequest, CreateSnapshotResult> asyncHandler) {
throw new java.lang.UnsupportedOperationException();
}
@Override
public java.util.concurrent.Future<CreateTrustResult> createTrustAsync(CreateTrustRequest request) {
return createTrustAsync(request, null);
}
@Override
public java.util.concurrent.Future<CreateTrustResult> createTrustAsync(CreateTrustRequest request,
com.amazonaws.handlers.AsyncHandler<CreateTrustRequest, CreateTrustResult> asyncHandler) {
throw new java.lang.UnsupportedOperationException();
}
@Override
public java.util.concurrent.Future<DeleteConditionalForwarderResult> deleteConditionalForwarderAsync(DeleteConditionalForwarderRequest request) {
return deleteConditionalForwarderAsync(request, null);
}
@Override
public java.util.concurrent.Future<DeleteConditionalForwarderResult> deleteConditionalForwarderAsync(DeleteConditionalForwarderRequest request,
com.amazonaws.handlers.AsyncHandler<DeleteConditionalForwarderRequest, DeleteConditionalForwarderResult> asyncHandler) {
throw new java.lang.UnsupportedOperationException();
}
@Override
public java.util.concurrent.Future<DeleteDirectoryResult> deleteDirectoryAsync(DeleteDirectoryRequest request) {
return deleteDirectoryAsync(request, null);
}
@Override
public java.util.concurrent.Future<DeleteDirectoryResult> deleteDirectoryAsync(DeleteDirectoryRequest request,
com.amazonaws.handlers.AsyncHandler<DeleteDirectoryRequest, DeleteDirectoryResult> asyncHandler) {
throw new java.lang.UnsupportedOperationException();
}
@Override
public java.util.concurrent.Future<DeleteSnapshotResult> deleteSnapshotAsync(DeleteSnapshotRequest request) {
return deleteSnapshotAsync(request, null);
}
@Override
public java.util.concurrent.Future<DeleteSnapshotResult> deleteSnapshotAsync(DeleteSnapshotRequest request,
com.amazonaws.handlers.AsyncHandler<DeleteSnapshotRequest, DeleteSnapshotResult> asyncHandler) {
throw new java.lang.UnsupportedOperationException();
}
@Override
public java.util.concurrent.Future<DeleteTrustResult> deleteTrustAsync(DeleteTrustRequest request) {
return deleteTrustAsync(request, null);
}
@Override
public java.util.concurrent.Future<DeleteTrustResult> deleteTrustAsync(DeleteTrustRequest request,
com.amazonaws.handlers.AsyncHandler<DeleteTrustRequest, DeleteTrustResult> asyncHandler) {
throw new java.lang.UnsupportedOperationException();
}
@Override
public java.util.concurrent.Future<DeregisterEventTopicResult> deregisterEventTopicAsync(DeregisterEventTopicRequest request) {
return deregisterEventTopicAsync(request, null);
}
@Override
public java.util.concurrent.Future<DeregisterEventTopicResult> deregisterEventTopicAsync(DeregisterEventTopicRequest request,
com.amazonaws.handlers.AsyncHandler<DeregisterEventTopicRequest, DeregisterEventTopicResult> asyncHandler) {
throw new java.lang.UnsupportedOperationException();
}
@Override
public java.util.concurrent.Future<DescribeConditionalForwardersResult> describeConditionalForwardersAsync(DescribeConditionalForwardersRequest request) {
return describeConditionalForwardersAsync(request, null);
}
@Override
public java.util.concurrent.Future<DescribeConditionalForwardersResult> describeConditionalForwardersAsync(DescribeConditionalForwardersRequest request,
com.amazonaws.handlers.AsyncHandler<DescribeConditionalForwardersRequest, DescribeConditionalForwardersResult> asyncHandler) {
throw new java.lang.UnsupportedOperationException();
}
@Override
public java.util.concurrent.Future<DescribeDirectoriesResult> describeDirectoriesAsync(DescribeDirectoriesRequest request) {
return describeDirectoriesAsync(request, null);
}
@Override
public java.util.concurrent.Future<DescribeDirectoriesResult> describeDirectoriesAsync(DescribeDirectoriesRequest request,
com.amazonaws.handlers.AsyncHandler<DescribeDirectoriesRequest, DescribeDirectoriesResult> asyncHandler) {
throw new java.lang.UnsupportedOperationException();
}
/**
* Simplified method form for invoking the DescribeDirectories operation.
*
* @see #describeDirectoriesAsync(DescribeDirectoriesRequest)
*/
@Override
public java.util.concurrent.Future<DescribeDirectoriesResult> describeDirectoriesAsync() {
return describeDirectoriesAsync(new DescribeDirectoriesRequest());
}
/**
* Simplified method form for invoking the DescribeDirectories operation with an AsyncHandler.
*
* @see #describeDirectoriesAsync(DescribeDirectoriesRequest, com.amazonaws.handlers.AsyncHandler)
*/
@Override
public java.util.concurrent.Future<DescribeDirectoriesResult> describeDirectoriesAsync(
com.amazonaws.handlers.AsyncHandler<DescribeDirectoriesRequest, DescribeDirectoriesResult> asyncHandler) {
return describeDirectoriesAsync(new DescribeDirectoriesRequest(), asyncHandler);
}
@Override
public java.util.concurrent.Future<DescribeEventTopicsResult> describeEventTopicsAsync(DescribeEventTopicsRequest request) {
return describeEventTopicsAsync(request, null);
}
@Override
public java.util.concurrent.Future<DescribeEventTopicsResult> describeEventTopicsAsync(DescribeEventTopicsRequest request,
com.amazonaws.handlers.AsyncHandler<DescribeEventTopicsRequest, DescribeEventTopicsResult> asyncHandler) {
throw new java.lang.UnsupportedOperationException();
}
@Override
public java.util.concurrent.Future<DescribeSnapshotsResult> describeSnapshotsAsync(DescribeSnapshotsRequest request) {
return describeSnapshotsAsync(request, null);
}
@Override
public java.util.concurrent.Future<DescribeSnapshotsResult> describeSnapshotsAsync(DescribeSnapshotsRequest request,
com.amazonaws.handlers.AsyncHandler<DescribeSnapshotsRequest, DescribeSnapshotsResult> asyncHandler) {
throw new java.lang.UnsupportedOperationException();
}
/**
* Simplified method form for invoking the DescribeSnapshots operation.
*
* @see #describeSnapshotsAsync(DescribeSnapshotsRequest)
*/
@Override
public java.util.concurrent.Future<DescribeSnapshotsResult> describeSnapshotsAsync() {
return describeSnapshotsAsync(new DescribeSnapshotsRequest());
}
/**
* Simplified method form for invoking the DescribeSnapshots operation with an AsyncHandler.
*
* @see #describeSnapshotsAsync(DescribeSnapshotsRequest, com.amazonaws.handlers.AsyncHandler)
*/
@Override
public java.util.concurrent.Future<DescribeSnapshotsResult> describeSnapshotsAsync(
com.amazonaws.handlers.AsyncHandler<DescribeSnapshotsRequest, DescribeSnapshotsResult> asyncHandler) {
return describeSnapshotsAsync(new DescribeSnapshotsRequest(), asyncHandler);
}
@Override
public java.util.concurrent.Future<DescribeTrustsResult> describeTrustsAsync(DescribeTrustsRequest request) {
return describeTrustsAsync(request, null);
}
@Override
public java.util.concurrent.Future<DescribeTrustsResult> describeTrustsAsync(DescribeTrustsRequest request,
com.amazonaws.handlers.AsyncHandler<DescribeTrustsRequest, DescribeTrustsResult> asyncHandler) {
throw new java.lang.UnsupportedOperationException();
}
@Override
public java.util.concurrent.Future<DisableRadiusResult> disableRadiusAsync(DisableRadiusRequest request) {
return disableRadiusAsync(request, null);
}
@Override
public java.util.concurrent.Future<DisableRadiusResult> disableRadiusAsync(DisableRadiusRequest request,
com.amazonaws.handlers.AsyncHandler<DisableRadiusRequest, DisableRadiusResult> asyncHandler) {
throw new java.lang.UnsupportedOperationException();
}
@Override
public java.util.concurrent.Future<DisableSsoResult> disableSsoAsync(DisableSsoRequest request) {
return disableSsoAsync(request, null);
}
@Override
public java.util.concurrent.Future<DisableSsoResult> disableSsoAsync(DisableSsoRequest request,
com.amazonaws.handlers.AsyncHandler<DisableSsoRequest, DisableSsoResult> asyncHandler) {
throw new java.lang.UnsupportedOperationException();
}
@Override
public java.util.concurrent.Future<EnableRadiusResult> enableRadiusAsync(EnableRadiusRequest request) {
return enableRadiusAsync(request, null);
}
@Override
public java.util.concurrent.Future<EnableRadiusResult> enableRadiusAsync(EnableRadiusRequest request,
com.amazonaws.handlers.AsyncHandler<EnableRadiusRequest, EnableRadiusResult> asyncHandler) {
throw new java.lang.UnsupportedOperationException();
}
@Override
public java.util.concurrent.Future<EnableSsoResult> enableSsoAsync(EnableSsoRequest request) {
return enableSsoAsync(request, null);
}
@Override
public java.util.concurrent.Future<EnableSsoResult> enableSsoAsync(EnableSsoRequest request,
com.amazonaws.handlers.AsyncHandler<EnableSsoRequest, EnableSsoResult> asyncHandler) {
throw new java.lang.UnsupportedOperationException();
}
@Override
public java.util.concurrent.Future<GetDirectoryLimitsResult> getDirectoryLimitsAsync(GetDirectoryLimitsRequest request) {
return getDirectoryLimitsAsync(request, null);
}
@Override
public java.util.concurrent.Future<GetDirectoryLimitsResult> getDirectoryLimitsAsync(GetDirectoryLimitsRequest request,
com.amazonaws.handlers.AsyncHandler<GetDirectoryLimitsRequest, GetDirectoryLimitsResult> asyncHandler) {
throw new java.lang.UnsupportedOperationException();
}
/**
* Simplified method form for invoking the GetDirectoryLimits operation.
*
* @see #getDirectoryLimitsAsync(GetDirectoryLimitsRequest)
*/
@Override
public java.util.concurrent.Future<GetDirectoryLimitsResult> getDirectoryLimitsAsync() {
return getDirectoryLimitsAsync(new GetDirectoryLimitsRequest());
}
/**
* Simplified method form for invoking the GetDirectoryLimits operation with an AsyncHandler.
*
* @see #getDirectoryLimitsAsync(GetDirectoryLimitsRequest, com.amazonaws.handlers.AsyncHandler)
*/
@Override
public java.util.concurrent.Future<GetDirectoryLimitsResult> getDirectoryLimitsAsync(
com.amazonaws.handlers.AsyncHandler<GetDirectoryLimitsRequest, GetDirectoryLimitsResult> asyncHandler) {
return getDirectoryLimitsAsync(new GetDirectoryLimitsRequest(), asyncHandler);
}
@Override
public java.util.concurrent.Future<GetSnapshotLimitsResult> getSnapshotLimitsAsync(GetSnapshotLimitsRequest request) {
return getSnapshotLimitsAsync(request, null);
}
@Override
public java.util.concurrent.Future<GetSnapshotLimitsResult> getSnapshotLimitsAsync(GetSnapshotLimitsRequest request,
com.amazonaws.handlers.AsyncHandler<GetSnapshotLimitsRequest, GetSnapshotLimitsResult> asyncHandler) {
throw new java.lang.UnsupportedOperationException();
}
@Override
public java.util.concurrent.Future<ListIpRoutesResult> listIpRoutesAsync(ListIpRoutesRequest request) {
return listIpRoutesAsync(request, null);
}
@Override
public java.util.concurrent.Future<ListIpRoutesResult> listIpRoutesAsync(ListIpRoutesRequest request,
com.amazonaws.handlers.AsyncHandler<ListIpRoutesRequest, ListIpRoutesResult> asyncHandler) {
throw new java.lang.UnsupportedOperationException();
}
@Override
public java.util.concurrent.Future<ListSchemaExtensionsResult> listSchemaExtensionsAsync(ListSchemaExtensionsRequest request) {
return listSchemaExtensionsAsync(request, null);
}
@Override
public java.util.concurrent.Future<ListSchemaExtensionsResult> listSchemaExtensionsAsync(ListSchemaExtensionsRequest request,
com.amazonaws.handlers.AsyncHandler<ListSchemaExtensionsRequest, ListSchemaExtensionsResult> asyncHandler) {
throw new java.lang.UnsupportedOperationException();
}
@Override
public java.util.concurrent.Future<ListTagsForResourceResult> listTagsForResourceAsync(ListTagsForResourceRequest request) {
return listTagsForResourceAsync(request, null);
}
@Override
public java.util.concurrent.Future<ListTagsForResourceResult> listTagsForResourceAsync(ListTagsForResourceRequest request,
com.amazonaws.handlers.AsyncHandler<ListTagsForResourceRequest, ListTagsForResourceResult> asyncHandler) {
throw new java.lang.UnsupportedOperationException();
}
@Override
public java.util.concurrent.Future<RegisterEventTopicResult> registerEventTopicAsync(RegisterEventTopicRequest request) {
return registerEventTopicAsync(request, null);
}
@Override
public java.util.concurrent.Future<RegisterEventTopicResult> registerEventTopicAsync(RegisterEventTopicRequest request,
com.amazonaws.handlers.AsyncHandler<RegisterEventTopicRequest, RegisterEventTopicResult> asyncHandler) {
throw new java.lang.UnsupportedOperationException();
}
@Override
public java.util.concurrent.Future<RemoveIpRoutesResult> removeIpRoutesAsync(RemoveIpRoutesRequest request) {
return removeIpRoutesAsync(request, null);
}
@Override
public java.util.concurrent.Future<RemoveIpRoutesResult> removeIpRoutesAsync(RemoveIpRoutesRequest request,
com.amazonaws.handlers.AsyncHandler<RemoveIpRoutesRequest, RemoveIpRoutesResult> asyncHandler) {
throw new java.lang.UnsupportedOperationException();
}
@Override
public java.util.concurrent.Future<RemoveTagsFromResourceResult> removeTagsFromResourceAsync(RemoveTagsFromResourceRequest request) {
return removeTagsFromResourceAsync(request, null);
}
@Override
public java.util.concurrent.Future<RemoveTagsFromResourceResult> removeTagsFromResourceAsync(RemoveTagsFromResourceRequest request,
com.amazonaws.handlers.AsyncHandler<RemoveTagsFromResourceRequest, RemoveTagsFromResourceResult> asyncHandler) {
throw new java.lang.UnsupportedOperationException();
}
@Override
public java.util.concurrent.Future<RestoreFromSnapshotResult> restoreFromSnapshotAsync(RestoreFromSnapshotRequest request) {
return restoreFromSnapshotAsync(request, null);
}
@Override
public java.util.concurrent.Future<RestoreFromSnapshotResult> restoreFromSnapshotAsync(RestoreFromSnapshotRequest request,
com.amazonaws.handlers.AsyncHandler<RestoreFromSnapshotRequest, RestoreFromSnapshotResult> asyncHandler) {
throw new java.lang.UnsupportedOperationException();
}
@Override
public java.util.concurrent.Future<StartSchemaExtensionResult> startSchemaExtensionAsync(StartSchemaExtensionRequest request) {
return startSchemaExtensionAsync(request, null);
}
@Override
public java.util.concurrent.Future<StartSchemaExtensionResult> startSchemaExtensionAsync(StartSchemaExtensionRequest request,
com.amazonaws.handlers.AsyncHandler<StartSchemaExtensionRequest, StartSchemaExtensionResult> asyncHandler) {
throw new java.lang.UnsupportedOperationException();
}
@Override
public java.util.concurrent.Future<UpdateConditionalForwarderResult> updateConditionalForwarderAsync(UpdateConditionalForwarderRequest request) {
return updateConditionalForwarderAsync(request, null);
}
@Override
public java.util.concurrent.Future<UpdateConditionalForwarderResult> updateConditionalForwarderAsync(UpdateConditionalForwarderRequest request,
com.amazonaws.handlers.AsyncHandler<UpdateConditionalForwarderRequest, UpdateConditionalForwarderResult> asyncHandler) {
throw new java.lang.UnsupportedOperationException();
}
@Override
public java.util.concurrent.Future<UpdateRadiusResult> updateRadiusAsync(UpdateRadiusRequest request) {
return updateRadiusAsync(request, null);
}
@Override
public java.util.concurrent.Future<UpdateRadiusResult> updateRadiusAsync(UpdateRadiusRequest request,
com.amazonaws.handlers.AsyncHandler<UpdateRadiusRequest, UpdateRadiusResult> asyncHandler) {
throw new java.lang.UnsupportedOperationException();
}
@Override
public java.util.concurrent.Future<VerifyTrustResult> verifyTrustAsync(VerifyTrustRequest request) {
return verifyTrustAsync(request, null);
}
@Override
public java.util.concurrent.Future<VerifyTrustResult> verifyTrustAsync(VerifyTrustRequest request,
com.amazonaws.handlers.AsyncHandler<VerifyTrustRequest, VerifyTrustResult> asyncHandler) {
throw new java.lang.UnsupportedOperationException();
}
}
| apache-2.0 |
sladecek/jmaze | src/main/java/com/github/sladecek/maze/jmaze/maze/MazeData.java | 1278 | package com.github.sladecek.maze.jmaze.maze;
//REV1
import com.github.sladecek.maze.jmaze.generator.MazePath;
import com.github.sladecek.maze.jmaze.print3d.generic3dmodel.Model3d;
import com.github.sladecek.maze.jmaze.properties.MazeProperties;
import com.github.sladecek.maze.jmaze.shapes.Shapes;
import java.util.Random;
/**
* Data structures for maze representation.
*/
public class MazeData {
public MazeGraph getGraph() {
return graph;
}
public Model3d getModel3d() {
return model3d;
}
public Shapes getPathShapes() {
return pathShapes;
}
public Shapes getAllShapes() {
return allShapes;
}
MazeProperties getProperties() {
return properties;
}
/**
* Set properties for concrete maze such as size or colors.
*/
public void setProperties(MazeProperties value) {
properties = value;
}
public Random getRandomGenerator() {
return randomGenerator;
}
public MazePath getPath() {
return path;
}
protected final MazeGraph graph = new MazeGraph();
protected MazeProperties properties;
protected Random randomGenerator;
protected Shapes allShapes;
Shapes pathShapes;
MazePath path;
Model3d model3d;
}
| apache-2.0 |
android-art-intel/Nougat | art-extension/opttests/src/OptimizationTests/Devirtualization/InvokeInterfaceByte/CondVirtExt.java | 866 | /*
* Copyright (C) 2016 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package OptimizationTests.Devirtualization.InvokeInterfaceByte;
interface CondVirtBase {
public byte getThingies();
}
class CondVirtExt implements CondVirtBase {
byte thingies = 3;
public byte getThingies() {
return thingies;
}
}
| apache-2.0 |
axbaretto/beam | sdks/java/nexmark/src/main/java/org/apache/beam/sdk/nexmark/queries/Query0Model.java | 2022 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.beam.sdk.nexmark.queries;
import java.util.Collection;
import java.util.Iterator;
import org.apache.beam.sdk.nexmark.NexmarkConfiguration;
import org.apache.beam.sdk.nexmark.NexmarkUtils;
import org.apache.beam.sdk.nexmark.model.Event;
import org.apache.beam.sdk.values.TimestampedValue;
/** A direct implementation of {@link Query0}. */
public class Query0Model extends NexmarkQueryModel {
/** Simulator for query 0. */
private static class Simulator extends AbstractSimulator<Event, Event> {
public Simulator(NexmarkConfiguration configuration) {
super(NexmarkUtils.standardEventIterator(configuration));
}
@Override
protected void run() {
TimestampedValue<Event> timestampedEvent = nextInput();
if (timestampedEvent == null) {
allDone();
return;
}
addResult(timestampedEvent);
}
}
public Query0Model(NexmarkConfiguration configuration) {
super(configuration);
}
@Override
public AbstractSimulator<?, ?> simulator() {
return new Simulator(configuration);
}
@Override
protected <T> Collection<String> toCollection(Iterator<TimestampedValue<T>> itr) {
return toValueTimestampOrder(itr);
}
}
| apache-2.0 |
Wechat-Group/WxJava | weixin-java-cp/src/main/java/me/chanjar/weixin/cp/api/impl/WxCpOaCalendarServiceImpl.java | 1905 | package me.chanjar.weixin.cp.api.impl;
import com.google.gson.reflect.TypeToken;
import lombok.RequiredArgsConstructor;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.util.json.GsonHelper;
import me.chanjar.weixin.common.util.json.GsonParser;
import me.chanjar.weixin.cp.api.WxCpOaCalendarService;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.bean.oa.calendar.WxCpOaCalendar;
import me.chanjar.weixin.cp.util.json.WxCpGsonBuilder;
import java.util.List;
import static me.chanjar.weixin.cp.constant.WxCpApiPathConsts.Oa.*;
/**
* .
*
* @author <a href="https://github.com/binarywang">Binary Wang</a>
* @date 2020-09-20
*/
@RequiredArgsConstructor
public class WxCpOaCalendarServiceImpl implements WxCpOaCalendarService {
private final WxCpService wxCpService;
@Override
public String add(WxCpOaCalendar calendar) throws WxErrorException {
return this.wxCpService.post(this.wxCpService.getWxCpConfigStorage().getApiUrl(CALENDAR_ADD), calendar);
}
@Override
public void update(WxCpOaCalendar calendar) throws WxErrorException {
this.wxCpService.post(this.wxCpService.getWxCpConfigStorage().getApiUrl(CALENDAR_UPDATE), calendar);
}
@Override
public List<WxCpOaCalendar> get(List<String> calIds) throws WxErrorException {
String response = this.wxCpService.post(this.wxCpService.getWxCpConfigStorage().getApiUrl(CALENDAR_GET),
GsonHelper.buildJsonObject("cal_id_list", calIds));
return WxCpGsonBuilder.create().fromJson(GsonParser.parse(response).get("calendar_list").getAsJsonArray().toString(),
new TypeToken<List<WxCpOaCalendar>>() {
}.getType());
}
@Override
public void delete(String calId) throws WxErrorException {
this.wxCpService.post(this.wxCpService.getWxCpConfigStorage().getApiUrl(CALENDAR_DEL),
GsonHelper.buildJsonObject("cal_id", calId));
}
}
| apache-2.0 |
thecocce/Tile-generator | Tile generator/src/de/sogomn/generator/util/ImageUtils.java | 3684 | package de.sogomn.generator.util;
import java.awt.AlphaComposite;
import java.awt.Graphics2D;
import java.awt.geom.Area;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public final class ImageUtils {
private ImageUtils() {
//...
}
public static BufferedImage load(final String path) {
try {
final BufferedImage image = ImageIO.read(ImageUtils.class.getResource(path));
return image;
} catch (final IOException ex) {
ex.printStackTrace();
return null;
}
}
public static BufferedImage combine(final BufferedImage base, final BufferedImage image) {
if (image == null) {
return base;
} else if (base == null) {
return image;
}
final BufferedImage result = new BufferedImage(base.getWidth(), base.getHeight(), base.getType());
final Graphics2D g = result.createGraphics();
g.drawImage(base, 0, 0, null);
g.drawImage(image, 0, 0, null);
g.dispose();
return result;
}
public static BufferedImage combineAndBlend(final BufferedImage base, final BufferedImage image, final float alpha) {
if (image == null) {
return base;
} else if (base == null) {
return image;
}
final BufferedImage result = new BufferedImage(base.getWidth(), base.getHeight(), BufferedImage.TYPE_INT_ARGB);
final Graphics2D g = result.createGraphics();
g.drawImage(image, 0, 0, null);
g.drawImage(base, 0, 0, null);
g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha));
g.drawImage(image, 0, 0, null);
g.dispose();
return result;
}
public static void write(final BufferedImage image, final String path) {
final File file = new File(path);
try {
ImageIO.write(image, "png", file);
} catch (final IOException ex) {
ex.printStackTrace();
}
}
public static BufferedImage loadExternal(final File file) {
try {
final BufferedImage image = ImageIO.read(file);
return image;
} catch (final IOException ex) {
ex.printStackTrace();
return null;
}
}
public static BufferedImage toSpriteSheet(final int tileWidth, final int tileHeight, final int tilesWide, final BufferedImage... images) {
final int tilesHigh = (int)Math.ceil((double)images.length / tilesWide);
final int width = tilesWide * tileWidth;
final int height = tilesHigh * tileHeight;
final BufferedImage spriteSheet = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
final Graphics2D g = spriteSheet.createGraphics();
for (int i = 0; i < images.length; i++) {
final BufferedImage image = images[i];
final int x = (i % tilesWide) * tileWidth;
final int y = (i / tilesWide) * tileHeight;
g.drawImage(image, x, y, null);
}
g.dispose();
return spriteSheet;
}
public static BufferedImage mask(final BufferedImage image, final Area mask) {
final BufferedImage result = new BufferedImage(image.getWidth(), image.getHeight(), image.getType());
final Graphics2D g = result.createGraphics();
g.clip(mask);
g.drawImage(image, 0, 0, null);
g.dispose();
return result;
}
public static BufferedImage createOverlap(final BufferedImage one, final BufferedImage two) {
if (one == null || two == null) {
return null;
}
final int width = Math.max(one.getWidth(), two.getWidth());
final int height = Math.max(one.getHeight(), two.getHeight());
final BufferedImage result = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
final Graphics2D g = result.createGraphics();
g.drawImage(one, 0, 0, null);
g.setComposite(AlphaComposite.SrcIn);
g.drawImage(two, 0, 0, null);
g.dispose();
return result;
}
}
| apache-2.0 |
shunfei/indexr | indexr-query-opt/src/main/java/org/apache/spark/util/collection/Sorter.java | 742 | package org.apache.spark.util.collection;
import java.util.Comparator;
/**
* A simple wrapper over the Java implementation [[TimSort]].
*
* The Java implementation is package private, and hence it cannot be called outside package
* org.apache.spark.util.collection. This is a simple wrapper of it that is available to spark.
*/
public class Sorter<K, Buffer> {
private SortDataFormat<K, Buffer> s;
public Sorter(SortDataFormat<K, Buffer> s) {
this.s = s;
}
private TimSort<K, Buffer> timSort = new TimSort<K, Buffer>(s);
/**
* Sorts the input buffer within range [lo, hi).
*/
public void sort(Buffer a, int lo, int hi, Comparator<? super K> c) {
timSort.sort(a, lo, hi, c);
}
}
| apache-2.0 |
multiscripter/job4j | junior/pack2_junior/p1_collections_pro/ch2_generic/src/test/java/ru/job4j/generic/SimpleListTest.java | 2403 | package ru.job4j.generic;
import java.util.Arrays;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
/**
* Класс SimpleListTest тестирует класс SimpleList.
*
* @author Gureyev Ilya (mailto:ill-jah@yandex.ru)
* @version 1
* @since 2017-05-24
*/
public class SimpleListTest {
/**
* Объект SimpleList<Integer>.
*/
private SimpleList<Integer> sl;
/**
* Действия перед тестом.
*/
@Before
public void beforeTest() {
int size = 11;
this.sl = new SimpleList<>(size);
for (int a = 0; a < size; a++) {
this.sl.add(a * 100);
}
}
/**
* Тестирует add().
*/
@Test
public void testAdd() {
this.sl.add(11);
}
/**
* Тестирует count().
*/
@Test
public void testCount() {
this.sl.add(200);
this.sl.add(100);
int result = this.sl.count();
assertEquals(13, result);
}
/**
* Тестирует delete().
*/
@Test
public void testDelete() {
Integer[] expected = new Integer[]{0, 100, 200, 300, 400, 600, 700, 800, 900, 1000};
this.sl.delete(5);
Integer[] result = Arrays.copyOfRange(this.sl.toArray(), 0, this.sl.count(), Integer[].class);
assertArrayEquals(expected, result);
}
/**
* Тестирует get().
*/
@Test
public void testGet() {
Integer expected = Integer.valueOf(400);
Integer result = this.sl.get(4);
assertEquals(expected, result);
}
/**
* Тестирует index().
*/
@Test
public void testIndex() {
assertEquals(11, this.sl.index());
}
/**
* Тестирует size().
*/
@Test
public void testSize() {
this.sl.add(211);
int result = this.sl.size();
assertEquals(22, result);
}
/**
* Тестирует update().
*/
@Test
public void testUpdate() {
int index = 4;
Integer expected = Integer.valueOf(222);
this.sl.update(index, expected);
Integer result = this.sl.get(index);
assertEquals(expected, result);
}
} | apache-2.0 |
CelloCodez/3DGameEngine | src/com/base/engine/rendering/meshLoading/OBJModel.java | 5491 | /*
* Copyright (C) 2014 Benny Bobaganoosh
*
* 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.base.engine.rendering.meshLoading;
import com.base.engine.core.Vector2f;
import com.base.engine.core.Vector3f;
import com.base.engine.util.Util;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.HashMap;
public class OBJModel
{
private ArrayList<Vector3f> m_positions;
private ArrayList<Vector2f> m_texCoords;
private ArrayList<Vector3f> m_normals;
private ArrayList<OBJIndex> m_indices;
private boolean m_hasTexCoords;
private boolean m_hasNormals;
public OBJModel(String fileName)
{
m_positions = new ArrayList<Vector3f>();
m_texCoords = new ArrayList<Vector2f>();
m_normals = new ArrayList<Vector3f>();
m_indices = new ArrayList<OBJIndex>();
m_hasTexCoords = false;
m_hasNormals = false;
BufferedReader meshReader = null;
try
{
meshReader = new BufferedReader(new FileReader(fileName));
String line;
while((line = meshReader.readLine()) != null)
{
String[] tokens = line.split(" ");
tokens = Util.RemoveEmptyStrings(tokens);
if(tokens.length == 0 || tokens[0].equals("#"))
continue;
else if(tokens[0].equals("v"))
{
m_positions.add(new Vector3f(Float.valueOf(tokens[1]),
Float.valueOf(tokens[2]),
Float.valueOf(tokens[3])));
}
else if(tokens[0].equals("vt"))
{
m_texCoords.add(new Vector2f(Float.valueOf(tokens[1]),
1.0f - Float.valueOf(tokens[2])));
}
else if(tokens[0].equals("vn"))
{
m_normals.add(new Vector3f(Float.valueOf(tokens[1]),
Float.valueOf(tokens[2]),
Float.valueOf(tokens[3])));
}
else if(tokens[0].equals("f"))
{
for(int i = 0; i < tokens.length - 3; i++)
{
m_indices.add(ParseOBJIndex(tokens[1]));
m_indices.add(ParseOBJIndex(tokens[2 + i]));
m_indices.add(ParseOBJIndex(tokens[3 + i]));
}
}
}
meshReader.close();
}
catch(Exception e)
{
e.printStackTrace();
System.exit(1);
}
}
public IndexedModel ToIndexedModel()
{
IndexedModel result = new IndexedModel();
IndexedModel normalModel = new IndexedModel();
HashMap<OBJIndex, Integer> resultIndexMap = new HashMap<OBJIndex, Integer>();
HashMap<Integer, Integer> normalIndexMap = new HashMap<Integer, Integer>();
HashMap<Integer, Integer> indexMap = new HashMap<Integer, Integer>();
for(int i = 0; i < m_indices.size(); i++)
{
OBJIndex currentIndex = m_indices.get(i);
Vector3f currentPosition = m_positions.get(currentIndex.GetVertexIndex());
Vector2f currentTexCoord;
Vector3f currentNormal;
if(m_hasTexCoords)
currentTexCoord = m_texCoords.get(currentIndex.GetTexCoordIndex());
else
currentTexCoord = new Vector2f(0,0);
if(m_hasNormals)
currentNormal = m_normals.get(currentIndex.GetNormalIndex());
else
currentNormal = new Vector3f(0,0,0);
Integer modelVertexIndex = resultIndexMap.get(currentIndex);
if(modelVertexIndex == null)
{
modelVertexIndex = result.GetPositions().size();
resultIndexMap.put(currentIndex, modelVertexIndex);
result.GetPositions().add(currentPosition);
result.GetTexCoords().add(currentTexCoord);
if(m_hasNormals)
result.GetNormals().add(currentNormal);
}
Integer normalModelIndex = normalIndexMap.get(currentIndex.GetVertexIndex());
if(normalModelIndex == null)
{
normalModelIndex = normalModel.GetPositions().size();
normalIndexMap.put(currentIndex.GetVertexIndex(), normalModelIndex);
normalModel.GetPositions().add(currentPosition);
normalModel.GetTexCoords().add(currentTexCoord);
normalModel.GetNormals().add(currentNormal);
normalModel.GetTangents().add(new Vector3f(0,0,0));
}
result.GetIndices().add(modelVertexIndex);
normalModel.GetIndices().add(normalModelIndex);
indexMap.put(modelVertexIndex, normalModelIndex);
}
if(!m_hasNormals)
{
normalModel.CalcNormals();
for(int i = 0; i < result.GetPositions().size(); i++)
result.GetNormals().add(normalModel.GetNormals().get(indexMap.get(i)));
}
normalModel.CalcTangents();
for(int i = 0; i < result.GetPositions().size(); i++)
result.GetTangents().add(normalModel.GetTangents().get(indexMap.get(i)));
// for(int i = 0; i < result.GetTexCoords().size(); i++)
// result.GetTexCoords().Get(i).SetY(1.0f - result.GetTexCoords().Get(i).GetY());
return result;
}
private OBJIndex ParseOBJIndex(String token)
{
String[] values = token.split("/");
OBJIndex result = new OBJIndex();
result.SetVertexIndex(Integer.parseInt(values[0]) - 1);
if(values.length > 1)
{
if(!values[1].isEmpty())
{
m_hasTexCoords = true;
result.SetTexCoordIndex(Integer.parseInt(values[1]) - 1);
}
if(values.length > 2)
{
m_hasNormals = true;
result.SetNormalIndex(Integer.parseInt(values[2]) - 1);
}
}
return result;
}
}
| apache-2.0 |
mkoslacz/Moviper | sample-ipc/src/main/java/com/mateuszkoslacz/moviper/ipcsample/viper/routing/ColorWidgetRouting.java | 358 | package com.mateuszkoslacz.moviper.ipcsample.viper.routing;
import android.app.Activity;
import com.mateuszkoslacz.moviper.base.routing.BaseRxRouting;
import com.mateuszkoslacz.moviper.ipcsample.viper.contract.ColorWidgetContract;
public class ColorWidgetRouting
extends BaseRxRouting<Activity>
implements ColorWidgetContract.Routing {
}
| apache-2.0 |
yeastrc/proxl-web-app | proxl_web_app/src/main/java/org/yeastrc/xlink/www/actions/ViewSearchProteinsAllAction.java | 13992 | package org.yeastrc.xlink.www.actions;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.LoggerFactory; import org.slf4j.Logger;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.yeastrc.xlink.www.dao.SearchDAO;
import org.yeastrc.xlink.www.searcher.ProjectIdsForProjectSearchIdsSearcher;
import org.yeastrc.xlink.www.user_session_management.UserSession;
import org.yeastrc.xlink.www.user_session_management.UserSessionManager;
import org.yeastrc.xlink.www.dto.SearchDTO;
import org.yeastrc.xlink.www.nav_links_image_structure.PopulateRequestDataForImageAndStructureAndQC_NavLinks;
import org.yeastrc.xlink.www.access_control.result_objects.WebSessionAuthAccessLevel;
import org.yeastrc.xlink.www.constants.StrutsGlobalForwardNames;
import org.yeastrc.xlink.www.constants.WebConstants;
import org.yeastrc.xlink.www.exceptions.ProxlWebappDataException;
import org.yeastrc.xlink.www.form_query_json_objects.PeptideQueryJSONRoot;
import org.yeastrc.xlink.www.form_query_json_objects.ProteinQueryJSONRoot;
import org.yeastrc.xlink.www.form_utils.GetProteinQueryJSONRootFromFormData;
import org.yeastrc.xlink.www.forms.PeptideProteinCommonForm;
import org.yeastrc.xlink.www.forms.SearchViewProteinsForm;
import org.yeastrc.xlink.www.access_control.access_control_main.GetWebSessionAuthAccessLevelForProjectIds_And_NO_ProjectId.GetWebSessionAuthAccessLevelForProjectIds_And_NO_ProjectId_Result;
import org.yeastrc.xlink.www.access_control.access_control_main.GetWebSessionAuthAccessLevelForProjectIds_And_NO_ProjectId;
import org.yeastrc.xlink.www.web_utils.ExcludeLinksWith_Remove_NonUniquePSMs_Checkbox_PopRequestItems;
import org.yeastrc.xlink.www.web_utils.GetAnnotationDisplayUserSelectionDetailsData;
import org.yeastrc.xlink.www.web_utils.GetMinimumPSMsDefaultForProject_PutInRequestScope;
import org.yeastrc.xlink.www.web_utils.GetPageHeaderData;
import org.yeastrc.xlink.www.web_utils.GetSearchDetailsData;
import org.yeastrc.xlink.www.web_utils.ProjectSearchIdsSearchIds_SetRequestParameter;
import org.yeastrc.xlink.www.web_utils.ProteinListingTooltipConfigUtil;
import org.yeastrc.xlink.www.web_utils.URLEncodeDecodeAURL;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
* Used for Showing all proteins on a page
*
* Separate from Crosslink Proteins and Looplink Proteins pages
*
*/
public class ViewSearchProteinsAllAction extends Action {
private static final Logger log = LoggerFactory.getLogger( ViewSearchProteinsAllAction.class);
/* (non-Javadoc)
* @see org.apache.struts.action.Action#execute(org.apache.struts.action.ActionMapping, org.apache.struts.action.ActionForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
*/
@Override
public ActionForward execute( ActionMapping mapping,
ActionForm actionForm,
HttpServletRequest request,
HttpServletResponse response )
throws Exception {
Integer projectId = null;
try {
// our form
SearchViewProteinsForm form = (SearchViewProteinsForm)actionForm;
request.setAttribute( "searchViewProteinsForm", form );
int projectSearchId = form.getProjectSearchIdSingle();
// Get the project id for this search
Collection<Integer> projectSearchIdsSet = new HashSet<>();
projectSearchIdsSet.add( projectSearchId );
List<Integer> projectIdsFromSearchIds = ProjectIdsForProjectSearchIdsSearcher.getInstance().getProjectIdsForProjectSearchIds( projectSearchIdsSet );
if ( projectIdsFromSearchIds.isEmpty() ) {
if ( projectSearchId != 0 ) { // projectSearchId == 0 if no value provided since is default value in form
// Only log if value provided.
String msg = "No project ids for projectSearchId: " + projectSearchId;
log.warn( msg );
}
return mapping.findForward( StrutsGlobalForwardNames.INVALID_REQUEST_DATA );
}
if ( projectIdsFromSearchIds.size() > 1 ) {
// Invalid request, searches across projects
return mapping.findForward( StrutsGlobalForwardNames.INVALID_REQUEST_SEARCHES_ACROSS_PROJECTS );
}
projectId = projectIdsFromSearchIds.get( 0 );
request.setAttribute( "projectId", projectId );
request.setAttribute( "project_id", projectId );
///////////////////////
GetWebSessionAuthAccessLevelForProjectIds_And_NO_ProjectId_Result accessAndSetupWebSessionResult =
GetWebSessionAuthAccessLevelForProjectIds_And_NO_ProjectId.getSinglesonInstance().getAccessAndSetupWebSessionWithProjectId( projectId, request, response );
// Test access to the project id
WebSessionAuthAccessLevel authAccessLevel = accessAndSetupWebSessionResult.getWebSessionAuthAccessLevel();
if ( ! authAccessLevel.isPublicAccessCodeReadAllowed() ) {
// No Access Allowed for this project id
if ( accessAndSetupWebSessionResult.isNoSession() ) {
// No User session
return mapping.findForward( StrutsGlobalForwardNames.NO_USER_SESSION );
}
return mapping.findForward( StrutsGlobalForwardNames.INSUFFICIENT_ACCESS_PRIVILEGE );
}
request.setAttribute( WebConstants.REQUEST_AUTH_ACCESS_LEVEL, authAccessLevel );
/// Done Processing Auth Check and Auth Level
request.setAttribute( "projectSearchId", projectSearchId );
//////////////////////////////
// Jackson JSON Mapper object for JSON deserialization and serialization
ObjectMapper jacksonJSON_Mapper = new ObjectMapper(); // Jackson JSON library object
// Populate request objects for Standard Header Display
GetPageHeaderData.getInstance().getPageHeaderDataWithProjectId( projectId, request );
// Populate request objects for Protein Name Tooltip JS
ProteinListingTooltipConfigUtil.getInstance().putProteinListingTooltipConfigForPage( projectSearchIdsSet, request );
request.setAttribute( "queryString", request.getQueryString() );
SearchDTO search = SearchDAO.getInstance().getSearchFromProjectSearchId( projectSearchId );
if ( search == null ) {
String msg = ": No searchId found for projectSearchId: " + projectSearchId;
log.warn( msg );
throw new ProxlWebappDataException( msg );
}
request.setAttribute( "search", search );
int searchId = search.getSearchId();
Collection<Integer> searchIdsSet = new HashSet<>();
searchIdsSet.add( searchId );
Map<Integer,Integer> mapProjectSearchIdToSearchId = new HashMap<>();
mapProjectSearchIdToSearchId.put( projectSearchId, searchId );
// Get Query JSON from the form and if not empty, deserialize it
ProteinQueryJSONRoot proteinQueryJSONRoot =
GetProteinQueryJSONRootFromFormData.getInstance()
.getProteinQueryJSONRootFromFormData( form, projectId, projectSearchIdsSet, searchIdsSet, mapProjectSearchIdToSearchId );
// Convert the protein sequence ids that come from the JS code to standard integers and put
// in the property excludeproteinSequenceVersionIds.
// Do this here since may have to convert old NRSeqProteinIds.
ProteinsMergedProteinsCommon.getInstance().processExcludeproteinSequenceVersionIdsFromJS( proteinQueryJSONRoot );
{
ProjectSearchIdsSearchIds_SetRequestParameter.SearchesAreUserSorted searchesAreUserSorted = ProjectSearchIdsSearchIds_SetRequestParameter.SearchesAreUserSorted.NO;
if ( PeptideProteinCommonForm.DO_NOT_SORT_PROJECT_SEARCH_IDS_YES.equals( form.getDs() ) ) {
searchesAreUserSorted = ProjectSearchIdsSearchIds_SetRequestParameter.SearchesAreUserSorted.YES;
}
// Populate request objects for Project Search Id / Search Id pairs in display order in JSON on Page for Javascript
ProjectSearchIdsSearchIds_SetRequestParameter.getSingletonInstance().populateProjectSearchIdsSearchIds_SetRequestParameter( search, searchesAreUserSorted, request );
}
{
GetSearchDetailsData.SearchesAreUserSorted searchesAreUserSorted = GetSearchDetailsData.SearchesAreUserSorted.NO;
if ( PeptideProteinCommonForm.DO_NOT_SORT_PROJECT_SEARCH_IDS_YES.equals( form.getDs() ) ) {
searchesAreUserSorted = GetSearchDetailsData.SearchesAreUserSorted.YES;
}
// Populate request objects for Standard Search Display
GetSearchDetailsData.getInstance().getSearchDetailsData( search, searchesAreUserSorted, request );
}
GetMinimumPSMsDefaultForProject_PutInRequestScope.getSingletonInstance().getMinimumPSMsDefaultForProject_PutInRequestScope( projectId, request );
// Populate request objects for User Selection of Annotation Data Display
GetAnnotationDisplayUserSelectionDetailsData.getInstance().getSearchDetailsData( search, request );
// Populate request objects for excludeLinksWith_Remove_NonUniquePSMs_Checkbox_Fragment.jsp
ExcludeLinksWith_Remove_NonUniquePSMs_Checkbox_PopRequestItems.getInstance().excludeLinksWith_Remove_NonUniquePSMs_Checkbox_PopRequestItems( search, request );
/////////////////////
// clear out form so value doesn't go back on the page in the form
form.setQueryJSON( "" );
/////////////////////
//// Put Updated queryJSON on the page
{
try {
String queryJSONToForm = jacksonJSON_Mapper.writeValueAsString( proteinQueryJSONRoot );
// Set queryJSON in request attribute to put on page outside of form
request.setAttribute( "queryJSONToForm", queryJSONToForm );
} catch ( JsonProcessingException e ) {
String msg = "Failed to write as JSON 'queryJSONToForm', JsonProcessingException. queryString" + request.getQueryString();
log.error( msg, e );
throw new ProxlWebappDataException( msg, e );
} catch ( Exception e ) {
String msg = "Failed to write as JSON 'queryJSONToForm', Exception. queryString" + request.getQueryString();
log.error( msg, e );
throw new ProxlWebappDataException( msg, e );
}
}
/////////////////////
//// Put queryJSON for Peptide Link on the page
{
try {
PeptideQueryJSONRoot peptideQueryJSONRoot = new PeptideQueryJSONRoot();
peptideQueryJSONRoot.setCutoffs( proteinQueryJSONRoot.getCutoffs() );
peptideQueryJSONRoot.setMinPSMs( proteinQueryJSONRoot.getMinPSMs() );
String[] peptidePageLinkTypes = null;
// String[] peptidePageLinkTypes = new String[ 1 ];
// if ( Struts_Config_Parameter_Values_Constants.STRUTS__PARAMETER__CROSSLINK.equals( strutsActionMappingParameter ) ) {
// peptidePageLinkTypes[ 0 ] = XLinkUtils.CROSS_TYPE_STRING_UPPERCASE;
// } else if ( Struts_Config_Parameter_Values_Constants.STRUTS__PARAMETER__LOOPLINK.equals( strutsActionMappingParameter ) ) {
// peptidePageLinkTypes[ 0 ] = XLinkUtils.LOOP_TYPE_STRING_UPPERCASE;
// }
peptideQueryJSONRoot.setLinkTypes( peptidePageLinkTypes );
String peptideQueryJSONRootJSONString = jacksonJSON_Mapper.writeValueAsString( peptideQueryJSONRoot );
// Create URI Encoded JSON for passing to Image and Structure pages in hash
String peptideQueryJSONRootJSONStringURIEncoded = URLEncodeDecodeAURL.urlEncodeAURL( peptideQueryJSONRootJSONString );
request.setAttribute( "peptidePageQueryJSON", peptideQueryJSONRootJSONStringURIEncoded );
} catch ( JsonProcessingException e ) {
String msg = "Failed to write as JSON 'queryJSONToForm', JsonProcessingException. queryString" + request.getQueryString();
log.error( msg, e );
throw new ProxlWebappDataException( msg, e );
} catch ( Exception e ) {
String msg = "Failed to write as JSON 'queryJSONToForm', Exception. queryString" + request.getQueryString();
log.error( msg, e );
throw new ProxlWebappDataException( msg, e );
}
}
// Create data for Links for Image and Structure pages and put in request
PopulateRequestDataForImageAndStructureAndQC_NavLinks.getInstance()
.populateRequestDataForImageAndStructureNavLinksForProtein( proteinQueryJSONRoot, projectId, authAccessLevel, form, request );
return mapping.findForward( "Success" );
} catch ( ProxlWebappDataException e ) {
Integer authUserId = null;
Integer userMgmtUserId = null;
String username = null;
try {
UserSession userSession = UserSessionManager.getSinglesonInstance().getUserSession(request);
if ( userSession != null ) {
authUserId = userSession.getAuthUserId();
userMgmtUserId = userSession.getUserMgmtUserId();
username = userSession.getUsername();
}
} catch ( Exception e2 ) {
log.error( "In Main } catch ( Exception e ) {: Error getting User Id and Username: ", e2 );
}
String msg = "Exception processing request data. authUserId (null if no session): "
+ authUserId
+ ", userMgmtUserId (null if no session): " + userMgmtUserId
+ ", username (null if no session): " + username
+ e.toString();
log.error( msg, e );
return mapping.findForward( StrutsGlobalForwardNames.INVALID_REQUEST_DATA );
} catch ( Exception e ) {
Integer authUserId = null;
Integer userMgmtUserId = null;
String username = null;
try {
UserSession userSession = UserSessionManager.getSinglesonInstance().getUserSession(request);
if ( userSession != null ) {
authUserId = userSession.getAuthUserId();
userMgmtUserId = userSession.getUserMgmtUserId();
username = userSession.getUsername();
}
} catch ( Exception e2 ) {
log.error( "In Main } catch ( Exception e ) {: Error getting User Id and Username: ", e2 );
}
String msg = "Exception caught. authUserId (null if no session): "
+ authUserId
+ ", userMgmtUserId (null if no session): " + userMgmtUserId
+ ", username (null if no session): " + username
+ e.toString();
log.error( msg, e );
throw e;
}
}
}
| apache-2.0 |
sandeepsajiru/gmaeOlninePlat | DBLayer/src/onlinegaming/dblayer/unittests/UserUnitTests.java | 702 | /*
* 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 onlinegaming.dblayer.unittests;
import onlinegaming.dblayer.OnilneGameDBLayer;
/**
*
* @author sandy
*/
public class UserUnitTests {
public static void main(String[] args) {
OnilneGameDBLayer ogdbl = new OnilneGameDBLayer();
//ogdbl.registerUser("dummy", "test", "testPWD", "nick", "", 1);
ogdbl.setUserOnline(0, "test");
System.out.println(ogdbl.isAlreadyRegistered("test"));
System.out.println(ogdbl.isUserValid("test", "testPWD"));
}
}
| apache-2.0 |
dbflute-test/dbflute-test-dbms-mysql | src/main/java/org/docksidestage/mysql/dbflute/bsentity/customize/BsSpReturnResultSetWithNotParamResult1.java | 18320 | /*
* Copyright 2004-2013 the Seasar Foundation and the 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.docksidestage.mysql.dbflute.bsentity.customize;
import java.util.List;
import java.util.ArrayList;
import org.dbflute.dbmeta.DBMeta;
import org.dbflute.dbmeta.AbstractEntity;
import org.dbflute.dbmeta.accessory.CustomizeEntity;
import org.docksidestage.mysql.dbflute.allcommon.CDef;
import org.docksidestage.mysql.dbflute.exentity.customize.*;
/**
* The entity of SpReturnResultSetWithNotParamResult1. <br>
* <pre>
* [primary-key]
*
*
* [column]
* MEMBER_ID, MEMBER_NAME, BIRTHDATE, FORMALIZED_DATETIME, MEMBER_STATUS_CODE
*
* [sequence]
*
*
* [identity]
*
*
* [version-no]
*
*
* [foreign table]
*
*
* [referrer table]
*
*
* [foreign property]
*
*
* [referrer property]
*
*
* [get/set template]
* /= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
* Integer memberId = entity.getMemberId();
* String memberName = entity.getMemberName();
* java.time.LocalDate birthdate = entity.getBirthdate();
* java.time.LocalDateTime formalizedDatetime = entity.getFormalizedDatetime();
* String memberStatusCode = entity.getMemberStatusCode();
* entity.setMemberId(memberId);
* entity.setMemberName(memberName);
* entity.setBirthdate(birthdate);
* entity.setFormalizedDatetime(formalizedDatetime);
* entity.setMemberStatusCode(memberStatusCode);
* = = = = = = = = = =/
* </pre>
* @author DBFlute(AutoGenerator)
*/
public abstract class BsSpReturnResultSetWithNotParamResult1 extends AbstractEntity implements CustomizeEntity {
// ===================================================================================
// Definition
// ==========
/** The serial version UID for object serialization. (Default) */
private static final long serialVersionUID = 1L;
// ===================================================================================
// Attribute
// =========
/** (会員ID)MEMBER_ID: {INT(11), refers to member.MEMBER_ID} */
protected Integer _memberId;
/** (会員名称)MEMBER_NAME: {VARCHAR(180), refers to member.MEMBER_NAME} */
protected String _memberName;
/** (生年月日)BIRTHDATE: {DATE(10), refers to member.BIRTHDATE} */
protected java.time.LocalDate _birthdate;
/** (正式会員日時)FORMALIZED_DATETIME: {DATETIME(19), refers to member.FORMALIZED_DATETIME} */
protected java.time.LocalDateTime _formalizedDatetime;
/** (会員ステータスコード)MEMBER_STATUS_CODE: {CHAR(3), refers to member.MEMBER_STATUS_CODE, classification=MemberStatus} */
protected String _memberStatusCode;
// ===================================================================================
// DB Meta
// =======
/** {@inheritDoc} */
public DBMeta asDBMeta() {
return org.docksidestage.mysql.dbflute.bsentity.customize.dbmeta.SpReturnResultSetWithNotParamResult1Dbm.getInstance();
}
/** {@inheritDoc} */
public String asTableDbName() {
return "SpReturnResultSetWithNotParamResult1";
}
// ===================================================================================
// Key Handling
// ============
/** {@inheritDoc} */
public boolean hasPrimaryKeyValue() {
return false;
}
// ===================================================================================
// Classification Property
// =======================
/**
* Get the value of memberStatusCode as the classification of MemberStatus. <br>
* (会員ステータスコード)MEMBER_STATUS_CODE: {CHAR(3), refers to member.MEMBER_STATUS_CODE, classification=MemberStatus} <br>
* 会員ステータス: 会員の状態を示す
* <p>It's treated as case insensitive and if the code value is null, it returns null.</p>
* @return The instance of classification definition (as ENUM type). (NullAllowed: when the column value is null)
*/
public CDef.MemberStatus getMemberStatusCodeAsMemberStatus() {
return CDef.MemberStatus.codeOf(getMemberStatusCode());
}
/**
* Set the value of memberStatusCode as the classification of MemberStatus. <br>
* (会員ステータスコード)MEMBER_STATUS_CODE: {CHAR(3), refers to member.MEMBER_STATUS_CODE, classification=MemberStatus} <br>
* 会員ステータス: 会員の状態を示す
* @param cdef The instance of classification definition (as ENUM type). (NullAllowed: if null, null value is set to the column)
*/
public void setMemberStatusCodeAsMemberStatus(CDef.MemberStatus cdef) {
setMemberStatusCode(cdef != null ? cdef.code() : null);
}
// ===================================================================================
// Classification Setting
// ======================
/**
* Set the value of memberStatusCode as Formalized (FML). <br>
* 正式会員: 正式な会員を示す
*/
public void setMemberStatusCode_Formalized() {
setMemberStatusCodeAsMemberStatus(CDef.MemberStatus.Formalized);
}
/**
* Set the value of memberStatusCode as Provisional (PRV). <br>
* 仮会員: 仮の会員を示す
*/
public void setMemberStatusCode_Provisional() {
setMemberStatusCodeAsMemberStatus(CDef.MemberStatus.Provisional);
}
/**
* Set the value of memberStatusCode as Withdrawal (WDL). <br>
* 退会会員: 退会した会員を示す
*/
public void setMemberStatusCode_Withdrawal() {
setMemberStatusCodeAsMemberStatus(CDef.MemberStatus.Withdrawal);
}
// ===================================================================================
// Classification Determination
// ============================
/**
* Is the value of memberStatusCode Formalized? <br>
* 正式会員: 正式な会員を示す
* <p>It's treated as case insensitive and if the code value is null, it returns false.</p>
* @return The determination, true or false.
*/
public boolean isMemberStatusCodeFormalized() {
CDef.MemberStatus cdef = getMemberStatusCodeAsMemberStatus();
return cdef != null ? cdef.equals(CDef.MemberStatus.Formalized) : false;
}
/**
* Is the value of memberStatusCode Provisional? <br>
* 仮会員: 仮の会員を示す
* <p>It's treated as case insensitive and if the code value is null, it returns false.</p>
* @return The determination, true or false.
*/
public boolean isMemberStatusCodeProvisional() {
CDef.MemberStatus cdef = getMemberStatusCodeAsMemberStatus();
return cdef != null ? cdef.equals(CDef.MemberStatus.Provisional) : false;
}
/**
* Is the value of memberStatusCode Withdrawal? <br>
* 退会会員: 退会した会員を示す
* <p>It's treated as case insensitive and if the code value is null, it returns false.</p>
* @return The determination, true or false.
*/
public boolean isMemberStatusCodeWithdrawal() {
CDef.MemberStatus cdef = getMemberStatusCodeAsMemberStatus();
return cdef != null ? cdef.equals(CDef.MemberStatus.Withdrawal) : false;
}
// ===================================================================================
// Classification Name/Alias
// =========================
/**
* Get the value of the column 'memberStatusCode' as classification name.
* @return The string of classification name. (NullAllowed: when the column value is null)
*/
public String getMemberStatusCodeName() {
CDef.MemberStatus cdef = getMemberStatusCodeAsMemberStatus();
return cdef != null ? cdef.name() : null;
}
/**
* Get the value of the column 'memberStatusCode' as classification alias.
* @return The string of classification alias. (NullAllowed: when the column value is null)
*/
public String getMemberStatusCodeAlias() {
CDef.MemberStatus cdef = getMemberStatusCodeAsMemberStatus();
return cdef != null ? cdef.alias() : null;
}
// ===================================================================================
// Foreign Property
// ================
// ===================================================================================
// Referrer Property
// =================
protected <ELEMENT> List<ELEMENT> newReferrerList() { // overriding to import
return new ArrayList<ELEMENT>();
}
// ===================================================================================
// Basic Override
// ==============
@Override
protected boolean doEquals(Object obj) {
if (obj instanceof BsSpReturnResultSetWithNotParamResult1) {
BsSpReturnResultSetWithNotParamResult1 other = (BsSpReturnResultSetWithNotParamResult1)obj;
if (!xSV(_memberId, other._memberId)) { return false; }
if (!xSV(_memberName, other._memberName)) { return false; }
if (!xSV(_birthdate, other._birthdate)) { return false; }
if (!xSV(_formalizedDatetime, other._formalizedDatetime)) { return false; }
if (!xSV(_memberStatusCode, other._memberStatusCode)) { return false; }
return true;
} else {
return false;
}
}
@Override
protected int doHashCode(int initial) {
int hs = initial;
hs = xCH(hs, asTableDbName());
hs = xCH(hs, _memberId);
hs = xCH(hs, _memberName);
hs = xCH(hs, _birthdate);
hs = xCH(hs, _formalizedDatetime);
hs = xCH(hs, _memberStatusCode);
return hs;
}
@Override
protected String doBuildStringWithRelation(String li) {
return "";
}
@Override
protected String doBuildColumnString(String dm) {
StringBuilder sb = new StringBuilder();
sb.append(dm).append(xfND(_memberId));
sb.append(dm).append(xfND(_memberName));
sb.append(dm).append(xfND(_birthdate));
sb.append(dm).append(xfND(_formalizedDatetime));
sb.append(dm).append(xfND(_memberStatusCode));
if (sb.length() > dm.length()) {
sb.delete(0, dm.length());
}
sb.insert(0, "{").append("}");
return sb.toString();
}
@Override
protected String doBuildRelationString(String dm) {
return "";
}
@Override
public SpReturnResultSetWithNotParamResult1 clone() {
return (SpReturnResultSetWithNotParamResult1)super.clone();
}
// ===================================================================================
// Accessor
// ========
/**
* [get] (会員ID)MEMBER_ID: {INT(11), refers to member.MEMBER_ID} <br>
* 会員を識別するID。連番として基本的に自動採番される。<br>
* (会員IDだけに限らず)採番方法はDBMSによって変わる。
* @return The value of the column 'MEMBER_ID'. (NullAllowed even if selected: for no constraint)
*/
public Integer getMemberId() {
checkSpecifiedProperty("memberId");
return _memberId;
}
/**
* [set] (会員ID)MEMBER_ID: {INT(11), refers to member.MEMBER_ID} <br>
* 会員を識別するID。連番として基本的に自動採番される。<br>
* (会員IDだけに限らず)採番方法はDBMSによって変わる。
* @param memberId The value of the column 'MEMBER_ID'. (NullAllowed: null update allowed for no constraint)
*/
public void setMemberId(Integer memberId) {
registerModifiedProperty("memberId");
_memberId = memberId;
}
/**
* [get] (会員名称)MEMBER_NAME: {VARCHAR(180), refers to member.MEMBER_NAME} <br>
* 会員のフルネームの名称。
* @return The value of the column 'MEMBER_NAME'. (NullAllowed even if selected: for no constraint)
*/
public String getMemberName() {
checkSpecifiedProperty("memberName");
return _memberName;
}
/**
* [set] (会員名称)MEMBER_NAME: {VARCHAR(180), refers to member.MEMBER_NAME} <br>
* 会員のフルネームの名称。
* @param memberName The value of the column 'MEMBER_NAME'. (NullAllowed: null update allowed for no constraint)
*/
public void setMemberName(String memberName) {
registerModifiedProperty("memberName");
_memberName = memberName;
}
/**
* [get] (生年月日)BIRTHDATE: {DATE(10), refers to member.BIRTHDATE} <br>
* 必須項目ではないので、このデータがない会員もいる。
* @return The value of the column 'BIRTHDATE'. (NullAllowed even if selected: for no constraint)
*/
public java.time.LocalDate getBirthdate() {
checkSpecifiedProperty("birthdate");
return _birthdate;
}
/**
* [set] (生年月日)BIRTHDATE: {DATE(10), refers to member.BIRTHDATE} <br>
* 必須項目ではないので、このデータがない会員もいる。
* @param birthdate The value of the column 'BIRTHDATE'. (NullAllowed: null update allowed for no constraint)
*/
public void setBirthdate(java.time.LocalDate birthdate) {
registerModifiedProperty("birthdate");
_birthdate = birthdate;
}
/**
* [get] (正式会員日時)FORMALIZED_DATETIME: {DATETIME(19), refers to member.FORMALIZED_DATETIME} <br>
* 会員が正式に確定した日時。一度確定したら更新されない。<br>
* 仮会員のときはnull。
* @return The value of the column 'FORMALIZED_DATETIME'. (NullAllowed even if selected: for no constraint)
*/
public java.time.LocalDateTime getFormalizedDatetime() {
checkSpecifiedProperty("formalizedDatetime");
return _formalizedDatetime;
}
/**
* [set] (正式会員日時)FORMALIZED_DATETIME: {DATETIME(19), refers to member.FORMALIZED_DATETIME} <br>
* 会員が正式に確定した日時。一度確定したら更新されない。<br>
* 仮会員のときはnull。
* @param formalizedDatetime The value of the column 'FORMALIZED_DATETIME'. (NullAllowed: null update allowed for no constraint)
*/
public void setFormalizedDatetime(java.time.LocalDateTime formalizedDatetime) {
registerModifiedProperty("formalizedDatetime");
_formalizedDatetime = formalizedDatetime;
}
/**
* [get] (会員ステータスコード)MEMBER_STATUS_CODE: {CHAR(3), refers to member.MEMBER_STATUS_CODE, classification=MemberStatus} <br>
* @return The value of the column 'MEMBER_STATUS_CODE'. (NullAllowed even if selected: for no constraint)
*/
public String getMemberStatusCode() {
checkSpecifiedProperty("memberStatusCode");
return _memberStatusCode;
}
/**
* [set] (会員ステータスコード)MEMBER_STATUS_CODE: {CHAR(3), refers to member.MEMBER_STATUS_CODE, classification=MemberStatus} <br>
* @param memberStatusCode The value of the column 'MEMBER_STATUS_CODE'. (NullAllowed: null update allowed for no constraint)
*/
protected void setMemberStatusCode(String memberStatusCode) {
checkClassificationCode("MEMBER_STATUS_CODE", CDef.DefMeta.MemberStatus, memberStatusCode);
registerModifiedProperty("memberStatusCode");
_memberStatusCode = memberStatusCode;
}
/**
* For framework so basically DON'T use this method.
* @param memberStatusCode The value of the column 'MEMBER_STATUS_CODE'. (NullAllowed: null update allowed for no constraint)
*/
public void mynativeMappingMemberStatusCode(String memberStatusCode) {
setMemberStatusCode(memberStatusCode);
}
}
| apache-2.0 |
googleapis/java-dlp | proto-google-cloud-dlp-v2/src/main/java/com/google/privacy/dlp/v2/EntityIdOrBuilder.java | 1681 | /*
* 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/privacy/dlp/v2/storage.proto
package com.google.privacy.dlp.v2;
public interface EntityIdOrBuilder
extends
// @@protoc_insertion_point(interface_extends:google.privacy.dlp.v2.EntityId)
com.google.protobuf.MessageOrBuilder {
/**
*
*
* <pre>
* Composite key indicating which field contains the entity identifier.
* </pre>
*
* <code>.google.privacy.dlp.v2.FieldId field = 1;</code>
*
* @return Whether the field field is set.
*/
boolean hasField();
/**
*
*
* <pre>
* Composite key indicating which field contains the entity identifier.
* </pre>
*
* <code>.google.privacy.dlp.v2.FieldId field = 1;</code>
*
* @return The field.
*/
com.google.privacy.dlp.v2.FieldId getField();
/**
*
*
* <pre>
* Composite key indicating which field contains the entity identifier.
* </pre>
*
* <code>.google.privacy.dlp.v2.FieldId field = 1;</code>
*/
com.google.privacy.dlp.v2.FieldIdOrBuilder getFieldOrBuilder();
}
| apache-2.0 |
shunfei/indexr | indexr-hive/src/main/java/io/indexr/hive/IndexRRecordReader.java | 6861 | package io.indexr.hive;
import com.google.common.base.Preconditions;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hive.serde2.ColumnProjectionUtils;
import org.apache.hadoop.hive.serde2.io.DateWritable;
import org.apache.hadoop.hive.serde2.io.DoubleWritable;
import org.apache.hadoop.hive.serde2.io.TimestampWritable;
import org.apache.hadoop.io.FloatWritable;
import org.apache.hadoop.io.IOUtils;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.mapred.FileSplit;
import org.apache.hadoop.mapred.InputSplit;
import org.apache.hadoop.mapred.RecordReader;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import io.indexr.io.ByteBufferReader;
import io.indexr.segment.ColumnSchema;
import io.indexr.segment.Row;
import io.indexr.segment.Segment;
import io.indexr.segment.storage.itg.IntegratedSegment;
import io.indexr.util.DateTimeUtil;
import io.indexr.util.Strings;
import io.indexr.util.Trick;
public class IndexRRecordReader implements RecordReader<Void, SchemaWritable> {
private static final Log LOG = LogFactory.getLog(IndexRRecordReader.class);
private Segment segment;
private Iterator<Row> rowIterator;
private long offset; // Current row id offset.
private ColumnSchema[] projectCols;
private int[] projectColIds;
public IndexRRecordReader(InputSplit inputSplit, Configuration configuration) throws IOException {
FileSplit fileSplit = (FileSplit) inputSplit;
Preconditions.checkState(fileSplit.getStart() == 0, "Segment should not splited");
Path filePath = fileSplit.getPath();
// Hive may ask to read a file located on local file system.
// We have to get the real file system by path's schema.
FileSystem fileSystem = FileSystem.get(filePath.toUri(), FileSystem.get(configuration).getConf());
if (SegmentHelper.checkSegmentByPath(filePath)) {
ByteBufferReader.Opener opener = ByteBufferReader.Opener.create(fileSystem, filePath);
IntegratedSegment.Fd fd = IntegratedSegment.Fd.create(filePath.toString(), opener);
if (fd != null) {
segment = fd.open();
offset = 0L;
rowIterator = segment.rowTraversal().iterator();
getIncludeColumns(configuration, segment);
}
} else {
LOG.warn("ignore " + filePath);
}
}
private void getIncludeColumns(Configuration conf, Segment segment) {
List<ColumnSchema> segColSchemas = segment.schema().getColumns();
String columnNamesStr = conf.get(ColumnProjectionUtils.READ_COLUMN_NAMES_CONF_STR);
if (ColumnProjectionUtils.isReadAllColumns(conf) ||
columnNamesStr == null) {
projectCols = new ColumnSchema[segColSchemas.size()];
projectColIds = new int[segColSchemas.size()];
for (int i = 0; i < segColSchemas.size(); i++) {
projectCols[i] = segColSchemas.get(i);
projectColIds[i] = i;
}
} else {
String[] ss = Strings.isEmpty(columnNamesStr.trim()) ? new String[]{} : columnNamesStr.split(",");
projectCols = new ColumnSchema[ss.length];
projectColIds = new int[ss.length];
for (int i = 0; i < ss.length; i++) {
String col = ss[i];
int colId = Trick.indexFirst(segColSchemas, c -> c.getName().equalsIgnoreCase(col));
//Preconditions.checkState(colId >= 0, String.format("Column [%s] not found in segment [%s]", col, segment.name()));
if (colId < 0) {
projectCols[i] = null;
projectColIds[i] = -1;
} else {
projectCols[i] = segColSchemas.get(colId);
projectColIds[i] = colId;
}
}
}
}
@Override
public boolean next(Void aVoid, SchemaWritable writable) throws IOException {
if (segment == null) {
return false;
}
if (offset >= segment.rowCount()) {
return false;
}
Row current = rowIterator.next();
Writable[] writables = new Writable[projectCols.length];
for (int i = 0; i < projectCols.length; i++) {
ColumnSchema columnSchema = projectCols[i];
int colId = projectColIds[i];
if (colId == -1 || columnSchema == null) {
writables[i] = null;
continue;
}
switch (columnSchema.getSqlType()) {
case INT:
writables[i] = new IntWritable(current.getInt(colId));
break;
case BIGINT:
writables[i] = new LongWritable(current.getLong(colId));
break;
case FLOAT:
writables[i] = new FloatWritable(current.getFloat(colId));
break;
case DOUBLE:
writables[i] = new DoubleWritable(current.getDouble(colId));
break;
case VARCHAR:
writables[i] = new Text(current.getString(colId).getBytes());
//writables[i] = new BytesWritable();
break;
case DATE:
writables[i] = new DateWritable(DateTimeUtil.getJavaSQLDate(current.getLong(colId)));
break;
case DATETIME:
writables[i] = new TimestampWritable(DateTimeUtil.getJavaSQLTimeStamp(current.getLong(colId)));
break;
default:
throw new IllegalStateException("Illegal type: " + columnSchema.getSqlType());
}
}
offset++;
// Must set it every fucking time, as writable could be reused between segments!
writable.columns = projectCols;
writable.set(writables);
return true;
}
@Override
public Void createKey() {
return null;
}
@Override
public SchemaWritable createValue() {
return new SchemaWritable();
}
@Override
public long getPos() throws IOException {
return offset;
}
@Override
public void close() throws IOException {
IOUtils.cleanup(LOG, segment);
}
@Override
public float getProgress() throws IOException {
if (segment == null) {
return 0;
}
return (float) (offset + 1) / segment.rowCount();
}
}
| apache-2.0 |
jperaltar/HashTable | gens/Lista.java | 2121 | package es.urjc.ist.gens;
import java.util.Iterator;
public class Lista<T> implements Iterable<T>, Secuencia<T> {
//Protected
int len;
Node<T> first_node;
static class Node<T> {
public T value;
public Node<T> next;
public Node(T new_value, Node<T> nod){
value = new_value;
next = nod;
}
}
public Lista(){
len = 0;
first_node = null;
}
//Iterator for the list
protected class ListIterator implements Iterator<T> {
public Node<T> aux;
public ListIterator(){
aux = first_node;
}
public boolean hasNext() {
if(aux == null){
return false;
}else{
return true;
}
}
public T next() {
Node<T> prev;
T aux_val;
if(aux != null){
prev = aux;
aux = aux.next;
aux_val = prev.value;
}else{
aux_val = null;
}
return aux_val;
}
public void remove() {
throw new UnsupportedOperationException("Not Supported");
}
}
public Iterator<T> iterator() {
ListIterator it = new ListIterator();
return it;
}
public void put(T val) {
Node<T> aux = first_node;
Node<T> new_node = new Node<T>(val, null);
//Go to the last node and inserts
//the new node after this one
if(aux != null){
for(int i = 0; i < len-1; i++){
aux = aux.next;
}
aux.next = new_node;
}else{
first_node = new_node;
}
//Add one to total length
len++;
}
public T get(int pos) {
Node<T> aux = first_node;
if(pos >= 0 && pos < len){
for(int i = 0; i < pos; i++){
aux = aux.next;
}
return aux.value;
}else{
return null;
}
}
public boolean delete(int pos) {
Node<T> aux = first_node;
if(pos > 0 && pos < len){
for(int i = 0; i < pos-1; i++){
aux = aux.next;
}
aux.next = aux.next.next;
len--;
return true;
}else if(pos == 0) {
first_node = aux.next;
len--;
return true;
}else {
return false;
}
}
public String toString(){
String str = "";
Node<T> aux = first_node;
while(aux != null){
str = str + aux.value.toString() + " ";
aux = aux.next;
}
return str;
}
public int length() {
return len;
}
}
| apache-2.0 |
google/schemaorg-java | src/main/java/com/google/schemaorg/core/GardenStore.java | 22986 | /*
* Copyright 2016 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.schemaorg.core;
import com.google.schemaorg.JsonLdContext;
import com.google.schemaorg.SchemaOrgType;
import com.google.schemaorg.core.datatype.Date;
import com.google.schemaorg.core.datatype.Text;
import com.google.schemaorg.core.datatype.URL;
import com.google.schemaorg.goog.PopularityScoreSpecification;
import javax.annotation.Nullable;
/** Interface of <a href="http://schema.org/GardenStore}">http://schema.org/GardenStore}</a>. */
public interface GardenStore extends Store {
/**
* Builder interface of <a
* href="http://schema.org/GardenStore}">http://schema.org/GardenStore}</a>.
*/
public interface Builder extends Store.Builder {
@Override
Builder addJsonLdContext(@Nullable JsonLdContext context);
@Override
Builder addJsonLdContext(@Nullable JsonLdContext.Builder context);
@Override
Builder setJsonLdId(@Nullable String value);
@Override
Builder setJsonLdReverse(String property, Thing obj);
@Override
Builder setJsonLdReverse(String property, Thing.Builder builder);
/** Add a value to property additionalProperty. */
Builder addAdditionalProperty(PropertyValue value);
/** Add a value to property additionalProperty. */
Builder addAdditionalProperty(PropertyValue.Builder value);
/** Add a value to property additionalProperty. */
Builder addAdditionalProperty(String value);
/** Add a value to property additionalType. */
Builder addAdditionalType(URL value);
/** Add a value to property additionalType. */
Builder addAdditionalType(String value);
/** Add a value to property address. */
Builder addAddress(PostalAddress value);
/** Add a value to property address. */
Builder addAddress(PostalAddress.Builder value);
/** Add a value to property address. */
Builder addAddress(Text value);
/** Add a value to property address. */
Builder addAddress(String value);
/** Add a value to property aggregateRating. */
Builder addAggregateRating(AggregateRating value);
/** Add a value to property aggregateRating. */
Builder addAggregateRating(AggregateRating.Builder value);
/** Add a value to property aggregateRating. */
Builder addAggregateRating(String value);
/** Add a value to property alternateName. */
Builder addAlternateName(Text value);
/** Add a value to property alternateName. */
Builder addAlternateName(String value);
/** Add a value to property alumni. */
Builder addAlumni(Person value);
/** Add a value to property alumni. */
Builder addAlumni(Person.Builder value);
/** Add a value to property alumni. */
Builder addAlumni(String value);
/** Add a value to property areaServed. */
Builder addAreaServed(AdministrativeArea value);
/** Add a value to property areaServed. */
Builder addAreaServed(AdministrativeArea.Builder value);
/** Add a value to property areaServed. */
Builder addAreaServed(GeoShape value);
/** Add a value to property areaServed. */
Builder addAreaServed(GeoShape.Builder value);
/** Add a value to property areaServed. */
Builder addAreaServed(Place value);
/** Add a value to property areaServed. */
Builder addAreaServed(Place.Builder value);
/** Add a value to property areaServed. */
Builder addAreaServed(Text value);
/** Add a value to property areaServed. */
Builder addAreaServed(String value);
/** Add a value to property award. */
Builder addAward(Text value);
/** Add a value to property award. */
Builder addAward(String value);
/** Add a value to property awards. */
Builder addAwards(Text value);
/** Add a value to property awards. */
Builder addAwards(String value);
/** Add a value to property branchCode. */
Builder addBranchCode(Text value);
/** Add a value to property branchCode. */
Builder addBranchCode(String value);
/** Add a value to property branchOf. */
Builder addBranchOf(Organization value);
/** Add a value to property branchOf. */
Builder addBranchOf(Organization.Builder value);
/** Add a value to property branchOf. */
Builder addBranchOf(String value);
/** Add a value to property brand. */
Builder addBrand(Brand value);
/** Add a value to property brand. */
Builder addBrand(Brand.Builder value);
/** Add a value to property brand. */
Builder addBrand(Organization value);
/** Add a value to property brand. */
Builder addBrand(Organization.Builder value);
/** Add a value to property brand. */
Builder addBrand(String value);
/** Add a value to property contactPoint. */
Builder addContactPoint(ContactPoint value);
/** Add a value to property contactPoint. */
Builder addContactPoint(ContactPoint.Builder value);
/** Add a value to property contactPoint. */
Builder addContactPoint(String value);
/** Add a value to property contactPoints. */
Builder addContactPoints(ContactPoint value);
/** Add a value to property contactPoints. */
Builder addContactPoints(ContactPoint.Builder value);
/** Add a value to property contactPoints. */
Builder addContactPoints(String value);
/** Add a value to property containedIn. */
Builder addContainedIn(Place value);
/** Add a value to property containedIn. */
Builder addContainedIn(Place.Builder value);
/** Add a value to property containedIn. */
Builder addContainedIn(String value);
/** Add a value to property containedInPlace. */
Builder addContainedInPlace(Place value);
/** Add a value to property containedInPlace. */
Builder addContainedInPlace(Place.Builder value);
/** Add a value to property containedInPlace. */
Builder addContainedInPlace(String value);
/** Add a value to property containsPlace. */
Builder addContainsPlace(Place value);
/** Add a value to property containsPlace. */
Builder addContainsPlace(Place.Builder value);
/** Add a value to property containsPlace. */
Builder addContainsPlace(String value);
/** Add a value to property currenciesAccepted. */
Builder addCurrenciesAccepted(Text value);
/** Add a value to property currenciesAccepted. */
Builder addCurrenciesAccepted(String value);
/** Add a value to property department. */
Builder addDepartment(Organization value);
/** Add a value to property department. */
Builder addDepartment(Organization.Builder value);
/** Add a value to property department. */
Builder addDepartment(String value);
/** Add a value to property description. */
Builder addDescription(Text value);
/** Add a value to property description. */
Builder addDescription(String value);
/** Add a value to property dissolutionDate. */
Builder addDissolutionDate(Date value);
/** Add a value to property dissolutionDate. */
Builder addDissolutionDate(String value);
/** Add a value to property duns. */
Builder addDuns(Text value);
/** Add a value to property duns. */
Builder addDuns(String value);
/** Add a value to property email. */
Builder addEmail(Text value);
/** Add a value to property email. */
Builder addEmail(String value);
/** Add a value to property employee. */
Builder addEmployee(Person value);
/** Add a value to property employee. */
Builder addEmployee(Person.Builder value);
/** Add a value to property employee. */
Builder addEmployee(String value);
/** Add a value to property employees. */
Builder addEmployees(Person value);
/** Add a value to property employees. */
Builder addEmployees(Person.Builder value);
/** Add a value to property employees. */
Builder addEmployees(String value);
/** Add a value to property event. */
Builder addEvent(Event value);
/** Add a value to property event. */
Builder addEvent(Event.Builder value);
/** Add a value to property event. */
Builder addEvent(String value);
/** Add a value to property events. */
Builder addEvents(Event value);
/** Add a value to property events. */
Builder addEvents(Event.Builder value);
/** Add a value to property events. */
Builder addEvents(String value);
/** Add a value to property faxNumber. */
Builder addFaxNumber(Text value);
/** Add a value to property faxNumber. */
Builder addFaxNumber(String value);
/** Add a value to property founder. */
Builder addFounder(Person value);
/** Add a value to property founder. */
Builder addFounder(Person.Builder value);
/** Add a value to property founder. */
Builder addFounder(String value);
/** Add a value to property founders. */
Builder addFounders(Person value);
/** Add a value to property founders. */
Builder addFounders(Person.Builder value);
/** Add a value to property founders. */
Builder addFounders(String value);
/** Add a value to property foundingDate. */
Builder addFoundingDate(Date value);
/** Add a value to property foundingDate. */
Builder addFoundingDate(String value);
/** Add a value to property foundingLocation. */
Builder addFoundingLocation(Place value);
/** Add a value to property foundingLocation. */
Builder addFoundingLocation(Place.Builder value);
/** Add a value to property foundingLocation. */
Builder addFoundingLocation(String value);
/** Add a value to property geo. */
Builder addGeo(GeoCoordinates value);
/** Add a value to property geo. */
Builder addGeo(GeoCoordinates.Builder value);
/** Add a value to property geo. */
Builder addGeo(GeoShape value);
/** Add a value to property geo. */
Builder addGeo(GeoShape.Builder value);
/** Add a value to property geo. */
Builder addGeo(String value);
/** Add a value to property globalLocationNumber. */
Builder addGlobalLocationNumber(Text value);
/** Add a value to property globalLocationNumber. */
Builder addGlobalLocationNumber(String value);
/** Add a value to property hasMap. */
Builder addHasMap(Map value);
/** Add a value to property hasMap. */
Builder addHasMap(Map.Builder value);
/** Add a value to property hasMap. */
Builder addHasMap(URL value);
/** Add a value to property hasMap. */
Builder addHasMap(String value);
/** Add a value to property hasOfferCatalog. */
Builder addHasOfferCatalog(OfferCatalog value);
/** Add a value to property hasOfferCatalog. */
Builder addHasOfferCatalog(OfferCatalog.Builder value);
/** Add a value to property hasOfferCatalog. */
Builder addHasOfferCatalog(String value);
/** Add a value to property hasPOS. */
Builder addHasPOS(Place value);
/** Add a value to property hasPOS. */
Builder addHasPOS(Place.Builder value);
/** Add a value to property hasPOS. */
Builder addHasPOS(String value);
/** Add a value to property image. */
Builder addImage(ImageObject value);
/** Add a value to property image. */
Builder addImage(ImageObject.Builder value);
/** Add a value to property image. */
Builder addImage(URL value);
/** Add a value to property image. */
Builder addImage(String value);
/** Add a value to property isicV4. */
Builder addIsicV4(Text value);
/** Add a value to property isicV4. */
Builder addIsicV4(String value);
/** Add a value to property legalName. */
Builder addLegalName(Text value);
/** Add a value to property legalName. */
Builder addLegalName(String value);
/** Add a value to property location. */
Builder addLocation(Place value);
/** Add a value to property location. */
Builder addLocation(Place.Builder value);
/** Add a value to property location. */
Builder addLocation(PostalAddress value);
/** Add a value to property location. */
Builder addLocation(PostalAddress.Builder value);
/** Add a value to property location. */
Builder addLocation(Text value);
/** Add a value to property location. */
Builder addLocation(String value);
/** Add a value to property logo. */
Builder addLogo(ImageObject value);
/** Add a value to property logo. */
Builder addLogo(ImageObject.Builder value);
/** Add a value to property logo. */
Builder addLogo(URL value);
/** Add a value to property logo. */
Builder addLogo(String value);
/** Add a value to property mainEntityOfPage. */
Builder addMainEntityOfPage(CreativeWork value);
/** Add a value to property mainEntityOfPage. */
Builder addMainEntityOfPage(CreativeWork.Builder value);
/** Add a value to property mainEntityOfPage. */
Builder addMainEntityOfPage(URL value);
/** Add a value to property mainEntityOfPage. */
Builder addMainEntityOfPage(String value);
/** Add a value to property makesOffer. */
Builder addMakesOffer(Offer value);
/** Add a value to property makesOffer. */
Builder addMakesOffer(Offer.Builder value);
/** Add a value to property makesOffer. */
Builder addMakesOffer(String value);
/** Add a value to property map. */
Builder addMap(URL value);
/** Add a value to property map. */
Builder addMap(String value);
/** Add a value to property maps. */
Builder addMaps(URL value);
/** Add a value to property maps. */
Builder addMaps(String value);
/** Add a value to property member. */
Builder addMember(Organization value);
/** Add a value to property member. */
Builder addMember(Organization.Builder value);
/** Add a value to property member. */
Builder addMember(Person value);
/** Add a value to property member. */
Builder addMember(Person.Builder value);
/** Add a value to property member. */
Builder addMember(String value);
/** Add a value to property memberOf. */
Builder addMemberOf(Organization value);
/** Add a value to property memberOf. */
Builder addMemberOf(Organization.Builder value);
/** Add a value to property memberOf. */
Builder addMemberOf(ProgramMembership value);
/** Add a value to property memberOf. */
Builder addMemberOf(ProgramMembership.Builder value);
/** Add a value to property memberOf. */
Builder addMemberOf(String value);
/** Add a value to property members. */
Builder addMembers(Organization value);
/** Add a value to property members. */
Builder addMembers(Organization.Builder value);
/** Add a value to property members. */
Builder addMembers(Person value);
/** Add a value to property members. */
Builder addMembers(Person.Builder value);
/** Add a value to property members. */
Builder addMembers(String value);
/** Add a value to property naics. */
Builder addNaics(Text value);
/** Add a value to property naics. */
Builder addNaics(String value);
/** Add a value to property name. */
Builder addName(Text value);
/** Add a value to property name. */
Builder addName(String value);
/** Add a value to property numberOfEmployees. */
Builder addNumberOfEmployees(QuantitativeValue value);
/** Add a value to property numberOfEmployees. */
Builder addNumberOfEmployees(QuantitativeValue.Builder value);
/** Add a value to property numberOfEmployees. */
Builder addNumberOfEmployees(String value);
/** Add a value to property openingHours. */
Builder addOpeningHours(Text value);
/** Add a value to property openingHours. */
Builder addOpeningHours(String value);
/** Add a value to property openingHoursSpecification. */
Builder addOpeningHoursSpecification(OpeningHoursSpecification value);
/** Add a value to property openingHoursSpecification. */
Builder addOpeningHoursSpecification(OpeningHoursSpecification.Builder value);
/** Add a value to property openingHoursSpecification. */
Builder addOpeningHoursSpecification(String value);
/** Add a value to property owns. */
Builder addOwns(OwnershipInfo value);
/** Add a value to property owns. */
Builder addOwns(OwnershipInfo.Builder value);
/** Add a value to property owns. */
Builder addOwns(Product value);
/** Add a value to property owns. */
Builder addOwns(Product.Builder value);
/** Add a value to property owns. */
Builder addOwns(String value);
/** Add a value to property parentOrganization. */
Builder addParentOrganization(Organization value);
/** Add a value to property parentOrganization. */
Builder addParentOrganization(Organization.Builder value);
/** Add a value to property parentOrganization. */
Builder addParentOrganization(String value);
/** Add a value to property paymentAccepted. */
Builder addPaymentAccepted(Text value);
/** Add a value to property paymentAccepted. */
Builder addPaymentAccepted(String value);
/** Add a value to property photo. */
Builder addPhoto(ImageObject value);
/** Add a value to property photo. */
Builder addPhoto(ImageObject.Builder value);
/** Add a value to property photo. */
Builder addPhoto(Photograph value);
/** Add a value to property photo. */
Builder addPhoto(Photograph.Builder value);
/** Add a value to property photo. */
Builder addPhoto(String value);
/** Add a value to property photos. */
Builder addPhotos(ImageObject value);
/** Add a value to property photos. */
Builder addPhotos(ImageObject.Builder value);
/** Add a value to property photos. */
Builder addPhotos(Photograph value);
/** Add a value to property photos. */
Builder addPhotos(Photograph.Builder value);
/** Add a value to property photos. */
Builder addPhotos(String value);
/** Add a value to property potentialAction. */
Builder addPotentialAction(Action value);
/** Add a value to property potentialAction. */
Builder addPotentialAction(Action.Builder value);
/** Add a value to property potentialAction. */
Builder addPotentialAction(String value);
/** Add a value to property priceRange. */
Builder addPriceRange(Text value);
/** Add a value to property priceRange. */
Builder addPriceRange(String value);
/** Add a value to property review. */
Builder addReview(Review value);
/** Add a value to property review. */
Builder addReview(Review.Builder value);
/** Add a value to property review. */
Builder addReview(String value);
/** Add a value to property reviews. */
Builder addReviews(Review value);
/** Add a value to property reviews. */
Builder addReviews(Review.Builder value);
/** Add a value to property reviews. */
Builder addReviews(String value);
/** Add a value to property sameAs. */
Builder addSameAs(URL value);
/** Add a value to property sameAs. */
Builder addSameAs(String value);
/** Add a value to property seeks. */
Builder addSeeks(Demand value);
/** Add a value to property seeks. */
Builder addSeeks(Demand.Builder value);
/** Add a value to property seeks. */
Builder addSeeks(String value);
/** Add a value to property serviceArea. */
Builder addServiceArea(AdministrativeArea value);
/** Add a value to property serviceArea. */
Builder addServiceArea(AdministrativeArea.Builder value);
/** Add a value to property serviceArea. */
Builder addServiceArea(GeoShape value);
/** Add a value to property serviceArea. */
Builder addServiceArea(GeoShape.Builder value);
/** Add a value to property serviceArea. */
Builder addServiceArea(Place value);
/** Add a value to property serviceArea. */
Builder addServiceArea(Place.Builder value);
/** Add a value to property serviceArea. */
Builder addServiceArea(String value);
/** Add a value to property subOrganization. */
Builder addSubOrganization(Organization value);
/** Add a value to property subOrganization. */
Builder addSubOrganization(Organization.Builder value);
/** Add a value to property subOrganization. */
Builder addSubOrganization(String value);
/** Add a value to property taxID. */
Builder addTaxID(Text value);
/** Add a value to property taxID. */
Builder addTaxID(String value);
/** Add a value to property telephone. */
Builder addTelephone(Text value);
/** Add a value to property telephone. */
Builder addTelephone(String value);
/** Add a value to property url. */
Builder addUrl(URL value);
/** Add a value to property url. */
Builder addUrl(String value);
/** Add a value to property vatID. */
Builder addVatID(Text value);
/** Add a value to property vatID. */
Builder addVatID(String value);
/** Add a value to property detailedDescription. */
Builder addDetailedDescription(Article value);
/** Add a value to property detailedDescription. */
Builder addDetailedDescription(Article.Builder value);
/** Add a value to property detailedDescription. */
Builder addDetailedDescription(String value);
/** Add a value to property popularityScore. */
Builder addPopularityScore(PopularityScoreSpecification value);
/** Add a value to property popularityScore. */
Builder addPopularityScore(PopularityScoreSpecification.Builder value);
/** Add a value to property popularityScore. */
Builder addPopularityScore(String value);
/**
* Add a value to property.
*
* @param name The property name.
* @param value The value of the property.
*/
Builder addProperty(String name, SchemaOrgType value);
/**
* Add a value to property.
*
* @param name The property name.
* @param builder The schema.org object builder for the property value.
*/
Builder addProperty(String name, Thing.Builder builder);
/**
* Add a value to property.
*
* @param name The property name.
* @param value The string value of the property.
*/
Builder addProperty(String name, String value);
/** Build a {@link GardenStore} object. */
GardenStore build();
}
}
| apache-2.0 |
shevart/Android-Map-Project | app/src/main/java/com/shevart/google_map/util/UiUtil.java | 1611 | package com.shevart.google_map.util;
import android.content.Context;
import android.os.Build;
import android.support.annotation.ColorRes;
import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import java.lang.reflect.Method;
@SuppressWarnings("unused")
public class UiUtil {
public static View inflate(@NonNull ViewGroup parent, @LayoutRes int layoutRes) {
return LayoutInflater.from(parent.getContext()).inflate(layoutRes, parent, false);
}
public static void disableKeyboardOpening(@NonNull final EditText editText) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
editText.setShowSoftInputOnFocus(false);
} else {
try {
@SuppressWarnings("RedundantArrayCreation")
final Method method =
EditText.class.getMethod("setShowSoftInputOnFocus", new Class[]{boolean.class});
method.setAccessible(true);
method.invoke(editText, false);
} catch (Exception e) {
LogUtil.e(e);
}
}
}
@SuppressWarnings("WeakerAccess")
public static int getColor(@NonNull Context context, @ColorRes int colorId) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
return context.getResources().getColor(colorId, context.getTheme());
} else {
return context.getResources().getColor(colorId);
}
}
}
| apache-2.0 |
otipc/smart-rpc | src/main/java/net/nio/ChannelEventType.java | 137 | package net.nio;
public enum ChannelEventType {
CHANNEL_OPENED,
CHANNEL_CLOSED,
CHANNEL_READ,
CHANNEL_WRITTEN,
CHANNEL_THROWN
}
| apache-2.0 |
zhangclong/pathlet | core/src/com/google/code/pathlet/core/ProceedingJoinPoint.java | 2872 | /*
* Copyright 2010-2012 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 com.google.code.pathlet.core;
import java.lang.reflect.Method;
/**
* This interface represents a generic runtime joinpoint (in the AOP
* terminology).
*
* <p>A runtime joinpoint is an <i>event</i> that occurs on a static
* joinpoint (i.e. a location in a the program). For instance, an
* invocation is the runtime joinpoint on a method (static joinpoint).
* The static part of a given joinpoint can be generically retrieved
* using the {@link #getStaticPart()} method.
*
* <p>In the context of an interception framework, a runtime joinpoint
* is then the reification of an access to an accessible object (a
* method, a constructor, a field), i.e. the static part of the
* joinpoint. It is passed to the interceptors that are installed on
* the static joinpoint.
*
* @author Charlie Zhang
* */
public interface ProceedingJoinPoint {
/**
* Get the arguments as an array object. It is possible to change element
* values within this array to change the arguments.
*
* @return the argument of the invocation
*/
Object[] getArguments();
/**
* Gets the method being called.
*
* <p>
* This method is a frienly implementation of the
* {@link JoinPoint#getStaticPart()} method (same result).
*
* @return the method being called.
*/
Method getMethod();
/**
* Gets intercepted object
* @return
*/
Object getTarget();
/**
* Return the proxy object for target.
* @return
*/
Object getTargetProxy();
/**
* Return the corresponding Resource of target
*/
Resource getResource();
/**
* Proceed with the next advice or target method invocation
*
* @return the advice or target method return value.
*
* @throws Throwable if the joinpoint throws an exception.
*/
Object proceed() throws Throwable;
/**
* Proceed with the next advice or target method invocation. The difference from the proceed() is
* this method add Object[] arguments which will transfer into target method arguments.
* Say in other words, the arguments value of target method could be changed in advice method at runtime.
*
* @param args
* @return
* @throws Throwable
*/
public Object proceed(Object[] args) throws Throwable;
}
| apache-2.0 |
googleads/googleads-java-lib | modules/dfp_axis/src/main/java/com/google/api/ads/admanager/axis/v202202/TargetingPresetPage.java | 9730 | // Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* TargetingPresetPage.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.admanager.axis.v202202;
/**
* Captures a paged query of {@link TargetingPresetDto} objects.
*/
public class TargetingPresetPage implements java.io.Serializable , Iterable<com.google.api.ads.admanager.axis.v202202.TargetingPreset>{
/* The size of the total result set to which this page belongs. */
private java.lang.Integer totalResultSetSize;
/* The absolute index in the total result set on which this page
* begins. */
private java.lang.Integer startIndex;
/* The collection of line items contained within this page. */
private com.google.api.ads.admanager.axis.v202202.TargetingPreset[] results;
public TargetingPresetPage() {
}
public TargetingPresetPage(
java.lang.Integer totalResultSetSize,
java.lang.Integer startIndex,
com.google.api.ads.admanager.axis.v202202.TargetingPreset[] results) {
this.totalResultSetSize = totalResultSetSize;
this.startIndex = startIndex;
this.results = results;
}
@Override
public String toString() {
return com.google.common.base.MoreObjects.toStringHelper(this.getClass())
.omitNullValues()
// Only include length of results to avoid overly verbose output
.add("results.length", getResults() == null ? 0 : getResults().length)
.add("startIndex", getStartIndex())
.add("totalResultSetSize", getTotalResultSetSize())
.toString();
}
/**
* Gets the totalResultSetSize value for this TargetingPresetPage.
*
* @return totalResultSetSize * The size of the total result set to which this page belongs.
*/
public java.lang.Integer getTotalResultSetSize() {
return totalResultSetSize;
}
/**
* Sets the totalResultSetSize value for this TargetingPresetPage.
*
* @param totalResultSetSize * The size of the total result set to which this page belongs.
*/
public void setTotalResultSetSize(java.lang.Integer totalResultSetSize) {
this.totalResultSetSize = totalResultSetSize;
}
/**
* Gets the startIndex value for this TargetingPresetPage.
*
* @return startIndex * The absolute index in the total result set on which this page
* begins.
*/
public java.lang.Integer getStartIndex() {
return startIndex;
}
/**
* Sets the startIndex value for this TargetingPresetPage.
*
* @param startIndex * The absolute index in the total result set on which this page
* begins.
*/
public void setStartIndex(java.lang.Integer startIndex) {
this.startIndex = startIndex;
}
/**
* Gets the results value for this TargetingPresetPage.
*
* @return results * The collection of line items contained within this page.
*/
public com.google.api.ads.admanager.axis.v202202.TargetingPreset[] getResults() {
return results;
}
/**
* Sets the results value for this TargetingPresetPage.
*
* @param results * The collection of line items contained within this page.
*/
public void setResults(com.google.api.ads.admanager.axis.v202202.TargetingPreset[] results) {
this.results = results;
}
public com.google.api.ads.admanager.axis.v202202.TargetingPreset getResults(int i) {
return this.results[i];
}
public void setResults(int i, com.google.api.ads.admanager.axis.v202202.TargetingPreset _value) {
this.results[i] = _value;
}
/**
* Returns an iterator over this page's {@code results} that:
* <ul>
* <li>Will not be {@code null}.</li>
* <li>Will not support {@link java.util.Iterator#remove()}.</li>
* </ul>
*
* @return a non-null iterator.
*/
@Override
public java.util.Iterator<com.google.api.ads.admanager.axis.v202202.TargetingPreset> iterator() {
if (results == null) {
return java.util.Collections.<com.google.api.ads.admanager.axis.v202202.TargetingPreset>emptyIterator();
}
return java.util.Arrays.<com.google.api.ads.admanager.axis.v202202.TargetingPreset>asList(results).iterator();
}
private java.lang.Object __equalsCalc = null;
public synchronized boolean equals(java.lang.Object obj) {
if (!(obj instanceof TargetingPresetPage)) return false;
TargetingPresetPage other = (TargetingPresetPage) obj;
if (obj == null) return false;
if (this == obj) return true;
if (__equalsCalc != null) {
return (__equalsCalc == obj);
}
__equalsCalc = obj;
boolean _equals;
_equals = true &&
((this.totalResultSetSize==null && other.getTotalResultSetSize()==null) ||
(this.totalResultSetSize!=null &&
this.totalResultSetSize.equals(other.getTotalResultSetSize()))) &&
((this.startIndex==null && other.getStartIndex()==null) ||
(this.startIndex!=null &&
this.startIndex.equals(other.getStartIndex()))) &&
((this.results==null && other.getResults()==null) ||
(this.results!=null &&
java.util.Arrays.equals(this.results, other.getResults())));
__equalsCalc = null;
return _equals;
}
private boolean __hashCodeCalc = false;
public synchronized int hashCode() {
if (__hashCodeCalc) {
return 0;
}
__hashCodeCalc = true;
int _hashCode = 1;
if (getTotalResultSetSize() != null) {
_hashCode += getTotalResultSetSize().hashCode();
}
if (getStartIndex() != null) {
_hashCode += getStartIndex().hashCode();
}
if (getResults() != null) {
for (int i=0;
i<java.lang.reflect.Array.getLength(getResults());
i++) {
java.lang.Object obj = java.lang.reflect.Array.get(getResults(), i);
if (obj != null &&
!obj.getClass().isArray()) {
_hashCode += obj.hashCode();
}
}
}
__hashCodeCalc = false;
return _hashCode;
}
// Type metadata
private static org.apache.axis.description.TypeDesc typeDesc =
new org.apache.axis.description.TypeDesc(TargetingPresetPage.class, true);
static {
typeDesc.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202202", "TargetingPresetPage"));
org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("totalResultSetSize");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202202", "totalResultSetSize"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "int"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("startIndex");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202202", "startIndex"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "int"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("results");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202202", "results"));
elemField.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202202", "TargetingPreset"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
elemField.setMaxOccursUnbounded(true);
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 |
destitutus/collab | src/main/java/com/codio/collab/core/types/DocumentMessage.java | 1791 | /**
* Copyright Suchkov Dmitrii
*
* 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.codio.collab.core.types;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;
import java.util.Map;
@JsonIgnoreProperties(ignoreUnknown=true)
public class DocumentMessage extends BasicMessage {
private String create;
private String delete;
private List<Object> op;
private Map<String, Object> meta;
@JsonProperty("delete")
public String getDelete() {
return delete;
}
@JsonProperty("delete")
public void setDelete(String delete) {
this.delete = delete;
}
@JsonProperty("create")
public String getCreate() {
return create;
}
@JsonProperty("create")
public void setCreate(String create) {
this.create = create;
}
@JsonProperty("op")
public List<Object> getOp() {
return op;
}
@JsonProperty("op")
public void setOp(List<Object> op) {
this.op = op;
}
@JsonProperty("m")
public Map<String, Object> getMeta() {
return meta;
}
@JsonProperty("m")
public void setMeta(Map<String, Object> meta) {
this.meta = meta;
}
}
| apache-2.0 |
vschs007/buck | src/com/facebook/buck/event/listener/DistBuildSlaveEventBusListener.java | 7802 | /*
* Copyright 2017-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.event.listener;
import com.facebook.buck.distributed.DistBuildService;
import com.facebook.buck.distributed.DistBuildUtil;
import com.facebook.buck.distributed.thrift.BuildSlaveConsoleEvent;
import com.facebook.buck.distributed.thrift.BuildSlaveStatus;
import com.facebook.buck.distributed.thrift.RunId;
import com.facebook.buck.distributed.thrift.StampedeId;
import com.facebook.buck.event.BuckEventListener;
import com.facebook.buck.event.ConsoleEvent;
import com.facebook.buck.log.Logger;
import com.facebook.buck.model.BuildId;
import com.facebook.buck.rules.BuildEvent;
import com.facebook.buck.rules.BuildRuleEvent;
import com.facebook.buck.test.selectors.Nullable;
import com.facebook.buck.timing.Clock;
import com.google.common.collect.ImmutableList;
import com.google.common.eventbus.Subscribe;
import java.io.Closeable;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import javax.annotation.concurrent.GuardedBy;
/**
* Listener to transmit DistBuildSlave events over to buck frontend.
* NOTE: We do not promise to transmit every single update to BuildSlaveStatus,
* but we do promise to always transmit BuildSlaveStatus with the latest updates.
*/
public class DistBuildSlaveEventBusListener implements BuckEventListener, Closeable {
private static final Logger LOG = Logger.get(DistBuildSlaveEventBusListener.class);
private static final int DEFAULT_SERVER_UPDATE_PERIOD_MILLIS = 500;
private final StampedeId stampedeId;
private final RunId runId;
private final Clock clock;
private final ScheduledFuture<?> scheduledServerUpdates;
private final Object consoleEventsLock = new Object();
@GuardedBy("consoleEventsLock")
private final List<BuildSlaveConsoleEvent> consoleEvents = new LinkedList<>();
private final Object statusLock = new Object();
@GuardedBy("statusLock")
private final BuildSlaveStatus status = new BuildSlaveStatus();
private volatile @Nullable DistBuildService distBuildService;
public DistBuildSlaveEventBusListener(
StampedeId stampedeId,
RunId runId,
Clock clock,
ScheduledExecutorService networkScheduler) {
this(stampedeId, runId, clock, networkScheduler, DEFAULT_SERVER_UPDATE_PERIOD_MILLIS);
}
public DistBuildSlaveEventBusListener(
StampedeId stampedeId,
RunId runId,
Clock clock,
ScheduledExecutorService networkScheduler,
long serverUpdatePeriodMillis) {
this.stampedeId = stampedeId;
this.runId = runId;
this.clock = clock;
// No synchronization needed here because status is final.
status.setStampedeId(stampedeId);
status.setRunId(runId);
scheduledServerUpdates = networkScheduler.scheduleAtFixedRate(
this::sendServerUpdates,
0,
serverUpdatePeriodMillis,
TimeUnit.MILLISECONDS);
}
public void setDistBuildService(DistBuildService service) {
this.distBuildService = service;
}
@Override
public void outputTrace(BuildId buildId) throws InterruptedException {}
@Override
public void close() throws IOException {
scheduledServerUpdates.cancel(false);
// Send final updates.
sendServerUpdates();
}
private void sendStatusToFrontend() {
if (distBuildService == null) {
return;
}
BuildSlaveStatus statusCopy;
synchronized (statusLock) {
statusCopy = status.deepCopy();
}
try {
distBuildService.updateBuildSlaveStatus(stampedeId, runId, statusCopy);
} catch (IOException e) {
LOG.error(e, "Could not update slave status to frontend.");
}
}
private void sendConsoleEventsToFrontend() {
if (distBuildService == null) {
return;
}
ImmutableList<BuildSlaveConsoleEvent> consoleEventsCopy;
synchronized (consoleEventsLock) {
consoleEventsCopy = ImmutableList.copyOf(consoleEvents);
consoleEvents.clear();
}
if (consoleEventsCopy.size() == 0) {
return;
}
try {
distBuildService.uploadBuildSlaveConsoleEvents(
stampedeId,
runId,
consoleEventsCopy);
} catch (IOException e) {
LOG.error(e, "Could not upload slave console events to frontend.");
}
}
private void sendServerUpdates() {
sendStatusToFrontend();
sendConsoleEventsToFrontend();
}
@Subscribe
public void logEvent(ConsoleEvent event) {
if (!event.getLevel().equals(Level.WARNING) &&
!event.getLevel().equals(Level.SEVERE)) {
return;
}
synchronized (consoleEventsLock) {
BuildSlaveConsoleEvent slaveConsoleEvent =
DistBuildUtil.createBuildSlaveConsoleEvent(event, clock.currentTimeMillis());
consoleEvents.add(slaveConsoleEvent);
}
}
@Subscribe
public void ruleCountCalculated(BuildEvent.RuleCountCalculated calculated) {
synchronized (statusLock) {
status.setTotalRulesCount(calculated.getNumRules());
}
}
@Subscribe
public void ruleCountUpdated(BuildEvent.UnskippedRuleCountUpdated updated) {
synchronized (statusLock) {
status.setTotalRulesCount(updated.getNumRules());
}
}
@SuppressWarnings("unused")
@Subscribe
public void buildRuleStarted(BuildRuleEvent.Started started) {
synchronized (statusLock) {
status.setRulesStartedCount(status.getRulesStartedCount() + 1);
}
}
@Subscribe
public void buildRuleFinished(BuildRuleEvent.Finished finished) {
synchronized (statusLock) {
status.setRulesStartedCount(status.getRulesStartedCount() - 1);
status.setRulesFinishedCount(status.getRulesFinishedCount() + 1);
switch (finished.getStatus()) {
case SUCCESS:
status.setRulesSuccessCount(status.getRulesSuccessCount() + 1);
break;
case FAIL:
status.setRulesFailureCount(status.getRulesFailureCount() + 1);
break;
case CANCELED:
break;
}
switch (finished.getCacheResult().getType()) {
case HIT:
status.setCacheHitsCount(status.getCacheHitsCount() + 1);
break;
case MISS:
status.setCacheMissesCount(status.getCacheMissesCount() + 1);
break;
case ERROR:
status.setCacheErrorsCount(status.getCacheErrorsCount() + 1);
break;
case IGNORED:
status.setCacheIgnoresCount(status.getCacheIgnoresCount() + 1);
break;
case LOCAL_KEY_UNCHANGED_HIT:
status.setCacheLocalKeyUnchangedHitsCount(
status.getCacheLocalKeyUnchangedHitsCount() + 1);
break;
}
}
}
/**
* TODO(shivanker): Add support for keeping track of suspended rules.
*
* @Subscribe public void buildRuleResumed(BuildRuleEvent.Resumed resumed) {}
* @Subscribe public void buildRuleSuspended(BuildRuleEvent.Suspended suspended) {}
*/
/**
* TODO(shivanker): Add support for keeping track of cache uploads.
* @Subscribe
* public void onHttpArtifactCacheFinishedEvent(HttpArtifactCacheEvent.Finished event) {}
*/
}
| apache-2.0 |
linkedin/pinot | pinot-core/src/main/java/org/apache/pinot/core/data/table/Key.java | 1782 | /**
* 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.pinot.core.data.table;
import java.util.Arrays;
/**
* Defines the key component of the record.
* <p>Key can be used as the key in a map, and may only contain single-value columns.
* <p>For each data type, the value should be stored as:
* <ul>
* <li>INT: Integer</li>
* <li>LONG: Long</li>
* <li>FLOAT: Float</li>
* <li>DOUBLE: Double</li>
* <li>STRING: String</li>
* <li>BYTES: ByteArray</li>
* </ul>
*
* TODO: Consider replacing Key with Record as the concept is very close and the implementation is the same
*/
public class Key {
private final Object[] _values;
public Key(Object[] values) {
_values = values;
}
// NOTE: Not check class for performance concern
@SuppressWarnings("EqualsWhichDoesntCheckParameterClass")
@Override
public boolean equals(Object o) {
return Arrays.equals(_values, ((Key) o)._values);
}
@Override
public int hashCode() {
return Arrays.hashCode(_values);
}
}
| apache-2.0 |
ketan/gocd | server/src/test-shared/java/com/thoughtworks/go/ClearSingleton.java | 2899 | /*
* Copyright 2020 ThoughtWorks, 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.thoughtworks.go;
import com.thoughtworks.go.plugin.access.analytics.AnalyticsMetadataStore;
import com.thoughtworks.go.plugin.access.artifact.ArtifactMetadataStore;
import com.thoughtworks.go.plugin.access.authorization.AuthorizationMetadataStore;
import com.thoughtworks.go.plugin.access.common.settings.PluginSettingsMetadataStore;
import com.thoughtworks.go.plugin.access.configrepo.ConfigRepoMetadataStore;
import com.thoughtworks.go.plugin.access.elastic.ElasticAgentMetadataStore;
import com.thoughtworks.go.plugin.access.notification.NotificationMetadataStore;
import com.thoughtworks.go.plugin.access.packagematerial.PackageMaterialMetadataStore;
import com.thoughtworks.go.plugin.access.packagematerial.PackageMetadataStore;
import com.thoughtworks.go.plugin.access.packagematerial.RepositoryMetadataStore;
import com.thoughtworks.go.plugin.access.pluggabletask.PluggableTaskConfigStore;
import com.thoughtworks.go.plugin.access.pluggabletask.PluggableTaskMetadataStore;
import com.thoughtworks.go.plugin.access.scm.NewSCMMetadataStore;
import com.thoughtworks.go.plugin.access.scm.SCMMetadataStore;
import com.thoughtworks.go.server.newsecurity.utils.SessionUtils;
import org.junit.rules.ExternalResource;
public class ClearSingleton extends ExternalResource {
@Override
protected void before() {
clearSingletons();
}
@Override
protected void after() {
clearSingletons();
}
public static void clearSingletons() {
AnalyticsMetadataStore.instance().clear();
ArtifactMetadataStore.instance().clear();
AuthorizationMetadataStore.instance().clear();
ConfigRepoMetadataStore.instance().clear();
ElasticAgentMetadataStore.instance().clear();
NewSCMMetadataStore.instance().clear();
NotificationMetadataStore.instance().clear();
PackageMaterialMetadataStore.instance().clear();
PluggableTaskMetadataStore.instance().clear();
//
SessionUtils.unsetCurrentUser();
//
PackageMetadataStore.getInstance().clear();
PluggableTaskConfigStore.store().clear();
PluginSettingsMetadataStore.getInstance().clear();
RepositoryMetadataStore.getInstance().clear();
SCMMetadataStore.getInstance().clear();
}
}
| apache-2.0 |
JoelMarcey/buck | test/com/facebook/buck/worker/WorkerProcessTest.java | 5911 | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* 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.worker;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import com.facebook.buck.core.exceptions.HumanReadableException;
import com.facebook.buck.io.filesystem.ProjectFilesystem;
import com.facebook.buck.io.filesystem.TestProjectFilesystems;
import com.facebook.buck.io.filesystem.impl.FakeProjectFilesystem;
import com.facebook.buck.testutil.TemporaryPaths;
import com.facebook.buck.testutil.integration.ProjectWorkspace;
import com.facebook.buck.testutil.integration.TestDataHelper;
import com.facebook.buck.util.Ansi;
import com.facebook.buck.util.Console;
import com.facebook.buck.util.DefaultProcessExecutor;
import com.facebook.buck.util.FakeProcessExecutor;
import com.facebook.buck.util.ProcessExecutorParams;
import com.facebook.buck.util.Verbosity;
import com.facebook.buck.util.environment.Platform;
import com.google.common.collect.ImmutableList;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Optional;
import org.junit.Rule;
import org.junit.Test;
public class WorkerProcessTest {
@Rule public TemporaryPaths temporaryPaths = new TemporaryPaths();
private ProcessExecutorParams createDummyParams() {
return ProcessExecutorParams.builder().setCommand(ImmutableList.of()).build();
}
@Test
public void testSubmitAndWaitForJob() throws IOException {
ProjectFilesystem filesystem = new FakeProjectFilesystem();
Path tmpPath = Files.createTempDirectory("tmp").toAbsolutePath().normalize();
Path argsPath = Paths.get(tmpPath.toString(), "0.args");
Path stdoutPath = Paths.get(tmpPath.toString(), "0.out");
Path stderrPath = Paths.get(tmpPath.toString(), "0.err");
Path workerStdErr = Paths.get(tmpPath.toString(), "stderr");
String jobArgs = "my job args";
int exitCode = 0;
Optional<String> stdout = Optional.of("my stdout");
Optional<String> stderr = Optional.of("my stderr");
try (DefaultWorkerProcess process =
new DefaultWorkerProcess(
new FakeProcessExecutor(), createDummyParams(), filesystem, workerStdErr, tmpPath)) {
process.setProtocol(
new FakeWorkerProcessProtocol.FakeCommandSender() {
@Override
public int receiveCommandResponse(int messageId) throws IOException {
// simulate the external tool and write the stdout and stderr files
filesystem.writeContentsToPath(
stdout.orElseThrow(IllegalStateException::new), stdoutPath);
filesystem.writeContentsToPath(
stderr.orElseThrow(IllegalStateException::new), stderrPath);
return super.receiveCommandResponse(messageId);
}
});
WorkerJobResult expectedResult = WorkerJobResult.of(exitCode, stdout, stderr);
assertThat(process.submitAndWaitForJob(jobArgs), equalTo(expectedResult));
assertThat(
filesystem.readFileIfItExists(argsPath).orElseThrow(IllegalStateException::new),
equalTo(jobArgs));
}
}
@Test
public void testClose() {
FakeWorkerProcessProtocol.FakeCommandSender protocol =
new FakeWorkerProcessProtocol.FakeCommandSender();
try (DefaultWorkerProcess process =
new DefaultWorkerProcess(
new FakeProcessExecutor(),
createDummyParams(),
new FakeProjectFilesystem(),
Paths.get("stderr"),
Paths.get("tmp").toAbsolutePath().normalize())) {
process.setProtocol(protocol);
assertFalse(protocol.isClosed());
process.close();
assertTrue(protocol.isClosed());
}
}
@Test(timeout = 20 * 1000)
public void testDoesNotBlockOnLargeStderr() throws IOException {
ProjectWorkspace workspace =
TestDataHelper.createProjectWorkspaceForScenario(this, "worker_process", temporaryPaths);
workspace.setUp();
ProjectFilesystem projectFilesystem =
TestProjectFilesystems.createProjectFilesystem(workspace.getDestPath());
Console console = new Console(Verbosity.ALL, System.out, System.err, Ansi.withoutTty());
String script;
if (Platform.detect() == Platform.WINDOWS) {
script = workspace.getDestPath().resolve("script.bat").toString();
} else {
script = "./script.py";
}
try (DefaultWorkerProcess workerProcess =
new DefaultWorkerProcess(
new DefaultProcessExecutor(console),
ProcessExecutorParams.builder()
.setCommand(ImmutableList.of(script))
.setDirectory(workspace.getDestPath())
.build(),
projectFilesystem,
temporaryPaths.newFile("stderr").getPath(),
temporaryPaths.newFolder().getPath())) {
workerProcess.ensureLaunchAndHandshake();
fail("Handshake should have failed");
} catch (HumanReadableException e) {
// Check that all of the process's stderr was reported.
assertThat(e.getMessage().length(), is(greaterThan(1024 * 1024)));
}
}
}
| apache-2.0 |
biezhi/blade | src/main/java/com/blade/validator/ValidationResult.java | 1950 | /**
* Copyright (c) 2018, biezhi 王爵nice (biezhi.me@gmail.com)
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.blade.validator;
import com.blade.exception.ValidatorException;
import com.blade.kit.BladeKit;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.var;
@Data
@AllArgsConstructor
public class ValidationResult {
private boolean valid;
private String message;
private String code;
public static ValidationResult ok() {
return new ValidationResult(true, null, null);
}
public static ValidationResult ok(String code) {
return new ValidationResult(true, null, code);
}
public static ValidationResult fail(String message) {
return new ValidationResult(false, message, null);
}
public static ValidationResult fail(String code, String message) {
return new ValidationResult(false, message, code);
}
public void throwIfInvalid() {
this.throwMessage(getMessage());
}
public void throwIfInvalid(String fieldName) {
if (!isValid()) throw new ValidatorException(fieldName + " " + getMessage());
}
public <T, R> void throwIfInvalid(TypeFunction<T, R> function) {
var fieldName = BladeKit.getLambdaFieldName(function);
throwIfInvalid(fieldName);
}
public void throwMessage(String msg) {
if (!isValid()) throw new ValidatorException(msg);
}
} | apache-2.0 |
sdgdsffdsfff/nedis | nedis-client/src/main/java/com/wandoulabs/nedis/exception/TxnDiscardException.java | 1153 | /**
* Copyright (c) 2015 Wandoujia 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.wandoulabs.nedis.exception;
import java.io.IOException;
/**
* @author Apache9
*/
public class TxnDiscardException extends IOException {
private static final long serialVersionUID = -1088947518802949094L;
public TxnDiscardException() {
super();
}
public TxnDiscardException(String message, Throwable cause) {
super(message, cause);
}
public TxnDiscardException(String message) {
super(message);
}
public TxnDiscardException(Throwable cause) {
super(cause);
}
}
| apache-2.0 |
MironovVadim/vmironov | chapter_004/src/test/java/ru/job4j/testtask/TicTacToeGameTest.java | 8266 | package ru.job4j.testtask;
import org.junit.Test;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.util.Arrays;
import java.util.Scanner;
import java.util.StringJoiner;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
/**
* Test class.
*/
public class TicTacToeGameTest {
/**
* Test start() method.
*/
@Test
public void whenExitTheGameThenGetExitMessage() {
String exit = "exit";
ByteArrayOutputStream baos = new ByteArrayOutputStream();
System.setOut(new PrintStream(baos));
ByteArrayInputStream bais = new ByteArrayInputStream(exit.getBytes());
Scanner scanner = new Scanner(new InputStreamReader(bais));
TicTacToeGame game = new TicTacToeGame(3, 3, scanner);
game.start();
String result = baos.toString();
String expected = String.format("Enter coordinates through a space or 'exit' to stop the game.%1$sExit the game.%1$s", System.lineSeparator());
assertThat(result, is(expected));
}
/**
* Test start() method.
*/
@Test
public void whenStartThenGetMessageWithFirstPlayerWin() {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
System.setOut(new PrintStream(baos));
StringJoiner answers = new StringJoiner(System.lineSeparator());
answers.add("1 0").add("0 0").add("1 1").add("0 2").add("1 2");
ByteArrayInputStream bais = new ByteArrayInputStream(answers.toString().getBytes());
Scanner scanner = new Scanner(new InputStreamReader(bais));
TicTacToeGame game = new TicTacToeGame(3, 3, scanner);
StringBuilder sb = new StringBuilder();
char[][] field = new char[3][3];
for (char[] line : field) {
Arrays.fill(line, ' ');
}
field[1][0] = 'X';
this.appendInSb(sb, field);
field[0][0] = 'O';
this.appendInSb(sb, field);
field[1][1] = 'X';
this.appendInSb(sb, field);
field[0][2] = 'O';
this.appendInSb(sb, field);
field[1][2] = 'X';
this.appendInSb(sb, field);
sb.append(String.format("First player win. (X)%s", System.lineSeparator()));
game.start();
String expected = sb.toString();
String result = baos.toString();
assertThat(result, is(expected));
}
/**
* Test start() method.
*/
@Test
public void whenStartThenGetNumberFormatExceptionMessage() {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
System.setOut(new PrintStream(baos));
StringJoiner answers = new StringJoiner(System.lineSeparator());
answers.add("0 0r").add("exit");
ByteArrayInputStream bais = new ByteArrayInputStream(answers.toString().getBytes());
Scanner scanner = new Scanner(new InputStreamReader(bais));
TicTacToeGame game = new TicTacToeGame(2, 3, scanner);
StringJoiner expectedSJ = new StringJoiner(System.lineSeparator());
String message = "Enter coordinates through a space or 'exit' to stop the game.";
expectedSJ.add(message).add("Wrong data format.").add(message).add("Exit the game.").add("");
game.start();
String expected = expectedSJ.toString();
String result = baos.toString();
assertThat(result, is(expected));
}
/**
* Test start() method.
*/
@Test
public void whenStartThenGetIndexOutOfBoundExceptionMessage() {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
System.setOut(new PrintStream(baos));
StringJoiner answers = new StringJoiner(System.lineSeparator());
answers.add("10 10").add("exit");
ByteArrayInputStream bais = new ByteArrayInputStream(answers.toString().getBytes());
Scanner scanner = new Scanner(new InputStreamReader(bais));
TicTacToeGame game = new TicTacToeGame(2, 3, scanner);
StringJoiner expectedSJ = new StringJoiner(System.lineSeparator());
String message = "Enter coordinates through a space or 'exit' to stop the game.";
expectedSJ.add(message).add("Index Out Of Bounds Exception.").add(message).add("Exit the game.").add("");
game.start();
String expected = expectedSJ.toString();
String result = baos.toString();
assertThat(result, is(expected));
}
/**
* Test start() method.
*/
@Test
public void whenWriteIncorrectDataThenGetMessage() {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
System.setOut(new PrintStream(baos));
StringJoiner answers = new StringJoiner(System.lineSeparator());
answers.add("0 0").add("0 1").add("1 0").add("1 1");
ByteArrayInputStream bais = new ByteArrayInputStream(answers.toString().getBytes());
Scanner scanner = new Scanner(new InputStreamReader(bais));
TicTacToeGame game = new TicTacToeGame(2, 3, scanner);
StringBuilder sb = new StringBuilder();
char[][] field = new char[2][2];
for (char[] line : field) {
Arrays.fill(line, ' ');
}
field[0][0] = 'X';
this.appendInSb(sb, field);
field[0][1] = 'O';
this.appendInSb(sb, field);
field[1][0] = 'X';
this.appendInSb(sb, field);
field[1][1] = 'O';
this.appendInSb(sb, field);
sb.append(String.format("Field is full, no one wins.%s", System.lineSeparator()));
game.start();
String result = baos.toString();
String expected = sb.toString();
assertThat(result, is(expected));
}
/**
* Test start() method.
*/
@Test
public void whenWriteIncorrectDataThenGetGridOccupiedExceptionMessage() {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
System.setOut(new PrintStream(baos));
StringJoiner answers = new StringJoiner(System.lineSeparator());
answers.add("0 0").add("0 0").add("exit");
ByteArrayInputStream bais = new ByteArrayInputStream(answers.toString().getBytes());
Scanner scanner = new Scanner(new InputStreamReader(bais));
TicTacToeGame game = new TicTacToeGame(2, 3, scanner);
StringBuilder sb = new StringBuilder();
char[][] field = new char[2][2];
for (char[] line : field) {
Arrays.fill(line, ' ');
}
field[0][0] = 'X';
this.appendInSb(sb, field);
String message = "Enter coordinates through a space or 'exit' to stop the game.";
sb.append(String.format("%s%s", message, System.lineSeparator()));
sb.append(String.format("Specified grid is occupied.%s", System.lineSeparator()));
sb.append(String.format("%s%s", message, System.lineSeparator()));
sb.append(String.format("Exit the game.%s", System.lineSeparator()));
game.start();
String expected = sb.toString();
String result = baos.toString();
assertThat(result, is(expected));
}
/**
* Helper in test TicTacToeGame class method.
* @param sb - StringBuilder.
* @param field - game field.
*/
private void appendInSb(StringBuilder sb, char[][] field) {
String message = "Enter coordinates through a space or 'exit' to stop the game.";
sb.append(String.format("%s%s", message, System.lineSeparator()));
sb.append("---------------------------------------------");
sb.append(System.lineSeparator());
sb.append(" ");
for (int gridNumber = 0; gridNumber < field.length; gridNumber++) {
sb.append(String.format(" %d ", gridNumber));
}
sb.append(System.lineSeparator());
for (int lineNumber = 0; lineNumber < field.length; lineNumber++) {
sb.append(String.format("%d ", lineNumber));
for (int grid = 0; grid < field.length; grid++) {
sb.append(String.format("[%s]", field[lineNumber][grid]));
}
sb.append(System.lineSeparator());
}
sb.append("---------------------------------------------");
sb.append(System.lineSeparator());
}
} | apache-2.0 |
quarkusio/quarkus | integration-tests/main/src/main/java/io/quarkus/it/jpa/CustomEnum.java | 72 | package io.quarkus.it.jpa;
public enum CustomEnum {
ONE,
TWO
}
| apache-2.0 |
amilaI/RepoExpress | common/src/java/com/strategicgains/repoexpress/adapter/StringToLongIdAdapter.java | 1446 | /*
Copyright 2011-2012, Strategic Gains, 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.strategicgains.repoexpress.adapter;
import com.strategicgains.repoexpress.domain.Identifier;
import com.strategicgains.repoexpress.exception.InvalidObjectIdException;
/**
* Converts between a String ID and an Identifier containing a Long.
*
* @author toddf
* @since Feb 16, 2011
*/
public class StringToLongIdAdapter
implements IdentifierAdapter
{
/**
* throws InvalidObjectIdException if the ID is not a valid long integer.
*/
@Override
public Identifier parse(String id)
{
if (id == null || id.isEmpty()) throw new InvalidObjectIdException("null ID");
try
{
return new Identifier(Long.valueOf(id));
}
catch (NumberFormatException e)
{
throw new InvalidObjectIdException(id, e);
}
}
@Override
public String format(Identifier id)
{
return (id == null ? null : id.primaryKey().toString());
}
}
| apache-2.0 |
DevOps-TangoMe/flume-kinesis | flume-kinesis-source/src/main/java/com/tango/flume/kinesis/source/serializer/Serializer.java | 1220 | /**
* Copyright 2014 TangoMe 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.tango.flume.kinesis.source.serializer;
import org.apache.flume.Event;
import org.apache.flume.conf.Configurable;
import org.apache.flume.conf.ConfigurableComponent;
import com.amazonaws.services.kinesis.model.Record;
import java.nio.charset.CharacterCodingException;
public interface Serializer extends Configurable, ConfigurableComponent{
/**
* Serialize an event for storage in Redis
*
* @param event
* Event to serialize
* @return Serialized data
*/
Event parseEvent(Record record) throws KinesisSerializerException, CharacterCodingException;
}
| apache-2.0 |
zhenshengcai/floodlight-hardware | src/main/java/net/floodlightcontroller/jython/JythonDebugInterface.java | 3412 | /**
* Copyright 2013, Big Switch Networks, 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 net.floodlightcontroller.jython;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import net.floodlightcontroller.core.internal.FloodlightProvider;
import net.floodlightcontroller.core.module.FloodlightModuleContext;
import net.floodlightcontroller.core.module.FloodlightModuleException;
import net.floodlightcontroller.core.module.IFloodlightModule;
import net.floodlightcontroller.core.module.IFloodlightService;
public class JythonDebugInterface implements IFloodlightModule {
protected static Logger log = LoggerFactory.getLogger(JythonDebugInterface.class);
protected JythonServer debug_server;
protected String jythonHost = null;
protected int jythonPort = 6655;
@Override
public Collection<Class<? extends IFloodlightService>> getModuleServices() {
// We don't export services
return null;
}
@Override
public Map<Class<? extends IFloodlightService>, IFloodlightService>
getServiceImpls() {
// We don't export services
return null;
}
@Override
public Collection<Class<? extends IFloodlightService>>
getModuleDependencies() {
// We don't have any dependencies
return null;
}
@Override
public void init(FloodlightModuleContext context)
throws FloodlightModuleException {
// no-op
}
@Override
public void startUp(FloodlightModuleContext context) {
Map<String, Object> locals = new HashMap<String, Object>();
// add all existing module references to the debug server
for (Class<? extends IFloodlightService> s : context.getAllServices()) {
// Put only the last part of the name
String[] bits = s.getCanonicalName().split("\\.");
String name = bits[bits.length-1];
locals.put(name, context.getServiceImpl(s));
}
// read our config options
Map<String, String> configOptions = context.getConfigParams(this);
jythonHost = configOptions.get("host");
if (jythonHost == null) {
Map<String, String> providerConfigOptions = context.getConfigParams(
FloodlightProvider.class);
jythonHost = providerConfigOptions.get("openflowhost");
}
if (jythonHost != null) {
log.debug("Jython host set to {}", jythonHost);
}
String port = configOptions.get("port");
if (port != null) {
jythonPort = Integer.parseInt(port);
}
log.debug("Jython port set to {}", jythonPort);
JythonServer debug_server = new JythonServer(jythonHost, jythonPort, locals);
debug_server.start();
}
}
| apache-2.0 |
mi9rom/VaadHLDemo | src/com/vaadHL/example/jpa/AppMain.java | 1848 | /*
* Copyright 2015 Mirosław Romaniuk (mi9rom@gmail.com)
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.vaadHL.example.jpa;
import java.util.Locale;
import javax.servlet.annotation.WebServlet;
import org.vaadin.googleanalytics.tracking.GoogleAnalyticsTracker;
import com.vaadHL.AppContext;
import com.vaadHL.example.i18n.MyI18;
import com.vaadin.annotations.Theme;
import com.vaadin.annotations.VaadinServletConfiguration;
import com.vaadin.server.VaadinRequest;
import com.vaadin.server.VaadinServlet;
import com.vaadin.ui.UI;
@SuppressWarnings("serial")
@Theme("oratstjpa")
public class AppMain extends UI {
@WebServlet(value = "/*", asyncSupported = true)
@VaadinServletConfiguration(productionMode = false, ui = AppMain.class, widgetset = "com.vaadHL.example.jpa.widgetset.VaadhldemoWidgetset")
public static class Servlet extends VaadinServlet {
}
private static final long serialVersionUID = 1891752310777496322L;
public AppMain() {
// TODO Auto-generated constructor stub
}
@Override
protected void init(VaadinRequest request) {
GoogleAnalyticsTracker tracker = new GoogleAnalyticsTracker(
"UA-71938697-2");
tracker.extend(this);
setLocale(Locale.getDefault());
setContent(new MainW(new AppContext(new MyI18(getLocale()))));
tracker.trackPageview("MainW");
}
}
| apache-2.0 |
codehaus/xbean | xbean-spring/src/main/java/org/apache/xbean/spring/context/impl/ObjectNameEditor.java | 1432 | /**
*
* Copyright 2005-2006 The Apache Software Foundation or its licensors, as applicable.
*
* 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.xbean.spring.context.impl;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import java.beans.PropertyEditorSupport;
/**
* Editor for <code>java.net.URI</code>
*/
public class ObjectNameEditor extends PropertyEditorSupport {
public void setAsText(String text) throws IllegalArgumentException {
try {
setValue(new ObjectName(text));
}
catch (MalformedObjectNameException e) {
throw new IllegalArgumentException("Could not convert ObjectName for " + text + ": " + e.getMessage());
}
}
public String getAsText() {
ObjectName value = (ObjectName) getValue();
return (value != null ? value.toString() : "");
}
}
| apache-2.0 |
ibnc/gocd | server/src/main/java/com/thoughtworks/go/server/newsecurity/filterchains/AuthorizeFilterChain.java | 8595 | /*
* Copyright 2019 ThoughtWorks, 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.thoughtworks.go.server.newsecurity.filterchains;
import com.thoughtworks.go.server.newsecurity.filters.AllowAllAccessFilter;
import com.thoughtworks.go.server.newsecurity.filters.DenyAllAccessFilter;
import com.thoughtworks.go.server.newsecurity.handlers.BasicAuthenticationWithChallengeFailureResponseHandler;
import com.thoughtworks.go.server.newsecurity.handlers.GenericAccessDeniedHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.web.FilterChainProxy;
import org.springframework.stereotype.Component;
import static com.thoughtworks.go.server.security.GoAuthority.*;
@Component("authorizeFilterChain")
public class AuthorizeFilterChain extends FilterChainProxy {
@Autowired
public AuthorizeFilterChain(AllowAllAccessFilter allowAllAccessFilter,
BasicAuthenticationWithChallengeFailureResponseHandler apiAccessDeniedHandler,
GenericAccessDeniedHandler genericAccessDeniedHandler) {
super(FilterChainBuilder.newInstance()
// agent access
.addAuthorityFilterChain("/remoting/remoteBuildRepository", apiAccessDeniedHandler, ROLE_AGENT)
.addAuthorityFilterChain("/remoting/files/**", apiAccessDeniedHandler, ROLE_AGENT)
.addAuthorityFilterChain("/remoting/properties/**", apiAccessDeniedHandler, ROLE_AGENT)
.addFilterChain("/remoting/**", new DenyAllAccessFilter())
// authentication urls, allow everyone
.addFilterChain("/auth/*", allowAllAccessFilter)
.addFilterChain("/plugin/*/login", allowAllAccessFilter)
.addFilterChain("/plugin/*/authenticate", allowAllAccessFilter)
.addFilterChain("/assets/**", allowAllAccessFilter)
// this is under the `/admin` namespace, but is used by the agent to download various jars
.addFilterChain("/admin/agent", allowAllAccessFilter)
.addFilterChain("/admin/agent/token", allowAllAccessFilter)
.addFilterChain("/admin/latest-agent.status", allowAllAccessFilter)
.addFilterChain("/admin/agent-launcher.jar", allowAllAccessFilter)
.addFilterChain("/admin/tfs-impl.jar", allowAllAccessFilter)
.addFilterChain("/admin/agent-plugins.zip", allowAllAccessFilter)
// some publicly available APIs
.addFilterChain("/api/version", allowAllAccessFilter)
.addFilterChain("/api/plugin_images/**", allowAllAccessFilter)
.addFilterChain("/api/v1/health/**", allowAllAccessFilter)
.addFilterChain("/api/webhooks/*/notify/**", allowAllAccessFilter)
// for some kind of admins
.addAuthorityFilterChain("/admin/configuration/file/**", genericAccessDeniedHandler, ROLE_SUPERVISOR)
.addAuthorityFilterChain("/admin/configuration/**", genericAccessDeniedHandler, ROLE_SUPERVISOR, ROLE_GROUP_SUPERVISOR)
.addAuthorityFilterChain("/admin/restful/configuration/**", genericAccessDeniedHandler, ROLE_SUPERVISOR, ROLE_GROUP_SUPERVISOR)
.addAuthorityFilterChain("/admin/pipelines/**", genericAccessDeniedHandler, ROLE_SUPERVISOR, ROLE_GROUP_SUPERVISOR)
.addAuthorityFilterChain("/admin/pipeline_group/**", genericAccessDeniedHandler, ROLE_SUPERVISOR, ROLE_GROUP_SUPERVISOR)
.addAuthorityFilterChain("/admin/templates/**", genericAccessDeniedHandler, ROLE_SUPERVISOR, ROLE_TEMPLATE_SUPERVISOR, ROLE_TEMPLATE_VIEW_USER, ROLE_GROUP_SUPERVISOR)
.addAuthorityFilterChain("/admin/commands/**", genericAccessDeniedHandler, ROLE_SUPERVISOR, ROLE_GROUP_SUPERVISOR, ROLE_TEMPLATE_SUPERVISOR)
.addAuthorityFilterChain("/admin/plugins", genericAccessDeniedHandler, ROLE_SUPERVISOR, ROLE_GROUP_SUPERVISOR)
.addAuthorityFilterChain("/admin/pipeline/**", genericAccessDeniedHandler, ROLE_SUPERVISOR, ROLE_GROUP_SUPERVISOR)
.addAuthorityFilterChain("/admin/materials/**", genericAccessDeniedHandler, ROLE_SUPERVISOR, ROLE_GROUP_SUPERVISOR)
.addAuthorityFilterChain("/admin/package_repositories/**", genericAccessDeniedHandler, ROLE_SUPERVISOR, ROLE_GROUP_SUPERVISOR)
.addAuthorityFilterChain("/admin/package_definitions/**", genericAccessDeniedHandler, ROLE_SUPERVISOR, ROLE_GROUP_SUPERVISOR)
.addAuthorityFilterChain("/admin/elastic_agent_configurations/**", genericAccessDeniedHandler, ROLE_SUPERVISOR, ROLE_GROUP_SUPERVISOR)
//allow /go/admin/environments page to be accessible by normal users
.addAuthorityFilterChain("/admin/environments", genericAccessDeniedHandler, ROLE_USER)
.addAuthorityFilterChain("/admin/config_repos", genericAccessDeniedHandler, ROLE_USER)
.addAuthorityFilterChain("/admin/**", genericAccessDeniedHandler, ROLE_SUPERVISOR)
.addAuthorityFilterChain("/agents/*/job_run_history/**", genericAccessDeniedHandler, ROLE_SUPERVISOR)
// all apis
.addAuthorityFilterChain("/cctray.xml", apiAccessDeniedHandler, ROLE_USER)
.addAuthorityFilterChain("/pipelines.json", apiAccessDeniedHandler, ROLE_USER)
// new controllers, so we say `ROLE_USER`, and let the controller handle authorization
.addAuthorityFilterChain("/api/admin/internal/*", apiAccessDeniedHandler, ROLE_USER)
.addAuthorityFilterChain("/api/admin/pipelines/**", apiAccessDeniedHandler, ROLE_USER)
.addAuthorityFilterChain("/api/admin/pipeline_groups/**", apiAccessDeniedHandler, ROLE_USER)
.addAuthorityFilterChain("/api/admin/export/**", apiAccessDeniedHandler, ROLE_USER)
.addAuthorityFilterChain("/api/admin/encrypt", apiAccessDeniedHandler, ROLE_USER)
.addAuthorityFilterChain("/api/admin/scms/**", apiAccessDeniedHandler, ROLE_USER)
.addAuthorityFilterChain("/api/admin/repositories/**", apiAccessDeniedHandler, ROLE_USER)
.addAuthorityFilterChain("/api/admin/packages/**", apiAccessDeniedHandler, ROLE_USER)
.addAuthorityFilterChain("/api/admin/plugin_info/**", apiAccessDeniedHandler, ROLE_USER)
.addAuthorityFilterChain("/api/admin/templates/**", apiAccessDeniedHandler, ROLE_USER)
.addAuthorityFilterChain("/api/elastic/profiles/**", apiAccessDeniedHandler, ROLE_USER)
.addAuthorityFilterChain("/api/admin/environments/**", apiAccessDeniedHandler, ROLE_USER)
.addAuthorityFilterChain("/api/admin/config_repos/**", apiAccessDeniedHandler, ROLE_USER)
.addAuthorityFilterChain("/api/admin/internal/environments/merged", apiAccessDeniedHandler, ROLE_USER)
.addAuthorityFilterChain("/api/admin/internal/environments/**", apiAccessDeniedHandler, ROLE_USER)
// blanket role that requires supervisor access, used by old admin apis
.addAuthorityFilterChain("/api/admin/**", apiAccessDeniedHandler, ROLE_SUPERVISOR)
.addAuthorityFilterChain("/api/config-repository.git/**", apiAccessDeniedHandler, ROLE_SUPERVISOR)
.addAuthorityFilterChain("/api/jobs/scheduled.xml", apiAccessDeniedHandler, ROLE_SUPERVISOR)
.addAuthorityFilterChain("/api/support", apiAccessDeniedHandler, ROLE_SUPERVISOR)
// any other APIs require `ROLE_USER`
.addAuthorityFilterChain("/api/**", apiAccessDeniedHandler, ROLE_USER)
// addons will be expected to do their own authentication/authorization
.addFilterChain("/add-on/**", allowAllAccessFilter)
.addAuthorityFilterChain("/**", genericAccessDeniedHandler, ROLE_USER)
.build());
}
}
| apache-2.0 |
ibissource/iaf | core/src/test/java/nl/nn/adapterframework/configuration/digester/ConfigurationDigesterTest.java | 6634 | package nl.nn.adapterframework.configuration.digester;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.io.StringWriter;
import java.net.URL;
import java.util.Properties;
import javax.xml.validation.ValidatorHandler;
import org.junit.Test;
import org.xml.sax.ContentHandler;
import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXParseException;
import nl.nn.adapterframework.configuration.Configuration;
import nl.nn.adapterframework.configuration.ConfigurationDigester;
import nl.nn.adapterframework.core.Resource;
import nl.nn.adapterframework.testutil.MatchUtils;
import nl.nn.adapterframework.testutil.TestConfiguration;
import nl.nn.adapterframework.testutil.TestFileUtils;
import nl.nn.adapterframework.util.XmlUtils;
import nl.nn.adapterframework.xml.XmlWriter;
public class ConfigurationDigesterTest {
private static final String FRANK_CONFIG_XSD = "/xml/xsd/FrankConfig-compatibility.xsd";
private static final String STUB4TESTTOOL_CONFIGURATION_KEY = "stub4testtool.configuration";
private static final String STUB4TESTTOOL_VALIDATORS_DISABLED_KEY = "validators.disabled";
@Test
public void testNewCanonicalizer() throws Exception {
XmlWriter writer = new XmlWriter();
ConfigurationDigester digester = new ConfigurationDigester();
ContentHandler handler = digester.getConfigurationCanonicalizer(writer, FRANK_CONFIG_XSD, new XmlErrorHandler());
Resource resource = Resource.getResource("/Digester/SimpleConfiguration/Configuration.xml");
XmlUtils.parseXml(resource, handler);
String result = writer.toString();
String expected = TestFileUtils.getTestFile("/Digester/Canonicalized/SimpleConfiguration.xml");
MatchUtils.assertXmlEquals(expected, result);
}
//Both OLD and NEW configuration parsers should set the same values for 'loadedConfiguration': properties resolved, secrets hidden
//The new configuration parser returns the configuration with all property not yet resolved
@Test
public void testNewConfigurationPreParser() throws Exception {
ConfigurationDigester digester = new ConfigurationDigester();
Resource resource = Resource.getResource("/Digester/SimpleConfiguration/Configuration.xml");
Properties properties = new Properties();
properties.setProperty("HelloWorld.active", "false");
properties.setProperty("HelloBeautifulWorld.active", "!false");
properties.setProperty("digester.property", "[ >\"< ]"); // new style non-escaped property values
properties.setProperty("secret", "GEHEIM");
properties.setProperty("properties.hide", "secret");
Configuration configuration = new TestConfiguration();
XmlWriter loadedConfigWriter = new XmlWriter();
digester.parseAndResolveEntitiesAndProperties(loadedConfigWriter, configuration, resource, properties);
String result = loadedConfigWriter.toString();
String expected = TestFileUtils.getTestFile("/Digester/Loaded/SimpleConfigurationUnresolved.xml");
MatchUtils.assertXmlEquals(expected, result);
String storedResult = configuration.getLoadedConfiguration();
String storedExpected = TestFileUtils.getTestFile("/Digester/Loaded/SimpleConfigurationResolvedAndHidden.xml");
MatchUtils.assertXmlEquals(storedExpected, storedResult);
loadedConfigWriter = new XmlWriter();
properties.setProperty(STUB4TESTTOOL_CONFIGURATION_KEY, "true");
digester.parseAndResolveEntitiesAndProperties(loadedConfigWriter, configuration, resource, properties);
String stubbedExpected = TestFileUtils.getTestFile("/Digester/Loaded/SimpleConfigurationStubbed.xml");
MatchUtils.assertXmlEquals(stubbedExpected, loadedConfigWriter.toString());
}
@Test
public void simpleXsdWithDefaultAndFixedAttributed() throws Exception {
URL schemaURL = TestFileUtils.getTestFileURL("/Digester/resolveDefaultAttribute.xsd");
ValidatorHandler validatorHandler = XmlUtils.getValidatorHandler(schemaURL);
XmlWriter writer = new XmlWriter();
validatorHandler.setContentHandler(writer);
validatorHandler.setErrorHandler(new XmlErrorHandler());
Resource resource = Resource.getResource("/Digester/resolveAttributes.xml");
XmlUtils.parseXml(resource, validatorHandler);
assertEquals("<note one=\"1\" two=\"2\"/>", writer.toString().trim());
}
@Test
public void testFixedValueAttributeResolverWithFrankConfig() throws Exception {
URL schemaURL = TestFileUtils.getTestFileURL(FRANK_CONFIG_XSD);
ValidatorHandler validatorHandler = XmlUtils.getValidatorHandler(schemaURL);
XmlWriter writer = new XmlWriter();
validatorHandler.setContentHandler(writer);
validatorHandler.setErrorHandler(new XmlErrorHandler());
Resource resource = Resource.getResource("/Digester/PreParsedConfiguration.xml");
assertNotNull(resource);
XmlUtils.parseXml(resource, validatorHandler);
String expected = TestFileUtils.getTestFile("/Digester/resolvedPreParsedConfiguration.xml");
assertEquals(expected, writer.toString().trim());
}
@Test
public void stub4testtoolTest() throws Exception {
String baseDirectory = "/ConfigurationUtils/stub4testtool/FullAdapter";
StringWriter target = new StringWriter();
XmlWriter xmlWriter = new XmlWriter(target);
Properties properties = new Properties();
properties.setProperty(STUB4TESTTOOL_CONFIGURATION_KEY, "true");
properties.setProperty(STUB4TESTTOOL_VALIDATORS_DISABLED_KEY, Boolean.toString(false));
String originalConfiguration = TestFileUtils.getTestFile(baseDirectory + "/original.xml");
ConfigurationDigester digester = new ConfigurationDigester();
ContentHandler filter = digester.getStub4TesttoolContentHandler(xmlWriter, properties);
XmlUtils.parseXml(originalConfiguration, filter);
String actual = new String(target.toString());
String expectedConfiguration = TestFileUtils.getTestFile(baseDirectory + "/expected.xml");
MatchUtils.assertXmlEquals(expectedConfiguration, actual);
}
private class XmlErrorHandler implements ErrorHandler {
@Override
public void warning(SAXParseException exception) throws SAXParseException {
System.err.println("Warning at line,column ["+exception.getLineNumber()+","+exception.getColumnNumber()+"]: " + exception.getMessage());
}
@Override
public void error(SAXParseException exception) throws SAXParseException {
System.err.println("Error at line,column ["+exception.getLineNumber()+","+exception.getColumnNumber()+"]: " + exception.getMessage());
}
@Override
public void fatalError(SAXParseException exception) throws SAXParseException {
System.err.println("FatalError at line,column ["+exception.getLineNumber()+","+exception.getColumnNumber()+"]: " + exception.getMessage());
}
}
}
| apache-2.0 |
kwakutwumasi/Quakearts-JSF-Webtools | qa-syshub/src/main/java/com/quakearts/syshub/model/AgentConfiguration.java | 7192 | /*******************************************************************************
* Copyright (C) 2016 Kwaku Twumasi-Afriyie <kwaku.twumasi@quakearts.com>.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Kwaku Twumasi-Afriyie <kwaku.twumasi@quakearts.com> - initial API and implementation
******************************************************************************/
package com.quakearts.syshub.model;
import java.io.Serializable;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Transient;
import javax.persistence.UniqueConstraint;
/**
* @author QuakesHome
*
*/
@Entity
@Table(name = "agent_configuration", uniqueConstraints = @UniqueConstraint(columnNames = {"agentName"}))
public class AgentConfiguration implements Serializable {
/**
*
*/
private static final long serialVersionUID = -7117694041115125087L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@Column(length = 100, nullable = false, unique = true)
private String agentName;
private RunType type = RunType.LOOPED;
private boolean active;
@OneToMany(mappedBy="agentConfiguration", fetch=FetchType.LAZY, cascade={CascadeType.ALL})
private Set<AgentModule> agentModules = new HashSet<>();
@OneToMany(mappedBy="agentConfiguration", fetch=FetchType.LAZY, cascade={CascadeType.ALL})
private Set<AgentConfigurationParameter> parameters = new HashSet<>();
@OneToMany(mappedBy="agentConfiguration", fetch=FetchType.LAZY, cascade={CascadeType.REMOVE})
private Set<ProcessingLog> processingLogs = new HashSet<>();
@OneToMany(mappedBy="agentConfiguration", fetch=FetchType.LAZY, cascade={CascadeType.ALL})
private Set<AgentConfigurationModuleMapping> agentConfigurationModuleMappings = new HashSet<>();
public enum RunType{
SCHEDULED,
LOOPED,
TRIGGERED
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getAgentName() {
return agentName;
}
public void setAgentName(String agentName) {
this.agentName = agentName;
}
public RunType getType() {
return type;
}
public void setType(RunType type) {
this.type = type;
}
public Set<AgentModule> getAgentModules() {
return agentModules;
}
public void setAgentModules(Set<AgentModule> agentModules) {
this.agentModules = agentModules;
}
public Set<AgentConfigurationParameter> getParameters() {
return parameters;
}
public void setParameters(Set<AgentConfigurationParameter> parameters) {
this.parameters = parameters;
}
public boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
public Set<AgentConfigurationModuleMapping> getAgentConfigurationModuleMappings() {
return agentConfigurationModuleMappings;
}
public void setAgentConfigurationModuleMappings(Set<AgentConfigurationModuleMapping> agentConfigurationModuleMappings) {
this.agentConfigurationModuleMappings = agentConfigurationModuleMappings;
}
@Transient
private Map<Integer, Map<String, AgentConfigurationParameter>> moduleConfigurationMaps;
@Transient
private Map<String, AgentConfigurationParameter> agentConfigurationMap;
private void createConfigurationMaps() {
agentConfigurationMap = new HashMap<>();
moduleConfigurationMaps = new HashMap<>();
if(!getParameters().isEmpty()){
loadParameters();
setEntries();
createMaps();
}
}
protected void loadParameters() {
for(AgentConfigurationParameter agentConfigurationParameter: getParameters()) {
if(agentConfigurationParameter.getAgentModule()!=null){
Map<String, AgentConfigurationParameter> agentModuleConfigurationMap =
moduleConfigurationMaps.get(agentConfigurationParameter.getAgentModule().getId());
if(agentModuleConfigurationMap == null){
agentModuleConfigurationMap = new HashMap<>();
moduleConfigurationMaps.put(agentConfigurationParameter.getAgentModule().getId(), agentModuleConfigurationMap);
}
agentModuleConfigurationMap.put(agentConfigurationParameter.getName(), agentConfigurationParameter);
if(agentConfigurationParameter.isGlobal())
agentConfigurationMap.put(agentConfigurationParameter.getName(), agentConfigurationParameter);
} else {
agentConfigurationMap.put(agentConfigurationParameter.getName(), agentConfigurationParameter);
}
}
}
protected void setEntries() {
for(Entry<Integer, Map<String, AgentConfigurationParameter>> entry:moduleConfigurationMaps.entrySet()){
entry.getValue().putAll(agentConfigurationMap);
entry.setValue(Collections.unmodifiableMap(entry.getValue()));
}
}
protected void createMaps() {
for(AgentConfigurationModuleMapping configurationModuleMapping:getAgentConfigurationModuleMappings()) {
moduleConfigurationMaps.put(configurationModuleMapping.getAgentModule().getId()
, configurationModuleMapping.getAgentModule().getModuleConfigurationMap());
}
agentConfigurationMap = Collections.unmodifiableMap(agentConfigurationMap);
moduleConfigurationMaps = Collections.unmodifiableMap(moduleConfigurationMaps);
}
@Transient
public AgentConfigurationParameter getAgentConfigurationParameter(String name) {
return getAgentConfigurationMap().get(name);
}
public Map<String, AgentConfigurationParameter> getAgentConfigurationMap() {
if(agentConfigurationMap==null)
createConfigurationMaps();
return agentConfigurationMap;
}
@Transient
public Map<String, AgentConfigurationParameter> getAgentModuleConfigurationMap(AgentModule agentModule) {
if(moduleConfigurationMaps==null)
createConfigurationMaps();
Map<String, AgentConfigurationParameter> agentModuleConfigurationMap = moduleConfigurationMaps.get(agentModule.getId());
if(agentModuleConfigurationMap!=null) {
return agentModuleConfigurationMap;
} else {
return null;
}
}
@Override
public int hashCode() {
return Objects.hash(agentName);
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
AgentConfiguration other = (AgentConfiguration) obj;
return Objects.equals(agentName, other.agentName);
}
@Override
public String toString() {
return Integer.toHexString(this.hashCode()+id>0?id:0);
}
}
| apache-2.0 |
HewlettPackard/oneview-sdk-java | oneview-sdk-java-lib/src/main/java/com/hp/ov/sdk/dto/networking/saslogicalinterconnectgroup/SasInterconnectMapEntryTemplate.java | 2646 | /*
* (C) Copyright 2016 Hewlett Packard Enterprise Development LP
*
* Licensed under the Apache License, Version 2.0 (the "License");
* You may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hp.ov.sdk.dto.networking.saslogicalinterconnectgroup;
import java.io.Serializable;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
import com.hp.ov.sdk.dto.networking.LogicalLocation;
public class SasInterconnectMapEntryTemplate implements Serializable {
private static final long serialVersionUID = -7235768479340040286L;
private Integer enclosureIndex;
private LogicalLocation logicalLocation;
private String permittedInterconnectTypeUri;
/**
* @return the enclosureIndex
*/
public Integer getEnclosureIndex() {
return enclosureIndex;
}
/**
* @param enclosureIndex the enclosureIndex to set
*/
public void setEnclosureIndex(Integer enclosureIndex) {
this.enclosureIndex = enclosureIndex;
}
/**
* @return the logicalLocation
*/
public LogicalLocation getLogicalLocation() {
return logicalLocation;
}
/**
* @param logicalLocation the logicalLocation to set
*/
public void setLogicalLocation(LogicalLocation logicalLocation) {
this.logicalLocation = logicalLocation;
}
/**
* @return the permittedInterconnectTypeUri
*/
public String getPermittedInterconnectTypeUri() {
return permittedInterconnectTypeUri;
}
/**
* @param permittedInterconnectTypeUri the permittedInterconnectTypeUri to set
*/
public void setPermittedInterconnectTypeUri(String permittedInterconnectTypeUri) {
this.permittedInterconnectTypeUri = permittedInterconnectTypeUri;
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
@Override
public boolean equals(Object obj) {
return EqualsBuilder.reflectionEquals(this, obj);
}
@Override
public int hashCode() {
return HashCodeBuilder.reflectionHashCode(this);
}
}
| apache-2.0 |
GaneshSPatil/gocd | server/src/test-fast/java/com/thoughtworks/go/server/service/ClusterProfilesServiceTest.java | 5046 | /*
* Copyright 2021 ThoughtWorks, 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.thoughtworks.go.server.service;
import com.thoughtworks.go.config.PluginProfiles;
import com.thoughtworks.go.config.elastic.ClusterProfile;
import com.thoughtworks.go.config.elastic.ClusterProfiles;
import com.thoughtworks.go.config.elastic.ElasticConfig;
import com.thoughtworks.go.plugin.access.elastic.ElasticAgentExtension;
import com.thoughtworks.go.server.domain.Username;
import com.thoughtworks.go.server.exceptions.RulesViolationException;
import com.thoughtworks.go.server.service.result.HttpLocalizedOperationResult;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.*;
@ExtendWith(MockitoExtension.class)
public class ClusterProfilesServiceTest {
@Mock
private GoConfigService goConfigService;
@Mock
private EntityHashingService hashingService;
@Mock
private ElasticAgentExtension extension;
@Mock
private SecretParamResolver secretParamResolver;
private ClusterProfilesService clusterProfilesService;
private ClusterProfile clusterProfile;
@BeforeEach
void setUp() {
clusterProfile = new ClusterProfile("prod_cluster", "k8s.ea.plugin");
clusterProfilesService = new ClusterProfilesService(goConfigService, hashingService, extension, secretParamResolver);
}
@Test
void shouldFetchClustersDefinedAsPartOfElasticTag() {
ElasticConfig elasticConfig = new ElasticConfig();
elasticConfig.setClusterProfiles(new ClusterProfiles(clusterProfile));
when(goConfigService.getElasticConfig()).thenReturn(elasticConfig);
PluginProfiles<ClusterProfile> actualClusterProfiles = clusterProfilesService.getPluginProfiles();
assertThat(actualClusterProfiles).isEqualTo(elasticConfig.getClusterProfiles());
}
@Test
void shouldValidateClusterProfileUponClusterProfileCreation() {
clusterProfilesService.create(clusterProfile, new Username("Bob"), new HttpLocalizedOperationResult());
verify(secretParamResolver).resolve(clusterProfile);
verify(extension, times(1)).validateClusterProfile(clusterProfile.getPluginId(), clusterProfile.getConfigurationAsMap(true));
}
@Test
void shouldNotValidateClusterProfileWhenDeletingClusterProfile() {
clusterProfilesService.delete(clusterProfile, new Username("Bob"), new HttpLocalizedOperationResult());
verifyNoInteractions(secretParamResolver);
verify(extension, never()).validateClusterProfile(clusterProfile.getPluginId(), clusterProfile.getConfigurationAsMap(true));
}
@Test
void shouldValidateClusterProfileUponClusterProfileUpdate() {
clusterProfilesService.update(clusterProfile, new Username("Bob"), new HttpLocalizedOperationResult());
verify(secretParamResolver).resolve(clusterProfile);
verify(extension, times(1)).validateClusterProfile(clusterProfile.getPluginId(), clusterProfile.getConfigurationAsMap(true));
}
@Test
void shouldSendResolvedValueToThePluginWhileValidation() {
clusterProfile.addNewConfigurationWithValue("key", "{{SECRET:[config_id][key]}}", false);
clusterProfile.getSecretParams().get(0).setValue("some-resolved-value");
clusterProfilesService.update(clusterProfile, new Username("Bob"), new HttpLocalizedOperationResult());
verify(secretParamResolver).resolve(clusterProfile);
verify(extension, times(1)).validateClusterProfile(clusterProfile.getPluginId(), clusterProfile.getConfigurationAsMap(true, true));
}
@Test
void shouldSetResultAsUnprocessableEntityWhenRulesAreViolated() {
clusterProfile.addNewConfigurationWithValue("key", "{{SECRET:[config_id][key]}}", false);
doThrow(new RulesViolationException("some rules violation message")).when(secretParamResolver).resolve(clusterProfile);
HttpLocalizedOperationResult result = new HttpLocalizedOperationResult();
clusterProfilesService.update(clusterProfile, new Username("Bob"), result);
assertThat(result.httpCode()).isEqualTo(422);
assertThat(result.message()).isEqualTo("Validations failed for clusterProfile 'prod_cluster'. Error(s): [some rules violation message]. Please correct and resubmit.");
}
}
| apache-2.0 |
shevek/tftp4j | tftp-protocol/src/main/java/org/anarres/tftp/protocol/resource/TftpByteArrayData.java | 968 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.anarres.tftp.protocol.resource;
import com.google.common.base.Preconditions;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.io.IOException;
import java.nio.ByteBuffer;
import javax.annotation.Nonnull;
/**
*
* @author shevek
*/
public class TftpByteArrayData extends AbstractTftpData {
private final byte[] data;
@SuppressFBWarnings("EI_EXPOSE_REP2")
public TftpByteArrayData(@Nonnull byte[] data) {
this.data = data;
}
@Override
public int getSize() {
return data.length;
}
@Override
public int read(ByteBuffer out, int offset) throws IOException {
Preconditions.checkPositionIndex(offset, getSize(), "Illegal data offset.");
int length = Math.min(getSize() - offset, out.remaining());
out.put(data, offset, length);
return length;
}
} | apache-2.0 |
aws/aws-sdk-java | aws-java-sdk-lookoutforvision/src/main/java/com/amazonaws/services/lookoutforvision/model/StartModelPackagingJobResult.java | 4682 | /*
* 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.lookoutforvision.model;
import java.io.Serializable;
import javax.annotation.Generated;
/**
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/lookoutvision-2020-11-20/StartModelPackagingJob"
* target="_top">AWS API Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class StartModelPackagingJobResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable {
/**
* <p>
* The job name for the model packaging job. If you don't supply a job name in the <code>JobName</code> input
* parameter, the service creates a job name for you.
* </p>
*/
private String jobName;
/**
* <p>
* The job name for the model packaging job. If you don't supply a job name in the <code>JobName</code> input
* parameter, the service creates a job name for you.
* </p>
*
* @param jobName
* The job name for the model packaging job. If you don't supply a job name in the <code>JobName</code> input
* parameter, the service creates a job name for you.
*/
public void setJobName(String jobName) {
this.jobName = jobName;
}
/**
* <p>
* The job name for the model packaging job. If you don't supply a job name in the <code>JobName</code> input
* parameter, the service creates a job name for you.
* </p>
*
* @return The job name for the model packaging job. If you don't supply a job name in the <code>JobName</code>
* input parameter, the service creates a job name for you.
*/
public String getJobName() {
return this.jobName;
}
/**
* <p>
* The job name for the model packaging job. If you don't supply a job name in the <code>JobName</code> input
* parameter, the service creates a job name for you.
* </p>
*
* @param jobName
* The job name for the model packaging job. If you don't supply a job name in the <code>JobName</code> input
* parameter, the service creates a job name for you.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public StartModelPackagingJobResult withJobName(String jobName) {
setJobName(jobName);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getJobName() != null)
sb.append("JobName: ").append(getJobName());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof StartModelPackagingJobResult == false)
return false;
StartModelPackagingJobResult other = (StartModelPackagingJobResult) obj;
if (other.getJobName() == null ^ this.getJobName() == null)
return false;
if (other.getJobName() != null && other.getJobName().equals(this.getJobName()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getJobName() == null) ? 0 : getJobName().hashCode());
return hashCode;
}
@Override
public StartModelPackagingJobResult clone() {
try {
return (StartModelPackagingJobResult) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
}
| apache-2.0 |
brandt/GridSphere | src/org/gridsphere/provider/portletui/tags/RenderLinkTag.java | 6146 | package org.gridsphere.provider.portletui.tags;
import org.gridsphere.portlet.impl.SportletProperties;
import org.gridsphere.provider.portletui.beans.ImageBean;
import org.gridsphere.provider.portletui.beans.MessageStyle;
import org.gridsphere.provider.portletui.beans.RenderLinkBean;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.Tag;
/**
* The <code>ActionLinkTag</code> provides a hyperlink element that includes a <code>DefaultPortletAction</code>
* and can contain nested <code>ActionParamTag</code>s
*/
public class RenderLinkTag extends ActionTag {
protected RenderLinkBean renderlink = null;
protected String style = MessageStyle.MSG_INFO;
protected ImageBean imageBean = null;
/**
* Sets the style of the text: Available styles are
* <ul>
* <li>nostyle</li>
* <li>error</li>
* <li>info</li>
* <li>status</li>
* <li>alert</li>
* <li>success</li>
*
* @param style the text style
*/
public void setStyle(String style) {
this.style = style;
}
/**
* Returns the style of the text: Available styles are
* <ul>
* <li>nostyle</li>
* <li>error</li>
* <li>info</li>
* <li>status</li>
* <li>alert</li>
* <li>success</li>
*
* @return the text style
*/
public String getStyle() {
return style;
}
/**
* Sets the image bean
*
* @param imageBean the image bean
*/
public void setImageBean(ImageBean imageBean) {
this.imageBean = imageBean;
}
/**
* Returns the image bean
*
* @return the image bean
*/
public ImageBean getImageBean() {
return imageBean;
}
public int doStartTag() throws JspException {
if (!beanId.equals("")) {
renderlink = (RenderLinkBean) getTagBean();
if (renderlink == null) {
renderlink = new RenderLinkBean(beanId);
renderlink.setStyle(style);
this.setBaseComponentBean(renderlink);
} else {
if (renderlink.getParamBeanList() != null) {
paramBeans = renderlink.getParamBeanList();
}
if (renderlink.getAction() != null) {
action = renderlink.getAction();
}
if (renderlink.getValue() != null) {
value = renderlink.getValue();
}
if (renderlink.getKey() != null) {
key = renderlink.getKey();
}
if (renderlink.getOnClick() != null) {
onClick = renderlink.getOnClick();
}
}
} else {
renderlink = new RenderLinkBean();
this.setBaseComponentBean(renderlink);
renderlink.setStyle(style);
}
renderlink.setUseAjax(useAjax);
if (name != null) renderlink.setName(name);
if (anchor != null) renderlink.setAnchor(anchor);
if (action != null) renderlink.setAction(action);
if (value != null) renderlink.setValue(value);
if (onClick != null) renderlink.setOnClick(onClick);
if (style != null) renderlink.setStyle(style);
if (cssStyle != null) renderlink.setCssStyle(cssStyle);
if (cssClass != null) renderlink.setCssClass(cssClass);
if (layout != null) renderlink.setLayout(label);
if (onMouseOut != null) renderlink.setOnMouseOut(onMouseOut);
if (onMouseOver != null) renderlink.setOnMouseOver(onMouseOver);
Tag parent = getParent();
if (parent instanceof ActionMenuTag) {
ActionMenuTag actionMenuTag = (ActionMenuTag) parent;
if (!actionMenuTag.getLayout().equals("horizontal")) {
renderlink.setCssStyle("display: block");
}
}
if (key != null) {
renderlink.setKey(key);
renderlink.setValue(getLocalizedText(key));
value = renderlink.getValue();
}
return EVAL_BODY_BUFFERED;
}
public int doEndTag() throws JspException {
if (!beanId.equals("")) {
paramBeans = renderlink.getParamBeanList();
label = renderlink.getLabel();
action = renderlink.getAction();
}
renderlink.setPortletURI(createRenderURI());
if ((bodyContent != null) && (value == null)) {
renderlink.setValue(bodyContent.getString());
}
if (pageContext.getRequest().getAttribute(SportletProperties.USE_AJAX) != null) {
String paction = ((!action.equals("")) ? "&" + portletPhase.toString() : "");
String portlet = (String) pageContext.getRequest().getAttribute(SportletProperties.PORTLET_NAME);
String compname = (String) pageContext.getRequest().getAttribute(SportletProperties.COMPONENT_NAME);
renderlink.setUseAjax(true);
renderlink.setOnClick("GridSphereAjaxHandler2.startRequest('" + portlet + "', '" + compname + "', '" + paction + "');");
}
if (useAjax) {
String cid = (String) pageContext.getRequest().getAttribute(SportletProperties.COMPONENT_ID);
String paction = ((!action.equals("")) ? "&" + portletPhase.toString() : "");
renderlink.setOnClick("GridSphereAjaxHandler.startRequest(" + cid + ", '" + paction + "');");
}
if (imageBean != null) {
String val = renderlink.getValue();
if (val == null) val = "";
renderlink.setValue(imageBean.toStartString() + val);
}
if (var == null) {
try {
JspWriter out = pageContext.getOut();
out.print(renderlink.toEndString());
} catch (Exception e) {
throw new JspException(e);
}
} else {
pageContext.setAttribute(var, renderlink.toEndString(), PageContext.PAGE_SCOPE);
}
release();
return EVAL_PAGE;
}
}
| apache-2.0 |
nhl/link-move | link-move/src/main/java/com/nhl/link/move/mapper/PathMapper.java | 2375 | package com.nhl.link.move.mapper;
import com.nhl.dflib.row.RowProxy;
import com.nhl.link.move.LmRuntimeException;
import org.apache.cayenne.DataObject;
import org.apache.cayenne.exp.Expression;
import org.apache.cayenne.exp.ExpressionFactory;
public class PathMapper implements Mapper {
private final String dbPath;
// created lazily and cached... parsing expressions is expensive
private Expression pathExpression;
private Expression keyValueExpression;
public PathMapper(String dbPath) {
this.dbPath = dbPath;
}
private Expression getOrCreatePathExpression() {
if (pathExpression == null) {
// as we expect both Db and Obj paths here, let's pass the path
// through the parser to generate the correct expression template...
this.pathExpression = ExpressionFactory.exp(dbPath);
}
return pathExpression;
}
private Expression getOrCreateKeyValueExpression() {
if (keyValueExpression == null) {
// as we expect both Db and Obj paths here, let's pass the path
// through the parser to generate the correct expression template...
this.keyValueExpression = ExpressionFactory.exp(dbPath + " = $v");
}
return keyValueExpression;
}
@Override
public Expression expressionForKey(Object key) {
return getOrCreateKeyValueExpression().paramsArray(key);
}
@Override
public Object keyForSource(RowProxy source) {
// if source does not contain a key, we must fail, otherwise multiple
// rows will be incorrectly matched against NULL key
try {
return source.get(dbPath);
}
catch (IllegalArgumentException e) {
throw new LmRuntimeException("Source does not contain key path: " + dbPath);
}
}
@Override
public Object keyForTarget(DataObject target) {
// cases:
// 1. "obj:" expressions are object properties
// 2. "db:" expressions mapping to ID columns
// 3. "db:" expressions mapping to object properties
// Cayenne exp can handle 1 & 2; we'll need to manually handle case 3
return getOrCreatePathExpression().evaluate(target);
}
@Override
public String toString() {
return getClass().getSimpleName() + "__" + dbPath;
}
}
| apache-2.0 |
zapbot/zaproxy | src/org/zaproxy/zap/extension/proxies/DialogAddProxy.java | 4085 | /*
* Zed Attack Proxy (ZAP) and its related class files.
*
* ZAP is an HTTP/HTTPS proxy for assessing web application security.
*
* Copyright 2017 The ZAP Development Team
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.zaproxy.zap.extension.proxies;
import java.awt.Dialog;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import org.parosproxy.paros.Constant;
import org.zaproxy.zap.view.AbstractFormDialog;
class DialogAddProxy extends AbstractFormDialog {
private static final long serialVersionUID = 4460797449668634319L;
private static final String DIALOG_TITLE = Constant.messages.getString("options.proxy.dialog.proxy.add.title");
private static final String CONFIRM_BUTTON_LABEL = Constant.messages
.getString("options.proxy.dialog.proxy.add.button.confirm");
protected OptionsLocalProxyPanel proxyPanel;
protected ProxiesParamProxy proxy;
private ExtensionProxies extension;
public DialogAddProxy(Dialog owner, ExtensionProxies extension) {
super(owner, DIALOG_TITLE);
this.extension = extension;
setConfirmButtonEnabled(true);
}
protected DialogAddProxy(Dialog owner, String title, ExtensionProxies extension) {
super(owner, title);
this.extension = extension;
}
@Override
protected JPanel getFieldsPanel() {
if (proxyPanel == null) {
proxyPanel = new OptionsLocalProxyPanel();
}
return proxyPanel;
}
@Override
protected String getConfirmButtonLabel() {
return CONFIRM_BUTTON_LABEL;
}
@Override
protected void init() {
proxy = null;
this.getFieldsPanel(); // to initialise proxyPanel
ProxiesParamProxy paramProxy = new ProxiesParamProxy(true);
proxyPanel.setProxy(paramProxy);
}
@Override
protected boolean validateFields() {
ProxiesParamProxy testProxy = proxyPanel.getProxy();
if (extension.getAdditionalProxy(testProxy.getAddress(), testProxy.getPort()) != null) {
JOptionPane.showMessageDialog(
this,
Constant.messages.getString("options.proxy.dialog.proxy.warning.dup.message"),
Constant.messages.getString("options.proxy.dialog.proxy.warning.dup.title"),
JOptionPane.ERROR_MESSAGE);
return false;
}
if (this.proxy == null
|| !(this.proxy.getAddress().equals(testProxy.getAddress()) && this.proxy.getPort() == testProxy.getPort())) {
// We're adding a proxy or changing the addr:port, so check that we can listen on this combination
if (!extension.canListenOn(testProxy.getAddress(), testProxy.getPort())) {
JOptionPane.showMessageDialog(
this,
Constant.messages.getString("options.proxy.dialog.proxy.warning.fail.message",
testProxy.getAddress(), Integer.toString(testProxy.getPort())),
Constant.messages.getString("options.proxy.dialog.proxy.warning.fail.title"),
JOptionPane.ERROR_MESSAGE);
return false;
}
}
return true;
}
@Override
protected void performAction() {
proxy = proxyPanel.getProxy();
}
@Override
protected void clearFields() {
}
public ProxiesParamProxy getProxy() {
return proxy;
}
public void clear() {
this.proxy = null;
}
}
| apache-2.0 |
echsylon/kraken | library/src/test/java/com/echsylon/kraken/request/OrderBookTest.java | 2819 | package com.echsylon.kraken.request;
import com.echsylon.atlantis.Atlantis;
import com.echsylon.kraken.Dictionary;
import com.echsylon.kraken.dto.Depth;
import org.junit.After;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import static com.echsylon.kraken.TestHelper.getKrakenInstance;
import static com.echsylon.kraken.TestHelper.startMockServer;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
/**
* These test cases will test the "order book (market depth)" feature of the
* Android Kraken SDK.
* <p>
* The tests will take advantage of the fact that the Kraken implementation
* returns a {@code Request} object. Since the {@code Request}
* class extends {@code FutureTask} we can block the test thread until a result
* is produced.
*/
@RunWith(RobolectricTestRunner.class)
@Config(manifest = Config.NONE, sdk = 25)
public class OrderBookTest {
private Atlantis atlantis;
@After
public void after() {
atlantis.stop();
atlantis = null;
}
@Test
public void requestingDepth_shouldReturnMapOfParsedDepthObject() throws Exception {
atlantis = startMockServer("GET", "/0/public/Depth",
"{'error': [], 'result': {" +
" 'XETHZEUR': {" +
" 'asks': [" +
" ['271.13309','2.368',1503523308]," +
" ['271.13317','0.300',1503521093]]," +
" 'bids': [" +
" ['271.07985','2.750',1503523300]," +
" ['271.00001','1.157',1503523300]]}}}");
Dictionary<Depth> result = getKrakenInstance()
.getOrderBook(null)
.enqueue()
.get(10, SECONDS);
assertThat(result.size(), is(1));
Depth depth = result.get("XETHZEUR");
assertThat(depth.asks.length, is(2));
assertThat(depth.asks[0].price, is("271.13309"));
assertThat(depth.asks[0].volume, is("2.368"));
assertThat(depth.asks[0].timestamp, is(1503523308L));
assertThat(depth.asks[1].price, is("271.13317"));
assertThat(depth.asks[1].volume, is("0.300"));
assertThat(depth.asks[1].timestamp, is(1503521093L));
assertThat(depth.bids.length, is(2));
assertThat(depth.bids[0].price, is("271.07985"));
assertThat(depth.bids[0].volume, is("2.750"));
assertThat(depth.bids[0].timestamp, is(1503523300L));
assertThat(depth.bids[1].price, is("271.00001"));
assertThat(depth.bids[1].volume, is("1.157"));
assertThat(depth.bids[1].timestamp, is(1503523300L));
}
}
| apache-2.0 |
ghonix/Problems | src/main/java/me/ghonix/practice/MedianTwoSortedArrays.java | 1827 | package me.ghonix.practice;
/**
* https://leetcode.com/problems/median-of-two-sorted-arrays/#/description
* Created by aghoneim on 4/18/17.
*/
public class MedianTwoSortedArrays {
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
if (nums1 == null) {
nums1 = new int[]{};
}
if (nums2 == null) {
nums2 = new int[]{};
}
int size = nums1.length + nums2.length;
if (size > 0) {
int firstMedian = 0 , secondMedian = 0;
int i = 0, j = 0, medianIndex = 0;
int middle = (size - 1)/ 2;
while (i < nums1.length || j < nums2.length) {
int current = 0;
if (i >= nums1.length) {
current = nums2[j];
j++;
} else if (j >= nums2.length) {
current = nums1[i];
i++;
} else if (nums1[i] < nums2[j]) {
current = nums1[i];
i++;
} else {
current = nums2[j];
j++;
}
if (medianIndex == middle) {
firstMedian = current;
} else if (medianIndex == middle + 1) {
secondMedian = current;
} else if(medianIndex > middle) {
break;
}
medianIndex++;
}
return size % 2 == 0 ? (firstMedian + secondMedian) / 2.0 : firstMedian;
} else {
return 0;
}
}
public static void main(String [] args) {
MedianTwoSortedArrays m = new MedianTwoSortedArrays();
System.out.println(m.findMedianSortedArrays(new int[]{0, 2, 3, 3}, new int[]{ 4, 5}));
}
}
| apache-2.0 |
gleb619/zana | app/src/main/java/org/test/boris/testapp/data/api/domain/response/CurrCourseServerResponseSingle.java | 786 | package org.test.boris.testapp.data.api.domain.response;
import org.test.boris.testapp.data.api.domain.entity.CurrCourse;
import org.test.boris.testapp.data.api.domain.response.core.ResponseSingle;
import org.test.boris.testapp.data.api.domain.response.core.ServerResponse;
import org.test.boris.testapp.data.api.domain.response.core.SimpleServerResponse;
/**
* Created by BORIS on 30.07.2015.
*/
public class CurrCourseServerResponseSingle extends SimpleServerResponse implements ResponseSingle<CurrCourse> {
private static final long serialVersionUID = 6710594620428582401L;
private CurrCourse data;
@Override
public CurrCourse getData() {
return data;
}
@Override
public void setData(CurrCourse data) {
this.data = data;
}
}
| apache-2.0 |
googleads/google-ads-java | google-ads-stubs-v9/src/main/java/com/google/ads/googleads/v9/errors/CampaignCriterionErrorProto.java | 3784 | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/ads/googleads/v9/errors/campaign_criterion_error.proto
package com.google.ads.googleads.v9.errors;
public final class CampaignCriterionErrorProto {
private CampaignCriterionErrorProto() {}
public static void registerAllExtensions(
com.google.protobuf.ExtensionRegistryLite registry) {
}
public static void registerAllExtensions(
com.google.protobuf.ExtensionRegistry registry) {
registerAllExtensions(
(com.google.protobuf.ExtensionRegistryLite) registry);
}
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_ads_googleads_v9_errors_CampaignCriterionErrorEnum_descriptor;
static final
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_ads_googleads_v9_errors_CampaignCriterionErrorEnum_fieldAccessorTable;
public static com.google.protobuf.Descriptors.FileDescriptor
getDescriptor() {
return descriptor;
}
private static com.google.protobuf.Descriptors.FileDescriptor
descriptor;
static {
java.lang.String[] descriptorData = {
"\n=google/ads/googleads/v9/errors/campaig" +
"n_criterion_error.proto\022\036google.ads.goog" +
"leads.v9.errors\032\034google/api/annotations." +
"proto\"\237\006\n\032CampaignCriterionErrorEnum\"\200\006\n" +
"\026CampaignCriterionError\022\017\n\013UNSPECIFIED\020\000" +
"\022\013\n\007UNKNOWN\020\001\022\032\n\026CONCRETE_TYPE_REQUIRED\020" +
"\002\022\031\n\025INVALID_PLACEMENT_URL\020\003\022 \n\034CANNOT_E" +
"XCLUDE_CRITERIA_TYPE\020\004\022\'\n#CANNOT_SET_STA" +
"TUS_FOR_CRITERIA_TYPE\020\005\022+\n\'CANNOT_SET_ST" +
"ATUS_FOR_EXCLUDED_CRITERIA\020\006\022\035\n\031CANNOT_T" +
"ARGET_AND_EXCLUDE\020\007\022\027\n\023TOO_MANY_OPERATIO" +
"NS\020\010\022-\n)OPERATOR_NOT_SUPPORTED_FOR_CRITE" +
"RION_TYPE\020\t\022C\n?SHOPPING_CAMPAIGN_SALES_C" +
"OUNTRY_NOT_SUPPORTED_FOR_SALES_CHANNEL\020\n" +
"\022\035\n\031CANNOT_ADD_EXISTING_FIELD\020\013\022$\n CANNO" +
"T_UPDATE_NEGATIVE_CRITERION\020\014\0228\n4CANNOT_" +
"SET_NEGATIVE_KEYWORD_THEME_CONSTANT_CRIT" +
"ERION\020\r\022\"\n\036INVALID_KEYWORD_THEME_CONSTAN" +
"T\020\016\022=\n9MISSING_KEYWORD_THEME_CONSTANT_OR" +
"_FREE_FORM_KEYWORD_THEME\020\017\022I\nECANNOT_TAR" +
"GET_BOTH_PROXIMITY_AND_LOCATION_CRITERIA" +
"_FOR_SMART_CAMPAIGN\020\020\022@\n<CANNOT_TARGET_M" +
"ULTIPLE_PROXIMITY_CRITERIA_FOR_SMART_CAM" +
"PAIGN\020\021B\366\001\n\"com.google.ads.googleads.v9." +
"errorsB\033CampaignCriterionErrorProtoP\001ZDg" +
"oogle.golang.org/genproto/googleapis/ads" +
"/googleads/v9/errors;errors\242\002\003GAA\252\002\036Goog" +
"le.Ads.GoogleAds.V9.Errors\312\002\036Google\\Ads\\" +
"GoogleAds\\V9\\Errors\352\002\"Google::Ads::Googl" +
"eAds::V9::Errorsb\006proto3"
};
descriptor = com.google.protobuf.Descriptors.FileDescriptor
.internalBuildGeneratedFileFrom(descriptorData,
new com.google.protobuf.Descriptors.FileDescriptor[] {
com.google.api.AnnotationsProto.getDescriptor(),
});
internal_static_google_ads_googleads_v9_errors_CampaignCriterionErrorEnum_descriptor =
getDescriptor().getMessageTypes().get(0);
internal_static_google_ads_googleads_v9_errors_CampaignCriterionErrorEnum_fieldAccessorTable = new
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_ads_googleads_v9_errors_CampaignCriterionErrorEnum_descriptor,
new java.lang.String[] { });
com.google.api.AnnotationsProto.getDescriptor();
}
// @@protoc_insertion_point(outer_class_scope)
}
| apache-2.0 |
vschs007/buck | src/com/facebook/buck/intellij/ideabuck/src/com/facebook/buck/intellij/ideabuck/actions/ChooseTargetAction.java | 4625 | /*
* Copyright 2015-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.intellij.ideabuck.actions;
import com.facebook.buck.intellij.ideabuck.actions.choosetargets.ChooseTargetItem;
import com.facebook.buck.intellij.ideabuck.actions.choosetargets.ChooseTargetModel;
import com.facebook.buck.intellij.ideabuck.config.BuckSettingsProvider;
import com.facebook.buck.intellij.ideabuck.icons.BuckIcons;
import com.facebook.buck.intellij.ideabuck.ui.BuckToolWindowFactory;
import com.intellij.ide.actions.GotoActionBase;
import com.intellij.ide.util.gotoByName.ChooseByNamePopup;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.actionSystem.Presentation;
import com.intellij.openapi.keymap.KeymapUtil;
import com.intellij.openapi.project.DumbAware;
import com.intellij.openapi.project.DumbService;
import com.intellij.openapi.project.Project;
import java.awt.event.KeyEvent;
import java.awt.event.KeyAdapter;
import javax.swing.KeyStroke;
/**
* Pop up a GUI for choose buck targets (alias).
*/
public class ChooseTargetAction extends GotoActionBase implements DumbAware {
public static final String ACTION_TITLE = "Choose build target";
public static final String ACTION_DESCRIPTION = "Choose Buck build target or alias";
public ChooseTargetAction() {
Presentation presentation = this.getTemplatePresentation();
presentation.setText(ACTION_TITLE);
presentation.setDescription(ACTION_DESCRIPTION);
presentation.setIcon(BuckIcons.ACTION_FIND);
}
@Override
public void update(AnActionEvent e) {
e.getPresentation().setEnabled(!(e.getProject() == null || DumbService.isDumb(e.getProject())));
}
@Override
protected void gotoActionPerformed(AnActionEvent e) {
final Project project = e.getData(CommonDataKeys.PROJECT);
if (project == null) {
return;
}
final ChooseTargetModel model = new ChooseTargetModel(project);
GotoActionCallback<String> callback = new GotoActionCallback<String>() {
@Override
public void elementChosen(ChooseByNamePopup chooseByNamePopup, Object element) {
if (element == null) {
return;
}
BuckSettingsProvider buckSettingsProvider = BuckSettingsProvider.getInstance();
if (buckSettingsProvider == null || buckSettingsProvider.getState() == null) {
return;
}
ChooseTargetItem item = (ChooseTargetItem) element;
// if the target selected isn't an alias, then it has to have : or end with /...
if (item.getName().contains("//") && !item.getName().contains(":") &&
!item.getName().endsWith("/...")) {
return;
}
if (buckSettingsProvider.getState().lastAlias != null) {
buckSettingsProvider.getState().lastAlias.put(
project.getBasePath(), item.getBuildTarget());
}
BuckToolWindowFactory.updateBuckToolWindowTitle(project);
}
};
showNavigationPopup(e, model, callback, "Choose Build Target", true, false);
// Add navigation listener for auto complete
final ChooseByNamePopup chooseByNamePopup = project.getUserData(
ChooseByNamePopup.CHOOSE_BY_NAME_POPUP_IN_PROJECT_KEY);
chooseByNamePopup.getTextField().addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
if (KeyEvent.VK_RIGHT == e.getKeyCode()) {
ChooseTargetItem obj = (ChooseTargetItem) chooseByNamePopup.getChosenElement();
if (obj != null) {
chooseByNamePopup.getTextField().setText(obj.getName());
chooseByNamePopup.getTextField().repaint();
}
} else {
super.keyPressed(e);
}
String adText = chooseByNamePopup.getAdText();
if (adText != null) {
chooseByNamePopup.setAdText(adText + " and " +
KeymapUtil.getKeystrokeText(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 2)) +
" to use autocomplete");
}
}
});
}
}
| apache-2.0 |
rocketraman/basicmon | src/main/java/org/basicmon/BasicMonManager.java | 7191 | package org.basicmon;
import org.basicmon.atomic.BasicCounterAtomicImpl;
import org.basicmon.atomic.BasicTimerAtomicImpl;
import org.basicmon.sync.BasicCounterSyncImpl;
import org.basicmon.sync.BasicTimerSyncImpl;
import java.util.SortedMap;
import java.util.TreeMap;
/**
* A manager for BasicTimer and BasicCounterAtomicImpl instances. BasicTimer is used to provide some (basic) timing information during
* testing and debugging. BasicCounterAtomicImpl provides count information, with associated stats.
*/
public final class BasicMonManager {
private static final BasicMonManager manager = new BasicMonManager();
private final SortedMap<String,BasicTimer> timers = new TreeMap<String, BasicTimer>();
private final SortedMap<String,BasicCounter> counters = new TreeMap<String, BasicCounter>();
public static BasicTimer getTimer(String id) {
return manager.doGetSyncTimer(id, false);
}
public static BasicTimer getTimerWithStats(String id) {
return manager.doGetSyncTimer(id, true);
}
public static BasicTimer getTimer(String id, boolean withStats) {
return manager.doGetSyncTimer(id, withStats);
}
public static BasicTimer getSyncTimer(String id) {
return manager.doGetSyncTimer(id, false);
}
public static BasicTimer getSyncTimerWithStats(String id) {
return manager.doGetSyncTimer(id, true);
}
public static BasicTimer getSyncTimer(String id, boolean withStats) {
return manager.doGetSyncTimer(id, withStats);
}
public static BasicTimer getAtomicTimer(String id) {
return manager.doGetAtomicTimer(id, false);
}
public static BasicTimer getAtomicTimerWithStats(String id) {
return manager.doGetAtomicTimer(id, true);
}
public static BasicTimer getAtomicTimer(String id, boolean withStats) {
return manager.doGetAtomicTimer(id, withStats);
}
public static BasicCounter getCounter(String id) {
return manager.doGetSyncCounter(id, false);
}
public static BasicCounter getCounterWithStats(String id) {
return manager.doGetSyncCounter(id, true);
}
public static BasicCounter getCounter(String id, boolean withStats) {
return manager.doGetSyncCounter(id, withStats);
}
public static BasicCounter getSyncCounter(String id) {
return manager.doGetSyncCounter(id, false);
}
public static BasicCounter getSyncCounterWithStats(String id) {
return manager.doGetSyncCounter(id, true);
}
public static BasicCounter getSyncCounter(String id, boolean withStats) {
return manager.doGetSyncCounter(id, withStats);
}
public static BasicCounter getAtomicCounter(String id) {
return manager.doGetAtomicCounter(id, false);
}
public static BasicCounter getAtomicCounterWithStats(String id) {
return manager.doGetAtomicCounter(id, true);
}
public static BasicCounter getAtomicCounter(String id, boolean withStats) {
return manager.doGetAtomicCounter(id, withStats);
}
public static String prettyPrint() {
return manager.doPrettyPrint();
}
public static void reset() {
manager.doReset();
}
/**
* Get a BasicTimer implemented using atomic classes. Creates it if it does not exist. Note that if the
* same ID already exists with a different implementation or with different stats setting, the earlier timer
* will be returned.
* @param id The id of the timer to assign or get.
* @param withStats Whether to record stats or not. If true, the timer will be much slower.
* @return The BasicTimer.
*/
private BasicTimer doGetAtomicTimer(String id, boolean withStats) {
synchronized (timers) {
BasicTimer timer = timers.get(id);
if(timer == null) {
timer = new BasicTimerAtomicImpl(id, withStats);
timers.put(id, timer);
}
return timer;
}
}
/**
* Get a BasicTimer implemented using synchronization. Creates it if it does not exist. Note that if the
* same ID already exists with a different implementation or with different stats setting, the earlier timer
* will be returned.
* @param id The id of the timer to assign or get.
* @param withStats Whether to record stats or not. If true, the timer will be much slower.
* @return The BasicTimer.
*/
private BasicTimer doGetSyncTimer(String id, boolean withStats) {
synchronized (timers) {
BasicTimer timer = timers.get(id);
if(timer == null) {
timer = new BasicTimerSyncImpl(id, withStats);
timers.put(id, timer);
}
return timer;
}
}
/**
* Get a BasicCounter implemented using atomic classes. Creates it if it does not exist. Note that if the
* same ID already exists with a different implementation or with different stats setting, the earlier counter
* will be returned.
* @param id The id of the counter to assign or get.
* @param withStats Whether to record stats or not. If true, the counter will be much slower.
* @return The BasicCounter.
*/
private BasicCounter doGetAtomicCounter(String id, boolean withStats) {
synchronized (counters) {
BasicCounter counter = counters.get(id);
if(counter == null) {
counter = new BasicCounterAtomicImpl(id, withStats);
counters.put(id, counter);
}
return counter;
}
}
/**
* Get a BasicCounter implemented using synchronization. Creates it if it does not exist. Note that if the
* same ID already exists with a different implementation or with different stats setting, the earlier counter
* will be returned.
* @param id The id of the counter to assign or get.
* @param withStats Whether to record stats or not. If true, the counter will be much slower.
* @return The BasicCounter.
*/
private BasicCounter doGetSyncCounter(String id, boolean withStats) {
synchronized (counters) {
BasicCounter counter = counters.get(id);
if(counter == null) {
counter = new BasicCounterSyncImpl(id, withStats);
counters.put(id, counter);
}
return counter;
}
}
private String doPrettyPrint() {
StringBuilder s = new StringBuilder(1024);
s.append("BasicTimers:\n");
synchronized (timers) {
for(Object timer : timers.values()) {
s.append("\t").append(timer.toString()).append("\n");
}
}
s.append("\nBasicCounters:\n");
synchronized (counters) {
for(Object counter : counters.values()) {
s.append("\t").append(counter.toString()).append("\n");
}
}
return s.toString();
}
private synchronized void doReset() {
timers.clear();
counters.clear();
}
}
| apache-2.0 |
liucijus/jinsist | report/src/test/java/jinsist/report/FormattedReportTest.java | 2532 | package jinsist.report;
import org.junit.Assert;
import org.junit.Test;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class FormattedReportTest {
@Test
public void formatsExpectationReport() {
ReportEvent expected = anEvent("expected invocation");
ReportEvent actual = anEvent("actual invocation");
List<ReportEvent> history = aHistory("event 1", "event 2", "event 3");
List<ReportEvent> unmetHistory = aHistory("event 4", "event 5", "event 6");
FormattedReport report = new FormattedReport(
expected,
actual,
history,
unmetHistory
);
String expectedReport = "" +
"Expected: expected invocation\n" +
"Actual: actual invocation\n" +
"What happened before:\n" +
" event 1\n" +
" event 2\n" +
" event 3\n" +
"Unmet Expectations:\n" +
" event 4\n" +
" event 5\n" +
" event 6\n";
Assert.assertEquals(expectedReport, report.format());
}
@Test
public void formatsEmptyHistoryAsNothing() {
ReportEvent expected = anEvent("expected invocation");
ReportEvent actual = anEvent("actual invocation");
List<ReportEvent> emptyHistory = aHistory();
List<ReportEvent> emptyUnmetHistory = aHistory();
FormattedReport report = new FormattedReport(
expected,
actual,
emptyHistory,
emptyUnmetHistory
);
String expectedReport = "" +
"Expected: expected invocation\n" +
"Actual: actual invocation\n" +
"What happened before:\n" +
" Nothing!\n" +
"Unmet Expectations:\n" +
" Nothing!\n";
Assert.assertEquals(expectedReport, report.format());
}
class TestReportEvent implements ReportEvent {
private String text;
TestReportEvent(String text) {
this.text = text;
}
@Override
public String toString() {
return text;
}
}
private ReportEvent anEvent(String text) {
return new TestReportEvent(text);
}
private List<ReportEvent> aHistory(String... events) {
return Arrays.stream(events).map(TestReportEvent::new).collect(Collectors.toList());
}
}
| apache-2.0 |
stacksync/sync-service | src/test/java/com/stacksync/syncservice/test/xmlrpc/ApiGetMetadata.java | 1225 | package com.stacksync.syncservice.test.xmlrpc;
import java.net.URL;
import org.apache.xmlrpc.client.XmlRpcClient;
import org.apache.xmlrpc.client.XmlRpcClientConfigImpl;
public class ApiGetMetadata {
public static void main(String[] args) throws Exception {
XmlRpcClientConfigImpl config = new XmlRpcClientConfigImpl();
config.setEnabledForExtensions(true);
config.setServerURL(new URL("http://127.0.0.1:" + Constants.XMLRPC_PORT));
XmlRpcClient client = new XmlRpcClient();
client.setConfig(config);
String strUserId = "159a1286-33df-4453-bf80-cff4af0d97b0";
String strItemId = "100";
String strIncludeList = "true";
String strIncludeDeleted = "true";
String strIncludeChunks = "true";
String strVersion = "null";
Object[] params = new Object[] { strUserId, strItemId, strIncludeList, strIncludeDeleted, strIncludeChunks, strVersion};
long startTotal = System.currentTimeMillis();
String strResponse = (String) client.execute("XmlRpcSyncHandler.getMetadata", params);
System.out.println("Response --> " + Constants.PrettyPrintJson(strResponse));
long totalTime = System.currentTimeMillis() - startTotal;
System.out.println("Total level time --> " + totalTime + " ms");
}
}
| apache-2.0 |
WilliamGoossen/epsos-common-components.gnomonportal | webapps/ROOT/WEB-INF/src/com/ext/portlet/epsos/demo/EDDetail.java | 5151 | package com.ext.portlet.epsos.demo;
public class EDDetail {
public String relativePrescriptionLineId;
public String dispensedQuantity;
public String dispensedQuantityUnit;
public String medicineBarcode;
public String medicineTainiaGnisiotitas;
public String medicineEofCode;
public String medicineCommercialName;
public String medicinePackageFormCode;
public String medicinePackageFormCodeDescription;
public String medicineFormCode;
public String medicineFormCodeDescription;
public String medicineCapacityQuantity;
public String medicineDrastikiATCCode;
public String medicineDrastikiName;
public String patientInstructions;
public String medicinePrice;
public String medicineRefPrice;
public String patientParticipation;
public String tameioParticipation;
public String patientDifference;
public String medicineExecutionCase;
public String getRelativePrescriptionLineId() {
return relativePrescriptionLineId;
}
public void setRelativePrescriptionLineId(String relativePrescriptionLineId) {
this.relativePrescriptionLineId = relativePrescriptionLineId;
}
public String getDispensedQuantity() {
return dispensedQuantity;
}
public void setDispensedQuantity(String dispensedQuantity) {
this.dispensedQuantity = dispensedQuantity;
}
public String getMedicineBarcode() {
return medicineBarcode;
}
public void setMedicineBarcode(String medicineBarcode) {
this.medicineBarcode = medicineBarcode;
}
public String getMedicineEofCode() {
return medicineEofCode;
}
public void setMedicineEofCode(String medicineEofCode) {
this.medicineEofCode = medicineEofCode;
}
public String getMedicineCommercialName() {
return medicineCommercialName;
}
public void setMedicineCommercialName(String medicineCommercialName) {
this.medicineCommercialName = medicineCommercialName;
}
public String getMedicineFormCode() {
return medicineFormCode;
}
public void setMedicineFormCode(String medicineFormCode) {
this.medicineFormCode = medicineFormCode;
}
public String getMedicineFormCodeDescription() {
return medicineFormCodeDescription;
}
public void setMedicineFormCodeDescription(String medicineFormCodeDescription) {
this.medicineFormCodeDescription = medicineFormCodeDescription;
}
public String getMedicineCapacityQuantity() {
return medicineCapacityQuantity;
}
public void setMedicineCapacityQuantity(String medicineCapacityQuantity) {
this.medicineCapacityQuantity = medicineCapacityQuantity;
}
public String getMedicineDrastikiATCCode() {
return medicineDrastikiATCCode;
}
public void setMedicineDrastikiATCCode(String medicineDrastikiATCCode) {
this.medicineDrastikiATCCode = medicineDrastikiATCCode;
}
public String getMedicineDrastikiName() {
return medicineDrastikiName;
}
public void setMedicineDrastikiName(String medicineDrastikiName) {
this.medicineDrastikiName = medicineDrastikiName;
}
public String getPatientInstructions() {
return patientInstructions;
}
public void setPatientInstructions(String patientInstructions) {
this.patientInstructions = patientInstructions;
}
public String getMedicinePrice() {
return medicinePrice;
}
public void setMedicinePrice(String medicinePrice) {
this.medicinePrice = medicinePrice;
}
public String getMedicineRefPrice() {
return medicineRefPrice;
}
public void setMedicineRefPrice(String medicineRefPrice) {
this.medicineRefPrice = medicineRefPrice;
}
public String getPatientParticipation() {
return patientParticipation;
}
public void setPatientParticipation(String patientParticipation) {
this.patientParticipation = patientParticipation;
}
public String getTameioParticipation() {
return tameioParticipation;
}
public void setTameioParticipation(String tameioParticipation) {
this.tameioParticipation = tameioParticipation;
}
public String getPatientDifference() {
return patientDifference;
}
public void setPatientDifference(String patientDifference) {
this.patientDifference = patientDifference;
}
public String getMedicineExecutionCase() {
return medicineExecutionCase;
}
public void setMedicineExecutionCase(String medicineExecutionCase) {
this.medicineExecutionCase = medicineExecutionCase;
}
public String getMedicineTainiaGnisiotitas() {
return medicineTainiaGnisiotitas;
}
public void setMedicineTainiaGnisiotitas(String medicineTainiaGnisiotitas) {
this.medicineTainiaGnisiotitas = medicineTainiaGnisiotitas;
}
public String getDispensedQuantityUnit() {
return dispensedQuantityUnit;
}
public void setDispensedQuantityUnit(String dispensedQuantityUnit) {
this.dispensedQuantityUnit = dispensedQuantityUnit;
}
public String getMedicinePackageFormCode() {
return medicinePackageFormCode;
}
public void setMedicinePackageFormCode(String medicinePackageFormCode) {
this.medicinePackageFormCode = medicinePackageFormCode;
}
public String getMedicinePackageFormCodeDescription() {
return medicinePackageFormCodeDescription;
}
public void setMedicinePackageFormCodeDescription(
String medicinePackageFormCodeDescription) {
this.medicinePackageFormCodeDescription = medicinePackageFormCodeDescription;
}
}
| apache-2.0 |
shakamunyi/drill | contrib/storage-hive/core/src/main/java/org/apache/drill/exec/store/hive/HiveScanBatchCreator.java | 4381 | /**
* 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.drill.exec.store.hive;
import java.lang.reflect.Constructor;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.drill.common.exceptions.ExecutionSetupException;
import org.apache.drill.exec.ops.FragmentContext;
import org.apache.drill.exec.physical.impl.BatchCreator;
import org.apache.drill.exec.physical.impl.ScanBatch;
import org.apache.drill.exec.record.RecordBatch;
import org.apache.drill.exec.store.RecordReader;
import org.apache.drill.exec.util.ImpersonationUtil;
import org.apache.hadoop.hive.conf.HiveConf;
import org.apache.hadoop.hive.ql.io.RCFileInputFormat;
import org.apache.hadoop.hive.ql.io.avro.AvroContainerInputFormat;
import org.apache.hadoop.hive.ql.io.orc.OrcInputFormat;
import org.apache.hadoop.hive.ql.io.parquet.MapredParquetInputFormat;
import org.apache.hadoop.mapred.InputSplit;
import com.google.common.collect.Lists;
import org.apache.hadoop.mapred.TextInputFormat;
import org.apache.hadoop.security.UserGroupInformation;
@SuppressWarnings("unused")
public class HiveScanBatchCreator implements BatchCreator<HiveSubScan> {
/**
* Use different classes for different Hive native formats:
* ORC, AVRO, RCFFile, Text and Parquet.
* If input format is none of them falls to default reader.
*/
static Map<String, Class> readerMap = new HashMap<>();
static {
readerMap.put(OrcInputFormat.class.getCanonicalName(), HiveOrcReader.class);
readerMap.put(AvroContainerInputFormat.class.getCanonicalName(), HiveAvroReader.class);
readerMap.put(RCFileInputFormat.class.getCanonicalName(), HiveRCFileReader.class);
readerMap.put(MapredParquetInputFormat.class.getCanonicalName(), HiveParquetReader.class);
readerMap.put(TextInputFormat.class.getCanonicalName(), HiveTextReader.class);
}
@Override
public ScanBatch getBatch(FragmentContext context, HiveSubScan config, List<RecordBatch> children)
throws ExecutionSetupException {
List<RecordReader> readers = Lists.newArrayList();
HiveTableWithColumnCache table = config.getTable();
List<InputSplit> splits = config.getInputSplits();
List<HivePartition> partitions = config.getPartitions();
boolean hasPartitions = (partitions != null && partitions.size() > 0);
int i = 0;
final UserGroupInformation proxyUgi = ImpersonationUtil.createProxyUgi(config.getUserName(),
context.getQueryUserName());
final HiveConf hiveConf = config.getHiveConf();
final String formatName = table.getSd().getInputFormat();
Class<? extends HiveAbstractReader> readerClass = HiveDefaultReader.class;
if (readerMap.containsKey(formatName)) {
readerClass = readerMap.get(formatName);
}
Constructor<? extends HiveAbstractReader> readerConstructor = null;
try {
readerConstructor = readerClass.getConstructor(HiveTableWithColumnCache.class, HivePartition.class,
InputSplit.class, List.class, FragmentContext.class, HiveConf.class,
UserGroupInformation.class);
for (InputSplit split : splits) {
readers.add(readerConstructor.newInstance(table,
(hasPartitions ? partitions.get(i++) : null), split, config.getColumns(), context, hiveConf, proxyUgi));
}
if (readers.size() == 0) {
readers.add(readerConstructor.newInstance(
table, null, null, config.getColumns(), context, hiveConf, proxyUgi));
}
} catch(Exception e) {
logger.error("No constructor for {}, thrown {}", readerClass.getName(), e);
}
return new ScanBatch(config, context, readers);
}
}
| apache-2.0 |
gcristian/minka | server/src/main/java/io/tilt/minka/model/Duty.java | 2186 | /*
* 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 io.tilt.minka.model;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* An abstract entity that the host application uses to represent anything able to balance and distribute.
* the user MUST guarantee to TAKE and RELEASE responsibilities when the user's {@link PartitionDelegate}
* receives events: EntityEvent.ATTACH or EntityEvent.DETTACH respectively.
* Wrapped to keep generics matters isolated
*
* Conditions:
* 1) implement hashCode() and equals() for consistency with your {@linkplain PartitionDelegate}
* 2) If you handle storage: you must avoid collissions
*
* @author Cristian Gonzalez
* @since Dec 3, 2015
*
* @param <T> the payload type
*/
@JsonAutoDetect
public interface Duty extends Entity {
/**
* @return a representation in the same measure unit than the delegate's pallet capacity
* Required to maintain a fairly load balancing */
@JsonProperty("weight")
double getWeight();
/** @return the pallet id to which this duty must be grouped into. */
@JsonProperty("palletId")
String getPalletId();
/** @return not mandatory only for Client usage */
@JsonIgnore
Pallet getPallet();
static DutyBuilder builder(final String id, final String palletId) {
return DutyBuilder.builder(id, palletId);
}
} | apache-2.0 |
fadeoutsoftware/acronetwork | AcronetworkServer/AcronetworkBusinessData/src/it/fadeout/acronetwork/business/DataChart.java | 3165 | package it.fadeout.acronetwork.business;
import java.util.ArrayList;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class DataChart {
/**
* Chart Title
*/
String title;
/**
* Chart SubTitle
*/
String subTitle;
/**
* Tooltip suffix
*/
String tooltipValueSuffix;
/**
* Additional vertical axes
*/
ArrayList<ChartAxis> verticalAxes = new ArrayList<>();
/**
* Dataseries
*/
ArrayList<DataSerie> dataSeries = new ArrayList<>();
/**
* Horizontal Lines
*/
ArrayList<ChartLine> horizontalLines = new ArrayList<>();
/**
* Other Chart links
*/
ArrayList<String> otherChart = new ArrayList<>();
/**
* Main Axes Min Value
*/
Double axisYMinValue;
/**
* Main Axes Max Value
*/
Double axisYMaxValue;
/**
* Main Axes Tick interval
*/
Double axisYTickInterval;
/**
* Main Axes Title
*/
String axisYTitle;
/**
* Flag to know if main Axis is opposite
*/
boolean axisIsOpposite = false;
public Double getAxisYMinValue() {
return axisYMinValue;
}
public void setAxisYMinValue(Double axisYMinValue) {
this.axisYMinValue = axisYMinValue;
}
public Double getAxisYMaxValue() {
return axisYMaxValue;
}
public void setAxisYMaxValue(Double axisYMaxValue) {
this.axisYMaxValue = axisYMaxValue;
}
public Double getAxisYTickInterval() {
return axisYTickInterval;
}
public void setAxisYTickInterval(Double axisYTickInterval) {
this.axisYTickInterval = axisYTickInterval;
}
public String getAxisYTitle() {
return axisYTitle;
}
public void setAxisYTitle(String axisYTitle) {
this.axisYTitle = axisYTitle;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getSubTitle() {
return subTitle;
}
public void setSubTitle(String subTitle) {
this.subTitle = subTitle;
}
public ArrayList<DataSerie> getDataSeries() {
return dataSeries;
}
public void setDataSeries(ArrayList<DataSerie> dataSeries) {
this.dataSeries = dataSeries;
}
public String getTooltipValueSuffix() {
return tooltipValueSuffix;
}
public void setTooltipValueSuffix(String tooltipValueSuffix) {
this.tooltipValueSuffix = tooltipValueSuffix;
}
public ArrayList<ChartLine> getHorizontalLines() {
return horizontalLines;
}
public void setHorizontalLines(ArrayList<ChartLine> horizontalLines) {
this.horizontalLines = horizontalLines;
}
public ArrayList<String> getOtherChart() {
return otherChart;
}
public void setOtherChart(ArrayList<String> otherChart) {
this.otherChart = otherChart;
}
public ArrayList<ChartAxis> getVerticalAxes() {
return verticalAxes;
}
public void setVerticalAxes(ArrayList<ChartAxis> verticalAxes) {
this.verticalAxes = verticalAxes;
}
public boolean isAxisIsOpposite() {
return axisIsOpposite;
}
public void setAxisIsOpposite(boolean axisIsOpposite) {
this.axisIsOpposite = axisIsOpposite;
}
}
| apache-2.0 |
lkumarjain/jain-I18n | src/main/java/com/jain/addon/i18N/handlers/I18NMenuBarHandler.java | 2943 | /*
* Copyright 2012 Lokesh Jain.
*
* 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.jain.addon.i18N.handlers;
import java.io.Serializable;
import java.util.Collection;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map.Entry;
import com.jain.addon.StringHelper;
import com.vaadin.ui.Component;
import com.vaadin.ui.MenuBar;
import com.vaadin.ui.MenuBar.MenuItem;
/**
* <code>I18NMenuBarHandler<code> is a i18N values handler for {@link MenuBar}
* @author Lokesh Jain
* @since December 6, 2012
* @version 1.1.0
*/
@SuppressWarnings("serial")
public class I18NMenuBarHandler extends I18NAbstractComponentHandler implements Serializable {
private final HashMap<MenuItem, String> i18NItemCaptions;
private final HashMap<MenuItem, String> i18NItemDescriptions;
public I18NMenuBarHandler(final MenuBar component) {
super(component);
this.i18NItemCaptions = new HashMap <MenuItem, String>();
this.i18NItemDescriptions = new HashMap<MenuItem, String>();
populateI18NItemCaptions (component);
}
private void populateI18NItemCaptions(final MenuBar component) {
Collection<MenuItem> items = (Collection<MenuItem>) component.getItems();
processMenuItem(items);
}
private void processMenuItem(Collection<MenuItem> items) {
if (items != null) {
for (MenuItem itemId : items) {
String i18NItemCaption = itemId.getText();
i18NItemCaptions.put(itemId, i18NItemCaption);
String i18NItemDescription = itemId.getDescription();
i18NItemDescriptions.put(itemId, i18NItemDescription);
processMenuItem(itemId.getChildren());
}
}
}
public void applyI18N(Component component, Locale locale) {
super.applyI18N(component, locale);
for (Entry<MenuItem, String> entry : i18NItemCaptions.entrySet()) {
if (StringHelper.isNotEmptyWithTrim(entry.getValue())) {
String value = provider.getTitle(locale, entry.getValue());
entry.getKey().setText(value);
}
}
for (Entry<MenuItem, String> entry : i18NItemDescriptions.entrySet()) {
if (StringHelper.isNotEmptyWithTrim(entry.getValue())) {
String value = provider.getTitle(locale, entry.getValue());
entry.getKey().setDescription(value);
}
}
}
public String getI18NCaption(Serializable serializable) {
String i18NItemCaption = i18NItemCaptions.get(serializable);
if (StringHelper.isNotEmptyWithTrim(i18NItemCaption))
return i18NItemCaption;
return getI18NCaption ();
}
}
| apache-2.0 |
clafonta/canyon | src/service/org/tll/canyon/service/UserSecurityAdvice.java | 6545 | package org.tll.canyon.service;
import java.lang.reflect.Method;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import org.acegisecurity.AccessDeniedException;
import org.acegisecurity.Authentication;
import org.acegisecurity.AuthenticationTrustResolver;
import org.acegisecurity.AuthenticationTrustResolverImpl;
import org.acegisecurity.GrantedAuthority;
import org.acegisecurity.context.SecurityContext;
import org.acegisecurity.context.SecurityContextHolder;
import org.acegisecurity.providers.UsernamePasswordAuthenticationToken;
import org.acegisecurity.providers.dao.UserCache;
import org.acegisecurity.userdetails.UserDetails;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.aop.AfterReturningAdvice;
import org.springframework.aop.MethodBeforeAdvice;
import org.tll.canyon.Constants;
import org.tll.canyon.model.Role;
import org.tll.canyon.model.User;
public class UserSecurityAdvice implements MethodBeforeAdvice, AfterReturningAdvice {
public final static String ACCESS_DENIED = "Access Denied: Only administrators are allowed to modify other users.";
protected final Log log = LogFactory.getLog(UserSecurityAdvice.class);
private UserCache userCache;
public void setUserCache(UserCache userCache) {
this.userCache = userCache;
}
/**
* Method to enforce security and only allow administrators to modify users. Regular
* users are allowed to modify themselves.
*/
public void before(Method method, Object[] args, Object target) throws Throwable {
SecurityContext ctx = SecurityContextHolder.getContext();
if (ctx.getAuthentication() != null) {
Authentication auth = ctx.getAuthentication();
boolean administrator = false;
GrantedAuthority[] roles = auth.getAuthorities();
for (int i=0; i < roles.length; i++) {
if (roles[i].getAuthority().equals(Constants.ADMIN_ROLE)) {
administrator = true;
break;
}
}
User user = (User) args[0];
String username = user.getUsername();
String currentUser;
if (auth.getPrincipal() instanceof UserDetails) {
currentUser = ((UserDetails) auth.getPrincipal()).getUsername();
} else {
currentUser = String.valueOf(auth.getPrincipal());
}
if (username != null && !username.equals(currentUser)) {
AuthenticationTrustResolver resolver = new AuthenticationTrustResolverImpl();
// allow new users to signup - this is OK b/c Signup doesn't allow setting of roles
boolean signupUser = resolver.isAnonymous(auth);
if (!signupUser) {
if (log.isDebugEnabled()) {
log.debug("Verifying that '" + currentUser + "' can modify '" + username + "'");
}
if (!administrator) {
log.warn("Access Denied: '" + currentUser + "' tried to modify '" + username + "'!");
throw new AccessDeniedException(ACCESS_DENIED);
}
} else {
if (log.isDebugEnabled()) {
log.debug("Registering new user '" + username + "'");
}
}
}
// fix for http://issues.appfuse.org/browse/APF-96
// don't allow users with "user" role to upgrade to "admin" role
else if (username != null && username.equalsIgnoreCase(currentUser) && !administrator) {
// get the list of roles the user is trying add
Set userRoles = new HashSet();
if (user.getRoles() != null) {
for (Iterator it = user.getRoles().iterator(); it.hasNext();) {
Role role = (Role) it.next();
userRoles.add(role.getName());
}
}
// get the list of roles the user currently has
Set authorizedRoles = new HashSet();
for (int i=0; i < roles.length; i++) {
authorizedRoles.add(roles[i].getAuthority());
}
// if they don't match - access denied
// users aren't allowed to change their roles
if (!CollectionUtils.isEqualCollection(userRoles, authorizedRoles)) {
log.warn("Access Denied: '" + currentUser + "' tried to change their role(s)!");
throw new AccessDeniedException(ACCESS_DENIED);
}
}
}
}
public void afterReturning(Object returnValue, Method method, Object[] args, Object target)
throws Throwable {
User user = (User) args[0];
if (userCache != null && user.getVersion() != null) {
if (log.isDebugEnabled()) {
log.debug("Removing '" + user.getUsername() + "' from userCache");
}
userCache.removeUserFromCache(user.getUsername());
// reset the authentication object if current user
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (auth != null && auth.getPrincipal() instanceof UserDetails) {
User currentUser = (User) auth.getPrincipal();
if (currentUser.getId().equals(user.getId())) {
if (!currentUser.getUsername().equalsIgnoreCase(user.getUsername())) {
// The name of the current user changed, so the previous flush won't have done anything.
// Flush the old name, too.
if (log.isDebugEnabled()) {
log.debug("Removing '" + currentUser.getUsername() + "' from userCache");
}
userCache.removeUserFromCache(currentUser.getUsername());
}
auth = new UsernamePasswordAuthenticationToken(user, user.getPassword(), user.getAuthorities());
SecurityContextHolder.getContext().setAuthentication(auth);
}
}
}
}
}
| apache-2.0 |
authlete/authlete-java-sample-server | src/main/java/com/authlete/sample/server/web/controller/ClientExtractor.java | 27140 | /*
* Copyright 2014 Authlete, 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.authlete.sample.server.web.controller;
import java.net.URI;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.ws.rs.core.MultivaluedMap;
import com.authlete.common.dto.Client;
import com.authlete.common.dto.TaggedValue;
import com.authlete.common.types.ApplicationType;
import com.authlete.common.types.ClientAuthMethod;
import com.authlete.common.types.ClientType;
import com.authlete.common.types.GrantType;
import com.authlete.common.types.JWEAlg;
import com.authlete.common.types.JWEEnc;
import com.authlete.common.types.JWSAlg;
import com.authlete.common.types.ResponseType;
import com.authlete.common.types.SubjectType;
import com.authlete.sample.server.util.ApiException;
import com.authlete.sample.server.util.RequestValidator;
/**
* This class has two roles.
* One is getting the input values to create a client
* from the information that are given in the client create page.
* The other one validating the values.<br>
*
* Note that the validation part here is just one example,
* which shows simply how to extract the input parameters.<br>
*
* In future, the functions that this class performs might be improved
* especially in terms of the validation part
* and will be provided as part of authlete-common library
* so that you can create clients in more effortlessly.
*/
public class ClientExtractor
{
/**
* The parameter names.
*/
private static final String APPLICATION_TYPE = "application_type";
private static final String CLIENT_ID = "client_id";
private static final String CLIENT_NAME = "client_name";
private static final String CLIENT_NAMES_TAGS = "client_names_tags";
private static final String CLIENT_NAMES_VALUES = "client_names_values";
private static final String CLIENT_TYPE = "client_type";
private static final String CLIENT_URI = "client_uri";
private static final String CLIENT_URIS_TAGS = "client_uris_tags";
private static final String CLIENT_URIS_VALUES = "client_uris_values";
private static final String CONTACTS = "contacts";
private static final String DEFAULT_ACRS = "default_acrs";
private static final String DEFAULT_MAX_AGE = "default_max_age";
private static final String DESCRIPTION = "description";
private static final String DESCRIPTIONS_TAGS = "descriptions_tags";
private static final String DESCRIPTIONS_VALUES = "descriptions_values";
private static final String DEVELOPER = "developer";
private static final String GRANT_TYPES = "grant_types";
private static final String ID_TOKEN_ENCRYPTION_ALG = "id_token_encryption_alg";
private static final String ID_TOKEN_ENCRYPTION_ENC = "id_token_encryption_enc";
private static final String ID_TOKEN_SIGN_ALG = "id_token_sign_alg";
private static final String JWKS = "jwks";
private static final String JWKS_URI = "jwks_uri";
private static final String LOGIN_URI = "login_uri";
private static final String LOGO_URI = "logo_uri";
private static final String LOGO_URIS_TAGS = "logo_uris_tags";
private static final String LOGO_URIS_VALUES = "logo_uris_values";
private static final String POLICY_URI = "policy_uri";
private static final String POLICY_URIS_TAGS = "policy_uris_tags";
private static final String POLICY_URIS_VALUES = "policy_uris_values";
private static final String REDIRECT_URIS = "redirect_uris";
private static final String REQUEST_ENCRYPTION_ALG = "request_encryption_alg";
private static final String REQUEST_ENCRYPTION_ENC = "request_encryption_enc";
private static final String REQUEST_SIGN_ALG = "request_sign_alg";
private static final String REQUEST_URIS = "request_uris";
private static final String RESPONSE_TYPES = "response_types";
private static final String SECTOR_IDENTIFIER = "sector_identifier";
private static final String SUBJECT_TYPE = "subject_type";
private static final String TOKEN_AUTH_METHOD = "token_auth_method";
private static final String TOKEN_AUTH_SIGN_ALG = "token_auth_sign_alg";
private static final String TOS_URI = "tos_uri";
private static final String TOS_URIS_TAGS = "tos_uris_tags";
private static final String TOS_URIS_VALUES = "tos_uris_values";
private static final String USER_INFO_ENCRYPTION_ALG = "user_info_encryption_alg";
private static final String USER_INFO_ENCRYPTION_ENC = "user_info_encryption_enc";
private static final String USER_INFO_SIGN_ALG = "user_info_sign_alg";
/**
* The parameter max length.
*/
private static final int CLIENT_NAME_MAX_LENGTH = 100;
private static final int CLIENT_URI_MAX_LENGTH = 200;
private static final int CONTACT_MAX_LENGTH = 100;
private static final int ACR_MAX_LENGTH = 200;
private static final int DESCRIPTION_MAX_LENGTH = 200;
private static final int DEVELOPER_MAX_LENGTH = 100;
private static final int JWKS_URI_MAX_LENGTH = 200;
private static final int LOGIN_URI_MAX_LENGTH = 200;
private static final int LOGO_URI_MAX_LENGTH = 200;
private static final int POLICY_URI_MAX_LENGTH = 200;
private static final int REDIRECT_URI_MAX_LENGTH = 200;
private static final int REQUEST_URI_MAX_LENGTH = 200;
private static final int SECTOR_IDENTIFIER_MAX_LENGTH = 200;
private static final int TOS_URI_MAX_LENGTH = 200;
private static final int TAGGED_VALUES_TAG_MAX_LENGTH = 30;
private static final int TAGGED_VALUES_VALUE_MAX_LENGTH = 200;
private ClientExtractor()
{
}
public static Client extract(MultivaluedMap<String, String> map)
{
return buildClient(map);
}
public static Client extractIdentifiable(MultivaluedMap<String, String> map)
{
return buildClient(map).setClientId(extractClientId(map));
}
private static Client buildClient(MultivaluedMap<String, String> map)
{
return new Client()
.setApplicationType(extractApplicationType(map))
.setClientName(extractClientName(map))
.setClientNames(extractClientNames(map))
.setClientType(extractClientType(map))
.setClientUri(extractClientUri(map))
.setClientUris(extractClientUris(map))
.setContacts(extractContacts(map))
.setDefaultAcrs(extractDefaultAcrs(map))
.setDefaultMaxAge(extractDefaultMaxAge(map))
.setDescription(extractDescription(map))
.setDescriptions(extractDescriptions(map))
.setDeveloper(extractDeveloper(map))
.setGrantTypes(extractGrantTypes(map))
.setIdTokenEncryptionAlg(extractIdTokenEncryptionAlg(map))
.setIdTokenEncryptionEnc(extractIdTokenEncryptionEnc(map))
.setIdTokenSignAlg(extractIdTokenSignAlg(map))
.setJwks(extractJwks(map))
.setJwksUri(extractJwksUri(map))
.setLoginUri(extractLoginUri(map))
.setLogoUri(extractLogoUri(map))
.setLogoUris(extractLogoUris(map))
.setPolicyUri(extractPolicyUri(map))
.setPolicyUris(extractPolicyUris(map))
.setRedirectUris(extractRedirectUris(map))
.setRequestEncryptionAlg(extractRequestEncryptionAlg(map))
.setRequestEncryptionEnc(extractRequestEncryptionEnc(map))
.setRequestSignAlg(extractRequestSignAlg(map))
.setRequestUris(extractRequestUris(map))
.setResponseTypes(extractResponseTypes(map))
.setSectorIdentifier(extractSectorIdentifier(map))
.setSubjectType(extractSubjectType(map))
.setTokenAuthMethod(extractTokenAuthMethod(map))
.setTokenAuthSignAlg(extractTokenAuthSignAlg(map))
.setTosUri(extractTosUri(map))
.setTosUris(extractTosUris(map))
.setUserInfoEncryptionAlg(extractUserInfoEncryptionAlg(map))
.setUserInfoEncryptionEnc(extractUserInfoEncryptionEnc(map))
.setUserInfoSignAlg(extractUserInfoSignAlg(map))
;
}
//----------------------
// Common Methods
//----------------------
private static String extractString(MultivaluedMap<String, String> map, String name, int max, boolean required)
{
// Get the first element as the value.
final String value = map.getFirst(name);
// If the value is required one, validate that it is not null.
if (required == true)
{
RequestValidator.validateNotNull(name, value);
}
// If the value is null,
// meaning the user did not specify the value, return null.
if (value == null)
{
return null;
}
// Validate the max length of the string.
RequestValidator.validateMaxLength(name, value, max);
return value;
}
private static String extractRequiredString(MultivaluedMap<String, String> map, String name, int max)
{
// Extract a string value as a required value.
return extractString(map, name, max, true);
}
private static String extractOptionalString(MultivaluedMap<String, String> map, String name, int max)
{
// Extract a string value as an optional value.
return extractString(map, name, max, false);
}
private static String[] extractStringArray(MultivaluedMap<String, String> map, String name, int max)
{
// Get the values as a list.
final List<String> values = map.get(name);
// If the value is null,
// meaning the user did not specify the value,
// or size-zero, return null.
if (values == null || values.size() == 0)
{
return null;
}
// The set to hold validated values.
final Set<String> validatedValues = new HashSet<String>();
// For each element in the list.
for (int i=0; i<values.size(); i++)
{
// Get the i-th element.
final String value = values.get(i);
// Validate that the value is not null or blank.
RequestValidator.validateNotNullAndNotBlank(name, value);
// Validate that the length of the value.
RequestValidator.validateMaxLength(name, value, max);
// Validate that the value is not duplicated.
RequestValidator.validateNotDuplicateInArray(name, value, validatedValues);
// Add the value as the validated one.
validatedValues.add(value);
}
// Convert the set to an array.
return validatedValues.toArray(new String[validatedValues.size()]);
}
private static URI extractUri(MultivaluedMap<String, String> map, String name, int max)
{
// Get the first element as the value.
final String value = map.getFirst(name);
// If the value is null,
// meaning the user did not specify the value, return null.
if (value == null)
{
return null;
}
// Validate the length of the value.
RequestValidator.validateMaxLength(name, value, max);
try
{
// Return the URI based on the value.
return new URI(value);
}
catch (Throwable t)
{
// The value is malformed as an URI.
final String message = String.format("%s is malformed as an URI.", value);
// 400 Bad Request.
throw ApiException.badRequest(message);
}
}
private static TaggedValue[] extractTaggedValues(MultivaluedMap<String, String> map, String tagsName, String valuesName)
{
// Get the tags as a list.
final List<String> tags = map.get(tagsName);
// Get the values as a list.
final List<String> values = map.get(valuesName);
// If either or both of the tags and the values are null or size zero,
// return null.
if (tags == null || values == null || tags.size() == 0 || values.size() == 0)
{
return null;
}
// The set to hold validated tags.
final Set<String> validatedTags = new HashSet<String>();
// The set to hold validated values.
final Set<TaggedValue> validatedValues = new HashSet<TaggedValue>();
// For each element.
// Note that the i-th element of the tags
// is assumed to be associated with the i-th element of the values.
for (int i=0; i<values.size(); i++)
{
// Extract the i-th tag.
final String tag = extractTag(tagsName, tags, i, validatedTags);
// Extract the i-th value.
final String value = extractValue(valuesName, values, i);
// Add them as the validated one.
validatedValues.add(new TaggedValue(tag, value));
}
return validatedValues.toArray(new TaggedValue[validatedValues.size()]);
}
private static String extractTag(String tagsName, List<String> tags, int index, Set<String> validatedTags)
{
// Get the value with the index.
final String tag = tags.get(index);
// Validate that the value is not null or blank.
RequestValidator.validateNotNullAndNotBlank(tagsName, tag);
// Validate that the length of the value.
RequestValidator.validateMaxLength(tagsName, tag, TAGGED_VALUES_TAG_MAX_LENGTH);
// Validate that the value is not duplicated.
RequestValidator.validateNotDuplicateInArray(tagsName, tag, validatedTags);
// Add the value as the validated one.
validatedTags.add(tag);
return tag;
}
private static String extractValue(String valuesName, List<String> values, int index)
{
// Get the value with the index.
final String value = values.get(index);
// Validate that the value is not null or blank.
RequestValidator.validateNotNullAndNotBlank(valuesName, value);
// Validate that the length of the value.
RequestValidator.validateMaxLength(valuesName, value, TAGGED_VALUES_VALUE_MAX_LENGTH);
return value;
}
private static JWSAlg extractJWSAlg(MultivaluedMap<String, String> map, String name)
{
// Get the first element and parse it to a JWSAlg.
return JWSAlg.parse(map.getFirst(name));
}
private static JWEAlg extractJWEAlg(MultivaluedMap<String, String> map, String name)
{
// Get the first element and parse it to a JWEAlg.
return JWEAlg.parse(map.getFirst(name));
}
private static JWEEnc extractJWEEnc(MultivaluedMap<String, String> map, String name)
{
// Get the first element and parse it to a JWEEnc.
return JWEEnc.parse(map.getFirst(name));
}
//---------------------------------
// Extracting Specific Parameters
//----------------------------------
private static ApplicationType extractApplicationType(MultivaluedMap<String, String> map)
{
// Get the 'application_type' and parse it to an ApplicationType.
return ApplicationType.parse(map.getFirst(APPLICATION_TYPE));
}
private static String extractClientName(MultivaluedMap<String, String> map)
{
// Get the 'client_name'.
return extractRequiredString(map, CLIENT_NAME, CLIENT_NAME_MAX_LENGTH);
}
private static TaggedValue[] extractClientNames(MultivaluedMap<String, String> map)
{
// Get the 'client_names'.
return extractTaggedValues(map, CLIENT_NAMES_TAGS, CLIENT_NAMES_VALUES);
}
private static ClientType extractClientType(MultivaluedMap<String, String> map)
{
// Get the 'client_type' and parse it to a ClientType.
final ClientType value = ClientType.parse(map.getFirst(CLIENT_TYPE));
// Validate that it is not null.
RequestValidator.validateNotNull(CLIENT_TYPE, value);
return value;
}
private static URI extractClientUri(MultivaluedMap<String, String> map)
{
// Extract the 'client_uri'.
return extractUri(map, CLIENT_URI, CLIENT_URI_MAX_LENGTH);
}
private static TaggedValue[] extractClientUris(MultivaluedMap<String, String> map)
{
// Extract the 'client_uris'.
return extractTaggedValues(map, CLIENT_URIS_TAGS, CLIENT_URIS_VALUES);
}
private static String[] extractContacts(MultivaluedMap<String, String> map)
{
// Extract the 'contacts'.
return extractStringArray(map, CONTACTS, CONTACT_MAX_LENGTH);
}
private static String[] extractDefaultAcrs(MultivaluedMap<String, String> map)
{
// Extract the 'default_acrs'.
return extractStringArray(map, DEFAULT_ACRS, ACR_MAX_LENGTH);
}
private static int extractDefaultMaxAge(MultivaluedMap<String, String> map)
{
try
{
// Get the 'default_max_age' and parse it into an int.
final int value = Integer.parseInt(map.getFirst(DEFAULT_MAX_AGE));
// Validate that the value is not negative.
RequestValidator.validateNotNegative(DEFAULT_MAX_AGE, value);
return value;
}
catch (Throwable t)
{
// Failed to parse the value into an int.
return 0;
}
}
private static String extractDescription(MultivaluedMap<String, String> map)
{
// Extract the 'description'.
return extractOptionalString(map, DESCRIPTION, DESCRIPTION_MAX_LENGTH);
}
private static TaggedValue[] extractDescriptions(MultivaluedMap<String, String> map)
{
// Extract the 'descriptions'.
return extractTaggedValues(map, DESCRIPTIONS_TAGS, DESCRIPTIONS_VALUES);
}
private static GrantType[] extractGrantTypes(MultivaluedMap<String, String> map)
{
// Get the 'grant_types' as a list.
final List<String> values = map.get(GRANT_TYPES);
// If the value is null,
// meaning the user did not specify the value,
// or size-zero, return null.
if (values == null || values.size() == 0)
{
return null;
}
// The set to hold validated values.
final Set<GrantType> validatedValues = new HashSet<GrantType>();
// For each element.
for (int i=0; i<values.size(); i++)
{
// Get the i-th element.
final String value = values.get(i);
// Validate that the value is not null or blank.
RequestValidator.validateNotNullAndNotBlank(GRANT_TYPES, value);
// Validate that the value is not duplicated.
RequestValidator.validateNotDuplicateInArray(GRANT_TYPES, value, validatedValues);
// Add it as a validated value.
validatedValues.add( GrantType.parse(values.get(i)) );
}
return validatedValues.toArray(new GrantType[validatedValues.size()]);
}
private static JWEAlg extractIdTokenEncryptionAlg(MultivaluedMap<String, String> map)
{
// Extract the 'id_token_encryption_alg'.
return extractJWEAlg(map, ID_TOKEN_ENCRYPTION_ALG);
}
private static JWEEnc extractIdTokenEncryptionEnc(MultivaluedMap<String, String> map)
{
// Extract the 'id_token_encryption_enc'.
return extractJWEEnc(map, ID_TOKEN_ENCRYPTION_ENC);
}
private static JWSAlg extractIdTokenSignAlg(MultivaluedMap<String, String> map)
{
// Extract the 'id_token_sign_alg'.
return extractJWSAlg(map, ID_TOKEN_SIGN_ALG);
}
private static String extractJwks(MultivaluedMap<String, String> map)
{
// Extract the 'jwks'.
return extractOptionalString(map, JWKS, JWKS_URI_MAX_LENGTH);
}
private static URI extractJwksUri(MultivaluedMap<String, String> map)
{
// Extract the 'jwks_uri'
return extractUri(map, JWKS_URI, JWKS_URI_MAX_LENGTH);
}
private static URI extractLoginUri(MultivaluedMap<String, String> map)
{
// Extract the 'login_uri'.
return extractUri(map, LOGIN_URI, LOGIN_URI_MAX_LENGTH);
}
private static URI extractLogoUri(MultivaluedMap<String, String> map)
{
// Extract the 'logo_uri'.
return extractUri(map, LOGO_URI, LOGO_URI_MAX_LENGTH);
}
private static TaggedValue[] extractLogoUris(MultivaluedMap<String, String> map)
{
// Extract the 'logo_uris_tags'.
return extractTaggedValues(map, LOGO_URIS_TAGS, LOGO_URIS_VALUES);
}
private static URI extractPolicyUri(MultivaluedMap<String, String> map)
{
// Extract the 'policy_uri'.
return extractUri(map, POLICY_URI, POLICY_URI_MAX_LENGTH);
}
private static TaggedValue[] extractPolicyUris(MultivaluedMap<String, String> map)
{
// Extract the 'policy_uris_tags'.
return extractTaggedValues(map, POLICY_URIS_TAGS, POLICY_URIS_VALUES);
}
private static String[] extractRedirectUris(MultivaluedMap<String, String> map)
{
// Extract the 'redirect_uris'.
return extractStringArray(map, REDIRECT_URIS, REDIRECT_URI_MAX_LENGTH);
}
private static JWEAlg extractRequestEncryptionAlg(MultivaluedMap<String, String> map)
{
// Extract the 'request_encryption_alg'.
return extractJWEAlg(map, REQUEST_ENCRYPTION_ALG);
}
private static JWEEnc extractRequestEncryptionEnc(MultivaluedMap<String, String> map)
{
// Extract the 'request_encryption_enc'.
return extractJWEEnc(map, REQUEST_ENCRYPTION_ENC);
}
private static JWSAlg extractRequestSignAlg(MultivaluedMap<String, String> map)
{
// Extract the 'request_sign_alg'.
return extractJWSAlg(map, REQUEST_SIGN_ALG);
}
private static String[] extractRequestUris(MultivaluedMap<String, String> map)
{
// Extract the 'request_uris'.
return extractStringArray(map, REQUEST_URIS, REQUEST_URI_MAX_LENGTH);
}
private static ResponseType[] extractResponseTypes(MultivaluedMap<String, String> map)
{
// Get the 'response_types'.
final List<String> values = map.get(RESPONSE_TYPES);
// If the value is null,
// meaning the user did not specify the value, return null.
if (values == null)
{
return null;
}
// The set to hold validated values.
final Set<ResponseType> validatedValues = new HashSet<ResponseType>();
// For each element.
for (int i=0; i<values.size(); i++)
{
// Get the i-th element.
final String value = values.get(i);
// Validate that the value is not null or blank.
RequestValidator.validateNotNullAndNotBlank(GRANT_TYPES, value);
// Validate that the value is not duplicated.
RequestValidator.validateNotDuplicateInArray(GRANT_TYPES, value, validatedValues);
// Add it as a validate value.
validatedValues.add( ResponseType.parse(values.get(i)) );
}
// Convert the set to an array.
return validatedValues.toArray(new ResponseType[validatedValues.size()]);
}
private static URI extractSectorIdentifier(MultivaluedMap<String, String> map)
{
// Extract the 'sector_identifier'.
return extractUri(map, SECTOR_IDENTIFIER, SECTOR_IDENTIFIER_MAX_LENGTH);
}
private static SubjectType extractSubjectType(MultivaluedMap<String, String> map)
{
// Extract the 'subject_type'.
return SubjectType.parse(map.getFirst(SUBJECT_TYPE));
}
private static ClientAuthMethod extractTokenAuthMethod(MultivaluedMap<String, String> map)
{
// Extract the 'token_auth_method'.
return ClientAuthMethod.parse(map.getFirst(TOKEN_AUTH_METHOD));
}
private static JWSAlg extractTokenAuthSignAlg(MultivaluedMap<String, String> map)
{
return extractJWSAlg(map, TOKEN_AUTH_SIGN_ALG);
}
private static URI extractTosUri(MultivaluedMap<String, String> map)
{
// Extract the 'tos_uri'.
return extractUri(map, TOS_URI, TOS_URI_MAX_LENGTH);
}
private static TaggedValue[] extractTosUris(MultivaluedMap<String, String> map)
{
// Extract the 'tos_uris_tags'.
return extractTaggedValues(map, TOS_URIS_TAGS, TOS_URIS_VALUES);
}
private static JWEAlg extractUserInfoEncryptionAlg(MultivaluedMap<String, String> map)
{
// Extract the 'user_info_encryption_alg'.
return extractJWEAlg(map, USER_INFO_ENCRYPTION_ALG);
}
private static JWEEnc extractUserInfoEncryptionEnc(MultivaluedMap<String, String> map)
{
// Extract the 'user_info_encryption_enc'.
return extractJWEEnc(map, USER_INFO_ENCRYPTION_ENC);
}
private static JWSAlg extractUserInfoSignAlg(MultivaluedMap<String, String> map)
{
// Extract the 'user_info_sign_alg'.
return extractJWSAlg(map, USER_INFO_SIGN_ALG);
}
private static long extractClientId(MultivaluedMap<String, String> map)
{
try
{
// Get the 'client_id' and parse it into a long.
final long value = Long.parseLong(map.getFirst(CLIENT_ID));
// Validate that the value is not negative.
RequestValidator.validateNotNegative(CLIENT_ID, value);
return value;
}
catch (Throwable t)
{
// Failed to parse the value into long.
return 0;
}
}
private static String extractDeveloper(MultivaluedMap<String, String> map)
{
// Extract the 'developer'.
return extractRequiredString(map, DEVELOPER, DEVELOPER_MAX_LENGTH);
}
}
| apache-2.0 |
hmlnarik/keycloak | model/map/src/main/java/org/keycloak/models/map/authorization/MapAuthorizationStoreFactory.java | 4274 | /*
* Copyright 2021 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* 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.keycloak.models.map.authorization;
import org.keycloak.Config;
import org.keycloak.authorization.AuthorizationProvider;
import org.keycloak.authorization.model.PermissionTicket;
import org.keycloak.authorization.model.Policy;
import org.keycloak.authorization.model.Resource;
import org.keycloak.authorization.model.ResourceServer;
import org.keycloak.authorization.model.Scope;
import org.keycloak.authorization.store.AuthorizationStoreFactory;
import org.keycloak.authorization.store.StoreFactory;
import org.keycloak.common.Profile;
import org.keycloak.component.AmphibianProviderFactory;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.map.authorization.entity.MapPermissionTicketEntity;
import org.keycloak.models.map.authorization.entity.MapPolicyEntity;
import org.keycloak.models.map.authorization.entity.MapResourceEntity;
import org.keycloak.models.map.authorization.entity.MapResourceServerEntity;
import org.keycloak.models.map.authorization.entity.MapScopeEntity;
import org.keycloak.models.map.common.AbstractMapProviderFactory;
import org.keycloak.models.map.storage.MapStorage;
import org.keycloak.models.map.storage.MapStorageProvider;
import org.keycloak.models.map.storage.MapStorageProviderFactory;
import org.keycloak.models.map.storage.MapStorageSpi;
import org.keycloak.provider.EnvironmentDependentProviderFactory;
import static org.keycloak.models.utils.KeycloakModelUtils.getComponentFactory;
/**
* @author mhajas
*/
public class MapAuthorizationStoreFactory<K> implements AmphibianProviderFactory<StoreFactory>, AuthorizationStoreFactory, EnvironmentDependentProviderFactory {
public static final String PROVIDER_ID = AbstractMapProviderFactory.PROVIDER_ID;
private Config.Scope storageConfigScope;
@Override
public StoreFactory create(KeycloakSession session) {
MapStorageProviderFactory storageProviderFactory = (MapStorageProviderFactory) getComponentFactory(session.getKeycloakSessionFactory(),
MapStorageProvider.class, storageConfigScope, MapStorageSpi.NAME);
final MapStorageProvider mapStorageProvider = storageProviderFactory.create(session);
AuthorizationProvider provider = session.getProvider(AuthorizationProvider.class);
MapStorage permissionTicketStore;
MapStorage policyStore;
MapStorage resourceServerStore;
MapStorage resourceStore;
MapStorage scopeStore;
permissionTicketStore = mapStorageProvider.getStorage(PermissionTicket.class);
policyStore = mapStorageProvider.getStorage(Policy.class);
resourceServerStore = mapStorageProvider.getStorage(ResourceServer.class);
resourceStore = mapStorageProvider.getStorage(Resource.class);
scopeStore = mapStorageProvider.getStorage(Scope.class);
return new MapAuthorizationStore(session,
permissionTicketStore,
policyStore,
resourceServerStore,
resourceStore,
scopeStore,
provider
);
}
@Override
public void init(org.keycloak.Config.Scope config) {
this.storageConfigScope = config.scope("storage");
}
@Override
public void close() {
}
@Override
public String getId() {
return PROVIDER_ID;
}
@Override
public String getHelpText() {
return "Authorization store provider";
}
@Override
public boolean isSupported() {
return Profile.isFeatureEnabled(Profile.Feature.MAP_STORAGE);
}
}
| apache-2.0 |