text
stringlengths 7
1.01M
|
|---|
// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3) annotate safe
package com.ibotta.android.mvp.ui.activity.account.withdraw.cashout;
import com.ibotta.android.mvp.base.loading.LoadingMvpView;
import com.ibotta.android.mvp.ui.activity.account.withdraw.WithdrawalDetails;
import com.ibotta.android.views.base.title.TitleBarViewState;
public interface CashOutView
extends LoadingMvpView
{
public abstract void finishSuccessfully(WithdrawalDetails withdrawaldetails);
public abstract void setAccountName(String s);
public abstract void setAmountAvailable(String s);
public abstract void setAmountRemaining(String s);
public abstract void setMinimumCashOutAmountHint(float f);
public abstract void setTransferCashEnabled(boolean flag);
public abstract void setTransferToTitle(TitleBarViewState titlebarviewstate);
public abstract void showCapturePassword(String s);
public abstract void showInvalidAmount();
}
|
/*
* smart-doc https://github.com/shalousun/smart-doc
*
* Copyright (C) 2018-2021 smart-doc
*
* 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.power.doc.builder;
import com.power.common.util.DateTimeUtil;
import com.power.doc.factory.BuildTemplateFactory;
import com.power.doc.model.ApiConfig;
import com.power.doc.model.ApiDoc;
import com.power.doc.template.IDocBuildTemplate;
import com.power.doc.template.SpringBootDocBuildTemplate;
import com.thoughtworks.qdox.JavaProjectBuilder;
import java.util.List;
import java.util.stream.Collectors;
import static com.power.doc.constants.DocGlobalConstants.*;
/**
* Use to create Asciidoc
*
* @author yu 2019/9/26.
*/
public class AdocDocBuilder {
private static final String API_EXTENSION = "Api.adoc";
private static final String INDEX_DOC = "index.adoc";
/**
* build adoc
*
* @param config ApiConfig
*/
public static void buildApiDoc(ApiConfig config) {
JavaProjectBuilder javaProjectBuilder = new JavaProjectBuilder();
buildApiDoc(config, javaProjectBuilder);
}
/**
* Only for smart-doc maven plugin and gradle plugin.
*
* @param config ApiConfig
* @param javaProjectBuilder ProjectDocConfigBuilder
*/
public static void buildApiDoc(ApiConfig config, JavaProjectBuilder javaProjectBuilder) {
DocBuilderTemplate builderTemplate = new DocBuilderTemplate();
builderTemplate.checkAndInit(config);
config.setParamsDataToTree(false);
config.setAdoc(true);
ProjectDocConfigBuilder configBuilder = new ProjectDocConfigBuilder(config, javaProjectBuilder);
IDocBuildTemplate docBuildTemplate = BuildTemplateFactory.getDocBuildTemplate(config.getFramework());
List<ApiDoc> apiDocList = docBuildTemplate.getApiData(configBuilder);
if (config.isAllInOne()) {
String docName = builderTemplate.allInOneDocName(config,INDEX_DOC,".doc");
apiDocList = docBuildTemplate.handleApiGroup(apiDocList, config);
builderTemplate.buildAllInOne(apiDocList, config, javaProjectBuilder, ALL_IN_ONE_ADOC_TPL, docName);
} else {
builderTemplate.buildApiDoc(apiDocList, config, API_DOC_ADOC_TPL, API_EXTENSION);
builderTemplate.buildErrorCodeDoc(config, ERROR_CODE_LIST_ADOC_TPL, ERROR_CODE_LIST_ADOC);
builderTemplate.buildDirectoryDataDoc(config, javaProjectBuilder, DICT_LIST_ADOC_TPL, DICT_LIST_ADOC);
}
}
/**
* Generate a single controller api document
*
* @param config ApiConfig
* @param controllerName controller name
*/
public static void buildSingleApiDoc(ApiConfig config, String controllerName) {
config.setAdoc(false);
ProjectDocConfigBuilder configBuilder = new ProjectDocConfigBuilder(config, new JavaProjectBuilder());
DocBuilderTemplate builderTemplate = new DocBuilderTemplate();
builderTemplate.checkAndInit(config);
builderTemplate.buildSingleApi(configBuilder, controllerName, API_DOC_ADOC_TPL, API_EXTENSION);
}
}
|
package rml.model.po;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
/**
* Trole entity. @author MyEclipse Persistence Tools
*/
@Entity
@Table(name = "QROLE", schema = "")
public class Trole implements java.io.Serializable {
// Fields
private String cid;
private String cdesc;
private String cname;
private Set<Troletauth> troletauths = new HashSet<Troletauth>(0);
private Set<Tusertrole> tusertroles = new HashSet<Tusertrole>(0);
// Constructors
/** default constructor */
public Trole() {
}
/** minimal constructor */
public Trole(String cid, String cname) {
this.cid = cid;
this.cname = cname;
}
/** full constructor */
public Trole(String cid, String cdesc, String cname, Set<Troletauth> troletauths, Set<Tusertrole> tusertroles) {
this.cid = cid;
this.cdesc = cdesc;
this.cname = cname;
this.troletauths = troletauths;
this.tusertroles = tusertroles;
}
// Property accessors
@Id
@Column(name = "CID", nullable = false, length = 36)
public String getCid() {
return this.cid;
}
public void setCid(String cid) {
this.cid = cid;
}
@Column(name = "CDESC", length = 200)
public String getCdesc() {
return this.cdesc;
}
public void setCdesc(String cdesc) {
this.cdesc = cdesc;
}
@Column(name = "CNAME", nullable = false, length = 100)
public String getCname() {
return this.cname;
}
public void setCname(String cname) {
this.cname = cname;
}
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "trole")
public Set<Troletauth> getTroletauths() {
return this.troletauths;
}
public void setTroletauths(Set<Troletauth> troletauths) {
this.troletauths = troletauths;
}
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "trole")
public Set<Tusertrole> getTusertroles() {
return this.tusertroles;
}
public void setTusertroles(Set<Tusertrole> tusertroles) {
this.tusertroles = tusertroles;
}
}
|
/**
* 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.ambari.view.capacityscheduler;
import org.apache.ambari.view.ViewContext;
import org.apache.ambari.view.capacityscheduler.utils.MisconfigurationFormattedException;
import org.apache.ambari.view.capacityscheduler.proxy.Proxy;
import org.apache.ambari.view.capacityscheduler.utils.ServiceFormattedException;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.HashMap;
import java.net.URL;
import java.net.MalformedURLException;
/**
* Help service
*/
public class ConfigurationService {
private static final Logger LOG = LoggerFactory.getLogger(ConfigurationService.class);
private final Proxy proxy;
private final String baseUrl;
private final String serverUrl;
private ViewContext context;
private final String refreshRMRequestData =
"{\n" +
" \"RequestInfo\" : {\n" +
" \"command\" : \"REFRESHQUEUES\",\n" +
" \"context\" : \"Refresh YARN Capacity Scheduler\"\n" +
" \"parameters/forceRefreshConfigTags\" : \"capacity-scheduler\"\n" +
" },\n" +
" \"Requests/resource_filters\": [{\n" +
" \"service_name\" : \"YARN\",\n" +
" \"component_name\" : \"RESOURCEMANAGER\",\n" +
" \"hosts\" : \"%s\"\n" +
" }]\n" +
"}";
private final String restartRMRequestData = "{\"RequestInfo\": {\n" +
" \"command\":\"RESTART\",\n" +
" \"context\":\"Restart ResourceManager\",\n" +
" \"operation_level\": {\n" +
" \"level\":\"HOST_COMPONENT\",\n" +
" \"cluster_name\":\"MyCluster\",\n" +
" \"host_name\":\"%s\",\n" +
" \"service_name\":\"YARN\",\n" +
" \"hostcomponent_name\":\"RESOURCEMANAGER\"\n" +
" }\n" +
" },\n" +
" \"Requests/resource_filters\": [\n" +
" {\n" +
" \"service_name\":\"YARN\",\n" +
" \"component_name\":\"RESOURCEMANAGER\",\n" +
" \"hosts\":\"%s\"\n" +
" }\n" +
" ]\n" +
"}\n";
/**
* Constructor.
* @param context the ViewContext instance (may not be <code>null</code>)
*/
public ConfigurationService(ViewContext context) {
this.context = context;
proxy = new Proxy(context.getURLStreamProvider());
proxy.setUseAuthorization(true);
proxy.setUsername(context.getProperties().get("ambari.server.username"));
proxy.setPassword(context.getProperties().get("ambari.server.password"));
HashMap<String, String> customHeaders = new HashMap<String, String>();
customHeaders.put("X-Requested-By", "view-capacity-scheduler");
proxy.setCustomHeaders(customHeaders);
baseUrl = context.getProperties().get("ambari.server.url");
URL url = null;
try {
url = new URL(baseUrl);
} catch (MalformedURLException ex) {
throw new ServiceFormattedException("Error in ambari.server.url property: " + ex.getMessage(), ex);
}
String clusterName = url.getFile(); // TODO: make it more robust
serverUrl = baseUrl.substring(0, baseUrl.length() - clusterName.length());
}
// ================================================================================
// Configuration Reading
// ================================================================================
private final String versionTagUrl = "%s?fields=Clusters/desired_configs/capacity-scheduler";
private final String configurationUrl = "%s/configurations?type=capacity-scheduler";
private final String configurationUrlByTag = "%%s/configurations?type=capacity-scheduler&tag=%s";
private final String rmHostUrl = "%s/services/YARN/components/RESOURCEMANAGER?fields=host_components/host_name";
private final String rmGetNodeLabelUrl = "http://%s:8088/ws/v1/cluster/get-node-labels";
// ================================================================================
// Privilege Reading
// ================================================================================
private final String clusterOperatorPrivilegeUrl = "%s?privileges/PrivilegeInfo/permission_name=CLUSTER.OPERATE&privileges/PrivilegeInfo/principal_name=%s";
private final String ambariAdminPrivilegeUrl = "%s/api/v1/users/%s?Users/admin=true";
/**
* Gets capacity scheduler configuration.
*
* @return scheduler configuration
*/
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response readLatestConfiguration() {
Response response = null;
try {
validateViewConfiguration();
String versionTag = getVersionTag();
JSONObject configurations = getConfigurationFromAmbari(versionTag);
response = Response.ok(configurations).build();
} catch (WebApplicationException ex) {
throw ex;
} catch (Exception ex) {
throw new ServiceFormattedException(ex.getMessage(), ex);
}
return response;
}
/**
* Gets capacity scheduler configuration by all tags.
*
* @return scheduler configuration
*/
@GET
@Path("all")
@Produces(MediaType.APPLICATION_JSON)
public Response readAllConfigurations() {
Response response = null;
try {
validateViewConfiguration();
String url = String.format(configurationUrl, baseUrl);
JSONObject configurations = proxy.request(url).get().asJSON();
response = Response.ok(configurations).build();
} catch (WebApplicationException ex) {
throw ex;
} catch (Exception ex) {
throw new ServiceFormattedException(ex.getMessage(), ex);
}
return response;
}
/**
* Gets capacity scheduler configuration by specific tag.
*
* @return scheduler configuration
*/
@GET
@Path("byTag/{tag}")
@Produces(MediaType.APPLICATION_JSON)
public Response readConfigurationByTag(@PathParam("tag") String tag) {
Response response = null;
try {
validateViewConfiguration();
JSONObject configurations = getConfigurationFromAmbari(tag);
response = Response.ok(configurations).build();
} catch (WebApplicationException ex) {
throw ex;
} catch (Exception ex) {
throw new ServiceFormattedException(ex.getMessage(), ex);
}
return response;
}
/**
* Gets the privilege for this user.
*
* @return scheduler configuration
*/
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("/privilege")
public Response getPrivilege() {
Response response = null;
try {
boolean operator = isOperator();
response = Response.ok(operator).build();
} catch (WebApplicationException ex) {
throw ex;
} catch (Exception ex) {
throw new ServiceFormattedException(ex.getMessage(), ex);
}
return response;
}
/**
* Gets node labels from RM
*
* @return node labels
*/
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("/nodeLabels")
public Response getNodeLabels() {
Response response;
try {
String nodeLabels = proxy.request(String.format(rmGetNodeLabelUrl, getRMHost())).get().asString();
response = Response.ok(nodeLabels).build();
} catch (WebApplicationException ex) {
throw ex;
} catch (Exception ex) {
throw new ServiceFormattedException(ex.getMessage(), ex);
}
return response;
}
/**
* Checks if the user is an operator.
*
* @return if <code>true</code>, the user is an operator; otherwise <code>false</code>
*/
private boolean isOperator() {
validateViewConfiguration();
// first check if the user is an CLUSTER.OPERATOR
String url = String.format(clusterOperatorPrivilegeUrl, baseUrl, context.getUsername());
JSONObject json = proxy.request(url).get().asJSON();
if (json == null || json.size() <= 0) {
// user is not a CLUSTER.OPERATOR but might be an AMBARI.ADMIN
url = String.format(ambariAdminPrivilegeUrl, serverUrl, context.getUsername());
json = proxy.request(url).get().asJSON();
if (json == null || json.size() <= 0)
return false;
}
return true;
}
/**
* Validates the view configuration properties.
*
* @throws MisconfigurationFormattedException if one of the required view configuration properties are not set
*/
private void validateViewConfiguration() {
String hostname = context.getProperties().get("ambari.server.url");
if (hostname == null)
throw new MisconfigurationFormattedException("ambari.server.url");
String username = context.getProperties().get("ambari.server.username");
if (username == null)
throw new MisconfigurationFormattedException("ambari.server.username");
String password = context.getProperties().get("ambari.server.password");
if (password == null)
throw new MisconfigurationFormattedException("ambari.server.password");
}
private JSONObject getConfigurationFromAmbari(String versionTag) {
String urlTemplate = String.format(configurationUrlByTag, versionTag);
String url = String.format(urlTemplate, baseUrl);
return proxy.request(url).get().asJSON();
}
/**
* Gets the capacity scheduler version tag.
*
* @return the capacity scheduler version tag
*/
private String getVersionTag() {
JSONObject json = getDesiredConfigs();
JSONObject clusters = (JSONObject) json.get("Clusters");
JSONObject configs = (JSONObject) clusters.get("desired_configs");
JSONObject scheduler = (JSONObject) configs.get("capacity-scheduler");
return (String) scheduler.get("tag");
}
/**
* Gets the cluster name.
*
* @return the cluster name
*/
private String getClusterName() {
JSONObject json = getDesiredConfigs();
JSONObject clusters = (JSONObject) json.get("Clusters");
return (String) clusters.get("cluster_name");
}
/**
* Gets the desired config.
*
* @return the desired config JSON object
*/
private JSONObject getDesiredConfigs() {
String url = String.format(versionTagUrl, baseUrl);
return proxy.request(url).get().asJSON();
}
// ================================================================================
// Configuration Writing
// ================================================================================
/**
* Sets capacity scheduler configuration.
*
* @return the http response
*/
@PUT
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response writeConfiguration(JSONObject request) {
JSONObject response;
try {
validateViewConfiguration();
if (isOperator() == false) {
return Response.status(401).build();
}
response = proxy.request(baseUrl).
setData(request).
put().asJSON();
} catch (WebApplicationException ex) {
throw ex;
} catch (Exception ex) {
throw new ServiceFormattedException(ex.getMessage(), ex);
}
return Response.ok(response).build();
}
/**
* Sets capacity scheduler configuration and refresh ResourceManager.
*
* @return http response
*/
@PUT
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Path("/saveAndRefresh")
public Response writeAndRefreshConfiguration(JSONObject request) {
try {
if (isOperator() == false) {
return Response.status(401).build();
}
String rmHost = getRMHost();
JSONObject data = (JSONObject) JSONValue.parse(String.format(refreshRMRequestData, rmHost));
proxy.request(baseUrl + "/requests/").
setData(data).
post();
} catch (WebApplicationException ex) {
throw ex;
} catch (Exception ex) {
throw new ServiceFormattedException(ex.getMessage(), ex);
}
return readLatestConfiguration();
}
/**
* Sets capacity scheduler configuration and restart ResourceManager.
*
* @return http response
*/
@PUT
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Path("/saveAndRestart")
public Response writeAndRestartConfiguration(JSONObject request) {
try {
if (isOperator() == false) {
return Response.status(401).build();
}
String rmHost = getRMHost();
JSONObject data = (JSONObject) JSONValue.parse(String.format(restartRMRequestData, rmHost, rmHost));
proxy.request(baseUrl + "/requests/").
setData(data).
post();
} catch (WebApplicationException ex) {
throw ex;
} catch (Exception ex) {
throw new ServiceFormattedException(ex.getMessage(), ex);
}
return readLatestConfiguration();
}
private String getRMHost() {
String rmHost = null;
JSONObject rmData = proxy.request(String.format(rmHostUrl, baseUrl)).get().asJSON();
JSONArray components = (JSONArray) rmData.get("host_components");
for(Object component : components) {
JSONObject roles = (JSONObject) ((JSONObject) component).get("HostRoles");
if (roles.get("component_name").equals("RESOURCEMANAGER")) {
rmHost = (String) roles.get("host_name");
break;
}
}
if (rmHost == null)
throw new ServiceFormattedException("Can't retrieve Resource Manager Host");
return rmHost;
}
}
|
// Copyright 2019 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.devtools.build.lib.starlarkbuildapi.cpp;
import com.google.devtools.build.lib.starlarkbuildapi.FileApi;
import com.google.devtools.build.lib.starlarkbuildapi.core.ProviderApi;
import com.google.devtools.build.lib.starlarkbuildapi.core.StructApi;
import com.google.devtools.build.lib.syntax.EvalException;
import net.starlark.java.annot.Param;
import net.starlark.java.annot.StarlarkBuiltin;
import net.starlark.java.annot.StarlarkConstructor;
import net.starlark.java.annot.StarlarkDocumentationCategory;
import net.starlark.java.annot.StarlarkMethod;
/** A target that provides C++ libraries to be linked into Go targets. */
@StarlarkBuiltin(
name = "GoCcLinkParamsInfo",
doc = "",
documented = false,
category = StarlarkDocumentationCategory.PROVIDER)
public interface GoCcLinkParamsInfoApi extends StructApi {
/** Provider for GoContextInfo objects. */
@StarlarkBuiltin(name = "Provider", doc = "", documented = false)
public interface Provider<
FileT extends FileApi, CcLinkingContextT extends CcLinkingContextApi<FileT>>
extends ProviderApi {
@StarlarkMethod(
name = "GoCcLinkParamsInfo",
doc = "The <code>GoCcLinkParamsInfo</code> constructor.",
parameters = {
@Param(
name = "linking_context",
doc = "The CC linking context.",
positional = false,
named = true,
type = CcLinkingContextApi.class),
},
selfCall = true)
@StarlarkConstructor(
objectType = GoCcLinkParamsInfoApi.class,
receiverNameForDoc = "GoCcLinkParamsInfo")
public GoCcLinkParamsInfoApi createInfo(CcLinkingContextT ccLinkingContext)
throws EvalException;
}
}
|
/**
* Generated by OpenJPA MetaModel Generator Tool.
**/
package com.x.bbs.entity;
import com.x.base.core.entity.SliceJpaObject_;
import java.lang.String;
import java.util.Date;
import javax.persistence.metamodel.SingularAttribute;
@javax.persistence.metamodel.StaticMetamodel
(value=com.x.bbs.entity.BBSSubjectPictureBase64.class)
@javax.annotation.Generated
(value="org.apache.openjpa.persistence.meta.AnnotationProcessor6",date="Fri Mar 10 10:08:02 CST 2017")
public class BBSSubjectPictureBase64_ extends SliceJpaObject_ {
public static volatile SingularAttribute<BBSSubjectPictureBase64,Date> createTime;
public static volatile SingularAttribute<BBSSubjectPictureBase64,String> id;
public static volatile SingularAttribute<BBSSubjectPictureBase64,String> pictureBase64;
public static volatile SingularAttribute<BBSSubjectPictureBase64,String> sequence;
public static volatile SingularAttribute<BBSSubjectPictureBase64,Date> updateTime;
}
|
package com.ebbin.learning.exception;
import com.ebbin.learning.exception.types.LearningExceptions;
public class LearningException extends Exception {
private static final long serialVersionUID = 1L;
public LearningException(LearningExceptions type) {
super(type.getMessage());
}
public LearningException(LearningExceptions type, Throwable t) {
super(type.getMessage(), t);
}
}
|
/*******************************************************************************
* COPYRIGHT(c) 2015 STMicroelectronics
*
* 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. Neither the name of STMicroelectronics nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS 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 com.st.BlueSTSDK.Log;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.util.Log;
import com.st.BlueSTSDK.Feature;
import com.st.BlueSTSDK.Features.Field;
import com.st.BlueSTSDK.Node;
import java.io.File;
import java.io.FileFilter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Formatter;
import java.util.List;
import java.util.Locale;
/**
* Common code between the csv and db log class
*
* @author STMicroelectronics - Central Labs.
* @version 1.0
*/
public abstract class FeatureLogBase implements Feature.FeatureLoggerListener{
private final static String TAG = FeatureLogBase.class.getCanonicalName();
final static SimpleDateFormat DATE_FORMAT_PREFIX = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault());
final static SimpleDateFormat DATE_FORMAT_TO_HEADER = new SimpleDateFormat("yyyy-MM-dd " +
"HH:mm:ss",Locale.getDefault());
protected static final String HOST_TIMESTAMP_COLUMN ="HostTimestamp";
protected static final String NODE_NAME_COLUMN ="NodeName";
protected static final String NODE_TIMESTAMP_COLUMN ="NodeTimestamp";
protected static final String NODE_RAW_DATA_COLUMN ="RawData";
/**
* directory where save the dump file
* */
protected String mDirectoryPath;
/**
* Start log date time
*/
protected Date mStartLog;
/**
* Node list connected, current logged
* */
protected List<Node> mNodeList;
/**
* print the file header, with the node name the raw data and the feature field
* @param out stream where write the feature data
* @param f feature that this close will dump
*/
protected void printHeader(Formatter out, Feature f) {
Field fields[] = f.getFieldsDesc();
out.format("Log start on," + DATE_FORMAT_TO_HEADER.format(mStartLog) + "\n");
out.format("Feature," + f.getName() + "\n");
out.format("Nodes,");
if (mNodeList != null)
for(Node n: mNodeList)
out.format(n.getFriendlyName() + ", ");
out.format("\n");
out.format(HOST_TIMESTAMP_COLUMN + " (ms)," + NODE_NAME_COLUMN + "," + NODE_TIMESTAMP_COLUMN + "," +
"" + NODE_RAW_DATA_COLUMN + ",");
for(Field field:fields){
out.format(field.getName());
String unit =field.getUnit();
if (unit!=null && !unit.isEmpty() )
out.format(" (%s)", field.getUnit());
out.format(",");
}//for
out.format("\n");
out.flush();
}//printHeader
/**
* dump an array of byte as a string of hexadecimal value
* <p> No coma will be added at the end of the string</p>
* @param out stream where write the feature data
* @param data byte data to dump
*/
protected void storeBlobData(Formatter out,byte data[]) {
for(byte b: data) {
out.format("%02X", b);
}//for
}//storeBlobData
/**
* dump the feature data
* @param out stream where write the feature data
* @param data feature data
*/
protected void storeFeatureData(Formatter out, Number data[]) {
for(Number n: data){
out.format("%s,",n.toString());
}//for
}
/**
* create a logger
* @param dumpDirectoryPath path where store the log data
* @param nodes list of node to log
*/
public FeatureLogBase(String dumpDirectoryPath, List<Node> nodes){
mDirectoryPath = dumpDirectoryPath;
mStartLog = new Date();
mNodeList = nodes;
File f = new File(mDirectoryPath);
if(!f.exists())
f.mkdirs();
}//FeatureLogCSVFile
/**
* create a string with the path where store the log. the name will have a timestamp for be
* unique
* @param f feature to log
* @return file path where store the log for that feature
*/
protected String logFeatureFileName(Feature f) {
return String.format("%s/%s_%s.csv",
mDirectoryPath, logSessionPrefix(), f.getName());
}
/**
* Get the file prefix of current session
* @return the file prefix of current session
*/
public String logSessionPrefix(){
String logPrefixName = "";
synchronized (mStartLog)
{
logPrefixName = DATE_FORMAT_PREFIX.format(mStartLog);
}
return logPrefixName;
}
/**
* get all the log file in the directory
* @param directoryPath path where search the file
* @return all file in the directory with an extension .csv
*/
static public File[] getLogFiles(String directoryPath){
File directory = new File(directoryPath);
//find all the csv files
final FileFilter csvFilter = new FileFilter() {
@Override
public boolean accept(File pathname) {
return pathname.getName().endsWith(".csv");
}//accept
};
return directory.listFiles(csvFilter);
}//getLogFiles
/**
* remove all the csv file in the directory
* @param c context where the file were created
* @param directoryPath directory where this class dumped the feature data
*/
static public void clean(Context c, String directoryPath){
File files[] =getLogFiles(directoryPath);
if(files==null || files.length==0) //nothing to do
return;
for(File f: getLogFiles(directoryPath) ){
if(!f.delete())
Log.e(TAG, "Error deleting the file " + f.getAbsolutePath());
c.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(f)));
}//for
}//clean
}
|
/*
* 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.simpleemailv2.model.transform;
import java.math.*;
import javax.annotation.Generated;
import com.amazonaws.services.simpleemailv2.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;
import static com.fasterxml.jackson.core.JsonToken.*;
/**
* UntagResourceResult JSON Unmarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class UntagResourceResultJsonUnmarshaller implements Unmarshaller<UntagResourceResult, JsonUnmarshallerContext> {
public UntagResourceResult unmarshall(JsonUnmarshallerContext context) throws Exception {
UntagResourceResult untagResourceResult = new UntagResourceResult();
return untagResourceResult;
}
private static UntagResourceResultJsonUnmarshaller instance;
public static UntagResourceResultJsonUnmarshaller getInstance() {
if (instance == null)
instance = new UntagResourceResultJsonUnmarshaller();
return instance;
}
}
|
package kxj;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class GlobalExceptionApplication {
public static void main(String[] args) {
SpringApplication.run(GlobalExceptionApplication.class, args);
}
}
|
/*
* Copyright 2022 ThoughtWorks, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.thoughtworks.go.server.service;
import com.thoughtworks.go.config.*;
import com.thoughtworks.go.config.exceptions.RecordNotFoundException;
import com.thoughtworks.go.config.materials.PackageMaterial;
import com.thoughtworks.go.config.materials.PluggableSCMMaterial;
import com.thoughtworks.go.domain.*;
import com.thoughtworks.go.domain.builder.Builder;
import com.thoughtworks.go.domain.exception.IllegalArtifactLocationException;
import com.thoughtworks.go.domain.materials.Material;
import com.thoughtworks.go.listener.ConfigChangedListener;
import com.thoughtworks.go.listener.EntityConfigChangedListener;
import com.thoughtworks.go.plugin.access.exceptions.SecretResolutionFailureException;
import com.thoughtworks.go.remote.AgentIdentifier;
import com.thoughtworks.go.remote.work.*;
import com.thoughtworks.go.server.exceptions.RulesViolationException;
import com.thoughtworks.go.server.materials.StaleMaterialsOnBuildCause;
import com.thoughtworks.go.server.messaging.JobStatusMessage;
import com.thoughtworks.go.server.messaging.JobStatusTopic;
import com.thoughtworks.go.server.service.builders.BuilderFactory;
import com.thoughtworks.go.server.transaction.TransactionTemplate;
import com.thoughtworks.go.util.SystemEnvironment;
import com.thoughtworks.go.util.command.EnvironmentVariableContext;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.IterableUtils;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import static com.thoughtworks.go.util.command.EnvironmentVariableContext.GO_ENVIRONMENT_NAME;
import static java.lang.String.format;
import static java.util.stream.Collectors.toList;
import static java.util.stream.StreamSupport.stream;
import static org.apache.commons.collections4.CollectionUtils.forAllDo;
/**
* @understands how to assign work to agents
*/
@Service
public class BuildAssignmentService implements ConfigChangedListener {
private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(BuildAssignmentService.class.getName());
public static final NoWork NO_WORK = new NoWork();
public static final String GO_PIPELINE_GROUP_NAME = "GO_PIPELINE_GROUP_NAME";
public static final String GO_AGENT_RESOURCES = "GO_AGENT_RESOURCES";
private GoConfigService goConfigService;
private JobInstanceService jobInstanceService;
private ScheduleService scheduleService;
private AgentService agentService;
private EnvironmentConfigService environmentConfigService;
private TransactionTemplate transactionTemplate;
private final ScheduledPipelineLoader scheduledPipelineLoader;
private List<JobPlan> jobPlans = new ArrayList<>();
private final UpstreamPipelineResolver resolver;
private final BuilderFactory builderFactory;
private MaintenanceModeService maintenanceModeService;
private final ElasticAgentPluginService elasticAgentPluginService;
private final SystemEnvironment systemEnvironment;
private SecretParamResolver secretParamResolver;
private JobStatusTopic jobStatusTopic;
private ConsoleService consoleService;
@Autowired
public BuildAssignmentService(GoConfigService goConfigService, JobInstanceService jobInstanceService,
ScheduleService scheduleService, AgentService agentService,
EnvironmentConfigService environmentConfigService, TransactionTemplate transactionTemplate,
ScheduledPipelineLoader scheduledPipelineLoader, PipelineService pipelineService,
BuilderFactory builderFactory,
MaintenanceModeService maintenanceModeService, ElasticAgentPluginService elasticAgentPluginService,
SystemEnvironment systemEnvironment, SecretParamResolver secretParamResolver, JobStatusTopic jobStatusTopic,
ConsoleService consoleService) {
this.goConfigService = goConfigService;
this.jobInstanceService = jobInstanceService;
this.scheduleService = scheduleService;
this.agentService = agentService;
this.environmentConfigService = environmentConfigService;
this.transactionTemplate = transactionTemplate;
this.scheduledPipelineLoader = scheduledPipelineLoader;
this.resolver = pipelineService;
this.builderFactory = builderFactory;
this.maintenanceModeService = maintenanceModeService;
this.elasticAgentPluginService = elasticAgentPluginService;
this.systemEnvironment = systemEnvironment;
this.secretParamResolver = secretParamResolver;
this.jobStatusTopic = jobStatusTopic;
this.consoleService = consoleService;
}
public void initialize() {
goConfigService.register(this);
goConfigService.register(pipelineConfigChangedListener());
}
protected EntityConfigChangedListener<PipelineConfig> pipelineConfigChangedListener() {
return new EntityConfigChangedListener<PipelineConfig>() {
@Override
public void onEntityConfigChange(PipelineConfig pipelineConfig) {
LOGGER.info("[Configuration Changed] Removing deleted jobs for pipeline {}.", pipelineConfig.name());
synchronized (BuildAssignmentService.this) {
List<JobPlan> jobsToRemove;
if (goConfigService.hasPipelineNamed(pipelineConfig.name())) {
jobsToRemove = getMismatchingJobPlansFromUpdatedPipeline(pipelineConfig, jobPlans);
} else {
jobsToRemove = getAllJobPlansFromDeletedPipeline(pipelineConfig, jobPlans);
}
IterableUtils.forEach(jobsToRemove, o -> removeJob(o));
}
}
};
}
private List<JobPlan> getMismatchingJobPlansFromUpdatedPipeline(PipelineConfig pipelineConfig, List<JobPlan> allJobPlans) {
List<JobPlan> jobsToRemove = new ArrayList<>();
for (JobPlan jobPlan : allJobPlans) {
if (pipelineConfig.name().equals(new CaseInsensitiveString(jobPlan.getPipelineName()))) {
StageConfig stageConfig = pipelineConfig.findBy(new CaseInsensitiveString(jobPlan.getStageName()));
if (stageConfig != null) {
JobConfig jobConfig = stageConfig.jobConfigByConfigName(new CaseInsensitiveString(jobPlan.getName()));
if (jobConfig == null) {
jobsToRemove.add(jobPlan);
}
} else {
jobsToRemove.add(jobPlan);
}
}
}
return jobsToRemove;
}
private List<JobPlan> getAllJobPlansFromDeletedPipeline(PipelineConfig pipelineConfig, List<JobPlan> allJobPlans) {
return allJobPlans.stream()
.filter(jobPlan -> new CaseInsensitiveString(jobPlan.getPipelineName()).equals(pipelineConfig.name()))
.collect(toList());
}
public Work assignWorkToAgent(AgentIdentifier agent) {
return assignWorkToAgent(agentService.findAgentAndRefreshStatus(agent.getUuid()));
}
Work assignWorkToAgent(final AgentInstance agent) {
if (!agent.isRegistered()) {
return new UnregisteredAgentWork(agent.getUuid());
}
if (agent.isDisabled()) {
return new DeniedAgentWork(agent.getUuid());
}
synchronized (this) {
// check to ensure agent is not disabled after entering the synchronized block
if (agent.isDisabled()) {
return new DeniedAgentWork(agent.getUuid());
}
//check if agent already has assigned build, if so, reschedule it
scheduleService.rescheduleAbandonedBuildIfNecessary(agent.getAgentIdentifier());
final JobPlan job = findMatchingJob(agent);
if (job != null) {
Work buildWork = createWork(agent, job);
AgentBuildingInfo buildingInfo = new AgentBuildingInfo(job.getIdentifier().buildLocatorForDisplay(),
job.getIdentifier().buildLocator());
agentService.building(agent.getUuid(), buildingInfo);
LOGGER.info("[Agent Assignment] Assigned job [{}] to agent [{}]", job.getIdentifier(), agent.getAgent().getAgentIdentifier());
return buildWork;
}
}
return NO_WORK;
}
JobPlan findMatchingJob(AgentInstance agent) {
List<JobPlan> filteredJobPlans = environmentConfigService.filterJobsByAgent(jobPlans, agent.getUuid());
JobPlan match = null;
if (!agent.isElastic()) {
match = agent.firstMatching(filteredJobPlans);
} else {
for (JobPlan jobPlan : filteredJobPlans) {
try {
if (jobPlan.requiresElasticAgent() && elasticAgentPluginService.shouldAssignWork(agent.elasticAgentMetadata(), environmentConfigService.envForPipeline(jobPlan.getPipelineName()), jobPlan.getElasticProfile(), jobPlan.getClusterProfile(), jobPlan.getIdentifier())) {
match = jobPlan;
break;
}
} catch (RulesViolationException | SecretResolutionFailureException e) {
JobInstance instance = jobInstanceService.buildById(jobPlan.getJobId());
JobIdentifier jobIdentifier = jobPlan.getIdentifier();
String failureMessage = format("\nThis job was failed by GoCD. This job is configured to run on an elastic agent, there were errors while resolving secrets for the the associated elastic configurations.\nReasons: %s", e.getMessage());
logToJobConsole(jobIdentifier, failureMessage);
scheduleService.failJob(instance);
jobStatusTopic.post(new JobStatusMessage(jobIdentifier, instance.getState(), agent.getUuid()));
}
}
}
if (match != null) {
jobPlans.remove(match);
}
return match;
}
public void onTimer() {
if (maintenanceModeService.isMaintenanceMode()) {
LOGGER.debug("[Maintenance Mode] GoCD server is in 'maintenance' mode, skip checking build assignments");
return;
}
reloadJobPlans();
}
private void reloadJobPlans() {
synchronized (this) {
if (jobPlans == null) {
jobPlans = jobInstanceService.orderedScheduledBuilds();
elasticAgentPluginService.createAgentsFor(jobPlans, new ArrayList<>());
} else {
List<JobPlan> old = jobPlans;
List<JobPlan> newPlan = jobInstanceService.orderedScheduledBuilds();
jobPlans = newPlan;
elasticAgentPluginService.createAgentsFor(old, newPlan);
}
}
}
@Override
public void onConfigChange(CruiseConfig newCruiseConfig) {
LOGGER.info("[Configuration Changed] Removing jobs for pipelines that no longer exist in configuration.");
synchronized (this) {
List<JobPlan> jobsToRemove = new ArrayList<>();
for (JobPlan jobPlan : jobPlans) {
if (!newCruiseConfig.hasBuildPlan(new CaseInsensitiveString(jobPlan.getPipelineName()), new CaseInsensitiveString(jobPlan.getStageName()), jobPlan.getName(), true)) {
jobsToRemove.add(jobPlan);
}
}
forAllDo(jobsToRemove, o -> removeJob((JobPlan) o));
}
}
private void removeJobIfNotPresentInCruiseConfig(CruiseConfig newCruiseConfig, JobPlan jobPlan) {
if (!newCruiseConfig.hasBuildPlan(new CaseInsensitiveString(jobPlan.getPipelineName()), new CaseInsensitiveString(jobPlan.getStageName()), jobPlan.getName(), true)) {
removeJob(jobPlan);
}
}
private void removeJob(JobPlan jobPlan) {
try {
jobPlans.remove(jobPlan);
LOGGER.info("Removing job plan {} that no longer exists in the config", jobPlan);
JobInstance instance = jobInstanceService.buildByIdWithTransitions(jobPlan.getJobId());
//#2846 - remove this hack
instance.setIdentifier(jobPlan.getIdentifier());
scheduleService.cancelJob(instance);
LOGGER.info("Successfully removed job plan {} that no longer exists in the config", jobPlan);
} catch (Exception e) {
LOGGER.warn("Unable to remove plan {} from queue that no longer exists in the config", jobPlan);
}
}
private Work createWork(final AgentInstance agent, final JobPlan job) {
try {
return (Work) transactionTemplate.transactionSurrounding(() -> {
final String agentUuid = agent.getUuid();
//TODO: Use fullPipeline and get the Stage from it?
final Pipeline pipeline;
try {
pipeline = scheduledPipelineLoader.pipelineWithPasswordAwareBuildCauseByBuildId(job.getJobId());
} catch (StaleMaterialsOnBuildCause e) {
// Detailed error msg is part of the exception object and it would be logged. Hence not adding msg while logging.
LOGGER.error("", e);
return NO_WORK;
}
List<Task> tasks = goConfigService.tasksForJob(pipeline.getName(), job.getIdentifier().getStageName(), job.getName());
final List<Builder> builders = builderFactory.buildersForTasks(pipeline, tasks, resolver);
return transactionTemplate.execute(status -> {
if (scheduleService.updateAssignedInfo(agentUuid, job)) {
return NO_WORK;
}
final EnvironmentVariableContext environmentVariableContext = buildEnvVarContext(job.getIdentifier().getPipelineName());
// Agent may have a NULL "resources"
if (CollectionUtils.isNotEmpty(agent.getResourceConfigs())) {
// Users relying on this env. var. can test for its existence rather than checking for an empty string
environmentVariableContext.setProperty(GO_AGENT_RESOURCES, agent.getResourceConfigs().getCommaSeparatedResourceNames(), false);
}
// Reason to resolve them separately: the rules for pluggable scm material verifies `SCM` based rules
// whereas the assignment considers `PipelineGroup` based rules
resolveSecretsForMaterials(pipeline.getBuildCause().getMaterialRevisions());
final ArtifactStores requiredArtifactStores = goConfigService.artifactStores().getArtifactStores(getArtifactStoreIdsRequiredByArtifactPlans(job.getArtifactPlans()));
BuildAssignment buildAssignment = BuildAssignment.create(job, pipeline.getBuildCause(), builders, pipeline.defaultWorkingFolder(), environmentVariableContext, requiredArtifactStores);
secretParamResolver.resolve(buildAssignment);
return new BuildWork(buildAssignment, systemEnvironment.consoleLogCharset());
});
});
} catch (RecordNotFoundException e) {
removeJobIfNotPresentInCruiseConfig(goConfigService.getCurrentConfig(), job);
throw e;
} catch (SecretResolutionFailureException e) {
JobInstance instance = jobInstanceService.buildById(job.getJobId());
logSecretsResolutionFailure(job.getIdentifier(), e);
scheduleService.failJob(instance);
jobStatusTopic.post(new JobStatusMessage(job.getIdentifier(), instance.getState(), agent.getUuid()));
throw e;
} catch (RulesViolationException e) {
JobInstance instance = jobInstanceService.buildById(job.getJobId());
logRulesViolation(job.getIdentifier(), e);
scheduleService.failJob(instance);
jobStatusTopic.post(new JobStatusMessage(job.getIdentifier(), instance.getState(), agent.getUuid()));
throw e;
}
}
/*
* This method will build the initial environment variable context as well as add the environment related variables.
* It will also resolve secrets, if any wrt environment config
*/
EnvironmentVariableContext buildEnvVarContext(String pipelineName) {
String pipelineGroupName = goConfigService.findGroupNameByPipeline(new CaseInsensitiveString(pipelineName));
EnvironmentVariableContext environmentVariableContext = new EnvironmentVariableContext(GO_PIPELINE_GROUP_NAME, pipelineGroupName);
EnvironmentConfig environmentForPipeline = environmentConfigService.environmentForPipeline(pipelineName);
if (environmentForPipeline == null) {
return environmentVariableContext;
}
secretParamResolver.resolve(environmentForPipeline);
environmentVariableContext.setProperty(GO_ENVIRONMENT_NAME, CaseInsensitiveString.str(environmentForPipeline.name()), false);
environmentForPipeline.getVariables().forEach(variable -> {
environmentVariableContext.setProperty(variable.getName(), variable.valueForCommandline(), variable.isSecure() || variable.hasSecretParams());
});
return environmentVariableContext;
}
private void logSecretsResolutionFailure(JobIdentifier jobIdentifier, SecretResolutionFailureException e) {
try {
final String description = format("\nJob for pipeline '%s' failed due to errors while resolving secret params.", jobIdentifier.buildLocator());
consoleService.appendToConsoleLog(jobIdentifier, description);
consoleService.appendToConsoleLog(jobIdentifier, format("\nReason: %s\n", e.getMessage()));
} catch (IllegalArtifactLocationException | IOException e1) {
LOGGER.error(e1.getMessage(), e1);
}
}
private void logRulesViolation(JobIdentifier jobIdentifier, RulesViolationException e) {
try {
final String description = format("\nJob for pipeline '%s' failed due to errors: %s", jobIdentifier.buildLocator(), e.getMessage());
consoleService.appendToConsoleLog(jobIdentifier, description);
} catch (IllegalArtifactLocationException | IOException e1) {
LOGGER.error(e1.getMessage(), e1);
}
}
private void logToJobConsole(JobIdentifier jobIdentifier, String errorMessage) {
try {
consoleService.appendToConsoleLog(jobIdentifier, errorMessage);
} catch (IllegalArtifactLocationException | IOException e) {
LOGGER.error(format("Failed to add message(%s) to the job(%s) console", errorMessage, jobIdentifier), e);
}
}
private Set<String> getArtifactStoreIdsRequiredByArtifactPlans(List<ArtifactPlan> artifactPlans) {
final Set<String> storeIds = new HashSet<>();
for (ArtifactPlan artifactPlan : artifactPlans) {
if (artifactPlan.getArtifactPlanType() == ArtifactPlanType.external) {
storeIds.add((String) artifactPlan.getPluggableArtifactConfiguration().get("storeId"));
}
}
return storeIds;
}
List<JobPlan> jobPlans() {
return jobPlans;
}
// This method will resolve secrets in all the pluggable scm materials if any
private void resolveSecretsForMaterials(MaterialRevisions materialRevisions) {
List<Material> materials = stream(materialRevisions.spliterator(), true)
.map(MaterialRevision::getMaterial)
.filter((material) -> material instanceof PluggableSCMMaterial || material instanceof PackageMaterial)
.collect(toList());
secretParamResolver.resolve(materials);
}
}
|
/*
* 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.openjena.riot.tokens;
/** Do nothing checker */
public class TokenCheckerBase implements TokenChecker
{
@Override
public void checkBlankNode(String blankNodeLabel)
{}
@Override
public void checkControl(int code)
{}
@Override
public void checkDirective(int cntrlCode)
{}
@Override
public void checkKeyword(String lexical)
{}
@Override
public void checkLiteralDT(String lexicalForm, Token datatype)
{}
@Override
public void checkLiteralLang(String lexicalForm, String langTag)
{}
@Override
public void checkNumber(String lexical, String datatypeURI)
{}
@Override
public void checkPrefixedName(String prefixName, String localName)
{}
@Override
public void checkString(String string)
{}
@Override
public void checkURI(String uriStr)
{}
@Override
public void checkVariable(String tokenImage)
{}
}
|
package edu.ranken.paul_smith.npr_tech_news;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import com.google.android.material.snackbar.Snackbar;
import java.util.ArrayList;
import edu.ranken.paul_smith.npr_tech_news.data.NewsAPI;
import edu.ranken.paul_smith.npr_tech_news.ui.NprNewsApp;
import edu.ranken.paul_smith.npr_tech_news.ui.NprNewsModel;
public class MainActivity extends AppCompatActivity {
// constants
private static final String LOG_TAG = "MainActivity";
// views
private Button refreshButton;
private TextView errorText;
private TextView outputText;
private TextView connectedText;
private ImageView connectedIcon;
// state
private NprNewsApp app;
private NprNewsModel model;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// find views
refreshButton = findViewById(R.id.refreshButton);
errorText = findViewById(R.id.errorText);
outputText = findViewById(R.id.outputText);
connectedText = findViewById(R.id.connectedText);
connectedIcon = findViewById(R.id.connectedIcon);
// bind to model
app = (NprNewsApp) getApplication(); // Remember to set android:name in manifest!!
model = app.getModel();
model.getConnected().observe(this, (connnected) -> showConnected(connnected));
model.getFetching().observe(this, (fetching) -> {
refreshButton.setEnabled(!fetching);
});
model.getErrorMessage().observe(this, (error) -> {
errorText.setVisibility(error != null ? View.VISIBLE : View.GONE);
errorText.setText(error);
});
model.getFeed().observe(this, (feed) -> showFeed(feed));
model.getSnackbarMessage().observe(this, (message) -> {
if (message != null) {
Snackbar.make(refreshButton, message, Snackbar.LENGTH_SHORT).show();
model.onSnackbarShown();
}
});
// register listeners
refreshButton.setOnClickListener((view) -> {
model.refreshFeed();
Log.i(LOG_TAG, "onClick");
});
Log.i(LOG_TAG, "onCreate");
}
@Override
protected void onDestroy() {
super.onDestroy();
}
private void showConnected(boolean isConnected) {
if (isConnected) {
connectedText.setText(R.string.connected);
connectedIcon.setImageResource(R.drawable.ic_wifi_on);
} else {
connectedText.setText(R.string.disconnected);
connectedIcon.setImageResource(R.drawable.ic_wifi_off);
}
}
private void showFeed(NewsAPI.Feed feed) {
StringBuilder output = new StringBuilder();
if (feed == null) {
output.append("FEED MISSING\n");
} else {
output.append("NEWS FEED\n");
output.append("description: ").append(feed.description).append("\n\n");
if (feed.author == null) {
output.append("AUTHOR MISSING\n\n");
} else {
output.append("author.name: ").append(feed.author.name).append("\n");
output.append("author.url: ").append(feed.author.url).append("\n");
output.append("author.avatar: ").append(feed.author.avatar).append("\n");
output.append("\n");
}
if (feed.items == null) {
output.append("ITEMS MISSING\n");
} else {
ArrayList<NewsAPI.FeedItem> items = feed.items;
for (int i = 0; i < items.size(); ++i) {
NewsAPI.FeedItem item = feed.items.get(i);
output.append("items[").append(i).append("]: ").append(item.title).append("\n");
}
output.append("\n");
}
}
outputText.setText(output);
}
}
|
/*
* 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.configurationprocessor.metadata;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Set;
/**
* Configuration meta-data.
*
* @author Stephane Nicoll
* @author Phillip Webb
* @since 1.2.0
* @see ItemMetadata
*/
public class ConfigurationMetadata {
private static final Set<Character> SEPARATORS;
static {
List<Character> chars = Arrays.asList('-', '_');
SEPARATORS = Collections.unmodifiableSet(new HashSet<Character>(chars));
}
private final Map<String, List<ItemMetadata>> items;
private final Map<String, List<ItemHint>> hints;
public ConfigurationMetadata() {
this.items = new LinkedHashMap<String, List<ItemMetadata>>();
this.hints = new LinkedHashMap<String, List<ItemHint>>();
}
public ConfigurationMetadata(ConfigurationMetadata metadata) {
this.items = new LinkedHashMap<String, List<ItemMetadata>>(metadata.items);
this.hints = new LinkedHashMap<String, List<ItemHint>>(metadata.hints);
}
/**
* Add item meta-data.
* @param itemMetadata the meta-data to add
*/
public void add(ItemMetadata itemMetadata) {
add(this.items, itemMetadata.getName(), itemMetadata);
}
/**
* Add item hint.
* @param itemHint the item hint to add
*/
public void add(ItemHint itemHint) {
add(this.hints, itemHint.getName(), itemHint);
}
/**
* Merge the content from another {@link ConfigurationMetadata}.
* @param metadata the {@link ConfigurationMetadata} instance to merge
*/
public void merge(ConfigurationMetadata metadata) {
for (ItemMetadata additionalItem : metadata.getItems()) {
mergeItemMetadata(additionalItem);
}
for (ItemHint itemHint : metadata.getHints()) {
add(itemHint);
}
}
/**
* Return item meta-data.
* @return the items
*/
public List<ItemMetadata> getItems() {
return flattenValues(this.items);
}
/**
* Return hint meta-data.
* @return the hints
*/
public List<ItemHint> getHints() {
return flattenValues(this.hints);
}
protected void mergeItemMetadata(ItemMetadata metadata) {
ItemMetadata matching = findMatchingItemMetadata(metadata);
if (matching != null) {
if (metadata.getDescription() != null) {
matching.setDescription(metadata.getDescription());
}
if (metadata.getDefaultValue() != null) {
matching.setDefaultValue(metadata.getDefaultValue());
}
ItemDeprecation deprecation = metadata.getDeprecation();
ItemDeprecation matchingDeprecation = matching.getDeprecation();
if (deprecation != null) {
if (matchingDeprecation == null) {
matching.setDeprecation(deprecation);
}
else {
if (deprecation.getReason() != null) {
matchingDeprecation.setReason(deprecation.getReason());
}
if (deprecation.getReplacement() != null) {
matchingDeprecation.setReplacement(deprecation.getReplacement());
}
}
}
}
else {
add(this.items, metadata.getName(), metadata);
}
}
private <K, V> void add(Map<K, List<V>> map, K key, V value) {
List<V> values = map.get(key);
if (values == null) {
values = new ArrayList<V>();
map.put(key, values);
}
values.add(value);
}
private ItemMetadata findMatchingItemMetadata(ItemMetadata metadata) {
List<ItemMetadata> candidates = this.items.get(metadata.getName());
if (candidates == null || candidates.isEmpty()) {
return null;
}
ListIterator<ItemMetadata> it = candidates.listIterator();
while (it.hasNext()) {
if (!it.next().hasSameType(metadata)) {
it.remove();
}
}
if (candidates.size() == 1) {
return candidates.get(0);
}
for (ItemMetadata candidate : candidates) {
if (nullSafeEquals(candidate.getSourceType(), metadata.getSourceType())) {
return candidate;
}
}
return null;
}
private boolean nullSafeEquals(Object o1, Object o2) {
if (o1 == o2) {
return true;
}
return o1 != null && o2 != null && o1.equals(o2);
}
public static String nestedPrefix(String prefix, String name) {
String nestedPrefix = (prefix == null ? "" : prefix);
String dashedName = toDashedCase(name);
nestedPrefix += ("".equals(nestedPrefix) ? dashedName : "." + dashedName);
return nestedPrefix;
}
static String toDashedCase(String name) {
StringBuilder dashed = new StringBuilder();
Character previous = null;
for (char current : name.toCharArray()) {
if (SEPARATORS.contains(current)) {
dashed.append("-");
}
else if (Character.isUpperCase(current) && previous != null
&& !SEPARATORS.contains(previous)) {
dashed.append("-").append(current);
}
else {
dashed.append(current);
}
previous = current;
}
return dashed.toString().toLowerCase();
}
private static <T extends Comparable<T>> List<T> flattenValues(Map<?, List<T>> map) {
List<T> content = new ArrayList<T>();
for (List<T> values : map.values()) {
content.addAll(values);
}
Collections.sort(content);
return content;
}
}
|
package com.jrestless.aws.examples;
import com.jrestless.aws.examples.SampleResource.PojoDto;
import feign.Headers;
import feign.Param;
import feign.RequestLine;
@Headers({
"Accept: application/json",
"Content-Type: application/json"
})
public interface BackendService {
@RequestLine("GET /api/info")
PojoDto getInfo();
@RequestLine("GET /api/pathparam/{value}")
PojoDto getPathParam(@Param("value") String value);
@RequestLine("GET /api/queryparam?value={value}")
PojoDto getQueryParam(@Param("value") String value);
@RequestLine("GET /api/service-request")
PojoDto getServiceRequest();
@RequestLine("GET /api/lambda-context")
PojoDto getLambdaContext();
@RequestLine("POST /api/post")
PojoDto post(PojoDto data);
}
|
package store.exception;
import lombok.EqualsAndHashCode;
import lombok.ToString;
@ToString
@EqualsAndHashCode(callSuper = false)
public class OverflowSupplyException extends RuntimeException {
public OverflowSupplyException() {
super("Overflow Supply!");
}
}
|
package learn.offer;
import java.util.Arrays;
/**
* 扑克牌顺子
*/
public class Test44 {
public static void main(String[] args) {
}
public boolean isContinuous(int [] numbers) {
if (numbers == null || numbers.length != 5) {
return false;
}
// 先排个序
Arrays.sort(numbers);
// 5,6,6,8,9
boolean result;
int le = numbers.length;
int count = 0; // 统计大王小王
for (int i = 0; i < 5; i++) {
if (numbers[i] == 0) {
count++;
}
}
int p1 = count;
int p2 = count + 1;
int index = 0;
while (p2 < le) {
// 有对子直接返回false
if (numbers[p1] == numbers[p2]) {
return false;
}
index += numbers[p2] - numbers[p1] - 1;
p1 = p2;
p2++;
}
result = count >= index ? true : false;
return result;
}
}
|
package mage.cards.d;
import java.util.Set;
import java.util.UUID;
import mage.abilities.Ability;
import mage.abilities.TriggeredAbility;
import mage.abilities.common.BeginningOfUpkeepTriggeredAbility;
import mage.abilities.condition.Condition;
import mage.abilities.decorator.ConditionalInterveningIfTriggeredAbility;
import mage.abilities.effects.common.SacrificeSourceEffect;
import mage.abilities.effects.common.search.SearchLibraryPutInPlayEffect;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.constants.Outcome;
import mage.constants.TargetController;
import mage.constants.Zone;
import mage.filter.StaticFilters;
import mage.filter.common.FilterCreatureCard;
import mage.game.Game;
import mage.target.common.TargetCardInLibrary;
/**
*
* @author Plopman
*/
public final class DefenseOfTheHeart extends CardImpl {
public DefenseOfTheHeart(UUID ownerId, CardSetInfo setInfo) {
super(ownerId, setInfo, new CardType[]{CardType.ENCHANTMENT}, "{3}{G}");
// At the beginning of your upkeep, if an opponent controls three or more creatures, sacrifice Defense of the Heart, search your library for up to two creature cards, and put those cards onto the battlefield. Then shuffle your library.
TriggeredAbility ability = new BeginningOfUpkeepTriggeredAbility(Zone.BATTLEFIELD, new SacrificeSourceEffect(), TargetController.YOU, false);
ability.addEffect(new SearchLibraryPutInPlayEffect(new TargetCardInLibrary(0, 2, new FilterCreatureCard()), false, Outcome.PutLandInPlay));
DefenseOfTheHeartCondition contition = new DefenseOfTheHeartCondition();
this.addAbility(new ConditionalInterveningIfTriggeredAbility(ability, contition, "At the beginning of your upkeep, if an opponent controls three or more creatures, sacrifice {this}, search your library for up to two creature cards, and put those cards onto the battlefield. Then shuffle your library"));
}
public DefenseOfTheHeart(final DefenseOfTheHeart card) {
super(card);
}
@Override
public DefenseOfTheHeart copy() {
return new DefenseOfTheHeart(this);
}
static class DefenseOfTheHeartCondition implements Condition {
@Override
public boolean apply(Game game, Ability source) {
Set<UUID> opponents = game.getOpponents(source.getControllerId());
for (UUID uuid : opponents) {
if (game.getBattlefield().countAll(StaticFilters.FILTER_PERMANENT_CREATURE, uuid, game) >= 3) {
return true;
}
}
return false;
}
}
}
|
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1
begin_package
DECL|package|org.jabref.model.entry
package|package
name|org
operator|.
name|jabref
operator|.
name|model
operator|.
name|entry
package|;
end_package
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|HashMap
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|Map
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|stream
operator|.
name|Collectors
import|;
end_import
begin_import
import|import
name|org
operator|.
name|jabref
operator|.
name|model
operator|.
name|entry
operator|.
name|field
operator|.
name|Field
import|;
end_import
begin_import
import|import
name|org
operator|.
name|jabref
operator|.
name|model
operator|.
name|entry
operator|.
name|field
operator|.
name|StandardField
import|;
end_import
begin_comment
comment|/** * Converts Entry models from BibTex to biblatex and back. */
end_comment
begin_class
DECL|class|EntryConverter
specifier|public
class|class
name|EntryConverter
block|{
comment|// BibTeX to biblatex
DECL|field|FIELD_ALIASES_TEX_TO_LTX
specifier|public
specifier|static
name|Map
argument_list|<
name|Field
argument_list|,
name|Field
argument_list|>
name|FIELD_ALIASES_TEX_TO_LTX
decl_stmt|;
comment|// biblatex to BibTeX
DECL|field|FIELD_ALIASES_LTX_TO_TEX
specifier|public
specifier|static
name|Map
argument_list|<
name|Field
argument_list|,
name|Field
argument_list|>
name|FIELD_ALIASES_LTX_TO_TEX
decl_stmt|;
comment|// All aliases
DECL|field|FIELD_ALIASES
specifier|public
specifier|static
name|Map
argument_list|<
name|Field
argument_list|,
name|Field
argument_list|>
name|FIELD_ALIASES
decl_stmt|;
static|static
block|{
name|EntryConverter
operator|.
name|FIELD_ALIASES_TEX_TO_LTX
operator|=
operator|new
name|HashMap
argument_list|<>
argument_list|()
expr_stmt|;
name|EntryConverter
operator|.
name|FIELD_ALIASES_TEX_TO_LTX
operator|.
name|put
argument_list|(
name|StandardField
operator|.
name|ADDRESS
argument_list|,
name|StandardField
operator|.
name|LOCATION
argument_list|)
expr_stmt|;
name|EntryConverter
operator|.
name|FIELD_ALIASES_TEX_TO_LTX
operator|.
name|put
argument_list|(
name|StandardField
operator|.
name|ANNOTE
argument_list|,
name|StandardField
operator|.
name|ANNOTATION
argument_list|)
expr_stmt|;
name|EntryConverter
operator|.
name|FIELD_ALIASES_TEX_TO_LTX
operator|.
name|put
argument_list|(
name|StandardField
operator|.
name|ARCHIVEPREFIX
argument_list|,
name|StandardField
operator|.
name|EPRINTTYPE
argument_list|)
expr_stmt|;
name|EntryConverter
operator|.
name|FIELD_ALIASES_TEX_TO_LTX
operator|.
name|put
argument_list|(
name|StandardField
operator|.
name|JOURNAL
argument_list|,
name|StandardField
operator|.
name|JOURNALTITLE
argument_list|)
expr_stmt|;
name|EntryConverter
operator|.
name|FIELD_ALIASES_TEX_TO_LTX
operator|.
name|put
argument_list|(
name|StandardField
operator|.
name|KEY
argument_list|,
name|StandardField
operator|.
name|SORTKEY
argument_list|)
expr_stmt|;
name|EntryConverter
operator|.
name|FIELD_ALIASES_TEX_TO_LTX
operator|.
name|put
argument_list|(
name|StandardField
operator|.
name|PRIMARYCLASS
argument_list|,
name|StandardField
operator|.
name|EPRINTCLASS
argument_list|)
expr_stmt|;
name|EntryConverter
operator|.
name|FIELD_ALIASES_TEX_TO_LTX
operator|.
name|put
argument_list|(
name|StandardField
operator|.
name|SCHOOL
argument_list|,
name|StandardField
operator|.
name|INSTITUTION
argument_list|)
expr_stmt|;
comment|// inverse map
name|EntryConverter
operator|.
name|FIELD_ALIASES_LTX_TO_TEX
operator|=
name|EntryConverter
operator|.
name|FIELD_ALIASES_TEX_TO_LTX
operator|.
name|entrySet
argument_list|()
operator|.
name|stream
argument_list|()
operator|.
name|collect
argument_list|(
name|Collectors
operator|.
name|toMap
argument_list|(
name|Map
operator|.
name|Entry
operator|::
name|getValue
argument_list|,
name|Map
operator|.
name|Entry
operator|::
name|getKey
argument_list|)
argument_list|)
expr_stmt|;
comment|// all aliases
name|FIELD_ALIASES
operator|=
operator|new
name|HashMap
argument_list|<>
argument_list|()
expr_stmt|;
name|FIELD_ALIASES
operator|.
name|putAll
argument_list|(
name|EntryConverter
operator|.
name|FIELD_ALIASES_TEX_TO_LTX
argument_list|)
expr_stmt|;
name|FIELD_ALIASES
operator|.
name|putAll
argument_list|(
name|EntryConverter
operator|.
name|FIELD_ALIASES_LTX_TO_TEX
argument_list|)
expr_stmt|;
block|}
DECL|method|EntryConverter ()
specifier|private
name|EntryConverter
parameter_list|()
block|{ }
block|}
end_class
end_unit
|
package com.blazemeter.jmeter;
import org.apache.jmeter.control.LoopController;
import org.apache.jmeter.threads.*;
import org.apache.jorphan.collections.HashTree;
import org.apache.jorphan.util.JMeterStopThreadException;
import org.junit.Test;
import java.io.File;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.*;
public class DirectoryListingConfigTest {
private static final String VARIABLE_NAME = "fname";
@Test
public void testShareList() throws Exception {
DirectoryListingConfig config = new DirectoryListingConfig();
File rootDir = TestDirectoryListingConfigActionTest.createFileTree();
setDirectoryConfig(config, rootDir.getAbsolutePath(), VARIABLE_NAME, true, false, true, false, false, false);
config.testStarted();
testFlow(config);
config.testEnded();
}
@Test
public void testNonShareList() throws Exception {
DirectoryListingConfig config = new DirectoryListingConfig();
File rootDir = TestDirectoryListingConfigActionTest.createFileTree();
setDirectoryConfig(config, rootDir.getAbsolutePath(), VARIABLE_NAME, true, false, true, false, true, false);
testFlow(config);
}
@Test
public void testThreadStopping() throws Exception {
DirectoryListingConfig config = new DirectoryListingConfig();
File rootDir = TestDirectoryListingConfigActionTest.createFileTree();
setDirectoryConfig(config, rootDir.getAbsolutePath(), VARIABLE_NAME, true, false, false, false, true, false);
final HashTree hashTree = new HashTree();
hashTree.add(new LoopController());
JMeterThread thread = new JMeterThread(hashTree, null, null);
JMeterContextService.getContext().setThread(thread);
testFlow(config);
try {
config.iterationStart(null);
} catch (JMeterStopThreadException ex) {
assertEquals("All files in the directory have been passed.", ex.getMessage());
}
}
private void testFlow(DirectoryListingConfig config) {
List<File> etalonList = config.createDirectoryListingIterator().getDirectoryListing();
if (config.getRandomOrder()) {
DirectoryListingIterator.shuffleList(etalonList);
}
assertNotNull(etalonList);
JMeterContext context = JMeterContextService.getContext();
JMeterVariables variables = context.getVariables();
if (variables == null) {
context.setVariables(variables = new JMeterVariables());
}
for (File etalonFile : etalonList) {
config.iterationStart(null);
assertEquals(etalonFile.getAbsolutePath(), variables.get(VARIABLE_NAME));
}
}
public static void setDirectoryConfig(
DirectoryListingConfig config,
String srcDir,
String varName,
boolean useFullPath,
boolean isRandomOrder,
boolean isRecursiveListing,
boolean isRewindOnTheEnd,
boolean isIndependentList,
boolean isReReadScrDir
) {
config.setSourceDirectory(srcDir);
config.setDestinationVariableName(varName);
config.setUseFullPath(useFullPath);
config.setRandomOrder(isRandomOrder);
config.setRecursiveListing(isRecursiveListing);
config.setRewindOnTheEnd(isRewindOnTheEnd);
config.setIndependentListPerThread(isIndependentList);
config.setReReadDirectoryOnTheEndOfList(isReReadScrDir);
}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.flink.table.runtime.util;
import org.apache.flink.annotation.VisibleForTesting;
import org.apache.flink.core.memory.MemorySegment;
import org.apache.flink.core.memory.MemorySegmentFactory;
import org.apache.flink.runtime.io.disk.RandomAccessInputView;
import org.apache.flink.runtime.io.disk.SimpleCollectingOutputView;
import org.apache.flink.runtime.io.disk.iomanager.BlockChannelReader;
import org.apache.flink.runtime.io.disk.iomanager.BlockChannelWriter;
import org.apache.flink.runtime.io.disk.iomanager.ChannelReaderInputView;
import org.apache.flink.runtime.io.disk.iomanager.FileIOChannel;
import org.apache.flink.runtime.io.disk.iomanager.HeaderlessChannelReaderInputView;
import org.apache.flink.runtime.io.disk.iomanager.IOManager;
import org.apache.flink.runtime.memory.MemoryManager;
import org.apache.flink.table.dataformat.BaseRow;
import org.apache.flink.table.dataformat.BinaryRow;
import org.apache.flink.table.runtime.io.BinaryRowChannelInputViewIterator;
import org.apache.flink.table.runtime.io.ChannelWithMeta;
import org.apache.flink.table.runtime.typeutils.AbstractRowSerializer;
import org.apache.flink.table.runtime.typeutils.BinaryRowSerializer;
import org.apache.flink.util.InstantiationUtil;
import org.apache.flink.util.MutableObjectIterator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.Closeable;
import java.io.EOFException;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.ConcurrentModificationException;
import java.util.List;
import static org.apache.flink.util.Preconditions.checkArgument;
import static org.apache.flink.util.Preconditions.checkState;
/**
* A resettable external buffer for binary row. It stores records in memory and spill to disk
* when memory is not enough. When the spill is completed, the records are written to memory again.
* The returned iterator reads the data in write order (read spilled records first). It supports
* infinite length. It can open multiple Iterators. It support new iterator with beginRow.
*
* <p>NOTE: Not supports reading while writing. In the face of concurrent modification, the
* iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior
* at an undetermined time in the future.
*/
public class ResettableExternalBuffer implements ResettableRowBuffer {
private static final Logger LOG = LoggerFactory.getLogger(ResettableExternalBuffer.class);
/** The minimum number of segments that are required, 320 KibiBytes. */
public static final int MIN_NUM_MEMORY = 10 * MemoryManager.DEFAULT_PAGE_SIZE;
// We will only read one spilled file at the same time.
private static final int READ_BUFFER = 2;
private final IOManager ioManager;
private final LazyMemorySegmentPool pool;
private final BinaryRowSerializer binaryRowSerializer;
private final InMemoryBuffer inMemoryBuffer;
// The size of each segment
private final int segmentSize;
private long spillSize;
// The length of each row, if each row is of fixed length
private long rowLength;
// If each row is of fixed length
private boolean isRowAllInFixedPart;
private final List<ChannelWithMeta> spilledChannelIDs;
private final List<Integer> spilledChannelRowOffsets;
private int numRows;
// Number of iterators currently opened
private int iterOpenedCount;
// Times of reset() called. Used to check validity of iterators.
private int externalBufferVersion;
private boolean addCompleted;
public ResettableExternalBuffer(
IOManager ioManager,
LazyMemorySegmentPool pool,
AbstractRowSerializer serializer,
boolean isRowAllInFixedPart) {
this.ioManager = ioManager;
this.pool = pool;
this.binaryRowSerializer = serializer instanceof BinaryRowSerializer ?
(BinaryRowSerializer) serializer.duplicate() :
new BinaryRowSerializer(serializer.getArity());
this.segmentSize = pool.pageSize();
this.spilledChannelIDs = new ArrayList<>();
this.spillSize = 0;
this.spilledChannelRowOffsets = new ArrayList<>();
this.numRows = 0;
this.iterOpenedCount = 0;
this.externalBufferVersion = 0;
this.isRowAllInFixedPart = isRowAllInFixedPart;
this.rowLength = isRowAllInFixedPart ? binaryRowSerializer.getSerializedRowFixedPartLength() : -1;
this.addCompleted = false;
this.inMemoryBuffer = new InMemoryBuffer(serializer);
}
@Override
public void reset() {
clearChannels();
inMemoryBuffer.reset();
numRows = 0;
externalBufferVersion++;
addCompleted = false;
}
@Override
public void add(BaseRow row) throws IOException {
checkState(!addCompleted, "This buffer has add completed.");
if (!inMemoryBuffer.write(row)) {
// Check if record is too big.
if (inMemoryBuffer.getCurrentDataBufferOffset() == 0) {
throwTooBigException(row);
}
spill();
if (!inMemoryBuffer.write(row)) {
throwTooBigException(row);
}
}
numRows++;
}
@Override
public void complete() {
addCompleted = true;
}
@Override
public BufferIterator newIterator() {
return newIterator(0);
}
@Override
public BufferIterator newIterator(int beginRow) {
checkState(addCompleted, "This buffer has not add completed.");
checkArgument(beginRow >= 0, "`beginRow` can't be negative!");
iterOpenedCount++;
return new BufferIterator(beginRow);
}
/**
* Delete all files and release the memory.
*/
@Override
public void close() {
clearChannels();
inMemoryBuffer.close();
pool.close();
}
private void throwTooBigException(BaseRow row) throws IOException {
int rowSize = InstantiationUtil.serializeToByteArray(inMemoryBuffer.serializer, row).length;
throw new IOException("Record is too big, it can't be added to a empty InMemoryBuffer! " +
"Record size: " + rowSize + ", Buffer: " + memorySize());
}
private void spill() throws IOException {
FileIOChannel.ID channel = ioManager.createChannel();
final BlockChannelWriter<MemorySegment> writer = this.ioManager.createBlockChannelWriter(channel);
int numRecordBuffers = inMemoryBuffer.getNumRecordBuffers();
ArrayList<MemorySegment> segments = inMemoryBuffer.getRecordBufferSegments();
try {
// spill in memory buffer in zero-copy.
for (int i = 0; i < numRecordBuffers; i++) {
writer.writeBlock(segments.get(i));
}
LOG.info("here spill the reset buffer data with {} bytes", writer.getSize());
writer.close();
} catch (IOException e) {
writer.closeAndDelete();
throw e;
}
spillSize += numRecordBuffers * segmentSize;
spilledChannelIDs.add(new ChannelWithMeta(
channel,
inMemoryBuffer.getNumRecordBuffers(),
inMemoryBuffer.getNumBytesInLastBuffer()));
this.spilledChannelRowOffsets.add(numRows);
inMemoryBuffer.reset();
}
public int size() {
return numRows;
}
private int memorySize() {
return pool.freePages() * segmentSize;
}
public long getUsedMemoryInBytes() {
return memorySize() + iterOpenedCount * READ_BUFFER * segmentSize;
}
public int getNumSpillFiles() {
return spilledChannelIDs.size();
}
public long getSpillInBytes() {
return spillSize;
}
private void clearChannels() {
for (ChannelWithMeta meta : spilledChannelIDs) {
final File f = new File(meta.getChannel().getPath());
if (f.exists()) {
f.delete();
}
}
spilledChannelIDs.clear();
spillSize = 0;
spilledChannelRowOffsets.clear();
}
/**
* Iterator of external buffer.
*/
public class BufferIterator implements ResettableRowBuffer.ResettableIterator {
MutableObjectIterator<BinaryRow> currentIterator;
// memory for file reader to store read result
List<MemorySegment> freeMemory = null;
BlockChannelReader<MemorySegment> fileReader;
int currentChannelID = -1;
BinaryRow reuse = binaryRowSerializer.createInstance();
BinaryRow row;
int beginRow;
int nextRow;
// reuse in memory buffer iterator to reduce initialization cost.
InMemoryBuffer.InMemoryBufferIterator reusableMemoryIterator;
// value of resetCount of buffer when this iterator is created.
// used to check validity.
int versionSnapshot;
// if this iterator is closed
boolean closed;
private BufferIterator(int beginRow) {
this.beginRow = Math.min(beginRow, numRows);
this.nextRow = this.beginRow;
this.versionSnapshot = externalBufferVersion;
this.closed = false;
}
private void checkValidity() {
if (closed) {
throw new RuntimeException("This iterator is closed!");
} else if (this.versionSnapshot != externalBufferVersion) {
throw new RuntimeException("This iterator is no longer valid!");
}
}
@Override
public void reset() throws IOException {
checkValidity();
resetImpl();
}
private void resetImpl() throws IOException {
closeCurrentFileReader();
nextRow = beginRow;
currentChannelID = -1;
currentIterator = null;
row = null;
reuse.clear();
}
@Override
public void close() {
if (closed) {
return;
}
try {
resetImpl();
} catch (IOException e) {
throw new RuntimeException(e);
}
if (freeMemory != null) {
freeMemory.clear();
}
if (reusableMemoryIterator != null) {
reusableMemoryIterator.close();
}
closed = true;
iterOpenedCount--;
}
@Override
public boolean advanceNext() {
checkValidity();
try {
updateIteratorIfNeeded();
// get from curr iterator or new iterator.
while (true) {
if (currentIterator != null &&
(row = currentIterator.next(reuse)) != null) {
this.nextRow++;
return true;
} else {
if (!nextIterator()) {
return false;
}
}
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private boolean nextIterator() throws IOException {
if (currentChannelID == -1) {
// First call to next iterator. Fetch iterator according to beginRow.
if (isRowAllInFixedPart) {
gotoAllInFixedPartRow(beginRow);
} else {
gotoVariableLengthRow(beginRow);
}
} else if (currentChannelID == Integer.MAX_VALUE) {
// The last one is in memory, so the end.
return false;
} else if (currentChannelID < spilledChannelIDs.size() - 1) {
// Next spilled iterator.
nextSpilledIterator();
} else {
// It is the last iterator.
newMemoryIterator();
}
return true;
}
private boolean iteratorNeedsUpdate() {
int size = spilledChannelRowOffsets.size();
return size > 0
&& currentChannelID == Integer.MAX_VALUE
&& nextRow <= spilledChannelRowOffsets.get(size - 1);
}
private void updateIteratorIfNeeded() throws IOException {
if (iteratorNeedsUpdate()) {
reuse.clear();
reusableMemoryIterator = null;
if (isRowAllInFixedPart) {
gotoAllInFixedPartRow(nextRow);
} else {
gotoVariableLengthRow(nextRow);
}
}
}
@Override
public BinaryRow getRow() {
return row;
}
private void closeCurrentFileReader() throws IOException {
if (fileReader != null) {
fileReader.close();
fileReader = null;
}
}
private void gotoAllInFixedPartRow(int beginRow) throws IOException {
// Find which channel contains the row.
int beginChannel = upperBound(beginRow, spilledChannelRowOffsets);
// Find the row number in its own channel (0-indexed).
int beginRowInChannel = getBeginIndexInChannel(beginRow, beginChannel);
if (beginRow == numRows) {
// Row number out of range! Should return an "empty" iterator.
newMemoryIterator(beginRowInChannel, inMemoryBuffer.getCurrentDataBufferOffset());
return;
}
// Fixed length. Calculate offset directly.
long numRecordsInSegment = segmentSize / rowLength;
long offset =
(beginRowInChannel / numRecordsInSegment) * segmentSize +
(beginRowInChannel % numRecordsInSegment) * rowLength;
if (beginChannel < spilledChannelRowOffsets.size()) {
// Data on disk
newSpilledIterator(beginChannel, offset);
} else {
// Data in memory
newMemoryIterator(beginRowInChannel, offset);
}
}
private void gotoVariableLengthRow(int beginRow) throws IOException {
// Find which channel contains the row.
int beginChannel = upperBound(beginRow, spilledChannelRowOffsets);
// Find the row number in its own channel (0-indexed).
int beginRowInChannel = getBeginIndexInChannel(beginRow, beginChannel);
if (beginRow == numRows) {
// Row number out of range! Should return an "empty" iterator.
newMemoryIterator(beginRowInChannel, inMemoryBuffer.getCurrentDataBufferOffset());
return;
}
if (beginChannel < spilledChannelRowOffsets.size()) {
// Data on disk
newSpilledIterator(beginChannel);
} else {
// Data in memory
newMemoryIterator();
}
nextRow -= beginRowInChannel;
for (int i = 0; i < beginRowInChannel; i++) {
advanceNext();
}
}
private void nextSpilledIterator() throws IOException {
newSpilledIterator(currentChannelID + 1);
}
private void newSpilledIterator(int channelID) throws IOException {
newSpilledIterator(channelID, 0);
}
private void newSpilledIterator(int channelID, long offset) throws IOException {
ChannelWithMeta channel = spilledChannelIDs.get(channelID);
currentChannelID = channelID;
// close current reader first.
closeCurrentFileReader();
// calculate segment number
int segmentNum = (int) (offset / segmentSize);
long seekPosition = segmentNum * segmentSize;
// new reader.
this.fileReader = ioManager.createBlockChannelReader(channel.getChannel());
if (offset > 0) {
// seek to the beginning of that segment
fileReader.seekToPosition(seekPosition);
}
ChannelReaderInputView inView = new HeaderlessChannelReaderInputView(
fileReader, getReadMemory(), channel.getBlockCount() - segmentNum,
channel.getNumBytesInLastBlock(), false, offset - seekPosition
);
this.currentIterator = new BinaryRowChannelInputViewIterator(inView, binaryRowSerializer);
}
private void newMemoryIterator() throws IOException {
newMemoryIterator(0, 0);
}
private void newMemoryIterator(int beginRow, long offset) throws IOException {
currentChannelID = Integer.MAX_VALUE;
// close curr reader first.
closeCurrentFileReader();
if (reusableMemoryIterator == null) {
reusableMemoryIterator = inMemoryBuffer.newIterator(beginRow, offset);
} else {
reusableMemoryIterator.reset(inMemoryBuffer.recordCount, offset);
}
this.currentIterator = reusableMemoryIterator;
}
private int getBeginIndexInChannel(int beginRow, int beginChannel) {
if (beginChannel > 0) {
return beginRow - spilledChannelRowOffsets.get(beginChannel - 1);
} else {
return beginRow;
}
}
private List<MemorySegment> getReadMemory() {
if (freeMemory == null) {
freeMemory = new ArrayList<>();
for (int i = 0; i < READ_BUFFER; i++) {
freeMemory.add(MemorySegmentFactory.allocateUnpooledSegment(segmentSize));
}
}
return freeMemory;
}
// Find the index of the first element which is strictly greater than `goal` in `list`.
// `list` must be sorted.
// If every element in `list` is not larger than `goal`, return `list.size()`.
private int upperBound(int goal, List<Integer> list) {
if (list.size() == 0) {
return 0;
}
if (list.get(list.size() - 1) <= goal) {
return list.size();
}
// Binary search
int head = 0;
int tail = list.size() - 1;
int mid;
while (head < tail) {
mid = (head + tail) / 2;
if (list.get(mid) <= goal) {
head = mid + 1;
} else {
tail = mid;
}
}
return head;
}
}
@VisibleForTesting
List<ChannelWithMeta> getSpillChannels() {
return spilledChannelIDs;
}
/**
* In memory buffer that stores records to memorySegments, returns a iterator that map from memory.
*/
private class InMemoryBuffer implements Closeable {
private final AbstractRowSerializer serializer;
private final ArrayList<MemorySegment> recordBufferSegments;
private final SimpleCollectingOutputView recordCollector;
// Can't use recordCollector.getCurrentOffset(), maybe the offset of recordCollector is
// disrupted by the attempt of record writing.
private long currentDataBufferOffset;
private int numBytesInLastBuffer;
private int recordCount;
private InMemoryBuffer(AbstractRowSerializer serializer) {
// serializer has states, so we must duplicate
this.serializer = (AbstractRowSerializer) serializer.duplicate();
this.recordBufferSegments = new ArrayList<>();
this.recordCollector = new SimpleCollectingOutputView(
this.recordBufferSegments, pool, segmentSize);
this.recordCount = 0;
}
private void reset() {
this.currentDataBufferOffset = 0;
this.recordCount = 0;
returnToSegmentPool();
this.recordCollector.reset();
}
@Override
public void close() {
returnToSegmentPool();
}
private void returnToSegmentPool() {
pool.returnAll(this.recordBufferSegments);
this.recordBufferSegments.clear();
}
public boolean write(BaseRow row) throws IOException {
try {
this.serializer.serializeToPages(row, this.recordCollector);
currentDataBufferOffset = this.recordCollector.getCurrentOffset();
numBytesInLastBuffer = this.recordCollector.getCurrentPositionInSegment();
recordCount++;
return true;
} catch (EOFException e) {
return false;
}
}
private ArrayList<MemorySegment> getRecordBufferSegments() {
return recordBufferSegments;
}
private long getCurrentDataBufferOffset() {
return currentDataBufferOffset;
}
private int getNumRecordBuffers() {
int result = (int) (currentDataBufferOffset / segmentSize);
long mod = currentDataBufferOffset % segmentSize;
if (mod != 0) {
result += 1;
}
return result;
}
private int getNumBytesInLastBuffer() {
return numBytesInLastBuffer;
}
private InMemoryBufferIterator newIterator(int beginRow, long offset) {
checkArgument(offset >= 0, "`offset` can't be negative!");
RandomAccessInputView recordBuffer = new RandomAccessInputView(
this.recordBufferSegments, segmentSize, numBytesInLastBuffer);
return new InMemoryBufferIterator(recordCount, beginRow, offset, recordBuffer);
}
/**
* Iterator of in memory buffer.
*/
public class InMemoryBufferIterator implements MutableObjectIterator<BinaryRow>, Closeable {
private final int beginRow;
private int nextRow;
private RandomAccessInputView recordBuffer;
private int expectedRecordCount;
private InMemoryBufferIterator(int expectedRecordCount, int beginRow, long offset, RandomAccessInputView recordBuffer) {
this.beginRow = beginRow;
this.recordBuffer = recordBuffer;
reset(expectedRecordCount, offset);
}
public void reset(int expectedRecordCount, long offset) {
this.nextRow = beginRow;
this.expectedRecordCount = expectedRecordCount;
recordBuffer.setReadPosition(offset);
}
@Override
public BinaryRow next(BinaryRow reuse) throws IOException {
try {
if (expectedRecordCount != recordCount) {
throw new ConcurrentModificationException();
}
if (nextRow >= recordCount) {
return null;
}
nextRow++;
return (BinaryRow) serializer.mapFromPages(reuse, recordBuffer);
} catch (EOFException e) {
return null;
}
}
@Override
public BinaryRow next() throws IOException {
throw new RuntimeException("Not support!");
}
@Override
public void close() {
}
}
}
}
|
/**
* Classes of this package represent structure elements of a webpage. We call these elements
* {@link de.edgeway.uiproxy.pagemodel.PageObject "PageObjects"}.
*
* <p>Each <a href="https://github.com/SeleniumHQ/selenium/wiki/PageObjects">PageObject</a>
* represents an entire page or a fraction of the page the user can interact with via the browser.
*
* @author Kai Hoelscher
* @since 0.0.1
*/
package de.edgeway.uiproxy.pagemodel;
|
/*
* Copyright 2008-2013 Hippo B.V. (http://www.onehippo.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.hippoecm.repository;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import javax.jcr.NamespaceException;
import javax.jcr.PropertyType;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.Value;
import javax.jcr.nodetype.NodeDefinition;
import javax.jcr.nodetype.NodeType;
import javax.jcr.nodetype.NodeTypeIterator;
import javax.jcr.nodetype.NodeTypeManager;
import javax.jcr.nodetype.PropertyDefinition;
import javax.jcr.version.OnParentVersionAction;
import org.apache.jackrabbit.core.SessionImpl;
import org.apache.jackrabbit.core.nodetype.NodeTypeImpl;
import org.apache.jackrabbit.spi.QNodeTypeDefinition;
import org.apache.jackrabbit.spi.commons.namespace.NamespaceResolver;
import org.apache.jackrabbit.spi.commons.namespace.SessionNamespaceResolver;
import org.apache.jackrabbit.spi.commons.nodetype.compact.CompactNodeTypeDefWriter;
import org.hippoecm.repository.api.StringCodecFactory;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.onehippo.repository.testutils.RepositoryTestCase;
public class ExportCndTest extends RepositoryTestCase {
@Before
public void setUp() throws Exception {
super.setUp();
}
@After
public void tearDown() throws Exception {
super.tearDown();
}
@Test
public void testJRCndExport() throws RepositoryException {
LinkedHashSet<NodeType> types = getSortedNodeTypes("hippo:");
List<QNodeTypeDefinition> nodeTypeDefs = new ArrayList<QNodeTypeDefinition>();
for (NodeType nt : types) {
nodeTypeDefs.add(((NodeTypeImpl) nt).getDefinition());
}
NamespaceResolver nsRes = new SessionNamespaceResolver(session);
Writer out = new StringWriter();
try {
Session impl = session;
impl = org.hippoecm.repository.decorating.SessionDecorator.unwrap(impl);
CompactNodeTypeDefWriter.write(nodeTypeDefs, nsRes, (SessionImpl)impl, out);
} catch (IOException e) {
e.printStackTrace();
}
/*
* this horrible line is because CompactNodeTypeDefWriter returns _x002a_ for something like:
* - * (String)
*
* For nodes, thus + * (nt:base) it works :S
*/
String cnd = out.toString().replaceAll("_x002a_", "*");
}
@Test
public void testJCROnlyCndExport() throws RepositoryException {
LinkedHashSet<NodeType> types = getSortedNodeTypes("hippo:");
Writer out = new StringWriter();
try {
out = new HippoCompactNodeTypeDefWriter(session).write(types, true);
} catch (IOException e) {
e.printStackTrace();
}
/*
* this horrible line is because CompactNodeTypeDefWriter returns _x002a_ for something like:
* - * (String)
*
* For nodes, thus + * (nt:base) it works :S
*/
String cnd = out.toString();
}
class HippoCompactNodeTypeDefWriter {
private static final String INDENT = " ";
private Writer out;
private Session session;
private Writer nsWriter ;
private Set<String> usedNamespaces = new HashSet<String>();
public HippoCompactNodeTypeDefWriter(Session session) {
this.session = session;
}
public Writer write(LinkedHashSet<NodeType> types, boolean includeNS) throws IOException {
this.out = new StringWriter();;
if(includeNS) {
nsWriter = new StringWriter();
}
for (NodeType nt : types) {
writeName(nt);
writeSupertypes(nt);
writeOptions(nt);
writePropDefs(nt);
writeNodeDefs(nt);
this.out.write("\n\n");
}
if (nsWriter != null) {
nsWriter.write("\n");
this.out.close();
nsWriter.write(((StringWriter) out).getBuffer().toString());
this.out = nsWriter;
nsWriter = null;
}
this.out.flush();
return out;
}
private void writeName(NodeType nt) throws IOException {
out.write("[");
out.write(resolve(nt.getName()));
out.write("]");
}
private void writeSupertypes(NodeType nt) throws IOException {
NodeType[] superTypes = nt.getDeclaredSupertypes();
String delim = " > ";
for (NodeType sn : superTypes) {
out.write(delim);
out.write(resolve(sn.getName()));
delim = ", ";
}
}
private void writeOptions(NodeType nt) throws IOException {
if (nt.hasOrderableChildNodes()) {
out.write("\n" + INDENT);
out.write("orderable");
if (nt.isMixin()) {
out.write(" mixin");
}
} else if (nt.isMixin()) {
out.write("\n" + INDENT);
out.write("mixin");
}
}
private void writePropDefs(NodeType nt) throws IOException {
PropertyDefinition[] propdefs = nt.getDeclaredPropertyDefinitions();
for (PropertyDefinition propdef : propdefs) {
writePropDef(nt, propdef);
}
}
private void writePropDef(NodeType nt, PropertyDefinition pd) throws IOException {
out.write("\n" + INDENT + "- ");
writeItemDefName(pd.getName());
out.write(" (");
out.write(PropertyType.nameFromValue(pd.getRequiredType()).toLowerCase());
out.write(")");
writeDefaultValues(pd.getDefaultValues());
out.write(nt.getPrimaryItemName() != null && nt.getPrimaryItemName().equals(pd.getName()) ? " primary" : "");
if (pd.isMandatory()) {
out.write(" mandatory");
}
if (pd.isAutoCreated()) {
out.write(" autocreated");
}
if (pd.isProtected()) {
out.write(" protected");
}
if (pd.isMultiple()) {
out.write(" multiple");
}
if (pd.getOnParentVersion() != OnParentVersionAction.COPY) {
out.write(" ");
out.write(OnParentVersionAction.nameFromValue(pd.getOnParentVersion()).toLowerCase());
}
writeValueConstraints(pd.getValueConstraints());
}
private void writeNodeDefs(NodeType nt) throws IOException {
NodeDefinition[] childnodeDefs = nt.getDeclaredChildNodeDefinitions();
for ( NodeDefinition childnodeDef : childnodeDefs) {
writeNodeDef(nt, childnodeDef);
}
}
private void writeNodeDef(NodeType nt, NodeDefinition nd) throws IOException {
out.write("\n" + INDENT + "+ ");
String name = nd.getName();
if (name.equals("*")) {
out.write('*');
} else {
writeItemDefName(name);
}
writeRequiredTypes(nd.getRequiredPrimaryTypes());
writeDefaultType(nd.getDefaultPrimaryType());
out.write(nt.getPrimaryItemName() != null && nt.getPrimaryItemName().equals(nd.getName()) ? " primary" : "");
if (nd.isMandatory()) {
out.write(" mandatory");
}
if (nd.isAutoCreated()) {
out.write(" autocreated");
}
if (nd.isProtected()) {
out.write(" protected");
}
if (nd.allowsSameNameSiblings()) {
out.write(" multiple");
}
if (nd.getOnParentVersion() != OnParentVersionAction.COPY) {
out.write(" ");
out.write(OnParentVersionAction.nameFromValue(nd.getOnParentVersion()).toLowerCase());
}
}
private void writeRequiredTypes(NodeType[] reqTypes) throws IOException {
if (reqTypes != null && reqTypes.length > 0) {
String delim = " (";
for (int i = 0; i < reqTypes.length; i++) {
out.write(delim);
out.write(resolve(reqTypes[i].getName()));
delim = ", ";
}
out.write(")");
}
}
/**
* write default types
* @param defType
*/
private void writeDefaultType(NodeType defType) throws IOException {
if (defType != null && !defType.getName().equals("*")) {
out.write(" = ");
out.write(resolve(defType.getName()));
}
}
private void writeValueConstraints(String[] vca) throws IOException {
if (vca != null && vca.length > 0) {
String vc = vca[0];
out.write(" < '");
out.write(escape(vc));
out.write("'");
for (int i = 1; i < vca.length; i++) {
vc = vca[i];
out.write(", '");
out.write(escape(vc));
out.write("'");
}
}
}
private void writeItemDefName(String name) throws IOException {
out.write(resolve(name));
}
private String resolve(String name) throws IOException {
if (name == null) {
return "";
}
if (name.indexOf(":") > -1) {
String prefix = name.substring(0, name.indexOf(":"));
if (!"".equals(prefix)) {
// check for writing namespaces
if (nsWriter != null) {
if (!usedNamespaces.contains(prefix)) {
usedNamespaces.add(prefix);
nsWriter.write("<'");
nsWriter.write(prefix);
nsWriter.write("'='");
// TODO write namespace
try {
nsWriter.write(escape(session.getNamespaceURI(prefix)));
} catch (NamespaceException e) {
e.printStackTrace();
} catch (RepositoryException e) {
e.printStackTrace();
}
nsWriter.write("'>\n");
}
}
prefix += ":";
}
final String localname = name.substring(name.indexOf(":") + 1);
String encLocalName = StringCodecFactory.ISO9075Helper.encodeLocalName(localname);
String resolvedName = prefix + encLocalName;
// check for '-' and '+'
if (resolvedName.indexOf('-') >= 0 || resolvedName.indexOf('+') >= 0) {
return "'" + resolvedName + "'";
} else {
return resolvedName;
}
} else {
return name;
}
}
private String escape(String s) {
StringBuffer sb = new StringBuffer(s);
for (int i = 0; i < sb.length(); i++) {
if (sb.charAt(i) == '\\') {
sb.insert(i, '\\');
i++;
} else if (sb.charAt(i) == '\'') {
sb.insert(i, '\'');
i++;
}
}
return sb.toString();
}
private void writeDefaultValues(Value[] dva) throws IOException {
if (dva != null && dva.length > 0) {
String delim = " = '";
for (int i = 0; i < dva.length; i++) {
out.write(delim);
try {
out.write(escape(dva[i].getString()));
} catch (RepositoryException e) {
out.write(escape(dva[i].toString()));
}
out.write("'");
delim = ", '";
}
}
}
}
private LinkedHashSet<NodeType> getSortedNodeTypes(String namespacePrefix) throws RepositoryException {
NodeTypeManager ntmgr = session.getWorkspace().getNodeTypeManager();
NodeTypeIterator it = ntmgr.getAllNodeTypes();
LinkedHashSet<NodeType> types = new LinkedHashSet<NodeType>();
while (it.hasNext()) {
NodeType nt = (NodeType) it.nextNodeType();
if (nt.getName().startsWith(namespacePrefix)) {
types.add(nt);
}
}
types = sortTypes(types);
return types;
}
private LinkedHashSet<NodeType> sortTypes(LinkedHashSet<NodeType> types) {
return new SortContext(types).sort();
}
class SortContext {
HashSet<NodeType> visited;
LinkedHashSet<NodeType> result;
LinkedHashSet<NodeType> set;
SortContext(LinkedHashSet<NodeType> set) {
this.set = set;
visited = new HashSet<NodeType>();
result = new LinkedHashSet<NodeType>();
}
void visit(NodeType nt) {
if (visited.contains(nt) || !set.contains(nt)) {
return;
}
visited.add(nt);
for (NodeType superType : nt.getSupertypes()) {
visit(superType);
}
for (NodeDefinition nd : nt.getChildNodeDefinitions()) {
visit(nd.getDeclaringNodeType());
}
result.add(nt);
}
LinkedHashSet<NodeType> sort() {
for (NodeType type : set) {
visit(type);
}
return result;
}
}
}
|
/*
* Copyright 2014-2016 Fukurou Mishiranu
*
* 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.mishiranu.dashchan.content.async;
import java.net.HttpURLConnection;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedHashMap;
import android.os.Parcel;
import android.os.Parcelable;
import chan.content.ChanConfiguration;
import chan.content.ChanPerformer;
import chan.content.ExtensionException;
import chan.content.InvalidResponseException;
import chan.content.RedirectException;
import chan.content.ThreadRedirectException;
import chan.content.model.Post;
import chan.content.model.Posts;
import chan.http.HttpException;
import chan.http.HttpHolder;
import chan.http.HttpValidator;
import chan.util.CommonUtils;
import chan.util.StringUtils;
import com.mishiranu.dashchan.content.model.ErrorItem;
import com.mishiranu.dashchan.content.model.PostItem;
import com.mishiranu.dashchan.content.net.YouTubeTitlesReader;
import com.mishiranu.dashchan.preference.Preferences;
import com.mishiranu.dashchan.text.HtmlParser;
import com.mishiranu.dashchan.text.SimilarTextEstimator;
import com.mishiranu.dashchan.util.Log;
public class ReadPostsTask extends HttpHolderTask<Void, Void, Boolean> {
private final Callback callback;
private final String chanName;
private final String boardName;
private final String threadNumber;
private final Posts cachedPosts;
private final HttpValidator validator;
private final boolean forceLoadFullThread;
private final String lastPostNumber;
private final ArrayList<UserPostPending> userPostPendings;
private Result result;
private boolean fullThread = false;
private ArrayList<UserPostPending> removedUserPostPendings;
private RedirectException.Target target;
private ErrorItem errorItem;
public interface Callback {
public void onRequestPreloadPosts(ArrayList<Patch> patches, int oldCount);
public void onReadPostsSuccess(Result result, boolean fullThread,
ArrayList<UserPostPending> removedUserPostPendings);
public void onReadPostsEmpty();
public void onReadPostsRedirect(RedirectException.Target target);
public void onReadPostsFail(ErrorItem errorItem);
}
public ReadPostsTask(Callback callback, String chanName, String boardName, String threadNumber, Posts cachedPosts,
boolean useValidator, boolean forceLoadFullThread, String lastPostNumber,
ArrayList<UserPostPending> userPostPendings) {
this.callback = callback;
this.chanName = chanName;
this.boardName = boardName;
this.threadNumber = threadNumber;
this.cachedPosts = cachedPosts;
this.validator = useValidator && cachedPosts != null ? cachedPosts.getValidator() : null;
this.forceLoadFullThread = forceLoadFullThread;
this.lastPostNumber = lastPostNumber;
this.userPostPendings = userPostPendings.size() > 0 ? userPostPendings : null;
}
@Override
protected Boolean doInBackground(HttpHolder holder, Void... params) {
String lastPostNumber = forceLoadFullThread ? null : this.lastPostNumber;
boolean partialThreadLoading = Preferences.isPartialThreadLoading(chanName) && !forceLoadFullThread;
ChanPerformer performer = ChanPerformer.get(chanName);
try {
ChanPerformer.ReadPostsResult result;
try {
result = performer.safe().onReadPosts(new ChanPerformer.ReadPostsData(boardName, threadNumber,
lastPostNumber, partialThreadLoading, cachedPosts, holder, validator));
} catch (ThreadRedirectException e) {
RedirectException.Target target = e.obtainTarget(chanName, boardName);
if (target == null) {
throw HttpException.createNotFoundException();
}
this.target = target;
return true;
} catch (RedirectException e) {
RedirectException.Target target = e.obtainTarget(chanName);
if (target == null) {
throw HttpException.createNotFoundException();
}
if (!chanName.equals(target.chanName) || target.threadNumber == null) {
Log.persistent().write(Log.TYPE_ERROR, Log.DISABLE_QUOTES,
"Only local thread redirects available there");
errorItem = new ErrorItem(ErrorItem.TYPE_INVALID_DATA_FORMAT);
return false;
} else if (StringUtils.equals(boardName, target.boardName) &&
threadNumber.equals(target.threadNumber)) {
throw HttpException.createNotFoundException();
} else {
this.target = target;
return true;
}
}
Posts readPosts = result != null ? result.posts : null;
HttpValidator validator = result != null ? result.validator : null;
if (result != null && result.fullThread) {
partialThreadLoading = false;
}
if (readPosts != null && readPosts.length() > 0) {
// Remove repeatings and sort
Post[] posts = readPosts.getPosts();
LinkedHashMap<String, Post> postsMap = new LinkedHashMap<>();
for (Post post : readPosts.getPosts()) {
String postNumber = post.getPostNumber();
postsMap.put(postNumber, post);
}
if (postsMap.size() != posts.length) {
posts = CommonUtils.toArray(postsMap.values(), Post.class);
}
Arrays.sort(posts);
readPosts.setPosts(posts);
// Validate model data format
Post firstPost = cachedPosts != null ? cachedPosts.getPosts()[0] : posts[0];
String firstPostNumber = firstPost.getPostNumber();
if (firstPostNumber == null) {
Log.persistent().write(Log.TYPE_ERROR, Log.DISABLE_QUOTES, "The getPostNumber() method of",
"original post returned null.");
errorItem = new ErrorItem(ErrorItem.TYPE_INVALID_DATA_FORMAT);
return false;
}
if (firstPost.getParentPostNumberOrNull() != null) {
Log.persistent().write(Log.TYPE_ERROR, Log.DISABLE_QUOTES, "The getParentPostNumber() method of",
"original post must return null, \"0\" or post number.");
errorItem = new ErrorItem(ErrorItem.TYPE_INVALID_DATA_FORMAT);
return false;
}
boolean resultWithOriginalPost = posts[0].getPostNumber().equals(firstPostNumber);
for (int i = 0; i < posts.length; i++) {
Post post = posts[i];
String postNumber = post.getPostNumber();
if (postNumber == null) {
Log.persistent().write(Log.TYPE_ERROR, Log.DISABLE_QUOTES, "The getPostNumber() method of", i,
"post returned null.");
errorItem = new ErrorItem(ErrorItem.TYPE_INVALID_DATA_FORMAT);
return false;
}
if (!threadNumber.equals(post.getThreadNumberOrOriginalPostNumber())) {
Log.persistent().write(Log.TYPE_ERROR, Log.DISABLE_QUOTES, "The number of requested thread and",
"number of thread in post", postNumber, "are not equal.");
errorItem = new ErrorItem(ErrorItem.TYPE_INVALID_DATA_FORMAT);
return false;
}
if (!resultWithOriginalPost || i > 0) {
if (!firstPostNumber.equals(post.getParentPostNumberOrNull())) {
Log.persistent().write(Log.TYPE_ERROR, Log.DISABLE_QUOTES, "The getParentPostNumber()",
"method of post", postNumber, "is not equal to original post's number.");
errorItem = new ErrorItem(ErrorItem.TYPE_INVALID_DATA_FORMAT);
return false;
}
}
}
}
Result handleResult = null;
boolean fullThread = false;
if (cachedPosts != null) {
boolean partial = partialThreadLoading && lastPostNumber != null;
handleResult = mergePosts(cachedPosts, readPosts, partial);
} else if (readPosts != null && readPosts.length() > 0) {
Post[] readPostsArray = readPosts.getPosts();
ArrayList<Patch> patches = new ArrayList<>();
for (int i = 0; i < readPostsArray.length; i++) {
patches.add(new Patch(readPostsArray[i], null, i, false, true));
}
handleResult = new Result(readPostsArray.length, 0, false, readPosts, patches, false);
fullThread = true;
}
if (handleResult != null) {
if (!handleResult.patches.isEmpty()) {
if (userPostPendings != null) {
ArrayList<UserPostPending> workUserPostPendings = new ArrayList<>(userPostPendings);
OUTER: for (int i = handleResult.patches.size() - 1; i >= 0; i--) {
Post post = handleResult.patches.get(i).newPost;
for (int j = workUserPostPendings.size() - 1; j >= 0; j--) {
UserPostPending userPostPending = workUserPostPendings.get(j);
if (userPostPending.isUserPost(post)) {
post.setUserPost(true);
workUserPostPendings.remove(j);
if (removedUserPostPendings == null) {
removedUserPostPendings = new ArrayList<>();
}
removedUserPostPendings.add(userPostPending);
if (workUserPostPendings.isEmpty()) {
break OUTER;
}
}
}
}
}
ArrayList<Post> handlePosts = new ArrayList<>();
for (Patch patch : handleResult.patches) {
handlePosts.add(patch.newPost);
}
YouTubeTitlesReader.getInstance().readAndApplyIfNecessary(handlePosts, holder);
}
for (Patch patch : handleResult.patches) {
patch.postItem = new PostItem(patch.newPost, chanName, boardName);
}
callback.onRequestPreloadPosts(handleResult.patches, cachedPosts != null ? cachedPosts.length() : 0);
if (validator == null) {
validator = holder.getValidator();
}
if (validator == null && cachedPosts != null) {
validator = cachedPosts.getValidator();
}
handleResult.posts.setValidator(validator);
this.result = handleResult;
this.fullThread = fullThread;
}
return true;
} catch (HttpException e) {
int responseCode = e.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_NOT_MODIFIED) {
return true;
}
if (responseCode == HttpURLConnection.HTTP_NOT_FOUND ||
responseCode == HttpURLConnection.HTTP_GONE) {
if (ChanConfiguration.get(chanName).getOption(ChanConfiguration.OPTION_READ_SINGLE_POST)) {
try {
ChanPerformer.ReadSinglePostResult result = performer.safe().onReadSinglePost
(new ChanPerformer.ReadSinglePostData(boardName, threadNumber, holder));
Post post = result != null ? result.post : null;
String threadNumber = post.getThreadNumberOrOriginalPostNumber();
if (threadNumber != null && !threadNumber.equals(this.threadNumber)) {
// noinspection ThrowableResultOfMethodCallIgnored
target = RedirectException.toThread(boardName, threadNumber, post.getPostNumber())
.obtainTarget(chanName);
return true;
}
} catch (ExtensionException | HttpException | InvalidResponseException e2) {
// Ignore exception
}
}
errorItem = new ErrorItem(ErrorItem.TYPE_THREAD_NOT_EXISTS);
} else {
errorItem = e.getErrorItemAndHandle();
}
return false;
} catch (ExtensionException | InvalidResponseException e) {
errorItem = e.getErrorItemAndHandle();
return false;
} finally {
ChanConfiguration.get(chanName).commit();
}
}
@Override
public void onPostExecute(Boolean success) {
if (success) {
if (result != null) {
callback.onReadPostsSuccess(result, fullThread, removedUserPostPendings);
} else if (target != null) {
callback.onReadPostsRedirect(target);
} else {
callback.onReadPostsEmpty();
}
} else {
callback.onReadPostsFail(errorItem);
}
}
public static class Patch {
public final Post newPost;
public final Post oldPost;
public PostItem postItem;
public final int index;
public final boolean replaceAtIndex;
public final boolean newPostAddedToEnd;
public Patch(Post newPost, Post oldPost, int index, boolean replaceAtIndex, boolean newPostAddedToEnd) {
this.newPost = newPost;
this.oldPost = oldPost;
this.index = index;
this.replaceAtIndex = replaceAtIndex;
this.newPostAddedToEnd = newPostAddedToEnd;
}
public Patch(PostItem postItem, int index) {
newPost = postItem.getPost();
oldPost = null;
this.postItem = postItem;
this.index = index;
replaceAtIndex = false;
newPostAddedToEnd = true;
}
}
public static class Result {
public final int newCount, deletedCount;
public final boolean hasEdited;
public final Posts posts;
public final ArrayList<Patch> patches;
public final boolean fieldsUpdated;
public Result(int newCount, int deletedCount, boolean hasEdited, Posts posts,
ArrayList<Patch> patches, boolean fieldsUpdated) {
this.newCount = newCount;
this.deletedCount = deletedCount;
this.hasEdited = hasEdited;
this.posts = posts;
this.patches = patches;
this.fieldsUpdated = fieldsUpdated;
}
}
private static Result mergePosts(Posts cachedPosts, Posts loadedPosts, boolean partial) {
int newCount = 0;
int deletedCount = 0;
boolean hasEdited = false;
ArrayList<Patch> patches = new ArrayList<>();
if (loadedPosts != null && loadedPosts.length() > 0) {
Post[] cachedPostsArray = cachedPosts.getPosts();
Post[] loadedPostsArray = loadedPosts.getPosts();
int resultSize = 0;
int i = 0, j = 0;
int ic = cachedPostsArray.length, jc = loadedPostsArray.length;
while (i < ic || j < jc) {
Post oldPost = i < ic ? cachedPostsArray[i] : null;
Post newPost = j < jc ? loadedPostsArray[j] : null;
int result;
if (oldPost == null) {
result = 1;
} else if (newPost == null) {
result = -1;
} else {
result = oldPost.compareTo(newPost);
}
if (result < 0) {
// Number of new post is greater
// So add old post to array and mark it as deleted, if downloading was not partial
if (!partial && !oldPost.isDeleted()) {
Post postBeforeCopy = oldPost;
// Copying will reset client internal flags in model
oldPost = oldPost.copy().setDeleted(true);
deletedCount++;
patches.add(new Patch(oldPost, postBeforeCopy, resultSize, true, false));
hasEdited = true;
}
resultSize++;
i++;
} else if (result > 0) {
// Number of old post is greater
// It's a new post. May be it will be inserted in center of list.
boolean addToEnd = oldPost == null;
patches.add(new Patch(newPost, null, resultSize, false, addToEnd));
resultSize++;
if (addToEnd) {
newCount++;
} else {
hasEdited = true;
}
j++;
} else {
// Post numbers are equal
if (!oldPost.contentEquals(newPost) || oldPost.isDeleted()) {
hasEdited = true;
patches.add(new Patch(newPost, oldPost, resultSize, true, false));
resultSize++;
} else {
// Keep old model if no changes, because PostItem bound to old PostModel
resultSize++;
}
i++;
j++;
}
}
}
Post[] postsArray = cachedPosts.getPosts();
if (!patches.isEmpty()) {
ArrayList<Post> newPosts = new ArrayList<>();
if (postsArray != null) {
Collections.addAll(newPosts, postsArray);
}
for (int i = 0; i < patches.size(); i++) {
Patch patch = patches.get(i);
if (patch.replaceAtIndex) {
newPosts.set(patch.index, patch.newPost);
} else {
newPosts.add(patch.index, patch.newPost);
}
}
postsArray = CommonUtils.toArray(newPosts, Post.class);
}
Posts resultPosts = new Posts(postsArray);
resultPosts.setArchivedThreadUriString(cachedPosts.getArchivedThreadUriString());
resultPosts.setUniquePosters(cachedPosts.getUniquePosters());
// The rest model fields must be updated in main thread
boolean fieldsUpdated = false;
if (loadedPosts != null) {
String archivedThreadUriString = loadedPosts.getArchivedThreadUriString();
if (archivedThreadUriString != null && !archivedThreadUriString
.equals(resultPosts.getArchivedThreadUriString())) {
resultPosts.setArchivedThreadUriString(archivedThreadUriString);
fieldsUpdated = true;
}
int uniquePosters = loadedPosts.getUniquePosters();
if (uniquePosters > 0 && uniquePosters != resultPosts.getUniquePosters()) {
resultPosts.setUniquePosters(uniquePosters);
fieldsUpdated = true;
}
}
if (patches.isEmpty() && !fieldsUpdated) {
return null;
}
return new Result(newCount, deletedCount, hasEdited, resultPosts, patches, fieldsUpdated);
}
public interface UserPostPending extends Parcelable {
public boolean isUserPost(Post post);
}
public static class PostNumberUserPostPending implements UserPostPending {
private final String postNumber;
public PostNumberUserPostPending(String postNumber) {
this.postNumber = postNumber;
}
@Override
public boolean isUserPost(Post post) {
return postNumber.equals(post.getPostNumber());
}
@Override
public boolean equals(Object o) {
if (o == this) {
return true;
}
if (o instanceof PostNumberUserPostPending) {
return ((PostNumberUserPostPending) o).postNumber.equals(postNumber);
}
return false;
}
@Override
public int hashCode() {
return postNumber.hashCode();
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(postNumber);
}
public static final Creator<PostNumberUserPostPending> CREATOR = new Creator<PostNumberUserPostPending>() {
@Override
public PostNumberUserPostPending[] newArray(int size) {
return new PostNumberUserPostPending[size];
}
@Override
public PostNumberUserPostPending createFromParcel(Parcel source) {
String postNumber = source.readString();
return new PostNumberUserPostPending(postNumber);
}
};
}
public static class NewThreadUserPostPending implements UserPostPending {
@Override
public boolean isUserPost(Post post) {
return post.getParentPostNumberOrNull() == null;
}
@Override
public boolean equals(Object o) {
if (o == this) {
return true;
}
if (o instanceof NewThreadUserPostPending) {
return true;
}
return false;
}
@Override
public int hashCode() {
return 1;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {}
public static final Creator<NewThreadUserPostPending> CREATOR = new Creator<NewThreadUserPostPending>() {
@Override
public NewThreadUserPostPending[] newArray(int size) {
return new NewThreadUserPostPending[size];
}
@Override
public NewThreadUserPostPending createFromParcel(Parcel source) {
return new NewThreadUserPostPending();
}
};
}
public static class CommentUserPostPending implements UserPostPending {
private static final SimilarTextEstimator ESTIMATOR = new SimilarTextEstimator(Integer.MAX_VALUE, true);
private final SimilarTextEstimator.WordsData wordsData;
public CommentUserPostPending(String comment) {
this(ESTIMATOR.getWords(comment));
}
private CommentUserPostPending(SimilarTextEstimator.WordsData wordsData) {
this.wordsData = wordsData;
}
@Override
public boolean isUserPost(Post post) {
String comment = HtmlParser.clear(post.getComment());
SimilarTextEstimator.WordsData wordsData = ESTIMATOR.getWords(comment);
return ESTIMATOR.checkSimiliar(this.wordsData, wordsData) || this.wordsData == null && wordsData == null;
}
@Override
public boolean equals(Object o) {
if (o == this) {
return true;
}
if (o instanceof CommentUserPostPending) {
CommentUserPostPending co = (CommentUserPostPending) o;
return co.wordsData == wordsData || co.wordsData != null && wordsData != null
&& co.wordsData.count == wordsData.count && co.wordsData.words.equals(wordsData.words);
}
return false;
}
@Override
public int hashCode() {
int prime = 31;
int result = 1;
if (wordsData != null) {
result = prime * result + wordsData.words.hashCode();
result = prime * result + wordsData.count;
}
return result;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeSerializable(wordsData != null ? wordsData.words : null);
dest.writeInt(wordsData != null ? wordsData.count : 0);
}
public static final Creator<CommentUserPostPending> CREATOR = new Creator<CommentUserPostPending>() {
@Override
public CommentUserPostPending[] newArray(int size) {
return new CommentUserPostPending[size];
}
@Override
public CommentUserPostPending createFromParcel(Parcel source) {
@SuppressWarnings("unchecked")
HashSet<String> words = (HashSet<String>) source.readSerializable();
int count = source.readInt();
return new CommentUserPostPending(words != null && count > 0
? new SimilarTextEstimator.WordsData(words, count) : null);
}
};
}
}
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.microsoft.azure.cognitiveservices.inkrecognizer;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
public enum ServiceVersion {
/**
* Version 1.0.0 of the preview
*/
PREVIEW_1_0_0("/v1.0-preview/recognize");
private String serviceVersionString;
private static final Map<String, ServiceVersion> MAP = new HashMap<>();
static {
for (ServiceVersion serviceVersion : ServiceVersion.values()) {
MAP.put(serviceVersion.toString().toLowerCase(Locale.getDefault()), serviceVersion);
}
}
ServiceVersion(String serviceVersionString) {
this.serviceVersionString = serviceVersionString;
}
static ServiceVersion getServiceVersionOrDefault(String serviceVersionString) {
if (serviceVersionString != null && MAP.containsKey(serviceVersionString.toLowerCase(Locale.getDefault()))) {
return MAP.get(serviceVersionString.toLowerCase(Locale.getDefault()));
} else {
return PREVIEW_1_0_0;
}
}
@Override
public String toString() {
return serviceVersionString;
}
}
|
package scenarios;
import io.appium.java_client.AppiumDriver;
public class AppiumBaseClass {
protected AppiumDriver driver() {
return AppiumController.instance.driver;
}
}
|
package mobileapp.ctemplar.com.ctemplarapp.repository.provider;
import com.google.gson.annotations.SerializedName;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import mobileapp.ctemplar.com.ctemplarapp.net.request.messages.SendMessageRequest;
public class SendMessageRequestProvider {
@SerializedName("sender")
private String sender;
@SerializedName("subject")
private String subject;
@SerializedName("content")
private String content;
@SerializedName("receiver")
private List<String> receivers;
@SerializedName("cc")
private List<String> cc;
@SerializedName("bcc")
private List<String> bcc;
@SerializedName("folder")
private String folder;
@SerializedName("destruct_date")
private Date destructDate;
@SerializedName("delayed_delivery")
private Date delayedDelivery;
@SerializedName("dead_man_duration")
private Long deadManDuration;
@SerializedName("send")
private boolean send;
@SerializedName("is_encrypted")
private boolean isEncrypted;
@SerializedName("is_html")
private boolean isHtml;
@SerializedName("is_subject_encrypted")
private boolean isSubjectEncrypted;
@SerializedName("mailbox")
private long mailbox;
@SerializedName("last_action")
private String lastAction;
@SerializedName("parent")
private Long parent;
public SendMessageRequestProvider() {
}
public SendMessageRequestProvider(String sender,
String content,
ArrayList<String> receivers,
ArrayList<String> cc,
ArrayList<String> bcc,
String folder,
long mailbox) {
this.sender = sender;
this.content = content;
this.receivers = receivers;
this.cc = cc;
this.bcc = bcc;
this.folder = folder;
this.mailbox = mailbox;
}
public String getSender() {
return sender;
}
public void setSender(String sender) {
this.sender = sender;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public List<String> getReceivers() {
return receivers;
}
public void setReceivers(List<String> receivers) {
this.receivers = receivers;
}
public List<String> getCc() {
return cc;
}
public void setCc(List<String> cc) {
this.cc = cc;
}
public List<String> getBcc() {
return bcc;
}
public void setBcc(List<String> bcc) {
this.bcc = bcc;
}
public String getFolder() {
return folder;
}
public void setFolder(String folder) {
this.folder = folder;
}
public Date getDestructDate() {
return destructDate;
}
public void setDestructDate(Date destructDate) {
this.destructDate = destructDate;
}
public Date getDelayedDelivery() {
return delayedDelivery;
}
public void setDelayedDelivery(Date delayedDelivery) {
this.delayedDelivery = delayedDelivery;
}
public Long getDeadManDuration() {
return deadManDuration;
}
public void setDeadManDuration(Long deadManDuration) {
this.deadManDuration = deadManDuration;
}
public boolean isSend() {
return send;
}
public void setSend(boolean send) {
this.send = send;
}
public boolean isEncrypted() {
return isEncrypted;
}
public void setEncrypted(boolean encrypted) {
isEncrypted = encrypted;
}
public boolean isHtml() {
return isHtml;
}
public void setHtml(boolean html) {
isHtml = html;
}
public boolean isSubjectEncrypted() {
return isSubjectEncrypted;
}
public void setSubjectEncrypted(boolean subjectEncrypted) {
isSubjectEncrypted = subjectEncrypted;
}
public long getMailbox() {
return mailbox;
}
public void setMailbox(long mailbox) {
this.mailbox = mailbox;
}
public String getLastAction() {
return lastAction;
}
public void setLastAction(String lastAction) {
this.lastAction = lastAction;
}
public Long getParent() {
return parent;
}
public void setParent(Long parent) {
this.parent = parent;
}
public SendMessageRequest toRequest() {
SendMessageRequest request = new SendMessageRequest();
request.setSender(getSender());
request.setSubject(getSubject());
request.setContent(getContent());
request.setReceivers(getReceivers());
request.setCc(getCc());
request.setBcc(getBcc());
request.setFolder(getFolder());
request.setDestructDate(getDestructDate());
request.setDelayedDelivery(getDelayedDelivery());
request.setDeadManDuration(getDeadManDuration());
request.setSend(isSend());
request.setEncrypted(isEncrypted());
request.setHtml(isHtml());
request.setSubjectEncrypted(isSubjectEncrypted());
request.setMailbox(getMailbox());
request.setLastAction(getLastAction());
request.setParent(getParent());
return request;
}
}
|
/*
* 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.linkis.filesystem.conf;
import org.apache.linkis.common.conf.CommonVars;
import org.apache.linkis.common.conf.CommonVars$;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class WorkSpaceConfiguration {
public static final CommonVars<String> LOCAL_USER_ROOT_PATH = CommonVars$.MODULE$.apply("wds.linkis.filesystem.root.path", "file:///tmp/linkis/");
public static final CommonVars<String> HDFS_USER_ROOT_PATH_PREFIX = CommonVars$.MODULE$.apply("wds.linkis.filesystem.hdfs.root.path", "hdfs:///tmp/");
public static final CommonVars<String> HDFS_USER_ROOT_PATH_SUFFIX = CommonVars$.MODULE$.apply("wds.linkis.workspace.filesystem.hdfsuserrootpath.suffix", "/linkis/");
public static final CommonVars<Boolean> RESULT_SET_DOWNLOAD_IS_LIMIT = CommonVars$.MODULE$.apply("wds.linkis.workspace.resultset.download.is.limit", true);
public static final CommonVars<Integer> RESULT_SET_DOWNLOAD_MAX_SIZE_CSV = CommonVars$.MODULE$.apply("wds.linkis.workspace.resultset.download.maxsize.csv", 5000);
public static final CommonVars<Integer> RESULT_SET_DOWNLOAD_MAX_SIZE_EXCEL = CommonVars$.MODULE$.apply("wds.linkis.workspace.resultset.download.maxsize.excel", 5000);
public static final CommonVars<Long> FILESYSTEM_GET_TIMEOUT = CommonVars$.MODULE$.apply("wds.linkis.workspace.filesystem.get.timeout", 10000L);
public static final CommonVars<Integer> FILESYSTEM_FS_THREAD_NUM = CommonVars$.MODULE$.apply("wds.linkis.workspace.filesystem.thread.num", 10);
public static final CommonVars<Integer> FILESYSTEM_FS_THREAD_CACHE = CommonVars$.MODULE$.apply("wds.linkis.workspace.filesystem.thread.cache", 1000);
public static final CommonVars<Boolean> FILESYSTEM_PATH_CHECK_TRIGGER = CommonVars$.MODULE$.apply("wds.linkis.workspace.filesystem.path.check", false);
public static final CommonVars<String> FILESYSTEM_LOG_ADMIN = CommonVars$.MODULE$.apply("wds.linkis.governance.station.admin", "hadoop");
public static final CommonVars<Boolean> FILESYSTEM_PATH_CHECK_OWNER= CommonVars$.MODULE$.apply("wds.linkis.workspace.filesystem.owner.check", false);
public static final ExecutorService executorService =
new ThreadPoolExecutor(FILESYSTEM_FS_THREAD_NUM.getValue(), FILESYSTEM_FS_THREAD_NUM.getValue(), 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(FILESYSTEM_FS_THREAD_CACHE.getValue()));
}
|
package com.applandeo.materialcalendarview.utils;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.support.v4.content.ContextCompat;
import com.annimon.stream.Stream;
import com.applandeo.materialcalendarview.CalendarView;
import com.applandeo.materialcalendarview.EventDay;
import com.applandeo.materialcalendarview.R;
import com.applandeo.materialcalendarview.exceptions.ErrorsMessages;
import com.applandeo.materialcalendarview.exceptions.UnsupportedMethodsException;
import com.applandeo.materialcalendarview.listeners.OnCalendarPageChangeListener;
import com.applandeo.materialcalendarview.listeners.OnDayClickListener;
import com.applandeo.materialcalendarview.listeners.OnSelectDateListener;
import com.applandeo.materialcalendarview.listeners.OnSelectionAbilityListener;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
/**
* This class contains all properties of the calendar
* <p>
* Created by Mateusz Kornakiewicz on 30.10.2017.
*/
public class CalendarProperties {
/**
* A number of months (pages) in the calendar
* 2401 months means 1200 months (100 years) before and 1200 months after the current month
*/
public static final int CALENDAR_SIZE = 2401;
public static final int FIRST_VISIBLE_PAGE = CALENDAR_SIZE / 2;
private int mCalendarType, mHeaderColor, mHeaderLabelColor, mSelectionColor, mTodayLabelColor,
mDialogButtonsColor, mItemLayoutResource, mDisabledDaysLabelsColor, mPagesColor,
mAbbreviationsBarColor, mAbbreviationsLabelsColor, mDaysLabelsColor, mSelectionLabelColor,
mAnotherMonthsDaysLabelsColor, mHeaderVisibility;
private boolean mEventsEnabled;
private Drawable mPreviousButtonSrc, mForwardButtonSrc;
private Calendar mFirstPageCalendarDate = DateUtils.getCalendar();
private Calendar mCalendar, mMinimumDate, mMaximumDate;
private OnDayClickListener mOnDayClickListener;
private OnSelectDateListener mOnSelectDateListener;
private OnSelectionAbilityListener mOnSelectionAbilityListener;
private OnCalendarPageChangeListener mOnPreviousPageChangeListener;
private OnCalendarPageChangeListener mOnForwardPageChangeListener;
private List<EventDay> mEventDays = new ArrayList<>();
private List<Calendar> mDisabledDays = new ArrayList<>();
private List<SelectedDay> mSelectedDays = new ArrayList<>();
private Context mContext;
public CalendarProperties(Context context) {
mContext = context;
}
public int getCalendarType() {
return mCalendarType;
}
public void setCalendarType(int calendarType) {
mCalendarType = calendarType;
}
public boolean getEventsEnabled() {
return mEventsEnabled;
}
public void setEventsEnabled(boolean eventsEnabled) {
mEventsEnabled = eventsEnabled;
}
public Calendar getCalendar() {
return mCalendar;
}
public void setCalendar(Calendar calendar) {
mCalendar = calendar;
}
public OnSelectDateListener getOnSelectDateListener() {
return mOnSelectDateListener;
}
public void setOnSelectDateListener(OnSelectDateListener onSelectDateListener) {
mOnSelectDateListener = onSelectDateListener;
}
public int getHeaderColor() {
if (mHeaderColor <= 0) {
return mHeaderColor;
}
return ContextCompat.getColor(mContext, mHeaderColor);
}
public void setHeaderColor(int headerColor) {
mHeaderColor = headerColor;
}
public int getHeaderLabelColor() {
if (mHeaderLabelColor <= 0) {
return mHeaderLabelColor;
}
return ContextCompat.getColor(mContext, mHeaderLabelColor);
}
public void setHeaderLabelColor(int headerLabelColor) {
mHeaderLabelColor = headerLabelColor;
}
public Drawable getPreviousButtonSrc() {
return mPreviousButtonSrc;
}
public void setPreviousButtonSrc(Drawable previousButtonSrc) {
mPreviousButtonSrc = previousButtonSrc;
}
public Drawable getForwardButtonSrc() {
return mForwardButtonSrc;
}
public void setForwardButtonSrc(Drawable forwardButtonSrc) {
mForwardButtonSrc = forwardButtonSrc;
}
public int getSelectionColor() {
if (mSelectionColor == 0) {
return ContextCompat.getColor(mContext, R.color.defaultColor);
}
return mSelectionColor;
}
public void setSelectionColor(int selectionColor) {
mSelectionColor = selectionColor;
}
public int getTodayLabelColor() {
if (mTodayLabelColor == 0) {
return ContextCompat.getColor(mContext, R.color.defaultColor);
}
return mTodayLabelColor;
}
public void setTodayLabelColor(int todayLabelColor) {
mTodayLabelColor = todayLabelColor;
}
public int getDialogButtonsColor() {
return mDialogButtonsColor;
}
public void setDialogButtonsColor(int dialogButtonsColor) {
mDialogButtonsColor = dialogButtonsColor;
}
public Calendar getMinimumDate() {
return mMinimumDate;
}
public void setMinimumDate(Calendar minimumDate) {
mMinimumDate = minimumDate;
}
public Calendar getMaximumDate() {
return mMaximumDate;
}
public void setMaximumDate(Calendar maximumDate) {
mMaximumDate = maximumDate;
}
public OnSelectionAbilityListener getOnSelectionAbilityListener() {
return mOnSelectionAbilityListener;
}
public void setOnSelectionAbilityListener(OnSelectionAbilityListener onSelectionAbilityListener) {
mOnSelectionAbilityListener = onSelectionAbilityListener;
}
public int getItemLayoutResource() {
return mItemLayoutResource;
}
public void setItemLayoutResource(int itemLayoutResource) {
mItemLayoutResource = itemLayoutResource;
}
public OnCalendarPageChangeListener getOnPreviousPageChangeListener() {
return mOnPreviousPageChangeListener;
}
public void setOnPreviousPageChangeListener(OnCalendarPageChangeListener onPreviousButtonClickListener) {
mOnPreviousPageChangeListener = onPreviousButtonClickListener;
}
public OnCalendarPageChangeListener getOnForwardPageChangeListener() {
return mOnForwardPageChangeListener;
}
public void setOnForwardPageChangeListener(OnCalendarPageChangeListener onForwardButtonClickListener) {
mOnForwardPageChangeListener = onForwardButtonClickListener;
}
public Calendar getFirstPageCalendarDate() {
return mFirstPageCalendarDate;
}
public OnDayClickListener getOnDayClickListener() {
return mOnDayClickListener;
}
public void setOnDayClickListener(OnDayClickListener onDayClickListener) {
mOnDayClickListener = onDayClickListener;
}
public List<EventDay> getEventDays() {
return mEventDays;
}
public void setEventDays(List<EventDay> eventDays) {
mEventDays = eventDays;
}
public List<Calendar> getDisabledDays() {
return mDisabledDays;
}
public void setDisabledDays(List<Calendar> disabledDays) {
mSelectedDays.removeAll(disabledDays);
mDisabledDays = Stream.of(disabledDays)
.map(calendar -> {
DateUtils.setMidnight(calendar);
return calendar;
}).toList();
}
public List<SelectedDay> getSelectedDays() {
return mSelectedDays;
}
public void setSelectedDay(Calendar calendar) {
setSelectedDay(new SelectedDay(calendar));
}
public void setSelectedDay(SelectedDay selectedDay) {
mSelectedDays.clear();
mSelectedDays.add(selectedDay);
}
public void setSelectedDays(List<Calendar> selectedDays) {
if (mCalendarType == CalendarView.ONE_DAY_PICKER) {
throw new UnsupportedMethodsException(ErrorsMessages.ONE_DAY_PICKER_MULTIPLE_SELECTION);
}
if(mCalendarType == CalendarView.RANGE_PICKER && !DateUtils.isFullDatesRange(selectedDays)){
throw new UnsupportedMethodsException(ErrorsMessages.RANGE_PICKER_NOT_RANGE);
}
mSelectedDays = Stream.of(selectedDays)
.map(calendar -> {
DateUtils.setMidnight(calendar);
return new SelectedDay(calendar);
}).filterNot(value -> mDisabledDays.contains(value.getCalendar()))
.toList();
}
public int getDisabledDaysLabelsColor() {
if (mDisabledDaysLabelsColor == 0) {
return ContextCompat.getColor(mContext, R.color.nextMonthDayColor);
}
return mDisabledDaysLabelsColor;
}
public void setDisabledDaysLabelsColor(int disabledDaysLabelsColor) {
mDisabledDaysLabelsColor = disabledDaysLabelsColor;
}
public int getPagesColor() {
return mPagesColor;
}
public void setPagesColor(int pagesColor) {
mPagesColor = pagesColor;
}
public int getAbbreviationsBarColor() {
return mAbbreviationsBarColor;
}
public void setAbbreviationsBarColor(int abbreviationsBarColor) {
mAbbreviationsBarColor = abbreviationsBarColor;
}
public int getAbbreviationsLabelsColor() {
return mAbbreviationsLabelsColor;
}
public void setAbbreviationsLabelsColor(int abbreviationsLabelsColor) {
mAbbreviationsLabelsColor = abbreviationsLabelsColor;
}
public int getDaysLabelsColor() {
if (mDaysLabelsColor == 0) {
return ContextCompat.getColor(mContext, R.color.currentMonthDayColor);
}
return mDaysLabelsColor;
}
public void setDaysLabelsColor(int daysLabelsColor) {
mDaysLabelsColor = daysLabelsColor;
}
public int getSelectionLabelColor() {
if (mSelectionLabelColor == 0) {
return ContextCompat.getColor(mContext, android.R.color.white);
}
return mSelectionLabelColor;
}
public void setSelectionLabelColor(int selectionLabelColor) {
mSelectionLabelColor = selectionLabelColor;
}
public int getAnotherMonthsDaysLabelsColor() {
if (mAnotherMonthsDaysLabelsColor == 0) {
return ContextCompat.getColor(mContext, R.color.nextMonthDayColor);
}
return mAnotherMonthsDaysLabelsColor;
}
public void setAnotherMonthsDaysLabelsColor(int anotherMonthsDaysLabelsColor) {
mAnotherMonthsDaysLabelsColor = anotherMonthsDaysLabelsColor;
}
public int getHeaderVisibility() {
return mHeaderVisibility;
}
public void setHeaderVisibility(int headerVisibility) {
mHeaderVisibility = headerVisibility;
}
}
|
class Test {
void test(String s) {
boolean r;
r = s.indexOf("substring") == -1;
r = s.indexOf("substring") != -1;
r = s.indexOf("substring") > -1;
r = -1 < s.indexOf("substring");
r = s.indexOf("substring") <= -1;
r = -1 >= s.indexOf("substring");
r = s.indexOf("substring") >= 0;
r = 0 <= s.indexOf("substring");
r = s.indexOf("substring") < 0;
r = 0 > s.indexOf("substring");
r = s.lastIndexOf("substring") == -1;
r = s.lastIndexOf("substring") != -1;
r = s.lastIndexOf("substring") > -1;
r = s.lastIndexOf("substring") <= -1;
r = s.lastIndexOf("substring") >= 0;
r = s.lastIndexOf("substring") < 0;
}
void testCorrect(String s) {
boolean r;
// Use custom start index
r = s.indexOf("substring", 1) == -1;
r = s.lastIndexOf("substring", 1) == -1;
// Check for code points
r = s.indexOf('a') == -1;
r = s.lastIndexOf('a') == -1;
// Use different compared index
r = s.indexOf("substring") != 5;
r = s.indexOf("substring") > 0;
r = s.indexOf("substring") <= 0;
}
}
|
package com.pizzaiolo.application.dtos;
import java.math.BigDecimal;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.pizzaiolo.domains.entities.Pizza;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Value;
@Value
@ApiModel(value = "Pizzas cortas", description = "Version corta de las pizzas.")
public class PizzaShortDTO {
@JsonProperty("idPizza")
@ApiModelProperty(value = "Identificador de la pizza.")
private int idPizza;
@JsonProperty("description")
@ApiModelProperty(value = "Descripción de la pizza.")
private String description;
@JsonProperty("amount")
@ApiModelProperty(value = "Coste total de la pizza.")
private BigDecimal amount;
public static PizzaShortDTO from(Pizza source) {
return new PizzaShortDTO(
source.getIdPizza(),
source.getDescription(),
source.getAmount());
}
}
|
package thierry.guessinggame;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("thierry.guessinggame", appContext.getPackageName());
}
}
|
// This is a generated file. Not intended for manual editing.
package com.neueda.jetbrains.plugin.graphdb.language.cypher.psi.impl;
import java.util.List;
import org.jetbrains.annotations.*;
import com.intellij.lang.ASTNode;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiElementVisitor;
import com.intellij.psi.util.PsiTreeUtil;
import static com.neueda.jetbrains.plugin.graphdb.language.cypher.psi.CypherTypes.*;
import com.intellij.extapi.psi.ASTWrapperPsiElement;
import com.neueda.jetbrains.plugin.graphdb.language.cypher.psi.*;
public class CypherRightArrowHeadImpl extends ASTWrapperPsiElement implements CypherRightArrowHead {
public CypherRightArrowHeadImpl(ASTNode node) {
super(node);
}
public void accept(@NotNull CypherVisitor visitor) {
visitor.visitRightArrowHead(this);
}
public void accept(@NotNull PsiElementVisitor visitor) {
if (visitor instanceof CypherVisitor) accept((CypherVisitor)visitor);
else super.accept(visitor);
}
}
|
// Author: Atharv Damle
// To learn about interfaces and their implementation
// Full Question: https://www.hackerrank.com/challenges/30-interfaces/problem
// Interface in java is inherited by using the 'implements' keyword
class Calculator implements AdvancedArithmetic {
public int divisorSum(int n) {
int sum = 0;
for (int i = 1; i <= n; i++)
{
if (n % i == 0)
{
sum += i;
}
}
return sum;
}
}
|
/*******************************************************************************
* ___ _ ____ ____
* / _ \ _ _ ___ ___| |_| _ \| __ )
* | | | | | | |/ _ \/ __| __| | | | _ \
* | |_| | |_| | __/\__ \ |_| |_| | |_) |
* \__\_\\__,_|\___||___/\__|____/|____/
*
* Copyright (c) 2014-2019 Appsicle
* Copyright (c) 2019-2022 QuestDB
*
* 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.questdb;
import io.questdb.network.Net;
import io.questdb.std.Chars;
import io.questdb.std.MemoryTag;
import io.questdb.std.Os;
import io.questdb.std.Unsafe;
public class RawTCPILPSenderMain {
public static void main(String[] args) {
final String ilp = "dhl_plug,building=ba1aa618-4de4-40be-a4f7-72e341274b91,floor=a3979437-5d95-4f4d-8ef2-ace635cffce4,label=144c8537-db16-11e9-a374-0e9c62fb84fe,room=d534235d-d253-4aaa-8e40-eb8dc07c0d2b,socket_id=affbe16e-6a9e-4a06-85fe-e24430a1d8ba,address_id=8ca1d63a-d119-45aa-9747-351eb40bedf9 mac_address=\"xxxx\",milliamps=4,millijoules=151200,millivolts=120609,milliwatts=2520,duration=60587 1635189276608000\n";
final int len = ilp.length();
long mem = Unsafe.malloc(len, MemoryTag.NATIVE_DEFAULT);
try {
Chars.asciiStrCpy(ilp, len, mem);
long fd = Net.socketTcp(true);
if (fd != -1) {
if (Net.connect(fd, Net.sockaddr("127.0.0.1", 9009)) == 0) {
try {
int sent = Net.send(fd, mem, len);
System.out.println("Sent " + sent + " out of " + len);
} finally {
Net.close(fd);
}
} else {
System.out.println("could not connect");
}
} else {
System.out.println("Could not open socket [errno=" + Os.errno() + "]");
}
} finally {
Unsafe.free(mem, len, MemoryTag.NATIVE_DEFAULT);
}
}
}
|
package cn.droidlover.txzn.cache;
import android.content.Context;
import android.content.SharedPreferences;
import cn.droidlover.txzn.XDroidConf;
/**
* Created by wanglei on 2016/11/27.
*/
public class SharedPref implements ICache {
private static SharedPreferences sharedPreferences;
private static SharedPreferences.Editor editor;
static final String SP_NAME = XDroidConf.CACHE_SP_NAME;
private static SharedPref instance;
private SharedPref(Context context) {
sharedPreferences = context.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE);
editor = sharedPreferences.edit();
}
public static SharedPref getInstance(Context context) {
if (instance == null) {
synchronized (SharedPref.class) {
if (instance == null) {
instance = new SharedPref(context.getApplicationContext());
}
}
}
return instance;
}
@Override
public void remove(String key) {
editor.remove(key);
editor.apply();
}
@Override
public boolean contains(String key) {
return sharedPreferences.contains(key);
}
@Override
public void clear() {
editor.clear().apply();
}
public void putInt(String key, int value) {
editor.putInt(key, value);
editor.apply();
}
public int getInt(String key, int defValue) {
return sharedPreferences.getInt(key, defValue);
}
public void putLong(String key, Long value) {
editor.putLong(key, value);
editor.apply();
}
public long getLong(String key, long defValue) {
return sharedPreferences.getLong(key, defValue);
}
public void putBoolean(String key, Boolean value) {
editor.putBoolean(key, value);
editor.apply();
}
public boolean getBoolean(String key, boolean defValue) {
return sharedPreferences.getBoolean(key, defValue);
}
public void putString(String key, String value) {
editor.putString(key, value);
editor.apply();
}
public String getString(String key, String defValue) {
return sharedPreferences.getString(key, defValue);
}
@Override
public Object get(String key) {
return null;
}
@Override
public void put(String key, Object value) {
}
}
|
package main.java.event.listener;
/**
* Represents objects which receive messages when an entity's state
* on the server changes.
*
* @author Tom Galvin
*
*/
public interface ServerEntityUpdatedListener extends EntityMovedListener {
}
|
package countdowntimer.sound;
import java.net.URL;
import javazoom.jl.player.Player;
public class PlaySoundsJLRunnable implements Runnable {
private URL url;
private int repeat;
private int delay;
private SoundCanceller canceller;
public PlaySoundsJLRunnable(URL url,int repeat,int delay,SoundCanceller canceller) {
this.url = url;
this.repeat = repeat;
this.delay = delay;
this.canceller = canceller;
}
public void run() {
Player p = null;
try {
SoundPlayer.decreaseSoundCount();
System.out.println("JL Playing "+url+" -- repeat "+repeat+", delay "+delay); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
for (int i=0; i<repeat; i++) {
if (!canceller.isCancelled()) {
p = new Player(url.openStream());
sleepThread();
p.play();
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
//if (p != null) p.close();
}
}
private void sleepThread() {
try {
Thread.sleep(delay);
} catch (InterruptedException e2) {}
}
}
|
/**
* SpriteSheet.java --A program responsible to represent sprite sheet for creating game entities.
* @author Ratna Lama
* @version 1.0
* @since 10/26/2018
*/
package com.ratnalama.intheden.graphics;
import java.awt.image.BufferedImage;
public class SpriteSheet {
private BufferedImage sheet;
// Constructor
public SpriteSheet(BufferedImage sheet) {
this.sheet = sheet;
} // end Constructor
public BufferedImage crop(int x, int y, int width, int height) {
return sheet.getSubimage(x, y, width, height);
} // end crop()
} // end SpriteSheet
|
package org.jasig.cas.web;
import org.apache.commons.lang3.StringEscapeUtils;
import org.jasig.cas.CasProtocolConstants;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;
import java.util.List;
/**
* Delegating controller.
* Tries to find a controller among its delegates, that can handle the current request.
* If none is found, an error is generated.
*
* @author Frederic Esnault
* @since 3.5
*/
public class DelegatingController extends AbstractController {
/**
* View if Service Ticket Validation Fails.
*/
private static final String DEFAULT_ERROR_VIEW_NAME = "casServiceFailureView";
private List<AbstractDelegateController> delegates;
/**
* The view to redirect if no delegate can handle the request.
*/
@NotNull
private String failureView = DEFAULT_ERROR_VIEW_NAME;
/**
* Handles the request.
* Ask all delegates if they can handle the current request.
* The first to answer true is elected as the delegate that will process the request.
* If no controller answers true, we redirect to the error page.
*
* @param request the request to handle
* @param response the response to write to
* @return the model and view object
* @throws Exception if an error occurs during request handling
*/
@Override
protected final ModelAndView handleRequestInternal(final HttpServletRequest request, final HttpServletResponse response)
throws Exception {
for (final AbstractDelegateController delegate : delegates) {
if (delegate.canHandle(request, response)) {
return delegate.handleRequestInternal(request, response);
}
}
return generateErrorView(CasProtocolConstants.ERROR_CODE_INVALID_REQUEST, CasProtocolConstants.ERROR_CODE_INVALID_REQUEST, null);
}
/**
* Generate error view based on {@link #setFailureView(String)}.
*
* @param code the code
* @param description the description
* @param args the args
* @return the model and view
*/
private ModelAndView generateErrorView(final String code, final String description, final Object[] args) {
final ModelAndView modelAndView = new ModelAndView(this.failureView);
final String convertedDescription = getMessageSourceAccessor().getMessage(description, args, description);
modelAndView.addObject("code", StringEscapeUtils.escapeHtml4(code));
modelAndView.addObject("description", StringEscapeUtils.escapeHtml4(convertedDescription));
return modelAndView;
}
/**
* @param delegates the delegate controllers to set
*/
public void setDelegates(@NotNull final List<AbstractDelegateController> delegates) {
this.delegates = delegates;
}
/**
* @param failureView The failureView to set.
*/
public final void setFailureView(final String failureView) {
this.failureView = failureView;
}
}
|
/**
* Copyright (c) 2016, 2020, Oracle and/or its affiliates. All rights reserved.
* This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
*/
package com.oracle.bmc.database.model;
/**
* The details about what actions to perform and using what patch to the specified target.
* This is part of an update request that is applied to a version field on the target such
* as DB system, Database Home, etc.
*
* <br/>
* Note: Objects should always be created or deserialized using the {@link Builder}. This model distinguishes fields
* that are {@code null} because they are unset from fields that are explicitly set to {@code null}. This is done in
* the setter methods of the {@link Builder}, which maintain a set of all explicitly set fields called
* {@link #__explicitlySet__}. The {@link #hashCode()} and {@link #equals(Object)} methods are implemented to take
* {@link #__explicitlySet__} into account. The constructor, on the other hand, does not set {@link #__explicitlySet__}
* (since the constructor cannot distinguish explicit {@code null} from unset {@code null}).
**/
@javax.annotation.Generated(value = "OracleSDKGenerator", comments = "API Version: 20160918")
@lombok.AllArgsConstructor(onConstructor = @__({@Deprecated}))
@lombok.Value
@com.fasterxml.jackson.databind.annotation.JsonDeserialize(builder = PatchDetails.Builder.class)
@com.fasterxml.jackson.annotation.JsonFilter(com.oracle.bmc.http.internal.ExplicitlySetFilter.NAME)
public class PatchDetails {
@com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder(withPrefix = "")
@lombok.experimental.Accessors(fluent = true)
public static class Builder {
@com.fasterxml.jackson.annotation.JsonProperty("patchId")
private String patchId;
public Builder patchId(String patchId) {
this.patchId = patchId;
this.__explicitlySet__.add("patchId");
return this;
}
@com.fasterxml.jackson.annotation.JsonProperty("action")
private Action action;
public Builder action(Action action) {
this.action = action;
this.__explicitlySet__.add("action");
return this;
}
@com.fasterxml.jackson.annotation.JsonIgnore
private final java.util.Set<String> __explicitlySet__ = new java.util.HashSet<String>();
public PatchDetails build() {
PatchDetails __instance__ = new PatchDetails(patchId, action);
__instance__.__explicitlySet__.addAll(__explicitlySet__);
return __instance__;
}
@com.fasterxml.jackson.annotation.JsonIgnore
public Builder copy(PatchDetails o) {
Builder copiedBuilder = patchId(o.getPatchId()).action(o.getAction());
copiedBuilder.__explicitlySet__.retainAll(o.__explicitlySet__);
return copiedBuilder;
}
}
/**
* Create a new builder.
*/
public static Builder builder() {
return new Builder();
}
/**
* The [OCID](https://docs.cloud.oracle.com/Content/General/Concepts/identifiers.htm) of the patch.
**/
@com.fasterxml.jackson.annotation.JsonProperty("patchId")
String patchId;
/**
* The action to perform on the patch.
**/
public enum Action {
Apply("APPLY"),
Precheck("PRECHECK"),
;
private final String value;
private static java.util.Map<String, Action> map;
static {
map = new java.util.HashMap<>();
for (Action v : Action.values()) {
map.put(v.getValue(), v);
}
}
Action(String value) {
this.value = value;
}
@com.fasterxml.jackson.annotation.JsonValue
public String getValue() {
return value;
}
@com.fasterxml.jackson.annotation.JsonCreator
public static Action create(String key) {
if (map.containsKey(key)) {
return map.get(key);
}
throw new IllegalArgumentException("Invalid Action: " + key);
}
};
/**
* The action to perform on the patch.
**/
@com.fasterxml.jackson.annotation.JsonProperty("action")
Action action;
@com.fasterxml.jackson.annotation.JsonIgnore
private final java.util.Set<String> __explicitlySet__ = new java.util.HashSet<String>();
}
|
/*
* (C) Copyright 2006-2011 Nuxeo SA (http://nuxeo.com/) and others.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Contributors:
* Nuxeo - initial API and implementation
*
* $Id$
*/
package org.nuxeo.ecm.platform.rendering.test;
import org.junit.Test;
import static org.junit.Assert.*;
import org.nuxeo.ecm.platform.rendering.wiki.extensions.PatternFilter;
public class TestPatternFilter {
@Test
public void test1() {
PatternFilter filter = new PatternFilter("[A-Z]+[a-z]+[A-Z][A-Za-z]*", "<link>$0</link>");
assertEquals("<link>MyName</link>", filter.apply("MyName"));
}
@Test
public void test2() {
PatternFilter filter = new PatternFilter("NXP-[0-9]+", "<a href=\"http://jira.nuxeo.org/browse/$0\">$0</a>");
assertEquals("<a href=\"http://jira.nuxeo.org/browse/NXP-1234\">NXP-1234</a>", filter.apply("NXP-1234"));
assertNull(filter.apply("NXP1234"));
}
}
|
package com.example.renosyahputra.pdfviewerlibrary.photoview;
import android.view.MotionEvent;
/**
* A callback to be invoked when the ImageView is flung with a single
* touch
*/
public interface OnSingleFlingListener {
/**
* A callback to receive where the user flings on a ImageView. You will receive a callback if
* the user flings anywhere on the view.
*
* @param e1 MotionEvent the user first touch.
* @param e2 MotionEvent the user last touch.
* @param velocityX distance of user's horizontal fling.
* @param velocityY distance of user's vertical fling.
*/
boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY);
}
|
package veritesting.apachecli;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
public class CLI_eqchk {
/*public static void main( String[] args ){
mainProcess('-', 'a', '-', 'm', '-', 'h', 'y', 'm', false);
}*/
public static CommandLine mainProcess(char a, char b, char c, char d, char e, char f, char g, char h, boolean stop) {
Options options = new Options();
options.addOption('a', 0, "display program help");
options.addOption('b', 1, "display the year");
options.addOption('c', 2, "display the month");
options.addOption('d', 5, "display the day");
options.addOption('e', 6, "display the hour");
options.addOption('f', 7, "display the minute");
options.addOption('g', 0, "display the second");
options.addOption('h', 1, "display the C");
options.addOption('i', 2, "display the L");
options.addOption('j', 5, "display the I");
options.addOption('k', 6, "display wang");
options.addOption('l', 7, "display ang");
options.addOption('m', 7, "display ng");
options.addOption('n', 6, "display g");
options.addOption('o', 5, "display ou");
options.addOption('p', 3, "display u");
options.addOption('q', 6, "display wang");
options.addOption('r', 7, "display ang");
options.addOption('s', 7, "display ng");
options.addOption('t', 6, "display g");
options.addOption('u', 3, "display u");
options.addOption('v', 6, "display wang");
options.addOption('w', 7, "display ang");
options.addOption('x', 7, "display ng");
options.addOption('y', 6, "display g");
options.addOption('z', 6, "display g");
options.addOption('A', 5, "display ou");
options.addOption('B', 3, "display u");
options.addOption('C', 6, "display wang");
options.addOption('D', 7, "display ang");
options.addOption('E', 5, "display yang");
options.addOption('F', 6, "display hui");
options.addOption('G', 5, "display yang");
options.addOption('H', 6, "display hui");
options.addOption('I', 5, "display yang");
options.addOption('J', 6, "display hui");
options.addOption('K', 7, "display yang");
options.addOption('L', 6, "display hui");
char[][] string = new char[8][1];
string[0][0] = a;
string[1][0] = b;
string[2][0] = c;
string[3][0] = d;
string[4][0] = e;
string[5][0] = f;
string[6][0] = g;
string[7][0] = h;
return execute(options, string, stop);
}
private static CommandLine execute(Options options, char[][] string, boolean stop) {
// char c = string[0][0];
// if ( c == '*') stop = true;
// create the parser
CommandLine commandLine = null;
CommandLineParser commandParser = new BasicParser();
try {
commandLine = commandParser.parse(options, string, stop);
List _options = options.helpOptions();
Iterator it = _options.iterator();
boolean _next = it.hasNext();
while(_next){
Option option = (Option) it.next();
char key = option.getKey();
System.out.println(key + "\t");
_next = it.hasNext();
}
// while(_next){
// Option option = (Option) it.next();
// char key = option.getKey();
// String optionValue = commandLine.getOptionValue(key);
// System.out.print(key + "\t");
// System.out.println(optionValue);
// _next = it.hasNext();
// }
// System.out.println("Unrecognized option or parameter!");
// String[] args = commandLine.getArgs();
// int argLen = args.length;
// if(argLen == 0){
// System.out.println("There is no");
// }
// else{
// for(int i=0; i<args.length; i++){
// System.out.println(args[i]);
// }
// }
} catch (ParseException e) {
e.printStackTrace();
}
// HelpFormatter formatter = new HelpFormatter();
// formatter.printHelp("CLI", options);
return commandLine;
}
}
|
/* See LICENSE for licensing and NOTICE for copyright. */
package org.ldaptive.schema;
import org.ldaptive.LdapException;
/**
* Exception that indicates a schema element string could not be parsed.
*
* @author Middleware Services
*/
public class SchemaParseException extends LdapException
{
/** serialVersionUID. */
private static final long serialVersionUID = -5214120370570326233L;
/**
* Creates a new schema parse exception.
*
* @param msg describing this exception
*/
public SchemaParseException(final String msg)
{
super(msg);
}
/**
* Creates a new schema parse exception.
*
* @param e underlying exception
*/
public SchemaParseException(final Throwable e)
{
super(e);
}
/**
* Creates a new schema parse exception.
*
* @param msg describing this exception
* @param e underlying exception
*/
public SchemaParseException(final String msg, final Throwable e)
{
super(msg, e);
}
}
|
package io.probedock.demo.itf.rest;
import java.util.HashSet;
import java.util.Set;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.Path;
import javax.ws.rs.core.Application;
import org.codehaus.jackson.jaxrs.JacksonJsonProvider;
import org.glassfish.jersey.jackson.JacksonFeature;
import org.reflections.Reflections;
import org.reflections.scanners.TypeAnnotationsScanner;
import org.reflections.util.ClasspathHelper;
import org.reflections.util.FilterBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Rest application for the API
*
* @author Laurent Prevost <laurent.prevost@probedock.io>
*/
@ApplicationPath("api")
public class ApiRestApplication extends Application {
private static final Logger LOG = LoggerFactory.getLogger(ApiRestApplication.class);
private Set<Class<?>> classes;
public ApiRestApplication() {
classes = new HashSet<>();
classes.add(JacksonFeature.class);
classes.add(JsonObjectMapper.class);
// Scan every packages to get @Path annotated classes
for (String pckg : new String[] { getClass().getPackage().getName() }) {
classes.addAll(new Reflections(
ClasspathHelper.forPackage(pckg), new TypeAnnotationsScanner(), new FilterBuilder().includePackage(pckg)).
getTypesAnnotatedWith(Path.class));
}
if (LOG.isTraceEnabled()) {
for (Class cl : classes) {
LOG.trace("Class registered: {}", cl.getCanonicalName());
}
}
}
@Override
public Set<Class<?>> getClasses() {
return classes;
}
@Override
public Set<Object> getSingletons() {
final Set<Object> singletons = new HashSet<>(2);
singletons.add(new JacksonJsonProvider());
return singletons;
}
}
|
/*
* Copyright 2018 Alexey Andreev.
*
* 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.teavm.tests;
import static org.junit.Assert.assertEquals;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.teavm.junit.TeaVMTestRunner;
@RunWith(TeaVMTestRunner.class)
public class JUnitDerivedTest extends JUnitBaseTest {
@Before
public void startDerived() {
b = "derived";
}
@Test
public void bar() {
assertEquals("derived", b);
}
}
|
/*
* Software Name : ATK
*
* Copyright (C) 2007 - 2012 France Télé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.
*
* ------------------------------------------------------------------
* File Name : MyDisplayJAI.java
*
* Created : 04/06/2009
* Author(s) : France Telecom
*/
package com.orange.atk.compUI;
import java.awt.AlphaComposite;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Observable;
import java.util.Observer;
import javax.imageio.ImageIO;
import com.orange.atk.compModel.Boolean2D;
import com.orange.atk.compModel.ComparaisonCouple;
import com.orange.atk.compModel.Mask;
import com.orange.atk.compModel.Model;
import com.sun.media.jai.widget.DisplayJAI;
public class MyDisplayJAI extends DisplayJAI implements Observer {
/**
*
*/
private static final long serialVersionUID = 1L;
private MyDisplayJAI me;
private BufferedImage bi;
private boolean isTest =true;
public static final Color colorSimilarPart = new Color(100,200,50);
public static final Color colorMaskSelected = Color.YELLOW;
public static final Color colorSumMask= Color.BLUE;
int w;
int h;
private Mask mask;
private Mask activeMask;
ArrayList<Integer> listMask;
private Boolean2D diff;
private double zoom = 1.0;
private BufferedImage img;
private ComparatorFrame comparatorFrame;
Model model;
/**
* constructor
* @param model
* @param index
* @param isTest - if the display will paint mask and differences
*/
public MyDisplayJAI(ComparaisonCouple couple, Model model, boolean isTest) {
super();
model.addObserver(this);
mask=couple.getMaskSum();
this.isTest=isTest;
me = this;
this.model = model;
try {
if (isTest){
img = ImageIO.read(couple.getImgTest());
}else{
img = ImageIO.read(model.getRefImage(couple.getImgRefId()).getImage());
}
w = img.getWidth();
h = img.getHeight();
bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
Graphics g = bi.getGraphics();
Dimension dim = new Dimension(w,h);
setPreferredSize(dim);
setMinimumSize(dim);
g.drawImage(img, 0, 0, null);
} catch (IOException e) {
e.printStackTrace();
}
diff = couple.getDifWithMask();
}
public void setZoom(double zoom) {
if (zoom != this.zoom) {
this.zoom = zoom;
w = (int) (img.getWidth() * zoom);
h = (int) (img.getHeight() * zoom);
bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
Graphics g = bi.getGraphics();
Dimension dim = new Dimension(w,h);
setPreferredSize(dim);
setMinimumSize(dim);
if (zoom != 1.0) g.drawImage(img.getScaledInstance(w, h, Image.SCALE_DEFAULT), 0, 0, null);
else g.drawImage(img, 0, 0, null);
}
}
public int getWidth() {
return w;
}
public int getHeight() {
return h;
}
public void set(BufferedImage img, ComparaisonCouple cp) {
//Logger.getLogger(this.getClass() ).debug("MyDisplay.set");
w = (int) (img.getWidth() * zoom);
h = (int) (img.getHeight() * zoom);
diff = cp.getDifWithMask();
mask = cp.getMaskSum();
listMask = cp.getImgRef().getMaskListId();
bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
Graphics g = bi.getGraphics();
setSize(w, h);
setMinimumSize(new Dimension(w,h) );
if (zoom != 1.0) g.drawImage(img.getScaledInstance(w, h, Image.SCALE_DEFAULT), 0, 0, null);
else g.drawImage(img, 0, 0, null);
}
public void paint(Graphics g) {
Graphics2D g2d = (Graphics2D)g;
/**
* Set to the active or to null if the active mask is not part of the active imageRef
*/
Mask activeMaskChecked = activeMask;
g.clearRect(0, 0, w, h);
g2d.drawImage(bi, null,0,0);
g2d.setStroke(new BasicStroke(1.5f));
g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,0.6f));
if(activeMask!=null){
if(!listMask.contains(activeMask.getId()))
activeMaskChecked = null;
}
if(model!=null){
for (int x=0; x<model.getMaskWidth(); x++){
for (int y=0; y<model.getMaskHeight(); y++){
if(isTest && !diff.get(x, y)){
g2d.setColor(colorSimilarPart);
g2d.fillRect(
(int)((2*x)*Mask.getCELL_HALF_SIZE()*zoom),
(int)((2*y)*Mask.getCELL_HALF_SIZE()*zoom),
(int)(2*Mask.getCELL_HALF_SIZE()*zoom),
(int)(2*Mask.getCELL_HALF_SIZE()*zoom));
}
else if (mask.getCell(x, y)){
if(activeMaskChecked!= null){
if (activeMaskChecked.getCell(x, y))
g2d.setColor(colorMaskSelected);
else
g2d.setColor(colorSumMask);
}else
g2d.setColor(colorSumMask);
g2d.fillRect(
(int)((2*x)*Mask.getCELL_HALF_SIZE()*zoom),
(int)((2*y)*Mask.getCELL_HALF_SIZE()*zoom),
(int)(2*Mask.getCELL_HALF_SIZE()*zoom),
(int)(2*Mask.getCELL_HALF_SIZE()*zoom));
}
}
}
}
}
public void update(Observable arg0, java.lang.Object arg1) {
repaint();
}
public void setActiveMask(Mask selectedMask) {
activeMask = selectedMask;
}
public void addListener(ComparatorFrame comparatorFrameArg){
comparatorFrame = comparatorFrameArg;
this.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent arg0) {
if(arg0.getButton()==MouseEvent.BUTTON1){
if(arg0.getClickCount() == 2)
comparatorFrame.addLine(arg0);
else
comparatorFrame.addZone(arg0);
}
else if(arg0.getButton()==MouseEvent.BUTTON3){
comparatorFrame.showInfoZone(arg0,me);
}
}
public void mousePressed(MouseEvent arg0) {
comparatorFrame.refScDescChanged();
comparatorFrame.mousePressed(arg0);
}
public void mouseReleased(MouseEvent arg0) {
comparatorFrame.mouseReleased(arg0);
}
});
this.addMouseMotionListener(new MouseMotionListener() {
public void mouseMoved(MouseEvent e) {
}
public void mouseDragged(MouseEvent e) {
comparatorFrame.addZoneDragged(e);
}
});
}
}
|
package com.lixin.litemall.db.domain;
import io.swagger.annotations.ApiModelProperty;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
public class LitemallAftersale {
public static final Boolean IS_DELETED = Deleted.IS_DELETED.value();
public static final Boolean NOT_DELETED = Deleted.NOT_DELETED.value();
private Integer id;
@ApiModelProperty(value = "售后编号")
private String aftersaleSn;
@ApiModelProperty(value = "订单ID")
private Integer orderId;
@ApiModelProperty(value = "用户ID")
private Integer userId;
@ApiModelProperty(value = "售后类型,0是未收货退款,1是已收货(无需退货)退款,2用户退货退款")
private Short type;
@ApiModelProperty(value = "退款原因")
private String reason;
@ApiModelProperty(value = "退款金额")
private BigDecimal amount;
@ApiModelProperty(value = "退款凭证图片链接数组")
private String[] pictures;
@ApiModelProperty(value = "退款说明")
private String comment;
@ApiModelProperty(value = "售后状态,0是可申请,1是用户已申请,2是管理员审核通过,3是管理员退款成功,4是管理员审核拒绝,5是用户已取消")
private Short status;
@ApiModelProperty(value = "管理员操作时间")
private LocalDateTime handleTime;
@ApiModelProperty(value = "添加时间")
private LocalDateTime addTime;
@ApiModelProperty(value = "更新时间")
private LocalDateTime updateTime;
@ApiModelProperty(value = "逻辑删除")
private Boolean deleted;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getAftersaleSn() {
return aftersaleSn;
}
public void setAftersaleSn(String aftersaleSn) {
this.aftersaleSn = aftersaleSn;
}
public Integer getOrderId() {
return orderId;
}
public void setOrderId(Integer orderId) {
this.orderId = orderId;
}
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public Short getType() {
return type;
}
public void setType(Short type) {
this.type = type;
}
public String getReason() {
return reason;
}
public void setReason(String reason) {
this.reason = reason;
}
public BigDecimal getAmount() {
return amount;
}
public void setAmount(BigDecimal amount) {
this.amount = amount;
}
public String[] getPictures() {
return pictures;
}
public void setPictures(String[] pictures) {
this.pictures = pictures;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public Short getStatus() {
return status;
}
public void setStatus(Short status) {
this.status = status;
}
public LocalDateTime getHandleTime() {
return handleTime;
}
public void setHandleTime(LocalDateTime handleTime) {
this.handleTime = handleTime;
}
public LocalDateTime getAddTime() {
return addTime;
}
public void setAddTime(LocalDateTime addTime) {
this.addTime = addTime;
}
public LocalDateTime getUpdateTime() {
return updateTime;
}
public void setUpdateTime(LocalDateTime updateTime) {
this.updateTime = updateTime;
}
public void andLogicalDeleted(boolean deleted) {
setDeleted(deleted ? Deleted.IS_DELETED.value() : Deleted.NOT_DELETED.value());
}
public Boolean getDeleted() {
return deleted;
}
public void setDeleted(Boolean deleted) {
this.deleted = deleted;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", IS_DELETED=").append(IS_DELETED);
sb.append(", NOT_DELETED=").append(NOT_DELETED);
sb.append(", id=").append(id);
sb.append(", aftersaleSn=").append(aftersaleSn);
sb.append(", orderId=").append(orderId);
sb.append(", userId=").append(userId);
sb.append(", type=").append(type);
sb.append(", reason=").append(reason);
sb.append(", amount=").append(amount);
sb.append(", pictures=").append(pictures);
sb.append(", comment=").append(comment);
sb.append(", status=").append(status);
sb.append(", handleTime=").append(handleTime);
sb.append(", addTime=").append(addTime);
sb.append(", updateTime=").append(updateTime);
sb.append(", deleted=").append(deleted);
sb.append("]");
return sb.toString();
}
@Override
public boolean equals(Object that) {
if (this == that) {
return true;
}
if (that == null) {
return false;
}
if (getClass() != that.getClass()) {
return false;
}
LitemallAftersale other = (LitemallAftersale) that;
return (this.getId() == null ? other.getId() == null : this.getId().equals(other.getId()))
&& (this.getAftersaleSn() == null ? other.getAftersaleSn() == null : this.getAftersaleSn().equals(other.getAftersaleSn()))
&& (this.getOrderId() == null ? other.getOrderId() == null : this.getOrderId().equals(other.getOrderId()))
&& (this.getUserId() == null ? other.getUserId() == null : this.getUserId().equals(other.getUserId()))
&& (this.getType() == null ? other.getType() == null : this.getType().equals(other.getType()))
&& (this.getReason() == null ? other.getReason() == null : this.getReason().equals(other.getReason()))
&& (this.getAmount() == null ? other.getAmount() == null : this.getAmount().equals(other.getAmount()))
&& (Arrays.equals(this.getPictures(), other.getPictures()))
&& (this.getComment() == null ? other.getComment() == null : this.getComment().equals(other.getComment()))
&& (this.getStatus() == null ? other.getStatus() == null : this.getStatus().equals(other.getStatus()))
&& (this.getHandleTime() == null ? other.getHandleTime() == null : this.getHandleTime().equals(other.getHandleTime()))
&& (this.getAddTime() == null ? other.getAddTime() == null : this.getAddTime().equals(other.getAddTime()))
&& (this.getUpdateTime() == null ? other.getUpdateTime() == null : this.getUpdateTime().equals(other.getUpdateTime()))
&& (this.getDeleted() == null ? other.getDeleted() == null : this.getDeleted().equals(other.getDeleted()));
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((getId() == null) ? 0 : getId().hashCode());
result = prime * result + ((getAftersaleSn() == null) ? 0 : getAftersaleSn().hashCode());
result = prime * result + ((getOrderId() == null) ? 0 : getOrderId().hashCode());
result = prime * result + ((getUserId() == null) ? 0 : getUserId().hashCode());
result = prime * result + ((getType() == null) ? 0 : getType().hashCode());
result = prime * result + ((getReason() == null) ? 0 : getReason().hashCode());
result = prime * result + ((getAmount() == null) ? 0 : getAmount().hashCode());
result = prime * result + (Arrays.hashCode(getPictures()));
result = prime * result + ((getComment() == null) ? 0 : getComment().hashCode());
result = prime * result + ((getStatus() == null) ? 0 : getStatus().hashCode());
result = prime * result + ((getHandleTime() == null) ? 0 : getHandleTime().hashCode());
result = prime * result + ((getAddTime() == null) ? 0 : getAddTime().hashCode());
result = prime * result + ((getUpdateTime() == null) ? 0 : getUpdateTime().hashCode());
result = prime * result + ((getDeleted() == null) ? 0 : getDeleted().hashCode());
return result;
}
public enum Deleted {
NOT_DELETED(new Boolean("0"), "未删除"),
IS_DELETED(new Boolean("1"), "已删除");
private final Boolean value;
private final String name;
Deleted(Boolean value, String name) {
this.value = value;
this.name = name;
}
public Boolean getValue() {
return this.value;
}
public Boolean value() {
return this.value;
}
public String getName() {
return this.name;
}
}
public enum Column {
id("id", "id", "INTEGER", false),
aftersaleSn("aftersale_sn", "aftersaleSn", "VARCHAR", false),
orderId("order_id", "orderId", "INTEGER", false),
userId("user_id", "userId", "INTEGER", false),
type("type", "type", "SMALLINT", true),
reason("reason", "reason", "VARCHAR", false),
amount("amount", "amount", "DECIMAL", false),
pictures("pictures", "pictures", "VARCHAR", false),
comment("comment", "comment", "VARCHAR", true),
status("status", "status", "SMALLINT", true),
handleTime("handle_time", "handleTime", "TIMESTAMP", false),
addTime("add_time", "addTime", "TIMESTAMP", false),
updateTime("update_time", "updateTime", "TIMESTAMP", false),
deleted("deleted", "deleted", "BIT", false);
private static final String BEGINNING_DELIMITER = "`";
private static final String ENDING_DELIMITER = "`";
private final String column;
private final boolean isColumnNameDelimited;
private final String javaProperty;
private final String jdbcType;
public String value() {
return this.column;
}
public String getValue() {
return this.column;
}
public String getJavaProperty() {
return this.javaProperty;
}
public String getJdbcType() {
return this.jdbcType;
}
Column(String column, String javaProperty, String jdbcType, boolean isColumnNameDelimited) {
this.column = column;
this.javaProperty = javaProperty;
this.jdbcType = jdbcType;
this.isColumnNameDelimited = isColumnNameDelimited;
}
public String desc() {
return this.getEscapedColumnName() + " DESC";
}
public String asc() {
return this.getEscapedColumnName() + " ASC";
}
public static Column[] excludes(Column... excludes) {
ArrayList<Column> columns = new ArrayList<>(Arrays.asList(Column.values()));
if (excludes != null && excludes.length > 0) {
columns.removeAll(new ArrayList<>(Arrays.asList(excludes)));
}
return columns.toArray(new Column[]{});
}
public static Column[] all() {
return Column.values();
}
public String getEscapedColumnName() {
if (this.isColumnNameDelimited) {
return new StringBuilder().append(BEGINNING_DELIMITER).append(this.column).append(ENDING_DELIMITER).toString();
} else {
return this.column;
}
}
public String getAliasedEscapedColumnName() {
return this.getEscapedColumnName();
}
}
}
|
package com.example.web_api_spotify.models;
import android.os.Parcel;
import android.os.Parcelable;
import java.util.List;
public class Albums implements Parcelable {
public List<Album> albums;
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeTypedList(albums);
}
public Albums() {
}
protected Albums(Parcel in) {
this.albums = in.createTypedArrayList(Album.CREATOR);
}
public static final Parcelable.Creator<Albums> CREATOR = new Parcelable.Creator<Albums>() {
public Albums createFromParcel(Parcel source) {
return new Albums(source);
}
public Albums[] newArray(int size) {
return new Albums[size];
}
};
}
|
/*
* MIT License
*
* Copyright (c) 2021 MASES s.r.l.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/**************************************************************************************
* <auto-generated>
* This code was generated from a template using JCOReflector
*
* Manual changes to this file may cause unexpected behavior in your application.
* Manual changes to this file will be overwritten if the code is regenerated.
* </auto-generated>
*************************************************************************************/
package microsoft.win32;
import org.mases.jcobridge.*;
import org.mases.jcobridge.netreflection.*;
// Import section
// PACKAGE_IMPORT_SECTION
/**
* The base .NET class managing Microsoft.Win32.RegistryView, Microsoft.Win32.Registry, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a. Extends {@link NetObject}.
* <p>
*
* See: <a href="https://docs.microsoft.com/en-us/dotnet/api/Microsoft.Win32.RegistryView" target="_top">https://docs.microsoft.com/en-us/dotnet/api/Microsoft.Win32.RegistryView</a>
*/
public class RegistryView extends NetObject {
/**
* Fully assembly qualified name: Microsoft.Win32.Registry, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
*/
public static final String assemblyFullName = "Microsoft.Win32.Registry, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";
/**
* Assembly name: Microsoft.Win32.Registry
*/
public static final String assemblyShortName = "Microsoft.Win32.Registry";
/**
* Qualified class name: Microsoft.Win32.RegistryView
*/
public static final String className = "Microsoft.Win32.RegistryView";
static JCOBridge bridge = JCOBridgeInstance.getInstance(assemblyFullName);
/**
* The type managed from JCOBridge. See {@link JCType}
*/
public static JCType classType = createType();
static JCEnum enumReflected = createEnum();
JCEnum classInstance = null;
static JCType createType() {
try {
String classToCreate = className + ", "
+ (JCOReflector.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName);
if (JCOReflector.getDebug())
JCOReflector.writeLog("Creating %s", classToCreate);
JCType typeCreated = bridge.GetType(classToCreate);
if (JCOReflector.getDebug())
JCOReflector.writeLog("Created: %s",
(typeCreated != null) ? typeCreated.toString() : "Returned null value");
return typeCreated;
} catch (JCException e) {
JCOReflector.writeLog(e);
return null;
}
}
static JCEnum createEnum() {
try {
String enumToCreate = className + ", "
+ (JCOReflector.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName);
if (JCOReflector.getDebug())
JCOReflector.writeLog("Creating Enum %s", enumToCreate);
JCEnum enumCreated = bridge.GetEnum(enumToCreate);
if (JCOReflector.getDebug())
JCOReflector.writeLog("Created Enum: %s",
(enumCreated != null) ? enumCreated.toString() : "Returned null value");
return enumCreated;
} catch (JCException e) {
JCOReflector.writeLog(e);
return null;
}
}
void addReference(String ref) throws Throwable {
try {
bridge.AddReference(ref);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public RegistryView(Object instance) {
super(instance);
if (instance instanceof JCObject) {
try {
String enumName = NetEnum.GetName(classType, (JCObject)instance);
classInstance = enumReflected.fromValue(enumName);
} catch (Throwable t) {
JCOReflector.writeLog(t);
classInstance = enumReflected;
}
} else if (instance instanceof JCEnum) {
classInstance = (JCEnum)instance;
}
}
public RegistryView() {
super();
// add reference to assemblyName.dll file
try {
addReference(JCOReflector.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName);
} catch (Throwable jcne) {
JCOReflector.writeLog(jcne);
}
}
public String getJCOAssemblyName() {
return assemblyFullName;
}
public String getJCOClassName() {
return className;
}
public String getJCOObjectName() {
return className + ", " + (JCOReflector.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName);
}
public Object getJCOInstance() {
return classInstance;
}
public JCType getJCOType() {
return classType;
}
final static RegistryView getFrom(JCEnum object, String value) {
try {
return new RegistryView(object.fromValue(value));
} catch (JCException e) {
return new RegistryView(object);
}
}
// Enum fields section
public static RegistryView Default = getFrom(enumReflected, "Default");
public static RegistryView Registry64 = getFrom(enumReflected, "Registry64");
public static RegistryView Registry32 = getFrom(enumReflected, "Registry32");
// Flags management section
}
|
/* See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* Esri Inc. licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.esri.gpt.catalog.harvest.protocols;
import com.esri.gpt.control.webharvest.IterationContext;
import com.esri.gpt.control.webharvest.client.oai.OaiQueryBuilder;
import com.esri.gpt.framework.collection.StringAttributeMap;
import com.esri.gpt.framework.resource.query.QueryBuilder;
import com.esri.gpt.framework.util.Val;
/**
* OAI protocol.
*/
public class HarvestProtocolOai extends AbstractHTTPHarvestProtocol {
// class variables =============================================================
// instance variables ==========================================================
/** OAI set name. */
private String _set = "";
/** OAI prefix. */
private String _prefix = "";
// constructors ================================================================
// properties ==================================================================
/**
* Gets set.
* @return set
*/
public String getSet() {
return _set;
}
/**
* Sets set.
* @param set set
*/
public void setSet(String set) {
_set = Val.chkStr(set);
}
/**
* Gets prefix.
* @return prefix
*/
public String getPrefix() {
return _prefix;
}
/**
* Sets prefix.
* @param prefix prefix
*/
public void setPrefix(String prefix) {
_prefix = Val.chkStr(prefix);
}
/**
* Gets protocol type.
* @return protocol type
* @deprecated
*/
@Override
@Deprecated
public final ProtocolType getType() {
return ProtocolType.OAI;
}
@Override
public String getKind() {
return "OAI";
}
// methods =====================================================================
/**
* Gets all the attributes.
* @return attributes as attribute map
*/
@Override
public StringAttributeMap getAttributeMap() {
StringAttributeMap properties = new StringAttributeMap();
properties.set("set", getSet());
properties.set("prefix", getPrefix());
return properties;
}
/**
* Sets all the attributes.
* @param attributeMap attributes as attribute map
*/
@Override
public void setAttributeMap(StringAttributeMap attributeMap) {
setSet(chckAttr(attributeMap.get("set")));
setPrefix(chckAttr(attributeMap.get("prefix")));
}
@Override
public QueryBuilder newQueryBuilder(IterationContext context, String url) {
return new OaiQueryBuilder(context, this, url);
}
}
|
package me.saro.commons.__old.bytes.fd;
import java.lang.reflect.Method;
import java.util.Calendar;
import java.util.Date;
import me.saro.commons.__old.bytes.DateFormat;
import me.saro.commons.__old.bytes.Bytes;
import me.saro.commons.__old.bytes.fd.annotations.DateData;
import me.saro.commons.__old.bytes.fd.annotations.DateDataType;
import me.saro.commons.__old.bytes.fd.annotations.FixedDataClass;
/**
* FixedMethodDateType
* @author PARK Yong Seo
* @since 4.0.0
*/
public class FixedMethodDateType implements FixedMethod {
final DateData meta;
final String parentClassName;
final FixedDataClass fixedDataClassInfo;
FixedMethodDateType(FixedDataClass fixedDataClassInfo, String parentClassName, DateData dateDate) {
this.fixedDataClassInfo = fixedDataClassInfo;
this.meta = dateDate;
this.parentClassName = parentClassName;
}
@Override
public FixedMethodConsumer toBytes(Method method) {
int offset = meta.offset();
boolean le = !fixedDataClassInfo.bigEndian();
DateDataType type = meta.type();
String genericReturnTypeName = method.getGenericReturnType().getTypeName();
switch (genericReturnTypeName) {
case "java.util.Date" :
switch (type) {
case millis8 :return (bytes, idx, val) -> System.arraycopy(Bytes.reverse(Bytes.toBytes(((Date)method.invoke(val)).getTime()), le), 0, bytes, offset + idx, 8);
case unix8 : return (bytes, idx, val) -> System.arraycopy(Bytes.reverse(Bytes.toBytes((((Date)method.invoke(val))).getTime() / 1000), le), 0, bytes, offset + idx, 8);
case unix4 : return (bytes, idx, val) -> System.arraycopy(Bytes.reverse(Bytes.toBytes((int)((((Date)method.invoke(val))).getTime() / 1000L)), le), 0, bytes, offset + idx, 4);
}
break;
case "java.util.Calendar" :
switch (type) {
case millis8 :return (bytes, idx, val) -> System.arraycopy(Bytes.reverse(Bytes.toBytes(((Calendar)method.invoke(val)).getTimeInMillis()), le), 0, bytes, offset + idx, 8);
case unix8 : return (bytes, idx, val) -> System.arraycopy(Bytes.reverse(Bytes.toBytes((((Calendar)method.invoke(val)).getTimeInMillis()) / 1000), le), 0, bytes, offset + idx, 8);
case unix4 : return (bytes, idx, val) -> System.arraycopy(Bytes.reverse(Bytes.toBytes((int)((((Calendar)method.invoke(val)).getTimeInMillis()) / 1000)), le), 0, bytes, offset + idx, 4);
}
break;
case "me.saro.commons.__old.bytes.DateFormat" :
switch (type) {
case millis8 :return (bytes, idx, val) -> System.arraycopy(Bytes.reverse(Bytes.toBytes(((DateFormat)method.invoke(val)).getTimeInMillis()), le), 0, bytes, offset + idx, 8);
case unix8 : return (bytes, idx, val) -> System.arraycopy(Bytes.reverse(Bytes.toBytes((((DateFormat)method.invoke(val)).getTimeInMillis()) / 1000), le), 0, bytes, offset + idx, 8);
case unix4 : return (bytes, idx, val) -> System.arraycopy(Bytes.reverse(Bytes.toBytes((int)((((DateFormat)method.invoke(val)).getTimeInMillis()) / 1000)), le), 0, bytes, offset + idx, 4);
}
break;
}
throw new IllegalArgumentException("does not support type, support type [Date, Calendar, DateFormat] : "+genericReturnTypeName+" " + method.getName() + "() in " + parentClassName);
}
@Override
public FixedMethodConsumer toClass(Method method) {
int offset = meta.offset();
boolean le = !fixedDataClassInfo.bigEndian();
DateDataType type = meta.type();
String genericParameterTypeName = method.getGenericParameterTypes()[0].getTypeName();
switch (genericParameterTypeName) {
case "java.util.Date" :
switch (type) {
case millis8 :return (bytes, idx, val) -> method.invoke(val, new Date(Bytes.toLong(Bytes.copy(bytes, idx + offset, 8, le))));
case unix8 : return (bytes, idx, val) -> method.invoke(val, new Date(Bytes.toLong(Bytes.copy(bytes, idx + offset, 8, le)) * 1000));
case unix4 : return (bytes, idx, val) -> method.invoke(val, new Date(Integer.toUnsignedLong(Bytes.toInt(Bytes.copy(bytes, idx + offset, 4, le))) * 1000L));
}
break;
case "java.util.Calendar" :
switch (type) {
case millis8 :return (bytes, idx, val) -> method.invoke(val, DateFormat.parse(Bytes.toLong(Bytes.copy(bytes, idx + offset, 8, le))).toCalendar());
case unix8 : return (bytes, idx, val) -> method.invoke(val, DateFormat.parse(Bytes.toLong(Bytes.copy(bytes, idx + offset, 8, le)) * 1000).toCalendar());
case unix4 : return (bytes, idx, val) -> method.invoke(val, DateFormat.parse(Integer.toUnsignedLong(Bytes.toInt(Bytes.copy(bytes, idx + offset, 4, le))) * 1000L).toCalendar());
}
break;
case "me.saro.commons.__old.bytes.DateFormat" :
switch (type) {
case millis8 :return (bytes, idx, val) -> method.invoke(val, DateFormat.parse(Bytes.toLong(Bytes.copy(bytes, idx + offset, 8, le))));
case unix8 : return (bytes, idx, val) -> method.invoke(val, DateFormat.parse(Bytes.toLong(Bytes.copy(bytes, idx + offset, 8, le)) * 1000));
case unix4 : return (bytes, idx, val) -> method.invoke(val, DateFormat.parse(Integer.toUnsignedLong(Bytes.toInt(Bytes.copy(bytes, idx + offset, 4, le))) * 1000L));
}
break;
}
throw new IllegalArgumentException("does not support type, support type [Date, Calendar, DateFormat] : " + method.getName() + "("+genericParameterTypeName+") in the " + parentClassName);
}
}
|
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/ads/googleads/v6/enums/mobile_app_vendor.proto
package com.google.ads.googleads.v6.enums;
public final class MobileAppVendorProto {
private MobileAppVendorProto() {}
public static void registerAllExtensions(
com.google.protobuf.ExtensionRegistryLite registry) {
}
public static void registerAllExtensions(
com.google.protobuf.ExtensionRegistry registry) {
registerAllExtensions(
(com.google.protobuf.ExtensionRegistryLite) registry);
}
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_ads_googleads_v6_enums_MobileAppVendorEnum_descriptor;
static final
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_ads_googleads_v6_enums_MobileAppVendorEnum_fieldAccessorTable;
public static com.google.protobuf.Descriptors.FileDescriptor
getDescriptor() {
return descriptor;
}
private static com.google.protobuf.Descriptors.FileDescriptor
descriptor;
static {
java.lang.String[] descriptorData = {
"\n5google/ads/googleads/v6/enums/mobile_a" +
"pp_vendor.proto\022\035google.ads.googleads.v6" +
".enums\032\034google/api/annotations.proto\"q\n\023" +
"MobileAppVendorEnum\"Z\n\017MobileAppVendor\022\017" +
"\n\013UNSPECIFIED\020\000\022\013\n\007UNKNOWN\020\001\022\023\n\017APPLE_AP" +
"P_STORE\020\002\022\024\n\020GOOGLE_APP_STORE\020\003B\351\001\n!com." +
"google.ads.googleads.v6.enumsB\024MobileApp" +
"VendorProtoP\001ZBgoogle.golang.org/genprot" +
"o/googleapis/ads/googleads/v6/enums;enum" +
"s\242\002\003GAA\252\002\035Google.Ads.GoogleAds.V6.Enums\312" +
"\002\035Google\\Ads\\GoogleAds\\V6\\Enums\352\002!Google" +
"::Ads::GoogleAds::V6::Enumsb\006proto3"
};
descriptor = com.google.protobuf.Descriptors.FileDescriptor
.internalBuildGeneratedFileFrom(descriptorData,
new com.google.protobuf.Descriptors.FileDescriptor[] {
com.google.api.AnnotationsProto.getDescriptor(),
});
internal_static_google_ads_googleads_v6_enums_MobileAppVendorEnum_descriptor =
getDescriptor().getMessageTypes().get(0);
internal_static_google_ads_googleads_v6_enums_MobileAppVendorEnum_fieldAccessorTable = new
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_ads_googleads_v6_enums_MobileAppVendorEnum_descriptor,
new java.lang.String[] { });
com.google.api.AnnotationsProto.getDescriptor();
}
// @@protoc_insertion_point(outer_class_scope)
}
|
/*
* This file is part of VLCJ.
*
* VLCJ is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* VLCJ is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with VLCJ. If not, see <http://www.gnu.org/licenses/>.
*
* Copyright 2009, 2010, 2011, 2012, 2013, 2014, 2015 Caprica Software Limited.
*/
package uk.co.caprica.vlcj.player.events;
import uk.co.caprica.vlcj.player.MediaPlayer;
import uk.co.caprica.vlcj.player.MediaPlayerEventListener;
/**
*
*/
class MediaNewEvent extends AbstractMediaPlayerEvent {
/**
* Create a media player event.
*/
MediaNewEvent(MediaPlayer mediaPlayer) {
super(mediaPlayer);
}
@Override
public void notify(MediaPlayerEventListener listener) {
listener.newMedia(mediaPlayer);
}
}
|
/*
* JBoss, Home of Professional Open Source
*
* Copyright 2013 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.keycloak.dom.xmlsec.w3.xmldsig;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* <p>
* Java class for ManifestType complex type.
*
* <p>
* The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="ManifestType">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element ref="{http://www.w3.org/2000/09/xmldsig#}Reference" maxOccurs="unbounded"/>
* </sequence>
* <attribute name="Id" type="{http://www.w3.org/2001/XMLSchema}ID" />
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*/
public class ManifestType {
protected List<ReferenceType> reference = new ArrayList<ReferenceType>();
protected String id;
public void addReference(ReferenceType ref) {
this.reference.add(ref);
}
public void removeReference(ReferenceType ref) {
this.reference.remove(ref);
}
/**
* Gets the value of the reference property.
*
* <p>
* Objects of the following type(s) are allowed in the list {@link ReferenceType }
*/
public List<ReferenceType> getReference() {
return Collections.unmodifiableList(this.reference);
}
/**
* Gets the value of the id property.
*
* @return possible object is {@link String }
*/
public String getId() {
return id;
}
/**
* Sets the value of the id property.
*
* @param value allowed object is {@link String }
*/
public void setId(String value) {
this.id = value;
}
}
|
/*
* 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.
*
* Other licenses:
* -----------------------------------------------------------------------------
* Commercial licenses for this work are available. These replace the above
* ASL 2.0 and offer limited warranties, support, maintenance, and commercial
* database integrations.
*
* For more information, please visit: http://www.jooq.org/licenses
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*/
package org.jooq.impl;
import static java.lang.Boolean.FALSE;
import static org.jooq.conf.InvocationOrder.REVERSE;
import static org.jooq.impl.Tools.EMPTY_EXECUTE_LISTENER;
import java.util.ArrayList;
import java.util.List;
import org.jooq.ExecuteContext;
import org.jooq.ExecuteListener;
import org.jooq.ExecuteListenerProvider;
import org.jooq.conf.Settings;
import org.jooq.conf.SettingsTools;
import org.jooq.tools.JooqLogger;
import org.jooq.tools.LoggerListener;
/**
* A queue implementation for several {@link ExecuteListener} objects as defined
* in {@link Settings#getExecuteListeners()}
*
* @author Lukas Eder
*/
final class ExecuteListeners implements ExecuteListener {
/**
* Generated UID
*/
private static final long serialVersionUID = 7399239846062763212L;
private static final ExecuteListener EMPTY_LISTENER = new DefaultExecuteListener();
private static final JooqLogger LOGGER_LISTENER_LOGGER = JooqLogger.getLogger(LoggerListener.class);
private final ExecuteListener[][] listeners;
// In some setups, these two events may get mixed up chronologically by the
// Cursor. Postpone fetchEnd event until after resultEnd event, if there is
// an open Result
private boolean resultStart;
private boolean fetchEnd;
static ExecuteListener get(ExecuteContext ctx) {
ExecuteListener[][] listeners = listeners(ctx);
if (listeners == null)
return EMPTY_LISTENER;
else
return new ExecuteListeners(ctx, listeners);
}
/**
* Provide delegate listeners from an <code>ExecuteContext</code>
*/
private static final ExecuteListener[][] listeners(ExecuteContext ctx) {
List<ExecuteListener> list = null;
// jOOQ-internal listeners are added first, so their results are available to user-defined listeners
// -------------------------------------------------------------------------------------------------
// [#6580] Fetching server output may require some pre / post actions around the actual statement
if (SettingsTools.getFetchServerOutputSize(0, ctx.settings()) > 0)
(list = init(list)).add(new FetchServerOutputListener());
// [#6051] The previously used StopWatchListener is no longer included by default
if (!FALSE.equals(ctx.settings().isExecuteLogging())) {
// [#6747] Avoid allocating the listener (and by consequence, the ExecuteListeners) if
// we do not DEBUG log anyway.
if (LOGGER_LISTENER_LOGGER.isDebugEnabled())
(list = init(list)).add(new LoggerListener());
}
for (ExecuteListenerProvider provider : ctx.configuration().executeListenerProviders())
// Could be null after deserialisation
if (provider != null)
(list = init(list)).add(provider.provide());
if (list == null)
return null;
ExecuteListener[] def = list.toArray(EMPTY_EXECUTE_LISTENER);
ExecuteListener[] rev = null;
return new ExecuteListener[][] {
ctx.settings().getExecuteListenerStartInvocationOrder() != REVERSE ? def : ( rev = Tools.reverse(def.clone())),
ctx.settings().getExecuteListenerEndInvocationOrder() != REVERSE ? def : (rev != null ? rev : (rev = Tools.reverse(def.clone())))
};
}
private static final List<ExecuteListener> init(List<ExecuteListener> result) {
return result == null ? new ArrayList<>() : result;
}
private ExecuteListeners(ExecuteContext ctx, ExecuteListener[][] listeners) {
this.listeners = listeners;
start(ctx);
}
@Override
public final void start(ExecuteContext ctx) {
for (ExecuteListener listener : listeners[0])
listener.start(ctx);
}
@Override
public final void renderStart(ExecuteContext ctx) {
for (ExecuteListener listener : listeners[0])
listener.renderStart(ctx);
}
@Override
public final void renderEnd(ExecuteContext ctx) {
for (ExecuteListener listener : listeners[1])
listener.renderEnd(ctx);
}
@Override
public final void prepareStart(ExecuteContext ctx) {
for (ExecuteListener listener : listeners[0])
listener.prepareStart(ctx);
}
@Override
public final void prepareEnd(ExecuteContext ctx) {
for (ExecuteListener listener : listeners[1])
listener.prepareEnd(ctx);
}
@Override
public final void bindStart(ExecuteContext ctx) {
for (ExecuteListener listener : listeners[0])
listener.bindStart(ctx);
}
@Override
public final void bindEnd(ExecuteContext ctx) {
for (ExecuteListener listener : listeners[1])
listener.bindEnd(ctx);
}
@Override
public final void executeStart(ExecuteContext ctx) {
if (ctx instanceof DefaultExecuteContext)
((DefaultExecuteContext) ctx).incrementStatementExecutionCount();
for (ExecuteListener listener : listeners[0])
listener.executeStart(ctx);
}
@Override
public final void executeEnd(ExecuteContext ctx) {
for (ExecuteListener listener : listeners[1])
listener.executeEnd(ctx);
}
@Override
public final void fetchStart(ExecuteContext ctx) {
for (ExecuteListener listener : listeners[0])
listener.fetchStart(ctx);
}
@Override
public final void outStart(ExecuteContext ctx) {
for (ExecuteListener listener : listeners[0])
listener.outStart(ctx);
}
@Override
public final void outEnd(ExecuteContext ctx) {
for (ExecuteListener listener : listeners[1])
listener.outEnd(ctx);
}
@Override
public final void resultStart(ExecuteContext ctx) {
resultStart = true;
for (ExecuteListener listener : listeners[0])
listener.resultStart(ctx);
}
@Override
public final void recordStart(ExecuteContext ctx) {
for (ExecuteListener listener : listeners[0])
listener.recordStart(ctx);
}
@Override
public final void recordEnd(ExecuteContext ctx) {
for (ExecuteListener listener : listeners[1])
listener.recordEnd(ctx);
}
@Override
public final void resultEnd(ExecuteContext ctx) {
resultStart = false;
for (ExecuteListener listener : listeners[1])
listener.resultEnd(ctx);
if (fetchEnd)
fetchEnd(ctx);
}
@Override
public final void fetchEnd(ExecuteContext ctx) {
if (resultStart)
fetchEnd = true;
else
for (ExecuteListener listener : listeners[1])
listener.fetchEnd(ctx);
}
@Override
public final void end(ExecuteContext ctx) {
for (ExecuteListener listener : listeners[1])
listener.end(ctx);
}
@Override
public final void exception(ExecuteContext ctx) {
for (ExecuteListener listener : listeners[0])
listener.exception(ctx);
}
@Override
public final void warning(ExecuteContext ctx) {
for (ExecuteListener listener : listeners[0])
listener.warning(ctx);
}
}
|
/*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @author cdr
*/
package com.intellij.codeInspection.i18n;
import com.intellij.codeInsight.CodeInsightBundle;
import com.intellij.codeInsight.intention.IntentionAction;
import com.intellij.ide.fileTemplates.FileTemplate;
import com.intellij.ide.fileTemplates.FileTemplateManager;
import com.intellij.ide.fileTemplates.impl.FileTemplateConfigurable;
import com.intellij.lang.properties.psi.I18nizedTextGenerator;
import com.intellij.lang.properties.psi.PropertiesFile;
import com.intellij.lang.properties.psi.PropertyCreationHandler;
import com.intellij.lang.properties.psi.ResourceBundleManager;
import com.intellij.lang.properties.references.I18nizeQuickFixDialog;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.event.DocumentAdapter;
import com.intellij.openapi.fileTypes.StdFileTypes;
import com.intellij.openapi.options.ShowSettingsUtil;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.ui.ex.MultiLineLabel;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.*;
import com.intellij.ui.EditorComboBox;
import com.intellij.ui.HyperlinkLabel;
import com.intellij.util.ArrayUtil;
import com.intellij.util.IncorrectOperationException;
import gnu.trove.THashMap;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkListener;
import java.awt.*;
import java.io.IOException;
import java.util.*;
import java.util.List;
public class JavaI18nizeQuickFixDialog extends I18nizeQuickFixDialog {
private final PsiLiteralExpression myLiteralExpression;
private final JLabel myPreviewLabel;
private final JPanel myHyperLinkPanel;
private final JPanel myResourceBundleSuggester;
private EditorComboBox myRBEditorTextField;
private final JPanel myJavaCodeInfoPanel;
private final JPanel myPreviewPanel;
private PsiClassType myResourceBundleType;
protected final ResourceBundleManager myResourceBundleManager;
private final boolean myShowJavaCodeInfo;
private final boolean myShowPreview;
@NonNls public static final String PROPERTY_KEY_OPTION_KEY = "PROPERTY_KEY";
@NonNls private static final String RESOURCE_BUNDLE_OPTION_KEY = "RESOURCE_BUNDLE";
@NonNls public static final String PROPERTY_VALUE_ATTR = "PROPERTY_VALUE";
public JavaI18nizeQuickFixDialog(@NotNull Project project,
@NotNull final PsiFile context,
@Nullable final PsiLiteralExpression literalExpression,
String defaultPropertyValue,
DialogCustomization customization,
final boolean showJavaCodeInfo,
final boolean showPreview) {
super(project, context, defaultPropertyValue, customization, true);
ResourceBundleManager resourceBundleManager = null;
try {
resourceBundleManager = ResourceBundleManager.getManager(context);
LOG.assertTrue(resourceBundleManager != null);
}
catch (ResourceBundleManager.ResourceBundleNotFoundException e) {
LOG.error(e);
}
myResourceBundleManager = resourceBundleManager;
JavaExtensibilityData data = new JavaExtensibilityData();
myExtensibilityPanel.setLayout(new BorderLayout());
myExtensibilityPanel.add(data.myPanel, BorderLayout.CENTER);
myJavaCodeInfoPanel = data.myJavaCodeInfoPanel;
myPreviewPanel = data.myPreviewPanel;
myHyperLinkPanel = data.myHyperLinkPanel;
myResourceBundleSuggester = data.myResourceBundleSuggester;
myPreviewLabel = data.myPreviewLabel;
myLiteralExpression = literalExpression;
myShowPreview = showPreview;
myResourceBundleSuggester.setLayout(new BorderLayout());
PsiElementFactory factory = JavaPsiFacade.getInstance(myProject).getElementFactory();
PsiClass resourceBundle = myResourceBundleManager.getResourceBundle();
myShowJavaCodeInfo = showJavaCodeInfo && myResourceBundleManager.canShowJavaCodeInfo();
if (myShowJavaCodeInfo) {
LOG.assertTrue(resourceBundle != null);
myResourceBundleType = factory.createType(resourceBundle);
@NonNls String defaultVarName = "resourceBundle";
final JavaCodeFragmentFactory codeFragmentFactory = JavaCodeFragmentFactory.getInstance(project);
PsiExpressionCodeFragment expressionCodeFragment =
codeFragmentFactory.createExpressionCodeFragment(defaultVarName, myLiteralExpression, myResourceBundleType, true);
Document document = PsiDocumentManager.getInstance(myProject).getDocument(expressionCodeFragment);
myRBEditorTextField = new EditorComboBox(document, myProject, StdFileTypes.JAVA);
myResourceBundleSuggester.add(myRBEditorTextField, BorderLayout.CENTER);
suggestAvailableResourceBundleExpressions();
myRBEditorTextField.addDocumentListener(new DocumentAdapter() {
@Override
public void documentChanged(com.intellij.openapi.editor.event.DocumentEvent e) {
somethingChanged();
}
});
}
myHyperLinkPanel.setLayout(new BorderLayout());
final String templateName = getTemplateName();
if (templateName != null) {
HyperlinkLabel link = new HyperlinkLabel(CodeInsightBundle.message("i18nize.dialog.template.link.label"));
link.addHyperlinkListener(new HyperlinkListener() {
@Override
public void hyperlinkUpdate(HyperlinkEvent e) {
final FileTemplateConfigurable configurable = new FileTemplateConfigurable();
final FileTemplate template = FileTemplateManager.getInstance().getCodeTemplate(templateName);
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
configurable.setTemplate(template, null);
}
});
boolean ok = ShowSettingsUtil.getInstance().editConfigurable(myPanel, configurable);
if (ok) {
somethingChanged();
if (myShowJavaCodeInfo) {
suggestAvailableResourceBundleExpressions();
}
}
}
});
myHyperLinkPanel.add(link, BorderLayout.CENTER);
}
if (!myShowJavaCodeInfo) {
myJavaCodeInfoPanel.setVisible(false);
}
if (!myShowPreview) {
myPreviewPanel.setVisible(false);
}
init();
}
public static boolean isAvailable(PsiFile file) {
final Project project = file.getProject();
final String title = CodeInsightBundle.message("i18nize.dialog.error.jdk.title");
try {
return ResourceBundleManager.getManager(file) != null;
}
catch (ResourceBundleManager.ResourceBundleNotFoundException e) {
final IntentionAction fix = e.getFix();
if (fix != null) {
if (Messages.showOkCancelDialog(project, e.getMessage(), title, Messages.getErrorIcon()) == OK_EXIT_CODE) {
try {
fix.invoke(project, null, file);
return false;
}
catch (IncorrectOperationException e1) {
LOG.error(e1);
}
}
}
Messages.showErrorDialog(project, e.getMessage(), title);
return false;
}
}
public PropertyCreationHandler getPropertyCreationHandler() {
PropertyCreationHandler handler = myResourceBundleManager.getPropertyCreationHandler();
return handler != null ? handler : JavaI18nUtil.DEFAULT_PROPERTY_CREATION_HANDLER;
}
private void suggestAvailableResourceBundleExpressions() {
String templateName = getTemplateName();
if (templateName == null) return;
if (myShowJavaCodeInfo) {
FileTemplate template = FileTemplateManager.getInstance().getCodeTemplate(templateName);
boolean showResourceBundleSuggester = template.getText().contains("${" + RESOURCE_BUNDLE_OPTION_KEY + "}");
myJavaCodeInfoPanel.setVisible(showResourceBundleSuggester);
}
Set<String> result = JavaI18nUtil.suggestExpressionOfType(myResourceBundleType, myLiteralExpression);
if (result.isEmpty()) {
result.add(getResourceBundleText());
}
myRBEditorTextField.setHistory(ArrayUtil.toStringArray(result));
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
myRBEditorTextField.setSelectedIndex(0);
}
});
}
@Override
protected void somethingChanged() {
if (myShowPreview) {
myPreviewLabel.setText(getI18nizedText());
}
super.somethingChanged();
}
@Nullable
protected String getTemplateName() {
return myResourceBundleManager.getTemplateName();
}
@Override
protected String defaultSuggestPropertyKey(String value) {
return myResourceBundleManager.suggestPropertyKey(value);
}
@Override
protected List<String> defaultSuggestPropertiesFiles() {
return myResourceBundleManager.suggestPropertiesFiles();
}
public String getI18nizedText() {
String propertyKey = StringUtil.escapeStringCharacters(getKey());
I18nizedTextGenerator textGenerator = myResourceBundleManager.getI18nizedTextGenerator();
if (textGenerator != null) {
return generateText(textGenerator, propertyKey, getPropertiesFile(), myLiteralExpression);
}
String templateName = getTemplateName();
LOG.assertTrue(templateName != null);
FileTemplate template = FileTemplateManager.getInstance().getCodeTemplate(templateName);
Map<String, String> attributes = new THashMap<String, String>();
attributes.put(PROPERTY_KEY_OPTION_KEY, propertyKey);
attributes.put(RESOURCE_BUNDLE_OPTION_KEY, getResourceBundleText());
attributes.put(PROPERTY_VALUE_ATTR, StringUtil.escapeStringCharacters(myDefaultPropertyValue));
addAdditionalAttributes(attributes);
String text = null;
try {
text = template.getText(attributes);
}
catch (IOException e) {
LOG.error(e);
}
return text;
}
protected String generateText(final I18nizedTextGenerator textGenerator,
final String propertyKey,
final PropertiesFile propertiesFile,
final PsiLiteralExpression literalExpression) {
return textGenerator.getI18nizedText(propertyKey, propertiesFile, literalExpression);
}
protected void addAdditionalAttributes(final Map<String, String> attributes) {
}
private String getResourceBundleText() {
return myShowJavaCodeInfo ? myRBEditorTextField.getText() : null;
}
public PsiLiteralExpression getLiteralExpression() {
return myLiteralExpression;
}
public PsiExpression[] getParameters() {
return PsiExpression.EMPTY_ARRAY;
}
static class JavaExtensibilityData {
private JPanel myPreviewPanel;
private JPanel myJavaCodeInfoPanel;
private JPanel myPanel;
private JPanel myHyperLinkPanel;
private MultiLineLabel myPreviewLabel;
private JPanel myResourceBundleSuggester;
}
}
|
package com.vacomall.mapper;
import com.baomidou.mybatisplus.mapper.BaseMapper;
import com.vacomall.entity.SysRole;
/**
*
* SysRole 表数据库控制层接口
*
*/
public interface SysRoleMapper extends BaseMapper<SysRole> {
}
|
/*
* The MIT License (MIT)
*
* Copyright © 2013-2021 Florian Barras <https://barras.io> (florian@barras.io)
*
* 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 jupiter.media.audio;
import static jupiter.common.io.InputOutput.IO;
import static jupiter.common.util.Characters.SEMICOLON;
import static jupiter.media.audio.Audio.AUDIO_FORMAT;
import java.awt.HeadlessException;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import javax.sound.sampled.AudioFileFormat.Type;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.LineUnavailableException;
import javax.swing.JOptionPane;
import jupiter.common.model.ICloneable;
import jupiter.common.struct.list.ExtendedLinkedList;
import jupiter.common.time.Dates;
import jupiter.common.util.Objects;
import jupiter.common.util.Strings;
import jupiter.gui.swing.Swings;
public class AudioRecorder
implements ICloneable<AudioRecorder>, Serializable {
////////////////////////////////////////////////////////////////////////////////////////////////
// CONSTANTS
////////////////////////////////////////////////////////////////////////////////////////////////
/**
* The generated serial version ID.
*/
private static final long serialVersionUID = 1L;
////////////////////////////////////////////////////////////////////////////////////////////////
// ATTRIBUTES
////////////////////////////////////////////////////////////////////////////////////////////////
/**
* The {@link AudioFormat}.
*/
protected final AudioFormat format;
/**
* The {@link AudioTargetInterface}.
*/
protected AudioTargetInterface targetInterface = null;
/**
* The internal {@link Lock}.
*/
protected final Lock lock = new ReentrantLock(true);
protected final Condition lockCondition = lock.newCondition();
/**
* The recording time (in seconds).
*/
protected Integer recordingTime = null;
////////////////////////////////////////////////////////////////////////////////////////////////
// CONSTRUCTORS
////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Constructs an {@link AudioRecorder} by default.
*/
public AudioRecorder() {
this(AUDIO_FORMAT);
}
/**
* Constructs an {@link AudioRecorder} with the specified {@link AudioFormat}.
* <p>
* @param format the {@link AudioFormat}
*/
public AudioRecorder(final AudioFormat format) {
this.format = format;
}
////////////////////////////////////////////////////////////////////////////////////////////////
// ACCESSORS
////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Sets the {@link AudioTargetInterface}.
* <p>
* @param targetInterface an {@link AudioTargetInterface}
*/
public void setTargetInterface(final AudioTargetInterface targetInterface) {
this.targetInterface = targetInterface;
}
/**
* Sets the {@link AudioTargetInterface} with the specified mixer name.
* <p>
* @param mixerName a {@link String}
*/
public void setTargetInterface(final String mixerName) {
final ExtendedLinkedList<AudioTargetInterface> targetInterfaces = Audio.getTargetInterfaces(
mixerName);
final int targetInterfaceCount = targetInterfaces.size();
if (targetInterfaceCount > 0) {
if (targetInterfaceCount > 1) {
IO.warn("Multiple microphones with the mixer name",
Strings.quote(mixerName) + SEMICOLON, targetInterfaces);
}
targetInterface = targetInterfaces.getFirst();
IO.info("Select the microphone:", targetInterface);
} else {
IO.warn("No microphone with the mixer name", Strings.quote(mixerName));
}
}
////////////////////////////////////////////////////////////////////////////////////////////////
// PROCESSORS
////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Captures the audio.
* <p>
* @return the WAV {@link File} containing the recording
*/
public File capture() {
new Thread() {
@Override
public void run() {
try {
// Prompt to select the microphone
selectMicrophone();
// Prompt to enter the recording time (in seconds)
enterRecordingTime();
// Start recording
startRecording();
// Show the recording progress
Swings.showTimeProgressBar("Recording...", recordingTime * 1000);
} catch (final HeadlessException ex) {
IO.error(ex, "The environment does not support display");
} catch (final NumberFormatException ex) {
IO.error(ex, "Cannot parse the recording time");
} finally {
// Stop recording
stopRecording();
}
}
}.start();
return record();
}
////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Starts recording.
*/
protected void startRecording() {
lock.lock();
try {
lockCondition.signal();
} finally {
lock.unlock();
}
}
/**
* Stops recording.
*/
protected void stopRecording() {
if (targetInterface != null && targetInterface.line != null) {
targetInterface.line.stop();
}
}
/**
* Waits until the fields are set.
*/
protected void waitUntilReady() {
lock.lock();
try {
while (targetInterface == null || targetInterface.line == null ||
recordingTime == null) {
lockCondition.await();
}
} catch (final InterruptedException ignored) {
} finally {
lock.unlock();
}
}
////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Records the audio.
* <p>
* @return the WAV {@link File} containing the recording
*/
protected File record() {
File targetFile = null;
try {
// Wait until the fields are set
waitUntilReady();
// Record with the microphone in the format to the target file
targetFile = record(targetInterface, format);
} finally {
if (targetInterface != null && targetInterface.line != null) {
targetInterface.line.close();
}
if (targetFile != null) {
JOptionPane.showMessageDialog(null, "Finish recording to " +
Strings.quote(targetFile) + ".");
} else {
JOptionPane.showMessageDialog(null, "Fail to record.");
}
}
return targetFile;
}
//////////////////////////////////////////////
/**
* Records the audio with the specified {@link AudioTargetInterface}.
* <p>
* @param targetInterface the {@link AudioTargetInterface} to record with
* <p>
* @return the WAV {@link File} containing the recording
*/
public static File record(final AudioTargetInterface targetInterface) {
final File targetFile = new File(Dates.getTimestamp() + ".wav");
record(targetInterface, targetFile, AUDIO_FORMAT);
return targetFile;
}
/**
* Records the audio with the specified {@link AudioTargetInterface} in the specified
* {@link AudioFormat}.
* <p>
* @param targetInterface the {@link AudioTargetInterface} to record with
* @param format the {@link AudioFormat} to record in
* <p>
* @return the WAV {@link File} containing the recording
*/
public static File record(final AudioTargetInterface targetInterface,
final AudioFormat format) {
final File targetFile = new File(Dates.getTimestamp() + ".wav");
record(targetInterface, targetFile, format);
return targetFile;
}
/**
* Records the audio with the specified {@link AudioTargetInterface} to the specified WAV
* {@link File}.
* <p>
* @param targetInterface the {@link AudioTargetInterface} to record with
* @param targetFile the WAV {@link File} to record to
*/
public static void record(final AudioTargetInterface targetInterface, final File targetFile) {
record(targetInterface, targetFile, AUDIO_FORMAT);
}
/**
* Records the audio with the specified {@link AudioTargetInterface} to the specified WAV
* {@link File} and in the specified {@link AudioFormat}.
* <p>
* @param targetInterface the {@link AudioTargetInterface} to record with
* @param targetFile the WAV {@link File} to record to
* @param format the {@link AudioFormat} to record in
*/
public static void record(final AudioTargetInterface targetInterface, final File targetFile,
final AudioFormat format) {
try {
IO.info("Start recording to", Strings.quote(targetFile));
targetInterface.line.open(format);
targetInterface.line.start();
final AudioInputStream input = new AudioInputStream(targetInterface.line);
AudioSystem.write(input, Type.WAVE, targetFile);
IO.info("Finish recording to", Strings.quote(targetFile));
} catch (final LineUnavailableException ex) {
IO.error(ex, "Cannot open the microphone due to resource restrictions");
} catch (final IOException ex) {
IO.error(ex);
}
}
////////////////////////////////////////////////////////////////////////////////////////////////
// GUI
////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Prompts to select the {@link AudioTargetInterface}.
*/
protected void selectMicrophone() {
while (targetInterface == null || targetInterface.line == null) {
final ExtendedLinkedList<AudioTargetInterface> targetInterfaces = Audio.getTargetInterfaces();
if (targetInterfaces.isEmpty()) {
throw new IllegalStateException("No available microphone");
}
targetInterface = (AudioTargetInterface) JOptionPane.showInputDialog(
null, "Select the microphone:", "Microphone Selection",
JOptionPane.QUESTION_MESSAGE, null, targetInterfaces.toArray(),
targetInterfaces.getFirst());
}
}
/**
* Prompts to enter the recording time (in seconds).
*/
protected void enterRecordingTime() {
while (recordingTime == null) {
recordingTime = Integer.parseInt(JOptionPane.showInputDialog(null,
"How many seconds do you want to record?", "Recording Time",
JOptionPane.QUESTION_MESSAGE)); // [s]
}
}
////////////////////////////////////////////////////////////////////////////////////////////////
// OBJECT
////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Clones {@code this}.
* <p>
* @return a clone of {@code this}
*
* @see ICloneable
*/
@Override
public AudioRecorder clone() {
try {
return (AudioRecorder) super.clone();
} catch (final CloneNotSupportedException ex) {
throw new IllegalStateException(Objects.toString(ex), ex);
}
}
}
|
/*
* The MIT License (MIT)
*
* Copyright (c) 2010 Technische Universitaet Berlin
*
* 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 net.mumie.jvmd.cmd;
import java.io.File;
import java.util.List;
import java.util.ArrayList;
import java.io.PrintStream;
import java.io.InputStream;
/**
* <p>
* Abstract base class for implementing Jvmd commands. Provides member variables for the
* i/o streams, the command line parameters, and the working directory (see <em>Field
* Summery</em> below). The respective getXxx, setXxx, and addXxx methods required by the
* {@link Command Command} interface are implemented accordingly. Another member variable
* is the so-called <em>stop flag</em> (see {@link #stop stop}). This boolean flag is
* false by default and set to true if the {@link #stop() stop()} method is
* called. Extending classes should check the flag at appropriate times and throw a
* {@link CommandStoppedException CommandStoppedException} if it is true. For convenience,
* a method {@link #checkStop checkStop} is provided which performs the checking and
* exception throwing.
* </p>
* <p>
* This class contains some utility methods:
* {@link #makeAbsoluteFile(File) makeAbsoluteFile(<var>File</var>)} and
* {@link #makeAbsoluteFile(String) makeAbsoluteFile(<var>String</var>)},
* which make relative file paths absolute with respect to the command's working
* directory; and {@link #expandShortOptions expandShortOptions}, which expands bundled
* short options (e.g., converts <code>-rfq</code> to <code>-r -f -q</code>).
* </p>
* <p>
* <strong>Please note:</strong> Do not use <code>myFile.getAbsoluteFile()</code> to make a
* {@link File File} object absolute in a Jvmd command – that would interpret
* <code>myFile</code> relative to the directory where you started the Jvmd server, not
* relative to the working directory of the command. Use
* <code>makeAbsoluteFile(myFile)</code> instead. (If <code>myFile</code> is already
* absolute, this is no issue, of course). The same applies to strings denoting relative
* paths.
* </p>
*
* @author Tilman Rassy <a href="mailto:rassy@math.tu-berlin.de">rassy@math.tu-berlin.de</a>
* @version <code>$Id: AbstractCommand.java,v 1.7 2007/07/16 10:49:29 grudzin Exp $</code>
*/
abstract public class AbstractCommand
implements Command
{
/**
* The working directory.
*/
protected File directory = null;
/**
* The parameters.
*/
protected List params = new ArrayList();
/**
* The input stream.
*/
protected InputStream in = null;
/**
* The output stream.
*/
protected PrintStream out = null;
/**
* The error stream.
*/
protected PrintStream err = null;
/**
* Flag indicating that this command should terminate execution..
*/
protected boolean stop = false;
/**
* Sets the working directory.
*/
public void setDirectory (File directory)
{
if ( !directory.exists() )
throw new IllegalArgumentException
("Working directory does not exist: " + directory);
if ( !directory.isDirectory() )
throw new IllegalArgumentException
("File specified as working directory is not a directory: " + directory);
this.directory = directory;
}
/**
* Returns the working directory.
*/
public File getDirectory ()
{
return this.directory;
}
/**
* Adds a command line parameter.
*/
public void addParameter (String parameter)
{
this.params.add(parameter);
}
/**
* Sets the input stream.
*/
public void setInputStream (InputStream in)
{
this.in = in;
}
/**
* Sets the output stream.
*/
public void setOutputStream (PrintStream out)
{
this.out = out;
}
/**
* Sets the error stream.
*/
public void setErrorStream (PrintStream err)
{
this.err = err;
}
/**
* Stops (or tries to stop) the execution of this command. This implementation sets the
* {@link #stop stop} flag to <code>true</code>. This implementation is synchronized.
*/
public synchronized void stop ()
{
this.stop = true;
}
/**
* Throws a {@link CommandStoppedException CommandStoppedException} if the
* {@link #stop stop} flag is set.
*/
protected void checkStop ()
throws CommandStoppedException
{
if ( this.stop )
throw new CommandStoppedException ();
}
/**
* Resets this instance for later reuse. This implemetation does the following:
* <ul>
* <li>The variables
* {@link #directory},
* {@link #in},
* {@link #out},
* {@link #err}, and
* {@link #stop}
* are set to null,</li>
* <li>The variable {@link #params} is set to a newly created, empty list.</li>
* </ul>
*/
public void reset ()
{
this.directory = null;
this.params = new ArrayList();
this.in = null;
this.out = null;
this.err = null;
this.stop = false;
}
/**
* Makes the specified file object absolute and returns it. If the file object is already
* absolute, it is simply returned. Otherwise, it is made absolute with
* {@link #directory directory} as parent.
*/
protected File makeAbsoluteFile (File file)
{
return (file.isAbsolute() ? file : new File(this.directory, file.getPath()));
}
/**
* <p>
* Makes the specified fileanme absolute and returns it a {@link File File} object. If
* the filename is already absolute, simply returns it a {@link File File} object.
* Otherwise, it is made absolute with {@link #directory directory} as parent.
* </p>
* <p>
* Same as
* {@link #makeAbsoluteFile(File) makeAbsoluteFile(new File(filename))}.
* </p>
*/
protected File makeAbsoluteFile (String filename)
{
return this.makeAbsoluteFile(new File(filename));
}
/**
* Expands boundled short options in the parameters. For example, replaces
* <code>-rbf</code> by <code>-r -b -f</code>. The string <code>shortOptions</code>
* specifies the short options that should be expanded. Each parameter that starts with a
* hyphen and contains only characters in <code>shortOptions</code> is replaced.
*/
protected void expandShortOptions (String shortOptions)
{
for (int i = 0; i < this.params.size(); i++)
{
char[] paramChars = ((String)this.params.get(i)).toCharArray();
if ( paramChars[0] == '-' )
{
// Checking if parameter contains only short option characters after the dash ...
int k = 1;
while ( k < paramChars.length && shortOptions.indexOf(paramChars[k]) != -1 ) k++;
if ( k == paramChars.length )
{ // ... yes.
this.params.remove(i);
i--;
for (int m = 1; m < paramChars.length; m++)
{
i++;
char[] expandedParamChars = {'-', paramChars[m]};
this.params.add(i, new String(expandedParamChars));
}
}
}
}
}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more contributor license
* agreements. See the NOTICE file distributed with this work for additional information regarding
* copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the License. You may obtain a
* copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable
* law or agreed to in writing, software distributed under the License is distributed on an "AS IS"
* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License
* for the specific language governing permissions and limitations under the License.
*/
package org.apache.hadoop.hbase.replication.regionserver;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileUtil;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.HConstants;
import org.apache.yetus.audience.InterfaceAudience;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This will load all the xml configuration files for the source cluster replication ID from
* user configured replication configuration directory.
*/
@InterfaceAudience.Private
public class DefaultSourceFSConfigurationProvider implements SourceFSConfigurationProvider {
private static final Logger LOG =
LoggerFactory.getLogger(DefaultSourceFSConfigurationProvider.class);
// Map containing all the source clusters configurations against their replication cluster id
private final Map<String, Configuration> sourceClustersConfs = new HashMap<>();
private static final String XML = ".xml";
@Override
public Configuration getConf(Configuration sinkConf, String replicationClusterId)
throws IOException {
if (sourceClustersConfs.get(replicationClusterId) == null) {
synchronized (this.sourceClustersConfs) {
if (sourceClustersConfs.get(replicationClusterId) == null) {
LOG.info("Loading source cluster FS client conf for cluster " + replicationClusterId);
// Load only user provided client configurations.
Configuration sourceClusterConf = new Configuration(false);
String replicationConfDir = sinkConf.get(HConstants.REPLICATION_CONF_DIR);
if (replicationConfDir == null) {
LOG.debug(HConstants.REPLICATION_CONF_DIR + " is not configured.");
URL resource = HBaseConfiguration.class.getClassLoader().getResource("hbase-site.xml");
if (resource != null) {
String path = resource.getPath();
replicationConfDir = path.substring(0, path.lastIndexOf("/"));
} else {
replicationConfDir = System.getenv("HBASE_CONF_DIR");
}
}
File confDir = new File(replicationConfDir, replicationClusterId);
LOG.info("Loading source cluster " + replicationClusterId
+ " file system configurations from xml "
+ "files under directory " + confDir);
String[] listofConfFiles = FileUtil.list(confDir);
for (String confFile : listofConfFiles) {
if (new File(confDir, confFile).isFile() && confFile.endsWith(XML)) {
// Add all the user provided client conf files
sourceClusterConf.addResource(new Path(confDir.getPath(), confFile));
}
}
this.sourceClustersConfs.put(replicationClusterId, sourceClusterConf);
}
}
}
return this.sourceClustersConfs.get(replicationClusterId);
}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.xream.rey.spring.beanconfiguration;
import io.xream.rey.api.ClientTemplate;
import io.xream.rey.internal.ClientBackend;
import io.xream.rey.internal.ClientBackendImpl;
import io.xream.rey.internal.ClientExceptionHandler;
import io.xream.rey.internal.DefaultClientTemplate;
import org.springframework.context.annotation.Bean;
/**
* @author Rolyer Luo
*/
public class ReyClientConfig {
@Bean
public ClientTemplate clientTemplate() {
return new DefaultClientTemplate();
}
@Bean
public ClientBackend clientBackend(ClientExceptionHandler clientExceptionHandler, ClientTemplate wrapper) {
ClientBackendImpl clientBackend = new ClientBackendImpl(wrapper);
clientBackend.setClientExceptionHandler(clientExceptionHandler);
return clientBackend;
}
}
|
/*
* Copyright 2004-2010 the Seasar Foundation and the Others.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
package org.seasar.doma.internal.apt.meta;
import static org.seasar.doma.internal.util.AssertionUtil.assertNotNull;
import java.io.File;
import javax.annotation.processing.ProcessingEnvironment;
import javax.lang.model.element.ExecutableElement;
import org.seasar.doma.internal.apt.AptException;
import org.seasar.doma.internal.apt.mirror.ScriptMirror;
import org.seasar.doma.internal.jdbc.util.ScriptFileUtil;
import org.seasar.doma.message.Message;
/**
* @author taedium
*
*/
public class SqlFileScriptQueryMetaFactory extends
AbstractSqlFileQueryMetaFactory<SqlFileScriptQueryMeta> {
public SqlFileScriptQueryMetaFactory(ProcessingEnvironment env) {
super(env);
}
@Override
public QueryMeta createQueryMeta(ExecutableElement method, DaoMeta daoMeta) {
assertNotNull(method, daoMeta);
SqlFileScriptQueryMeta queryMeta = createSqlFileScriptQueryMeta(method,
daoMeta);
if (queryMeta == null) {
return null;
}
doTypeParameters(queryMeta, method, daoMeta);
doReturnType(queryMeta, method, daoMeta);
doParameters(queryMeta, method, daoMeta);
doThrowTypes(queryMeta, method, daoMeta);
doSqlFiles(queryMeta, method, daoMeta, false);
return queryMeta;
}
protected SqlFileScriptQueryMeta createSqlFileScriptQueryMeta(
ExecutableElement method, DaoMeta daoMeta) {
SqlFileScriptQueryMeta queryMeta = new SqlFileScriptQueryMeta(method);
ScriptMirror scriptMirror = ScriptMirror.newInstance(method, env);
if (scriptMirror == null) {
return null;
}
queryMeta.setScriptMirror(scriptMirror);
queryMeta.setQueryKind(QueryKind.SQLFILE_SCRIPT);
return queryMeta;
}
@Override
protected void doReturnType(SqlFileScriptQueryMeta queryMeta,
ExecutableElement method, DaoMeta daoMeta) {
QueryReturnMeta returnMeta = createReturnMeta(method);
if (!returnMeta.isPrimitiveVoid()) {
throw new AptException(Message.DOMA4172, env,
returnMeta.getElement());
}
queryMeta.setReturnMeta(returnMeta);
}
@Override
protected void doParameters(SqlFileScriptQueryMeta queryMeta,
ExecutableElement method, DaoMeta daoMeta) {
if (!method.getParameters().isEmpty()) {
throw new AptException(Message.DOMA4173, env, method);
}
}
@Override
protected void doSqlFiles(SqlFileScriptQueryMeta queryMeta,
ExecutableElement method, DaoMeta daoMeta, boolean expandable) {
String filePath = ScriptFileUtil.buildPath(daoMeta.getDaoElement()
.getQualifiedName().toString(), queryMeta.getName());
File file = getFile(queryMeta, method, filePath);
File[] siblingfiles = getSiblingFiles(queryMeta, method, file);
String methodName = queryMeta.getName();
for (File siblingfile : siblingfiles) {
if (ScriptFileUtil.isScriptFile(siblingfile, methodName)) {
String fileName = siblingfile.getName();
queryMeta.addFileName(fileName);
}
}
}
}
|
/*
* Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package sun.java2d.jules;
import java.util.*;
public class IdleTileCache {
final static int IDLE_TILE_SYNC_GRANULARITY = 16;
final static ArrayList<JulesTile> idleBuffers = new ArrayList<JulesTile>();
ArrayList<JulesTile> idleTileWorkerCacheList = new ArrayList<JulesTile>();
ArrayList<JulesTile> idleTileConsumerCacheList =
new ArrayList<JulesTile>(IDLE_TILE_SYNC_GRANULARITY);
/**
* Return a cached Tile, if possible from cache.
* Allowed caller: Rasterizer/Producer-Thread
*
* @param: maxCache - Specify the maximum amount of tiles needed
*/
public JulesTile getIdleTileWorker(int maxCache) {
/* Try to fetch idle tiles from the global cache list */
if (idleTileWorkerCacheList.size() == 0) {
idleTileWorkerCacheList.ensureCapacity(maxCache);
synchronized (idleBuffers) {
for (int i = 0; i < maxCache && idleBuffers.size() > 0; i++) {
idleTileWorkerCacheList.add(
idleBuffers.remove(idleBuffers.size() - 1));
}
}
}
if (idleTileWorkerCacheList.size() > 0) {
return idleTileWorkerCacheList.remove(idleTileWorkerCacheList.size() - 1);
}
return new JulesTile();
}
/**
* Release tile and allow it to be re-used by another thread. Allowed
* Allowed caller: MaskBlit/Consumer-Thread
*/
public void releaseTile(JulesTile tile) {
if (tile != null && tile.hasBuffer()) {
idleTileConsumerCacheList.add(tile);
if (idleTileConsumerCacheList.size() > IDLE_TILE_SYNC_GRANULARITY) {
synchronized (idleBuffers) {
idleBuffers.addAll(idleTileConsumerCacheList);
}
idleTileConsumerCacheList.clear();
}
}
}
/**
* Releases thread-local tiles cached for use by the rasterizing thread.
* Allowed caller: Rasterizer/Producer-Thread
*/
public void disposeRasterizerResources() {
releaseTiles(idleTileWorkerCacheList);
}
/**
* Releases thread-local tiles cached for performance reasons. Allowed
* Allowed caller: MaskBlit/Consumer-Thread
*/
public void disposeConsumerResources() {
releaseTiles(idleTileConsumerCacheList);
}
/**
* Release a list of tiles and allow it to be re-used by another thread.
* Thread safe.
*/
public void releaseTiles(List<JulesTile> tileList) {
if (tileList.size() > 0) {
synchronized (idleBuffers) {
idleBuffers.addAll(tileList);
}
tileList.clear();
}
}
}
|
/*
* Copyright 2017 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.workbench.screens.dsltext.backend.server;
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.event.Event;
import javax.inject.Inject;
import org.drools.workbench.screens.dsltext.type.DSLResourceTypeDefinition;
import org.guvnor.common.services.project.builder.events.InvalidateDMOPackageCacheEvent;
import org.kie.workbench.common.services.backend.helpers.AbstractInvalidateDMOPackageCacheDeleteHelper;
/**
* DeleteHelper for DSLs to invalidate LRUDataModelOracleCache entries when a DSL is deleted.
*/
@ApplicationScoped
public class DSLInvalidateDMOPackageCacheDeleteHelper extends AbstractInvalidateDMOPackageCacheDeleteHelper<DSLResourceTypeDefinition> {
@Inject
public DSLInvalidateDMOPackageCacheDeleteHelper( final DSLResourceTypeDefinition resourceType,
final Event<InvalidateDMOPackageCacheEvent> invalidateDMOPackageCache ) {
super( resourceType,
invalidateDMOPackageCache );
}
}
|
package org.openapitools.api;
import org.openapitools.model.*;
import org.openapitools.api.FakeClassnameTestApiService;
import org.openapitools.api.factories.FakeClassnameTestApiServiceFactory;
import io.swagger.annotations.ApiParam;
import io.swagger.jaxrs.*;
import org.openapitools.model.Client;
import java.util.Map;
import java.util.List;
import org.openapitools.api.NotFoundException;
import java.io.InputStream;
import com.sun.jersey.core.header.FormDataContentDisposition;
import com.sun.jersey.multipart.FormDataParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.SecurityContext;
import javax.ws.rs.*;
import javax.validation.constraints.*;
import javax.validation.Valid;
@Path("/fake_classname_test")
@io.swagger.annotations.Api(description = "the fake_classname_test API")
public class FakeClassnameTestApi {
private final FakeClassnameTestApiService delegate = FakeClassnameTestApiServiceFactory.getFakeClassnameTestApi();
@PATCH
@Consumes({ "application/json" })
@Produces({ "application/json" })
@io.swagger.annotations.ApiOperation(value = "To test class name in snake case", notes = "To test class name in snake case", response = Client.class, authorizations = {
@io.swagger.annotations.Authorization(value = "api_key_query")
}, tags={ "fake_classname_tags 123#$%^" })
@io.swagger.annotations.ApiResponses(value = {
@io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Client.class) })
public Response testClassname(
@ApiParam(value = "client model" ,required=true) @NotNull @Valid Client body,
@Context SecurityContext securityContext)
throws NotFoundException {
return delegate.testClassname(body,securityContext);
}
}
|
/*
* 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.sysds.test.functions.federated.algorithms;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.apache.sysds.api.DMLScript;
import org.apache.sysds.common.Types;
import org.apache.sysds.runtime.meta.MatrixCharacteristics;
import org.apache.sysds.test.AutomatedTestBase;
import org.apache.sysds.test.TestConfiguration;
import org.apache.sysds.test.TestUtils;
import java.util.Arrays;
import java.util.Collection;
@RunWith(value = Parameterized.class)
@net.jcip.annotations.NotThreadSafe
public class FederatedL2SVMTest extends AutomatedTestBase {
private final static String TEST_DIR = "functions/federated/";
private final static String TEST_NAME = "FederatedL2SVMTest";
private final static String TEST_CLASS_DIR = TEST_DIR + FederatedL2SVMTest.class.getSimpleName() + "/";
private final static int blocksize = 1024;
@Parameterized.Parameter()
public int rows;
@Parameterized.Parameter(1)
public int cols;
@Override
public void setUp() {
TestUtils.clearAssertionInformation();
addTestConfiguration(TEST_NAME, new TestConfiguration(TEST_CLASS_DIR, TEST_NAME, new String[] {"Z"}));
}
@Parameterized.Parameters
public static Collection<Object[]> data() {
// rows have to be even and > 1
return Arrays.asList(new Object[][] {
// {2, 1000}, {10, 100}, {100, 10}, {1000, 1}, {10, 2000},
{2000, 10}});
}
@Test
public void federatedL2SVM2CP() {
federatedL2SVM(Types.ExecMode.SINGLE_NODE, false);
}
@Test
public void federatedL2SVM1CP() {
federatedL2SVM(Types.ExecMode.SINGLE_NODE, true);
}
/*
* TODO support SPARK execution mode -> RDDs and SPARK instructions lead to quite a few problems
*
* @Test public void federatedL2SVMSP() { federatedL2SVM(Types.ExecMode.SPARK); }
*/
public void federatedL2SVM(Types.ExecMode execMode, boolean singleWorker) {
boolean sparkConfigOld = DMLScript.USE_LOCAL_SPARK_CONFIG;
Types.ExecMode platformOld = rtplatform;
rtplatform = execMode;
if(rtplatform == Types.ExecMode.SPARK) {
DMLScript.USE_LOCAL_SPARK_CONFIG = true;
}
getAndLoadTestConfiguration(TEST_NAME);
String HOME = SCRIPT_DIR + TEST_DIR;
// write input matrices
int halfRows = rows / 2;
// We have two matrices handled by a single federated worker
double[][] X1 = getRandomMatrix(halfRows, cols, 0, 1, 1, 42);
double[][] X2 = getRandomMatrix(halfRows, cols, 0, 1, 1, 1340);
double[][] Y = getRandomMatrix(rows, 1, -1, 1, 1, 1233);
for(int i = 0; i < rows; i++)
Y[i][0] = (Y[i][0] > 0) ? 1 : -1;
writeInputMatrixWithMTD("X1", X1, false, new MatrixCharacteristics(halfRows, cols, blocksize, halfRows * cols));
writeInputMatrixWithMTD("X2", X2, false, new MatrixCharacteristics(halfRows, cols, blocksize, halfRows * cols));
writeInputMatrixWithMTD("Y", Y, false, new MatrixCharacteristics(rows, 1, blocksize, rows));
// empty script name because we don't execute any script, just start the worker
fullDMLScriptName = "";
int port1 = getRandomAvailablePort();
int port2 = getRandomAvailablePort();
Thread t1 = startLocalFedWorkerThread(port1, FED_WORKER_WAIT_S);
Thread t2 = startLocalFedWorkerThread(port2);
TestConfiguration config = availableTestConfigurations.get(TEST_NAME);
loadTestConfiguration(config);
// Run reference dml script with normal matrix
fullDMLScriptName = HOME + TEST_NAME + "Reference.dml";
programArgs = new String[] {"-args", input("X1"), input("X2"), input("Y"),
String.valueOf(singleWorker).toUpperCase(), expected("Z")};
runTest(true, false, null, -1);
// Run actual dml script with federated matrix
fullDMLScriptName = HOME + TEST_NAME + ".dml";
programArgs = new String[] {"-nvargs", "in_X1=" + TestUtils.federatedAddress(port1, input("X1")),
"in_X2=" + TestUtils.federatedAddress(port2, input("X2")), "rows=" + rows, "cols=" + cols,
"in_Y=" + input("Y"), "single=" + String.valueOf(singleWorker).toUpperCase(), "out=" + output("Z")};
runTest(true, false, null, -1);
// compare via files
compareResults(1e-9);
TestUtils.shutdownThreads(t1, t2);
rtplatform = platformOld;
DMLScript.USE_LOCAL_SPARK_CONFIG = sparkConfigOld;
}
}
|
package xyz.vopen.framework.cropdb.transaction;
import xyz.vopen.framework.cropdb.collection.CropCollection;
import xyz.vopen.framework.cropdb.repository.ObjectRepository;
/**
* Represents an ACID transaction on crop database.
*
* @author <a href="mailto:iskp.me@gmail.com">Elve.Xu</a>
* @since 4.0
*/
public interface Transaction extends AutoCloseable {
/**
* Gets the transaction id.
*
* @return the id
*/
String getId();
/**
* Gets the current state of the transaction.
*
* @return the state
*/
State getState();
/**
* Gets a {@link CropCollection} to perform ACID operations on it.
*
* @param name the name
* @return the collection
*/
CropCollection getCollection(String name);
/**
* Gets an {@link ObjectRepository} to perform ACID operations on it.
*
* @param <T> the type parameter
* @param type the type
* @return the repository
*/
<T> ObjectRepository<T> getRepository(Class<T> type);
/**
* Gets an {@link ObjectRepository} to perform ACID operations on it.
*
* @param <T> the type parameter
* @param type the type
* @param key the key
* @return the repository
*/
<T> ObjectRepository<T> getRepository(Class<T> type, String key);
/** Completes the transaction and commits the data to the underlying store. */
void commit();
/** Rolls back the changes. */
void rollback();
/** Closes this {@link Transaction}. */
void close();
}
|
/*
* 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.accumulo.core.util;
import static org.easymock.EasyMock.createMock;
import static org.easymock.EasyMock.replay;
import static org.easymock.EasyMock.verify;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.net.SocketAppender;
import org.apache.log4j.spi.LoggingEvent;
import org.junit.Before;
import org.junit.Test;
public class AsyncSocketAppenderTest {
private SocketAppender sa;
private AsyncSocketAppender asa;
@Before
public void setUp() throws Exception {
sa = createMock(SocketAppender.class);
}
@Test
public void testDelegates() {
asa = new AsyncSocketAppender();
asa.setApplication("myapp");
asa.setLocationInfo(true);
asa.setPort(1234);
asa.setReconnectionDelay(56);
asa.setRemoteHost("remotehost");
assertEquals("myapp", asa.getApplication());
assertEquals(true, asa.getLocationInfo()); // not really delegating
assertEquals(1234, asa.getPort());
assertEquals(56, asa.getReconnectionDelay());
assertEquals("remotehost", asa.getRemoteHost());
}
@Test
public void testSetLocationInfo() {
sa.setLocationInfo(true);
replay(sa);
asa = new AsyncSocketAppender(sa);
asa.setLocationInfo(true);
verify(sa);
}
@Test
public void testAppend() {
asa = new AsyncSocketAppender(sa);
assertFalse(asa.isAttached(sa));
LoggingEvent event1 = new LoggingEvent("java.lang.String", Logger.getRootLogger(), Level.INFO, "event1", null);
LoggingEvent event2 = new LoggingEvent("java.lang.Integer", Logger.getRootLogger(), Level.WARN, "event2", null);
sa.activateOptions();
sa.doAppend(event1);
sa.doAppend(event2);
sa.close();
replay(sa);
asa.doAppend(event1);
asa.doAppend(event2);
asa.close(); // forces events to be appended to socket appender
assertTrue(asa.isAttached(sa));
verify(sa);
}
}
|
package Launcher;
import java.io.*;
import java.net.*;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.util.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.swing.*;
/**
* Tiny Api for HTTP Get requests
* @author etsubu
* @version 28 Aug 2018
*
*/
public class HttpApi {
private static final Logger log = LoggerFactory.getLogger(HttpApi.class);
private HttpClient client;
public HttpApi() {
this.client = HttpClient.newHttpClient();
}
/**
* Sends HTTP Get request and returns the response in String
* @param url URL to request
* @return Response in String
* @throws IOException If there was an connection error
*/
public String sendGet(String url) throws IOException, InterruptedException {
HttpRequest request = HttpRequest.newBuilder() .uri(URI.create(url)).build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
if(response.statusCode() != 200) {
throw new IOException("Invalid HTTP response: " + response.statusCode());
}
return response.body();
}
public boolean downloadToFile(String url, Path file, JProgressBar progressBar, int length) throws IOException, InterruptedException {
return downloadToFile(url, file, progressBar, length, false);
}
public boolean downloadToFile(String url, Path file, JProgressBar progressBar, int length, boolean overwrite) throws IOException, InterruptedException {
if(file.toFile().exists()) {
if(overwrite) {
if(!file.toFile().delete()) {
log.error("Failed to delete file before overwriting {}", file.toString());
}
} else {
//log.info("File: " + file.toString() + " exists. Skipping download");
return true;
}
}
HttpRequest request = HttpRequest.newBuilder() .uri(URI.create(url)).build();
HttpResponse<InputStream> response = client.send(request, HttpResponse.BodyHandlers.ofInputStream());
if(response.statusCode() != HttpURLConnection.HTTP_OK) {
throw new IOException("Invalid HTTP response: " + response.statusCode());
}
Optional<File> parent = Optional.ofNullable(file.getParent()).map(Path::toFile);
if(!parent.map(File::exists).orElse(true)) {
if(!parent.map(File::mkdirs).orElse(true)) {
log.error("Failed to create folder: " + parent.map(x -> x.toString()).orElse("No parent available"));
return false;
}
}
String title = url;
int index = url.lastIndexOf("/");
if(index != -1 && index != url.length() -1) {
title = url.substring(index + 1);
}
// this will be useful to display download percentage
// might be -1: server did not report the length
progressBar.setString(title);
progressBar.setMaximum(length);
progressBar.setValue(0);
InputStream input = response.body();
byte[] buffer = new byte[4096];
int n;
int counter = 0;
try(OutputStream output = new FileOutputStream( file.toFile())) {
while ((n = input.read(buffer)) != -1) {
output.write(buffer, 0, n);
counter += n;
progressBar.setValue(counter);
}
}
progressBar.setValue(progressBar.getMaximum());
return true;
}
}
|
package org.h5z.fval4j;
import static org.organicdesign.fp.StaticImports.map;
import static org.organicdesign.fp.StaticImports.tup;
import static org.organicdesign.fp.StaticImports.vec;
import static org.organicdesign.fp.StaticImports.xform;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import org.organicdesign.fp.collections.ImList;
import org.organicdesign.fp.collections.ImMap;
import org.organicdesign.fp.collections.ImSet;
import org.organicdesign.fp.function.Fn1;
import org.organicdesign.fp.oneOf.Option;
public class Trie<E> {
static final String ROOT_KEY = "";
final ImList<E> errors;
final ImMap<String, Trie<E>> children;
/**
*
* @param errors
* @param children
*
* @see {@link Trie#invalid(Object)} to create a trie with an error at the root
* @see {@link Trie#invalid(String, List)} to create a trie with the given errors with the given path
* @see {@link Trie#valid(Object)} to create a valid trie for the given value
* @see {@link Trie#valid(String, Object)} to create a valid trie with the given path
* @see {@link Trie#trie(List, Map)} to create a trie on your own
*
* @author Eric Honorez
*/
private Trie(ImList<E> errors, ImMap<String, Trie<E>> children) {
this.errors = errors;
this.children = children;
}
public List<E> getErrors() {
return this.errors;
}
public List<E> getErrors(List<String> path) {
return this.get(path)
.match(n -> n.getErrors(),
() -> vec());
}
public List<E> getErrors(String... path) {
return this.getErrors(Arrays.asList(path));
}
public Map<String, Trie<E>> getChildren() {
return this.children;
}
/**
* Tests if a given trie is valid.
*
* @return <code>true</code> if the this trie has no error and all of its
* children are valid. <code>false</code> otherwise.
*/
public boolean isValid() {
return this.getErrors().isEmpty() &&
this.getChildren().entrySet()
.stream()
.map(kv -> kv.getValue().isValid())
.reduce(true, (a, b) -> a && b);
}
public boolean isValid(List<String> path) {
return this.get(path)
.match(
el -> el.isValid(),
() -> false);
}
/**
* Test if a given trie is invalid.
*
* @return <code>true</code> if this trie has an error or if one of its
* children is invalid. <code>false</code> otherwise.
*/
public boolean isInvalid() {
return !this.isValid();
}
public boolean isInvalid(List<String> path) {
return !this.isValid(path);
}
public boolean hasErrors() {
return !this.getErrors().isEmpty();
}
public boolean hasErrors(List<String> path) {
return this.get(path)
.match(
el -> !el.getErrors().isEmpty(),
() -> false);
}
public boolean hasErrors(String... path) {
return this.hasErrors(Arrays.asList(path));
}
/**
* Returns maybe the node at given key in the given trie if it exists.
*
* @param path the sequence of keys to access the node.
* @return {@link Option.Some} containing the node with specified key in the
* given trie. {@link Option.none} otherwise.
*/
public Option<Trie<E>> get(List<String> path) {
ImList<String> pathImList = xform(path).toImList();
String current = pathImList.head().getOrElse("");
ImList<String> tail = pathImList.drop(1).toImList();
return recurGet(current, tail, this);
}
public Option<Trie<E>> get(String... path) {
return get(Arrays.asList(path));
}
private static <E> Option<Trie<E>> recurGet(String head, ImList<String> tail, Trie<E> root) {
if ("".equals(head)) {
return Option.some(root);
}
if (!root.getChildren().containsKey(head)) {
return Option.none();
}
Trie<E> child = root.getChildren().get(head);
String next = tail.head().getOrElse("");
return recurGet(next, tail.drop(1).toImList(), child);
}
/**
* Merges two tries together.
*
* @return the merged trie.
*/
public Trie<E> merge(Trie<E> b) {
ImList<E> mergedErrors = this.errors.concat(b.errors);
if (this.getChildren().isEmpty()
&& b.getChildren().isEmpty()) {
return new Trie<>(mergedErrors, map());
}
ImSet<String> aKeys = this.children.keySet();
ImSet<String> bKeys = b.children.keySet();
ImSet<String> intersection = aKeys.filter(x -> bKeys.contains(x)).toImSet();
ImMap<String, Trie<E>> outer = this.children.concat(b.children)
.filter(kv -> !intersection.contains(kv.getKey()))
.toImMap(Fn1.identity());
Trie<E> zero = trie(mergedErrors, map());
Trie<E> withOuter = outer.fold(zero, (t, kv) -> {
return trie(
t.errors,
t.children.assoc(kv));
});
return intersection.fold(withOuter, (t, k) -> {
return trie(
t.errors,
t.children.assoc(k, this.get(vec(k)).get().merge(b.get(vec(k)).get()) // unsafeGet
));
});
}
/**
* Transforms a trie to a map.
*
* Keys of the map are the keys of the nodes in the trie and their associated
* value is the list of errors of the node identified by the key in the trie.
*
* @return a map
*/
public Map<String, ImList<E>> toMap() {
return recurToMap("", this, map());
}
private static <E> ImMap<String, ImList<E>> recurToMap(String currentPath, Trie<E> root,
ImMap<String, ImList<E>> acc) {
ImMap<String, ImList<E>> withErrors = acc.assoc(currentPath, root.errors);
if (root.getChildren().isEmpty()) {
return withErrors;
}
return root.children
.fold(withErrors, (newAcc, child) -> {
String nextPath = currentPath + "." + child.getKey();
if ("".equals(currentPath)) {
nextPath = child.getKey();
}
return newAcc.concat(
recurToMap(nextPath, child.getValue(), map())).toImMap(Fn1.identity());
});
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof Trie))
return false;
Trie<?> trie = (Trie<?>) o;
if (!getErrors().equals(trie.getErrors()))
return false;
return getChildren().equals(trie.getChildren());
}
@Override
public int hashCode() {
int result = getErrors().hashCode();
result = 31 * result + getChildren().hashCode();
return result;
}
@Override
public String toString() {
return "{ errors: [%s], children: [%s] }"
.formatted(
String.join(", ", this.errors.map(Object::toString)),
String.join(", \n", this.children.map(kv -> "{ %s: %s }".formatted(kv.getKey(), kv.getValue().toString())))
);
}
public static <E, T> Trie<E> valid(T v) {
return trie(vec(), map());
}
public static <E, T> Trie<E> valid(String key, T v) {
if (ROOT_KEY.equals(key)) {
return Trie.valid(v);
}
return trie(vec(), map(tup(key, Trie.valid(v))));
}
public static <E> Trie<E> invalid(List<E> es) {
return trie(es, map());
}
public static <E> Trie<E> invalid(E e) {
return invalid(vec(e));
}
public static <E> Trie<E> invalid(String key, List<E> es) {
if (ROOT_KEY.equals(key)) {
return invalid(es);
}
return trie(vec(), map(tup(key, invalid(es))));
}
public static <E> Trie<E> trie(List<E> errors, Map<String, Trie<E>> children) {
return new Trie<>(xform(errors).toImList(), xform(children.entrySet()).toImMap(kv -> kv));
}
}
|
package com.symphony.bdk.core.service.user;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import com.symphony.bdk.core.auth.AuthSession;
import com.symphony.bdk.core.retry.RetryWithRecoveryBuilder;
import com.symphony.bdk.core.service.pagination.model.CursorPaginationAttribute;
import com.symphony.bdk.core.service.pagination.model.PaginationAttribute;
import com.symphony.bdk.core.service.pagination.model.StreamPaginationAttribute;
import com.symphony.bdk.core.service.user.constant.RoleId;
import com.symphony.bdk.core.service.user.constant.UserFeature;
import com.symphony.bdk.core.service.user.mapper.UserDetailMapper;
import com.symphony.bdk.core.test.JsonHelper;
import com.symphony.bdk.core.test.MockApiClient;
import com.symphony.bdk.gen.api.AuditTrailApi;
import com.symphony.bdk.gen.api.UserApi;
import com.symphony.bdk.gen.api.UsersApi;
import com.symphony.bdk.gen.api.model.Avatar;
import com.symphony.bdk.gen.api.model.AvatarUpdate;
import com.symphony.bdk.gen.api.model.DelegateAction;
import com.symphony.bdk.gen.api.model.Disclaimer;
import com.symphony.bdk.gen.api.model.Feature;
import com.symphony.bdk.gen.api.model.FollowersList;
import com.symphony.bdk.gen.api.model.FollowersListResponse;
import com.symphony.bdk.gen.api.model.FollowingListResponse;
import com.symphony.bdk.gen.api.model.RoleDetail;
import com.symphony.bdk.gen.api.model.StringId;
import com.symphony.bdk.gen.api.model.UserAttributes;
import com.symphony.bdk.gen.api.model.UserDetail;
import com.symphony.bdk.gen.api.model.UserFilter;
import com.symphony.bdk.gen.api.model.UserSearchFilter;
import com.symphony.bdk.gen.api.model.UserSearchQuery;
import com.symphony.bdk.gen.api.model.UserStatus;
import com.symphony.bdk.gen.api.model.UserSuspension;
import com.symphony.bdk.gen.api.model.UserV2;
import com.symphony.bdk.gen.api.model.V1AuditTrailInitiatorList;
import com.symphony.bdk.gen.api.model.V1AuditTrailInitiatorResponse;
import com.symphony.bdk.gen.api.model.V2UserAttributes;
import com.symphony.bdk.gen.api.model.V2UserCreate;
import com.symphony.bdk.gen.api.model.V2UserDetail;
import com.symphony.bdk.http.api.ApiClient;
import com.symphony.bdk.http.api.ApiException;
import com.symphony.bdk.http.api.ApiRuntimeException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.time.Duration;
import java.time.Instant;
import java.util.Arrays;
import java.util.Base64;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
class UserServiceTest {
private static final String V2_USER_DETAIL_BY_ID = "/pod/v2/admin/user/{uid}";
private static final String V2_USER_LIST = "/pod/v2/admin/user/list";
private static final String V2_USER_CREATE = "/pod/v2/admin/user/create";
private static final String V2_USER_UPDATE = "/pod/v2/admin/user/{uid}/update";
private static final String USER_FIND = "/pod/v1/admin/user/find";
private static final String ADD_ROLE_TO_USER = "/pod/v1/admin/user/{uid}/roles/add";
private static final String REMOVE_ROLE_FROM_USER = "/pod/v1/admin/user/{uid}/roles/remove";
private static final String LIST_ROLES = "/pod/v1/admin/system/roles/list";
private static final String GET_AVATAR_FROM_USER = "/pod/v1/admin/user/{uid}/avatar";
private static final String UPDATE_AVATAR_OF_USER = "/pod/v1/admin/user/{uid}/avatar/update";
private static final String GET_DISCLAIMER_OF_USER = "/pod/v1/admin/user/{uid}/disclaimer";
private static final String UNASSIGN_DISCLAIMER_FROM_USER = "/pod/v1/admin/user/{uid}/disclaimer";
private static final String ASSIGN_DISCLAIMER_TO_USER = "/pod/v1/admin/user/{uid}/disclaimer/update";
private static final String GET_DELEGATE_OF_USER = "/pod/v1/admin/user/{uid}/delegates";
private static final String UPDATE_DELEGATE_OF_USER = "/pod/v1/admin/user/{uid}/delegates/update";
private static final String GET_FEATURE_ENTITLEMENTS_OF_USER = "/pod/v1/admin/user/{uid}/features";
private static final String UPDATE_FEATURE_ENTITLEMENTS_OF_USER = "/pod/v1/admin/user/{uid}/features/update";
private static final String GET_STATUS_OF_USER = "/pod/v1/admin/user/{uid}/status";
private static final String UPDATE_STATUS_OF_USER = "/pod/v1/admin/user/{uid}/status/update";
private static final String SEARCH_USERS_V3 = "/pod/v3/users";
private static final String SEARCH_USER_BY_QUERY = "/pod/v1/user/search";
private static final String V1_USER_FOLLOW = "/pod/v1/user/{uid}/follow";
private static final String V1_USER_UNFOLLOW = "/pod/v1/user/{uid}/unfollow";
private static final String V1_LIST_FOLLOWERS = "/pod/v1/user/{uid}/followers";
private static final String V1_LIST_FOLLOWING = "/pod/v1/user/{uid}/following";
private static final String V1_AUDIT_TRAIL_PRIVILEGED_USER = "/agent/v1/audittrail/privilegeduser";
private static final String SUSPEND_USER = "/pod/v1/admin/user/{uid}/suspension/update";
private static final String MISSING_REQUIRED_PARAMETER_EXCEPTION_MESSAGE = "Missing the required parameter '%s' when calling %s";
private UserService service;
private UserApi spiedUserApi;
private MockApiClient mockApiClient;
private UsersApi spiedUsersApi;
private AuditTrailApi spiedAuditTrailApi;
private AuthSession authSession;
@BeforeEach
void init() {
this.mockApiClient = new MockApiClient();
this.authSession = mock(AuthSession.class);
ApiClient podClient = mockApiClient.getApiClient("/pod");
ApiClient agentClient = mockApiClient.getApiClient("/agent");
this.spiedUserApi = spy(new UserApi(podClient));
this.spiedUsersApi = spy(new UsersApi(podClient));
this.spiedAuditTrailApi = spy(new AuditTrailApi(agentClient));
this.service = new UserService(this.spiedUserApi, spiedUsersApi, this.spiedAuditTrailApi, authSession, new RetryWithRecoveryBuilder());
when(authSession.getSessionToken()).thenReturn("1234");
when(authSession.getKeyManagerToken()).thenReturn("1234");
}
@Test
void nonOboEndpointShouldThrowExceptionInOboMode() {
this.service = new UserService(this.spiedUserApi, spiedUsersApi, this.spiedAuditTrailApi, new RetryWithRecoveryBuilder());
assertThrows(IllegalStateException.class, () -> this.service.getUserDetail(1234L));
}
@Test
void listUsersByIdOboMode() throws IOException {
String response = JsonHelper.readFromClasspath("/user/users.json");
this.mockApiClient.onGet(SEARCH_USERS_V3, response);
List<UserV2> users = this.service.obo(this.authSession).listUsersByIds(Collections.singletonList(1234L));
assertEquals(users.size(), 1);
}
@Test
void getUserDetailByUidTest() throws IOException {
String response = JsonHelper.readFromClasspath("/user/user_detail.json");
this.mockApiClient.onGet(V2_USER_DETAIL_BY_ID.replace("{uid}", "1234"), response);
V2UserDetail userDetail = this.service.getUserDetail(1234L);
assertEquals(userDetail.getUserAttributes().getCompanyName(), "Company");
assertEquals(userDetail.getUserAttributes().getUserName(), "johndoe");
assertEquals(V2UserAttributes.AccountTypeEnum.NORMAL, userDetail.getUserAttributes().getAccountType());
assertEquals(userDetail.getRoles().size(), 6);
}
@Test
void getUserDetailWithUnknownAccountType() throws IOException {
String response = JsonHelper.readFromClasspath("/user/user_detail_unknown_account_type.json");
this.mockApiClient.onGet(V2_USER_DETAIL_BY_ID.replace("{uid}", "1234"), response);
V2UserDetail userDetail = this.service.getUserDetail(1234L);
assertEquals(userDetail.getUserAttributes().getCompanyName(), "Company");
assertEquals(userDetail.getUserAttributes().getUserName(), "johndoe");
assertNull(userDetail.getUserAttributes().getAccountType());
assertEquals(userDetail.getRoles().size(), 6);
}
@Test
void listUsersDetailTest() throws IOException {
String responseV2 = JsonHelper.readFromClasspath("/user/list_users_detail_v2.json");
this.mockApiClient.onGet(V2_USER_LIST, responseV2);
List<V2UserDetail> userDetails = this.service.listUsersDetail();
assertEquals(userDetails.size(), 5);
assertEquals(userDetails.get(0).getUserAttributes().getUserName(), "agentservice");
assertEquals(userDetails.get(1).getUserAttributes().getUserName(), "bot.user1");
}
@Test
void listUsersDetailTestFailed() {
this.mockApiClient.onGet(400, V2_USER_LIST, "{}");
assertThrows(ApiRuntimeException.class, () -> this.service.listUsersDetail());
}
@Test
void listUsersDetailSkipLimitTest() throws IOException {
String responseV2 = JsonHelper.readFromClasspath("/user/list_users_detail_v2.json");
this.mockApiClient.onGet(V2_USER_LIST, responseV2);
List<V2UserDetail> userDetails = this.service.listUsersDetail(new PaginationAttribute(0, 100));
assertEquals(userDetails.size(), 5);
assertEquals(userDetails.get(0).getUserAttributes().getUserName(), "agentservice");
assertEquals(userDetails.get(1).getUserAttributes().getUserName(), "bot.user1");
}
@Test
void listAllUsersDetailTest() throws IOException {
String responseV2 = JsonHelper.readFromClasspath("/user/list_users_detail_v2.json");
this.mockApiClient.onGet(V2_USER_LIST, responseV2);
List<V2UserDetail> userDetails = this.service.listAllUsersDetail().collect(Collectors.toList());
assertEquals(userDetails.size(), 5);
assertEquals(userDetails.get(0).getUserAttributes().getUserName(), "agentservice");
assertEquals(userDetails.get(1).getUserAttributes().getUserName(), "bot.user1");
}
@Test
void listAllUsersDetailPaginationTest() throws IOException {
String responseV2 = JsonHelper.readFromClasspath("/user/list_users_detail_v2.json");
this.mockApiClient.onGet(V2_USER_LIST, responseV2);
List<V2UserDetail> userDetails =
this.service.listAllUsersDetail(new StreamPaginationAttribute(100, 100)).collect(Collectors.toList());
assertEquals(userDetails.size(), 5);
assertEquals(userDetails.get(0).getUserAttributes().getUserName(), "agentservice");
assertEquals(userDetails.get(1).getUserAttributes().getUserName(), "bot.user1");
}
@Test
void listUsersDetailByFilterTest() throws IOException {
String responseV1 = JsonHelper.readFromClasspath("/user/list_users_detail_v1.json");
this.mockApiClient.onPost(USER_FIND, responseV1);
UserFilter userFilter = new UserFilter();
List<V2UserDetail> userDetails = this.service.listUsersDetail(userFilter);
assertEquals(userDetails.size(), 4);
assertEquals(userDetails.get(2).getUserAttributes().getUserName(), "bot.user");
assertEquals(userDetails.get(3).getUserAttributes().getUserName(), "nexus.user");
}
@Test
void listUsersDetailByFilterTestFailed() {
this.mockApiClient.onPost(400, USER_FIND, "{}");
assertThrows(ApiRuntimeException.class, () -> this.service.listUsersDetail(new UserFilter()));
}
@Test
void listUsersDetailByFilterSkipLimitTest() throws IOException {
String responseV1 = JsonHelper.readFromClasspath("/user/list_users_detail_v1.json");
this.mockApiClient.onPost(USER_FIND, responseV1);
UserFilter userFilter = new UserFilter();
List<V2UserDetail> userDetails = this.service.listUsersDetail(userFilter, new PaginationAttribute(0, 100));
assertEquals(userDetails.size(), 4);
assertEquals(userDetails.get(2).getUserAttributes().getUserName(), "bot.user");
assertEquals(userDetails.get(3).getUserAttributes().getUserName(), "nexus.user");
}
@Test
void listAllUsersDetailByFilterTest() throws IOException {
String responseV1 = JsonHelper.readFromClasspath("/user/list_users_detail_v1.json");
this.mockApiClient.onPost(USER_FIND, responseV1);
UserFilter userFilter = new UserFilter();
List<V2UserDetail> userDetails = this.service.listAllUsersDetail(userFilter).collect(Collectors.toList());
assertEquals(userDetails.size(), 4);
assertEquals(userDetails.get(2).getUserAttributes().getUserName(), "bot.user");
assertEquals(userDetails.get(3).getUserAttributes().getUserName(), "nexus.user");
}
@Test
void listAllUsersDetailByFilterPaginationTest() throws IOException {
String responseV1 = JsonHelper.readFromClasspath("/user/list_users_detail_v1.json");
this.mockApiClient.onPost(USER_FIND, responseV1);
UserFilter userFilter = new UserFilter();
List<V2UserDetail> userDetails =
this.service.listAllUsersDetail(userFilter, new StreamPaginationAttribute(100, 100))
.collect(Collectors.toList());
assertEquals(userDetails.size(), 4);
assertEquals(userDetails.get(2).getUserAttributes().getUserName(), "bot.user");
assertEquals(userDetails.get(3).getUserAttributes().getUserName(), "nexus.user");
}
@Test
void addRoleToUserTest() throws ApiException {
this.mockApiClient.onPost(ADD_ROLE_TO_USER.replace("{uid}", "1234"),
"{\"format\": \"TEXT\", \"message\": \"Role added\"}");
this.service.addRole(1234L, RoleId.INDIVIDUAL);
verify(spiedUserApi).v1AdminUserUidRolesAddPost(eq("1234"), eq(1234L), eq(new StringId().id("INDIVIDUAL")));
}
@Test
void addRoleToUserTestFailed() {
this.mockApiClient.onPost(400, ADD_ROLE_TO_USER.replace("{uid}", "1234"), "{}");
assertThrows(ApiRuntimeException.class, () -> this.service.addRole(1234L, RoleId.INDIVIDUAL));
}
@Test
void removeRoleFromUserTest() throws ApiException {
this.mockApiClient.onPost(REMOVE_ROLE_FROM_USER.replace("{uid}", "1234"),
"{\"format\": \"TEXT\", \"message\": \"Role removed\"}");
this.service.removeRole(1234L, RoleId.INDIVIDUAL);
verify(spiedUserApi).v1AdminUserUidRolesRemovePost(eq("1234"), eq(1234L), eq(new StringId().id("INDIVIDUAL")));
}
@Test
void removeRoleFromUserTestFailed() {
this.mockApiClient.onPost(400, REMOVE_ROLE_FROM_USER.replace("{uid}", "1234"), "{}");
assertThrows(ApiRuntimeException.class, () -> this.service.removeRole(1234L, RoleId.INDIVIDUAL));
}
@Test
void listRoles() throws IOException {
String response = JsonHelper.readFromClasspath("/roles/list_roles.json");
this.mockApiClient.onGet(LIST_ROLES, response);
List<RoleDetail> roleDetails = this.service.listRoles();
assertEquals(12, roleDetails.size());
assertEquals("Content Management", roleDetails.get(0).getName());
}
@Test
void listRolesTestFailed() {
this.mockApiClient.onGet(400, LIST_ROLES, "{}");
assertThrows(ApiRuntimeException.class, () -> this.service.listRoles());
}
@Test
void getAvatarFromUser() {
this.mockApiClient.onGet(GET_AVATAR_FROM_USER.replace("{uid}", "1234"), "[\n"
+ " {\n"
+ " \"size\": \"600\",\n"
+ " \"url\": \"../avatars/acme/600/7215545057281/3gXMhglCCTwLPL9JAprnyHzYn5-PR49-wYDG814n1g8.png\"\n"
+ " },\n"
+ " {\n"
+ " \"size\": \"150\",\n"
+ " \"url\": \"../avatars/acme/150/7215545057281/3gXMhglCCTwLPL9JAprnyHzYn5-PR49-wYDG814n1g8.png\"\n"
+ " }\n"
+ "]");
List<Avatar> avatars = this.service.getAvatar(1234L);
assertEquals(avatars.size(), 2);
assertEquals(avatars.get(0).getSize(), "600");
assertEquals(avatars.get(1).getSize(), "150");
}
@Test
void getAvatarFromUserTestFailed() {
this.mockApiClient.onGet(400, GET_AVATAR_FROM_USER.replace("{uid}", "1234"), "{}");
assertThrows(ApiRuntimeException.class, () -> this.service.getAvatar(1234L));
}
@Test
void updateAvatarOfUserTest() throws ApiException, IOException {
this.mockApiClient.onPost(UPDATE_AVATAR_OF_USER.replace("{uid}", "1234"),
"{\"format\": \"TEXT\", \"message\": \"OK\"}");
String avatar = "iVBORw0KGgoAAAANSUhEUgAAAJgAAAAoCAMAAAA11s";
byte[] bytes = avatar.getBytes();
InputStream inputStream = new ByteArrayInputStream(bytes);
this.service.updateAvatar(1234L, avatar);
this.service.updateAvatar(1234L, bytes);
this.service.updateAvatar(1234L, inputStream);
verify(spiedUserApi).v1AdminUserUidAvatarUpdatePost(eq("1234"), eq(1234L),
eq(new AvatarUpdate().image("iVBORw0KGgoAAAANSUhEUgAAAJgAAAAoCAMAAAA11s")));
verify(spiedUserApi, times(2)).v1AdminUserUidAvatarUpdatePost(eq("1234"), eq(1234L),
eq(new AvatarUpdate().image(Base64.getEncoder().encodeToString(bytes))));
}
@Test
void updateAvatarOfUserTestFailed() {
this.mockApiClient.onPost(400, UPDATE_AVATAR_OF_USER.replace("{uid}", "1234"), "{}");
String avatar = "iVBORw0KGgoAAAANSUhEUgAAAJgAAAAoCAMAAAA11s";
byte[] bytes = avatar.getBytes();
InputStream inputStream = new ByteArrayInputStream(bytes);
assertThrows(ApiRuntimeException.class, () -> this.service.updateAvatar(1234L, avatar));
assertThrows(ApiRuntimeException.class, () -> this.service.updateAvatar(1234L, bytes));
assertThrows(ApiRuntimeException.class, () -> this.service.updateAvatar(1234L, inputStream));
}
@Test
void getDisclaimerAssignedToUserTest() {
this.mockApiClient.onGet(GET_DISCLAIMER_OF_USER.replace("{uid}", "1234"), "{\n"
+ " \"id\": \"571d2052e4b042aaf06d2e7a\",\n"
+ " \"name\": \"Enterprise Disclaimer\",\n"
+ " \"content\": \"This is a disclaimer for the enterprise.\",\n"
+ " \"frequencyInHours\": 24,\n"
+ " \"isDefault\": false,\n"
+ " \"isActive\": true,\n"
+ " \"createdDate\": 1461526610846,\n"
+ " \"modifiedDate\": 1461526610846\n"
+ "}");
Disclaimer disclaimer = this.service.getDisclaimer(1234L);
assertEquals(disclaimer.getName(), "Enterprise Disclaimer");
assertEquals(disclaimer.getIsActive(), true);
assertEquals(disclaimer.getIsDefault(), false);
}
@Test
void getDisclaimerAssignedToUserTestFailed() {
this.mockApiClient.onGet(400, GET_DISCLAIMER_OF_USER.replace("{uid}", "1234"), "{}");
assertThrows(ApiRuntimeException.class, () -> this.service.getDisclaimer(1234L));
}
@Test
void unAssignDisclaimerFromUserTest() throws ApiException {
this.mockApiClient.onDelete(UNASSIGN_DISCLAIMER_FROM_USER.replace("{uid}", "1234"), "{}");
this.service.removeDisclaimer(1234L);
verify(spiedUserApi).v1AdminUserUidDisclaimerDelete("1234", 1234L);
}
@Test
void unAssignDisclaimerFromUserTestFailed() {
this.mockApiClient.onDelete(400, UNASSIGN_DISCLAIMER_FROM_USER.replace("{uid}", "1234"), "{}");
assertThrows(ApiRuntimeException.class, () -> this.service.removeDisclaimer(1234L));
}
@Test
void assignDisclaimerToUserTest() throws ApiException {
this.mockApiClient.onPost(ASSIGN_DISCLAIMER_TO_USER.replace("{uid}", "1234"), "{}");
this.service.addDisclaimer(1234L, "disclaimer");
verify(spiedUserApi).v1AdminUserUidDisclaimerUpdatePost(eq("1234"), eq(1234L), eq(new StringId().id("disclaimer")));
}
@Test
void assignDisclaimerToUserTestFailed() {
this.mockApiClient.onPost(400, ASSIGN_DISCLAIMER_TO_USER.replace("{uid}", "1234"), "{}");
assertThrows(ApiRuntimeException.class, () -> this.service.addDisclaimer(1234L, "disclaimer"));
}
@Test
void getDelegatesAssignedToUserTest() {
this.mockApiClient.onGet(GET_DELEGATE_OF_USER.replace("{uid}", "1234"), "[7215545078461]");
List<Long> delegates = this.service.getDelegates(1234L);
assertEquals(delegates.size(), 1);
assertEquals(delegates.get(0), 7215545078461L);
}
@Test
void getDelegatesAssignedToUserTestFailed() {
this.mockApiClient.onGet(400, GET_DELEGATE_OF_USER.replace("{uid}", "1234"), "{}");
assertThrows(ApiRuntimeException.class, () -> this.service.getDelegates(1234L));
}
@Test
void updateDelegatesAssignedToUserTest() throws ApiException {
this.mockApiClient.onPost(UPDATE_DELEGATE_OF_USER.replace("{uid}", "1234"), "{}");
this.service.udpateDelegates(1234L, 1234L, DelegateAction.ActionEnum.ADD);
verify(spiedUserApi).v1AdminUserUidDelegatesUpdatePost(
eq("1234"),
eq(1234L),
eq(new DelegateAction().action(DelegateAction.ActionEnum.ADD).userId(1234L)));
}
@Test
void updateDelegatesAssignedToUserTestFailed() {
this.mockApiClient.onPost(400, UPDATE_DELEGATE_OF_USER.replace("{uid}", "1234"), "{}");
assertThrows(ApiRuntimeException.class,
() -> this.service.udpateDelegates(1234L, 1234L, DelegateAction.ActionEnum.ADD));
}
@Test
void getFeatureEntitlementsOfUserTest() {
this.mockApiClient.onGet(GET_FEATURE_ENTITLEMENTS_OF_USER.replace("{uid}", "1234"), "[\n"
+ " {\n"
+ " \"entitlment\": \"canCreatePublicRoom\",\n"
+ " \"enabled\": true\n"
+ " },\n"
+ " {\n"
+ " \"entitlment\": \"isExternalRoomEnabled\",\n"
+ " \"enabled\": false\n"
+ " },\n"
+ " {\n"
+ " \"entitlment\": \"delegatesEnabled\",\n"
+ " \"enabled\": true\n"
+ " },\n"
+ " {\n"
+ " \"entitlment\": \"isExternalIMEnabled\",\n"
+ " \"enabled\": true\n"
+ " }\n"
+ "]");
List<Feature> features = this.service.getFeatureEntitlements(1234L);
assertEquals(features.size(), 4);
assertEquals(features.get(0).getEntitlment(), UserFeature.canCreatePublicRoom.name());
assertEquals(features.get(1).getEnabled(), false);
}
@Test
void getFeatureEntitlementsOfUserTestFailed() {
this.mockApiClient.onGet(400, GET_FEATURE_ENTITLEMENTS_OF_USER.replace("{uid}", "1234"), "{}");
assertThrows(ApiRuntimeException.class, () -> this.service.getFeatureEntitlements(1234L));
}
@Test
void updateFeatureEntitlementsOfUserTest() throws ApiException {
this.mockApiClient.onPost(UPDATE_FEATURE_ENTITLEMENTS_OF_USER.replace("{uid}", "1234"), "{}");
List<Feature> features = Collections.singletonList(new Feature().entitlment("delegatesEnabled").enabled(true));
this.service.updateFeatureEntitlements(1234L, features);
verify(spiedUserApi).v1AdminUserUidFeaturesUpdatePost("1234", 1234L, features);
}
@Test
void updateFeatureEntitlementsOfUserTestFailed() {
this.mockApiClient.onPost(400, UPDATE_FEATURE_ENTITLEMENTS_OF_USER.replace("{uid}", "1234"),
"{}");
List<Feature> features = Collections.singletonList(new Feature().entitlment("delegatesEnabled").enabled(true));
assertThrows(ApiRuntimeException.class, () -> this.service.updateFeatureEntitlements(1234L, features));
}
@Test
void getStatusOfUserTest() {
this.mockApiClient.onGet(GET_STATUS_OF_USER.replace("{uid}", "1234"), "{\"status\": \"ENABLED\"}");
UserStatus userStatus = this.service.getStatus(1234L);
assertEquals(userStatus.getStatus(), UserStatus.StatusEnum.ENABLED);
}
@Test
void getStatusOfUserTestFailed() {
this.mockApiClient.onGet(400, GET_STATUS_OF_USER.replace("{uid}", "1234"), "{}");
assertThrows(ApiRuntimeException.class, () -> this.service.getStatus(1234L));
}
@Test
void updateStatusOfUserTest() throws ApiException {
this.mockApiClient.onPost(UPDATE_STATUS_OF_USER.replace("{uid}", "1234"), "{}");
UserStatus userStatus = new UserStatus().status(UserStatus.StatusEnum.ENABLED);
this.service.updateStatus(1234L, userStatus);
verify(spiedUserApi).v1AdminUserUidStatusUpdatePost("1234", 1234L, userStatus);
}
@Test
void updateStatusOfUserTestFailed() {
this.mockApiClient.onPost(400, UPDATE_STATUS_OF_USER.replace("{uid}", "1234"), "{}");
assertThrows(ApiRuntimeException.class, () -> this.service.updateStatus(1234L,
new UserStatus().status(UserStatus.StatusEnum.ENABLED)));
}
@Test
void searchUserV3Test() throws IOException {
String response = JsonHelper.readFromClasspath("/user/users.json");
this.mockApiClient.onGet(SEARCH_USERS_V3, response);
List<UserV2> users1 = this.service.listUsersByIds(Collections.singletonList(1234L), true, true);
assertEquals(users1.size(), 1);
assertEquals(users1.get(0).getDisplayName(), "Test Bot");
List<UserV2> users2 = this.service.listUsersByEmails(Collections.singletonList("tibot@symphony.com"), true, true);
assertEquals(users2.size(), 1);
assertEquals(users2.get(0).getUsername(), "tibot");
List<UserV2> users3 = this.service.listUsersByUsernames(Collections.singletonList("tibot"), true);
assertEquals(users3.size(), 1);
assertEquals(users3.get(0).getId(), 1234L);
List<UserV2> users4 = this.service.listUsersByIds(Collections.singletonList(1234L));
assertEquals(users4.size(), 1);
assertEquals(users4.get(0).getId(), 1234L);
List<UserV2> users5 = this.service.listUsersByEmails(Collections.singletonList("tibot@symphony.com"));
assertEquals(users5.size(), 1);
assertEquals(users5.get(0).getId(), 1234L);
List<UserV2> users6 = this.service.listUsersByUsernames(Collections.singletonList("tibot"));
assertEquals(users6.size(), 1);
assertEquals(users6.get(0).getId(), 1234L);
}
@Test
void searchUserV3TestFailed() {
this.mockApiClient.onGet(400, SEARCH_USERS_V3, "{}");
assertThrows(ApiRuntimeException.class,
() -> this.service.listUsersByIds(Collections.singletonList(1234L), true, true));
this.mockApiClient.onGet(400, SEARCH_USERS_V3, "{}");
assertThrows(ApiRuntimeException.class,
() -> this.service.listUsersByEmails(Collections.singletonList("tibot@symphony.com"), true, true));
assertThrows(ApiRuntimeException.class,
() -> this.service.listUsersByUsernames(Collections.singletonList("tibot"), true));
assertThrows(ApiRuntimeException.class, () -> this.service.listUsersByIds(Collections.singletonList(1234L)));
assertThrows(ApiRuntimeException.class,
() -> this.service.listUsersByEmails(Collections.singletonList("tibot@symphony.com")));
assertThrows(ApiRuntimeException.class,
() -> this.service.listUsersByUsernames(Collections.singletonList("tibot")));
}
@Test
void searchUserV3ByIds_withParams_Content() {
this.mockApiClient.onGet(SEARCH_USERS_V3, "{}");
assertEquals(Collections.emptyList(),
this.service.listUsersByIds(Collections.singletonList(1234L), true, true));
}
@Test
void searchUserV3ByIds_noParams_noContent() {
this.mockApiClient.onGet(SEARCH_USERS_V3, "{}");
assertEquals(Collections.emptyList(),
this.service.listUsersByIds(Collections.singletonList(1234L)));
}
@Test
void searchUserV3ByEmails_withParams_noContent() {
this.mockApiClient.onGet(SEARCH_USERS_V3, "{}");
assertEquals(Collections.emptyList(),
this.service.listUsersByEmails(Collections.singletonList("x@x.com"), true, true));
}
@Test
void searchUserV3ByUsernames_noParams_noContent() {
this.mockApiClient.onGet(SEARCH_USERS_V3, "{}");
assertEquals(Collections.emptyList(),
this.service.listUsersByEmails(Collections.singletonList("user-name")));
}
@Test
void searchUserV3ByUsernames_withParams_noContent() {
this.mockApiClient.onGet(SEARCH_USERS_V3, "{}");
assertEquals(Collections.emptyList(),
this.service.listUsersByUsernames(Collections.singletonList("user-name"), true));
}
@Test
void searchUserV3ByEmails_noParams_noContent() {
this.mockApiClient.onGet(SEARCH_USERS_V3, "{}");
assertEquals(Collections.emptyList(),
this.service.listUsersByUsernames(Collections.singletonList("x@x.com")));
}
@Test
void searchUserBySearchQueryTest() throws IOException {
String response = JsonHelper.readFromClasspath("/user/users_by_query.json");
this.mockApiClient.onPost(SEARCH_USER_BY_QUERY, response);
UserSearchQuery query = new UserSearchQuery().query("john doe")
.filters(new UserSearchFilter().title("title").company("Gotham").location("New York"));
List<UserV2> users = this.service.searchUsers(query, true);
assertEquals(users.size(), 1);
assertEquals(users.get(0).getUsername(), "john.doe");
assertEquals(users.get(0).getDisplayName(), "John Doe");
}
@Test
void searchUserBySearchQuerySkipLimitTest() throws IOException {
String response = JsonHelper.readFromClasspath("/user/users_by_query.json");
this.mockApiClient.onPost(SEARCH_USER_BY_QUERY, response);
UserSearchQuery query = new UserSearchQuery().query("john doe")
.filters(new UserSearchFilter().title("title").company("Gotham").location("New York"));
List<UserV2> users = this.service.searchUsers(query, true, new PaginationAttribute(0, 100));
assertEquals(users.size(), 1);
assertEquals(users.get(0).getUsername(), "john.doe");
assertEquals(users.get(0).getDisplayName(), "John Doe");
}
@Test
void searchAllUserBySearchQueryTest() throws IOException {
String response = JsonHelper.readFromClasspath("/user/users_by_query.json");
this.mockApiClient.onPost(SEARCH_USER_BY_QUERY, response);
UserSearchQuery query = new UserSearchQuery().query("john doe")
.filters(new UserSearchFilter().title("title").company("Gotham").location("New York"));
List<UserV2> users = this.service.searchAllUsers(query, true).collect(Collectors.toList());
assertEquals(users.size(), 1);
assertEquals(users.get(0).getUsername(), "john.doe");
assertEquals(users.get(0).getDisplayName(), "John Doe");
}
@Test
void searchAllUserBySearchQueryPaginationTest() throws IOException {
String response = JsonHelper.readFromClasspath("/user/users_by_query.json");
this.mockApiClient.onPost(SEARCH_USER_BY_QUERY, response);
UserSearchQuery query = new UserSearchQuery().query("john doe")
.filters(new UserSearchFilter().title("title").company("Gotham").location("New York"));
List<UserV2> users = this.service.searchAllUsers(query, true, new StreamPaginationAttribute(100, 100))
.collect(Collectors.toList());
assertEquals(users.size(), 1);
assertEquals(users.get(0).getUsername(), "john.doe");
assertEquals(users.get(0).getDisplayName(), "John Doe");
}
@Test
void followUserTest() throws ApiException {
this.mockApiClient.onPost(V1_USER_FOLLOW.replace("{uid}", "1234"), "{}");
this.service.followUser(Arrays.asList(12345L, 12346L), 1234L);
verify(this.spiedUserApi).v1UserUidFollowPost(eq("1234"), eq(1234L),
eq(new FollowersList().followers(Arrays.asList(12345L, 12346L))));
}
@Test
void followUserFailed() {
this.mockApiClient.onPost(400, V1_USER_FOLLOW.replace("{uid}", "1234"), "{}");
assertThrows(ApiRuntimeException.class, () -> this.service.followUser(Collections.singletonList(12345L), 1234L));
}
@Test
void unfollowUserTest() throws ApiException {
this.mockApiClient.onPost(V1_USER_UNFOLLOW.replace("{uid}", "1234"), "{}");
this.service.unfollowUser(Arrays.asList(12345L, 12346L), 1234L);
verify(this.spiedUserApi).v1UserUidUnfollowPost(eq("1234"), eq(1234L),
eq(new FollowersList().followers(Arrays.asList(12345L, 12346L))));
}
@Test
void unfollowFailed() {
this.mockApiClient.onPost(400, V1_USER_UNFOLLOW.replace("{uid}", "1234"), "{}");
assertThrows(ApiRuntimeException.class, () -> this.service.unfollowUser(Collections.singletonList(12345L), 1234L));
}
@Test
void listUserFollowersTest() {
this.mockApiClient.onGet(V1_LIST_FOLLOWERS.replace("{uid}", "1234"),
"{\n"
+ " \"count\": 3,\n"
+ " \"followers\": [\n"
+ " 13056700579848,\n"
+ " 13056700580889,\n"
+ " 13056700580890\n"
+ " ],\n"
+ " \"pagination\": {\n"
+ " \"cursors\": {\n"
+ " \"before\": \"1\",\n"
+ " \"after\": \"4\"\n"
+ " }\n"
+ " }\n"
+ "}");
FollowersListResponse response = this.service.listUserFollowers(1234L);
assertEquals(response.getCount(), 3);
assertEquals(response.getFollowers().get(0), 13056700579848L);
assertEquals(response.getFollowers().get(1), 13056700580889L);
assertEquals(response.getFollowers().get(2), 13056700580890L);
}
@Test
void listUserFollowersPaginationTest() {
this.mockApiClient.onGet(V1_LIST_FOLLOWERS.replace("{uid}", "1234"),
"{\n"
+ " \"count\": 3,\n"
+ " \"followers\": [\n"
+ " 13056700579848,\n"
+ " 13056700580889,\n"
+ " 13056700580890\n"
+ " ],\n"
+ " \"pagination\": {\n"
+ " \"cursors\": {\n"
+ " \"before\": \"1\",\n"
+ " \"after\": \"4\"\n"
+ " }\n"
+ " }\n"
+ "}");
FollowersListResponse response = this.service.listUserFollowers(1234L, new CursorPaginationAttribute(4, 1, 5));
assertEquals(response.getCount(), 3);
assertEquals(response.getFollowers().get(0), 13056700579848L);
assertEquals(response.getFollowers().get(1), 13056700580889L);
assertEquals(response.getFollowers().get(2), 13056700580890L);
}
@Test
void listAllUserFollowersTest() {
this.mockApiClient.onGet(V1_LIST_FOLLOWERS.replace("{uid}", "1234"), "{\n"
+ " \"count\": 3,\n"
+ " \"followers\": [\n"
+ " 13056700579848,\n"
+ " 13056700580889,\n"
+ " 13056700580890\n"
+ " ],\n"
+ " \"pagination\": {\n"
+ " \"cursors\": {\n"
+ " \"before\": \"1\"\n"
+ " }\n"
+ " }\n"
+ "}");
List<Long> followers = this.service.listAllUserFollowers(1234L).collect(Collectors.toList());
assertEquals(followers.size(), 3);
assertEquals(followers.get(0), 13056700579848L);
assertEquals(followers.get(1), 13056700580889L);
assertEquals(followers.get(2), 13056700580890L);
}
@Test
void listAllUserFollowersNoPaginationTest() {
this.mockApiClient.onGet(V1_LIST_FOLLOWERS.replace("{uid}", "1234"), "{\n"
+ " \"count\": 3,\n"
+ " \"followers\": [\n"
+ " 13056700579848,\n"
+ " 13056700580889,\n"
+ " 13056700580890\n"
+ " ]\n"
+ "}");
List<Long> followers = this.service.listAllUserFollowers(1234L).collect(Collectors.toList());
assertEquals(followers.size(), 3);
assertEquals(followers.get(0), 13056700579848L);
assertEquals(followers.get(1), 13056700580889L);
assertEquals(followers.get(2), 13056700580890L);
}
@Test
void listAllUserFollowersPaginationTest() {
this.mockApiClient.onGet(V1_LIST_FOLLOWERS.replace("{uid}", "1234"), "{\n"
+ " \"count\": 3,\n"
+ " \"followers\": [\n"
+ " 13056700579848,\n"
+ " 13056700580889,\n"
+ " 13056700580890\n"
+ " ],\n"
+ " \"pagination\": {\n"
+ " \"cursors\": {\n"
+ " \"before\": \"1\"\n"
+ " }\n"
+ " }\n"
+ "}");
List<Long> followers = this.service.listAllUserFollowers(1234L, new StreamPaginationAttribute(10, 10)).collect(Collectors.toList());
assertEquals(followers.size(), 3);
assertEquals(followers.get(0), 13056700579848L);
assertEquals(followers.get(1), 13056700580889L);
assertEquals(followers.get(2), 13056700580890L);
}
@Test
void listUserFollowingTest() {
this.mockApiClient.onGet(V1_LIST_FOLLOWING.replace("{uid}", "1234"),
"{\n"
+ " \"count\": 2,\n"
+ " \"following\": [\n"
+ " 13056700580888,\n"
+ " 13056700580889\n"
+ " ],\n"
+ " \"pagination\": {\n"
+ " \"cursors\": {\n"
+ " \"before\": \"1\"\n"
+ " }\n"
+ " }\n"
+ "}");
FollowingListResponse response = this.service.listUsersFollowing(1234L);
assertEquals(response.getCount(), 2);
assertEquals(response.getFollowing().get(0), 13056700580888L);
assertEquals(response.getFollowing().get(1), 13056700580889L);
}
@Test
void listUserFollowingPaginationTest() {
this.mockApiClient.onGet(V1_LIST_FOLLOWING.replace("{uid}", "1234"),
"{\n"
+ " \"count\": 2,\n"
+ " \"following\": [\n"
+ " 13056700580888,\n"
+ " 13056700580889\n"
+ " ],\n"
+ " \"pagination\": {\n"
+ " \"cursors\": {\n"
+ " \"before\": \"1\"\n"
+ " }\n"
+ " }\n"
+ "}");
FollowingListResponse response = this.service.listUsersFollowing(1234L, new CursorPaginationAttribute(4, 1, 5));
assertEquals(response.getCount(), 2);
assertEquals(response.getFollowing().get(0), 13056700580888L);
assertEquals(response.getFollowing().get(1), 13056700580889L);
}
@Test
void listAllUserFollowingTest() {
this.mockApiClient.onGet(V1_LIST_FOLLOWING.replace("{uid}", "1234"),
"{\n"
+ " \"count\": 2,\n"
+ " \"following\": [\n"
+ " 13056700580888,\n"
+ " 13056700580889\n"
+ " ],\n"
+ " \"pagination\": {\n"
+ " \"cursors\": {\n"
+ " \"before\": \"1\"\n"
+ " }\n"
+ " }\n"
+ "}");
List<Long> followers = this.service.listAllUserFollowing(1234L).collect(Collectors.toList());
assertEquals(followers.size(), 2);
assertEquals(followers.get(0), 13056700580888L);
assertEquals(followers.get(1), 13056700580889L);
}
@Test
void listAllUserFollowingsPaginationTest() {
this.mockApiClient.onGet(V1_LIST_FOLLOWING.replace("{uid}", "1234"),
"{\n"
+ " \"count\": 2,\n"
+ " \"following\": [\n"
+ " 13056700580888,\n"
+ " 13056700580889\n"
+ " ],\n"
+ " \"pagination\": {\n"
+ " \"cursors\": {\n"
+ " \"before\": \"1\"\n"
+ " }\n"
+ " }\n"
+ "}");
List<Long> followers = this.service.listAllUserFollowing(1234L, new StreamPaginationAttribute(10, 10)).collect(Collectors.toList());
assertEquals(followers.size(), 2);
assertEquals(followers.get(0), 13056700580888L);
assertEquals(followers.get(1), 13056700580889L);
}
@Test
void listAllUserFollowingsPaginationNoPaginationTest() {
this.mockApiClient.onGet(V1_LIST_FOLLOWING.replace("{uid}", "1234"),
"{\n"
+ " \"count\": 2,\n"
+ " \"following\": [\n"
+ " 13056700580888,\n"
+ " 13056700580889\n"
+ " ]\n"
+ "}");
List<Long> followers = this.service.listAllUserFollowing(1234L, new StreamPaginationAttribute(10, 10)).collect(Collectors.toList());
assertEquals(followers.size(), 2);
assertEquals(followers.get(0), 13056700580888L);
assertEquals(followers.get(1), 13056700580889L);
}
@Test
void userDetailMapperNullTest() {
V2UserDetail userDetailNull = UserDetailMapper.INSTANCE.userDetailToV2UserDetail(null);
assertNull(userDetailNull);
V2UserDetail userDetail = UserDetailMapper.INSTANCE.userDetailToV2UserDetail(new UserDetail());
assertNull(userDetail.getUserAttributes());
V2UserDetail userDetail1 = UserDetailMapper.INSTANCE.userDetailToV2UserDetail(
new UserDetail().userAttributes(new UserAttributes().accountType(null)));
assertNull(userDetail1.getUserAttributes().getAccountType());
}
@Test
void createUser() throws IOException {
String responseV2 = JsonHelper.readFromClasspath("/user/user_detail.json");
this.mockApiClient.onPost(V2_USER_CREATE, responseV2);
V2UserDetail userDetails = this.service.create(new V2UserCreate());
assertEquals(userDetails.getUserAttributes().getUserName(), "johndoe");
}
@Test
void createUserMissingPayload() {
Exception exception = assertThrows(ApiRuntimeException.class, () -> this.service.create(null));
assertTrue(exception.getMessage().contains(
String.format(MISSING_REQUIRED_PARAMETER_EXCEPTION_MESSAGE, "payload", "v2AdminUserCreatePost")));
}
@Test
void updateUser() throws IOException {
String responseV2 = JsonHelper.readFromClasspath("/user/user_detail.json");
responseV2 = responseV2.replace("\"userName\": \"johndoe\"", "\"userName\": \"johndoe-UPDATED\"");
Long userId = 7215545078461L;
this.mockApiClient.onPost(V2_USER_UPDATE.replace("{uid}", userId+""), responseV2);
V2UserDetail userDetails = this.service.update(userId, new V2UserAttributes());
assertEquals(userDetails.getUserAttributes().getUserName(), "johndoe-UPDATED");
}
@Test
void updateUserMissingPayload() {
this.mockApiClient.onPost(V2_USER_UPDATE.replace("{uid}", "123L"), "resContent");
Exception exception = assertThrows(ApiRuntimeException.class, () -> this.service.update(123L, null));
assertTrue(exception.getMessage().contains(
String.format(MISSING_REQUIRED_PARAMETER_EXCEPTION_MESSAGE, "payload", "v2AdminUserUidUpdatePost")));
}
@Test
void updateUserMissingUserId() {
this.mockApiClient.onPost(V2_USER_UPDATE.replace("{uid}", "123L"), "resContent");
Exception exception = assertThrows(ApiRuntimeException.class, () -> this.service.update(null, new V2UserAttributes()));
assertTrue(exception.getMessage().contains(
String.format(MISSING_REQUIRED_PARAMETER_EXCEPTION_MESSAGE, "uid", "v2AdminUserUidUpdatePost")));
}
@Test
void listAuditTrail() throws IOException {
String response = JsonHelper.readFromClasspath("/audit_trail/audit_trail_initiator_list_v1.json");
this.mockApiClient.onGet(V1_AUDIT_TRAIL_PRIVILEGED_USER, response);
V1AuditTrailInitiatorList v1AuditTrailInitiatorList = this.service.listAuditTrail(1551888601279L, 1551888601279L,
new CursorPaginationAttribute(1,3,2),1353716993L, "SUPER_ADMINISTRATOR");
assertEquals(v1AuditTrailInitiatorList.getItems().size(), 2);
assertEquals(v1AuditTrailInitiatorList.getPagination(), null);
}
@Test
void listAllAuditTrailNoPagination() throws IOException {
String response = JsonHelper.readFromClasspath("/audit_trail/audit_trail_initiator_list_v1.json");
this.mockApiClient.onGet(V1_AUDIT_TRAIL_PRIVILEGED_USER, response);
final List<V1AuditTrailInitiatorResponse> auditTrails =
this.service.listAllAuditTrail(1551888601279L, 1551888601279L, 1353716993L, "SUPER_ADMINISTRATOR", 2, 3)
.collect(Collectors.toList());
assertEquals(auditTrails.size(), 2);
}
@Test
void listAllAuditTrail() throws IOException {
String response = JsonHelper.readFromClasspath("/audit_trail/audit_trail_initiator_list_v1_pagination.json");
this.mockApiClient.onGet(V1_AUDIT_TRAIL_PRIVILEGED_USER, response);
final List<V1AuditTrailInitiatorResponse> auditTrails =
this.service.listAllAuditTrail(1551888601279L, 1551888601279L, 1353716993L, "SUPER_ADMINISTRATOR", 2, 3)
.collect(Collectors.toList());
assertEquals(auditTrails.size(), 2);
}
@Test
void listAuditTrailOnlyRequiredParams() throws IOException {
String response = JsonHelper.readFromClasspath("/audit_trail/audit_trail_initiator_list_v1.json");
this.mockApiClient.onGet(V1_AUDIT_TRAIL_PRIVILEGED_USER, response);
V1AuditTrailInitiatorList v1AuditTrailInitiatorList = this.service.listAuditTrail(1551888601279L, null,
null, null, null);
assertEquals(v1AuditTrailInitiatorList.getItems().size(), 2);
assertEquals(v1AuditTrailInitiatorList.getPagination(), null);
}
@Test
void listAuditTrailRequiredParamsMissing() throws IOException {
this.mockApiClient.onGet(V1_AUDIT_TRAIL_PRIVILEGED_USER, "resContent");
Exception exception = assertThrows(ApiRuntimeException.class, () -> this.service.listAuditTrail(null, 1551888601279L,
new CursorPaginationAttribute(1,3,2),1353716993L, "SUPER_ADMINISTRATOR"));
assertTrue(exception.getMessage().contains(
String.format(MISSING_REQUIRED_PARAMETER_EXCEPTION_MESSAGE, "startTimestamp", "v1AudittrailPrivilegeduserGet")));
}
@Test
void suspendUserTestSuccess() throws ApiException {
this.mockApiClient.onPut(SUSPEND_USER.replace("{uid}", "1234"), "{}");
UserSuspension userSuspension = new UserSuspension();
userSuspension.setSuspended(true);
userSuspension.setSuspensionReason("reason why");
Instant now = Instant.now();
userSuspension.setSuspendedUntil(now.toEpochMilli());
this.service.suspendUser(1234L, "reason why", now);
verify(spiedUserApi).v1AdminUserUserIdSuspensionUpdatePut(
eq("1234"),
eq(1234L),
eq(userSuspension));
}
@Test
void suspendUserTestFailed() {
this.mockApiClient.onPut(400, SUSPEND_USER.replace("{uid}", "1234"), "{}");
assertThrows(ApiRuntimeException.class,
() -> this.service.suspendUser(1234L, "reason", Instant.now().plus(Duration.ofDays(1))));
}
@Test
void unsuspendUserTestSuccess() throws ApiException {
this.mockApiClient.onPut(SUSPEND_USER.replace("{uid}", "1234"), "{}");
UserSuspension userSuspension = new UserSuspension();
userSuspension.setSuspended(false);
this.service.unsuspendUser(1234L);
verify(spiedUserApi).v1AdminUserUserIdSuspensionUpdatePut(
eq("1234"),
eq(1234L),
eq(userSuspension));
}
@Test
void unsuspendUserTestFailed() {
this.mockApiClient.onPut(400, SUSPEND_USER.replace("{uid}", "1234"), "{}");
assertThrows(ApiRuntimeException.class,
() -> this.service.unsuspendUser(1234L));
}
}
|
package com.github.dantin.cubic.protocol.room;
import com.fasterxml.jackson.annotation.JsonGetter;
import com.fasterxml.jackson.annotation.JsonSetter;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.github.dantin.cubic.protocol.Pagination;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
@JsonDeserialize(builder = RoutePage.Builder.class)
public class RoutePage extends Pagination {
private static final String ROUTES_FIELD = "routes";
private final List<Route> routes;
private RoutePage(Builder builder) {
super(builder);
this.routes = builder.routes;
}
public static Builder builder() {
return new Builder();
}
@JsonGetter(ROUTES_FIELD)
public List<Route> getRoutes() {
return routes;
}
public static final class Builder extends PaginationBuilder<Builder, RoutePage> {
private List<Route> routes;
private Builder() {
this.routes = new ArrayList<>();
}
@JsonSetter(ROUTES_FIELD)
public Builder routes(List<Route> routes) {
this.routes = routes;
return this;
}
public Builder addRoute(Route route) {
if (!Objects.isNull(route)) {
this.routes.add(route);
}
return this;
}
@Override
public RoutePage build() {
this.size(routes.size());
return new RoutePage(this);
}
}
}
|
package server.service;
import com.zada.hackathon.client.DataClients;
/**
* Created by omar on 15/10/30.
*/
public class DataClientService {
// public static DataClients keyWordClient = new DataClients("127.0.0.1:9090,127.0.0.1:9090");
public static DataClients keyWordClient = new DataClients("192.168.99.1:9090,192.168.99.1:9090");
}
|
/*
* Copyright 2016-present Open Networking Laboratory
*
* 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.
*/
/**
* Server-side modeling of UI entities.
* <p>
* The classes in this package are thin wrappers around core model objects
* (where possible). Together, they provide a model of what the user can
* "see" in the UI, and how the user can interact with that (visual) model.
*/
package org.onosproject.ui.model;
|
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ohos.devtools.views.applicationtrace.bean;
import org.junit.jupiter.api.Test;
import java.lang.reflect.Field;
import java.util.ArrayList;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
class CpuTest {
@Test
void getCpu() throws NoSuchFieldException, IllegalAccessException {
Cpu cpu = new Cpu();
final Field field = cpu.getClass().getDeclaredField("cpu");
field.setAccessible(true);
field.set(cpu, -1);
assertEquals(-1, cpu.getCpu());
final Field nullField = cpu.getClass().getDeclaredField("cpu");
nullField.setAccessible(true);
nullField.set(cpu, null);
assertNull(cpu.getCpu());
final Field emptyField = cpu.getClass().getDeclaredField("cpu");
emptyField.setAccessible(true);
emptyField.set(cpu, 0);
assertEquals(0, cpu.getCpu());
}
@Test
void setCpu() throws NoSuchFieldException, IllegalAccessException {
Cpu cpu = new Cpu();
cpu.setCpu(0);
final Field field = cpu.getClass().getDeclaredField("cpu");
field.setAccessible(true);
assertEquals(field.get(cpu), 0);
cpu.setCpu(-1);
final Field emptyField = cpu.getClass().getDeclaredField("cpu");
emptyField.setAccessible(true);
assertEquals(emptyField.get(cpu), -1);
cpu.setCpu(null);
final Field nullField = cpu.getClass().getDeclaredField("cpu");
nullField.setAccessible(true);
assertNull(nullField.get(cpu));
}
@Test
void getName() throws NoSuchFieldException, IllegalAccessException {
Cpu cpu = new Cpu();
final Field field = cpu.getClass().getDeclaredField("name");
field.setAccessible(true);
field.set(cpu, "cpu");
assertEquals("cpu", cpu.getName());
final Field nullField = cpu.getClass().getDeclaredField("name");
nullField.setAccessible(true);
nullField.set(cpu, null);
assertNull(cpu.getName());
final Field emptyField = cpu.getClass().getDeclaredField("name");
emptyField.setAccessible(true);
emptyField.set(cpu, "");
assertEquals("", cpu.getName());
}
@Test
void setName() throws NoSuchFieldException, IllegalAccessException {
Cpu cpu = new Cpu();
cpu.setName("name");
final Field field = cpu.getClass().getDeclaredField("name");
field.setAccessible(true);
assertEquals(field.get(cpu), "name");
cpu.setName("");
final Field emptyField = cpu.getClass().getDeclaredField("name");
emptyField.setAccessible(true);
assertEquals(emptyField.get(cpu), "");
cpu.setName(null);
final Field nullField = cpu.getClass().getDeclaredField("name");
nullField.setAccessible(true);
assertNull(nullField.get(cpu));
}
@Test
void getStats() throws NoSuchFieldException, IllegalAccessException {
Cpu cpu = new Cpu();
ArrayList<Integer> ints = new ArrayList<>();
ints.add(1);
ints.add(2);
ints.add(3);
ints.add(4);
ints.add(5);
ints.add(6);
final Field field = cpu.getClass().getDeclaredField("stats");
field.setAccessible(true);
field.set(cpu, ints);
assertEquals(ints, cpu.getStats());
final Field nullField = cpu.getClass().getDeclaredField("stats");
nullField.setAccessible(true);
nullField.set(cpu, null);
assertNull(cpu.getStats());
final Field emptyField = cpu.getClass().getDeclaredField("stats");
emptyField.setAccessible(true);
emptyField.set(cpu, ints);
assertEquals(ints, cpu.getStats());
}
@Test
void setStats() throws NoSuchFieldException, IllegalAccessException {
Cpu cpu = new Cpu();
ArrayList<Integer> ints = new ArrayList<>();
ints.add(1);
ints.add(2);
ints.add(3);
ints.add(4);
ints.add(5);
ints.add(6);
cpu.setStats(ints);
final Field field = cpu.getClass().getDeclaredField("stats");
field.setAccessible(true);
assertEquals(field.get(cpu), ints);
ArrayList<Integer> emptyInts = new ArrayList<>();
cpu.setStats(emptyInts);
final Field emptyField = cpu.getClass().getDeclaredField("stats");
emptyField.setAccessible(true);
assertEquals(emptyField.get(cpu), emptyInts);
cpu.setStats(null);
final Field nullField = cpu.getClass().getDeclaredField("stats");
nullField.setAccessible(true);
assertNull(nullField.get(cpu));
}
@Test
void getEndState() throws NoSuchFieldException, IllegalAccessException {
Cpu cpu = new Cpu();
final Field field = cpu.getClass().getDeclaredField("endState");
field.setAccessible(true);
field.set(cpu, "endState");
assertEquals("endState", cpu.getEndState());
final Field nullField = cpu.getClass().getDeclaredField("endState");
nullField.setAccessible(true);
nullField.set(cpu, null);
assertNull(cpu.getEndState());
final Field emptyField = cpu.getClass().getDeclaredField("endState");
emptyField.setAccessible(true);
emptyField.set(cpu, "");
assertEquals("", cpu.getEndState());
}
@Test
void setEndState() throws NoSuchFieldException, IllegalAccessException {
Cpu cpu = new Cpu();
cpu.setEndState("endState");
final Field field = cpu.getClass().getDeclaredField("endState");
field.setAccessible(true);
assertEquals(field.get(cpu), "endState");
cpu.setEndState("");
final Field emptyField = cpu.getClass().getDeclaredField("endState");
emptyField.setAccessible(true);
assertEquals(emptyField.get(cpu), "");
cpu.setEndState(null);
final Field nullField = cpu.getClass().getDeclaredField("endState");
nullField.setAccessible(true);
assertNull(nullField.get(cpu));
}
@Test
void getPriority() throws NoSuchFieldException, IllegalAccessException {
Cpu cpu = new Cpu();
final Field field = cpu.getClass().getDeclaredField("priority");
field.setAccessible(true);
field.set(cpu, 0);
assertEquals(0, cpu.getPriority());
final Field nullField = cpu.getClass().getDeclaredField("priority");
nullField.setAccessible(true);
nullField.set(cpu, null);
assertNull(cpu.getPriority());
final Field emptyField = cpu.getClass().getDeclaredField("priority");
emptyField.setAccessible(true);
emptyField.set(cpu, -1);
assertEquals(-1, cpu.getPriority());
}
@Test
void setPriority() throws NoSuchFieldException, IllegalAccessException {
Cpu cpu = new Cpu();
cpu.setPriority(0);
final Field field = cpu.getClass().getDeclaredField("priority");
field.setAccessible(true);
assertEquals(field.get(cpu), 0);
cpu.setPriority(-1);
final Field emptyField = cpu.getClass().getDeclaredField("priority");
emptyField.setAccessible(true);
assertEquals(emptyField.get(cpu), -1);
cpu.setPriority(null);
final Field nullField = cpu.getClass().getDeclaredField("priority");
nullField.setAccessible(true);
assertNull(nullField.get(cpu));
}
@Test
void getSchedId() throws NoSuchFieldException, IllegalAccessException {
Cpu cpu = new Cpu();
final Field field = cpu.getClass().getDeclaredField("schedId");
field.setAccessible(true);
field.set(cpu, 0);
assertEquals(0, cpu.getSchedId());
final Field nullField = cpu.getClass().getDeclaredField("schedId");
nullField.setAccessible(true);
nullField.set(cpu, null);
assertNull(cpu.getSchedId());
final Field emptyField = cpu.getClass().getDeclaredField("schedId");
emptyField.setAccessible(true);
emptyField.set(cpu, -1);
assertEquals(-1, cpu.getSchedId());
}
@Test
void setSchedId() throws NoSuchFieldException, IllegalAccessException {
Cpu cpu = new Cpu();
cpu.setSchedId(0);
final Field field = cpu.getClass().getDeclaredField("schedId");
field.setAccessible(true);
assertEquals(field.get(cpu), 0);
cpu.setSchedId(-1);
final Field emptyField = cpu.getClass().getDeclaredField("schedId");
emptyField.setAccessible(true);
assertEquals(emptyField.get(cpu), -1);
cpu.setSchedId(null);
final Field nullField = cpu.getClass().getDeclaredField("schedId");
nullField.setAccessible(true);
assertNull(nullField.get(cpu));
}
@Test
void getStartTime() throws NoSuchFieldException, IllegalAccessException {
Cpu cpu = new Cpu();
final Field field = cpu.getClass().getDeclaredField("startTime");
field.setAccessible(true);
field.set(cpu, 0L);
assertEquals(0L, cpu.getStartTime());
final Field nullField = cpu.getClass().getDeclaredField("startTime");
nullField.setAccessible(true);
nullField.set(cpu, 1L);
assertEquals(1L, cpu.getStartTime());
final Field emptyField = cpu.getClass().getDeclaredField("startTime");
emptyField.setAccessible(true);
emptyField.set(cpu, -1L);
assertEquals(-1L, cpu.getStartTime());
}
@Test
void setStartTime() throws NoSuchFieldException, IllegalAccessException {
Cpu cpu = new Cpu();
cpu.setStartTime(0L);
final Field field = cpu.getClass().getDeclaredField("startTime");
field.setAccessible(true);
assertEquals(field.get(cpu), 0L);
cpu.setStartTime(-1L);
final Field emptyField = cpu.getClass().getDeclaredField("startTime");
emptyField.setAccessible(true);
assertEquals(emptyField.get(cpu), -1L);
cpu.setStartTime(1L);
final Field nullField = cpu.getClass().getDeclaredField("startTime");
nullField.setAccessible(true);
assertEquals(nullField.get(cpu), 1L);
}
@Test
void getDuration() throws NoSuchFieldException, IllegalAccessException {
Cpu cpu = new Cpu();
final Field field = cpu.getClass().getDeclaredField("duration");
field.setAccessible(true);
field.set(cpu, 0L);
assertEquals(0L, cpu.getDuration());
final Field nullField = cpu.getClass().getDeclaredField("duration");
nullField.setAccessible(true);
nullField.set(cpu, 1L);
assertEquals(1L, cpu.getDuration());
final Field emptyField = cpu.getClass().getDeclaredField("duration");
emptyField.setAccessible(true);
emptyField.set(cpu, -1L);
assertEquals(-1L, cpu.getDuration());
}
@Test
void setDuration() throws NoSuchFieldException, IllegalAccessException {
Cpu cpu = new Cpu();
cpu.setDuration(0L);
final Field field = cpu.getClass().getDeclaredField("duration");
field.setAccessible(true);
assertEquals(field.get(cpu), 0L);
cpu.setDuration(-1L);
final Field emptyField = cpu.getClass().getDeclaredField("duration");
emptyField.setAccessible(true);
assertEquals(emptyField.get(cpu), -1L);
cpu.setDuration(1L);
final Field nullField = cpu.getClass().getDeclaredField("duration");
nullField.setAccessible(true);
assertEquals(nullField.get(cpu), 1L);
}
@Test
void getType() throws NoSuchFieldException, IllegalAccessException {
Cpu cpu = new Cpu();
final Field field = cpu.getClass().getDeclaredField("type");
field.setAccessible(true);
field.set(cpu, "type");
assertEquals("type", cpu.getType());
final Field nullField = cpu.getClass().getDeclaredField("type");
nullField.setAccessible(true);
nullField.set(cpu, null);
assertNull(cpu.getType());
final Field emptyField = cpu.getClass().getDeclaredField("type");
emptyField.setAccessible(true);
emptyField.set(cpu, "");
assertEquals("", cpu.getType());
}
@Test
void setType() throws NoSuchFieldException, IllegalAccessException {
Cpu cpu = new Cpu();
cpu.setType("type");
final Field field = cpu.getClass().getDeclaredField("type");
field.setAccessible(true);
assertEquals(field.get(cpu), "type");
cpu.setType("");
final Field emptyField = cpu.getClass().getDeclaredField("type");
emptyField.setAccessible(true);
assertEquals(emptyField.get(cpu), "");
cpu.setType(null);
final Field nullField = cpu.getClass().getDeclaredField("type");
nullField.setAccessible(true);
assertNull(nullField.get(cpu));
}
@Test
void getId() throws NoSuchFieldException, IllegalAccessException {
Cpu cpu = new Cpu();
final Field field = cpu.getClass().getDeclaredField("id");
field.setAccessible(true);
field.set(cpu, 0);
assertEquals(0, cpu.getId());
final Field nullField = cpu.getClass().getDeclaredField("id");
nullField.setAccessible(true);
nullField.set(cpu, null);
assertNull(cpu.getId());
final Field emptyField = cpu.getClass().getDeclaredField("id");
emptyField.setAccessible(true);
emptyField.set(cpu, -1);
assertEquals(-1, cpu.getId());
}
@Test
void setId() throws NoSuchFieldException, IllegalAccessException {
Cpu cpu = new Cpu();
cpu.setId(0);
final Field field = cpu.getClass().getDeclaredField("id");
field.setAccessible(true);
assertEquals(field.get(cpu), 0);
cpu.setId(-1);
final Field emptyField = cpu.getClass().getDeclaredField("id");
emptyField.setAccessible(true);
assertEquals(emptyField.get(cpu), -1);
cpu.setId(null);
final Field nullField = cpu.getClass().getDeclaredField("id");
nullField.setAccessible(true);
assertNull(nullField.get(cpu));
}
@Test
void getTid() throws NoSuchFieldException, IllegalAccessException {
Cpu cpu = new Cpu();
final Field field = cpu.getClass().getDeclaredField("tid");
field.setAccessible(true);
field.set(cpu, 0);
assertEquals(0, cpu.getTid());
final Field nullField = cpu.getClass().getDeclaredField("tid");
nullField.setAccessible(true);
nullField.set(cpu, null);
assertNull(cpu.getTid());
final Field emptyField = cpu.getClass().getDeclaredField("tid");
emptyField.setAccessible(true);
emptyField.set(cpu, -1);
assertEquals(-1, cpu.getTid());
}
@Test
void setTid() throws NoSuchFieldException, IllegalAccessException {
Cpu cpu = new Cpu();
cpu.setTid(0);
final Field field = cpu.getClass().getDeclaredField("tid");
field.setAccessible(true);
assertEquals(field.get(cpu), 0);
cpu.setTid(-1);
final Field emptyField = cpu.getClass().getDeclaredField("tid");
emptyField.setAccessible(true);
assertEquals(emptyField.get(cpu), -1);
cpu.setTid(null);
final Field nullField = cpu.getClass().getDeclaredField("tid");
nullField.setAccessible(true);
assertNull(nullField.get(cpu));
}
@Test
void getProcessCmdLine() throws NoSuchFieldException, IllegalAccessException {
Cpu cpu = new Cpu();
final Field field = cpu.getClass().getDeclaredField("processCmdLine");
field.setAccessible(true);
field.set(cpu, "processCmdLine");
assertEquals("processCmdLine", cpu.getProcessCmdLine());
final Field nullField = cpu.getClass().getDeclaredField("processCmdLine");
nullField.setAccessible(true);
nullField.set(cpu, null);
assertNull(cpu.getProcessCmdLine());
final Field emptyField = cpu.getClass().getDeclaredField("processCmdLine");
emptyField.setAccessible(true);
emptyField.set(cpu, "");
assertEquals("", cpu.getProcessCmdLine());
}
@Test
void setProcessCmdLine() throws NoSuchFieldException, IllegalAccessException {
Cpu cpu = new Cpu();
cpu.setProcessCmdLine("processCmdLine");
final Field field = cpu.getClass().getDeclaredField("processCmdLine");
field.setAccessible(true);
assertEquals(field.get(cpu), "processCmdLine");
cpu.setProcessCmdLine("");
final Field emptyField = cpu.getClass().getDeclaredField("processCmdLine");
emptyField.setAccessible(true);
assertEquals(emptyField.get(cpu), "");
cpu.setProcessCmdLine(null);
final Field nullField = cpu.getClass().getDeclaredField("processCmdLine");
nullField.setAccessible(true);
assertNull(nullField.get(cpu));
}
@Test
void getProcessName() throws NoSuchFieldException, IllegalAccessException {
Cpu cpu = new Cpu();
final Field field = cpu.getClass().getDeclaredField("processName");
field.setAccessible(true);
field.set(cpu, "processName");
assertEquals("processName", cpu.getProcessName());
final Field nullField = cpu.getClass().getDeclaredField("processName");
nullField.setAccessible(true);
nullField.set(cpu, null);
assertNull(cpu.getProcessName());
final Field emptyField = cpu.getClass().getDeclaredField("processName");
emptyField.setAccessible(true);
emptyField.set(cpu, "");
assertEquals("", cpu.getProcessName());
}
}
|
package info.orestes.rest.forms;
import org.junit.Test;
import java.io.StringReader;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import static info.orestes.rest.forms.Part.formData;
import static java.util.Arrays.asList;
import static org.junit.Assert.*;
/**
* Created on 2018-10-23.
*
* @author Konstantin Simon Maria Möllers
*/
public class FormDataTest {
@Test
public void iterator() {
var formData = new FormData();
assertTrue(formData.isEmpty());
assertEquals(0, formData.size());
// Try appending a new entry
formData.append("foo", "42");
formData.append("bar", "12");
formData.append("bar", "23");
Iterator<Part> iterator = formData.iterator();
assertTrue(iterator.hasNext());
assertEquals(formData("bar", "12"), iterator.next());
assertTrue(iterator.hasNext());
assertEquals(formData("bar", "23"), iterator.next());
assertTrue(iterator.hasNext());
assertEquals(formData("foo", "42"), iterator.next());
assertFalse(iterator.hasNext());
}
@Test
public void set() {
var formData = new FormData();
assertFalse(formData.has("foo"));
assertTrue(formData.isEmpty());
assertEquals(0, formData.size());
assertNull(formData.get("foo"));
assertEquals(Collections.emptyList(), formData.getAll("foo"));
// Try setting a new entry
formData.set("foo", "12");
assertTrue(formData.has("foo"));
assertEquals(1, formData.size());
assertEquals(formData("foo", "12"), formData.get("foo"));
assertEquals(Collections.singletonList(formData("foo", "12")), formData.getAll("foo"));
// Try appending a new entry
formData.append("foo", "42");
assertTrue(formData.has("foo"));
assertEquals(1, formData.size());
assertEquals(formData("foo", "12"), formData.get("foo"));
assertEquals(asList(formData("foo", "12"), formData("foo", "42")), formData.getAll("foo"));
// Only append should add new entries
var foo = formData.getAll("foo");
foo.add(formData("foo", "false entry"));
assertEquals(asList(
Part.formData("foo", "12"),
Part.formData("foo", "42")
), formData.getAll("foo"));
}
@Test
public void delete() {
var formData = new FormData();
assertFalse(formData.has("foo"));
assertTrue(formData.isEmpty());
assertEquals(0, formData.size());
assertNull(formData.get("foo"));
assertEquals(Collections.emptyList(), formData.getAll("foo"));
// Try deleting an entry which does not exist
assertNull(formData.delete("bar"));
formData.append("bar", "foo");
formData.append("bar", "baz");
assertNotEquals(Collections.emptyList(), formData.getAll("bar"));
// Try deleting an entry which does exist
assertEquals(formData("bar", "foo"), formData.delete("bar"));
assertTrue(formData.isEmpty());
assertEquals(0, formData.size());
assertEquals(Collections.emptyList(), formData.getAll("bar"));
}
@Test
public void deleteAll() {
var formData = new FormData();
assertFalse(formData.has("foo"));
assertTrue(formData.isEmpty());
assertEquals(0, formData.size());
assertNull(formData.get("foo"));
assertEquals(Collections.emptyList(), formData.getAll("foo"));
// Try deleting an entry which does not exist
assertEquals(Collections.emptyList(), formData.deleteAll("bar"));
formData.append("bar", "foo");
formData.append("bar", "baz");
assertNotEquals(Collections.emptyList(), formData.getAll("bar"));
// Try deleting an entry which does exist
assertEquals(asList(formData("bar", "foo"), formData("bar", "baz")), formData.deleteAll("bar"));
assertTrue(formData.isEmpty());
assertEquals(0, formData.size());
assertEquals(Collections.emptyList(), formData.getAll("bar"));
}
@Test
public void append() {
var formData = new FormData();
assertFalse(formData.has("foo"));
assertTrue(formData.isEmpty());
assertEquals(0, formData.size());
assertNull(formData.get("foo"));
assertEquals(Collections.emptyList(), formData.getAll("foo"));
// Try setting a new entry
formData.append("foo", "12");
assertTrue(formData.has("foo"));
assertEquals(1, formData.size());
assertEquals(formData("foo", "12"), formData.get("foo"));
assertEquals(Collections.singletonList(formData("foo", "12")), formData.getAll("foo"));
// Try appending a new entry
formData.append("foo", "42");
assertTrue(formData.has("foo"));
assertEquals(1, formData.size());
assertEquals(formData("foo", "12"), formData.get("foo"));
assertEquals(asList(formData("foo", "12"), formData("foo", "42")), formData.getAll("foo"));
// Only append should add new entries
var foo = formData.getAll("foo");
foo.add(formData("foo", "false entry"));
assertEquals(asList(formData("foo", "12"), formData("foo", "42")), formData.getAll("foo"));
}
@Test
public void fromReader() throws Exception {
var str1 = new StringReader("------boundary\n" +
"Content-Disposition: form-data; name=\"pageLoadTime\"\n" +
"\n" +
"395\n" +
"------boundary\n" +
"Content-Disposition: form-data; name=\"dns\"\n" +
"\n" +
"0\n" +
"------boundary\n" +
"Content-Disposition: form-data; name=\"tcp\"\n" +
"\n" +
"1\n" +
"------boundary\n" +
"Content-Disposition: form-data; name=\"serverResponseTime\"\n" +
"\n" +
"25\n" +
"------boundary\n" +
"Content-Disposition: form-data; name=\"download\"\n" +
"\n" +
"8\n" +
"------boundary\n" +
"Content-Disposition: form-data; name=\"redirectTime\"\n" +
"\n" +
"1\n" +
"------boundary\n" +
"Content-Disposition: form-data; name=\"domInteractive\"\n" +
"\n" +
"326\n" +
"------boundary\n" +
"Content-Disposition: form-data; name=\"contentLoaded\"\n" +
"\n" +
"326\n" +
"------boundary--");
var formData1 = FormData.fromReader(str1, "----boundary");
assertNotNull(formData1);
assertEquals(8, formData1.size());
assertEquals(formData("pageLoadTime", "395"), formData1.get("pageLoadTime"));
assertEquals(formData("dns", "0"), formData1.get("dns"));
assertEquals(formData("tcp", "1"), formData1.get("tcp"));
assertEquals(formData("serverResponseTime", "25"), formData1.get("serverResponseTime"));
assertEquals(formData("download", "8"), formData1.get("download"));
assertEquals(formData("redirectTime", "1"), formData1.get("redirectTime"));
assertEquals(formData("domInteractive", "326"), formData1.get("domInteractive"));
assertEquals(formData("contentLoaded", "326"), formData1.get("contentLoaded"));
var str2 = new StringReader("------WebKitFormBoundaryxLLEzKa7Nb1eI2Mr\n" +
"Content-Disposition: form-data; name=\"foo\"\n" +
"\n" +
"bar\n" +
"------WebKitFormBoundaryxLLEzKa7Nb1eI2Mr\n" +
"Content-Disposition: form-data; name=\"foo\"\n" +
"\n" +
"baz\n" +
"------WebKitFormBoundaryxLLEzKa7Nb1eI2Mr--");
var formData2 = FormData.fromReader(str2, "----WebKitFormBoundaryxLLEzKa7Nb1eI2Mr");
assertNotNull(formData2);
assertEquals(1, formData2.size());
assertEquals(formData("foo", "bar"), formData2.get("foo"));
assertEquals(asList(formData("foo", "bar"), formData("foo", "baz")), formData2.getAll("foo"));
}
@Test
public void stringify() {
var formData = new FormData();
formData.append("foo", "bar");
formData.append("baz", "bar");
assertEquals(
"--b\ncontent-disposition: form-data; name=\"foo\"\n\nbar\n--b\ncontent-disposition: form-data; name=\"baz\"\n\nbar\n--b--",
formData.toString("b")
);
}
}
|
package commandnode;
import exception.SLogoException;
import model.SLogoCharacterState;
/**
* @author Adam Tache
* Node representation of ClearScreen command
*/
public class ClearScreenNode extends NullaryNode{
/**
* @return distance to home
* Sets state to be cleared on next display update
* Creates and evaluates HomeNode to send turtle to (0,0)
*/
public double evaluate(SLogoCharacterState state) throws SLogoException {
state.queueLineClearing(true);
return new HomeNode().evaluate(state);
}
}
|
/*
* Copyright © 2014 - 2021 Leipzig University (Database Research Group)
*
* 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.gradoop.temporal.model.impl.operators.matching.single.cypher.functions;
import com.google.common.collect.Maps;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.util.Collector;
import org.gradoop.common.model.api.entities.EdgeFactory;
import org.gradoop.common.model.api.entities.Element;
import org.gradoop.common.model.api.entities.GraphHeadFactory;
import org.gradoop.common.model.api.entities.VertexFactory;
import org.gradoop.common.model.impl.id.GradoopId;
import org.gradoop.common.model.impl.properties.PropertyValue;
import org.gradoop.flink.model.impl.operators.matching.single.PatternMatching;
import org.gradoop.flink.model.impl.operators.matching.single.cypher.pojos.Embedding;
import org.gradoop.flink.model.impl.operators.matching.single.cypher.pojos.EmbeddingMetaData;
import org.gradoop.flink.model.impl.operators.matching.single.cypher.utils.ExpandDirection;
import org.gradoop.temporal.model.impl.pojo.TemporalEdge;
import org.gradoop.temporal.model.impl.pojo.TemporalGraphHead;
import org.gradoop.temporal.model.impl.pojo.TemporalVertex;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Extracts elements from an {@link Embedding}.
* Is almost identical to
* {@link org.gradoop.flink.model.impl.operators.matching.single.cypher.functions.ElementsFromEmbedding}
* extends it for TPGM embeddings.
* Could be further extended to specify temporal properties like global val/tx in the graph head
*
* @param <G> The graph head type.
* @param <V> The vertex type.
* @param <E> The edge type.
*/
public class ElementsFromEmbeddingTPGM<
G extends TemporalGraphHead,
V extends TemporalVertex,
E extends TemporalEdge> implements FlatMapFunction<Embedding, Element> {
/**
* Constructs temporal graph heads
*/
private final GraphHeadFactory<G> graphHeadFactory;
/**
* Constructs temporal vertices
*/
private final VertexFactory<V> vertexFactory;
/**
* Constructs temporal edges
*/
private final EdgeFactory<E> edgeFactory;
/**
* Describes the embedding content
*/
private final EmbeddingMetaData metaData;
/**
* Source vertex variables by edge id
*/
private final Map<String, Pair<String, String>> sourceTargetVariables;
/**
* Stores the mapping between query variable and element id. The mapping is added as a property
* to the graph head representing an embedding.
*/
private final Map<PropertyValue, PropertyValue> variableMapping;
/**
* Stores the identifiers that have already been processed.
*/
private final Set<GradoopId> processedIds;
/**
* Stores the mapping between return pattern variables and its labels
*/
private final Map<String, String> labelMapping;
/**
* Constructor.
*
* @param graphHeadFactory temporal graph head factory
* @param vertexFactory temporal vertex factory
* @param edgeFactory temporal edge factory
* @param embeddingMetaData meta data for the TPGM embedding
* @param sourceTargetVariables source and target vertex variables by edge variable
*/
public ElementsFromEmbeddingTPGM(GraphHeadFactory<G> graphHeadFactory,
VertexFactory<V> vertexFactory, EdgeFactory<E> edgeFactory,
EmbeddingMetaData embeddingMetaData,
Map<String, Pair<String, String>> sourceTargetVariables) {
this(graphHeadFactory, vertexFactory, edgeFactory, embeddingMetaData,
sourceTargetVariables, Maps.newHashMapWithExpectedSize(0));
}
/**
* Constructor.
*
* @param graphHeadFactory temporal graph head factory
* @param vertexFactory temporal vertex factory
* @param edgeFactory temporal edge factory
* @param embeddingMetaData meta data for the TPGM embedding
* @param sourceTargetVariables source and target vertex variables by edge variable
* @param labelMapping mapping between newElementVariables and its labels
*/
public ElementsFromEmbeddingTPGM(GraphHeadFactory<G> graphHeadFactory,
VertexFactory<V> vertexFactory,
EdgeFactory<E> edgeFactory,
EmbeddingMetaData embeddingMetaData,
Map<String, Pair<String, String>> sourceTargetVariables,
Map<String, String> labelMapping) {
this.graphHeadFactory = graphHeadFactory;
this.vertexFactory = vertexFactory;
this.edgeFactory = edgeFactory;
this.metaData = embeddingMetaData;
this.sourceTargetVariables = sourceTargetVariables;
this.labelMapping = labelMapping;
this.variableMapping = new HashMap<>(embeddingMetaData.getEntryCount());
this.processedIds = new HashSet<>(embeddingMetaData.getEntryCount());
}
@Override
public void flatMap(Embedding embedding, Collector<Element> out) throws Exception {
// clear for each embedding
processedIds.clear();
// create graph head for this embedding
TemporalGraphHead graphHead = graphHeadFactory.createGraphHead();
// vertices
for (String vertexVariable : metaData.getVertexVariables()) {
GradoopId id = embedding.getId(metaData.getEntryColumn(vertexVariable));
if (labelMapping.containsKey(vertexVariable)) {
String label = labelMapping.get(vertexVariable);
initVertexWithData(out, graphHead, id, label);
} else {
initVertex(out, graphHead, id);
}
variableMapping.put(PropertyValue.create(vertexVariable), PropertyValue.create(id));
}
// edges
GradoopId edgeId;
GradoopId sourceId;
GradoopId targetId;
// Long[] timeData;
for (String edgeVariable : metaData.getEdgeVariables()) {
edgeId = embedding.getId(metaData.getEntryColumn(edgeVariable));
sourceId = embedding.getId(
metaData.getEntryColumn(sourceTargetVariables.get(edgeVariable).getLeft()));
targetId = embedding.getId(
metaData.getEntryColumn(sourceTargetVariables.get(edgeVariable).getRight()));
if (labelMapping.containsKey(edgeVariable)) {
String label = labelMapping.get(edgeVariable);
initEdgeWithData(out, graphHead, edgeId, sourceId, targetId, label);
} else {
initEdge(out, graphHead, edgeId, sourceId, targetId);
}
variableMapping.put(PropertyValue.create(edgeVariable), PropertyValue.create(edgeId));
}
// paths (copied from EPGM)
for (String pathVariable : metaData.getPathVariables()) {
ExpandDirection direction = metaData.getDirection(pathVariable);
List<GradoopId> path = embedding.getIdList(metaData.getEntryColumn(pathVariable));
List<PropertyValue> mappingValue = new ArrayList<>(path.size());
for (int i = 0; i < path.size(); i += 2) {
edgeId = path.get(i);
mappingValue.add(PropertyValue.create(edgeId));
if (direction == ExpandDirection.OUT) {
sourceId = i > 0 ?
path.get(i - 1) :
embedding.getId(
metaData.getEntryColumn(sourceTargetVariables.get(pathVariable).getLeft()));
targetId = i < path.size() - 1 ?
path.get(i + 1) :
embedding.getId(
metaData.getEntryColumn(sourceTargetVariables.get(pathVariable).getRight()));
if (i + 2 < path.size()) {
mappingValue.add(PropertyValue.create(targetId));
}
} else {
sourceId = i < path.size() - 1 ?
path.get(i + 1) :
embedding.getId(
metaData.getEntryColumn(sourceTargetVariables.get(pathVariable).getLeft()));
targetId = i > 0 ?
path.get(i - 1) :
embedding.getId(metaData.getEntryColumn(
sourceTargetVariables.get(pathVariable).getRight()));
if (i > 0) {
mappingValue.add(PropertyValue.create(sourceId));
}
}
initVertex(out, graphHead, sourceId);
initVertex(out, graphHead, targetId);
initEdge(out, graphHead, edgeId, sourceId, targetId);
}
variableMapping.put(PropertyValue.create(pathVariable), PropertyValue.create(mappingValue));
}
graphHead.setProperty(PatternMatching.VARIABLE_MAPPING_KEY, variableMapping);
out.collect(graphHead);
}
/**
* Initializes an vertex using the specified parameters
*
* @param out flat map collector
* @param graphHead temporal graph head to assign vertex to
* @param vertexId vertex identifier
*/
private void initVertex(Collector<Element> out, TemporalGraphHead graphHead,
GradoopId vertexId) {
initVertexWithData(out, graphHead, vertexId, null);
}
/**
* Initializes an vertex using the specified parameters and adds its label
* if the given vertex was created for the return pattern.
*
* @param out flat map collector
* @param graphHead temporal graph head to assign vertex to
* @param vertexId vertex identifier
* @param label label associated with vertex
*/
private void initVertexWithData(Collector<Element> out, TemporalGraphHead graphHead,
GradoopId vertexId,
String label) {
if (!processedIds.contains(vertexId)) {
TemporalVertex v = vertexFactory.initVertex(vertexId);
v.addGraphId(graphHead.getId());
v.setLabel(label);
out.collect(v);
processedIds.add(vertexId);
}
}
/**
* Initializes an edge using the specified parameters.
*
* @param out flat map collector
* @param graphHead temporal graph head to assign edge to
* @param edgeId edge identifier
* @param sourceId source vertex identifier
* @param targetId target vertex identifier
*/
private void initEdge(Collector<Element> out, TemporalGraphHead graphHead,
GradoopId edgeId, GradoopId sourceId, GradoopId targetId) {
initEdgeWithData(out, graphHead, edgeId, sourceId, targetId, null);
}
/**
* Initializes an edge using the specified parameters and adds its label
* if the given edge was created for return pattern
*
* @param out flat map collector
* @param graphHead temporal graph head to assign edge to
* @param edgeId edge identifier
* @param sourceId source vertex identifier
* @param targetId target vertex identifier
* @param label label associated with edge
*/
private void initEdgeWithData(Collector<Element> out, TemporalGraphHead graphHead,
GradoopId edgeId, GradoopId sourceId, GradoopId targetId,
String label) {
if (!processedIds.contains(edgeId)) {
TemporalEdge e = edgeFactory.initEdge(edgeId, sourceId, targetId);
e.addGraphId(graphHead.getId());
e.setLabel(label);
out.collect(e);
processedIds.add(edgeId);
}
}
}
|
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.metrics2.lib;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.hadoop.hbase.classification.InterfaceAudience;
import org.apache.hadoop.metrics2.MetricsExecutor;
/**
* Class to handle the ScheduledExecutorService{@link ScheduledExecutorService} used by
* MetricMutableQuantiles{@link MetricMutableQuantiles}, MetricsRegionAggregateSourceImpl, and
* JmxCacheBuster
*/
@InterfaceAudience.Private
public class MetricsExecutorImpl implements MetricsExecutor {
@Override
public ScheduledExecutorService getExecutor() {
return ExecutorSingleton.INSTANCE.scheduler;
}
@Override
public void stop() {
if (!getExecutor().isShutdown()) {
getExecutor().shutdown();
}
}
private enum ExecutorSingleton {
INSTANCE;
private final ScheduledExecutorService scheduler = new ScheduledThreadPoolExecutor(1,
new ThreadPoolExecutorThreadFactory("HBase-Metrics2-"));
}
private final static class ThreadPoolExecutorThreadFactory implements ThreadFactory {
private final String name;
private final AtomicInteger threadNumber = new AtomicInteger(1);
private ThreadPoolExecutorThreadFactory(String name) {
this.name = name;
}
@Override
public Thread newThread(Runnable runnable) {
Thread t = new Thread(runnable, name + threadNumber.getAndIncrement());
t.setDaemon(true);
return t;
}
}
}
|
/*
* Copyright (c) 2019-2020 GeyserMC. http://geysermc.org
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* @author GeyserMC
* @link https://github.com/GeyserMC/Geyser
*/
package org.geysermc.connector.utils;
public enum MapColor {
COLOR_0(-1, -1, -1),
COLOR_1(-1, -1, -1),
COLOR_2(-1, -1, -1),
COLOR_3(-1, -1, -1),
COLOR_4(90, 126, 40),
COLOR_5(110, 154, 48),
COLOR_6(127, 178, 56),
COLOR_7(67, 94, 30),
COLOR_8(174, 164, 115),
COLOR_9(213, 201, 141),
COLOR_10(247, 233, 163),
COLOR_11(131, 123, 86),
COLOR_12(140, 140, 140),
COLOR_13(172, 172, 172),
COLOR_14(199, 199, 199),
COLOR_15(105, 105, 105),
COLOR_16(180, 0, 0),
COLOR_17(220, 0, 0),
COLOR_18(255, 0, 0),
COLOR_19(135, 0, 0),
COLOR_20(113, 113, 180),
COLOR_21(138, 138, 220),
COLOR_22(160, 160, 255),
COLOR_23(85, 85, 135),
COLOR_24(118, 118, 118),
COLOR_25(144, 144, 144),
COLOR_26(167, 167, 167),
COLOR_27(88, 88, 88),
COLOR_28(0, 88, 0),
COLOR_29(0, 107, 0),
COLOR_30(0, 124, 0),
COLOR_31(0, 66, 0),
COLOR_32(180, 180, 180),
COLOR_33(220, 220, 220),
COLOR_34(255, 255, 255),
COLOR_35(135, 135, 135),
COLOR_36(116, 119, 130),
COLOR_37(141, 145, 159),
COLOR_38(164, 168, 184),
COLOR_39(87, 89, 97),
COLOR_40(107, 77, 54),
COLOR_41(130, 94, 66),
COLOR_42(151, 109, 77),
COLOR_43(80, 58, 41),
COLOR_44(79, 79, 79),
COLOR_45(97, 97, 97),
COLOR_46(112, 112, 112),
COLOR_47(59, 59, 59),
COLOR_48(45, 45, 180),
COLOR_49(55, 55, 220),
COLOR_50(64, 64, 255),
COLOR_51(34, 34, 135),
COLOR_52(101, 84, 51),
COLOR_53(123, 103, 62),
COLOR_54(143, 119, 72),
COLOR_55(76, 63, 38),
COLOR_56(180, 178, 173),
COLOR_57(220, 217, 211),
COLOR_58(255, 252, 245),
COLOR_59(135, 133, 130),
COLOR_60(152, 90, 36),
COLOR_61(186, 110, 44),
COLOR_62(216, 127, 51),
COLOR_63(114, 67, 27),
COLOR_64(126, 54, 152),
COLOR_65(154, 66, 186),
COLOR_66(178, 76, 216),
COLOR_67(94, 40, 114),
COLOR_68(72, 108, 152),
COLOR_69(88, 132, 186),
COLOR_70(102, 153, 216),
COLOR_71(54, 81, 114),
COLOR_72(162, 162, 36),
COLOR_73(198, 198, 44),
COLOR_74(229, 229, 51),
COLOR_75(121, 121, 27),
COLOR_76(90, 144, 18),
COLOR_77(110, 176, 22),
COLOR_78(127, 204, 25),
COLOR_79(67, 108, 13),
COLOR_80(171, 90, 116),
COLOR_81(209, 110, 142),
COLOR_82(242, 127, 165),
COLOR_83(128, 67, 87),
COLOR_84(54, 54, 54),
COLOR_85(66, 66, 66),
COLOR_86(76, 76, 76),
COLOR_87(40, 40, 40),
COLOR_88(108, 108, 108),
COLOR_89(132, 132, 132),
COLOR_90(153, 153, 153),
COLOR_91(81, 81, 81),
COLOR_92(54, 90, 108),
COLOR_93(66, 110, 132),
COLOR_94(76, 127, 153),
COLOR_95(40, 67, 81),
COLOR_96(90, 44, 126),
COLOR_97(110, 54, 154),
COLOR_98(127, 63, 178),
COLOR_99(67, 33, 94),
COLOR_100(36, 54, 126),
COLOR_101(44, 66, 154),
COLOR_102(51, 76, 178),
COLOR_103(27, 40, 94),
COLOR_104(72, 54, 36),
COLOR_105(88, 66, 44),
COLOR_106(102, 76, 51),
COLOR_107(54, 40, 27),
COLOR_108(72, 90, 36),
COLOR_109(88, 110, 44),
COLOR_110(102, 127, 51),
COLOR_111(54, 67, 27),
COLOR_112(108, 36, 36),
COLOR_113(132, 44, 44),
COLOR_114(153, 51, 51),
COLOR_115(81, 27, 27),
COLOR_116(18, 18, 18),
COLOR_117(22, 22, 22),
COLOR_118(25, 25, 25),
COLOR_119(13, 13, 13),
COLOR_120(176, 168, 54),
COLOR_121(216, 205, 66),
COLOR_122(250, 238, 77),
COLOR_123(132, 126, 41),
COLOR_124(65, 155, 150),
COLOR_125(79, 189, 184),
COLOR_126(92, 219, 213),
COLOR_127(49, 116, 113),
COLOR_128(52, 90, 180),
COLOR_129(64, 110, 220),
COLOR_130(74, 128, 255),
COLOR_131(39, 68, 135),
COLOR_132(0, 153, 41),
COLOR_133(0, 187, 50),
COLOR_134(0, 217, 58),
COLOR_135(0, 115, 31),
COLOR_136(91, 61, 35),
COLOR_137(111, 74, 42),
COLOR_138(129, 86, 49),
COLOR_139(68, 46, 26),
COLOR_140(79, 1, 0),
COLOR_141(97, 2, 0),
COLOR_142(112, 2, 0),
COLOR_143(59, 1, 0),
COLOR_144(148, 125, 114),
COLOR_145(180, 153, 139),
COLOR_146(209, 177, 161),
COLOR_147(111, 94, 85),
COLOR_148(112, 58, 25),
COLOR_149(137, 71, 31),
COLOR_150(159, 82, 36),
COLOR_151(84, 43, 19),
COLOR_152(105, 61, 76),
COLOR_153(129, 75, 93),
COLOR_154(149, 87, 108),
COLOR_155(79, 46, 57),
COLOR_156(79, 76, 97),
COLOR_157(97, 93, 119),
COLOR_158(112, 108, 138),
COLOR_159(59, 57, 73),
COLOR_160(131, 94, 25),
COLOR_161(160, 115, 31),
COLOR_162(186, 133, 36),
COLOR_163(98, 70, 19),
COLOR_164(73, 83, 37),
COLOR_165(89, 101, 46),
COLOR_166(103, 117, 53),
COLOR_167(55, 62, 28),
COLOR_168(113, 54, 55),
COLOR_169(138, 66, 67),
COLOR_170(160, 77, 78),
COLOR_171(85, 41, 41),
COLOR_172(40, 29, 25),
COLOR_173(49, 35, 30),
COLOR_174(57, 41, 35),
COLOR_175(30, 22, 19),
COLOR_176(95, 76, 69),
COLOR_177(116, 92, 85),
COLOR_178(135, 107, 98),
COLOR_179(71, 57, 52),
COLOR_180(61, 65, 65),
COLOR_181(75, 79, 79),
COLOR_182(87, 92, 92),
COLOR_183(46, 49, 49),
COLOR_184(86, 52, 62),
COLOR_185(105, 63, 76),
COLOR_186(122, 73, 88),
COLOR_187(65, 39, 47),
COLOR_188(54, 44, 65),
COLOR_189(66, 53, 79),
COLOR_190(76, 62, 92),
COLOR_191(40, 33, 49),
COLOR_192(54, 35, 25),
COLOR_193(66, 43, 30),
COLOR_194(76, 50, 35),
COLOR_195(40, 26, 19),
COLOR_196(54, 58, 30),
COLOR_197(66, 71, 36),
COLOR_198(76, 82, 42),
COLOR_199(40, 43, 22),
COLOR_200(100, 42, 32),
COLOR_201(123, 52, 40),
COLOR_202(142, 60, 46),
COLOR_203(75, 32, 24),
COLOR_204(26, 16, 11),
COLOR_205(32, 19, 14),
COLOR_206(37, 22, 16),
COLOR_207(20, 12, 8),
COLOR_208(133, 34, 35),
COLOR_209(163, 41, 42),
COLOR_210(189, 48, 49),
COLOR_211(100, 25, 26),
COLOR_212(104, 44, 68),
COLOR_213(128, 54, 84),
COLOR_214(148, 63, 97),
COLOR_215(78, 33, 51),
COLOR_216(65, 18, 20),
COLOR_217(79, 22, 25),
COLOR_218(92, 25, 29),
COLOR_219(49, 13, 15),
COLOR_220(16, 89, 95),
COLOR_221(19, 109, 116),
COLOR_222(22, 126, 134),
COLOR_223(12, 67, 71),
COLOR_224(41, 100, 99),
COLOR_225(50, 123, 121),
COLOR_226(58, 142, 140),
COLOR_227(31, 75, 74),
COLOR_228(61, 31, 44),
COLOR_229(74, 38, 53),
COLOR_230(86, 44, 62),
COLOR_231(46, 23, 33),
COLOR_232(14, 127, 94),
COLOR_233(17, 155, 115),
COLOR_234(20, 180, 133),
COLOR_235(11, 95, 70);
private static final MapColor[] VALUES = values();
private final int red;
private final int green;
private final int blue;
MapColor(int red, int green, int blue) {
this.red = red;
this.green = green;
this.blue = blue;
}
public static MapColor fromId(int id) {
return id >= 0 && id < VALUES.length ? VALUES[id] : COLOR_0;
}
public int toABGR() {
int alpha = 255;
if (red == -1 && green == -1 && blue == -1)
alpha = 0; // transparent
return ((alpha & 0xFF) << 24) |
((blue & 0xFF) << 16) |
((green & 0xFF) << 8) |
((red & 0xFF) << 0);
}
}
|
package com.keqi.apihu.sys.domain.db;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* 用户-项目关联表
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class AccountProjectDO {
/**
* 用户ID
*/
private Long accountId;
/**
* 项目ID
*/
private Long projectId;
}
|
package org.jesperancinha.jtd.jee.teeth.serialization;
import javax.ejb.Local;
@Local
public interface PeriodontitisPassivation {
void setPropertyObject(PeriodontitisObject periodontitisObject);
PeriodontitisObject getPropertyObject();
}
|
//
// ========================================================================
// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others.
// ------------------------------------------------------------------------
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
//
package org.eclipse.jetty.util;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
public class Atomics
{
private Atomics()
{
}
public static boolean updateMin(AtomicLong currentMin, long newValue)
{
long oldValue = currentMin.get();
while (newValue < oldValue)
{
if (currentMin.compareAndSet(oldValue, newValue))
return true;
oldValue = currentMin.get();
}
return false;
}
public static boolean updateMax(AtomicLong currentMax, long newValue)
{
long oldValue = currentMax.get();
while (newValue > oldValue)
{
if (currentMax.compareAndSet(oldValue, newValue))
return true;
oldValue = currentMax.get();
}
return false;
}
public static boolean updateMin(AtomicInteger currentMin, int newValue)
{
int oldValue = currentMin.get();
while (newValue < oldValue)
{
if (currentMin.compareAndSet(oldValue, newValue))
return true;
oldValue = currentMin.get();
}
return false;
}
public static boolean updateMax(AtomicInteger currentMax, int newValue)
{
int oldValue = currentMax.get();
while (newValue > oldValue)
{
if (currentMax.compareAndSet(oldValue, newValue))
return true;
oldValue = currentMax.get();
}
return false;
}
}
|
/*
* This file is part of the OpenKinect Project. http://www.openkinect.org
*
* Copyright (c) 2010 individual OpenKinect contributors. See the CONTRIB file
* for details.
*
* This code is licensed to you under the terms of the Apache License, version
* 2.0, or, at your option, the terms of the GNU General Public License,
* version 2.0. See the APACHE20 and GPL2 files for the text of the licenses,
* or the following URLs:
* http://www.apache.org/licenses/LICENSE-2.0
* http://www.gnu.org/licenses/gpl-2.0.txt
*
* If you redistribute this file in source form, modified or unmodified, you
* may:
* 1) Leave this header intact and distribute it under the same terms,
* accompanying it with the APACHE20 and GPL20 files, or
* 2) Delete the Apache 2.0 clause and accompany it with the GPL2 file, or
* 3) Delete the GPL v2 clause and accompany it with the APACHE20 file
* In all cases you must keep the copyright notice intact and include a copy
* of the CONTRIB file.
*
* Binary distributions must follow the binary distribution requirements of
* either License.
*/
package com.libfreenect;
/**
* Implementation of the RGBCamera class to wrap the Kinect RGB camera.
*
* @author Scott Byrns
* @version 0.2a
*/
public class KinectRGBCamera extends Camera {
public KinectRGBCamera (KinectDevice device) {
super(device);
}
/**
* Open a connection to the Kinect's depth camera.
*/
public void open() {
getHostDevice().issueCommand(KinectCommands.TURN_RGB_CAMERA_ON);
}
/**
* Close the connection to the Kinect's depth camera.
*/
public void close() {
getHostDevice().issueCommand(KinectCommands.TURN_RGB_CAMERA_OFF);
}
}
|
package manage.format;
import manage.TestUtils;
import manage.model.MetaData;
import org.junit.Test;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static java.util.Collections.singletonMap;
import static java.util.Optional.empty;
import static java.util.Optional.of;
import static org.junit.Assert.assertEquals;
@SuppressWarnings("unchecked")
public class EngineBlockFormatterTest implements TestUtils {
private EngineBlockFormatter subject = new EngineBlockFormatter();
@Test
@SuppressWarnings("unchecked")
public void testParse() throws Exception {
MetaData metaData = objectMapper.readValue(readFile("json/meta_data_detail.json"), MetaData.class);
Map<String, Object> result = subject.parseServiceProvider(metaData);
Map<String, Object> expected = objectMapper.readValue(readFile("push/push_results.json"), Map.class);
assertEquals(new HashMap<>(expected).toString(), new HashMap<>(result).toString());
}
@Test
public void addToResult() throws Exception {
MetaData metaData = objectMapper.readValue(readFile("json/meta_data_detail.json"), MetaData.class);
Map<String, Object> source = metaData.getData();
Map<String, Object> result = new TreeMap<>();
subject.addToResult(source, result, "entityid", of("name"));
subject.addToResult(source, result, "metadata:certData", empty());
subject.addToResult(source, result, "metadata:OrganizationDisplayName:nl", empty());
subject.addToResult(source, result, "metadata:OrganizationDisplayName:en", empty());
subject.addToResult(source, result, "metadata:coin:bogus", empty());
subject.addToResult(source, result, "metadata:coin:bogus", empty());
subject.addToResult(source, result, "metadata:coin:no_consent_required", empty());
subject.addToResult(source, result, "metadata:logo:0:height", empty());
assertAttribute("name", "https://teams.surfconext.nl/shibboleth", result);
assertAttribute("metadata:certData",
"MIIDEzCCAfugAwIBAgIJAKoK" +
"/heBjcOYMA0GCSqGSIb3DQEBBQUAMCAxHjAcBgNVBAoMFU9yZ2FuaXphdGlvbiwgQ049T0lEQzAeFw0xNTExMTExMDEyMTVaFw0yNTExMTAxMDEyMTVaMCAxHjAcBgNVBAoMFU9yZ2FuaXphdGlvbiwgQ049T0lEQzCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBANBGwJ/qpTQNiSgUglSE2UzEkUow+wS8r67etxoEhlzJZfgK/k5TfG1wICDqapHAxEVgUM10aBHRctNocA5wmlHtxdidhzRZroqHwpKy2BmsKX5Z2oK25RLpsyusB1KroemgA/CjUnI6rIL1xxFn3KyOFh1ZBLUQtKNQeMS7HFGgSDAp+sXuTFujz12LFDugX0T0KB5a1+0l8y0PEa0yGa1oi6seONx849ZHxM0PRvUunWkuTM+foZ0jZpFapXe02yWMqhc/2iYMieE/3GvOguJchJt6R+cut8VBb6ubKUIGK7pmoq/TB6DVXpvsHqsDJXechxcicu4pdKVDHSec850CAwEAAaNQME4wHQYDVR0OBBYEFK7RqjoodSYVXGTVEdLf3kJflP/sMB8GA1UdIwQYMBaAFK7RqjoodSYVXGTVEdLf3kJflP/sMAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQEFBQADggEBADNZkxlFXh4F45muCbnQd+WmaXlGvb9tkUyAIxVL8AIu8J18F420vpnGpoUAE+Hy3evBmp2nkrFAgmr055fAjpHeZFgDZBAPCwYd3TNMDeSyMta3Ka+oS7GRFDePkMEm+kH4/rITNKUF1sOvWBTSowk9TudEDyFqgGntcdu/l/zRxvx33y3LMG5USD0x4X4IKjRrRN1BbcKgi8dq10C3jdqNancTuPoqT3WWzRvVtB/q34B7F74/6JzgEoOCEHufBMp4ZFu54P0yEGtWfTwTzuoZobrChVVBt4w/XZagrRtUCDNwRpHNbpjxYudbqLqpi1MQpV9oht/BpTHVJG2i0ro=", result);
assertAttribute("metadata:OrganizationDisplayName:nl", "SURFnet", result);
assertAttribute("metadata:OrganizationDisplayName:en", "SURFnet", result);
assertAttribute("metadata:OrganizationDisplayName:bogus", null, result);
assertAttribute("metadata:OrganizationDisplayName:bogus", null, result);
assertAttribute("metadata:coin:no_consent_required", "1", result);
assertAttribute("metadata:logo:0:height", "300", result);
}
@Test
public void emptySource() {
MetaData metaDataContainer = new MetaData("oidc10_rp", singletonMap("metaDataFields", new HashMap<String, Object>()));
Map<String, Object> rp = subject.parseOidcClient(metaDataContainer);
assertEquals(Stream.of("allow_all_entities", "metadata", "allowed_connections", "arp_attributes", "type").collect(Collectors.toSet()), rp.keySet());
}
private void assertAttribute(String path, String value, Map<String, Object> result) {
String[] split = path.split(":");
if (split.length == 1) {
assertEquals(value, result.get(split[0]));
} else {
Iterator<String> iterator = Arrays.asList(split).iterator();
while (iterator.hasNext()) {
Object o = result.get(iterator.next());
if (!iterator.hasNext()) {
assertEquals(value, o);
} else {
result = (Map<String, Object>) o;
}
}
}
}
}
|
/*
* 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.tomcat.dbcp.pool2.impl;
import java.io.PrintWriter;
/**
* CallStack strategy using no-op implementations of all functionality. Can be used by default when abandoned object
* logging is disabled.
*
* @since 2.5
*/
public class NoOpCallStack implements CallStack {
/**
* Singleton instance.
*/
public static final CallStack INSTANCE = new NoOpCallStack();
/**
* Constructs the singleton instance.
*/
private NoOpCallStack() {
}
@Override
public boolean printStackTrace(final PrintWriter writer) {
return false;
}
@Override
public void fillInStackTrace() {
// no-op
}
@Override
public void clear() {
// no-op
}
}
|
/*
* Copyright 2002-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.samples.petclinic.api.application;
import static java.util.stream.Collectors.joining;
import java.util.List;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.samples.petclinic.api.dto.Visits;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.client.WebClient;
import lombok.RequiredArgsConstructor;
import reactor.core.publisher.Mono;
/**
* @author Maciej Szarlinski
*/
@Component
@RequiredArgsConstructor
public class VisitsServiceClient {
@Value("${visits-service-id://visits-service}")
private String hostname;
private final WebClient.Builder webClientBuilder;
public Mono<Visits> getVisitsForPets(final List<Integer> petIds) {
return webClientBuilder.build()
.get()
.uri(hostname + "/pets/visits?petId={petId}", joinIds(petIds))
.retrieve()
.bodyToMono(Visits.class);
}
private String joinIds(List<Integer> petIds) {
return petIds.stream().map(Object::toString).collect(joining(","));
}
void setHostname(String hostname) {
this.hostname = hostname;
}
}
|
package com.github.piedpiper.node.rest;
import org.apache.commons.lang3.reflect.MethodUtils;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.github.commons.utils.JsonUtils;
import com.github.piedpiper.common.PiedPiperConstants;
import com.github.piedpiper.node.NodeInput;
import com.github.piedpiper.node.NodeOutput;
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.request.GetRequest;
public class RESTGetHandler extends BaseRestHandler {
@Override
public NodeOutput apply(NodeInput input) {
try {
String outputType = getOutputType(input);
GetRequest getRequest = Unirest.get(getUrl(input));
JsonNode jsonHeader = getHeaders(input);
getRequest = (GetRequest) populateHeaders(getRequest, jsonHeader);
HttpResponse<?> response = (HttpResponse<?>) MethodUtils.invokeExactMethod(getRequest, "asString");
ObjectNode node = (ObjectNode) JsonUtils.mapper.valueToTree(response);
if (outputType.equals(PiedPiperConstants.AS_JSON))
parseAndUpdateBodyAsJson(node);
NodeOutput output = new NodeOutput();
output.setOutput(node);
return output;
} catch (IllegalArgumentException e) {
throw e;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
|
package com.leyou.user.api;
import com.leyou.user.pojo.User;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
public interface UserApi {
@GetMapping("/query")
User queryUserByUsernameAndPassword(
@RequestParam("username") String username, @RequestParam("password") String password
);
}
|
/**
* Copyright 2019 ForgeRock AS.
*
* 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.forgerock.openbanking.aspsp.rs.store.api.openbanking.payment.v3_1_7.domesticscheduledpayments;
import com.forgerock.openbanking.analytics.services.ConsentMetricService;
import com.forgerock.openbanking.aspsp.rs.store.repository.payments.DomesticScheduledConsentRepository;
import com.forgerock.openbanking.common.conf.discovery.DiscoveryConfigurationProperties;
import com.forgerock.openbanking.common.conf.discovery.ResourceLinkService;
import com.forgerock.openbanking.repositories.TppRepository;
import org.springframework.stereotype.Controller;
import uk.org.openbanking.datamodel.discovery.OBDiscoveryAPILinksPayment4;
@Controller("DomesticScheduledPaymentConsentsApiV3.1.7")
public class DomesticScheduledPaymentConsentsApiController extends com.forgerock.openbanking.aspsp.rs.store.api.openbanking.payment.v3_1_6.domesticscheduledpayments.DomesticScheduledPaymentConsentsApiController implements DomesticScheduledPaymentConsentsApi {
public DomesticScheduledPaymentConsentsApiController(ConsentMetricService consentMetricService,
DomesticScheduledConsentRepository domesticScheduledConsentRepository,
TppRepository tppRepository,
ResourceLinkService resourceLinkService) {
super(consentMetricService, domesticScheduledConsentRepository, tppRepository, resourceLinkService);
}
@Override
protected OBDiscoveryAPILinksPayment4 getVersion(DiscoveryConfigurationProperties.PaymentApis discovery) {
return discovery.getV_3_1_7();
}
}
|
package com.atguigu.gmall.oms.dao;
import com.atguigu.gmall.oms.entity.OrderOperateHistoryEntity;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
/**
* 订单操作历史记录
*
* @author canjian
* @email
* @date 2021-12-25 20:05:15
*/
@Mapper
public interface OrderOperateHistoryDao extends BaseMapper<OrderOperateHistoryEntity> {
}
|
package me.hugeblank.allium.lua.event;
import me.hugeblank.allium.lua.type.UserdataFactory;
import net.minecraft.block.BlockState;
import net.minecraft.entity.damage.DamageSource;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.util.Hand;
import net.minecraft.util.hit.BlockHitResult;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import org.squiddev.cobalt.Constants;
import org.squiddev.cobalt.LuaString;
import org.squiddev.cobalt.ValueFactory;
public class Events {
// TODO: Make the Event class smarter
public static final Event CHAT_MESSAGE;
public static final Event PLAYER_TICK;
public static final Event PLAYER_JOIN;
public static final Event PLAYER_QUIT;
public static final Event PLAYER_BLOCK_COLLISION;
public static final Event PLAYER_DEATH;
public static final Event BLOCK_INTERACT;
public static final Event SERVER_TICK;
static {
CHAT_MESSAGE = new Event("chat_message", (objects) -> {
// Expects: [ServerPlayerEntity player, String message]
try {
return ValueFactory.varargsOf(
UserdataFactory.of(ServerPlayerEntity.class).create(objects[0]),
LuaString.valueOf((String)objects[1])
);
} catch(ClassCastException e) {
return Constants.NIL;
}
});
PLAYER_TICK = new Event("player_tick", (objects) -> {
// Expects: [ServerPlayerEntity player]
try {
return ValueFactory.varargsOf(
UserdataFactory.of(ServerPlayerEntity.class).create(objects[0])
);
} catch(ClassCastException e) {
return Constants.NIL;
}
});
PLAYER_JOIN = new Event("player_join", (objects) -> {
// Expects: [ServerPlayerEntity player]
try {
return ValueFactory.varargsOf(
UserdataFactory.of(ServerPlayerEntity.class).create(objects[0])
);
} catch(ClassCastException e) {
return Constants.NIL;
}
});
PLAYER_QUIT = new Event("player_quit", (objects) -> {
// Expects: [ServerPlayerEntity player]
try {
return ValueFactory.varargsOf(
UserdataFactory.of(ServerPlayerEntity.class).create(objects[0])
);
} catch(ClassCastException e) {
return Constants.NIL;
}
});
PLAYER_BLOCK_COLLISION = new Event("player_block_collision", (objects) -> {
try {
return ValueFactory.varargsOf(
UserdataFactory.of(ServerPlayerEntity.class).create(objects[0]),
UserdataFactory.of(BlockState.class).create(objects[1])
);
} catch(ClassCastException e) {
return Constants.NIL;
}
});
PLAYER_DEATH = new Event("player_death", (objects) -> {
try {
return ValueFactory.varargsOf(
UserdataFactory.of(ServerPlayerEntity.class).create(objects[0]),
UserdataFactory.of(DamageSource.class).create(objects[1])
);
} catch(ClassCastException e) {
return Constants.NIL;
}
});
BLOCK_INTERACT = new Event("block_interact", (objects) -> {
try {
return ValueFactory.varargsOf(
UserdataFactory.of(BlockState.class).create(objects[0]),
UserdataFactory.of(World.class).create(objects[1]),
UserdataFactory.of(BlockPos.class).create(objects[2]),
UserdataFactory.of(ServerPlayerEntity.class).create(objects[3]),
UserdataFactory.of(Hand.class).create(objects[4]),
UserdataFactory.of(BlockHitResult.class).create(objects[5])
);
} catch(ClassCastException e) {
return Constants.NIL;
}
});
SERVER_TICK = new Event("server_tick", (objects) -> {
try {
return ValueFactory.varargsOf(
);
} catch(ClassCastException e) {
return Constants.NIL;
}
});
}
public static void init() {}
}
|
/*
Copyright 2014 Google Inc. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package fr.steren.cloudcup.games;
import android.content.Context;
import android.os.Bundle;
import android.os.Vibrator;
import android.view.View;
import android.widget.Button;
import fr.steren.cloudcup.GameActivity;
import fr.steren.cloudcup.R;
/**
* Created by mirnabouchra on 11/21/14.
*/
public class SequenceGameActivity extends GameActivity {
private static final String LOG_TAG = SequenceGameActivity.class.getSimpleName();
private Button blueButton;
private Button redButton;
private Button greenButton;
private Button yellowButton;
private String sequence = "";
public Vibrator vibrator;
@Override
public void onCreate(Bundle savedInstanceState) {
state = GameState.GAME;
sequence = "";
vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
super.onCreate(savedInstanceState);
setContentView(R.layout.sequence_game);
blueButton = (Button) findViewById(R.id.blue_button);
redButton = (Button) findViewById(R.id.red_button);
greenButton = (Button) findViewById(R.id.green_button);
yellowButton = (Button) findViewById(R.id.yellow_button);
blueButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onButtonClick("b");
}
});
redButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onButtonClick("r");
}
});
greenButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onButtonClick("g");
}
});
yellowButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onButtonClick("y");
}
});
}
public void onButtonClick(String letter) {
sequence += letter;
vibrator.vibrate(100);
gameDataRef.setValue(sequence);
}
}
|
/*
* 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 dk.statsbiblioteket.summa.releasetest;
import dk.statsbiblioteket.summa.control.service.FilterService;
import dk.statsbiblioteket.util.qa.QAInfo;
import dk.statsbiblioteket.util.Profiler;
import dk.statsbiblioteket.summa.common.unittest.NoExitTestCase;
import dk.statsbiblioteket.summa.common.configuration.Configuration;
import dk.statsbiblioteket.summa.common.configuration.Resolver;
import dk.statsbiblioteket.summa.common.filter.FilterControl;
import dk.statsbiblioteket.summa.common.filter.object.FilterSequence;
import dk.statsbiblioteket.summa.common.index.IndexDescriptor;
import dk.statsbiblioteket.summa.ingest.source.RecordGenerator;
import dk.statsbiblioteket.summa.index.XMLTransformer;
import dk.statsbiblioteket.summa.index.IndexControllerImpl;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.logging.Log;
import junit.framework.Test;
import junit.framework.TestSuite;
import java.util.List;
import java.io.File;
/**
* Updates an index with pseudo-random Records, in order to test scalability in
* index building and searching. No Storage is used in this process.
*/
@SuppressWarnings({"DuplicateStringLiteralInspection"})
@QAInfo(level = QAInfo.Level.NORMAL,
state = QAInfo.State.IN_DEVELOPMENT,
author = "te")
public class ScaleTest extends NoExitTestCase {
private static Log log = LogFactory.getLog(ScaleTest.class);
@Override
public void setUp() throws Exception {
super.setUp();
// ReleaseTestCommon.setup();
/* if (SearchTest.INDEX_ROOT.exists()) {
Files.delete(SearchTest.INDEX_ROOT);
SearchTest.INDEX_ROOT.mkdirs();
}*/
}
@Override
public void tearDown() throws Exception {
super.tearDown();
// ReleaseTestCommon.tearDown();
}
public static Test suite() {
return new TestSuite(ScaleTest.class);
}
public void testBuild1() throws Exception {
testBuild(1);
}
public void testBuild20() throws Exception {
testBuild(20);
}
public void testBuild1000() throws Exception {
testBuild(1000);
}
public void testBuild10000() throws Exception {
testBuild(10000);
}
public void testBuild(int records) throws Exception {
Profiler profiler = new Profiler();
Configuration conf = getConfiguration();
conf.getSubConfigurations(FilterControl.CONF_CHAINS).get(0).
getSubConfigurations(FilterSequence.CONF_FILTERS).get(0).
set(RecordGenerator.CONF_RECORDS, records);
FilterService indexService = new FilterService(conf);
indexService.start();
IndexTest.waitForService(indexService, Integer.MAX_VALUE);
indexService.stop(); // Just to make sure
File indexLocation = ((IndexControllerImpl)indexService.
getFilterControl().getPumps().get(0).getFilters().get(4)).
getIndexLocation();
log.debug("Finished indexing " + records + " to " + indexLocation
+ " in " + profiler.getSpendTime());
}
private Configuration getConfiguration() throws Exception {
Configuration conf =
Configuration.load("integration/scale/scale_configuration.xml");
List<Configuration> filters =
conf.getSubConfigurations(FilterControl.CONF_CHAINS).get(0).
getSubConfigurations(FilterSequence.CONF_FILTERS);
// Generator
filters.get(0).set(RecordGenerator.CONF_CONTENT_TEMPLATE_LOCATION,
Resolver.getFile("integration/scale/fagref_template.xml").
getAbsolutePath());
// Fagref-XSLT
String xsltLocation =
Resolver.getURL("integration/scale/xslt/fagref_index.xsl").getFile();
filters.get(1).set(XMLTransformer.CONF_XSLT, xsltLocation);
// OldToNew
String legacyLocation =
Resolver.getURL("LegacyToSummaDocumentXML.xslt").getFile();
filters.get(2).set(XMLTransformer.CONF_XSLT, legacyLocation);
// Document creator
String descriptorLocation = Resolver.getURL(
"integration/scale/scale_index_descriptor.xml").getFile();
log.debug("Descriptor location: " + descriptorLocation);
filters.get(3).getSubConfiguration(IndexDescriptor.CONF_DESCRIPTOR).
set(IndexDescriptor.CONF_ABSOLUTE_LOCATION, descriptorLocation);
// Index - general
filters.get(4).set(IndexControllerImpl.CONF_INDEX_ROOT_LOCATION,
ReleaseTestCommon.PERSISTENT_FOLDER);
// Index - Lucene
filters.get(4).getSubConfigurations(
IndexControllerImpl.CONF_MANIPULATORS).get(0).
getSubConfiguration(IndexDescriptor.CONF_DESCRIPTOR).set(
IndexDescriptor.CONF_ABSOLUTE_LOCATION, descriptorLocation);
return conf;
}
}
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2016 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.keycloak.authorization.policy.provider;
import org.keycloak.authorization.AuthorizationProvider;
import org.keycloak.authorization.model.Policy;
import org.keycloak.authorization.model.ResourceServer;
import org.keycloak.provider.ProviderFactory;
/**
* @author <a href="mailto:psilva@redhat.com">Pedro Igor</a>
*/
public interface PolicyProviderFactory extends ProviderFactory<PolicyProvider> {
String getName();
String getGroup();
PolicyProvider create(AuthorizationProvider authorization);
PolicyProviderAdminService getAdminResource(ResourceServer resourceServer);
}
|
/**
* Leetcode - card_group
*/
package com.duol.leetcode.y20.before.card_group;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* 914. 卡牌分组
*
* 给定一副牌,每张牌上都写着一个整数。
*
* 此时,你需要选定一个数字 X,使我们可以将整副牌按下述规则分成 1 组或更多组:
*
* 每组都有 X 张牌。
* 组内所有的牌上都写着相同的整数。
* 仅当你可选的 X >= 2 时返回 true。
*
*
*
* 示例 1:
*
* 输入:[1,2,3,4,4,3,2,1]
* 输出:true
* 解释:可行的分组是 [1,1],[2,2],[3,3],[4,4]
* 示例 2:
*
* 输入:[1,1,1,2,2,2,3,3]
* 输出:false
* 解释:没有满足要求的分组。
* 示例 3:
*
* 输入:[1]
* 输出:false
* 解释:没有满足要求的分组。
* 示例 4:
*
* 输入:[1,1]
* 输出:true
* 解释:可行的分组是 [1,1]
* 示例 5:
*
* 输入:[1,1,2,2,2,2]
* 输出:true
* 解释:可行的分组是 [1,1],[2,2],[2,2]
*
* 提示:
*
* 1 <= deck.length <= 10000
* 0 <= deck[i] < 10000
*
*/
interface Solution {
// use this Object to print the log (call from slf4j facade)
static Logger log = LoggerFactory.getLogger(Solution.class);
boolean hasGroupsSizeX(int[] deck);
}
|
package ch2;
/**
* Created by wenqing on 2016/5/19.
*/
public class ConditionConsumer implements Runnable {
private ConditionResources resources;
public ConditionConsumer(ConditionResources resources) {
this.resources = resources;
}
public void run() {
for (int i = 0; i < 100 ; i++) {
String event = resources.get();
System.out.printf("消费者获取:%s\n", event);
}
}
}
|
package org.fugerit.java.core.db.daogen;
import org.fugerit.java.core.util.result.Result;
public interface DaoResult extends Result {
String getResultDescription();
void appendDescription( String v );
void setResultDescription( String v );
void setResult( DaoResult result);
void setResult( int resultCode, String resultDescription );
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.