text
stringlengths 7
1.01M
|
|---|
/*
* Copyright 2013-2018 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.redshift.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.AmazonWebServiceRequest;
/**
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/redshift-2012-12-01/ModifyClusterSnapshot" target="_top">AWS API
* Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class ModifyClusterSnapshotRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable {
/**
* <p>
* The identifier of the snapshot whose setting you want to modify.
* </p>
*/
private String snapshotIdentifier;
/**
* <p>
* The number of days that a manual snapshot is retained. If the value is -1, the manual snapshot is retained
* indefinitely.
* </p>
* <p>
* If the manual snapshot falls outside of the new retention period, you can specify the force option to immediately
* delete the snapshot.
* </p>
* <p>
* The value must be either -1 or an integer between 1 and 3,653.
* </p>
*/
private Integer manualSnapshotRetentionPeriod;
/**
* <p>
* A Boolean option to override an exception if the retention period has already passed.
* </p>
*/
private Boolean force;
/**
* <p>
* The identifier of the snapshot whose setting you want to modify.
* </p>
*
* @param snapshotIdentifier
* The identifier of the snapshot whose setting you want to modify.
*/
public void setSnapshotIdentifier(String snapshotIdentifier) {
this.snapshotIdentifier = snapshotIdentifier;
}
/**
* <p>
* The identifier of the snapshot whose setting you want to modify.
* </p>
*
* @return The identifier of the snapshot whose setting you want to modify.
*/
public String getSnapshotIdentifier() {
return this.snapshotIdentifier;
}
/**
* <p>
* The identifier of the snapshot whose setting you want to modify.
* </p>
*
* @param snapshotIdentifier
* The identifier of the snapshot whose setting you want to modify.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ModifyClusterSnapshotRequest withSnapshotIdentifier(String snapshotIdentifier) {
setSnapshotIdentifier(snapshotIdentifier);
return this;
}
/**
* <p>
* The number of days that a manual snapshot is retained. If the value is -1, the manual snapshot is retained
* indefinitely.
* </p>
* <p>
* If the manual snapshot falls outside of the new retention period, you can specify the force option to immediately
* delete the snapshot.
* </p>
* <p>
* The value must be either -1 or an integer between 1 and 3,653.
* </p>
*
* @param manualSnapshotRetentionPeriod
* The number of days that a manual snapshot is retained. If the value is -1, the manual snapshot is retained
* indefinitely.</p>
* <p>
* If the manual snapshot falls outside of the new retention period, you can specify the force option to
* immediately delete the snapshot.
* </p>
* <p>
* The value must be either -1 or an integer between 1 and 3,653.
*/
public void setManualSnapshotRetentionPeriod(Integer manualSnapshotRetentionPeriod) {
this.manualSnapshotRetentionPeriod = manualSnapshotRetentionPeriod;
}
/**
* <p>
* The number of days that a manual snapshot is retained. If the value is -1, the manual snapshot is retained
* indefinitely.
* </p>
* <p>
* If the manual snapshot falls outside of the new retention period, you can specify the force option to immediately
* delete the snapshot.
* </p>
* <p>
* The value must be either -1 or an integer between 1 and 3,653.
* </p>
*
* @return The number of days that a manual snapshot is retained. If the value is -1, the manual snapshot is
* retained indefinitely.</p>
* <p>
* If the manual snapshot falls outside of the new retention period, you can specify the force option to
* immediately delete the snapshot.
* </p>
* <p>
* The value must be either -1 or an integer between 1 and 3,653.
*/
public Integer getManualSnapshotRetentionPeriod() {
return this.manualSnapshotRetentionPeriod;
}
/**
* <p>
* The number of days that a manual snapshot is retained. If the value is -1, the manual snapshot is retained
* indefinitely.
* </p>
* <p>
* If the manual snapshot falls outside of the new retention period, you can specify the force option to immediately
* delete the snapshot.
* </p>
* <p>
* The value must be either -1 or an integer between 1 and 3,653.
* </p>
*
* @param manualSnapshotRetentionPeriod
* The number of days that a manual snapshot is retained. If the value is -1, the manual snapshot is retained
* indefinitely.</p>
* <p>
* If the manual snapshot falls outside of the new retention period, you can specify the force option to
* immediately delete the snapshot.
* </p>
* <p>
* The value must be either -1 or an integer between 1 and 3,653.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ModifyClusterSnapshotRequest withManualSnapshotRetentionPeriod(Integer manualSnapshotRetentionPeriod) {
setManualSnapshotRetentionPeriod(manualSnapshotRetentionPeriod);
return this;
}
/**
* <p>
* A Boolean option to override an exception if the retention period has already passed.
* </p>
*
* @param force
* A Boolean option to override an exception if the retention period has already passed.
*/
public void setForce(Boolean force) {
this.force = force;
}
/**
* <p>
* A Boolean option to override an exception if the retention period has already passed.
* </p>
*
* @return A Boolean option to override an exception if the retention period has already passed.
*/
public Boolean getForce() {
return this.force;
}
/**
* <p>
* A Boolean option to override an exception if the retention period has already passed.
* </p>
*
* @param force
* A Boolean option to override an exception if the retention period has already passed.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ModifyClusterSnapshotRequest withForce(Boolean force) {
setForce(force);
return this;
}
/**
* <p>
* A Boolean option to override an exception if the retention period has already passed.
* </p>
*
* @return A Boolean option to override an exception if the retention period has already passed.
*/
public Boolean isForce() {
return this.force;
}
/**
* Returns a string representation of this object; useful for testing and debugging.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getSnapshotIdentifier() != null)
sb.append("SnapshotIdentifier: ").append(getSnapshotIdentifier()).append(",");
if (getManualSnapshotRetentionPeriod() != null)
sb.append("ManualSnapshotRetentionPeriod: ").append(getManualSnapshotRetentionPeriod()).append(",");
if (getForce() != null)
sb.append("Force: ").append(getForce());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof ModifyClusterSnapshotRequest == false)
return false;
ModifyClusterSnapshotRequest other = (ModifyClusterSnapshotRequest) obj;
if (other.getSnapshotIdentifier() == null ^ this.getSnapshotIdentifier() == null)
return false;
if (other.getSnapshotIdentifier() != null && other.getSnapshotIdentifier().equals(this.getSnapshotIdentifier()) == false)
return false;
if (other.getManualSnapshotRetentionPeriod() == null ^ this.getManualSnapshotRetentionPeriod() == null)
return false;
if (other.getManualSnapshotRetentionPeriod() != null
&& other.getManualSnapshotRetentionPeriod().equals(this.getManualSnapshotRetentionPeriod()) == false)
return false;
if (other.getForce() == null ^ this.getForce() == null)
return false;
if (other.getForce() != null && other.getForce().equals(this.getForce()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getSnapshotIdentifier() == null) ? 0 : getSnapshotIdentifier().hashCode());
hashCode = prime * hashCode + ((getManualSnapshotRetentionPeriod() == null) ? 0 : getManualSnapshotRetentionPeriod().hashCode());
hashCode = prime * hashCode + ((getForce() == null) ? 0 : getForce().hashCode());
return hashCode;
}
@Override
public ModifyClusterSnapshotRequest clone() {
return (ModifyClusterSnapshotRequest) super.clone();
}
}
|
/*
* Kubernetes
* No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
*
* OpenAPI spec version: v1.8.1
*
*
* 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 io.kubernetes.client.models;
import java.util.Objects;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import io.kubernetes.client.models.V1ListMeta;
import io.kubernetes.client.models.V1Namespace;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* NamespaceList is a list of Namespaces.
*/
@ApiModel(description = "NamespaceList is a list of Namespaces.")
public class V1NamespaceList {
@SerializedName("apiVersion")
private String apiVersion = null;
@SerializedName("items")
private List<V1Namespace> items = new ArrayList<V1Namespace>();
@SerializedName("kind")
private String kind = null;
@SerializedName("metadata")
private V1ListMeta metadata = null;
public V1NamespaceList apiVersion(String apiVersion) {
this.apiVersion = apiVersion;
return this;
}
/**
* APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#resources
* @return apiVersion
**/
@ApiModelProperty(value = "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#resources")
public String getApiVersion() {
return apiVersion;
}
public void setApiVersion(String apiVersion) {
this.apiVersion = apiVersion;
}
public V1NamespaceList items(List<V1Namespace> items) {
this.items = items;
return this;
}
public V1NamespaceList addItemsItem(V1Namespace itemsItem) {
this.items.add(itemsItem);
return this;
}
/**
* Items is the list of Namespace objects in the list. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/namespaces/
* @return items
**/
@ApiModelProperty(required = true, value = "Items is the list of Namespace objects in the list. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/namespaces/")
public List<V1Namespace> getItems() {
return items;
}
public void setItems(List<V1Namespace> items) {
this.items = items;
}
public V1NamespaceList kind(String kind) {
this.kind = kind;
return this;
}
/**
* Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#types-kinds
* @return kind
**/
@ApiModelProperty(value = "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#types-kinds")
public String getKind() {
return kind;
}
public void setKind(String kind) {
this.kind = kind;
}
public V1NamespaceList metadata(V1ListMeta metadata) {
this.metadata = metadata;
return this;
}
/**
* Standard list metadata. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#types-kinds
* @return metadata
**/
@ApiModelProperty(value = "Standard list metadata. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#types-kinds")
public V1ListMeta getMetadata() {
return metadata;
}
public void setMetadata(V1ListMeta metadata) {
this.metadata = metadata;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
V1NamespaceList v1NamespaceList = (V1NamespaceList) o;
return Objects.equals(this.apiVersion, v1NamespaceList.apiVersion) &&
Objects.equals(this.items, v1NamespaceList.items) &&
Objects.equals(this.kind, v1NamespaceList.kind) &&
Objects.equals(this.metadata, v1NamespaceList.metadata);
}
@Override
public int hashCode() {
return Objects.hash(apiVersion, items, kind, metadata);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class V1NamespaceList {\n");
sb.append(" apiVersion: ").append(toIndentedString(apiVersion)).append("\n");
sb.append(" items: ").append(toIndentedString(items)).append("\n");
sb.append(" kind: ").append(toIndentedString(kind)).append("\n");
sb.append(" metadata: ").append(toIndentedString(metadata)).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 ");
}
}
|
/**
* Copyright © 2017 <a href="www.wanhutong.com">wanhutong</a> All rights reserved.
*/
package com.wanhutong.backend.modules.sys.interceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import com.wanhutong.backend.common.service.BaseService;
import com.wanhutong.backend.common.utils.StringUtils;
import com.wanhutong.backend.common.utils.UserAgentUtils;
/**
* 手机端视图拦截器
* @author ThinkGem
* @version 2014-9-1
*/
public class MobileInterceptor extends BaseService implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
Object handler) throws Exception {
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
if (modelAndView != null){
// 如果是手机或平板访问的话,则跳转到手机视图页面。
if(UserAgentUtils.isMobileOrTablet(request) && !StringUtils.startsWithIgnoreCase(modelAndView.getViewName(), "redirect:")){
modelAndView.setViewName("mobile/" + modelAndView.getViewName());
}
}
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
Object handler, Exception ex) throws Exception {
}
}
|
package sk.ksp.baklazan.sketchalgo.structure.arraylist;
import sk.ksp.baklazan.sketchalgo.structure.*;
import sk.ksp.baklazan.sketchalgo.Theme;
import java.util.*;
import java.lang.*;
import java.awt.image.*;
import java.awt.Graphics2D;
import java.awt.geom.*;
import java.awt.Rectangle;
import javafx.scene.canvas.*;
import javafx.scene.image.*;
import javafx.scene.text.*;
import javafx.scene.*;
import javafx.application.*;
/** Cells vertically */
public class VerticalAssemblingStrategy extends ListAssemblingStrategy
{
private VerticalAssemblingStrategy()
{
}
private static class singletonHolder
{
private static final VerticalAssemblingStrategy INSTANCE = new VerticalAssemblingStrategy();
}
public static VerticalAssemblingStrategy getInstance()
{
return singletonHolder.INSTANCE;
}
@Override
public BufferedImage assemble(ArrayList<BufferedImage> elements, Rectangle cellSize, Theme theme, boolean inner)
{
int border = theme.getExternalBorder(inner);
int width = cellSize.width + 2*border;
int height = cellSize.height * elements.size();
height += theme.internalBorder * Math.max(0,elements.size()-1);
height += 2*border;
height = Math.max(height, 1);
BufferedImage result = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics2D graphics = result.createGraphics();
graphics.setColor(theme.borderColor);
graphics.fillRect(0, 0, result.getWidth(), result.getHeight());
graphics.setColor(theme.backgroundColor);
for(int i=0; i<elements.size(); i++)
{
int x = border;
int y = (cellSize.height + theme.internalBorder) * i + border;
graphics.fillRect(x, y, cellSize.width, cellSize.height);
graphics.drawImage(elements.get(i), x, y, null);
}
return result;
}
@Override
public Rectangle preferredSize(Rectangle cellSize, int count, Theme theme, boolean inner)
{
int border = theme.getExternalBorder(inner);
int height = cellSize.height * count + theme.internalBorder*(count-1) + 2*border;
int width = cellSize.width + 2*border;
return new Rectangle(width, height);
}
@Override
public Rectangle cellSize(Rectangle totalSize, int count, Theme theme, boolean inner)
{
if(count == 0)return new Rectangle(1,1);
int border = theme.getExternalBorder(inner);
int width = totalSize.width - 2*border;
int height = totalSize.height - 2*border;
height -= (count-1) * theme.internalBorder;
height /= count;
return new Rectangle(width, height);
}
@Override
public ListAssemblingStrategy getPerpendicular()
{
return HorizontalAssemblingStrategy.getInstance();
}
}
|
package com.github.gustavopm1.gotcamel.routes.themoviedb.movies;
import com.fasterxml.jackson.core.type.TypeReference;
import com.github.gustavopm1.gotcamel.models.Request;
import com.github.gustavopm1.gotcamel.models.Response;
import com.github.gustavopm1.gotcamel.models.SearchType;
import com.github.gustavopm1.gotcamel.models.themoviedb.movie.*;
import com.github.gustavopm1.gotcamel.routes.AbstractRouteTest;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
import java.io.IOException;
import java.util.Arrays;
import static org.assertj.core.api.Assertions.assertThat;
@SpringBootTest
@RunWith(SpringRunner.class)
@Slf4j
@ActiveProfiles({"route","prod"})
public class MovieApiRouteTest extends AbstractRouteTest {
@Test
public void testRouteMovie() throws IOException {
Response<Movie> returned = sendMessage(
configuration.getRoutes().getInbound().getMovie(),
Request.<TypeValueData>builder().body( TypeValueData.builder().type(SearchType.MOVIENAME).value("The 13th Warrior").build() ).user("testuser").build(),
NO_HEADERS,
(new TypeReference<Response<Movie>>(){})
);
assertThat(returned)
.isNotNull()
.hasFieldOrPropertyWithValue("found",true)
.hasFieldOrProperty("body");
assertThat(returned.getBody())
.isNotNull()
.isInstanceOf(Movie.class)
.hasFieldOrPropertyWithValue("original_title","The 13th Warrior");
}
@Test
public void testRouteMovieById() throws IOException {
Response<Movie> returned = sendMessage(
configuration.getRoutes().getInbound().getMovie(),
Request.<TypeValueData>builder().body( TypeValueData.builder().type(SearchType.MOVIEID).value("1911").build() ).user("testuser").build(),
NO_HEADERS,
(new TypeReference<Response<Movie>>(){})
);
assertThat(returned)
.isNotNull()
.hasFieldOrPropertyWithValue("found",true)
.hasFieldOrProperty("body");
assertThat(returned.getBody())
.isNotNull()
.isInstanceOf(Movie.class)
.hasFieldOrPropertyWithValue("original_title","The 13th Warrior");
}
@Test
public void testCompleteRouteMovieById() throws IOException{
Response<Movie> returned = sendMessage(
configuration.getRoutes().getInbound().getMovie(),
Request.<TypeValueData>builder().body( TypeValueData.builder().type(SearchType.FULLMOVIE).value("1911").build() ).user("testuser").build(),
NO_HEADERS,
(new TypeReference<Response<Movie>>(){})
);
assertThat(returned)
.isNotNull()
.hasFieldOrPropertyWithValue("found",true)
.hasFieldOrProperty("body");
assertThat(returned.getBody())
.isNotNull()
.isInstanceOf(Movie.class)
.hasFieldOrPropertyWithValue("original_title","The 13th Warrior")
.hasFieldOrPropertyWithValue("keywords", Arrays.asList(MovieKeyword.builder().id(616).name("witch").build(),
MovieKeyword.builder().id(1585).name("snake").build(),
MovieKeyword.builder().id(1964).name("cave").build()))
.hasFieldOrPropertyWithValue("crew", Arrays.asList(Crew.builder().id(19893).name("Warren Lewis").department("Writing").build(),
Crew.builder().id(1090).name("John McTiernan").department("Directing").build()))
.hasFieldOrPropertyWithValue("cast", Arrays.asList(MovieCast.builder()
.id(3131)
.name("Antonio Banderas")
.character("Ahmad Ibn Fadlān")
.profile_path("/85197jARsr06xQ84NhP9YoBL3sR.jpg")
.build(),
MovieCast.builder()
.id(6200)
.name("Diane Venora")
.character("Queen Weilew")
.profile_path("/3k7w5Y7gTAxN1JML7jhN8F8rVrS.jpg")
.build(),
MovieCast.builder()
.id(19899)
.name("Dennis Storhøi")
.character("Herger the Joyous")
.profile_path("/zc8O7O8l8wtX3EQmDV7jWOPjmHJ.jpg")
.build()));
}
}
|
/**
* Copyright (C) 2010 Asterios Raptis
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.alpharogroup.wicket.base.util.url;
import org.apache.wicket.Page;
import org.apache.wicket.protocol.https.Scheme;
import org.apache.wicket.request.Url;
import org.apache.wicket.request.cycle.RequestCycle;
import org.apache.wicket.request.mapper.parameter.PageParameters;
import de.alpharogroup.wicket.base.util.WicketComponentExtensions;
/**
* The Class WicketUrlUtils.
*/
public class WicketUrlExtensions
{
/**
* Returns the absolute url for the given page without the server port.
*
* @param <C>
* the generic type
* @param page
* the page
* @return the string
*/
public static <C extends Page> String absoluteUrlFor(final Class<C> page)
{
return absoluteUrlFor(page, null, false);
}
/**
* Returns the absolute url for the given page and optionally with the server port.
*
* @param <C>
* the generic type
* @param page
* the page
* @param withServerPort
* the with server port
* @return the string
*/
public static <C extends Page> String absoluteUrlFor(final Class<C> page,
final boolean withServerPort)
{
return absoluteUrlFor(page, null, withServerPort);
}
/**
* Returns the absolute url for the given page with the parameters and optionally with the
* server port.
*
* @param <C>
* the generic type
* @param page
* the page
* @param parameters
* the parameters
* @param withServerPort
* the with server port
* @return the string
*/
public static <C extends Page> String absoluteUrlFor(final Class<C> page,
final PageParameters parameters, final boolean withServerPort)
{
final StringBuilder url = new StringBuilder();
url.append(WicketUrlExtensions.getDomainUrl(withServerPort));
url.append(WicketUrlExtensions.getBaseUrl(page, parameters).canonical().toString());
return url.toString();
}
/**
* Gets the base Url.
*
* @return base Url
*/
public static Url getBaseUrl()
{
return RequestCycle.get().getUrlRenderer().getBaseUrl();
}
/**
* Gets the base url from the given WebPage class object.
*
* @param pageClass
* the page class
* @return the base url
*/
public static Url getBaseUrl(final Class<? extends Page> pageClass)
{
return getBaseUrl(pageClass, null);
}
/**
* Gets the base url.
*
* @param pageClass
* the page class
* @param parameters
* the parameters
* @return the base url
*/
public static Url getBaseUrl(final Class<? extends Page> pageClass,
final PageParameters parameters)
{
return RequestCycle.get().mapUrlFor(pageClass, parameters);
}
/**
* Gets the base url from the given WebPage.
*
* @param page
* the page
* @return the base url
*/
public static Url getBaseUrl(final Page page)
{
return getBaseUrl(page.getPageClass());
}
/**
* Gets the canonical page url. Try to reduce url by eliminating '..' and '.' from the path
* where appropriate (this is somehow similar to {@link java.io.File#getCanonicalPath()}).
*
* @param pageClass
* the page class
* @return the page url
* @see Url#canonical()
*/
public static Url getCanonicalPageUrl(final Class<? extends Page> pageClass)
{
return getCanonicalPageUrl(pageClass, null);
}
/**
* Gets the canonical page url. Try to reduce url by eliminating '..' and '.' from the path
* where appropriate (this is somehow similar to {@link java.io.File#getCanonicalPath()}).
*
* @param pageClass
* the page class
* @param parameters
* the parameters
* @return the page url
* @see Url#canonical()
*/
public static Url getCanonicalPageUrl(final Class<? extends Page> pageClass,
final PageParameters parameters)
{
return getPageUrl(pageClass, parameters).canonical();
}
/**
* Gets the context path.
*
* @return the context path
*/
public static String getContextPath()
{
return RequestCycle.get().getRequest().getContextPath();
}
/**
* Gets the context path from the given WebPage.
*
* @param page
* the page
* @return the context path
*/
public static String getContextPath(final Page page)
{
return page.getRequest().getContextPath();
}
/**
* Gets the domain url.
*
* @return the domain url
*/
public static String getDomainUrl()
{
return getDomainUrl(true);
}
/**
* Gets the domain url.
*
* @param withServerPort
* the with server port
* @return the domain url
*/
public static String getDomainUrl(final boolean withServerPort)
{
return getDomainUrl(withServerPort, true);
}
/**
* Gets the domain url.
*
* @param withServerPort
* the with server port
* @param withSlashAtTheEnd
* the with slash at the end
* @return the domain url
*/
public static String getDomainUrl(final boolean withServerPort, final boolean withSlashAtTheEnd)
{
return getDomainUrl(false, withServerPort, withSlashAtTheEnd);
}
/**
* Gets the domain url.
*
* @param ssl
* if the domain url is secure the scheme https will be added otherwise http
* @param withServerPort
* the with server port
* @param withSlashAtTheEnd
* the with slash at the end
* @return the domain url
*/
public static String getDomainUrl(final boolean ssl, final boolean withServerPort,
final boolean withSlashAtTheEnd)
{
return newDomainUrl(ssl ? Scheme.HTTPS.urlName() : Scheme.HTTP.urlName(),
WicketUrlExtensions.getServerName(),
WicketComponentExtensions.getHttpServletRequest().getServerPort(), withServerPort,
withSlashAtTheEnd);
}
/**
* Returns the host name or the ip address on which the request was received.
*
* @return a <code>String</code> containing the host name of the ip address on which the request
* was received.
*
* @see javax.servlet.ServletRequest#getLocalName()
*/
public static String getLocalName()
{
return WicketComponentExtensions.getHttpServletRequest().getLocalName();
}
/**
* Gets the page url as Url object from the given WebPage class object.
*
* @param pageClass
* the page class
* @return the page url
*/
public static Url getPageUrl(final Class<? extends Page> pageClass)
{
return getPageUrl(pageClass, null);
}
/**
* Gets the page url.
*
* @param pageClass
* the page class
* @param parameters
* the parameters
* @return the page url
*/
public static Url getPageUrl(final Class<? extends Page> pageClass,
final PageParameters parameters)
{
final String url = RequestCycle.get().urlFor(pageClass, parameters).toString();
return Url.parse(url);
}
/**
* Gets the page url as Url object from the given WebPage.
*
* @param page
* the page
* @return the page url
*/
public static Url getPageUrl(final Page page)
{
return getPageUrl(page.getPageClass());
}
/**
* Gets the page url.
*
* @param page
* the page
* @param parameters
* the parameters
* @return the page url
*/
public static Url getPageUrl(final Page page, final PageParameters parameters)
{
return getPageUrl(page.getPageClass(), parameters);
}
/**
* Gets the server name.
*
* @return the server name
*/
public static String getServerName()
{
return WicketComponentExtensions.getHttpServletRequest().getServerName();
}
/**
* Gets the url as string from the given WebPage class object.
*
* @param pageClass
* the page class
* @return the url as string
*/
public static String getUrlAsString(final Class<? extends Page> pageClass)
{
final Url pageUrl = getPageUrl(pageClass);
final Url url = getBaseUrl(pageClass);
url.resolveRelative(pageUrl);
final String contextPath = getContextPath();
return String.format("%s/%s", contextPath, url);
}
/**
* Gets the url as string from the given WebPage.
*
* @param page
* the page
* @return the url as string
*/
public static String getUrlAsString(final Page page)
{
return getUrlAsString(page.getPageClass());
}
/**
* Creates a new domain url from the given parameters.
*
* @param scheme
* the scheme
* @param domainName
* the domain name
* @param port
* the port
* @param withServerPort
* the with server port
* @param withSlashAtTheEnd
* the with slash at the end
* @return the string
*/
public static String newDomainUrl(final String scheme, final String domainName, final int port,
final boolean withServerPort, final boolean withSlashAtTheEnd)
{
final StringBuilder domainUrl = new StringBuilder();
domainUrl.append(scheme);
domainUrl.append("://");
domainUrl.append(domainName);
if (withServerPort)
{
domainUrl.append(":");
domainUrl.append(port);
}
if (withSlashAtTheEnd)
{
domainUrl.append("/");
}
return domainUrl.toString();
}
/**
* Gets the base Url as String.
*
* @return base Url as String.
*/
public static String toBaseUrl()
{
return getBaseUrl().canonical().toString();
}
/**
* Gets the base url from the given WebPage class object as String.
*
* @param pageClass
* the page class
* @return the base url as String.
*/
public static String toBaseUrl(final Class<? extends Page> pageClass)
{
return getBaseUrl(pageClass).canonical().toString();
}
/**
* Gets the base ur as String.
*
* @param pageClass
* the page class
* @param parameters
* the parameters
* @return the base url as String.
*/
public static String toBaseUrl(final Class<? extends Page> pageClass,
final PageParameters parameters)
{
return getBaseUrl(pageClass, parameters).canonical().toString();
}
}
|
/*
* 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.isis.unittestsupport.value;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.notNullValue;
import static org.junit.Assert.assertThat;
import static org.junit.Assume.assumeThat;
/**
* Contract test for value types ({@link #equals(Object) equals} and
* {@link #hashCode() hashCode}), and also {@link Comparable#compareTo(Object) compareTo} for
* any value types that also are {@link Comparable}
*/
public abstract class ValueTypeContractTestAbstract<T> {
@Before
public void setUp() throws Exception {
assertSizeAtLeast(getObjectsWithSameValue(), 2);
assertSizeAtLeast(getObjectsWithDifferentValue(), 1);
}
private void assertSizeAtLeast(final List<T> objects, final int i) {
assertThat(objects, is(notNullValue()));
assertThat(objects.size(), is(greaterThan(i - 1)));
}
@Test
public void notEqualToNull() throws Exception {
for (final T o1 : getObjectsWithSameValue()) {
assertThat(o1.equals(null), is(false));
}
for (final T o1 : getObjectsWithDifferentValue()) {
assertThat(o1.equals(null), is(false));
}
}
@Test
public void reflexiveAndSymmetric() throws Exception {
for (final T o1 : getObjectsWithSameValue()) {
for (final T o2 : getObjectsWithSameValue()) {
assertThat(o1.equals(o2), is(true));
assertThat(o2.equals(o1), is(true));
assertThat(o1.hashCode(), is(equalTo(o2.hashCode())));
}
}
}
@Test
public void notEqual() throws Exception {
for (final T o1 : getObjectsWithSameValue()) {
for (final T o2 : getObjectsWithDifferentValue()) {
assertThat(o1.equals(o2), is(false));
assertThat(o2.equals(o1), is(false));
}
}
}
@Test
public void transitiveWhenEqual() throws Exception {
for (final T o1 : getObjectsWithSameValue()) {
for (final T o2 : getObjectsWithSameValue()) {
for (final Object o3 : getObjectsWithSameValue()) {
assertThat(o1.equals(o2), is(true));
assertThat(o2.equals(o3), is(true));
assertThat(o1.equals(o3), is(true));
}
}
}
}
@Test
@SuppressWarnings({ "rawtypes", "unchecked" })
public void comparableEquivalence() throws Exception {
for (final T o1 : getObjectsWithSameValue()) {
assumeThat(o1 instanceof Comparable, is(true));
Comparable c1 = (Comparable)o1;
for (final T o2 : getObjectsWithSameValue()) {
assumeThat(o2 instanceof Comparable, is(true));
Comparable c2 = (Comparable)o2;
assertThat(c1.compareTo(c2), is(0));
assertThat(c2.compareTo(c1), is(0));
}
for (final T o2 : getObjectsWithDifferentValue()) {
assumeThat(o2 instanceof Comparable, is(true));
Comparable c2 = (Comparable)o2;
final int x = c1.compareTo(c2);
final int y = c2.compareTo(c1);
assertThat(x, is(not(0)));
assertThat(x, is(-y));
}
}
}
protected abstract List<T> getObjectsWithSameValue();
protected abstract List<T> getObjectsWithDifferentValue();
}
|
/*
* Copyright (c) "Neo4j"
* Neo4j Sweden AB [http://neo4j.com]
*
* This file is part of Neo4j.
*
* 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.neo4j.driver.internal.async.pool;
import io.netty.channel.Channel;
import io.netty.channel.pool.ChannelHealthChecker;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.Promise;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicReference;
import org.neo4j.driver.Logger;
import org.neo4j.driver.Logging;
import org.neo4j.driver.exceptions.AuthorizationExpiredException;
import org.neo4j.driver.internal.async.connection.AuthorizationStateListener;
import org.neo4j.driver.internal.handlers.PingResponseHandler;
import org.neo4j.driver.internal.messaging.request.ResetMessage;
import org.neo4j.driver.internal.util.Clock;
import static org.neo4j.driver.internal.async.connection.ChannelAttributes.creationTimestamp;
import static org.neo4j.driver.internal.async.connection.ChannelAttributes.lastUsedTimestamp;
import static org.neo4j.driver.internal.async.connection.ChannelAttributes.messageDispatcher;
public class NettyChannelHealthChecker implements ChannelHealthChecker, AuthorizationStateListener
{
private final PoolSettings poolSettings;
private final Clock clock;
private final Logger log;
private final AtomicReference<Optional<Long>> minCreationTimestampMillisOpt;
public NettyChannelHealthChecker( PoolSettings poolSettings, Clock clock, Logging logging )
{
this.poolSettings = poolSettings;
this.clock = clock;
this.log = logging.getLog( getClass().getSimpleName() );
this.minCreationTimestampMillisOpt = new AtomicReference<>( Optional.empty() );
}
@Override
public Future<Boolean> isHealthy( Channel channel )
{
if ( isTooOld( channel ) )
{
return channel.eventLoop().newSucceededFuture( Boolean.FALSE );
}
if ( hasBeenIdleForTooLong( channel ) )
{
return ping( channel );
}
return ACTIVE.isHealthy( channel );
}
@Override
public void onExpired( AuthorizationExpiredException e, Channel channel )
{
long ts = creationTimestamp( channel );
// Override current value ONLY if the new one is greater
minCreationTimestampMillisOpt.getAndUpdate( prev -> Optional.of( prev.filter( prevTs -> ts <= prevTs ).orElse( ts ) ) );
}
private boolean isTooOld( Channel channel )
{
long creationTimestampMillis = creationTimestamp( channel );
Optional<Long> minCreationTimestampMillisOpt = this.minCreationTimestampMillisOpt.get();
if ( minCreationTimestampMillisOpt.isPresent() && creationTimestampMillis <= minCreationTimestampMillisOpt.get() )
{
log.trace( "The channel %s is marked for closure as its creation timestamp is older than or equal to the acceptable minimum timestamp: %s <= %s",
channel, creationTimestampMillis, minCreationTimestampMillisOpt.get() );
return true;
}
else if ( poolSettings.maxConnectionLifetimeEnabled() )
{
long currentTimestampMillis = clock.millis();
long ageMillis = currentTimestampMillis - creationTimestampMillis;
long maxAgeMillis = poolSettings.maxConnectionLifetime();
boolean tooOld = ageMillis > maxAgeMillis;
if ( tooOld )
{
log.trace( "Failed acquire channel %s from the pool because it is too old: %s > %s",
channel, ageMillis, maxAgeMillis );
}
return tooOld;
}
return false;
}
private boolean hasBeenIdleForTooLong( Channel channel )
{
if ( poolSettings.idleTimeBeforeConnectionTestEnabled() )
{
Long lastUsedTimestamp = lastUsedTimestamp( channel );
if ( lastUsedTimestamp != null )
{
long idleTime = clock.millis() - lastUsedTimestamp;
boolean idleTooLong = idleTime > poolSettings.idleTimeBeforeConnectionTest();
if ( idleTooLong )
{
log.trace( "Channel %s has been idle for %s and needs a ping", channel, idleTime );
}
return idleTooLong;
}
}
return false;
}
private Future<Boolean> ping( Channel channel )
{
Promise<Boolean> result = channel.eventLoop().newPromise();
messageDispatcher( channel ).enqueue( new PingResponseHandler( result, channel, log ) );
channel.writeAndFlush( ResetMessage.RESET, channel.voidPromise() );
return result;
}
}
|
//
// ========================================================================
// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others.
//
// This program and the accompanying materials are made available under
// the terms of the Eclipse Public License 2.0 which is available at
// https://www.eclipse.org/legal/epl-2.0
//
// This Source Code may also be made available under the following
// Secondary Licenses when the conditions for such availability set
// forth in the Eclipse Public License, v. 2.0 are satisfied:
// the Apache License v2.0 which is available at
// https://www.apache.org/licenses/LICENSE-2.0
//
// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
// ========================================================================
//
package org.eclipse.jetty.websocket.core;
import java.net.URI;
/**
* Exception during WebSocket Upgrade Handshake.
*/
@SuppressWarnings("serial")
public class UpgradeException extends WebSocketException
{
private final URI requestURI;
private final int responseStatusCode;
public UpgradeException(URI requestURI, int responseStatusCode, String message)
{
super(message);
this.requestURI = requestURI;
this.responseStatusCode = responseStatusCode;
}
public UpgradeException(URI requestURI, int responseStatusCode, String message, Throwable cause)
{
super(message, cause);
this.requestURI = requestURI;
this.responseStatusCode = responseStatusCode;
}
public UpgradeException(URI requestURI, Throwable cause)
{
super(cause);
this.requestURI = requestURI;
this.responseStatusCode = -1;
}
public URI getRequestURI()
{
return requestURI;
}
public int getResponseStatusCode()
{
return responseStatusCode;
}
}
|
/**
* Copyright © 2015 Christian Wulf, Nelson Tavares de Sousa (http://teetime-framework.github.io)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package teetime.framework.performancelogging.formatstrategy;
import java.util.Collection;
import teetime.framework.AbstractStage;
import teetime.framework.StateStatisticsUtils;
import teetime.framework.performancelogging.ActivationStateLogger.IFormatingStrategy;
import teetime.framework.performancelogging.StateChange;
import teetime.framework.performancelogging.StateChange.StageActivationState;
public class CumulativeActivePassivTime implements IFormatingStrategy {
private final Collection<AbstractStage> stages;
public CumulativeActivePassivTime(final Collection<AbstractStage> stages) {
this.stages = stages;
}
/**
* Will return the simple name of the given stage and added enough spaces to match the longest name.
*
* @param stage
* Stage which name should be formated.
* @return Simple name of the given stage plus spaces to match the longest name.
*/
String formateName(final AbstractStage stage) {
return stage.getClass().getSimpleName() + ";";
}
@Override
public String formatData() {
String result = "\n Formating to analyse differences in runtime:\n\n";
result += "name;total time;cumulative blocked time;cumulative active waiting time time;active time\n";
// go through all the stages
for (AbstractStage stage : stages) {
// first add a formated version of their names to the line.
result += formateName(stage);
long earliestTimeStamp = Long.MAX_VALUE;
long latestTimeStamp = Long.MIN_VALUE;
long lastTimeStamp = 0;
StageActivationState lastState = StageActivationState.INITIALIZED;
long cumulativeActiveTime = 0;
long cumulativeActiveWaitingTime = StateStatisticsUtils.getActiveWaitingTime(stage);
long cumulativeBlockedTime = 0;
// go through all states of this stage and sum up the active times while counting the number of active timestamp
for (StateChange state : StateStatisticsUtils.getStates(stage)) {
long actualTimeStamp = state.getTimeStamp();
// update earliest and latest timeStamp if necessary
if (actualTimeStamp < earliestTimeStamp) {
earliestTimeStamp = actualTimeStamp;
} else if (actualTimeStamp > latestTimeStamp) {
latestTimeStamp = actualTimeStamp;
}
// In the first loop neither lastTimeStamp nor lastState are set. So the next part wouldn't calculate correct.
if (lastState != StageActivationState.INITIALIZED) {
long elapsedTime = actualTimeStamp - lastTimeStamp;
switch (lastState) {
case ACTIVE:
cumulativeActiveTime += elapsedTime;
break;
case BLOCKED:
cumulativeBlockedTime += elapsedTime;
break;
case TERMINATED:
break;
default:
break;
}
}
lastTimeStamp = actualTimeStamp;
lastState = state.getStageActivationState();
}
// The ActiveWaiting time was counted into active time till now. So it it subtracted now.
cumulativeActiveTime -= cumulativeActiveWaitingTime;
result += (latestTimeStamp - earliestTimeStamp) + ";" + cumulativeBlockedTime + ";" + cumulativeActiveWaitingTime + ";" + cumulativeActiveTime;
result += "\n";
}
return result.replace("\n", String.format("%n"));
}
}
|
package com.zandero.rest.example.rest;
import com.zandero.rest.RestRouter;
import com.zandero.rest.injection.InjectionProvider;
import io.vertx.core.Vertx;
import io.vertx.ext.web.client.WebClient;
import io.vertx.junit5.VertxTestContext;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Disabled;
import javax.validation.Validator;
/**
*
*/
@Disabled
public class BaseTest {
protected static final int PORT = 3333;
protected static final String HOST = "localhost";
protected static final String ROOT_PATH = "http://" + HOST + ":" + PORT;
protected static Vertx vertx = null;
protected static VertxTestContext vertxTestContext;
protected static WebClient client;
public static void before() {
vertx = Vertx.vertx();
vertxTestContext = new VertxTestContext();
// clear all registered writers or reader and handlers
RestRouter.getReaders().clear();
RestRouter.getWriters().clear();
RestRouter.getExceptionHandlers().clear();
RestRouter.getContextProviders().clear();
// clear
RestRouter.validateWith((Validator) null);
RestRouter.injectWith((InjectionProvider) null);
client = WebClient.create(vertx);
}
@AfterEach
void lastChecks(Vertx vertx) {
vertx.close(vertxTestContext.succeeding());
}
@AfterAll
static void close() {
vertx.close();
}
}
|
/*
* Copyright 2012-2016 Credit Suisse
* Copyright 2018-2020 Werner Keil, Otavio Santana, Trivadis AG
*
* 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 javax.money.convert;
import org.testng.annotations.Test;
import javax.money.MonetaryException;
import javax.money.TestCurrency;
import static org.testng.Assert.*;
/**
* Tests for {@link javax.money.convert.MonetaryConversions}.
*/
public class MonetaryConversionsTest {
@Test
public void testGetConversion() throws Exception {
assertNotNull(MonetaryConversions.getConversion(TestCurrency.of("CHF")));
}
@Test
public void testGetConversion1() throws Exception {
assertNotNull(MonetaryConversions.getConversion(
ConversionQueryBuilder.of().setTermCurrency(TestCurrency.of("CHF")).build()));
}
@Test
public void testGetExchangeRateProvider1() throws Exception {
assertNotNull(MonetaryConversions.getExchangeRateProvider(
ConversionQueryBuilder.of().setTermCurrency(TestCurrency.of("CHF")).build()));
}
@Test
public void testIsConversionAvailable1_Query() throws Exception {
assertTrue(MonetaryConversions.isConversionAvailable(
ConversionQueryBuilder.of().setTermCurrency(TestCurrency.of("CHF")).build()));
}
@Test
public void testIsExchangeRateProviderAvailable1_Query() throws Exception {
assertTrue(MonetaryConversions.isExchangeRateProviderAvailable(
ConversionQueryBuilder.of().setTermCurrency(TestCurrency.of("CHF")).build()));
}
@Test
public void testGetConversion2() throws Exception {
assertNotNull(MonetaryConversions.getConversion(
ConversionQueryBuilder.of().setTermCurrency(TestCurrency.of("CHF")).setProviderNames("test").build()));
try {
MonetaryConversions.getConversion(
ConversionQueryBuilder.of().setTermCurrency(TestCurrency.of("CHF")).setProviderNames("foo").build());
fail("Should throw MonetaryException");
} catch (MonetaryException e) {
// OK
}
}
@Test
public void testIsConversionAvailable2() throws Exception {
assertTrue(MonetaryConversions.isConversionAvailable(
ConversionQueryBuilder.of().setTermCurrency(TestCurrency.of("CHF")).setProviderNames("test").build()));
}
@Test
public void testGetConversion_String_StringArr() throws Exception {
assertNotNull(MonetaryConversions.getConversion("test1", "test"));
assertNotNull(MonetaryConversions.getConversion("test1"));
try {
MonetaryConversions.getConversion("test1", "foo");
fail("Should throw MonetaryException");
} catch (MonetaryException e) {
// OK
}
}
@Test
public void testIsConversionAvailable_String_StringArr() throws Exception {
assertTrue(MonetaryConversions.isConversionAvailable("test1", "test"));
assertTrue(MonetaryConversions.isConversionAvailable("test1"));
assertFalse(MonetaryConversions.isConversionAvailable("test1", "foo"));
}
@Test
public void testGetConversion3() throws Exception {
assertNotNull(MonetaryConversions.getConversion(TestCurrency.of("CHF"), "test"));
}
@Test
public void testGetExchangeRateProvider() throws Exception {
assertNotNull(MonetaryConversions.getExchangeRateProvider("test"));
}
@Test(expectedExceptions = MonetaryException.class)
public void testGetExchangeRateProvider_Invalid() throws Exception {
MonetaryConversions.getExchangeRateProvider("fooBarAnyBla");
}
@Test
public void testGetProviderNames() throws Exception {
assertNotNull(MonetaryConversions.getConversionProviderNames());
assertTrue(MonetaryConversions.getConversionProviderNames().contains("test"));
assertTrue(MonetaryConversions.getConversionProviderNames().size() == 1);
}
@Test
public void testGetDefaultProviderChain() throws Exception {
assertNotNull(MonetaryConversions.getDefaultConversionProviderChain());
assertFalse(MonetaryConversions.getDefaultConversionProviderChain().isEmpty());
assertEquals(1, MonetaryConversions.getDefaultConversionProviderChain().size());
}
}
|
/*
* This file is part of choco-solver, http://choco-solver.org/
*
* Copyright (c) 2022, IMT Atlantique. All rights reserved.
*
* Licensed under the BSD 4-clause license.
*
* See LICENSE file in the project root for full license information.
*/
package org.chocosolver.solver;
import org.chocosolver.memory.ICondition;
import org.chocosolver.memory.IEnvironment;
import org.chocosolver.solver.constraints.ISatFactory;
import org.chocosolver.solver.constraints.PropagatorPriority;
import org.chocosolver.solver.constraints.real.Ibex;
import org.chocosolver.solver.search.strategy.Search;
import org.chocosolver.solver.search.strategy.strategy.AbstractStrategy;
import org.chocosolver.util.ESat;
import java.util.HashMap;
import java.util.function.Function;
import java.util.function.IntPredicate;
import java.util.function.Predicate;
/**
* Settings for Model and Solver.
* Can be modified programmatically
* and can be defined in a Model only on creation.
*
* <p> Project: choco-solver.
*
* @author Charles Prud'homme
* @since 14/12/2017.
*/
public class Settings {
private Predicate<Solver> modelChecker = s -> !ESat.FALSE.equals(s.isSatisfied());
private boolean cloneVariableArrayInPropagator = true;
private boolean enableViews = true;
private int maxDomSizeForEnumerated = 1 << 16;
private int minCardForSumDecomposition = 50;
private boolean enableTableSubstitution = true;
private int maxTupleSizeForSubstitution = 10_000;
private boolean sortPropagatorActivationWRTPriority = true;
private int maxPropagatorPriority = PropagatorPriority.VERY_SLOW.getValue();
private Function<Model, AbstractStrategy<?>> defaultSearch = Search::defaultSearch;
private boolean warnUser = false;
private boolean enableDecompositionOfBooleanSum = false;
private IntPredicate enableIncrementalityOnBoolSum = i -> i > 10;
private boolean enableSAT = false;
private boolean swapOnPassivate = false;
private boolean checkDeclaredConstraints = true;
private boolean checkDeclaredViews = true;
private boolean checkDeclaredMonitors = true;
private boolean printAllUndeclaredConstraints = false;
private byte hybridEngine = 0b00;
private int nbMaxLearnt = 100_000;
private int maxLearntCardinlity = Integer.MAX_VALUE / 100;
private float clauseReductionRatio = .5f;
private int dominancePerimeter = 4;
private boolean explainGlobalFailureInSum = true;
private double ibexContractionRatio = Ibex.RATIO;
private boolean ibexRestoreRounding = Ibex.PRESERVE_ROUNDING;
private Function<Model, Solver> initSolver = Solver::new;
private final HashMap<String, Object> additionalSettings = new HashMap<>();
private Settings() {
}
/**
* Create a new instance of `Settings` which can then be adapted to requirements.
*
* @return a Settings with default values
* @see #dev()
* @see #prod()
*/
public static Settings init() {
return new Settings();
}
/**
* Define and returns settings adapted to production environment.
* All checks and warnings are turned off.
*
* @return a settings adapted to production environment.
*/
public static Settings prod() {
return Settings.init()
.setModelChecker(s -> true)
.setWarnUser(false)
.setCheckDeclaredConstraints(false)
.setCheckDeclaredViews(false)
.setCheckDeclaredMonitors(false)
.setPrintAllUndeclaredConstraints(false);
}
/**
* Define and returns settings adapted to development environment.
* All checks and warnings are turned on.
*
* @return a settings adapted to development environment.
*/
public static Settings dev() {
return Settings.init()
.setModelChecker(s -> !ESat.FALSE.equals(s.isSatisfied()))
.setWarnUser(true)
.setCheckDeclaredConstraints(true)
.setCheckDeclaredViews(true)
.setCheckDeclaredMonitors(true)
.setPrintAllUndeclaredConstraints(true);
}
/**
* @param solver the solver
* @return <tt>true</tt> if the model is OK wrt the checker, <tt>false</tt> otherwise
*/
public boolean checkModel(Solver solver) {
return modelChecker.test(solver);
}
/**
* Define what to do when a solution is found. By default, it makes a weak check of the model:
* <pre>
* {@code
* return !ESat.FALSE.equals(solver.isSatisfied());
* }
* </pre>
* A hard check of the model can be done like this:
* <pre>
* {@code
* return ESat.TRUE.equals(solver.isSatisfied());
* }
* </pre>
*
* @param modelChecker a predicate to check the solution
* @return the current instance
*/
public Settings setModelChecker(Predicate<Solver> modelChecker) {
this.modelChecker = modelChecker;
return this;
}
/**
* @return true if all propagators should clone the input variable array instead of simply referencing it.
*/
public boolean cloneVariableArrayInPropagator() {
return cloneVariableArrayInPropagator;
}
/**
* If this setting is set to true (default value), a clone of the input variable array is made in any propagator constructors.
* This prevents, for instance, wrong behavior when permutations occurred on the input array (e.g., sorting variables).
* Setting this to false may limit the memory consumption during modelling.
*
* @param cloneVariableArrayInPropagator {@code true} to clone variables array on constructor
* @return the current instance
*/
public Settings setCloneVariableArrayInPropagator(boolean cloneVariableArrayInPropagator) {
this.cloneVariableArrayInPropagator = cloneVariableArrayInPropagator;
return this;
}
/**
* @return <tt>true</tt> if views are enabled.
*/
public boolean enableViews() {
return enableViews;
}
/**
* Set to 'true' to allow the creation of views in the {@link org.chocosolver.solver.Model}.
* Creates new variables with channeling constraints otherwise.
*
* @param enableViews {@code true} to enable views
* @return the current instance
*/
public Settings setEnableViews(boolean enableViews) {
this.enableViews = enableViews;
return this;
}
/**
* @return maximum domain size threshold to force integer variable to be enumerated
*/
public int getMaxDomSizeForEnumerated() {
return maxDomSizeForEnumerated;
}
/**
* Define the minimum number of cardinality threshold to a sum/scalar constraint to be decomposed in intermediate
* sub-sums.
*
* @param maxDomSizeForEnumerated cardinality threshold
* @return the current instance
*/
public Settings setMaxDomSizeForEnumerated(int maxDomSizeForEnumerated) {
this.maxDomSizeForEnumerated = maxDomSizeForEnumerated;
return this;
}
/**
* @return minimum number of cardinality threshold to a sum constraint to be decomposed
*/
public int getMinCardForSumDecomposition() {
return minCardForSumDecomposition;
}
/**
* Define the default minimum number of cardinality threshold to a sum/scalar constraint to be
* decomposed into intermediate sub-sums.
*
* @param defaultMinCardinalityForSumDecomposition cardinality threshold
* @return the current instance
*/
public Settings setMinCardinalityForSumDecomposition(int defaultMinCardinalityForSumDecomposition) {
this.minCardForSumDecomposition = defaultMinCardinalityForSumDecomposition;
return this;
}
/**
* @return <tt>true</tt> if some intension constraints can be replaced by extension constraints
*/
public boolean enableTableSubstitution() {
return enableTableSubstitution;
}
/**
* Define whether some intension constraints are replaced by extension constraints
*
* @param enableTableSubstitution enable table substitution
* @return the current instance
*/
public Settings setEnableTableSubstitution(boolean enableTableSubstitution) {
this.enableTableSubstitution = enableTableSubstitution;
return this;
}
/**
* @return maximum domain size threshold to replace intension constraints by extension constraints
*/
public int getMaxTupleSizeForSubstitution() {
return maxTupleSizeForSubstitution;
}
/**
* Define the maximum domain size threshold to replace intension constraints by extension constraints
* Only checked when {@link #enableTableSubstitution()} returns {@code true}
*
* @param maxTupleSizeForSubstitution threshold to substitute intension constraint by table one.
* @return the current instance
*/
public Settings setMaxTupleSizeForSubstitution(int maxTupleSizeForSubstitution) {
this.maxTupleSizeForSubstitution = maxTupleSizeForSubstitution;
return this;
}
/**
* @return {@code true} if propagators are sorted wrt their priority on initial activation.
*/
public boolean sortPropagatorActivationWRTPriority() {
return sortPropagatorActivationWRTPriority;
}
/**
* Set whether propagators are sorted wrt their priority in {@link org.chocosolver.solver.propagation.PropagationEngine} when
* dealing with propagator activation.
*
* @param sortPropagatorActivationWRTPriority {@code true} to allow sorting static propagators.
* @return the current instance
*/
public Settings setSortPropagatorActivationWRTPriority(boolean sortPropagatorActivationWRTPriority) {
this.sortPropagatorActivationWRTPriority = sortPropagatorActivationWRTPriority;
return this;
}
/**
* @return the maximum priority any propagators can have (default is 7)
*/
public int getMaxPropagatorPriority(){
return maxPropagatorPriority;
}
/**
* Increase the number of priority for propagators (default is {@link PropagatorPriority#VERY_SLOW}).
* This directly impacts the number of queues to schedule propagators in the propagation engine.
*
* @param maxPropagatorPriority the new maximum prioirity any propagator can declare
* @return the current instance
*/
public Settings setMaxPropagatorPriority(int maxPropagatorPriority){
this.maxPropagatorPriority = maxPropagatorPriority;
return this;
}
/**
* Creates a default search strategy for the input model
*
* @param model a model requiring a default search strategy
* @return a default search strategy for model
* @see Search#defaultSearch(Model)
*/
public AbstractStrategy<?> makeDefaultSearch(Model model) {
return defaultSearch.apply(model);
}
/**
* Define a default search strategy for the input model
*
* @param defaultSearch what default search strategy should be
* @return the current instance
*/
public Settings setDefaultSearch(Function<Model, AbstractStrategy<?>> defaultSearch) {
this.defaultSearch = defaultSearch;
return this;
}
@Deprecated
public ICondition getEnvironmentHistorySimulationCondition() {
return null;
}
@Deprecated
public Settings setEnvironmentHistorySimulationCondition(ICondition environmentHistorySimulationCondition) {
return null;
}
/**
* @return <tt>true</tt> if warnings detected during modeling/solving are output.
*/
public boolean warnUser() {
return warnUser;
}
/**
* To be informed of warnings detected during modeling/solving
*
* @param warnUser {@code true} to be print warnings on console
* @return the current instance
*/
public Settings setWarnUser(boolean warnUser) {
this.warnUser = warnUser;
return this;
}
/**
* @return {@code true} if boolean sum should be decomposed into an equality constraint and an arithmetic constraint,
* {@code false}if a single constraint should be used instead.
*/
public boolean enableDecompositionOfBooleanSum() {
return enableDecompositionOfBooleanSum;
}
/**
* Define if boolean sums should be decomposed into an equality constraint + arithmetic constraint
*
* @param enableDecompositionOfBooleanSum {@code true} to enable decomposition
* @return the current instance
*/
public Settings setEnableDecompositionOfBooleanSum(boolean enableDecompositionOfBooleanSum) {
this.enableDecompositionOfBooleanSum = enableDecompositionOfBooleanSum;
return this;
}
/**
* @param nbvars number of variables in the constraint
* @return {@code true} if the incrementality is enabled on boolean sum, based on the number of variables involved.
*/
public boolean enableIncrementalityOnBoolSum(int nbvars) {
return enableIncrementalityOnBoolSum.test(nbvars);
}
/**
* Define the predicate to choose incremental sum, based on number variables declared
*
* @param enableIncrementalityOnBoolSum predicate to pick declare sum
* @return the current instance
*/
public Settings setEnableIncrementalityOnBoolSum(IntPredicate enableIncrementalityOnBoolSum) {
this.enableIncrementalityOnBoolSum = enableIncrementalityOnBoolSum;
return this;
}
/**
* @return <i>true</i> when an underlying SAT solver is used to manage clauses declared through {@link ISatFactory},
* <i>false</i> when clauses are managed with CSP constraints only.
*/
public boolean enableSAT() {
return enableSAT;
}
/**
* Indicate if clauses are managed by a unique SAT solver.
*
* @param enableSAT {@code true} to rely on SAT Solver to handle clauses
* @return the current instance
*/
public Settings setEnableSAT(boolean enableSAT) {
this.enableSAT = enableSAT;
return this;
}
/**
* @return <i>true</i> if, on propagator passivation, the propagator is swapped from active to passive in its variables' propagators list.
* <i>false</i> if, on propagator passivation, only the propagator's state is set to PASSIVE.
*/
public boolean swapOnPassivate() {
return swapOnPassivate;
}
/**
* Define if passivation of propagator swap it in variables' list
*
* @param swapOnPassivate {@code true} to enable swapping
* @return the current instance
*/
public Settings setSwapOnPassivate(boolean swapOnPassivate) {
this.swapOnPassivate = swapOnPassivate;
return this;
}
/**
* @return <i>true</i> (default value) to check if all declared constraints are not free anymore,
* that is either posted or reified, before running the resolution.
* <i>false</i> to skip the control.
*/
public boolean checkDeclaredConstraints() {
return checkDeclaredConstraints;
}
/**
* Indicate if the declared constraints are either posted or reified.
*
* @param checkDeclaredConstraints {@code true} to check constraints before resolution
* @return the current instance
*/
public Settings setCheckDeclaredConstraints(boolean checkDeclaredConstraints) {
this.checkDeclaredConstraints = checkDeclaredConstraints;
return this;
}
/**
* @return <i>true</i> to list all undeclared constraint, <i>false</i> (default value) otherwise.
* Only active when {@link #checkDeclaredConstraints()} is on.
*/
public boolean printAllUndeclaredConstraints() {
return printAllUndeclaredConstraints;
}
/**
* Indicate if all undeclared constraints are listed on console when {@link #checkDeclaredConstraints()} is on.
*
* @param printAllUndeclaredConstraints {@code true} to list all undeclared constraints
* @return the current instance
*/
public Settings setPrintAllUndeclaredConstraints(boolean printAllUndeclaredConstraints) {
this.printAllUndeclaredConstraints = printAllUndeclaredConstraints;
return this;
}
/**
* @return <i>true</i> (default value) to check prior to creation
* if a view already semantically exists.
*/
public boolean checkDeclaredViews() {
return checkDeclaredViews;
}
/**
* Check if a view already semantically exists before creating it.
*
* @param checkDeclaredViews {@code true} to check views before creation
* @return the current instance
*/
public Settings setCheckDeclaredViews(boolean checkDeclaredViews) {
this.checkDeclaredViews = checkDeclaredViews;
return this;
}
public Settings setCheckDeclaredMonitors(boolean check) {
this.checkDeclaredMonitors = check;
return this;
}
public boolean checkDeclaredMonitors() {
return this.checkDeclaredMonitors;
}
/**
* This method is called in {@link Model#Model(IEnvironment, String, Settings)} to create the
* solver to associate with a model.
*
* @param model a model to initialize with a solver
* @return the new solver
*/
public Solver initSolver(Model model) {
return initSolver.apply(model);
}
/**
* Define the solver initialization
*
* @param initSolver function to initialize the solver
* @return the current instance
*/
public Settings setInitSolver(Function<Model, Solver> initSolver) {
this.initSolver = initSolver;
return this;
}
/**
* @return <i>0b00<i/> if constraint-oriented propagation engine,
* <i>0b01<i/> if hybridization between variable and constraint oriented and
* <i>0b10<i/> if variable-oriented.
*/
public byte enableHybridizationOfPropagationEngine() {
return hybridEngine;
}
/**
* Define behavior of the propagation engine.
*
* @param hybrid When set to '0b00', this works as a constraint-oriented propagation engine;
* when set to '0b01', this workds as an hybridization between variable and constraint oriented
* propagation engine.
* when set to '0b10', this workds as a variable- oriented propagation engine.
* @return the current instance
*/
public Settings setHybridizationOfPropagationEngine(byte hybrid) {
this.hybridEngine = hybrid;
return this;
}
/**
* @return maximum number of learnt clauses to store. When reached, a reduction is applied.
* @see #setNbMaxLearntClauses(int)
* @see #setRatioForClauseStoreReduction(float)
* @see #getRatioForClauseStoreReduction()
* @see #setMaxLearntClauseCardinality(int)
* @see #getMaxLearntClauseCardinality()
*/
public int getNbMaxLearntClauses() {
return nbMaxLearnt;
}
/**
* Set the maximum of number of learnt clauses to store before running a reduction of the store.
*
* @param n maximum number of learnt clauses before reducing the store.
* @return the current instance
* @see #getNbMaxLearntClauses()
* @see #setRatioForClauseStoreReduction(float)
* @see #getRatioForClauseStoreReduction()
* @see #setMaxLearntClauseCardinality(int)
* @see #getMaxLearntClauseCardinality()
*/
public Settings setNbMaxLearntClauses(int n) {
this.nbMaxLearnt = n;
return this;
}
/**
* when clauses store need to be reduced, 'ratio' of them are kept (between 0.1 and .99)
*
* @see #setRatioForClauseStoreReduction(float)
* @see #setNbMaxLearntClauses(int)
* @see #getNbMaxLearntClauses()
* @see #setMaxLearntClauseCardinality(int)
* @see #getMaxLearntClauseCardinality()
*/
public float getRatioForClauseStoreReduction() {
return this.clauseReductionRatio;
}
/**
* when clauses store need to be reduced, 'ratio' of them are kept (between 0.1 and .99).
* A call to this defines 'ratio'.
*
* @param f ratio for clause store reduction
* @return the current instance
* @see #getRatioForClauseStoreReduction()
* @see #setNbMaxLearntClauses(int)
* @see #getNbMaxLearntClauses()
* @see #setMaxLearntClauseCardinality(int)
* @see #getMaxLearntClauseCardinality()
*/
public Settings setRatioForClauseStoreReduction(float f) {
this.clauseReductionRatio = f;
return this;
}
/**
* @return maximum learnt clause cardinality, clauses beyond this value are ignored.
* @see #setMaxLearntClauseCardinality(int)
* @see #setNbMaxLearntClauses(int)
* @see #setRatioForClauseStoreReduction(float)
* @see #getRatioForClauseStoreReduction()
* @see #setRatioForClauseStoreReduction(float)
*/
public int getMaxLearntClauseCardinality() {
return maxLearntCardinlity;
}
/**
* Set the maximum learnt clause cardinality, clauses beyond this value are ignored.
*
* @param n maximum learnt clause cardinality.
* @return the current instance
* @see #getMaxLearntClauseCardinality()
* @see #getNbMaxLearntClauses()
* @see #setRatioForClauseStoreReduction(float)
* @see #getRatioForClauseStoreReduction()
* @see #setRatioForClauseStoreReduction(float)
*/
public Settings setMaxLearntClauseCardinality(int n) {
maxLearntCardinlity = n;
return this;
}
/**
* When a clause is learnt from a conflict, it may happen that it dominates previously learnt ones.
* The dominance will be evaluated with the <i>n</i> last learnt clauses.
* n = 0 means no dominance check, n = {@link Integer#MAX_VALUE} means checking all clauses with the last one.
*
* @return dominance perimeter
*/
public int getLearntClausesDominancePerimeter() {
return dominancePerimeter;
}
/**
* When a clause is learnt from a conflict, it may happen that it dominates previously learnt ones.
* The dominance will be evaluated with the <i>n</i> last learnt clauses.
* n = 0 means no dominance check, n = {@link Integer#MAX_VALUE} means checking all clauses with the last one.
*
* @return dominance perimeter
*/
public Settings setLearntClausesDominancePerimeter(int n) {
this.dominancePerimeter = n;
return this;
}
/**
* @return <i>true</i> if additional clauses can be learned from sum's global failure
*/
public boolean explainGlobalFailureInSum() {
return explainGlobalFailureInSum;
}
/**
* Set to <i>true</i> to allow additional clauses to be learned from sum's global failure
*/
public Settings explainGlobalFailureInSum(boolean b) {
this.explainGlobalFailureInSum = b;
return this;
}
/**
* @return the ratio that a domains must be contracted by ibex to compute the constraint.
*/
public double getIbexContractionRatio() {
return ibexContractionRatio;
}
/**
* Defines the ratio that real domains must be contracted by ibex
* to compute the constraint. A contraction is considered as significant
* when at least {@param ratio} of a domain has been reduced.
* If the contraction is not meet, then it is considered as insufficient
* and therefore ignored. A too small ratio can degrade the ibex performance.
* The default value is 1% (0.01). See issue #653.
* <p>
* Example: given x = [0.0, 100.0], y = [0.5,0.5] and CSTR(x > y)
* - When the ratio is 1% (0.01) bounds of X are kept as [0.0, 100.0]
* because it's contraction is less than 1%.
* - When the ratio is 0.1% (0.001) bounds of X are update to [0.5, 100.0]
* because it's contraction is greater than 0.1%.
*
* @param ibexContractionRatio defines the ratio that a domains must be
* contract to compute the constraint.
* @implNote Supported since ibex-java version 1.2.0
*/
public void setIbexContractionRatio(double ibexContractionRatio) {
this.ibexContractionRatio = ibexContractionRatio;
}
/**
* If preserve_rounding is true, Ibex will restore the default
* Java rounding method when coming back from Ibex, which is
* transparent for Java but causes a little loss of efficiency.
* To improve the running time, ibex changes the rounding system
* for double values during contraction. In Linux/MACOS environments
* it leads to different results in calculations like `Math.pow(10, 6)`.
* See issue #740.
*
* @param ibexRestoreRounding either Java or ibex rounding method
* @implNote Supported since ibex-java version 1.2.0
*/
public Settings setIbexRestoreRounding(boolean ibexRestoreRounding) {
this.ibexRestoreRounding = ibexRestoreRounding;
return this;
}
/**
* @return if ibex must restore java rounding mode when returning a call.
*/
public boolean getIbexRestoreRounding() {
return ibexRestoreRounding;
}
public Object get(String key) {
return additionalSettings.get(key);
}
public Settings set(String key, Object value) {
this.additionalSettings.put(key, value);
return this;
}
}
|
package com.lizij.binder;
import com.lizij.IWebBinder;
import com.lizij.jsbridge.MyRemoteJsBridge;
/**
* For remote web process call java method in main process
* @author lizijian
*/
public class WebBinder extends IWebBinder.Stub {
/**
* Call java method registered in main process
* @param func method name
* @param params json string
* @return result json string
*/
@Override
public String invokeJavaMethod(String func, String params) {
return MyRemoteJsBridge.inst().invokeJavaMethod(func, params);
}
}
|
package org.apereo.cas.services;
import org.apereo.cas.category.RestfulApiCategory;
import org.apereo.cas.config.CasCoreServicesConfiguration;
import org.apereo.cas.config.RestServiceRegistryConfiguration;
import org.apereo.cas.configuration.CasConfigurationProperties;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.http.HttpStatus;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.actuate.autoconfigure.metrics.MetricsAutoConfiguration;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.cloud.autoconfigure.RefreshAutoConfiguration;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.test.context.TestPropertySource;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Collection;
import java.util.Collections;
import static org.mockito.Mockito.*;
/**
* This is {@link RestfulServiceRegistryTests}.
*
* @author Misagh Moayyed
* @since 5.3.0
*/
@RunWith(Parameterized.class)
@SpringBootTest(classes = {
RestfulServiceRegistryTests.RestServicesTestConfiguration.class,
RestServiceRegistryConfiguration.class,
RefreshAutoConfiguration.class
},
webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
@EnableConfigurationProperties(CasConfigurationProperties.class)
@EnableAutoConfiguration(exclude = {
CasCoreServicesConfiguration.class,
MetricsAutoConfiguration.class
})
@TestPropertySource(properties = {"server.port=9303", "cas.serviceRegistry.rest.url=http://localhost:9303", "cas.serviceRegistry.initFromJson=false"})
@Category(RestfulApiCategory.class)
public class RestfulServiceRegistryTests extends AbstractServiceRegistryTests {
@Autowired
@Qualifier("restfulServiceRegistry")
private ServiceRegistry dao;
public RestfulServiceRegistryTests(final Class<? extends RegisteredService> registeredServiceClass) {
super(registeredServiceClass);
}
@Parameterized.Parameters
public static Collection<Object> getTestParameters() {
return Collections.singletonList(RegexRegisteredService.class);
}
@Override
public ServiceRegistry getNewServiceRegistry() {
return this.dao;
}
@TestConfiguration
public static class RestServicesTestConfiguration {
@RestController("servicesController")
@RequestMapping("/")
public static class ServicesController {
private final InMemoryServiceRegistry serviceRegistry = new InMemoryServiceRegistry(mock(ApplicationEventPublisher.class));
@DeleteMapping
public Integer findByServiceId(@RequestBody final RegisteredService service) {
serviceRegistry.delete(service);
return HttpStatus.SC_OK;
}
@PostMapping
public RegisteredService save(@RequestBody final RegisteredService service) {
serviceRegistry.save(service);
return service;
}
@GetMapping("/{id}")
public RegisteredService findServiceById(@PathVariable(name = "id") final String id) {
if (NumberUtils.isParsable(id)) {
return serviceRegistry.findServiceById(Long.valueOf(id));
}
return serviceRegistry.findServiceByExactServiceId(id);
}
@GetMapping
public RegisteredService[] load() {
return serviceRegistry.load().toArray(RegisteredService[]::new);
}
}
}
}
|
package com.evil.inc.platedecisiontaker.service;
import com.evil.inc.platedecisiontaker.model.Car;
import com.evil.inc.platedecisiontaker.model.exception.CarNotFoundException;
import com.evil.inc.platedecisiontaker.repository.CarRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
@Service
@RequiredArgsConstructor
public class CarServiceImpl implements CarService {
private final CarRepository carRepository;
@Override
public Car getCarByLicensePLate(String licensePLate) {
return carRepository.findByLicensePlate(licensePLate).orElseThrow(() -> new CarNotFoundException("This " + licensePLate + " is not valid"));
}
}
|
package model;
import java.util.Date;
public class AppointmentDoctor implements ISchedulable {
private int id;
private Patient patient;
private Doctor doctor;
private Date date;
private String time;
public AppointmentDoctor(Patient patient, Doctor doctor) {
this.patient = patient;
this.doctor = doctor;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Patient getPatient() {
return patient;
}
public void setPatient(Patient patient) {
this.patient = patient;
}
public Doctor getDoctor() {
return doctor;
}
public void setDoctor(Doctor doctor) {
this.doctor = doctor;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public String getTime() {
return time + " hrs. ";
}
public void setTime(String time) {
this.time = time;
}
@Override
public void schedule(Date date, String time) {
this.date = date;
this.time = time;
}
}
|
package patterns.observer.cycle;
public interface Observer {
void update(Observable source, Object arg);
}
|
/**
* Copyright (C) 2009 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.bbg.referencedata.statistics;
import java.util.Set;
/**
* A class which records interesting statistics about usage of bloomberg reference data.
*/
public interface BloombergReferenceDataStatistics {
/**
* Records the fact that some Bloomberg fields were read.
*
* @param identifiers
* the identifiers, such as securities, not null
* @param fields
* the fields read, not null
*/
void recordStatistics(Set<String> identifiers, Set<String> fields);
}
|
package library.domain.model.reservation;
/**
* 予約の状態
*/
public enum ReservationStatus {
未準備("予約があるが、未取置"),
消込済("貸出または取置期限切れにより取置を解放");
String description;
ReservationStatus(String description) {
this.description = description;
}
}
|
package com.jb.example.vo;
import java.time.LocalDate;
public class RelatorioVendasVO {
private String produto;
private Long quantidade;
private LocalDate ultimaData;
public RelatorioVendasVO(String produto, Long quantidade, LocalDate ultimaData) {
this.produto = produto;
this.quantidade = quantidade;
this.ultimaData = ultimaData;
}
public String getProduto() {
return produto;
}
public Long getQuantidade() {
return quantidade;
}
public LocalDate getUltimaData() {
return ultimaData;
}
@Override
public String toString() {
return "RelatorioVendasVO{" +
"produto='" + produto + '\'' +
", quantidade=" + quantidade +
", ultimaData=" + ultimaData +
'}';
}
}
|
package com.analise.credito.module.domain.mensagemanalisecredito;
public enum StatusContaCartao {
CRIADA, REJEITADA
}
|
/*
* Copyright 2000-2014 Vaadin Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.vaadin.ui;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.jsoup.nodes.Attributes;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import com.vaadin.event.LayoutEvents.LayoutClickEvent;
import com.vaadin.event.LayoutEvents.LayoutClickListener;
import com.vaadin.event.LayoutEvents.LayoutClickNotifier;
import com.vaadin.server.PaintException;
import com.vaadin.server.PaintTarget;
import com.vaadin.shared.Connector;
import com.vaadin.shared.EventId;
import com.vaadin.shared.MouseEventDetails;
import com.vaadin.shared.ui.MarginInfo;
import com.vaadin.shared.ui.gridlayout.GridLayoutServerRpc;
import com.vaadin.shared.ui.gridlayout.GridLayoutState;
import com.vaadin.shared.ui.gridlayout.GridLayoutState.ChildComponentData;
import com.vaadin.ui.declarative.DesignAttributeHandler;
import com.vaadin.ui.declarative.DesignContext;
/**
* A layout where the components are laid out on a grid using cell coordinates.
*
* <p>
* The GridLayout also maintains a cursor for adding components in
* left-to-right, top-to-bottom order.
* </p>
*
* <p>
* Each component in a <code>GridLayout</code> uses a defined
* {@link GridLayout.Area area} (column1,row1,column2,row2) from the grid. The
* components may not overlap with the existing components - if you try to do so
* you will get an {@link OverlapsException}. Adding a component with cursor
* automatically extends the grid by increasing the grid height.
* </p>
*
* <p>
* The grid coordinates, which are specified by a row and column index, always
* start from 0 for the topmost row and the leftmost column.
* </p>
*
* @author Vaadin Ltd.
* @since 3.0
*/
@SuppressWarnings("serial")
public class GridLayout extends AbstractLayout implements
Layout.AlignmentHandler, Layout.SpacingHandler, Layout.MarginHandler,
LayoutClickNotifier, LegacyComponent {
private GridLayoutServerRpc rpc = new GridLayoutServerRpc() {
@Override
public void layoutClick(MouseEventDetails mouseDetails,
Connector clickedConnector) {
fireEvent(LayoutClickEvent.createEvent(GridLayout.this,
mouseDetails, clickedConnector));
}
};
/**
* Cursor X position: this is where the next component with unspecified x,y
* is inserted
*/
private int cursorX = 0;
/**
* Cursor Y position: this is where the next component with unspecified x,y
* is inserted
*/
private int cursorY = 0;
private final LinkedList<Component> components = new LinkedList<Component>();
private Map<Integer, Float> columnExpandRatio = new HashMap<Integer, Float>();
private Map<Integer, Float> rowExpandRatio = new HashMap<Integer, Float>();
private Alignment defaultComponentAlignment = Alignment.TOP_LEFT;
/**
* Constructor for a grid of given size (number of columns and rows).
*
* The grid may grow or shrink later. Grid grows automatically if you add
* components outside its area.
*
* @param columns
* Number of columns in the grid.
* @param rows
* Number of rows in the grid.
*/
public GridLayout(int columns, int rows) {
setColumns(columns);
setRows(rows);
registerRpc(rpc);
}
/**
* Constructs an empty (1x1) grid layout that is extended as needed.
*/
public GridLayout() {
this(1, 1);
}
/**
* Constructs a GridLayout of given size (number of columns and rows) and
* adds the given components in order to the grid.
*
* @see #addComponents(Component...)
*
* @param columns
* Number of columns in the grid.
* @param rows
* Number of rows in the grid.
* @param children
* Components to add to the grid.
*/
public GridLayout(int columns, int rows, Component... children) {
this(columns, rows);
addComponents(children);
}
@Override
protected GridLayoutState getState() {
return (GridLayoutState) super.getState();
}
@Override
protected GridLayoutState getState(boolean markAsDirty) {
return (GridLayoutState) super.getState(markAsDirty);
}
/**
* <p>
* Adds a component to the grid in the specified area. The area is defined
* by specifying the upper left corner (column1, row1) and the lower right
* corner (column2, row2) of the area. The coordinates are zero-based.
* </p>
*
* <p>
* If the area overlaps with any of the existing components already present
* in the grid, the operation will fail and an {@link OverlapsException} is
* thrown.
* </p>
*
* @param component
* the component to be added, not <code>null</code>.
* @param column1
* the column of the upper left corner of the area <code>c</code>
* is supposed to occupy. The leftmost column has index 0.
* @param row1
* the row of the upper left corner of the area <code>c</code> is
* supposed to occupy. The topmost row has index 0.
* @param column2
* the column of the lower right corner of the area
* <code>c</code> is supposed to occupy.
* @param row2
* the row of the lower right corner of the area <code>c</code>
* is supposed to occupy.
* @throws OverlapsException
* if the new component overlaps with any of the components
* already in the grid.
* @throws OutOfBoundsException
* if the cells are outside the grid area.
*/
public void addComponent(Component component, int column1, int row1,
int column2, int row2) throws OverlapsException,
OutOfBoundsException {
if (component == null) {
throw new NullPointerException("Component must not be null");
}
// Checks that the component does not already exist in the container
if (components.contains(component)) {
throw new IllegalArgumentException(
"Component is already in the container");
}
// Creates the area
final Area area = new Area(component, column1, row1, column2, row2);
// Checks the validity of the coordinates
if (column2 < column1 || row2 < row1) {
throw new IllegalArgumentException(
"Illegal coordinates for the component");
}
if (column1 < 0 || row1 < 0 || column2 >= getColumns()
|| row2 >= getRows()) {
throw new OutOfBoundsException(area);
}
// Checks that newItem does not overlap with existing items
checkExistingOverlaps(area);
// Inserts the component to right place at the list
// Respect top-down, left-right ordering
// component.setParent(this);
final Iterator<Component> i = components.iterator();
final Map<Connector, ChildComponentData> childDataMap = getState().childData;
int index = 0;
boolean done = false;
while (!done && i.hasNext()) {
final ChildComponentData existingArea = childDataMap.get(i.next());
if ((existingArea.row1 >= row1 && existingArea.column1 > column1)
|| existingArea.row1 > row1) {
components.add(index, component);
done = true;
}
index++;
}
if (!done) {
components.addLast(component);
}
childDataMap.put(component, area.childData);
// Attempt to add to super
try {
super.addComponent(component);
} catch (IllegalArgumentException e) {
childDataMap.remove(component);
components.remove(component);
throw e;
}
// update cursor position, if it's within this area; use first position
// outside this area, even if it's occupied
if (cursorX >= column1 && cursorX <= column2 && cursorY >= row1
&& cursorY <= row2) {
// cursor within area
cursorX = column2 + 1; // one right of area
if (cursorX >= getColumns()) {
// overflowed columns
cursorX = 0; // first col
// move one row down, or one row under the area
cursorY = (column1 == 0 ? row2 : row1) + 1;
} else {
cursorY = row1;
}
}
}
/**
* Tests if the given area overlaps with any of the items already on the
* grid.
*
* @param area
* the Area to be checked for overlapping.
* @throws OverlapsException
* if <code>area</code> overlaps with any existing area.
*/
private void checkExistingOverlaps(Area area) throws OverlapsException {
for (Entry<Connector, ChildComponentData> entry : getState().childData
.entrySet()) {
if (componentsOverlap(entry.getValue(), area.childData)) {
// Component not added, overlaps with existing component
throw new OverlapsException(new Area(entry.getValue(),
(Component) entry.getKey()));
}
}
}
/**
* Adds the component to the grid in cells column1,row1 (NortWest corner of
* the area.) End coordinates (SouthEast corner of the area) are the same as
* column1,row1. The coordinates are zero-based. Component width and height
* is 1.
*
* @param component
* the component to be added, not <code>null</code>.
* @param column
* the column index, starting from 0.
* @param row
* the row index, starting from 0.
* @throws OverlapsException
* if the new component overlaps with any of the components
* already in the grid.
* @throws OutOfBoundsException
* if the cell is outside the grid area.
*/
public void addComponent(Component component, int column, int row)
throws OverlapsException, OutOfBoundsException {
this.addComponent(component, column, row, column, row);
}
/**
* Forces the next component to be added at the beginning of the next line.
*
* <p>
* Sets the cursor column to 0 and increments the cursor row by one.
* </p>
*
* <p>
* By calling this function you can ensure that no more components are added
* right of the previous component.
* </p>
*
* @see #space()
*/
public void newLine() {
cursorX = 0;
cursorY++;
}
/**
* Moves the cursor forward by one. If the cursor goes out of the right grid
* border, it is moved to the first column of the next row.
*
* @see #newLine()
*/
public void space() {
cursorX++;
if (cursorX >= getColumns()) {
cursorX = 0;
cursorY++;
}
}
/**
* Adds the component into this container to the cursor position. If the
* cursor position is already occupied, the cursor is moved forwards to find
* free position. If the cursor goes out from the bottom of the grid, the
* grid is automatically extended.
*
* @param component
* the component to be added, not <code>null</code>.
*/
@Override
public void addComponent(Component component) {
if (component == null) {
throw new IllegalArgumentException("Component must not be null");
}
// Finds first available place from the grid
Area area;
boolean done = false;
while (!done) {
try {
area = new Area(component, cursorX, cursorY, cursorX, cursorY);
checkExistingOverlaps(area);
done = true;
} catch (final OverlapsException e) {
space();
}
}
// Extends the grid if needed
if (cursorX >= getColumns()) {
setColumns(cursorX + 1);
}
if (cursorY >= getRows()) {
setRows(cursorY + 1);
}
addComponent(component, cursorX, cursorY);
}
/**
* Removes the specified component from the layout.
*
* @param component
* the component to be removed.
*/
@Override
public void removeComponent(Component component) {
// Check that the component is contained in the container
if (component == null || !components.contains(component)) {
return;
}
getState().childData.remove(component);
components.remove(component);
super.removeComponent(component);
}
/**
* Removes the component specified by its cell coordinates.
*
* @param column
* the component's column, starting from 0.
* @param row
* the component's row, starting from 0.
*/
public void removeComponent(int column, int row) {
// Finds the area
for (final Iterator<Component> i = components.iterator(); i.hasNext();) {
final Component component = i.next();
final ChildComponentData childData = getState().childData
.get(component);
if (childData.column1 == column && childData.row1 == row) {
removeComponent(component);
return;
}
}
}
/**
* Gets an Iterator for the components contained in the layout. By using the
* Iterator it is possible to step through the contents of the layout.
*
* @return the Iterator of the components inside the layout.
*/
@Override
public Iterator<Component> iterator() {
return Collections.unmodifiableCollection(components).iterator();
}
/**
* Gets the number of components contained in the layout. Consistent with
* the iterator returned by {@link #getComponentIterator()}.
*
* @return the number of contained components
*/
@Override
public int getComponentCount() {
return components.size();
}
@Override
public void changeVariables(Object source, Map<String, Object> variables) {
// TODO Remove once LegacyComponent is no longer implemented
}
/**
* Paints the contents of this component.
*
* @param target
* the Paint Event.
* @throws PaintException
* if the paint operation failed.
*/
@Override
public void paintContent(PaintTarget target) throws PaintException {
final Integer[] columnExpandRatioArray = new Integer[getColumns()];
final Integer[] rowExpandRatioArray = new Integer[getRows()];
int realColExpandRatioSum = 0;
float colSum = getExpandRatioSum(columnExpandRatio);
if (colSum == 0) {
// no columns has been expanded, all cols have same expand
// rate
float equalSize = 1 / (float) getColumns();
int myRatio = Math.round(equalSize * 1000);
for (int i = 0; i < getColumns(); i++) {
columnExpandRatioArray[i] = myRatio;
}
realColExpandRatioSum = myRatio * getColumns();
} else {
for (int i = 0; i < getColumns(); i++) {
int myRatio = Math
.round((getColumnExpandRatio(i) / colSum) * 1000);
columnExpandRatioArray[i] = myRatio;
realColExpandRatioSum += myRatio;
}
}
int realRowExpandRatioSum = 0;
float rowSum = getExpandRatioSum(rowExpandRatio);
if (rowSum == 0) {
// no rows have been expanded
float equalSize = 1 / (float) getRows();
int myRatio = Math.round(equalSize * 1000);
for (int i = 0; i < getRows(); i++) {
rowExpandRatioArray[i] = myRatio;
}
realRowExpandRatioSum = myRatio * getRows();
} else {
for (int cury = 0; cury < getRows(); cury++) {
int myRatio = Math
.round((getRowExpandRatio(cury) / rowSum) * 1000);
rowExpandRatioArray[cury] = myRatio;
realRowExpandRatioSum += myRatio;
}
}
// correct possible rounding error
if (rowExpandRatioArray.length > 0) {
rowExpandRatioArray[0] -= realRowExpandRatioSum - 1000;
}
if (columnExpandRatioArray.length > 0) {
columnExpandRatioArray[0] -= realColExpandRatioSum - 1000;
}
target.addAttribute("colExpand", columnExpandRatioArray);
target.addAttribute("rowExpand", rowExpandRatioArray);
}
private float getExpandRatioSum(Map<Integer, Float> ratioMap) {
float sum = 0;
for (Iterator<Entry<Integer, Float>> iterator = ratioMap.entrySet()
.iterator(); iterator.hasNext();) {
sum += iterator.next().getValue();
}
return sum;
}
/*
* (non-Javadoc)
*
* @see com.vaadin.ui.Layout.AlignmentHandler#getComponentAlignment(com
* .vaadin.ui.Component)
*/
@Override
public Alignment getComponentAlignment(Component childComponent) {
ChildComponentData childComponentData = getState(false).childData
.get(childComponent);
if (childComponentData == null) {
throw new IllegalArgumentException(
"The given component is not a child of this layout");
} else {
return new Alignment(childComponentData.alignment);
}
}
/**
* Defines a rectangular area of cells in a GridLayout.
*
* <p>
* Also maintains a reference to the component contained in the area.
* </p>
*
* <p>
* The area is specified by the cell coordinates of its upper left corner
* (column1,row1) and lower right corner (column2,row2). As otherwise with
* GridLayout, the column and row coordinates start from zero.
* </p>
*
* @author Vaadin Ltd.
* @since 3.0
*/
public class Area implements Serializable {
private final ChildComponentData childData;
private final Component component;
/**
* <p>
* Construct a new area on a grid.
* </p>
*
* @param component
* the component connected to the area.
* @param column1
* The column of the upper left corner cell of the area. The
* leftmost column has index 0.
* @param row1
* The row of the upper left corner cell of the area. The
* topmost row has index 0.
* @param column2
* The column of the lower right corner cell of the area. The
* leftmost column has index 0.
* @param row2
* The row of the lower right corner cell of the area. The
* topmost row has index 0.
*/
public Area(Component component, int column1, int row1, int column2,
int row2) {
this.component = component;
childData = new ChildComponentData();
childData.alignment = getDefaultComponentAlignment().getBitMask();
childData.column1 = column1;
childData.row1 = row1;
childData.column2 = column2;
childData.row2 = row2;
}
public Area(ChildComponentData childData, Component component) {
this.childData = childData;
this.component = component;
}
/**
* Tests if this Area overlaps with another Area.
*
* @param other
* the other Area that is to be tested for overlap with this
* area
* @return <code>true</code> if <code>other</code> area overlaps with
* this on, <code>false</code> if it does not.
*/
public boolean overlaps(Area other) {
return componentsOverlap(childData, other.childData);
}
/**
* Gets the component connected to the area.
*
* @return the Component.
*/
public Component getComponent() {
return component;
}
/**
* Gets the column of the top-left corner cell.
*
* @return the column of the top-left corner cell.
*/
public int getColumn1() {
return childData.column1;
}
/**
* Gets the column of the bottom-right corner cell.
*
* @return the column of the bottom-right corner cell.
*/
public int getColumn2() {
return childData.column2;
}
/**
* Gets the row of the top-left corner cell.
*
* @return the row of the top-left corner cell.
*/
public int getRow1() {
return childData.row1;
}
/**
* Gets the row of the bottom-right corner cell.
*
* @return the row of the bottom-right corner cell.
*/
public int getRow2() {
return childData.row2;
}
}
private static boolean componentsOverlap(ChildComponentData a,
ChildComponentData b) {
return a.column1 <= b.column2 && a.row1 <= b.row2
&& a.column2 >= b.column1 && a.row2 >= b.row1;
}
/**
* Gridlayout does not support laying components on top of each other. An
* <code>OverlapsException</code> is thrown when a component already exists
* (even partly) at the same space on a grid with the new component.
*
* @author Vaadin Ltd.
* @since 3.0
*/
public class OverlapsException extends java.lang.RuntimeException {
private final Area existingArea;
/**
* Constructs an <code>OverlapsException</code>.
*
* @param existingArea
*/
public OverlapsException(Area existingArea) {
this.existingArea = existingArea;
}
@Override
public String getMessage() {
StringBuilder sb = new StringBuilder();
Component component = existingArea.getComponent();
sb.append(component);
sb.append("( type = ");
sb.append(component.getClass().getName());
if (component.getCaption() != null) {
sb.append(", caption = \"");
sb.append(component.getCaption());
sb.append("\"");
}
sb.append(")");
sb.append(" is already added to ");
sb.append(existingArea.childData.column1);
sb.append(",");
sb.append(existingArea.childData.column1);
sb.append(",");
sb.append(existingArea.childData.row1);
sb.append(",");
sb.append(existingArea.childData.row2);
sb.append("(column1, column2, row1, row2).");
return sb.toString();
}
/**
* Gets the area .
*
* @return the existing area.
*/
public Area getArea() {
return existingArea;
}
}
/**
* An <code>Exception</code> object which is thrown when an area exceeds the
* bounds of the grid.
*
* @author Vaadin Ltd.
* @since 3.0
*/
public class OutOfBoundsException extends java.lang.RuntimeException {
private final Area areaOutOfBounds;
/**
* Constructs an <code>OoutOfBoundsException</code> with the specified
* detail message.
*
* @param areaOutOfBounds
*/
public OutOfBoundsException(Area areaOutOfBounds) {
this.areaOutOfBounds = areaOutOfBounds;
}
/**
* Gets the area that is out of bounds.
*
* @return the area out of Bound.
*/
public Area getArea() {
return areaOutOfBounds;
}
}
/**
* Sets the number of columns in the grid. The column count can not be
* reduced if there are any areas that would be outside of the shrunk grid.
*
* @param columns
* the new number of columns in the grid.
*/
public void setColumns(int columns) {
// The the param
if (columns < 1) {
throw new IllegalArgumentException(
"The number of columns and rows in the grid must be at least 1");
}
// In case of no change
if (getColumns() == columns) {
return;
}
// Checks for overlaps
if (getColumns() > columns) {
for (Entry<Connector, ChildComponentData> entry : getState().childData
.entrySet()) {
if (entry.getValue().column2 >= columns) {
throw new OutOfBoundsException(new Area(entry.getValue(),
(Component) entry.getKey()));
}
}
}
// Forget expands for removed columns
if (columns < getColumns()) {
for (int i = columns - 1; i < getColumns(); i++) {
columnExpandRatio.remove(i);
getState().explicitColRatios.remove(i);
}
}
getState().columns = columns;
}
/**
* Get the number of columns in the grid.
*
* @return the number of columns in the grid.
*/
public int getColumns() {
return getState(false).columns;
}
/**
* Sets the number of rows in the grid. The number of rows can not be
* reduced if there are any areas that would be outside of the shrunk grid.
*
* @param rows
* the new number of rows in the grid.
*/
public void setRows(int rows) {
// The the param
if (rows < 1) {
throw new IllegalArgumentException(
"The number of columns and rows in the grid must be at least 1");
}
// In case of no change
if (getRows() == rows) {
return;
}
// Checks for overlaps
if (getRows() > rows) {
for (Entry<Connector, ChildComponentData> entry : getState().childData
.entrySet()) {
if (entry.getValue().row2 >= rows) {
throw new OutOfBoundsException(new Area(entry.getValue(),
(Component) entry.getKey()));
}
}
}
// Forget expands for removed rows
if (rows < getRows()) {
for (int i = rows - 1; i < getRows(); i++) {
rowExpandRatio.remove(i);
getState().explicitRowRatios.remove(i);
}
}
getState().rows = rows;
}
/**
* Get the number of rows in the grid.
*
* @return the number of rows in the grid.
*/
public int getRows() {
return getState(false).rows;
}
/**
* Gets the current x-position (column) of the cursor.
*
* <p>
* The cursor position points the position for the next component that is
* added without specifying its coordinates (grid cell). When the cursor
* position is occupied, the next component will be added to first free
* position after the cursor.
* </p>
*
* @return the grid column the cursor is on, starting from 0.
*/
public int getCursorX() {
return cursorX;
}
/**
* Sets the current cursor x-position. This is usually handled automatically
* by GridLayout.
*
* @param cursorX
*/
public void setCursorX(int cursorX) {
this.cursorX = cursorX;
}
/**
* Gets the current y-position (row) of the cursor.
*
* <p>
* The cursor position points the position for the next component that is
* added without specifying its coordinates (grid cell). When the cursor
* position is occupied, the next component will be added to the first free
* position after the cursor.
* </p>
*
* @return the grid row the Cursor is on.
*/
public int getCursorY() {
return cursorY;
}
/**
* Sets the current y-coordinate (row) of the cursor. This is usually
* handled automatically by GridLayout.
*
* @param cursorY
* the row number, starting from 0 for the topmost row.
*/
public void setCursorY(int cursorY) {
this.cursorY = cursorY;
}
/* Documented in superclass */
@Override
public void replaceComponent(Component oldComponent, Component newComponent) {
// Gets the locations
ChildComponentData oldLocation = getState().childData.get(oldComponent);
ChildComponentData newLocation = getState().childData.get(newComponent);
if (oldLocation == null) {
addComponent(newComponent);
} else if (newLocation == null) {
removeComponent(oldComponent);
addComponent(newComponent, oldLocation.column1, oldLocation.row1,
oldLocation.column2, oldLocation.row2);
} else {
int oldAlignment = oldLocation.alignment;
oldLocation.alignment = newLocation.alignment;
newLocation.alignment = oldAlignment;
getState().childData.put(newComponent, oldLocation);
getState().childData.put(oldComponent, newLocation);
}
}
/*
* Removes all components from this container.
*
* @see com.vaadin.ui.ComponentContainer#removeAllComponents()
*/
@Override
public void removeAllComponents() {
super.removeAllComponents();
cursorX = 0;
cursorY = 0;
}
@Override
public void setComponentAlignment(Component childComponent,
Alignment alignment) {
ChildComponentData childComponentData = getState().childData
.get(childComponent);
if (childComponentData == null) {
throw new IllegalArgumentException(
"Component must be added to layout before using setComponentAlignment()");
} else {
if (alignment == null) {
childComponentData.alignment = GridLayoutState.ALIGNMENT_DEFAULT
.getBitMask();
} else {
childComponentData.alignment = alignment.getBitMask();
}
}
}
/*
* (non-Javadoc)
*
* @see com.vaadin.ui.Layout.SpacingHandler#setSpacing(boolean)
*/
@Override
public void setSpacing(boolean spacing) {
getState().spacing = spacing;
}
/*
* (non-Javadoc)
*
* @see com.vaadin.ui.Layout.SpacingHandler#isSpacing()
*/
@Override
public boolean isSpacing() {
return getState(false).spacing;
}
/**
* Inserts an empty row at the specified position in the grid.
*
* @param row
* Index of the row before which the new row will be inserted.
* The leftmost row has index 0.
*/
public void insertRow(int row) {
if (row > getRows()) {
throw new IllegalArgumentException("Cannot insert row at " + row
+ " in a gridlayout with height " + getRows());
}
for (ChildComponentData existingArea : getState().childData.values()) {
// Areas ending below the row needs to be moved down or stretched
if (existingArea.row2 >= row) {
existingArea.row2++;
// Stretch areas that span over the selected row
if (existingArea.row1 >= row) {
existingArea.row1++;
}
}
}
if (cursorY >= row) {
cursorY++;
}
setRows(getRows() + 1);
markAsDirty();
}
/**
* Removes a row and all the components in the row.
*
* <p>
* Components which span over several rows are removed if the selected row
* is on the first row of such a component.
* </p>
*
* <p>
* If the last row is removed then all remaining components will be removed
* and the grid will be reduced to one row. The cursor will be moved to the
* upper left cell of the grid.
* </p>
*
* @param row
* Index of the row to remove. The leftmost row has index 0.
*/
public void removeRow(int row) {
if (row >= getRows()) {
throw new IllegalArgumentException("Cannot delete row " + row
+ " from a gridlayout with height " + getRows());
}
// Remove all components in row
for (int col = 0; col < getColumns(); col++) {
removeComponent(col, row);
}
// Shrink or remove areas in the selected row
for (ChildComponentData existingArea : getState().childData.values()) {
if (existingArea.row2 >= row) {
existingArea.row2--;
if (existingArea.row1 > row) {
existingArea.row1--;
}
}
}
if (getRows() == 1) {
/*
* Removing the last row means that the dimensions of the Grid
* layout will be truncated to 1 empty row and the cursor is moved
* to the first cell
*/
cursorX = 0;
cursorY = 0;
} else {
setRows(getRows() - 1);
if (cursorY > row) {
cursorY--;
}
}
markAsDirty();
}
/**
* Sets the expand ratio of given column.
*
* <p>
* The expand ratio defines how excess space is distributed among columns.
* Excess space means space that is left over from components that are not
* sized relatively. By default, the excess space is distributed evenly.
* </p>
*
* <p>
* Note that the component width of the GridLayout must be defined (fixed or
* relative, as opposed to undefined) for this method to have any effect.
* </p>
*
* @see #setWidth(float, int)
*
* @param columnIndex
* @param ratio
*/
public void setColumnExpandRatio(int columnIndex, float ratio) {
columnExpandRatio.put(columnIndex, ratio);
getState().explicitColRatios.add(columnIndex);
markAsDirty();
}
/**
* Returns the expand ratio of given column
*
* @see #setColumnExpandRatio(int, float)
*
* @param columnIndex
* @return the expand ratio, 0.0f by default
*/
public float getColumnExpandRatio(int columnIndex) {
Float r = columnExpandRatio.get(columnIndex);
return r == null ? 0 : r.floatValue();
}
/**
* Sets the expand ratio of given row.
*
* <p>
* Expand ratio defines how excess space is distributed among rows. Excess
* space means the space left over from components that are not sized
* relatively. By default, the excess space is distributed evenly.
* </p>
*
* <p>
* Note, that height needs to be defined (fixed or relative, as opposed to
* undefined height) for this method to have any effect.
* </p>
*
* @see #setHeight(float, int)
*
* @param rowIndex
* The row index, starting from 0 for the topmost row.
* @param ratio
*/
public void setRowExpandRatio(int rowIndex, float ratio) {
rowExpandRatio.put(rowIndex, ratio);
getState().explicitRowRatios.add(rowIndex);
markAsDirty();
}
/**
* Returns the expand ratio of given row.
*
* @see #setRowExpandRatio(int, float)
*
* @param rowIndex
* The row index, starting from 0 for the topmost row.
* @return the expand ratio, 0.0f by default
*/
public float getRowExpandRatio(int rowIndex) {
Float r = rowExpandRatio.get(rowIndex);
return r == null ? 0 : r.floatValue();
}
/**
* Gets the Component at given index.
*
* @param x
* The column index, starting from 0 for the leftmost column.
* @param y
* The row index, starting from 0 for the topmost row.
* @return Component in given cell or null if empty
*/
public Component getComponent(int x, int y) {
for (Entry<Connector, ChildComponentData> entry : getState(false).childData
.entrySet()) {
ChildComponentData childData = entry.getValue();
if (childData.column1 <= x && x <= childData.column2
&& childData.row1 <= y && y <= childData.row2) {
return (Component) entry.getKey();
}
}
return null;
}
/**
* Returns information about the area where given component is laid in the
* GridLayout.
*
* @param component
* the component whose area information is requested.
* @return an Area object that contains information how component is laid in
* the grid
*/
public Area getComponentArea(Component component) {
ChildComponentData childComponentData = getState(false).childData
.get(component);
if (childComponentData == null) {
return null;
} else {
return new Area(childComponentData, component);
}
}
@Override
public void addLayoutClickListener(LayoutClickListener listener) {
addListener(EventId.LAYOUT_CLICK_EVENT_IDENTIFIER,
LayoutClickEvent.class, listener,
LayoutClickListener.clickMethod);
}
/**
* @deprecated As of 7.0, replaced by
* {@link #addLayoutClickListener(LayoutClickListener)}
**/
@Override
@Deprecated
public void addListener(LayoutClickListener listener) {
addLayoutClickListener(listener);
}
@Override
public void removeLayoutClickListener(LayoutClickListener listener) {
removeListener(EventId.LAYOUT_CLICK_EVENT_IDENTIFIER,
LayoutClickEvent.class, listener);
}
/**
* @deprecated As of 7.0, replaced by
* {@link #removeLayoutClickListener(LayoutClickListener)}
**/
@Override
@Deprecated
public void removeListener(LayoutClickListener listener) {
removeLayoutClickListener(listener);
}
/*
* (non-Javadoc)
*
* @see com.vaadin.ui.Layout.MarginHandler#setMargin(boolean)
*/
@Override
public void setMargin(boolean enabled) {
setMargin(new MarginInfo(enabled));
}
/*
* (non-Javadoc)
*
* @see
* com.vaadin.ui.Layout.MarginHandler#setMargin(com.vaadin.shared.ui.MarginInfo
* )
*/
@Override
public void setMargin(MarginInfo marginInfo) {
getState().marginsBitmask = marginInfo.getBitMask();
}
/*
* (non-Javadoc)
*
* @see com.vaadin.ui.Layout.MarginHandler#getMargin()
*/
@Override
public MarginInfo getMargin() {
return new MarginInfo(getState(false).marginsBitmask);
}
/*
* (non-Javadoc)
*
* @see com.vaadin.ui.Layout.AlignmentHandler#getDefaultComponentAlignment()
*/
@Override
public Alignment getDefaultComponentAlignment() {
return defaultComponentAlignment;
}
/*
* (non-Javadoc)
*
* @see
* com.vaadin.ui.Layout.AlignmentHandler#setDefaultComponentAlignment(com
* .vaadin.ui.Alignment)
*/
@Override
public void setDefaultComponentAlignment(Alignment defaultAlignment) {
defaultComponentAlignment = defaultAlignment;
}
/**
* Sets whether empty rows and columns should be considered as non-existent
* when rendering or not. If this is set to true then the spacing between
* multiple empty columns (or rows) will be collapsed.
*
* The default behavior is to consider all rows and columns as visible
*
* NOTE that this must be set before the initial rendering takes place.
* Updating this on the fly is not supported.
*
* @since 7.3
* @param hideEmptyRowsAndColumns
* true to hide empty rows and columns, false to leave them as-is
*/
public void setHideEmptyRowsAndColumns(boolean hideEmptyRowsAndColumns) {
getState().hideEmptyRowsAndColumns = hideEmptyRowsAndColumns;
}
/**
* Checks whether whether empty rows and columns should be considered as
* non-existent when rendering or not.
*
* @see #setHideEmptyRowsAndColumns(boolean)
* @since 7.3
* @return true if empty rows and columns are hidden, false otherwise
*/
public boolean isHideEmptyRowsAndColumns() {
return getState(false).hideEmptyRowsAndColumns;
}
/**
* {@inheritDoc}
* <p>
* After reading the design, cursorY is set to point to a row outside of the
* GridLayout area. CursorX is reset to 0.
*/
@Override
public void readDesign(Element design, DesignContext designContext) {
super.readDesign(design, designContext);
setMargin(readMargin(design, getMargin(), designContext));
List<Element> rowElements = new ArrayList<Element>();
List<Map<Integer, Component>> rows = new ArrayList<Map<Integer, Component>>();
// Prepare a 2D map for reading column contents
for (Element e : design.children()) {
if (e.tagName().equalsIgnoreCase("row")) {
rowElements.add(e);
rows.add(new HashMap<Integer, Component>());
}
}
setRows(Math.max(rows.size(), 1));
List<Integer> columnExpandRatios = new ArrayList<Integer>();
for (int row = 0; row < rowElements.size(); ++row) {
Element rowElement = rowElements.get(row);
// Row Expand
if (rowElement.hasAttr("expand")) {
int expand = DesignAttributeHandler.readAttribute("expand",
rowElement.attributes(), int.class);
setRowExpandRatio(row, expand);
}
Elements cols = rowElement.children();
// Amount of skipped columns due to spanned components
int skippedColumns = 0;
for (int column = 0; column < cols.size(); ++column) {
while (rows.get(row).containsKey(column + skippedColumns)) {
// Skip any spanned components
skippedColumns++;
}
Element col = cols.get(column);
Component child = null;
if (col.children().size() > 0) {
child = designContext.readDesign(col.child(0));
// TODO: Currently ignoring any extra children.
// Needs Error handling?
} // Else: Empty placeholder. No child component.
// Handle rowspan and colspan for this child component
Attributes attr = col.attributes();
int colspan = DesignAttributeHandler.readAttribute("colspan",
attr, 1, int.class);
int rowspan = DesignAttributeHandler.readAttribute("rowspan",
attr, 1, int.class);
for (int rowIndex = row; rowIndex < row + rowspan; ++rowIndex) {
for (int colIndex = column; colIndex < column + colspan; ++colIndex) {
if (rowIndex == rows.size()) {
// Rowspan with not enough rows. Fix by adding rows.
rows.add(new HashMap<Integer, Component>());
}
rows.get(rowIndex)
.put(colIndex + skippedColumns, child);
}
}
// Read column expand ratios if handling the first row.
if (row == 0) {
if (col.hasAttr("expand")) {
for (String expand : col.attr("expand").split(",")) {
columnExpandRatios.add(Integer.parseInt(expand));
}
} else {
for (int c = 0; c < colspan; ++c) {
columnExpandRatios.add(0);
}
}
}
skippedColumns += (colspan - 1);
}
}
// Calculate highest column count and set columns
int colMax = 0;
for (Map<Integer, Component> cols : rows) {
if (colMax < cols.size()) {
colMax = cols.size();
}
}
setColumns(Math.max(colMax, 1));
for (int i = 0; i < columnExpandRatios.size(); ++i) {
setColumnExpandRatio(i, columnExpandRatios.get(i));
}
// Reiterate through the 2D map and add components to GridLayout
Set<Component> visited = new HashSet<Component>();
// Ignore any missing components
visited.add(null);
for (int i = 0; i < rows.size(); ++i) {
Map<Integer, Component> row = rows.get(i);
for (int j = 0; j < colMax; ++j) {
Component child = row.get(j);
if (visited.contains(child)) {
// Empty location or already handled child
continue;
}
visited.add(child);
// Figure out col and rowspan from 2D map
int colspan = 0;
while (j + colspan + 1 < row.size()
&& row.get(j + colspan + 1) == child) {
++colspan;
}
int rowspan = 0;
while (i + rowspan + 1 < rows.size()
&& rows.get(i + rowspan + 1).get(j) == child) {
++rowspan;
}
// Add component with area
addComponent(child, j, i, j + colspan, i + rowspan);
}
}
// Set cursor position explicitly
setCursorY(getRows());
setCursorX(0);
}
@Override
public void writeDesign(Element design, DesignContext designContext) {
super.writeDesign(design, designContext);
GridLayout def = designContext.getDefaultInstance(this);
writeMargin(design, getMargin(), def.getMargin(), designContext);
if (components.isEmpty()
|| !designContext.shouldWriteChildren(this, def)) {
return;
}
final Map<Connector, ChildComponentData> childData = getState().childData;
// Make a 2D map of component areas.
Component[][] componentMap = new Component[getState().rows][getState().columns];
final Component dummyComponent = new Label("");
for (Component component : components) {
ChildComponentData coords = childData.get(component);
for (int row = coords.row1; row <= coords.row2; ++row) {
for (int col = coords.column1; col <= coords.column2; ++col) {
componentMap[row][col] = component;
}
}
}
// Go through the map and write only needed column tags
Set<Connector> visited = new HashSet<Connector>();
// Skip the dummy placeholder
visited.add(dummyComponent);
for (int i = 0; i < componentMap.length; ++i) {
Element row = design.appendElement("row");
// Row Expand
DesignAttributeHandler.writeAttribute("expand", row.attributes(),
(int) getRowExpandRatio(i), 0, int.class);
int colspan = 1;
Element col;
for (int j = 0; j < componentMap[i].length; ++j) {
Component child = componentMap[i][j];
if (child != null) {
if (visited.contains(child)) {
// Child has already been written in the design
continue;
}
visited.add(child);
Element childElement = designContext.createElement(child);
col = row.appendElement("column");
// Write child data into design
ChildComponentData coords = childData.get(child);
Alignment alignment = getComponentAlignment(child);
if (alignment.isMiddle()) {
childElement.attr(":middle", "");
} else if (alignment.isBottom()) {
childElement.attr(":bottom", "");
}
if (alignment.isCenter()) {
childElement.attr(":center", "");
} else if (alignment.isRight()) {
childElement.attr(":right", "");
}
col.appendChild(childElement);
if (coords.row1 != coords.row2) {
col.attr("rowspan", ""
+ (1 + coords.row2 - coords.row1));
}
colspan = 1 + coords.column2 - coords.column1;
if (colspan > 1) {
col.attr("colspan", "" + colspan);
}
} else {
boolean hasExpands = false;
if (i == 0
&& lastComponentOnRow(componentMap[i], j, visited)) {
// A column with expand and no content in the end of
// first row needs to be present.
for (int c = j; c < componentMap[i].length; ++c) {
if ((int) getColumnExpandRatio(c) > 0) {
hasExpands = true;
}
}
}
if (lastComponentOnRow(componentMap[i], j, visited)
&& !hasExpands) {
continue;
}
// Empty placeholder tag.
col = row.appendElement("column");
// Use colspan to make placeholders more pleasant
while (j + colspan < componentMap[i].length
&& componentMap[i][j + colspan] == child) {
++colspan;
}
int rowspan = getRowSpan(componentMap, i, j, colspan, child);
if (colspan > 1) {
col.attr("colspan", "" + colspan);
}
if (rowspan > 1) {
col.attr("rowspan", "" + rowspan);
}
for (int x = 0; x < rowspan; ++x) {
for (int y = 0; y < colspan; ++y) {
// Mark handled columns
componentMap[i + x][j + y] = dummyComponent;
}
}
}
// Column expands
if (i == 0) {
// Only do expands on first row
String expands = "";
boolean expandRatios = false;
for (int c = 0; c < colspan; ++c) {
int colExpand = (int) getColumnExpandRatio(j + c);
if (colExpand > 0) {
expandRatios = true;
}
expands += (c > 0 ? "," : "") + colExpand;
}
if (expandRatios) {
col.attr("expand", expands);
}
}
j += colspan - 1;
}
}
}
private int getRowSpan(Component[][] compMap, int i, int j, int colspan,
Component child) {
int rowspan = 1;
while (i + rowspan < compMap.length && compMap[i + rowspan][j] == child) {
for (int k = 0; k < colspan; ++k) {
if (compMap[i + rowspan][j + k] != child) {
return rowspan;
}
}
rowspan++;
}
return rowspan;
}
private boolean lastComponentOnRow(Component[] componentArray, int j,
Set<Connector> visited) {
while ((++j) < componentArray.length) {
Component child = componentArray[j];
if (child != null && !visited.contains(child)) {
return false;
}
}
return true;
}
@Override
protected Collection<String> getCustomAttributes() {
Collection<String> result = super.getCustomAttributes();
result.add("cursor-x");
result.add("cursor-y");
result.add("rows");
result.add("columns");
return result;
}
}
|
/**
* 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 org.apache.flink.streaming.connectors.pulsar;
import lombok.extern.slf4j.Slf4j;
import org.apache.flink.api.common.ExecutionConfig;
import org.apache.flink.api.common.serialization.SerializationSchema;
import org.apache.flink.api.java.ClosureCleaner;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.runtime.state.FunctionInitializationContext;
import org.apache.flink.runtime.state.FunctionSnapshotContext;
import org.apache.flink.shaded.guava18.com.google.common.collect.Maps;
import org.apache.flink.streaming.api.checkpoint.CheckpointedFunction;
import org.apache.flink.streaming.api.functions.sink.RichSinkFunction;
import org.apache.flink.streaming.api.operators.StreamingRuntimeContext;
import org.apache.flink.streaming.connectors.pulsar.internal.CachedPulsarClient;
import org.apache.flink.streaming.connectors.pulsar.internal.PulsarAdminUtils;
import org.apache.flink.streaming.connectors.pulsar.internal.SchemaUtils;
import org.apache.flink.streaming.connectors.pulsar.internal.SourceSinkUtils;
import org.apache.flink.util.ExceptionUtils;
import org.apache.flink.util.SerializableObject;
import org.apache.pulsar.client.admin.PulsarAdmin;
import org.apache.pulsar.client.api.MessageId;
import org.apache.pulsar.client.api.Producer;
import org.apache.pulsar.client.api.PulsarClientException;
import org.apache.pulsar.client.api.Schema;
import org.apache.pulsar.client.impl.conf.ClientConfigurationData;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.Properties;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.function.BiConsumer;
import static org.apache.flink.util.Preconditions.checkNotNull;
/**
* Flink Sink to produce data into Pulsar topics.
*
* <p>Please note that this producer provides at-least-once reliability guarantees when
* checkpoints are enabled and setFlushOnCheckpoint(true) is set.
* Otherwise, the producer doesn't provide any reliability guarantees.
*
* @param <T> Type of the messages to write into Kafka.
*/
@Slf4j
abstract class FlinkPulsarSinkBase<T> extends RichSinkFunction<T> implements CheckpointedFunction {
protected String adminUrl;
protected ClientConfigurationData clientConfigurationData;
protected final Map<String, String> caseInsensitiveParams;
protected final Map<String, Object> producerConf;
protected final Properties properties;
protected boolean flushOnCheckpoint;
protected boolean failOnWrite;
/** Lock for accessing the pending records. */
protected final SerializableObject pendingRecordsLock = new SerializableObject();
/** Number of unacknowledged records. */
protected long pendingRecords = 0L;
protected final boolean forcedTopic;
protected final String defaultTopic;
protected final TopicKeyExtractor<T> topicKeyExtractor;
protected transient volatile Throwable failedWrite;
protected transient PulsarAdmin admin;
protected transient BiConsumer<MessageId, Throwable> sendCallback;
protected transient Producer<?> singleProducer;
protected transient Map<String, Producer<?>> topic2Producer;
protected final SerializationSchema<T> schema;
public FlinkPulsarSinkBase(
String adminUrl,
Optional<String> defaultTopicName,
ClientConfigurationData clientConf,
Properties properties,
TopicKeyExtractor<T> topicKeyExtractor,
SerializationSchema<T> schema) {
this.adminUrl = checkNotNull(adminUrl);
if (defaultTopicName.isPresent()) {
this.forcedTopic = true;
this.defaultTopic = defaultTopicName.get();
this.topicKeyExtractor = null;
} else {
this.forcedTopic = false;
this.defaultTopic = null;
ClosureCleaner.clean(
topicKeyExtractor, ExecutionConfig.ClosureCleanerLevel.RECURSIVE, true);
this.topicKeyExtractor = checkNotNull(topicKeyExtractor);
}
this.clientConfigurationData = clientConf;
this.properties = checkNotNull(properties);
this.caseInsensitiveParams =
SourceSinkUtils.toCaceInsensitiveParams(Maps.fromProperties(properties));
this.producerConf =
SourceSinkUtils.getProducerParams(Maps.fromProperties(properties));
this.flushOnCheckpoint =
SourceSinkUtils.flushOnCheckpoint(caseInsensitiveParams);
this.failOnWrite =
SourceSinkUtils.failOnWrite(caseInsensitiveParams);
CachedPulsarClient.setCacheSize(SourceSinkUtils.getClientCacheSize(caseInsensitiveParams));
if (this.clientConfigurationData.getServiceUrl() == null) {
throw new IllegalArgumentException("ServiceUrl must be supplied in the client configuration");
}
this.schema = schema;
}
public FlinkPulsarSinkBase(
String serviceUrl,
String adminUrl,
Optional<String> defaultTopicName,
Properties properties,
TopicKeyExtractor<T> topicKeyExtractor,
SerializationSchema<T> schema) {
this(adminUrl, defaultTopicName, newClientConf(checkNotNull(serviceUrl)), properties, topicKeyExtractor, schema);
}
protected static ClientConfigurationData newClientConf(String serviceUrl) {
ClientConfigurationData clientConf = new ClientConfigurationData();
clientConf.setServiceUrl(serviceUrl);
return clientConf;
}
@Override
public void snapshotState(FunctionSnapshotContext context) throws Exception {
checkErroneous();
if (flushOnCheckpoint) {
producerFlush();
synchronized (pendingRecordsLock) {
if (pendingRecords != 0) {
throw new IllegalStateException("Pending record count must be zero at this point " + pendingRecords);
}
checkErroneous();
}
}
}
@Override
public void initializeState(FunctionInitializationContext context) throws Exception {
}
protected abstract Schema<?> getPulsarSchema();
@Override
public void open(Configuration parameters) throws Exception {
if (flushOnCheckpoint && !((StreamingRuntimeContext) this.getRuntimeContext()).isCheckpointingEnabled()) {
log.warn("Flushing on checkpoint is enabled, but checkpointing is not enabled. Disabling flushing.");
flushOnCheckpoint = false;
}
admin = PulsarAdminUtils.newAdminFromConf(adminUrl, clientConfigurationData);
if (forcedTopic) {
// uploadSchema(defaultTopic);
singleProducer = createProducer(clientConfigurationData, producerConf, defaultTopic, getPulsarSchema());
} else {
topic2Producer = new HashMap<>();
}
}
protected void initializeSendCallback() {
if (sendCallback != null) {
return;
}
if (failOnWrite) {
this.sendCallback = (t, u) -> {
if (failedWrite == null && u == null) {
acknowledgeMessage();
} else if (failedWrite == null && u != null) {
failedWrite = u;
} else { // failedWrite != null
// do nothing and wait next checkForError to throw exception
}
};
} else {
this.sendCallback = (t, u) -> {
if (failedWrite == null && u != null) {
log.error("Error while sending message to Pulsar: {}", ExceptionUtils.stringifyException(u));
}
acknowledgeMessage();
};
}
}
private void uploadSchema(String topic) {
SchemaUtils.uploadPulsarSchema(admin, topic, getPulsarSchema().getSchemaInfo());
}
@Override
public void close() throws Exception {
checkErroneous();
producerClose();
checkErroneous();
}
protected <R> Producer<R> getProducer(String topic) {
if (forcedTopic) {
return (Producer<R>) singleProducer;
}
if (topic2Producer.containsKey(topic)) {
return (Producer<R>) topic2Producer.get(topic);
} else {
uploadSchema(topic);
Producer p = createProducer(clientConfigurationData, producerConf, topic, getPulsarSchema());
topic2Producer.put(topic, p);
return (Producer<R>) p;
}
}
protected Producer<?> createProducer(
ClientConfigurationData clientConf,
Map<String, Object> producerConf,
String topic,
Schema<?> schema) {
try {
return CachedPulsarClient
.getOrCreate(clientConf)
.newProducer(schema)
.topic(topic)
.batchingMaxPublishDelay(100, TimeUnit.MILLISECONDS)
// maximizing the throughput
.batchingMaxMessages(5 * 1024 * 1024)
.loadConf(producerConf)
.create();
} catch (PulsarClientException e) {
log.error("Failed to create producer for topic {}", topic);
throw new RuntimeException(e);
} catch (ExecutionException e) {
log.error("Failed to getOrCreate a PulsarClient");
throw new RuntimeException(e);
}
}
public void producerFlush() throws Exception {
if (singleProducer != null) {
singleProducer.flush();
} else {
if (topic2Producer != null) {
for (Producer<?> p : topic2Producer.values()) {
p.flush();
}
}
}
synchronized (pendingRecordsLock) {
while (pendingRecords > 0) {
try {
pendingRecordsLock.wait();
} catch (InterruptedException e) {
// this can be interrupted when the Task has been cancelled.
// by throwing an exception, we ensure that this checkpoint doesn't get confirmed
throw new RuntimeException("Flushing got interrupted while checkpointing", e);
}
}
}
}
protected void producerClose() throws Exception {
producerFlush();
if (admin != null) {
admin.close();
}
if (singleProducer != null) {
singleProducer.close();
} else {
if (topic2Producer != null) {
for (Producer<?> p : topic2Producer.values()) {
p.close();
}
topic2Producer.clear();
}
}
}
protected void checkErroneous() throws Exception {
Throwable e = failedWrite;
if (e != null) {
// prevent double throwing
failedWrite = null;
throw new Exception("Failed to send data to Kafka: " + e.getMessage(), e);
}
}
private void acknowledgeMessage() {
if (flushOnCheckpoint) {
synchronized (pendingRecordsLock) {
pendingRecords--;
if (pendingRecords == 0) {
pendingRecordsLock.notifyAll();
}
}
}
}
}
|
package net.ion.exception.message;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class ErrorResponse {
private int errorCode;
private String message;
}
|
package org.javawebstack.abstractdata.exception;
import org.javawebstack.abstractdata.AbstractElement;
public class AbstractCoercingException extends RuntimeException {
public AbstractCoercingException(AbstractElement.Type requested, AbstractElement.Type found) {
this(requested.name(), found);
}
public AbstractCoercingException(String requested, AbstractElement.Type found) {
super("Type '" + found.name() + "' can not be coerced into type '" + requested + "' or strict mode prohibits type coercing");
}
public AbstractCoercingException(AbstractElement.Type requested, AbstractElement found) {
super("Value '" + found.toJsonString() + "' can not be coerced into type '" + requested.name() + "'");
}
}
|
package com.ll.services.tools.rxbus;
/**
* Created by Liujc on 2016/11/20.
* Email: liujiangchuan@hotmail.com
*/
public class RxEventBean
{
public int id;
public Object data;
public RxEventBean(int id, Object data)
{
this.id = id;
this.data = data;
}
}
|
package com.termux.shared.settings.preferences;
/*
* Version: v0.11.0
*
* Changelog
*
* - 0.1.0 (2021-03-12)
* - Initial Release.
*
* - 0.2.0 (2021-03-13)
* - Added `KEY_LOG_LEVEL` and `KEY_TERMINAL_VIEW_LOGGING_ENABLED`.
*
* - 0.3.0 (2021-03-16)
* - Changed to per app scoping of variables so that the same file can store all constants of
* Termux app and its plugins. This will allow {@link com.termux.app.TermuxSettings} to
* manage preferences of plugins as well if they don't have launcher activity themselves
* and also allow plugin apps to make changes to preferences from background.
* - Added following to `TERMUX_TASKER_APP`:
* `KEY_LOG_LEVEL`.
*
* - 0.4.0 (2021-03-13)
* - Added following to `TERMUX_APP`:
* `KEY_PLUGIN_ERROR_NOTIFICATIONS_ENABLED` and `DEFAULT_VALUE_PLUGIN_ERROR_NOTIFICATIONS_ENABLED`.
*
* - 0.5.0 (2021-03-24)
* - Added following to `TERMUX_APP`:
* `KEY_LAST_NOTIFICATION_ID` and `DEFAULT_VALUE_KEY_LAST_NOTIFICATION_ID`.
*
* - 0.6.0 (2021-03-24)
* - Change `DEFAULT_VALUE_KEEP_SCREEN_ON` value to `false` in `TERMUX_APP`.
*
* - 0.7.0 (2021-03-27)
* - Added following to `TERMUX_APP`:
* `KEY_SOFT_KEYBOARD_ENABLED` and `DEFAULT_VALUE_KEY_SOFT_KEYBOARD_ENABLED`.
*
* - 0.8.0 (2021-04-06)
* - Added following to `TERMUX_APP`:
* `KEY_CRASH_REPORT_NOTIFICATIONS_ENABLED` and `DEFAULT_VALUE_CRASH_REPORT_NOTIFICATIONS_ENABLED`.
*
* - 0.9.0 (2021-04-07)
* - Updated javadocs.
*
* - 0.10.0 (2021-05-12)
* - Added following to `TERMUX_APP`:
* `KEY_SOFT_KEYBOARD_ENABLED_ONLY_IF_NO_HARDWARE` and `DEFAULT_VALUE_KEY_SOFT_KEYBOARD_ENABLED_ONLY_IF_NO_HARDWARE`.
*
* - 0.11.0 (2021-07-08)
* - Added following to `TERMUX_APP`:
* `KEY_DISABLE_TERMINAL_MARGIN_ADJUSTMENT`.
*/
/**
* A class that defines shared constants of the SharedPreferences used by Termux app and its plugins.
* This class will be hosted by termux-shared lib and should be imported by other termux plugin
* apps as is instead of copying constants to random classes. The 3rd party apps can also import
* it for interacting with termux apps. If changes are made to this file, increment the version number
* and add an entry in the Changelog section above.
*/
public final class TermuxPreferenceConstants {
/**
* Termux app constants.
*/
public static final class TERMUX_APP {
/**
* Defines the key for whether terminal view margin adjustment that is done to prevent soft
* keyboard from covering bottom part of terminal view on some devices is enabled or not.
* Margin adjustment may cause screen flickering on some devices and so should be disabled.
*/
public static final String KEY_TERMINAL_MARGIN_ADJUSTMENT = "terminal_margin_adjustment";
public static final boolean DEFAULT_TERMINAL_MARGIN_ADJUSTMENT = true;
/**
* Defines the key for whether to show terminal toolbar containing extra keys and text input field.
*/
public static final String KEY_SHOW_TERMINAL_TOOLBAR = "show_extra_keys";
public static final boolean DEFAULT_VALUE_SHOW_TERMINAL_TOOLBAR = true;
/**
* Defines the key for whether the soft keyboard will be enabled, for cases where users want
* to use a hardware keyboard instead.
*/
public static final String KEY_SOFT_KEYBOARD_ENABLED = "soft_keyboard_enabled";
public static final boolean DEFAULT_VALUE_KEY_SOFT_KEYBOARD_ENABLED = true;
/**
* Defines the key for whether the soft keyboard will be enabled only if no hardware keyboard
* attached, for cases where users want to use a hardware keyboard instead.
*/
public static final String KEY_SOFT_KEYBOARD_ENABLED_ONLY_IF_NO_HARDWARE = "soft_keyboard_enabled_only_if_no_hardware";
public static final boolean DEFAULT_VALUE_KEY_SOFT_KEYBOARD_ENABLED_ONLY_IF_NO_HARDWARE = false;
/**
* Defines the key for whether to always keep screen on.
*/
public static final String KEY_KEEP_SCREEN_ON = "screen_always_on";
public static final boolean DEFAULT_VALUE_KEEP_SCREEN_ON = false;
/**
* Defines the key for font size of termux terminal view.
*/
public static final String KEY_FONTSIZE = "fontsize";
/**
* Defines the key for current termux terminal session.
*/
public static final String KEY_CURRENT_SESSION = "current_session";
/**
* Defines the key for current termux log level.
*/
public static final String KEY_LOG_LEVEL = "log_level";
/**
* Defines the key for last used notification id.
*/
public static final String KEY_LAST_NOTIFICATION_ID = "last_notification_id";
public static final int DEFAULT_VALUE_KEY_LAST_NOTIFICATION_ID = 0;
/**
* Defines the key for whether termux terminal view key logging is enabled or not
*/
public static final String KEY_TERMINAL_VIEW_KEY_LOGGING_ENABLED = "terminal_view_key_logging_enabled";
public static final boolean DEFAULT_VALUE_TERMINAL_VIEW_KEY_LOGGING_ENABLED = false;
/**
* Defines the key for whether flashes and notifications for plugin errors are enabled or not.
*/
public static final String KEY_PLUGIN_ERROR_NOTIFICATIONS_ENABLED = "plugin_error_notifications_enabled";
public static final boolean DEFAULT_VALUE_PLUGIN_ERROR_NOTIFICATIONS_ENABLED = true;
/**
* Defines the key for whether notifications for crash reports are enabled or not.
*/
public static final String KEY_CRASH_REPORT_NOTIFICATIONS_ENABLED = "crash_report_notifications_enabled";
public static final boolean DEFAULT_VALUE_CRASH_REPORT_NOTIFICATIONS_ENABLED = true;
}
/**
* Termux Tasker app constants.
*/
public static final class TERMUX_TASKER_APP {
/**
* Defines the key for current termux log level.
*/
public static final String KEY_LOG_LEVEL = "log_level";
}
}
|
package cookiedragon.eventsystem;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.parallel.Execution;
import org.junit.jupiter.api.parallel.ExecutionMode;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.IntStream;
@Execution(ExecutionMode.SAME_THREAD)
public class StressTest {
private static final String event = "";
private static int hits = 0;
@Test
void test() {
final int subs = 1_000;
final int pubs = 1_000;
System.out.println("subs: " + subs);
System.out.println("pubs: " + pubs);
List<Listener> listenerContainers = new ArrayList<>();
IntStream.range(0, subs).forEach(i -> {
listenerContainers.add(new Listener());
});
final long start = System.nanoTime();
IntStream
.range(0, subs)
.forEach(i -> {
EventDispatcher.Companion.register(listenerContainers.get(i));
EventDispatcher.Companion.subscribe(listenerContainers.get(i));
});
IntStream
.range(0, pubs)
.forEach(i -> EventDispatcher.Companion.dispatch(event));
final long end = System.nanoTime() - start;
System.out.println("hits: " + hits);
System.out.printf("%,dns (%,dms)\n", end, end / 1000000);
}
private class Listener {
@Subscriber
private void on(String e) {
hits++;
}
}
}
|
package sunning.democollection.custom.viewgroup.flowlayout;
import android.os.Bundle;
import sunning.democollection.BaseActivity;
import sunning.democollection.R;
/**
* Created by sunning on 16/2/17.
*/
public class FlowActivity extends BaseActivity{
@Override
protected void onCreate(Bundle arg0) {
super.onCreate(arg0);
setContentView(R.layout.flow_layout);
}
}
|
/*
* MIT License
*
* Copyright (c) 2021 MASES s.r.l.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/**************************************************************************************
* <auto-generated>
* This code was generated from a template using JCOReflector
*
* Manual changes to this file may cause unexpected behavior in your application.
* Manual changes to this file will be overwritten if the code is regenerated.
* </auto-generated>
*************************************************************************************/
package system.componentmodel;
import org.mases.jcobridge.*;
import org.mases.jcobridge.netreflection.*;
import java.util.ArrayList;
// Import section
import system.Attribute;
/**
* The base .NET class managing System.ComponentModel.InstallerTypeAttribute, System.ComponentModel.TypeConverter, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a.
* <p>
*
* See: <a href="https://docs.microsoft.com/en-us/dotnet/api/System.ComponentModel.InstallerTypeAttribute" target="_top">https://docs.microsoft.com/en-us/dotnet/api/System.ComponentModel.InstallerTypeAttribute</a>
*/
public class InstallerTypeAttribute extends Attribute {
/**
* Fully assembly qualified name: System.ComponentModel.TypeConverter, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
*/
public static final String assemblyFullName = "System.ComponentModel.TypeConverter, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";
/**
* Assembly name: System.ComponentModel.TypeConverter
*/
public static final String assemblyShortName = "System.ComponentModel.TypeConverter";
/**
* Qualified class name: System.ComponentModel.InstallerTypeAttribute
*/
public static final String className = "System.ComponentModel.InstallerTypeAttribute";
static JCOBridge bridge = JCOBridgeInstance.getInstance(assemblyFullName);
/**
* The type managed from JCOBridge. See {@link JCType}
*/
public static JCType classType = createType();
static JCEnum enumInstance = null;
JCObject classInstance = null;
static JCType createType() {
try {
String classToCreate = className + ", "
+ (JCOReflector.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName);
if (JCOReflector.getDebug())
JCOReflector.writeLog("Creating %s", classToCreate);
JCType typeCreated = bridge.GetType(classToCreate);
if (JCOReflector.getDebug())
JCOReflector.writeLog("Created: %s",
(typeCreated != null) ? typeCreated.toString() : "Returned null value");
return typeCreated;
} catch (JCException e) {
JCOReflector.writeLog(e);
return null;
}
}
void addReference(String ref) throws Throwable {
try {
bridge.AddReference(ref);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
/**
* Internal constructor. Use with caution
*/
public InstallerTypeAttribute(java.lang.Object instance) throws Throwable {
super(instance);
if (instance instanceof JCObject) {
classInstance = (JCObject) instance;
} else
throw new Exception("Cannot manage object, it is not a JCObject");
}
public String getJCOAssemblyName() {
return assemblyFullName;
}
public String getJCOClassName() {
return className;
}
public String getJCOObjectName() {
return className + ", " + (JCOReflector.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName);
}
public java.lang.Object getJCOInstance() {
return classInstance;
}
public void setJCOInstance(JCObject instance) {
classInstance = instance;
super.setJCOInstance(classInstance);
}
public JCType getJCOType() {
return classType;
}
/**
* Try to cast the {@link IJCOBridgeReflected} instance into {@link InstallerTypeAttribute}, a cast assert is made to check if types are compatible.
* @param from {@link IJCOBridgeReflected} instance to be casted
* @return {@link InstallerTypeAttribute} instance
* @throws java.lang.Throwable in case of error during cast operation
*/
public static InstallerTypeAttribute cast(IJCOBridgeReflected from) throws Throwable {
NetType.AssertCast(classType, from);
return new InstallerTypeAttribute(from.getJCOInstance());
}
// Constructors section
public InstallerTypeAttribute() throws Throwable {
}
public InstallerTypeAttribute(java.lang.String typeName) throws Throwable {
try {
// add reference to assemblyName.dll file
addReference(JCOReflector.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName);
setJCOInstance((JCObject)classType.NewObject(typeName));
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public InstallerTypeAttribute(NetType installerType) throws Throwable, system.ArgumentException, system.ArgumentOutOfRangeException, system.ArgumentNullException, system.InvalidOperationException, system.PlatformNotSupportedException, system.IndexOutOfRangeException, system.NotSupportedException, system.ObjectDisposedException, system.RankException, system.ArrayTypeMismatchException {
try {
// add reference to assemblyName.dll file
addReference(JCOReflector.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName);
setJCOInstance((JCObject)classType.NewObject(installerType == null ? null : installerType.getJCOInstance()));
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
// Methods section
// Properties section
public NetType getInstallerType() throws Throwable, system.ArgumentException, system.IndexOutOfRangeException, system.NotSupportedException, system.ArgumentNullException, system.InvalidOperationException, system.ArgumentOutOfRangeException, system.PlatformNotSupportedException, system.TypeLoadException {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
JCObject val = (JCObject)classInstance.Get("InstallerType");
return new NetType(val);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
// Instance Events section
}
|
/*
* *****************************************************************
*
* Copyright 2018 DEKRA Testing and Certification, S.A.U. 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.mango.home.domain.model.resource.secure.cred;
import org.iotivity.OCCredData;
import org.iotivity.OCCredUtil;
public class OcCredPublicData {
private String encoding;
private String pemData;
private byte[] derData;
public OcCredPublicData() {
}
public String getEncoding() {
return encoding;
}
public void setEncoding(String encoding) {
this.encoding = encoding;
}
public String getPemData() {
return pemData;
}
public void setPemData(String data) {
this.pemData = data;
}
public byte[] getDerData() {
return derData;
}
public void setDerData(byte[] derData) {
this.derData = derData;
}
public void parseOCRepresentation(OCCredData data) {
/* data PEM format */
String dataPem = data.getData();
this.setPemData(dataPem);
/* encoding */
String encoding = OCCredUtil.readEncoding(data.getEncoding());
this.setEncoding(encoding);
}
}
|
package gaia3d.security.crypto;
import java.io.UnsupportedEncodingException;
import java.util.Base64;
public class KeyManager {
private static final String randomKeyword = "ZDNhaWFnQCBzaSBlbWFuIHltIC5kM2FpYWcgcm9mIGFlZGkgZGFiIGEgZWthbSB0b24gb2QgZXNhZWxwICx5ZWsgdGVyY3MjIGRudW9mIGV2YWggdW95IGZJ";
public static String getInitKey() {
String result = null;
try {
byte[] base64decodedBytes = Base64.getDecoder().decode(randomKeyword.getBytes("UTF-8"));
result = new String(base64decodedBytes, "UTF-8");
} catch(UnsupportedEncodingException e) {
System.out.println("UnsupportedEncodingException ===== " + e.getMessage());
}
result = reverseString(result);
return parse(result);
}
private static String reverseString(String value) {
if(value == null) return "";
return (new StringBuffer(value)).reverse().toString();
}
private static String parse(String value) {
return value.substring(83, 90) + value.substring(18, 24) + value.substring(25, 28);
}
}
|
/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mozilla.javascript;
/**
* This class is used by the V8 extension "Error.prepareStackTrace." It is passed to
* that function, which may then use it to format the stack as it sees fit.
*/
public class NativeCallSite extends IdScriptableObject {
private static final String CALLSITE_TAG = "CallSite";
private static final int
Id_constructor = 1,
Id_getThis = 2,
Id_getTypeName = 3,
Id_getFunction = 4,
Id_getFunctionName = 5,
Id_getMethodName = 6,
Id_getFileName = 7,
Id_getLineNumber = 8,
Id_getColumnNumber = 9,
Id_getEvalOrigin = 10,
Id_isToplevel = 11,
Id_isEval = 12,
Id_isNative = 13,
Id_isConstructor = 14,
Id_toString = 15,
MAX_PROTOTYPE_ID = 15;
private ScriptStackElement element;
private NativeCallSite() {
}
static void init(Scriptable scope, boolean sealed) {
NativeCallSite cs = new NativeCallSite();
cs.exportAsJSClass(MAX_PROTOTYPE_ID, scope, sealed);
}
static NativeCallSite make(Scriptable scope, Scriptable ctorObj) {
NativeCallSite cs = new NativeCallSite();
Scriptable proto = (Scriptable) (ctorObj.get("prototype", ctorObj));
cs.setParentScope(scope);
cs.setPrototype(proto);
return cs;
}
void setElement(ScriptStackElement elt) {
this.element = elt;
}
@Override
public String getClassName() {
return "CallSite";
}
@Override
protected void initPrototypeId(int id) {
String s;
int arity;
switch (id) {
case Id_constructor:
arity = 0;
s = "constructor";
break;
case Id_getThis:
arity = 0;
s = "getThis";
break;
case Id_getTypeName:
arity = 0;
s = "getTypeName";
break;
case Id_getFunction:
arity = 0;
s = "getFunction";
break;
case Id_getFunctionName:
arity = 0;
s = "getFunctionName";
break;
case Id_getMethodName:
arity = 0;
s = "getMethodName";
break;
case Id_getFileName:
arity = 0;
s = "getFileName";
break;
case Id_getLineNumber:
arity = 0;
s = "getLineNumber";
break;
case Id_getColumnNumber:
arity = 0;
s = "getColumnNumber";
break;
case Id_getEvalOrigin:
arity = 0;
s = "getEvalOrigin";
break;
case Id_isToplevel:
arity = 0;
s = "isToplevel";
break;
case Id_isEval:
arity = 0;
s = "isEval";
break;
case Id_isNative:
arity = 0;
s = "isNative";
break;
case Id_isConstructor:
arity = 0;
s = "isConstructor";
break;
case Id_toString:
arity = 0;
s = "toString";
break;
default:
throw new IllegalArgumentException(String.valueOf(id));
}
initPrototypeMethod(CALLSITE_TAG, id, s, arity);
}
@Override
public Object execIdCall(IdFunctionObject f, Context cx, Scriptable scope,
Scriptable thisObj, Object[] args) {
if (!f.hasTag(CALLSITE_TAG)) {
return super.execIdCall(f, cx, scope, thisObj, args);
}
int id = f.methodId();
switch (id) {
case Id_constructor:
return make(scope, f);
case Id_getFunctionName:
return getFunctionName(thisObj);
case Id_getFileName:
return getFileName(thisObj);
case Id_getLineNumber:
return getLineNumber(thisObj);
case Id_getThis:
case Id_getTypeName:
case Id_getFunction:
case Id_getColumnNumber:
return getUndefined();
case Id_getMethodName:
return getNull();
case Id_getEvalOrigin:
case Id_isEval:
case Id_isConstructor:
case Id_isNative:
case Id_isToplevel:
return getFalse();
case Id_toString:
return js_toString(thisObj);
default:
throw new IllegalArgumentException(String.valueOf(id));
}
}
@Override
public String toString() {
if (element == null) {
return "";
}
return element.toString();
}
private Object js_toString(Scriptable obj) {
while (obj != null && !(obj instanceof NativeCallSite)) {
obj = obj.getPrototype();
}
if (obj == null) {
return NOT_FOUND;
}
NativeCallSite cs = (NativeCallSite) obj;
StringBuilder sb = new StringBuilder();
cs.element.renderJavaStyle(sb);
return sb.toString();
}
private Object getUndefined() {
return Undefined.instance;
}
private Object getNull() {
return null;
}
private Object getFalse() {
return Boolean.FALSE;
}
private Object getFunctionName(Scriptable obj) {
while (obj != null && !(obj instanceof NativeCallSite)) {
obj = obj.getPrototype();
}
if (obj == null) {
return NOT_FOUND;
}
NativeCallSite cs = (NativeCallSite) obj;
return (cs.element == null ? null : cs.element.functionName);
}
private Object getFileName(Scriptable obj) {
while (obj != null && !(obj instanceof NativeCallSite)) {
obj = obj.getPrototype();
}
if (obj == null) {
return NOT_FOUND;
}
NativeCallSite cs = (NativeCallSite) obj;
return (cs.element == null ? null : cs.element.fileName);
}
// #string_id_map#
private Object getLineNumber(Scriptable obj) {
while (obj != null && !(obj instanceof NativeCallSite)) {
obj = obj.getPrototype();
}
if (obj == null) {
return NOT_FOUND;
}
NativeCallSite cs = (NativeCallSite) obj;
if ((cs.element == null) || (cs.element.lineNumber < 0)) {
return Undefined.instance;
}
return cs.element.lineNumber;
}
@Override
protected int findPrototypeId(String s) {
int id;
// #generated# Last update: 2015-03-02 23:42:12 PST
L0:
{
id = 0;
String X = null;
int c;
L:
switch (s.length()) {
case 6:
X = "isEval";
id = Id_isEval;
break L;
case 7:
X = "getThis";
id = Id_getThis;
break L;
case 8:
c = s.charAt(0);
if (c == 'i') {
X = "isNative";
id = Id_isNative;
} else if (c == 't') {
X = "toString";
id = Id_toString;
}
break L;
case 10:
X = "isToplevel";
id = Id_isToplevel;
break L;
case 11:
switch (s.charAt(4)) {
case 'i':
X = "getFileName";
id = Id_getFileName;
break L;
case 't':
X = "constructor";
id = Id_constructor;
break L;
case 'u':
X = "getFunction";
id = Id_getFunction;
break L;
case 'y':
X = "getTypeName";
id = Id_getTypeName;
break L;
}
break L;
case 13:
switch (s.charAt(3)) {
case 'E':
X = "getEvalOrigin";
id = Id_getEvalOrigin;
break L;
case 'L':
X = "getLineNumber";
id = Id_getLineNumber;
break L;
case 'M':
X = "getMethodName";
id = Id_getMethodName;
break L;
case 'o':
X = "isConstructor";
id = Id_isConstructor;
break L;
}
break L;
case 15:
c = s.charAt(3);
if (c == 'C') {
X = "getColumnNumber";
id = Id_getColumnNumber;
} else if (c == 'F') {
X = "getFunctionName";
id = Id_getFunctionName;
}
break L;
}
if (X != null && X != s && !X.equals(s)) id = 0;
break L0;
}
// #/generated#
return id;
}
// #/string_id_map#
}
|
/**
* InternalRedirectCreative.java
*
* This file was auto-generated from WSDL
* by the Apache Axis 1.4 Apr 22, 2006 (06:55:48 PDT) WSDL2Java emitter.
*/
package com.google.api.ads.dfp.v201311;
/**
* A {@code Creative} hosted by either DoubleClick for Advertisers
* (DFA) or DART
* for Publishers.
* <p>
* Similar to third-party creatives, a DoubleClick tag is
* used to retrieve a
* creative asset. However, DoubleClick tags are not sent
* to the user's browser.
* Instead, they are processed internally within the DoubleClick
* system..
*/
public class InternalRedirectCreative extends com.google.api.ads.dfp.v201311.Creative implements java.io.Serializable {
/* The asset size of an internal redirect creative.
* Note that this may differ from {@code size} if
* users set {@code overrideSize} to true.
* This attribute is read-only and is populated
* by Google. */
private com.google.api.ads.dfp.v201311.Size assetSize;
/* The internal redirect URL of the DFA or DART for Publishers
* hosted creative.
* This attribute is required and has a maximum length
* of 1024 characters. */
private java.lang.String internalRedirectUrl;
/* Allows the creative size to differ from the actual size specified
* in the
* internal redirect's url. This attribute is optional. */
private java.lang.Boolean overrideSize;
/* {@code true} if this internal redirect creative is interstitial. */
private java.lang.Boolean isInterstitial;
public InternalRedirectCreative() {
}
public InternalRedirectCreative(
java.lang.Long advertiserId,
java.lang.Long id,
java.lang.String name,
com.google.api.ads.dfp.v201311.Size size,
java.lang.String previewUrl,
com.google.api.ads.dfp.v201311.AppliedLabel[] appliedLabels,
com.google.api.ads.dfp.v201311.DateTime lastModifiedDateTime,
com.google.api.ads.dfp.v201311.BaseCustomFieldValue[] customFieldValues,
java.lang.String creativeType,
com.google.api.ads.dfp.v201311.Size assetSize,
java.lang.String internalRedirectUrl,
java.lang.Boolean overrideSize,
java.lang.Boolean isInterstitial) {
super(
advertiserId,
id,
name,
size,
previewUrl,
appliedLabels,
lastModifiedDateTime,
customFieldValues,
creativeType);
this.assetSize = assetSize;
this.internalRedirectUrl = internalRedirectUrl;
this.overrideSize = overrideSize;
this.isInterstitial = isInterstitial;
}
/**
* Gets the assetSize value for this InternalRedirectCreative.
*
* @return assetSize * The asset size of an internal redirect creative.
* Note that this may differ from {@code size} if
* users set {@code overrideSize} to true.
* This attribute is read-only and is populated
* by Google.
*/
public com.google.api.ads.dfp.v201311.Size getAssetSize() {
return assetSize;
}
/**
* Sets the assetSize value for this InternalRedirectCreative.
*
* @param assetSize * The asset size of an internal redirect creative.
* Note that this may differ from {@code size} if
* users set {@code overrideSize} to true.
* This attribute is read-only and is populated
* by Google.
*/
public void setAssetSize(com.google.api.ads.dfp.v201311.Size assetSize) {
this.assetSize = assetSize;
}
/**
* Gets the internalRedirectUrl value for this InternalRedirectCreative.
*
* @return internalRedirectUrl * The internal redirect URL of the DFA or DART for Publishers
* hosted creative.
* This attribute is required and has a maximum length
* of 1024 characters.
*/
public java.lang.String getInternalRedirectUrl() {
return internalRedirectUrl;
}
/**
* Sets the internalRedirectUrl value for this InternalRedirectCreative.
*
* @param internalRedirectUrl * The internal redirect URL of the DFA or DART for Publishers
* hosted creative.
* This attribute is required and has a maximum length
* of 1024 characters.
*/
public void setInternalRedirectUrl(java.lang.String internalRedirectUrl) {
this.internalRedirectUrl = internalRedirectUrl;
}
/**
* Gets the overrideSize value for this InternalRedirectCreative.
*
* @return overrideSize * Allows the creative size to differ from the actual size specified
* in the
* internal redirect's url. This attribute is optional.
*/
public java.lang.Boolean getOverrideSize() {
return overrideSize;
}
/**
* Sets the overrideSize value for this InternalRedirectCreative.
*
* @param overrideSize * Allows the creative size to differ from the actual size specified
* in the
* internal redirect's url. This attribute is optional.
*/
public void setOverrideSize(java.lang.Boolean overrideSize) {
this.overrideSize = overrideSize;
}
/**
* Gets the isInterstitial value for this InternalRedirectCreative.
*
* @return isInterstitial * {@code true} if this internal redirect creative is interstitial.
*/
public java.lang.Boolean getIsInterstitial() {
return isInterstitial;
}
/**
* Sets the isInterstitial value for this InternalRedirectCreative.
*
* @param isInterstitial * {@code true} if this internal redirect creative is interstitial.
*/
public void setIsInterstitial(java.lang.Boolean isInterstitial) {
this.isInterstitial = isInterstitial;
}
private java.lang.Object __equalsCalc = null;
public synchronized boolean equals(java.lang.Object obj) {
if (!(obj instanceof InternalRedirectCreative)) return false;
InternalRedirectCreative other = (InternalRedirectCreative) obj;
if (obj == null) return false;
if (this == obj) return true;
if (__equalsCalc != null) {
return (__equalsCalc == obj);
}
__equalsCalc = obj;
boolean _equals;
_equals = super.equals(obj) &&
((this.assetSize==null && other.getAssetSize()==null) ||
(this.assetSize!=null &&
this.assetSize.equals(other.getAssetSize()))) &&
((this.internalRedirectUrl==null && other.getInternalRedirectUrl()==null) ||
(this.internalRedirectUrl!=null &&
this.internalRedirectUrl.equals(other.getInternalRedirectUrl()))) &&
((this.overrideSize==null && other.getOverrideSize()==null) ||
(this.overrideSize!=null &&
this.overrideSize.equals(other.getOverrideSize()))) &&
((this.isInterstitial==null && other.getIsInterstitial()==null) ||
(this.isInterstitial!=null &&
this.isInterstitial.equals(other.getIsInterstitial())));
__equalsCalc = null;
return _equals;
}
private boolean __hashCodeCalc = false;
public synchronized int hashCode() {
if (__hashCodeCalc) {
return 0;
}
__hashCodeCalc = true;
int _hashCode = super.hashCode();
if (getAssetSize() != null) {
_hashCode += getAssetSize().hashCode();
}
if (getInternalRedirectUrl() != null) {
_hashCode += getInternalRedirectUrl().hashCode();
}
if (getOverrideSize() != null) {
_hashCode += getOverrideSize().hashCode();
}
if (getIsInterstitial() != null) {
_hashCode += getIsInterstitial().hashCode();
}
__hashCodeCalc = false;
return _hashCode;
}
// Type metadata
private static org.apache.axis.description.TypeDesc typeDesc =
new org.apache.axis.description.TypeDesc(InternalRedirectCreative.class, true);
static {
typeDesc.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201311", "InternalRedirectCreative"));
org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("assetSize");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201311", "assetSize"));
elemField.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201311", "Size"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("internalRedirectUrl");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201311", "internalRedirectUrl"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("overrideSize");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201311", "overrideSize"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "boolean"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("isInterstitial");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201311", "isInterstitial"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "boolean"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
}
/**
* Return type metadata object
*/
public static org.apache.axis.description.TypeDesc getTypeDesc() {
return typeDesc;
}
/**
* Get Custom Serializer
*/
public static org.apache.axis.encoding.Serializer getSerializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanSerializer(
_javaType, _xmlType, typeDesc);
}
/**
* Get Custom Deserializer
*/
public static org.apache.axis.encoding.Deserializer getDeserializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanDeserializer(
_javaType, _xmlType, typeDesc);
}
}
|
/*
* 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.iceberg.mr.hive;
import java.io.IOException;
import java.util.Collection;
import java.util.Collections;
import java.util.EnumSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Properties;
import java.util.Set;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hive.common.TableName;
import org.apache.hadoop.hive.metastore.HiveMetaHook;
import org.apache.hadoop.hive.metastore.api.EnvironmentContext;
import org.apache.hadoop.hive.metastore.api.FieldSchema;
import org.apache.hadoop.hive.metastore.api.MetaException;
import org.apache.hadoop.hive.metastore.api.SerDeInfo;
import org.apache.hadoop.hive.metastore.api.StorageDescriptor;
import org.apache.hadoop.hive.metastore.api.hive_metastoreConstants;
import org.apache.hadoop.hive.metastore.partition.spec.PartitionSpecProxy;
import org.apache.hadoop.hive.metastore.utils.MetaStoreUtils;
import org.apache.hadoop.hive.ql.ddl.table.AlterTableType;
import org.apache.hadoop.hive.ql.io.AcidUtils;
import org.apache.hadoop.hive.ql.parse.PartitionTransform;
import org.apache.hadoop.hive.ql.parse.PartitionTransformSpec;
import org.apache.hadoop.hive.ql.session.SessionStateUtil;
import org.apache.hadoop.hive.serde2.typeinfo.TypeInfoUtils;
import org.apache.iceberg.BaseMetastoreTableOperations;
import org.apache.iceberg.BaseTable;
import org.apache.iceberg.CatalogUtil;
import org.apache.iceberg.DeleteFiles;
import org.apache.iceberg.FileFormat;
import org.apache.iceberg.PartitionSpec;
import org.apache.iceberg.PartitionSpecParser;
import org.apache.iceberg.Schema;
import org.apache.iceberg.SchemaParser;
import org.apache.iceberg.Table;
import org.apache.iceberg.TableMetadata;
import org.apache.iceberg.TableMetadataParser;
import org.apache.iceberg.TableProperties;
import org.apache.iceberg.Transaction;
import org.apache.iceberg.UpdatePartitionSpec;
import org.apache.iceberg.UpdateProperties;
import org.apache.iceberg.UpdateSchema;
import org.apache.iceberg.catalog.TableIdentifier;
import org.apache.iceberg.exceptions.NoSuchTableException;
import org.apache.iceberg.expressions.Expressions;
import org.apache.iceberg.hive.HiveSchemaUtil;
import org.apache.iceberg.hive.HiveTableOperations;
import org.apache.iceberg.io.FileIO;
import org.apache.iceberg.mr.Catalogs;
import org.apache.iceberg.mr.InputFormatConfig;
import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
import org.apache.iceberg.relocated.com.google.common.base.Splitter;
import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
import org.apache.iceberg.relocated.com.google.common.collect.ImmutableSet;
import org.apache.iceberg.relocated.com.google.common.collect.Lists;
import org.apache.iceberg.types.Type;
import org.apache.iceberg.util.Pair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class HiveIcebergMetaHook implements HiveMetaHook {
private static final Logger LOG = LoggerFactory.getLogger(HiveIcebergMetaHook.class);
private static final Set<String> PARAMETERS_TO_REMOVE = ImmutableSet
.of(InputFormatConfig.TABLE_SCHEMA, Catalogs.LOCATION, Catalogs.NAME, InputFormatConfig.PARTITION_SPEC);
private static final Set<String> PROPERTIES_TO_REMOVE = ImmutableSet
// We don't want to push down the metadata location props to Iceberg from HMS,
// since the snapshot pointer in HMS would always be one step ahead
.of(BaseMetastoreTableOperations.METADATA_LOCATION_PROP,
BaseMetastoreTableOperations.PREVIOUS_METADATA_LOCATION_PROP);
static final EnumSet<AlterTableType> SUPPORTED_ALTER_OPS = EnumSet.of(
AlterTableType.ADDCOLS, AlterTableType.REPLACE_COLUMNS, AlterTableType.RENAME_COLUMN,
AlterTableType.ADDPROPS, AlterTableType.DROPPROPS, AlterTableType.SETPARTITIONSPEC,
AlterTableType.UPDATE_COLUMNS);
private static final List<String> MIGRATION_ALLOWED_SOURCE_FORMATS = ImmutableList.of(
FileFormat.PARQUET.name().toLowerCase(),
FileFormat.ORC.name().toLowerCase(),
FileFormat.AVRO.name().toLowerCase());
private final Configuration conf;
private Table icebergTable = null;
private Properties catalogProperties;
private boolean deleteIcebergTable;
private FileIO deleteIo;
private TableMetadata deleteMetadata;
private boolean isTableMigration;
private PreAlterTableProperties preAlterTableProperties;
private UpdateSchema updateSchema;
private UpdatePartitionSpec updatePartitionSpec;
private Transaction transaction;
private AlterTableType currentAlterTableOp;
public HiveIcebergMetaHook(Configuration conf) {
this.conf = conf;
}
@Override
public void preCreateTable(org.apache.hadoop.hive.metastore.api.Table hmsTable) {
this.catalogProperties = getCatalogProperties(hmsTable);
// Set the table type even for non HiveCatalog based tables
hmsTable.getParameters().put(BaseMetastoreTableOperations.TABLE_TYPE_PROP,
BaseMetastoreTableOperations.ICEBERG_TABLE_TYPE_VALUE.toUpperCase());
if (!Catalogs.hiveCatalog(conf, catalogProperties)) {
// For non-HiveCatalog tables too, we should set the input and output format
// so that the table can be read by other engines like Impala
hmsTable.getSd().setInputFormat(HiveIcebergInputFormat.class.getCanonicalName());
hmsTable.getSd().setOutputFormat(HiveIcebergOutputFormat.class.getCanonicalName());
// If not using HiveCatalog check for existing table
try {
this.icebergTable = IcebergTableUtil.getTable(conf, catalogProperties);
Preconditions.checkArgument(catalogProperties.getProperty(InputFormatConfig.TABLE_SCHEMA) == null,
"Iceberg table already created - can not use provided schema");
Preconditions.checkArgument(catalogProperties.getProperty(InputFormatConfig.PARTITION_SPEC) == null,
"Iceberg table already created - can not use provided partition specification");
LOG.info("Iceberg table already exists {}", icebergTable);
return;
} catch (NoSuchTableException nte) {
// If the table does not exist we will create it below
}
}
// If the table does not exist collect data for table creation
// - InputFormatConfig.TABLE_SCHEMA, InputFormatConfig.PARTITION_SPEC takes precedence so the user can override the
// Iceberg schema and specification generated by the code
Schema schema = schema(catalogProperties, hmsTable);
PartitionSpec spec = spec(conf, schema, hmsTable);
// If there are partition keys specified remove them from the HMS table and add them to the column list
if (hmsTable.isSetPartitionKeys()) {
hmsTable.getSd().getCols().addAll(hmsTable.getPartitionKeys());
hmsTable.setPartitionKeysIsSet(false);
}
catalogProperties.put(InputFormatConfig.TABLE_SCHEMA, SchemaParser.toJson(schema));
catalogProperties.put(InputFormatConfig.PARTITION_SPEC, PartitionSpecParser.toJson(spec));
updateHmsTableProperties(hmsTable);
}
@Override
public void rollbackCreateTable(org.apache.hadoop.hive.metastore.api.Table hmsTable) {
// do nothing
}
@Override
public void commitCreateTable(org.apache.hadoop.hive.metastore.api.Table hmsTable) {
if (icebergTable == null) {
if (Catalogs.hiveCatalog(conf, catalogProperties)) {
catalogProperties.put(TableProperties.ENGINE_HIVE_ENABLED, true);
}
Catalogs.createTable(conf, catalogProperties);
}
}
@Override
public void preDropTable(org.apache.hadoop.hive.metastore.api.Table hmsTable) {
// do nothing
}
@Override
public void preDropTable(org.apache.hadoop.hive.metastore.api.Table hmsTable, boolean deleteData) {
this.catalogProperties = getCatalogProperties(hmsTable);
this.deleteIcebergTable = hmsTable.getParameters() != null &&
"TRUE".equalsIgnoreCase(hmsTable.getParameters().get(InputFormatConfig.EXTERNAL_TABLE_PURGE));
if (deleteIcebergTable && Catalogs.hiveCatalog(conf, catalogProperties) && deleteData) {
// Store the metadata and the io for deleting the actual table data
try {
String metadataLocation = hmsTable.getParameters().get(BaseMetastoreTableOperations.METADATA_LOCATION_PROP);
this.deleteIo = Catalogs.loadTable(conf, catalogProperties).io();
this.deleteMetadata = TableMetadataParser.read(deleteIo, metadataLocation);
} catch (Exception e) {
LOG.error("preDropTable: Error during loading Iceberg table or parsing its metadata for HMS table: {}.{}. " +
"In some cases, this might lead to undeleted metadata files under the table directory: {}. " +
"Please double check and, if needed, manually delete any dangling files/folders, if any. " +
"In spite of this error, the HMS table drop operation should proceed as normal.",
hmsTable.getDbName(), hmsTable.getTableName(), hmsTable.getSd().getLocation(), e);
}
}
}
@Override
public void rollbackDropTable(org.apache.hadoop.hive.metastore.api.Table hmsTable) {
// do nothing
}
@Override
public void commitDropTable(org.apache.hadoop.hive.metastore.api.Table hmsTable, boolean deleteData) {
if (deleteData && deleteIcebergTable) {
try {
if (!Catalogs.hiveCatalog(conf, catalogProperties)) {
LOG.info("Dropping with purge all the data for table {}.{}", hmsTable.getDbName(), hmsTable.getTableName());
Catalogs.dropTable(conf, catalogProperties);
} else {
// do nothing if metadata folder has been deleted already (Hive 4 behaviour for purge=TRUE)
if (deleteMetadata != null && deleteIo.newInputFile(deleteMetadata.location()).exists()) {
CatalogUtil.dropTableData(deleteIo, deleteMetadata);
}
}
} catch (Exception e) {
// we want to successfully complete the Hive DROP TABLE command despite catalog-related exceptions here
// e.g. we wish to successfully delete a Hive table even if the underlying Hadoop table has already been deleted
LOG.warn("Exception during commitDropTable operation for table {}.{}.",
hmsTable.getDbName(), hmsTable.getTableName(), e);
}
}
}
@Override
public void preAlterTable(org.apache.hadoop.hive.metastore.api.Table hmsTable, EnvironmentContext context)
throws MetaException {
setupAlterOperationType(hmsTable, context);
catalogProperties = getCatalogProperties(hmsTable);
try {
icebergTable = IcebergTableUtil.getTable(conf, catalogProperties);
} catch (NoSuchTableException nte) {
context.getProperties().put(MIGRATE_HIVE_TO_ICEBERG, "true");
// If the iceberg table does not exist, then this is an ALTER command aimed at migrating the table to iceberg
// First we must check whether it's eligible for migration to iceberg
// If so, we will create the iceberg table in commitAlterTable and go ahead with the migration
checkEligibilityForMigrationOrThrow(hmsTable);
isTableMigration = true;
StorageDescriptor sd = hmsTable.getSd();
preAlterTableProperties = new PreAlterTableProperties();
preAlterTableProperties.tableLocation = sd.getLocation();
preAlterTableProperties.format = sd.getInputFormat();
preAlterTableProperties.schema = schema(catalogProperties, hmsTable);
preAlterTableProperties.partitionKeys = hmsTable.getPartitionKeys();
context.getProperties().put(HiveMetaHook.ALLOW_PARTITION_KEY_CHANGE, "true");
// If there are partition keys specified remove them from the HMS table and add them to the column list
if (hmsTable.isSetPartitionKeys() && !hmsTable.getPartitionKeys().isEmpty()) {
List<PartitionTransformSpec> spec = PartitionTransform.getPartitionTransformSpec(hmsTable.getPartitionKeys());
if (!SessionStateUtil.addResource(conf, hive_metastoreConstants.PARTITION_TRANSFORM_SPEC, spec)) {
throw new MetaException("Query state attached to Session state must be not null. " +
"Partition transform metadata cannot be saved.");
}
hmsTable.getSd().getCols().addAll(hmsTable.getPartitionKeys());
hmsTable.setPartitionKeysIsSet(false);
}
preAlterTableProperties.spec = spec(conf, preAlterTableProperties.schema, hmsTable);
sd.setInputFormat(HiveIcebergInputFormat.class.getCanonicalName());
sd.setOutputFormat(HiveIcebergOutputFormat.class.getCanonicalName());
sd.setSerdeInfo(new SerDeInfo("icebergSerde", HiveIcebergSerDe.class.getCanonicalName(),
Collections.emptyMap()));
updateHmsTableProperties(hmsTable);
}
if (AlterTableType.ADDCOLS.equals(currentAlterTableOp)) {
handleAddColumns(hmsTable);
} else if (AlterTableType.REPLACE_COLUMNS.equals(currentAlterTableOp)) {
handleReplaceColumns(hmsTable);
} else if (AlterTableType.RENAME_COLUMN.equals(currentAlterTableOp)) {
handleChangeColumn(hmsTable);
}
}
/**
* Checks if the table can be migrated to iceberg format. An eligible table is:
* - external
* - not temporary
* - not acid
* - uses one of supported file formats
* @param hmsTable the table which should be migrated to iceberg, if eligible
* @throws MetaException if the table is not eligible for migration due to violating one of the conditions above
*/
private void checkEligibilityForMigrationOrThrow(org.apache.hadoop.hive.metastore.api.Table hmsTable)
throws MetaException {
StorageDescriptor sd = hmsTable.getSd();
boolean hasCorrectTableType = MetaStoreUtils.isExternalTable(hmsTable) && !hmsTable.isTemporary() &&
!AcidUtils.isTransactionalTable(hmsTable);
if (!hasCorrectTableType) {
throw new MetaException("Converting non-external, temporary or transactional hive table to iceberg " +
"table is not allowed.");
}
boolean hasCorrectFileFormat = MIGRATION_ALLOWED_SOURCE_FORMATS.stream()
.anyMatch(f -> sd.getInputFormat().toLowerCase().contains(f));
if (!hasCorrectFileFormat) {
throw new MetaException("Cannot convert hive table to iceberg with input format: " + sd.getInputFormat());
}
}
@Override
public void commitAlterTable(org.apache.hadoop.hive.metastore.api.Table hmsTable, EnvironmentContext context,
PartitionSpecProxy partitionSpecProxy) throws MetaException {
if (isTableMigration) {
catalogProperties = getCatalogProperties(hmsTable);
catalogProperties.put(InputFormatConfig.TABLE_SCHEMA, SchemaParser.toJson(preAlterTableProperties.schema));
catalogProperties.put(InputFormatConfig.PARTITION_SPEC, PartitionSpecParser.toJson(preAlterTableProperties.spec));
setFileFormat();
if (Catalogs.hiveCatalog(conf, catalogProperties)) {
catalogProperties.put(TableProperties.ENGINE_HIVE_ENABLED, true);
}
HiveTableUtil.importFiles(preAlterTableProperties.tableLocation, preAlterTableProperties.format,
partitionSpecProxy, preAlterTableProperties.partitionKeys, catalogProperties, conf);
} else if (currentAlterTableOp != null) {
switch (currentAlterTableOp) {
case REPLACE_COLUMNS:
case RENAME_COLUMN:
case ADDCOLS:
if (transaction != null) {
transaction.commitTransaction();
}
break;
case ADDPROPS:
case DROPPROPS:
alterTableProperties(hmsTable, context.getProperties());
break;
case SETPARTITIONSPEC:
IcebergTableUtil.updateSpec(conf, icebergTable);
break;
}
}
}
@Override
public void rollbackAlterTable(org.apache.hadoop.hive.metastore.api.Table hmsTable, EnvironmentContext context) {
if (Boolean.parseBoolean(context.getProperties().getOrDefault(MIGRATE_HIVE_TO_ICEBERG, "false"))) {
LOG.debug("Initiating rollback for table {} at location {}",
hmsTable.getTableName(), hmsTable.getSd().getLocation());
context.getProperties().put(INITIALIZE_ROLLBACK_MIGRATION, "true");
this.catalogProperties = getCatalogProperties(hmsTable);
try {
this.icebergTable = Catalogs.loadTable(conf, catalogProperties);
} catch (NoSuchTableException nte) {
// iceberg table was not yet created, no need to delete the metadata dir separately
return;
}
// we want to keep the data files but get rid of the metadata directory
String metadataLocation = ((BaseTable) this.icebergTable).operations().current().metadataFileLocation();
try {
Path path = new Path(metadataLocation).getParent();
FileSystem.get(path.toUri(), conf).delete(path, true);
LOG.debug("Metadata directory of iceberg table {} at location {} was deleted",
icebergTable.name(), path);
} catch (IOException e) {
// the file doesn't exists, do nothing
}
}
}
@Override
public void preTruncateTable(org.apache.hadoop.hive.metastore.api.Table table, EnvironmentContext context)
throws MetaException {
this.catalogProperties = getCatalogProperties(table);
this.icebergTable = Catalogs.loadTable(conf, catalogProperties);
DeleteFiles delete = icebergTable.newDelete();
delete.deleteFromRowFilter(Expressions.alwaysTrue());
delete.commit();
context.putToProperties("truncateSkipDataDeletion", "true");
}
private void alterTableProperties(org.apache.hadoop.hive.metastore.api.Table hmsTable,
Map<String, String> contextProperties) {
Map<String, String> hmsTableParameters = hmsTable.getParameters();
Splitter splitter = Splitter.on(PROPERTIES_SEPARATOR);
UpdateProperties icebergUpdateProperties = icebergTable.updateProperties();
if (contextProperties.containsKey(SET_PROPERTIES)) {
splitter.splitToList(contextProperties.get(SET_PROPERTIES))
.forEach(k -> icebergUpdateProperties.set(k, hmsTableParameters.get(k)));
} else if (contextProperties.containsKey(UNSET_PROPERTIES)) {
splitter.splitToList(contextProperties.get(UNSET_PROPERTIES)).forEach(icebergUpdateProperties::remove);
}
icebergUpdateProperties.commit();
}
private void setupAlterOperationType(org.apache.hadoop.hive.metastore.api.Table hmsTable,
EnvironmentContext context) throws MetaException {
TableName tableName = new TableName(hmsTable.getCatName(), hmsTable.getDbName(), hmsTable.getTableName());
if (context == null || context.getProperties() == null) {
throw new MetaException("ALTER TABLE operation type on Iceberg table " + tableName +
" could not be determined.");
}
String stringOpType = context.getProperties().get(ALTER_TABLE_OPERATION_TYPE);
if (stringOpType != null) {
currentAlterTableOp = AlterTableType.valueOf(stringOpType);
if (SUPPORTED_ALTER_OPS.stream().noneMatch(op -> op.equals(currentAlterTableOp))) {
throw new MetaException(
"Unsupported ALTER TABLE operation type on Iceberg table " + tableName + ", must be one of: " +
SUPPORTED_ALTER_OPS);
}
}
}
private void setFileFormat() {
String format = preAlterTableProperties.format.toLowerCase();
if (format.contains("orc")) {
catalogProperties.put(TableProperties.DEFAULT_FILE_FORMAT, "orc");
} else if (format.contains("parquet")) {
catalogProperties.put(TableProperties.DEFAULT_FILE_FORMAT, "parquet");
} else if (format.contains("avro")) {
catalogProperties.put(TableProperties.DEFAULT_FILE_FORMAT, "avro");
}
}
private void updateHmsTableProperties(org.apache.hadoop.hive.metastore.api.Table hmsTable) {
// Set the table type even for non HiveCatalog based tables
hmsTable.getParameters().put(BaseMetastoreTableOperations.TABLE_TYPE_PROP,
BaseMetastoreTableOperations.ICEBERG_TABLE_TYPE_VALUE.toUpperCase());
// Allow purging table data if the table is created now and not set otherwise
hmsTable.getParameters().putIfAbsent(InputFormatConfig.EXTERNAL_TABLE_PURGE, "TRUE");
// If the table is not managed by Hive catalog then the location should be set
if (!Catalogs.hiveCatalog(conf, catalogProperties)) {
Preconditions.checkArgument(hmsTable.getSd() != null && hmsTable.getSd().getLocation() != null,
"Table location not set");
}
// Remove null values from hms table properties
hmsTable.getParameters().entrySet().removeIf(e -> e.getKey() == null || e.getValue() == null);
// Remove creation related properties
PARAMETERS_TO_REMOVE.forEach(hmsTable.getParameters()::remove);
}
/**
* Calculates the properties we would like to send to the catalog.
* <ul>
* <li>The base of the properties is the properties stored at the Hive Metastore for the given table
* <li>We add the {@link Catalogs#LOCATION} as the table location
* <li>We add the {@link Catalogs#NAME} as TableIdentifier defined by the database name and table name
* <li>We add the serdeProperties of the HMS table
* <li>We remove some parameters that we don't want to push down to the Iceberg table props
* </ul>
* @param hmsTable Table for which we are calculating the properties
* @return The properties we can provide for Iceberg functions, like {@link Catalogs}
*/
private static Properties getCatalogProperties(org.apache.hadoop.hive.metastore.api.Table hmsTable) {
Properties properties = new Properties();
hmsTable.getParameters().entrySet().stream().filter(e -> e.getKey() != null && e.getValue() != null).forEach(e -> {
// translate key names between HMS and Iceberg where needed
String icebergKey = HiveTableOperations.translateToIcebergProp(e.getKey());
properties.put(icebergKey, e.getValue());
});
if (properties.get(Catalogs.LOCATION) == null &&
hmsTable.getSd() != null && hmsTable.getSd().getLocation() != null) {
properties.put(Catalogs.LOCATION, hmsTable.getSd().getLocation());
}
if (properties.get(Catalogs.NAME) == null) {
properties.put(Catalogs.NAME, TableIdentifier.of(hmsTable.getDbName(), hmsTable.getTableName()).toString());
}
SerDeInfo serdeInfo = hmsTable.getSd().getSerdeInfo();
if (serdeInfo != null) {
serdeInfo.getParameters().entrySet().stream()
.filter(e -> e.getKey() != null && e.getValue() != null).forEach(e -> {
String icebergKey = HiveTableOperations.translateToIcebergProp(e.getKey());
properties.put(icebergKey, e.getValue());
});
}
// Remove HMS table parameters we don't want to propagate to Iceberg
PROPERTIES_TO_REMOVE.forEach(properties::remove);
return properties;
}
private Schema schema(Properties properties, org.apache.hadoop.hive.metastore.api.Table hmsTable) {
boolean autoConversion = conf.getBoolean(InputFormatConfig.SCHEMA_AUTO_CONVERSION, false);
if (properties.getProperty(InputFormatConfig.TABLE_SCHEMA) != null) {
return SchemaParser.fromJson(properties.getProperty(InputFormatConfig.TABLE_SCHEMA));
} else if (hmsTable.isSetPartitionKeys() && !hmsTable.getPartitionKeys().isEmpty()) {
// Add partitioning columns to the original column list before creating the Iceberg Schema
List<FieldSchema> cols = Lists.newArrayList(hmsTable.getSd().getCols());
cols.addAll(hmsTable.getPartitionKeys());
return HiveSchemaUtil.convert(cols, autoConversion);
} else {
return HiveSchemaUtil.convert(hmsTable.getSd().getCols(), autoConversion);
}
}
private static PartitionSpec spec(Configuration configuration, Schema schema,
org.apache.hadoop.hive.metastore.api.Table hmsTable) {
Preconditions.checkArgument(!hmsTable.isSetPartitionKeys() || hmsTable.getPartitionKeys().isEmpty(),
"We can only handle non-partitioned Hive tables. The Iceberg schema should be in " +
InputFormatConfig.PARTITION_SPEC + " or already converted to a partition transform ");
PartitionSpec spec = IcebergTableUtil.spec(configuration, schema);
if (spec != null) {
Preconditions.checkArgument(hmsTable.getParameters().get(InputFormatConfig.PARTITION_SPEC) == null,
"Provide only one of the following: Hive partition transform specification, or the " +
InputFormatConfig.PARTITION_SPEC + " property");
return spec;
}
if (hmsTable.getParameters().get(InputFormatConfig.PARTITION_SPEC) != null) {
return PartitionSpecParser.fromJson(schema, hmsTable.getParameters().get(InputFormatConfig.PARTITION_SPEC));
} else {
return PartitionSpec.unpartitioned();
}
}
private void handleAddColumns(org.apache.hadoop.hive.metastore.api.Table hmsTable) {
Collection<FieldSchema> addedCols =
HiveSchemaUtil.getSchemaDiff(hmsTable.getSd().getCols(), HiveSchemaUtil.convert(icebergTable.schema()), false)
.getMissingFromSecond();
if (!addedCols.isEmpty()) {
transaction = icebergTable.newTransaction();
updateSchema = transaction.updateSchema();
}
for (FieldSchema addedCol : addedCols) {
updateSchema.addColumn(addedCol.getName(),
HiveSchemaUtil.convert(TypeInfoUtils.getTypeInfoFromTypeString(addedCol.getType())), addedCol.getComment());
}
updateSchema.commit();
}
private void handleReplaceColumns(org.apache.hadoop.hive.metastore.api.Table hmsTable) throws MetaException {
List<FieldSchema> hmsCols = hmsTable.getSd().getCols();
List<FieldSchema> icebergCols = HiveSchemaUtil.convert(icebergTable.schema());
HiveSchemaUtil.SchemaDifference schemaDifference = HiveSchemaUtil.getSchemaDiff(hmsCols, icebergCols, true);
// if there are columns dropped, let's remove them from the iceberg schema as well so we can compare the order
if (!schemaDifference.getMissingFromFirst().isEmpty()) {
schemaDifference.getMissingFromFirst().forEach(icebergCols::remove);
}
Pair<String, Optional<String>> outOfOrder = HiveSchemaUtil.getFirstOutOfOrderColumn(
hmsCols, icebergCols, ImmutableMap.of());
// limit the scope of this operation to only dropping columns
if (!schemaDifference.getMissingFromSecond().isEmpty() || !schemaDifference.getTypeChanged().isEmpty() ||
!schemaDifference.getCommentChanged().isEmpty() || outOfOrder != null) {
throw new MetaException("Unsupported operation to use REPLACE COLUMNS for adding a column, changing a " +
"column type, column comment or reordering columns. Only use REPLACE COLUMNS for dropping columns. " +
"For the other operations, consider using the ADD COLUMNS or CHANGE COLUMN commands.");
}
if (schemaDifference.getMissingFromFirst().isEmpty()) {
throw new MetaException("No schema change detected from REPLACE COLUMNS operations. For rectifying any schema " +
"mismatches between HMS and Iceberg, please consider the UPDATE COLUMNS command.");
}
transaction = icebergTable.newTransaction();
updateSchema = transaction.updateSchema();
LOG.info("handleReplaceColumns: Dropping the following columns for Iceberg table {}, cols: {}",
hmsTable.getTableName(), schemaDifference.getMissingFromFirst());
for (FieldSchema droppedCol : schemaDifference.getMissingFromFirst()) {
updateSchema.deleteColumn(droppedCol.getName());
}
updateSchema.commit();
}
private void handleChangeColumn(org.apache.hadoop.hive.metastore.api.Table hmsTable) throws MetaException {
List<FieldSchema> hmsCols = hmsTable.getSd().getCols();
List<FieldSchema> icebergCols = HiveSchemaUtil.convert(icebergTable.schema());
// compute schema difference for renames, type/comment changes
HiveSchemaUtil.SchemaDifference schemaDifference = HiveSchemaUtil.getSchemaDiff(hmsCols, icebergCols, true);
// check column reorder (which could happen even in the absence of any rename, type or comment change)
Map<String, String> renameMapping = ImmutableMap.of();
if (!schemaDifference.getMissingFromSecond().isEmpty()) {
renameMapping = ImmutableMap.of(
schemaDifference.getMissingFromSecond().get(0).getName(),
schemaDifference.getMissingFromFirst().get(0).getName());
}
Pair<String, Optional<String>> outOfOrder = HiveSchemaUtil.getFirstOutOfOrderColumn(hmsCols, icebergCols,
renameMapping);
if (!schemaDifference.isEmpty() || outOfOrder != null) {
transaction = icebergTable.newTransaction();
updateSchema = transaction.updateSchema();
} else {
// we should get here if the user didn't change anything about the column
// i.e. no changes to the name, type, comment or order
LOG.info("Found no difference between new and old schema for ALTER TABLE CHANGE COLUMN for" +
" table: {}. There will be no Iceberg commit.", hmsTable.getTableName());
return;
}
// case 1: column name has been renamed
if (!schemaDifference.getMissingFromSecond().isEmpty()) {
FieldSchema updatedField = schemaDifference.getMissingFromSecond().get(0);
FieldSchema oldField = schemaDifference.getMissingFromFirst().get(0);
updateSchema.renameColumn(oldField.getName(), updatedField.getName());
// check if type/comment changed too
if (!Objects.equals(oldField.getType(), updatedField.getType())) {
updateSchema.updateColumn(oldField.getName(), getPrimitiveTypeOrThrow(updatedField), updatedField.getComment());
} else if (!Objects.equals(oldField.getComment(), updatedField.getComment())) {
updateSchema.updateColumnDoc(oldField.getName(), updatedField.getComment());
}
// case 2: only column type and/or comment changed
} else if (!schemaDifference.getTypeChanged().isEmpty()) {
FieldSchema updatedField = schemaDifference.getTypeChanged().get(0);
updateSchema.updateColumn(updatedField.getName(), getPrimitiveTypeOrThrow(updatedField),
updatedField.getComment());
// case 3: only comment changed
} else if (!schemaDifference.getCommentChanged().isEmpty()) {
FieldSchema updatedField = schemaDifference.getCommentChanged().get(0);
updateSchema.updateColumnDoc(updatedField.getName(), updatedField.getComment());
}
// case 4: handle any order change
if (outOfOrder != null) {
if (outOfOrder.second().isPresent()) {
updateSchema.moveAfter(outOfOrder.first(), outOfOrder.second().get());
} else {
updateSchema.moveFirst(outOfOrder.first());
}
}
updateSchema.commit();
handlePartitionRename(schemaDifference);
}
private void handlePartitionRename(HiveSchemaUtil.SchemaDifference schemaDifference) {
// in case a partition column has been renamed, spec needs to be adjusted too
if (!schemaDifference.getMissingFromSecond().isEmpty()) {
FieldSchema oldField = schemaDifference.getMissingFromFirst().get(0);
FieldSchema updatedField = schemaDifference.getMissingFromSecond().get(0);
if (icebergTable.spec().fields().stream().anyMatch(pf -> pf.name().equals(oldField.getName()))) {
updatePartitionSpec = transaction.updateSpec();
updatePartitionSpec.renameField(oldField.getName(), updatedField.getName());
updatePartitionSpec.commit();
}
}
}
private Type.PrimitiveType getPrimitiveTypeOrThrow(FieldSchema field) throws MetaException {
Type newType = HiveSchemaUtil.convert(TypeInfoUtils.getTypeInfoFromTypeString(field.getType()));
if (!(newType instanceof Type.PrimitiveType)) {
throw new MetaException(String.format("Cannot promote type of column: '%s' to a non-primitive type: %s.",
field.getName(), newType));
}
return (Type.PrimitiveType) newType;
}
private class PreAlterTableProperties {
private String tableLocation;
private String format;
private Schema schema;
private PartitionSpec spec;
private List<FieldSchema> partitionKeys;
}
}
|
package uk.gov.hmcts.reform.divorce.validationservice.rules.divorce.session;
import com.deliveredtechnologies.rulebook.annotation.Given;
import com.deliveredtechnologies.rulebook.annotation.Result;
import com.deliveredtechnologies.rulebook.annotation.Rule;
import com.deliveredtechnologies.rulebook.annotation.Then;
import com.deliveredtechnologies.rulebook.annotation.When;
import lombok.Data;
import uk.gov.hmcts.reform.divorce.validationservice.domain.request.DivorceSession;
import java.util.List;
import java.util.Optional;
@Rule(order = 8)
@Data
public class PetitionerContactDetailsConfidential {
private static final String BLANK_SPACE = " ";
private static final String ACTUAL_DATA = "Actual data is: %s";
private static final String ERROR_MESSAGE = "petitionerContactDetailsConfidential can not be null or empty.";
@Result
public List<String> result;
@Given("divorceSession")
public DivorceSession divorceSession = new DivorceSession();
@When
public boolean when() {
return !Optional.ofNullable(divorceSession.getPetitionerContactDetailsConfidential()).isPresent();
}
@Then
public void then() {
result.add(String.join(
BLANK_SPACE, // delimiter
ERROR_MESSAGE,
String.format(ACTUAL_DATA, divorceSession.getPetitionerContactDetailsConfidential())
));
}
}
|
package com.planet_ink.coffee_mud.CharClasses;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Libraries.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;
import java.util.*;
/*
Copyright 2004-2017 Bo Zimmerman
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.
*/
public class Gaoler extends StdCharClass
{
@Override
public String ID()
{
return "Gaoler";
}
private final static String localizedStaticName = CMLib.lang().L("Gaoler");
@Override
public String name()
{
return localizedStaticName;
}
@Override
public String baseClass()
{
return "Commoner";
}
@Override
public int getBonusPracLevel()
{
return 2;
}
@Override
public int getBonusAttackLevel()
{
return -1;
}
@Override
public int getAttackAttribute()
{
return CharStats.STAT_STRENGTH;
}
@Override
public int getLevelsPerBonusDamage()
{
return 5;
}
@Override
public String getHitPointsFormula()
{
return "((@x6<@x7)/6)+(1*(1?5))";
}
@Override
public String getManaFormula()
{
return "((@x4<@x5)/10)+(1*(1?2))";
}
@Override
public int allowedArmorLevel()
{
return CharClass.ARMOR_CLOTH;
}
@Override
public int allowedWeaponLevel()
{
return CharClass.WEAPONS_FLAILONLY;
}
private final Set<Integer> disallowedWeapons = buildDisallowedWeaponClasses();
@Override
protected Set<Integer> disallowedWeaponClasses(MOB mob)
{
return disallowedWeapons;
}
@Override
public int availabilityCode()
{
return Area.THEME_FANTASY;
}
public Hashtable<String, int[]> mudHourMOBXPMap = new Hashtable<String, int[]>();
public Gaoler()
{
super();
maxStatAdj[CharStats.STAT_STRENGTH]=6;
maxStatAdj[CharStats.STAT_DEXTERITY]=6;
}
@Override
public void initializeClass()
{
super.initializeClass();
CMLib.ableMapper().addCharAbilityMapping(ID(),1,"Skill_Write",true);
CMLib.ableMapper().addCharAbilityMapping(ID(),1,"Specialization_Natural",false);
CMLib.ableMapper().addCharAbilityMapping(ID(),1,"Specialization_FlailedWeapon",true);
CMLib.ableMapper().addCharAbilityMapping(ID(),1,"Skill_Recall",25,true);
CMLib.ableMapper().addCharAbilityMapping(ID(),1,"Skill_Swim",false);
CMLib.ableMapper().addCharAbilityMapping(ID(),1,"Skill_Climb",true);
CMLib.ableMapper().addCharAbilityMapping(ID(),1,"ClanCrafting",false);
CMLib.ableMapper().addCharAbilityMapping(ID(),1,"SmokeRings",true);
CMLib.ableMapper().addCharAbilityMapping(ID(),1,"Cooking",false);
CMLib.ableMapper().addCharAbilityMapping(ID(),1,"Baking",false);
CMLib.ableMapper().addCharAbilityMapping(ID(),1,"FoodPrep",false);
CMLib.ableMapper().addCharAbilityMapping(ID(),2,"Butchering",false);
CMLib.ableMapper().addCharAbilityMapping(ID(),3,"BodyPiercing",true);
CMLib.ableMapper().addCharAbilityMapping(ID(),4,"Searching",false);
CMLib.ableMapper().addCharAbilityMapping(ID(),5,"Blacksmithing",true);
CMLib.ableMapper().addCharAbilityMapping(ID(),6,"Carpentry",false);
CMLib.ableMapper().addCharAbilityMapping(ID(),7,"Tattooing",true);
CMLib.ableMapper().addCharAbilityMapping(ID(),8,"LockSmith",false);
CMLib.ableMapper().addCharAbilityMapping(ID(),9,"Skill_Warrants",true);
CMLib.ableMapper().addCharAbilityMapping(ID(),10,"Thief_Hide",false);
// CMLib.ableMapper().addCharAbilityMapping(ID(),10,"Skill_MakeSomeoneSleeplessAndFatigued",false);
// CMLib.ableMapper().addCharAbilityMapping(ID(),10,"Skill_Waterboard",false);
CMLib.ableMapper().addCharAbilityMapping(ID(),11,"Spell_Brainwash",true);
CMLib.ableMapper().addCharAbilityMapping(ID(),12,"Skill_ArrestingSap",true);
CMLib.ableMapper().addCharAbilityMapping(ID(),13,"Skill_HandCuff",false);
CMLib.ableMapper().addCharAbilityMapping(ID(),14,"Thief_TarAndFeather",true);
CMLib.ableMapper().addCharAbilityMapping(ID(),15,"Thief_Flay",false);
CMLib.ableMapper().addCharAbilityMapping(ID(),16,"Torturesmithing",false,CMParms.parseSemicolons("Carpentry,Blacksmithing(75)",true),"+INT 14");
CMLib.ableMapper().addCharAbilityMapping(ID(),17,"Skill_Leeching",false);
CMLib.ableMapper().addCharAbilityMapping(ID(),18,"Skill_CollectBounty",true);
CMLib.ableMapper().addCharAbilityMapping(ID(),19,"Skill_Arrest",false);
CMLib.ableMapper().addCharAbilityMapping(ID(),20,"Fighter_Behead",true);
CMLib.ableMapper().addCharAbilityMapping(ID(),21,"Prayer_Stoning",false);
CMLib.ableMapper().addCharAbilityMapping(ID(),22,"SlaveTrading",true);
CMLib.ableMapper().addCharAbilityMapping(ID(),23,"Skill_Enslave",false);
CMLib.ableMapper().addCharAbilityMapping(ID(),24,"Skill_JailKey",true);
CMLib.ableMapper().addCharAbilityMapping(ID(),25,"Skill_Chirgury",false,CMParms.parseSemicolons("Butchering",true));
CMLib.ableMapper().addCharAbilityMapping(ID(),30,"Amputation",true);
// to separate from artisam
CMLib.ableMapper().addCharAbilityMapping(ID(),-1,"Chopping",0,"",false,true);
CMLib.ableMapper().addCharAbilityMapping(ID(),-1,"Digging",0,"",false,true);
CMLib.ableMapper().addCharAbilityMapping(ID(),-1,"Drilling",0,"",false,true);
CMLib.ableMapper().addCharAbilityMapping(ID(),-1,"Fishing",0,"",false,true);
CMLib.ableMapper().addCharAbilityMapping(ID(),-1,"Foraging",0,"",false,true);
CMLib.ableMapper().addCharAbilityMapping(ID(),-1,"Herbology",0,"",false,true);
CMLib.ableMapper().addCharAbilityMapping(ID(),-1,"Cobbling",0,"",false,true,CMParms.parseSemicolons("LeatherWorking",true),"");
CMLib.ableMapper().addCharAbilityMapping(ID(),-1,"Hunting",0,"",false,true);
CMLib.ableMapper().addCharAbilityMapping(ID(),-1,"Mining",0,"",false,true);
CMLib.ableMapper().addCharAbilityMapping(ID(),-1,"Pottery",0,"",false,true);
CMLib.ableMapper().addCharAbilityMapping(ID(),-1,"ScrimShaw",0,"",false,true);
CMLib.ableMapper().addCharAbilityMapping(ID(),-1,"LeatherWorking",0,"",false,true);
CMLib.ableMapper().addCharAbilityMapping(ID(),-1,"GlassBlowing",0,"",false,true);
CMLib.ableMapper().addCharAbilityMapping(ID(),-1,"Sculpting",0,"",false,true);
CMLib.ableMapper().addCharAbilityMapping(ID(),-1,"Tailoring",0,"",false,true);
CMLib.ableMapper().addCharAbilityMapping(ID(),-1,"Weaving",0,"",false,true);
CMLib.ableMapper().addCharAbilityMapping(ID(),-1,"CageBuilding",0,"",false,true);
CMLib.ableMapper().addCharAbilityMapping(ID(),-1,"JewelMaking",0,"",false,true);
CMLib.ableMapper().addCharAbilityMapping(ID(),-1,"Dyeing",0,"",false,true);
CMLib.ableMapper().addCharAbilityMapping(ID(),-1,"Shearing",0,"",false,true);
CMLib.ableMapper().addCharAbilityMapping(ID(),-1,"Embroidering",0,"",false,true,CMParms.parseSemicolons("Skill_Write",true),"");
CMLib.ableMapper().addCharAbilityMapping(ID(),-1,"Engraving",0,"",false,true,CMParms.parseSemicolons("Skill_Write",true),"");
CMLib.ableMapper().addCharAbilityMapping(ID(),-1,"Lacquerring",0,"",false,true);
CMLib.ableMapper().addCharAbilityMapping(ID(),-1,"Smelting",0,"",false,true);
CMLib.ableMapper().addCharAbilityMapping(ID(),-1,"Armorsmithing",0,"",false,true,CMParms.parseSemicolons("Blacksmithing",true),"");
CMLib.ableMapper().addCharAbilityMapping(ID(),-1,"Fletching",0,"",false,true);
CMLib.ableMapper().addCharAbilityMapping(ID(),-1,"Weaponsmithing",0,"",false,true,CMParms.parseSemicolons("Blacksmithing;Specialization_*",true),"");
CMLib.ableMapper().addCharAbilityMapping(ID(),-1,"Shipwright",0,"",false,true,CMParms.parseSemicolons("Carpentry",true),"");
CMLib.ableMapper().addCharAbilityMapping(ID(),-1,"Wainwrighting",0,"",false,true,CMParms.parseSemicolons("Carpentry",true),"");
CMLib.ableMapper().addCharAbilityMapping(ID(),-1,"PaperMaking",0,"",false,true);
CMLib.ableMapper().addCharAbilityMapping(ID(),-1,"Distilling",0,"",false,true);
CMLib.ableMapper().addCharAbilityMapping(ID(),-1,"Farming",0,"",false,true);
CMLib.ableMapper().addCharAbilityMapping(ID(),-1,"Speculate",0,"",false,true);
CMLib.ableMapper().addCharAbilityMapping(ID(),-1,"Painting",0,"",false,true);
CMLib.ableMapper().addCharAbilityMapping(ID(),-1,"Construction",0,"",false,true,CMParms.parseSemicolons("Carpentry",true),"");
CMLib.ableMapper().addCharAbilityMapping(ID(),-1,"Masonry",0,"",false,true);
CMLib.ableMapper().addCharAbilityMapping(ID(),-1,"Excavation",0,"",false,true);
CMLib.ableMapper().addCharAbilityMapping(ID(),-1,"Irrigation",0,"",false,true);
CMLib.ableMapper().addCharAbilityMapping(ID(),-1,"Landscaping",0,"",false,true);
CMLib.ableMapper().addCharAbilityMapping(ID(),-1,"Taxidermy",0,"",false,true);
CMLib.ableMapper().addCharAbilityMapping(ID(),-1,"Merchant",0,"",false,true);
CMLib.ableMapper().addCharAbilityMapping(ID(),-1,"Scrapping",0,"",false,true);
CMLib.ableMapper().addCharAbilityMapping(ID(),-1,"Costuming",0,"",false,true);
}
@Override
public boolean tick(Tickable ticking, int tickID)
{
if((tickID==Tickable.TICKID_MOB)&&(ticking instanceof MOB))
{
final MOB mob=(MOB)ticking;
if(mob.charStats().getCurrentClass().ID().equals(ID()))
{
int exp=0;
for(final Enumeration<Ability> a=mob.effects();a.hasMoreElements();)
{
final Ability A=a.nextElement();
if((A!=null)
&&(!A.isAutoInvoked())
&&(mob.isMine(A))
&&((A.classificationCode()&Ability.ALL_ACODES)==Ability.ACODE_COMMON_SKILL))
exp++;
}
if(exp>0)
CMLib.leveler().postExperience(mob,null,null,exp,true);
}
}
return super.tick(ticking,tickID);
}
@Override
public void executeMsg(Environmental host, CMMsg msg)
{
if((msg.source()==host)
&&(msg.target() instanceof MOB)
&&(msg.target()!=msg.source())
&&(((MOB)host).charStats().getCurrentClass().ID().equals(ID()))
&&(msg.tool() instanceof Ability)
&&((MOB)host).isMine(msg.tool())
&&(msg.tool().ID().equals("Thief_Flay")
||msg.tool().ID().equals("Skill_Chirgury")
||msg.tool().ID().equals("Tattooing")
||msg.tool().ID().equals("Thief_TarAndFeather")
||msg.tool().ID().equals("BodyPiercing")
||msg.tool().ID().equals("Amputation"))
&&(CMLib.map().getStartArea(host)!=null)
&&(((MOB)host).charStats().getClassLevel(this)>0))
{
final CMMsg msg2=CMClass.getMsg((MOB)msg.target(),null,null,CMMsg.MSG_NOISE,L("<S-NAME> scream(s) in agony, AAAAAAARRRRGGGHHH!!@x1",CMLib.protocol().msp("scream.wav",40)));
if(((MOB)msg.target()).location().okMessage(msg.target(),msg2))
{
final int xp=(int)Math.round(10.0*CMath.div(((MOB)msg.target()).phyStats().level(),((MOB)host).charStats().getClassLevel(this)));
int[] done=mudHourMOBXPMap.get(host.Name()+"/"+msg.tool().ID());
if (done == null)
{
done = new int[3];
mudHourMOBXPMap.put(host.Name() + "/" + msg.tool().ID(), done);
}
if(Calendar.getInstance().get(Calendar.SECOND)!=done[2])
{
final TimeClock clock =CMLib.map().getStartArea(host).getTimeObj();
if(done[0]!=clock.getHourOfDay())
done[1]=0;
done[0]=clock.getHourOfDay();
done[2]=Calendar.getInstance().get(Calendar.SECOND);
if(done[1]<(90+(10*((MOB)host).phyStats().level())))
{
done[1]+=xp;
CMLib.leveler().postExperience((MOB)host,null,null,xp,true);
msg2.addTrailerMsg(CMClass.getMsg((MOB)host,null,null,CMMsg.MSG_OK_VISUAL,L("The sweet screams of your victim earns you @x1 experience points.",""+xp),CMMsg.NO_EFFECT,null,CMMsg.NO_EFFECT,null));
}
else
msg2.addTrailerMsg(CMClass.getMsg((MOB)host,null,null,CMMsg.MSG_OK_VISUAL,L("The screams of this victim bore you now."),CMMsg.NO_EFFECT,null,CMMsg.NO_EFFECT,null));
msg.addTrailerMsg(msg2);
}
}
}
}
private final String[] raceRequiredList = new String[] { "All" };
@Override
public String[] getRequiredRaceList()
{
return raceRequiredList;
}
@SuppressWarnings("unchecked")
private final Pair<String,Integer>[] minimumStatRequirements=new Pair[]{
new Pair<String,Integer>("Strength",Integer.valueOf(5)),
new Pair<String,Integer>("Dexterity",Integer.valueOf(5))
};
@Override
public Pair<String, Integer>[] getMinimumStatRequirements()
{
return minimumStatRequirements;
}
@Override
public List<Item> outfit(MOB myChar)
{
if(outfitChoices==null)
{
final Weapon w=CMClass.getWeapon("Whip");
if(w == null)
return new Vector<Item>();
outfitChoices=new Vector<Item>();
outfitChoices.add(w);
}
return outfitChoices;
}
@Override
public String getOtherBonusDesc()
{
return L("Gains experience when using certain skills. Screams of flayed, amputated, tattooed, body pierced, or chirguried victims grants xp/hr.");
}
}
|
/*
* 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.isis.testdomain.model.good;
import java.util.List;
import org.apache.isis.applib.annotation.DomainObject;
import org.apache.isis.applib.annotation.Nature;
@DomainObject(nature = Nature.VIEW_MODEL)
public class ProperFullyImpl
extends ProperFullyAbstract {
@Override
public String title() {
return "title";
}
@Override
public String iconName() {
return "icon";
}
@Override
public String cssClass() {
return "css";
}
@Override
public String layout() {
return "layout";
}
@Override
public void sampleAction() {
}
@Override
public String getSampleProperty() {
return null;
}
@Override
public void setSampleProperty(final String sampleProperty) {
}
@Override
public List<String> getSampleCollection() {
return null;
}
@Override
public void setSampleCollection(final List<String> sampleCollection) {
}
}
|
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1
begin_comment
comment|/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */
end_comment
begin_package
DECL|package|org.apache.camel.itest.springboot
package|package
name|org
operator|.
name|apache
operator|.
name|camel
operator|.
name|itest
operator|.
name|springboot
package|;
end_package
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|camel
operator|.
name|itest
operator|.
name|springboot
operator|.
name|util
operator|.
name|ArquillianPackager
import|;
end_import
begin_import
import|import
name|org
operator|.
name|jboss
operator|.
name|arquillian
operator|.
name|container
operator|.
name|test
operator|.
name|api
operator|.
name|Deployment
import|;
end_import
begin_import
import|import
name|org
operator|.
name|jboss
operator|.
name|arquillian
operator|.
name|junit
operator|.
name|Arquillian
import|;
end_import
begin_import
import|import
name|org
operator|.
name|jboss
operator|.
name|shrinkwrap
operator|.
name|api
operator|.
name|Archive
import|;
end_import
begin_import
import|import
name|org
operator|.
name|junit
operator|.
name|Test
import|;
end_import
begin_import
import|import
name|org
operator|.
name|junit
operator|.
name|runner
operator|.
name|RunWith
import|;
end_import
begin_class
annotation|@
name|RunWith
argument_list|(
name|Arquillian
operator|.
name|class
argument_list|)
DECL|class|CamelAtomTest
specifier|public
class|class
name|CamelAtomTest
extends|extends
name|AbstractSpringBootTestSupport
block|{
annotation|@
name|Deployment
DECL|method|createSpringBootPackage ()
specifier|public
specifier|static
name|Archive
argument_list|<
name|?
argument_list|>
name|createSpringBootPackage
parameter_list|()
throws|throws
name|Exception
block|{
return|return
name|ArquillianPackager
operator|.
name|springBootPackage
argument_list|(
name|createTestConfig
argument_list|()
argument_list|)
return|;
block|}
DECL|method|createTestConfig ()
specifier|public
specifier|static
name|ITestConfig
name|createTestConfig
parameter_list|()
block|{
return|return
operator|new
name|ITestConfigBuilder
argument_list|()
operator|.
name|module
argument_list|(
name|inferModuleName
argument_list|(
name|CamelAtomTest
operator|.
name|class
argument_list|)
argument_list|)
operator|.
name|build
argument_list|()
return|;
block|}
annotation|@
name|Test
DECL|method|componentTests ()
specifier|public
name|void
name|componentTests
parameter_list|()
throws|throws
name|Exception
block|{
name|this
operator|.
name|runComponentTest
argument_list|(
name|config
argument_list|)
expr_stmt|;
name|this
operator|.
name|runModuleUnitTestsIfEnabled
argument_list|(
name|config
argument_list|)
expr_stmt|;
block|}
block|}
end_class
end_unit
|
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE369_Divide_by_Zero__int_Environment_divide_67b.java
Label Definition File: CWE369_Divide_by_Zero__int.label.xml
Template File: sources-sinks-67b.tmpl.java
*/
/*
* @description
* CWE: 369 Divide by zero
* BadSource: Environment Read data from an environment variable
* GoodSource: A hardcoded non-zero, non-min, non-max, even number
* Sinks: divide
* GoodSink: Check for zero before dividing
* BadSink : Dividing by a value that may be zero
* Flow Variant: 67 Data flow: data passed in a class from one method to another in different source files in the same package
*
* */
public class CWE369_Divide_by_Zero__int_Environment_divide_67b
{
public void badSink(CWE369_Divide_by_Zero__int_Environment_divide_67a.Container dataContainer ) throws Throwable
{
int data = dataContainer.containerOne;
/* POTENTIAL FLAW: Zero denominator will cause an issue. An integer division will
result in an exception. */
IO.writeLine("bad: 100/" + data + " = " + (100 / data) + "\n");
}
/* goodG2B() - use goodsource and badsink */
public void goodG2BSink(CWE369_Divide_by_Zero__int_Environment_divide_67a.Container dataContainer ) throws Throwable
{
int data = dataContainer.containerOne;
/* POTENTIAL FLAW: Zero denominator will cause an issue. An integer division will
result in an exception. */
IO.writeLine("bad: 100/" + data + " = " + (100 / data) + "\n");
}
/* goodB2G() - use badsource and goodsink */
public void goodB2GSink(CWE369_Divide_by_Zero__int_Environment_divide_67a.Container dataContainer ) throws Throwable
{
int data = dataContainer.containerOne;
/* FIX: test for a zero denominator */
if (data != 0)
{
IO.writeLine("100/" + data + " = " + (100 / data) + "\n");
}
else
{
IO.writeLine("This would result in a divide by zero");
}
}
}
|
package proguard.classfile.attribute.annotation.target;
import proguard.classfile.Clazz;
import proguard.classfile.Method;
import proguard.classfile.attribute.annotation.TypeAnnotation;
import proguard.classfile.attribute.annotation.target.visitor.TargetInfoVisitor;
public class TypeParameterTargetInfo
extends TargetInfo
{
public int u1typeParameterIndex;
public TypeParameterTargetInfo() {}
public TypeParameterTargetInfo(byte u1targetType)
{
super(u1targetType);
}
public TypeParameterTargetInfo(byte u1targetType, int u1typeParameterIndex)
{
super(u1targetType);
this.u1typeParameterIndex = u1typeParameterIndex;
}
public void accept(Clazz clazz, TypeAnnotation typeAnnotation, TargetInfoVisitor targetInfoVisitor)
{
targetInfoVisitor.visitTypeParameterTargetInfo(clazz, typeAnnotation, this);
}
public void accept(Clazz clazz, Method method, TypeAnnotation typeAnnotation, TargetInfoVisitor targetInfoVisitor)
{
targetInfoVisitor.visitTypeParameterTargetInfo(clazz, method, typeAnnotation, this);
}
}
|
package com.games.review.service;
public class UsernameAlreadyUsedException extends RuntimeException {
public UsernameAlreadyUsedException() {
super("Login name already used!");
}
}
|
package io.quarkiverse.operatorsdk.it;
import javax.enterprise.context.ApplicationScoped;
import io.javaoperatorsdk.operator.api.Context;
import io.javaoperatorsdk.operator.api.Controller;
import io.javaoperatorsdk.operator.api.ResourceController;
import io.javaoperatorsdk.operator.api.UpdateControl;
@ApplicationScoped
@Controller(name = ApplicationScopedController.NAME)
public class ApplicationScopedController implements ResourceController<ChildTestResource> {
public static final String NAME = "ApplicationScoped";
@Override
public UpdateControl<ChildTestResource> createOrUpdateResource(ChildTestResource childTestResource,
Context<ChildTestResource> context) {
return UpdateControl.noUpdate();
}
}
|
/*
* Copyright 2011-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not
* use this file except in compliance with the License. A copy of the License is
* located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.services.iot.model.transform;
import java.util.Map;
import java.util.List;
import com.amazonaws.AmazonClientException;
import com.amazonaws.services.iot.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.util.BinaryUtils;
import com.amazonaws.util.StringUtils;
import com.amazonaws.util.IdempotentUtils;
import com.amazonaws.util.StringInputStream;
import com.amazonaws.protocol.json.*;
/**
* CACertificateMarshaller
*/
public class CACertificateJsonMarshaller {
/**
* Marshall the given parameter object, and output to a SdkJsonGenerator
*/
public void marshall(CACertificate cACertificate,
StructuredJsonGenerator jsonGenerator) {
if (cACertificate == null) {
throw new AmazonClientException(
"Invalid argument passed to marshall(...)");
}
try {
jsonGenerator.writeStartObject();
if (cACertificate.getCertificateArn() != null) {
jsonGenerator.writeFieldName("certificateArn").writeValue(
cACertificate.getCertificateArn());
}
if (cACertificate.getCertificateId() != null) {
jsonGenerator.writeFieldName("certificateId").writeValue(
cACertificate.getCertificateId());
}
if (cACertificate.getStatus() != null) {
jsonGenerator.writeFieldName("status").writeValue(
cACertificate.getStatus());
}
if (cACertificate.getCreationDate() != null) {
jsonGenerator.writeFieldName("creationDate").writeValue(
cACertificate.getCreationDate());
}
jsonGenerator.writeEndObject();
} catch (Throwable t) {
throw new AmazonClientException(
"Unable to marshall request to JSON: " + t.getMessage(), t);
}
}
private static CACertificateJsonMarshaller instance;
public static CACertificateJsonMarshaller getInstance() {
if (instance == null)
instance = new CACertificateJsonMarshaller();
return instance;
}
}
|
/*
* Copyright (c) 2020 the original author or authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.jmnarloch.aws.events.matchers;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import com.fasterxml.jackson.databind.node.ObjectNode;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import static java.util.stream.Collectors.toList;
public class AnythingButMatcher extends Matcher {
private static final String OPERATOR = "anything-but";
private final Object[] values;
public AnythingButMatcher(Object[] values) {
this.values = values;
}
public Object[] getValues() {
return values;
}
@Override
protected Collection<JsonNode> toJson() {
final List<JsonNode> vals = Arrays.stream(values)
.map(this::valuesToJson)
.collect(toList());
return Collections.singleton(createNode(vals));
}
private ObjectNode createNode(List<JsonNode> vals) {
final ObjectNode node = JsonNodeFactory.instance.objectNode();
if (vals.size() > 1) {
final ArrayNode valuesArray = node.putArray(OPERATOR);
vals.forEach(valuesArray::add);
} else {
node.set(OPERATOR, vals.get(0));
}
return node;
}
}
|
/*
* Waxeye Parser Generator
* www.waxeye.org
* Copyright (C) 2008-2010 Orlando Hill
* Licensed under the MIT license. See 'LICENSE' for details.
*/
package org.waxeye.input;
import java.io.ByteArrayInputStream;
import java.io.StringReader;
import static org.testng.Assert.*;
import org.testng.annotations.Test;
/**
* Tests for BufferFiller.
*
* @author Orlando Hill
*/
public final class BufferFillerTest
{
private final String data = "ù%*é=^``~&°.:!§,?/#çà][-|";
private final char[] expected = data.toCharArray();
/** Test for asArray(InputStream). */
@Test
public void asArrayInputStream()
{
final byte[] bytes = data.getBytes();
final ByteArrayInputStream bs = new ByteArrayInputStream(bytes);
assertEquals(BufferFiller.asArray(bs), expected);
}
/** Test for asArray(Reader). */
@Test
public void asArrayReader()
{
final StringReader sr = new StringReader(data);
assertEquals(BufferFiller.asArray(sr), expected);
}
}
|
/*
* Copyright 1997-2019 Unidata Program Center/University Corporation for
* Atmospheric Research, P.O. Box 3000, Boulder, CO 80307,
* support@unidata.ucar.edu.
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or (at
* your option) any later version.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser
* General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this library; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package ucar.unidata.idv;
import ucar.unidata.idv.ui.IdvUIManager;
import ucar.unidata.util.GuiUtils;
import ucar.unidata.util.HttpServer;
import ucar.unidata.util.IOUtil;
import ucar.unidata.util.LogUtil;
import ucar.unidata.util.Misc;
import ucar.unidata.xml.XmlUtil;
import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Hashtable;
/**
* Used for other idv instances to connect to so we only have one running at a time.
*/
public class OneInstanceServer extends HttpServer {
/** http arg */
public static final String ARG_ARGS = "args";
/** The idv_ */
IntegratedDataViewer idv;
/** The localhost */
InetAddress localHost;
/**
* ctor
*
* @param idv The idv
* @param port The port to listen on
*/
public OneInstanceServer(IntegratedDataViewer idv, int port) {
super(port);
this.idv = idv;
}
/**
* Handle the error
*
* @param msg Error message_
* @param exc Exception
*/
protected void handleError(String msg, Exception exc) {
LogUtil.consoleMessage(msg);
LogUtil.consoleMessage("Exception:" + exc);
}
/**
* Create the url that we ping
*
* @param port The port to connect to
* @param args The command line args
*
* @return The url
*
* @throws Exception On badness
*/
static String assembleUrl(int port, String[] args) throws Exception {
return "http://localhost:" + port + "?" + ARG_ARGS + "="
+ URLEncoder.encode(
XmlUtil.encodeBase64(Misc.serialize(args)), "UTF-8");
}
/**
* Make the handler for this connection
*
* @param socket The connection
*
* @return The handler
*
* @throws Exception On badness
*/
protected RequestHandler doMakeRequestHandler(Socket socket)
throws Exception {
if (localHost == null) {
localHost = InetAddress.getLocalHost();
}
InetAddress inet = socket.getInetAddress();
// System.err.println("inet:" + inet.getHostAddress() + " localhost:" + localHost.getHostAddress());
//Only accept requests from localhost
if ( !inet.getHostAddress().equals("127.0.0.1")) {
return null;
}
// System.err.println ("got request");
// Misc.sleepSeconds(120);
return new OneInstanceRequestHandler(idv, this, socket);
}
/**
* Class OneInstanceRequestHandler the handler
*
*
* @author IDV Development Team
* @version $Revision: 1.11 $
*/
public static class OneInstanceRequestHandler extends HttpServer
.RequestHandler {
/** The idv */
IntegratedDataViewer idv;
/**
* ctor
*
* @param idv the idv
* @param server the server
* @param socket the socket we handle the connection of
*
* @throws Exception On badness
*/
public OneInstanceRequestHandler(IntegratedDataViewer idv,
HttpServer server, Socket socket)
throws Exception {
super(server, socket);
this.idv = idv;
}
/**
* Handle the request. This reads the command line arguments, writes back "ok",
* nad has the idv process the args.
*
* @param path url path. ignored.
* @param formArgs form args
* @param httpArgs http args
* @param content content. unused.
*
* @throws Exception On badness
*/
protected void handleRequest(String path, Hashtable formArgs,
Hashtable httpArgs, String content)
throws Exception {
String argStr = (String) formArgs.get(ARG_ARGS);
byte[] argBytes = XmlUtil.decodeBase64(argStr);
String[] args = (String[]) Misc.deserialize(argBytes);
writeResult(true, "ok", "text");
idv.getArgsManager().processInstanceArgs(args);
idv.getIdvUIManager().toFrontMainWindows();
}
}
}
|
/*
* Copyright (c) 2020 Tobias Briones. All rights reserved.
*
* SPDX-License-Identifier: MIT
*
* This file is part of Example Project: Factura.
*
* This source code is licensed under the MIT License found in the
* LICENSE file in the root directory of this source tree or at
* https://opensource.org/licenses/MIT.
*/
package dev.tobiasbriones.ep.factura.ui.mainbilling.print;
import dev.tobiasbriones.ep.factura.ui.core.MvcController;
final class PrintController extends MvcController<PrintView, Print.Output> {
private PrintView view;
PrintController() {
super();
this.view = null;
}
@Override
public PrintView getView() {
return view;
}
@Override
public void setView(PrintView value) {
view = value;
}
@Override
public void init() {
view.update();
}
void onPrintButtonClick() {
final boolean mustCreateNewCustomer = view.isCreateNewCustomerSelected();
getOutput().ifPresent(output -> {
if (mustCreateNewCustomer) {
output.onPrintWithNewCustomer();
}
else {
output.onPrint();
}
});
}
}
|
package moriyashiine.bewitchment.common.fortune;
import moriyashiine.bewitchment.api.component.MagicComponent;
import moriyashiine.bewitchment.api.registry.Fortune;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.server.world.ServerWorld;
public class ExhaustedFortune extends Fortune {
public ExhaustedFortune(boolean positive) {
super(positive);
}
@Override
public boolean finish(ServerWorld world, PlayerEntity target) {
return MagicComponent.get(target).drainMagic(50, false);
}
}
|
/**
* Copyright 2013 MIR@MU Project
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package cz.muni.fi.mir.mathmlcanonicalization.utils;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.io.IOUtils;
import org.custommonkey.xmlunit.XMLTestCase;
import org.custommonkey.xmlunit.XMLUnit;
import org.junit.Test;
import org.xml.sax.SAXException;
import static org.junit.Assert.*;
/**
*
* @author Michal Růžička
*/
public class DTDManipulatorTest {
private static final Logger LOGGER = Logger.getLogger(DTDManipulatorTest.class.getName());
private static final String RESOURCE_SUBDIR = DTDManipulatorTest.class.getSimpleName() + "/";
/**
* Test of injectXHTML11PlusMathML20PlusSVG11DTD method, of class
* DTDManipulator.
*/
@Test
public void testInjectXHTMLPlusMathMLPlusSVGDTD() throws IOException {
System.out.println("testInjectXHTMLPlusMathMLDTD");
InputStream in = this.getClass().getResourceAsStream(RESOURCE_SUBDIR + "injectXHTMLPlusMathMLPlusSVGDTD.input.xml");
InputStream expResult = this.getClass().getResourceAsStream(RESOURCE_SUBDIR + "injectXHTMLPlusMathMLPlusSVGDTD.output.xml");
InputStream result = DTDManipulator.injectXHTML11PlusMathML20PlusSVG11DTD(in);
StringWriter resultWriter = new StringWriter();
IOUtils.copy(result, resultWriter, StandardCharsets.UTF_8);
String resultString = resultWriter.toString();
StringWriter expResultWriter = new StringWriter();
IOUtils.copy(expResult, expResultWriter, StandardCharsets.UTF_8);
String expResultString = expResultWriter.toString();
assertEquals("DTD not properly injected", expResultString, resultString);
}
/**
* Test of removeDTD method, of class DTDManipulator.
*/
@Test
public void testRemoveDTD() throws Exception {
System.out.println("removeDTD");
InputStream in = this.getClass().getResourceAsStream(RESOURCE_SUBDIR + "testRemoveDTD.input.xml");
InputStreamReader result = new InputStreamReader(DTDManipulator.removeDTD(in));
StringWriter resultWriter = new StringWriter();
IOUtils.copy(result, resultWriter);
String resultString = resultWriter.toString();
assertFalse("DTD not properly removed – string '<!DOCTYPE' presented in the result", resultString.contains("<!DOCTYPE"));
InputStreamReader expResult = new InputStreamReader(this.getClass().getResourceAsStream(RESOURCE_SUBDIR + "testRemoveDTD.output.xml"));
// Once read, the input stream can not be read again.
in = this.getClass().getResourceAsStream(RESOURCE_SUBDIR + "testRemoveDTD.input.xml");
result = new InputStreamReader(DTDManipulator.removeDTD(in));
XMLUnit.setIgnoreWhitespace(true);
XMLUnit.setExpandEntityReferences(true);
try {
new XMLTestCase() {
}.assertXMLEqual("DTD not properly removed – result differs from expected code", expResult, result);
} catch (SAXException ex) {
LOGGER.log(Level.SEVERE, "cannot compare XML streams", ex);
}
}
}
|
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1
begin_comment
comment|/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */
end_comment
begin_package
DECL|package|org.apache.camel.component.google.calendar
package|package
name|org
operator|.
name|apache
operator|.
name|camel
operator|.
name|component
operator|.
name|google
operator|.
name|calendar
package|;
end_package
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|camel
operator|.
name|builder
operator|.
name|RouteBuilder
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|camel
operator|.
name|component
operator|.
name|google
operator|.
name|calendar
operator|.
name|internal
operator|.
name|CalendarAclApiMethod
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|camel
operator|.
name|component
operator|.
name|google
operator|.
name|calendar
operator|.
name|internal
operator|.
name|GoogleCalendarApiCollection
import|;
end_import
begin_import
import|import
name|org
operator|.
name|junit
operator|.
name|Test
import|;
end_import
begin_import
import|import
name|org
operator|.
name|slf4j
operator|.
name|Logger
import|;
end_import
begin_import
import|import
name|org
operator|.
name|slf4j
operator|.
name|LoggerFactory
import|;
end_import
begin_comment
comment|/** * Test class for {@link com.google.api.services.calendar.Calendar$Acl} APIs. */
end_comment
begin_class
DECL|class|CalendarAclIntegrationTest
specifier|public
class|class
name|CalendarAclIntegrationTest
extends|extends
name|AbstractGoogleCalendarTestSupport
block|{
DECL|field|LOG
specifier|private
specifier|static
specifier|final
name|Logger
name|LOG
init|=
name|LoggerFactory
operator|.
name|getLogger
argument_list|(
name|CalendarAclIntegrationTest
operator|.
name|class
argument_list|)
decl_stmt|;
DECL|field|PATH_PREFIX
specifier|private
specifier|static
specifier|final
name|String
name|PATH_PREFIX
init|=
name|GoogleCalendarApiCollection
operator|.
name|getCollection
argument_list|()
operator|.
name|getApiName
argument_list|(
name|CalendarAclApiMethod
operator|.
name|class
argument_list|)
operator|.
name|getName
argument_list|()
decl_stmt|;
annotation|@
name|Test
DECL|method|testList ()
specifier|public
name|void
name|testList
parameter_list|()
throws|throws
name|Exception
block|{
comment|// using String message body for single parameter "calendarId"
specifier|final
name|com
operator|.
name|google
operator|.
name|api
operator|.
name|services
operator|.
name|calendar
operator|.
name|model
operator|.
name|Acl
name|result
init|=
name|requestBody
argument_list|(
literal|"direct://LIST"
argument_list|,
name|getCalendar
argument_list|()
operator|.
name|getId
argument_list|()
argument_list|)
decl_stmt|;
comment|// should have at least one rule (reader, owner, etc.) for the calendar
comment|// or we wouldn't be able to view it!
name|assertTrue
argument_list|(
name|result
operator|.
name|getItems
argument_list|()
operator|.
name|size
argument_list|()
operator|>
literal|0
argument_list|)
expr_stmt|;
name|LOG
operator|.
name|debug
argument_list|(
literal|"list: "
operator|+
name|result
argument_list|)
expr_stmt|;
block|}
annotation|@
name|Override
DECL|method|createRouteBuilder ()
specifier|protected
name|RouteBuilder
name|createRouteBuilder
parameter_list|()
throws|throws
name|Exception
block|{
return|return
operator|new
name|RouteBuilder
argument_list|()
block|{
annotation|@
name|Override
specifier|public
name|void
name|configure
parameter_list|()
block|{
comment|// test route for delete
name|from
argument_list|(
literal|"direct://DELETE"
argument_list|)
operator|.
name|to
argument_list|(
literal|"google-calendar://"
operator|+
name|PATH_PREFIX
operator|+
literal|"/delete"
argument_list|)
expr_stmt|;
comment|// test route for get
name|from
argument_list|(
literal|"direct://GET"
argument_list|)
operator|.
name|to
argument_list|(
literal|"google-calendar://"
operator|+
name|PATH_PREFIX
operator|+
literal|"/get"
argument_list|)
expr_stmt|;
comment|// test route for insert
name|from
argument_list|(
literal|"direct://INSERT"
argument_list|)
operator|.
name|to
argument_list|(
literal|"google-calendar://"
operator|+
name|PATH_PREFIX
operator|+
literal|"/insert"
argument_list|)
expr_stmt|;
comment|// test route for list
name|from
argument_list|(
literal|"direct://LIST"
argument_list|)
operator|.
name|to
argument_list|(
literal|"google-calendar://"
operator|+
name|PATH_PREFIX
operator|+
literal|"/list?inBody=calendarId"
argument_list|)
expr_stmt|;
comment|// test route for patch
name|from
argument_list|(
literal|"direct://PATCH"
argument_list|)
operator|.
name|to
argument_list|(
literal|"google-calendar://"
operator|+
name|PATH_PREFIX
operator|+
literal|"/patch"
argument_list|)
expr_stmt|;
comment|// test route for update
name|from
argument_list|(
literal|"direct://UPDATE"
argument_list|)
operator|.
name|to
argument_list|(
literal|"google-calendar://"
operator|+
name|PATH_PREFIX
operator|+
literal|"/update"
argument_list|)
expr_stmt|;
comment|// test route for watch
name|from
argument_list|(
literal|"direct://WATCH"
argument_list|)
operator|.
name|to
argument_list|(
literal|"google-calendar://"
operator|+
name|PATH_PREFIX
operator|+
literal|"/watch"
argument_list|)
expr_stmt|;
block|}
block|}
return|;
block|}
block|}
end_class
end_unit
|
/*
* Copyright 2010-2013 Ning, Inc.
*
* Ning licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.billing.payment.invoice;
import java.util.UUID;
import org.killbill.billing.ObjectType;
import org.killbill.billing.account.api.Account;
import org.killbill.billing.account.api.AccountApiException;
import org.killbill.billing.account.api.AccountInternalApi;
import org.killbill.billing.callcontext.InternalCallContext;
import org.killbill.billing.events.ControlTagDeletionInternalEvent;
import org.killbill.billing.osgi.api.OSGIServiceRegistration;
import org.killbill.billing.payment.core.PaymentProcessor;
import org.killbill.billing.routing.plugin.api.PaymentRoutingPluginApi;
import org.killbill.billing.util.callcontext.CallOrigin;
import org.killbill.billing.util.callcontext.InternalCallContextFactory;
import org.killbill.billing.util.callcontext.UserType;
import org.killbill.billing.util.tag.ControlTagType;
import org.killbill.clock.Clock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.eventbus.Subscribe;
import com.google.inject.Inject;
public class PaymentTagHandler {
private static final Logger log = LoggerFactory.getLogger(PaymentTagHandler.class);
private final Clock clock;
private final AccountInternalApi accountApi;
private final PaymentProcessor paymentProcessor;
private final InternalCallContextFactory internalCallContextFactory;
private final OSGIServiceRegistration<PaymentRoutingPluginApi> paymentControlPluginRegistry;
private final PaymentRoutingPluginApi invoicePaymentControlPlugin;
@Inject
public PaymentTagHandler(final Clock clock,
final AccountInternalApi accountApi,
final PaymentProcessor paymentProcessor,
final OSGIServiceRegistration<PaymentRoutingPluginApi> paymentControlPluginRegistry,
final InternalCallContextFactory internalCallContextFactory) {
this.clock = clock;
this.accountApi = accountApi;
this.paymentProcessor = paymentProcessor;
this.paymentControlPluginRegistry = paymentControlPluginRegistry;
this.invoicePaymentControlPlugin = paymentControlPluginRegistry.getServiceForName(InvoicePaymentRoutingPluginApi.PLUGIN_NAME);
this.internalCallContextFactory = internalCallContextFactory;
}
@Subscribe
public void process_AUTO_PAY_OFF_removal(final ControlTagDeletionInternalEvent event) {
if (event.getTagDefinition().getName().equals(ControlTagType.AUTO_PAY_OFF.toString()) && event.getObjectType() == ObjectType.ACCOUNT) {
final UUID accountId = event.getObjectId();
processUnpaid_AUTO_PAY_OFF_payments(accountId, event.getSearchKey1(), event.getSearchKey2(), event.getUserToken());
}
}
private void processUnpaid_AUTO_PAY_OFF_payments(final UUID accountId, final Long accountRecordId, final Long tenantRecordId, final UUID userToken) {
try {
final InternalCallContext internalCallContext = internalCallContextFactory.createInternalCallContext(tenantRecordId, accountRecordId,
"PaymentRequestProcessor", CallOrigin.INTERNAL, UserType.SYSTEM, userToken);
final Account account = accountApi.getAccountById(accountId, internalCallContext);
((InvoicePaymentRoutingPluginApi) invoicePaymentControlPlugin).process_AUTO_PAY_OFF_removal(account, internalCallContext);
} catch (AccountApiException e) {
log.warn(String.format("Failed to process process removal AUTO_PAY_OFF for account %s", accountId), e);
}
}
}
|
/**
* Copyright 2009-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.ibatis.submitted.sql;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.SelectProvider;
import org.apache.ibatis.builder.annotation.ProviderMethodResolver;
import org.apache.ibatis.jdbc.SQL;
public interface Mapper {
@SelectProvider(type = SqlProvider.class)
List<User> findAll(@Param("offset") long offset, @Param("limit") int limit);
class SqlProvider implements ProviderMethodResolver {
public String findAll() {
return new SQL()
.SELECT("user_id", "name")
.FROM("${schema}users")
.ORDER_BY("user_id")
.OFFSET_ROWS("#{offset}")
.FETCH_FIRST_ROWS_ONLY("#{limit}")
.toString();
}
}
}
|
/*-
* #%L
* Coffee
* %%
* Copyright (C) 2020 i-Cell Mobilsoft Zrt.
* %%
* 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 hu.icellmobilsoft.roaster.tm4j.common;
import javax.inject.Qualifier;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
/**
* CDI qualifier for rest implementations
*
* @author martin.nagy
* @since 0.2.0
*/
@Target({ TYPE, METHOD, PARAMETER, FIELD })
@Retention(RUNTIME)
@Qualifier
public @interface Tm4jRest {
}
|
/*
* Copyright 2002-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.aggregator;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.Map;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.integration.handler.support.MessagingMethodInvokerHelper;
import org.springframework.integration.support.management.ManageableLifecycle;
import org.springframework.integration.util.AbstractExpressionEvaluator;
import org.springframework.lang.NonNull;
import org.springframework.messaging.Message;
/**
* A MessageListProcessor implementation that invokes a method on a target POJO.
*
* @author Dave Syer
* @author Artem Bilan
* @author Gary Russell
*
* @since 2.0
*/
public class MethodInvokingMessageListProcessor<T> extends AbstractExpressionEvaluator
implements ManageableLifecycle {
private final MessagingMethodInvokerHelper delegate;
public MethodInvokingMessageListProcessor(Object targetObject, Method method, Class<T> expectedType) {
this.delegate = new MessagingMethodInvokerHelper(targetObject, method, expectedType, true);
}
public MethodInvokingMessageListProcessor(Object targetObject, Method method) {
this.delegate = new MessagingMethodInvokerHelper(targetObject, method, true);
}
public MethodInvokingMessageListProcessor(Object targetObject, String methodName, Class<T> expectedType) {
this.delegate = new MessagingMethodInvokerHelper(targetObject, methodName,
expectedType, true);
}
public MethodInvokingMessageListProcessor(Object targetObject, String methodName) {
this.delegate = new MessagingMethodInvokerHelper(targetObject, methodName, true);
}
public MethodInvokingMessageListProcessor(Object targetObject, Class<? extends Annotation> annotationType) {
this.delegate = new MessagingMethodInvokerHelper(targetObject, annotationType, Object.class, true);
}
@Override
public void setBeanFactory(@NonNull BeanFactory beanFactory) {
super.setBeanFactory(beanFactory);
this.delegate.setBeanFactory(beanFactory);
}
/**
* A {@code boolean} flag to use SpEL Expression evaluation or
* {@link org.springframework.messaging.handler.invocation.InvocableHandlerMethod}
* for target method invocation.
* @param useSpelInvoker to use SpEL Expression evaluation or not.
* @since 5.0
*/
public void setUseSpelInvoker(boolean useSpelInvoker) {
this.delegate.setUseSpelInvoker(useSpelInvoker);
}
@Override
public String toString() {
return this.delegate.toString();
}
@SuppressWarnings("unchecked")
public T process(Collection<Message<?>> messages, Map<String, Object> aggregateHeaders) {
return (T) this.delegate.process(messages, aggregateHeaders);
}
@Override
public void start() {
this.delegate.start();
}
@Override
public void stop() {
this.delegate.stop();
}
@Override
public boolean isRunning() {
return this.delegate.isRunning();
}
}
|
package main;
import com.eudycontreras.othello.controllers.AgentController.DeepeningType;
import com.eudycontreras.othello.enumerations.GameMode;
/**
* <H2>Created by</h2> Eudy Contreras
* <h4> Mozilla Public License 2.0 </h4>
* Licensed under the Mozilla Public License 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
* <a href="https://www.mozilla.org/en-US/MPL/2.0/">visit Mozilla Public Lincense Version 2.0</a>
* <H2>Class description</H2>
*
* @author Eudy Contreras
*
*/
public class UserSettings {
/**
* If deepening logic is use please define here
*/
public static final DeepeningType DEEPENING = DeepeningType.NONE;
/**
* Determines the game mode to use
*/
public static final GameMode GAME_MODE = GameMode.HUMAN_VS_AGENT;
/**
* Delay before the game starts when the agent is playing
*/
public static final int START_DELAY = 1000;
/**
* Used for defining the maximum search time.
* By popular rules the max search time should not
* go above 5000 milliseconds;
*/
public static final int MAX_SEARCH_TIME = 5000;
/**
* Used for defining the minimum search time
* If the search is done before the minimum search time
* the move will not be made until the the minimum time
* has passed. Adjust in order for play consistency. when
* Human vs Agent is activated.
*/
public static final int MIN_SEARCH_TIME = 0;
/**
* Used for defining the search time
*/
public static final int SEARCH_TIME = 2500;
/**
* The time it take for each Agent to play when
* Agent vs Agent is active. Adjust to better see
* play sequence or to make the game go quick.
*/
public static final int TURN_INTERVAL = 0;
/**
* Used for defining the maximum value
*/
public static final int MAX_VALUE = Integer.MAX_VALUE;
/**
* Used for defining the minimum value
*/
public static final int MIN_VALUE = Integer.MIN_VALUE;
/**
* The name of the player one : White player
* The name must be less than 15 characters long
* Any name with more than 14 characters will be cut off.
*/
public static final String PLAYER_ONE = "Player One";
/**
* The name of the player two : Black player
* The name must be less than 15 characters long.
* Any name with more than 14 characters will be cut off.
*/
public static final String PLAYER_TWO = "Player Two";
/**
* Determines whether or not animations should be used
* The animations may reduce performance on some systems.
* Specially on systems running other OS than windows. This
* is off by default.
*/
public static final boolean USE_ANIMATION = (TURN_INTERVAL >= 1000) ;
/**
* This defines the scale at which the
* game is rendered. This options helps
* for cases where the game resolution is either
* too big or to small recommended values range
* from 0.4 to 1.4 and a value of 1.0 is default
* Play around to find your sweet spot.
*/
public static final double GAME_WINDOW_SCALE = 0.9d;
/**
* The size of the board:
* The size can be 4, 6, or 8 any other value
* will be converted to the closest valid value
* The default size of the Othello board is 8x8
*/
public static final int BOARD_GRID_SIZE = 8;
/**
* The theme which is to be set to the board
* There are a total of 14 available themes
* Choose a number between 0 and 13. You may also
* cycle through themes in game
*/
public static final int THEME_INDEX = 0;
/**
* Weight from high to low. The higher the
* weight the higher the reward. Take a look at
* the weight matrix insidet the AgentController to see how
* the weights are distributed. Feel free to modify
* the weights in order to achieve desired heuristics
*/
public static final int A = 256;
public static final int B = 128;
public static final int C = 64;
public static final int D = 8;
public static final int E = 4;
public static final int F = 2;
public static final int G = -128;
public static final int H = -256;
}
|
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.naming.core.v2.index;
import com.alibaba.nacos.common.notify.Event;
import com.alibaba.nacos.common.notify.NotifyCenter;
import com.alibaba.nacos.common.notify.listener.SmartSubscriber;
import com.alibaba.nacos.common.utils.ConcurrentHashSet;
import com.alibaba.nacos.naming.core.v2.client.Client;
import com.alibaba.nacos.naming.core.v2.event.client.ClientEvent;
import com.alibaba.nacos.naming.core.v2.event.client.ClientOperationEvent;
import com.alibaba.nacos.naming.core.v2.event.service.ServiceEvent;
import com.alibaba.nacos.naming.core.v2.pojo.Service;
import org.springframework.stereotype.Component;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
/**
* Client and service index manager.
*
* @author xiweng.yy
*/
@Component
public class ClientServiceIndexesManager extends SmartSubscriber {
private final ConcurrentMap<Service, Set<String>> publisherIndexes = new ConcurrentHashMap<>();
private final ConcurrentMap<Service, Set<String>> subscriberIndexes = new ConcurrentHashMap<>();
public ClientServiceIndexesManager() {
NotifyCenter.registerSubscriber(this);
}
public Collection<String> getAllClientsRegisteredService(Service service) {
return publisherIndexes.containsKey(service) ? publisherIndexes.get(service) : new ConcurrentHashSet<>();
}
public Collection<String> getAllClientsSubscribeService(Service service) {
return subscriberIndexes.containsKey(service) ? subscriberIndexes.get(service) : new ConcurrentHashSet<>();
}
public Collection<Service> getSubscribedService() {
return subscriberIndexes.keySet();
}
/**
* Clear the service index without instances.
*
* @param service The service of the Nacos.
*/
public void removePublisherIndexesByEmptyService(Service service) {
if (publisherIndexes.containsKey(service) && publisherIndexes.get(service).isEmpty()) {
publisherIndexes.remove(service);
}
}
@Override
public List<Class<? extends Event>> subscribeTypes() {
List<Class<? extends Event>> result = new LinkedList<>();
result.add(ClientOperationEvent.ClientRegisterServiceEvent.class);
result.add(ClientOperationEvent.ClientDeregisterServiceEvent.class);
result.add(ClientOperationEvent.ClientSubscribeServiceEvent.class);
result.add(ClientOperationEvent.ClientUnsubscribeServiceEvent.class);
result.add(ClientEvent.ClientDisconnectEvent.class);
return result;
}
@Override
public void onEvent(Event event) {
if (event instanceof ClientEvent.ClientDisconnectEvent) {
handleClientDisconnect((ClientEvent.ClientDisconnectEvent) event);
} else if (event instanceof ClientOperationEvent) {
handleClientOperation((ClientOperationEvent) event);
}
}
private void handleClientDisconnect(ClientEvent.ClientDisconnectEvent event) {
Client client = event.getClient();
for (Service each : client.getAllSubscribeService()) {
removeSubscriberIndexes(each, client.getClientId());
}
for (Service each : client.getAllPublishedService()) {
removePublisherIndexes(each, client.getClientId());
}
}
private void handleClientOperation(ClientOperationEvent event) {
Service service = event.getService();
String clientId = event.getClientId();
if (event instanceof ClientOperationEvent.ClientRegisterServiceEvent) {
addPublisherIndexes(service, clientId);
} else if (event instanceof ClientOperationEvent.ClientDeregisterServiceEvent) {
removePublisherIndexes(service, clientId);
} else if (event instanceof ClientOperationEvent.ClientSubscribeServiceEvent) {
addSubscriberIndexes(service, clientId);
} else if (event instanceof ClientOperationEvent.ClientUnsubscribeServiceEvent) {
removeSubscriberIndexes(service, clientId);
}
}
private void addPublisherIndexes(Service service, String clientId) {
publisherIndexes.computeIfAbsent(service, (key) -> new ConcurrentHashSet<>());
publisherIndexes.get(service).add(clientId);
NotifyCenter.publishEvent(new ServiceEvent.ServiceChangedEvent(service, true));
}
private void removePublisherIndexes(Service service, String clientId) {
if (!publisherIndexes.containsKey(service)) {
return;
}
publisherIndexes.get(service).remove(clientId);
NotifyCenter.publishEvent(new ServiceEvent.ServiceChangedEvent(service, true));
}
private void addSubscriberIndexes(Service service, String clientId) {
subscriberIndexes.computeIfAbsent(service, (key) -> new ConcurrentHashSet<>());
// Fix #5404, Only first time add need notify event.
if (subscriberIndexes.get(service).add(clientId)) {
NotifyCenter.publishEvent(new ServiceEvent.ServiceSubscribedEvent(service, clientId));
}
}
private void removeSubscriberIndexes(Service service, String clientId) {
if (!subscriberIndexes.containsKey(service)) {
return;
}
subscriberIndexes.get(service).remove(clientId);
if (subscriberIndexes.get(service).isEmpty()) {
subscriberIndexes.remove(service);
}
}
}
|
package BeltLineApplication.java.model;
public class Manager extends Employee {
}
|
/*
* RED5 Open Source Flash Server - https://github.com/red5 Copyright 2006-2015 by respective authors (see below). All rights reserved. Licensed under the Apache License, Version
* 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless
* required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language governing permissions and limitations under the License.
*/
package org.red5.net.websocket.codec.extension;
/**
* Extension to WebSocket which provides per-message deflate.
*
* @see <a href="http://tools.ietf.org/html/draft-ietf-hybi-permessage-compression-18">IETF Draft</a>
* @see <a href="https://www.igvita.com/2013/11/27/configuring-and-optimizing-websocket-compression/">Configuration and optimization</a>
*
* @author Paul Gregoire
*/
public class PerMessageDeflateExt implements WebSocketExtension {
private static final String id = "permessage-deflate";
/** {@inheritDoc} */
public String getId() {
return id;
}
}
|
package com.xianglesong.dao;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Component;
import java.util.Calendar;
import javax.annotation.Resource;
@Component
public class MongoDao {
public static Logger logger = LoggerFactory.getLogger(MongoDao.class);
@Resource(name = "serverMongoTemplate")
public MongoTemplate mongoTemplate;
public void execute() {
// mongoTemplate.getDb().collectionExists("searchIndex");
System.out.println(mongoTemplate.getDb().collectionExists("searchIndex"));
System.out.println("execute: " + Calendar.getInstance());
}
}
|
/*
* Copyright 2004-2010 Information & Software Engineering Group (188/1)
* Institute of Software Technology and Interactive Systems
* Vienna University of Technology, Austria
*
* 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.ifs.tuwien.ac.at/dm/somtoolbox/license.html
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package at.tuwien.ifs.somtoolbox.util;
/**
* A singleton factory creating {@link ProgressListener ProgressListeners}. If an instance of a ProgressListener is set,
* this instance is returned instead of creating a new one. This allows calling applications to set their own
* ProgressListener, while preserving backwards compatibility.
*
* @author Christoph Becker
* @version $Id: ProgressListenerFactory.java 3583 2010-05-21 10:07:41Z mayer $
*/
public class ProgressListenerFactory {
private static ProgressListenerFactory me = null;
private ProgressListener listener = null;
/**
* @param numIterations maxIterations
* @return the singleton progress listener
*/
public ProgressListener createProgressListener(int numIterations, String iteration) {
return createProgressListener(numIterations, iteration, 1);
}
public ProgressListener createProgressListener(int numIterations, String iteration, int stepWidth) {
if (listener != null) {
return listener;
}
return new StdErrProgressWriter(numIterations, iteration, stepWidth);
}
public ProgressListener createProgressListener(int numIterations, String iteration, int stepWidth, int newLineWidth) {
if (listener != null) {
return listener;
}
return new StdErrProgressWriter(numIterations, iteration, stepWidth, newLineWidth);
}
public static ProgressListenerFactory getInstance() {
if (me == null) {
me = new ProgressListenerFactory();
}
return me;
}
public ProgressListener getListener() {
return listener;
}
public void setListener(ProgressListener listener) {
this.listener = listener;
}
}
|
/*
* Copyright 2019 ConsenSys AG.
*
* 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 tech.pegasys.teku.storage.client;
import static com.google.common.base.Preconditions.checkNotNull;
import static tech.pegasys.teku.datastructures.util.BeaconStateUtil.compute_start_slot_at_epoch;
import static tech.pegasys.teku.datastructures.util.BeaconStateUtil.get_committee_count_at_slot;
import static tech.pegasys.teku.infrastructure.async.SafeFuture.completedFuture;
import static tech.pegasys.teku.util.config.Constants.SLOTS_PER_EPOCH;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.primitives.UnsignedLong;
import java.util.ArrayList;
import java.util.List;
import java.util.NavigableMap;
import java.util.Optional;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.tuweni.bytes.Bytes32;
import tech.pegasys.teku.core.StateTransition;
import tech.pegasys.teku.core.exceptions.EpochProcessingException;
import tech.pegasys.teku.core.exceptions.SlotProcessingException;
import tech.pegasys.teku.datastructures.blocks.BeaconBlock;
import tech.pegasys.teku.datastructures.blocks.BeaconBlockAndState;
import tech.pegasys.teku.datastructures.blocks.SignedBeaconBlock;
import tech.pegasys.teku.datastructures.blocks.SlotAndBlockRoot;
import tech.pegasys.teku.datastructures.state.BeaconState;
import tech.pegasys.teku.datastructures.state.CommitteeAssignment;
import tech.pegasys.teku.datastructures.util.CommitteeUtil;
import tech.pegasys.teku.infrastructure.async.SafeFuture;
import tech.pegasys.teku.storage.api.StorageQueryChannel;
import tech.pegasys.teku.storage.store.UpdatableStore;
public class CombinedChainDataClient {
private static final Logger LOG = LogManager.getLogger();
private static final SafeFuture<Optional<BeaconState>> STATE_NOT_AVAILABLE =
completedFuture(Optional.empty());
private static final SafeFuture<Optional<SignedBeaconBlock>> BLOCK_NOT_AVAILABLE =
completedFuture(Optional.empty());
private final RecentChainData recentChainData;
private final StorageQueryChannel historicalChainData;
private final StateTransition stateTransition;
public CombinedChainDataClient(
final RecentChainData recentChainData, final StorageQueryChannel historicalChainData) {
this.recentChainData = recentChainData;
this.historicalChainData = historicalChainData;
this.stateTransition = new StateTransition();
}
public CombinedChainDataClient(
final RecentChainData recentChainData,
final StorageQueryChannel historicalChainData,
final StateTransition stateTransition) {
this.recentChainData = recentChainData;
this.historicalChainData = historicalChainData;
this.stateTransition = stateTransition;
}
/**
* Returns the block proposed at the requested slot. If the slot is empty, no block is returned.
*
* @param slot the slot to get the block for
* @return the block at the requested slot or empty if the slot was empty
*/
public SafeFuture<Optional<SignedBeaconBlock>> getBlockAtSlotExact(final UnsignedLong slot) {
return getBlockInEffectAtSlot(slot)
.thenApply(maybeBlock -> maybeBlock.filter(block -> block.getSlot().equals(slot)));
}
/**
* Returns the block proposed for the requested slot on the chain identified by <code>
* headBlockRoot</code>. If the slot was empty, no block is returned.
*
* @param slot the slot to get the block for
* @param headBlockRoot the block root of the head of the chain
* @return the block at the requested slot or empty if the slot was empty
*/
public SafeFuture<Optional<SignedBeaconBlock>> getBlockAtSlotExact(
final UnsignedLong slot, final Bytes32 headBlockRoot) {
return getBlockInEffectAtSlot(slot, headBlockRoot)
.thenApply(maybeBlock -> maybeBlock.filter(block -> block.getSlot().equals(slot)));
}
/**
* Returns the block which was proposed in or most recently before the requested slot on the chain
* specified by <code>headBlockRoot</code>. If the slot was empty, the block at the last filled
* slot is returned.
*
* @param slot the slot to get the effective block for
* @return the block at slot or the closest previous slot if empty
*/
private SafeFuture<Optional<SignedBeaconBlock>> getBlockInEffectAtSlot(
final UnsignedLong slot, Bytes32 headBlockRoot) {
if (!isStoreAvailable()) {
return BLOCK_NOT_AVAILABLE;
}
// Try to pull root from recent data
final Optional<Bytes32> recentRoot = recentChainData.getBlockRootBySlot(slot, headBlockRoot);
if (recentRoot.isPresent()) {
return getBlockByBlockRoot(recentRoot.get());
}
return historicalChainData.getLatestFinalizedBlockAtSlot(slot);
}
public SafeFuture<Optional<SignedBeaconBlock>> getBlockInEffectAtSlot(final UnsignedLong slot) {
if (!isChainDataFullyAvailable()) {
return BLOCK_NOT_AVAILABLE;
}
// Try to pull root from recent data
final Optional<Bytes32> recentRoot = recentChainData.getBlockRootBySlot(slot);
if (recentRoot.isPresent()) {
return getBlockByBlockRoot(recentRoot.get());
}
return historicalChainData.getLatestFinalizedBlockAtSlot(slot);
}
public SafeFuture<Optional<BeaconBlockAndState>> getBlockAndStateInEffectAtSlot(
final UnsignedLong slot) {
return getBlockInEffectAtSlot(slot)
.thenCompose(
maybeBlock ->
maybeBlock
.map(SignedBeaconBlock::getMessage)
.map(this::getStateForBlock)
.orElseGet(() -> SafeFuture.completedFuture(Optional.empty())));
}
public SafeFuture<Optional<BeaconState>> getStateAtSlotExact(final UnsignedLong slot) {
return getBlockAndStateInEffectAtSlot(slot)
.thenApplyChecked(
maybeBlockAndState ->
maybeBlockAndState.flatMap(
blockAndState -> regenerateBeaconState(blockAndState.getState(), slot)));
}
private SafeFuture<Optional<BeaconBlockAndState>> getStateForBlock(final BeaconBlock block) {
return getStateByBlockRoot(block.hash_tree_root())
.thenApply(maybeState -> maybeState.map(state -> new BeaconBlockAndState(block, state)));
}
public boolean isFinalized(final UnsignedLong slot) {
final UnsignedLong finalizedEpoch = recentChainData.getFinalizedEpoch();
final UnsignedLong finalizedSlot = compute_start_slot_at_epoch(finalizedEpoch);
return finalizedSlot.compareTo(slot) >= 0;
}
public boolean isFinalizedEpoch(final UnsignedLong epoch) {
final UnsignedLong finalizedEpoch = recentChainData.getFinalizedEpoch();
return finalizedEpoch.compareTo(epoch) >= 0;
}
/**
* Returns the latest state at the given slot on the current chain.
*
* @param slot the slot to get the state for
* @return the State at slot
*/
public SafeFuture<Optional<BeaconState>> getLatestStateAtSlot(final UnsignedLong slot) {
if (!isChainDataFullyAvailable()) {
return STATE_NOT_AVAILABLE;
}
if (isRecentData(slot)) {
return recentChainData
.retrieveStateInEffectAtSlot(slot)
.thenCompose(
recentState -> {
if (recentState.isPresent()) {
return completedFuture(recentState);
}
// Fall-through to historical query in case state has moved into historical range
// during processing
return historicalChainData.getLatestFinalizedStateAtSlot(slot);
});
}
return historicalChainData.getLatestFinalizedStateAtSlot(slot);
}
public SafeFuture<Optional<BeaconState>> getStateByBlockRoot(final Bytes32 blockRoot) {
final UpdatableStore store = getStore();
if (store == null) {
LOG.trace("No state at blockRoot {} because the store is not set", blockRoot);
return STATE_NOT_AVAILABLE;
}
return store
.retrieveBlockState(blockRoot)
.thenCompose(
maybeState -> {
if (maybeState.isPresent()) {
return completedFuture(maybeState);
}
return historicalChainData.getFinalizedStateByBlockRoot(blockRoot);
});
}
public SafeFuture<Optional<BeaconState>> getStateByStateRoot(final Bytes32 stateRoot) {
final UpdatableStore store = getStore();
if (store == null) {
LOG.trace("No state at stateRoot {} because the store is not set", stateRoot);
return STATE_NOT_AVAILABLE;
}
return historicalChainData
.getSlotAndBlockRootByStateRoot(stateRoot)
.thenCompose(
maybeSlotAndBlockRoot ->
maybeSlotAndBlockRoot
.map(this::getStateFromSlotAndBlock)
.orElseGet(() -> getFinalizedStateFromStateRoot(stateRoot)));
}
private SafeFuture<Optional<BeaconState>> getFinalizedStateFromStateRoot(
final Bytes32 stateRoot) {
return historicalChainData
.getFinalizedSlotByStateRoot(stateRoot)
.thenCompose(
maybeSlot -> maybeSlot.map(this::getStateAtSlotExact).orElse(STATE_NOT_AVAILABLE));
}
private SafeFuture<Optional<BeaconState>> getStateFromSlotAndBlock(
final SlotAndBlockRoot slotAndBlockRoot) {
return getStateByBlockRoot(slotAndBlockRoot.getBlockRoot())
.thenApply(
maybeState ->
maybeState.flatMap(
preState -> regenerateBeaconState(preState, slotAndBlockRoot.getSlot())));
}
private Optional<BeaconState> regenerateBeaconState(
final BeaconState preState, final UnsignedLong slot) {
if (preState.getSlot().equals(slot)) {
return Optional.of(preState);
} else if (slot.compareTo(getBestSlot()) > 0) {
LOG.debug("Attempted to wind forward to a future state: {}", slot.toString());
return Optional.empty();
}
try {
return Optional.of(stateTransition.process_slots(preState, slot));
} catch (SlotProcessingException | EpochProcessingException | IllegalArgumentException e) {
LOG.debug("State Transition error", e);
return Optional.empty();
}
}
public Optional<BeaconState> getHeadStateFromStore() {
return recentChainData.getBestState();
}
public Optional<Bytes32> getBestBlockRoot() {
return recentChainData.getBestBlockRoot();
}
public Optional<SignedBeaconBlock> getBestBlock() {
return recentChainData.getBestBlock();
}
public boolean isStoreAvailable() {
return recentChainData != null && recentChainData.getStore() != null;
}
public boolean isChainDataFullyAvailable() {
return !recentChainData.isPreGenesis() && !recentChainData.isPreForkChoice();
}
public List<CommitteeAssignment> getCommitteesFromState(
BeaconState state, UnsignedLong startingSlot) {
List<CommitteeAssignment> result = new ArrayList<>();
for (int i = 0; i < SLOTS_PER_EPOCH; i++) {
UnsignedLong slot = startingSlot.plus(UnsignedLong.valueOf(i));
int committeeCount = get_committee_count_at_slot(state, slot).intValue();
for (int j = 0; j < committeeCount; j++) {
UnsignedLong idx = UnsignedLong.valueOf(j);
List<Integer> committee = CommitteeUtil.get_beacon_committee(state, slot, idx);
result.add(new CommitteeAssignment(committee, idx, slot));
}
}
return result;
}
public UnsignedLong getBestSlot() {
return this.recentChainData.getBestSlot();
}
@VisibleForTesting
public UpdatableStore getStore() {
return recentChainData.getStore();
}
public NavigableMap<UnsignedLong, Bytes32> getAncestorRoots(
final UnsignedLong startSlot, final UnsignedLong step, final UnsignedLong count) {
return recentChainData.getAncestorRoots(startSlot, step, count);
}
public SafeFuture<Optional<SignedBeaconBlock>> getBlockByBlockRoot(final Bytes32 blockRoot) {
return recentChainData
.retrieveSignedBlockByRoot(blockRoot)
.thenCompose(
maybeBlock -> {
if (maybeBlock.isPresent()) {
return SafeFuture.completedFuture(maybeBlock);
}
return historicalChainData.getBlockByBlockRoot(blockRoot);
});
}
private boolean isRecentData(final UnsignedLong slot) {
checkNotNull(slot);
if (recentChainData.isPreGenesis()) {
return false;
}
final UnsignedLong finalizedSlot = recentChainData.getStore().getLatestFinalizedBlockSlot();
return slot.compareTo(finalizedSlot) >= 0;
}
}
|
package de.homelab.madgaksha.lotsofbs.enums;
public enum TrackingOrientationStrategy {
MINIBALL,
ABSOLUTE,
RELATIVE;
}
|
package com.jslabs.gophysicengine.simulation;
/**
* <p>Title: Go! PhysicEngine</p>
*
* <p>Description: Moteur physique permettant la simulation de la dynamique des
* corps rigides.</p>
* <p>This exception is thrown whenever a scene contains objects that cannot be
intialized correctly. Initialization procedure assigns mass, velocity and inertia.</p>
*
* <p>Copyright: Copyright (c) 2006</p>
*
* <p>Company: </p>
*
* @author Jerome Schmaltz
* @version 1.0
*/
public class CompilationException
extends Exception
{
/**
* Message sentence of this exception.
*/
private String _msg;
/**
* Return the message to the user.
*/
public String getMessage()
{
return _msg;
}
/**
* Default constructor of this class.
*/
public CompilationException(String message)
{
_msg = message;
}
}
|
package systems.whitestar.mediasite_monitor;
import com.bettercloud.vault.Vault;
import com.bettercloud.vault.VaultConfig;
import com.bettercloud.vault.VaultException;
import com.bettercloud.vault.response.AuthResponse;
import com.bettercloud.vault.response.LogicalResponse;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import lombok.extern.log4j.Log4j;
import javax.inject.Singleton;
import java.util.Map;
/**
* Manage Secrets in the Vault.
* Connection and authentication settings for the vault are set via Environment Variables to prevent them from being
* included in the code base accidentally.
* <p>
* VAULT_ADDR = Vault Address, including protocol (HTTP/S)
* VAULT_ROLE = For authentication via AppRole, Role ID
* VAULT_SECRET = AppRole Secret
* WWW_APP = App (Secret Key) Name in Vault
*
* @author Tom Paulus
* Created on 9/30/17.
*/
@Singleton
@Log4j
public class Secret {
private static Vault vault = null;
private static Secret secret = null;
private String mVaultAddr;
private String mRoleId;
private String mSecretId;
private String mAppName;
private VaultConfig vaultConfig;
Secret() throws VaultException {
mVaultAddr = System.getenv("VAULT_ADDR");
if (mVaultAddr.endsWith("/")) mVaultAddr = mVaultAddr.substring(0, mVaultAddr.length() - 2);
mRoleId = System.getenv("VAULT_ROLE");
mSecretId = System.getenv("VAULT_SECRET");
mAppName = System.getenv("MS_APP");
initializeVaultConnector();
}
public static Secret getInstance() {
try {
if (secret == null) secret = new Secret();
return secret;
} catch (VaultException e) {
log.fatal("Could not connect to Vault", e);
throw new RuntimeException(e);
}
}
/**
* Get a Secret String from the Default App Name
*
* @param secretName {@link String} Parameter Name
* @return {@link String} Secret Value
*/
public String getSecret(String secretName) {
return getSecret(mAppName, secretName, String.class);
}
/**
* Get a Secret from the Default App Name
*
* @param secretName {@link String} Parameter Name
* @param type {@link T} Retrieved Object Type
* @param <T> Retrieved Object Type
* @return {@link T} Secret Value
*/
public <T> T getSecret(String secretName, Class<T> type) {
return getSecret(mAppName, secretName, type);
}
/**
* Get a Secret String from a given app name
*
* @param appName {@link String} App Name
* @param secretName {@link String} Parameter Name
* @return {@link String} Secret Value
*/
public String getSecret(String appName, String secretName) {
return getSecret(appName, secretName, String.class);
}
/**
* Get a Secret String from a given app name
*
* @param appName {@link String} App Name
* @param secretName {@link String} Parameter Name
* @param type {@link T} Retrieved Object Type
* @param <T> Retrieved Object Type
* @return {@link T} Secret Value
*/
public <T> T getSecret(String appName, String secretName, Class<T> type) {
return getSecret(appName, secretName, type, true);
}
private <T> T getSecret(String appName, String secretName, Class<T> type, boolean retry) {
try {
String response = vault.logical()
.read("secret/" + appName)
.getData().get(secretName);
try {
return new Gson().fromJson(response, type);
} catch (JsonSyntaxException e) {
//noinspection unchecked
return (T) response;
}
} catch (VaultException e) {
if (e.getHttpStatusCode() == 403) {
log.info("Vault Token may be expired, or the Role permissions don't allow for us to access this option.");
try {
authenticate();
} catch (VaultException e1) {
log.error("Could not authenticate with the vault", e1);
throw new RuntimeException(e1);
}
if (retry) {
return getSecret(appName, secretName, type, false);
} else {
throw new RuntimeException(e);
}
} else {
log.error(String.format("Secret with name \"%s\" in app \"%s\" is not defined", secretName, appName));
throw new RuntimeException(e);
}
}
}
/**
* Get all secrets for the default application
*
* @return {@link Map} Secret Map
*/
public Map<String, String> getApplication() {
return getApplication(mAppName);
}
/**
* Get all secrets for the default application
*
* @return {@link Map} Secret Map
*/
public Map<String, String> getApplication(String appName) {
try {
return vault.logical()
.read("secret/" + appName)
.getData();
} catch (VaultException e) {
log.error(String.format("App \"%s\" is not defined", appName));
throw new RuntimeException(e);
}
}
/**
* Set a Secret Value of the default app
*
* @param secret {@link Map} Key, Value Mappings
* @return {@link LogicalResponse} Vault Response
*/
public LogicalResponse setSecret(Map<String, Object> secret) {
return setSecret(mAppName, secret);
}
/**
* Set a Secret Value of a given app
*
* @param appName {@link String} App Name
* @param secret {@link Map} Key, Value Mappings
* @return {@link LogicalResponse} Vault Response
*/
public LogicalResponse setSecret(String appName, Map<String, Object> secret) {
final Gson gson = new Gson();
log.debug("App Name: " + appName);
log.debug("Secret Payload: " + gson.toJson(secret));
for (final Map.Entry<String, Object> pair : secret.entrySet()) {
final Object value = pair.getValue();
if (value != null && !(value instanceof String)) {
pair.setValue(gson.toJson(value));
}
}
try {
return vault.logical()
.write("secret/" + appName, secret);
} catch (VaultException e) {
log.error(String.format("Problem writing secret %s", appName));
throw new RuntimeException(e);
}
}
/**
* Delete an App from the Vault
*
* @param appName {@link String } App Name
* @return {@link LogicalResponse} Vault Response
*/
LogicalResponse deleteSecret(String appName) {
log.warn(String.format("Deleting Secret %s", appName));
try {
return vault.logical().delete("secret/" + appName);
} catch (VaultException e) {
log.error(String.format("Problem deleting secret %s", appName));
throw new RuntimeException(e);
}
}
private void initializeVaultConnector() throws VaultException {
vaultConfig = new VaultConfig()
.address(mVaultAddr)
.build();
vault = new Vault(vaultConfig);
authenticate();
}
private void authenticate() throws VaultException {
AuthResponse response = vault.auth().loginByAppRole("approle", mRoleId, mSecretId);
vaultConfig.token(response.getAuthClientToken());
vault = new Vault(vaultConfig);
}
}
|
/*
Copyright 2018 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.alexa.myThaiStar;
import com.alexa.myThaiStar.handlers.CallFoodMenu;
import com.alexa.myThaiStar.handlers.CancelandStopIntentHandler;
import com.alexa.myThaiStar.handlers.DescriptionDishes;
import com.alexa.myThaiStar.handlers.DescriptionDrinks;
import com.alexa.myThaiStar.handlers.FallbackIntentHandler;
import com.alexa.myThaiStar.handlers.HelpIntentHandler;
import com.alexa.myThaiStar.handlers.LaunchRequestHandler;
import com.alexa.myThaiStar.handlers.SessionEndedRequestHandler;
import com.alexa.myThaiStar.handlers.OrderInhouse.AmountDishesOrCorrectExtras;
import com.alexa.myThaiStar.handlers.OrderInhouse.AmountDrinks;
import com.alexa.myThaiStar.handlers.OrderInhouse.AnotherDishOrDoUWantToDrink;
import com.alexa.myThaiStar.handlers.OrderInhouse.AnotherDishYesNoOrCorrectTheDish;
import com.alexa.myThaiStar.handlers.OrderInhouse.AnotherDrinkOrServeTimeYesNo;
import com.alexa.myThaiStar.handlers.OrderInhouse.AnotherDrinkYesNoOrCorrectTheDrink;
import com.alexa.myThaiStar.handlers.OrderInhouse.CloseOrder;
import com.alexa.myThaiStar.handlers.OrderInhouse.CloseOrderOrMakeServingTime;
import com.alexa.myThaiStar.handlers.OrderInhouse.Completed;
import com.alexa.myThaiStar.handlers.OrderInhouse.CustomerDetailsConfirmSlot;
import com.alexa.myThaiStar.handlers.OrderInhouse.DishesConfirmSlot;
import com.alexa.myThaiStar.handlers.OrderInhouse.DrinksConfirmSlot;
import com.alexa.myThaiStar.handlers.OrderInhouse.QueryTable;
import com.alexa.myThaiStar.handlers.OrderInhouse.StartedOrder;
import com.alexa.myThaiStar.handlers.OrderInhouse.WhichExtrasDishes;
import com.alexa.myThaiStar.handlers.OrderInhouse.EatOrDrink;
import com.alexa.myThaiStar.handlers.OrderInhouse.WhatDoUWantDoDrinkOrServeTimeYesNo;
import com.amazon.ask.Skill;
import com.amazon.ask.SkillStreamHandler;
import com.amazon.ask.Skills;
public class MyThaiStarStreamHandler extends SkillStreamHandler {
public static final String BASE_URL = "http://73a95b898c49.ngrok.io";
private static Skill getSkill() {
return Skills.standard()
.addRequestHandlers(new CancelandStopIntentHandler(),
new CallFoodMenu(),
new DescriptionDrinks(BASE_URL),
new DescriptionDishes(BASE_URL),
new HelpIntentHandler(),
new LaunchRequestHandler(),
new AnotherDishYesNoOrCorrectTheDish(),
new SessionEndedRequestHandler(),
new FallbackIntentHandler(),
new EatOrDrink(),
new WhatDoUWantDoDrinkOrServeTimeYesNo(),
new WhichExtrasDishes(),
new DrinksConfirmSlot(),
new DishesConfirmSlot(),
new Completed(),
new AnotherDrinkYesNoOrCorrectTheDrink(),
new AnotherDrinkOrServeTimeYesNo(),
new AnotherDishOrDoUWantToDrink(),
new AmountDrinks(),
new AmountDishesOrCorrectExtras(),
new QueryTable(),
new CustomerDetailsConfirmSlot(),
new CloseOrderOrMakeServingTime(),
new CloseOrder(),
new StartedOrder())
// Add your skill id below
.withSkillId("amzn1.ask.skill.b8b902af-2c98-409c-92be-3d0ff9c3096f").build();
}
public MyThaiStarStreamHandler() {
super(getSkill());
}
}
|
//
// LocalRegistrationInstanceNumber.java
// hclaps
//
// Created by Robert La Ferla on 1/26/06.
// Copyright 2006 Harvard University. All rights reserved.
//
package edu.harvard.hcl.hclaps.umid;
import edu.harvard.hcl.hclaps.util.ByteConvertor;
/**
* @author Robert La Ferla
*/
public class LocalRegistrationInstanceNumber extends InstanceNumber {
public void dump() {
System.out.println("*** Instance Number (Local Registration) ***");
for (int i = 0; i < 3; i++) {
System.out.print(ByteConvertor.hexForByte(value[i]));
}
System.out.println("");
}
}
|
/*
* #%L
* GwtMaterial
* %%
* Copyright (C) 2015 - 2016 GwtMaterialDesign
* %%
* 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 gwt.material.design.client.base.mixin;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.event.shared.HasHandlers;
import com.google.gwt.user.client.ui.UIObject;
import gwt.material.design.client.base.HasFieldSensitivity;
import gwt.material.design.client.base.HasInputType;
import gwt.material.design.client.constants.InputType;
import gwt.material.design.client.events.SensitivityChangedEvent;
/**
* @author Ben Dol
*/
public class FieldSensitivityMixin<T extends UIObject & HasFieldSensitivity & HasInputType> extends AbstractMixin<T>
implements HasFieldSensitivity {
protected final InputType defaultInputType;
public FieldSensitivityMixin(T uiObject) {
super(uiObject);
defaultInputType = uiObject.getType();
}
@Override
public void setSensitive(boolean sensitive) {
setSensitive(sensitive, false);
}
@Override
public void setSensitive(boolean sensitive, boolean fireEvents) {
uiObject.setType(sensitive ? InputType.PASSWORD : defaultInputType);
if (fireEvents) {
SensitivityChangedEvent.fire((HasHandlers) uiObject, sensitive);
}
}
@Override
public boolean isSensitive() {
return uiObject.getType().equals(InputType.PASSWORD);
}
@Override
public HandlerRegistration addSensitivityChangedHandler(SensitivityChangedEvent.SensitivityChangedHandler handler) {
return uiObject.addSensitivityChangedHandler(handler);
}
}
|
package demo.rpc;
import javax.net.SocketFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.ipc.Client;
public class RPCClient extends Client{
public RPCClient(Class<? extends Writable> valueClass, Configuration conf) {
super(valueClass, conf);
// TODO Auto-generated constructor stub
}
public RPCClient(Class<? extends Writable> valueClass, Configuration conf, SocketFactory factory) {
super(valueClass, conf, factory);
// TODO Auto-generated constructor stub
}
}
|
/*******************************************************************************
* Open Behavioral Health Information Technology Architecture (OBHITA.org)
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the <organization> nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
package gov.samhsa.consent2share.domain.clinicaldata;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.stereotype.Repository;
/**
* The Interface ClinicalDocumentRepository.
*/
@Repository
public interface ClinicalDocumentRepository extends
JpaSpecificationExecutor<ClinicalDocument>,
JpaRepository<ClinicalDocument, Long> {
/**
* Find by patient id.
*
* @param id the id
* @return the list
*/
public abstract List<ClinicalDocument> findByPatientId(long id);
}
|
/*
* Copyright Strimzi authors.
* License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html).
*/
package io.strimzi.systemtest.bridge;
import io.fabric8.kubernetes.api.model.Service;
import io.strimzi.api.kafka.model.CertSecretSource;
import io.strimzi.api.kafka.model.KafkaResources;
import io.strimzi.api.kafka.model.listener.KafkaListenerAuthenticationTls;
import io.strimzi.systemtest.Constants;
import io.strimzi.systemtest.kafkaclients.externalClients.BasicExternalKafkaClient;
import io.strimzi.systemtest.utils.kafkaUtils.KafkaBridgeUtils;
import io.strimzi.systemtest.utils.kafkaUtils.KafkaTopicUtils;
import io.strimzi.systemtest.utils.kubeUtils.objects.ServiceUtils;
import io.strimzi.systemtest.utils.specific.BridgeUtils;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.junit5.VertxExtension;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.common.security.auth.SecurityProtocol;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import io.strimzi.systemtest.resources.KubernetesResource;
import io.strimzi.systemtest.resources.crd.KafkaBridgeResource;
import io.strimzi.systemtest.resources.crd.KafkaResource;
import io.strimzi.systemtest.resources.crd.KafkaTopicResource;
import io.strimzi.systemtest.resources.crd.KafkaUserResource;
import static io.strimzi.systemtest.Constants.ACCEPTANCE;
import static io.strimzi.systemtest.Constants.BRIDGE;
import static io.strimzi.systemtest.Constants.EXTERNAL_CLIENTS_USED;
import static io.strimzi.systemtest.Constants.NODEPORT_SUPPORTED;
import static io.strimzi.systemtest.Constants.REGRESSION;
import static io.strimzi.systemtest.bridge.HttpBridgeST.NAMESPACE;
import static io.strimzi.test.k8s.KubeClusterResource.kubeClient;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
@Tag(BRIDGE)
@Tag(ACCEPTANCE)
@Tag(REGRESSION)
@Tag(NODEPORT_SUPPORTED)
@Tag(EXTERNAL_CLIENTS_USED)
@ExtendWith(VertxExtension.class)
class HttpBridgeTlsST extends HttpBridgeAbstractST {
private static final Logger LOGGER = LogManager.getLogger(HttpBridgeTlsST.class);
private String bridgeHost = "";
private int bridgePort = Constants.HTTP_BRIDGE_DEFAULT_PORT;
@Test
void testSendSimpleMessageTls() throws Exception {
String topicName = KafkaTopicUtils.generateRandomNameOfTopic();
// Create topic
KafkaTopicResource.topic(CLUSTER_NAME, topicName).done();
JsonObject records = BridgeUtils.generateHttpMessages(MESSAGE_COUNT);
JsonObject response = BridgeUtils.sendMessagesHttpRequest(records, bridgeHost, bridgePort, topicName, client);
KafkaBridgeUtils.checkSendResponse(response, MESSAGE_COUNT);
BasicExternalKafkaClient basicExternalKafkaClient = new BasicExternalKafkaClient.Builder()
.withTopicName(topicName)
.withNamespaceName(NAMESPACE)
.withClusterName(CLUSTER_NAME)
.withMessageCount(MESSAGE_COUNT)
.withSecurityProtocol(SecurityProtocol.SSL)
.withKafkaUsername(USER_NAME)
.build();
assertThat(basicExternalKafkaClient.receiveMessagesTls(), is(MESSAGE_COUNT));
}
@Test
void testReceiveSimpleMessageTls() throws Exception {
String topicName = KafkaTopicUtils.generateRandomNameOfTopic();
// Create topic
KafkaTopicResource.topic(CLUSTER_NAME, topicName).done();
KafkaTopicUtils.waitForKafkaTopicCreation(topicName);
JsonObject config = new JsonObject();
config.put("name", USER_NAME);
config.put("format", "json");
config.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
// Create consumer
JsonObject response = BridgeUtils.createBridgeConsumer(config, bridgeHost, bridgePort, CONSUMER_GROUP_NAME, client);
assertThat("Consumer wasn't created correctly", response.getString("instance_id"), is(USER_NAME));
// Create topics json
JsonArray topic = new JsonArray();
topic.add(topicName);
JsonObject topics = new JsonObject();
topics.put("topics", topic);
// Subscribe
assertThat(BridgeUtils.subscribeHttpConsumer(topics, bridgeHost, bridgePort, CONSUMER_GROUP_NAME, USER_NAME, client), is(true));
// Send messages to Kafka
BasicExternalKafkaClient basicExternalKafkaClient = new BasicExternalKafkaClient.Builder()
.withTopicName(topicName)
.withNamespaceName(NAMESPACE)
.withClusterName(CLUSTER_NAME)
.withMessageCount(MESSAGE_COUNT)
.withSecurityProtocol(SecurityProtocol.SSL)
.withKafkaUsername(USER_NAME)
.build();
assertThat(basicExternalKafkaClient.sendMessagesTls(), is(MESSAGE_COUNT));
// Try to consume messages
JsonArray bridgeResponse = BridgeUtils.receiveMessagesHttpRequest(bridgeHost, bridgePort, CONSUMER_GROUP_NAME, USER_NAME, client);
if (bridgeResponse.size() == 0) {
// Real consuming
bridgeResponse = BridgeUtils.receiveMessagesHttpRequest(bridgeHost, bridgePort, CONSUMER_GROUP_NAME, USER_NAME, client);
}
assertThat("Sent message count is not equal with received message count", bridgeResponse.size(), is(MESSAGE_COUNT));
// Delete consumer
assertThat(BridgeUtils.deleteConsumer(bridgeHost, bridgePort, CONSUMER_GROUP_NAME, USER_NAME, client), is(true));
}
@Test
void testTlsAuthWithWeirdNamedUser() throws Exception {
// Create weird named user with . and maximum of 64 chars -> TLS
String weirdUserName = "jjglmahyijoambryleyxjjglmahy.ijoambryleyxjjglmahyijoambryleyxasd";
// Create user with normal name -> we don't need to set weird name for consumer
String aliceUser = "alice";
// Create topic
KafkaTopicResource.topic(CLUSTER_NAME, TOPIC_NAME).done();
// Create user
KafkaUserResource.tlsUser(CLUSTER_NAME, weirdUserName).done();
KafkaUserResource.tlsUser(CLUSTER_NAME, aliceUser).done();
JsonObject config = new JsonObject();
config.put("name", aliceUser);
config.put("format", "json");
config.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
// Create consumer
JsonObject response = BridgeUtils.createBridgeConsumer(config, bridgeHost, bridgePort, CONSUMER_GROUP_NAME, client);
assertThat("Consumer wasn't created correctly", response.getString("instance_id"), is(aliceUser));
// Create topics json
JsonArray topic = new JsonArray();
topic.add(TOPIC_NAME);
JsonObject topics = new JsonObject();
topics.put("topics", topic);
// Subscribe
assertThat(BridgeUtils.subscribeHttpConsumer(topics, bridgeHost, bridgePort, CONSUMER_GROUP_NAME, aliceUser, client), is(true));
BasicExternalKafkaClient basicExternalKafkaClient = new BasicExternalKafkaClient.Builder()
.withTopicName(TOPIC_NAME)
.withNamespaceName(NAMESPACE)
.withClusterName(CLUSTER_NAME)
.withMessageCount(MESSAGE_COUNT)
.withSecurityProtocol(SecurityProtocol.SSL)
.withKafkaUsername(weirdUserName)
.build();
assertThat(basicExternalKafkaClient.sendMessagesTls(), is(MESSAGE_COUNT));
// Try to consume messages
JsonArray bridgeResponse = BridgeUtils.receiveMessagesHttpRequest(bridgeHost, bridgePort, CONSUMER_GROUP_NAME, aliceUser, client);
if (bridgeResponse.size() == 0) {
// Real consuming
bridgeResponse = BridgeUtils.receiveMessagesHttpRequest(bridgeHost, bridgePort, CONSUMER_GROUP_NAME, aliceUser, client);
}
assertThat("Sent message count is not equal with received message count", bridgeResponse.size(), is(MESSAGE_COUNT));
// Delete consumer
assertThat(BridgeUtils.deleteConsumer(bridgeHost, bridgePort, CONSUMER_GROUP_NAME, aliceUser, client), is(true));
}
@BeforeAll
void createClassResources() throws InterruptedException {
LOGGER.info("Deploy Kafka and KafkaBridge before tests");
// Deploy kafka
KafkaResource.kafkaEphemeral(CLUSTER_NAME, 1, 1)
.editSpec()
.editKafka()
.editListeners()
.withNewKafkaListenerExternalNodePort()
.withAuth(new KafkaListenerAuthenticationTls())
.endKafkaListenerExternalNodePort()
.endListeners()
.endKafka()
.endSpec().done();
// Create Kafka user
KafkaUserResource.tlsUser(CLUSTER_NAME, USER_NAME).done();
// Initialize CertSecretSource with certificate and secret names for consumer
CertSecretSource certSecret = new CertSecretSource();
certSecret.setCertificate("ca.crt");
certSecret.setSecretName(KafkaResources.clusterCaCertificateSecretName(CLUSTER_NAME));
// Deploy http bridge
KafkaBridgeResource.kafkaBridge(CLUSTER_NAME, KafkaResources.tlsBootstrapAddress(CLUSTER_NAME), 1)
.editSpec()
.withNewTls()
.withTrustedCertificates(certSecret)
.endTls()
.endSpec()
.done();
Service service = KafkaBridgeUtils.createBridgeNodePortService(CLUSTER_NAME, NAMESPACE, bridgeExternalService);
KubernetesResource.createServiceResource(service, NAMESPACE).done();
ServiceUtils.waitForNodePortService(bridgeExternalService);
bridgePort = KafkaBridgeUtils.getBridgeNodePort(NAMESPACE, bridgeExternalService);
bridgeHost = kubeClient(NAMESPACE).getNodeAddress();
}
}
|
/**
* 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.hadoop.gateway.shell.job;
import com.jayway.jsonpath.JsonPath;
import org.apache.hadoop.gateway.shell.AbstractRequest;
import org.apache.hadoop.gateway.shell.BasicResponse;
import org.apache.hadoop.gateway.shell.Hadoop;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
public class Sqoop {
public static class Request extends AbstractRequest<Response> {
private String statusDir;
List<NameValuePair> params = new ArrayList<NameValuePair>();
public Request( Hadoop session ) {
super( session );
}
public Request command( String command ) {
addParam( params, "command", command );
return this;
}
public Request libdir( String libdir ) {
addParam( params, "libdir", libdir );
return this;
}
public Request files( String files ) {
addParam( params, "files", files );
return this;
}
public Request optionsfile( String optionsFile ) {
addParam( params, "optionsfile", optionsFile );
return this;
}
public Request statusDir( String dir ) {
this.statusDir = dir;
return this;
}
protected Callable<Response> callable() {
return new Callable<Response>() {
@Override
public Response call() throws Exception {
URIBuilder uri = uri( Job.SERVICE_PATH, "/sqoop" );
addParam( params, "statusdir", statusDir );
UrlEncodedFormEntity form = new UrlEncodedFormEntity( params );
HttpPost request = new HttpPost( uri.build() );
request.setEntity( form );
return new Response( execute( request ) );
}
};
}
}
public static class Response extends BasicResponse {
protected Response( HttpResponse response ) {
super( response );
}
public String getJobId() throws IOException {
return JsonPath.read( getString(), "$.id" );
}
}
}
|
package io.wildlabs.maildeaf.core;
import io.wildlabs.maildeaf.core.exception.MailException;
import io.wildlabs.maildeaf.core.model.Mail;
import io.wildlabs.maildeaf.core.sender.MailSender;
public class MailDeaf {
private final MailSender mailSender;
public MailDeaf(MailSender mailSender) {
this.mailSender = mailSender;
}
public void sendMail(Mail mail) throws MailException {
mailSender.sendMail(mail);
}
}
|
package no.nav.bidrag.commons.web;
import java.util.Map.Entry;
import java.util.Optional;
import java.util.stream.Collectors;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.CollectionUtils;
/**
* Redirecting {@link ResponseEntity} from one service to another
*
* @param <T> type of http payload
*/
public class HttpResponse<T> {
private final ResponseEntity<T> responseEntity;
public HttpResponse(ResponseEntity<T> responseEntity) {
this.responseEntity = responseEntity;
}
public Optional<T> fetchBody() {
return Optional.ofNullable(responseEntity.getBody());
}
public boolean is2xxSuccessful() {
return responseEntity.getStatusCode().is2xxSuccessful();
}
public HttpHeaders fetchHeaders() {
return responseEntity.getHeaders();
}
public HttpResponse<T> clearContentHeaders() {
var headersMap = responseEntity.getHeaders().entrySet().stream().collect(Collectors.toMap(Entry::getKey, Entry::getValue));
var headers = new HttpHeaders(CollectionUtils.toMultiValueMap(headersMap));
headers.clearContentHeaders();
return from(responseEntity.getBody(), headers, responseEntity.getStatusCode());
}
public ResponseEntity<T> getResponseEntity() {
return responseEntity;
}
public static <E> HttpResponse<E> from(HttpStatus httpStatus) {
var responseEntity = new ResponseEntity<E>(httpStatus);
return new HttpResponse<>(responseEntity);
}
public static <E> HttpResponse<E> from(HttpStatus httpStatus, E body) {
var responseEntity = new ResponseEntity<>(body, httpStatus);
return new HttpResponse<>(responseEntity);
}
public static <E> HttpResponse<E> from(HttpHeaders httpHeaders, HttpStatus httpStatus) {
var responseEntity = new ResponseEntity<E>(httpHeaders, httpStatus);
return new HttpResponse<>(responseEntity);
}
public static <E> HttpResponse<E> from(E body, HttpHeaders httpHeaders, HttpStatus httpStatus) {
var responseEntity = new ResponseEntity<>(body, httpHeaders, httpStatus);
return new HttpResponse<>(responseEntity);
}
}
|
/**
* VMware Continuent Tungsten Replicator
* Copyright (C) 2015 VMware, 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.
*
* Initial developer(s): Linas Virbalas
* Contributor(s):
*/
package com.continuent.tungsten.replicator.database;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Iterator;
import org.apache.log4j.Logger;
import com.continuent.tungsten.replicator.ReplicatorException;
import com.continuent.tungsten.replicator.dbms.OneRowChange;
/**
* Implements DBMS-specific operations for MySQL.
*
* @author <a href="mailto:scott.martin@continuent.com">Scott Martin</a>
*/
public class GreenplumDatabase extends AbstractDatabase
{
private static Logger logger = Logger.getLogger(GreenplumDatabase.class);
public GreenplumDatabase() throws SQLException
{
dbms = DBMS.GREENPLUM;
// Hard code the driver so it gets loaded correctly.
dbDriver = "org.postgresql.Driver";
}
protected String columnToTypeString(Column c, String tableType)
{
switch (c.getType())
{
case Types.TINYINT :
return "SMALLINT";
case Types.SMALLINT :
return "SMALLINT";
case Types.INTEGER :
return "INTEGER";
case Types.BIGINT :
return "BIGINT";
case Types.CHAR :
{
if (c.getLength() == 1)
// This is a hack written to support storing
// boolean values into "character(1)" type "last_frag" field
// of "trep_commit_seqno" and "history" tables. We do not have
// any current Greenplum implementation so this will do for now.
return "BOOLEAN";
else
return "CHAR(" + c.getLength() + ")";
}
case Types.VARCHAR :
return "VARCHAR(" + c.getLength() + ")";
case Types.DATE :
return "DATE";
case Types.TIMESTAMP :
return "TIMESTAMP";
case Types.CLOB :
return "TEXT";
case Types.BLOB :
return "BYTEA";
default :
return "UNKNOWN";
}
}
@Override
protected Column addColumn(ResultSet rs) throws SQLException
{
// Generic initialization.
Column column = super.addColumn(rs);
// Greenplum specifics.
int type = column.getType();
column.setBlob(type == Types.BLOB || type == Types.BINARY
|| type == Types.VARBINARY || type == Types.LONGVARBINARY);
return column;
}
/**
* Connect to a PostgreSQL database. {@inheritDoc}
*
* @see com.continuent.tungsten.replicator.database.AbstractDatabase#connect()
*/
public void connect() throws SQLException
{
super.connect();
}
public boolean supportsReplace()
{
return false;
}
public boolean supportsUseDefaultSchema()
{
return true;
}
public void useDefaultSchema(String schema) throws SQLException
{
execute(getUseSchemaQuery(schema));
this.defaultSchema = schema;
}
public String getUseSchemaQuery(String schema)
{
return "SET search_path TO " + schema + ", \"$user\"";
}
public boolean supportsCreateDropSchema()
{
return true;
}
/**
* Checks whether the schema exists and, if not, creates it. This mimics
* MySQLDatabase's behavior "CREATE DATABASE IF NOT EXISTS". {@inheritDoc}
*
* @see com.continuent.tungsten.replicator.database.AbstractDatabase#createSchema(java.lang.String)
*/
public void createSchema(String schema) throws SQLException
{
if (!getSchemas().contains(schema))
{
String SQL = "CREATE SCHEMA " + schema;
execute(SQL);
}
else if (logger.isDebugEnabled())
logger.debug("Schema already exists, thus not recreating it: "
+ schema);
}
/**
* Checks whether the schema exists and, if it does, drops it. This mimics
* MySQLDatabase's behavior "DROP DATABASE IF EXISTS". {@inheritDoc}
*
* @see com.continuent.tungsten.replicator.database.AbstractDatabase#dropSchema(java.lang.String)
*/
public void dropSchema(String schema) throws SQLException
{
if (getSchemas().contains(schema))
{
String SQL = "DROP SCHEMA " + schema;
execute(SQL);
}
else if (logger.isDebugEnabled())
logger.debug("Schema does not exist, thus not dropping it: "
+ schema);
}
/**
* Checks whether the given table exists in the currently connected
* database. Check is made against "schema.table".
*
* @return true, if table exists, false, if not.
*/
private boolean tableExists(Table t) throws SQLException
{
String sql = "SELECT * FROM pg_tables WHERE schemaname='"
+ t.getSchema() + "' and tablename='" + t.getName() + "'";
Statement stmt = dbConn.createStatement();
ResultSet res = stmt.executeQuery(sql);
if (res.next())
return true;
else
return false;
}
/**
* {@inheritDoc}
*
* @see com.continuent.tungsten.replicator.database.AbstractDatabase#createTable(com.continuent.tungsten.replicator.database.Table,
* boolean, java.lang.String)
*/
@Override
public void createTable(Table t, boolean replace) throws SQLException
{
boolean comma = false;
boolean hasNonUnique = false;
if (replace)
dropTable(t);
else
{
// If table already exists, do nothing. This behavior is a mimic of
// MySQLDatabase for initial configuration to work. For some reason,
// Replicator is trying to create Tungsten tables more than once.
if (tableExists(t))
return;
}
String SQL = "CREATE TABLE " + t.getSchema() + "." + t.getName() + " (";
Iterator<Column> i = t.getAllColumns().iterator();
while (i.hasNext())
{
Column c = i.next();
SQL += (comma ? ", " : "") + c.getName() + " "
+ columnToTypeString(c, null)
+ (c.isNotNull() ? " NOT NULL" : "");
comma = true;
}
Iterator<Key> j = t.getKeys().iterator();
while (j.hasNext())
{
Key key = j.next();
if (key.getType() == Key.NonUnique)
{
// Non-unique keys will be created with a separate CREATE
// INDEX statement.
hasNonUnique = true;
continue;
}
SQL += ", ";
switch (key.getType())
{
case Key.Primary :
SQL += "PRIMARY KEY (";
break;
case Key.Unique :
SQL += "UNIQUE (";
break;
}
i = key.getColumns().iterator();
comma = false;
while (i.hasNext())
{
Column c = i.next();
SQL += (comma ? ", " : "") + c.getName();
comma = true;
}
SQL += ")";
}
SQL += ")";
// Create the table.
execute(SQL);
// Create non-unique keys.
if (hasNonUnique)
createNonUnique(t);
}
/**
* Creates a non unique index for the given table.
*/
private void createNonUnique(Table t) throws SQLException
{
boolean comma = false;
int indexNumber = 1;
Iterator<Key> j = t.getKeys().iterator();
while (j.hasNext())
{
Key key = j.next();
if (key.getType() == Key.NonUnique)
{
String SQL = "CREATE INDEX " + t.getName() + "_" + indexNumber;
SQL += " ON " + t.getSchema() + "." + t.getName() + "(";
Iterator<Column> i = key.getColumns().iterator();
comma = false;
while (i.hasNext())
{
Column c = i.next();
SQL += (comma ? ", " : "") + c.getName();
comma = true;
}
indexNumber++;
SQL += ")";
execute(SQL);
}
}
}
/**
* Set's a Distribution Key for the table.
*/
public void setDistributedBy(String schema, String table, String column)
throws SQLException
{
String SQL = "ALTER TABLE " + schema + "." + table
+ " SET DISTRIBUTED BY (" + column + ")";
execute(SQL);
}
/**
* Before using session variables in PostgreSQL one needs to define them in
* postgresql.conf
*
* @see com.continuent.tungsten.replicator.database.Database#supportsSessionVariables()
*/
public boolean supportsSessionVariables()
{
return false;
}
/**
* Returns schemas in the currently connected database. {@inheritDoc}
*
* @see com.continuent.tungsten.replicator.database.Database#getSchemas()
*/
public ArrayList<String> getSchemas() throws SQLException
{
ArrayList<String> schemas = new ArrayList<String>();
try
{
DatabaseMetaData md = this.getDatabaseMetaData();
ResultSet rs = md.getSchemas();
while (rs.next())
{
schemas.add(rs.getString("TABLE_SCHEM"));
}
rs.close();
}
finally
{
}
return schemas;
}
public ResultSet getColumnsResultSet(DatabaseMetaData md,
String schemaName, String tableName) throws SQLException
{
// TENT-288: the following call is different from MySQL's, because of
// getColumns(catalog, schema, table, col) definition and because in
// PostgreSQL schema~eventSchema (not catalog~eventSchema as in MySQL).
return md.getColumns(null, schemaName, tableName, null);
}
protected ResultSet getPrimaryKeyResultSet(DatabaseMetaData md,
String schemaName, String tableName) throws SQLException
{
return md.getPrimaryKeys(schemaName, null, tableName);
}
protected ResultSet getIndexResultSet(DatabaseMetaData md,
String schemaName, String tableName, boolean unique)
throws SQLException
{
throw new UnsupportedOperationException("Not implemented.");
}
protected ResultSet getTablesResultSet(DatabaseMetaData md,
String schemaName, boolean baseTablesOnly) throws SQLException
{
return md.getTables(schemaName, null, null, null);
}
/**
* getTimeDiff returns the database-specific way of subtracting two "dates"
* and return the result in seconds complete with space for the two bind
* variables. E.g. in MySQL it might be "time_to_sec(timediff(?, ?))". If
* either of the string variables are null, replace with the bind character
* (e.g. "?") else use the string given. For example getTimeDiff(null,
* "myTimeCol") -> time_to_sec(timediff(?, myTimeCol))
*/
public String getTimeDiff(String string1, String string2)
{
String retval = "FLOOR(EXTRACT(EPOCH FROM (";
if (string1 == null)
retval += "?::timestamp";
else
retval += string1;
retval += " - ";
if (string2 == null)
retval += "?::timestamp";
else
retval += string2;
retval += ")))";
return retval;
}
public String getNowFunction()
{
return "NOW()";
}
public String getPlaceHolder(OneRowChange.ColumnSpec col, Object colValue)
{
return " ? ";
}
public boolean nullsBoundDifferently(OneRowChange.ColumnSpec col)
{
return false;
}
public boolean nullsEverBoundDifferently()
{
return false;
}
/**
* {@inheritDoc}
*
* @see com.continuent.tungsten.replicator.database.Database#getBlobAsBytes(ResultSet,
* int)
*/
@Override
public byte[] getBlobAsBytes(ResultSet resultSet, int column)
throws SQLException
{
return resultSet.getBytes(column);
}
/**
* {@inheritDoc}
*
* @see com.continuent.tungsten.replicator.database.AbstractDatabase#getDatabaseObjectName(java.lang.String)
*/
@Override
public String getDatabaseObjectName(String name)
{
return "\"" + name + "\"";
}
/**
* {@inheritDoc}
*
* @see com.continuent.tungsten.replicator.database.AbstractDatabase#getSqlNameMatcher()
*/
@Override
public SqlOperationMatcher getSqlNameMatcher() throws ReplicatorException
{
// Return MySQL matcher for now.
return new MySQLOperationMatcher();
}
}
|
/**
* Copyright (c) 2015 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 org.trustedanalytics.usermanagement.users.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.context.annotation.Scope;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.client.resource.OAuth2ProtectedResourceDetails;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.web.client.RestOperations;
import org.springframework.web.client.RestTemplate;
import org.trustedanalytics.auth.AuthTokenRetriever;
import org.trustedanalytics.auth.HeaderAddingHttpInterceptor;
import org.trustedanalytics.uaa.UaaClient;
import org.trustedanalytics.uaa.UaaOperations;
import org.trustedanalytics.usermanagement.invitations.service.AccessInvitationsService;
import org.trustedanalytics.usermanagement.invitations.service.InvitationsService;
import org.trustedanalytics.usermanagement.security.OAuth2PrivilegedInterceptor;
import org.trustedanalytics.usermanagement.users.PasswordGenerator;
import org.trustedanalytics.usermanagement.users.RandomPasswordGenerator;
import org.trustedanalytics.usermanagement.users.rest.AuthGatewayOperations;
import org.trustedanalytics.usermanagement.users.service.UaaUsersService;
import org.trustedanalytics.usermanagement.users.service.UsersService;
import static java.util.Collections.singletonList;
import static org.springframework.context.annotation.ScopedProxyMode.TARGET_CLASS;
import static org.springframework.web.context.WebApplicationContext.SCOPE_REQUEST;
@Profile("cloud")
@Configuration
public class UsersServiceConfig {
@Value("${oauth.uaa}")
private String uaaBaseUrl;
@Value("${oauth.resource}")
private String apiBaseUrl;
@Autowired
private AuthTokenRetriever tokenRetriever;
@Bean
protected OAuth2PrivilegedInterceptor oauth2PrivilegedInterceptor(OAuth2ProtectedResourceDetails clientCredentials) {
return new OAuth2PrivilegedInterceptor(clientCredentials);
}
@Bean
protected UaaOperations uaaPrivilegedClient(RestOperations clientRestTemplate) {
return new UaaClient(uaaBaseUrl, clientRestTemplate);
}
@Bean
@Scope(value = SCOPE_REQUEST, proxyMode = TARGET_CLASS)
protected UaaOperations uaaClient(RestTemplate userRestTemplate) {
return new UaaClient(uaaBaseUrl, setAccessToken(userRestTemplate));
}
private OAuth2Authentication getAuthentication() {
SecurityContext context = SecurityContextHolder.getContext();
if (context == null) {
return null;
}
return (OAuth2Authentication) context.getAuthentication();
}
private RestTemplate setAccessToken(RestTemplate restTemplate) {
ClientHttpRequestInterceptor interceptor =
new HeaderAddingHttpInterceptor("Authorization", "bearer " + getAccessToken());
restTemplate.setInterceptors(singletonList(interceptor));
return restTemplate;
}
private String getAccessToken() {
OAuth2Authentication authentication = getAuthentication();
return tokenRetriever.getAuthToken(authentication);
}
@Bean
protected UsersService usersService(UaaOperations uaaClient,
InvitationsService invitationsService,
AccessInvitationsService accessInvitationsService,
AuthGatewayOperations authGatewayOperations) {
return new UaaUsersService(uaaClient, invitationsService, accessInvitationsService, authGatewayOperations);
}
@Bean
protected UsersService privilegedUsersService(UaaOperations uaaPrivilegedClient,
InvitationsService invitationsService,
AccessInvitationsService accessInvitationsService,
AuthGatewayOperations authGatewayOperations) {
return new UaaUsersService(
uaaPrivilegedClient,
invitationsService,
accessInvitationsService,
authGatewayOperations);
}
@Bean
protected PasswordGenerator passwordGenerator() {
return new RandomPasswordGenerator();
}
}
|
package com.sparrowwallet.sparrow.control;
import com.sparrowwallet.drongo.ExtendedKey;
import com.sparrowwallet.drongo.KeyDerivation;
import com.sparrowwallet.drongo.OutputDescriptor;
import com.sparrowwallet.drongo.crypto.ChildNumber;
import com.sparrowwallet.drongo.policy.Policy;
import com.sparrowwallet.drongo.policy.PolicyType;
import com.sparrowwallet.drongo.protocol.ScriptType;
import com.sparrowwallet.drongo.psbt.PSBT;
import com.sparrowwallet.drongo.wallet.Keystore;
import com.sparrowwallet.drongo.wallet.KeystoreSource;
import com.sparrowwallet.drongo.wallet.Wallet;
import com.sparrowwallet.sparrow.EventManager;
import com.sparrowwallet.sparrow.event.*;
import com.sparrowwallet.sparrow.io.Device;
import com.sparrowwallet.sparrow.io.Hwi;
import com.sparrowwallet.sparrow.glyphfont.FontAwesome5;
import javafx.application.Platform;
import javafx.beans.property.SimpleStringProperty;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import org.controlsfx.control.textfield.CustomPasswordField;
import org.controlsfx.control.textfield.TextFields;
import org.controlsfx.glyphfont.Glyph;
import org.controlsfx.validation.ValidationResult;
import org.controlsfx.validation.ValidationSupport;
import org.controlsfx.validation.Validator;
import org.controlsfx.validation.decoration.StyleClassValidationDecoration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class DevicePane extends TitledDescriptionPane {
private static final Logger log = LoggerFactory.getLogger(DevicePane.class);
private final DeviceOperation deviceOperation;
private final Wallet wallet;
private final PSBT psbt;
private final OutputDescriptor outputDescriptor;
private final KeyDerivation keyDerivation;
private final String message;
private final Device device;
private CustomPasswordField pinField;
private Button unlockButton;
private Button enterPinButton;
private Button setPassphraseButton;
private ButtonBase importButton;
private Button signButton;
private Button displayAddressButton;
private Button signMessageButton;
private final SimpleStringProperty passphrase = new SimpleStringProperty("");
private boolean defaultDevice;
public DevicePane(Wallet wallet, Device device, boolean defaultDevice, KeyDerivation requiredDerivation) {
super(device.getModel().toDisplayString(), "", "", "image/" + device.getType() + ".png");
this.deviceOperation = DeviceOperation.IMPORT;
this.wallet = wallet;
this.psbt = null;
this.outputDescriptor = null;
this.keyDerivation = requiredDerivation;
this.message = null;
this.device = device;
this.defaultDevice = defaultDevice;
setDefaultStatus();
showHideLink.setVisible(false);
createSetPassphraseButton();
createImportButton();
initialise(device);
buttonBox.getChildren().addAll(setPassphraseButton, importButton);
}
public DevicePane(PSBT psbt, Device device, boolean defaultDevice) {
super(device.getModel().toDisplayString(), "", "", "image/" + device.getType() + ".png");
this.deviceOperation = DeviceOperation.SIGN;
this.wallet = null;
this.psbt = psbt;
this.outputDescriptor = null;
this.keyDerivation = null;
this.message = null;
this.device = device;
this.defaultDevice = defaultDevice;
setDefaultStatus();
showHideLink.setVisible(false);
createSetPassphraseButton();
createSignButton();
initialise(device);
buttonBox.getChildren().addAll(setPassphraseButton, signButton);
}
public DevicePane(Wallet wallet, OutputDescriptor outputDescriptor, Device device, boolean defaultDevice) {
super(device.getModel().toDisplayString(), "", "", "image/" + device.getType() + ".png");
this.deviceOperation = DeviceOperation.DISPLAY_ADDRESS;
this.wallet = wallet;
this.psbt = null;
this.outputDescriptor = outputDescriptor;
this.keyDerivation = null;
this.message = null;
this.device = device;
this.defaultDevice = defaultDevice;
setDefaultStatus();
showHideLink.setVisible(false);
createSetPassphraseButton();
createDisplayAddressButton();
initialise(device);
buttonBox.getChildren().addAll(setPassphraseButton, displayAddressButton);
}
public DevicePane(Wallet wallet, String message, KeyDerivation keyDerivation, Device device, boolean defaultDevice) {
super(device.getModel().toDisplayString(), "", "", "image/" + device.getType() + ".png");
this.deviceOperation = DeviceOperation.SIGN_MESSAGE;
this.wallet = wallet;
this.psbt = null;
this.outputDescriptor = null;
this.keyDerivation = keyDerivation;
this.message = message;
this.device = device;
this.defaultDevice = defaultDevice;
setDefaultStatus();
showHideLink.setVisible(false);
createSetPassphraseButton();
createSignMessageButton();
initialise(device);
buttonBox.getChildren().addAll(setPassphraseButton, signMessageButton);
}
private void initialise(Device device) {
if(device.isNeedsPinSent()) {
unlockButton.setDefaultButton(defaultDevice);
unlockButton.setVisible(true);
} else if(device.isNeedsPassphraseSent()) {
setPassphraseButton.setVisible(true);
} else if(device.getError() != null) {
setError("Error", device.getError());
Platform.runLater(() -> {
setExpanded(true);
});
} else {
showOperationButton();
}
}
@Override
protected Control createButton() {
createUnlockButton();
return unlockButton;
}
private void setDefaultStatus() {
setDescription(device.isNeedsPinSent() ? "Locked" : device.isNeedsPassphraseSent() ? "Passphrase Required" : "Unlocked");
}
private void createUnlockButton() {
unlockButton = new Button("Unlock");
unlockButton.setAlignment(Pos.CENTER_RIGHT);
unlockButton.setOnAction(event -> {
unlockButton.setDisable(true);
unlock(device);
});
unlockButton.managedProperty().bind(unlockButton.visibleProperty());
unlockButton.setVisible(false);
}
private void createSetPassphraseButton() {
setPassphraseButton = new Button("Set Passphrase");
setPassphraseButton.setAlignment(Pos.CENTER_RIGHT);
setPassphraseButton.setOnAction(event -> {
setPassphraseButton.setDisable(true);
setContent(getPassphraseEntry());
setExpanded(true);
});
setPassphraseButton.managedProperty().bind(setPassphraseButton.visibleProperty());
setPassphraseButton.setVisible(false);
}
private void createImportButton() {
importButton = keyDerivation == null ? new SplitMenuButton() : new Button();
importButton.setAlignment(Pos.CENTER_RIGHT);
importButton.setText("Import Keystore");
importButton.setOnAction(event -> {
importButton.setDisable(true);
List<ChildNumber> defaultDerivation = wallet.getScriptType() == null ? ScriptType.P2WPKH.getDefaultDerivation() : wallet.getScriptType().getDefaultDerivation();
importKeystore(keyDerivation == null ? defaultDerivation : keyDerivation.getDerivation());
});
if(importButton instanceof SplitMenuButton importMenuButton) {
if(wallet.getScriptType() == null) {
ScriptType[] scriptTypes = new ScriptType[] {ScriptType.P2WPKH, ScriptType.P2SH_P2WPKH, ScriptType.P2PKH};
for(ScriptType scriptType : scriptTypes) {
MenuItem item = new MenuItem(scriptType.getDescription());
final List<ChildNumber> derivation = scriptType.getDefaultDerivation();
item.setOnAction(event -> {
importMenuButton.setDisable(true);
importKeystore(derivation);
});
importMenuButton.getItems().add(item);
}
} else {
String[] accounts = new String[] {"Default Account #0", "Account #1", "Account #2", "Account #3", "Account #4", "Account #5", "Account #6", "Account #7", "Account #8", "Account #9"};
int scriptAccountsLength = ScriptType.P2SH.equals(wallet.getScriptType()) ? 1 : accounts.length;
for(int i = 0; i < scriptAccountsLength; i++) {
MenuItem item = new MenuItem(accounts[i]);
final List<ChildNumber> derivation = wallet.getScriptType().getDefaultDerivation(i);
item.setOnAction(event -> {
importMenuButton.setDisable(true);
importKeystore(derivation);
});
importMenuButton.getItems().add(item);
}
}
}
importButton.managedProperty().bind(importButton.visibleProperty());
importButton.setVisible(false);
}
private void createSignButton() {
signButton = new Button("Sign");
signButton.setAlignment(Pos.CENTER_RIGHT);
signButton.setMinWidth(44);
signButton.setOnAction(event -> {
signButton.setDisable(true);
sign();
});
signButton.managedProperty().bind(signButton.visibleProperty());
signButton.setVisible(false);
}
private void createDisplayAddressButton() {
displayAddressButton = new Button("Display Address");
displayAddressButton.setAlignment(Pos.CENTER_RIGHT);
displayAddressButton.setOnAction(event -> {
displayAddressButton.setDisable(true);
displayAddress();
});
displayAddressButton.managedProperty().bind(displayAddressButton.visibleProperty());
displayAddressButton.setVisible(false);
List<String> fingerprints = outputDescriptor.getExtendedPublicKeys().stream().map(extKey -> outputDescriptor.getKeyDerivation(extKey).getMasterFingerprint()).collect(Collectors.toList());
if(device.getFingerprint() != null && !fingerprints.contains(device.getFingerprint())) {
displayAddressButton.setDisable(true);
}
}
private void createSignMessageButton() {
signMessageButton = new Button("Sign Message");
signMessageButton.setAlignment(Pos.CENTER_RIGHT);
signMessageButton.setOnAction(event -> {
signMessageButton.setDisable(true);
signMessage();
});
signMessageButton.managedProperty().bind(signMessageButton.visibleProperty());
signMessageButton.setVisible(false);
if(device.getFingerprint() != null && !device.getFingerprint().equals(keyDerivation.getMasterFingerprint())) {
signMessageButton.setDisable(true);
}
}
private void unlock(Device device) {
if(device.getModel().requiresPinPrompt()) {
promptPin();
}
}
private Node getPinEntry() {
VBox vBox = new VBox();
vBox.setMaxHeight(120);
vBox.setSpacing(42);
pinField = (CustomPasswordField)TextFields.createClearablePasswordField();
Platform.runLater(() -> pinField.requestFocus());
enterPinButton = new Button("Enter PIN");
enterPinButton.setDefaultButton(true);
enterPinButton.setOnAction(event -> {
enterPinButton.setDisable(true);
sendPin(pinField.getText());
});
vBox.getChildren().addAll(pinField, enterPinButton);
TilePane tilePane = new TilePane();
tilePane.setPrefColumns(3);
tilePane.setHgap(10);
tilePane.setVgap(10);
tilePane.setMaxWidth(150);
tilePane.setMaxHeight(120);
int[] digits = new int[] {7, 8, 9, 4, 5, 6, 1, 2, 3};
for(int i = 0; i < digits.length; i++) {
Button pinButton = new Button();
Glyph circle = new Glyph(FontAwesome5.FONT_NAME, "CIRCLE");
pinButton.setGraphic(circle);
pinButton.setUserData(digits[i]);
tilePane.getChildren().add(pinButton);
pinButton.setOnAction(event -> {
pinField.setText(pinField.getText() + pinButton.getUserData());
});
}
HBox contentBox = new HBox();
contentBox.setSpacing(50);
contentBox.getChildren().add(tilePane);
contentBox.getChildren().add(vBox);
contentBox.setPadding(new Insets(10, 0, 10, 0));
contentBox.setAlignment(Pos.TOP_CENTER);
return contentBox;
}
private Node getPassphraseEntry() {
CustomPasswordField passphraseField = (CustomPasswordField)TextFields.createClearablePasswordField();
passphrase.bind(passphraseField.textProperty());
HBox.setHgrow(passphraseField, Priority.ALWAYS);
passphraseField.setOnAction(event -> {
setExpanded(false);
setDescription("Confirm passphrase on device...");
sendPassphrase(passphrase.get());
});
SplitMenuButton sendPassphraseButton = new SplitMenuButton();
sendPassphraseButton.setText("Send Passphrase");
sendPassphraseButton.getStyleClass().add("default-button");
sendPassphraseButton.setOnAction(event -> {
setExpanded(false);
setDescription("Confirm passphrase on device...");
sendPassphrase(passphrase.get());
});
MenuItem removePassphrase = new MenuItem("Toggle Passphrase Off");
removePassphrase.setOnAction(event -> {
setExpanded(false);
setDescription("Toggling passphrase off, check device...");
togglePassphraseOff();
});
sendPassphraseButton.getItems().add(removePassphrase);
HBox contentBox = new HBox();
contentBox.setAlignment(Pos.TOP_RIGHT);
contentBox.setSpacing(20);
contentBox.getChildren().add(passphraseField);
contentBox.getChildren().add(sendPassphraseButton);
contentBox.setPadding(new Insets(10, 30, 10, 30));
Platform.runLater(passphraseField::requestFocus);
return contentBox;
}
private Node getTogglePassphraseOn() {
CopyableLabel label = new CopyableLabel("Passphrase is currently disabled");
HBox.setHgrow(label, Priority.ALWAYS);
Button togglePassphraseOn = new Button("Toggle Passphrase On");
togglePassphraseOn.setOnAction(event -> {
setExpanded(false);
hideButtons(importButton, signButton, displayAddressButton, signMessageButton);
setDescription("Toggling passphrase on, check device...");
togglePassphraseOn();
});
HBox contentBox = new HBox();
contentBox.setSpacing(20);
contentBox.setAlignment(Pos.CENTER_LEFT);
contentBox.getChildren().addAll(label, togglePassphraseOn);
contentBox.setPadding(new Insets(10, 30, 10, 30));
return contentBox;
}
private void hideButtons(Node... buttons) {
for(Node button : buttons) {
if(button != null) {
button.setVisible(false);
}
}
}
private void promptPin() {
Hwi.PromptPinService promptPinService = new Hwi.PromptPinService(device);
promptPinService.setOnSucceeded(workerStateEvent -> {
Boolean result = promptPinService.getValue();
if(result) {
setContent(getPinEntry());
setExpanded(true);
} else {
setError("Could not request PIN", null);
unlockButton.setDisable(false);
}
});
promptPinService.setOnFailed(workerStateEvent -> {
setError("Error", promptPinService.getException().getMessage());
unlockButton.setDisable(false);
});
promptPinService.start();
}
private void sendPin(String pin) {
Hwi.SendPinService sendPinService = new Hwi.SendPinService(device, pin);
sendPinService.setOnSucceeded(workerStateEvent -> {
Boolean result = sendPinService.getValue();
if(result) {
device.setNeedsPinSent(false);
setDefaultStatus();
setExpanded(false);
unlockButton.setVisible(false);
if(device.isNeedsPassphraseSent()) {
setPassphraseButton.setVisible(true);
setPassphraseButton.setDisable(true);
setContent(getPassphraseEntry());
setExpanded(true);
} else {
showOperationButton();
if(!deviceOperation.equals(DeviceOperation.IMPORT)) {
setContent(getTogglePassphraseOn());
}
}
} else {
setError("Incorrect PIN", null);
unlockButton.setDisable(false);
if(pinField != null) {
pinField.setText("");
}
}
});
sendPinService.setOnFailed(workerStateEvent -> {
setError("Error", sendPinService.getException().getMessage());
enterPinButton.setDisable(false);
});
setDescription("Unlocking...");
showHideLink.setVisible(false);
sendPinService.start();
}
private void sendPassphrase(String passphrase) {
Hwi.EnumerateService enumerateService = new Hwi.EnumerateService(passphrase);
enumerateService.setOnSucceeded(workerStateEvent -> {
List<Device> devices = enumerateService.getValue();
for (Device freshDevice : devices) {
if (device.getPath().equals(freshDevice.getPath()) && device.getModel().equals(freshDevice.getModel())) {
device.setFingerprint(freshDevice.getFingerprint());
}
}
if(device.getFingerprint() != null) {
setPassphraseButton.setVisible(false);
setDescription("Passphrase sent");
showOperationButton();
} else {
setError("Passphrase send failed", null);
setPassphraseButton.setDisable(false);
setPassphraseButton.setVisible(true);
}
});
enumerateService.setOnFailed(workerStateEvent -> {
setError("Error", enumerateService.getException().getMessage());
setPassphraseButton.setDisable(false);
setPassphraseButton.setVisible(true);
});
enumerateService.start();
}
private void togglePassphraseOff() {
Hwi.TogglePassphraseService togglePassphraseService = new Hwi.TogglePassphraseService(device);
togglePassphraseService.setOnSucceeded(workerStateEvent -> {
device.setNeedsPassphraseSent(false);
setPassphraseButton.setVisible(false);
setDescription("Unlocked");
showOperationButton();
});
togglePassphraseService.setOnFailed(workerStateEvent -> {
setError("Error", togglePassphraseService.getException().getMessage());
});
togglePassphraseService.start();
}
private void togglePassphraseOn() {
Hwi.TogglePassphraseService togglePassphraseService = new Hwi.TogglePassphraseService(device);
togglePassphraseService.setOnSucceeded(workerStateEvent -> {
device.setNeedsPassphraseSent(true);
setPassphraseButton.setVisible(true);
setPassphraseButton.setDisable(true);
setDescription("Enter passphrase");
setContent(getPassphraseEntry());
setExpanded(true);
});
togglePassphraseService.setOnFailed(workerStateEvent -> {
setError("Error", togglePassphraseService.getException().getMessage());
});
togglePassphraseService.start();
}
private void importKeystore(List<ChildNumber> derivation) {
if(device.getFingerprint() == null) {
Hwi.EnumerateService enumerateService = new Hwi.EnumerateService(passphrase.get());
enumerateService.setOnSucceeded(workerStateEvent -> {
List<Device> devices = enumerateService.getValue();
for (Device freshDevice : devices) {
if (device.getPath().equals(freshDevice.getPath()) && device.getModel().equals(freshDevice.getModel())) {
device.setFingerprint(freshDevice.getFingerprint());
}
}
importXpub(derivation);
});
enumerateService.setOnFailed(workerStateEvent -> {
setError("Error", enumerateService.getException().getMessage());
importButton.setDisable(false);
});
enumerateService.start();
} else {
importXpub(derivation);
}
}
private void importXpub(List<ChildNumber> derivation) {
String derivationPath = KeyDerivation.writePath(derivation);
Hwi.GetXpubService getXpubService = new Hwi.GetXpubService(device, passphrase.get(), derivationPath);
getXpubService.setOnSucceeded(workerStateEvent -> {
String xpub = getXpubService.getValue();
try {
Keystore keystore = new Keystore();
keystore.setLabel(device.getModel().toDisplayString());
keystore.setSource(KeystoreSource.HW_USB);
keystore.setWalletModel(device.getModel());
keystore.setKeyDerivation(new KeyDerivation(device.getFingerprint(), derivationPath));
keystore.setExtendedPublicKey(ExtendedKey.fromDescriptor(xpub));
if(wallet.getScriptType() == null) {
ScriptType scriptType = Arrays.stream(ScriptType.ADDRESSABLE_TYPES).filter(type -> type.getDefaultDerivation().get(0).equals(derivation.get(0))).findFirst().orElse(ScriptType.P2PKH);
wallet.setName(device.getModel().toDisplayString());
wallet.setPolicyType(PolicyType.SINGLE);
wallet.setScriptType(scriptType);
wallet.getKeystores().add(keystore);
wallet.setDefaultPolicy(Policy.getPolicy(PolicyType.SINGLE, scriptType, wallet.getKeystores(), null));
EventManager.get().post(new WalletImportEvent(wallet));
} else {
EventManager.get().post(new KeystoreImportEvent(keystore));
}
} catch(Exception e) {
setError("Could not retrieve xpub", e.getMessage());
}
});
getXpubService.setOnFailed(workerStateEvent -> {
setError("Could not retrieve xpub", getXpubService.getException().getMessage());
importButton.setDisable(false);
});
setDescription("Importing...");
showHideLink.setVisible(false);
getXpubService.start();
}
private void sign() {
Hwi.SignPSBTService signPSBTService = new Hwi.SignPSBTService(device, passphrase.get(), psbt);
signPSBTService.setOnSucceeded(workerStateEvent -> {
PSBT signedPsbt = signPSBTService.getValue();
EventManager.get().post(new PSBTSignedEvent(psbt, signedPsbt));
});
signPSBTService.setOnFailed(workerStateEvent -> {
setError("Signing Error", signPSBTService.getException().getMessage());
log.error("Signing Error: " + signPSBTService.getException().getMessage());
signButton.setDisable(false);
});
setDescription("Signing...");
showHideLink.setVisible(false);
signPSBTService.start();
}
private void displayAddress() {
Hwi.DisplayAddressService displayAddressService = new Hwi.DisplayAddressService(device, passphrase.get(), wallet.getScriptType(), outputDescriptor);
displayAddressService.setOnSucceeded(successEvent -> {
String address = displayAddressService.getValue();
EventManager.get().post(new AddressDisplayedEvent(address));
});
displayAddressService.setOnFailed(failedEvent -> {
setError("Could not display address", displayAddressService.getException().getMessage());
displayAddressButton.setDisable(false);
});
setDescription("Check device for address");
displayAddressService.start();
}
private void signMessage() {
Hwi.SignMessageService signMessageService = new Hwi.SignMessageService(device, passphrase.get(), message, keyDerivation.getDerivationPath());
signMessageService.setOnSucceeded(successEvent -> {
String signature = signMessageService.getValue();
EventManager.get().post(new MessageSignedEvent(wallet, signature));
});
signMessageService.setOnFailed(failedEvent -> {
setError("Could not sign message", signMessageService.getException().getMessage());
signMessageButton.setDisable(false);
});
setDescription("Signing message...");
signMessageService.start();
}
private void showOperationButton() {
if(deviceOperation.equals(DeviceOperation.IMPORT)) {
if(defaultDevice) {
importButton.getStyleClass().add("default-button");
}
importButton.setVisible(true);
showHideLink.setText("Show derivation...");
showHideLink.setVisible(true);
List<ChildNumber> defaultDerivation = wallet.getScriptType() == null ? ScriptType.P2WPKH.getDefaultDerivation() : wallet.getScriptType().getDefaultDerivation();
setContent(getDerivationEntry(keyDerivation == null ? defaultDerivation : keyDerivation.getDerivation()));
} else if(deviceOperation.equals(DeviceOperation.SIGN)) {
signButton.setDefaultButton(defaultDevice);
signButton.setVisible(true);
showHideLink.setVisible(false);
} else if(deviceOperation.equals(DeviceOperation.DISPLAY_ADDRESS)) {
displayAddressButton.setDefaultButton(defaultDevice);
displayAddressButton.setVisible(true);
showHideLink.setVisible(false);
} else if(deviceOperation.equals(DeviceOperation.SIGN_MESSAGE)) {
signMessageButton.setDefaultButton(defaultDevice);
signMessageButton.setVisible(true);
showHideLink.setVisible(false);
}
}
private Node getDerivationEntry(List<ChildNumber> derivation) {
TextField derivationField = new TextField();
derivationField.setPromptText("Derivation path");
derivationField.setText(KeyDerivation.writePath(derivation));
derivationField.setDisable(keyDerivation != null);
HBox.setHgrow(derivationField, Priority.ALWAYS);
ValidationSupport validationSupport = new ValidationSupport();
validationSupport.setValidationDecorator(new StyleClassValidationDecoration());
validationSupport.registerValidator(derivationField, Validator.combine(
Validator.createEmptyValidator("Derivation is required"),
(Control c, String newValue) -> ValidationResult.fromErrorIf( c, "Invalid derivation", !KeyDerivation.isValid(newValue))
));
Button importDerivationButton = new Button("Import Custom Derivation");
importDerivationButton.setDisable(true);
importDerivationButton.setOnAction(event -> {
showHideLink.setVisible(true);
setExpanded(false);
List<ChildNumber> importDerivation = KeyDerivation.parsePath(derivationField.getText());
importXpub(importDerivation);
});
derivationField.textProperty().addListener((observable, oldValue, newValue) -> {
importButton.setDisable(newValue.isEmpty() || !KeyDerivation.isValid(newValue) || !KeyDerivation.parsePath(newValue).equals(derivation));
importDerivationButton.setDisable(newValue.isEmpty() || !KeyDerivation.isValid(newValue) || KeyDerivation.parsePath(newValue).equals(derivation));
});
HBox contentBox = new HBox();
contentBox.setAlignment(Pos.TOP_RIGHT);
contentBox.setSpacing(20);
contentBox.getChildren().add(derivationField);
contentBox.getChildren().add(importDerivationButton);
contentBox.setPadding(new Insets(10, 30, 10, 30));
contentBox.setPrefHeight(60);
return contentBox;
}
public Device getDevice() {
return device;
}
public enum DeviceOperation {
IMPORT, SIGN, DISPLAY_ADDRESS, SIGN_MESSAGE;
}
}
|
package com.qa.ims.controller;
import java.util.List;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.qa.ims.persistence.dao.CustomerDAO;
import com.qa.ims.persistence.dao.OrderDAO;
import com.qa.ims.persistence.domain.Customer;
import com.qa.ims.persistence.domain.Order;
import com.qa.ims.utils.Utils;
/**
* Takes in customer details for CRUD functionality
*
*/
public class CustomerController implements CrudController<Customer> {
public static final Logger LOGGER = LogManager.getLogger();
private CustomerDAO customerDAO;
private OrderDAO orderDAO;
private Utils utils;
public CustomerController(CustomerDAO customerDAO, OrderDAO orderDAO, Utils utils) {
super();
this.customerDAO = customerDAO;
this.orderDAO = orderDAO;
this.utils = utils;
}
/**
* Reads all customers to the logger
*/
@Override
public List<Customer> readAll() {
List<Customer> customers = customerDAO.readAll();
for (Customer customer : customers) {
LOGGER.info(customer.toString());
}
return customers;
}
/**
* Creates a customer by taking in user input
*/
@Override
public Customer create() {
LOGGER.info("Please enter a first name");
String firstName = utils.getString();
LOGGER.info("Please enter a surname");
String surname = utils.getString();
Customer customer = customerDAO.create(new Customer(firstName, surname));
LOGGER.info("Customer created");
return customer;
}
/**
* Updates an existing customer by taking in user input
*/
@Override
public Customer update() {
LOGGER.info("Please enter the id of the customer you would like to update");
Long id = utils.getLong();
LOGGER.info("Please enter a first name");
String firstName = utils.getString();
LOGGER.info("Please enter a surname");
String surname = utils.getString();
Customer customer = customerDAO.update(new Customer(id, firstName, surname));
LOGGER.info("Customer Updated");
return customer;
}
/**
* Deletes an existing customer by the id of the customer
*
* @return
*/
@Override
public int delete() {
LOGGER.info("Please enter the id of the customer you would like to delete");
Long id = utils.getLong();
List<Order> orderID = orderDAO.getCustomerOrder(id);
for(Order order: orderID)
{
orderDAO.deleteOrderLines(order.getId());
orderDAO.delete(order.getId());
}
return customerDAO.delete(id);
}
}
|
package com.networknt.apic.handler;
import com.networknt.client.Client;
import com.networknt.server.Server;
import com.networknt.exception.ClientException;
import com.networknt.exception.ApiException;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.*;
import org.apache.http.impl.client.CloseableHttpClient;
import org.junit.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
public class ServerInfoGetHandlerTest {
@ClassRule
public static TestServer server = TestServer.getInstance();
static final Logger logger = LoggerFactory.getLogger(ServerInfoGetHandlerTest.class);
@Test
public void testServerInfoGetHandlerTest() throws ClientException, ApiException {
CloseableHttpClient client = Client.getInstance().getSyncClient();
HttpGet httpGet = new HttpGet ("http://localhost:8080/v1/server/info");
/*
Client.getInstance().addAuthorization(httpGet);
try {
CloseableHttpResponse response = client.execute(httpGet);
int statusCode = response.getStatusLine().getStatusCode();
String body = IOUtils.toString(response.getEntity().getContent(), "utf8");
Assert.assertEquals(200, statusCode);
Assert.assertEquals("", body);
} catch (Exception e) {
e.printStackTrace();
}
*/
}
}
|
/*
* Copyright © 2013-2018 camunda services GmbH and various authors (info@camunda.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.camunda.spin.plugin.variables;
public class JsonSerializable {
private String stringProperty;
private int intProperty;
private boolean booleanProperty;
public JsonSerializable() {
}
public JsonSerializable(String stringProperty, int intProperty, boolean booleanProperty) {
this.stringProperty = stringProperty;
this.intProperty = intProperty;
this.booleanProperty = booleanProperty;
}
public String getStringProperty() {
return stringProperty;
}
public void setStringProperty(String stringProperty) {
this.stringProperty = stringProperty;
}
public int getIntProperty() {
return intProperty;
}
public void setIntProperty(int intProperty) {
this.intProperty = intProperty;
}
public boolean getBooleanProperty() {
return booleanProperty;
}
public void setBooleanProperty(boolean booleanProperty) {
this.booleanProperty = booleanProperty;
}
public String toExpectedJsonString() {
StringBuilder jsonBuilder = new StringBuilder();
jsonBuilder.append("{\"stringProperty\":\"");
jsonBuilder.append(stringProperty);
jsonBuilder.append("\",\"intProperty\":");
jsonBuilder.append(intProperty);
jsonBuilder.append(",\"booleanProperty\":");
jsonBuilder.append(booleanProperty);
jsonBuilder.append("}");
return jsonBuilder.toString();
}
public String toString() {
return toExpectedJsonString();
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (booleanProperty ? 1231 : 1237);
result = prime * result + intProperty;
result = prime * result + ((stringProperty == null) ? 0 : stringProperty.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
JsonSerializable other = (JsonSerializable) obj;
if (booleanProperty != other.booleanProperty)
return false;
if (intProperty != other.intProperty)
return false;
if (stringProperty == null) {
if (other.stringProperty != null)
return false;
} else if (!stringProperty.equals(other.stringProperty))
return false;
return true;
}
}
|
package io.onedev.server.model.support.issue.field.spec;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import io.onedev.server.model.support.inputspec.choiceinput.ChoiceInput;
import io.onedev.server.model.support.inputspec.choiceinput.choiceprovider.ChoiceProvider;
import io.onedev.server.model.support.inputspec.choiceinput.choiceprovider.SpecifiedChoices;
import io.onedev.server.model.support.inputspec.choiceinput.defaultmultivalueprovider.DefaultMultiValueProvider;
import io.onedev.server.model.support.inputspec.choiceinput.defaultvalueprovider.DefaultValueProvider;
import io.onedev.server.util.EditContext;
import io.onedev.server.util.usage.Usage;
import io.onedev.server.web.editable.annotation.Editable;
import io.onedev.server.web.editable.annotation.ShowCondition;
@Editable(order=145, name=FieldSpec.ENUMERATION)
public class ChoiceField extends FieldSpec {
private static final long serialVersionUID = 1L;
private ChoiceProvider choiceProvider = new SpecifiedChoices();
private DefaultValueProvider defaultValueProvider;
private DefaultMultiValueProvider defaultMultiValueProvider;
@Editable(order=1000, name="Available Choices")
@NotNull(message="may not be empty")
@Valid
public ChoiceProvider getChoiceProvider() {
return choiceProvider;
}
public void setChoiceProvider(ChoiceProvider choiceProvider) {
this.choiceProvider = choiceProvider;
}
@ShowCondition("isDefaultValueProviderVisible")
@Editable(order=1100, name="Default Value", placeholder="No default value")
@Valid
public DefaultValueProvider getDefaultValueProvider() {
return defaultValueProvider;
}
public void setDefaultValueProvider(DefaultValueProvider defaultValueProvider) {
this.defaultValueProvider = defaultValueProvider;
}
@SuppressWarnings("unused")
private static boolean isDefaultValueProviderVisible() {
return EditContext.get().getInputValue("allowMultiple").equals(false);
}
@ShowCondition("isDefaultMultiValueProviderVisible")
@Editable(order=1100, name="Default Value", placeholder="No default value")
@Valid
public DefaultMultiValueProvider getDefaultMultiValueProvider() {
return defaultMultiValueProvider;
}
public void setDefaultMultiValueProvider(DefaultMultiValueProvider defaultMultiValueProvider) {
this.defaultMultiValueProvider = defaultMultiValueProvider;
}
@SuppressWarnings("unused")
private static boolean isDefaultMultiValueProviderVisible() {
return EditContext.get().getInputValue("allowMultiple").equals(true);
}
@Override
public List<String> getPossibleValues() {
return ChoiceInput.getPossibleValues(choiceProvider);
}
@Override
public String getPropertyDef(Map<String, Integer> indexes) {
return ChoiceInput.getPropertyDef(this, indexes, choiceProvider, defaultValueProvider, defaultMultiValueProvider);
}
@Override
public Object convertToObject(List<String> strings) {
return ChoiceInput.convertToObject(this, strings);
}
@Override
public List<String> convertToStrings(Object value) {
return ChoiceInput.convertToStrings(this, value);
}
@Override
public long getOrdinal(String fieldValue) {
if (fieldValue != null) {
List<String> choices = new ArrayList<>(getChoiceProvider().getChoices(true).keySet());
return choices.indexOf(fieldValue);
} else {
return super.getOrdinal(fieldValue);
}
}
@Override
protected void runScripts() {
if (isAllowMultiple() && getDefaultMultiValueProvider() != null)
getDefaultMultiValueProvider().getDefaultValue();
if (!isAllowMultiple() && getDefaultValueProvider() != null)
getDefaultValueProvider().getDefaultValue();
getChoiceProvider().getChoices(true);
}
@Override
public void onMoveProject(String oldPath, String newPath) {
super.onMoveProject(oldPath, newPath);
choiceProvider.onMoveProject(oldPath, newPath);
}
@Override
protected void onDeleteProject(Usage usage, String projectPath) {
usage.add(choiceProvider.onDeleteProject(projectPath));
}
}
|
/*
* Copyright 2004-2012 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 jp.fieldnotes.hatunatu.util.collection;
import java.util.Iterator;
import jp.fieldnotes.hatunatu.util.exception.SNoSuchElementException;
import jp.fieldnotes.hatunatu.util.exception.SUnsupportedOperationException;
import static jp.fieldnotes.hatunatu.util.misc.AssertionUtil.*;
/**
* 配列を{@link Iterator}にするAdaptorです。
* <p>
* 次のように使います.
* </p>
*
* <pre>
* import static org.seasar.util.collection.ArrayIterator.*;
*
* String[] array = ...;
* for (String element : iterable(array)) {
* ...
* }
* </pre>
*
* @author shot
* @param <T>
* 配列の要素の型
*/
public class ArrayIterator<T> implements Iterator<T> {
/** イテレートする要素の配列 */
protected final T[] items;
/** 現在参照している要素のインデックス */
protected int index = 0;
/**
* for each構文で使用するために配列をラップした{@link Iterable}を返します。
*
* @param <T>
* 列挙する要素の型
* @param items
* イテレートする要素の並び。{@literal null}であってはいけません
* @return 配列をラップした{@link Iterable}
*/
public static <T> Iterable<T> iterable(final T... items) {
assertArgumentNotNull("items", items);
return new Iterable<T>() {
@Override
public Iterator<T> iterator() {
return new ArrayIterator<T>(items);
}
};
}
/**
* {@link ArrayIterator}を作成します。
*
* @param items
* イテレートする要素の並び。{@literal null}であってはいけません
*/
public ArrayIterator(final T... items) {
this.items = items;
}
@Override
public boolean hasNext() {
return index < items.length;
}
@Override
public T next() {
try {
final T o = items[index];
index++;
return o;
} catch (final IndexOutOfBoundsException e) {
throw new SNoSuchElementException("index=" + index);
}
}
@Override
public void remove() {
throw new SUnsupportedOperationException("remove");
}
}
|
package frc.robot.commands;
import java.util.function.DoubleSupplier;
import edu.wpi.first.wpilibj.controller.PIDController;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
import edu.wpi.first.wpilibj2.command.CommandBase;
import edu.wpi.first.wpiutil.math.MathUtil;
import frc.robot.Constants.DriveConstants;
import frc.robot.subsystems.DriveTrainSubsystem;
import frc.robot.util.GyroProvider;
/**
* A command that will turn the robot to the specified angle.
*/
public class AimCommand extends CommandBase {
private final DriveTrainSubsystem m_driveTrain;
private final GyroProvider m_gyro;
private double m_desiredAngleToHold = 0;
private DoubleSupplier m_centerXDoubleSupplier;
private final PIDController m_pidController = new PIDController(0.028, 0, 0);
/**
* Turns to robot to the specified angle.
*
* @param targetAngleDegrees The angle to turn to
* @param drive The drive subsystem to use
*/
public AimCommand(DriveTrainSubsystem driveTrain, GyroProvider gyro, DoubleSupplier centerXSupplier) {
addRequirements(driveTrain);
m_gyro = gyro;
m_driveTrain = driveTrain;
m_centerXDoubleSupplier = centerXSupplier;
// Set the controller to be continuous (because it is an angle controller)
m_pidController.enableContinuousInput(-180, 180);
// Set the controller tolerance - the delta tolerance ensures the robot is
// stationary at the
// setpoint before it is considered as having reached the reference
m_pidController.setTolerance(DriveConstants.kTurnToleranceDeg, DriveConstants.kTurnRateToleranceDegPerS);
}
@Override
public void initialize()
{
m_desiredAngleToHold = m_gyro.getHeading() + ((-5.0 / 11.0) * (m_centerXDoubleSupplier.getAsDouble() - 65));
m_pidController.setSetpoint(m_desiredAngleToHold);
System.out.println("Initialized holdcommand to hold angle at " + m_desiredAngleToHold);
}
@Override
public void execute()
{
m_desiredAngleToHold = m_gyro.getHeading() + ((-5.0 / 11.0) * (m_centerXDoubleSupplier.getAsDouble() - 65));
m_pidController.setSetpoint(m_desiredAngleToHold);
// m_desiredAngleToHold = m_angleDoubleSupplier.getAsDouble();
double currentHeading = m_gyro.getHeading();
System.out.println(currentHeading + " " + m_desiredAngleToHold);
double pidOutput = m_pidController.calculate(currentHeading);
// Clamp the output so it doesn't try to turn too fast
double pidOutputClamped = MathUtil.clamp(pidOutput, -0.18, 0.18);
double speedToTurnToCorrect = 0;
if (Math.abs(pidOutputClamped) > 0.02) {
speedToTurnToCorrect = pidOutputClamped * DriveConstants.kMaxAngularSpeed;
m_driveTrain.arcadeDrive(0, speedToTurnToCorrect);
} else {
m_driveTrain.arcadeDrive(0, 0);
}
SmartDashboard.putNumber("AutoAim SetPoint", m_pidController.getSetpoint());
SmartDashboard.putNumber("Current Angle", currentHeading);
SmartDashboard.putNumber("PID Output", pidOutputClamped);
SmartDashboard.putNumber("Turn rate to correct (in radians)", speedToTurnToCorrect);
}
@Override
public boolean isFinished() {
return false;
}
}
|
package systemtests;
import static guitests.guihandles.WebViewUtil.waitUntilBrowserLoaded;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static seedu.giatros.ui.StatusBarFooter.SYNC_STATUS_INITIAL;
import static seedu.giatros.ui.StatusBarFooter.SYNC_STATUS_UPDATED;
import static seedu.giatros.ui.testutil.GuiTestAssert.assertListMatching;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import guitests.guihandles.BrowserPanelHandle;
import guitests.guihandles.CommandBoxHandle;
import guitests.guihandles.MainMenuHandle;
import guitests.guihandles.MainWindowHandle;
import guitests.guihandles.PatientCardHandle;
import guitests.guihandles.PatientListPanelHandle;
import guitests.guihandles.ResultDisplayHandle;
import guitests.guihandles.StatusBarFooterHandle;
import seedu.giatros.TestApp;
import seedu.giatros.commons.core.index.Index;
import seedu.giatros.logic.commands.ClearCommand;
import seedu.giatros.logic.commands.FindCommand;
import seedu.giatros.logic.commands.ListCommand;
import seedu.giatros.logic.commands.SelectCommand;
import seedu.giatros.model.GiatrosBook;
import seedu.giatros.model.Model;
import seedu.giatros.testutil.TypicalPatients;
import seedu.giatros.ui.BrowserPanel;
import seedu.giatros.ui.CommandBox;
/**
* A system test class for GiatrosBook, which provides access to handles of GUI components and helper methods
* for test verification.
*/
public abstract class GiatrosBookSystemTest {
@ClassRule
public static ClockRule clockRule = new ClockRule();
private static final List<String> COMMAND_BOX_DEFAULT_STYLE = Arrays.asList("text-input", "text-field");
private static final List<String> COMMAND_BOX_ERROR_STYLE =
Arrays.asList("text-input", "text-field", CommandBox.ERROR_STYLE_CLASS);
private MainWindowHandle mainWindowHandle;
private TestApp testApp;
private SystemTestSetupHelper setupHelper;
@BeforeClass
public static void setupBeforeClass() {
SystemTestSetupHelper.initialize();
}
@Before
public void setUp() {
setupHelper = new SystemTestSetupHelper();
testApp = setupHelper.setupApplication(this::getInitialData, getDataFileLocation());
mainWindowHandle = setupHelper.setupMainWindowHandle();
waitUntilBrowserLoaded(getBrowserPanel());
assertApplicationStartingStateIsCorrect();
}
@After
public void tearDown() {
setupHelper.tearDownStage();
}
/**
* Returns the data to be loaded into the file in {@link #getDataFileLocation()}.
*/
protected GiatrosBook getInitialData() {
return TypicalPatients.getTypicalGiatrosBook();
}
/**
* Returns the directory of the data file.
*/
protected Path getDataFileLocation() {
return TestApp.SAVE_LOCATION_FOR_TESTING;
}
public MainWindowHandle getMainWindowHandle() {
return mainWindowHandle;
}
public CommandBoxHandle getCommandBox() {
return mainWindowHandle.getCommandBox();
}
public PatientListPanelHandle getPatientListPanel() {
return mainWindowHandle.getPatientListPanel();
}
public MainMenuHandle getMainMenu() {
return mainWindowHandle.getMainMenu();
}
public BrowserPanelHandle getBrowserPanel() {
return mainWindowHandle.getBrowserPanel();
}
public StatusBarFooterHandle getStatusBarFooter() {
return mainWindowHandle.getStatusBarFooter();
}
public ResultDisplayHandle getResultDisplay() {
return mainWindowHandle.getResultDisplay();
}
/**
* Executes {@code command} in the application's {@code CommandBox}.
* Method returns after UI components have been updated.
*/
protected void executeCommand(String command) {
rememberStates();
// Injects a fixed clock before executing a command so that the time stamp shown in the status bar
// after each command is predictable and also different from the previous command.
clockRule.setInjectedClockToCurrentTime();
mainWindowHandle.getCommandBox().run(command);
waitUntilBrowserLoaded(getBrowserPanel());
}
/**
* Displays all patients in the Giatros book.
*/
protected void showAllPatients() {
executeCommand(ListCommand.COMMAND_WORD);
assertEquals(getModel().getGiatrosBook().getPatientList().size(), getModel().getFilteredPatientList().size());
}
/**
* Displays all patients with any parts of their names matching {@code keyword} (case-insensitive).
*/
protected void showPatientsWithName(String keyword) {
executeCommand(FindCommand.COMMAND_WORD + " " + keyword);
assertTrue(getModel().getFilteredPatientList().size() < getModel().getGiatrosBook().getPatientList().size());
}
/**
* Selects the patient at {@code index} of the displayed list.
*/
protected void selectPatient(Index index) {
executeCommand(SelectCommand.COMMAND_WORD + " " + index.getOneBased());
assertEquals(index.getZeroBased(), getPatientListPanel().getSelectedCardIndex());
}
/**
* Deletes all patients in the Giatros book.
*/
protected void deleteAllPatients() {
executeCommand(ClearCommand.COMMAND_WORD);
assertEquals(0, getModel().getGiatrosBook().getPatientList().size());
}
/**
* Asserts that the {@code CommandBox} displays {@code expectedCommandInput}, the {@code ResultDisplay} displays
* {@code expectedResultMessage}, the storage contains the same patient objects as {@code expectedModel}
* and the patient list panel displays the patients in the model correctly.
*/
protected void assertApplicationDisplaysExpected(String expectedCommandInput, String expectedResultMessage,
Model expectedModel) {
assertEquals(expectedCommandInput, getCommandBox().getInput());
assertEquals(expectedResultMessage, getResultDisplay().getText());
assertEquals(new GiatrosBook(expectedModel.getGiatrosBook()), testApp.readStorageGiatrosBook());
assertListMatching(getPatientListPanel(), expectedModel.getFilteredPatientList());
}
/**
* Calls {@code BrowserPanelHandle}, {@code PatientListPanelHandle} and {@code StatusBarFooterHandle} to remember
* their current state.
*/
private void rememberStates() {
StatusBarFooterHandle statusBarFooterHandle = getStatusBarFooter();
getBrowserPanel().rememberUrl();
statusBarFooterHandle.rememberSaveLocation();
statusBarFooterHandle.rememberSyncStatus();
getPatientListPanel().rememberSelectedPatientCard();
}
/**
* Asserts that the previously selected card is now deselected and the browser's url is now displaying the
* default page.
* @see BrowserPanelHandle#isUrlChanged()
*/
protected void assertSelectedCardDeselected() {
assertEquals(BrowserPanel.DEFAULT_PAGE, getBrowserPanel().getLoadedUrl());
assertFalse(getPatientListPanel().isAnyCardSelected());
}
/**
* Asserts that the browser's url is changed to display the details of the patient in the patient list panel at
* {@code expectedSelectedCardIndex}, and only the card at {@code expectedSelectedCardIndex} is selected.
* @see BrowserPanelHandle#isUrlChanged()
* @see PatientListPanelHandle#isSelectedPatientCardChanged()
*/
protected void assertSelectedCardChanged(Index expectedSelectedCardIndex) {
getPatientListPanel().navigateToCard(getPatientListPanel().getSelectedCardIndex());
PatientCardHandle selectedCard = getPatientListPanel().getHandleToSelectedCard();
URL expectedUrl;
try {
expectedUrl = new URL(BrowserPanel.SEARCH_PAGE_URL + selectedCard.getAllergies().toArray()[0]);
} catch (MalformedURLException mue) {
throw new AssertionError("URL expected to be valid.", mue);
} catch (IndexOutOfBoundsException ioube) {
expectedUrl = BrowserPanel.DEFAULT_PAGE;
}
assertEquals(expectedUrl, getBrowserPanel().getLoadedUrl());
assertEquals(expectedSelectedCardIndex.getZeroBased(), getPatientListPanel().getSelectedCardIndex());
}
/**
* Asserts that the browser's url and the selected card in the patient list panel remain unchanged.
* @see BrowserPanelHandle#isUrlChanged()
* @see PatientListPanelHandle#isSelectedPatientCardChanged()
*/
protected void assertSelectedCardUnchanged() {
assertFalse(getBrowserPanel().isUrlChanged());
assertFalse(getPatientListPanel().isSelectedPatientCardChanged());
}
/**
* Asserts that the command box's shows the default style.
*/
protected void assertCommandBoxShowsDefaultStyle() {
assertEquals(COMMAND_BOX_DEFAULT_STYLE, getCommandBox().getStyleClass());
}
/**
* Asserts that the command box's shows the error style.
*/
protected void assertCommandBoxShowsErrorStyle() {
assertEquals(COMMAND_BOX_ERROR_STYLE, getCommandBox().getStyleClass());
}
/**
* Asserts that the entire status bar remains the same.
*/
protected void assertStatusBarUnchanged() {
StatusBarFooterHandle handle = getStatusBarFooter();
assertFalse(handle.isSaveLocationChanged());
assertFalse(handle.isSyncStatusChanged());
}
/**
* Asserts that only the sync status in the status bar was changed to the timing of
* {@code ClockRule#getInjectedClock()}, while the save location remains the same.
*/
protected void assertStatusBarUnchangedExceptSyncStatus() {
StatusBarFooterHandle handle = getStatusBarFooter();
String timestamp = new Date(clockRule.getInjectedClock().millis()).toString();
String expectedSyncStatus = String.format(SYNC_STATUS_UPDATED, timestamp);
assertEquals(expectedSyncStatus, handle.getSyncStatus());
assertFalse(handle.isSaveLocationChanged());
}
/**
* Asserts that the starting state of the application is correct.
*/
private void assertApplicationStartingStateIsCorrect() {
assertEquals("", getCommandBox().getInput());
assertEquals("", getResultDisplay().getText());
assertListMatching(getPatientListPanel(), getModel().getFilteredPatientList());
assertEquals(BrowserPanel.DEFAULT_PAGE, getBrowserPanel().getLoadedUrl());
assertEquals(Paths.get(".").resolve(testApp.getStorageSaveLocation()).toString(),
getStatusBarFooter().getSaveLocation());
assertEquals(SYNC_STATUS_INITIAL, getStatusBarFooter().getSyncStatus());
}
/**
* Returns a defensive copy of the current model.
*/
protected Model getModel() {
return testApp.getModel();
}
}
|
/*
*
*/
package com.compomics.pride_asa_pipeline.core.service.impl;
import com.compomics.omssa.xsd.UserModCollection;
import com.compomics.pride_asa_pipeline.core.logic.modification.OmssaModificationMarshaller;
import com.compomics.pride_asa_pipeline.core.model.ModificationHolder;
import com.compomics.pride_asa_pipeline.core.model.SpectrumAnnotatorResult;
import com.compomics.pride_asa_pipeline.core.service.ModificationService;
import static com.compomics.pride_asa_pipeline.core.service.ModificationService.MASS_DELTA_TOLERANCE;
import com.compomics.pride_asa_pipeline.core.util.MathUtils;
import com.compomics.pride_asa_pipeline.model.AminoAcid;
import com.compomics.pride_asa_pipeline.model.Identification;
import com.compomics.pride_asa_pipeline.model.Modification;
import com.compomics.pride_asa_pipeline.model.ModificationFacade;
import com.compomics.pride_asa_pipeline.model.ModifiedPeptide;
import com.compomics.pride_asa_pipeline.model.Peptide;
import com.google.common.collect.HashMultiset;
import com.google.common.collect.Multiset;
import java.util.*;
import org.apache.log4j.Logger;
/**
*
* @author Niels Hulstaert
*/
public abstract class ModificationServiceImpl implements ModificationService {
private static final Logger LOGGER = Logger.getLogger(ModificationServiceImpl.class);
private static final String[] MS1_MODIFICATION_NAMES = {"itraq", "tmt"};
protected OmssaModificationMarshaller omssaModificationMarshaller;
public OmssaModificationMarshaller getOmssaModificationMarshaller() {
return omssaModificationMarshaller;
}
public void setOmssaModificationMarshaller(OmssaModificationMarshaller omssaModificationMarshaller) {
this.omssaModificationMarshaller = omssaModificationMarshaller;
}
@Override
public Map<Modification, Integer> getUsedModifications(SpectrumAnnotatorResult spectrumAnnotatorResult) {
Map<Modification, Integer> modifications = new HashMap<>();
for (Identification identification : spectrumAnnotatorResult.getModifiedPrecursors()) {
ModifiedPeptide modifiedPeptide = (ModifiedPeptide) identification.getPeptide();
if (modifiedPeptide.getNTermMod() != null) {
addModificationToMap(modifications, (Modification) modifiedPeptide.getNTermMod());
}
if (modifiedPeptide.getNTModifications() != null) {
for (int i = 0; i < modifiedPeptide.getNTModifications().length; i++) {
Modification modification = (Modification) modifiedPeptide.getNTModifications()[i];
if (modification != null) {
addModificationToMap(modifications, modification);
}
}
}
if (modifiedPeptide.getCTermMod() != null) {
addModificationToMap(modifications, (Modification) modifiedPeptide.getCTermMod());
}
}
return modifications;
}
public Map<Modification, Double> estimateModificationRate2(Map<Modification, Integer> usedModifications, SpectrumAnnotatorResult spectrumAnnotatorResult, double fixedModificationThreshold) {
// calculate number of peptides that contain
HashMultiset<AminoAcid> aminoAcidHashMultiset = HashMultiset.create();
List<Identification> identifications = spectrumAnnotatorResult.getIdentifications();
for (Identification identification : identifications) {
String sequenceString = identification.getPeptide().getSequenceString();
for (AminoAcid aa : EnumSet.allOf(AminoAcid.class)) {
if (sequenceString.contains("" + aa.letter())) {
aminoAcidHashMultiset.add(aa);
}
}
}
// convert to aminoacid/integer map
Map<AminoAcid, Integer> aminoAcidCounts = new HashMap<>();
for (Multiset.Entry entry : aminoAcidHashMultiset.entrySet()) {
aminoAcidCounts.put((AminoAcid) entry.getElement(), entry.getCount());
}
// run over used modifications and their frequencies,
// verify which Modifications are nearly always present when the
// affected amino acid is in the peptide sequence
Map<Modification, Double> result = new HashMap<>();
for (Modification usedModifiation : usedModifications.keySet()) {
double modificationCount = new Double(usedModifications.get(usedModifiation));
double aminoAcidCount = 0;
for (AminoAcid affectedAminoAcid : usedModifiation.getAffectedAminoAcids()) {
aminoAcidCount += aminoAcidCounts.get(affectedAminoAcid);
}
// Fix the fixed modification treshold at 95%
double modificationRate = modificationCount / aminoAcidCount;
result.put(usedModifiation, modificationRate);
}
return result;
}
@Override
public Map<Modification, Double> estimateModificationRate(Map<Modification, Integer> usedModifications, SpectrumAnnotatorResult spectrumAnnotatorResult, double fixedModificationThreshold) {
Map<Modification, Double> modificationRates = new HashMap<>();
//create hashmultisets for the 3 types of modifications (N-terminal, Non-terminal, C-terminal)
//to keep track of the AA counts
HashMultiset<AminoAcid> nTermimalAminoAcidHashMultiset = HashMultiset.create();
HashMultiset<AminoAcid> nonTermimalAminoAcidHashMultiset = HashMultiset.create();
HashMultiset<AminoAcid> cTermimalAminoAcidHashMultiset = HashMultiset.create();
//iterate over the identifications
List<Identification> identifications = spectrumAnnotatorResult.getIdentifications();
for (Identification identification : identifications) {
Peptide peptide = identification.getPeptide();
nTermimalAminoAcidHashMultiset.add(peptide.getSequence().getAA(0));
for (AminoAcid aminoAcid : peptide.getSequence().getAASequence()) {
nonTermimalAminoAcidHashMultiset.add(aminoAcid);
}
cTermimalAminoAcidHashMultiset.add(peptide.getSequence().getAA(peptide.getSequence().length() - 1));
}
//convert to maps
Map<AminoAcid, Integer> nTermimalAminoAcidCounts = new HashMap<>();
for (Multiset.Entry entry : nTermimalAminoAcidHashMultiset.entrySet()) {
nTermimalAminoAcidCounts.put((AminoAcid) entry.getElement(), entry.getCount());
}
Map<AminoAcid, Integer> nonTermimalAminoAcidCounts = new HashMap<>();
for (Multiset.Entry entry : nonTermimalAminoAcidHashMultiset.entrySet()) {
nonTermimalAminoAcidCounts.put((AminoAcid) entry.getElement(), entry.getCount());
}
Map<AminoAcid, Integer> cTermimalAminoAcidCounts = new HashMap<>();
for (Multiset.Entry entry : cTermimalAminoAcidHashMultiset.entrySet()) {
cTermimalAminoAcidCounts.put((AminoAcid) entry.getElement(), entry.getCount());
}
//run over used modifications and their frequencies,
//verify which Modifications are nearly always present when the
//affected amino acid is in the peptide sequence
for (Modification modifiation : usedModifications.keySet()) {
double modificationRate = 0.0;
Map<AminoAcid, Integer> modificationAminoAcidCounts = calculateModificationAminoAcidCounts(spectrumAnnotatorResult, modifiation);
List<Double> modificationAminoAcidRates = new ArrayList<>();
if (modifiation.getLocation().equals(Modification.Location.N_TERMINAL)) {
for (AminoAcid affectedAminoAcid : modificationAminoAcidCounts.keySet()) {
modificationAminoAcidRates.add(modificationAminoAcidCounts.get(affectedAminoAcid).doubleValue() / nTermimalAminoAcidCounts.get(affectedAminoAcid));
}
modificationRate = MathUtils.calculateMedian(modificationAminoAcidRates);
} else if (modifiation.getLocation().equals(Modification.Location.NON_TERMINAL)) {
for (AminoAcid affectedAminoAcid : modificationAminoAcidCounts.keySet()) {
modificationAminoAcidRates.add(modificationAminoAcidCounts.get(affectedAminoAcid).doubleValue() / nonTermimalAminoAcidCounts.get(affectedAminoAcid));
}
modificationRate = MathUtils.calculateMedian(modificationAminoAcidRates);
} else if (modifiation.getLocation().equals(Modification.Location.C_TERMINAL)){
for (AminoAcid affectedAminoAcid : modificationAminoAcidCounts.keySet()) {
modificationAminoAcidRates.add(modificationAminoAcidCounts.get(affectedAminoAcid).doubleValue() / cTermimalAminoAcidCounts.get(affectedAminoAcid));
}
modificationRate = MathUtils.calculateMedian(modificationAminoAcidRates);
}
else{
//do nothing
}
modificationRates.put(modifiation, modificationRate);
}
return modificationRates;
}
@Override
public UserModCollection getModificationsAsUserModCollection(SpectrumAnnotatorResult spectrumAnnotatorResult) {
Set<Modification> modifications = getUsedModifications(spectrumAnnotatorResult).keySet();
return omssaModificationMarshaller.marshallModifications(modifications);
}
@Override
public Set<Modification> filterModifications(ModificationHolder modificationHolder, Set<Modification> modifications) {
Set<Modification> conflictingModifications = new HashSet<>();
//first, check for mods with too many affected amino acids/locations
for (Modification modification : modifications) {
//only look for non-terminal mods
if (modification.getLocation().equals(Modification.Location.NON_TERMINAL) && modification.getAffectedAminoAcids().size() > MAX_AFFECTED_AMINO_ACIDS) {
LOGGER.info("Excluded PRIDE modification " + modification.getAccession() + " (" + modification.getName() + ") with too many affected amino acids.");
conflictingModifications.add(modification);
}
}
//second, check for mods with equal masses within the pride mods
Modification[] modificationsArray = modifications.toArray(new Modification[0]);
for (int i = 0; i < modificationsArray.length; i++) {
for (int j = (modificationsArray.length - 1); j > i && j >= 0; j--) {
//first, check for equal masses
if ((Math.abs(modificationsArray[i].getMonoIsotopicMassShift() - modificationsArray[j].getMonoIsotopicMassShift())) < MASS_DELTA_TOLERANCE) {
//second, check for same location
if (modificationsArray[i].getLocation().equals(modificationsArray[j].getLocation())) {
//third, check for same affected amino acids
for (AminoAcid aminoAcid : modificationsArray[i].getAffectedAminoAcids()) {
if (modificationsArray[j].getAffectedAminoAcids().contains(aminoAcid)) {
LOGGER.info("Excluded PRIDE modification " + modificationsArray[j].getAccession() + " (" + modificationsArray[j].getName() + ") with equal mass.");
conflictingModifications.add(modificationsArray[j]);
//break as soon as one of the affected amino acids is the same
break;
}
}
}
}
}
}
//third, check for modifications with the same mass compared to the pipeline modifications
for (Modification modification : modificationHolder.getAllModifications()) {
for (Modification modificationToCheck : modifications) {
//first, check for equal masses
if ((Math.abs(modification.getMonoIsotopicMassShift() - modificationToCheck.getMonoIsotopicMassShift())) < MASS_DELTA_TOLERANCE) {
//second, check for same location
if (modification.getLocation().equals(modificationToCheck.getLocation())) {
//third, check for same affected amino acids
for (AminoAcid aminoAcid : modification.getAffectedAminoAcids()) {
if (modificationToCheck.getAffectedAminoAcids().contains(aminoAcid)) {
LOGGER.info("Excluded PRIDE modification " + modificationToCheck.getAccession() + " (" + modificationToCheck.getName() + ") with equal mass.");
conflictingModifications.add(modificationToCheck);
//break as soon as one of the affected amino acids is the same
break;
}
}
}
}
}
}
return conflictingModifications;
}
/**
* Adds a modification to the modifications. If the modification is already
* present, check if the location needs to be updated.
*
* @param modification the modification
* @param modifications the map of modifications (key: modification name;
* value: modification)
*/
protected void addModificationToModifications(Modification modification, Map<String, Modification> modifications) {
if (modifications.containsKey(modification.getName())) {
Modification presentModification = modifications.get(modification.getName());
//update affected amino acids
presentModification.getAffectedAminoAcids().addAll(modification.getAffectedAminoAcids());
//check if location is the same as the present one
//if the location differs, update it to Location.NON_TERMINAL
if (!presentModification.getLocation().equals(Modification.Location.NON_TERMINAL) && !presentModification.getLocation().equals(modification.getLocation())) {
presentModification.setLocation(Modification.Location.NON_TERMINAL);
}
} else {
//check for a MS1 modification
for (String ms1ModName : MS1_MODIFICATION_NAMES) {
if (modification.getName().toLowerCase().contains(ms1ModName)) {
modification.setType(Modification.Type.MS1);
}
}
modifications.put(modification.getName(), modification);
}
}
/**
* Adds a modification to the modifications map. If already present, the
* occurence count is incremented.
*
* @param modifications the modifications map (key: modification, value:
* modification occurence count)
* @param modification the modification
*/
private void addModificationToMap(Map<Modification, Integer> modifications, Modification modification) {
if (modifications.containsKey(modification)) {
modifications.put(modification, modifications.get(modification) + 1);
} else {
modifications.put(modification, 1);
}
}
/**
* Calculate the AA counts for given modification.
*
* @param spectrumAnnotatorResult
* @param modification
* @return
*/
private Map<AminoAcid, Integer> calculateModificationAminoAcidCounts(SpectrumAnnotatorResult spectrumAnnotatorResult, Modification modification) {
Map<AminoAcid, Integer> modificationAminoAcidCounts = new HashMap<>();
HashMultiset<AminoAcid> modificationAminoAcidCountsMultiSet = HashMultiset.create();
for (Identification identification : spectrumAnnotatorResult.getModifiedPrecursors()) {
ModifiedPeptide modifiedPeptide = (ModifiedPeptide) identification.getPeptide();
if (modification.getLocation().equals(Modification.Location.N_TERMINAL) && modifiedPeptide.getNTermMod() != null) {
ModificationFacade modificationFacade = modifiedPeptide.getNTermMod();
if (modificationFacade != null && modificationFacade.getName().equals(modification.getName())) {
modificationAminoAcidCountsMultiSet.add(modifiedPeptide.getAA(0));
}
} else if (modification.getLocation().equals(Modification.Location.NON_TERMINAL)) {
for (int i = 0; i < modifiedPeptide.getNTModifications().length; i++) {
ModificationFacade modificationFacade = modifiedPeptide.getNTModifications()[i];
if (modificationFacade != null && modificationFacade.getName().equals(modification.getName())) {
modificationAminoAcidCountsMultiSet.add(modifiedPeptide.getAA(i));
}
}
} else if (modification.getLocation().equals(Modification.Location.C_TERMINAL) && modifiedPeptide.getCTermMod() != null) {
ModificationFacade modificationFacade = modifiedPeptide.getCTermMod();
if (modificationFacade != null && modificationFacade.getName().equals(modification.getName())) {
modificationAminoAcidCountsMultiSet.add(modifiedPeptide.getAA(modifiedPeptide.length() - 1));
}
} else {
//do nothing
}
}
for (Multiset.Entry entry : modificationAminoAcidCountsMultiSet.entrySet()) {
modificationAminoAcidCounts.put((AminoAcid) entry.getElement(), entry.getCount());
}
return modificationAminoAcidCounts;
}
}
|
package aima.core.probability.bayes.exact;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import aima.core.probability.CategoricalDistribution;
import aima.core.probability.Factor;
import aima.core.probability.RandomVariable;
import aima.core.probability.bayes.BayesInference;
import aima.core.probability.bayes.BayesianNetwork;
import aima.core.probability.bayes.FiniteNode;
import aima.core.probability.bayes.Node;
import aima.core.probability.proposition.AssignmentProposition;
import aima.core.probability.util.ProbabilityTable;
/**
* Artificial Intelligence A Modern Approach (3rd Edition): Figure 14.11, page
* 528.<br>
* <br>
*
* <pre>
* function ELIMINATION-ASK(X, e, bn) returns a distribution over X
* inputs: X, the query variable
* e, observed values for variables E
* bn, a Bayesian network specifying joint distribution P(X<sub>1</sub>, ..., X<sub>n</sub>)
*
* factors <- []
* for each var in ORDER(bn.VARS) do
* factors <- [MAKE-FACTOR(var, e) | factors]
* if var is hidden variable the factors <- SUM-OUT(var, factors)
* return NORMALIZE(POINTWISE-PRODUCT(factors))
* </pre>
*
* Figure 14.11 The variable elimination algorithm for inference in Bayesian
* networks. <br>
* <br>
* <b>Note:</b> The implementation has been extended to handle queries with
* multiple variables. <br>
*
* @author Ciaran O'Reilly
*/
public class EliminationAsk implements BayesInference {
//
private static final ProbabilityTable _identity = new ProbabilityTable(
new double[] { 1.0 });
public EliminationAsk() {
}
// function ELIMINATION-ASK(X, e, bn) returns a distribution over X
/**
* The ELIMINATION-ASK algorithm in Figure 14.11.
*
* @param X
* the query variables.
* @param e
* observed values for variables E.
* @param bn
* a Bayes net with variables {X} ∪ E ∪ Y /* Y = hidden
* variables //
* @return a distribution over the query variables.
*/
public CategoricalDistribution eliminationAsk(final RandomVariable[] X,
final AssignmentProposition[] e, final BayesianNetwork bn) {
Set<RandomVariable> hidden = new HashSet<RandomVariable>();
List<RandomVariable> VARS = new ArrayList<RandomVariable>();
calculateVariables(X, e, bn, hidden, VARS);
// factors <- []
List<Factor> factors = new ArrayList<Factor>();
// for each var in ORDER(bn.VARS) do
for (RandomVariable var : order(bn, VARS)) {
// factors <- [MAKE-FACTOR(var, e) | factors]
factors.add(0, makeFactor(var, e, bn));
// if var is hidden variable then factors <- SUM-OUT(var, factors)
if (hidden.contains(var)) {
factors = sumOut(var, factors, bn);
}
}
// return NORMALIZE(POINTWISE-PRODUCT(factors))
Factor product = pointwiseProduct(factors);
// Note: Want to ensure the order of the product matches the
// query variables
return ((ProbabilityTable) product.pointwiseProductPOS(_identity, X))
.normalize();
}
//
// START-BayesInference
public CategoricalDistribution ask(final RandomVariable[] X,
final AssignmentProposition[] observedEvidence,
final BayesianNetwork bn) {
return this.eliminationAsk(X, observedEvidence, bn);
}
// END-BayesInference
//
//
// PROTECTED METHODS
//
/**
* <b>Note:</b>Override this method for a more efficient implementation as
* outlined in AIMA3e pgs. 527-28. Calculate the hidden variables from the
* Bayesian Network. The default implementation does not perform any of
* these.<br>
* <br>
* Two calcuations to be performed here in order to optimize iteration over
* the Bayesian Network:<br>
* 1. Calculate the hidden variables to be enumerated over. An optimization
* (AIMA3e pg. 528) is to remove 'every variable that is not an ancestor of
* a query variable or evidence variable as it is irrelevant to the query'
* (i.e. sums to 1). 2. The subset of variables from the Bayesian Network to
* be retained after irrelevant hidden variables have been removed.
*
* @param X
* the query variables.
* @param e
* observed values for variables E.
* @param bn
* a Bayes net with variables {X} ∪ E ∪ Y /* Y = hidden
* variables //
* @param hidden
* to be populated with the relevant hidden variables Y.
* @param bnVARS
* to be populated with the subset of the random variables
* comprising the Bayesian Network with any irrelevant hidden
* variables removed.
*/
protected void calculateVariables(final RandomVariable[] X,
final AssignmentProposition[] e, final BayesianNetwork bn,
Set<RandomVariable> hidden, Collection<RandomVariable> bnVARS) {
bnVARS.addAll(bn.getVariablesInTopologicalOrder());
hidden.addAll(bnVARS);
for (RandomVariable x : X) {
hidden.remove(x);
}
for (AssignmentProposition ap : e) {
hidden.removeAll(ap.getScope());
}
return;
}
/**
* <b>Note:</b>Override this method for a more efficient implementation as
* outlined in AIMA3e pgs. 527-28. The default implementation does not
* perform any of these.<br>
*
* @param bn
* the Bayesian Network over which the query is being made. Note,
* is necessary to provide this in order to be able to determine
* the dependencies between variables.
* @param vars
* a subset of the RandomVariables making up the Bayesian
* Network, with any irrelevant hidden variables alreay removed.
* @return a possibly opimal ordering for the random variables to be
* iterated over by the algorithm. For example, one fairly effective
* ordering is a greedy one: eliminate whichever variable minimizes
* the size of the next factor to be constructed.
*/
protected List<RandomVariable> order(BayesianNetwork bn,
Collection<RandomVariable> vars) {
// Note: Trivial Approach:
// For simplicity just return in the reverse order received,
// i.e. received will be the default topological order for
// the Bayesian Network and we want to ensure the network
// is iterated from bottom up to ensure when hidden variables
// are come across all the factors dependent on them have
// been seen so far.
List<RandomVariable> order = new ArrayList<RandomVariable>(vars);
Collections.reverse(order);
return order;
}
//
// PRIVATE METHODS
//
private Factor makeFactor(RandomVariable var, AssignmentProposition[] e,
BayesianNetwork bn) {
Node n = bn.getNode(var);
if (!(n instanceof FiniteNode)) {
throw new IllegalArgumentException(
"Elimination-Ask only works with finite Nodes.");
}
FiniteNode fn = (FiniteNode) n;
List<AssignmentProposition> evidence = new ArrayList<AssignmentProposition>();
for (AssignmentProposition ap : e) {
if (fn.getCPT().contains(ap.getTermVariable())) {
evidence.add(ap);
}
}
return fn.getCPT().getFactorFor(
evidence.toArray(new AssignmentProposition[evidence.size()]));
}
private List<Factor> sumOut(RandomVariable var, List<Factor> factors,
BayesianNetwork bn) {
List<Factor> summedOutFactors = new ArrayList<Factor>();
List<Factor> toMultiply = new ArrayList<Factor>();
for (Factor f : factors) {
if (f.contains(var)) {
toMultiply.add(f);
} else {
// This factor does not contain the variable
// so no need to sum out - see AIMA3e pg. 527.
summedOutFactors.add(f);
}
}
summedOutFactors.add(pointwiseProduct(toMultiply).sumOut(var));
return summedOutFactors;
}
private Factor pointwiseProduct(List<Factor> factors) {
Factor product = factors.get(0);
for (int i = 1; i < factors.size(); i++) {
product = product.pointwiseProduct(factors.get(i));
}
return product;
}
}
|
package org.irods.jargon.dataone.utils;
public final class RestVersion {
public static String VERSION="4.2.1.0-SNAPSHOT";
public static String BUILD_TIME="2017-10-04T13:54:11Z";
}
|
//,temp,CapacityDaoImpl.java,543,564,temp,ManagementServerHostDaoImpl.java,126,150
//,3
public class xxx {
@Override
@DB
public void update(long id, long runid, Date lastUpdate) {
TransactionLegacy txn = TransactionLegacy.currentTxn();
PreparedStatement pstmt = null;
try {
txn.start();
pstmt = txn.prepareAutoCloseStatement("update mshost set last_update=?, removed=null, alert_count=0 where id=? and runid=?");
pstmt.setString(1, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), lastUpdate));
pstmt.setLong(2, id);
pstmt.setLong(3, runid);
int count = pstmt.executeUpdate();
txn.commit();
if (count < 1) {
s_logger.info("Invalid cluster session detected, runId " + runid + " is no longer valid");
throw new CloudRuntimeException("Invalid cluster session detected, runId " + runid + " is no longer valid", new ClusterInvalidSessionException("runId " + runid + " is no longer valid"));
}
} catch (Exception e) {
s_logger.warn("Unexpected exception, ", e);
throw new RuntimeException(e.getMessage(), e);
}
}
};
|
/****************************************************************
* Licensed to the AOS Community (AOS) under one or more *
* contributor license agreements. See the NOTICE file *
* distributed with this work for additional information *
* regarding copyright ownership. The AOS 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.wideplay.warp.persist.jdo;
import org.testng.annotations.*;
import com.google.inject.Guice;
import com.google.inject.AbstractModule;
import com.google.inject.Injector;
import com.google.inject.Inject;
import com.google.inject.matcher.Matchers;
import com.wideplay.warp.persist.PersistenceService;
import com.wideplay.warp.persist.UnitOfWork;
import com.wideplay.warp.persist.WorkManager;
import com.wideplay.warp.persist.Transactional;
import javax.jdo.*;
import javax.persistence.EntityManager;
import java.io.IOException;
import java.util.Date;
import java.util.List;
/**
* @author Miroslav Genov (mgenov@gmail.com)
*/
@Test(suiteName = "jdo")
public class JoiningLocalTransactionsTest {
private Injector injector;
private static final String UNIQUE_TEXT = JoiningLocalTransactionsTest.class + "some unique text" + new Date();
private static final String TRANSIENT_UNIQUE_TEXT = JoiningLocalTransactionsTest.class + "some other unique text" + new Date();
private static final Long ID = new Long(0);
@BeforeClass
public void before() {
injector = Guice.createInjector(PersistenceService.usingJdo()
.across(UnitOfWork.TRANSACTION)
.forAll(Matchers.any())
.buildModule(),
new AbstractModule() {
protected void configure() {
//bind persistence unit to may establish connection to the database
bindConstant().annotatedWith(JdoUnit.class).to("testFactory");
}
});
JDOEnhancer enhancer = JDOHelper.getEnhancer();
enhancer.setVerbose(true);
enhancer.addClasses(JdoTestEntity.class.getName());
enhancer.enhance();
injector.getInstance(PersistenceService.class).start();
}
@AfterMethod
//cleanup persistencemanager in case some of the rollback tests left it in an open state
public void post() {
injector.getInstance(WorkManager.class).endWork();
}
@AfterClass
public void postClass() {
injector.getInstance(PersistenceService.class).shutdown();
}
@Test
public void testSimpleTransaction() {
injector.getInstance(JoiningLocalTransactionsTest.TransactionalObject.class).runOperationInTxn();
PersistenceManager pm = injector.getInstance(PersistenceManager.class);
assert !pm.currentTransaction().isActive() : "txn was not closed by transactional service";
//test that the data has been stored
List<JdoTestEntity> result = (List<JdoTestEntity>) pm.newQuery(JdoTestEntity.class, "text == '" + UNIQUE_TEXT + "'").execute();
injector.getInstance(WorkManager.class).endWork();
assert 1 == result.size() : "queried entity did not match--did automatic txn fail?";
}
@Test
public void sampleTest() {
PersistenceManagerFactory f = injector.getInstance(PersistenceManagerFactory.class);
PersistenceManagerFactory f2 = injector.getInstance(PersistenceManagerFactory.class);
assert f == f2 : "factory is not singleton";
}
@Test
public void testSimpleTransactionRollbackOnChecked() {
try {
injector.getInstance(JoiningLocalTransactionsTest.TransactionalObject.class).runOperationInTxnThrowingChecked();
} catch (IOException e) {
//ignore
System.out.println("caught (expecting rollback) " + e);
injector.getInstance(WorkManager.class).endWork();
}
PersistenceManager pm = injector.getInstance(PersistenceManager.class);
assert !pm.currentTransaction().isActive() : "PM was not closed by transactional service (rollback didnt happen?)";
//test that the data has been stored
List<JdoTestEntity> result = (List<JdoTestEntity>)pm.newQuery(JdoTestEntity.class, "text == '" + TRANSIENT_UNIQUE_TEXT + "'").execute();
injector.getInstance(WorkManager.class).endWork();
assert 0 == result.size() : "a result was returned! rollback sure didnt happen!!!";
}
@Test
public void testSimpleTransactionRollbackOnUnchecked() {
try {
injector.getInstance(JoiningLocalTransactionsTest.TransactionalObject.class).runOperationInTxnThrowingUnchecked();
} catch(RuntimeException re) {
//ignore
System.out.println("caught (expecting rollback) " + re);
injector.getInstance(WorkManager.class).endWork();
}
PersistenceManager pm = injector.getInstance(PersistenceManager.class);
assert !pm.currentTransaction().isActive() : "Session was not closed by transactional service (rollback didnt happen?)";
//test that the data has been stored
List<JdoTestEntity> result = (List<JdoTestEntity>) pm.newQuery(JdoTestEntity.class, "text == '" + TRANSIENT_UNIQUE_TEXT + "'").execute();
injector.getInstance(WorkManager.class).endWork();
assert 0 == result.size() : "a result was returned! rollback sure didnt happen!!!";
}
public static class TransactionalObject {
private final PersistenceManager pm;
@Inject
public TransactionalObject(PersistenceManager pm) {
this.pm = pm;
}
@Transactional
public void runOperationInTxn() {
runOperationInTxnInternal();
}
@Transactional(rollbackOn = IOException.class)
public void runOperationInTxnInternal() {
JdoTestEntity entity = new JdoTestEntity();
entity.setText(UNIQUE_TEXT);
pm.makePersistent(entity);
}
@Transactional(rollbackOn = IOException.class)
public void runOperationInTxnThrowingChecked() throws IOException {
runOperationInTxnThrowingCheckedInternal();
}
@Transactional
private void runOperationInTxnThrowingCheckedInternal() throws IOException {
JdoTestEntity entity = new JdoTestEntity();
entity.setText(TRANSIENT_UNIQUE_TEXT);
pm.makePersistent(entity);
throw new IOException();
}
@Transactional
public void runOperationInTxnThrowingUnchecked() {
runOperationInTxnThrowingUncheckedInternal();
}
@Transactional(rollbackOn = IOException.class)
public void runOperationInTxnThrowingUncheckedInternal() {
JdoTestEntity entity = new JdoTestEntity();
entity.setText(TRANSIENT_UNIQUE_TEXT);
pm.makePersistent(entity);
throw new IllegalStateException();
}
}
}
|
/*
* Copyright 2021 Apollo 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.yofish.apollo.openapi.repository;
import com.yofish.apollo.openapi.entity.ConsumerAudit;
import org.springframework.data.repository.PagingAndSortingRepository;
/**
* @author Jason Song(song_s@ctrip.com)
*/
public interface ConsumerAuditRepository extends PagingAndSortingRepository<ConsumerAudit, Long> {
}
|
/*
* 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.sandynz.sdcommons.base.time.range;
import java.util.ArrayList;
import java.util.List;
import lombok.Data;
import lombok.ToString;
import lombok.experimental.Accessors;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormatter;
import org.junit.Assert;
import org.junit.Test;
import org.sandynz.sdcommons.base.time.JodaDateTimeFormatters;
/**
* JodaDateTimeRange test cases.
*
* @author sandynz
*/
@Slf4j
public class JodaDateTimeRangeTest {
@Data
@Accessors(chain = true)
@ToString
private static class TestCfg {
String startTimeStr;
String endTimeStr;
DateTimeFormatter dateTimeFormatter;
TimeRangeIntervalUnit intervalUnit;
int expectedCount;
}
private void test0(TestCfg cfg) {
log.info("------\nstart, cfg={}", cfg);
DateTimeFormatter dateTimeFormatter = cfg.dateTimeFormatter;
List<DateTime> dateTimeList = new ArrayList<>();
for (DateTime next : new JodaDateTimeRange(
dateTimeFormatter.parseDateTime(cfg.startTimeStr),
dateTimeFormatter.parseDateTime(cfg.endTimeStr),
cfg.intervalUnit)) {
log.info("next {} = {}", cfg.intervalUnit, dateTimeFormatter.print(next));
dateTimeList.add(next);
}
Assert.assertEquals(cfg.expectedCount, dateTimeList.size());
Assert.assertEquals(cfg.startTimeStr, dateTimeFormatter.print(dateTimeList.get(0)));
Assert.assertEquals(cfg.endTimeStr, dateTimeFormatter.print(dateTimeList.get(dateTimeList.size() - 1)));
}
@Test
public void testYearRange() {
TestCfg cfg = new TestCfg()
.setStartTimeStr("2017").setEndTimeStr("2019")
.setDateTimeFormatter(JodaDateTimeFormatters.yyyy)
.setIntervalUnit(TimeRangeIntervalUnit.YEAR)
.setExpectedCount(3);
test0(cfg);
cfg.setEndTimeStr(cfg.getStartTimeStr()).setExpectedCount(1);
test0(cfg);
}
@Test
public void testMonthRange() {
TestCfg cfg = new TestCfg()
.setStartTimeStr("2019-01").setEndTimeStr("2019-03")
.setDateTimeFormatter(JodaDateTimeFormatters.yyyyMM)
.setIntervalUnit(TimeRangeIntervalUnit.MONTH)
.setExpectedCount(3);
test0(cfg);
cfg.setEndTimeStr(cfg.getStartTimeStr()).setExpectedCount(1);
test0(cfg);
}
@Test
public void testDayRange() {
TestCfg cfg = new TestCfg()
.setStartTimeStr("2019-09-26").setEndTimeStr("2019-09-28")
.setDateTimeFormatter(JodaDateTimeFormatters.yyyyMMdd)
.setIntervalUnit(TimeRangeIntervalUnit.DAY)
.setExpectedCount(3);
test0(cfg);
cfg.setEndTimeStr(cfg.getStartTimeStr()).setExpectedCount(1);
test0(cfg);
}
@Test
public void testHourRange() {
TestCfg cfg = new TestCfg()
.setStartTimeStr("2019-09-26 21").setEndTimeStr("2019-09-26 23")
.setDateTimeFormatter(JodaDateTimeFormatters.yyyyMMddHH)
.setIntervalUnit(TimeRangeIntervalUnit.HOUR)
.setExpectedCount(3);
test0(cfg);
cfg.setEndTimeStr(cfg.getStartTimeStr()).setExpectedCount(1);
test0(cfg);
}
}
|
package com.redeban.payment.example.utils;
/**
* Created by mmucito on 02/06/16.
*/
public class Constants {
//This is the identifier of the user you use inside your application.
public static String USER_ID = "uid12345";
//Email of the user initiating the purchase.
public static String USER_EMAIL = "dev@paymentez.com";
//Is Redeban SDK DEV environment?
public static boolean REDEBAN_IS_TEST_MODE = true;
//Ask the Redeban team for it
public static String REDEBAN_CLIENT_APP_CODE = "IOS-CO-CLIENT";
//Ask the Redeban team for it.
public static String REDEBAN_CLIENT_APP_KEY = "AKKqsezFDHtanNv1G0ARyxb8DiYARE";
//Backend Deployed from https://github.com/paymentez/example-java-backend
public static String BACKEND_URL = "https://example-paymentez-backend.herokuapp.com";
}
|
package io.nuls.block.constant;
import io.nuls.block.model.ChainParameters;
import io.nuls.core.core.annotation.Configuration;
import java.io.File;
/**
* 配置信息,所有时间配置默认单位为毫秒
*
* @author captain
* @version 1.0
* @date 18-11-20 上午11:01
*/
@Configuration(domain = "block")
public class BlockConfig extends ChainParameters {
/**
* db文件存放目录
*/
private String dataFolder;
/**
* 国际化
*/
private String language;
/**
* 分叉链监视线程执行间隔
*/
private int forkChainsMonitorInterval;
/**
* 孤儿链监视线程执行间隔
*/
private int orphanChainsMonitorInterval;
/**
* 孤儿链维护线程执行间隔
*/
private int orphanChainsMaintainerInterval;
/**
* 数据库监视线程执行间隔
*/
private int storageSizeMonitorInterval;
/**
* 网络监视线程执行间隔
*/
private int networkResetMonitorInterval;
/**
* 节点数量监控线程执行间隔
*/
private int nodesMonitorInterval;
/**
* TxGroup请求器线程执行间隔
*/
private int txGroupRequestorInterval;
/**
* TxGroup请求器任务执行延时
*/
private int txGroupTaskDelay;
private String dataPath;
/**
* 启动后自动回滚多少个区块
*/
private int testAutoRollbackAmount;
public int getNodesMonitorInterval() {
return nodesMonitorInterval;
}
public void setNodesMonitorInterval(int nodesMonitorInterval) {
this.nodesMonitorInterval = nodesMonitorInterval;
}
public void setDataFolder(String dataFolder) {
this.dataFolder = dataFolder;
}
public String getLanguage() {
return language;
}
public void setLanguage(String language) {
this.language = language;
}
public int getForkChainsMonitorInterval() {
return forkChainsMonitorInterval;
}
public void setForkChainsMonitorInterval(int forkChainsMonitorInterval) {
this.forkChainsMonitorInterval = forkChainsMonitorInterval;
}
public int getOrphanChainsMonitorInterval() {
return orphanChainsMonitorInterval;
}
public void setOrphanChainsMonitorInterval(int orphanChainsMonitorInterval) {
this.orphanChainsMonitorInterval = orphanChainsMonitorInterval;
}
public int getOrphanChainsMaintainerInterval() {
return orphanChainsMaintainerInterval;
}
public void setOrphanChainsMaintainerInterval(int orphanChainsMaintainerInterval) {
this.orphanChainsMaintainerInterval = orphanChainsMaintainerInterval;
}
public int getStorageSizeMonitorInterval() {
return storageSizeMonitorInterval;
}
public void setStorageSizeMonitorInterval(int storageSizeMonitorInterval) {
this.storageSizeMonitorInterval = storageSizeMonitorInterval;
}
public int getNetworkResetMonitorInterval() {
return networkResetMonitorInterval;
}
public void setNetworkResetMonitorInterval(int networkResetMonitorInterval) {
this.networkResetMonitorInterval = networkResetMonitorInterval;
}
public int getTxGroupRequestorInterval() {
return txGroupRequestorInterval;
}
public void setTxGroupRequestorInterval(int txGroupRequestorInterval) {
this.txGroupRequestorInterval = txGroupRequestorInterval;
}
public int getTxGroupTaskDelay() {
return txGroupTaskDelay;
}
public void setTxGroupTaskDelay(int txGroupTaskDelay) {
this.txGroupTaskDelay = txGroupTaskDelay;
}
public String getDataPath() {
return dataPath;
}
public void setDataPath(String dataPath) {
this.dataPath = dataPath;
}
public int getTestAutoRollbackAmount() {
return testAutoRollbackAmount;
}
public void setTestAutoRollbackAmount(int testAutoRollbackAmount) {
this.testAutoRollbackAmount = testAutoRollbackAmount;
}
public String getDataFolder() {
return dataPath + File.separator + dataFolder;
}
}
|
/*
* Copyright 2013 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.appengine.tck.datastore;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Map;
import com.google.appengine.api.datastore.Blob;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Text;
import org.jboss.arquillian.junit.Arquillian;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import static com.google.appengine.api.datastore.Query.FilterOperator.EQUAL;
import static com.google.appengine.api.datastore.Query.FilterOperator.GREATER_THAN;
import static com.google.appengine.api.datastore.Query.FilterOperator.GREATER_THAN_OR_EQUAL;
import static com.google.appengine.api.datastore.Query.FilterOperator.LESS_THAN;
import static com.google.appengine.api.datastore.Query.FilterOperator.LESS_THAN_OR_EQUAL;
import static com.google.appengine.api.datastore.Query.FilterPredicate;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
/**
* @author <a href="mailto:mluksa@redhat.com">Marko Luksa</a>
*/
@RunWith(Arquillian.class)
public class UnindexedPropertiesTest extends SimpleTestBase {
private static final Field PROPERTY_MAP_FIELD;
private static final String UNINDEXED_ENTITY = "unindexedTest";
static {
try {
PROPERTY_MAP_FIELD = Entity.class.getDeclaredField("propertyMap");
} catch (NoSuchFieldException e) {
throw new RuntimeException(e);
}
PROPERTY_MAP_FIELD.setAccessible(true);
}
@Test
public void testUnindexedProperties() throws Exception {
Entity entity = new Entity(UNINDEXED_ENTITY);
entity.setUnindexedProperty("unindexedString", "unindexedString");
entity.setUnindexedProperty("unindexedList", new ArrayList<String>(Arrays.asList("listElement1", "listElement2", "listElement3")));
entity.setUnindexedProperty("unindexedText", new Text("unindexedText"));
entity.setUnindexedProperty("unindexedBlob", new Blob("unindexedBlob".getBytes()));
entity.setProperty("text", new Text("text"));
entity.setProperty("blob", new Blob("blob".getBytes()));
Key key = service.put(entity);
sync(3000); // Not using ancestor queries, so pause before doing queries below.
Entity entity2 = service.get(key);
assertTrue(isUnindexed(getRawProperty(entity2, "unindexedString")));
assertTrue(isUnindexed(getRawProperty(entity2, "unindexedList")));
assertTrue(isUnindexed(getRawProperty(entity2, "unindexedText")));
assertTrue(isUnindexed(getRawProperty(entity2, "unindexedBlob")));
assertTrue(isUnindexed(getRawProperty(entity2, "text")));
assertTrue(isUnindexed(getRawProperty(entity2, "blob")));
assertNull(getResult(new Query(UNINDEXED_ENTITY).setFilter(new FilterPredicate("unindexedString", EQUAL, "unindexedString"))));
assertNull(getResult(new Query(UNINDEXED_ENTITY).setFilter(new FilterPredicate("unindexedList", EQUAL, "listElement1"))));
assertNull(getResult(new Query(UNINDEXED_ENTITY).setFilter(new FilterPredicate("unindexedText", EQUAL, "unindexedText"))));
assertNull(getResult(new Query(UNINDEXED_ENTITY).setFilter(new FilterPredicate("text", EQUAL, "text"))));
service.delete(key);
}
@Ignore("CAPEDWARF-66")
@Test
public void testFilterWithUnindexedPropertyType() throws Exception {
Entity entity = new Entity(UNINDEXED_ENTITY);
entity.setProperty("prop", "bbb");
service.put(entity);
sync(3000);
assertNull(getResult(new Query(UNINDEXED_ENTITY).setFilter(new FilterPredicate("prop", EQUAL, new Text("bbb")))));
assertNull(getResult(new Query(UNINDEXED_ENTITY).setFilter(new FilterPredicate("prop", LESS_THAN, new Text("ccc")))));
assertNull(getResult(new Query(UNINDEXED_ENTITY).setFilter(new FilterPredicate("prop", LESS_THAN_OR_EQUAL, new Text("ccc")))));
// it's strange that GREATER_THAN actually DOES return a result, whereas LESS_THAN doesn't
assertEquals(entity, getResult(new Query(UNINDEXED_ENTITY).setFilter(new FilterPredicate("prop", GREATER_THAN, new Text("aaa")))));
assertEquals(entity, getResult(new Query(UNINDEXED_ENTITY).setFilter(new FilterPredicate("prop", GREATER_THAN_OR_EQUAL, new Text("aaa")))));
service.delete(entity.getKey());
}
private Entity getResult(Query query) {
return service.prepare(query).asSingleEntity();
}
private boolean isUnindexed(Object rawProperty) {
return rawProperty.getClass().getName().endsWith("$UnindexedValue");
}
private Object getRawProperty(Entity entity, String propertyName) throws IllegalAccessException {
return getRawPropertyMap(entity).get(propertyName);
}
private Map getRawPropertyMap(Entity entity) throws IllegalAccessException {
return ((Map) PROPERTY_MAP_FIELD.get(entity));
}
}
|
package br.com.fiap.aoj.productcategories.configurations;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.config.AbstractMongoClientConfiguration;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
@Configuration
@EnableMongoRepositories(basePackages = "br.com.fiap.aoj.productcategories.data")
class MongoConfiguration extends AbstractMongoClientConfiguration {
private final String databaseName;
public MongoConfiguration(@Value("${spring.data.mongodb.database:product-categories}") final String databaseName) {
this.databaseName = databaseName;
}
@Override
protected String getDatabaseName() {
return databaseName;
}
}
|
package com.iyihua.demo.docker.web;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HomeController {
@GetMapping("/")
public Object home() {
return "hello.";
}
}
|
/*
* Copyright (c) 2016 Cisco and/or 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 org.openvpp.jvpp;
/**
* Base exception representing failed operation of JVpp request call
*/
public abstract class VppBaseCallException extends Exception {
private final String methodName;
private final int errorCode;
/**
* Constructs an VppCallbackException with the specified api method name and error code.
*
* @param methodName name of a method, which invocation or execution failed
* @param errorCode negative error code value associated with this failure
* @throws NullPointerException if apiMethodName is null
*/
public VppBaseCallException(final String methodName, final int errorCode) {
super(String.format("vppApi.%s failed with error code: %d", methodName, errorCode));
this.methodName = java.util.Objects.requireNonNull(methodName, "apiMethodName is null!");
this.errorCode = errorCode;
if(errorCode >= 0) {
throw new IllegalArgumentException("Error code must be < 0. Was " + errorCode +
" for " + methodName );
}
}
/**
* Returns name of a method, which invocation failed.
*
* @return method name
*/
public String getMethodName() {
return methodName;
}
/**
* Returns the error code associated with this failure.
*
* @return a negative integer error code
*/
public int getErrorCode() {
return errorCode;
}
}
|
/**
* NetworkErrorReason.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.adwords.axis.v201406.video;
public class NetworkErrorReason implements java.io.Serializable {
private java.lang.String _value_;
private static java.util.HashMap _table_ = new java.util.HashMap();
// Constructor
protected NetworkErrorReason(java.lang.String value) {
_value_ = value;
_table_.put(_value_,this);
}
public static final java.lang.String _EMPTY = "EMPTY";
public static final java.lang.String _INVALID = "INVALID";
public static final java.lang.String _NOT_ALLOWED = "NOT_ALLOWED";
public static final java.lang.String _UNKNOWN = "UNKNOWN";
public static final NetworkErrorReason EMPTY = new NetworkErrorReason(_EMPTY);
public static final NetworkErrorReason INVALID = new NetworkErrorReason(_INVALID);
public static final NetworkErrorReason NOT_ALLOWED = new NetworkErrorReason(_NOT_ALLOWED);
public static final NetworkErrorReason UNKNOWN = new NetworkErrorReason(_UNKNOWN);
public java.lang.String getValue() { return _value_;}
public static NetworkErrorReason fromValue(java.lang.String value)
throws java.lang.IllegalArgumentException {
NetworkErrorReason enumeration = (NetworkErrorReason)
_table_.get(value);
if (enumeration==null) throw new java.lang.IllegalArgumentException();
return enumeration;
}
public static NetworkErrorReason fromString(java.lang.String value)
throws java.lang.IllegalArgumentException {
return fromValue(value);
}
public boolean equals(java.lang.Object obj) {return (obj == this);}
public int hashCode() { return toString().hashCode();}
public java.lang.String toString() { return _value_;}
public java.lang.Object readResolve() throws java.io.ObjectStreamException { return fromValue(_value_);}
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.EnumSerializer(
_javaType, _xmlType);
}
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.EnumDeserializer(
_javaType, _xmlType);
}
// Type metadata
private static org.apache.axis.description.TypeDesc typeDesc =
new org.apache.axis.description.TypeDesc(NetworkErrorReason.class);
static {
typeDesc.setXmlType(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/video/v201406", "NetworkError.Reason"));
}
/**
* Return type metadata object
*/
public static org.apache.axis.description.TypeDesc getTypeDesc() {
return typeDesc;
}
}
|
package com.marklogic.appdeployer.command;
import com.marklogic.appdeployer.AppConfig;
/**
* Used by commands to replace tokens in configuration files that are dependent on names of resources in the application.
* Typically, the tokens are replaced by values in the AppConfig instance. This allows for configuration files to be
* reused across applications with different names.
*/
public interface TokenReplacer {
public String replaceTokens(String payload, AppConfig appConfig, boolean isTestResource);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.