text
stringlengths 7
1.01M
|
|---|
package wxzw.gamec.controller;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/helloworld")
public class helloworld extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println(req.getMethod());
req.setAttribute("user","wxj");
System.out.println(req.getAttribute("user"));
//resp.sendRedirect("");
req.getRequestDispatcher("/jsp/helloworld.jsp").forward(req,resp);
}
}
|
package net.wessendorf.ce.impl;
import net.wessendorf.ce.CloudEvent;
import java.io.Serializable;
import java.net.URI;
import java.util.Date;
import java.util.Map;
public class CloudEventImpl<T> implements CloudEvent<T>, Serializable {
private static final long serialVersionUID = 1;
private String eventType;
private String cloudEventsVersion;
private URI source;
private String eventID;
private String eventTypeVersion;
private Date eventTime;
private URI schemaURL;
private String contentType;
private Map extensions;
private T data;
public CloudEventImpl(final String eventType, final String cloudEventsVersion, final URI source, final String eventID, final String eventTypeVersion, final Date eventTime, final URI schemaURL, final String contentType, final Map extensions, final T data) {
this.eventType = eventType;
this.cloudEventsVersion = cloudEventsVersion;
this.source = source;
this.eventID = eventID;
this.eventTypeVersion = eventTypeVersion;
this.eventTime = eventTime;
this.schemaURL = schemaURL;
this.contentType = contentType;
this.extensions = extensions;
this.data = data;
}
CloudEventImpl() {
}
@Override
public String getEventType() {
return eventType;
}
@Override
public String getCloudEventsVersion() {
return cloudEventsVersion;
}
@Override
public URI getSource() {
return source;
}
@Override
public String getEventID() {
return eventID;
}
@Override
public String getEventTypeVersion() {
return eventTypeVersion;
}
@Override
public Date getEventTime() {
return eventTime;
}
@Override
public URI getSchemaURL() {
return schemaURL;
}
@Override
public String getContentType() {
return contentType;
}
@Override
public Map getExtensions() {
return extensions;
}
@Override
public T getData() {
return data;
}
}
|
package lavaplayer.source.youtube;
import java.io.IOException;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import lavaplayer.tools.DataFormatTools;
import lavaplayer.tools.ExceptionTools;
import lavaplayer.tools.io.HttpInterface;
import lavaplayer.track.AudioItem;
import lavaplayer.track.AudioReference;
import lavaplayer.track.AudioTrack;
import lavaplayer.track.BasicAudioPlaylist;
/**
* Handles processing YouTube searches.
*/
public class YoutubeSearchProvider {
private static final Logger log = LoggerFactory.getLogger(YoutubeSearchProvider.class);
private final YoutubeAudioSourceManager sourceManager;
/**
* @param sourceManager YouTube source manager used for created tracks.
*/
public YoutubeSearchProvider(YoutubeAudioSourceManager sourceManager) {
this.sourceManager = sourceManager;
}
/**
* @param query Search query.
* @return Playlist of the first page of results.
*/
public AudioItem loadSearchResult(String query) {
log.debug("Performing a search with query {}", query);
try (HttpInterface httpInterface = sourceManager.getHttpInterface()) {
URI url = new URIBuilder("https://www.youtube.com/results").addParameter("search_query", query).build();
try (CloseableHttpResponse response = httpInterface.execute(new HttpGet(url))) {
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != 200) {
throw new IOException("Invalid status code for search response: " + statusCode);
}
Document document = Jsoup.parse(response.getEntity().getContent(), StandardCharsets.UTF_8.name(), "");
return extractSearchResults(document, query);
}
} catch (Exception e) {
throw ExceptionTools.wrapUnfriendlyExceptions(e);
}
}
private AudioItem extractSearchResults(Document document, String query) {
List<AudioTrack> tracks = new ArrayList<>();
for (Element results : document.select("#page > #content #results")) {
for (Element result : results.select(".yt-lockup-video")) {
if (!result.hasAttr("data-ad-impressions") && result.select(".standalone-ypc-badge-renderer-label").isEmpty()) {
extractTrackFromResultEntry(tracks, result);
}
}
}
if (tracks.isEmpty()) {
return AudioReference.NO_TRACK;
} else {
return new BasicAudioPlaylist("Search results for: " + query, tracks, null, true);
}
}
private void extractTrackFromResultEntry(List<AudioTrack> tracks, Element element) {
Element durationElement = element.select("[class^=video-time]").first();
Element contentElement = element.select(".yt-lockup-content").first();
String videoId = element.attr("data-context-item-id");
if (durationElement == null || contentElement == null || videoId.isEmpty()) {
return;
}
long duration = DataFormatTools.durationTextToMillis(durationElement.text());
String title = contentElement.select(".yt-lockup-title > a").text();
String author = contentElement.select(".yt-lockup-byline > a").text();
tracks.add(sourceManager.buildTrackObject(videoId, title, author, false, duration));
}
}
|
package com.sonar.vishal.medico.common.structure;
import com.google.gson.annotations.SerializedName;
public class SearchData extends Data {
@SerializedName("Keyword")
private String keyword;
public String getKeyword() {
return keyword;
}
public void setKeyword(String keyword) {
this.keyword = keyword;
}
}
|
package org.whitesource.fs;
import org.junit.Before;
import org.whitesource.agent.*;
import org.whitesource.agent.api.model.AgentProjectInfo;
import org.whitesource.agent.api.model.Coordinates;
import org.whitesource.agent.dependency.resolver.npm.TestHelper;
import org.whitesource.agent.utils.Pair;
import org.whitesource.fs.configuration.ResolverConfiguration;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.*;
/**
* @author chen.luigi
*/
public class InitializeConfiguration {
/* --- Static members --- */
private static final String DIRECTORY_PATH = "\\src\\test\\resources\\via\\maven\\ksa\\ksa-core";
private static final String CONFIG_PATH = "\\src\\test\\resources\\via\\whitesource-fs-agent-ksa.config";
private static final String CONFIG = Paths.get(Constants.DOT).toAbsolutePath().normalize().toString() + TestHelper.getOsRelativePath(CONFIG_PATH);
private static final String DIRECTORY = Paths.get(Constants.DOT).toAbsolutePath().normalize().toString() + TestHelper.getOsRelativePath(DIRECTORY_PATH);
/* --- Private Members --- */
private FSAConfigProperties config;
private FSAConfiguration fsaConfiguration;
private ProjectsSender projectsSender;
private Map<AgentProjectInfo, LinkedList<ViaComponents>> projectToViaComponents;
private String[] args = new String[]{};
@Before
public void setUp() throws IOException {
config = new FSAConfigProperties();
config.load(new FileInputStream(CONFIG));
config.setProperty(Constants.DIRECTORY, DIRECTORY);
String directory = config.getProperty(Constants.DIRECTORY);
String[] directories = directory.split(Constants.COMMA);
List<String> scannerBaseDirs = new ArrayList<>(Arrays.asList(directories));
if (!scannerBaseDirs.isEmpty()) {
// configure properties
fsaConfiguration = new FSAConfiguration(config, args);
projectsSender = new ProjectsSender(fsaConfiguration.getSender(), fsaConfiguration.getOffline(), fsaConfiguration.getRequest(), new FileSystemAgentInfo());
// set default values in case of missing parameters
ResolverConfiguration resolverConfiguration = fsaConfiguration.getResolver();
String[] includes = config.getProperty(ConfigPropertyKeys.INCLUDES_PATTERN_PROPERTY_KEY) != null ?
config.getProperty(ConfigPropertyKeys.INCLUDES_PATTERN_PROPERTY_KEY).split(FSAConfiguration.INCLUDES_EXCLUDES_SEPARATOR_REGEX) : ExtensionUtils.INCLUDES;
String[] excludes = config.getProperty(ConfigPropertyKeys.EXCLUDES_PATTERN_PROPERTY_KEY) != null ?
config.getProperty(ConfigPropertyKeys.EXCLUDES_PATTERN_PROPERTY_KEY).split(FSAConfiguration.INCLUDES_EXCLUDES_SEPARATOR_REGEX) : ExtensionUtils.EXCLUDES;
boolean globCaseSensitive = config.getProperty(ConfigPropertyKeys.CASE_SENSITIVE_GLOB_PROPERTY_KEY) != null ?
Boolean.valueOf(config.getProperty(ConfigPropertyKeys.CASE_SENSITIVE_GLOB_PROPERTY_KEY)) : false;
boolean followSymlinks = config.getProperty(ConfigPropertyKeys.CASE_SENSITIVE_GLOB_PROPERTY_KEY) != null ?
Boolean.valueOf(config.getProperty(ConfigPropertyKeys.CASE_SENSITIVE_GLOB_PROPERTY_KEY)) : false;
Collection<String> excludedCopyrights = fsaConfiguration.getAgent().getExcludedCopyrights();
excludedCopyrights.remove(Constants.EMPTY_STRING);
// Resolving dependencies
// via should not run for componentScan
Set<String> setDirs = new HashSet<>();
setDirs.addAll(scannerBaseDirs);
Map<String, Set<String>> appPathsToDependencyDirs = new HashMap<>();
appPathsToDependencyDirs.put(FSAConfiguration.DEFAULT_KEY, setDirs);
ProjectConfiguration projectConfiguration = new ProjectConfiguration(fsaConfiguration.getAgent(), scannerBaseDirs, appPathsToDependencyDirs, false);
projectToViaComponents = new FileSystemScanner(resolverConfiguration, fsaConfiguration.getAgent(), false).createProjects(projectConfiguration);
}
}
/* --- Public methods --- */
public Pair<String, StatusCode> sendProjects(ProjectsSender projectsSender, ProjectsDetails projectsDetails) {
Collection<AgentProjectInfo> projects = projectsDetails.getProjects();
Iterator<AgentProjectInfo> iterator = projects.iterator();
while (iterator.hasNext()) {
AgentProjectInfo project = iterator.next();
if (project.getDependencies().isEmpty()) {
iterator.remove();
// if coordinates are null, then use token
String projectIdentifier;
Coordinates coordinates = project.getCoordinates();
if (coordinates == null) {
projectIdentifier = project.getProjectToken();
} else {
projectIdentifier = coordinates.getArtifactId();
}
}
}
if (projects.isEmpty()) {
return new Pair<>("Exiting, nothing to update", StatusCode.SUCCESS);
} else {
return projectsSender.sendRequest(projectsDetails);//todo
}
}
/* --- Getters / Setters --- */
public Properties getConfig() {
return config;
}
public void setConfig(FSAConfigProperties config) {
this.config = config;
}
public FSAConfiguration getFsaConfiguration() {
return fsaConfiguration;
}
public void setFsaConfiguration(FSAConfiguration fsaConfiguration) {
this.fsaConfiguration = fsaConfiguration;
}
public Map<AgentProjectInfo, LinkedList<ViaComponents>> getProjectToViaComponents() {
return projectToViaComponents;
}
public void setProjectToViaComponents(Map<AgentProjectInfo, LinkedList<ViaComponents>> projectToViaComponents) {
this.projectToViaComponents = projectToViaComponents;
}
public ProjectsSender getProjectsSender() {
return projectsSender;
}
public void setProjectsSender(ProjectsSender projectsSender) {
this.projectsSender = projectsSender;
}
public String[] getArgs() {
return args;
}
public void setArgs(String[] args) {
this.args = args;
}
}
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2006, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.system;
/**
* An extension of the ServiceMBean interface that provides for
* declarative JMX notification subscription handling.
* <p>
* The SubscriptionList attribute is used to specify the list
* of MBeans/notifications that the listener service instance
* will subscribe for.
* <p>
* The abstract class ListenerServiceMBeanSupport implements
* this interface.
*
* @see ServiceMBean
* @see ListenerServiceMBeanSupport
*
* @author <a href="mailto:dimitris@jboss.org">Dimitris Andreadis</a>
* @version $Revision: 57205 $
**/
public interface ListenerServiceMBean
extends ServiceMBean
{
// Constants -----------------------------------------------------
/** The XML subscription-list elements and attributes */
public static final String SL_ROOT_ELEMENT = "subscription-list";
public static final String SL_MBEAN_ELEMENT = "mbean";
public static final String SL_FILTER_ELEMENT = "filter";
public static final String SL_NOTIFICATION_ELEMENT = "notification";
public static final String SL_MBEAN_NAME_ATTRIBUTE = "name";
public static final String SL_MBEAN_HANDBACK_ATTRIBUTE = "handback";
public static final String SL_FILTER_FACTORY_ATTRIBUTE = "factory";
public static final String SL_NOTIFICATION_TYPE_ATTRIBUTE = "type";
// Public --------------------------------------------------------
/**
* Used to configure at start-up the JMX notification subscriptions.
*
* The configuration is done inline in the mbean descriptor. For example:
*
* <code>
* ...
* <attribute name="SubscriptionList">
* <subscription-list>
* <mbean name="jboss.system:*">
* <notification type="org.jboss.system.ServiceMBean.start"/>
* <notification type="org.jboss.system.ServiceMBean.stop"/>
* </mbean>
* </subscription-list>
* </attribute>
* ...
* </code>
*
* The filter mechanism has been extended to support specification
* of arbitrary filters, using filter factory plugins:
*
* <code>
* ...
* <attribute name="SubscriptionList">
* <subscription-list>
* <mbean name="jboss.system:*">
* <filter factory="NotificationFilterSupportFactory">
* <enable type="org.jboss.system.ServiceMBean.start"/>
* <enable type="org.jboss.system.ServiceMBean.stop"/>
* </filter>
* </mbean>
* <mbean name="jboss.monitor:service=MemoryMonitor">
* <filter factory="AttributeChangeNotificationFilterFactory">
* <enable attribute-name="State"/>
* </filter>
* </mbean>
* <mbean name="JMImplementation:type=MBeanServerDelegate">
* <filter factory="MBeanServerNotificationFilterFactory">
* <enable type="JMX.mbean"/>
* <enable object-name="jboss:type=Service,name=SystemProperties"/>
* </filter>
* </mbean>
* </subscription-list>
* </attribute>
* ...
* </code>
*
* 'factory' is the full class name of a class that implements the
* org.jboss.system.NotificationFilterFactory interface. If the
* class cannot be loaded, a second attempt is made to load the
* class from within the org.jboss.system.filterfactory package.
*
* Three NotificationFilterFactories corresponding to the three
* "standard" jmx notification filters, have been pre-packaged.
*
* Those are:
*
* @see org.jboss.system.filterfactory.AttributeChangeNotificationFilterFactory
* @see org.jboss.system.filterfactory.MBeanServerNotificationFilterFactory
* @see org.jboss.system.filterfactory.NotificationFilterSupportFactory
*
* See also jboss-subscription.dtd
**/
public void setSubscriptionList(org.w3c.dom.Element list);
}
|
package io.rong.app.ui.widget;
import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
/**
* Created by zhjchen on 8/12/15.
*/
public class RongHorizontalScrollView extends HorizontalScrollView {
public RongHorizontalScrollView(Context context) {
super(context);
initView();
}
public RongHorizontalScrollView(Context context, AttributeSet attrs) {
super(context, attrs);
initView();
}
public RongHorizontalScrollView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initView();
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public RongHorizontalScrollView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
initView();
}
private void initView() {
LinearLayout linearLayout = new LinearLayout(getContext());
ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
linearLayout.setOrientation(LinearLayout.HORIZONTAL);
linearLayout.setLayoutParams(layoutParams);
addView(linearLayout);
}
public void addLayoutChildView(View v) {
if (v == null) return;
View view = getChildAt(0);
if (view != null) {
if (view instanceof LinearLayout) {
LinearLayout layout = (LinearLayout) view;
layout.addView(v);
}
}
}
public void removeLayoutChildView(View v) {
if (v == null) return;
View view = getChildAt(0);
if (view != null) {
if (view instanceof LinearLayout) {
LinearLayout layout = (LinearLayout) view;
layout.removeView(v);
}
}
}
public View getLayoutChileView(String tag) {
if (tag == null) return null;
View layoutView = getChildAt(0);
if (layoutView != null) {
if (layoutView instanceof LinearLayout) {
LinearLayout layout = (LinearLayout) layoutView;
int childCount = layout.getChildCount();
for (int i = 0; i < childCount; i++) {
View view = layout.getChildAt(i);
if (view.getTag() != null && tag.equals(view.getTag())) {
return view;
}
}
}
}
return null;
}
}
|
package hr.fer.zemris.java.webserver;
/**
* Interface for classes which process client requests.
*/
public interface IWebWorker {
/**
* The actual processing done by the instances. The result of
* whatever must be written to the arguments output stream.
* @param context the context of the request which should be processed.
*/
public void processRequest(RequestContext context);
}
|
package com.qatix.base.concurrent.queue;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.LinkedBlockingDeque;
/**
* 双端队列,两边都可以插入,两端都可以取出
*/
public class LinkedBlockingDequeTest {
public static void main(String[] args) throws InterruptedException {
BlockingDeque<String> deque = new LinkedBlockingDeque<String>();
deque.addFirst("h-1");
deque.addFirst("h-2");
deque.addLast("t-1");
deque.addLast("t-2");
/**
* h-2
h-1
t-1
t-2
*/
// System.out.println(deque.takeFirst());
// System.out.println(deque.takeFirst());
// System.out.println(deque.takeFirst());
// System.out.println(deque.takeFirst());
//
/**
* 调用的是takeFirst()
* take() 就是takeFirst()
* h-2
h-1
t-1
t-2
*/
System.out.println(deque.take());
System.out.println(deque.take());
System.out.println(deque.take());
System.out.println(deque.take());
}
}
|
package com.kafkamgt.uiapi.helpers.db.rdbms;
import com.kafkamgt.uiapi.dao.*;
import com.kafkamgt.uiapi.repository.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import java.util.List;
import java.util.Optional;
@Configuration
public class DeleteDataJdbc {
private static Logger LOG = LoggerFactory.getLogger(DeleteDataJdbc.class);
@Autowired(required=false)
TopicRequestsRepo topicRequestsRepo;
@Autowired(required=false)
private TopicRepo topicRepo;
@Autowired(required=false)
SchemaRequestRepo schemaRequestRepo;
@Autowired(required = false)
EnvRepo envRepo;
@Autowired(required=false)
TeamRepo teamRepo;
@Autowired(required=false)
AclRequestsRepo aclRequestsRepo;
@Autowired(required=false)
AclRepo aclRepo;
@Autowired(required = false)
UserInfoRepo userInfoRepo;
public DeleteDataJdbc(){}
public DeleteDataJdbc(TopicRequestsRepo topicRequestsRepo, SchemaRequestRepo schemaRequestRepo,
EnvRepo envRepo, TeamRepo teamRepo, AclRequestsRepo aclRequestsRepo,
AclRepo aclRepo, UserInfoRepo userInfoRepo){
this.topicRequestsRepo = topicRequestsRepo;
this.schemaRequestRepo = schemaRequestRepo;
this.envRepo = envRepo;
this.teamRepo = teamRepo;
this.aclRepo = aclRepo;
this.aclRequestsRepo = aclRequestsRepo;
this.userInfoRepo = userInfoRepo;
}
public String deleteTopicRequest(String topicName, String env){
TopicRequest topicRequest = new TopicRequest();
TopicRequestPK topicRequestPK = new TopicRequestPK();
topicRequestPK.setTopicname(topicName);
topicRequestPK.setEnvironment(env);
topicRequest.setTopicRequestPK(topicRequestPK);
topicRequest.setTopicstatus("created");
topicRequestsRepo.delete(topicRequest);
return "success";
}
public String deleteSchemaRequest(String topicName, String schemaVersion, String env){
SchemaRequest schemaRequest = new SchemaRequest();
SchemaRequestPK messageSchemaPK = new SchemaRequestPK();
messageSchemaPK.setEnvironment(env);
messageSchemaPK.setSchemaversion(schemaVersion);
messageSchemaPK.setTopicname(topicName);
schemaRequest.setSchemaRequestPK(messageSchemaPK);
schemaRequestRepo.delete(schemaRequest);
return "success";
}
public String deleteAclRequest(String req_no){
AclRequests aclRequests = new AclRequests();
aclRequests.setReq_no(req_no);
aclRequestsRepo.delete(aclRequests);
return "success";
}
public String deleteClusterRequest(String clusterId){
Env env = new Env();
env.setName(clusterId);
envRepo.delete(env);
return "success";
}
public String deleteUserRequest(String userId){
UserInfo user = new UserInfo();
user.setUsername(userId);
userInfoRepo.delete(user);
return "success";
}
public String deleteTeamRequest(String teamId){
Team team = new Team();
TeamPK teamPK = new TeamPK();
teamPK.setTeamname(teamId);
team.setTeamPK(teamPK);
team.setTeamname(teamId);
teamRepo.delete(team);
return "success";
}
public String deletePrevAclRecs(List<Acl> aclsToBeDeleted){
for(Acl aclToBeDeleted :aclsToBeDeleted){
Optional<Acl> acl = aclRepo.findById(aclToBeDeleted.getReq_no());
if(acl.isPresent() && acl.get().getTopicname().equals(aclToBeDeleted.getTopicname())) {
aclRepo.delete(acl.get());
}
}
return "success";
}
}
|
package io.fabric8.openshift.api.model.machineconfig.v1;
import java.util.HashMap;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import io.fabric8.kubernetes.api.model.Container;
import io.fabric8.kubernetes.api.model.HasMetadata;
import io.fabric8.kubernetes.api.model.IntOrString;
import io.fabric8.kubernetes.api.model.LabelSelector;
import io.fabric8.kubernetes.api.model.LocalObjectReference;
import io.fabric8.kubernetes.api.model.ObjectReference;
import io.fabric8.kubernetes.api.model.PersistentVolumeClaim;
import io.fabric8.kubernetes.api.model.PodTemplateSpec;
import io.fabric8.kubernetes.api.model.ResourceRequirements;
import io.fabric8.kubernetes.model.annotation.Group;
import io.fabric8.kubernetes.model.annotation.Version;
import io.sundr.builder.annotations.Buildable;
import io.sundr.builder.annotations.BuildableReference;
import io.sundr.transform.annotations.TemplateTransformation;
import io.sundr.transform.annotations.TemplateTransformations;
import lombok.EqualsAndHashCode;
import lombok.Setter;
import lombok.ToString;
import lombok.experimental.Accessors;
@JsonDeserialize(using = com.fasterxml.jackson.databind.JsonDeserializer.None.class)
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
"apiVersion",
"kind",
"metadata",
"spec",
"status"
})
@ToString
@EqualsAndHashCode
@Setter
@Accessors(prefix = {
"_",
""
})
@Buildable(editableEnabled = false, validationEnabled = false, generateBuilderPackage = false, lazyCollectionInitEnabled = false, builderPackage = "io.fabric8.kubernetes.api.builder", refs = {
@BuildableReference(io.fabric8.kubernetes.api.model.ObjectMeta.class),
@BuildableReference(LabelSelector.class),
@BuildableReference(Container.class),
@BuildableReference(PodTemplateSpec.class),
@BuildableReference(ResourceRequirements.class),
@BuildableReference(IntOrString.class),
@BuildableReference(ObjectReference.class),
@BuildableReference(LocalObjectReference.class),
@BuildableReference(PersistentVolumeClaim.class)
})
@Version("v1")
@Group("machineconfiguration.openshift.io")
@TemplateTransformations({
@TemplateTransformation(value = "/manifest.vm", outputPath = "machineconfig.properties", gather = true)
})
public class KubeletConfig implements HasMetadata
{
/**
*
* (Required)
*
*/
@JsonProperty("apiVersion")
private String apiVersion = "machineconfiguration.openshift.io/v1";
/**
*
* (Required)
*
*/
@JsonProperty("kind")
private String kind = "KubeletConfig";
@JsonProperty("metadata")
private io.fabric8.kubernetes.api.model.ObjectMeta metadata;
@JsonProperty("spec")
private KubeletConfigSpec spec;
@JsonProperty("status")
private KubeletConfigStatus status;
@JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
/**
* No args constructor for use in serialization
*
*/
public KubeletConfig() {
}
/**
*
* @param metadata
* @param apiVersion
* @param kind
* @param spec
* @param status
*/
public KubeletConfig(String apiVersion, String kind, io.fabric8.kubernetes.api.model.ObjectMeta metadata, KubeletConfigSpec spec, KubeletConfigStatus status) {
super();
this.apiVersion = apiVersion;
this.kind = kind;
this.metadata = metadata;
this.spec = spec;
this.status = status;
}
/**
*
* (Required)
*
*/
@JsonProperty("apiVersion")
public String getApiVersion() {
return apiVersion;
}
/**
*
* (Required)
*
*/
@JsonProperty("apiVersion")
public void setApiVersion(String apiVersion) {
this.apiVersion = apiVersion;
}
/**
*
* (Required)
*
*/
@JsonProperty("kind")
public String getKind() {
return kind;
}
/**
*
* (Required)
*
*/
@JsonProperty("kind")
public void setKind(String kind) {
this.kind = kind;
}
@JsonProperty("metadata")
public io.fabric8.kubernetes.api.model.ObjectMeta getMetadata() {
return metadata;
}
@JsonProperty("metadata")
public void setMetadata(io.fabric8.kubernetes.api.model.ObjectMeta metadata) {
this.metadata = metadata;
}
@JsonProperty("spec")
public KubeletConfigSpec getSpec() {
return spec;
}
@JsonProperty("spec")
public void setSpec(KubeletConfigSpec spec) {
this.spec = spec;
}
@JsonProperty("status")
public KubeletConfigStatus getStatus() {
return status;
}
@JsonProperty("status")
public void setStatus(KubeletConfigStatus status) {
this.status = status;
}
@JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
@JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}
|
package testclasses.antidebug;
import it.oblive.annotations.AntidebugSelf;
import it.oblive.annotations.NativeObfuscation;
import java.time.Duration;
import java.time.Instant;
public class AntidebugSelfDebugging {
public AntidebugSelfDebugging() {
}
public static String pi(int digits) {
Instant start = Instant.now();
String retval = piInternal(digits);
Instant end = Instant.now();
Duration duration = Duration.between(start, end);
System.out.println(duration.getSeconds()+"."+duration.getNano());
return retval;
}
@NativeObfuscation
@AntidebugSelf
public static String piInternal(int digits) {
StringBuffer pi = new StringBuffer();
int[] arr = new int[digits + 1];
int carry = 0;
for (int i = 0; i <= digits; ++i)
arr[i] = 2000;
for (int i = digits; i > 0; i-= 14) {
int sum = 0;
for (int j = i; j > 0; --j) {
sum = sum * j + 10000 * arr[j];
arr[j] = sum % (j * 2 - 1);
sum /= j * 2 - 1;
}
pi.append(String.format("%04d", carry + sum / 10000));
carry = sum % 10000;
}
return pi.toString();
}
}
|
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.jetbrains.python.inspections.quickfix;
import com.intellij.codeInspection.LocalQuickFix;
import com.intellij.codeInspection.ProblemDescriptor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiReference;
import com.jetbrains.python.PyPsiBundle;
import com.jetbrains.python.psi.*;
import com.jetbrains.python.refactoring.PyPsiRefactoringUtil;
import org.jetbrains.annotations.NotNull;
import java.util.Map;
public class PyAddPropertyForFieldQuickFix implements LocalQuickFix {
private String myName = PyPsiBundle.message("QFIX.add.property");
public PyAddPropertyForFieldQuickFix(String name) {
myName = name;
}
@Override
@NotNull
public String getFamilyName() {
return myName;
}
@Override
public void applyFix(@NotNull final Project project, @NotNull final ProblemDescriptor descriptor) {
final PsiElement element = descriptor.getPsiElement();
if (element instanceof PyReferenceExpression) {
final PsiReference reference = element.getReference();
if (reference == null) return;
final PsiElement resolved = reference.resolve();
if (resolved instanceof PyTargetExpression) {
PyTargetExpression target = (PyTargetExpression)resolved;
final PyClass containingClass = target.getContainingClass();
if (containingClass != null) {
final String name = target.getName();
if (name == null) return;
String propertyName = StringUtil.trimStart(name, "_");
final Map<String,Property> properties = containingClass.getProperties();
final PyElementGenerator generator = PyElementGenerator.getInstance(project);
if (!properties.containsKey(propertyName)) {
final PyFunction property = generator.createProperty(LanguageLevel.forElement(containingClass), propertyName, name, AccessDirection.READ);
PyPsiRefactoringUtil.addElementToStatementList(property, containingClass.getStatementList(), false);
}
final PyExpression qualifier = ((PyReferenceExpression)element).getQualifier();
if (qualifier != null) {
String newElementText = qualifier.getText() + "." + propertyName;
final PyExpression newElement = generator.createExpressionFromText(LanguageLevel.forElement(containingClass), newElementText);
element.replace(newElement);
}
}
}
}
}
}
|
package org.firstinspires.ftc.teamcode;
import android.graphics.Color;
import com.qualcomm.hardware.bosch.BNO055IMU;
import com.qualcomm.robotcore.eventloop.opmode.Autonomous;
import com.qualcomm.robotcore.eventloop.opmode.Disabled;
import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode;
import com.qualcomm.robotcore.hardware.ColorSensor;
import com.qualcomm.robotcore.hardware.DcMotor;
import com.qualcomm.robotcore.util.ElapsedTime;
import org.firstinspires.ftc.robotcore.external.navigation.AngleUnit;
import org.firstinspires.ftc.robotcore.external.navigation.AxesOrder;
import org.firstinspires.ftc.robotcore.external.navigation.AxesReference;
import org.firstinspires.ftc.robotcore.external.navigation.DistanceUnit;
import org.firstinspires.ftc.robotcore.external.navigation.Orientation;
import java.nio.file.Watchable;
import java.util.Locale;
@Autonomous
@Disabled
public class BlueColorCAL extends LinearOpMode {
/* Declare OpMode members. */
HardwareSky robot = new HardwareSky(); // Use Skybot hardware
private ElapsedTime runtime = new ElapsedTime();
ColorSensor sensorColor;
ColorSensor sensorColorleft;
float[] hsvValues = {0F, 0F, 0F};// hsvValues is an array that will hold the hue, saturation, and value information.
final float[] values = hsvValues; // values is a reference to the hsvValues array.
final double SCALE_FACTOR = 255;
int counter;
float HueValue, aveHue;
// @Override
public void runOpMode() {
robot.init(hardwareMap);
sensorColor = hardwareMap.get(ColorSensor.class, "sensor_color_distance");
// sensorColor = hardwareMap.get(ColorSensor.class, "sensor_color_left");
telemetry.addData("Status", "Resetting Encoders"); //
telemetry.update();
//
// Wait for the game to start (driver presses PLAY)
waitForStart();
// Step through each leg of the path,
// Note: Reverse movement is obtained by setting a negative distance (not speed)
while (opModeIsActive()) {
// convert the RGB values to HSV values.
// multiply by the SCALE_FACTOR.
// then cast it back to int (SCALE_FACTOR is a double)
HueValue = 0;
aveHue = 0;
for (counter = 0; counter < 10; counter++) {
Color.RGBToHSV((int) (sensorColor.red() * SCALE_FACTOR),
(int) (sensorColor.green() * SCALE_FACTOR),
(int) (sensorColor.blue() * SCALE_FACTOR),
hsvValues);
HueValue = HueValue + hsvValues[0];
}
aveHue = (HueValue / 10);
// send the info back to driver station using telemetry function.
// telemetry.addData("Distance (cm)",
// String.format(Locale.US, "%.02f", sensorDistance.getDistance(DistanceUnit.CM)));
telemetry.addData("Alpha", sensorColor.alpha());
telemetry.addData("Red ", sensorColor.red());
telemetry.addData("Green", sensorColor.green());
telemetry.addData("Blue ", sensorColor.blue());
telemetry.addData("ave", aveHue);
// change the background color to match the color detected by the RGB sensor.
// pass a reference to the hue, saturation, and value array as an argument
// to the HSVToColor method.
// relativeLayout.post(new Runnable() {
// public void run() {
// relativeLayout.setBackgroundColor(Color.HSVToColor(0xff, values));
telemetry.update();
}
HueValue = 0;
aveHue = 0;
for (counter = 0; counter < 10; counter++) {
Color.RGBToHSV((int) (sensorColor.red() * SCALE_FACTOR),
(int) (sensorColor.green() * SCALE_FACTOR),
(int) (sensorColor.blue() * SCALE_FACTOR),
hsvValues);
HueValue = HueValue + hsvValues[0];
telemetry.addData("Hue",HueValue);
telemetry.update();
}
}
}
|
package com.example.ma806p.viewpagedemo;
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("com.example.ma806p.viewpagedemo", appContext.getPackageName());
}
}
|
/*
Copyright 2022 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package io.kubernetes.client.openapi.models;
/** Generated */
public interface V1IngressSpecFluent<
A extends io.kubernetes.client.openapi.models.V1IngressSpecFluent<A>>
extends io.kubernetes.client.fluent.Fluent<A> {
/**
* This method has been deprecated, please use method buildDefaultBackend instead.
*
* @return The buildable object.
*/
@java.lang.Deprecated
public io.kubernetes.client.openapi.models.V1IngressBackend getDefaultBackend();
public io.kubernetes.client.openapi.models.V1IngressBackend buildDefaultBackend();
public A withDefaultBackend(io.kubernetes.client.openapi.models.V1IngressBackend defaultBackend);
public java.lang.Boolean hasDefaultBackend();
public io.kubernetes.client.openapi.models.V1IngressSpecFluent.DefaultBackendNested<A>
withNewDefaultBackend();
public io.kubernetes.client.openapi.models.V1IngressSpecFluent.DefaultBackendNested<A>
withNewDefaultBackendLike(io.kubernetes.client.openapi.models.V1IngressBackend item);
public io.kubernetes.client.openapi.models.V1IngressSpecFluent.DefaultBackendNested<A>
editDefaultBackend();
public io.kubernetes.client.openapi.models.V1IngressSpecFluent.DefaultBackendNested<A>
editOrNewDefaultBackend();
public io.kubernetes.client.openapi.models.V1IngressSpecFluent.DefaultBackendNested<A>
editOrNewDefaultBackendLike(io.kubernetes.client.openapi.models.V1IngressBackend item);
public java.lang.String getIngressClassName();
public A withIngressClassName(java.lang.String ingressClassName);
public java.lang.Boolean hasIngressClassName();
/** Method is deprecated. use withIngressClassName instead. */
@java.lang.Deprecated
public A withNewIngressClassName(java.lang.String original);
public A addToRules(
java.lang.Integer index, io.kubernetes.client.openapi.models.V1IngressRule item);
public A setToRules(
java.lang.Integer index, io.kubernetes.client.openapi.models.V1IngressRule item);
public A addToRules(io.kubernetes.client.openapi.models.V1IngressRule... items);
public A addAllToRules(
java.util.Collection<io.kubernetes.client.openapi.models.V1IngressRule> items);
public A removeFromRules(io.kubernetes.client.openapi.models.V1IngressRule... items);
public A removeAllFromRules(
java.util.Collection<io.kubernetes.client.openapi.models.V1IngressRule> items);
public A removeMatchingFromRules(
java.util.function.Predicate<io.kubernetes.client.openapi.models.V1IngressRuleBuilder>
predicate);
/**
* This method has been deprecated, please use method buildRules instead.
*
* @return The buildable object.
*/
@java.lang.Deprecated
public java.util.List<io.kubernetes.client.openapi.models.V1IngressRule> getRules();
public java.util.List<io.kubernetes.client.openapi.models.V1IngressRule> buildRules();
public io.kubernetes.client.openapi.models.V1IngressRule buildRule(java.lang.Integer index);
public io.kubernetes.client.openapi.models.V1IngressRule buildFirstRule();
public io.kubernetes.client.openapi.models.V1IngressRule buildLastRule();
public io.kubernetes.client.openapi.models.V1IngressRule buildMatchingRule(
java.util.function.Predicate<io.kubernetes.client.openapi.models.V1IngressRuleBuilder>
predicate);
public java.lang.Boolean hasMatchingRule(
java.util.function.Predicate<io.kubernetes.client.openapi.models.V1IngressRuleBuilder>
predicate);
public A withRules(java.util.List<io.kubernetes.client.openapi.models.V1IngressRule> rules);
public A withRules(io.kubernetes.client.openapi.models.V1IngressRule... rules);
public java.lang.Boolean hasRules();
public io.kubernetes.client.openapi.models.V1IngressSpecFluent.RulesNested<A> addNewRule();
public io.kubernetes.client.openapi.models.V1IngressSpecFluent.RulesNested<A> addNewRuleLike(
io.kubernetes.client.openapi.models.V1IngressRule item);
public io.kubernetes.client.openapi.models.V1IngressSpecFluent.RulesNested<A> setNewRuleLike(
java.lang.Integer index, io.kubernetes.client.openapi.models.V1IngressRule item);
public io.kubernetes.client.openapi.models.V1IngressSpecFluent.RulesNested<A> editRule(
java.lang.Integer index);
public io.kubernetes.client.openapi.models.V1IngressSpecFluent.RulesNested<A> editFirstRule();
public io.kubernetes.client.openapi.models.V1IngressSpecFluent.RulesNested<A> editLastRule();
public io.kubernetes.client.openapi.models.V1IngressSpecFluent.RulesNested<A> editMatchingRule(
java.util.function.Predicate<io.kubernetes.client.openapi.models.V1IngressRuleBuilder>
predicate);
public A addToTls(java.lang.Integer index, io.kubernetes.client.openapi.models.V1IngressTLS item);
public A setToTls(java.lang.Integer index, io.kubernetes.client.openapi.models.V1IngressTLS item);
public A addToTls(io.kubernetes.client.openapi.models.V1IngressTLS... items);
public A addAllToTls(
java.util.Collection<io.kubernetes.client.openapi.models.V1IngressTLS> items);
public A removeFromTls(io.kubernetes.client.openapi.models.V1IngressTLS... items);
public A removeAllFromTls(
java.util.Collection<io.kubernetes.client.openapi.models.V1IngressTLS> items);
public A removeMatchingFromTls(
java.util.function.Predicate<io.kubernetes.client.openapi.models.V1IngressTLSBuilder>
predicate);
/**
* This method has been deprecated, please use method buildTls instead.
*
* @return The buildable object.
*/
@java.lang.Deprecated
public java.util.List<io.kubernetes.client.openapi.models.V1IngressTLS> getTls();
public java.util.List<io.kubernetes.client.openapi.models.V1IngressTLS> buildTls();
public io.kubernetes.client.openapi.models.V1IngressTLS buildTl(java.lang.Integer index);
public io.kubernetes.client.openapi.models.V1IngressTLS buildFirstTl();
public io.kubernetes.client.openapi.models.V1IngressTLS buildLastTl();
public io.kubernetes.client.openapi.models.V1IngressTLS buildMatchingTl(
java.util.function.Predicate<io.kubernetes.client.openapi.models.V1IngressTLSBuilder>
predicate);
public java.lang.Boolean hasMatchingTl(
java.util.function.Predicate<io.kubernetes.client.openapi.models.V1IngressTLSBuilder>
predicate);
public A withTls(java.util.List<io.kubernetes.client.openapi.models.V1IngressTLS> tls);
public A withTls(io.kubernetes.client.openapi.models.V1IngressTLS... tls);
public java.lang.Boolean hasTls();
public io.kubernetes.client.openapi.models.V1IngressSpecFluent.TlsNested<A> addNewTl();
public io.kubernetes.client.openapi.models.V1IngressSpecFluent.TlsNested<A> addNewTlLike(
io.kubernetes.client.openapi.models.V1IngressTLS item);
public io.kubernetes.client.openapi.models.V1IngressSpecFluent.TlsNested<A> setNewTlLike(
java.lang.Integer index, io.kubernetes.client.openapi.models.V1IngressTLS item);
public io.kubernetes.client.openapi.models.V1IngressSpecFluent.TlsNested<A> editTl(
java.lang.Integer index);
public io.kubernetes.client.openapi.models.V1IngressSpecFluent.TlsNested<A> editFirstTl();
public io.kubernetes.client.openapi.models.V1IngressSpecFluent.TlsNested<A> editLastTl();
public io.kubernetes.client.openapi.models.V1IngressSpecFluent.TlsNested<A> editMatchingTl(
java.util.function.Predicate<io.kubernetes.client.openapi.models.V1IngressTLSBuilder>
predicate);
public interface DefaultBackendNested<N>
extends io.kubernetes.client.fluent.Nested<N>,
io.kubernetes.client.openapi.models.V1IngressBackendFluent<
io.kubernetes.client.openapi.models.V1IngressSpecFluent.DefaultBackendNested<N>> {
public N and();
public N endDefaultBackend();
}
public interface RulesNested<N>
extends io.kubernetes.client.fluent.Nested<N>,
io.kubernetes.client.openapi.models.V1IngressRuleFluent<
io.kubernetes.client.openapi.models.V1IngressSpecFluent.RulesNested<N>> {
public N and();
public N endRule();
}
public interface TlsNested<N>
extends io.kubernetes.client.fluent.Nested<N>,
io.kubernetes.client.openapi.models.V1IngressTLSFluent<
io.kubernetes.client.openapi.models.V1IngressSpecFluent.TlsNested<N>> {
public N and();
public N endTl();
}
}
|
/*
* 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 edu.internet2.middleware.tierApiAuthzClientExt.org.apache.commons.collections.functors;
import java.io.Serializable;
import edu.internet2.middleware.tierApiAuthzClientExt.org.apache.commons.collections.Predicate;
import edu.internet2.middleware.tierApiAuthzClientExt.org.apache.commons.collections.Transformer;
/**
* Transformer implementation that calls a Predicate using the input object
* and then returns the input.
*
* @since Commons Collections 3.0
* @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $
*
* @author Stephen Colebourne
*/
public class PredicateTransformer implements Transformer, Serializable {
/** Serial version UID */
private static final long serialVersionUID = 5278818408044349346L;
/** The closure to wrap */
private final Predicate iPredicate;
/**
* Factory method that performs validation.
*
* @param predicate the predicate to call, not null
* @return the <code>predicate</code> transformer
* @throws IllegalArgumentException if the predicate is null
*/
public static Transformer getInstance(Predicate predicate) {
if (predicate == null) {
throw new IllegalArgumentException("Predicate must not be null");
}
return new PredicateTransformer(predicate);
}
/**
* Constructor that performs no validation.
* Use <code>getInstance</code> if you want that.
*
* @param predicate the predicate to call, not null
*/
public PredicateTransformer(Predicate predicate) {
super();
iPredicate = predicate;
}
/**
* Transforms the input to result by calling a predicate.
*
* @param input the input object to transform
* @return the transformed result
*/
public Object transform(Object input) {
return (iPredicate.evaluate(input) ? Boolean.TRUE : Boolean.FALSE);
}
/**
* Gets the predicate.
*
* @return the predicate
* @since Commons Collections 3.1
*/
public Predicate getPredicate() {
return iPredicate;
}
}
|
package com.weique.overhaul.v2.app.service.localtion;
import android.content.Context;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.weique.overhaul.v2.app.common.Constant;
/**
* 百度定位sdk 坐标获取工具类
*/
public class LocSdkClient {
private static LocSdkClient mInstance = null;
public LocationClient mLocationClient = null;
private LocSdkClient(Context context) {
mLocationClient = new LocationClient(context.getApplicationContext());
// 声明LocationClient类
// mLocationClient.registerLocationListener(myListener);
// 注册监听函数
LocationClientOption option = new LocationClientOption();
option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
// 可选,设置定位模式,默认高精度
// LocationMode.Hight_Accuracy:高精度;
// LocationMode. Battery_Saving:低功耗;
// LocationMode. Device_Sensors:仅使用设备;
option.setCoorType(Constant.CoorType_BD09LL);
// 可选,设置返回经纬度坐标类型,默认gcj02
// gcj02:国测局坐标;
// bd09ll:百度经纬度坐标;
// bd09:百度墨卡托坐标;
// 海外地区定位,无需设置坐标类型,统一返回wgs84类型坐标
option.setScanSpan(60 * 1000);
// 可选,设置发起定位请求的间隔,int类型,单位ms
// 如果设置为0,则代表单次定位,即仅定位一次,默认为0
// 如果设置非0,需设置1000ms以上才有效
//可选,设置是否需要地址信息,默认不需要
option.setIsNeedAddress(true);
//可选,设置是否需要地址描述
option.setIsNeedLocationDescribe(true);
option.setOpenGps(true);
// 可选,设置是否使用gps,默认false
// 使用高精度和仅用设备两种定位模式的,参数必须设置为true
option.setLocationNotify(true);
// 可选,设置是否当GPS有效时按照1S/1次频率输出GPS结果,默认false
option.setIgnoreKillProcess(false);
// 可选,定位SDK内部是一个service,并放到了独立进程。
// 设置是否在stop的时候杀死这个进程,默认(建议)不杀死,即setIgnoreKillProcess(true)
option.SetIgnoreCacheException(false);
// 可选,设置是否收集Crash信息,默认收集,即参数为false
option.setWifiCacheTimeOut(5 * 60 * 1000);
// 可选,7.2版本新增能力
// 如果设置了该接口,首次启动定位时,会先判断当前WiFi是否超出有效期,若超出有效期,会先重新扫描WiFi,然后定位
option.setEnableSimulateGps(false);
// 可选,设置是否需要过滤GPS仿真结果,默认需要,即参数为false
mLocationClient.setLocOption(option);
// mLocationClient为第二步初始化过的LocationClient对象
// 需将配置好的LocationClientOption对象,通过setLocOption方法传递给LocationClient对象使用
// 更多LocationClientOption的配置,请参照类参考中LocationClientOption类的详细说明
mLocationClient.start();
// mLocationClient为第二步初始化过的LocationClient对象
// 调用LocationClient的start()方法,便可发起定位请求e
}
public LocationClient getLocationStart() {
return mLocationClient;
}
public static LocSdkClient getInstance(Context context) {
if (mInstance == null) {
Class var0 = LocSdkClient.class;
synchronized (LocSdkClient.class) {
if (mInstance == null) {
mInstance = new LocSdkClient(context);
}
}
}
return mInstance;
}
}
|
/*
* Copyright (c) 2018 Baidu, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.baidu.brpc.naming;
import com.baidu.brpc.client.EndPoint;
import com.baidu.brpc.utils.CustomThreadFactory;
import io.netty.util.HashedWheelTimer;
import io.netty.util.Timeout;
import io.netty.util.Timer;
import io.netty.util.TimerTask;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Validate;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.TimeUnit;
public class DnsNamingService implements NamingService {
private BrpcURI namingUrl;
private String host;
private int port;
private String hostPort;
private List<EndPoint> lastEndPoints = new ArrayList<EndPoint>();
private Timer namingServiceTimer;
private int updateInterval;
public DnsNamingService(BrpcURI namingUrl) {
Validate.notNull(namingUrl);
Validate.notEmpty(namingUrl.getHosts());
this.namingUrl = namingUrl;
this.host = namingUrl.getHosts().get(0);
String portString = namingUrl.getPorts().get(0);
if (StringUtils.isNotBlank(portString)) {
this.port = Integer.valueOf(portString);
} else {
this.port = 80;
}
this.hostPort = this.host + ":" + this.port;
this.updateInterval = namingUrl.getIntParameter(
BrpcURI.INTERVAL, BrpcURI.DEFAULT_INTERVAL);
namingServiceTimer = new HashedWheelTimer(new CustomThreadFactory("namingService-timer-thread"));
}
@Override
public List<EndPoint> lookup(RegisterInfo registerInfo) {
InetAddress[] addresses;
try {
addresses = InetAddress.getAllByName(host);
} catch (UnknownHostException ex) {
throw new IllegalArgumentException("unknown http host");
}
List<EndPoint> endPoints = new ArrayList<EndPoint>();
for (InetAddress address : addresses) {
EndPoint endPoint = new EndPoint(address.getHostAddress(), port);
endPoints.add(endPoint);
}
this.lastEndPoints = endPoints;
return endPoints;
}
@Override
public void subscribe(RegisterInfo registerInfo, final NotifyListener listener) {
namingServiceTimer.newTimeout(
new TimerTask() {
@Override
public void run(Timeout timeout) throws Exception {
try {
List<EndPoint> currentEndPoints = lookup(null);
Collection<EndPoint> addList = CollectionUtils.subtract(
currentEndPoints, lastEndPoints);
Collection<EndPoint> deleteList = CollectionUtils.subtract(
lastEndPoints, currentEndPoints);
listener.notify(addList, deleteList);
} catch (Exception ex) {
// ignore exception
}
namingServiceTimer.newTimeout(this, updateInterval, TimeUnit.MILLISECONDS);
}
},
updateInterval, TimeUnit.MILLISECONDS);
}
@Override
public void unsubscribe(RegisterInfo registerInfo) {
namingServiceTimer.stop();
}
@Override
public void register(RegisterInfo url) {
}
@Override
public void unregister(RegisterInfo url) {
}
public String getHostPort() {
return hostPort;
}
}
|
/*******************************************************************************
* ___ _ ____ ____
* / _ \ _ _ ___ ___| |_| _ \| __ )
* | | | | | | |/ _ \/ __| __| | | | _ \
* | |_| | |_| | __/\__ \ |_| |_| | |_) |
* \__\_\\__,_|\___||___/\__|____/|____/
*
* Copyright (c) 2014-2019 Appsicle
* Copyright (c) 2019-2020 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 io.questdb.cutlass.http.processors;
import io.questdb.cairo.sql.Record;
import io.questdb.cairo.sql.RecordCursor;
import io.questdb.cairo.sql.RecordCursorFactory;
import io.questdb.cairo.sql.RecordMetadata;
import io.questdb.cutlass.http.HttpConnectionContext;
import io.questdb.std.Misc;
import io.questdb.std.Mutable;
import io.questdb.std.Rnd;
import io.questdb.std.str.StringSink;
import java.io.Closeable;
public class TextQueryProcessorState implements Mutable, Closeable {
final StringSink query = new StringSink();
private final HttpConnectionContext httpConnectionContext;
boolean countRows = false;
boolean noMeta = false;
RecordCursorFactory recordCursorFactory;
RecordMetadata metadata;
RecordCursor cursor;
long count;
long skip;
long stop;
Record record;
Rnd rnd;
int queryState = JsonQueryProcessorState.QUERY_PREFIX;
int columnIndex;
private boolean queryCacheable = false;
String fileName;
public TextQueryProcessorState(HttpConnectionContext httpConnectionContext) {
this.httpConnectionContext = httpConnectionContext;
}
@Override
public void clear() {
metadata = null;
cursor = Misc.free(cursor);
record = null;
if (null != recordCursorFactory) {
if (queryCacheable) {
QueryCache.getInstance().push(query, recordCursorFactory);
} else {
recordCursorFactory.close();
}
recordCursorFactory = null;
}
queryCacheable = false;
query.clear();
queryState = JsonQueryProcessorState.QUERY_PREFIX;
columnIndex = 0;
countRows = false;
}
@Override
public void close() {
cursor = Misc.free(cursor);
recordCursorFactory = Misc.free(recordCursorFactory);
}
public long getFd() {
return httpConnectionContext.getFd();
}
void setQueryCacheable(boolean queryCacheable) {
this.queryCacheable = queryCacheable;
}
}
|
package lee.code.code_63__Unique_Paths_II;
import java.util.*;
import lee.util.*;
/**
*
*
* 63.Unique Paths II
*
* difficulty: Medium
* @see https://leetcode.com/problems/unique-paths-ii/description/
* @see description_63.md
* @Similiar Topics
* -->Dynamic Programming https://leetcode.com//tag/dynamic-programming
* -->Array https://leetcode.com//tag/array
* @Similiar Problems
* -->Unique Paths https://leetcode.com//problems/unique-paths
* Run solution from Unit Test:
* @see lee.codetest.code_63__Unique_Paths_II.CodeTest
* Run solution from Main Judge Class:
* @see lee.code.code_63__Unique_Paths_II.C63_MainClass
*
*/
/**
testcase:[[0,0,0],[0,1,0],[0,0,0]]
*/
public class MainTest {
public static void main(String[] args) {
//new Solution().uniquePathsWithObstacles(int[][]obstacleGrid);
}
}
|
package com.apress.springrecipes.shop;
public class Battery extends Product {
private boolean rechargeable;
public Battery() {
super();
}
public Battery(String name, double price) {
super(name, price);
}
public boolean getRechargeable() {
return rechargeable;
}
public void setRechargeable(boolean rechargeable) {
this.rechargeable = rechargeable;
}
}
|
package com.jake.csamanagement.util;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import java.util.Date;
public class JWTUtil {
// 过期时间 24 小时
// private static final long EXPIRE_TIME = 60 * 24 * 60 * 1000;
private static final long EXPIRE_TIME = 120 * 60 * 1000;//token2小时后过期
private static final long REFRESH_EXPIRE_TIME=60 * 24 * 60 * 1000;//refreshtoken一天后过期
// 密钥
private static final String SECRET = "SHIRO+JWT";
private static final String SECRET2 = "SHIRO+JWT+REFRESH";
public static String createToken(String username) {
Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
Algorithm algorithm = Algorithm.HMAC256(SECRET);
// 附带username信息
return JWT.create()
.withClaim("username", username)
//到期时间
.withExpiresAt(date)
//创建一个新的JWT,并使用给定的算法进行标记
.sign(algorithm);
}
public static String createRefreshToken(String username) {
Date date = new Date(System.currentTimeMillis() + REFRESH_EXPIRE_TIME);
Algorithm algorithm = Algorithm.HMAC256(SECRET2);
// 附带username信息
return JWT.create()
.withClaim("username", username)
//到期时间
.withExpiresAt(date)
//创建一个新的JWT,并使用给定的算法进行标记
.sign(algorithm);
}
public static int verify(String token, String username) {
try {
Algorithm algorithm = Algorithm.HMAC256(SECRET);
//在token中附带了username信息
JWTVerifier verifier = JWT.require(algorithm)
.withClaim("username", username)
.build();
//验证 token
verifier.verify(token);
return 1;
} catch (TokenExpiredException e) {
return 2;
}catch (Exception e){
return 3;
}
}
public static int verifyRefresh(String token, String username) {
try {
Algorithm algorithm = Algorithm.HMAC256(SECRET2);
//在token中附带了username信息
JWTVerifier verifier = JWT.require(algorithm)
.withClaim("username", username)
.build();
//验证 token
verifier.verify(token);
return 1;
} catch (TokenExpiredException e) {
return 2;
}catch (Exception e){
return 3;
}
}
public static String getUsername(String token) {
try {
DecodedJWT jwt = JWT.decode(token);
return jwt.getClaim("username").asString();
} catch (JWTDecodeException e) {
return null;
}
}
}
|
package us.ihmc.avatar.sensors.microphone;
import java.io.InputStream;
import java.net.Authenticator;
import java.net.PasswordAuthentication;
import java.net.URL;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import us.ihmc.commons.thread.ThreadTools;
public abstract class DrillDetectionThread extends Thread
{
// The annoying audio.cgi disconnects us every ~33 seconds
private static final int reconnectPeriodSeconds = 30;
private static final double checkForDrillFrequencyHz = 5.0;
private static final int iterationsCount = (int) ((double) reconnectPeriodSeconds * checkForDrillFrequencyHz);
private static final long iterationSleep = (long) (1000.0 / checkForDrillFrequencyHz);
private DrillDetectionAlgorithm algorithm = null;
private boolean isRunning = false;
public DrillDetectionThread(DrillDetectionAlgorithm algorithm)
{
// set webcam authentification
Authenticator.setDefault(new Authenticator()
{
protected PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication("admin", "unknownpw".toCharArray());
}
});
this.isRunning = true;
this.algorithm = algorithm;
}
public boolean isRunning()
{
return isRunning;
}
public void shutdown()
{
isRunning = false;
}
private InputStream connectToStream()
{
try
{
// URL url = new URL("http://192.168.0.19:80/audio.cgi"); //Home
// URL url = new URL("http://139.169.44.114:80/audio.cgi"); //JSC
URL url = new URL("http://10.6.100.57:80/audio.cgi"); //Robotlab
return url.openStream();
}
catch (Exception e)
{
e.printStackTrace();
return null;
}
}
@Override
public void run()
{
System.out.println("Starting drill detection thread...");
while (isRunning)
{
InputStream inputStream = connectToStream();
if (inputStream == null)
{
ThreadTools.sleep(iterationSleep);
continue;
}
System.out.println("Connected to the webcam. Opening the stream...");
// AudioPlayer is gone
// AudioPlayer.player.start(inputStream);
// Untested replacement code using javax.sound library
Clip clip = null;
try
{
clip = AudioSystem.getClip();
clip.open(AudioSystem.getAudioInputStream(inputStream));
clip.start();
}
catch (Exception e)
{
System.err.println(e.getMessage());
}
for (int i = 0; i < iterationsCount; i++)
{
ThreadTools.sleep(iterationSleep);
DrillDetectionResult result = algorithm.isDrillOn(inputStream);
if (result != null)
{
onDrillDetectionResult(result);
}
if (!isRunning)
{
break;
}
}
System.out.println("Closing the stream...");
if (clip != null)
{
clip.stop();
clip.close();
}
try
{
inputStream.close();
}
catch (Exception ignored)
{
}
System.out.println("Waiting for reconnect...");
}
System.out.println("Stopping drill detection thread...");
}
public abstract void onDrillDetectionResult(DrillDetectionResult result);
}
|
/*
* 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.camel.processor;
import org.apache.camel.ContextTestSupport;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.junit.jupiter.api.Test;
/**
* Unit test with multi route specific error handlers
*/
public class MultiErrorHandlerInRouteTest extends ContextTestSupport {
private MyProcessor outer = new MyProcessor();
private MyProcessor inner = new MyProcessor();
@Test
public void testNoErrors() throws Exception {
outer.setName("Claus");
inner.setName("James");
MockEndpoint mock = getMockEndpoint("mock:end");
mock.expectedHeaderReceived("name", "James");
template.sendBody("direct:start", "Hello World");
assertMockEndpointsSatisfied();
}
@Test
public void testOuterError() throws Exception {
outer.setName("Error");
inner.setName("James");
MockEndpoint mock = getMockEndpoint("mock:outer");
mock.expectedMessageCount(1);
template.sendBody("direct:start", "Hello World");
assertMockEndpointsSatisfied();
}
@Test
public void testInnerError() throws Exception {
outer.setName("Claus");
inner.setName("Error");
MockEndpoint mock = getMockEndpoint("mock:inner");
mock.expectedHeaderReceived("name", "Claus");
mock.expectedMessageCount(1);
template.sendBody("direct:start", "Hello World");
assertMockEndpointsSatisfied();
}
@Override
protected RouteBuilder createRouteBuilder() throws Exception {
return new RouteBuilder() {
public void configure() throws Exception {
from("direct:start").errorHandler(deadLetterChannel("mock:outer").maximumRedeliveries(1).redeliveryDelay(0))
.process(outer).to("direct:outer");
from("direct:outer").errorHandler(deadLetterChannel("mock:inner").maximumRedeliveries(2).redeliveryDelay(0))
.process(inner).to("mock:end");
}
};
}
private static class MyProcessor implements Processor {
private String name;
@Override
public void process(Exchange exchange) throws Exception {
if (name.equals("Error")) {
throw new IllegalArgumentException("Forced exception by unit test");
}
exchange.getIn().setHeader("name", name);
}
public void setName(String name) {
this.name = name;
}
}
}
|
package com.lilithsthrone.game.inventory.enchanting;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import com.lilithsthrone.game.character.attributes.Attribute;
import com.lilithsthrone.game.character.fetishes.Fetish;
import com.lilithsthrone.game.character.race.Subspecies;
import com.lilithsthrone.game.inventory.Rarity;
import com.lilithsthrone.main.Main;
import com.lilithsthrone.utils.Colour;
import com.lilithsthrone.utils.SvgUtil;
import com.lilithsthrone.utils.Util;
/**
* @since 0.1.7
* @version 0.2.11
* @author Innoxia
*/
public enum TFModifier {
NONE("Empty",
"No modifier",
"nullification",
"modifier_circle",
Colour.TEXT_GREY,
Rarity.COMMON),
// Pos/Neg
ARCANE_BOOST("arcane booster",
"Applies a more powerful effect in relation to the primary essence.",
"boosted",
"modifier_circle_arcane",
Colour.GENERIC_ARCANE,
Rarity.COMMON),
REMOVAL("removal",
"Applies an effect such that the primary modifier's body part is removed.",
"vanishing",
"modifier_circle_removal",
Colour.GENERIC_TERRIBLE,
Rarity.UNCOMMON),
// Misc:
ORIENTATION_GYNEPHILIC("gynephilia",
"Applies an effect related to changing orientation to gynephilic.",
"gynephilia",
"modifier_circle_orientation_gynephilic",
Colour.FEMININE_PLUS,
Rarity.LEGENDARY),
ORIENTATION_AMBIPHILIC("ambiphilia",
"Applies an effect related to changing orientation to ambiphilic.",
"ambiphilia",
"modifier_circle_orientation_ambiphilic",
Colour.ANDROGYNOUS,
Rarity.LEGENDARY),
ORIENTATION_ANDROPHILIC("androphilia",
"Applies an effect related to changing orientation to androphilic.",
"androphilia",
"modifier_circle_orientation_androphilic",
Colour.MASCULINE_PLUS,
Rarity.LEGENDARY),
// Attributes:
HEALTH_MAXIMUM(AttributeCategory.STRENGTH,
Attribute.HEALTH_MAXIMUM,
"Applies an effect related to the primary attribute 'Maximum Energy'.",
"modifier_circle_strength",//"modifier_circle_health",
Rarity.EPIC),
MANA_MAXIMUM(AttributeCategory.INTELLIGENCE,
Attribute.MANA_MAXIMUM,
"Applies an effect related to the primary attribute 'Maximum Aura'.",
"modifier_circle_mana",
Rarity.EPIC),
STRENGTH(AttributeCategory.STRENGTH,
Attribute.MAJOR_PHYSIQUE,
"Applies an effect related to the primary attribute 'Physique'.",
"modifier_circle_strength",
Rarity.LEGENDARY),
INTELLIGENCE(AttributeCategory.INTELLIGENCE,
Attribute.MAJOR_ARCANE,
"Applies an effect related to the primary attribute 'Arcane'.",
"modifier_circle_intelligence",
Rarity.LEGENDARY),
CORRUPTION(AttributeCategory.CORRUPTION,
Attribute.MAJOR_CORRUPTION,
"Applies an effect related to the primary attribute 'Corruption'.",
"modifier_circle_corruption",
Rarity.LEGENDARY),
FERTILITY(AttributeCategory.CORRUPTION,
Attribute.FERTILITY,
"Applies an effect related to the secondary attribute 'Fertility'.",
"modifier_circle_fertility",
Rarity.RARE),
VIRILITY(AttributeCategory.CORRUPTION,
Attribute.VIRILITY,
"Applies an effect related to the secondary attribute 'Virility'.",
"modifier_circle_virility",
Rarity.RARE),
SPELL_COST_MODIFIER(AttributeCategory.INTELLIGENCE,
Attribute.SPELL_COST_MODIFIER,
"Applies an effect related to the secondary attribute 'Spell cost reduction'.",
"modifier_circle_spell_efficiency",
Rarity.RARE),
CRITICAL_DAMAGE(AttributeCategory.STRENGTH,
Attribute.CRITICAL_DAMAGE,
"Applies an effect related to the secondary attribute 'Critical power'.",
"modifier_circle_critical_damage",
Rarity.RARE),
DAMAGE_LUST(AttributeCategory.CORRUPTION,
Attribute.DAMAGE_LUST,
"Applies an effect related to the secondary attribute 'Seduction damage'.",
"modifier_circle_damage",
Rarity.RARE),
DAMAGE_SPELLS(AttributeCategory.INTELLIGENCE,
Attribute.DAMAGE_SPELLS,
"Applies an effect related to the secondary attribute 'Spell damage'.",
"modifier_circle_damage",
Rarity.RARE),
DAMAGE_UNARMED(AttributeCategory.STRENGTH,
Attribute.DAMAGE_UNARMED,
"Applies an effect related to the secondary attribute 'Unarmed damage'.",
"modifier_circle_damage_unarmed",
Rarity.RARE),
DAMAGE_MELEE_WEAPON(AttributeCategory.STRENGTH,
Attribute.DAMAGE_MELEE_WEAPON,
"Applies an effect related to the secondary attribute 'Melee weapon damage'.",
"modifier_circle_damage_melee",
Rarity.RARE),
DAMAGE_RANGED_WEAPON(AttributeCategory.STRENGTH,
Attribute.DAMAGE_RANGED_WEAPON,
"Applies an effect related to the secondary attribute 'Ranged weapon damage'.",
"modifier_circle_damage_ranged",
Rarity.RARE),
DAMAGE_PHYSICAL(AttributeCategory.STRENGTH,
Attribute.DAMAGE_PHYSICAL,
"Applies an effect related to the secondary attribute 'Physical damage'.",
"modifier_circle_damage",
Rarity.RARE),
DAMAGE_FIRE(AttributeCategory.INTELLIGENCE,
Attribute.DAMAGE_FIRE,
"Applies an effect related to the secondary attribute 'Fire damage'.",
"modifier_circle_damage",
Rarity.RARE),
DAMAGE_ICE(AttributeCategory.INTELLIGENCE,
Attribute.DAMAGE_ICE,
"Applies an effect related to the secondary attribute 'Ice damage'.",
"modifier_circle_damage",
Rarity.RARE),
DAMAGE_POISON(AttributeCategory.INTELLIGENCE,
Attribute.DAMAGE_POISON,
"Applies an effect related to the secondary attribute 'Poison damage'.",
"modifier_circle_damage",
Rarity.RARE),
/**
* Utility value for initialising a weapon to have attribute bonuses related to its damage type.
*/
DAMAGE_WEAPON(AttributeCategory.STRENGTH,
Attribute.DAMAGE_PHYSICAL,
"Applies a damage effect related to the weapon's damage type.",
"modifier_circle_damage",
Rarity.RARE),
RESISTANCE_LUST(AttributeCategory.CORRUPTION,
Attribute.RESISTANCE_LUST,
"Applies an effect related to the secondary attribute 'Seduction shielding'.",
"modifier_circle_resistance",
Rarity.RARE),
RESISTANCE_PHYSICAL(AttributeCategory.STRENGTH,
Attribute.RESISTANCE_PHYSICAL,
"Applies an effect related to the secondary attribute 'Physical shielding'.",
"modifier_circle_resistance",
Rarity.RARE),
RESISTANCE_FIRE(AttributeCategory.INTELLIGENCE,
Attribute.RESISTANCE_FIRE,
"Applies an effect related to the secondary attribute 'Fire shielding'.",
"modifier_circle_resistance",
Rarity.RARE),
RESISTANCE_ICE(AttributeCategory.INTELLIGENCE,
Attribute.RESISTANCE_ICE,
"Applies an effect related to the secondary attribute 'Ice shielding'.",
"modifier_circle_resistance",
Rarity.RARE),
RESISTANCE_POISON(AttributeCategory.INTELLIGENCE,
Attribute.RESISTANCE_POISON,
"Applies an effect related to the secondary attribute 'Poison shielding'.",
"modifier_circle_resistance",
Rarity.RARE),
/**
* Utility value for initialising a weapon to have attribute bonuses related to its damage type.
*/
RESISTANCE_WEAPON(AttributeCategory.STRENGTH,
Attribute.RESISTANCE_PHYSICAL,
"Applies a shielding effect related to the weapon's damage type.",
"modifier_circle_resistance",
Rarity.RARE),
// Clothing parts:
CLOTHING_MAJOR_ATTRIBUTE("core attribute",
"Applies a modifier to a core attribute.",
"attribute",
"modifier_circle_attribute_major",
Colour.GENERIC_ATTRIBUTE,
Rarity.LEGENDARY),
CLOTHING_ATTRIBUTE("attribute",
"Applies a modifier to an attribute.",
"attribute",
"modifier_circle_attribute",
Colour.GENERIC_ATTRIBUTE,
Rarity.UNCOMMON),
CLOTHING_ENSLAVEMENT("enslavement",
"Makes this piece of clothing enslave the wearer.",
"enslavement",
"modifier_circle_enslavement",
Colour.BASE_PURPLE_DARK,
Rarity.LEGENDARY),
CLOTHING_SEALING("sealing",
"Makes this piece of clothing seal itself onto the wearer.",
"sealing",
"modifier_circle_sealing",
Colour.SEALED,
Rarity.LEGENDARY),
CLOTHING_CONDOM("condom strength",
"Provides underlying strength to the condom.",
"condom strength",
"modifier_circle_resistance",
Colour.BASE_GREEN,
Rarity.COMMON),
// Racial parts:
TF_MATERIAL_FLESH("flesh",
"Turns a person's body material to flesh.",
"flesh",
"modifier_circle_tf_material_flesh",
Colour.BASE_CRIMSON,
Rarity.LEGENDARY),
TF_ANTENNA("antennae",
"Applies a transformative effect to your antennae.",
"antennae",
"modifier_circle_tf_antenna",
Colour.TRANSFORMATION_PARTIAL,
Rarity.UNCOMMON),
TF_ARMS("arms",
"Applies a transformative effect to your arms.",
"arms",
"modifier_circle_tf_arm",
Colour.TRANSFORMATION_LESSER,
Rarity.RARE),
TF_ASS("ass",
"Applies a transformative effect to your ass.",
"asses",
"modifier_circle_tf_ass",
Colour.TRANSFORMATION_SEXUAL,
Rarity.UNCOMMON),
TF_BREASTS("breasts",
"Applies a transformative effect to your breasts.",
"breasts",
"modifier_circle_tf_breast",
Colour.TRANSFORMATION_SEXUAL,
Rarity.UNCOMMON),
TF_BREASTS_CROTCH("crotch-boobs",
"Applies a transformative effect to your crotch-boobs/udders.",
"crotch-boobs",
"modifier_circle_tf_breast_crotch",
Colour.TRANSFORMATION_SEXUAL,
Rarity.UNCOMMON),
TF_CORE("core",
"Applies a transformative effect to your body.",
"core",
"modifier_circle_tf_core",
Colour.TRANSFORMATION_GREATER,
Rarity.RARE),
TF_EARS("ears",
"Applies a transformative effect to your ears.",
"ears",
"modifier_circle_tf_ear",
Colour.TRANSFORMATION_PARTIAL,
Rarity.UNCOMMON),
TF_EYES("eyes",
"Applies a transformative effect to your eyes.",
"eyes",
"modifier_circle_tf_eye",
Colour.TRANSFORMATION_PARTIAL,
Rarity.UNCOMMON),
TF_FACE("face",
"Applies a transformative effect to your face.",
"faces",
"modifier_circle_tf_face",
Colour.TRANSFORMATION_GREATER,
Rarity.EPIC),
TF_HAIR("hair",
"Applies a transformative effect to your hair.",
"hair",
"modifier_circle_tf_hair",
Colour.TRANSFORMATION_PARTIAL,
Rarity.UNCOMMON),
TF_HORNS("horns",
"Applies a transformative effect to your horns.",
"horns",
"modifier_circle_tf_horn",
Colour.TRANSFORMATION_PARTIAL,
Rarity.UNCOMMON),
TF_LEGS("legs",
"Applies a transformative effect to your legs.",
"legs",
"modifier_circle_tf_leg",
Colour.TRANSFORMATION_LESSER,
Rarity.RARE),
TF_PENIS("penis",
"Applies a transformative effect to your penis.",
"cocks",
"modifier_circle_tf_penis",
Colour.TRANSFORMATION_SEXUAL,
Rarity.UNCOMMON),
TF_SKIN("torso",
"Applies a transformative effect to your torso.",
"torso",
"modifier_circle_tf_skin",
Colour.TRANSFORMATION_GREATER,
Rarity.EPIC),
TF_TAIL("tail",
"Applies a transformative effect to your tail.",
"tails",
"modifier_circle_tf_tail",
Colour.TRANSFORMATION_PARTIAL,
Rarity.UNCOMMON),
TF_VAGINA("vagina",
"Applies a transformative effect to your vagina.",
"pussies",
"modifier_circle_tf_vagina",
Colour.TRANSFORMATION_SEXUAL,
Rarity.UNCOMMON),
TF_WINGS("wings",
"Applies a transformative effect to your wings.",
"wings",
"modifier_circle_tf_wing",
Colour.TRANSFORMATION_PARTIAL,
Rarity.UNCOMMON),
TF_MILK("milk",
"Applies a transformative effect to your milk.",
"milk",
"modifier_circle_tf_milk",
Colour.TRANSFORMATION_SEXUAL,
Rarity.UNCOMMON),
TF_MILK_CROTCH("udder-milk",
"Applies a transformative effect to your udder-milk.",
"udder-milk",
"modifier_circle_tf_milk_crotch",
Colour.TRANSFORMATION_SEXUAL,
Rarity.UNCOMMON),
TF_CUM("cum",
"Applies a transformative effect to your cum.",
"cum",
"modifier_circle_tf_cum",
Colour.TRANSFORMATION_SEXUAL,
Rarity.UNCOMMON),
TF_GIRLCUM("girlcum",
"Applies a transformative effect to your girlcum.",
"girlcum",
"modifier_circle_tf_girlcum",
Colour.TRANSFORMATION_SEXUAL,
Rarity.UNCOMMON),
// Body part modifiers:
TF_TYPE_1("transformative I",
"Transforms the related body part into that of a different race.",
"transformative",
"modifier_circle_tf_1",
Colour.TRANSFORMATION_GENERIC,
Rarity.COMMON),
TF_TYPE_2("transformative II",
"Transforms the related body part into that of a different race.",
"transformative",
"modifier_circle_tf_2",
Colour.TRANSFORMATION_GENERIC,
Rarity.COMMON),
TF_TYPE_3("transformative III",
"Transforms the related body part into that of a different race.",
"transformative",
"modifier_circle_tf_3",
Colour.TRANSFORMATION_GENERIC,
Rarity.COMMON),
TF_TYPE_4("transformative IV",
"Transforms the related body part into that of a different race.",
"transformative",
"modifier_circle_tf_4",
Colour.TRANSFORMATION_GENERIC,
Rarity.COMMON),
TF_TYPE_5("transformative V",
"Transforms the related body part into that of a different race.",
"transformative",
"modifier_circle_tf_5",
Colour.TRANSFORMATION_GENERIC,
Rarity.COMMON),
TF_MOD_FEMININITY("femininity",
"Applies an effect to change the user's femininity.",
"feminine",
"modifier_circle_femininity",
Colour.ANDROGYNOUS,
Rarity.COMMON),
TF_MOD_COUNT("count",
"Applies an effect related to adding or removing extra body parts.",
"counting",
"modifier_circle_count",
Colour.BASE_AQUA,
Rarity.COMMON),
TF_MOD_COUNT_SECONDARY("secondary count",
"Applies an effect related to adding or removing extra body parts.",
"counting",
"modifier_circle_count_secondary",
Colour.BASE_TEAL,
Rarity.COMMON),
TF_MOD_BODY_HAIR("hairiness",
"Applies an effect related to adding or removing body hair.",
"hairy",
"modifier_circle_bodyHair",
Colour.BASE_TAN,
Rarity.COMMON),
TF_MOD_FOOT_STRUCTURE_PLANTIGRADE("plantigrade feet",
"Applies an effect to give the user a plantigrade foot structure.",
"plantigrade feet",
"modifier_circle_tf_footStructure_plantigrade",
Colour.BASE_BLUE_LIGHT,
Rarity.LEGENDARY),
TF_MOD_FOOT_STRUCTURE_DIGITIGRADE("digitigrade feet",
"Applies an effect to give the user a digitigrade foot structure.",
"digitigrade feet",
"modifier_circle_tf_footStructure_digitigrade",
Colour.BASE_BROWN_DARK,
Rarity.LEGENDARY),
TF_MOD_FOOT_STRUCTURE_UNGULIGRADE("unguligrade feet",
"Applies an effect to give the user an unguligrade foot structure.",
"unguligrade feet",
"modifier_circle_tf_footStructure_unguligrade",
Colour.BASE_TAN,
Rarity.LEGENDARY),
TF_MOD_LEG_CONFIG_BIPEDAL("bidepal body",
"Applies an effect to give the user a bipedal body.",
"bipedal body",
"modifier_circle_tf_legConfig_bipedal",
Colour.BASE_BLUE_LIGHT,
Rarity.LEGENDARY),
TF_MOD_LEG_CONFIG_TAUR("taur body",
"Applies an effect to give the user a taur body.",
"taur body",
"modifier_circle_tf_legConfig_taur",
Colour.BASE_TAN,
Rarity.LEGENDARY),
TF_MOD_LEG_CONFIG_TAIL_LONG("long-tailed body",
"Applies an effect to give the user a long-tailed body.",
"long-tailed body",
"modifier_circle_tf_legConfig_tail_long",
Colour.BASE_GREEN,
Rarity.LEGENDARY),
TF_MOD_LEG_CONFIG_TAIL("tailed body",
"Applies an effect to give the user a tailed body.",
"tailed body",
"modifier_circle_tf_legConfig_tail",
Colour.BASE_AQUA,
Rarity.LEGENDARY),
TF_MOD_LEG_CONFIG_ARACHNID("arachnid body",
"Applies an effect to give the user an arachnid body.",
"arachnid body",
"modifier_circle_tf_legConfig_arachnid",
Colour.BASE_BLACK,
Rarity.LEGENDARY),
TF_MOD_LEG_CONFIG_CEPHALOPOD("cephalopod body",
"Applies an effect to give the user a cephalopod body.",
"cephalopod body",
"modifier_circle_tf_legConfig_cephalopod",
Colour.BASE_RED,
Rarity.LEGENDARY),
TF_MOD_INTERNAL("internal",
"Applies an effect related to making a body part internal.",
"internal",
"modifier_circle_internal",
Colour.BASE_BLUE_STEEL,
Rarity.COMMON),
TF_MOD_SIZE("size",
"Applies an effect related to the change in size of a certain body part.",
"resizing",
"modifier_circle_size",
Colour.BASE_LILAC,
Rarity.COMMON),
TF_MOD_SIZE_SECONDARY("secondary size",
"Applies an effect related to the change in size of a different body part.",
"resizing",
"modifier_circle_size_secondary",
Colour.BASE_LILAC_LIGHT,
Rarity.COMMON),
TF_MOD_SIZE_TERTIARY("tertiary size",
"Applies an effect related to the change in size of yet another body part.",
"resizing",
"modifier_circle_size_tertiary",
Colour.BASE_ROSE,
Rarity.COMMON),
TF_MOD_REGENERATION("regeneration",
"Applies an effect related to the regeneration rate of fluids.",
"refilling",
"modifier_circle_regeneration",
Colour.BASE_GREEN_LIGHT,
Rarity.COMMON),
// Orifices:
TF_MOD_CAPACITY("capacity",
"Applies an effect related to changing an orifice's capacity.",
"capacity",
"modifier_circle_capacity",
Colour.BASE_PINK_LIGHT,
Rarity.COMMON),
TF_MOD_CAPACITY_2("capacity II",
"Applies an effect related to changing an orifice's capacity.",
"capacity",
"modifier_circle_capacity",
Colour.BASE_PINK,
Rarity.COMMON),
TF_MOD_WETNESS("wetness",
"Applies an effect related to changing the wetness of an orifice, or the fluid production of a body part.",
"wet",
"modifier_circle_wetness",
Colour.BASE_BLUE_LIGHT,
Rarity.COMMON),
TF_MOD_ELASTICITY("elasticity",
"Applies an effect related to changing the elasticity of an orifice.",
"elastic",
"modifier_circle_elasticity",
Colour.BASE_AQUA,
Rarity.COMMON),
TF_MOD_ELASTICITY_2("elasticity II",
"Applies an effect related to changing the elasticity of an orifice.",
"elastic",
"modifier_circle_elasticity",
Colour.BASE_BLUE_LIGHT,
Rarity.COMMON),
TF_MOD_PLASTICITY("plasticity",
"Applies an effect related to changing the plasticity of an orifice.",
"plastic",
"modifier_circle_plasticity",
Colour.BASE_TEAL,
Rarity.COMMON),
TF_MOD_PLASTICITY_2("plasticity II",
"Applies an effect related to changing the plasticity of an orifice.",
"plastic",
"modifier_circle_plasticity",
Colour.BASE_BLUE,
Rarity.COMMON),
// modifiers:
TF_MOD_ORIFICE_PUFFY("puffiness",
"Applies an effect related to making an orifice puffy.",
"puffy",
"modifier_circle_orifice_puffy",
Colour.BASE_BLUE_LIGHT,
Rarity.COMMON),
TF_MOD_ORIFICE_RIBBED("ribbing",
"Applies an effect related to making an orifice internally-ribbed.",
"ribbed",
"modifier_circle_orifice_ribbed",
Colour.BASE_PINK_LIGHT,
Rarity.COMMON),
TF_MOD_ORIFICE_TENTACLED("tentacled",
"Applies an effect related to making an orifice internally-tentacled.",
"tentacled",
"modifier_circle_orifice_tentacled",
Colour.BASE_CRIMSON,
Rarity.COMMON),
TF_MOD_ORIFICE_MUSCLED("muscled",
"Applies an effect related to making an orifice internally-muscled.",
"muscled",
"modifier_circle_orifice_muscled",
Colour.BASE_MAGENTA,
Rarity.COMMON),
TF_MOD_ORIFICE_PUFFY_2("puffiness II",
"Applies an effect related to making an orifice puffy.",
"puffy",
"modifier_circle_orifice_puffy",
Colour.BASE_BLUE,
Rarity.COMMON),
TF_MOD_ORIFICE_RIBBED_2("ribbing II",
"Applies an effect related to making an orifice internally-ribbed.",
"ribbed",
"modifier_circle_orifice_ribbed",
Colour.BASE_PINK,
Rarity.COMMON),
TF_MOD_ORIFICE_TENTACLED_2("tentacled II",
"Applies an effect related to making an orifice internally-tentacled.",
"tentacled",
"modifier_circle_orifice_tentacled",
Colour.BASE_RED,
Rarity.COMMON),
TF_MOD_ORIFICE_MUSCLED_2("muscled II",
"Applies an effect related to making an orifice internally-muscled.",
"muscled",
"modifier_circle_orifice_muscled",
Colour.BASE_PURPLE,
Rarity.COMMON),
// eye shapes:
TF_MOD_EYE_IRIS_CIRCLE("circular irises",
"Applies an effect related to making irises shaped like normal circles.",
"circular irises",
"modifier_circle_eye_iris_normal",
Colour.BASE_PURPLE,
Rarity.COMMON),
TF_MOD_EYE_IRIS_HORIZONTAL("horizontal irises",
"Applies an effect related to making irises take a more horizontal shape.",
"horizontal irises",
"modifier_circle_eye_iris_horizontal",
Colour.BASE_LILAC_LIGHT,
Rarity.COMMON),
TF_MOD_EYE_IRIS_VERTICAL("vertical irises",
"Applies an effect related to making irises take a more vertical shape.",
"vertical irises",
"modifier_circle_eye_iris_vertical",
Colour.BASE_PURPLE_LIGHT,
Rarity.COMMON),
TF_MOD_EYE_IRIS_HEART("heart-shaped irises",
"Applies an effect related to making irises shaped like hearts.",
"heart-shaped irises",
"modifier_circle_eye_iris_heart",
Colour.BASE_PINK,
Rarity.COMMON),
TF_MOD_EYE_IRIS_STAR("star-shaped irises",
"Applies an effect related to making irises shaped like stars.",
"star-shaped irises",
"modifier_circle_eye_iris_star",
Colour.BASE_YELLOW,
Rarity.COMMON),
TF_MOD_EYE_PUPIL_CIRCLE("circular pupils",
"Applies an effect related to making pupils shaped like normal circles.",
"circular pupils",
"modifier_circle_eye_iris_normal",
Colour.BASE_BLACK,
Rarity.COMMON),
TF_MOD_EYE_PUPIL_HORIZONTAL("horizontal pupils",
"Applies an effect related to making pupils take a more horizontal shape.",
"horizontal pupils",
"modifier_circle_eye_iris_horizontal",
Colour.BASE_AQUA,
Rarity.COMMON),
TF_MOD_EYE_PUPIL_VERTICAL("vertical pupils",
"Applies an effect related to making pupils take a more vertical shape.",
"vertical pupils",
"modifier_circle_eye_iris_vertical",
Colour.BASE_TEAL,
Rarity.COMMON),
TF_MOD_EYE_PUPIL_HEART("heart-shaped pupils",
"Applies an effect related to making pupils shaped like hearts.",
"heart-shaped pupils",
"modifier_circle_eye_iris_heart",
Colour.BASE_BLUE_LIGHT,
Rarity.COMMON),
TF_MOD_EYE_PUPIL_STAR("star-shaped pupils",
"Applies an effect related to making pupils shaped like stars.",
"star-shaped pupils",
"modifier_circle_eye_iris_star",
Colour.BASE_BLUE,
Rarity.COMMON),
// breast shapes:
TF_MOD_BREAST_SHAPE_UDDERS("udders",
"Applies an effect related to turning crotch-boobs into udders.",
"udders",
"modifier_circle_breastShape_udders",
Colour.BASE_TAN,
Rarity.COMMON),
TF_MOD_BREAST_SHAPE_ROUND("round breasts",
"Applies an effect related to making breasts take on a round shape.",
"round",
"modifier_circle_breastShape_round",
Colour.BASE_TAN,
Rarity.COMMON),
TF_MOD_BREAST_SHAPE_NARROW("narrow breasts",
"Applies an effect related to making breasts take on a narrow shape.",
"narrow",
"modifier_circle_breastShape_narrow",
Colour.BASE_TAN,
Rarity.COMMON),
TF_MOD_BREAST_SHAPE_WIDE("wide breasts",
"Applies an effect related to making breasts take on a wide shape.",
"wide",
"modifier_circle_breastShape_wide",
Colour.BASE_TAN,
Rarity.COMMON),
TF_MOD_BREAST_SHAPE_POINTY("pointy breasts",
"Applies an effect related to making breasts take on a pointy shape.",
"pointy",
"modifier_circle_breastShape_pointy",
Colour.BASE_TAN,
Rarity.COMMON),
TF_MOD_BREAST_SHAPE_PERKY("perky breasts",
"Applies an effect related to making breasts take on a perky shape.",
"perky",
"modifier_circle_breastShape_perky",
Colour.BASE_TAN,
Rarity.COMMON),
TF_MOD_BREAST_SHAPE_SIDESET("side-set breasts",
"Applies an effect related to making breasts take on a side-set shape.",
"side-set",
"modifier_circle_breastShape_sideset",
Colour.BASE_TAN,
Rarity.COMMON),
// nipple shapes:
TF_MOD_NIPPLE_NORMAL("normal nipples",
"Applies an effect related to making nipples look normal.",
"normal nipples",
"modifier_circle_nipple_normal",
Colour.BASE_PURPLE_LIGHT,
Rarity.COMMON),
TF_MOD_NIPPLE_VAGINA("nipple cunts",
"Applies an effect related to making nipples look like pussies.",
"nipple cunts",
"modifier_circle_nipple_vagina",
Colour.BASE_PINK_LIGHT,
Rarity.COMMON),
TF_MOD_NIPPLE_LIPS("lipples",
"Applies an effect related to making nipples look like a pair of lips.",
"lipples",
"modifier_circle_nipple_lips",
Colour.BASE_MAGENTA,
Rarity.COMMON),
// areolae shapes:
TF_MOD_AREOLAE_CIRCLE("circular areolae",
"Applies an effect related to making areolae shaped like normal circles.",
"circular areolae",
"modifier_circle_areolae_normal",
Colour.BASE_PURPLE,
Rarity.COMMON),
TF_MOD_AREOLAE_HEART("heart-shaped areolae",
"Applies an effect related to making areolae shaped like hearts.",
"heart-shaped areolae",
"modifier_circle_areolae_heart",
Colour.BASE_PINK,
Rarity.COMMON),
TF_MOD_AREOLAE_STAR("star-shaped areolae",
"Applies an effect related to making areolae shaped like stars.",
"star-shaped areolae",
"modifier_circle_areolae_star",
Colour.BASE_YELLOW,
Rarity.COMMON),
// tongue modifiers:
TF_MOD_TONGUE_RIBBED("ribbing",
"Applies an effect related to adding ribbing to a tongue.",
"ribbed",
"modifier_circle_orifice_ribbed",
Colour.BASE_PINK,
Rarity.COMMON),
TF_MOD_TONGUE_TENTACLED("tentacled",
"Applies an effect related to adding tentacles to a tongue.",
"tentacled",
"modifier_circle_orifice_tentacled",
Colour.BASE_VIOLET,
Rarity.COMMON),
TF_MOD_TONGUE_BIFURCATED("bifurcated",
"Applies an effect related to making a tongue bifurcated.",
"bifurcated",
"modifier_circle_tongue_bifurcated",
Colour.BASE_CRIMSON,
Rarity.COMMON),
// penis & clit modifiers:
TF_MOD_PENIS_SHEATHED("sheathing",
"Applies an effect related to making a body part sheathed.",
"sheathed",
"modifier_circle_penis_sheathed",
Colour.BASE_ORANGE,
Rarity.COMMON),
TF_MOD_PENIS_RIBBED("ribbing",
"Applies an effect related to making a body part ribbed.",
"ribbed",
"modifier_circle_penis_ribbed",
Colour.BASE_PINK,
Rarity.COMMON),
TF_MOD_PENIS_TENTACLED("tentacled",
"Applies an effect related to making a body part tentacled.",
"tentacled",
"modifier_circle_orifice_tentacled",
Colour.BASE_VIOLET,
Rarity.COMMON),
TF_MOD_PENIS_KNOTTED("knotting",
"Applies an effect related to making a body part knotted.",
"knotted",
"modifier_circle_penis_knotted",
Colour.BASE_CRIMSON,
Rarity.COMMON),
TF_MOD_PENIS_TAPERED("tapering",
"Applies an effect related to making a body part tapered.",
"tapered",
"modifier_circle_penis_tapered",
Colour.BASE_LILAC,
Rarity.COMMON),
TF_MOD_PENIS_FLARED("flaring",
"Applies an effect related to making a body part flared.",
"flared",
"modifier_circle_penis_flared",
Colour.BASE_BROWN,
Rarity.COMMON),
TF_MOD_PENIS_BLUNT("blunting",
"Applies an effect related to making a body part blunted.",
"blunt",
"modifier_circle_penis_blunt",
Colour.BASE_TAN,
Rarity.COMMON),
TF_MOD_PENIS_BARBED("barbing",
"Applies an effect related to making a body part barbed.",
"barbed",
"modifier_circle_penis_barbed",
Colour.BASE_RED,
Rarity.COMMON),
TF_MOD_PENIS_VEINY("veins",
"Applies an effect related to making a body part veiny.",
"veiny",
"modifier_circle_penis_veiny",
Colour.BASE_VIOLET,
Rarity.COMMON),
TF_MOD_PENIS_PREHENSILE("prehensile",
"Applies an effect related to making a body part prehensile.",
"prehensile",
"modifier_circle_penis_prehensile",
Colour.BASE_TEAL,
Rarity.COMMON),
TF_MOD_CUM_EXPULSION("cum expulsion",
"Applies an effect related to modifying the amount of cum expelled at each orgasm.",
"cumming",
"modifier_circle_squirter",
Colour.BASE_AQUA,
Rarity.COMMON),
// vagina:
TF_MOD_VAGINA_SQUIRTER("squirter",
"Applies an effect related to making someone a squirter.",
"squirting",
"modifier_circle_squirter",
Colour.BASE_AQUA,
Rarity.COMMON),
// fluid modifiers:
TF_MOD_FLUID_MUSKY("musky",
"Applies an effect related to changing a fluid.",
"musk",
"modifier_circle_fluid_modifier",
Colour.BASE_BROWN,
Rarity.COMMON),
TF_MOD_FLUID_VISCOUS("viscous",
"Applies an effect related to changing a fluid.",
"viscous",
"modifier_circle_fluid_modifier",
Colour.BASE_GREY,
Rarity.COMMON),
TF_MOD_FLUID_STICKY("sticky",
"Applies an effect related to changing a fluid.",
"sticky",
"modifier_circle_fluid_modifier",
Colour.BASE_YELLOW_LIGHT,
Rarity.COMMON),
TF_MOD_FLUID_SLIMY("slimy",
"Applies an effect related to changing a fluid.",
"slimy",
"modifier_circle_fluid_modifier",
Colour.BASE_BLUE_LIGHT,
Rarity.COMMON),
TF_MOD_FLUID_BUBBLING("bubbling",
"Applies an effect related to changing a fluid.",
"bubbling",
"modifier_circle_fluid_modifier",
Colour.BASE_AQUA,
Rarity.COMMON),
TF_MOD_FLUID_ALCOHOLIC("alcoholic",
"Applies an effect related to changing a fluid.",
"alcoholic",
"modifier_circle_fluid_modifier",
Colour.BASE_ORANGE,
Rarity.COMMON),
TF_MOD_FLUID_ADDICTIVE("addictive",
"Applies an effect related to changing a fluid.",
"addictive",
"modifier_circle_fluid_modifier",
Colour.BASE_PINK_DEEP,
Rarity.COMMON),
TF_MOD_FLUID_HALLUCINOGENIC("psychoactive",
"Applies an effect related to changing a fluid.",
"psychoactive",
"modifier_circle_fluid_modifier",
Colour.BASE_MAGENTA,
Rarity.COMMON),
TF_MOD_FLUID_MINERAL_OIL("mineral oil",
"Applies an effect related to changing a fluid.",
"mineral oil",
"modifier_circle_fluid_modifier",
Colour.BASE_BLACK,
Rarity.COMMON),
// fluid flavours: TODO background
TF_MOD_FLAVOUR_CUM("cum-flavour",
"Applies an effect related to changing a fluid's flavour.",
"cum-flavour",
"modifier_circle_flavour_cum",
Colour.BASE_YELLOW_LIGHT,
Rarity.COMMON),
TF_MOD_FLAVOUR_MILK("milk-flavour",
"Applies an effect related to changing a fluid's flavour.",
"milk-flavour",
"modifier_circle_flavour_cum",
Colour.BASE_WHITE,
Rarity.COMMON),
TF_MOD_FLAVOUR_GIRLCUM("girlcum-flavour",
"Applies an effect related to changing a fluid's flavour.",
"milk-flavour",
"modifier_circle_flavour_cum",
Colour.BASE_PINK_LIGHT,
Rarity.COMMON),
TF_MOD_FLAVOUR_BUBBLEGUM("bubblegum-flavour",
"Applies an effect related to changing a fluid's flavour.",
"bubblegum-flavour",
"modifier_circle_flavour_bubblegum",
Colour.BASE_PINK,
Rarity.COMMON),
TF_MOD_FLAVOUR_BEER("beer-flavour",
"Applies an effect related to changing a fluid's flavour.",
"beer-flavour",
"modifier_circle_flavour_beer",
Colour.BASE_ORANGE,
Rarity.COMMON),
TF_MOD_FLAVOUR_VANILLA("vanilla-flavour",
"Applies an effect related to changing a fluid's flavour.",
"vanilla-flavour",
"modifier_circle_flavour_vanilla",
Colour.BASE_YELLOW_LIGHT,
Rarity.COMMON),
TF_MOD_FLAVOUR_STRAWBERRY("strawberry-flavour",
"Applies an effect related to changing a fluid's flavour.",
"strawberry-flavour",
"modifier_circle_flavour_strawberry",
Colour.BASE_RED,
Rarity.COMMON),
TF_MOD_FLAVOUR_CHOCOLATE("chocolate-flavour",
"Applies an effect related to changing a fluid's flavour.",
"chocolate-flavour",
"modifier_circle_flavour_chocolate",
Colour.BASE_BROWN_DARK,
Rarity.COMMON),
TF_MOD_FLAVOUR_PINEAPPLE("pineapple-flavour",
"Applies an effect related to changing a fluid's flavour.",
"pineapple-flavour",
"modifier_circle_flavour_pineapple",
Colour.BASE_YELLOW_LIGHT,
Rarity.COMMON),
TF_MOD_FLAVOUR_HONEY("honey-flavour",
"Applies an effect related to changing a fluid's flavour.",
"honey-flavour",
"modifier_circle_flavour_honey",
Colour.BASE_YELLOW,
Rarity.COMMON),
TF_MOD_FLAVOUR_MINT("mint-flavour",
"Applies an effect related to changing a fluid's flavour.",
"mint-flavour",
"modifier_circle_flavour_mint",
Colour.BASE_GREEN_LIME,
Rarity.COMMON),
TF_MOD_FLAVOUR_CHERRY("cherry-flavour",
"Applies an effect related to changing a fluid's flavour.",
"cherry-flavour",
"modifier_circle_flavour_cherry",
Colour.BASE_CRIMSON,
Rarity.COMMON),
// Fetishes:
TF_MOD_FETISH_BODY_PART("body part fetishes",
"Applies an effect related to a body part fetish.",
"fetish",
"modifier_circle_desires",
Colour.BASE_PINK,
Rarity.COMMON),
TF_MOD_FETISH_BEHAVIOUR("behavioural fetishes",
"Applies an effect related to a behavioural fetish.",
"fetish",
"modifier_circle_desires",
Colour.BASE_PURPLE,
Rarity.COMMON),
TF_MOD_FETISH_ANAL_GIVING(Fetish.FETISH_ANAL_GIVING),
TF_MOD_FETISH_ANAL_RECEIVING(Fetish.FETISH_ANAL_RECEIVING),
TF_MOD_FETISH_VAGINAL_GIVING(Fetish.FETISH_VAGINAL_GIVING),
TF_MOD_FETISH_VAGINAL_RECEIVING(Fetish.FETISH_VAGINAL_RECEIVING),
TF_MOD_FETISH_PENIS_GIVING(Fetish.FETISH_PENIS_GIVING),
TF_MOD_FETISH_PENIS_RECEIVING(Fetish.FETISH_PENIS_RECEIVING),
TF_MOD_FETISH_BREASTS_OTHERS(Fetish.FETISH_BREASTS_OTHERS),
TF_MOD_FETISH_BREASTS_SELF(Fetish.FETISH_BREASTS_SELF),
TF_MOD_FETISH_ORAL_GIVING(Fetish.FETISH_ORAL_GIVING),
TF_MOD_FETISH_ORAL_RECEIVING(Fetish.FETISH_ORAL_RECEIVING),
TF_MOD_FETISH_LEG_LOVER(Fetish.FETISH_LEG_LOVER),
TF_MOD_FETISH_STRUTTER(Fetish.FETISH_STRUTTER),
TF_MOD_FETISH_FOOT_GIVING(Fetish.FETISH_FOOT_GIVING),
TF_MOD_FETISH_FOOT_RECEIVING(Fetish.FETISH_FOOT_RECEIVING),
TF_MOD_FETISH_LACTATION_OTHERS(Fetish.FETISH_LACTATION_OTHERS),
TF_MOD_FETISH_LACTATION_SELF(Fetish.FETISH_LACTATION_SELF),
TF_MOD_FETISH_DOMINANT(Fetish.FETISH_DOMINANT),
TF_MOD_FETISH_SUBMISSIVE(Fetish.FETISH_SUBMISSIVE),
TF_MOD_FETISH_CROSS_DRESSER(Fetish.FETISH_CROSS_DRESSER),
TF_MOD_FETISH_CUM_ADDICT(Fetish.FETISH_CUM_ADDICT),
TF_MOD_FETISH_CUM_STUD(Fetish.FETISH_CUM_STUD),
TF_MOD_FETISH_DEFLOWERING(Fetish.FETISH_DEFLOWERING),
TF_MOD_FETISH_DENIAL(Fetish.FETISH_DENIAL),
TF_MOD_FETISH_DENIAL_SELF(Fetish.FETISH_DENIAL_SELF),
TF_MOD_FETISH_EXHIBITIONIST(Fetish.FETISH_EXHIBITIONIST),
TF_MOD_FETISH_VOYEURIST(Fetish.FETISH_VOYEURIST),
TF_MOD_FETISH_IMPREGNATION(Fetish.FETISH_IMPREGNATION),
TF_MOD_FETISH_INCEST(Fetish.FETISH_INCEST),
TF_MOD_FETISH_MASOCHIST(Fetish.FETISH_MASOCHIST),
TF_MOD_FETISH_MASTURBATION(Fetish.FETISH_MASTURBATION),
TF_MOD_FETISH_NON_CON_DOM(Fetish.FETISH_NON_CON_DOM),
TF_MOD_FETISH_NON_CON_SUB(Fetish.FETISH_NON_CON_SUB),
TF_MOD_FETISH_PREGNANCY(Fetish.FETISH_PREGNANCY),
TF_MOD_FETISH_PURE_VIRGIN(Fetish.FETISH_PURE_VIRGIN),
TF_MOD_FETISH_SADIST(Fetish.FETISH_SADIST),
TF_MOD_FETISH_TRANSFORMATION_GIVING(Fetish.FETISH_TRANSFORMATION_GIVING),
TF_MOD_FETISH_TRANSFORMATION_RECEIVING(Fetish.FETISH_TRANSFORMATION_RECEIVING),
TF_MOD_FETISH_BIMBO(Fetish.FETISH_BIMBO),
TF_MOD_FETISH_KINK_GIVING(Fetish.FETISH_KINK_GIVING),
TF_MOD_FETISH_KINK_RECEIVING(Fetish.FETISH_KINK_RECEIVING),
;
private static List<TFModifier> TFModStrengthList = new ArrayList<>();
private static List<TFModifier> TFModIntelligenceList = new ArrayList<>();
private static List<TFModifier> TFModCorruptionList = new ArrayList<>();
private static List<TFModifier> TFModSexualList = new ArrayList<>();
private static List<TFModifier> TFAttributeList = new ArrayList<>();
private static List<TFModifier> TFRacialBodyPartsList = new ArrayList<>();
private static List<TFModifier> TFBodyPartFetishList = new ArrayList<>();
private static List<TFModifier> TFBehaviouralFetishList = new ArrayList<>();
private static List<TFModifier> clothingPrimaryList = new ArrayList<>();
private static List<TFModifier> clothingAttributeList = new ArrayList<>();
private static List<TFModifier> clothingMajorAttributeList = new ArrayList<>();
private static List<TFModifier> tattooPrimaryList = new ArrayList<>();
private static List<TFModifier> weaponPrimaryList = new ArrayList<>();
private static List<TFModifier> weaponAttributeList = new ArrayList<>();
private static List<TFModifier> weaponMajorAttributeList = new ArrayList<>();
static {
TFModStrengthList.add(NONE);
TFModIntelligenceList.add(NONE);
TFModCorruptionList.add(NONE);
TFModSexualList.add(NONE);
for(TFModifier tfMod : TFModifier.values()) {
if(tfMod.getAttributeCategory()!=null && tfMod!=TFModifier.DAMAGE_WEAPON && tfMod!=TFModifier.RESISTANCE_WEAPON) {
switch(tfMod.getAttributeCategory()) {
case CORRUPTION:
TFModCorruptionList.add(tfMod);
break;
case INTELLIGENCE:
TFModIntelligenceList.add(tfMod);
break;
case STRENGTH:
TFModStrengthList.add(tfMod);
break;
}
}
}
TFModSexualList.add(FERTILITY);
TFModSexualList.add(VIRILITY);
TFModSexualList.add(DAMAGE_LUST);
TFModSexualList.add(RESISTANCE_LUST);
// Body parts:
TFRacialBodyPartsList.add(NONE);
TFRacialBodyPartsList.add(TF_FACE);
TFRacialBodyPartsList.add(TF_SKIN);
TFRacialBodyPartsList.add(TF_CORE);
TFRacialBodyPartsList.add(TF_ARMS);
TFRacialBodyPartsList.add(TF_LEGS);
TFRacialBodyPartsList.add(TF_EARS);
TFRacialBodyPartsList.add(TF_EYES);
TFRacialBodyPartsList.add(TF_HAIR);
TFRacialBodyPartsList.add(TF_ANTENNA);
TFRacialBodyPartsList.add(TF_HORNS);
TFRacialBodyPartsList.add(TF_TAIL);
TFRacialBodyPartsList.add(TF_WINGS);
TFRacialBodyPartsList.add(TF_ASS);
TFRacialBodyPartsList.add(TF_BREASTS);
TFRacialBodyPartsList.add(TF_BREASTS_CROTCH);
TFRacialBodyPartsList.add(TF_PENIS);
TFRacialBodyPartsList.add(TF_VAGINA);
TFRacialBodyPartsList.add(TF_MILK);
TFRacialBodyPartsList.add(TF_MILK_CROTCH);
TFRacialBodyPartsList.add(TF_CUM);
TFRacialBodyPartsList.add(TF_GIRLCUM);
// TFAttributeList.add(NONE);
TFAttributeList.add(ARCANE_BOOST);
TFBodyPartFetishList.add(TF_MOD_FETISH_ANAL_GIVING);
TFBodyPartFetishList.add(TF_MOD_FETISH_ANAL_RECEIVING);
TFBodyPartFetishList.add(TF_MOD_FETISH_BREASTS_OTHERS);
TFBodyPartFetishList.add(TF_MOD_FETISH_BREASTS_SELF);
TFBodyPartFetishList.add(TF_MOD_FETISH_ORAL_GIVING);
TFBodyPartFetishList.add(TF_MOD_FETISH_ORAL_RECEIVING);
TFBodyPartFetishList.add(TF_MOD_FETISH_VAGINAL_GIVING);
TFBodyPartFetishList.add(TF_MOD_FETISH_VAGINAL_RECEIVING);
TFBodyPartFetishList.add(TF_MOD_FETISH_PENIS_GIVING);
TFBodyPartFetishList.add(TF_MOD_FETISH_PENIS_RECEIVING);
TFBodyPartFetishList.add(TF_MOD_FETISH_LEG_LOVER);
TFBodyPartFetishList.add(TF_MOD_FETISH_STRUTTER);
TFBodyPartFetishList.add(TF_MOD_FETISH_FOOT_GIVING);
TFBodyPartFetishList.add(TF_MOD_FETISH_FOOT_RECEIVING);
TFBodyPartFetishList.add(TF_MOD_FETISH_LACTATION_OTHERS);
TFBodyPartFetishList.add(TF_MOD_FETISH_LACTATION_SELF);
TFBehaviouralFetishList.add(TF_MOD_FETISH_DOMINANT);
TFBehaviouralFetishList.add(TF_MOD_FETISH_SUBMISSIVE);
TFBehaviouralFetishList.add(TF_MOD_FETISH_CUM_STUD);
TFBehaviouralFetishList.add(TF_MOD_FETISH_CUM_ADDICT);
TFBehaviouralFetishList.add(TF_MOD_FETISH_DEFLOWERING);
TFBehaviouralFetishList.add(TF_MOD_FETISH_PURE_VIRGIN);
TFBehaviouralFetishList.add(TF_MOD_FETISH_IMPREGNATION);
TFBehaviouralFetishList.add(TF_MOD_FETISH_PREGNANCY);
TFBehaviouralFetishList.add(TF_MOD_FETISH_TRANSFORMATION_GIVING);
TFBehaviouralFetishList.add(TF_MOD_FETISH_TRANSFORMATION_RECEIVING);
TFBehaviouralFetishList.add(TF_MOD_FETISH_SADIST);
TFBehaviouralFetishList.add(TF_MOD_FETISH_MASOCHIST);
TFBehaviouralFetishList.add(TF_MOD_FETISH_NON_CON_DOM);
TFBehaviouralFetishList.add(TF_MOD_FETISH_NON_CON_SUB);
TFBehaviouralFetishList.add(TF_MOD_FETISH_DENIAL);
TFBehaviouralFetishList.add(TF_MOD_FETISH_DENIAL_SELF);
TFBehaviouralFetishList.add(TF_MOD_FETISH_VOYEURIST);
TFBehaviouralFetishList.add(TF_MOD_FETISH_EXHIBITIONIST);
TFBehaviouralFetishList.add(TF_MOD_FETISH_BIMBO);
TFBehaviouralFetishList.add(TF_MOD_FETISH_CROSS_DRESSER);
TFBehaviouralFetishList.add(TF_MOD_FETISH_MASTURBATION);
TFBehaviouralFetishList.add(TF_MOD_FETISH_INCEST);
TFBehaviouralFetishList.add(TF_MOD_FETISH_KINK_GIVING);
TFBehaviouralFetishList.add(TF_MOD_FETISH_KINK_RECEIVING);
clothingPrimaryList.add(TFModifier.CLOTHING_MAJOR_ATTRIBUTE);
clothingPrimaryList.add(TFModifier.CLOTHING_ATTRIBUTE);
clothingPrimaryList.add(TFModifier.CLOTHING_SEALING);
clothingPrimaryList.add(TFModifier.CLOTHING_ENSLAVEMENT);
clothingPrimaryList.add(TFModifier.TF_MOD_FETISH_BODY_PART);
clothingPrimaryList.add(TFModifier.TF_MOD_FETISH_BEHAVIOUR);
clothingPrimaryList.add(TF_FACE);
clothingPrimaryList.add(TF_CORE);
clothingPrimaryList.add(TF_HAIR);
clothingPrimaryList.add(TF_ASS);
clothingPrimaryList.add(TF_BREASTS);
clothingPrimaryList.add(TF_BREASTS_CROTCH);
clothingPrimaryList.add(TF_PENIS);
clothingPrimaryList.add(TF_VAGINA);
clothingMajorAttributeList.add(TFModifier.HEALTH_MAXIMUM);
clothingMajorAttributeList.add(TFModifier.MANA_MAXIMUM);
clothingMajorAttributeList.add(TFModifier.STRENGTH);
clothingMajorAttributeList.add(TFModifier.INTELLIGENCE);
clothingMajorAttributeList.add(TFModifier.CORRUPTION);
clothingAttributeList.add(TFModifier.FERTILITY);
clothingAttributeList.add(TFModifier.VIRILITY);
clothingAttributeList.add(TFModifier.DAMAGE_UNARMED);
clothingAttributeList.add(TFModifier.DAMAGE_MELEE_WEAPON);
clothingAttributeList.add(TFModifier.DAMAGE_RANGED_WEAPON);
clothingAttributeList.add(TFModifier.DAMAGE_PHYSICAL);
clothingAttributeList.add(TFModifier.DAMAGE_LUST);
clothingAttributeList.add(TFModifier.DAMAGE_FIRE);
clothingAttributeList.add(TFModifier.DAMAGE_ICE);
clothingAttributeList.add(TFModifier.DAMAGE_POISON);
clothingAttributeList.add(TFModifier.DAMAGE_SPELLS);
clothingAttributeList.add(TFModifier.RESISTANCE_FIRE);
clothingAttributeList.add(TFModifier.RESISTANCE_ICE);
clothingAttributeList.add(TFModifier.RESISTANCE_LUST);
clothingAttributeList.add(TFModifier.RESISTANCE_PHYSICAL);
clothingAttributeList.add(TFModifier.RESISTANCE_POISON);
clothingAttributeList.add(TFModifier.SPELL_COST_MODIFIER);
clothingAttributeList.add(TFModifier.CRITICAL_DAMAGE);
tattooPrimaryList.add(TFModifier.CLOTHING_ATTRIBUTE);
tattooPrimaryList.add(TFModifier.TF_MOD_FETISH_BODY_PART);
tattooPrimaryList.add(TFModifier.TF_MOD_FETISH_BEHAVIOUR);
tattooPrimaryList.add(TF_FACE);
tattooPrimaryList.add(TF_CORE);
tattooPrimaryList.add(TF_HAIR);
tattooPrimaryList.add(TF_ASS);
tattooPrimaryList.add(TF_BREASTS);
tattooPrimaryList.add(TF_BREASTS_CROTCH);
tattooPrimaryList.add(TF_PENIS);
tattooPrimaryList.add(TF_VAGINA);
weaponPrimaryList.add(TFModifier.CLOTHING_MAJOR_ATTRIBUTE);
weaponPrimaryList.add(TFModifier.CLOTHING_ATTRIBUTE);
// weaponAttributeList.add(TFModifier.RESISTANCE_WEAPON);
// weaponAttributeList.add(TFModifier.DAMAGE_WEAPON);
weaponMajorAttributeList.add(TFModifier.HEALTH_MAXIMUM);
weaponMajorAttributeList.add(TFModifier.MANA_MAXIMUM);
weaponMajorAttributeList.add(TFModifier.STRENGTH);
weaponMajorAttributeList.add(TFModifier.INTELLIGENCE);
weaponMajorAttributeList.add(TFModifier.CORRUPTION);
weaponAttributeList.add(TFModifier.FERTILITY);
weaponAttributeList.add(TFModifier.VIRILITY);
weaponAttributeList.add(TFModifier.DAMAGE_UNARMED);
weaponAttributeList.add(TFModifier.DAMAGE_MELEE_WEAPON);
weaponAttributeList.add(TFModifier.DAMAGE_RANGED_WEAPON);
weaponAttributeList.add(TFModifier.DAMAGE_PHYSICAL);
weaponAttributeList.add(TFModifier.DAMAGE_LUST);
weaponAttributeList.add(TFModifier.DAMAGE_FIRE);
weaponAttributeList.add(TFModifier.DAMAGE_ICE);
weaponAttributeList.add(TFModifier.DAMAGE_POISON);
weaponAttributeList.add(TFModifier.DAMAGE_SPELLS);
weaponAttributeList.add(TFModifier.RESISTANCE_FIRE);
weaponAttributeList.add(TFModifier.RESISTANCE_ICE);
weaponAttributeList.add(TFModifier.RESISTANCE_LUST);
weaponAttributeList.add(TFModifier.RESISTANCE_PHYSICAL);
weaponAttributeList.add(TFModifier.RESISTANCE_POISON);
weaponAttributeList.add(TFModifier.SPELL_COST_MODIFIER);
weaponAttributeList.add(TFModifier.CRITICAL_DAMAGE);
}
private enum AttributeCategory {
STRENGTH,
INTELLIGENCE,
CORRUPTION;
}
private AttributeCategory attributeCategory;
private Attribute associatedAttribute;
private String name;
private String description;
private String descriptor;
private String SVGString;
private Colour colour;
private Rarity rarity;
private Fetish fetish;
private TFModifier(AttributeCategory attributeCategory, Attribute associatedAttribute, String description, String SVGString, Rarity rarity) {
this.attributeCategory=attributeCategory;
this.associatedAttribute=associatedAttribute;
this.name = associatedAttribute.getName();
this.description = description;
this.descriptor = associatedAttribute.getPositiveEnchantment();
this.colour = associatedAttribute.getColour();
this.rarity=rarity;
// Set this item's file image:
try {
InputStream is = this.getClass().getResourceAsStream("/com/lilithsthrone/res/crafting/" + SVGString + ".svg");
if(is==null) {
System.err.println("Error! TFModifier icon file does not exist (Trying to read from '"+SVGString+"')! (Code 1)");
}
String s = Util.inputStreamToString(is);
is.close();
if(SVGString.contains("flavour")) {
String SVGStringBackground = "";
is = Subspecies.class.getClassLoader().getResourceAsStream("com/lilithsthrone/res/crafting/modifier_circle_flavour_background.svg");
if(is==null) {
System.err.println("Error! Subspecies background icon file does not exist (Trying to read from 'modifier_circle_flavour_background')!");
}
SVGStringBackground = "<div style='width:100%;height:100%;position:absolute;left:0;bottom:0;'>"+SvgUtil.colourReplacement(this.toString()+"_B", colour, Util.inputStreamToString(is))+"</div>";
s = SVGStringBackground + "<div style='width:100%;height:100%;position:absolute;left:0;bottom:0;'>" + SvgUtil.colourReplacement(this.toString(), colour, s)+"</div>";
} else {
s = SvgUtil.colourReplacement(this.toString(), colour, s);
}
this.SVGString = s;
is.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
private TFModifier(String name, String description, String descriptor, String SVGString, Colour colour, Rarity rarity) {
this.name = name;
this.description = description;
this.descriptor = descriptor;
this.rarity=rarity;
if (colour == null) {
this.colour = Colour.CLOTHING_BLACK;
} else {
this.colour = colour;
}
// Set this item's file image:
try {
InputStream is = this.getClass().getResourceAsStream("/com/lilithsthrone/res/crafting/" + SVGString + ".svg");
if(is==null) {
System.err.println("Error! TFModifier icon file does not exist (Trying to read from '"+SVGString+"')! (Code 2)");
}
String s = Util.inputStreamToString(is);
is.close();
if(SVGString.contains("flavour")) {
String SVGStringBackground = "";
is = Subspecies.class.getClassLoader().getResourceAsStream("com/lilithsthrone/res/crafting/modifier_circle_flavour_background.svg");
if(is==null) {
System.err.println("Error! Subspecies background icon file does not exist (Trying to read from 'modifier_circle_flavour_background')!");
}
SVGStringBackground = "<div style='width:100%;height:100%;position:absolute;left:0;bottom:0;'>"+SvgUtil.colourReplacement(this.toString()+"_B", colour, Util.inputStreamToString(is))+"</div>";
s = SVGStringBackground + "<div style='width:100%;height:100%;position:absolute;left:0;bottom:0;'>" + SvgUtil.colourReplacement(this.toString(), colour, s)+"</div>";
} else {
s = SvgUtil.colourReplacement(this.toString(), colour, s);
}
this.SVGString = s;
is.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
private TFModifier(Fetish f) {
this.name = f.getName(null);
this.description = "Applies an effect related to the "+name+" fetish. ("+f.getShortDescriptor()+")";
this.descriptor = name;
this.rarity = Rarity.EPIC;
this.colour = Colour.FETISH;
this.fetish = f;
this.SVGString = f.getSVGString();
}
public int getValue() {
switch(getRarity()) {
case JINXED:
return 1;
case COMMON:
return 1;
case UNCOMMON:
return 2;
case RARE:
return 4;
case EPIC:
return 8;
case LEGENDARY:
return 12;
case QUEST:
return 1;
}
return 1;
}
public AttributeCategory getAttributeCategory() {
return attributeCategory;
}
public Attribute getAssociatedAttribute() {
return associatedAttribute;
}
public String getName() {
return name;
}
public String getDescription() {
return description;
}
public String getDescriptor() {
return descriptor;
}
public String getSVGString() {
return SVGString;
}
public Colour getColour() {
return colour;
}
public boolean isSoloDescriptor() {
return false;
}
public Rarity getRarity() {
return rarity;
}
public static List<TFModifier> getTFModStrengthList() {
return TFModStrengthList;
}
public static List<TFModifier> getTFModIntelligenceList() {
return TFModIntelligenceList;
}
public static List<TFModifier> getTFModCorruptionList() {
return TFModCorruptionList;
}
public static List<TFModifier> getTFModSexualList() {
return TFModSexualList;
}
public static List<TFModifier> getTFRacialBodyPartsList() {
if(Main.getProperties().udders==0) {
return TFRacialBodyPartsList.stream().filter(mod -> mod!=TFModifier.TF_BREASTS_CROTCH && mod!=TFModifier.TF_MILK_CROTCH).collect(Collectors.toList());
}
return TFRacialBodyPartsList;
}
public static List<TFModifier> getTFAttributeList() {
return TFAttributeList;
}
public static List<TFModifier> getTFBodyPartFetishList() {
return TFBodyPartFetishList;
}
public static List<TFModifier> getTFBehaviouralFetishList() {
return TFBehaviouralFetishList;
}
public Fetish getFetish() {
return fetish;
}
public static List<TFModifier> getClothingAttributeList() {
return clothingAttributeList;
}
public static List<TFModifier> getClothingMajorAttributeList() {
return clothingMajorAttributeList;
}
public static List<TFModifier> getClothingPrimaryList() {
return clothingPrimaryList;
}
public static List<TFModifier> getTattooPrimaryList() {
return tattooPrimaryList;
}
public static List<TFModifier> getWeaponPrimaryList() {
return weaponPrimaryList;
}
public static List<TFModifier> getWeaponMajorAttributeList() {
return weaponMajorAttributeList;
}
public static List<TFModifier> getWeaponAttributeList() {
return weaponAttributeList;
}
}
|
package me.kirinrin.author.enumation;
/**
* LoginTypeEnum
*
* @author Felordcn
* @since 16 :23 2019/10/17
*/
public enum LoginTypeEnum {
/**
* 原始登录方式.
*/
FORM,
/**
* Json 提交.
*/
JSON,
/**
* 验证码.
*/
CAPTCHA
}
|
/*-
* ============LICENSE_START=======================================================
* ONAP : APPC
* ================================================================================
* Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Copyright (C) 2017 Amdocs
* =============================================================================
* 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.
*
* ============LICENSE_END=========================================================
*/
package org.onap.appc.seqgen.impl;
import com.att.eelf.configuration.EELFLogger;
import com.att.eelf.configuration.EELFManager;
import org.apache.commons.lang3.StringUtils;
import org.onap.appc.dg.flowbuilder.FlowBuilder;
import org.onap.appc.dg.flowbuilder.exception.InvalidDependencyModelException;
import org.onap.appc.dg.flowbuilder.impl.FlowBuilderFactory;
import org.onap.appc.dg.objects.FlowStrategies;
import org.onap.appc.dg.objects.InventoryModel;
import org.onap.appc.dg.objects.VnfcDependencyModel;
import org.onap.appc.dg.objects.VnfcFlowModel;
import org.onap.appc.domainmodel.Vnfc;
import org.onap.appc.domainmodel.Vserver;
import org.onap.appc.exceptions.APPCException;
import org.onap.appc.seqgen.SequenceGenerator;
import org.onap.appc.seqgen.objects.ActionIdentifier;
import org.onap.appc.seqgen.objects.CapabilityModel;
import org.onap.appc.seqgen.objects.Constants;
import org.onap.appc.seqgen.objects.PreCheckOption;
import org.onap.appc.seqgen.objects.Response;
import org.onap.appc.seqgen.objects.SequenceGeneratorInput;
import org.onap.appc.seqgen.objects.Transaction;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import static org.onap.appc.seqgen.objects.Constants.Action;
import static org.onap.appc.seqgen.objects.Constants.ActionLevel;
import static org.onap.appc.seqgen.objects.Constants.ResponseAction;
import static org.onap.appc.seqgen.objects.Constants.ResponseMessage;
import static org.onap.appc.seqgen.objects.Constants.PreCheckOperator;
import static org.onap.appc.seqgen.objects.Constants.Capabilties;
import static org.onap.appc.seqgen.objects.Constants.CapabilityLevel;
import static org.onap.appc.seqgen.objects.Constants.RETRY_COUNT_VALUE;
import static org.onap.appc.seqgen.objects.Constants.WAIT_TIME;
import static org.onap.appc.seqgen.objects.Constants.RETRY_COUNT;
import static org.onap.appc.seqgen.objects.Constants.WAIT_TIME_VALUE;;
public class StartSequenceGenerator implements SequenceGenerator {
private static final EELFLogger logger = EELFManager.getInstance().getLogger(StartSequenceGenerator.class);
private List<Transaction> generateSequenceWithOutDependency(SequenceGeneratorInput input) throws Exception {
String payload = null;
PayloadGenerator payloadGenerator = new PayloadGenerator();
List<Transaction> transactionList = new LinkedList<>();
Integer transactionId = 1;
List<Vserver> vservers = input.getInventoryModel().getVnf().getVservers();
List<Integer> transactionIds = new LinkedList<>();
for (Vserver vm : vservers) {
// check vm-Start-capabilities for this vm's vnfc-function-code (before incrementing transactionId)
if (!vmSupportsStart(input, vm)) {
continue;
}
Transaction transaction = new Transaction();
transaction.setTransactionId(transactionId);
transactionIds.add(transactionId++);
transaction.setAction(Action.START.getActionType());
transaction.setActionLevel(ActionLevel.VM.getAction());
ActionIdentifier actionIdentifier = new ActionIdentifier();
actionIdentifier.setvServerId(vm.getId());
transaction.setActionIdentifier(actionIdentifier);
String vmId = vm.getUrl();
String url = vm.getUrl();
payload = payloadGenerator.getPayload(input, vmId, url);
transaction.setPayload(payload);
if(vservers.size()>1){
Response ignoreResponse = new Response();
ignoreResponse.setResponseMessage(ResponseMessage.FAILURE.getResponse());
Map<String, String> ignoreAction = new HashMap<>();
ignoreAction.put(ResponseAction.STOP.getAction(), Boolean.TRUE.toString());
ignoreResponse.setResponseAction(ignoreAction);
transaction.addResponse(ignoreResponse);
}
transactionList.add(transaction);
}
return transactionList;
}
private boolean checkSingleTransaction(List<Vnfc> invVnfcList) {
int vServerCount=0;
for(Vnfc vnfc : invVnfcList) {
List<Vserver> vms = vnfc.getVserverList();
vServerCount=vServerCount+vms.size();
}
return vServerCount <= 1;
}
private void updateResponse(Transaction transaction) {
Response ignoreResponse = new Response();
ignoreResponse.setResponseMessage(ResponseMessage.FAILURE.getResponse());
Map<String, String> ignoreAction = new HashMap<>();
ignoreAction.put(ResponseAction.STOP.getAction(), Boolean.TRUE.toString());
ignoreResponse.setResponseAction(ignoreAction);
transaction.addResponse(ignoreResponse);
}
private List<Transaction> generateSequenceWithDependencyModel(VnfcFlowModel flowModel, SequenceGeneratorInput input) throws APPCException {
Integer waitTime = readWaitTime(input);
Integer retryCount = readRetryCount(input);
List<Transaction> transactionList = new LinkedList<>();
Integer transactionId = 1;
Iterator<List<Vnfc>> itr = flowModel.getModelIterator();
while (itr.hasNext()) {
List<Vnfc> vnfcs = itr.next();
for (Vnfc vnfc : vnfcs) {
List<Vserver> vms = vnfc.getVserverList();
List<Integer> transactionIds = new LinkedList<>();
if(!vms.isEmpty()) {
for (Vserver vm : vms) {
// check vm-Start-capabilities for this vm's vnfc-function-code (before incrementing transactionId)
if (!vmSupportsStart(input, vm)) {
continue;
}
Transaction transaction = new Transaction();
transaction.setTransactionId(transactionId);
transactionIds.add(transactionId++);
transaction.setAction(Action.START.getActionType());
transaction.setActionLevel(ActionLevel.VM.getAction());
ActionIdentifier actionIdentifier = new ActionIdentifier();
actionIdentifier.setvServerId(vm.getId());
transaction.setActionIdentifier(actionIdentifier);
transaction.setPayload(input.getRequestInfo().getPayload());
Response ignoreResponse = new Response();
ignoreResponse.setResponseMessage(ResponseMessage.FAILURE.getResponse());
Map<String, String> ignoreAction = new HashMap<>();
ignoreAction.put(ResponseAction.STOP.getAction(), Boolean.TRUE.toString());
ignoreResponse.setResponseAction(ignoreAction);
transaction.addResponse(ignoreResponse);
transactionList.add(transaction);
}
boolean startApplicationSupported = readApplicationStartCapability(input);
if (startApplicationSupported) {
Transaction startAppTransaction = new Transaction();
startAppTransaction.setTransactionId(transactionId++);
startAppTransaction.setAction(Action.START_APPLICATION.getActionType());
startAppTransaction.setActionLevel(ActionLevel.VNFC.getAction());
ActionIdentifier startActionIdentifier = new ActionIdentifier();
startActionIdentifier.setVnfcName(vnfc.getVnfcName());
startAppTransaction.setActionIdentifier(startActionIdentifier);
startAppTransaction.setPayload(input.getRequestInfo().getPayload());
List<PreCheckOption> preCheckOptions = buildPreCheckOptions(transactionIds);
startAppTransaction.setPreCheckOperator(PreCheckOperator.ANY.getOperator());
startAppTransaction.setPrecheckOptions(preCheckOptions);
transactionList.add(startAppTransaction);
}
boolean healthCheckSupported = readHealthCheckCapabilites(input.getCapability());
if (healthCheckSupported) {
Transaction healthCheckTransaction = new Transaction();
healthCheckTransaction.setTransactionId(transactionId++);
healthCheckTransaction.setAction(Action.HEALTH_CHECK.getActionType());
healthCheckTransaction.setActionLevel(ActionLevel.VNFC.getAction());
ActionIdentifier healthCheckActionIdentifier = new ActionIdentifier();
healthCheckActionIdentifier.setVnfcName(vnfc.getVnfcName());
healthCheckTransaction.setActionIdentifier(healthCheckActionIdentifier);
healthCheckTransaction.setPayload(input.getRequestInfo().getPayload());
Response retryResponse = new Response();
retryResponse.setResponseMessage(ResponseMessage.UNHEALTHY.getResponse());
Map<String, String> retryAction = new HashMap<>();
retryAction.put(ResponseAction.RETRY.getAction(), retryCount.toString());
retryAction.put(ResponseAction.WAIT.getAction(), waitTime.toString());
retryResponse.setResponseAction(retryAction);
healthCheckTransaction.addResponse(retryResponse);
Response healthyResponse = new Response();
healthyResponse.setResponseMessage(ResponseMessage.HEALTHY.getResponse());
Map<String, String> healthyAction = new HashMap<>();
healthyAction.put(ResponseAction.CONTINUE.getAction().toLowerCase(), Boolean.TRUE.toString());
healthyResponse.setResponseAction(healthyAction);
healthCheckTransaction.addResponse(healthyResponse);
Response failureResponse = new Response();
failureResponse.setResponseMessage(ResponseMessage.FAILURE.getResponse());
Map<String, String> failureResonseAction = new HashMap<>();
failureResonseAction.put(ResponseAction.STOP.getAction(), Boolean.TRUE.toString());
failureResponse.setResponseAction(failureResonseAction);
healthCheckTransaction.addResponse(failureResponse);
transactionList.add(healthCheckTransaction);
}
}
}
}
return transactionList;
}
private List<PreCheckOption> buildPreCheckOptions(List<Integer> transactionIds) {
List<PreCheckOption> preCheckOptions = new LinkedList<>();
for (Integer vmTransactionId : transactionIds) {
PreCheckOption option = new PreCheckOption();
option.setPreTransactionId(vmTransactionId);
option.setParamName("status");
option.setParamValue("success");
preCheckOptions.add(option);
}
return preCheckOptions;
}
@Override
public List<Transaction> generateSequence(SequenceGeneratorInput input) throws Exception {
if (input.getRequestInfo().getActionLevel().equals(ActionLevel.VNF.getAction()) && input.getDependencyModel() != null) {
if(isVnfcPresent(input)) {
FlowStrategies flowStrategy = readFlowStrategy(input);
VnfcFlowModel flowModel = null;
try {
flowModel = buildFlowModel(input.getInventoryModel()
, input.getDependencyModel(), flowStrategy);
} catch (InvalidDependencyModelException invalidDependencyModelException) {
logger.error("Error Generating Sequence", invalidDependencyModelException);
throw new APPCException(invalidDependencyModelException.getMessage(), invalidDependencyModelException);
}
logger.debug("Flow Model " + flowModel);
return generateSequenceWithDependencyModel(flowModel, input);
}
else throw new APPCException("Vnfc details is missing in the input");
} else {
logger.info("Generating sequence without dependency model");
return generateSequenceWithOutDependency(input);
}
}
private VnfcFlowModel buildFlowModel(InventoryModel inventoryModel, VnfcDependencyModel dependencyModel, FlowStrategies flowStrategy) throws APPCException, InvalidDependencyModelException {
FlowBuilder flowBuilder = FlowBuilderFactory.getInstance().getFlowBuilder(flowStrategy);
if (flowBuilder == null) {
throw new APPCException("Flow Strategy not supported " + flowStrategy);
}
return flowBuilder.buildFlowModel(dependencyModel, inventoryModel);
}
private FlowStrategies readFlowStrategy(SequenceGeneratorInput sequenceGeneratorInput) {
Map<String, String> tunableParams = sequenceGeneratorInput.getTunableParams();
FlowStrategies strategy=null;
String strategyStr = null;
if (tunableParams != null) {
strategyStr = tunableParams.get(Constants.STRATEGY);
strategy = FlowStrategies.findByString(strategyStr);
}
if (strategy == null)
strategy= FlowStrategies.FORWARD;
return strategy;
}
private boolean readHealthCheckCapabilites(CapabilityModel capabilities) {
if (capabilities == null) {
return true;
}
List<String> vnfcCapabilities = capabilities.getVnfcCapabilities();
if (vnfcCapabilities != null)
return vnfcCapabilities.stream()
.anyMatch(p -> Capabilties.HEALTH_CHECK.getCapability().equalsIgnoreCase(p));
return false;
}
private boolean readApplicationStartCapability(SequenceGeneratorInput input) {
CapabilityModel capability = input.getCapability();
if (capability == null)
return true;
List<String> vnfcCapabilities = capability.getVnfcCapabilities();
if (vnfcCapabilities != null)
return vnfcCapabilities.stream()
.anyMatch(p -> Capabilties.START_APPLICATION.getCapability().equalsIgnoreCase(p));
return false;
}
private Integer readRetryCount(SequenceGeneratorInput input) throws APPCException {
String paramValStr = input.getTunableParams().get(RETRY_COUNT);
if (StringUtils.isEmpty(paramValStr)) {
return RETRY_COUNT_VALUE;
}
try {
return Integer.parseInt(paramValStr);
} catch (NumberFormatException e) {
String message = "Invalid Number for Retry Count " + paramValStr;
logger.error(message, e);
throw new APPCException(message);
}
}
private boolean isVnfcPresent(SequenceGeneratorInput input){
boolean vnfcPresent=true;
List<Vserver> vservers = input.getInventoryModel().getVnf().getVservers();
for (Vserver vm : vservers) {
if(!(vm.getVnfc()!=null&& vm.getVnfc().getVnfcType()!=null&& vm.getVnfc().getVnfcName()!=null)){
vnfcPresent=false;
break;
}
}
return vnfcPresent;
}
private Integer readWaitTime(SequenceGeneratorInput input) throws APPCException {
String paramValStr = input.getTunableParams().get(WAIT_TIME);
if (StringUtils.isEmpty(paramValStr)) {
return WAIT_TIME_VALUE;
}
try {
return Integer.parseInt(paramValStr);
} catch (NumberFormatException e) {
String message = "Invalid Number for Wait Time " + paramValStr;
logger.error(message, e);
throw new APPCException(message);
}
}
private boolean vmSupportsStart(SequenceGeneratorInput input, Vserver vm) {
boolean vmSupported = true;
if (input.getCapability() == null) {
logger.info("vmSupportsStart: " + "Capabilities model is null, returning vmSupported=" + vmSupported);
return vmSupported;
}
Map<String, List<String>> vmCapabilities = input.getCapability().getVmCapabilities();
if (vmCapabilities != null) {
if (!vmCapabilities.isEmpty()) {
List<String> vmCapsForThisAction = vmCapabilities.get(Action.START.getActionType());
if (vmCapsForThisAction != null) {
vmSupported = false;
if (!vmCapsForThisAction.isEmpty()) {
if (vm.getVnfc() != null) {
String vnfcFunctionCode = vm.getVnfc().getVnfcFunctionCode();
if (vnfcFunctionCode != null && !vnfcFunctionCode.isEmpty()) {
for (String s : vmCapabilities.get(Action.START.getActionType()) ) {
if (s.equalsIgnoreCase(vnfcFunctionCode)) {
vmSupported = true;
logger.info("vmSupportsStart: vnfcFunctionCode=" + vnfcFunctionCode + " found in vmCapabilities");
break;
}
}
} else {
logger.info("vmSupportsStart: " + "Inventory vnfcFunctionCode is null or empty");
}
} else {
logger.info("vmSupportsStart: " + "Inventory vnfc is null or empty");
}
} else {
logger.info("vmSupportsStart: " + "Given action in vm entry in Capabilities model is empty");
}
} else {
logger.info("vmSupportsStart: " + "Given action in vm entry in Capabilities model is null");
}
} else {
logger.info("vmSupportsStart: " + "Vm entry in Capabilities model is empty");
}
} else {
logger.info("vmSupportsStart: " + "Vm entry in Capabilities model is null");
}
logger.info("vmSupportsStart: " + "returning vmSupported=" + vmSupported + ", " + ((vmSupported)?"including":"excluding") + " vm=" + vm.getId());
return vmSupported;
}
}
|
package com.fges.rizomm.m1iii.learningagreementAPI.services.user;
import com.fges.rizomm.m1iii.learningagreementAPI.components.SendMail;
import com.fges.rizomm.m1iii.learningagreementAPI.dto.user.UserDTO;
import com.fges.rizomm.m1iii.learningagreementAPI.entity.user.User;
import com.fges.rizomm.m1iii.learningagreementAPI.exception.userNotFound.UserNotFoundException;
import com.fges.rizomm.m1iii.learningagreementAPI.repository.user.UserRepository;
import com.fges.rizomm.m1iii.learningagreementAPI.services.SuperService;
import com.fges.rizomm.m1iii.learningagreementAPI.util.BCryptManagerUtil;
import com.fges.rizomm.m1iii.learningagreementAPI.util.RoleEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
@Service
@Transactional
public class UserService extends SuperService<User,UserDTO> implements IUserService, UserDetailsService {
private final UserRepository userRepository;
private final BCryptManagerUtil bcrypt;
private final SendMail sendMail;
@Autowired
public UserService(UserRepository userRepository,
BCryptManagerUtil bcrypt,
SendMail sendMail) {
this.userRepository = userRepository;
this.bcrypt = bcrypt;
this.sendMail = sendMail;
}
public UserDTO entityToDto(User entity) {
return super.getMapper().map(entity, UserDTO.class);
}
public User dtoToEntity(UserDTO dto) {
return super.getMapper().map(dto, User.class);
}
@Override
public UserDTO addUser(UserDTO userDTO) {
List<RoleEnum> roleEnumList = Collections.singletonList(RoleEnum.STUDENT);
userDTO.setRoles(roleEnumList);
userDTO.setPassword(this.bcrypt.getPasswordEncoder().encode(userDTO.getPassword()));
User user = this.dtoToEntity(userDTO);
user.getSpinneret().setUser(user);
return this.entityToDto(this.userRepository.save(user));
}
public UserDTO resetPassword(Long id, UserDTO userDto) {
BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
User user = this.userRepository.getOne(id);
user.setPassword(bCryptPasswordEncoder.encode(userDto.getPassword()));
return this.entityToDto(this.userRepository.save(user));
}
public UserDTO getByToken(String token) {
User user = userRepository.findByResetToken(token);
UserDTO userDto = null;
if (user != null) {
userDto = this.entityToDto(user);
}
return userDto;
}
public User loadUserByUsername(String email) throws UsernameNotFoundException {
return userRepository.findByEmail(email)
.orElseThrow(() -> new UserNotFoundException(email));
}
@Override
public List<UserDTO> getUsers(Authentication authentication) {
User userDetails = (User) authentication.getPrincipal();
UserDTO userDTO = this.entityToDto(userDetails);
switch (userDTO.getRole().toString()) {
case "ADMIN":
return this.entityListToDtoList(this.userRepository.findAll());
case "RPI":
return this.entityListToDtoList(this.userRepository.findAllByRpi(userDetails));
case "STUDENT":
default:
return null;
}
}
@Override
public UserDTO findOne(Long id) {
return this.entityToDto(this.userRepository.findById(id).orElseThrow(() -> new UserNotFoundException(id)));
}
@Override
public UserDTO updateUser(UserDTO userDto, Long id) {
User newUser = this.dtoToEntity(userDto);
return this.userRepository.findById(id).map(user -> {
UserDTO previousUser = this.entityToDto(user);
if (!bcrypt.passwordMatch(previousUser.getPassword(), newUser.getPassword())) {
newUser.setPassword(this.bcrypt.getPasswordEncoder().encode(newUser.getPassword()));
}
return this.entityToDto(this.userRepository.save(newUser));
}).orElseThrow(() -> new UserNotFoundException(id));
}
public UserDTO passwordForgot(UserDTO userDto) {
Optional<User> mayUser = this.userRepository.findByEmail(userDto.getEmail());
if (mayUser.isPresent()) {
User user = mayUser.get();
user.setResetToken(Long.toString(System.currentTimeMillis()));
UserDTO userDto1 = this.entityToDto(userRepository.save(user));
this.sendMail.sendEmailForPasswordForgot(userDto1);
return userDto1;
} else {
throw new UsernameNotFoundException("There is no user with this mail address in the database : " + userDto.getEmail());
}
}
public void deleteUser(Long id) {
this.userRepository.deleteById(id);
}
}
|
/**
* 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.atlas.web.rest;
import org.apache.atlas.AtlasClient;
import org.apache.atlas.AtlasErrorCode;
import org.apache.atlas.SortOrder;
import org.apache.atlas.discovery.AtlasDiscoveryService;
import org.apache.atlas.exception.AtlasBaseException;
import org.apache.atlas.model.discovery.AtlasQuickSearchResult;
import org.apache.atlas.model.discovery.AtlasSearchResult;
import org.apache.atlas.model.discovery.AtlasSuggestionsResult;
import org.apache.atlas.model.discovery.SearchParameters;
import org.apache.atlas.model.discovery.SearchParameters.FilterCriteria;
import org.apache.atlas.model.profile.AtlasUserSavedSearch;
import org.apache.atlas.repository.Constants;
import org.apache.atlas.type.AtlasEntityType;
import org.apache.atlas.type.AtlasStructType;
import org.apache.atlas.type.AtlasTypeRegistry;
import org.apache.atlas.utils.AtlasPerfTracer;
import org.apache.atlas.web.util.Servlets;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.springframework.stereotype.Service;
import javax.inject.Inject;
import javax.inject.Singleton;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import java.io.IOException;
import java.util.List;
/**
* REST interface for data discovery using dsl or full text search
*/
@Path("v2/search")
@Singleton
@Service
@Consumes({Servlets.JSON_MEDIA_TYPE, MediaType.APPLICATION_JSON})
@Produces({Servlets.JSON_MEDIA_TYPE, MediaType.APPLICATION_JSON})
public class DiscoveryREST {
private static final Logger PERF_LOG = AtlasPerfTracer.getPerfLogger("rest.DiscoveryREST");
@Context
private HttpServletRequest httpServletRequest;
private final int maxFullTextQueryLength;
private final int maxDslQueryLength;
private final AtlasTypeRegistry typeRegistry;
private final AtlasDiscoveryService atlasDiscoveryService;
@Inject
public DiscoveryREST(AtlasTypeRegistry typeRegistry, AtlasDiscoveryService atlasDiscoveryService, Configuration configuration) {
this.typeRegistry = typeRegistry;
this.atlasDiscoveryService = atlasDiscoveryService;
this.maxFullTextQueryLength = configuration.getInt(Constants.MAX_FULLTEXT_QUERY_STR_LENGTH, 4096);
this.maxDslQueryLength = configuration.getInt(Constants.MAX_DSL_QUERY_STR_LENGTH, 4096);
}
/**
* Retrieve data for the specified DSL
*
* @param query DSL query
* @param typeName limit the result to only entities of specified type or its sub-types
* @param classification limit the result to only entities tagged with the given classification or or its sub-types
* @param limit limit the result set to only include the specified number of entries
* @param offset start offset of the result set (useful for pagination)
* @return Search results
* @throws AtlasBaseException
* @HTTP 200 On successful DSL execution with some results, might return an empty list if execution succeeded
* without any results
* @HTTP 400 Invalid DSL or query parameters
*/
@GET
@Path("/dsl")
public AtlasSearchResult searchUsingDSL(@QueryParam("query") String query,
@QueryParam("typeName") String typeName,
@QueryParam("classification") String classification,
@QueryParam("limit") int limit,
@QueryParam("offset") int offset) throws AtlasBaseException {
Servlets.validateQueryParamLength("typeName", typeName);
Servlets.validateQueryParamLength("classification", classification);
if (StringUtils.isNotEmpty(query) && query.length() > maxDslQueryLength) {
throw new AtlasBaseException(AtlasErrorCode.INVALID_QUERY_LENGTH, Constants.MAX_DSL_QUERY_STR_LENGTH);
}
AtlasPerfTracer perf = null;
try {
query = Servlets.decodeQueryString(query);
if (AtlasPerfTracer.isPerfTraceEnabled(PERF_LOG)) {
perf = AtlasPerfTracer.getPerfTracer(PERF_LOG, "DiscoveryREST.searchUsingDSL(" + query + "," + typeName
+ "," + classification + "," + limit + "," + offset + ")");
}
String queryStr = atlasDiscoveryService.getDslQueryUsingTypeNameClassification(query, typeName, classification);
return atlasDiscoveryService.searchUsingDslQuery(queryStr, limit, offset);
} finally {
AtlasPerfTracer.log(perf);
}
}
/**
* Retrieve data for the specified fulltext query
*
* @param query Fulltext query
* @param limit limit the result set to only include the specified number of entries
* @param offset start offset of the result set (useful for pagination)
* @return Search results
* @throws AtlasBaseException
* @HTTP 200 On successful FullText lookup with some results, might return an empty list if execution succeeded
* without any results
* @HTTP 400 Invalid fulltext or query parameters
*/
@GET
@Path("/fulltext")
public AtlasSearchResult searchUsingFullText(@QueryParam("query") String query,
@QueryParam("excludeDeletedEntities") boolean excludeDeletedEntities,
@QueryParam("limit") int limit,
@QueryParam("offset") int offset) throws AtlasBaseException {
// Validate FullText query for max allowed length
if(StringUtils.isNotEmpty(query) && query.length() > maxFullTextQueryLength){
throw new AtlasBaseException(AtlasErrorCode.INVALID_QUERY_LENGTH, Constants.MAX_FULLTEXT_QUERY_STR_LENGTH );
}
AtlasPerfTracer perf = null;
try {
if (AtlasPerfTracer.isPerfTraceEnabled(PERF_LOG)) {
perf = AtlasPerfTracer.getPerfTracer(PERF_LOG, "DiscoveryREST.searchUsingFullText(" + query + "," +
limit + "," + offset + ")");
}
return atlasDiscoveryService.searchUsingFullTextQuery(query, excludeDeletedEntities, limit, offset);
} finally {
AtlasPerfTracer.log(perf);
}
}
/**
* Retrieve data for the specified fulltext query
*
* @param query Fulltext query
* @param typeName limit the result to only entities of specified type or its sub-types
* @param classification limit the result to only entities tagged with the given classification or or its sub-types
* @param limit limit the result set to only include the specified number of entries
* @param offset start offset of the result set (useful for pagination)
* @return Search results
* @throws AtlasBaseException
* @HTTP 200 On successful FullText lookup with some results, might return an empty list if execution succeeded
* without any results
* @HTTP 400 Invalid fulltext or query parameters
*/
@GET
@Path("/basic")
public AtlasSearchResult searchUsingBasic(@QueryParam("query") String query,
@QueryParam("typeName") String typeName,
@QueryParam("classification") String classification,
@QueryParam("excludeDeletedEntities") boolean excludeDeletedEntities,
@QueryParam("limit") int limit,
@QueryParam("offset") int offset) throws AtlasBaseException {
Servlets.validateQueryParamLength("typeName", typeName);
Servlets.validateQueryParamLength("classification", classification);
if (StringUtils.isNotEmpty(query) && query.length() > maxFullTextQueryLength) {
throw new AtlasBaseException(AtlasErrorCode.INVALID_QUERY_LENGTH, Constants.MAX_FULLTEXT_QUERY_STR_LENGTH);
}
AtlasPerfTracer perf = null;
try {
if (AtlasPerfTracer.isPerfTraceEnabled(PERF_LOG)) {
perf = AtlasPerfTracer.getPerfTracer(PERF_LOG, "DiscoveryREST.searchUsingBasic(" + query + "," +
typeName + "," + classification + "," + limit + "," + offset + ")");
}
SearchParameters searchParameters = new SearchParameters();
searchParameters.setTypeName(typeName);
searchParameters.setClassification(classification);
searchParameters.setQuery(query);
searchParameters.setExcludeDeletedEntities(excludeDeletedEntities);
searchParameters.setLimit(limit);
searchParameters.setOffset(offset);
return atlasDiscoveryService.searchWithParameters(searchParameters);
} finally {
AtlasPerfTracer.log(perf);
}
}
/**
* Retrieve data for the specified attribute search query
*
* @param attrName Attribute name
* @param attrValuePrefix Attibute value to search on
* @param typeName limit the result to only entities of specified type or its sub-types
* @param limit limit the result set to only include the specified number of entries
* @param offset start offset of the result set (useful for pagination)
* @return Search results
* @throws AtlasBaseException
* @HTTP 200 On successful FullText lookup with some results, might return an empty list if execution succeeded
* without any results
* @HTTP 400 Invalid wildcard or query parameters
*/
@GET
@Path("/attribute")
public AtlasSearchResult searchUsingAttribute(@QueryParam("attrName") String attrName,
@QueryParam("attrValuePrefix") String attrValuePrefix,
@QueryParam("typeName") String typeName,
@QueryParam("limit") int limit,
@QueryParam("offset") int offset) throws AtlasBaseException {
Servlets.validateQueryParamLength("attrName", attrName);
Servlets.validateQueryParamLength("attrValuePrefix", attrValuePrefix);
Servlets.validateQueryParamLength("typeName", typeName);
AtlasPerfTracer perf = null;
try {
if (AtlasPerfTracer.isPerfTraceEnabled(PERF_LOG)) {
perf = AtlasPerfTracer.getPerfTracer(PERF_LOG, "DiscoveryREST.searchUsingAttribute(" + attrName + "," +
attrValuePrefix + "," + typeName + "," + limit + "," + offset + ")");
}
if (StringUtils.isEmpty(attrName) && StringUtils.isEmpty(attrValuePrefix)) {
throw new AtlasBaseException(AtlasErrorCode.INVALID_PARAMETERS,
String.format("attrName : %s, attrValue: %s for attribute search.", attrName, attrValuePrefix));
}
if (StringUtils.isEmpty(attrName)) {
AtlasEntityType entityType = typeRegistry.getEntityTypeByName(typeName);
if (entityType != null) {
String[] defaultAttrNames = new String[] { AtlasClient.QUALIFIED_NAME, AtlasClient.NAME };
for (String defaultAttrName : defaultAttrNames) {
AtlasStructType.AtlasAttribute attribute = entityType.getAttribute(defaultAttrName);
if (attribute != null) {
attrName = defaultAttrName;
break;
}
}
}
if (StringUtils.isEmpty(attrName)) {
attrName = AtlasClient.QUALIFIED_NAME;
}
}
SearchParameters searchParams = new SearchParameters();
FilterCriteria attrFilter = new FilterCriteria();
attrFilter.setAttributeName(StringUtils.isEmpty(attrName) ? AtlasClient.QUALIFIED_NAME : attrName);
attrFilter.setOperator(SearchParameters.Operator.STARTS_WITH);
attrFilter.setAttributeValue(attrValuePrefix);
searchParams.setTypeName(typeName);
searchParams.setEntityFilters(attrFilter);
searchParams.setOffset(offset);
searchParams.setLimit(limit);
return searchWithParameters(searchParams);
} finally {
AtlasPerfTracer.log(perf);
}
}
/**
* Attribute based search for entities satisfying the search parameters
*
* @param parameters Search parameters
* @return Atlas search result
* @throws AtlasBaseException
* @HTTP 200 On successful search
* @HTTP 400 Tag/Entity doesn't exist or Tag/entity filter is present without tag/type name
*/
@Path("basic")
@POST
public AtlasSearchResult searchWithParameters(SearchParameters parameters) throws AtlasBaseException {
AtlasPerfTracer perf = null;
try {
if (AtlasPerfTracer.isPerfTraceEnabled(PERF_LOG)) {
perf = AtlasPerfTracer.getPerfTracer(PERF_LOG, "DiscoveryREST.searchWithParameters(" + parameters + ")");
}
if (parameters.getLimit() < 0 || parameters.getOffset() < 0) {
throw new AtlasBaseException(AtlasErrorCode.BAD_REQUEST, "Limit/offset should be non-negative");
}
if (StringUtils.isEmpty(parameters.getTypeName()) && !isEmpty(parameters.getEntityFilters())) {
throw new AtlasBaseException(AtlasErrorCode.BAD_REQUEST, "EntityFilters specified without Type name");
}
if (StringUtils.isEmpty(parameters.getClassification()) && !isEmpty(parameters.getTagFilters())) {
throw new AtlasBaseException(AtlasErrorCode.BAD_REQUEST, "TagFilters specified without tag name");
}
if (StringUtils.isEmpty(parameters.getTypeName()) && StringUtils.isEmpty(parameters.getClassification()) && StringUtils.isEmpty(parameters.getQuery()) && StringUtils.isEmpty(parameters.getTermName())) {
throw new AtlasBaseException(AtlasErrorCode.INVALID_SEARCH_PARAMS);
}
validateSearchParameters(parameters);
return atlasDiscoveryService.searchWithParameters(parameters);
} finally {
AtlasPerfTracer.log(perf);
}
}
/**
* Relationship search to search for related entities satisfying the search parameters
*
* @param guid Attribute name
* @param relation relationName
* @param sortByAttribute sort the result using this attribute name, default value is 'name'
* @param sortOrder sorting order
* @param limit limit the result set to only include the specified number of entries
* @param offset start offset of the result set (useful for pagination)
* @return Atlas search result
* @throws AtlasBaseException
* @HTTP 200 On successful search
* @HTTP 400 guid is not a valid entity type or attributeName is not a valid relationship attribute
*/
@GET
@Path("relationship")
public AtlasSearchResult searchRelatedEntities(@QueryParam("guid") String guid,
@QueryParam("relation") String relation,
@QueryParam("sortBy") String sortByAttribute,
@QueryParam("sortOrder") SortOrder sortOrder,
@QueryParam("excludeDeletedEntities") boolean excludeDeletedEntities,
@QueryParam("limit") int limit,
@QueryParam("offset") int offset) throws AtlasBaseException {
Servlets.validateQueryParamLength("guid", guid);
Servlets.validateQueryParamLength("relation", relation);
Servlets.validateQueryParamLength("sortBy", sortByAttribute);
AtlasPerfTracer perf = null;
try {
if (AtlasPerfTracer.isPerfTraceEnabled(PERF_LOG)) {
perf = AtlasPerfTracer.getPerfTracer(PERF_LOG, "DiscoveryREST.relatedEntitiesSearchUsingGremlin(" + guid +
", " + relation + ", " + sortByAttribute + ", " + sortOrder + ", " + excludeDeletedEntities + ", " + ", " + limit + ", " + offset + ")");
}
return atlasDiscoveryService.searchRelatedEntities(guid, relation, sortByAttribute, sortOrder, excludeDeletedEntities, limit, offset);
} finally {
AtlasPerfTracer.log(perf);
}
}
/**
* @param savedSearch
* @return the saved search-object
* @throws AtlasBaseException
* @throws IOException
*/
@POST
@Path("saved")
public AtlasUserSavedSearch addSavedSearch(AtlasUserSavedSearch savedSearch) throws AtlasBaseException, IOException {
validateUserSavedSearch(savedSearch);
AtlasPerfTracer perf = null;
try {
if (AtlasPerfTracer.isPerfTraceEnabled(PERF_LOG)) {
perf = AtlasPerfTracer.getPerfTracer(PERF_LOG, "DiscoveryREST.addSavedSearch(userName=" + savedSearch.getOwnerName() + ", name=" + savedSearch.getName() + ", searchType=" + savedSearch.getSearchType() + ")");
}
return atlasDiscoveryService.addSavedSearch(Servlets.getUserName(httpServletRequest), savedSearch);
} finally {
AtlasPerfTracer.log(perf);
}
}
/***
*
* @param savedSearch
* @return the updated search-object
* @throws AtlasBaseException
*/
@PUT
@Path("saved")
public AtlasUserSavedSearch updateSavedSearch(AtlasUserSavedSearch savedSearch) throws AtlasBaseException {
validateUserSavedSearch(savedSearch);
AtlasPerfTracer perf = null;
try {
if (AtlasPerfTracer.isPerfTraceEnabled(PERF_LOG)) {
perf = AtlasPerfTracer.getPerfTracer(PERF_LOG, "DiscoveryREST.updateSavedSearch(userName=" + savedSearch.getOwnerName() + ", name=" + savedSearch.getName() + ", searchType=" + savedSearch.getSearchType() + ")");
}
return atlasDiscoveryService.updateSavedSearch(Servlets.getUserName(httpServletRequest), savedSearch);
} finally {
AtlasPerfTracer.log(perf);
}
}
/**
*
* @param searchName Name of the saved search
* @param userName User for whom the search is retrieved
* @return
* @throws AtlasBaseException
*/
@GET
@Path("saved/{name}")
public AtlasUserSavedSearch getSavedSearch(@PathParam("name") String searchName,
@QueryParam("user") String userName) throws AtlasBaseException {
Servlets.validateQueryParamLength("name", searchName);
Servlets.validateQueryParamLength("user", userName);
AtlasPerfTracer perf = null;
try {
if (AtlasPerfTracer.isPerfTraceEnabled(PERF_LOG)) {
perf = AtlasPerfTracer.getPerfTracer(PERF_LOG, "DiscoveryREST.getSavedSearch(userName=" + userName + ", name=" + searchName + ")");
}
return atlasDiscoveryService.getSavedSearchByName(Servlets.getUserName(httpServletRequest), userName, searchName);
} finally {
AtlasPerfTracer.log(perf);
}
}
/**
*
* @param userName User for whom the search is retrieved
* @throws AtlasBaseException
* @return list of all saved searches for given user
*/
@GET
@Path("saved")
public List<AtlasUserSavedSearch> getSavedSearches(@QueryParam("user") String userName) throws AtlasBaseException {
Servlets.validateQueryParamLength("user", userName);
AtlasPerfTracer perf = null;
try {
if (AtlasPerfTracer.isPerfTraceEnabled(PERF_LOG)) {
perf = AtlasPerfTracer.getPerfTracer(PERF_LOG, "DiscoveryREST.getSavedSearches(userName=" + userName + ")");
}
return atlasDiscoveryService.getSavedSearches(Servlets.getUserName(httpServletRequest), userName);
} finally {
AtlasPerfTracer.log(perf);
}
}
/**
* @param guid Name of the saved search
*/
@DELETE
@Path("saved/{guid}")
public void deleteSavedSearch(@PathParam("guid") String guid) throws AtlasBaseException {
Servlets.validateQueryParamLength("guid", guid);
AtlasPerfTracer perf = null;
try {
if (AtlasPerfTracer.isPerfTraceEnabled(PERF_LOG)) {
perf = AtlasPerfTracer.getPerfTracer(PERF_LOG, "DiscoveryREST.deleteSavedSearch(guid=" + guid + ")");
}
atlasDiscoveryService.deleteSavedSearch(Servlets.getUserName(httpServletRequest), guid);
} finally {
AtlasPerfTracer.log(perf);
}
}
/**
* Attribute based search for entities satisfying the search parameters
*
* @param searchName name of saved-search
* @param userName saved-search owner
* @return Atlas search result
* @throws AtlasBaseException
*/
@Path("saved/execute/{name}")
@GET
public AtlasSearchResult executeSavedSearchByName(@PathParam("name") String searchName,
@QueryParam("user") String userName) throws AtlasBaseException {
Servlets.validateQueryParamLength("name", searchName);
Servlets.validateQueryParamLength("user", userName);
AtlasPerfTracer perf = null;
try {
if (AtlasPerfTracer.isPerfTraceEnabled(PERF_LOG)) {
perf = AtlasPerfTracer.getPerfTracer(PERF_LOG,
"DiscoveryREST.executeSavedSearchByName(userName=" + userName + ", " + "name=" + searchName + ")");
}
AtlasUserSavedSearch savedSearch = atlasDiscoveryService.getSavedSearchByName(Servlets.getUserName(httpServletRequest), userName, searchName);
return executeSavedSearch(savedSearch);
} finally {
AtlasPerfTracer.log(perf);
}
}
/**
* Attribute based search for entities satisfying the search parameters
*
* @param searchGuid Guid identifying saved search
* @return Atlas search result
* @throws AtlasBaseException
*/
@Path("saved/execute/guid/{guid}")
@GET
public AtlasSearchResult executeSavedSearchByGuid(@PathParam("guid") String searchGuid) throws AtlasBaseException {
Servlets.validateQueryParamLength("guid", searchGuid);
AtlasPerfTracer perf = null;
try {
if (AtlasPerfTracer.isPerfTraceEnabled(PERF_LOG)) {
perf = AtlasPerfTracer.getPerfTracer(PERF_LOG, "DiscoveryREST.executeSavedSearchByGuid(" + searchGuid + ")");
}
AtlasUserSavedSearch savedSearch = atlasDiscoveryService.getSavedSearchByGuid(Servlets.getUserName(httpServletRequest), searchGuid);
return executeSavedSearch(savedSearch);
} finally {
AtlasPerfTracer.log(perf);
}
}
/**
* Attribute based search for entities satisfying the search parameters
*@return Atlas search result
* @throws AtlasBaseException
* @HTTP 200 On successful search
* @HTTP 400 Tag/Entity doesn't exist or Tag/entity filter is present without tag/type name
*/
@Path("/quick")
@GET
public AtlasQuickSearchResult searchUsingFreeText(@QueryParam("query") String query,
@QueryParam("excludeDeletedEntities") boolean excludeDeletedEntities,
@QueryParam("limit") int limit,
@QueryParam("offset") int offset) throws AtlasBaseException {
if (StringUtils.isNotEmpty(query) && query.length() > maxFullTextQueryLength) {
throw new AtlasBaseException(AtlasErrorCode.INVALID_QUERY_LENGTH, Constants.MAX_FULLTEXT_QUERY_STR_LENGTH);
}
AtlasPerfTracer perf = null;
try {
if (AtlasPerfTracer.isPerfTraceEnabled(PERF_LOG)) {
perf = AtlasPerfTracer.getPerfTracer(PERF_LOG, "DiscoveryREST.quick(" + query + "," +
"excludeDeletedEntities:" + excludeDeletedEntities + "," + limit + "," + offset + ")");
}
SearchParameters searchParameters = new SearchParameters();
searchParameters.setQuery(query);
searchParameters.setExcludeDeletedEntities(excludeDeletedEntities);
searchParameters.setLimit(limit);
searchParameters.setOffset(offset);
return atlasDiscoveryService.quickSearchWithParameters(searchParameters);
} finally {
AtlasPerfTracer.log(perf);
}
}
@Path("suggestions")
@GET
public AtlasSuggestionsResult getSuggestions(@QueryParam("prefixString") String prefixString) throws AtlasBaseException {
AtlasPerfTracer perf = null;
try {
if (AtlasPerfTracer.isPerfTraceEnabled(PERF_LOG)) {
perf = AtlasPerfTracer.getPerfTracer(PERF_LOG, "DiscoveryREST.getSuggestions(" + prefixString + ")");
}
return atlasDiscoveryService.getSuggestions(prefixString);
} finally {
AtlasPerfTracer.log(perf);
}
}
private boolean isEmpty(SearchParameters.FilterCriteria filterCriteria) {
return filterCriteria == null ||
(StringUtils.isEmpty(filterCriteria.getAttributeName()) && CollectionUtils.isEmpty(filterCriteria.getCriterion()));
}
private AtlasSearchResult executeSavedSearch(AtlasUserSavedSearch savedSearch) throws AtlasBaseException {
SearchParameters sp = savedSearch.getSearchParameters();
if(savedSearch.getSearchType() == AtlasUserSavedSearch.SavedSearchType.ADVANCED) {
String dslQuery = atlasDiscoveryService.getDslQueryUsingTypeNameClassification(sp.getQuery(), sp.getTypeName(), sp.getClassification());
return atlasDiscoveryService.searchUsingDslQuery(dslQuery, sp.getLimit(), sp.getOffset());
} else {
return atlasDiscoveryService.searchWithParameters(sp);
}
}
private void validateUserSavedSearch(AtlasUserSavedSearch savedSearch) throws AtlasBaseException {
if (savedSearch != null) {
Servlets.validateQueryParamLength("name", savedSearch.getName());
Servlets.validateQueryParamLength("ownerName", savedSearch.getOwnerName());
Servlets.validateQueryParamLength("guid", savedSearch.getGuid());
validateSearchParameters(savedSearch.getSearchParameters());
}
}
private void validateSearchParameters(SearchParameters parameters) throws AtlasBaseException {
if (parameters != null) {
Servlets.validateQueryParamLength("typeName", parameters.getTypeName());
Servlets.validateQueryParamLength("classification", parameters.getClassification());
if (StringUtils.isNotEmpty(parameters.getQuery()) && parameters.getQuery().length() > maxFullTextQueryLength) {
throw new AtlasBaseException(AtlasErrorCode.INVALID_QUERY_LENGTH, Constants.MAX_FULLTEXT_QUERY_STR_LENGTH);
}
}
}
}
|
package com.seovic.chronos.feed;
import com.seovic.chronos.Request;
import com.seovic.chronos.RequestFeed;
import java.time.Duration;
import java.util.concurrent.atomic.AtomicLong;
/**
* Limits duration (in milliseconds) of the underlying feed.
*
* @author Aleksandar Seovic 2015.04.24
*/
public class DurationLimiter
implements RequestFeed
{
private volatile long start;
private final RequestFeed feed;
private final Duration limit;
/**
* Construct DurationLimiter instance.
*
* @param feed the RequestFeed to wrap
* @param limit the number of milliseconds to limit the request generation to
*/
public DurationLimiter(RequestFeed feed, Duration limit)
{
this.feed = feed;
this.limit = limit;
}
@Override
public Request next()
{
if (start == 0)
{
start = System.currentTimeMillis();
}
long t = System.currentTimeMillis();
return t - start > limit.toMillis() ? null : feed.next();
}
}
|
/*
* The MIT License
*
* Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, Yahoo! Inc., CloudBees, Inc.
*
* 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 hudson.model;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import com.gargoylesoftware.htmlunit.HttpMethod;
import com.gargoylesoftware.htmlunit.Page;
import com.gargoylesoftware.htmlunit.WebRequest;
import com.gargoylesoftware.htmlunit.html.DomElement;
import com.gargoylesoftware.htmlunit.html.DomNodeUtil;
import com.gargoylesoftware.htmlunit.html.HtmlAnchor;
import com.gargoylesoftware.htmlunit.html.HtmlForm;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import hudson.model.Node.Mode;
import hudson.search.SearchTest;
import hudson.security.AuthorizationStrategy;
import hudson.security.SecurityRealm;
import hudson.tasks.Ant;
import hudson.tasks.Ant.AntInstallation;
import hudson.tasks.BuildStep;
import java.lang.reflect.Field;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import jenkins.model.Jenkins;
import org.junit.Rule;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.jvnet.hudson.test.Email;
import org.jvnet.hudson.test.Issue;
import org.jvnet.hudson.test.JenkinsRule;
import org.jvnet.hudson.test.JenkinsRule.WebClient;
import org.jvnet.hudson.test.SmokeTest;
import org.jvnet.hudson.test.recipes.LocalData;
/**
* @author Kohsuke Kawaguchi
*/
@Category(SmokeTest.class)
public class HudsonTest {
@Rule
public JenkinsRule j = new JenkinsRule();
/**
* Tests the basic UI sanity and HtmlUnit set up.
*/
@Test
public void globalConfigRoundtrip() throws Exception {
j.jenkins.setQuietPeriod(10);
j.jenkins.setScmCheckoutRetryCount(9);
j.jenkins.setNumExecutors(8);
j.configRoundtrip();
assertEquals(10, j.jenkins.getQuietPeriod());
assertEquals(9, j.jenkins.getScmCheckoutRetryCount());
assertEquals(8, j.jenkins.getNumExecutors());
}
/**
* Performs a very basic round-trip of a non-empty system configuration screen.
* This makes sure that the structured form submission is working (to some limited extent.)
*/
@Test
@LocalData
@Email("http://www.nabble.com/Hudson.configure-calling-deprecated-Descriptor.configure-td19051815.html")
public void simpleConfigSubmit() throws Exception {
// just load the page and resubmit
HtmlPage configPage = j.createWebClient().goTo("configure");
HtmlForm form = configPage.getFormByName("config");
j.submit(form);
// Load tools page and resubmit too
HtmlPage toolsConfigPage = j.createWebClient().goTo("configureTools");
HtmlForm toolsForm = toolsConfigPage.getFormByName("config");
j.submit(toolsForm);
// make sure all the pieces are intact
assertEquals(2, j.jenkins.getNumExecutors());
assertSame(Mode.NORMAL, j.jenkins.getMode());
assertSame(SecurityRealm.NO_AUTHENTICATION, j.jenkins.getSecurityRealm());
assertSame(AuthorizationStrategy.UNSECURED, j.jenkins.getAuthorizationStrategy());
assertEquals(5, j.jenkins.getQuietPeriod());
List<JDK> jdks = j.jenkins.getJDKs();
assertEquals(3,jdks.size()); // Hudson adds one more
assertJDK(jdks.get(0),"jdk1","/tmp");
assertJDK(jdks.get(1),"jdk2","/tmp");
AntInstallation[] ants = j.jenkins.getDescriptorByType(Ant.DescriptorImpl.class).getInstallations();
assertEquals(2,ants.length);
assertAnt(ants[0],"ant1","/tmp");
assertAnt(ants[1],"ant2","/tmp");
}
private void assertAnt(AntInstallation ant, String name, String home) {
assertEquals(ant.getName(),name);
assertEquals(ant.getHome(),home);
}
private void assertJDK(JDK jdk, String name, String home) {
assertEquals(jdk.getName(),name);
assertEquals(jdk.getHome(),home);
}
/**
* Makes sure that the search index includes job names.
*
* @see SearchTest#testFailure
* This test makes sure that a failure will result in an exception
*/
@Test
public void searchIndex() throws Exception {
FreeStyleProject p = j.createFreeStyleProject();
Page jobPage = j.search(p.getName());
URL url = jobPage.getUrl();
System.out.println(url);
assertTrue(url.getPath().endsWith("/job/"+p.getName()+"/"));
}
/**
* Top page should only have one item in the breadcrumb.
*/
@Test
public void breadcrumb() throws Exception {
HtmlPage root = j.createWebClient().goTo("");
DomElement navbar = root.getElementById("breadcrumbs");
assertEquals(1, DomNodeUtil.selectNodes(navbar, "LI/A").size());
}
/**
* Configure link from "/computer/(built-in)/" should work.
*/
@Test
@Email("http://www.nabble.com/Master-slave-refactor-td21361880.html")
public void computerConfigureLink() throws Exception {
HtmlPage page = j.createWebClient().goTo("computer/(built-in)/configure");
j.submit(page.getFormByName("config"));
}
/**
* Configure link from "/computer/(built-in)/" should work.
*/
@Test
@Email("http://www.nabble.com/Master-slave-refactor-td21361880.html")
public void deleteHudsonComputer() throws Exception {
WebClient wc = j.createWebClient();
HtmlPage page = wc.goTo("computer/(built-in)/");
for (HtmlAnchor a : page.getAnchors()) {
assertFalse(a.getHrefAttribute(), a.getHrefAttribute().endsWith("delete"));
}
wc.setThrowExceptionOnFailingStatusCode(false);
// try to delete it by hitting the final URL directly
WebRequest req = new WebRequest(new URL(wc.getContextPath()+"computer/(built-in)/doDelete"), HttpMethod.POST);
page = wc.getPage(wc.addCrumb(req));
assertEquals(HttpURLConnection.HTTP_BAD_REQUEST, page.getWebResponse().getStatusCode());
// the built-in computer object should be still here
page = wc.goTo("computer/(built-in)/");
assertEquals(HttpURLConnection.HTTP_OK, page.getWebResponse().getStatusCode());
}
/**
* Legacy descriptors should be visible in the /descriptor/xyz URL.
*/
@Test
@Email("http://www.nabble.com/1.286-version-and-description-The-requested-resource-%28%29-is-not--available.-td22233801.html")
public void legacyDescriptorLookup() {
Descriptor dummy = new Descriptor(HudsonTest.class) {};
BuildStep.PUBLISHERS.addRecorder(dummy);
assertSame(dummy, j.jenkins.getDescriptor(HudsonTest.class.getName()));
BuildStep.PUBLISHERS.remove(dummy);
assertNull(j.jenkins.getDescriptor(HudsonTest.class.getName()));
}
/**
* Verify null/invalid primaryView setting doesn't result in infinite loop.
*/
@Test
@Issue("JENKINS-6938")
public void invalidPrimaryView() throws Exception {
Field pv = Jenkins.class.getDeclaredField("primaryView");
pv.setAccessible(true);
String value = null;
pv.set(j.jenkins, value);
assertNull("null primaryView", j.jenkins.getView(value));
value = "some bogus name";
pv.set(j.jenkins, value);
assertNull("invalid primaryView", j.jenkins.getView(value));
}
}
|
package com.atguigu.gulimall.product.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import java.io.Serializable;
import java.util.Date;
import lombok.Data;
/**
* spu信息介绍
*
* @author guoxiaolong
* @email 18240885452@163.com
* @date 2020-05-16 02:48:45
*/
@Data
@TableName("pms_spu_info_desc")
public class SpuInfoDescEntity implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 商品id
*/
@TableId(type= IdType.INPUT)
private Long spuId;
/**
* 商品介绍
*/
private String decript;
}
|
package tn.esprit.spring.service;
import java.io.ByteArrayInputStream;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tn.esprit.spring.entity.Category;
import tn.esprit.spring.entity.Product;
import tn.esprit.spring.helper.ExcelHelper;
import tn.esprit.spring.repository.CategoryRepository;
import tn.esprit.spring.repository.ProductRepository;
@Service
public class ProductServiceImpl implements IProductService{
@Autowired
ProductRepository productRepository;
@Autowired
CategoryRepository catRepository;
@Autowired
IOrdersService ordersService;
@Override
public List<Product> retrieveAllProducts() {
// TODO Auto-generated method stub
return (List<Product>) productRepository.findAll();
}
@Override
public Product addProduct(Product p) {
// TODO Auto-generated method stub
return productRepository.save(p);
}
@Override
public void deleteProduct(Long id_prod) {
// TODO Auto-generated method stub
productRepository.deleteById((long) id_prod);
}
@Override
public Product updateProduct(Product p) {
// TODO Auto-generated method stub
return productRepository.save(p);
}
@Override
public Product retrieveProduct(String id_prod) {
// TODO Auto-generated method stub
return productRepository.findById(Long.parseLong(id_prod)).orElse(null);
}
@Override
public List<Product> SearchProductByName(String name_prod) {
// TODO Auto-generated method stub
return productRepository.SearchProductByName(name_prod);
}
@Override
public List<Product> retrieveProductByCategory(Category category) {
// TODO Auto-generated method stub
return (List<Product>) productRepository.SearchProductByCategory(category);
}
@Override
public List<Product> Range(float min, float max) {
// TODO Auto-generated method stub
return productRepository.Range(min, max);
}
@Override
public List<Product> orderByAscendingQantity() {
// TODO Auto-generated method stub
return productRepository.orderByAscendingQantity();
}
@Override
public List<Product> orderByDescendingQantity() {
// TODO Auto-generated method stub
return productRepository.orderByDescendingQantity();
}
@Override
public void affectCategoryProduct(int id_cat, int id_prod) {
// TODO Auto-generated method stub
Category category = catRepository.findById((long) id_cat).orElse(null);
Product product = productRepository.findById((long) id_prod).orElse(null);
product.setCategory(category);
productRepository.save(product);
}
@Override
public ByteArrayInputStream load() {
List<Product> products = (List<Product>) productRepository.findAll();
ByteArrayInputStream in = ExcelHelper.productsToExcel(products);
return in;
}
@Override
public Map<Product, Integer> getProductsSells() {
// TODO Auto-generated method stub
List<Product> products = (List<Product>) productRepository.findAll();
Map<Product, Integer> productsSells = new HashMap<>();
products.forEach(p -> {
int sells = ordersService.GetOrderrsByProduct(p).size();
productsSells.put(p, sells);
});
return productsSells;
}
@Override
public Map<Product, Integer> getTopNProducts(int n) {
Map<Product, Integer> productsSells = getProductsSells();
return productsSells.entrySet().stream().sorted(Entry.<Product, Integer>comparingByValue().reversed()).limit(n)
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (oldValue, newValue) -> oldValue,
LinkedHashMap::new));
// productsSells;
}
}
|
package AllClasses;
import javafx.animation.Transition;
import javafx.scene.image.Image;
import javafx.scene.layout.AnchorPane;
import javafx.scene.paint.ImagePattern;
import javafx.util.Duration;
public class CageAnimation extends Transition {
public Cage cage;
AnchorPane anchorPane;
public CageAnimation(Cage cage,AnchorPane anchorPane)
{
this.cage=cage;
setCycleDuration(Duration.millis(1000));
setCycleCount(10);
}
@Override
protected void interpolate(double frac) {
int frame=(int) Math.floor(frac*24);
try {
cage.setFill(new ImagePattern(new Image(getClass().getResource("../img/cageBreak/cageBreak_"+ (frame + 1)+".png").toExternalForm())));
}
catch (Exception e){}
}
}
|
/*
* Copyright (c) 2014 Spotify AB.
*
* 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.spotify.helios.rollingupdate;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.spotify.helios.common.descriptors.DeploymentGroup;
import com.spotify.helios.common.descriptors.HostStatus;
import com.spotify.helios.common.descriptors.RolloutTask;
import java.util.List;
import java.util.Map;
import static com.google.common.base.Preconditions.checkNotNull;
public class DefaultRolloutPlanner implements RolloutPlanner {
private final DeploymentGroup deploymentGroup;
private DefaultRolloutPlanner(final DeploymentGroup deploymentGroup) {
this.deploymentGroup = checkNotNull(deploymentGroup, "deploymentGroup");
}
public static DefaultRolloutPlanner of(final DeploymentGroup deploymentGroup) {
return new DefaultRolloutPlanner(deploymentGroup);
}
@Override
public List<RolloutTask> plan(final Map<String, HostStatus> hostsAndStatuses) {
// we only care about hosts that are UP
final List<String> hosts = Lists.newArrayList();
for (final Map.Entry<String, HostStatus> entry : hostsAndStatuses.entrySet()) {
if (entry.getValue().getStatus().equals(HostStatus.Status.UP)) {
hosts.add(entry.getKey());
}
}
// generate the rollout tasks
final List<RolloutTask> rolloutTasks = Lists.newArrayList();
final int parallelism = deploymentGroup.getRolloutOptions() != null ?
deploymentGroup.getRolloutOptions().getParallelism() : 1;
final boolean overlap = deploymentGroup.getRolloutOptions() != null &&
deploymentGroup.getRolloutOptions().getOverlap();
for (final List<String> partition : Lists.partition(hosts, parallelism)) {
rolloutTasks.addAll(overlap ? rolloutTasksWithOverlap(partition) : rolloutTasks(partition));
}
return ImmutableList.copyOf(rolloutTasks);
}
private List<RolloutTask> rolloutTasks(final List<String> hosts) {
final ImmutableList.Builder<RolloutTask> result = ImmutableList.builder();
for (final String host : hosts) {
result.add(RolloutTask.of(RolloutTask.Action.UNDEPLOY_OLD_JOBS, host));
result.add(RolloutTask.of(RolloutTask.Action.DEPLOY_NEW_JOB, host));
}
for (final String host : hosts) {
result.add(RolloutTask.of(RolloutTask.Action.AWAIT_RUNNING, host));
}
return result.build();
}
private List<RolloutTask> rolloutTasksWithOverlap(final List<String> hosts) {
final ImmutableList.Builder<RolloutTask> result = ImmutableList.builder();
for (final String host : hosts) {
result.add(RolloutTask.of(RolloutTask.Action.DEPLOY_NEW_JOB, host));
}
for (final String host : hosts) {
result.add(RolloutTask.of(RolloutTask.Action.AWAIT_RUNNING, host));
}
for (final String host : hosts) {
result.add(RolloutTask.of(RolloutTask.Action.UNDEPLOY_OLD_JOBS, host));
}
return result.build();
}
}
|
package chatapp;
// Client connection imports:
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.URL;
import java.net.UnknownHostException;
// UI:
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.geometry.Pos;
import javafx.scene.control.Label;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.ScrollPane.ScrollBarPolicy;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.scene.control.TextField;
import javafx.geometry.Insets;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
// Other:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ResourceBundle;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.scene.control.TitledPane;
public class ClientController implements Initializable {
private static String clientUsername;
// Client Attributes
private String ip;
private int port;
private Socket socket;
private OutputStream out;
private static PrintWriter writer;
// UI Attributes
@FXML private ScrollPane container;
@FXML private TextField textMsg;
@FXML private TitledPane title;
static private VBox chatBox = new VBox(5);
// Statically called from the login controller class to set nickname
public static void setUsername(String name){
clientUsername = name;
}
@Override // On start method.
public void initialize(URL url, ResourceBundle rb) {
container.setPrefSize(392, 501);
container.setHbarPolicy(ScrollBarPolicy.NEVER);
container.setContent(chatBox);
chatBox.getStyleClass().add("chatbox");
container.vvalueProperty().bind(chatBox.heightProperty());
title.setText("Guy Fieri's Friends: " + clientUsername);
readServerInfo(); // Reads the file for IP/Port to connect to.
// Initializes IP and Port Variables.
try{
socket = new Socket(ip, port);
// Where messages are sent. (send)
out = socket.getOutputStream();
writer = new PrintWriter(out, true);
// Send User nickname to server
writer.print(formatPostRequest(clientUsername, "/nickname"));
writer.flush();
// If the above are successful (connected) let user know.
Label l = new Label("You have established a connection!");
l.setStyle("-fx-background-color:#333333;");
chatBox.getChildren().add(l);
// Start thread for waiting for incoming messages/updates.
Thread r = new ReceiveMsg(socket);
r.start();
}catch(UnknownHostException ex){
System.out.println("Server not found: " + ex.getMessage());
}catch(IOException ex){
System.out.println("I/O Error: " + ex.getMessage());
}
}
// Reads from an assets file the server information to connect to.
void readServerInfo(){
try {
File file = new File("src/assets/server_info.txt");
Scanner in = new Scanner(file);
if(in.hasNext()){
ip = in.next();
}
if(in.hasNext()){
port = in.nextInt();
}
in.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(ClientController.class.getName()).log(Level.SEVERE, null, ex);
}
}
/*************************************
UI: Action Methods
*************************************/
@FXML // When the send button is pressed.
private void handleSendAction(ActionEvent event) {
sendMessage();
}
@FXML // When a user presses enter after typing a message.
private void onEnter(KeyEvent ke){
if(ke.getCode().equals(KeyCode.ENTER)){
sendMessage();
}
}
// Send message from current client.
private void sendMessage(){
if(textMsg.getText() != null && textMsg.getText().length() > 0){
// Initialize label with message in it.
Label message = new Label(textMsg.getText());
message.setAlignment(Pos.CENTER_RIGHT);
message.setFont(new Font("Comic Sans MS", 16));
message.setWrapText(true);
message.setMaxWidth(235);
// Initialize label with timestamp.
ZonedDateTime time = ZonedDateTime.now();
DateTimeFormatter timeFormatted = DateTimeFormatter.ofPattern("hh:mm a");
Label timestamp = new Label(time.format(timeFormatted));
timestamp.setFont(new Font("Comic Sans MS", 8));
timestamp.setStyle("-fx-background-color:#333333");
// Add message and timestamp to UI.
HBox align = new HBox();
align.setPadding(new Insets(5,5,5,5));
align.getChildren().add(timestamp); // Add timestamp
align.getChildren().add(message); // Add message.
align.setAlignment(Pos.BASELINE_RIGHT); // Set right
chatBox.getChildren().add(align); // Adds to screen.
// Send to server.
writer.print(formatPostRequest(textMsg.getText(), "/send_message"));
writer.flush();
textMsg.clear(); // clears text input box.
}
}
// formats messages sent in a http request to be sent to the server.
private String formatPostRequest(String message, String version){
//debug
System.out.println(message);
return "POST " + version + " HTTP/1.1\n" +
"Host: " + ip + ":" + port + "\n" +
"Content-Type: text/plain;\n" +
"Content-Length: " + message.length() +
"\nAccept-Language: en-us\n" +
"Connection: Keep-Alive\n\n" + message + "\n";
}
@FXML // Statically called (RecieveMessageThread)
static void recieveMessage(String response){
// Initialize label with message in it
Label message = new Label(response);
message.setAlignment(Pos.CENTER_LEFT);
message.setFont(new Font("Comic Sans MS", 16));
message.setWrapText(true);
message.setMaxWidth(235);
// Initialize label with timestamp.
ZonedDateTime time = ZonedDateTime.now();
DateTimeFormatter timeFormatted = DateTimeFormatter.ofPattern("hh:mm a");
Label timestamp = new Label(time.format(timeFormatted));
timestamp.setFont(new Font("Comic Sans MS", 8));
timestamp.setStyle("-fx-background-color:#333333");
// Add message and timestamp to UI
HBox align = new HBox();
align.setPadding(new Insets(5,5,5,5));
align.getChildren().add(message);
align.getChildren().add(timestamp);
align.setAlignment(Pos.BASELINE_LEFT);
chatBox.getChildren().add(align);
}
// function for flagging the user if user lost connection to server (server closed)
static void lostConnectionFlag(){
// If the above are successful (connected) let user know.
Label l = new Label("You have lost connection to the server!");
l.setStyle("-fx-background-color:#333333;");
chatBox.getChildren().add(l);
}
}
|
/*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.sunshine;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.AsyncTaskLoader;
import android.support.v4.content.Loader;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.example.android.sunshine.data.SunshinePreferences;
import com.example.android.sunshine.utilities.NetworkUtils;
import com.example.android.sunshine.utilities.OpenWeatherJsonUtils;
import com.example.android.sunshine.ForecastAdapter.ForecastAdapterOnClickHandler;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import java.net.URL;
public class MainActivity extends AppCompatActivity implements ForecastAdapterOnClickHandler,LoaderCallbacks<String[]>,
SharedPreferences.OnSharedPreferenceChangeListener{
private static final String TAG = MainActivity.class.getSimpleName();
private RecyclerView mRecyclerView;
private ForecastAdapter mForecastAdapter;
private TextView merrormsg;
private ProgressBar mprogressBar;
private static final int FORECAST_LOADER_ID=0;
private static boolean PREFERENCES_HAVE_BEEN_UPDATED=false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_forecast);
mRecyclerView=(RecyclerView)findViewById(R.id.recyclerview_forecast);
merrormsg = (TextView)findViewById(R.id.errormsg);
LinearLayoutManager layoutManager = new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false);
mRecyclerView.setLayoutManager(layoutManager);
mRecyclerView.setHasFixedSize(true);
mForecastAdapter = new ForecastAdapter(this);
mRecyclerView.setAdapter(mForecastAdapter);
mprogressBar = (ProgressBar)findViewById(R.id.mprogress);
int loaderId = FORECAST_LOADER_ID;
LoaderCallbacks<String[]> callback = MainActivity.this;
Bundle bundleForLoader = null;
getSupportLoaderManager().initLoader(loaderId,bundleForLoader,callback);
PreferenceManager.getDefaultSharedPreferences(this)
.registerOnSharedPreferenceChangeListener(this);
}
@Override
public Loader<String[]> onCreateLoader(int i, @Nullable Bundle bundle) {
return new AsyncTaskLoader<String[]>(this) {
String[] mWeatherData = null;
@Override
protected void onStartLoading() {
if(mWeatherData !=null)
{
deliverResult(mWeatherData);
}
else
{
mprogressBar.setVisibility(View.VISIBLE);
forceLoad();
}
}
@Override
public String[] loadInBackground() {
String locationQuery = SunshinePreferences.getPreferredWeatherLocation(MainActivity.this);
URL weatherRequestUrl = NetworkUtils.buildUrl(locationQuery);
try{
String jsonWeatherResponse = NetworkUtils.getResponseFromHttpUrl(weatherRequestUrl);
String[] simpleJsonWeatherData = OpenWeatherJsonUtils.getSimpleWeatherStringsFromJson(MainActivity.this,jsonWeatherResponse);
return simpleJsonWeatherData;
}
catch (Exception e)
{
e.printStackTrace();
return null;
}
}
@Override
public void deliverResult(String[] data) {
mWeatherData = data;
super.deliverResult(data);
}
};
}
@Override
public void onLoadFinished(@NonNull Loader<String[]> loader, String[] data) {
mprogressBar.setVisibility(View.INVISIBLE);
mForecastAdapter.setWeatherData(data);
if(null == data)
{
showErrorMessage();
}
else
{
showWeatherDataView();
}
}
@Override
public void onLoaderReset(@NonNull Loader<String[]> loader) {
}
public void invalidateData()
{
mForecastAdapter.setWeatherData(null);
}
private void openLocationInMap()
{
String addressString = SunshinePreferences.getPreferredWeatherLocation(this);
//String addressString = "Sardar Bridge, Surat";
Uri geoLocation = Uri.parse("geo:0,0?q=" + addressString);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(geoLocation);
if(intent.resolveActivity(getPackageManager())!=null)
{
startActivity(intent);
}
else
{
Log.d(TAG,"couldn't call" +geoLocation.toString() + ", no receiving apps installed!");
}
}
@Override
public void onClick(String weatherForDay) {
Context context =this;
Toast.makeText(context, weatherForDay, Toast.LENGTH_SHORT).show();
Intent intent = new Intent(MainActivity.this,DetailActivity.class);
intent.putExtra("weather_msg",weatherForDay);
startActivity(intent);
}
private void showWeatherDataView(){
mRecyclerView.setVisibility(View.VISIBLE);
merrormsg.setVisibility(View.INVISIBLE);
}
private void showErrorMessage()
{
merrormsg.setVisibility(View.VISIBLE);
mRecyclerView.setVisibility(View.INVISIBLE);
}
@Override
protected void onStart() {
super.onStart();
if(PREFERENCES_HAVE_BEEN_UPDATED)
{
Log.d(TAG,"onStart:preferences were updated");
getSupportLoaderManager().restartLoader(FORECAST_LOADER_ID,null,this);
PREFERENCES_HAVE_BEEN_UPDATED=false;
}
}
@Override
protected void onDestroy() {
super.onDestroy();
PreferenceManager.getDefaultSharedPreferences(this)
.unregisterOnSharedPreferenceChangeListener(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
//MenuInflater inflater = getMenuInflater();
//inflater.inflate(R.menu.forecast,menu);
getMenuInflater().inflate(R.menu.forecast,menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id=item.getItemId();
if(id == R.id.action_refresh)
{
invalidateData();
getSupportLoaderManager().restartLoader(FORECAST_LOADER_ID,null,this);
return true;
}
if(id==R.id.action_map)
{
openLocationInMap();
return true;
}
if(id == R.id.action_settings)
{
Intent settingsintent = new Intent(MainActivity.this,SettingsActivity.class);
startActivity(settingsintent);
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
PREFERENCES_HAVE_BEEN_UPDATED=true;
}
}
|
package bio.terra.janitor.service.cleanup;
import bio.terra.stairway.FlightMap;
/** Constant of stairway {@link FlightMap} keys in Janitor. */
public final class FlightMapKeys {
public static final String TRACKED_RESOURCE_ID = "trackedResourceId";
public static final String CLOUD_RESOURCE_UID = "cloudResourceUid";
}
|
/*
* Copyright 2006 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.felix.daemon;
import java.io.File;
import org.apache.directory.daemon.InstallationLayout;
/**
* A felix specific installation layout.
*
* @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
*/
public class FelixLayout extends InstallationLayout
{
public FelixLayout( InstallationLayout layout )
{
super( layout.getBaseDirectory() );
}
public FelixLayout( File baseDirectory )
{
super( baseDirectory );
}
public FelixLayout( String baseDirectoryPath )
{
super( baseDirectoryPath );
}
public File getBundleDirectory()
{
return new File( super.baseDirectory, "bundle" );
}
public File getConfigurationFile()
{
return super.getConfigurationFile( "config.properties" );
}
public File getSystemPropertiesFile()
{
return new File( super.baseDirectory, "system.properties" );
}
}
|
/**
* @author Jakob Jenkov, Jenkov Development
*/
package com.jenkov.db.impl.mapping.method;
import java.sql.PreparedStatement;
import java.sql.SQLException;
/**
* A subclass of <code>GetterMapping</code> capable of inserting a <code>Float</code> into
* a <code>PreparedStatement</code>.
*
* @author Jakob Jenkov, Jenkov Development
*/
public class FloatGetterMapping extends GetterMapping{
protected void insertObjectDo(Object value, PreparedStatement statement, int index) throws SQLException {
if(value != null){
statement.setFloat(index, ((Float) value).floatValue());
} else {
statement.setNull(index, java.sql.Types.FLOAT);
}
}
}
|
package com.j256.ormlite.jdbc.db;
import static org.junit.Assert.assertEquals;
import java.io.File;
import java.sql.SQLException;
import java.util.ArrayList;
import org.junit.Test;
import com.j256.ormlite.TestUtils;
import com.j256.ormlite.jdbc.JdbcConnectionSource;
import com.j256.ormlite.support.DatabaseConnection;
import com.j256.ormlite.table.TableInfo;
public class H2DatabaseTypeTest extends BaseJdbcDatabaseTypeTest {
private final static String DATABASE_NAME = "ormlite";
private final String DB_DIRECTORY = "target/" + getClass().getSimpleName();
@Override
protected void setDatabaseParams() {
databaseUrl = "jdbc:h2:mem:" + DATABASE_NAME;
databaseType = new H2DatabaseType();
}
@Test(expected = SQLException.class)
public void testGeneratedIdSequenceNotSupported() throws Exception {
TableInfo<GeneratedIdSequence, Integer> tableInfo =
new TableInfo<GeneratedIdSequence, Integer>(databaseType, GeneratedIdSequence.class);
assertEquals(2, tableInfo.getFieldTypes().length);
StringBuilder sb = new StringBuilder();
ArrayList<String> additionalArgs = new ArrayList<String>();
ArrayList<String> statementsBefore = new ArrayList<String>();
databaseType.appendColumnArg(null, sb, tableInfo.getFieldTypes()[0], additionalArgs, statementsBefore, null,
null);
}
@Test
public void testUsernamePassword() throws Exception {
closeConnectionSource();
databaseType = new DerbyEmbeddedDatabaseType();
}
@Test(expected = SQLException.class)
public void testRemotePort() throws Exception {
File dbDir = new File(DB_DIRECTORY);
TestUtils.deleteDirectory(dbDir);
dbDir.mkdirs();
// bad port
int notTheRightPort = 12345;
closeConnectionSource();
// try to disable the retry feature which delays this test failure
System.setProperty("h2.socketConnectRetry", "0");
String dbUrl = "jdbc:h2:tcp://localhost:" + notTheRightPort + "/" + dbDir.getPath() + "/" + DATABASE_NAME;
connectionSource = new JdbcConnectionSource(dbUrl);
DatabaseConnection conn = connectionSource.getReadOnlyConnection(null);
try {
DatabaseTypeUtils.createDatabaseType(dbUrl);
} finally {
connectionSource.releaseConnection(conn);
}
}
}
|
package com.darren.exception;
/**
* Project: light
* Author : Darren
* Time : 2017/7/19
* Desc : 接口异常响应码集合
* 异常状态码在此处统一定义,对外含义统一
*/
public enum ExceptionEnum {
SUCCESS(0, "SUCCESS"),
SIGN_ERROR(10001, "SIGN_ERROR"),
MISSING_PARAMS(10003, "MISSING_PARAMS"),
INTERNAL_ERROR(10004, "INTERNAL_ERROR"),
MISSING_TIMESTAMP(10005, "MISSING_TIMESTAMP"),
AUTH_RESPONSE_FAIL(10006, "auth response fail", "账户异常,请重新登录"),
USER_NOT_LOGIN(10007, "user not login", "账户异常,请重新登录"),
USER_NOT_VALID(10008, "user not valid"),
TIME_PARAM_ERROR(10010, "time format error", "请求已过期"),
CHANNEL_REQUEST_ERROR(10012, "channel request failed"),
REQUEST_FREQUENTLY_ERROR(10015, "request frequently"),
DEVICE_TYPE_NOT_SUPPORT(10100, "not supported device"),
// DB 操作相关
DB_INSERT_FAILED(10512, "db insert failed"),
DB_UPDATE_FAILED(10513, "db update failed"),
// 结尾符
END_FOR_QUOTE(10999, "DO NOT MODIFY THIS LINE, NEVEL !!!"),
TEST_TIME_OUT_ERROR(99999, "testTimeoutError!");//TODO
/**
* 错误码
*/
private int code;
/**
* 错误信息
*/
private String msg;
private String showMsg;
ExceptionEnum(int code, String msg) {
this(code, msg, COMMON_SHOW_ERROR_MSG);
}
ExceptionEnum(int code, String msg, String showMsg) {
this.code = code;
this.msg = msg;
this.showMsg = showMsg;
}
public int getCode() {
return code;
}
public String getMsg() {
return msg;
}
public RequestException createException() {
return new RequestException(this.code, this.msg, this.showMsg);
}
public RequestException createException(String msg) {
return new RequestException(this.code, msg);
}
public RequestException createExceptionMsg(String msg) {
return new RequestException(this.code, msg);
}
public final static String COMMON_SHOW_ERROR_MSG = "服务器开小差了";
}
|
package org.zalando.intellij.swagger.traversal.path.swagger;
import com.intellij.psi.PsiElement;
public class DefinitionsInRootPathResolver implements PathResolver {
@Override
public final boolean childOfDefinitions(final PsiElement psiElement) {
return hasPath(psiElement, "$.*");
}
}
|
package webDomestika.bases;
import io.cucumber.java.After;
import io.cucumber.java.Before;
import io.github.bonigarcia.wdm.WebDriverManager;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.util.concurrent.TimeUnit;
public class AppHook {
//contiene las configuraciones basicas de los Test a ejecutar
//atributos
protected static WebDriver driver;
protected static WebDriverWait wait;
@Before(order =0)
public static void initialiseBrowser() {
WebDriverManager.chromedriver().setup();
}
@Before(order = 1)
public void setupBrowser() {
driver = new ChromeDriver();
wait = new WebDriverWait(driver,15);
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
}
@After
public void cleanup() {
if (driver != null) driver.close();
}
public static WebDriver getDriver(){
return driver;
}
public static WebDriverWait getWait(){return wait;}
}
|
/*
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.jdbc.datasource.lookup;
import org.junit.Test;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanNotOfRequiredTypeException;
import javax.sql.DataSource;
import static org.assertj.core.api.Assertions.*;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
/**
* @author Rick Evans
* @author Juergen Hoeller
* @author Chris Beams
*/
public class BeanFactoryDataSourceLookupTests {
private static final String DATASOURCE_BEAN_NAME = "dataSource";
@Test
public void testLookupSunnyDay() {
BeanFactory beanFactory = mock(BeanFactory.class);
StubDataSource expectedDataSource = new StubDataSource();
given(beanFactory.getBean(DATASOURCE_BEAN_NAME, DataSource.class)).willReturn(expectedDataSource);
BeanFactoryDataSourceLookup lookup = new BeanFactoryDataSourceLookup();
lookup.setBeanFactory(beanFactory);
DataSource dataSource = lookup.getDataSource(DATASOURCE_BEAN_NAME);
assertThat(dataSource).as("A DataSourceLookup implementation must *never* return null from " +
"getDataSource(): this one obviously (and incorrectly) is").isNotNull();
assertThat(dataSource).isSameAs(expectedDataSource);
}
@Test
public void testLookupWhereBeanFactoryYieldsNonDataSourceType() throws Exception {
final BeanFactory beanFactory = mock(BeanFactory.class);
given(beanFactory.getBean(DATASOURCE_BEAN_NAME, DataSource.class)).willThrow(
new BeanNotOfRequiredTypeException(DATASOURCE_BEAN_NAME,
DataSource.class, String.class));
BeanFactoryDataSourceLookup lookup = new BeanFactoryDataSourceLookup(beanFactory);
assertThatExceptionOfType(DataSourceLookupFailureException.class).isThrownBy(() ->
lookup.getDataSource(DATASOURCE_BEAN_NAME));
}
@Test
public void testLookupWhereBeanFactoryHasNotBeenSupplied() throws Exception {
BeanFactoryDataSourceLookup lookup = new BeanFactoryDataSourceLookup();
assertThatIllegalStateException().isThrownBy(() ->
lookup.getDataSource(DATASOURCE_BEAN_NAME));
}
}
|
/* Copyright 2004 - 2007 Kasper Nielsen <kasper@codehaus.org> Licensed under
* the Apache 2.0 License, see http://coconut.codehaus.org/license.
*/
package org.coconut.cache.internal.service.memorystore;
import java.util.Collections;
import java.util.List;
import org.coconut.cache.CacheEntry;
import org.coconut.cache.internal.CacheMutex;
import org.coconut.cache.internal.InternalCache;
import org.coconut.cache.internal.service.entry.AbstractCacheEntryFactoryService;
import org.coconut.cache.internal.service.listener.InternalCacheListener;
import org.coconut.cache.service.memorystore.MemoryStoreConfiguration;
import org.coconut.management.ManagedGroup;
import org.coconut.management.ManagedLifecycle;
/**
* <p>
* NOTICE: This is an internal class and should not be directly referred. No guarantee is
* made to the compatibility of this class between different releases of Coconut Cache.
*
* @author <a href="mailto:kasper@codehaus.org">Kasper Nielsen</a>
* @version $Id: SynchronizedCacheEvictionService.java 559 2008-01-09 16:28:27Z kasper $
* @param <K>
* the type of keys maintained by the cache
* @param <V>
* the type of mapped values
*/
public class SynchronizedMemoryStoreService<K, V> extends UnsynchronizedMemoryStoreService
implements ManagedLifecycle {
private final Object mutex;
public SynchronizedMemoryStoreService(
InternalCache cache,
MemoryStore<K, V> ms, CacheMutex mutex,
InternalCacheListener listener, AbstractCacheEntryFactoryService<K, V> factory) {
super(cache, ms, listener, factory);
this.mutex = mutex.getMutex();
}
/** {@inheritDoc} */
public void manage(ManagedGroup parent) {
ManagedGroup g = parent.addChild(MemoryStoreConfiguration.SERVICE_NAME,
"Cache Eviction attributes and operations");
g.add(MemoryStoreUtils.wrapMXBean(this));
}
/** {@inheritDoc} */
@Override
public long getMaximumVolume() {
synchronized (mutex) {
return super.getMaximumVolume();
}
}
/** {@inheritDoc} */
@Override
public int getMaximumSize() {
synchronized (mutex) {
return super.getMaximumSize();
}
}
/** {@inheritDoc} */
@Override
public void setMaximumVolume(long size) {
synchronized (mutex) {
super.setMaximumVolume(size);
}
}
/** {@inheritDoc} */
@Override
public void setMaximumSize(int size) {
synchronized (mutex) {
super.setMaximumSize(size);
}
}
/** {@inheritDoc} */
@Override
void trimCache(int toSize, long toVolume) {
long started = listener.beforeTrim(toSize, toVolume);
int size = 0;
int newSize = 0;
long volume = 0;
long newVolume = 0;
List<CacheEntry<K, V>> l = Collections.EMPTY_LIST;
synchronized (this) {
// manager.lazyStart(true);
// size = map.size();
// volume = map.volume();
// l = map.trimCache(toSize, toVolume);
// newSize = map.size();
// newVolume = map.volume();
}
listener.afterTrimCache(started, l, size, newSize, volume, newVolume);
}
}
|
// 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 android.support.v4.content;
public final class SharedPreferencesCompat
{
public static final class EditorCompat
{
public static EditorCompat getInstance()
{
if(sInstance == null)
//* 0 0:getstatic #27 <Field SharedPreferencesCompat$EditorCompat sInstance>
//* 1 3:ifnonnull 16
sInstance = new EditorCompat();
// 2 6:new #2 <Class SharedPreferencesCompat$EditorCompat>
// 3 9:dup
// 4 10:invokespecial #28 <Method void SharedPreferencesCompat$EditorCompat()>
// 5 13:putstatic #27 <Field SharedPreferencesCompat$EditorCompat sInstance>
return sInstance;
// 6 16:getstatic #27 <Field SharedPreferencesCompat$EditorCompat sInstance>
// 7 19:areturn
}
public void apply(android.content.SharedPreferences.Editor editor)
{
mHelper.apply(editor);
// 0 0:aload_0
// 1 1:getfield #22 <Field SharedPreferencesCompat$EditorCompat$Helper mHelper>
// 2 4:aload_1
// 3 5:invokevirtual #34 <Method void SharedPreferencesCompat$EditorCompat$Helper.apply(android.content.SharedPreferences$Editor)>
// 4 8:return
}
private static EditorCompat sInstance;
private final Helper mHelper = new Helper();
private EditorCompat()
{
// 0 0:aload_0
// 1 1:invokespecial #19 <Method void Object()>
// 2 4:aload_0
// 3 5:new #9 <Class SharedPreferencesCompat$EditorCompat$Helper>
// 4 8:dup
// 5 9:invokespecial #20 <Method void SharedPreferencesCompat$EditorCompat$Helper()>
// 6 12:putfield #22 <Field SharedPreferencesCompat$EditorCompat$Helper mHelper>
// 7 15:return
}
}
private static class EditorCompat.Helper
{
public void apply(android.content.SharedPreferences.Editor editor)
{
AbstractMethodError abstractmethoderror;
try
{
editor.apply();
// 0 0:aload_1
// 1 1:invokeinterface #24 <Method void android.content.SharedPreferences$Editor.apply()>
return;
// 2 6:return
}
//* 3 7:aload_1
//* 4 8:invokeinterface #28 <Method boolean android.content.SharedPreferences$Editor.commit()>
//* 5 13:pop
//* 6 14:return
// Misplaced declaration of an exception variable
catch(AbstractMethodError abstractmethoderror)
{
editor.commit();
}
//* 7 15:astore_2
//* 8 16:goto 7
}
EditorCompat.Helper()
{
// 0 0:aload_0
// 1 1:invokespecial #14 <Method void Object()>
// 2 4:return
}
}
private SharedPreferencesCompat()
{
// 0 0:aload_0
// 1 1:invokespecial #15 <Method void Object()>
// 2 4:return
}
}
|
/*
* Copyright 2016 Pete Cornish
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.apiman.cli;
import com.beust.jcommander.Parameters;
import io.apiman.cli.command.core.AbstractCommand;
import io.apiman.cli.command.core.Command;
import io.apiman.cli.managerapi.command.api.command.ApiCommand;
import io.apiman.cli.managerapi.command.gateway.command.GatewayCommand;
import io.apiman.cli.managerapi.command.org.command.OrgCommand;
import io.apiman.cli.managerapi.command.plugin.command.PluginCommand;
import io.apiman.cli.managerapi.declarative.command.ManagerApplyCommand;
import java.util.Map;
/**
* The main class; the root of all Manager Commands.
*
* @author Pete Cornish {@literal <outofcoffee@gmail.com>}
*/
@Parameters(commandDescription = "Interact with the Apiman Manager")
public class ManagerCli extends AbstractCommand {
@Override
protected void populateCommands(Map<String, Class<? extends Command>> commandMap) {
commandMap.put("org", OrgCommand.class);
commandMap.put("gateway", GatewayCommand.class);
commandMap.put("plugin", PluginCommand.class);
commandMap.put("api", ApiCommand.class);
commandMap.put("apply", ManagerApplyCommand.class);
}
}
|
package com.codingame.game;
import java.util.List;
public class Creature extends Unit {
Point camp;
CreatureState state = CreatureState.peacefull;
String creatureType;
public Creature(double x, double y) {
super(x, y, 1, -1, 300, null);
this.camp = new Point(x, y);
}
@Override
public String getType() {
return this.creatureType;
}
void findAction(List<Unit> allUnits) {
if (isDead || stunTime>0) return;
if (this.state.equals(CreatureState.aggressive)) {
aggressiveBehavior(allUnits);
} else if (this.state.equals(CreatureState.runningback)) {
runningBackBehavior();
}
}
void aggressiveBehavior(List<Unit> allUnits) {
Unit attacker = allUnits.stream()
.filter(u -> u instanceof Hero)
.sorted((u1, u2) -> u1.distance2(this) < u2.distance2(this) ? -1 : 1)
.findFirst()
.get();
Point target = attacker;
if (distance2(camp) < Const.AGGROUNITRANGE2) {
this.attackUnitOrMoveTowards((Unit) target, 0.0);
} else {
this.state = CreatureState.runningback;
this.runTowards(camp);
}
}
void runningBackBehavior() {
this.runTowards(camp);
if (distance(camp) < 2) {
this.state = CreatureState.peacefull;
this.health = maxHealth;
Const.viewController.addEffect(this, this, "default", 0);
}
}
}
|
package application;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.text.DateFormat;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Random;
import javafx.event.ActionEvent;
import javafx.fxml.FXMLLoader;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.fxml.FXML;
import javafx.scene.control.Label;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
public class CreateEditEmpController { //CONFIG REQD : Add dept??
@FXML
private TextField Fname;
@FXML
private TextField Lname;
@FXML
private TextField DOB;
@FXML
private TextField Sex;
@FXML
private TextField UID;
@FXML
private PasswordField Pass;
@FXML
private TextField D1name;
@FXML
private TextField D1sex;
@FXML
private TextField D1DOB;
@FXML
private TextField D2Name;
@FXML
private TextField D2se;
@FXML
private TextField D2DOB;
@FXML
private Label relation1;
@FXML
private Label relation11;
@FXML
private TextField D1Relation;
@FXML
private TextField D2Relation;
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/timecard";
// Database credentials
static final String USER = "root";
static final String PASS = "abc123";
public void back(ActionEvent event) throws IOException
{
Parent tableView = FXMLLoader.load(getClass().getClassLoader().getResource("Admin.fxml"));
Scene tableViewscene = new Scene(tableView);
Stage window = (Stage)((Node)event.getSource()).getScene().getWindow();
window.setScene(tableViewscene);
window.show();
}
public void save(ActionEvent event) throws IOException
{
System.out.println("In save");
String first = Fname.getText();
String last = Lname.getText();
String birth = DOB.getText();
String s = Sex.getText();
String id = UID.getText();
String pass = Pass.getText();
String name1 = D1name.getText();
String sex1 = D1sex.getText();
String birth1 = D1DOB.getText();
String rel1 = D1Relation.getText();
String name2 = D2Name.getText();
String sex2 = D2se.getText();
String birth2 = D2DOB.getText();
String rel2 = D1Relation.getText();
Connection conn = null;
Statement stmt1 = null;
Statement stmt2 = null;
Statement stmt3 = null;
Statement stmt = null;
try{
//STEP 2: RegdateFormatister JDBC driver
Class.forName("com.mysql.jdbc.Driver");
//STEP 3: Open a connection
System.out.println("Connecting to database for emp...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
//STEP 4: Execute a query
System.out.println("Creating statement for leave...");
String sql1,sql2,sql3,sqlCheck;
stmt = conn.createStatement();
sqlCheck = "select uid from emp";
ResultSet rs = stmt.executeQuery(sqlCheck);
boolean checker = false;
//STEP 5: Extract data from result set
while(rs.next()){
int idtable = rs.getInt("uid");
if(idtable == Integer.parseInt(id)) {
checker = true;
break;
}
}
if(checker == true ) {
System.out.println("ID Exists");
stmt1 = conn.createStatement();
sql1 = "update emp set f_name='"+first+"',l_name='"+last+"',sex='"+s+"',pass='"+pass+"' where uid="+id;
stmt1.executeUpdate(sql1);
}
else {
// Config reqd
System.out.println("ID does not Exist");
stmt1 = conn.createStatement();
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
String doj = df.format(java.time.LocalDate.now());
int dno = 10;
int pidx =102;
String sanswer = "pet";
sql1 = "insert into emp values("+id+",'"+first+"','"+last+"','"+s+"','"+pass+"','"+sanswer+"','"+doj+"',"+dno+","+pidx+");";
stmt1.executeUpdate(sql1);
}
if(name1 != null) {
stmt2 = conn.createStatement();
sql2 = "insert into dependents values("+id+",'"+name1+"','"+sex1+"','"+birth1+"','"+rel1+"');";
stmt2.executeUpdate(sql2);
}
if(name2 != null) {
stmt3 = conn.createStatement();
sql3 = "insert into dependents values("+id+",'"+name2+"','"+sex2+"','"+birth2+"','"+rel2+"');";
stmt3.executeUpdate(sql3);
}
//STEP 6: Clean-up environment
stmt1.close();
stmt2.close();
stmt3.close();
conn.close();
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(stmt1!=null)
stmt1.close();
}catch(SQLException se2){
}// nothing we can do
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
Parent tableView = FXMLLoader.load(getClass().getClassLoader().getResource("Admin.fxml"));
Scene tableViewscene = new Scene(tableView);
Stage window = (Stage)((Node)event.getSource()).getScene().getWindow();
window.setScene(tableViewscene);
window.show();
}
}
|
package de.scandio.settingsframework.stores;
import com.atlassian.confluence.core.ContentPropertyManager;
import com.atlassian.confluence.pages.Page;
public class ConfluencePageXmlStore extends AbstractXmlStore {
private final ContentPropertyManager contentPropertyManager;
private final Page page;
public ConfluencePageXmlStore(Page page, ContentPropertyManager contentPropertyManager) {
this.page = page;
this.contentPropertyManager = contentPropertyManager;
}
@Override
protected String loadValuesXml(String storageKey) {
return contentPropertyManager.getTextProperty(page, storageKey);
}
@Override
protected void removeValuesXml(String storageKey) {
contentPropertyManager.removeProperty(page, storageKey);
}
@Override
protected void storeValuesXml(String storageKey, String valuesXml) {
contentPropertyManager.setTextProperty(page, storageKey, valuesXml);
}
}
|
// Copyright 2018 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.api.ads.dfp.jaxws.v201802;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;
/**
*
* Represents targeted or excluded ad units.
*
*
* <p>Java class for AdUnitTargeting complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="AdUnitTargeting">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="adUnitId" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="includeDescendants" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "AdUnitTargeting", propOrder = {
"adUnitId",
"includeDescendants"
})
public class AdUnitTargeting {
protected String adUnitId;
protected Boolean includeDescendants;
/**
* Gets the value of the adUnitId property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getAdUnitId() {
return adUnitId;
}
/**
* Sets the value of the adUnitId property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setAdUnitId(String value) {
this.adUnitId = value;
}
/**
* Gets the value of the includeDescendants property.
*
* @return
* possible object is
* {@link Boolean }
*
*/
public Boolean isIncludeDescendants() {
return includeDescendants;
}
/**
* Sets the value of the includeDescendants property.
*
* @param value
* allowed object is
* {@link Boolean }
*
*/
public void setIncludeDescendants(Boolean value) {
this.includeDescendants = value;
}
}
|
package org.dave.bats.util.serialization;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
public @interface Store {
String key() default "";
boolean storeWithItem() default false;
boolean sendInUpdatePackage() default false;
}
|
package id.recharge.library.core.helper;
public class CommonMathHelper
{
public static float getDistanceBetweenTwoPoints(float x1, float y1, float x2, float y2)
{
return (float) Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));
}
}
|
// Copyright (c) FIRST and other WPILib contributors.
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
package frc.robot.subsystems;
import edu.wpi.first.wpilibj2.command.SubsystemBase;
public class DriveTrain extends SubsystemBase {
public DoubleMotors driveLeft;
public DoubleMotors driveRight;
/** Creates a new DriveTrain. */
public DriveTrain(DoubleMotors l, DoubleMotors r) {
driveLeft = l;
driveRight = r;
}
public void stop() {
drive(0, 0);
}
public void drive(double l, double r) {
driveLeft(l);
driveRight(r);
}
public void driveVolts(double v1, double v2) {
driveLeft.setVolts(v1);
driveRight.setVolts(v2);
}
public void driveLeft(double s) {
driveLeft.setSpeed(s);
}
public void driveRight(double s) {
driveRight.setSpeed(s);
}
@Override
public void periodic() {
// This method will be called once per scheduler run
}
@Override
public void simulationPeriodic() {
// This method will be called once per scheduler run during simulation
}
}
|
/*******************************************************************************
* 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.ilscipio.scipio.ce.webapp.ftl.context;
import java.util.List;
import freemarker.template.TemplateModelException;
/**
* SCIPIO: PushRequestStackMethod - Freemarker Method providing support for a stack
* structure having request scope, with fallback to globals.
*/
public class SetLastRequestStackMethod extends RequestStackMethod {
//private static final Debug.OfbizLogger module = Debug.getOfbizLogger(java.lang.invoke.MethodHandles.lookup().lookupClass());
/*
* @see freemarker.template.TemplateMethodModel#exec(java.util.List)
*/
@Override
public Object exec(@SuppressWarnings("rawtypes") List args) throws TemplateModelException {
return execPush(args, true);
}
}
|
package com.ruoyi.project.vocdeliver.controller;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.project.vocdeliver.domain.dto.InsertVocDeliverRequestDto;
import com.ruoyi.project.vocdeliver.service.VocDeliverService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* Created by Fyc on 2021-7-28.
* 出库信息
*/
@Api(tags = "出库信息")
@RestController
@RequestMapping("/voc/deliver")
public class VocDeliverController extends BaseController
{
@Autowired
private VocDeliverService vocDeliverService;
@ApiOperationSupport(author = "Fyc")
@ApiOperation(value = "新增出库信息", notes = "添加商品出库信息")
@PostMapping("/insert")
public AjaxResult insertDeliver(@RequestBody InsertVocDeliverRequestDto insertVocDeliverRequestDto)
{
return vocDeliverService.insertVocDeliver(insertVocDeliverRequestDto);
}
}
|
package HamsterYDS.UntilTheEnd.item.combat;
import HamsterYDS.UntilTheEnd.Config;
import HamsterYDS.UntilTheEnd.internal.ArrowManager;
import HamsterYDS.UntilTheEnd.internal.DisableManager;
import HamsterYDS.UntilTheEnd.internal.EventHelper;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import HamsterYDS.UntilTheEnd.item.ItemManager;
/**
* @author 南外丶仓鼠
* @version V5.1.1
*/
public class BlowArrow3 implements Listener {
public static double damage = ItemManager.itemAttributes.getDouble("BlowArrow3.damage");
public static double range = ItemManager.itemAttributes.getDouble("BlowArrow3.range");
public static int maxDist = ItemManager.itemAttributes.getInt("BlowArrow3.maxDist");
public static int blindPeriod = ItemManager.itemAttributes.getInt("BlowArrow3.blindPeriod");
public BlowArrow3() {
ItemManager.plugin.getServer().getPluginManager().registerEvents(this, ItemManager.plugin);
}
@EventHandler(priority = EventPriority.MONITOR)
public void onRight(PlayerInteractEvent event) {
if (event.isCancelled() && !DisableManager.bypass_right_action_cancelled) return;
Player player = event.getPlayer();
if (!Config.enableWorlds.contains(player.getWorld())) return;
if (!event.hasItem()) return;
if (EventHelper.isRight(event.getAction())) {
ItemStack item = player.getInventory().getItemInMainHand();
if (ItemManager.isSimilar(item, getClass())) {
event.setCancelled(true);
ArrowManager.startFire(le -> {
le.damage(damage);
le.addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS, blindPeriod * 20, 0));
le.addPotionEffect(new PotionEffect(PotionEffectType.NIGHT_VISION, blindPeriod * 20, 0));
}, null, new ItemStack(Material.STONE_SWORD),
player.getLocation().add(0, 1, 0),
maxDist,
ItemManager.plugin.getConfig().getInt("item.blowarrow.autoclear"),
player, range);
}
}
}
}
|
/*
* 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.
*/
package com.intellij.codeInsight.javadoc;
import com.intellij.psi.*;
import com.intellij.util.ArrayUtil;
import org.jetbrains.annotations.NotNull;
import java.awt.*;
import java.lang.reflect.Field;
/**
* @author spleaner
*/
public class ColorUtil {
private ColorUtil() {
}
public static String generatePreviewHtml(@NotNull final Color color) {
return String.format("<div style=\"padding: 1px; width: 52px; height: 32px; background-color: #555555;\"><div style=\"width: 50px; height: 30px; background-color: #%s;\"> </div></div>", com.intellij.ui.ColorUtil.toHex(color));
}
public static void appendColorPreview(final PsiVariable variable, final StringBuilder buffer) {
final PsiExpression initializer = variable.getInitializer();
if (initializer != null) {
final PsiType type = initializer.getType();
if (type != null && "java.awt.Color".equals(type.getCanonicalText())) {
if (initializer instanceof PsiNewExpression) {
final PsiExpressionList argumentList = ((PsiNewExpression) initializer).getArgumentList();
if (argumentList != null) {
final PsiExpression[] expressions = argumentList.getExpressions();
int[] values = ArrayUtil.newIntArray(expressions.length);
float[] values2 = new float[expressions.length];
int i = 0;
int j = 0;
final PsiConstantEvaluationHelper helper = JavaPsiFacade.getInstance(initializer.getProject()).getConstantEvaluationHelper();
for (final PsiExpression each : expressions) {
final Object o = helper.computeConstantExpression(each);
if (o instanceof Integer) {
values[i] = ((Integer) o).intValue();
values[i] = values[i] > 255 && expressions.length > 1 ? 255 : values[i] < 0 ? 0 : values[i];
i++;
} else if (o instanceof Float) {
values2[j] = ((Float) o).floatValue();
values2[j] = values2[j] > 1 ? 1 : values2[j] < 0 ? 0 : values2[j];
j++;
}
}
Color c = null;
if (i == expressions.length) {
switch (values.length) {
case 1:
c = new Color(values[0]);
break;
case 3:
c = new Color(values[0], values[1], values[2]);
break;
case 4:
c = new Color(values[0], values[1], values[2], values[3]);
break;
default:
break;
}
} else if (j == expressions.length) {
switch (values2.length) {
case 3:
c = new Color(values2[0], values2[1], values2[2]);
break;
case 4:
c = new Color(values2[0], values2[1], values2[2], values2[3]);
break;
default:
break;
}
}
if (c != null) {
buffer.append(generatePreviewHtml(c));
}
}
} else if (initializer instanceof PsiReferenceExpression) {
final PsiReference reference = initializer.getReference();
if (reference != null) {
final PsiElement psiElement = reference.resolve();
if (psiElement instanceof PsiField) {
final PsiClass psiClass = ((PsiField) psiElement).getContainingClass();
if (psiClass != null && "java.awt.Color".equals(psiClass.getQualifiedName())) {
try {
Field field = Class.forName("java.awt.Color").getField(((PsiField)psiElement).getName());
final Color c = (Color) field.get(null);
buffer.append(generatePreviewHtml(c));
} catch (Exception e) {
// nothing
}
}
}
}
}
}
}
}
}
|
/*
* Copyright 2019-2021 Bunjlabs
*
* 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 fuga.inject.support;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
class ReflectConstructionProxy<T> implements ConstructionProxy<T> {
private final Constructor<T> constructor;
ReflectConstructionProxy(Constructor<T> constructor) {
this.constructor = constructor;
}
@Override
public T newInstance(Object[] parameters) throws InvocationTargetException {
try {
return constructor.newInstance(parameters);
} catch (InstantiationException | IllegalAccessException e) {
throw new AssertionError(e);
}
}
}
|
package group244.zaicev.com;
import org.junit.Assert;
import org.junit.Test;
import java.util.Iterator;
import java.util.NoSuchElementException;
public class BinaryTreeTest {
private BinaryTree<Integer> tree = new BinaryTree<>();
@Test
public void addTest() {
tree.add(1);
Assert.assertEquals(tree.getSize(), 1);
tree.add(4);
Assert.assertEquals(tree.getSize(), 2);
tree.add(1);
Assert.assertEquals(tree.getSize(), 2);
tree.add(3);
Assert.assertEquals(tree.getSize(), 3);
tree.add(-3);
Assert.assertEquals(tree.getSize(), 4);
tree.add(-2);
Assert.assertEquals(tree.getSize(), 5);
}
@Test
public void isContains() {
Assert.assertFalse(tree.isContains(1));
tree.add(1);
Assert.assertTrue(tree.isContains(1));
Assert.assertFalse(tree.isContains(2));
tree.add(2);
Assert.assertTrue(tree.isContains(2));
Assert.assertFalse(tree.isContains(0));
tree.add(0);
Assert.assertTrue(tree.isContains(0));
}
@Test
public void isEmpty() {
Assert.assertTrue(tree.isEmpty());
tree.add(1);
Assert.assertFalse(tree.isEmpty());
}
@Test
public void removeFirstTest() {
tree.add(1);
tree.add(2);
Assert.assertTrue(tree.isContains(2));
tree.remove(2);
Assert.assertFalse(tree.isContains(2));
tree.remove(1);
Assert.assertTrue(tree.isEmpty());
tree.remove(1);
}
@Test
public void removeSecondTest() {
tree.add(0);
tree.add(-3);
tree.add(-5);
tree.add(-1);
tree.add(4);
tree.add(3);
tree.add(5);
tree.add(2);
tree.add(1);
tree.remove(0);
tree.remove(4);
tree.remove(2);
tree.remove(3);
}
@Test(expected = NoSuchElementException.class)
public void iteratorNoThisElementExceptionTest() {
tree.add(0);
Iterator<Integer> iterator = tree.iterator();
iterator.next();
iterator.next();
}
@Test
public void iteratorHasNextTest() {
Iterator<Integer> iterator = tree.iterator();
Assert.assertFalse(iterator.hasNext());
}
@Test
public void iteratorNextTest() {
tree.add(0);
tree.add(-3);
tree.add(-5);
tree.add(-1);
tree.add(4);
tree.add(3);
tree.add(5);
tree.add(2);
Iterator<Integer> iterator = tree.iterator();
int buff = iterator.next();
for (int i = 0; i < tree.getSize() - 1; i++) {
int temp = iterator.next();
Assert.assertTrue(buff <= temp);
buff = temp;
}
}
@Test
public void foreachTest() {
tree.add(0);
tree.add(-3);
tree.add(-5);
tree.add(-1);
tree.add(4);
tree.add(3);
tree.add(5);
tree.add(2);
int size = 0;
int[] correctBypass = {-5, -3, -1, 0, 2, 3, 4, 5};
for(Integer ignored : tree) {
Assert.assertEquals(correctBypass[size], ignored.intValue());
size++;
}
Assert.assertEquals(tree.getSize(), size);
}
}
|
/**
* Licensed to Jasig under one or more contributor license
* agreements. See the NOTICE file distributed with this work
* for additional information regarding copyright ownership.
* Jasig 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.jasig.portlet.announcements.model;
import java.util.Calendar;
import java.util.Date;
import java.util.Set;
import java.util.TreeSet;
import org.apache.log4j.Logger;
/**
* @author Erik A. Olsson (eolsson@uci.edu)
*
* $LastChangedBy$
* $LastChangedDate$
*/
public class Topic {
/* Announcements for this topic are... */
public static final int PUSHED_FORCED = 1; /* ...Pushed to the audience members and they cannot unsubscribe */
public static final int PUSHED_INITIAL = 2; /* ...Pushed initially, but users can unsubscribe */
public static final int PULLED = 3; /* ...Not pushed to anybody, but target audience members can subscribe (pull) if they want to */
public static final int EMERGENCY = 4; /* A topic that supercedes all other topics */
private static final org.apache.log4j.Logger logger = Logger
.getLogger(Topic.class);
private Set<Announcement> announcements;
private Set<String> admins;
private Set<String> moderators;
private Set<String> authors;
private Set<String> audience;
private String creator;
private String title;
private String description;
private boolean allowRss;
private int subscriptionMethod;
private Long id;
public Topic() {
admins = new TreeSet<String>();
moderators = new TreeSet<String>();
authors = new TreeSet<String>();
audience = new TreeSet<String>();
}
public Set<String> getGroup(String key) {
if (key.compareTo("admins") == 0) {
return getAdmins();
}
else if (key.compareTo("moderators") == 0) {
return getModerators();
}
else if (key.compareTo("authors") == 0) {
return getAuthors();
}
else {
return getAudience();
}
}
public void setGroup(String key, Set<String> members) {
if (key.compareTo("admins") == 0) {
setAdmins(members);
}
else if (key.compareTo("moderators") == 0) {
setModerators(members);
}
else if (key.compareTo("authors") == 0) {
setAuthors(members);
}
else {
setAudience(members);
}
}
public boolean hasId() {
return (this.id != null);
}
/**
* @return the moderators
*/
public Set<String> getModerators() {
return moderators;
}
/**
* @return the creator
*/
public String getCreator() {
return creator;
}
/**
* @return the title
*/
public String getTitle() {
return title;
}
/**
* @return the description
*/
public String getDescription() {
return description;
}
/**
* @return the allowRss
*/
public boolean isAllowRss() {
return allowRss;
}
/**
* @param moderators the moderators to set
*/
public void setModerators(Set<String> moderators) {
this.moderators = moderators;
}
/**
* @param creator the creator to set
*/
public void setCreator(String creator) {
this.creator = creator;
}
/**
* @param title the title to set
*/
public void setTitle(String title) {
this.title = title;
}
/**
* @param description the description to set
*/
public void setDescription(String description) {
this.description = description;
}
/**
* @param allowRss the allowRss to set
*/
public void setAllowRss(boolean allowRss) {
this.allowRss = allowRss;
}
/**
* Returns a list of all announcements in this topic, regardless of status.
* @return the announcements
*/
public Set<Announcement> getAnnouncements() {
return announcements;
}
/**
* Returns a list of all published announcements in this topic. For topics to be included in this
* list, they must also be within their specified display period.
* @return the announcements
*/
public Set<Announcement> getPublishedAnnouncements() {
Set<Announcement> announcementsFiltered = new TreeSet<Announcement>();
Date now = new Date();
if (this.announcements != null) {
for (Announcement ann : this.announcements) {
if (ann.isPublished() && ann.getStartDisplay().before(now)
&& ann.getEndDisplay().after(now)) {
announcementsFiltered.add(ann);
}
}
}
return announcementsFiltered;
}
/**
* Returns a list of all published announcements in this topic. For topics
* to be included in this list, they must also be within their specified
* display period which is the window from yesterday to 30 days ago.
*
* @return the announcements
*/
public Set<Announcement> getHistoricAnnouncements() {
Set<Announcement> announcementsFiltered = new TreeSet<Announcement>();
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, -1); // subtract 1 day from today.
Date now = cal.getTime();
cal = Calendar.getInstance();
cal.add(Calendar.DATE, -30); // subtract 30 days from today.
Date then = cal.getTime();
if (this.announcements != null) {
for (Announcement ann : this.announcements) {
if (logger.isInfoEnabled()) {
logger.info("hist title: " + ann.getTitle() + "\n"
+ "published? " + ann.isPublished() + "\n"
+ "now: " + now + "\n" + "then: " + then + "\n"
+ "startDisplay: " + ann.getStartDisplay() + "\n"
+ "enDisplay: " + ann.getEndDisplay() + "\n"
+ "before now? "
+ ann.getStartDisplay().before(now) + "\n"
+ "after then? " + ann.getEndDisplay().after(then));
}
if (ann.getEndDisplay().before(now)
&& ann.getEndDisplay().after(then)) {
announcementsFiltered.add(ann);
}
}
}
return announcementsFiltered;
}
/**
* Get the current number of displaying announcements
* @return
*/
public int getDisplayingAnnouncementCount() {
return getPublishedAnnouncements().size();
}
/**
* Get the current number of approved & scheduled announcements
* @return
*/
public int getScheduledAnnouncementCount() {
int count = 0;
Date now = new Date();
if (this.announcements != null) {
for (Announcement ann: this.announcements) {
if (ann.isPublished() &&
ann.getStartDisplay().after(now)) {
count++;
}
}
}
return count;
}
/**
* Get the current number of pending announcements
* @return
*/
public int getPendingAnnouncementCount() {
int count = 0;
if (this.announcements != null) {
for (Announcement ann: this.announcements) {
if (!ann.isPublished()) {
count++;
}
}
}
return count;
}
/**
* @return the id
*/
public Long getId() {
return id;
}
/**
* @param announcements the announcements to set
*/
public void setAnnouncements(Set<Announcement> announcements) {
this.announcements = announcements;
}
/**
* @param id the id to set
*/
public void setId(Long id) {
this.id = id;
}
/**
* @return the authors
*/
public Set<String> getAuthors() {
return authors;
}
/**
* @param authors the authors to set
*/
public void setAuthors(Set<String> authors) {
this.authors = authors;
}
/**
* @return the admins
*/
public Set<String> getAdmins() {
return admins;
}
/**
* @return the audience
*/
public Set<String> getAudience() {
return audience;
}
/**
* @param admins the admins to set
*/
public void setAdmins(Set<String> admins) {
this.admins = admins;
}
/**
* @param audience the audience to set
*/
public void setAudience(Set<String> audience) {
this.audience = audience;
}
/**
* @return the subscriptionMethod
*/
public int getSubscriptionMethod() {
return subscriptionMethod;
}
/**
* @param subscriptionMethod the subscriptionMethod to set
*/
public void setSubscriptionMethod(int subscriptionMethod) {
this.subscriptionMethod = subscriptionMethod;
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
Topic t = (Topic) obj;
return (t.getId().compareTo(this.id) == 0);
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "Topic [allowRss=" + allowRss + ", creator=" + creator
+ ", description=" + description + ", id=" + id
+ ", moderators=" + moderators + ", subscriptionMethod="
+ subscriptionMethod + ", title=" + title + "]";
}
}
|
/*
* Copyright (C) 2012 DataStax 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.datastax.driver.core.policies;
import com.datastax.driver.core.ConsistencyLevel;
import com.datastax.driver.core.Statement;
import com.datastax.driver.core.WriteType;
public class AlwaysIgnoreRetryPolicy implements RetryPolicy {
public static final AlwaysIgnoreRetryPolicy INSTANCE = new AlwaysIgnoreRetryPolicy();
private AlwaysIgnoreRetryPolicy() {}
public RetryDecision onReadTimeout(Statement statement, ConsistencyLevel cl, int requiredResponses, int receivedResponses, boolean dataRetrieved, int nbRetry) {
return RetryDecision.ignore();
}
public RetryDecision onWriteTimeout(Statement statement, ConsistencyLevel cl, WriteType writeType, int requiredAcks, int receivedAcks, int nbRetry) {
return RetryDecision.ignore();
}
public RetryDecision onUnavailable(Statement statement, ConsistencyLevel cl, int requiredReplica, int aliveReplica, int nbRetry) {
return RetryDecision.ignore();
}
}
|
package edu.fiuba.algo3.modelo.batallas_de_dados;
public class DadoPersonalizado implements Dado {
private final int valor;
public DadoPersonalizado(int valor) {
this.valor = valor;
}
@Override
public void lanzar() {
}
@Override
public int obtenerValor() {
return this.valor;
}
@Override
public int compareTo(Dado otroDado) {
return Integer.compare(this.obtenerValor(), otroDado.obtenerValor());
}
@Override
public boolean esMayorQue(Dado otroDado) {
return this.compareTo(otroDado) > 0;
}
}
|
package lab.chabingba.eventorganizer.Visual;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.AbstractList;
import lab.chabingba.eventorganizer.R;
/**
* Created by Tsvetan on 2015-05-27.
*/
public class CustomSpinnerItem extends ArrayAdapter<String> {
private AbstractList<String> items;
public CustomSpinnerItem(Context context, AbstractList<String> items) {
super(context, R.layout.custom_spinner, items);
this.items = items;
}
@Override
public View getDropDownView(int position, View convertView, ViewGroup parent) {
return getCustomView(position, convertView, parent);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
return getCustomView(position, convertView, parent);
}
public View getCustomView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(getContext());
View mySpinner = inflater.inflate(R.layout.custom_spinner, parent, false);
TextView tvSpinnerItem = (TextView) mySpinner.findViewById(R.id.tvSpinnerItem);
tvSpinnerItem.setText(this.items.get(position));
return mySpinner;
}
}
|
package uk.gov.companieshouse.service;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import uk.gov.companieshouse.TestData;
import uk.gov.companieshouse.TestUtil;
import uk.gov.companieshouse.client.ChipsRestClient;
import uk.gov.companieshouse.config.ChipsConfiguration;
import uk.gov.companieshouse.database.entity.AppealEntity;
import uk.gov.companieshouse.database.entity.CreatedByEntity;
import uk.gov.companieshouse.database.entity.ReasonEntity;
import uk.gov.companieshouse.exception.ChipsServiceException;
import uk.gov.companieshouse.mapper.AppealMapper;
import uk.gov.companieshouse.model.Appeal;
import uk.gov.companieshouse.model.ChipsContact;
import uk.gov.companieshouse.model.CreatedBy;
import uk.gov.companieshouse.model.Reason;
import uk.gov.companieshouse.repository.AppealRepository;
import uk.gov.companieshouse.util.ChipsContactDescriptionFormatter;
@ExtendWith(MockitoExtension.class)
class AppealServiceTest {
private static final String TEST_CHIPS_URL = "http://someurl";
private static final ChipsContact CONTACT = new ChipsContact();
private static final String USER_ID = "user_id";
private static final String APPEAL_ID = "appeal_id";
private static final String PENALTY_REF = "penalty_reference";
private static final String COMPANY_NUMBER = "company_number";
private static final String UNABLE_TO_SAVE_APPEAL_ERROR_MESSAGE = "Appeal not saved in database for companyNumber: 12345678, penaltyReference: A1234567 and userId: USER#1";
@Mock
private ChipsContactDescriptionFormatter chipsContactDescriptionFormatter;
@InjectMocks
private AppealService appealService;
@Mock
private AppealMapper appealMapper;
@Mock
private AppealRepository appealRepository;
@Mock
private ChipsRestClient chipsRestClient;
@Mock
private ChipsConfiguration chipsConfiguration;
@Mock
private EmailService emailService;
@Test
void testCreateAppeal_returnsResourceId() {
CreatedBy createdBy = TestUtil.buildCreatedBy();
CreatedByEntity createdByEntity = TestUtil.buildCreatedByEntity();
ReasonEntity reasonEntity = TestUtil.createReasonEntityWithOther();
Reason reason = TestUtil.createReasonWithOther();
when(appealMapper.map(any(Appeal.class))).thenReturn(TestUtil.createAppealEntity(null, createdByEntity, reasonEntity));
when(appealRepository.insert(any(AppealEntity.class))).thenReturn(TestUtil.createAppealEntity(TestData.ID, createdByEntity, reasonEntity));
assertEquals(TestData.ID, appealService.saveAppeal(TestUtil.createAppeal(createdBy, reason), TestData.USER_ID));
}
@Test
void testCreateAppeal_verify_createdBy_createdAt_setOnAppeal() {
CreatedBy createdBy = TestUtil.buildCreatedBy();
CreatedByEntity createdByEntity = TestUtil.buildCreatedByEntity();
ReasonEntity reasonEntity = TestUtil.createReasonEntityWithOther();
Reason reason = TestUtil.createReasonWithOther();
when(appealMapper.map(any(Appeal.class))).thenReturn(TestUtil.createAppealEntity(null, createdByEntity, reasonEntity));
when(appealRepository.insert(any(AppealEntity.class))).thenReturn(TestUtil.createAppealEntity(TestData.ID, createdByEntity, reasonEntity));
appealService.saveAppeal(TestUtil.createAppeal(createdBy, reason), TestData.USER_ID);
ArgumentCaptor<AppealEntity> appealArgumentCaptor = ArgumentCaptor.forClass(AppealEntity.class);
verify(appealRepository).insert(appealArgumentCaptor.capture());
assertEquals(TestData.USER_ID, appealArgumentCaptor.getValue().getCreatedBy().getId());
assertNotNull(appealArgumentCaptor.getValue().getCreatedAt());
}
@Test
void testCreateAppeal_throwsExceptionIfNoResourceIdReturned() {
CreatedBy createdBy = TestUtil.buildCreatedBy();
CreatedByEntity createdByEntity = TestUtil.buildCreatedByEntity();
ReasonEntity reasonEntity = TestUtil.createReasonEntityWithOther();
Reason reason = TestUtil.createReasonWithOther();
when(appealMapper.map(any(Appeal.class))).thenReturn(TestUtil.createAppealEntity(null, createdByEntity, reasonEntity));
when(appealRepository.insert(any(AppealEntity.class))).thenReturn(TestUtil.createAppealEntity(null, createdByEntity, reasonEntity));
String message = assertThrows(Exception.class, () -> appealService.saveAppeal(TestUtil.createAppeal(createdBy, reason), TestData.USER_ID)).getMessage();
assertEquals(UNABLE_TO_SAVE_APPEAL_ERROR_MESSAGE, message);
}
@Test
void testCreateAppeal_throwsExceptionIfUnableToInsertData() {
CreatedBy createdBy = TestUtil.buildCreatedBy();
CreatedByEntity createdByEntity = TestUtil.buildCreatedByEntity();
ReasonEntity reasonEntity = TestUtil.createReasonEntityWithOther();
Reason reason = TestUtil.createReasonWithOther();
when(appealMapper.map(any(Appeal.class))).thenReturn(TestUtil.createAppealEntity(null, createdByEntity, reasonEntity));
when(appealRepository.insert(any(AppealEntity.class))).thenReturn(null);
String message = assertThrows(Exception.class, () -> appealService.saveAppeal(TestUtil.createAppeal(createdBy, reason), TestData.USER_ID)).getMessage();
assertEquals(UNABLE_TO_SAVE_APPEAL_ERROR_MESSAGE, message);
}
@Test
void testCreateAppealChipsEnabled_returnsResourceId() {
CreatedBy createdBy = TestUtil.buildCreatedBy();
CreatedByEntity createdByEntity = TestUtil.buildCreatedByEntity();
ReasonEntity reasonEntity = TestUtil.createReasonEntityWithOther();
Reason reason = TestUtil.createReasonWithOther();
when(chipsConfiguration.isChipsEnabled()).thenReturn(true);
when(chipsConfiguration.getChipsRestServiceUrl()).thenReturn(TEST_CHIPS_URL);
when(chipsContactDescriptionFormatter.buildChipsContact(any(Appeal.class))).thenReturn(CONTACT);
when(appealMapper.map(any(Appeal.class))).thenReturn(TestUtil.createAppealEntity(null, createdByEntity, reasonEntity));
when(appealRepository.insert(any(AppealEntity.class))).thenReturn(TestUtil.createAppealEntity(TestData.ID, createdByEntity, reasonEntity));
assertEquals(TestData.ID, appealService.saveAppeal(TestUtil.createAppeal(createdBy, reason), TestData.USER_ID));
}
@Test
void testCreateAppeal_throwsExceptionIfChipsReturnsError() {
CreatedBy createdBy = TestUtil.buildCreatedBy();
CreatedByEntity createdByEntity = TestUtil.buildCreatedByEntity();
ReasonEntity reasonEntity = TestUtil.createReasonEntityWithOther();
Reason reason = TestUtil.createReasonWithOther();
Appeal appeal = TestUtil.createAppeal(createdBy, reason);
when(chipsConfiguration.isChipsEnabled()).thenReturn(true);
when(chipsConfiguration.getChipsRestServiceUrl()).thenReturn(TEST_CHIPS_URL);
when(chipsContactDescriptionFormatter.buildChipsContact(appeal)).thenReturn(CONTACT);
doThrow(ChipsServiceException.class).when(chipsRestClient).createContactInChips(CONTACT, TEST_CHIPS_URL);
when(appealMapper.map(any(Appeal.class))).thenReturn(TestUtil.createAppealEntity(null, createdByEntity, reasonEntity));
when(appealRepository.insert(any(AppealEntity.class))).thenReturn(TestUtil.createAppealEntity(TestData.ID, createdByEntity, reasonEntity));
assertThrows(ChipsServiceException.class, () -> appealService.saveAppeal(appeal, TestData.USER_ID));
verify(appealRepository).insert(TestUtil.createAppealEntity(null, createdByEntity, reasonEntity));
}
@Test
void testGetAppealById_returnsAppeal() {
CreatedBy createdBy = TestUtil.buildCreatedBy();
CreatedByEntity createdByEntity = TestUtil.buildCreatedByEntity();
ReasonEntity reasonEntity = TestUtil.createReasonEntityWithOther();
Reason reason = TestUtil.createReasonWithOther();
when(appealRepository.findById(any(String.class))).thenReturn(
Optional.of(TestUtil.createAppealEntity(TestData.ID, createdByEntity, reasonEntity)));
when(appealMapper.map(any(AppealEntity.class))).thenReturn(TestUtil.createAppeal(createdBy, reason));
Appeal appeal = appealService.getAppeal(TestData.ID).orElseThrow();
assertEquals(TestData.COMPANY_NUMBER, appeal.getPenaltyIdentifier().getCompanyNumber());
assertEquals(TestData.PENALTY_REFERENCE, appeal.getPenaltyIdentifier().getPenaltyReference());
assertEquals(TestData.TITLE, appeal.getReason().getOther().getTitle());
assertEquals(TestData.DESCRIPTION, appeal.getReason().getOther().getDescription());
assertEquals(1, appeal.getReason().getOther().getAttachments().size());
assertEquals(TestData.ATTACHMENT_ID, appeal.getReason().getOther().getAttachments().get(0).getId());
assertEquals(TestData.ATTACHMENT_NAME, appeal.getReason().getOther().getAttachments().get(0).getName());
assertEquals(TestData.CONTENT_TYPE, appeal.getReason().getOther().getAttachments().get(0).getContentType());
assertEquals(TestData.ATTACHMENT_SIZE, appeal.getReason().getOther().getAttachments().get(0).getSize());
}
@Test
void testGetAppealById_returnsEmptyAppeal() {
when(appealRepository.findById(any(String.class))).thenReturn(Optional.empty());
Optional<Appeal> appeal = appealService.getAppeal(TestData.ID);
assertFalse(appeal.isPresent());
}
@Test
void testGetAppealsByPenaltyReference_returnsListOfAppeals() {
CreatedBy createdBy = TestUtil.buildCreatedBy();
CreatedByEntity createdByEntity = TestUtil.buildCreatedByEntity();
ReasonEntity reasonEntity = TestUtil.createReasonEntityWithOther();
Reason reason = TestUtil.createReasonWithOther();
when(appealRepository.findByPenaltyReference(any(String.class))).thenReturn(
List.of(TestUtil.createAppealEntity(TestData.PENALTY_REFERENCE, createdByEntity, reasonEntity)));
when(appealMapper.map(any(AppealEntity.class))).thenReturn(TestUtil.createAppeal(createdBy, reason));
List<Appeal> appealList = appealService.getAppealsByPenaltyReference(
TestData.PENALTY_REFERENCE);
Appeal appeal = appealList.get(0);
assertEquals(1, appealList.size());
assertEquals(TestData.PENALTY_REFERENCE, appeal.getPenaltyIdentifier().getPenaltyReference());
assertEquals(TestData.COMPANY_NUMBER, appeal.getPenaltyIdentifier().getCompanyNumber());
assertEquals(TestData.TITLE, appeal.getReason().getOther().getTitle());
assertEquals(TestData.DESCRIPTION, appeal.getReason().getOther().getDescription());
assertEquals(1, appeal.getReason().getOther().getAttachments().size());
assertEquals(TestData.ATTACHMENT_ID, appeal.getReason().getOther().getAttachments().get(0).getId());
assertEquals(TestData.ATTACHMENT_NAME, appeal.getReason().getOther().getAttachments().get(0).getName());
assertEquals(TestData.CONTENT_TYPE, appeal.getReason().getOther().getAttachments().get(0).getContentType());
assertEquals(TestData.ATTACHMENT_SIZE, appeal.getReason().getOther().getAttachments().get(0).getSize());
}
@Test
void testGetMultipleAppealByPenaltyReference_returnsListOfAppeals() {
CreatedBy createdBy = TestUtil.buildCreatedBy();
CreatedByEntity createdByEntity = TestUtil.buildCreatedByEntity();
ReasonEntity reasonEntity = TestUtil.createReasonEntityWithOther();
Reason reason = TestUtil.createReasonWithOther();
when(appealRepository.findByPenaltyReference(any(String.class))).thenReturn(
List.of(TestUtil.createAppealEntity(TestData.PENALTY_REFERENCE, createdByEntity, reasonEntity),
TestUtil.createAppealEntity(TestData.PENALTY_REFERENCE, createdByEntity, reasonEntity)));
when(appealMapper.map(any(AppealEntity.class))).thenReturn(TestUtil.createAppeal(createdBy,reason));
List<Appeal> appealList = appealService.getAppealsByPenaltyReference(TestData.PENALTY_REFERENCE);
assertEquals(2, appealList.size());
}
@Test
void testGetAppealsByPenaltyReference_returnsEmptyListOfAppeals() {
when(appealRepository.findByPenaltyReference(any(String.class))).thenReturn(List.of());
List<Appeal> appealList = appealService.getAppealsByPenaltyReference(TestData.PENALTY_REFERENCE);
assertTrue(appealList.isEmpty());
}
@Test
void testCreateDebugMapWithAppeal_returnsMapWithAppealDetails() {
Map<String, Object> returnedMap = appealService.createAppealDebugMap(TestData.USER_ID,
TestUtil.createAppeal(TestUtil.buildCreatedBy(), TestUtil.createReasonWithOther()));
assertEquals(4, returnedMap.size());
assertEquals(TestData.ID, returnedMap.get(APPEAL_ID));
assertEquals(TestData.USER_ID, returnedMap.get(USER_ID));
assertEquals(TestData.PENALTY_REFERENCE, returnedMap.get(PENALTY_REF));
assertEquals(TestData.COMPANY_NUMBER, returnedMap.get(COMPANY_NUMBER));
}
@Test
void testCreateDebugMapWithoutAppeal_retursnMapWithID(){
Map<String, Object> returnedMap = appealService.createDebugMapWithoutAppeal(TestData.ID);
assertEquals(TestData.ID, returnedMap.get(APPEAL_ID));
}
}
|
package com.example.android.sunshine.sync;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import com.example.android.sunshine.data.SunshinePreferences;
import com.firebase.jobdispatcher.JobParameters;
import com.firebase.jobdispatcher.JobService;
/**
* Clase que contiene el código que ejecutará el job.
*
* Se utiliza una AsyncTask para realizar una actividad
* cuyo punto de ejecución será en segundo plano (conexión
* a internet, acceso a base de datos... etc)
*/
public class SunshineFirebaseJobService extends JobService {
private AsyncTask<Void, Void, Void> mFetchWeatherTask;
@Override
public boolean onStartJob(final JobParameters jobParameters) {
Log.d("sunshine_sync", "Arrancando el job de sincronización");
mFetchWeatherTask = new AsyncTask<Void, Void, Void>(){
@Override
protected Void doInBackground(Void... voids) {
Context context = getApplicationContext();
SunshinePreferences preferences = new SunshinePreferences(context);
SunshineSyncTask syncTask = new SunshineSyncTask(preferences);
syncTask.syncWeather(
preferences.getPreferredWeatherLocation(),
preferences.getTemperatureUnits(),
context);
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
jobFinished(jobParameters, false);
}
};
mFetchWeatherTask.execute();
return true; // al devolver true se indica que si falla, se desea reinicialización
}
@Override
public boolean onStopJob(JobParameters job) {
return false;
}
}
|
// Copyright (c) FIRST and other WPILib contributors.
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
package frc.robot.commands;
import edu.wpi.first.wpilibj.Timer;
import edu.wpi.first.wpilibj2.command.CommandBase;
import frc.robot.subsystems.Conveyer;
import frc.robot.subsystems.Gun;
import frc.robot.subsystems.Transfer;
/** An example command that uses an example subsystem. */
public class LowFire extends CommandBase {
@SuppressWarnings({"PMD.UnusedPrivateField", "PMD.SingularField"})
private final Conveyer m_conveyer;
private final Transfer m_transfer;
private final Gun m_gun;
/**
* Creates a new ExampleCommand.
*
* @param subsystem The subsystem used by this command.
*/
public LowFire(Conveyer conveyer, Transfer transfer, Gun gun) {
m_conveyer = conveyer;
m_gun = gun;
m_transfer = transfer;
// Use addRequirements() here to declare subsystem dependencies.
addRequirements(m_conveyer);
addRequirements(m_gun);
addRequirements(m_transfer);
}
// Called when the command is initially scheduled.
@Override
public void initialize() {
m_gun.setRaw(0.25);
Timer.delay(2);
m_conveyer.setRaw(0.6);
m_transfer.setRaw(-0.65);
}
// Called every time the scheduler runs while the command is scheduled.
@Override
public void execute() {
}
// Called once the command ends or is interrupted.
@Override
public void end(boolean interrupted) {
m_conveyer.setRaw(0);
m_gun.setRaw(0);
m_transfer.setRaw(0);
}
// Returns true when the command should end.
@Override
public boolean isFinished() {
return false;
}
}
|
package com.mimose.component.deduplicate.starter;
/**
* @author mimose
* @description
* @date 2021/5/15
*/
public interface IPartStarter {
/**
* start
*/
void start();
}
|
/*******************************************************************************
* Copyright 2014 Felipe Takiyama
*
* 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 br.usp.poli.takiyama.acfove;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import br.usp.poli.takiyama.cfove.StdParfactor;
import br.usp.poli.takiyama.cfove.StdParfactor.StdParfactorBuilder;
import br.usp.poli.takiyama.common.Marginal;
import br.usp.poli.takiyama.common.Parfactor;
import br.usp.poli.takiyama.common.StdMarginal.StdMarginalBuilder;
import br.usp.poli.takiyama.prv.Prv;
import br.usp.poli.takiyama.prv.Prvs;
import br.usp.poli.takiyama.prv.RandomVariableSet;
import br.usp.poli.takiyama.utils.Sets;
final class GlobalSumOut implements MacroOperation {
// The marginal where elimination will take place
private final Marginal marginal;
// The set of random variables to eliminate
private final RandomVariableSet eliminables;
/*
* These variables are redundant. If cost is INFINITY, then this operation
* is automatically impossible.
*/
private int cost;
private boolean isPossible;
private static int infinity = (int) Double.POSITIVE_INFINITY;
public GlobalSumOut(Marginal marginal, RandomVariableSet eliminables) {
this.marginal = marginal;
this.eliminables = eliminables;
calculateFeasibility();
}
/*
* Calculates the feasibility of this operation. This operation is possible
* if all parfactors involving the variables being eliminated can be
* multiplied and those variables can be summed out from the product.
*/
private void calculateFeasibility() {
setCost(infinity);
RandomVariableSet elim = RandomVariableSet.getInstance(eliminables.prv().getCanonicalForm(), eliminables.constraints());
if (Prvs.areDisjoint(elim, marginal.preservable())) {
Queue<Parfactor> queue = new LinkedList<Parfactor>(marginal.distribution().toSet());
Parfactor result = new StdParfactorBuilder().build();
for (Parfactor candidate : queue) {
if (containsEliminable(candidate)) {
if (result.isMultipliable(candidate)) {
result = result.multiply(candidate);
} else {
// contains eliminables but cannot be multiplied: be sure
// to shatter before!
return;
}
}
}
if (result.isEliminable(eliminables)) {
int f = result.factor().size();
int v = eliminables.range().size();
setCost(f / v);
}
}
}
/*
* Updates cost and isPossible. Helps to keep consistency.
*/
private void setCost(int c) {
if (c < infinity) {
this.cost = c;
this.isPossible = true;
} else {
this.cost = infinity;
this.isPossible = false;
}
}
/**
* Returns true if the specified parfactor contains the set of variables
* to eliminate.
*/
private boolean containsEliminable(Parfactor candidate) {
/*
* In theory, marginal is shattered, so candidate either contains
* eliminables or not.
*/
RandomVariableSet elim = RandomVariableSet.getInstance(eliminables.prv().getCanonicalForm(), Sets.union(eliminables.prv().constraints(), eliminables.constraints()));
List<Prv> variables = candidate.prvs();
for (Prv prv : variables) {
RandomVariableSet rvs = RandomVariableSet.getInstance(prv.getCanonicalForm(), candidate.constraints());
if (rvs.equals(elim)) {
return true;
}
}
return false;
}
@Override
public Marginal run() {
if (isPossible) {
Parfactor result = new StdParfactorBuilder().build();
StdMarginalBuilder marginalResult = new StdMarginalBuilder();
marginalResult.add(marginal);
// Multiplies all parfactors that involve the eliminable PRV
for (Parfactor candidate : marginal) {
if (containsEliminable(candidate)) {
result = result.multiply(candidate);
marginalResult.remove(candidate);
}
}
// Sums out the eliminable if possible - actually it should be possible at this point
//if (Sets.setOf(eliminables.prv().parameters()).equals(result.logicalVariables())) {
try {
result = result.sumOut(eliminables.prv());
} catch (IllegalArgumentException e) {
result = new StdParfactor.StdParfactorBuilder().build();
}
//}
// Adds the result to marginal result if not constant (constant
// parfactors are irrelevant)
if (!result.isConstant()) {
marginalResult.add(result);
}
return marginalResult.build();
} else {
return marginal;
}
}
@Override
public int cost() {
return cost;
}
@Override
public int numberOfRandomVariablesEliminated() {
// cost = infinity means this operation is impossible, thus no vars
// can be eliminated.
if (cost() == infinity) {
return 0;
} else {
return eliminables.prv().groundSetSize(eliminables.constraints());
}
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("GLOBAL-SUM-OUT").append(" ").append(eliminables);
return builder.toString();
}
}
|
/* Generic definitions */
/* Assertions (useful to generate conditional code) */
/* Current type and class (and size, if applicable) */
/* Value methods */
/* Interfaces (keys) */
/* Interfaces (values) */
/* Abstract implementations (keys) */
/* Abstract implementations (values) */
/* Static containers (keys) */
/* Static containers (values) */
/* Implementations */
/* Synchronized wrappers */
/* Unmodifiable wrappers */
/* Other wrappers */
/* Methods (keys) */
/* Methods (values) */
/* Methods (keys/values) */
/* Methods that have special names depending on keys (but the special names depend on values) */
/* Equality */
/* Object/Reference-only definitions (keys) */
/* Primitive-type-only definitions (keys) */
/* Object/Reference-only definitions (values) */
/* Primitive-type-only definitions (values) */
/*
* Copyright (C) 2002-2013 Sebastiano Vigna
*
* 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 it.unimi.dsi.fastutil.shorts;
import it.unimi.dsi.fastutil.objects.ObjectSet;
import it.unimi.dsi.fastutil.objects.ObjectSets;
import it.unimi.dsi.fastutil.ints.IntCollection;
import it.unimi.dsi.fastutil.ints.IntCollections;
import it.unimi.dsi.fastutil.ints.IntSets;
import java.util.Map;
/** A class providing static methods and objects that do useful things with type-specific maps.
*
* @see it.unimi.dsi.fastutil.Maps
* @see java.util.Collections
*/
public class Short2IntMaps {
private Short2IntMaps() {}
/** An immutable class representing an empty type-specific map.
*
* <P>This class may be useful to implement your own in case you subclass
* a type-specific map.
*/
public static class EmptyMap extends Short2IntFunctions.EmptyFunction implements Short2IntMap , java.io.Serializable, Cloneable {
private static final long serialVersionUID = -7046029254386353129L;
protected EmptyMap() {}
public boolean containsValue( final int v ) { return false; }
public void putAll( final Map<? extends Short, ? extends Integer> m ) { throw new UnsupportedOperationException(); }
@SuppressWarnings("unchecked")
public ObjectSet<Short2IntMap.Entry > short2IntEntrySet() { return ObjectSets.EMPTY_SET; }
@SuppressWarnings("unchecked")
public ShortSet keySet() { return ShortSets.EMPTY_SET; }
@SuppressWarnings("unchecked")
public IntCollection values() { return IntSets.EMPTY_SET; }
public boolean containsValue( final Object ov ) { return false; }
private Object readResolve() { return EMPTY_MAP; }
public Object clone() { return EMPTY_MAP; }
public boolean isEmpty() { return true; }
@SuppressWarnings({ "rawtypes", "unchecked" })
public ObjectSet<Map.Entry<Short, Integer>> entrySet() { return (ObjectSet)short2IntEntrySet(); }
public int hashCode() { return 0; }
public boolean equals( final Object o ) {
if ( ! ( o instanceof Map ) ) return false;
return ((Map<?,?>)o).isEmpty();
}
public String toString() { return "{}"; }
}
/** An empty type-specific map (immutable). It is serializable and cloneable. */
@SuppressWarnings("rawtypes")
public static final EmptyMap EMPTY_MAP = new EmptyMap();
/** An immutable class representing a type-specific singleton map.
*
* <P>This class may be useful to implement your own in case you subclass
* a type-specific map.
*/
public static class Singleton extends Short2IntFunctions.Singleton implements Short2IntMap , java.io.Serializable, Cloneable {
private static final long serialVersionUID = -7046029254386353129L;
protected transient volatile ObjectSet<Short2IntMap.Entry > entries;
protected transient volatile ShortSet keys;
protected transient volatile IntCollection values;
protected Singleton( final short key, final int value ) {
super( key, value );
}
public boolean containsValue( final int v ) { return ( (value) == (v) ); }
public boolean containsValue( final Object ov ) { return ( (((((Integer)(ov)).intValue()))) == (value) ); }
public void putAll( final Map<? extends Short, ? extends Integer> m ) { throw new UnsupportedOperationException(); }
public ObjectSet<Short2IntMap.Entry > short2IntEntrySet() { if ( entries == null ) entries = ObjectSets.singleton( (Short2IntMap.Entry )new SingletonEntry() ); return entries; }
public ShortSet keySet() { if ( keys == null ) keys = ShortSets.singleton( key ); return keys; }
public IntCollection values() { if ( values == null ) values = IntSets.singleton( value ); return values; }
protected class SingletonEntry implements Short2IntMap.Entry , Map.Entry<Short,Integer> {
public Short getKey() { return (Short.valueOf(Singleton.this.key)); }
public Integer getValue() { return (Integer.valueOf(Singleton.this.value)); }
public short getShortKey() { return Singleton.this.key; }
public int getIntValue() { return Singleton.this.value; }
public int setValue( final int value ) { throw new UnsupportedOperationException(); }
public Integer setValue( final Integer value ) { throw new UnsupportedOperationException(); }
public boolean equals( final Object o ) {
if (!(o instanceof Map.Entry)) return false;
Map.Entry<?,?> e = (Map.Entry<?,?>)o;
return ( (Singleton.this.key) == (((((Short)(e.getKey())).shortValue()))) ) && ( (Singleton.this.value) == (((((Integer)(e.getValue())).intValue()))) );
}
public int hashCode() { return (Singleton.this.key) ^ (Singleton.this.value); }
public String toString() { return Singleton.this.key + "->" + Singleton.this.value; }
}
public boolean isEmpty() { return false; }
@SuppressWarnings({ "rawtypes", "unchecked" })
public ObjectSet<Map.Entry<Short, Integer>> entrySet() { return (ObjectSet)short2IntEntrySet(); }
public int hashCode() { return (key) ^ (value); }
public boolean equals( final Object o ) {
if ( o == this ) return true;
if ( ! ( o instanceof Map ) ) return false;
Map<?,?> m = (Map<?,?>)o;
if ( m.size() != 1 ) return false;
return entrySet().iterator().next().equals( m.entrySet().iterator().next() );
}
public String toString() { return "{" + key + "=>" + value + "}"; }
}
/** Returns a type-specific immutable map containing only the specified pair. The returned map is serializable and cloneable.
*
* <P>Note that albeit the returned map is immutable, its default return value may be changed.
*
* @param key the only key of the returned map.
* @param value the only value of the returned map.
* @return a type-specific immutable map containing just the pair <code><key,value></code>.
*/
public static Short2IntMap singleton( final short key, int value ) {
return new Singleton ( key, value );
}
/** Returns a type-specific immutable map containing only the specified pair. The returned map is serializable and cloneable.
*
* <P>Note that albeit the returned map is immutable, its default return value may be changed.
*
* @param key the only key of the returned map.
* @param value the only value of the returned map.
* @return a type-specific immutable map containing just the pair <code><key,value></code>.
*/
public static Short2IntMap singleton( final Short key, final Integer value ) {
return new Singleton ( ((key).shortValue()), ((value).intValue()) );
}
/** A synchronized wrapper class for maps. */
public static class SynchronizedMap extends Short2IntFunctions.SynchronizedFunction implements Short2IntMap , java.io.Serializable {
private static final long serialVersionUID = -7046029254386353129L;
protected final Short2IntMap map;
protected transient volatile ObjectSet<Short2IntMap.Entry > entries;
protected transient volatile ShortSet keys;
protected transient volatile IntCollection values;
protected SynchronizedMap( final Short2IntMap m, final Object sync ) {
super( m, sync );
this.map = m;
}
protected SynchronizedMap( final Short2IntMap m ) {
super( m );
this.map = m;
}
public int size() { synchronized( sync ) { return map.size(); } }
public boolean containsKey( final short k ) { synchronized( sync ) { return map.containsKey( k ); } }
public boolean containsValue( final int v ) { synchronized( sync ) { return map.containsValue( v ); } }
public int defaultReturnValue() { synchronized( sync ) { return map.defaultReturnValue(); } }
public void defaultReturnValue( final int defRetValue ) { synchronized( sync ) { map.defaultReturnValue( defRetValue ); } }
public int put( final short k, final int v ) { synchronized( sync ) { return map.put( k, v ); } }
//public void putAll( final MAP KEY_VALUE_EXTENDS_GENERIC c ) { synchronized( sync ) { map.putAll( c ); } }
public void putAll( final Map<? extends Short, ? extends Integer> m ) { synchronized( sync ) { map.putAll( m ); } }
public ObjectSet<Short2IntMap.Entry > short2IntEntrySet() { if ( entries == null ) entries = ObjectSets.synchronize( map.short2IntEntrySet(), sync ); return entries; }
public ShortSet keySet() { if ( keys == null ) keys = ShortSets.synchronize( map.keySet(), sync ); return keys; }
public IntCollection values() { if ( values == null ) return IntCollections.synchronize( map.values(), sync ); return values; }
public void clear() { synchronized( sync ) { map.clear(); } }
public String toString() { synchronized( sync ) { return map.toString(); } }
public Integer put( final Short k, final Integer v ) { synchronized( sync ) { return map.put( k, v ); } }
public int remove( final short k ) { synchronized( sync ) { return map.remove( k ); } }
public int get( final short k ) { synchronized( sync ) { return map.get( k ); } }
public boolean containsKey( final Object ok ) { synchronized( sync ) { return map.containsKey( ok ); } }
public boolean containsValue( final Object ov ) { synchronized( sync ) { return map.containsValue( ov ); } }
public boolean isEmpty() { synchronized( sync ) { return map.isEmpty(); } }
public ObjectSet<Map.Entry<Short, Integer>> entrySet() { synchronized( sync ) { return map.entrySet(); } }
public int hashCode() { synchronized( sync ) { return map.hashCode(); } }
public boolean equals( final Object o ) { synchronized( sync ) { return map.equals( o ); } }
}
/** Returns a synchronized type-specific map backed by the given type-specific map.
*
* @param m the map to be wrapped in a synchronized map.
* @return a synchronized view of the specified map.
* @see java.util.Collections#synchronizedMap(Map)
*/
public static Short2IntMap synchronize( final Short2IntMap m ) { return new SynchronizedMap ( m ); }
/** Returns a synchronized type-specific map backed by the given type-specific map, using an assigned object to synchronize.
*
* @param m the map to be wrapped in a synchronized map.
* @param sync an object that will be used to synchronize the access to the map.
* @return a synchronized view of the specified map.
* @see java.util.Collections#synchronizedMap(Map)
*/
public static Short2IntMap synchronize( final Short2IntMap m, final Object sync ) { return new SynchronizedMap ( m, sync ); }
/** An unmodifiable wrapper class for maps. */
public static class UnmodifiableMap extends Short2IntFunctions.UnmodifiableFunction implements Short2IntMap , java.io.Serializable {
private static final long serialVersionUID = -7046029254386353129L;
protected final Short2IntMap map;
protected transient volatile ObjectSet<Short2IntMap.Entry > entries;
protected transient volatile ShortSet keys;
protected transient volatile IntCollection values;
protected UnmodifiableMap( final Short2IntMap m ) {
super( m );
this.map = m;
}
public int size() { return map.size(); }
public boolean containsKey( final short k ) { return map.containsKey( k ); }
public boolean containsValue( final int v ) { return map.containsValue( v ); }
public int defaultReturnValue() { throw new UnsupportedOperationException(); }
public void defaultReturnValue( final int defRetValue ) { throw new UnsupportedOperationException(); }
public int put( final short k, final int v ) { throw new UnsupportedOperationException(); }
//public void putAll( final MAP KEY_VALUE_EXTENDS_GENERIC c ) { throw new UnsupportedOperationException(); }
public void putAll( final Map<? extends Short, ? extends Integer> m ) { throw new UnsupportedOperationException(); }
public ObjectSet<Short2IntMap.Entry > short2IntEntrySet() { if ( entries == null ) entries = ObjectSets.unmodifiable( map.short2IntEntrySet() ); return entries; }
public ShortSet keySet() { if ( keys == null ) keys = ShortSets.unmodifiable( map.keySet() ); return keys; }
public IntCollection values() { if ( values == null ) return IntCollections.unmodifiable( map.values() ); return values; }
public void clear() { throw new UnsupportedOperationException(); }
public String toString() { return map.toString(); }
public Integer put( final Short k, final Integer v ) { throw new UnsupportedOperationException(); }
public int remove( final short k ) { throw new UnsupportedOperationException(); }
public int get( final short k ) { return map.get( k ); }
public boolean containsKey( final Object ok ) { return map.containsKey( ok ); }
public boolean containsValue( final Object ov ) { return map.containsValue( ov ); }
public boolean isEmpty() { return map.isEmpty(); }
public ObjectSet<Map.Entry<Short, Integer>> entrySet() { return ObjectSets.unmodifiable( map.entrySet() ); }
}
/** Returns an unmodifiable type-specific map backed by the given type-specific map.
*
* @param m the map to be wrapped in an unmodifiable map.
* @return an unmodifiable view of the specified map.
* @see java.util.Collections#unmodifiableMap(Map)
*/
public static Short2IntMap unmodifiable( final Short2IntMap m ) { return new UnmodifiableMap ( m ); }
}
|
package robosky.uplands.world.feature.plants;
import com.mojang.datafixers.Dynamic;
import java.util.Random;
import java.util.function.Function;
import net.minecraft.block.Block;
import net.minecraft.block.BlockState;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.MathHelper;
import net.minecraft.world.IWorld;
import net.minecraft.world.biome.Biome;
import net.minecraft.world.gen.chunk.ChunkGenerator;
import net.minecraft.world.gen.chunk.ChunkGeneratorConfig;
import net.minecraft.world.gen.feature.DefaultFeatureConfig;
import net.minecraft.world.gen.feature.FlowerFeature;
import robosky.uplands.block.BlockRegistry;
public class UplandFlowerFeature extends FlowerFeature {
private static final Block[] FLOWERS;
public UplandFlowerFeature(Function<Dynamic<?>, ? extends DefaultFeatureConfig> function_1) {
super(function_1);
}
public BlockState getFlowerToPlace(Random random_1, BlockPos blockPos_1) {
double double_1 = MathHelper.clamp((1.0D + Biome.FOLIAGE_NOISE.sample((double)blockPos_1.getX() / 48.0D, (double)blockPos_1.getZ() / 48.0D)) / 2.0D, 0.0D, 0.9999D);
Block block_1 = FLOWERS[(int)(double_1 * (double)FLOWERS.length)];
return block_1.getDefaultState();
}
public boolean generate(IWorld iWorld_1, ChunkGenerator<? extends ChunkGeneratorConfig> chunkGenerator_1, Random random_1, BlockPos blockPos_1, DefaultFeatureConfig defaultFeatureConfig_1) {
BlockState blockState_1 = this.getFlowerToPlace(random_1, blockPos_1);
int int_1 = 0;
for(int int_2 = 0; int_2 < 64; ++int_2) {
BlockPos blockPos_2 = blockPos_1.add(random_1.nextInt(8) - random_1.nextInt(8), random_1.nextInt(4) - random_1.nextInt(4), random_1.nextInt(8) - random_1.nextInt(8));
if (iWorld_1.isAir(blockPos_2) && blockPos_2.getY() < 255 && blockState_1.canPlaceAt(iWorld_1, blockPos_2)) {
iWorld_1.setBlockState(blockPos_2, blockState_1, 2);
++int_1;
}
}
return int_1 > 0;
}
static {
FLOWERS = new Block[]{BlockRegistry.CLOUD_DAISIES()};
}
}
|
package com.airbnb.lottie.model.content;
import com.airbnb.lottie.model.animatable.AnimatableIntegerValue;
import com.airbnb.lottie.model.animatable.AnimatableShapeValue;
public class Mask {
public enum MaskMode {
MASK_MODE_ADD,
MASK_MODE_SUBTRACT,
MASK_MODE_INTERSECT,
MASK_MODE_NONE
}
private final MaskMode maskMode;
private final AnimatableShapeValue maskPath;
private final AnimatableIntegerValue opacity;
private final boolean inverted;
public Mask(MaskMode maskMode, AnimatableShapeValue maskPath, AnimatableIntegerValue opacity, boolean inverted) {
this.maskMode = maskMode;
this.maskPath = maskPath;
this.opacity = opacity;
this.inverted = inverted;
}
public MaskMode getMaskMode() {
return maskMode;
}
public AnimatableShapeValue getMaskPath() {
return maskPath;
}
public AnimatableIntegerValue getOpacity() {
return opacity;
}
public boolean isInverted() {
return inverted;
}
}
|
/*
* 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.catalina.core;
import java.io.PrintStream;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Stack;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import javax.management.ListenerNotFoundException;
import javax.management.MBeanNotificationInfo;
import javax.management.Notification;
import javax.management.NotificationBroadcasterSupport;
import javax.management.NotificationEmitter;
import javax.management.NotificationFilter;
import javax.management.NotificationListener;
import javax.management.ObjectName;
import javax.servlet.MultipartConfigElement;
import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletSecurityElement;
import javax.servlet.SingleThreadModel;
import javax.servlet.UnavailableException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.ServletSecurity;
import org.apache.catalina.Container;
import org.apache.catalina.ContainerServlet;
import org.apache.catalina.Context;
import org.apache.catalina.Globals;
import org.apache.catalina.InstanceEvent;
import org.apache.catalina.InstanceListener;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.LifecycleState;
import org.apache.catalina.Wrapper;
import org.apache.catalina.security.SecurityUtil;
import org.apache.catalina.util.InstanceSupport;
import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
import org.apache.tomcat.InstanceManager;
import org.apache.tomcat.PeriodicEventListener;
import org.apache.tomcat.util.ExceptionUtils;
import org.apache.tomcat.util.log.SystemLogHandler;
import org.apache.tomcat.util.modeler.Registry;
import org.apache.tomcat.util.modeler.Util;
/**
* Standard implementation of the <b>Wrapper</b> interface that represents
* an individual servlet definition. No child Containers are allowed, and
* the parent Container must be a Context.
*
* @author Craig R. McClanahan
* @author Remy Maucherat
*/
@SuppressWarnings("deprecation") // SingleThreadModel
public class StandardWrapper extends ContainerBase
implements ServletConfig, Wrapper, NotificationEmitter {
private static final Log log = LogFactory.getLog( StandardWrapper.class );
protected static final String[] DEFAULT_SERVLET_METHODS = new String[] {
"GET", "HEAD", "POST" };
// ----------------------------------------------------------- Constructors
/**
* Create a new StandardWrapper component with the default basic Valve.
*/
public StandardWrapper() {
super();
swValve=new StandardWrapperValve();
pipeline.setBasic(swValve);
broadcaster = new NotificationBroadcasterSupport();
}
// ----------------------------------------------------- Instance Variables
/**
* The date and time at which this servlet will become available (in
* milliseconds since the epoch), or zero if the servlet is available.
* If this value equals Long.MAX_VALUE, the unavailability of this
* servlet is considered permanent.
*/
protected long available = 0L;
/**
* The broadcaster that sends j2ee notifications.
*/
protected final NotificationBroadcasterSupport broadcaster;
/**
* The count of allocations that are currently active (even if they
* are for the same instance, as will be true on a non-STM servlet).
*/
protected final AtomicInteger countAllocated = new AtomicInteger(0);
/**
* The facade associated with this wrapper.
*/
protected final StandardWrapperFacade facade = new StandardWrapperFacade(this);
/**
* The (single) possibly uninitialized instance of this servlet.
*/
protected volatile Servlet instance = null;
/**
* Flag that indicates if this instance has been initialized
*/
protected volatile boolean instanceInitialized = false;
/**
* The support object for our instance listeners.
*/
protected final InstanceSupport instanceSupport = new InstanceSupport(this);
/**
* The load-on-startup order value (negative value means load on
* first call) for this servlet.
*/
protected int loadOnStartup = -1;
/**
* Mappings associated with the wrapper.
*/
protected final ArrayList<String> mappings = new ArrayList<>();
/**
* The initialization parameters for this servlet, keyed by
* parameter name.
*/
protected HashMap<String, String> parameters = new HashMap<>();
/**
* The security role references for this servlet, keyed by role name
* used in the servlet. The corresponding value is the role name of
* the web application itself.
*/
protected HashMap<String, String> references = new HashMap<>();
/**
* The run-as identity for this servlet.
*/
protected String runAs = null;
/**
* The notification sequence number.
*/
protected long sequenceNumber = 0;
/**
* The fully qualified servlet class name for this servlet.
*/
protected String servletClass = null;
/**
* Does this servlet implement the SingleThreadModel interface?
*/
protected volatile boolean singleThreadModel = false;
/**
* Are we unloading our servlet instance at the moment?
*/
protected volatile boolean unloading = false;
/**
* Maximum number of STM instances.
*/
protected int maxInstances = 20;
/**
* Number of instances currently loaded for a STM servlet.
*/
protected int nInstances = 0;
/**
* Stack containing the STM instances.
*/
protected Stack<Servlet> instancePool = null;
/**
* Wait time for servlet unload in ms.
*/
protected long unloadDelay = 2000;
/**
* True if this StandardWrapper is for the JspServlet
*/
protected boolean isJspServlet;
/**
* The ObjectName of the JSP monitoring mbean
*/
protected ObjectName jspMonitorON;
/**
* Should we swallow System.out
*/
protected boolean swallowOutput = false;
// To support jmx attributes
protected StandardWrapperValve swValve;
protected long loadTime=0;
protected int classLoadTime=0;
/**
* Multipart config
*/
protected MultipartConfigElement multipartConfigElement = null;
/**
* Async support
*/
protected boolean asyncSupported = false;
/**
* Enabled
*/
protected boolean enabled = true;
protected volatile boolean servletSecurityAnnotationScanRequired = false;
private boolean overridable = false;
/**
* Static class array used when the SecurityManager is turned on and
* <code>Servlet.init</code> is invoked.
*/
protected static Class<?>[] classType = new Class[]{ServletConfig.class};
private final ReentrantReadWriteLock parametersLock =
new ReentrantReadWriteLock();
private final ReentrantReadWriteLock mappingsLock =
new ReentrantReadWriteLock();
private final ReentrantReadWriteLock referencesLock =
new ReentrantReadWriteLock();
// ------------------------------------------------------------- Properties
@Override
public boolean isOverridable() {
return overridable;
}
@Override
public void setOverridable(boolean overridable) {
this.overridable = overridable;
}
/**
* Return the available date/time for this servlet, in milliseconds since
* the epoch. If this date/time is Long.MAX_VALUE, it is considered to mean
* that unavailability is permanent and any request for this servlet will return
* an SC_NOT_FOUND error. If this date/time is in the future, any request for
* this servlet will return an SC_SERVICE_UNAVAILABLE error. If it is zero,
* the servlet is currently available.
*/
@Override
public long getAvailable() {
return (this.available);
}
/**
* Set the available date/time for this servlet, in milliseconds since the
* epoch. If this date/time is Long.MAX_VALUE, it is considered to mean
* that unavailability is permanent and any request for this servlet will return
* an SC_NOT_FOUND error. If this date/time is in the future, any request for
* this servlet will return an SC_SERVICE_UNAVAILABLE error.
*
* @param available The new available date/time
*/
@Override
public void setAvailable(long available) {
long oldAvailable = this.available;
if (available > System.currentTimeMillis())
this.available = available;
else
this.available = 0L;
support.firePropertyChange("available", Long.valueOf(oldAvailable),
Long.valueOf(this.available));
}
/**
* Return the number of active allocations of this servlet, even if they
* are all for the same instance (as will be true for servlets that do
* not implement <code>SingleThreadModel</code>.
*/
public int getCountAllocated() {
return (this.countAllocated.get());
}
/**
* Return the InstanceSupport object for this Wrapper instance.
*/
public InstanceSupport getInstanceSupport() {
return (this.instanceSupport);
}
/**
* Return the load-on-startup order value (negative value means
* load on first call).
*/
@Override
public int getLoadOnStartup() {
if (isJspServlet && loadOnStartup < 0) {
/*
* JspServlet must always be preloaded, because its instance is
* used during registerJMX (when registering the JSP
* monitoring mbean)
*/
return Integer.MAX_VALUE;
} else {
return (this.loadOnStartup);
}
}
/**
* Set the load-on-startup order value (negative value means
* load on first call).
*
* @param value New load-on-startup value
*/
@Override
public void setLoadOnStartup(int value) {
int oldLoadOnStartup = this.loadOnStartup;
this.loadOnStartup = value;
support.firePropertyChange("loadOnStartup",
Integer.valueOf(oldLoadOnStartup),
Integer.valueOf(this.loadOnStartup));
}
/**
* Set the load-on-startup order value from a (possibly null) string.
* Per the specification, any missing or non-numeric value is converted
* to a zero, so that this servlet will still be loaded at startup
* time, but in an arbitrary order.
*
* @param value New load-on-startup value
*/
public void setLoadOnStartupString(String value) {
try {
setLoadOnStartup(Integer.parseInt(value));
} catch (NumberFormatException e) {
setLoadOnStartup(0);
}
}
public String getLoadOnStartupString() {
return Integer.toString( getLoadOnStartup());
}
/**
* Return maximum number of instances that will be allocated when a single
* thread model servlet is used.
*/
public int getMaxInstances() {
return (this.maxInstances);
}
/**
* Set the maximum number of instances that will be allocated when a single
* thread model servlet is used.
*
* @param maxInstances New value of maxInstances
*/
public void setMaxInstances(int maxInstances) {
int oldMaxInstances = this.maxInstances;
this.maxInstances = maxInstances;
support.firePropertyChange("maxInstances", oldMaxInstances,
this.maxInstances);
}
/**
* Set the parent Container of this Wrapper, but only if it is a Context.
*
* @param container Proposed parent Container
*/
@Override
public void setParent(Container container) {
if ((container != null) &&
!(container instanceof Context))
throw new IllegalArgumentException
(sm.getString("standardWrapper.notContext"));
if (container instanceof StandardContext) {
swallowOutput = ((StandardContext)container).getSwallowOutput();
unloadDelay = ((StandardContext)container).getUnloadDelay();
}
super.setParent(container);
}
/**
* Return the run-as identity for this servlet.
*/
@Override
public String getRunAs() {
return (this.runAs);
}
/**
* Set the run-as identity for this servlet.
*
* @param runAs New run-as identity value
*/
@Override
public void setRunAs(String runAs) {
String oldRunAs = this.runAs;
this.runAs = runAs;
support.firePropertyChange("runAs", oldRunAs, this.runAs);
}
/**
* Return the fully qualified servlet class name for this servlet.
*/
@Override
public String getServletClass() {
return (this.servletClass);
}
/**
* Set the fully qualified servlet class name for this servlet.
*
* @param servletClass Servlet class name
*/
@Override
public void setServletClass(String servletClass) {
String oldServletClass = this.servletClass;
this.servletClass = servletClass;
support.firePropertyChange("servletClass", oldServletClass,
this.servletClass);
if (Constants.JSP_SERVLET_CLASS.equals(servletClass)) {
isJspServlet = true;
}
}
/**
* Set the name of this servlet. This is an alias for the normal
* <code>Container.setName()</code> method, and complements the
* <code>getServletName()</code> method required by the
* <code>ServletConfig</code> interface.
*
* @param name The new name of this servlet
*/
public void setServletName(String name) {
setName(name);
}
/**
* Return <code>true</code> if the servlet class represented by this
* component implements the <code>SingleThreadModel</code> interface.
*/
public boolean isSingleThreadModel() {
// Short-cuts
// If singleThreadModel is true, must have already checked this
// If instance != null, must have already loaded
if (singleThreadModel || instance != null) {
return singleThreadModel;
}
// The logic to determine this safely is more complex than one might
// expect. allocate() already has the necessary logic so re-use it.
// Make sure the Servlet is loaded with the right class loader
ClassLoader oldCL = null;
try {
oldCL = ((Context) getParent()).bind(false, null);
Servlet s = allocate();
deallocate(s);
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
} finally {
((Context) getParent()).unbind(false, oldCL);
}
return singleThreadModel;
}
/**
* Is this servlet currently unavailable?
*/
@Override
public boolean isUnavailable() {
if (!isEnabled())
return true;
else if (available == 0L)
return false;
else if (available <= System.currentTimeMillis()) {
available = 0L;
return false;
} else
return true;
}
/**
* Gets the names of the methods supported by the underlying servlet.
*
* This is the same set of methods included in the Allow response header
* in response to an OPTIONS request method processed by the underlying
* servlet.
*
* @return Array of names of the methods supported by the underlying
* servlet
*/
@Override
public String[] getServletMethods() throws ServletException {
instance = loadServlet();
Class<? extends Servlet> servletClazz = instance.getClass();
if (!javax.servlet.http.HttpServlet.class.isAssignableFrom(
servletClazz)) {
return DEFAULT_SERVLET_METHODS;
}
HashSet<String> allow = new HashSet<>();
allow.add("TRACE");
allow.add("OPTIONS");
Method[] methods = getAllDeclaredMethods(servletClazz);
for (int i=0; methods != null && i<methods.length; i++) {
Method m = methods[i];
if (m.getName().equals("doGet")) {
allow.add("GET");
allow.add("HEAD");
} else if (m.getName().equals("doPost")) {
allow.add("POST");
} else if (m.getName().equals("doPut")) {
allow.add("PUT");
} else if (m.getName().equals("doDelete")) {
allow.add("DELETE");
}
}
String[] methodNames = new String[allow.size()];
return allow.toArray(methodNames);
}
/**
* Return the associated servlet instance.
*/
@Override
public Servlet getServlet() {
return instance;
}
/**
* Set the associated servlet instance.
*/
@Override
public void setServlet(Servlet servlet) {
instance = servlet;
}
/**
* {@inheritDoc}
*/
@Override
public void setServletSecurityAnnotationScanRequired(boolean b) {
this.servletSecurityAnnotationScanRequired = b;
}
// --------------------------------------------------------- Public Methods
/**
* Execute a periodic task, such as reloading, etc. This method will be
* invoked inside the classloading context of this container. Unexpected
* throwables will be caught and logged.
*/
@Override
public void backgroundProcess() {
super.backgroundProcess();
if (!getState().isAvailable())
return;
if (getServlet() != null && (getServlet() instanceof PeriodicEventListener)) {
((PeriodicEventListener) getServlet()).periodicEvent();
}
}
/**
* Extract the root cause from a servlet exception.
*
* @param e The servlet exception
*/
public static Throwable getRootCause(ServletException e) {
Throwable rootCause = e;
Throwable rootCauseCheck = null;
// Extra aggressive rootCause finding
int loops = 0;
do {
loops++;
rootCauseCheck = rootCause.getCause();
if (rootCauseCheck != null)
rootCause = rootCauseCheck;
} while (rootCauseCheck != null && (loops < 20));
return rootCause;
}
/**
* Refuse to add a child Container, because Wrappers are the lowest level
* of the Container hierarchy.
*
* @param child Child container to be added
*/
@Override
public void addChild(Container child) {
throw new IllegalStateException
(sm.getString("standardWrapper.notChild"));
}
/**
* Add a new servlet initialization parameter for this servlet.
*
* @param name Name of this initialization parameter to add
* @param value Value of this initialization parameter to add
*/
@Override
public void addInitParameter(String name, String value) {
parametersLock.writeLock().lock();
try {
parameters.put(name, value);
} finally {
parametersLock.writeLock().unlock();
}
fireContainerEvent("addInitParameter", name);
}
/**
* Add a new listener interested in InstanceEvents.
*
* @param listener The new listener
*/
@Override
public void addInstanceListener(InstanceListener listener) {
instanceSupport.addInstanceListener(listener);
}
/**
* Add a mapping associated with the Wrapper.
*
* @param mapping The new wrapper mapping
*/
@Override
public void addMapping(String mapping) {
mappingsLock.writeLock().lock();
try {
mappings.add(mapping);
} finally {
mappingsLock.writeLock().unlock();
}
if(parent.getState().equals(LifecycleState.STARTED))
fireContainerEvent(ADD_MAPPING_EVENT, mapping);
}
/**
* Add a new security role reference record to the set of records for
* this servlet.
*
* @param name Role name used within this servlet
* @param link Role name used within the web application
*/
@Override
public void addSecurityReference(String name, String link) {
referencesLock.writeLock().lock();
try {
references.put(name, link);
} finally {
referencesLock.writeLock().unlock();
}
fireContainerEvent("addSecurityReference", name);
}
/**
* Allocate an initialized instance of this Servlet that is ready to have
* its <code>service()</code> method called. If the servlet class does
* not implement <code>SingleThreadModel</code>, the (only) initialized
* instance may be returned immediately. If the servlet class implements
* <code>SingleThreadModel</code>, the Wrapper implementation must ensure
* that this instance is not allocated again until it is deallocated by a
* call to <code>deallocate()</code>.
*
* @exception ServletException if the servlet init() method threw
* an exception
* @exception ServletException if a loading error occurs
*/
@Override
public Servlet allocate() throws ServletException {
// If we are currently unloading this servlet, throw an exception
if (unloading)
throw new ServletException
(sm.getString("standardWrapper.unloading", getName()));
boolean newInstance = false;
// If not SingleThreadedModel, return the same instance every time
if (!singleThreadModel) {
// Load and initialize our instance if necessary
if (instance == null) {
synchronized (this) {
if (instance == null) {
try {
if (log.isDebugEnabled())
log.debug("Allocating non-STM instance");
instance = loadServlet();
if (!singleThreadModel) {
// For non-STM, increment here to prevent a race
// condition with unload. Bug 43683, test case
// #3
newInstance = true;
countAllocated.incrementAndGet();
}
} catch (ServletException e) {
throw e;
} catch (Throwable e) {
ExceptionUtils.handleThrowable(e);
throw new ServletException
(sm.getString("standardWrapper.allocate"), e);
}
}
}
}
if (!instanceInitialized) {
initServlet(instance);
}
if (singleThreadModel) {
if (newInstance) {
// Have to do this outside of the sync above to prevent a
// possible deadlock
synchronized (instancePool) {
instancePool.push(instance);
nInstances++;
}
}
} else {
if (log.isTraceEnabled())
log.trace(" Returning non-STM instance");
// For new instances, count will have been incremented at the
// time of creation
if (!newInstance) {
countAllocated.incrementAndGet();
}
return (instance);
}
}
synchronized (instancePool) {
while (countAllocated.get() >= nInstances) {
// Allocate a new instance if possible, or else wait
if (nInstances < maxInstances) {
try {
instancePool.push(loadServlet());
nInstances++;
} catch (ServletException e) {
throw e;
} catch (Throwable e) {
ExceptionUtils.handleThrowable(e);
throw new ServletException
(sm.getString("standardWrapper.allocate"), e);
}
} else {
try {
instancePool.wait();
} catch (InterruptedException e) {
// Ignore
}
}
}
if (log.isTraceEnabled())
log.trace(" Returning allocated STM instance");
countAllocated.incrementAndGet();
return instancePool.pop();
}
}
/**
* Return this previously allocated servlet to the pool of available
* instances. If this servlet class does not implement SingleThreadModel,
* no action is actually required.
*
* @param servlet The servlet to be returned
*
* @exception ServletException if a deallocation error occurs
*/
@Override
public void deallocate(Servlet servlet) throws ServletException {
// If not SingleThreadModel, no action is required
if (!singleThreadModel) {
countAllocated.decrementAndGet();
return;
}
// Unlock and free this instance
synchronized (instancePool) {
countAllocated.decrementAndGet();
instancePool.push(servlet);
instancePool.notify();
}
}
/**
* Return the value for the specified initialization parameter name,
* if any; otherwise return <code>null</code>.
*
* @param name Name of the requested initialization parameter
*/
@Override
public String findInitParameter(String name) {
parametersLock.readLock().lock();
try {
return parameters.get(name);
} finally {
parametersLock.readLock().unlock();
}
}
/**
* Return the names of all defined initialization parameters for this
* servlet.
*/
@Override
public String[] findInitParameters() {
parametersLock.readLock().lock();
try {
String results[] = new String[parameters.size()];
return parameters.keySet().toArray(results);
} finally {
parametersLock.readLock().unlock();
}
}
/**
* Return the mappings associated with this wrapper.
*/
@Override
public String[] findMappings() {
mappingsLock.readLock().lock();
try {
return mappings.toArray(new String[mappings.size()]);
} finally {
mappingsLock.readLock().unlock();
}
}
/**
* Return the security role link for the specified security role
* reference name, if any; otherwise return <code>null</code>.
*
* @param name Security role reference used within this servlet
*/
@Override
public String findSecurityReference(String name) {
referencesLock.readLock().lock();
try {
return references.get(name);
} finally {
referencesLock.readLock().unlock();
}
}
/**
* Return the set of security role reference names associated with
* this servlet, if any; otherwise return a zero-length array.
*/
@Override
public String[] findSecurityReferences() {
referencesLock.readLock().lock();
try {
String results[] = new String[references.size()];
return references.keySet().toArray(results);
} finally {
referencesLock.readLock().unlock();
}
}
/**
* Load and initialize an instance of this servlet, if there is not already
* at least one initialized instance. This can be used, for example, to
* load servlets that are marked in the deployment descriptor to be loaded
* at server startup time.
* <p>
* <b>IMPLEMENTATION NOTE</b>: Servlets whose classnames begin with
* <code>org.apache.catalina.</code> (so-called "container" servlets)
* are loaded by the same classloader that loaded this class, rather than
* the classloader for the current web application.
* This gives such classes access to Catalina internals, which are
* prevented for classes loaded for web applications.
*
* @exception ServletException if the servlet init() method threw
* an exception
* @exception ServletException if some other loading problem occurs
*/
@Override
public synchronized void load() throws ServletException {
instance = loadServlet();
if (!instanceInitialized) {
initServlet(instance);
}
if (isJspServlet) {
StringBuilder oname = new StringBuilder(getDomain());
oname.append(":type=JspMonitor");
oname.append(getWebModuleKeyProperties());
oname.append(",name=");
oname.append(getName());
oname.append(getJ2EEKeyProperties());
try {
jspMonitorON = new ObjectName(oname.toString());
Registry.getRegistry(null, null)
.registerComponent(instance, jspMonitorON, null);
} catch( Exception ex ) {
log.info("Error registering JSP monitoring with jmx " +
instance);
}
}
}
/**
* Load and initialize an instance of this servlet, if there is not already
* at least one initialized instance. This can be used, for example, to
* load servlets that are marked in the deployment descriptor to be loaded
* at server startup time.
*/
public synchronized Servlet loadServlet() throws ServletException {
if (unloading) {
throw new ServletException(
sm.getString("standardWrapper.unloading", getName()));
}
// Nothing to do if we already have an instance or an instance pool
if (!singleThreadModel && (instance != null))
return instance;
PrintStream out = System.out;
if (swallowOutput) {
SystemLogHandler.startCapture();
}
Servlet servlet;
try {
long t1=System.currentTimeMillis();
// Complain if no servlet class has been specified
if (servletClass == null) {
unavailable(null);
throw new ServletException
(sm.getString("standardWrapper.notClass", getName()));
}
InstanceManager instanceManager = ((StandardContext)getParent()).getInstanceManager();
try {
servlet = (Servlet) instanceManager.newInstance(servletClass);
} catch (ClassCastException e) {
unavailable(null);
// Restore the context ClassLoader
throw new ServletException
(sm.getString("standardWrapper.notServlet", servletClass), e);
} catch (Throwable e) {
e = ExceptionUtils.unwrapInvocationTargetException(e);
ExceptionUtils.handleThrowable(e);
unavailable(null);
// Added extra log statement for Bugzilla 36630:
// http://issues.apache.org/bugzilla/show_bug.cgi?id=36630
if(log.isDebugEnabled()) {
log.debug(sm.getString("standardWrapper.instantiate", servletClass), e);
}
// Restore the context ClassLoader
throw new ServletException
(sm.getString("standardWrapper.instantiate", servletClass), e);
}
if (multipartConfigElement == null) {
MultipartConfig annotation =
servlet.getClass().getAnnotation(MultipartConfig.class);
if (annotation != null) {
multipartConfigElement =
new MultipartConfigElement(annotation);
}
}
processServletSecurityAnnotation(servlet.getClass());
// Special handling for ContainerServlet instances
if ((servlet instanceof ContainerServlet) &&
(isContainerProvidedServlet(servletClass) ||
((Context) getParent()).getPrivileged() )) {
((ContainerServlet) servlet).setWrapper(this);
}
classLoadTime=(int) (System.currentTimeMillis() -t1);
if (servlet instanceof SingleThreadModel) {
if (instancePool == null) {
instancePool = new Stack<>();
}
singleThreadModel = true;
}
initServlet(servlet);
fireContainerEvent("load", this);
loadTime=System.currentTimeMillis() -t1;
} finally {
if (swallowOutput) {
String log = SystemLogHandler.stopCapture();
if (log != null && log.length() > 0) {
if (getServletContext() != null) {
getServletContext().log(log);
} else {
out.println(log);
}
}
}
}
return servlet;
}
/**
* {@inheritDoc}
*/
@Override
public void servletSecurityAnnotationScan() throws ServletException {
if (getServlet() == null) {
Class<?> clazz = null;
try {
clazz = ((Context) getParent()).getLoader().getClassLoader().loadClass(
getServletClass());
processServletSecurityAnnotation(clazz);
} catch (ClassNotFoundException e) {
// Safe to ignore. No class means no annotations to process
}
} else {
if (servletSecurityAnnotationScanRequired) {
processServletSecurityAnnotation(getServlet().getClass());
}
}
}
private void processServletSecurityAnnotation(Class<?> clazz) {
// Calling this twice isn't harmful so no syncs
servletSecurityAnnotationScanRequired = false;
Context ctxt = (Context) getParent();
if (ctxt.getIgnoreAnnotations()) {
return;
}
ServletSecurity secAnnotation =
clazz.getAnnotation(ServletSecurity.class);
if (secAnnotation != null) {
ctxt.addServletSecurity(
new ApplicationServletRegistration(this, ctxt),
new ServletSecurityElement(secAnnotation));
}
}
private synchronized void initServlet(Servlet servlet)
throws ServletException {
if (instanceInitialized && !singleThreadModel) return;
// Call the initialization method of this servlet
try {
instanceSupport.fireInstanceEvent(InstanceEvent.BEFORE_INIT_EVENT,
servlet);
if( Globals.IS_SECURITY_ENABLED) {
boolean success = false;
try {
Object[] args = new Object[] { facade };
SecurityUtil.doAsPrivilege("init",
servlet,
classType,
args);
success = true;
} finally {
if (!success) {
// destroy() will not be called, thus clear the reference now
SecurityUtil.remove(servlet);
}
}
} else {
servlet.init(facade);
}
instanceInitialized = true;
instanceSupport.fireInstanceEvent(InstanceEvent.AFTER_INIT_EVENT,
servlet);
} catch (UnavailableException f) {
instanceSupport.fireInstanceEvent(InstanceEvent.AFTER_INIT_EVENT,
servlet, f);
unavailable(f);
throw f;
} catch (ServletException f) {
instanceSupport.fireInstanceEvent(InstanceEvent.AFTER_INIT_EVENT,
servlet, f);
// If the servlet wanted to be unavailable it would have
// said so, so do not call unavailable(null).
throw f;
} catch (Throwable f) {
ExceptionUtils.handleThrowable(f);
getServletContext().log("StandardWrapper.Throwable", f );
instanceSupport.fireInstanceEvent(InstanceEvent.AFTER_INIT_EVENT,
servlet, f);
// If the servlet wanted to be unavailable it would have
// said so, so do not call unavailable(null).
throw new ServletException
(sm.getString("standardWrapper.initException", getName()), f);
}
}
/**
* Remove the specified initialization parameter from this servlet.
*
* @param name Name of the initialization parameter to remove
*/
@Override
public void removeInitParameter(String name) {
parametersLock.writeLock().lock();
try {
parameters.remove(name);
} finally {
parametersLock.writeLock().unlock();
}
fireContainerEvent("removeInitParameter", name);
}
/**
* Remove a listener no longer interested in InstanceEvents.
*
* @param listener The listener to remove
*/
@Override
public void removeInstanceListener(InstanceListener listener) {
instanceSupport.removeInstanceListener(listener);
}
/**
* Remove a mapping associated with the wrapper.
*
* @param mapping The pattern to remove
*/
@Override
public void removeMapping(String mapping) {
mappingsLock.writeLock().lock();
try {
mappings.remove(mapping);
} finally {
mappingsLock.writeLock().unlock();
}
if(parent.getState().equals(LifecycleState.STARTED))
fireContainerEvent(REMOVE_MAPPING_EVENT, mapping);
}
/**
* Remove any security role reference for the specified role name.
*
* @param name Security role used within this servlet to be removed
*/
@Override
public void removeSecurityReference(String name) {
referencesLock.writeLock().lock();
try {
references.remove(name);
} finally {
referencesLock.writeLock().unlock();
}
fireContainerEvent("removeSecurityReference", name);
}
/**
* Return a String representation of this component.
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
if (getParent() != null) {
sb.append(getParent().toString());
sb.append(".");
}
sb.append("StandardWrapper[");
sb.append(getName());
sb.append("]");
return (sb.toString());
}
/**
* Process an UnavailableException, marking this servlet as unavailable
* for the specified amount of time.
*
* @param unavailable The exception that occurred, or <code>null</code>
* to mark this servlet as permanently unavailable
*/
@Override
public void unavailable(UnavailableException unavailable) {
getServletContext().log(sm.getString("standardWrapper.unavailable", getName()));
if (unavailable == null)
setAvailable(Long.MAX_VALUE);
else if (unavailable.isPermanent())
setAvailable(Long.MAX_VALUE);
else {
int unavailableSeconds = unavailable.getUnavailableSeconds();
if (unavailableSeconds <= 0)
unavailableSeconds = 60; // Arbitrary default
setAvailable(System.currentTimeMillis() +
(unavailableSeconds * 1000L));
}
}
/**
* Unload all initialized instances of this servlet, after calling the
* <code>destroy()</code> method for each instance. This can be used,
* for example, prior to shutting down the entire servlet engine, or
* prior to reloading all of the classes from the Loader associated with
* our Loader's repository.
*
* @exception ServletException if an exception is thrown by the
* destroy() method
*/
@Override
public synchronized void unload() throws ServletException {
// Nothing to do if we have never loaded the instance
if (!singleThreadModel && (instance == null))
return;
unloading = true;
// Loaf a while if the current instance is allocated
// (possibly more than once if non-STM)
if (countAllocated.get() > 0) {
int nRetries = 0;
long delay = unloadDelay / 20;
while ((nRetries < 21) && (countAllocated.get() > 0)) {
if ((nRetries % 10) == 0) {
log.info(sm.getString("standardWrapper.waiting",
countAllocated.toString(),
getName()));
}
try {
Thread.sleep(delay);
} catch (InterruptedException e) {
// Ignore
}
nRetries++;
}
}
if (instanceInitialized) {
PrintStream out = System.out;
if (swallowOutput) {
SystemLogHandler.startCapture();
}
// Call the servlet destroy() method
try {
instanceSupport.fireInstanceEvent
(InstanceEvent.BEFORE_DESTROY_EVENT, instance);
if( Globals.IS_SECURITY_ENABLED) {
try {
SecurityUtil.doAsPrivilege("destroy",
instance);
} finally {
SecurityUtil.remove(instance);
}
} else {
instance.destroy();
}
instanceSupport.fireInstanceEvent
(InstanceEvent.AFTER_DESTROY_EVENT, instance);
// Annotation processing
if (!((Context) getParent()).getIgnoreAnnotations()) {
((StandardContext)getParent()).getInstanceManager().destroyInstance(instance);
}
} catch (Throwable t) {
t = ExceptionUtils.unwrapInvocationTargetException(t);
ExceptionUtils.handleThrowable(t);
instanceSupport.fireInstanceEvent
(InstanceEvent.AFTER_DESTROY_EVENT, instance, t);
instance = null;
instancePool = null;
nInstances = 0;
fireContainerEvent("unload", this);
unloading = false;
throw new ServletException
(sm.getString("standardWrapper.destroyException", getName()),
t);
} finally {
// Write captured output
if (swallowOutput) {
String log = SystemLogHandler.stopCapture();
if (log != null && log.length() > 0) {
if (getServletContext() != null) {
getServletContext().log(log);
} else {
out.println(log);
}
}
}
}
}
// Deregister the destroyed instance
instance = null;
if (isJspServlet && jspMonitorON != null ) {
Registry.getRegistry(null, null).unregisterComponent(jspMonitorON);
}
if (singleThreadModel && (instancePool != null)) {
try {
while (!instancePool.isEmpty()) {
Servlet s = instancePool.pop();
if (Globals.IS_SECURITY_ENABLED) {
try {
SecurityUtil.doAsPrivilege("destroy", s);
} finally {
SecurityUtil.remove(s);
}
} else {
s.destroy();
}
// Annotation processing
if (!((Context) getParent()).getIgnoreAnnotations()) {
((StandardContext)getParent()).getInstanceManager().destroyInstance(s);
}
}
} catch (Throwable t) {
t = ExceptionUtils.unwrapInvocationTargetException(t);
ExceptionUtils.handleThrowable(t);
instancePool = null;
nInstances = 0;
unloading = false;
fireContainerEvent("unload", this);
throw new ServletException
(sm.getString("standardWrapper.destroyException",
getName()), t);
}
instancePool = null;
nInstances = 0;
}
singleThreadModel = false;
unloading = false;
fireContainerEvent("unload", this);
}
// -------------------------------------------------- ServletConfig Methods
/**
* Return the initialization parameter value for the specified name,
* if any; otherwise return <code>null</code>.
*
* @param name Name of the initialization parameter to retrieve
*/
@Override
public String getInitParameter(String name) {
return (findInitParameter(name));
}
/**
* Return the set of initialization parameter names defined for this
* servlet. If none are defined, an empty Enumeration is returned.
*/
@Override
public Enumeration<String> getInitParameterNames() {
parametersLock.readLock().lock();
try {
return Collections.enumeration(parameters.keySet());
} finally {
parametersLock.readLock().unlock();
}
}
/**
* Return the servlet context with which this servlet is associated.
*/
@Override
public ServletContext getServletContext() {
if (parent == null)
return (null);
else if (!(parent instanceof Context))
return (null);
else
return (((Context) parent).getServletContext());
}
/**
* Return the name of this servlet.
*/
@Override
public String getServletName() {
return (getName());
}
public long getProcessingTime() {
return swValve.getProcessingTime();
}
public long getMaxTime() {
return swValve.getMaxTime();
}
public long getMinTime() {
return swValve.getMinTime();
}
public int getRequestCount() {
return swValve.getRequestCount();
}
public int getErrorCount() {
return swValve.getErrorCount();
}
/**
* Increment the error count used for monitoring.
*/
@Override
public void incrementErrorCount(){
swValve.incrementErrorCount();
}
public long getLoadTime() {
return loadTime;
}
public int getClassLoadTime() {
return classLoadTime;
}
@Override
public MultipartConfigElement getMultipartConfigElement() {
return multipartConfigElement;
}
@Override
public void setMultipartConfigElement(
MultipartConfigElement multipartConfigElement) {
this.multipartConfigElement = multipartConfigElement;
}
@Override
public boolean isAsyncSupported() {
return asyncSupported;
}
@Override
public void setAsyncSupported(boolean asyncSupported) {
this.asyncSupported = asyncSupported;
}
@Override
public boolean isEnabled() {
return enabled;
}
@Override
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
// -------------------------------------------------------- Package Methods
// -------------------------------------------------------- protected Methods
/**
* Return <code>true</code> if the specified class name represents a
* container provided servlet class that should be loaded by the
* server class loader.
*
* @param classname Name of the class to be checked
*/
protected boolean isContainerProvidedServlet(String classname) {
if (classname.startsWith("org.apache.catalina.")) {
return (true);
}
try {
Class<?> clazz =
this.getClass().getClassLoader().loadClass(classname);
return (ContainerServlet.class.isAssignableFrom(clazz));
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
return (false);
}
}
protected Method[] getAllDeclaredMethods(Class<?> c) {
if (c.equals(javax.servlet.http.HttpServlet.class)) {
return null;
}
Method[] parentMethods = getAllDeclaredMethods(c.getSuperclass());
Method[] thisMethods = c.getDeclaredMethods();
if (thisMethods == null) {
return parentMethods;
}
if ((parentMethods != null) && (parentMethods.length > 0)) {
Method[] allMethods =
new Method[parentMethods.length + thisMethods.length];
System.arraycopy(parentMethods, 0, allMethods, 0,
parentMethods.length);
System.arraycopy(thisMethods, 0, allMethods, parentMethods.length,
thisMethods.length);
thisMethods = allMethods;
}
return thisMethods;
}
// ------------------------------------------------------ Lifecycle Methods
/**
* Start this component and implement the requirements
* of {@link org.apache.catalina.util.LifecycleBase#startInternal()}.
*
* @exception LifecycleException if this component detects a fatal error
* that prevents this component from being used
*/
@Override
protected synchronized void startInternal() throws LifecycleException {
// Send j2ee.state.starting notification
if (this.getObjectName() != null) {
Notification notification = new Notification("j2ee.state.starting",
this.getObjectName(),
sequenceNumber++);
broadcaster.sendNotification(notification);
}
// Start up this component
super.startInternal();
setAvailable(0L);
// Send j2ee.state.running notification
if (this.getObjectName() != null) {
Notification notification =
new Notification("j2ee.state.running", this.getObjectName(),
sequenceNumber++);
broadcaster.sendNotification(notification);
}
}
/**
* Stop this component and implement the requirements
* of {@link org.apache.catalina.util.LifecycleBase#stopInternal()}.
*
* @exception LifecycleException if this component detects a fatal error
* that prevents this component from being used
*/
@Override
protected synchronized void stopInternal() throws LifecycleException {
setAvailable(Long.MAX_VALUE);
// Send j2ee.state.stopping notification
if (this.getObjectName() != null) {
Notification notification =
new Notification("j2ee.state.stopping", this.getObjectName(),
sequenceNumber++);
broadcaster.sendNotification(notification);
}
// Shut down our servlet instance (if it has been initialized)
try {
unload();
} catch (ServletException e) {
getServletContext().log(sm.getString
("standardWrapper.unloadException", getName()), e);
}
// Shut down this component
super.stopInternal();
// Send j2ee.state.stoppped notification
if (this.getObjectName() != null) {
Notification notification =
new Notification("j2ee.state.stopped", this.getObjectName(),
sequenceNumber++);
broadcaster.sendNotification(notification);
}
// Send j2ee.object.deleted notification
Notification notification =
new Notification("j2ee.object.deleted", this.getObjectName(),
sequenceNumber++);
broadcaster.sendNotification(notification);
}
@Override
protected String getObjectNameKeyProperties() {
StringBuilder keyProperties =
new StringBuilder("j2eeType=Servlet");
keyProperties.append(getWebModuleKeyProperties());
keyProperties.append(",name=");
String name = getName();
if (Util.objectNameValueNeedsQuote(name)) {
name = ObjectName.quote(name);
}
keyProperties.append(name);
keyProperties.append(getJ2EEKeyProperties());
return keyProperties.toString();
}
private String getWebModuleKeyProperties() {
StringBuilder keyProperties = new StringBuilder(",WebModule=//");
String hostName = getParent().getParent().getName();
if (hostName == null) {
keyProperties.append("DEFAULT");
} else {
keyProperties.append(hostName);
}
String contextName = ((Context) getParent()).getName();
if (!contextName.startsWith("/")) {
keyProperties.append('/');
}
keyProperties.append(contextName);
return keyProperties.toString();
}
private String getJ2EEKeyProperties() {
StringBuilder keyProperties = new StringBuilder(",J2EEApplication=");
StandardContext ctx = null;
if (parent instanceof StandardContext) {
ctx = (StandardContext) getParent();
}
if (ctx == null) {
keyProperties.append("none");
} else {
keyProperties.append(ctx.getJ2EEApplication());
}
keyProperties.append(",J2EEServer=");
if (ctx == null) {
keyProperties.append("none");
} else {
keyProperties.append(ctx.getJ2EEServer());
}
return keyProperties.toString();
}
/**
* JSR 77. Always return false.
*/
public boolean isStateManageable() {
return false;
}
/* Remove a JMX notficationListener
* @see javax.management.NotificationEmitter#removeNotificationListener(javax.management.NotificationListener, javax.management.NotificationFilter, java.lang.Object)
*/
@Override
public void removeNotificationListener(NotificationListener listener,
NotificationFilter filter, Object object) throws ListenerNotFoundException {
broadcaster.removeNotificationListener(listener,filter,object);
}
protected MBeanNotificationInfo[] notificationInfo;
/* Get JMX Broadcaster Info
* @TODO use StringManager for international support!
* @TODO This two events we not send j2ee.state.failed and j2ee.attribute.changed!
* @see javax.management.NotificationBroadcaster#getNotificationInfo()
*/
@Override
public MBeanNotificationInfo[] getNotificationInfo() {
if(notificationInfo == null) {
notificationInfo = new MBeanNotificationInfo[]{
new MBeanNotificationInfo(new String[] {
"j2ee.object.created"},
Notification.class.getName(),
"servlet is created"
),
new MBeanNotificationInfo(new String[] {
"j2ee.state.starting"},
Notification.class.getName(),
"servlet is starting"
),
new MBeanNotificationInfo(new String[] {
"j2ee.state.running"},
Notification.class.getName(),
"servlet is running"
),
new MBeanNotificationInfo(new String[] {
"j2ee.state.stopped"},
Notification.class.getName(),
"servlet start to stopped"
),
new MBeanNotificationInfo(new String[] {
"j2ee.object.stopped"},
Notification.class.getName(),
"servlet is stopped"
),
new MBeanNotificationInfo(new String[] {
"j2ee.object.deleted"},
Notification.class.getName(),
"servlet is deleted"
)
};
}
return notificationInfo;
}
/* Add a JMX-NotificationListener
* @see javax.management.NotificationBroadcaster#addNotificationListener(javax.management.NotificationListener, javax.management.NotificationFilter, java.lang.Object)
*/
@Override
public void addNotificationListener(NotificationListener listener,
NotificationFilter filter, Object object) throws IllegalArgumentException {
broadcaster.addNotificationListener(listener,filter,object);
}
/**
* Remove a JMX-NotificationListener
* @see javax.management.NotificationBroadcaster#removeNotificationListener(javax.management.NotificationListener)
*/
@Override
public void removeNotificationListener(NotificationListener listener)
throws ListenerNotFoundException {
broadcaster.removeNotificationListener(listener);
}
}
|
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2019.12.04 at 03:04:02 PM EST
//
package dev.igorartsoft.hierarchical.data.xml.jasperreports.model;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <attribute name="name" use="required" type="{http://www.w3.org/2001/XMLSchema}string" />
* <attribute name="order" default="Ascending">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <enumeration value="Ascending"/>
* <enumeration value="Descending"/>
* </restriction>
* </simpleType>
* </attribute>
* <attribute name="type" default="Field">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <enumeration value="Field"/>
* <enumeration value="Variable"/>
* </restriction>
* </simpleType>
* </attribute>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "")
@XmlRootElement(name = "sortField")
public class SortField {
@XmlAttribute(name = "name", required = true)
protected String name;
@XmlAttribute(name = "order")
protected String order;
@XmlAttribute(name = "type")
protected String type;
/**
* Gets the value of the name property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getName() {
return name;
}
/**
* Sets the value of the name property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setName(String value) {
this.name = value;
}
/**
* Gets the value of the order property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getOrder() {
if (order == null) {
return "Ascending";
} else {
return order;
}
}
/**
* Sets the value of the order property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setOrder(String value) {
this.order = value;
}
/**
* Gets the value of the type property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getType() {
if (type == null) {
return "Field";
} else {
return type;
}
}
/**
* Sets the value of the type property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setType(String value) {
this.type = value;
}
}
|
package com.dtflys.forest.springboot.test;
import com.dtflys.forest.exceptions.ForestRuntimeException;
import com.dtflys.forest.http.ForestRequest;
import com.dtflys.forest.http.ForestResponse;
import com.dtflys.forest.logging.DefaultLogHandler;
import com.dtflys.forest.logging.ForestLogger;
import com.dtflys.forest.retryer.BackOffRetryer;
import com.dtflys.forest.springboot.annotation.ForestScan;
import com.dtflys.forest.springboot.test.moudle.TestUser;
import com.dtflys.forest.config.ForestConfiguration;
import com.dtflys.forest.springboot.test.client0.BeastshopClient;
import com.dtflys.forest.springboot.test.service.impl.TestServiceImpl;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
import javax.annotation.Resource;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertNotNull;
import static org.junit.Assert.*;
@RunWith(SpringRunner.class)
@ActiveProfiles("test0")
@SpringBootTest(classes = Test0.class)
@ComponentScan(basePackages = "com.dtflys.forest.springboot.test.service")
@ForestScan(basePackages = "com.dtflys.forest.springboot.test.client0")
@EnableAutoConfiguration
public class Test0 {
@Resource
private BeastshopClient beastshopClient;
@Autowired
private TestServiceImpl testService;
@Resource(name = "config0")
private ForestConfiguration config0;
@Test
public void testConfiguration() {
assertEquals(Integer.valueOf(1200), config0.getMaxConnections());
assertEquals(Integer.valueOf(1100), config0.getMaxRouteConnections());
assertEquals(Integer.valueOf(1000), config0.getTimeout());
assertEquals(Integer.valueOf(1123), config0.getConnectTimeout());
assertEquals("UTF-8", config0.getCharset());
assertEquals(Integer.valueOf(5), config0.getRetryCount());
assertEquals("okhttp3", config0.getBackend().getName());
assertEquals("SSLv3", config0.getSslProtocol());
assertTrue(config0.getLogHandler() instanceof DefaultLogHandler);
assertEquals("http://www.thebeastshop.com", config0.getVariableValue("baseUrl"));
assertEquals("xxx", config0.getVariableValue("myName"));
assertNotNull(config0.getVariableValue("user"));
assertTrue(!config0.isLogEnabled());
assertEquals(Integer.valueOf(12), config0.getVariableValue("myCount"));
assertEquals(BackOffRetryer.class, config0.getRetryer());
assertEquals(Integer.valueOf(5), config0.getRetryCount());
assertEquals(Long.valueOf(2000), Long.valueOf(config0.getMaxRetryInterval()));
}
@Test
public void testClient0() {
ForestResponse<String> response = beastshopClient.shops();
assertNotNull(response);
assertNotNull(response.getResult());
ForestRequest request = response.getRequest();
assertNotNull(request);
String name = request.getHeaderValue("MyName");
String pass = request.getHeaderValue("MyPass");
assertEquals("foo", name);
assertEquals("bar", pass);
}
@Test
public void testServiceClient0() {
beastshopClient.shops();
ForestResponse<String> response = testService.shops();
assertNotNull(response);
assertNotNull(response.getResult());
ForestRequest request = response.getRequest();
assertNotNull(request);
String name = request.getHeaderValue("MyName");
String pass = request.getHeaderValue("MyPass");
assertEquals("foo", name);
assertEquals("bar", pass);
}
@Test
public void testBug() {
String result = beastshopClient.testBug(1);
assertNotNull(result);
}
@Test
public void testBug2() {
TestUser user = new TestUser();
user.setUsername("foo");
user.setPassword("bar");
String result = beastshopClient.testBug2(user);
assertNotNull(result);
}
@Test
public void testRetry() {
ForestLogger logger = Mockito.mock(ForestLogger.class);
config0.getLogHandler().setLogger(logger);
try {
beastshopClient.testRetry();
} catch (ForestRuntimeException e) {
}
Mockito.verify(logger).info("[Forest] Request: \n" +
"\t[Retry]: 1\n" +
"\tGET http://www.thebeastshop.com/autopage/shops.htm HTTP");
Mockito.verify(logger).info("[Forest] Request: \n" +
"\t[Retry]: 2\n" +
"\tGET http://www.thebeastshop.com/autopage/shops.htm HTTP");
Mockito.verify(logger).info("[Forest] Request: \n" +
"\t[Retry]: 3\n" +
"\tGET http://www.thebeastshop.com/autopage/shops.htm HTTP");
Mockito.verify(logger).info("[Forest] Request: \n" +
"\t[Retry]: 4\n" +
"\tGET http://www.thebeastshop.com/autopage/shops.htm HTTP");
Mockito.verify(logger).info("[Forest] Request: \n" +
"\t[Retry]: 5\n" +
"\tGET http://www.thebeastshop.com/autopage/shops.htm HTTP");
// Mockito.verify(logger).info("[Forest] [Network Error]: connect timed out");
}
}
|
package wvw.mobile.androjena;
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() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("wvw.mobile.androjena", appContext.getPackageName());
}
}
|
package star;
public class Number11111111 {
public static void main(String[] args) {
//number print like
//11111
//22222
//33333
for (int num = 1; num <= 3; num++) {
for (int number = 1; number <= 5; number++) {
System.out.print(num);
}
System.out.println();
}
}
}
|
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class p07_CollectTheCoins {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
List<String> inputs = new ArrayList<>();
for (int i = 0; i < 4; i++) {
String input = scanner.nextLine();
inputs.add(input);
}
char[] moves = scanner.nextLine().toCharArray();
ArrayList<ArrayList<Character>> matrix = new ArrayList<>();
fillMatrix(inputs, matrix);
int currentRow = 0;
int currentCol = 0;
int coins = 0;
int hitWall = 0;
for (char move : moves) {
switch (move) {
case '>':
currentCol++;
if (currentCol >= matrix.get(currentRow).size()) {
currentCol--;
hitWall++;
} else if (matrix.get(currentRow).get(currentCol) == '$') {
coins++;
}
break;
case '<':
currentCol--;
if (currentCol < 0) {
currentCol++;
hitWall++;
} else if (matrix.get(currentRow).get(currentCol) == '$') {
coins++;
}
break;
case '^':
currentRow--;
if (currentRow < 0) {
currentRow++;
hitWall++;
} else if (matrix.get(currentRow).get(currentCol) == '$') {
coins++;
}
break;
case 'V':
currentRow++;
if (currentRow > 3 || currentCol >= matrix.get(currentRow).size()) {
currentRow--;
hitWall++;
} else if (matrix.get(currentRow).get(currentCol) == '$') {
coins++;
}
break;
}
}
System.out.println("Coins = " + coins);
System.out.println("Walls = " + hitWall);
}
private static void fillMatrix(List<String> inputs, ArrayList<ArrayList<Character>> matrix) {
for (int rows = 0; rows < 4; rows++) {
char[] line = inputs.get(rows).toCharArray();
ArrayList<Character> list = new ArrayList<>();
for (char aLine : line) {
list.add(aLine);
}
matrix.add(list);
}
}
}
|
package com.spring.batch.input.xmlreader.domain;
import java.util.Date;
public class Customer {
private final long id;
private final String firstName;
private final String lastName;
private final Date birthdate;
public Customer(long id, String firstName, String lastName, Date birthdate) {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
this.birthdate = birthdate;
}
@Override
public String toString() {
return "Customer{" +
"id=" + id +
", firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
", birthdate=" + birthdate +
'}';
}
}
|
package org.sonar.plugins.clojure;
import org.sonar.api.Plugin;
import org.sonar.plugins.clojure.language.ClojureLanguage;
import org.sonar.plugins.clojure.language.ClojureSonarWayProfile;
import org.sonar.plugins.clojure.rules.ClojureLintRulesDefinition;
import org.sonar.plugins.clojure.sensors.CommandRunner;
import org.sonar.plugins.clojure.sensors.ancient.AncientSensor;
import org.sonar.plugins.clojure.sensors.cloverage.CloverageSensor;
import org.sonar.plugins.clojure.sensors.eastwood.EastwoodSensor;
import org.sonar.plugins.clojure.sensors.kibit.KibitSensor;
import org.sonar.plugins.clojure.sensors.leinnvd.LeinNvdSensor;
import org.sonar.plugins.clojure.settings.Properties;
public class ClojurePlugin implements Plugin {
@Override
public void define(Context context) {
context.addExtension(Properties.getAllProperties());
context.addExtension(ClojureLanguage.class);
context.addExtension(ClojureSonarWayProfile.class);
context.addExtension(ClojureLintRulesDefinition.class);
context.addExtension(CommandRunner.class);
context.addExtension(EastwoodSensor.class);
context.addExtension(KibitSensor.class);
context.addExtension(AncientSensor.class);
context.addExtension(CloverageSensor.class);
context.addExtension(LeinNvdSensor.class);
}
}
|
/*
* Copyright (C) 2008 feilong
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.feilong.excel.reader;
import java.util.ArrayList;
import java.util.List;
/**
* The Interface ReadStatus.
*/
public class ReadStatus{
/** The Constant STATUS_SUCCESS. */
public static final int STATUS_SUCCESS = 0;
//---------------------------------------------------------------
/** The status. */
private int status = STATUS_SUCCESS;
/** The message. */
private String message;
/** The exceptions. */
private List<Exception> exceptions = new ArrayList<>();
//---------------------------------------------------------------
/**
* Instantiates a new read status.
*/
public ReadStatus(){
super();
}
/**
* Instantiates a new read status.
*
* @param status
* the status
* @param message
* the message
*/
public ReadStatus(int status, String message){
super();
this.status = status;
this.message = message;
}
/**
* Instantiates a new read status.
*
* @param status
* the status
* @param message
* the message
* @param exceptions
* the exceptions
*/
public ReadStatus(int status, String message, List<Exception> exceptions){
super();
this.status = status;
this.message = message;
this.exceptions = exceptions;
}
//---------------------------------------------------------------
/**
* Gets the status.
*
* @return the status
*/
public int getStatus(){
return status;
}
/**
* Sets the status.
*
* @param status
* the new status
*/
public void setStatus(int status){
this.status = status;
}
/**
* Gets the message.
*
* @return the message
*/
public String getMessage(){
return message;
}
/**
* Sets the message.
*
* @param message
* the new message
*/
public void setMessage(String message){
this.message = message;
}
/**
* Gets the exceptions.
*
* @return the exceptions
*/
public List<Exception> getExceptions(){
return exceptions;
}
/**
* Sets the exceptions.
*
* @param exceptions
* the new exceptions
*/
public void setExceptions(List<Exception> exceptions){
this.exceptions = exceptions;
}
//---------------------------------------------------------------
/**
* 添加 exception.
*
* @param exception
* the exception
*/
public void addException(Exception exception){
this.exceptions.add(exception);
}
}
|
package com.github.steveice10.mc.protocol.packet.ingame.client.window;
import com.github.steveice10.mc.protocol.data.MagicValues;
import com.github.steveice10.mc.protocol.data.game.entity.metadata.Position;
import com.github.steveice10.mc.protocol.data.game.world.block.CommandBlockMode;
import com.github.steveice10.packetlib.io.NetInput;
import com.github.steveice10.packetlib.io.NetOutput;
import com.github.steveice10.packetlib.packet.Packet;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.NonNull;
import lombok.Setter;
import lombok.With;
import java.io.IOException;
@Data
@With
@Setter(AccessLevel.NONE)
@NoArgsConstructor(access = AccessLevel.PRIVATE)
@AllArgsConstructor
public class ClientUpdateCommandBlockPacket implements Packet {
private static final int FLAG_TRACK_OUTPUT = 0x01;
private static final int FLAG_CONDITIONAL = 0x02;
private static final int FLAG_AUTOMATIC = 0x04;
private @NonNull Position position;
private @NonNull String command;
private @NonNull CommandBlockMode mode;
private boolean doesTrackOutput;
private boolean conditional;
private boolean automatic;
@Override
public void read(NetInput in) throws IOException {
this.position = Position.read(in);
this.command = in.readString();
this.mode = MagicValues.key(CommandBlockMode.class, in.readVarInt());
int flags = in.readUnsignedByte();
this.doesTrackOutput = (flags & FLAG_TRACK_OUTPUT) != 0;
this.conditional = (flags & FLAG_CONDITIONAL) != 0;
this.automatic = (flags & FLAG_AUTOMATIC) != 0;
}
@Override
public void write(NetOutput out) throws IOException {
Position.write(out, this.position);
out.writeString(this.command);
out.writeVarInt(MagicValues.value(Integer.class, this.mode));
int flags = 0;
if (this.doesTrackOutput) {
flags |= FLAG_TRACK_OUTPUT;
}
if (this.conditional) {
flags |= FLAG_CONDITIONAL;
}
if (this.automatic) {
flags |= FLAG_AUTOMATIC;
}
out.writeByte(flags);
}
@Override
public boolean isPriority() {
return false;
}
}
|
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.test.disruption;
import com.carrotsearch.randomizedtesting.generators.RandomPicks;
import org.apache.logging.log4j.Logger;
import org.elasticsearch.common.logging.Loggers;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.util.set.Sets;
import org.elasticsearch.test.InternalTestCluster;
import org.elasticsearch.test.transport.MockTransportService;
import org.elasticsearch.transport.ConnectTransportException;
import org.elasticsearch.transport.TransportService;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Random;
import java.util.Set;
import java.util.function.BiConsumer;
import static org.junit.Assert.assertFalse;
/**
* Network disruptions are modeled using two components:
* 1) the {@link DisruptedLinks} represents the links in the network that are to be disrupted
* 2) the {@link NetworkLinkDisruptionType} represents the failure mode that is to be applied to the links
*/
public class NetworkDisruption implements ServiceDisruptionScheme {
private final Logger logger = Loggers.getLogger(NetworkDisruption.class);
private final DisruptedLinks disruptedLinks;
private final NetworkLinkDisruptionType networkLinkDisruptionType;
protected volatile InternalTestCluster cluster;
protected volatile boolean activeDisruption = false;
public NetworkDisruption(DisruptedLinks disruptedLinks, NetworkLinkDisruptionType networkLinkDisruptionType) {
this.disruptedLinks = disruptedLinks;
this.networkLinkDisruptionType = networkLinkDisruptionType;
}
@Override
public void applyToCluster(InternalTestCluster cluster) {
this.cluster = cluster;
}
@Override
public void removeFromCluster(InternalTestCluster cluster) {
stopDisrupting();
}
@Override
public void removeAndEnsureHealthy(InternalTestCluster cluster) {
removeFromCluster(cluster);
ensureNodeCount(cluster);
}
protected void ensureNodeCount(InternalTestCluster cluster) {
assertFalse("cluster failed to form after disruption was healed", cluster.client().admin().cluster().prepareHealth()
.setWaitForNodes("" + cluster.size())
.setWaitForNoRelocatingShards(true)
.get().isTimedOut());
}
@Override
public synchronized void applyToNode(String node, InternalTestCluster cluster) {
}
@Override
public synchronized void removeFromNode(String node1, InternalTestCluster cluster) {
logger.info("stop disrupting node (disruption type: {}, disrupted links: {})", networkLinkDisruptionType, disruptedLinks);
applyToNodes(new String[]{ node1 }, cluster.getNodeNames(), networkLinkDisruptionType::removeDisruption);
applyToNodes(cluster.getNodeNames(), new String[]{ node1 }, networkLinkDisruptionType::removeDisruption);
}
@Override
public synchronized void testClusterClosed() {
}
@Override
public synchronized void startDisrupting() {
logger.info("start disrupting (disruption type: {}, disrupted links: {})", networkLinkDisruptionType, disruptedLinks);
applyToNodes(cluster.getNodeNames(), cluster.getNodeNames(), networkLinkDisruptionType::applyDisruption);
activeDisruption = true;
}
@Override
public synchronized void stopDisrupting() {
if (!activeDisruption) {
return;
}
logger.info("stop disrupting (disruption scheme: {}, disrupted links: {})", networkLinkDisruptionType, disruptedLinks);
applyToNodes(cluster.getNodeNames(), cluster.getNodeNames(), networkLinkDisruptionType::removeDisruption);
activeDisruption = false;
}
/**
* Applies action to all disrupted links between two sets of nodes.
*/
private void applyToNodes(String[] nodes1, String[] nodes2, BiConsumer<MockTransportService, MockTransportService> consumer) {
for (String node1 : nodes1) {
if (disruptedLinks.nodes().contains(node1)) {
for (String node2 : nodes2) {
if (disruptedLinks.nodes().contains(node2)) {
if (node1.equals(node2) == false) {
if (disruptedLinks.disrupt(node1, node2)) {
consumer.accept(transport(node1), transport(node2));
}
}
}
}
}
}
}
@Override
public TimeValue expectedTimeToHeal() {
return networkLinkDisruptionType.expectedTimeToHeal();
}
private MockTransportService transport(String node) {
return (MockTransportService) cluster.getInstance(TransportService.class, node);
}
/**
* Represents a set of nodes with connections between nodes that are to be disrupted
*/
public abstract static class DisruptedLinks {
private final Set<String> nodes;
protected DisruptedLinks(Set<String>... nodeSets) {
Set<String> allNodes = new HashSet<>();
for (Set<String> nodeSet : nodeSets) {
allNodes.addAll(nodeSet);
}
this.nodes = allNodes;
}
/**
* Set of all nodes that can participate in disruptions
*/
public Set<String> nodes() {
return nodes;
}
/**
* Returns true iff network should be disrupted between the two nodes
*/
public abstract boolean disrupt(String node1, String node2);
}
/**
* Creates two partitions with symmetric failures
*/
public static class TwoPartitions extends DisruptedLinks {
protected final Set<String> nodesSideOne;
protected final Set<String> nodesSideTwo;
public TwoPartitions(String node1, String node2) {
this(Collections.singleton(node1), Collections.singleton(node2));
}
public TwoPartitions(Set<String> nodesSideOne, Set<String> nodesSideTwo) {
super(nodesSideOne, nodesSideTwo);
this.nodesSideOne = nodesSideOne;
this.nodesSideTwo = nodesSideTwo;
assert nodesSideOne.isEmpty() == false;
assert nodesSideTwo.isEmpty() == false;
assert Sets.haveEmptyIntersection(nodesSideOne, nodesSideTwo);
}
public static TwoPartitions random(Random random, String... nodes) {
return random(random, Sets.newHashSet(nodes));
}
public static TwoPartitions random(Random random, Set<String> nodes) {
assert nodes.size() >= 2 : "two partitions topology requires at least 2 nodes";
Set<String> nodesSideOne = new HashSet<>();
Set<String> nodesSideTwo = new HashSet<>();
for (String node : nodes) {
if (nodesSideOne.isEmpty()) {
nodesSideOne.add(node);
} else if (nodesSideTwo.isEmpty()) {
nodesSideTwo.add(node);
} else if (random.nextBoolean()) {
nodesSideOne.add(node);
} else {
nodesSideTwo.add(node);
}
}
return new TwoPartitions(nodesSideOne, nodesSideTwo);
}
@Override
public boolean disrupt(String node1, String node2) {
if (nodesSideOne.contains(node1) && nodesSideTwo.contains(node2)) {
return true;
}
if (nodesSideOne.contains(node2) && nodesSideTwo.contains(node1)) {
return true;
}
return false;
}
public Set<String> getNodesSideOne() {
return Collections.unmodifiableSet(nodesSideOne);
}
public Set<String> getNodesSideTwo() {
return Collections.unmodifiableSet(nodesSideTwo);
}
public Collection<String> getMajoritySide() {
if (nodesSideOne.size() >= nodesSideTwo.size()) {
return getNodesSideOne();
} else {
return getNodesSideTwo();
}
}
public Collection<String> getMinoritySide() {
if (nodesSideOne.size() >= nodesSideTwo.size()) {
return getNodesSideTwo();
} else {
return getNodesSideOne();
}
}
@Override
public String toString() {
return "two partitions (partition 1: " + nodesSideOne + " and partition 2: " + nodesSideTwo + ")";
}
}
/**
* Creates two partitions with symmetric failures and a bridge node that can connect to both of the partitions
*/
public static class Bridge extends DisruptedLinks {
private final String bridgeNode;
private final Set<String> nodesSideOne;
private final Set<String> nodesSideTwo;
public Bridge(String bridgeNode, Set<String> nodesSideOne, Set<String> nodesSideTwo) {
super(Collections.singleton(bridgeNode), nodesSideOne, nodesSideTwo);
this.bridgeNode = bridgeNode;
this.nodesSideOne = nodesSideOne;
this.nodesSideTwo = nodesSideTwo;
assert nodesSideOne.isEmpty() == false;
assert nodesSideTwo.isEmpty() == false;
assert Sets.haveEmptyIntersection(nodesSideOne, nodesSideTwo);
assert nodesSideOne.contains(bridgeNode) == false && nodesSideTwo.contains(bridgeNode) == false;
}
public static Bridge random(Random random, String... nodes) {
return random(random, Sets.newHashSet(nodes));
}
public static Bridge random(Random random, Set<String> nodes) {
assert nodes.size() >= 3 : "bridge topology requires at least 3 nodes";
String bridgeNode = RandomPicks.randomFrom(random, nodes);
Set<String> nodesSideOne = new HashSet<>();
Set<String> nodesSideTwo = new HashSet<>();
for (String node : nodes) {
if (node.equals(bridgeNode) == false) {
if (nodesSideOne.isEmpty()) {
nodesSideOne.add(node);
} else if (nodesSideTwo.isEmpty()) {
nodesSideTwo.add(node);
} else if (random.nextBoolean()) {
nodesSideOne.add(node);
} else {
nodesSideTwo.add(node);
}
}
}
return new Bridge(bridgeNode, nodesSideOne, nodesSideTwo);
}
@Override
public boolean disrupt(String node1, String node2) {
if (nodesSideOne.contains(node1) && nodesSideTwo.contains(node2)) {
return true;
}
if (nodesSideOne.contains(node2) && nodesSideTwo.contains(node1)) {
return true;
}
return false;
}
public String getBridgeNode() {
return bridgeNode;
}
public Set<String> getNodesSideOne() {
return nodesSideOne;
}
public Set<String> getNodesSideTwo() {
return nodesSideTwo;
}
public String toString() {
return "bridge partition (super connected node: [" + bridgeNode + "], partition 1: " + nodesSideOne +
" and partition 2: " + nodesSideTwo + ")";
}
}
public static class IsolateAllNodes extends DisruptedLinks {
public IsolateAllNodes(Set<String> nodes) {
super(nodes);
}
@Override
public boolean disrupt(String node1, String node2) {
return true;
}
}
/**
* Abstract class representing various types of network disruptions. Instances of this class override the {@link #applyDisruption}
* method to apply their specific disruption type to requests that are send from a source to a target node.
*/
public abstract static class NetworkLinkDisruptionType {
/**
* Applies network disruption for requests send from the node represented by the source transport service to the node represented
* by the target transport service.
*
* @param sourceTransportService source transport service from which requests are sent
* @param targetTransportService target transport service to which requests are sent
*/
public abstract void applyDisruption(MockTransportService sourceTransportService, MockTransportService targetTransportService);
/**
* Removes network disruption that was added by {@link #applyDisruption}.
*
* @param sourceTransportService source transport service from which requests are sent
* @param targetTransportService target transport service to which requests are sent
*/
public void removeDisruption(MockTransportService sourceTransportService, MockTransportService targetTransportService) {
sourceTransportService.clearRule(targetTransportService);
}
/**
* Returns expected time to heal after disruption has been removed. Defaults to instant healing.
*/
public TimeValue expectedTimeToHeal() {
return TimeValue.timeValueMillis(0);
}
}
/**
* Simulates a network disconnect. Sending a request from source to target node throws a {@link ConnectTransportException}.
*/
public static class NetworkDisconnect extends NetworkLinkDisruptionType {
@Override
public void applyDisruption(MockTransportService sourceTransportService, MockTransportService targetTransportService) {
sourceTransportService.addFailToSendNoConnectRule(targetTransportService);
}
@Override
public String toString() {
return "network disconnects";
}
}
/**
* Simulates an unresponsive target node by dropping requests sent from source to target node.
*/
public static class NetworkUnresponsive extends NetworkLinkDisruptionType {
@Override
public void applyDisruption(MockTransportService sourceTransportService, MockTransportService targetTransportService) {
sourceTransportService.addUnresponsiveRule(targetTransportService);
}
@Override
public String toString() {
return "network unresponsive";
}
}
/**
* Simulates slow or congested network. Delivery of requests that are sent from source to target node are delayed by a configurable
* time amount.
*/
public static class NetworkDelay extends NetworkLinkDisruptionType {
public static TimeValue DEFAULT_DELAY_MIN = TimeValue.timeValueSeconds(10);
public static TimeValue DEFAULT_DELAY_MAX = TimeValue.timeValueSeconds(90);
private final TimeValue delay;
/**
* Delays requests by a fixed time value.
*
* @param delay time to delay requests
*/
public NetworkDelay(TimeValue delay) {
this.delay = delay;
}
/**
* Delays requests by a random but fixed time value between {@link #DEFAULT_DELAY_MIN} and {@link #DEFAULT_DELAY_MAX}.
*
* @param random instance to use for randomization of delay
*/
public static NetworkDelay random(Random random) {
return random(random, DEFAULT_DELAY_MIN, DEFAULT_DELAY_MAX);
}
/**
* Delays requests by a random but fixed time value between delayMin and delayMax.
*
* @param random instance to use for randomization of delay
* @param delayMin minimum delay
* @param delayMax maximum delay
*/
public static NetworkDelay random(Random random, TimeValue delayMin, TimeValue delayMax) {
return new NetworkDelay(TimeValue.timeValueMillis(delayMin.millis() == delayMax.millis() ?
delayMin.millis() :
delayMin.millis() + random.nextInt((int) (delayMax.millis() - delayMin.millis()))));
}
@Override
public void applyDisruption(MockTransportService sourceTransportService, MockTransportService targetTransportService) {
sourceTransportService.addUnresponsiveRule(targetTransportService, delay);
}
@Override
public TimeValue expectedTimeToHeal() {
return delay;
}
@Override
public String toString() {
return "network delays for [" + delay + "]";
}
}
}
|
package com.github.malitsplus.shizurunotes.data.action;
import com.github.malitsplus.shizurunotes.R;
import com.github.malitsplus.shizurunotes.common.I18N;
import com.github.malitsplus.shizurunotes.data.Property;
import com.github.malitsplus.shizurunotes.utils.Utils;
class PassiveDamageUpAction extends ActionParameter {
protected double debuffDamageUpValue;
protected double debuffDamageUpLimitValue;
protected double debuffDamageUpTimer;
protected eCountType countType;
protected eEffectType effectType;
@Override
protected void childInit() {
debuffDamageUpLimitValue = actionValue2;
debuffDamageUpValue = actionValue1;
debuffDamageUpTimer = actionValue3;
countType = eCountType.parse(actionDetail1);
effectType = eEffectType.parse(actionDetail2);
actionValues.add(new ActionValue(actionValue3, actionValue4, null));
}
@Override
public String localizedDetail(int level, Property property) {
switch (countType) {
case Debuff:
return I18N.getString(R.string.Make_s1_damage_changes_into_s234_times_caps_to_s5_times_dur_s6_sec,
targetParameter.buildTargetClause(),
effectType.description(),
Utils.roundIfNeed(debuffDamageUpValue),
countType.description(),
Utils.roundIfNeed(debuffDamageUpLimitValue),
buildExpression(level, property)
);
default:
return localizedDetail(level, property);
}
}
protected enum eCountType {
Unknown(-1),
Debuff(1);
private int value;
eCountType(int value){
this.value = value;
}
public int getValue(){
return value;
}
public static eCountType parse(int value){
for(eCountType item : eCountType.values()){
if(item.getValue() == value)
return item;
}
return Unknown;
}
public String description() {
switch (this) {
case Debuff:
return I18N.getString(R.string.debuff);
default:
return I18N.getString(R.string.Unknown);
}
}
}
protected enum eEffectType {
Unknown(-1),
Add(1),
Subtract(2);
private int value;
eEffectType(int value){
this.value = value;
}
public int getValue(){
return value;
}
public static eEffectType parse(int value){
for(eEffectType item : eEffectType.values()){
if(item.getValue() == value)
return item;
}
return Unknown;
}
public String description() {
switch (this) {
case Add:
return I18N.getString(R.string.add);
case Subtract:
return I18N.getString(R.string.subtract);
default:
return I18N.getString(R.string.Unknown);
}
}
}
}
|
/**
* 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.camel.processor;
import org.junit.Test;
import org.apache.camel.ContextTestSupport;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import static org.apache.camel.processor.ExchangeAwareDelayCalcBean.BEAN_DELAYER_HEADER;
/**
* @version
*/
public class DelayerTest extends ContextTestSupport {
private MyDelayCalcBean bean = new MyDelayCalcBean();
private ExchangeAwareDelayCalcBean exchangeAwareBean = new ExchangeAwareDelayCalcBean();
@Test
public void testSendingMessageGetsDelayed() throws Exception {
MockEndpoint resultEndpoint = resolveMandatoryEndpoint("mock:result", MockEndpoint.class);
// do not wait for the first message
resultEndpoint.expectedMessageCount(0);
resultEndpoint.setResultWaitTime(10);
template.sendBodyAndHeader("seda:a", "<hello>world!</hello>", "MyDelay", 100);
// we should not receive it as we wait at most 0.01 sec and it take 0.1 sec to send
resultEndpoint.assertIsSatisfied();
// now if we wait a bit longer we should receive the message!
resultEndpoint.reset();
resultEndpoint.expectedMessageCount(1);
resultEndpoint.assertIsSatisfied();
}
@Test
public void testDelayConstant() throws Exception {
MockEndpoint resultEndpoint = resolveMandatoryEndpoint("mock:result", MockEndpoint.class);
resultEndpoint.expectedMessageCount(1);
// should at least take 0.1 sec to complete
resultEndpoint.setResultMinimumWaitTime(90);
template.sendBody("seda:b", "<hello>world!</hello>");
resultEndpoint.assertIsSatisfied();
}
@Test
public void testDelayBean() throws Exception {
MockEndpoint resultEndpoint = resolveMandatoryEndpoint("mock:result", MockEndpoint.class);
resultEndpoint.expectedMessageCount(1);
// should at least take 0.1 sec to complete
resultEndpoint.setResultMinimumWaitTime(90);
template.sendBody("seda:c", "<hello>world!</hello>");
resultEndpoint.assertIsSatisfied();
}
@Test
public void testExchangeAwareDelayBean() throws Exception {
MockEndpoint resultEndpoint = resolveMandatoryEndpoint("mock:result", MockEndpoint.class);
resultEndpoint.expectedMessageCount(1);
// should at least take 0.1 sec to complete
resultEndpoint.setResultMinimumWaitTime(90);
template.sendBodyAndHeader("seda:d", "<hello>world!</hello>", BEAN_DELAYER_HEADER, 100);
resultEndpoint.assertIsSatisfied();
}
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
public void configure() {
// START SNIPPET: ex
from("seda:a").delay().header("MyDelay").to("mock:result");
// END SNIPPET: ex
// START SNIPPET: ex2
from("seda:b").delay(100).to("mock:result");
// END SNIPPET: ex2
// START SNIPPET: ex3
from("seda:c").delay().method(bean, "delayMe").to("mock:result");
// END SNIPPET: ex3
from("seda:d").delay().method(exchangeAwareBean, "delayMe").to("mock:result");
}
};
}
}
|
package com.alibaba.easyexcel.test.core.style;
import com.alibaba.excel.annotation.ExcelProperty;
import lombok.Data;
/**
* @author Jiaju Zhuang
*/
@Data
public class StyleData {
@ExcelProperty("字符串")
private String string;
@ExcelProperty("字符串1")
private String string1;
}
|
package Custom_List_Iterator;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.function.Consumer;
public class CustomList<T extends Comparable<T>> implements Iterable<T> {
private List<T> list;
public CustomList() {
this.list = new ArrayList<>();
}
public void add(T element) {
this.list.add(element);
}
public T remove(int index) {
return this.list.remove(index);
}
public boolean contains(T element) {
return this.list.contains(element);
}
public void swap(int index1, int index2) {
T temp = list.get(index1);
list.set(index1, list.get(index2));
list.set(index2, temp);
}
public int countGreaterThan(T element) {
int count = 0;
for (T el : list) {
if (element.compareTo(el) < 0) {
count++;
}
}
return count;
}
public T getMax() {
T max = list.get(0);
for (T element : list) {
if (element.compareTo(max) > 0) {
max = element;
}
}
return max;
}
public T getMin() {
T min = list.get(0);
for (T element : list) {
if (element.compareTo(min) < 0) {
min = element;
}
}
return min;
}
@Override
public Iterator<T> iterator() {
return new Iterator<T>() {
private int index = 0;
@Override
public boolean hasNext() {
return this.index < list.size();
}
@Override
public T next() {
return list.get(this.index++);
}
};
}
}
|
package byps.test.api.remote;
/*
* Serializer for byps.test.api.remote.BRequest_RemoteSetTypes_getInt2
*
* THIS FILE HAS BEEN GENERATED BY class byps.gen.j.GenSerStruct DO NOT MODIFY.
*/
import byps.*;
// DEBUG
// isEnum=false
// isFinal=true
// isInline=false
// #members=0
// checkpoint byps.gen.j.GenSerStruct:304
@SuppressWarnings("all")
public class BSerializer_1772226269 extends BSerializer {
public final static BSerializer instance = new BSerializer_1772226269();
public BSerializer_1772226269() {
super(1772226269);
}
public BSerializer_1772226269(int typeId) {
super(typeId);
}
@Override
public Object read(final Object obj1, final BInput bin1, final long version) throws BException {
final BInputBin bin = (BInputBin)bin1;
final BRequest_RemoteSetTypes_getInt2 obj = (BRequest_RemoteSetTypes_getInt2)(obj1 != null ? obj1 : bin.onObjectCreated(new BRequest_RemoteSetTypes_getInt2()));
return obj;
}
@Override
public void prepareForLazyLoading(final Object obj1, final BInput bin, final long version) throws BException {
}
}
|
/*
* 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.camel.example.kubernetes.jkube;
import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class CqlPopulateBean {
private static final Logger log = LoggerFactory.getLogger(CqlPopulateBean.class);
public void populate() {
Cluster cluster = Cluster.builder().addContactPoint("cassandra").build();
Session session = cluster.connect();
session.execute("CREATE KEYSPACE IF NOT EXISTS test WITH REPLICATION = {'class':'SimpleStrategy', 'replication_factor':1};");
session.execute("CREATE TABLE IF NOT EXISTS test.users ( id int primary key, name text );");
session.execute("INSERT INTO test.users (id,name) VALUES (1, 'oscerd') IF NOT EXISTS;");
session.execute("INSERT INTO test.users (id,name) VALUES (2, 'not-a-bot') IF NOT EXISTS;");
session.close();
cluster.close();
log.info("Cassandra was populated with sample values for test.users table");
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.language.perl.project.existing.sources;
import java.io.File;
import javax.swing.JFileChooser;
import javax.swing.JPanel;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.Document;
import org.netbeans.spi.project.ui.support.ProjectChooser;
import org.openide.WizardDescriptor;
import org.openide.WizardValidationException;
import org.openide.filesystems.FileUtil;
public class PerlProjectWithExistingSourcesPanelVisual extends JPanel implements DocumentListener {
public static final String PROP_PROJECT_NAME = "projectName";
public static final String PERL_PROJECT = ".perl_project.ini";
public static final String PERL_PROJECT_EXISTING_SOURCES = ".perl_project_existing_sources.ini";
private PerlProjectWithExistingSourcesWizardPanel panel;
public PerlProjectWithExistingSourcesPanelVisual(PerlProjectWithExistingSourcesWizardPanel panel) {
initComponents();
this.panel = panel;
projectNameTextField.getDocument().addDocumentListener(this);
projectLocationTextField.getDocument().addDocumentListener(this);
}
public String getProjectName() {
return this.projectNameTextField.getText();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jScrollPane2 = new javax.swing.JScrollPane();
jTable1 = new javax.swing.JTable();
projectNameLabel = new javax.swing.JLabel();
projectNameTextField = new javax.swing.JTextField();
projectLocationLabel = new javax.swing.JLabel();
projectLocationTextField = new javax.swing.JTextField();
browseButton = new javax.swing.JButton();
jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"Title 1", "Title 2", "Title 3", "Title 4"
}
));
jScrollPane2.setViewportView(jTable1);
projectNameLabel.setLabelFor(projectNameTextField);
org.openide.awt.Mnemonics.setLocalizedText(projectNameLabel, "Project &Name:");
projectNameTextField.setEditable(false);
projectLocationLabel.setLabelFor(projectLocationTextField);
org.openide.awt.Mnemonics.setLocalizedText(projectLocationLabel, "Project &Location:");
projectLocationTextField.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
projectLocationTextFieldActionPerformed(evt);
}
});
org.openide.awt.Mnemonics.setLocalizedText(browseButton, "Br&owse...");
browseButton.setActionCommand("BROWSE");
browseButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
browseButtonActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(projectLocationLabel)
.addComponent(projectNameLabel))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(projectNameTextField)
.addComponent(projectLocationTextField, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 166, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(browseButton)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(projectLocationLabel)
.addComponent(projectLocationTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(browseButton))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(projectNameLabel)
.addComponent(projectNameTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(178, Short.MAX_VALUE))
);
}// </editor-fold>//GEN-END:initComponents
private void browseButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_browseButtonActionPerformed
String command = evt.getActionCommand();
if ("BROWSE".equals(command)) {
JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory(null);
chooser.setDialogTitle("Select Project Location");
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
String path = this.projectLocationTextField.getText();
if (path.length() > 0) {
File f = new File(path);
if (f.exists()) {
chooser.setSelectedFile(f);
}
}
if (JFileChooser.APPROVE_OPTION == chooser.showOpenDialog(this)) {
File projectDir = chooser.getSelectedFile();
projectLocationTextField.setText(FileUtil.normalizeFile(projectDir).getAbsolutePath());
projectNameTextField.setText(FileUtil.normalizeFile(projectDir).getName());
}
panel.fireChangeEvent();
}
}//GEN-LAST:event_browseButtonActionPerformed
private void projectLocationTextFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_projectLocationTextFieldActionPerformed
}//GEN-LAST:event_projectLocationTextFieldActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton browseButton;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JTable jTable1;
private javax.swing.JLabel projectLocationLabel;
private javax.swing.JTextField projectLocationTextField;
private javax.swing.JLabel projectNameLabel;
private javax.swing.JTextField projectNameTextField;
// End of variables declaration//GEN-END:variables
@Override
public void addNotify() {
super.addNotify();
//same problem as in 31086, initial focus on Cancel button
}
boolean valid(WizardDescriptor wizardDescriptor) {
/*
if (projectNameTextField.getText().length() == 0) {
// TODO if using org.openide.dialogs >= 7.8, can use WizardDescriptor.PROP_ERROR_MESSAGE:
wizardDescriptor.putProperty("WizardPanel_errorMessage",
"Project Name is not a valid folder name.");
return false; // Display name not specified
}
File f = FileUtil.normalizeFile(new File(projectLocationTextField.getText()).getAbsoluteFile());
if (!f.isDirectory()) {
String message = "Project Folder is not a valid path.";
wizardDescriptor.putProperty("WizardPanel_errorMessage", message);
return false;
}*/
final File destFolder = FileUtil.normalizeFile(new File(projectLocationTextField.getText()).getAbsoluteFile());
File projLoc = destFolder;
/*
while (projLoc != null && !projLoc.exists()) {
projLoc = projLoc.getParentFile();
}
if (projLoc == null || !projLoc.canWrite()) {
wizardDescriptor.putProperty("WizardPanel_errorMessage",
"Project Folder is read-only.");
return false;
}
*/
if (FileUtil.toFileObject(projLoc) == null) {
String message = "Project Folder is not a valid path.";
wizardDescriptor.putProperty("WizardPanel_errorMessage", message);
return false;
}
/*
File[] kids = destFolder.listFiles();
if (destFolder.exists() && kids != null && kids.length > 0) {
// Folder exists and is not empty
wizardDescriptor.putProperty("WizardPanel_errorMessage",
"Project Folder already exists and is not empty.");
return false;
}
*/
File PerlProjectIndicator = new File(destFolder.getAbsoluteFile().getAbsoluteFile() + File.separator + PERL_PROJECT);
if (PerlProjectIndicator.exists()) {
wizardDescriptor.putProperty("WizardPanel_errorMessage",
"Project Folder is already a Perl Project.");
return false;
}
File PerlProjectWithExistinSourcesIndicator = new File(destFolder.getAbsoluteFile().getAbsoluteFile() + File.separator + PERL_PROJECT_EXISTING_SOURCES);
if (PerlProjectWithExistinSourcesIndicator.exists()) {
wizardDescriptor.putProperty("WizardPanel_errorMessage",
"Project Folder is already a Perl Project.");
return false;
}
wizardDescriptor.putProperty("WizardPanel_errorMessage", "");
return true;
}
void store(WizardDescriptor d) {
String name = projectNameTextField.getText().trim();
String folder = projectLocationTextField.getText().trim();
d.putProperty("projdir", new File(folder));
d.putProperty("name", name);
}
void read(WizardDescriptor settings) {
File projectLocation = (File) settings.getProperty("projdir");
if (projectLocation == null || projectLocation.getParentFile() == null || !projectLocation.getParentFile().isDirectory()) {
projectLocation = ProjectChooser.getProjectsFolder();
} else {
projectLocation = projectLocation.getParentFile();
}
this.projectLocationTextField.setText(projectLocation.getAbsolutePath());
String projectName = (String) settings.getProperty("name");
if (projectName == null) {
projectName = projectLocation.getName();
}
this.projectNameTextField.setText(projectName);
}
void validate(WizardDescriptor wizardDescriptor) throws WizardValidationException {
// nothing to validate
}
// Implementation of DocumentListener --------------------------------------
@Override
public void changedUpdate(DocumentEvent e) {
updateTexts(e);
if (this.projectNameTextField.getDocument() == e.getDocument()) {
firePropertyChange(PROP_PROJECT_NAME, null, this.projectNameTextField.getText());
}
}
@Override
public void insertUpdate(DocumentEvent e) {
updateTexts(e);
if (this.projectNameTextField.getDocument() == e.getDocument()) {
firePropertyChange(PROP_PROJECT_NAME, null, this.projectNameTextField.getText());
}
}
@Override
public void removeUpdate(DocumentEvent e) {
updateTexts(e);
if (this.projectNameTextField.getDocument() == e.getDocument()) {
firePropertyChange(PROP_PROJECT_NAME, null, this.projectNameTextField.getText());
}
}
/**
* Handles changes in the Project name and project directory,
*/
private void updateTexts(DocumentEvent e) {
Document doc = e.getDocument();
if (doc == projectNameTextField.getDocument() || doc == projectLocationTextField.getDocument()) {
// Change in the project name
String projectName = projectNameTextField.getText();
String projectFolder = projectLocationTextField.getText();
//createdFolderTextField.setText(projectFolder + File.separatorChar + projectName);
}
panel.fireChangeEvent(); // Notify that the panel changed
}
}
|
package com.daimajia.slider.demo;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.daimajia.slider.library.SliderLayout;
/**
* Created by daimajia on 14-5-29.
*/
public class TransformerAdapter extends BaseAdapter {
private Context mContext;
public TransformerAdapter(Context context) {
mContext = context;
}
@Override
public int getCount() {
return SliderLayout.Transformer.values().length;
}
@Override
public Object getItem(int position) {
return SliderLayout.Transformer.values()[position].toString();
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
TextView t = (TextView) convertView;
if (t == null)
t = (TextView) LayoutInflater.from(mContext).inflate(R.layout.item, parent, false);
t.setText(getItem(position).toString());
return t;
}
}
|
// Targeted by JavaCPP version 1.5-SNAPSHOT: DO NOT EDIT THIS FILE
package org.bytedeco.liquidfun;
import java.nio.*;
import org.bytedeco.javacpp.*;
import org.bytedeco.javacpp.annotation.*;
import static org.bytedeco.liquidfun.global.liquidfun.*;
/** Small color object for each particle */
@NoOffset @Properties(inherit = org.bytedeco.liquidfun.presets.liquidfun.class)
public class b2ParticleColor extends Pointer {
static { Loader.load(); }
/** Pointer cast constructor. Invokes {@link Pointer#Pointer(Pointer)}. */
public b2ParticleColor(Pointer p) { super(p); }
/** Native array allocator. Access with {@link Pointer#position(long)}. */
public b2ParticleColor(long size) { super((Pointer)null); allocateArray(size); }
private native void allocateArray(long size);
@Override public b2ParticleColor position(long position) {
return (b2ParticleColor)super.position(position);
}
public b2ParticleColor() { super((Pointer)null); allocate(); }
private native void allocate();
/** Constructor with four elements: r (red), g (green), b (blue), and a
* (opacity).
* Each element can be specified 0 to 255. */
public b2ParticleColor(@Cast("uint8") short r, @Cast("uint8") short g, @Cast("uint8") short b, @Cast("uint8") short a) { super((Pointer)null); allocate(r, g, b, a); }
private native void allocate(@Cast("uint8") short r, @Cast("uint8") short g, @Cast("uint8") short b, @Cast("uint8") short a);
/** Constructor that initializes the above four elements with the value of
* the b2Color object. */
///
public b2ParticleColor(@Const @ByRef b2Color color) { super((Pointer)null); allocate(color); }
private native void allocate(@Const @ByRef b2Color color);
/** True when all four color elements equal 0. When true, a particle color
* buffer isn't allocated by CreateParticle().
* */
///
public native @Cast("bool") boolean IsZero();
/** Used internally to convert the value of b2Color.
* */
///
public native @ByVal b2Color GetColor();
/** Sets color for current object using the four elements described above.
* */
///
public native void Set(@Cast("uint8") short r_, @Cast("uint8") short g_, @Cast("uint8") short b_, @Cast("uint8") short a_);
/** Initializes the object with the value of the b2Color.
* */
public native void Set(@Const @ByRef b2Color color);
/** Assign a b2ParticleColor to this instance. */
public native @ByRef @Name("operator =") b2ParticleColor put(@Const @ByRef b2ParticleColor color);
/** Multiplies r, g, b, a members by s where s is a value between 0.0
* and 1.0. */
public native @ByRef @Name("operator *=") b2ParticleColor multiplyPut(@Cast("float32") float s);
/** Scales r, g, b, a members by s where s is a value between 0 and 255. */
public native @ByRef @Name("operator *=") b2ParticleColor multiplyPut(@Cast("uint8") short s);
/** Scales r, g, b, a members by s returning the modified b2ParticleColor. */
public native @ByVal @Name("operator *") b2ParticleColor multiply(@Cast("float32") float s);
/** Scales r, g, b, a members by s returning the modified b2ParticleColor. */
public native @ByVal @Name("operator *") b2ParticleColor multiply(@Cast("uint8") short s);
/** Add two colors. This is a non-saturating addition so values
* overflows will wrap. */
public native @ByRef @Name("operator +=") b2ParticleColor addPut(@Const @ByRef b2ParticleColor color);
/** Add two colors. This is a non-saturating addition so values
* overflows will wrap. */
public native @ByVal @Name("operator +") b2ParticleColor add(@Const @ByRef b2ParticleColor color);
/** Subtract a color from this color. This is a subtraction without
* saturation so underflows will wrap. */
public native @ByRef @Name("operator -=") b2ParticleColor subtractPut(@Const @ByRef b2ParticleColor color);
/** Subtract a color from this color returning the result. This is a
* subtraction without saturation so underflows will wrap. */
public native @ByVal @Name("operator -") b2ParticleColor subtract(@Const @ByRef b2ParticleColor color);
/** Compare this color with the specified color. */
public native @Cast("bool") @Name("operator ==") boolean equals(@Const @ByRef b2ParticleColor color);
/** Mix mixColor with this color using strength to control how much of
* mixColor is mixed with this color and vice versa. The range of
* strength is 0..128 where 0 results in no color mixing and 128 results
* in an equal mix of both colors. strength 0..128 is analogous to an
* alpha channel value between 0.0f..0.5f. */
public native void Mix(b2ParticleColor mixColor, @Cast("const int32") int strength);
/** Mix colorA with colorB using strength to control how much of
* colorA is mixed with colorB and vice versa. The range of
* strength is 0..128 where 0 results in no color mixing and 128 results
* in an equal mix of both colors. strength 0..128 is analogous to an
* alpha channel value between 0.0f..0.5f. */
public static native void MixColors(b2ParticleColor colorA,
b2ParticleColor colorB,
@Cast("const int32") int strength);
public native @Cast("uint8") short r(); public native b2ParticleColor r(short r);
public native @Cast("uint8") short g(); public native b2ParticleColor g(short g);
public native @Cast("uint8") short b(); public native b2ParticleColor b(short b);
public native @Cast("uint8") short a(); public native b2ParticleColor a(short a);
}
|
package com.twistlet.qir.admin.usermanagement.controller;
import static org.hamcrest.core.IsEqual.*;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.hamcrest.core.IsSame;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.web.servlet.ModelAndView;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.twistlet.qir.admin.usermanagement.service.UserManagementService;
import com.twistlet.qir.common.model.entity.User;
public class UserManagementControllerTest {
private UserManagementController sut;
private List<User> list;
@Mock
private UserManagementService userManagementService;
@Before
public void init() {
MockitoAnnotations.initMocks(this);
list = new ArrayList<User>();
list.add(new User());
list.add(new User());
list.add(new User());
list.add(new User());
when(userManagementService.listUser()).thenReturn(list);
sut = new UserManagementController(userManagementService);
}
@Test
public void testList() {
final ModelAndView mav = sut.list();
@SuppressWarnings("unchecked")
final List<User> list = (List<User>) mav.getModel().get("list");
assertEquals(4, list.size());
}
@Test
public void testRemoveError() throws JsonProcessingException {
doThrow(new RuntimeException("ignore: fake exception on delete user"))
.when(userManagementService).remove("1");
final Map<String, String> map = sut.remove("1");
final ObjectMapper objectMapper = new ObjectMapper();
final String actual = objectMapper.writeValueAsString(map);
final String expected = "{\"status\":\"error\",\"message\":\"java.lang.RuntimeException: ignore: fake exception on delete user\"}";
assertThat(actual, equalTo(expected));
}
@Test
public void testRemoveSuccess() throws JsonProcessingException {
final Map<String, String> map = sut.remove("1");
final ObjectMapper objectMapper = new ObjectMapper();
final String actual = objectMapper.writeValueAsString(map);
final String expected = "{\"status\":\"success\",\"id\":\"1\"}";
assertThat(actual, equalTo(expected));
}
@Test
public void testPasswordChange() {
final User user = new User();
user.setFullname("Bill Joy");
when(userManagementService.get("abc")).thenReturn(user);
final ModelAndView mav = sut.passwordChange("abc");
assertThat(mav.getModel().get("user"), IsSame.sameInstance(user));
}
}
|
/*
* Copyright 2019-2020 Zheng Jie
*
* 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 me.zhengjie.hd.BhApply.rest;
import me.zhengjie.annotation.Log;
import me.zhengjie.hd.BhApply.domain.BhApply;
import me.zhengjie.hd.BhApply.service.BhApplyService;
import me.zhengjie.hd.BhApply.service.dto.BhApplyQueryCriteria;
import org.springframework.data.domain.Pageable;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.*;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
/**
* @website https://el-admin.vip
* @author fb
* @date 2020-07-28
**/
@RestController
@RequiredArgsConstructor
@Api(tags = "主申请人管理")
@RequestMapping("/api/bhApply")
public class BhApplyController {
private final BhApplyService bhApplyService;
@Log("导出数据")
@ApiOperation("导出数据")
@GetMapping(value = "/download")
@PreAuthorize("@el.check('bhApply:list')")
public void download(HttpServletResponse response, BhApplyQueryCriteria criteria) throws IOException {
bhApplyService.download(bhApplyService.queryAll(criteria), response);
}
@GetMapping
@Log("查询主申请人")
@ApiOperation("查询主申请人")
@PreAuthorize("@el.check('bhApply:list')")
public ResponseEntity<Object> query(BhApplyQueryCriteria criteria, Pageable pageable){
return new ResponseEntity<>(bhApplyService.queryAll(criteria,pageable),HttpStatus.OK);
}
@PostMapping
@Log("新增主申请人")
@ApiOperation("新增主申请人")
@PreAuthorize("@el.check('bhApply:add')")
public ResponseEntity<Object> create(@Validated @RequestBody BhApply resources){
return new ResponseEntity<>(bhApplyService.create(resources),HttpStatus.CREATED);
}
@PutMapping
@Log("修改主申请人")
@ApiOperation("修改主申请人")
@PreAuthorize("@el.check('bhApply:edit')")
public ResponseEntity<Object> update(@Validated @RequestBody BhApply resources){
bhApplyService.update(resources);
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
@Log("删除主申请人")
@ApiOperation("删除主申请人")
@PreAuthorize("@el.check('bhApply:del')")
@DeleteMapping
public ResponseEntity<Object> delete(@RequestBody String[] ids) {
bhApplyService.deleteAll(ids);
return new ResponseEntity<>(HttpStatus.OK);
}
}
|
/*
* Copyright 2000-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.application.options.codeStyle.arrangement.match;
import com.intellij.application.options.codeStyle.arrangement.ArrangementConstants;
import com.intellij.application.options.codeStyle.arrangement.color.ArrangementColorsProvider;
import com.intellij.application.options.codeStyle.arrangement.util.TitleWithToolbar;
import com.intellij.ide.ui.customization.CustomizationUtil;
import com.intellij.lang.Language;
import com.intellij.openapi.actionSystem.DataProvider;
import com.intellij.openapi.application.ApplicationBundle;
import com.intellij.psi.codeStyle.arrangement.match.ArrangementSectionRule;
import com.intellij.psi.codeStyle.arrangement.std.StdArrangementRuleAliasToken;
import com.intellij.psi.codeStyle.arrangement.std.ArrangementStandardSettingsManager;
import com.intellij.ui.components.JBScrollPane;
import com.intellij.util.ui.GridBag;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.*;
import java.util.Collection;
import java.util.List;
/**
* @author Denis Zhdanov
* @since 10/30/12 5:28 PM
*/
public class ArrangementMatchingRulesPanel extends JPanel implements DataProvider {
@NotNull protected final ArrangementSectionRulesControl myControl;
public ArrangementMatchingRulesPanel(@NotNull Language language,
@NotNull ArrangementStandardSettingsManager settingsManager,
@NotNull ArrangementColorsProvider colorsProvider)
{
super(new GridBagLayout());
JBScrollPane scrollPane = new JBScrollPane();
final JViewport viewport = scrollPane.getViewport();
ArrangementSectionRulesControl.RepresentationCallback callback = new ArrangementSectionRulesControl.RepresentationCallback() {
@Override
public void ensureVisible(@NotNull Rectangle r) {
Rectangle visibleRect = viewport.getViewRect();
if (r.y <= visibleRect.y) {
return;
}
int excessiveHeight = r.y + r.height - (visibleRect.y + visibleRect.height);
if (excessiveHeight <= 0) {
return;
}
int verticalShift = Math.min(r.y - visibleRect.y, excessiveHeight);
if (verticalShift > 0) {
viewport.setViewPosition(new Point(visibleRect.x, visibleRect.y + verticalShift));
}
}
};
myControl = createRulesControl(language, settingsManager, colorsProvider, callback);
scrollPane.setViewportView(myControl);
CustomizationUtil.installPopupHandler(
myControl, ArrangementConstants.ACTION_GROUP_MATCHING_RULES_CONTEXT_MENU, ArrangementConstants.MATCHING_RULES_CONTROL_PLACE
);
TitleWithToolbar top = new TitleWithToolbar(
ApplicationBundle.message("arrangement.settings.section.match"),
ArrangementConstants.ACTION_GROUP_MATCHING_RULES_CONTROL_TOOLBAR,
ArrangementConstants.MATCHING_RULES_CONTROL_TOOLBAR_PLACE,
myControl
);
add(top, new GridBag().coverLine().fillCellHorizontally().weightx(1));
add(scrollPane, new GridBag().fillCell().weightx(1).weighty(1).insets(0, ArrangementConstants.HORIZONTAL_PADDING, 0, 0));
}
protected ArrangementSectionRulesControl createRulesControl(@NotNull Language language,
@NotNull ArrangementStandardSettingsManager settingsManager,
@NotNull ArrangementColorsProvider colorsProvider,
@NotNull ArrangementSectionRulesControl.RepresentationCallback callback) {
return new ArrangementSectionRulesControl(language, settingsManager, colorsProvider, callback);
}
@NotNull
public List<ArrangementSectionRule> getSections() {
return myControl.getSections();
}
public void setSections(@Nullable List<ArrangementSectionRule> rules) {
myControl.setSections(rules);
}
@Nullable
public Collection<StdArrangementRuleAliasToken> getRulesAliases() {
return myControl.getRulesAliases();
}
public void setRulesAliases(@Nullable Collection<StdArrangementRuleAliasToken> aliases) {
myControl.setRulesAliases(aliases);
}
public void hideEditor() {
myControl.hideEditor();
}
@Nullable
@Override
public Object getData(@NonNls String dataId) {
if (ArrangementSectionRulesControl.KEY.is(dataId)) {
return myControl;
}
return null;
}
}
|
package com.dong.cms.utils;
import java.io.InputStream;
import java.util.Properties;
/**
*
* @ClassName: PropertiesUtil
* @Description: properties配置文件工具类
* @author dong
* @date May 6, 2019 4:26:46 PM
* @keywords :
*
*/
public class PropertiesUtil {
/**
* 根据key获取value,数据写在配置文件cms.properties中
* @param key
* @return
*/
public static String getValue(String key) {
Properties prop = new Properties();
InputStream in = PropertiesUtil.class.getResourceAsStream("/cms.properties");
try {
prop.load(in);
} catch (Exception e) {
e.printStackTrace();
}
return prop.getProperty(key);
}
/*public static void main(String[] args) {
System.out.println(PropertiesUtil.getValue("host"));
}*/
}
|
import java.util.Objects;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Wojciech Orzechowski
*/
class Person {
private int id;
private String name;
public Person(int id, String name) {
this.id = id;
this.name = name;
}
@Override
public String toString() {
return "Person: id = " + id + ", name = " + name;
}
@Override
public int hashCode() {
int hash = 7;
hash = 47 * hash + this.id;
hash = 47 * hash + Objects.hashCode(this.name);
return hash;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Person other = (Person) obj;
if (this.id != other.id) {
return false;
}
if (!Objects.equals(this.name, other.name)) {
return false;
}
return true;
}
}
public class Main {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Person person1 = new Person(7, "Bob");
Person person2 = new Person(7, "Bob");
// They point to two different objects, which are same semantically.
System.out.println(person2 == person1);
// Semantical comparison
System.out.println(person1.equals(person2));
System.out.println(person2.equals(person1));
// Working with values
// It will not work with Doubles
Double d1 = 7.2;
Double d2 = 7.2;
System.out.println(d1 == d2);
System.out.println(d1.equals(d2));
// '==' is checking if it is pointing at the same objects
// Don't use it to compare non-primitives.
// Use '.equals()'
String t1 = "Hello";
String t2 = "Hello, hi".substring(0, 5);
System.out.println(t1);
System.out.println(t2);
// They point at two different objects...
System.out.println(t1 == t2);
// ... but are same semantically
System.out.println(t1.equals(t2));
}
}
|
package com.casa.misc;
import java.util.List;
import com.casa.misc.forms.MerchantForm;
import com.smslai_eoddb.data.Tbbillspayment;
import com.smslai_eoddb.data.Tbcheckbook;
import com.smslai_eoddb.data.Tbmerchant;
import com.smslai_eoddb.data.Tbmiscellaneous;
import com.smslai_eoddb.data.Tbpassbookissuance;
public interface MiscTxService {
List<MerchantForm> getMerchantList();
String createPayment(Tbbillspayment payment);
String createMiscTx(Tbmiscellaneous misc);
String addMerchant(Tbmerchant merch);
String checkbookIssuance(Tbcheckbook data);
String passbookIssuance(Tbpassbookissuance pbissuance);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.