text
stringlengths
7
1.01M
/* * Copyright (c) 2008-2019, Hazelcast, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hazelcast.map.impl.querycache.accumulator; import com.hazelcast.map.impl.querycache.event.sequence.Sequenced; import java.util.concurrent.atomic.AtomicLong; import static com.hazelcast.util.Preconditions.checkNotNull; import static com.hazelcast.util.Preconditions.checkPositive; import static com.hazelcast.util.QuickMath.nextPowerOfTwo; /** * Default implementation of {@link CyclicBuffer} interface. * This class is not thread-safe and only one thread can access it at a time. * * @param <E> the element to be placed in this buffer. * @see CyclicBuffer */ public class DefaultCyclicBuffer<E extends Sequenced> implements CyclicBuffer<E> { private static final long UNAVAILABLE = -1L; private int capacity; private E[] buffer; private AtomicLong headSequence; private AtomicLong tailSequence; public DefaultCyclicBuffer(int capacity) throws IllegalArgumentException { checkPositive(capacity, "capacity"); init(capacity); } private void init(int maxSize) { this.capacity = nextPowerOfTwo(maxSize); this.buffer = (E[]) new Sequenced[capacity]; this.tailSequence = new AtomicLong(UNAVAILABLE); this.headSequence = new AtomicLong(UNAVAILABLE); } @Override public void add(E event) { checkNotNull(event, "event cannot be null"); long sequence = event.getSequence(); int tailIndex = findIndex(sequence); buffer[tailIndex] = event; tailSequence.set(sequence); long head = headSequence.get(); if (head == UNAVAILABLE) { headSequence.set(sequence); } else { if (head != sequence) { int headIndex = findIndex(head); if (headIndex == tailIndex) { if (++headIndex == capacity) { headIndex = 0; } E e = buffer[headIndex]; if (e != null) { headSequence.set(e.getSequence()); } else { headSequence.incrementAndGet(); } } } } } @Override public E get(long sequence) { checkPositive(sequence, "sequence"); int index = findIndex(sequence); E e = buffer[index]; if (e != null && e.getSequence() != sequence) { return null; } return e; } @Override public boolean setHead(long sequence) { checkPositive(sequence, "sequence"); E e = get(sequence); if (e == null) { return false; } else { headSequence.set(sequence); return true; } } @Override public E getAndAdvance() { long head = headSequence.get(); long tail = tailSequence.get(); if (tail == UNAVAILABLE || head > tail) { return null; } int headIndex = findIndex(head); E e = buffer[headIndex]; if (e == null) { return null; } headSequence.incrementAndGet(); return e; } @Override public void reset() { init(this.capacity); } @Override public int size() { long head = headSequence.get(); long tail = tailSequence.get(); if (tail == UNAVAILABLE) { return 0; } int avail = (int) (tail - head + 1); if (avail <= capacity) { return avail; } else { return capacity; } } @Override public long getHeadSequence() { return headSequence.get(); } private int findIndex(long sequence) { return (int) (sequence % capacity); } }
package sketches.demo; import static sketches.demo.UtilsKt.showHLLDetails; import java.util.stream.IntStream; import java.util.stream.LongStream; import org.apache.datasketches.hll.HllSketch; import org.apache.datasketches.hll.Union; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; public class HyperLogLog { @Test @DisplayName("Count to 5M and compare sketches of different sizes") void lgkComparison() { var hllSketch12 = new HllSketch(12); var hllSketch16 = new HllSketch(16); var hllSketch20 = new HllSketch(20); showHLLDetails(hllSketch12, 0); showHLLDetails(hllSketch16, 0); showHLLDetails(hllSketch20, 0); IntStream.range(0, 5_000_000) .mapToObj(it -> "user_" + it) .forEach(it -> { hllSketch12.update(it); hllSketch16.update(it); hllSketch20.update(it); }); showHLLDetails(hllSketch12, 5_000_000); showHLLDetails(hllSketch16, 5_000_000); showHLLDetails(hllSketch20, 5_000_000); } @Test @DisplayName("Count to 300M and compare a small and large sketch") void extremeCount() { var small = new HllSketch(10); var large = new HllSketch(20); IntStream.range(0, 300_000_000) .mapToObj(it -> "user_" + it) .forEach(it -> { small.update(it); large.update(it); }); showHLLDetails(small, 300_000_000); showHLLDetails(large, 300_000_000); } @Test @DisplayName("Union between sketches") void unionExample() { var lgK = 12; // varying lgK changes size and precision of sketches+unions var sketch0To75k = new HllSketch(lgK); var sketch50kTo100k = new HllSketch(lgK); // Use different items/types to get different accuracy LongStream.range(0, 75_000) // .mapToObj(it -> "user_" + it) .forEach(sketch0To75k::update); LongStream.range(50_000, 100_000) // .mapToObj(it -> "user_" + it) .forEach(sketch50kTo100k::update); showHLLDetails(sketch0To75k, 75_000); showHLLDetails(sketch50kTo100k, 50_000); var union = new Union(lgK); union.update(sketch0To75k); union.update(sketch50kTo100k); showHLLDetails(union.getResult(), 100_000); } @Test @DisplayName("Serialize and deserialize sketch") void serializationExample() { var sketch0To75k = new HllSketch(); LongStream.range(0, 75_000).mapToObj(it -> "user_" + it).forEach(sketch0To75k::update); showHLLDetails(sketch0To75k, 75_000); var firstSketchBytes = sketch0To75k.toCompactByteArray(); Assertions.assertEquals(sketch0To75k.getCompactSerializationBytes(), firstSketchBytes.length); var reconstructed0to75kSketch = HllSketch.heapify(firstSketchBytes); showHLLDetails(reconstructed0to75kSketch, 75_000); reconstructed0to75kSketch.update("another value"); } }
package com.atlassian.jira.plugins.dvcs.pageobjects.common; import com.atlassian.pageobjects.Page; public interface PageController<T extends Page> { T getPage(); }
/* * 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.solr.response; import org.apache.lucene.search.Query; import org.apache.solr.handler.component.ResponseBuilder; import org.apache.solr.request.SolrQueryRequest; import org.apache.solr.search.DocList; import org.apache.solr.search.ReturnFields; import org.apache.solr.search.SolrIndexSearcher; public class BasicResultContext extends ResultContext { private DocList docList; private ReturnFields returnFields; private SolrIndexSearcher searcher; private Query query; private SolrQueryRequest req; public BasicResultContext(DocList docList, ReturnFields returnFields, SolrIndexSearcher searcher, Query query, SolrQueryRequest req) { this.docList = docList; this.returnFields = returnFields; this.searcher = searcher; this.query = query; this.req = req; } public BasicResultContext(ResponseBuilder rb) { this(rb.getResults().docList, rb.rsp.getReturnFields(), null, rb.getQuery(), rb.req); } public BasicResultContext(ResponseBuilder rb, DocList docList) { this(docList, rb.rsp.getReturnFields(), null, rb.getQuery(), rb.req); } @Override public DocList getDocList() { return docList; } @Override public ReturnFields getReturnFields() { return returnFields; } @Override public SolrIndexSearcher getSearcher() { if (searcher != null) return searcher; if (req != null) return req.getSearcher(); return null; } @Override public Query getQuery() { return query; } @Override public SolrQueryRequest getRequest() { return req; } }
package cwurbs.demo.docker; import cwurbs.demo.docker.health.TemplateHealthCheck; import cwurbs.demo.docker.resources.EstimationResource; import io.dropwizard.Application; import io.dropwizard.setup.Bootstrap; import io.dropwizard.setup.Environment; public class JobType1Application extends Application<JobType1Configuration> { public static void main(final String[] args) throws Exception { new JobType1Application().run(args); } @Override public String getName() { return "JobType1"; } @Override public void initialize(final Bootstrap<JobType1Configuration> bootstrap) { // TODO: application initialization } @Override public void run(final JobType1Configuration configuration, final Environment environment) { final EstimationResource resource = new EstimationResource( configuration.getTemplate(), configuration.getDefaultName() ); environment.jersey().register(resource); final TemplateHealthCheck healthCheck = new TemplateHealthCheck(configuration.getTemplate()); environment.healthChecks().register("template", healthCheck); } }
package com.exmaple.util; public class Greeting { private final long id; private final String content; public Greeting(long id, String content) { this.id = id; this.content = content; } public long getId() { return id; } public String getContent() { return content; } }
/* * Copyright (c) 2017-2018 THL A29 Limited, a Tencent company. 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.tencentcloudapi.tcss.v20201101.models; import com.tencentcloudapi.common.AbstractModel; import com.google.gson.annotations.SerializedName; import com.google.gson.annotations.Expose; import java.util.HashMap; public class DescribeVirusScanTaskStatusResponse extends AbstractModel{ /** * 查杀容器个数 */ @SerializedName("ContainerTotal") @Expose private Long ContainerTotal; /** * 风险容器个数 */ @SerializedName("RiskContainerCnt") @Expose private Long RiskContainerCnt; /** * 扫描状态 任务状态: SCAN_NONE:无, SCAN_SCANNING:正在扫描中, SCAN_FINISH:扫描完成, SCAN_TIMEOUT:扫描超时 SCAN_CANCELING: 取消中 SCAN_CANCELED:已取消 */ @SerializedName("Status") @Expose private String Status; /** * 扫描进度 I */ @SerializedName("Schedule") @Expose private Long Schedule; /** * 已经扫描了的容器个数 */ @SerializedName("ContainerScanCnt") @Expose private Long ContainerScanCnt; /** * 风险个数 */ @SerializedName("RiskCnt") @Expose private Long RiskCnt; /** * 剩余扫描时间 */ @SerializedName("LeftSeconds") @Expose private Long LeftSeconds; /** * 扫描开始时间 */ @SerializedName("StartTime") @Expose private String StartTime; /** * 扫描结束时间 */ @SerializedName("EndTime") @Expose private String EndTime; /** * 扫描类型,"CYCLE":周期扫描, "MANUAL":手动扫描 */ @SerializedName("ScanType") @Expose private String ScanType; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ @SerializedName("RequestId") @Expose private String RequestId; /** * Get 查杀容器个数 * @return ContainerTotal 查杀容器个数 */ public Long getContainerTotal() { return this.ContainerTotal; } /** * Set 查杀容器个数 * @param ContainerTotal 查杀容器个数 */ public void setContainerTotal(Long ContainerTotal) { this.ContainerTotal = ContainerTotal; } /** * Get 风险容器个数 * @return RiskContainerCnt 风险容器个数 */ public Long getRiskContainerCnt() { return this.RiskContainerCnt; } /** * Set 风险容器个数 * @param RiskContainerCnt 风险容器个数 */ public void setRiskContainerCnt(Long RiskContainerCnt) { this.RiskContainerCnt = RiskContainerCnt; } /** * Get 扫描状态 任务状态: SCAN_NONE:无, SCAN_SCANNING:正在扫描中, SCAN_FINISH:扫描完成, SCAN_TIMEOUT:扫描超时 SCAN_CANCELING: 取消中 SCAN_CANCELED:已取消 * @return Status 扫描状态 任务状态: SCAN_NONE:无, SCAN_SCANNING:正在扫描中, SCAN_FINISH:扫描完成, SCAN_TIMEOUT:扫描超时 SCAN_CANCELING: 取消中 SCAN_CANCELED:已取消 */ public String getStatus() { return this.Status; } /** * Set 扫描状态 任务状态: SCAN_NONE:无, SCAN_SCANNING:正在扫描中, SCAN_FINISH:扫描完成, SCAN_TIMEOUT:扫描超时 SCAN_CANCELING: 取消中 SCAN_CANCELED:已取消 * @param Status 扫描状态 任务状态: SCAN_NONE:无, SCAN_SCANNING:正在扫描中, SCAN_FINISH:扫描完成, SCAN_TIMEOUT:扫描超时 SCAN_CANCELING: 取消中 SCAN_CANCELED:已取消 */ public void setStatus(String Status) { this.Status = Status; } /** * Get 扫描进度 I * @return Schedule 扫描进度 I */ public Long getSchedule() { return this.Schedule; } /** * Set 扫描进度 I * @param Schedule 扫描进度 I */ public void setSchedule(Long Schedule) { this.Schedule = Schedule; } /** * Get 已经扫描了的容器个数 * @return ContainerScanCnt 已经扫描了的容器个数 */ public Long getContainerScanCnt() { return this.ContainerScanCnt; } /** * Set 已经扫描了的容器个数 * @param ContainerScanCnt 已经扫描了的容器个数 */ public void setContainerScanCnt(Long ContainerScanCnt) { this.ContainerScanCnt = ContainerScanCnt; } /** * Get 风险个数 * @return RiskCnt 风险个数 */ public Long getRiskCnt() { return this.RiskCnt; } /** * Set 风险个数 * @param RiskCnt 风险个数 */ public void setRiskCnt(Long RiskCnt) { this.RiskCnt = RiskCnt; } /** * Get 剩余扫描时间 * @return LeftSeconds 剩余扫描时间 */ public Long getLeftSeconds() { return this.LeftSeconds; } /** * Set 剩余扫描时间 * @param LeftSeconds 剩余扫描时间 */ public void setLeftSeconds(Long LeftSeconds) { this.LeftSeconds = LeftSeconds; } /** * Get 扫描开始时间 * @return StartTime 扫描开始时间 */ public String getStartTime() { return this.StartTime; } /** * Set 扫描开始时间 * @param StartTime 扫描开始时间 */ public void setStartTime(String StartTime) { this.StartTime = StartTime; } /** * Get 扫描结束时间 * @return EndTime 扫描结束时间 */ public String getEndTime() { return this.EndTime; } /** * Set 扫描结束时间 * @param EndTime 扫描结束时间 */ public void setEndTime(String EndTime) { this.EndTime = EndTime; } /** * Get 扫描类型,"CYCLE":周期扫描, "MANUAL":手动扫描 * @return ScanType 扫描类型,"CYCLE":周期扫描, "MANUAL":手动扫描 */ public String getScanType() { return this.ScanType; } /** * Set 扫描类型,"CYCLE":周期扫描, "MANUAL":手动扫描 * @param ScanType 扫描类型,"CYCLE":周期扫描, "MANUAL":手动扫描 */ public void setScanType(String ScanType) { this.ScanType = ScanType; } /** * Get 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 * @return RequestId 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ public String getRequestId() { return this.RequestId; } /** * Set 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 * @param RequestId 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ public void setRequestId(String RequestId) { this.RequestId = RequestId; } public DescribeVirusScanTaskStatusResponse() { } /** * NOTE: Any ambiguous key set via .set("AnyKey", "value") will be a shallow copy, * and any explicit key, i.e Foo, set via .setFoo("value") will be a deep copy. */ public DescribeVirusScanTaskStatusResponse(DescribeVirusScanTaskStatusResponse source) { if (source.ContainerTotal != null) { this.ContainerTotal = new Long(source.ContainerTotal); } if (source.RiskContainerCnt != null) { this.RiskContainerCnt = new Long(source.RiskContainerCnt); } if (source.Status != null) { this.Status = new String(source.Status); } if (source.Schedule != null) { this.Schedule = new Long(source.Schedule); } if (source.ContainerScanCnt != null) { this.ContainerScanCnt = new Long(source.ContainerScanCnt); } if (source.RiskCnt != null) { this.RiskCnt = new Long(source.RiskCnt); } if (source.LeftSeconds != null) { this.LeftSeconds = new Long(source.LeftSeconds); } if (source.StartTime != null) { this.StartTime = new String(source.StartTime); } if (source.EndTime != null) { this.EndTime = new String(source.EndTime); } if (source.ScanType != null) { this.ScanType = new String(source.ScanType); } if (source.RequestId != null) { this.RequestId = new String(source.RequestId); } } /** * Internal implementation, normal users should not use it. */ public void toMap(HashMap<String, String> map, String prefix) { this.setParamSimple(map, prefix + "ContainerTotal", this.ContainerTotal); this.setParamSimple(map, prefix + "RiskContainerCnt", this.RiskContainerCnt); this.setParamSimple(map, prefix + "Status", this.Status); this.setParamSimple(map, prefix + "Schedule", this.Schedule); this.setParamSimple(map, prefix + "ContainerScanCnt", this.ContainerScanCnt); this.setParamSimple(map, prefix + "RiskCnt", this.RiskCnt); this.setParamSimple(map, prefix + "LeftSeconds", this.LeftSeconds); this.setParamSimple(map, prefix + "StartTime", this.StartTime); this.setParamSimple(map, prefix + "EndTime", this.EndTime); this.setParamSimple(map, prefix + "ScanType", this.ScanType); this.setParamSimple(map, prefix + "RequestId", this.RequestId); } }
package com.checktrip.mas.checktrip; 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.*; /** * Instrumentation 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("com.checktrip.mas.checktrip", appContext.getPackageName()); } }
package dev.thunderegg; /** * Represents the neighbor of a patch * * @author Scott Aiton */ public class EdgeNeighbor { /** * The edge of the patch that the neighbor is on */ public Edge edge; /** * The type of neighbor */ public String type; /** * The ids of the neighboring patches */ public int[] ids; /** * The ranks of the neighboring patches */ public int[] ranks; /** * The orthant of the neighboring patch */ public Orthant orth_on_coarse; /** * Create new Neighbor * * @param edge the edge that the neighbor is on * @param type the type of neighbor can be "coarse", "fine", or * "normal" * @param ids the ids of the neighbors * @param ranks the ranks of the neighbors * @param orth_on_coarse the orthant on the neighbor if "coarse", null otherwise */ public EdgeNeighbor(Edge edge, String type, int[] ids, int[] ranks, Orthant orth_on_coarse) { this.edge = edge; this.type = type; this.ids = ids; this.ranks = ranks; this.orth_on_coarse = orth_on_coarse; } }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.mapred; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.InetSocketAddress; import java.security.PrivilegedExceptionAction; import java.util.EnumSet; import java.util.HashMap; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; import org.apache.commons.lang.StringUtils; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.CommonConfigurationKeysPublic; import org.apache.hadoop.ipc.RPC; import org.apache.hadoop.mapreduce.JobID; import org.apache.hadoop.mapreduce.JobStatus; import org.apache.hadoop.mapreduce.MRJobConfig; import org.apache.hadoop.mapreduce.TaskAttemptID; import org.apache.hadoop.mapreduce.TaskType; import org.apache.hadoop.mapreduce.TypeConverter; import org.apache.hadoop.mapreduce.v2.LogParams; import org.apache.hadoop.mapreduce.v2.api.MRClientProtocol; import org.apache.hadoop.mapreduce.v2.api.protocolrecords.FailTaskAttemptRequest; import org.apache.hadoop.mapreduce.v2.api.protocolrecords.GetCountersRequest; import org.apache.hadoop.mapreduce.v2.api.protocolrecords.GetCountersResponse; import org.apache.hadoop.mapreduce.v2.api.protocolrecords.GetDiagnosticsRequest; import org.apache.hadoop.mapreduce.v2.api.protocolrecords.GetDiagnosticsResponse; import org.apache.hadoop.mapreduce.v2.api.protocolrecords.GetJobReportRequest; import org.apache.hadoop.mapreduce.v2.api.protocolrecords.GetJobReportResponse; import org.apache.hadoop.mapreduce.v2.api.protocolrecords.GetTaskAttemptCompletionEventsRequest; import org.apache.hadoop.mapreduce.v2.api.protocolrecords.GetTaskAttemptCompletionEventsResponse; import org.apache.hadoop.mapreduce.v2.api.protocolrecords.GetTaskAttemptReportRequest; import org.apache.hadoop.mapreduce.v2.api.protocolrecords.GetTaskAttemptReportResponse; import org.apache.hadoop.mapreduce.v2.api.protocolrecords.GetTaskReportsRequest; import org.apache.hadoop.mapreduce.v2.api.protocolrecords.GetTaskReportsResponse; import org.apache.hadoop.mapreduce.v2.api.protocolrecords.KillJobRequest; import org.apache.hadoop.mapreduce.v2.api.protocolrecords.KillTaskAttemptRequest; import org.apache.hadoop.mapreduce.v2.api.records.AMInfo; import org.apache.hadoop.mapreduce.v2.api.records.Counters; import org.apache.hadoop.mapreduce.v2.api.records.JobReport; import org.apache.hadoop.mapreduce.v2.api.records.JobState; import org.apache.hadoop.mapreduce.v2.api.records.TaskAttemptReport; import org.apache.hadoop.mapreduce.v2.util.MRApps; import org.apache.hadoop.net.NetUtils; import org.apache.hadoop.security.UserGroupInformation; import org.apache.hadoop.security.authorize.AuthorizationException; import org.apache.hadoop.security.token.Token; import org.apache.hadoop.yarn.api.records.ApplicationId; import org.apache.hadoop.yarn.api.records.ApplicationReport; import org.apache.hadoop.yarn.api.records.NodeId; import org.apache.hadoop.yarn.api.records.YarnApplicationState; import org.apache.hadoop.yarn.exceptions.ApplicationNotFoundException; import org.apache.hadoop.yarn.exceptions.YarnException; import org.apache.hadoop.yarn.exceptions.YarnRuntimeException; import org.apache.hadoop.yarn.factories.RecordFactory; import org.apache.hadoop.yarn.factory.providers.RecordFactoryProvider; import org.apache.hadoop.yarn.ipc.YarnRPC; import org.apache.hadoop.yarn.security.client.ClientToAMTokenIdentifier; import org.apache.hadoop.yarn.util.ConverterUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.annotations.VisibleForTesting; public class ClientServiceDelegate { private static final Logger LOG = LoggerFactory.getLogger(ClientServiceDelegate.class); private static final String UNAVAILABLE = "N/A"; // Caches for per-user NotRunningJobs private HashMap<JobState, HashMap<String, NotRunningJob>> notRunningJobs; private final Configuration conf; private final JobID jobId; private final ApplicationId appId; private final ResourceMgrDelegate rm; private final MRClientProtocol historyServerProxy; private MRClientProtocol realProxy = null; private RecordFactory recordFactory = RecordFactoryProvider.getRecordFactory(null); private static String UNKNOWN_USER = "Unknown User"; private String trackingUrl; private AtomicBoolean usingAMProxy = new AtomicBoolean(false); private int maxClientRetry; private boolean amAclDisabledStatusLogged = false; public ClientServiceDelegate(Configuration conf, ResourceMgrDelegate rm, JobID jobId, MRClientProtocol historyServerProxy) { this.conf = new Configuration(conf); // Cloning for modifying. // For faster redirects from AM to HS. this.conf.setInt( CommonConfigurationKeysPublic.IPC_CLIENT_CONNECT_MAX_RETRIES_KEY, this.conf.getInt(MRJobConfig.MR_CLIENT_TO_AM_IPC_MAX_RETRIES, MRJobConfig.DEFAULT_MR_CLIENT_TO_AM_IPC_MAX_RETRIES)); this.conf.setInt( CommonConfigurationKeysPublic.IPC_CLIENT_CONNECT_MAX_RETRIES_ON_SOCKET_TIMEOUTS_KEY, this.conf.getInt(MRJobConfig.MR_CLIENT_TO_AM_IPC_MAX_RETRIES_ON_TIMEOUTS, MRJobConfig.DEFAULT_MR_CLIENT_TO_AM_IPC_MAX_RETRIES_ON_TIMEOUTS)); this.rm = rm; this.jobId = jobId; this.historyServerProxy = historyServerProxy; this.appId = TypeConverter.toYarn(jobId).getAppId(); notRunningJobs = new HashMap<JobState, HashMap<String, NotRunningJob>>(); } // Get the instance of the NotRunningJob corresponding to the specified // user and state private NotRunningJob getNotRunningJob(ApplicationReport applicationReport, JobState state) { synchronized (notRunningJobs) { HashMap<String, NotRunningJob> map = notRunningJobs.get(state); if (map == null) { map = new HashMap<String, NotRunningJob>(); notRunningJobs.put(state, map); } String user = (applicationReport == null) ? UNKNOWN_USER : applicationReport.getUser(); NotRunningJob notRunningJob = map.get(user); if (notRunningJob == null) { notRunningJob = new NotRunningJob(applicationReport, state); map.put(user, notRunningJob); } return notRunningJob; } } private MRClientProtocol getProxy() throws IOException { if (realProxy != null) { return realProxy; } // Possibly allow nulls through the PB tunnel, otherwise deal with an exception // and redirect to the history server. ApplicationReport application = null; try { application = rm.getApplicationReport(appId); } catch (ApplicationNotFoundException e) { application = null; } catch (YarnException e2) { throw new IOException(e2); } if (application != null) { trackingUrl = application.getTrackingUrl(); } InetSocketAddress serviceAddr = null; while (application == null || YarnApplicationState.RUNNING == application .getYarnApplicationState()) { if (application == null) { LOG.info("Could not get Job info from RM for job " + jobId + ". Redirecting to job history server."); return checkAndGetHSProxy(null, JobState.NEW); } try { if (application.getHost() == null || "".equals(application.getHost())) { LOG.debug("AM not assigned to Job. Waiting to get the AM ..."); Thread.sleep(2000); LOG.debug("Application state is " + application.getYarnApplicationState()); application = rm.getApplicationReport(appId); continue; } else if (UNAVAILABLE.equals(application.getHost())) { if (!amAclDisabledStatusLogged) { LOG.info("Job " + jobId + " is running, but the host is unknown." + " Verify user has VIEW_JOB access."); amAclDisabledStatusLogged = true; } return getNotRunningJob(application, JobState.RUNNING); } if(!conf.getBoolean(MRJobConfig.JOB_AM_ACCESS_DISABLED, false)) { UserGroupInformation newUgi = UserGroupInformation.createRemoteUser( UserGroupInformation.getCurrentUser().getUserName()); serviceAddr = NetUtils.createSocketAddrForHost( application.getHost(), application.getRpcPort()); if (UserGroupInformation.isSecurityEnabled()) { org.apache.hadoop.yarn.api.records.Token clientToAMToken = application.getClientToAMToken(); Token<ClientToAMTokenIdentifier> token = ConverterUtils.convertFromYarn(clientToAMToken, serviceAddr); newUgi.addToken(token); } LOG.debug("Connecting to " + serviceAddr); final InetSocketAddress finalServiceAddr = serviceAddr; realProxy = newUgi.doAs(new PrivilegedExceptionAction<MRClientProtocol>() { @Override public MRClientProtocol run() throws IOException { return instantiateAMProxy(finalServiceAddr); } }); } else { if (!amAclDisabledStatusLogged) { LOG.info("Network ACL closed to AM for job " + jobId + ". Not going to try to reach the AM."); amAclDisabledStatusLogged = true; } return getNotRunningJob(null, JobState.RUNNING); } return realProxy; } catch (IOException e) { //possibly the AM has crashed //there may be some time before AM is restarted //keep retrying by getting the address from RM LOG.info("Could not connect to " + serviceAddr + ". Waiting for getting the latest AM address..."); try { Thread.sleep(2000); } catch (InterruptedException e1) { LOG.warn("getProxy() call interruped", e1); throw new YarnRuntimeException(e1); } try { application = rm.getApplicationReport(appId); } catch (YarnException e1) { throw new IOException(e1); } if (application == null) { LOG.info("Could not get Job info from RM for job " + jobId + ". Redirecting to job history server."); return checkAndGetHSProxy(null, JobState.RUNNING); } } catch (InterruptedException e) { LOG.warn("getProxy() call interruped", e); throw new YarnRuntimeException(e); } catch (YarnException e) { throw new IOException(e); } } /** we just want to return if its allocating, so that we don't * block on it. This is to be able to return job status * on an allocating Application. */ String user = application.getUser(); if (user == null) { throw new IOException("User is not set in the application report"); } if (application.getYarnApplicationState() == YarnApplicationState.NEW || application.getYarnApplicationState() == YarnApplicationState.NEW_SAVING || application.getYarnApplicationState() == YarnApplicationState.SUBMITTED || application.getYarnApplicationState() == YarnApplicationState.ACCEPTED) { realProxy = null; return getNotRunningJob(application, JobState.NEW); } if (application.getYarnApplicationState() == YarnApplicationState.FAILED) { realProxy = null; return getNotRunningJob(application, JobState.FAILED); } if (application.getYarnApplicationState() == YarnApplicationState.KILLED) { realProxy = null; return getNotRunningJob(application, JobState.KILLED); } //History server can serve a job only if application //succeeded. if (application.getYarnApplicationState() == YarnApplicationState.FINISHED) { LOG.info("Application state is completed. FinalApplicationStatus=" + application.getFinalApplicationStatus().toString() + ". Redirecting to job history server"); realProxy = checkAndGetHSProxy(application, JobState.SUCCEEDED); } return realProxy; } private MRClientProtocol checkAndGetHSProxy( ApplicationReport applicationReport, JobState state) { if (null == historyServerProxy) { LOG.warn("Job History Server is not configured."); return getNotRunningJob(applicationReport, state); } return historyServerProxy; } MRClientProtocol instantiateAMProxy(final InetSocketAddress serviceAddr) throws IOException { LOG.trace("Connecting to ApplicationMaster at: " + serviceAddr); YarnRPC rpc = YarnRPC.create(conf); MRClientProtocol proxy = (MRClientProtocol) rpc.getProxy(MRClientProtocol.class, serviceAddr, conf); usingAMProxy.set(true); LOG.trace("Connected to ApplicationMaster at: " + serviceAddr); return proxy; } private synchronized Object invoke(String method, Class argClass, Object args) throws IOException { Method methodOb = null; try { methodOb = MRClientProtocol.class.getMethod(method, argClass); } catch (SecurityException e) { throw new YarnRuntimeException(e); } catch (NoSuchMethodException e) { throw new YarnRuntimeException("Method name mismatch", e); } maxClientRetry = this.conf.getInt( MRJobConfig.MR_CLIENT_MAX_RETRIES, MRJobConfig.DEFAULT_MR_CLIENT_MAX_RETRIES); IOException lastException = null; while (maxClientRetry > 0) { MRClientProtocol MRClientProxy = null; try { MRClientProxy = getProxy(); return methodOb.invoke(MRClientProxy, args); } catch (InvocationTargetException e) { // Will not throw out YarnException anymore LOG.debug("Failed to contact AM/History for job " + jobId + " retrying..", e.getTargetException()); // Force reconnection by setting the proxy to null. realProxy = null; // HS/AMS shut down if (e.getCause() instanceof AuthorizationException) { throw new IOException(e.getTargetException()); } // if its AM shut down, do not decrement maxClientRetry while we wait // for its AM to be restarted. if (!usingAMProxy.get()) { maxClientRetry--; } usingAMProxy.set(false); lastException = new IOException(e.getTargetException()); try { Thread.sleep(100); } catch (InterruptedException ie) { LOG.warn("ClientServiceDelegate invoke call interrupted", ie); throw new YarnRuntimeException(ie); } } catch (Exception e) { LOG.debug("Failed to contact AM/History for job " + jobId + " Will retry..", e); // Force reconnection by setting the proxy to null. realProxy = null; // RM shutdown maxClientRetry--; lastException = new IOException(e.getMessage()); try { Thread.sleep(100); } catch (InterruptedException ie) { LOG.warn("ClientServiceDelegate invoke call interrupted", ie); throw new YarnRuntimeException(ie); } } } throw lastException; } // Only for testing @VisibleForTesting public int getMaxClientRetry() { return this.maxClientRetry; } public org.apache.hadoop.mapreduce.Counters getJobCounters(JobID arg0) throws IOException, InterruptedException { org.apache.hadoop.mapreduce.v2.api.records.JobId jobID = TypeConverter.toYarn(arg0); GetCountersRequest request = recordFactory.newRecordInstance(GetCountersRequest.class); request.setJobId(jobID); Counters cnt = ((GetCountersResponse) invoke("getCounters", GetCountersRequest.class, request)).getCounters(); return TypeConverter.fromYarn(cnt); } public TaskCompletionEvent[] getTaskCompletionEvents(JobID arg0, int arg1, int arg2) throws IOException, InterruptedException { org.apache.hadoop.mapreduce.v2.api.records.JobId jobID = TypeConverter .toYarn(arg0); GetTaskAttemptCompletionEventsRequest request = recordFactory .newRecordInstance(GetTaskAttemptCompletionEventsRequest.class); request.setJobId(jobID); request.setFromEventId(arg1); request.setMaxEvents(arg2); List<org.apache.hadoop.mapreduce.v2.api.records.TaskAttemptCompletionEvent> list = ((GetTaskAttemptCompletionEventsResponse) invoke( "getTaskAttemptCompletionEvents", GetTaskAttemptCompletionEventsRequest.class, request)). getCompletionEventList(); return TypeConverter .fromYarn(list .toArray(new org.apache.hadoop.mapreduce.v2.api.records.TaskAttemptCompletionEvent[0])); } public String[] getTaskDiagnostics(org.apache.hadoop.mapreduce.TaskAttemptID arg0) throws IOException, InterruptedException { org.apache.hadoop.mapreduce.v2.api.records.TaskAttemptId attemptID = TypeConverter .toYarn(arg0); GetDiagnosticsRequest request = recordFactory .newRecordInstance(GetDiagnosticsRequest.class); request.setTaskAttemptId(attemptID); List<String> list = ((GetDiagnosticsResponse) invoke("getDiagnostics", GetDiagnosticsRequest.class, request)).getDiagnosticsList(); String[] result = new String[list.size()]; int i = 0; for (String c : list) { result[i++] = c.toString(); } return result; } public JobStatus getJobStatus(JobID oldJobID) throws IOException { org.apache.hadoop.mapreduce.v2.api.records.JobId jobId = TypeConverter.toYarn(oldJobID); GetJobReportRequest request = recordFactory.newRecordInstance(GetJobReportRequest.class); request.setJobId(jobId); JobReport report = ((GetJobReportResponse) invoke("getJobReport", GetJobReportRequest.class, request)).getJobReport(); JobStatus jobStatus = null; if (report != null) { if (StringUtils.isEmpty(report.getJobFile())) { String jobFile = MRApps.getJobFile(conf, report.getUser(), oldJobID); report.setJobFile(jobFile); } String historyTrackingUrl = report.getTrackingUrl(); String url = StringUtils.isNotEmpty(historyTrackingUrl) ? historyTrackingUrl : trackingUrl; jobStatus = TypeConverter.fromYarn(report, url); } return jobStatus; } public org.apache.hadoop.mapreduce.TaskReport[] getTaskReports(JobID oldJobID, TaskType taskType) throws IOException{ org.apache.hadoop.mapreduce.v2.api.records.JobId jobId = TypeConverter.toYarn(oldJobID); GetTaskReportsRequest request = recordFactory.newRecordInstance(GetTaskReportsRequest.class); request.setJobId(jobId); request.setTaskType(TypeConverter.toYarn(taskType)); List<org.apache.hadoop.mapreduce.v2.api.records.TaskReport> taskReports = ((GetTaskReportsResponse) invoke("getTaskReports", GetTaskReportsRequest.class, request)).getTaskReportList(); return TypeConverter.fromYarn (taskReports).toArray(new org.apache.hadoop.mapreduce.TaskReport[0]); } public boolean killTask(TaskAttemptID taskAttemptID, boolean fail) throws IOException { org.apache.hadoop.mapreduce.v2.api.records.TaskAttemptId attemptID = TypeConverter.toYarn(taskAttemptID); if (fail) { FailTaskAttemptRequest failRequest = recordFactory.newRecordInstance(FailTaskAttemptRequest.class); failRequest.setTaskAttemptId(attemptID); invoke("failTaskAttempt", FailTaskAttemptRequest.class, failRequest); } else { KillTaskAttemptRequest killRequest = recordFactory.newRecordInstance(KillTaskAttemptRequest.class); killRequest.setTaskAttemptId(attemptID); invoke("killTaskAttempt", KillTaskAttemptRequest.class, killRequest); } return true; } public boolean killJob(JobID oldJobID) throws IOException { org.apache.hadoop.mapreduce.v2.api.records.JobId jobId = TypeConverter.toYarn(oldJobID); KillJobRequest killRequest = recordFactory.newRecordInstance(KillJobRequest.class); killRequest.setJobId(jobId); invoke("killJob", KillJobRequest.class, killRequest); return true; } public LogParams getLogFilePath(JobID oldJobID, TaskAttemptID oldTaskAttemptID) throws IOException { org.apache.hadoop.mapreduce.v2.api.records.JobId jobId = TypeConverter.toYarn(oldJobID); GetJobReportRequest request = recordFactory.newRecordInstance(GetJobReportRequest.class); request.setJobId(jobId); JobReport report = ((GetJobReportResponse) invoke("getJobReport", GetJobReportRequest.class, request)).getJobReport(); if (EnumSet.of(JobState.SUCCEEDED, JobState.FAILED, JobState.KILLED, JobState.ERROR).contains(report.getJobState())) { if (oldTaskAttemptID != null) { GetTaskAttemptReportRequest taRequest = recordFactory.newRecordInstance(GetTaskAttemptReportRequest.class); taRequest.setTaskAttemptId(TypeConverter.toYarn(oldTaskAttemptID)); TaskAttemptReport taReport = ((GetTaskAttemptReportResponse) invoke("getTaskAttemptReport", GetTaskAttemptReportRequest.class, taRequest)) .getTaskAttemptReport(); if (taReport.getContainerId() == null || taReport.getNodeManagerHost() == null) { throw new IOException("Unable to get log information for task: " + oldTaskAttemptID); } return new LogParams( taReport.getContainerId().toString(), taReport.getContainerId().getApplicationAttemptId() .getApplicationId().toString(), NodeId.newInstance(taReport.getNodeManagerHost(), taReport.getNodeManagerPort()).toString(), report.getUser()); } else { if (report.getAMInfos() == null || report.getAMInfos().size() == 0) { throw new IOException("Unable to get log information for job: " + oldJobID); } AMInfo amInfo = report.getAMInfos().get(report.getAMInfos().size() - 1); return new LogParams( amInfo.getContainerId().toString(), amInfo.getAppAttemptId().getApplicationId().toString(), NodeId.newInstance(amInfo.getNodeManagerHost(), amInfo.getNodeManagerPort()).toString(), report.getUser()); } } else { throw new IOException("Cannot get log path for a in-progress job"); } } public void close() throws IOException { if (rm != null) { rm.close(); } if (historyServerProxy != null) { RPC.stopProxy(historyServerProxy); } if (realProxy != null) { RPC.stopProxy(realProxy); realProxy = null; } } }
package us.tlatoani.tablisknu.skin; import com.comphenix.protocol.wrappers.WrappedGameProfile; import com.comphenix.protocol.wrappers.WrappedSignedProperty; import org.json.simple.JSONObject; import java.util.Optional; import java.util.UUID; /** * Created by Tlatoani on 8/3/16. */ public class Skin { public static final Skin EMPTY = new Skin("", ""); public static final Skin STEVE = new Skin( "eyJ0aW1lc3RhbXAiOjE0NzQyMTc3NjkwMDAsInByb2ZpbGVJZCI6ImIwZDRiMjhiYzFkNzQ4ODlhZjBlODY2MWNlZTk2YWFiIiwicHJvZmlsZU5hbWUiOiJJbnZlbnRpdmVHYW1lcyIsInNpZ25hdHVyZVJlcXVpcmVkIjp0cnVlLCJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvZWE5MmI0NTY2ZjlhMjg2OTNlNGMyNGFiMTQxNzJjZDM0MjdiNzJiZGE4ZjM0ZDRhNjEwODM3YTQ3ZGEwZGUifX19", "pRQbSEnKkNmi0uW7r8H4xzoWS3E4tkWNbiwwRYgmvITr0xHWSKii69TcaYDoDBXGBwZ525Ex5z5lYe5Xg6zb7pyBPiTJj8J0QdKenQefVnm6Vi1SAR1uN131sRddgK2Gpb2z0ffsR9USDjJAPQtQwCqz0M7sHeXUJhuRxnbznpuZwGq+B34f1TqyVH8rcOSQW9zd+RY/MEUuIHxmSRZlfFIwYVtMCEmv4SbhjLNIooGp3z0CWqDhA7GlJcDFb64FlsJyxrAGnAsUwL2ocoikyIQceyj+TVyGIEuMIpdEifO6+NkCnV7v+zTmcutOfA7kHlj4d1e5ylwi3/3k4VKZhINyFRE8M8gnLgbVxNZ4mNtI3ZMWmtmBnl9dVujyo+5g+vceIj5Admq6TOE0hy7XoDVifLWyNwO/kSlXl34ZDq1MCVN9f1ryj4aN7BB8/Tb2M4sJf3YoGi0co0Hz/A4y14M5JriG21lngw/vi5Pg90GFz64ASssWDN9gwuf5xPLUHvADGo0Bue8KPZPyI0iuIi/3sZCQrMcdyVcur+facIObTQhMut71h8xFeU05yFkQUOKIQswaz2fpPb/cEypWoSCeQV8T0w0e3YKLi4RaWWvKS1MFJDHn7xMYaTk0OhALJoV5BxRD8vJeRi5jYf3DjEgt9+xB742HrbVRDlJuTp4=" ); public static final Skin ALEX = new Skin( "eyJ0aW1lc3RhbXAiOjE0NzQyMTc5MjMyMDAsInByb2ZpbGVJZCI6IjQzYTgzNzNkNjQyOTQ1MTBhOWFhYjMwZjViM2NlYmIzIiwicHJvZmlsZU5hbWUiOiJTa3VsbENsaWVudFNraW42Iiwic2lnbmF0dXJlUmVxdWlyZWQiOnRydWUsInRleHR1cmVzIjp7IlNLSU4iOnsibWV0YWRhdGEiOnsibW9kZWwiOiJzbGltIn0sInVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvMTcxMDFmYTQ3NWI2NjA1NmQ2ZDcxZjJmZDI1Y2NkZmI1NjNhOTI1NGZhMjEzZTYyOGNkN2Q4MWQxZWVlOGUifX19", "vwUYP+IUwLgb5X4EEzZ9ThB8Pv2hq2LZWuSUr8i/FWcmCc9C4Q4FzxbeMPFKZihVdL7zL2cnmuTiXwxo7TewDjH0S4pIIm2fIvuYKSgoAjStVozL81vdWnhIuB5nNlgigjFLTuWMol36upujFcSDhvzF2ebZQprOEYWVjo3BjqccMBYsz4Uqy8/Kl2dzvPK7V8A167+Zt2l1LTkSBMMmvYoBHYC+L0eu5OCAe81WdtpXHAsKbVcz1VSGKNKhXE+eh2PsC5OHNQo7hc3H3gfVksrrJXjx3TmA5XFzA/7JAz3jmtYWhe3YGoJlZIBC9Y1WVK99c+yHl2x6TJUjwIS6IGqicNcSlhuqu51qnz6ICp7nklK7UPWA0lCME5Ufxu4Ao5aU5F4C9erelJt/t40vWq/2NiBaz7YUjOFZ2gvq1CKnnJnNjqbW0fuZsU4Gc1PtGiX36teq5BBNew7vmOWK0KmObUlXFoF2/tCsbYKP+GiJ8PG+XxGJ5OImIznmh/Y/ZI3tcRdcw8SL8UvgbdqaGjeScq+az8iHxLGSEHwu6ZGdkq3I3oJxUz7eCLkfrqhbRWOwQ8YHh8oz48iGLxiQoElQqzwEIbr6qaXrvCWam0ZcyLc2T9u+K9PcAnUFF781YIveI3kuUytQVm+kbWeb0+31xAzQfrOCFOP3O1WEIMU=" ); public static String MULTIMAP_KEY = "textures"; public final String value; public final String signature; public final UUID uuid; //Currently used to ensure uniqueness when creating a player_head using a skin public Skin(String value, String signature) { this.value = Optional.ofNullable(value).orElse(""); this.signature = Optional.ofNullable(signature).orElse(""); this.uuid = UUID.nameUUIDFromBytes(this.value.getBytes()); } public JSONObject toJSON() { JSONObject jsonObject = new JSONObject(); jsonObject.put("value", value); jsonObject.put("signature", signature); return jsonObject; } public WrappedSignedProperty toWrappedSignedProperty() { return new WrappedSignedProperty("textures", value, signature); } public WrappedGameProfile toGameProfile(String name) { WrappedGameProfile wrappedGameProfile = new WrappedGameProfile(uuid, name); wrappedGameProfile.getProperties().put(MULTIMAP_KEY, toWrappedSignedProperty()); return wrappedGameProfile; } @Override public String toString() { return toJSON().toJSONString(); } @Override public boolean equals(Object other) { if (other instanceof Skin) { Skin otherSkin = (Skin) other; return value.equals(otherSkin.value) && signature.equals(otherSkin.signature); } else { return false; } } //44701 is prime @Override public int hashCode() { return 13 + value.hashCode() + (44701 * signature.hashCode()); } //Creation Methods public static Skin fromJSON(JSONObject jsonObject) { return new Skin((String) jsonObject.get("value"), (String) jsonObject.get("signature")); } public static Skin fromWrappedSignedProperty(WrappedSignedProperty wrappedSignedProperty) { return new Skin(wrappedSignedProperty.getValue(), wrappedSignedProperty.getSignature()); } public static Skin fromGameProfile(WrappedGameProfile gameProfile) { WrappedSignedProperty[] wrappedSignedProperties = gameProfile.getProperties().get(MULTIMAP_KEY).toArray(new WrappedSignedProperty[0]); if (wrappedSignedProperties.length == 0) { return Skin.EMPTY; } else { return fromWrappedSignedProperty(wrappedSignedProperties[0]); } } }
package test.factory; import org.testng.Assert; import org.testng.annotations.DataProvider; import org.testng.annotations.Factory; import org.testng.annotations.Test; @Test(groups = { "x" }) public class FactoryAndTestMethodTest { @Factory(dataProvider = "data") public Object[] ohNo(String s) { return makeNullArgTests(s); } public static class NullArgsTest { public final String s; public NullArgsTest(String s) { this.s = s; } @Test public void test() { Assert.assertNotNull(s); } } private Object[] makeNullArgTests(String s) { return new Object[0]; } @DataProvider(name = "data") public Object[][] makeData() { return new Object[][] { { "foo" } }; } }
package tenten0213.entity; import javax.persistence.*; import java.sql.Timestamp; @Entity @Table(name = "todo") @NamedQuery( name = "todo_findAll", query = "select t from TodoEntity t order by t.updatedTime desc" ) public class TodoEntity { @Id @GeneratedValue @Column(name = "id") private Long todoId; @Column(nullable = false, length = 200) private String descrption; @Column(nullable = false) private Boolean done; @Column(nullable = false) private Timestamp updatedTime; public Timestamp getUpdatedTime() { return updatedTime; } public void setUpdatedTime(Timestamp updatedTime) { this.updatedTime = updatedTime; } public Long getTodoId() { return todoId; } public void setTodoId(Long todoId) { this.todoId = todoId; } public String getDescrption() { return descrption; } public void setDescrption(String descrption) { this.descrption = descrption; } public Boolean getDone() { return done; } public void setDone(Boolean done) { this.done = done; } @PrePersist @PreUpdate public void pre() { this.updatedTime = new Timestamp(System.currentTimeMillis()); } }
/* * Copyright 2017 HugeGraph Authors * * 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.baidu.hugegraph.schema.builder; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.commons.collections.CollectionUtils; import com.baidu.hugegraph.HugeGraph; import com.baidu.hugegraph.backend.id.Id; import com.baidu.hugegraph.backend.id.IdGenerator; import com.baidu.hugegraph.backend.tx.SchemaTransaction; import com.baidu.hugegraph.exception.ExistedException; import com.baidu.hugegraph.exception.NotAllowException; import com.baidu.hugegraph.exception.NotFoundException; import com.baidu.hugegraph.schema.EdgeLabel; import com.baidu.hugegraph.schema.PropertyKey; import com.baidu.hugegraph.schema.SchemaElement; import com.baidu.hugegraph.schema.Userdata; import com.baidu.hugegraph.type.HugeType; import com.baidu.hugegraph.type.define.Action; import com.baidu.hugegraph.type.define.Frequency; import com.baidu.hugegraph.util.CollectionUtil; import com.baidu.hugegraph.util.E; import com.google.common.collect.ImmutableList; public class EdgeLabelBuilder implements EdgeLabel.Builder { private Id id; private String name; private String sourceLabel; private String targetLabel; private Frequency frequency; private Set<String> properties; private List<String> sortKeys; private Set<String> nullableKeys; private Boolean enableLabelIndex; private Userdata userdata; private boolean checkExist; private SchemaTransaction transaction; public EdgeLabelBuilder(String name, SchemaTransaction transaction) { E.checkNotNull(name, "name"); E.checkNotNull(transaction, "transaction"); this.id = null; this.name = name; this.sourceLabel = null; this.targetLabel = null; this.frequency = Frequency.DEFAULT; this.properties = new HashSet<>(); this.sortKeys = new ArrayList<>(); this.nullableKeys = new HashSet<>(); this.enableLabelIndex = null; this.userdata = new Userdata(); this.checkExist = true; this.transaction = transaction; } @Override public EdgeLabel build() { Id id = this.transaction.validOrGenerateId(HugeType.EDGE_LABEL, this.id, this.name); HugeGraph graph = this.transaction.graph(); EdgeLabel edgeLabel = new EdgeLabel(graph, id, this.name); edgeLabel.sourceLabel(this.transaction.getVertexLabel( this.sourceLabel).id()); edgeLabel.targetLabel(this.transaction.getVertexLabel( this.targetLabel).id()); edgeLabel.frequency(this.frequency); edgeLabel.enableLabelIndex(this.enableLabelIndex == null || this.enableLabelIndex); for (String key : this.properties) { PropertyKey propertyKey = this.transaction.getPropertyKey(key); edgeLabel.property(propertyKey.id()); } for (String key : this.sortKeys) { PropertyKey propertyKey = this.transaction.getPropertyKey(key); edgeLabel.sortKey(propertyKey.id()); } for (String key : this.nullableKeys) { PropertyKey propertyKey = this.transaction.getPropertyKey(key); edgeLabel.nullableKey(propertyKey.id()); } edgeLabel.userdata(this.userdata); return edgeLabel; } @Override public EdgeLabel create() { HugeType type = HugeType.EDGE_LABEL; SchemaTransaction tx = this.transaction; SchemaElement.checkName(this.name, tx.graph().configuration()); return tx.lockCheckAndCreateSchema(type, this.name, name -> { EdgeLabel edgeLabel = tx.getEdgeLabel(name); if (edgeLabel != null) { if (this.checkExist) { throw new ExistedException(type, name); } return edgeLabel; } tx.checkIdIfRestoringMode(type, this.id); if (this.frequency == Frequency.DEFAULT) { this.frequency = Frequency.SINGLE; } // These methods will check params and fill to member variables this.checkRelation(); this.checkProperties(Action.INSERT); this.checkSortKeys(); this.checkNullableKeys(Action.INSERT); Userdata.check(this.userdata, Action.INSERT); edgeLabel = this.build(); assert edgeLabel.name().equals(name); tx.addEdgeLabel(edgeLabel); return edgeLabel; }); } @Override public EdgeLabel append() { EdgeLabel edgeLabel = this.transaction.getEdgeLabel(this.name); if (edgeLabel == null) { throw new NotFoundException("Can't update edge label '%s' " + "since it doesn't exist", this.name); } // These methods will check params and fill to member variables this.checkStableVars(); this.checkProperties(Action.APPEND); this.checkNullableKeys(Action.APPEND); Userdata.check(this.userdata, Action.APPEND); for (String key : this.properties) { PropertyKey propertyKey = this.transaction.getPropertyKey(key); edgeLabel.property(propertyKey.id()); } for (String key : this.nullableKeys) { PropertyKey propertyKey = this.transaction.getPropertyKey(key); edgeLabel.nullableKey(propertyKey.id()); } edgeLabel.userdata(this.userdata); this.transaction.addEdgeLabel(edgeLabel); return edgeLabel; } @Override public EdgeLabel eliminate() { EdgeLabel edgeLabel = this.transaction.getEdgeLabel(this.name); if (edgeLabel == null) { throw new NotFoundException("Can't update edge label '%s' " + "since it doesn't exist", this.name); } // Only allowed to eliminate user data this.checkStableVars(); this.checkProperties(Action.ELIMINATE); this.checkNullableKeys(Action.ELIMINATE); Userdata.check(this.userdata, Action.ELIMINATE); edgeLabel.removeUserdata(this.userdata); this.transaction.addEdgeLabel(edgeLabel); return edgeLabel; } @Override public Id remove() { EdgeLabel edgeLabel = this.transaction.getEdgeLabel(this.name); if (edgeLabel == null) { return null; } return this.transaction.removeEdgeLabel(edgeLabel.id()); } @Override public Id rebuildIndex() { EdgeLabel edgeLabel = this.transaction.graph().edgeLabel(this.name); if (edgeLabel == null) { return null; } return this.transaction.rebuildIndex(edgeLabel); } @Override public EdgeLabelBuilder id(long id) { E.checkArgument(id != 0L, "Not allowed to assign 0 as edge label id"); this.id = IdGenerator.of(id); return this; } @Override public EdgeLabelBuilder properties(String... properties) { this.properties.addAll(Arrays.asList(properties)); return this; } @Override public EdgeLabelBuilder nullableKeys(String... keys) { this.nullableKeys.addAll(Arrays.asList(keys)); return this; } @Override public EdgeLabelBuilder sortKeys(String... keys) { if (keys.length == 0) { return this; } E.checkArgument(this.sortKeys.isEmpty(), "Not allowed to assign sort keys multitimes"); List<String> sortKeys = Arrays.asList(keys); E.checkArgument(CollectionUtil.allUnique(sortKeys), "Invalid sort keys %s, which contains some " + "duplicate properties", sortKeys); this.sortKeys.addAll(sortKeys); return this; } @Override public EdgeLabelBuilder link(String sourceLabel, String targetLabel) { this.sourceLabel(sourceLabel); this.targetLabel(targetLabel); return this; } @Override public EdgeLabelBuilder sourceLabel(String label) { this.sourceLabel = label; return this; } @Override public EdgeLabelBuilder targetLabel(String label) { this.targetLabel = label; return this; } @Override public EdgeLabelBuilder singleTime() { this.frequency = Frequency.SINGLE; return this; } @Override public EdgeLabelBuilder multiTimes() { this.frequency = Frequency.MULTIPLE; return this; } @Override public EdgeLabelBuilder ifNotExist() { this.checkExist = false; return this; } @Override public EdgeLabelBuilder frequency(Frequency frequency) { this.frequency = frequency; return this; } @Override public EdgeLabelBuilder enableLabelIndex(boolean enable) { this.enableLabelIndex = enable; return this; } @Override public EdgeLabelBuilder userdata(String key, Object value) { this.userdata.put(key, value); return this; } @Override public EdgeLabelBuilder userdata(Map<String, Object> userdata) { this.userdata.putAll(userdata); return this; } @Override public EdgeLabelBuilder checkExist(boolean checkExist) { this.checkExist = checkExist; return this; } private void checkProperties(Action action) { switch (action) { case INSERT: case APPEND: for (String key : this.properties) { PropertyKey pkey = this.transaction.getPropertyKey(key); E.checkArgumentNotNull(pkey, "Undefined property key '%s'", key); } break; case ELIMINATE: if (!this.properties.isEmpty()) { throw new NotAllowException( "Not support to eliminate properties " + "for edge label currently"); } break; case DELETE: break; default: throw new AssertionError(String.format( "Unknown schema action '%s'", action)); } } @SuppressWarnings("unchecked") private void checkNullableKeys(Action action) { // Not using switch-case to avoid indent too much if (action == Action.ELIMINATE) { if (!this.nullableKeys.isEmpty()) { throw new NotAllowException( "Not support to eliminate nullableKeys " + "for edge label currently"); } return; } EdgeLabel edgeLabel = this.transaction.getEdgeLabel(this.name); // The originProps is empty when firstly create edge label List<String> originProps = edgeLabel == null ? ImmutableList.of() : this.transaction.graph() .mapPkId2Name(edgeLabel.properties()); Set<String> appendProps = this.properties; E.checkArgument(CollectionUtil.union(originProps, appendProps) .containsAll(this.nullableKeys), "The nullableKeys: %s to be created or appended " + "must belong to the origin/new properties: %s/%s ", this.nullableKeys, originProps, appendProps); E.checkArgument(!CollectionUtil.hasIntersection(this.sortKeys, this.nullableKeys), "The nullableKeys: %s are not allowed to " + "belong to sortKeys: %s of edge label '%s'", this.nullableKeys, this.sortKeys, this.name); if (action == Action.APPEND) { Collection<String> newAddedProps = CollectionUtils.subtract( appendProps, originProps); E.checkArgument(this.nullableKeys.containsAll(newAddedProps), "The new added properties: %s must be nullable", newAddedProps); } } private void checkSortKeys() { if (this.frequency == Frequency.SINGLE) { E.checkArgument(this.sortKeys.isEmpty(), "EdgeLabel can't contain sortKeys " + "when the cardinality property is single"); } else { E.checkState(this.sortKeys != null, "The sortKeys can't be null when the " + "cardinality property is multiple"); E.checkArgument(!this.sortKeys.isEmpty(), "EdgeLabel must contain sortKeys " + "when the cardinality property is multiple"); } if (this.sortKeys.isEmpty()) { return; } // Check whether the properties contains the specified keys E.checkArgument(!this.properties.isEmpty(), "The properties can't be empty when exist " + "sort keys for edge label '%s'", this.name); for (String key : this.sortKeys) { E.checkArgument(this.properties.contains(key), "The sort key '%s' must be contained in " + "properties '%s' for edge label '%s'", key, this.name, this.properties); } } private void checkRelation() { String srcLabel = this.sourceLabel; String tgtLabel = this.targetLabel; E.checkArgument(srcLabel != null && tgtLabel != null, "Must set source and target label " + "for edge label '%s'", this.name); E.checkArgumentNotNull(this.transaction.getVertexLabel(srcLabel), "Undefined source vertex label '%s' " + "in edge label '%s'", srcLabel, this.name); E.checkArgumentNotNull(this.transaction.getVertexLabel(tgtLabel), "Undefined target vertex label '%s' " + "in edge label '%s'", tgtLabel, this.name); } private void checkStableVars() { if (this.sourceLabel != null) { throw new NotAllowException( "Not allowed to update source label " + "for edge label '%s', it must be null", this.name); } if (this.targetLabel != null) { throw new NotAllowException( "Not allowed to update target label " + "for edge label '%s', it must be null", this.name); } if (this.frequency != Frequency.DEFAULT) { throw new NotAllowException( "Not allowed to update frequency " + "for edge label '%s'", this.name); } if (!this.sortKeys.isEmpty()) { throw new NotAllowException( "Not allowed to update sort keys " + "for edge label '%s'", this.name); } if (this.enableLabelIndex != null) { throw new NotAllowException( "Not allowed to update enable_label_index " + "for edge label '%s'", this.name); } } }
package net.officefloor.demo; import net.officefloor.demo.entity.WeavedRequest; import net.officefloor.demo.entity.WeavedRequestRepository; import net.officefloor.plugin.section.clazz.Next; import net.officefloor.plugin.variable.Out; import net.officefloor.plugin.variable.Val; /** * Registers the request. * * @author Daniel Sagenschneider */ public class RegisterRequestService { // START SNIPPET: tutorial public static void registerRequest(@Val int requestIdentifier, WeavedRequestRepository repository, Out<WeavedRequest> weavedRequest) { WeavedRequest entity = new WeavedRequest(requestIdentifier); repository.save(entity); weavedRequest.set(entity); } // END SNIPPET: tutorial }
package com.bobocode.basics; /** * This demo demonstrates why using Object is not safe. It's not safe because runtime casting can cause runtime * exceptions. We should always fail as soon as possible. So in this code we should not allow setting String * value at compile time, if we expect to work with integers. * <p> * todo: refactor class {@link Box} to make type parameterization safe and make this demo fail at compile time */ public class BoxDemoApp { public static void main(String[] args) { Box<Integer> intBox = new Box<>(123); Box<Integer> intBox2 = new Box<>(321); System.out.println(intBox.getValue() + intBox2.getValue()); intBox.setValue(222); // intBox.setValue("abc"); // this should not be allowed // the following code will compile, but will throw runtime exception System.out.println((int) intBox.getValue() + (int) intBox2.getValue()); } }
// 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.doris.stack.dao; import org.apache.doris.stack.entity.ManagerDatabaseEntity; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import java.util.List; public interface ManagerDatabaseRepository extends JpaRepository<ManagerDatabaseEntity, Integer> { @Query("select d from ManagerDatabaseEntity d where d.clusterId = :clusterId and d.name = :name") List<ManagerDatabaseEntity> getByClusterIdAndName(@Param("clusterId") int clusterId, @Param("name") String name); @Query("select d from ManagerDatabaseEntity d where d.clusterId = :clusterId") List<ManagerDatabaseEntity> getByClusterId(@Param("clusterId") int clusterId); @Query("select d.name from ManagerDatabaseEntity d where d.clusterId = :clusterId") List<String> getNameByClusterId(@Param("clusterId") int clusterId); }
/* * Copyright 2011 Google 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 org.sumcoinj.store; /** * Thrown when something goes wrong with storing a block. Examples: out of disk space. */ public class BlockStoreException extends Exception { public BlockStoreException(String message) { super(message); } public BlockStoreException(Throwable t) { super(t); } public BlockStoreException(String message, Throwable t) { super(message, t); } }
import Andromeda.GameObject.GameObject; import Andromeda.GameObject.MouseCaller; import Andromeda.GameObject.ObjectManipulator; import Andromeda.GameObject.BoxObject; import Andromeda.Manager.GameManager; import Andromeda.Utils.Vector2; import java.awt.Color; import java.lang.reflect.InvocationTargetException; /** * Classname: Main * Author: Elias Jätte * Date: 18/07/26 */ public class Main { public static void main(String[] args) throws InvocationTargetException, InterruptedException { new Main().test(); } public void test(){ GameManager gameManager = GameManager.getInstance(); gameManager.startThread(); gameManager.getScene().addGameObject(new MouseCaller()); GameObject g1 = new BoxObject(); g1.transform.setPosition(new Vector2(5,5)); g1.transform.scale(new Vector2(2,2)); g1.rigidbody.setMass(60); g1.transform.rotate(20); g1.rigidbody.isKinematic = false; g1.rigidbody.elasticity = 0.1; g1.collider.setDefaultColor(new Color(144, 66, 255)); GameObject.instantiate(g1); GameObject g2 = new BoxObject(); g2.transform.setPosition(new Vector2(5,14)); g2.transform.scale(new Vector2(2,2)); g2.rigidbody.setMass(60); g2.transform.rotate(35); g2.rigidbody.isKinematic = false; g2.rigidbody.elasticity = 0.1; g2.collider.setDefaultColor(new Color(144, 66, 255)); GameObject.instantiate(g2); ObjectManipulator s1 = new ObjectManipulator(); s1.transform.setPosition(new Vector2(5.5,0)); GameObject.instantiate(s1); } }
package org.hl7.fhir.r5.model.codesystems; /* * #%L * org.hl7.fhir.r5 * %% * Copyright (C) 2014 - 2019 Health Level 7 * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ /* Copyright (c) 2011+, HL7, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of HL7 nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ // Generated on Thu, Oct 17, 2019 09:42+1100 for FHIR v4.1.0 import org.hl7.fhir.exceptions.FHIRException; public enum ProcedureProgressStatusCodes { /** * A patient is in the Operating Room. */ INOPERATINGROOM, /** * The patient is prepared for a procedure. */ PREPARED, /** * The patient is under anesthesia. */ ANESTHESIAINDUCED, /** * The patient has open incision(s). */ OPENINCISION, /** * The patient has incision(s) closed. */ CLOSEDINCISION, /** * The patient is in the recovery room. */ INRECOVERYROOM, /** * added to help the parsers */ NULL; public static ProcedureProgressStatusCodes fromCode(String codeString) throws FHIRException { if (codeString == null || "".equals(codeString)) return null; if ("in-operating-room".equals(codeString)) return INOPERATINGROOM; if ("prepared".equals(codeString)) return PREPARED; if ("anesthesia-induced".equals(codeString)) return ANESTHESIAINDUCED; if ("open-incision".equals(codeString)) return OPENINCISION; if ("closed-incision".equals(codeString)) return CLOSEDINCISION; if ("in-recovery-room".equals(codeString)) return INRECOVERYROOM; throw new FHIRException("Unknown ProcedureProgressStatusCodes code '"+codeString+"'"); } public String toCode() { switch (this) { case INOPERATINGROOM: return "in-operating-room"; case PREPARED: return "prepared"; case ANESTHESIAINDUCED: return "anesthesia-induced"; case OPENINCISION: return "open-incision"; case CLOSEDINCISION: return "closed-incision"; case INRECOVERYROOM: return "in-recovery-room"; default: return "?"; } } public String getSystem() { return "http://hl7.org/fhir/procedure-progress-status-code"; } public String getDefinition() { switch (this) { case INOPERATINGROOM: return "A patient is in the Operating Room."; case PREPARED: return "The patient is prepared for a procedure."; case ANESTHESIAINDUCED: return "The patient is under anesthesia."; case OPENINCISION: return "The patient has open incision(s)."; case CLOSEDINCISION: return "The patient has incision(s) closed."; case INRECOVERYROOM: return "The patient is in the recovery room."; default: return "?"; } } public String getDisplay() { switch (this) { case INOPERATINGROOM: return "In Operating Room"; case PREPARED: return "Prepared"; case ANESTHESIAINDUCED: return "Anesthesia Induced"; case OPENINCISION: return "Open Incision"; case CLOSEDINCISION: return "Closed Incision"; case INRECOVERYROOM: return "In Recovery Room"; default: return "?"; } } }
package ar.edu.unlam.recycloud.web.pages.puntoreciclaje.recypoints.home; import ar.edu.unlam.recycloud.app.recypoints.RecypointService; import ar.edu.unlam.recycloud.app.usuario.Usuario; import org.springframework.stereotype.Service; @Service public class RecypointsVMService { private final RecypointService recypointService; public RecypointsVMService(RecypointService recypointService) { this.recypointService = recypointService; } public RecypointsHomeViewModel build(Usuario usuario) { RecypointsHomeViewModel model = new RecypointsHomeViewModel(); model.setGivenRecypoints(this.recypointService.getAllPointsFromProvider(usuario)); model.setProviderId(usuario.getId()); return model; } }
/** * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved. */ package com.mingcai.edu.modules.oa.entity.eos; import com.mingcai.edu.modules.oa.entity.wx.OaWxDepartment; import org.hibernate.validator.constraints.Length; import com.mingcai.edu.common.persistence.DataEntity; import java.util.*; /** * 报销主表Entity * @author 李艺杰 * @version 2019-03-23 */ public class OaWxExtendedSuper extends DataEntity<OaWxExtendedSuper> { private static final long serialVersionUID = 1L; private String state; // 状态(-1已驳回,0默认(未审核),1审核通过) private OaEosFlowItem flow; // 流程id private String proId; // 项目id private String appropriation; // 确定财务是否拨款(-1审核未通过,0未拨款,1已拨款) private String rbsType; private String enclosure; // 附件 private OaEosPro pro; private List<Map> mapList=new ArrayList<Map>(); private List<OaWxExtended> list=new ArrayList<OaWxExtended>(); public List<Map> getMapList() { return mapList; } private String proItemType;//0.预立项项目,1.立项项目,2.非销售项目 private OaWxDepartment oaWxDepartment; private OaEosProUn oaEosProUn; private String userId; private Map<String,Object> objmap= new HashMap<String, Object>(); private boolean cw=false; //是否为财务查询 private String starttime; private String endtime; public String getUserId() { return userId; } public Map<String, Object> getObjmap() { return objmap; } public String getStarttime() { return starttime; } public void setStarttime(String starttime) { this.starttime = starttime; } public String getEndtime() { return endtime; } public void setEndtime(String endtime) { this.endtime = endtime; } public boolean isCw() { return cw; } public void setCw(boolean cw) { this.cw = cw; } public void setObjmap(Map<String, Object> objmap) { this.objmap = objmap; } public void setUserId(String userId) { this.userId = userId; } public String getRbsType() { return rbsType; } public void setRbsType(String rbsType) { this.rbsType = rbsType; } public OaEosProUn getOaEosProUn() { return oaEosProUn; } public void setOaEosProUn(OaEosProUn oaEosProUn) { this.oaEosProUn = oaEosProUn; } public OaWxDepartment getOaWxDepartment() { return oaWxDepartment; } public void setOaWxDepartment(OaWxDepartment oaWxDepartment) { this.oaWxDepartment = oaWxDepartment; } public String getProItemType() { return proItemType; } public void setProItemType(String proItemType) { this.proItemType = proItemType; } public void setMapList(List<Map> mapList) { this.mapList = mapList; } public OaWxExtendedSuper() { super(); } public OaWxExtendedSuper(String id){ super(id); } public List<OaWxExtended> getList() { return list; } public void setList(List<OaWxExtended> list) { this.list = list; } @Length(min=0, max=100, message="状态(-1已驳回,0默认(未审核),1审核通过)长度必须介于 0 和 100 之间") public String getState() { return state; } public void setState(String state) { this.state = state; } public OaEosFlowItem getFlow() { return flow; } public void setFlow(OaEosFlowItem flow) { this.flow = flow; } @Length(min=0, max=64, message="子项目长度必须介于 0 和 64 之间") public String getProId() { return proId; } public void setProId(String proId) { this.proId = proId; } @Length(min=0, max=100, message="确定财务是否拨款(-1审核未通过,0未拨款,1已拨款)长度必须介于 0 和 100 之间") public String getAppropriation() { return appropriation; } public void setAppropriation(String appropriation) { this.appropriation = appropriation; } @Length(min=0, max=255, message="附件长度必须介于 0 和 255 之间") public String getEnclosure() { return enclosure; } public void setEnclosure(String enclosure) { this.enclosure = enclosure; } public OaEosPro getPro() { return pro; } public void setPro(OaEosPro pro) { this.pro = pro; } }
package com.huxq17.download.core; import com.huxq17.download.core.task.DownloadTask; import java.util.List; public final class RealDownloadChain implements DownloadInterceptor.DownloadChain { private final int index; private int calls; private final List<DownloadInterceptor> interceptors; private final DownloadRequest downloadRequest; public RealDownloadChain(List<DownloadInterceptor> interceptors, DownloadRequest downloadRequest , int index) { this.index = index; this.downloadRequest = downloadRequest; this.interceptors = interceptors; } @Override public DownloadRequest request() { return downloadRequest; } public DownloadTask downloadTask() { return null; } @Override public DownloadInfo proceed(DownloadRequest downloadRequest) { return proceed(downloadRequest, false); } public DownloadInfo proceed(DownloadRequest downloadRequest, boolean shouldRetry) { calls++; if (!shouldRetry && calls > 1) { throw new IllegalStateException("download interceptor " + interceptors.get(index - 1) + " must call proceed() exactly once"); } DownloadInterceptor interceptor = interceptors.get(index); DownloadInterceptor.DownloadChain nextChain = new RealDownloadChain(interceptors, downloadRequest, index + 1); return interceptor.intercept(nextChain); } }
/** * */ package za.co.sindi.validations.core.constraint.impl; import za.co.sindi.validations.core.constraint.StringConstraint; /** * @author Buhake Sindi * @since 16 July 2012 * */ public class EndsWithConstraint extends StringConstraint { private String suffix; /** * @param endString */ public EndsWithConstraint(String suffix) { super(); if (suffix == null || suffix.isEmpty()) { throw new IllegalArgumentException("Suffix may not be null or empty."); } this.suffix = suffix; // setMessage("Value ends with '" + this.suffix + "'."); } /* (non-Javadoc) * @see za.co.bayport.validations.core.Constraint#isValid(java.lang.Object) */ public boolean isValid(String value) { // TODO Auto-generated method stub if (value == null) { return false; } return value.toLowerCase().endsWith(suffix.toLowerCase()); } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. package com.azure.ai.metricsadvisor.implementation.util; import com.azure.ai.metricsadvisor.models.FeedbackType; import com.azure.ai.metricsadvisor.models.MetricFeedback; import java.time.OffsetDateTime; /** * The helper class to set the non-public properties of an {@link MetricFeedback} instance. */ public final class MetricFeedbackHelper { private static MetricFeedbackAccessor accessor; private MetricFeedbackHelper() { } /** * Type defining the methods to set the non-public properties of an {@link MetricFeedback} instance. */ public interface MetricFeedbackAccessor { void setId(MetricFeedback feedback, String id); void setMetricId(MetricFeedback feedback, String metricId); void setCreatedTime(MetricFeedback feedback, OffsetDateTime createdTime); void setUserPrincipal(MetricFeedback feedback, String userPrincipal); void setFeedbackType(MetricFeedback feedback, FeedbackType feedbackType); } /** * The method called from {@link MetricFeedback} to set it's accessor. * * @param feedbackAccessor The accessor. */ public static void setAccessor(final MetricFeedbackAccessor feedbackAccessor) { accessor = feedbackAccessor; } static void setId(MetricFeedback feedback, String id) { accessor.setId(feedback, id); } static void setMetricId(MetricFeedback feedback, String metricId) { accessor.setMetricId(feedback, metricId); } static void setCreatedTime(MetricFeedback feedback, OffsetDateTime createdTime) { accessor.setCreatedTime(feedback, createdTime); } static void setUserPrincipal(MetricFeedback feedback, String userPrincipal) { accessor.setUserPrincipal(feedback, userPrincipal); } static void setFeedbackType(MetricFeedback feedback, FeedbackType feedbackType) { accessor.setFeedbackType(feedback, feedbackType); } }
package json; /* Copyright (c) 2002 JSON.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. The Software shall be used for Good, not Evil. 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. */ import java.io.IOException; import java.io.StringWriter; import java.io.Writer; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.Map; /** * A JSONArray is an ordered sequence of values. Its external text form is a * string wrapped in square brackets with commas separating the values. The * internal form is an object having <code>get</code> and <code>opt</code> * methods for accessing the values by index, and <code>put</code> methods for * adding or replacing values. The values can be any of these types: * <code>Boolean</code>, <code>JSONArray</code>, <code>JSONObject</code>, * <code>Number</code>, <code>String</code>, or the * <code>JSONObject.NULL object</code>. * <p> * The constructor can convert a JSON text into a Java object. The * <code>toString</code> method converts to JSON text. * <p> * A <code>get</code> method returns a value if one can be found, and throws an * exception if one cannot be found. An <code>opt</code> method returns a * default value instead of throwing an exception, and so is useful for * obtaining optional values. * <p> * The generic <code>get()</code> and <code>opt()</code> methods return an * object which you can cast or query for type. There are also typed * <code>get</code> and <code>opt</code> methods that do type checking and type * coercion for you. * <p> * The texts produced by the <code>toString</code> methods strictly conform to * JSON syntax rules. The constructors are more forgiving in the texts they will * accept: * <ul> * <li>An extra <code>,</code>&nbsp;<small>(comma)</small> may appear just * before the closing bracket.</li> * <li>The <code>null</code> value will be inserted when there is <code>,</code> * &nbsp;<small>(comma)</small> elision.</li> * <li>Strings may be quoted with <code>'</code>&nbsp;<small>(single * quote)</small>.</li> * <li>Strings do not need to be quoted at all if they do not begin with a quote * or single quote, and if they do not contain leading or trailing spaces, and * if they do not contain any of these characters: * <code>{ } [ ] / \ : , #</code> and if they do not look like numbers and * if they are not the reserved words <code>true</code>, <code>false</code>, or * <code>null</code>.</li> * </ul> * * @author JSON.org * @version 2014-05-03 */ public class JSONArray { /** * The arrayList where the JSONArray's properties are kept. */ private final ArrayList<Object> myArrayList; /** * Construct an empty JSONArray. */ public JSONArray() { this.myArrayList = new ArrayList<Object>(); } /** * Construct a JSONArray from a JSONTokener. * * @param x * A JSONTokener * @throws JSONException * If there is a syntax error. */ public JSONArray(JSONTokener x) throws JSONException { this(); if (x.nextClean() != '[') { throw x.syntaxError("A JSONArray text must start with '['"); } if (x.nextClean() != ']') { x.back(); for (;;) { if (x.nextClean() == ',') { x.back(); this.myArrayList.add(JSONObject.NULL); } else { x.back(); this.myArrayList.add(x.nextValue()); } switch (x.nextClean()) { case ',': if (x.nextClean() == ']') { return; } x.back(); break; case ']': return; default: throw x.syntaxError("Expected a ',' or ']'"); } } } } /** * Construct a JSONArray from a source JSON text. * * @param source * A string that begins with <code>[</code>&nbsp;<small>(left * bracket)</small> and ends with <code>]</code> * &nbsp;<small>(right bracket)</small>. * @throws JSONException * If there is a syntax error. */ public JSONArray(String source) throws JSONException { this(new JSONTokener(source)); } /** * Construct a JSONArray from a Collection. * * @param collection * A Collection. */ public JSONArray(Collection<Object> collection) { this.myArrayList = new ArrayList<Object>(); if (collection != null) { Iterator<Object> iter = collection.iterator(); while (iter.hasNext()) { this.myArrayList.add(JSONObject.wrap(iter.next())); } } } /** * Construct a JSONArray from an array * * @throws JSONException * If not an array. */ public JSONArray(Object array) throws JSONException { this(); if (array.getClass().isArray()) { int length = Array.getLength(array); for (int i = 0; i < length; i += 1) { this.put(JSONObject.wrap(Array.get(array, i))); } } else { throw new JSONException( "JSONArray initial value should be a string or collection or array."); } } /** * Get the object value associated with an index. * * @param index * The index must be between 0 and length() - 1. * @return An object value. * @throws JSONException * If there is no value for the index. */ public Object get(int index) throws JSONException { Object object = this.opt(index); if (object == null) { throw new JSONException("JSONArray[" + index + "] not found."); } return object; } /** * Get the boolean value associated with an index. The string values "true" * and "false" are converted to boolean. * * @param index * The index must be between 0 and length() - 1. * @return The truth. * @throws JSONException * If there is no value for the index or if the value is not * convertible to boolean. */ public boolean getBoolean(int index) throws JSONException { Object object = this.get(index); if (object.equals(Boolean.FALSE) || (object instanceof String && ((String) object) .equalsIgnoreCase("false"))) { return false; } else if (object.equals(Boolean.TRUE) || (object instanceof String && ((String) object) .equalsIgnoreCase("true"))) { return true; } throw new JSONException("JSONArray[" + index + "] is not a boolean."); } /** * Get the double value associated with an index. * * @param index * The index must be between 0 and length() - 1. * @return The value. * @throws JSONException * If the key is not found or if the value cannot be converted * to a number. */ public double getDouble(int index) throws JSONException { Object object = this.get(index); try { return object instanceof Number ? ((Number) object).doubleValue() : Double.parseDouble((String) object); } catch (Exception e) { throw new JSONException("JSONArray[" + index + "] is not a number."); } } /** * Get the int value associated with an index. * * @param index * The index must be between 0 and length() - 1. * @return The value. * @throws JSONException * If the key is not found or if the value is not a number. */ public int getInt(int index) throws JSONException { Object object = this.get(index); try { return object instanceof Number ? ((Number) object).intValue() : Integer.parseInt((String) object); } catch (Exception e) { throw new JSONException("JSONArray[" + index + "] is not a number."); } } /** * Get the JSONArray associated with an index. * * @param index * The index must be between 0 and length() - 1. * @return A JSONArray value. * @throws JSONException * If there is no value for the index. or if the value is not a * JSONArray */ public JSONArray getJSONArray(int index) throws JSONException { Object object = this.get(index); if (object instanceof JSONArray) { return (JSONArray) object; } throw new JSONException("JSONArray[" + index + "] is not a JSONArray."); } /** * Get the JSONObject associated with an index. * * @param index * subscript * @return A JSONObject value. * @throws JSONException * If there is no value for the index or if the value is not a * JSONObject */ public JSONObject getJSONObject(int index) throws JSONException { Object object = this.get(index); if (object instanceof JSONObject) { return (JSONObject) object; } throw new JSONException("JSONArray[" + index + "] is not a JSONObject."); } /** * Get the long value associated with an index. * * @param index * The index must be between 0 and length() - 1. * @return The value. * @throws JSONException * If the key is not found or if the value cannot be converted * to a number. */ public long getLong(int index) throws JSONException { Object object = this.get(index); try { return object instanceof Number ? ((Number) object).longValue() : Long.parseLong((String) object); } catch (Exception e) { throw new JSONException("JSONArray[" + index + "] is not a number."); } } /** * Get the string associated with an index. * * @param index * The index must be between 0 and length() - 1. * @return A string value. * @throws JSONException * If there is no string value for the index. */ public String getString(int index) throws JSONException { Object object = this.get(index); if (object instanceof String) { return (String) object; } throw new JSONException("JSONArray[" + index + "] not a string."); } /** * Determine if the value is null. * * @param index * The index must be between 0 and length() - 1. * @return true if the value at the index is null, or if there is no value. */ public boolean isNull(int index) { return JSONObject.NULL.equals(this.opt(index)); } /** * Make a string from the contents of this JSONArray. The * <code>separator</code> string is inserted between each element. Warning: * This method assumes that the data structure is acyclical. * * @param separator * A string that will be inserted between the elements. * @return a string. * @throws JSONException * If the array contains an invalid number. */ public String join(String separator) throws JSONException { int len = this.length(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < len; i += 1) { if (i > 0) { sb.append(separator); } sb.append(JSONObject.valueToString(this.myArrayList.get(i))); } return sb.toString(); } /** * Get the number of elements in the JSONArray, included nulls. * * @return The length (or size). */ public int length() { return this.myArrayList.size(); } /** * Get the optional object value associated with an index. * * @param index * The index must be between 0 and length() - 1. * @return An object value, or null if there is no object at that index. */ public Object opt(int index) { return (index < 0 || index >= this.length()) ? null : this.myArrayList .get(index); } /** * Get the optional boolean value associated with an index. It returns false * if there is no value at that index, or if the value is not Boolean.TRUE * or the String "true". * * @param index * The index must be between 0 and length() - 1. * @return The truth. */ public boolean optBoolean(int index) { return this.optBoolean(index, false); } /** * Get the optional boolean value associated with an index. It returns the * defaultValue if there is no value at that index or if it is not a Boolean * or the String "true" or "false" (case insensitive). * * @param index * The index must be between 0 and length() - 1. * @param defaultValue * A boolean default. * @return The truth. */ public boolean optBoolean(int index, boolean defaultValue) { try { return this.getBoolean(index); } catch (Exception e) { return defaultValue; } } /** * Get the optional double value associated with an index. NaN is returned * if there is no value for the index, or if the value is not a number and * cannot be converted to a number. * * @param index * The index must be between 0 and length() - 1. * @return The value. */ public double optDouble(int index) { return this.optDouble(index, Double.NaN); } /** * Get the optional double value associated with an index. The defaultValue * is returned if there is no value for the index, or if the value is not a * number and cannot be converted to a number. * * @param index * subscript * @param defaultValue * The default value. * @return The value. */ public double optDouble(int index, double defaultValue) { try { return this.getDouble(index); } catch (Exception e) { return defaultValue; } } /** * Get the optional int value associated with an index. Zero is returned if * there is no value for the index, or if the value is not a number and * cannot be converted to a number. * * @param index * The index must be between 0 and length() - 1. * @return The value. */ public int optInt(int index) { return this.optInt(index, 0); } /** * Get the optional int value associated with an index. The defaultValue is * returned if there is no value for the index, or if the value is not a * number and cannot be converted to a number. * * @param index * The index must be between 0 and length() - 1. * @param defaultValue * The default value. * @return The value. */ public int optInt(int index, int defaultValue) { try { return this.getInt(index); } catch (Exception e) { return defaultValue; } } /** * Get the optional JSONArray associated with an index. * * @param index * subscript * @return A JSONArray value, or null if the index has no value, or if the * value is not a JSONArray. */ public JSONArray optJSONArray(int index) { Object o = this.opt(index); return o instanceof JSONArray ? (JSONArray) o : null; } /** * Get the optional JSONObject associated with an index. Null is returned if * the key is not found, or null if the index has no value, or if the value * is not a JSONObject. * * @param index * The index must be between 0 and length() - 1. * @return A JSONObject value. */ public JSONObject optJSONObject(int index) { Object o = this.opt(index); return o instanceof JSONObject ? (JSONObject) o : null; } /** * Get the optional long value associated with an index. Zero is returned if * there is no value for the index, or if the value is not a number and * cannot be converted to a number. * * @param index * The index must be between 0 and length() - 1. * @return The value. */ public long optLong(int index) { return this.optLong(index, 0); } /** * Get the optional long value associated with an index. The defaultValue is * returned if there is no value for the index, or if the value is not a * number and cannot be converted to a number. * * @param index * The index must be between 0 and length() - 1. * @param defaultValue * The default value. * @return The value. */ public long optLong(int index, long defaultValue) { try { return this.getLong(index); } catch (Exception e) { return defaultValue; } } /** * Get the optional string value associated with an index. It returns an * empty string if there is no value at that index. If the value is not a * string and is not null, then it is coverted to a string. * * @param index * The index must be between 0 and length() - 1. * @return A String value. */ public String optString(int index) { return this.optString(index, ""); } /** * Get the optional string associated with an index. The defaultValue is * returned if the key is not found. * * @param index * The index must be between 0 and length() - 1. * @param defaultValue * The default value. * @return A String value. */ public String optString(int index, String defaultValue) { Object object = this.opt(index); return JSONObject.NULL.equals(object) ? defaultValue : object .toString(); } /** * Append a boolean value. This increases the array's length by one. * * @param value * A boolean value. * @return this. */ public JSONArray put(boolean value) { this.put(value ? Boolean.TRUE : Boolean.FALSE); return this; } /** * Put a value in the JSONArray, where the value will be a JSONArray which * is produced from a Collection. * * @param value * A Collection value. * @return this. */ public JSONArray put(Collection<Object> value) { this.put(new JSONArray(value)); return this; } /** * Append a double value. This increases the array's length by one. * * @param value * A double value. * @throws JSONException * if the value is not finite. * @return this. */ public JSONArray put(double value) throws JSONException { Double d = new Double(value); JSONObject.testValidity(d); this.put(d); return this; } /** * Append an int value. This increases the array's length by one. * * @param value * An int value. * @return this. */ public JSONArray put(int value) { this.put(new Integer(value)); return this; } /** * Append an long value. This increases the array's length by one. * * @param value * A long value. * @return this. */ public JSONArray put(long value) { this.put(new Long(value)); return this; } /** * Put a value in the JSONArray, where the value will be a JSONObject which * is produced from a Map. * * @param value * A Map value. * @return this. */ public JSONArray put(Map<String, Object> value) { this.put(new JSONObject(value)); return this; } /** * Append an object value. This increases the array's length by one. * * @param value * An object value. The value should be a Boolean, Double, * Integer, JSONArray, JSONObject, Long, or String, or the * JSONObject.NULL object. * @return this. */ public JSONArray put(Object value) { this.myArrayList.add(value); return this; } /** * Put or replace a boolean value in the JSONArray. If the index is greater * than the length of the JSONArray, then null elements will be added as * necessary to pad it out. * * @param index * The subscript. * @param value * A boolean value. * @return this. * @throws JSONException * If the index is negative. */ public JSONArray put(int index, boolean value) throws JSONException { this.put(index, value ? Boolean.TRUE : Boolean.FALSE); return this; } /** * Put a value in the JSONArray, where the value will be a JSONArray which * is produced from a Collection. * * @param index * The subscript. * @param value * A Collection value. * @return this. * @throws JSONException * If the index is negative or if the value is not finite. */ public JSONArray put(int index, Collection<Object> value) throws JSONException { this.put(index, new JSONArray(value)); return this; } /** * Put or replace a double value. If the index is greater than the length of * the JSONArray, then null elements will be added as necessary to pad it * out. * * @param index * The subscript. * @param value * A double value. * @return this. * @throws JSONException * If the index is negative or if the value is not finite. */ public JSONArray put(int index, double value) throws JSONException { this.put(index, new Double(value)); return this; } /** * Put or replace an int value. If the index is greater than the length of * the JSONArray, then null elements will be added as necessary to pad it * out. * * @param index * The subscript. * @param value * An int value. * @return this. * @throws JSONException * If the index is negative. */ public JSONArray put(int index, int value) throws JSONException { this.put(index, new Integer(value)); return this; } /** * Put or replace a long value. If the index is greater than the length of * the JSONArray, then null elements will be added as necessary to pad it * out. * * @param index * The subscript. * @param value * A long value. * @return this. * @throws JSONException * If the index is negative. */ public JSONArray put(int index, long value) throws JSONException { this.put(index, new Long(value)); return this; } /** * Put a value in the JSONArray, where the value will be a JSONObject that * is produced from a Map. * * @param index * The subscript. * @param value * The Map value. * @return this. * @throws JSONException * If the index is negative or if the the value is an invalid * number. */ public JSONArray put(int index, Map<String, Object> value) throws JSONException { this.put(index, new JSONObject(value)); return this; } /** * Put or replace an object value in the JSONArray. If the index is greater * than the length of the JSONArray, then null elements will be added as * necessary to pad it out. * * @param index * The subscript. * @param value * The value to put into the array. The value should be a * Boolean, Double, Integer, JSONArray, JSONObject, Long, or * String, or the JSONObject.NULL object. * @return this. * @throws JSONException * If the index is negative or if the the value is an invalid * number. */ public JSONArray put(int index, Object value) throws JSONException { JSONObject.testValidity(value); if (index < 0) { throw new JSONException("JSONArray[" + index + "] not found."); } if (index < this.length()) { this.myArrayList.set(index, value); } else { while (index != this.length()) { this.put(JSONObject.NULL); } this.put(value); } return this; } /** * Remove an index and close the hole. * * @param index * The index of the element to be removed. * @return The value that was associated with the index, or null if there * was no value. */ public Object remove(int index) { return index >= 0 && index < this.length() ? this.myArrayList.remove(index) : null; } /** * Determine if two JSONArrays are similar. * They must contain similar sequences. * * @param other The other JSONArray * @return true if they are equal */ public boolean similar(Object other) { if (!(other instanceof JSONArray)) { return false; } int len = this.length(); if (len != ((JSONArray)other).length()) { return false; } for (int i = 0; i < len; i += 1) { Object valueThis = this.get(i); Object valueOther = ((JSONArray)other).get(i); if (valueThis instanceof JSONObject) { if (!((JSONObject)valueThis).similar(valueOther)) { return false; } } else if (valueThis instanceof JSONArray) { if (!((JSONArray)valueThis).similar(valueOther)) { return false; } } else if (!valueThis.equals(valueOther)) { return false; } } return true; } /** * Produce a JSONObject by combining a JSONArray of names with the values of * this JSONArray. * * @param names * A JSONArray containing a list of key strings. These will be * paired with the values. * @return A JSONObject, or null if there are no names or if this JSONArray * has no values. * @throws JSONException * If any of the names are null. */ public JSONObject toJSONObject(JSONArray names) throws JSONException { if (names == null || names.length() == 0 || this.length() == 0) { return null; } JSONObject jo = new JSONObject(); for (int i = 0; i < names.length(); i += 1) { jo.put(names.getString(i), this.opt(i)); } return jo; } /** * Make a JSON text of this JSONArray. For compactness, no unnecessary * whitespace is added. If it is not possible to produce a syntactically * correct JSON text then null will be returned instead. This could occur if * the array contains an invalid number. * <p> * Warning: This method assumes that the data structure is acyclical. * * @return a printable, displayable, transmittable representation of the * array. */ public String toString() { try { return this.toString(0); } catch (Exception e) { return null; } } /** * Make a prettyprinted JSON text of this JSONArray. Warning: This method * assumes that the data structure is acyclical. * * @param indentFactor * The number of spaces to add to each level of indentation. * @return a printable, displayable, transmittable representation of the * object, beginning with <code>[</code>&nbsp;<small>(left * bracket)</small> and ending with <code>]</code> * &nbsp;<small>(right bracket)</small>. * @throws JSONException */ public String toString(int indentFactor) throws JSONException { StringWriter sw = new StringWriter(); synchronized (sw.getBuffer()) { return this.write(sw, indentFactor, 0).toString(); } } /** * Write the contents of the JSONArray as JSON text to a writer. For * compactness, no whitespace is added. * <p> * Warning: This method assumes that the data structure is acyclical. * * @return The writer. * @throws JSONException */ public Writer write(Writer writer) throws JSONException { return this.write(writer, 0, 0); } /** * Write the contents of the JSONArray as JSON text to a writer. For * compactness, no whitespace is added. * <p> * Warning: This method assumes that the data structure is acyclical. * * @param indentFactor * The number of spaces to add to each level of indentation. * @param indent * The indention of the top level. * @return The writer. * @throws JSONException */ Writer write(Writer writer, int indentFactor, int indent) throws JSONException { try { boolean commanate = false; int length = this.length(); writer.write('['); if (length == 1) { JSONObject.writeValue(writer, this.myArrayList.get(0), indentFactor, indent); } else if (length != 0) { final int newindent = indent + indentFactor; for (int i = 0; i < length; i += 1) { if (commanate) { writer.write(','); } if (indentFactor > 0) { writer.write('\n'); } JSONObject.indent(writer, newindent); JSONObject.writeValue(writer, this.myArrayList.get(i), indentFactor, newindent); commanate = true; } if (indentFactor > 0) { writer.write('\n'); } JSONObject.indent(writer, indent); } writer.write(']'); return writer; } catch (IOException e) { throw new JSONException(e); } } }
package com.puppycrawl.tools.checkstyle.checks.imports; import static java.io.File.createTempFile; import static java.awt.Button.ABORT; import static javax.swing.WindowConstants.*; import java.awt.Button; import java.awt.Dialog; import java.awt.Frame; import java.awt.event.ActionEvent; /***comment test***/ import java.io.IOException; import java.io.InputStream; import javax.swing.JComponent; import javax.swing.JTable; import static java.io.File.*; import java.io.File; import java.io.Reader; public class InputImportOrder_Top { }
/* * Copyright 2002,2004 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.commons.jelly.impl; import java.util.List; import org.apache.commons.jelly.Script; /** * <p><code>CompositeTextScriptBlock</code> represents a text body of a * a tag which contains expressions, so that whitespace trimming * can be handled differently.</p> * * @author <a href="mailto:jstrachan@apache.org">James Strachan</a> * @version $Revision: 155420 $ */ public class CompositeTextScriptBlock extends ScriptBlock { /** * Create an instance. */ public CompositeTextScriptBlock() { } /** * Trim the body of the script. * In this case, trim the whitespace from the start of the first element * and from the end of the last element. */ public void trimWhitespace() { List list = getScriptList(); int size = list.size(); if ( size > 0 ) { Script script = (Script) list.get(0); if ( script instanceof TextScript ) { TextScript textScript = (TextScript) script; textScript.trimWhitespace(); } if ( size > 1 ) { script = (Script) list.get(size - 1); if ( script instanceof TextScript ) { TextScript textScript = (TextScript) script; textScript.trimWhitespace(); } } } } }
/* * Copyright 2013-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.inspector.model.transform; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import com.amazonaws.Request; import com.amazonaws.http.HttpMethodName; import com.amazonaws.services.inspector.model.*; import com.amazonaws.transform.Marshaller; import com.amazonaws.protocol.*; import com.amazonaws.protocol.Protocol; import com.amazonaws.annotation.SdkInternalApi; /** * DescribeExclusionsRequest Marshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") @SdkInternalApi public class DescribeExclusionsRequestProtocolMarshaller implements Marshaller<Request<DescribeExclusionsRequest>, DescribeExclusionsRequest> { private static final OperationInfo SDK_OPERATION_BINDING = OperationInfo.builder().protocol(Protocol.AWS_JSON).requestUri("/") .httpMethodName(HttpMethodName.POST).hasExplicitPayloadMember(false).hasPayloadMembers(true) .operationIdentifier("InspectorService.DescribeExclusions").serviceName("AmazonInspector").build(); private final com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory; public DescribeExclusionsRequestProtocolMarshaller(com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory) { this.protocolFactory = protocolFactory; } public Request<DescribeExclusionsRequest> marshall(DescribeExclusionsRequest describeExclusionsRequest) { if (describeExclusionsRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { final ProtocolRequestMarshaller<DescribeExclusionsRequest> protocolMarshaller = protocolFactory.createProtocolMarshaller(SDK_OPERATION_BINDING, describeExclusionsRequest); protocolMarshaller.startMarshalling(); DescribeExclusionsRequestMarshaller.getInstance().marshall(describeExclusionsRequest, protocolMarshaller); return protocolMarshaller.finishMarshalling(); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
package com.neeve.ccfd.fraudanalyzer; import java.io.File; import java.io.IOException; import java.net.URL; import java.util.HashSet; import java.util.Properties; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.rules.TestName; import com.neeve.server.embedded.EmbeddedXVM; import com.neeve.util.UtlFile; public class AbstractTest { @Rule public TestName testcaseName = new TestName(); protected static final HashSet<EmbeddedXVM> xvms = new HashSet<EmbeddedXVM>(); @BeforeClass public static void unitTestIntialize() throws IOException { File testRoot = getTestbedRoot(); System.setProperty("NVROOT", testRoot.getCanonicalPath()); File rdat = new File(testRoot, "rdat"); if (rdat.exists()) { UtlFile.deleteDirectory(rdat); } if (!testRoot.exists()) { testRoot.mkdirs(); } } protected static File getProjectBaseDirectory() { final String basedir = System.getProperty("basedir"); if (basedir != null) { return new File(basedir); } return new File("."); } protected static File getTestbedRoot() { return new File(getProjectBaseDirectory(), "target/testbed"); } @AfterClass public static void cleanup() throws Throwable { Throwable error = null; for (EmbeddedXVM xvm : xvms) { try { xvm.shutdown(); } catch (Throwable thrown) { if (error != null) { error = thrown; } thrown.printStackTrace(); } } System.clearProperty("NVROOT"); if (error != null) { throw error; } } @SuppressWarnings("unchecked") public <T> T startApp(Class<T> appClass, String appName, String xvmName, Properties env) throws Throwable { URL ddlConfig = new File(getProjectBaseDirectory(), "/conf/config.xml").toURI().toURL(); env.setProperty("x.env.nv.data.directory", new File(getTestbedRoot(), "rdat/" + xvmName).getCanonicalPath()); EmbeddedXVM xvm = EmbeddedXVM.create(ddlConfig, xvmName, env); xvms.add(xvm); xvm.start(); return (T)xvm.getApplication(appName); } }
package other; import java.util.LinkedList; public class P66 { public int[] plusOne(int[] digits) { LinkedList<Integer> linkedList = new LinkedList<>(); boolean is = false; for (int i = digits.length - 1; i >= 0; i--) { int num = digits[i]; if (i == digits.length - 1) { linkedList.add((num + 1) % 10); is = ((num + 1) % 10 == 0); } else { if (is) { num = (num + 1) % 10; is = (num == 0); } linkedList.addFirst(num); } } if (is) linkedList.addFirst(1); int[] array = new int[linkedList.size()]; for (int i = 0; i < array.length; i++) array[i] = linkedList.get(i); return array; } }
/* * Copyright 2017 * * Paul Rybitskyi, paul.rybitskyi.work@gmail.com * Arthur Ivanets, arthur.ivanets.l@gmail.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.paulrybitskyi.persistentsearchview.animations; import android.animation.ValueAnimator; import android.view.View; import android.view.animation.Interpolator; import android.view.animation.LinearInterpolator; import com.paulrybitskyi.persistentsearchview.utils.Preconditions; import com.paulrybitskyi.persistentsearchview.utils.Utils; import androidx.annotation.ColorInt; import androidx.annotation.NonNull; /** * An animation used for dimming a background of a view by changing * its alpha values. */ public final class BackgroundDimmingAnimation { private int mDimColor; private float mFromAlpha; private float mToAlpha; private View mView; private ValueAnimator mAnimator; private boolean mIsRecycled; public BackgroundDimmingAnimation(@NonNull View view, @ColorInt int dimColor, float fromAlpha, float toAlpha) { mView = view; mDimColor = dimColor; mFromAlpha = fromAlpha; mToAlpha = toAlpha; mIsRecycled = false; initAnimator(); } private void initAnimator() { mAnimator = ValueAnimator.ofFloat(mFromAlpha, mToAlpha); mAnimator.setInterpolator(new LinearInterpolator()); mAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator valueAnimator) { mView.setBackgroundColor(Utils.adjustColorAlpha( mDimColor, ((Float) valueAnimator.getAnimatedValue()) )); } }); } /** * Sets the color of the dim. * * @param dimColor The color to set * * @return this */ public BackgroundDimmingAnimation setDimColor(@ColorInt int dimColor) { mDimColor = dimColor; return this; } /** * Sets the starting alpha value of the animation. * * @param fromAlpha The starting alpha value to set * * @return this */ public BackgroundDimmingAnimation setFromAlpha(float fromAlpha) { mFromAlpha = fromAlpha; return this; } /** * Sets the ending alpha value to of the animation. * * @param toAlpha The ending alpha value to set * * @return this */ public BackgroundDimmingAnimation setToAlpha(float toAlpha) { mToAlpha = toAlpha; return this; } /** * Sets the interpolator of the animator. * * @param interpolator The interpolator to set * * @return this */ public BackgroundDimmingAnimation setInterpolator(@NonNull Interpolator interpolator) { Preconditions.nonNull(interpolator); mAnimator.setInterpolator(interpolator); return this; } /** * Sets the duration of the animation. * * @param duration The duration to set * * @return this */ public BackgroundDimmingAnimation setDuration(long duration) { mAnimator.setDuration(duration); return this; } /** * Starts the animation. */ public void start() { if(isRecycled()) { return; } stop(); mAnimator.start(); } /** * Stops the animation. */ public void stop() { if(!isRecycled() && isRunning()) { mAnimator.cancel(); } } /** * Checks whether the animation is running or not. * * @return true if running; false otherwise */ public boolean isRunning() { return mAnimator.isRunning(); } /** * Recycles the animation by releasing all underlying resources. */ public void recycle() { if(mIsRecycled) { return; } mView = null; mAnimator = null; mIsRecycled = true; } /** * Checks whether the animation has been recycled or not. * * @return true if recycled; false otherwise */ public boolean isRecycled() { return mIsRecycled; } }
package org.hawkular.alerts.netty.handlers; import static io.netty.handler.codec.http.HttpMethod.DELETE; import static io.netty.handler.codec.http.HttpMethod.GET; import static io.netty.handler.codec.http.HttpMethod.POST; import static io.netty.handler.codec.http.HttpMethod.PUT; import static io.netty.handler.codec.http.HttpResponseStatus.OK; import static org.hawkular.alerts.api.json.JsonUtil.collectionFromJson; import static org.hawkular.alerts.api.json.JsonUtil.toJson; import static org.hawkular.alerts.netty.HandlersManager.TENANT_HEADER_NAME; import static org.hawkular.alerts.netty.util.ResponseUtil.badRequest; import static org.hawkular.alerts.netty.util.ResponseUtil.extractPaging; import static org.hawkular.alerts.netty.util.ResponseUtil.handleExceptions; import static org.hawkular.alerts.netty.util.ResponseUtil.internalServerError; import static org.hawkular.alerts.netty.util.ResponseUtil.isEmpty; import static org.hawkular.alerts.netty.util.ResponseUtil.notFound; import static org.hawkular.alerts.netty.util.ResponseUtil.ok; import static org.hawkular.alerts.netty.util.ResponseUtil.paginatedOk; import static org.hawkular.alerts.netty.util.ResponseUtil.parseTagQuery; import static org.hawkular.alerts.netty.util.ResponseUtil.parseTags; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import org.hawkular.alerts.api.model.data.Data; import org.hawkular.alerts.api.model.event.Alert; import org.hawkular.alerts.api.model.paging.Page; import org.hawkular.alerts.api.model.paging.Pager; import org.hawkular.alerts.api.services.AlertsCriteria; import org.hawkular.alerts.api.services.AlertsService; import org.hawkular.alerts.engine.StandaloneAlerts; import org.hawkular.alerts.log.MsgLogger; import org.hawkular.alerts.netty.RestEndpoint; import org.hawkular.alerts.netty.RestHandler; import org.hawkular.alerts.netty.handlers.AlertsWatcher.AlertsListener; import org.hawkular.alerts.netty.util.ResponseUtil; import org.hawkular.alerts.netty.util.ResponseUtil.BadRequestException; import org.hawkular.alerts.netty.util.ResponseUtil.InternalServerException; import org.jboss.logging.Logger; import org.reactivestreams.Publisher; import io.netty.handler.codec.http.HttpMethod; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import reactor.core.scheduler.Schedulers; import reactor.ipc.netty.http.server.HttpServerRequest; import reactor.ipc.netty.http.server.HttpServerResponse; /** * @author Jay Shaughnessy * @author Lucas Ponce */ @RestEndpoint(path = "/") public class AlertsHandler implements RestHandler { private static final MsgLogger log = Logger.getMessageLogger(MsgLogger.class, AlertsHandler.class.getName()); private static final String ROOT = "/"; private static final String WATCH = "/watch"; private static final String ACK = "/ack"; private static final String NOTE = "/note"; private static final String TAGS = "/tags"; private static final String ALERT = "/alert"; private static final String RESOLVE = "/resolve"; private static final String DATA = "/data"; private static final String _DELETE = "/delete"; private static final String PARAM_START_TIME = "startTime"; private static final String PARAM_END_TIME = "endTime"; private static final String PARAM_ALERT_IDS = "alertIds"; private static final String PARAM_TRIGGER_IDS = "triggerIds"; private static final String PARAM_STATUSES = "statuses"; private static final String PARAM_SEVERITIES = "severities"; private static final String PARAM_TAGS = "tags"; private static final String PARAM_TAG_QUERY = "tagQuery"; private static final String PARAM_START_RESOLVED_TIME = "startResolvedTime"; private static final String PARAM_END_RESOLVED_TIME = "endResolvedTime"; private static final String PARAM_START_ACK_TIME = "startAckTime"; private static final String PARAM_END_ACK_TIME = "endAckTime"; private static final String PARAM_START_STATUS_TIME = "startStatusTime"; private static final String PARAM_END_STATUS_TIME = "endStatusTime"; private static final String PARAM_WATCH_INTERVAL = "watchInterval"; private static final String PARAM_ACK_BY = "ackBy"; private static final String PARAM_ACK_NOTES = "ackNotes"; private static final String PARAM_USER = "user"; private static final String PARAM_TEXT = "text"; private static final String PARAM_TAG_NAMES = "tagNames"; private static final String PARAM_THIN = "thin"; private static final String PARAM_RESOLVED_BY = "resolvedBy"; private static final String PARAM_RESOLVED_NOTES = "resolvedNotes"; AlertsService alertsService; public AlertsHandler() { alertsService = StandaloneAlerts.getAlertsService(); } @Override public Publisher<Void> process(HttpServerRequest req, HttpServerResponse resp, String tenantId, String subpath, Map<String, List<String>> params) { HttpMethod method = req.method(); if (isEmpty(tenantId)) { return badRequest(resp, TENANT_HEADER_NAME + " header is required"); } // GET / if (method == GET && subpath.equals(ROOT)) { return findAlerts(req, resp, tenantId, params, req.uri()); } // GET /watch if (method == GET && subpath.equals(WATCH)) { return watchAlerts(resp, tenantId, params); } // PUT /tags if (method == PUT && subpath.equals(TAGS)) { return addTags(req, resp, tenantId, params); } // DELETE /tags if (method == DELETE && subpath.equals(TAGS)) { return removeTags(req, resp, tenantId, params); } // PUT /ack if (method == PUT && subpath.equals(ACK)) { return ackAlerts(req, resp, tenantId, params); } // PUT /delete if (method == PUT && subpath.equals(_DELETE)) { return deleteAlerts(req, resp, tenantId, null, params); } // PUT /resolve if (method == PUT && subpath.equals(RESOLVE)) { return resolveAlerts(req, resp, tenantId, null, params); } // POST /data if (method == POST && subpath.equals(DATA)) { return sendData(req, resp, tenantId); } String[] tokens = subpath.substring(1).split(ROOT); // DELETE /{alertId} if (method == DELETE && tokens.length == 1) { return deleteAlerts(req, resp, tenantId, tokens[0], params); } // PUT /ack/{alertId} if (method == PUT && subpath.startsWith(ACK) && tokens.length == 2) { return ackAlert(req, resp, tenantId, tokens[1], params); } // PUT /note/{alertId} if (method == PUT && subpath.startsWith(NOTE) && tokens.length == 2) { return addAlertNote(req, resp, tenantId, tokens[1], params); } // GET /alert/{alertId} if (method == GET && subpath.startsWith(ALERT) && tokens.length == 2) { return getAlert(req, resp, tenantId, tokens[1], params); } // PUT /resolve/{alertId} if (method == PUT && subpath.startsWith(RESOLVE) && tokens.length == 2) { return resolveAlerts(req, resp, tenantId, tokens[1], params); } return badRequest(resp, "Wrong path " + method + " " + subpath); } Publisher<Void> findAlerts(HttpServerRequest req, HttpServerResponse resp, String tenantId, Map<String, List<String>> params, String uri) { return req .receive() .publishOn(Schedulers.elastic()) .thenMany(Mono.fromSupplier(() -> { try { Pager pager = extractPaging(params); AlertsCriteria criteria = buildCriteria(params); Page<Alert> alertPage = alertsService.getAlerts(tenantId, criteria, pager); log.debugf("Alerts: %s", alertPage); return alertPage; } catch (IllegalArgumentException e) { throw new BadRequestException("Bad arguments: " + e.getMessage()); } catch (Exception e) { log.debug(e.getMessage(), e); throw new InternalServerException(e.toString()); } })) .flatMap(alertPage -> { if (isEmpty(alertPage)) { return ok(resp, alertPage); } return paginatedOk(req, resp, alertPage, uri); }) .onErrorResumeWith(e -> handleExceptions(resp, e)); } Publisher<Void> watchAlerts(HttpServerResponse resp, String tenantId, Map<String, List<String>> params) { AlertsCriteria criteria = buildCriteria(params); Flux<String> watcherFlux = Flux.create(sink -> { Long watchInterval = null; if (params.get(PARAM_WATCH_INTERVAL) != null) { watchInterval = Long.valueOf(params.get(PARAM_WATCH_INTERVAL).get(0)); } AlertsListener listener = alert -> { sink.next(toJson(alert) + "\r\n"); }; String channelId = resp.context().channel().id().asShortText(); AlertsWatcher watcher = new AlertsWatcher(channelId, listener, Collections.singleton(tenantId), criteria, watchInterval); sink.onCancel(() -> watcher.dispose()); watcher.start(); }); resp.status(OK); // Watcher send alerts one by one, so flux is splited in windows of one element return watcherFlux.window(1).concatMap(w -> resp.sendString(w)); } Publisher<Void> ackAlert(HttpServerRequest req, HttpServerResponse resp, String tenantId, String alertId, Map<String, List<String>> params) { return req .receive() .publishOn(Schedulers.elastic()) .thenMany(Mono.fromSupplier(() -> { String ackBy = null; String ackNotes = null; if (isEmpty(alertId)) { return badRequest(resp, "AlertId required for ack"); } if (params.get(PARAM_ACK_BY) != null) { ackBy = params.get(PARAM_ACK_BY).get(0); } if (params.get(PARAM_ACK_NOTES) != null) { ackNotes = params.get(PARAM_ACK_NOTES).get(0); } try { alertsService.ackAlerts(tenantId, Arrays.asList(alertId), ackBy, ackNotes); log.debugf("Ack AlertId: ", alertId); return ackBy; } catch (IllegalArgumentException e) { throw new BadRequestException("Bad arguments: " + e.getMessage()); } catch (Exception e) { log.debug(e.getMessage(), e); throw new InternalServerException(e.toString()); } })) .flatMap(ackBy -> ok(resp)) .onErrorResumeWith(e -> handleExceptions(resp, e)); } Publisher<Void> addAlertNote(HttpServerRequest req, HttpServerResponse resp, String tenantId, String alertId, Map<String, List<String>> params) { return req .receive() .publishOn(Schedulers.elastic()) .thenMany(Mono.fromSupplier(() -> { String user = null; String text = null; if (isEmpty(alertId)) { throw new BadRequestException("AlertId required for adding notes"); } if (params.get(PARAM_USER) != null) { user = params.get(PARAM_USER).get(0); } if (params.get(PARAM_TEXT) != null) { text = params.get(PARAM_TEXT).get(0); } try { alertsService.addNote(tenantId, alertId, user, text); log.debugf("Noted AlertId: ", alertId); return user; } catch (IllegalArgumentException e) { throw new BadRequestException("Bad arguments: " + e.getMessage()); } catch (Exception e) { log.debug(e.getMessage(), e); throw new InternalServerException(e.toString()); } })) .flatMap(user -> ok(resp)) .onErrorResumeWith(e -> handleExceptions(resp, e)); } Publisher<Void> addTags(HttpServerRequest req, HttpServerResponse resp, String tenantId, Map<String, List<String>> params) { return req .receive() .publishOn(Schedulers.elastic()) .thenMany(Mono.fromSupplier(() -> { String alertIds = null; String tags = null; if (params.get(PARAM_ALERT_IDS) != null) { alertIds = params.get(PARAM_ALERT_IDS).get(0); } if (params.get(PARAM_TAGS) != null) { tags = params.get(PARAM_TAGS).get(0); } if (isEmpty(alertIds) || isEmpty(tags)) { throw new BadRequestException("AlertIds and Tags required for adding tags"); } try { List<String> alertIdList = Arrays.asList(alertIds.split(",")); Map<String, String> tagsMap = parseTags(tags); alertsService.addAlertTags(tenantId, alertIdList, tagsMap); log.debugf("Tagged alertIds:%s, %s", alertIdList, tagsMap); return tags; } catch (IllegalArgumentException e) { throw new BadRequestException("Bad arguments: " + e.getMessage()); } catch (Exception e) { throw new InternalServerException(e.toString()); } })) .flatMap(tags -> ok(resp)) .onErrorResumeWith(e -> handleExceptions(resp, e)); } Publisher<Void> removeTags(HttpServerRequest req, HttpServerResponse resp, String tenantId, Map<String, List<String>> params) { return req .receive() .publishOn(Schedulers.elastic()) .thenMany(Mono.fromSupplier(() -> { String alertIds = null; String tagNames = null; if (params.get(PARAM_ALERT_IDS) != null) { alertIds = params.get(PARAM_ALERT_IDS).get(0); } if (params.get(PARAM_TAG_NAMES) != null) { tagNames = params.get(PARAM_TAG_NAMES).get(0); } if (isEmpty(alertIds) || isEmpty(tagNames)) { throw new BadRequestException("AlertIds and Tags required for removing tags"); } try { Collection<String> ids = Arrays.asList(alertIds.split(",")); Collection<String> tags = Arrays.asList(tagNames.split(",")); alertsService.removeAlertTags(tenantId, ids, tags); log.debugf("Untagged alertIds:%s, %s", ids, tags); return tags; } catch (IllegalArgumentException e) { throw new BadRequestException("Bad arguments: " + e.getMessage()); } catch (Exception e) { throw new InternalServerException(e.toString()); } })) .flatMap(tags -> ok(resp)) .onErrorResumeWith(e -> handleExceptions(resp, e)); } Publisher<Void> ackAlerts(HttpServerRequest req, HttpServerResponse resp, String tenantId, Map<String, List<String>> params) { return req .receive() .publishOn(Schedulers.elastic()) .thenMany(Mono.fromSupplier(() -> { String alertIds = null; String ackBy = null; String ackNotes = null; if (params.get(PARAM_ALERT_IDS) != null) { alertIds = params.get(PARAM_ALERT_IDS).get(0); } if (params.get(PARAM_ACK_BY) != null) { ackBy = params.get(PARAM_ACK_BY).get(0); } if (params.get(PARAM_ACK_NOTES) != null) { ackNotes = params.get(PARAM_ACK_NOTES).get(0); } if (isEmpty(alertIds)) { throw new BadRequestException("AlertIds required for ack"); } try { alertsService.ackAlerts(tenantId, Arrays.asList(alertIds.split(",")), ackBy, ackNotes); log.debugf("Acked alertIds: %s", alertIds); return alertIds; } catch (IllegalArgumentException e) { throw new BadRequestException("Bad arguments: " + e.getMessage()); } catch (Exception e) { throw new InternalServerException(e.toString()); } })) .flatMap(alertIds -> ok(resp)) .onErrorResumeWith(e -> handleExceptions(resp, e)); } Publisher<Void> deleteAlerts(HttpServerRequest req, HttpServerResponse resp, String tenantId, String alertId, Map<String, List<String>> params) { return req .receive() .publishOn(Schedulers.elastic()) .thenMany(Mono.fromSupplier(() -> { AlertsCriteria criteria = buildCriteria(params); criteria.setAlertId(alertId); int numDeleted = -1; try { numDeleted = alertsService.deleteAlerts(tenantId, criteria); log.debugf("Alerts deleted: ", numDeleted); } catch (IllegalArgumentException e) { throw new BadRequestException("Bad arguments: " + e.getMessage()); } catch (Exception e) { log.debug(e.getMessage(), e); throw new InternalServerException(e.toString()); } if (numDeleted <= 0 && alertId != null) { throw new ResponseUtil.NotFoundException("Alert " + alertId + " doesn't exist for delete"); } Map<String, Integer> deleted = new HashMap<>(); deleted.put("deleted", new Integer(numDeleted)); return deleted; })) .flatMap(deleted -> ok(resp,deleted)) .onErrorResumeWith(e -> handleExceptions(resp, e)); } Publisher<Void> getAlert(HttpServerRequest req, HttpServerResponse resp, String tenantId, String alertId, Map<String, List<String>> params) { return req .receive() .publishOn(Schedulers.elastic()) .thenMany(Mono.fromSupplier(() -> { boolean thin = false; if (params.get(PARAM_THIN) != null) { thin = Boolean.valueOf(params.get(PARAM_THIN).get(0)); } Alert found; try { found = alertsService.getAlert(tenantId, alertId, thin); log.debugf("Alert: ", found); } catch (IllegalArgumentException e) { throw new BadRequestException("Bad arguments: " + e.getMessage()); } catch (Exception e) { log.debug(e.getMessage(), e); throw new InternalServerException(e.toString()); } if (found == null) { throw new ResponseUtil.NotFoundException("alertId: " + alertId + " not found"); } return found; })) .flatMap(found -> ok(resp, found)) .onErrorResumeWith(e -> handleExceptions(resp, e)); } Publisher<Void> resolveAlerts(HttpServerRequest req, HttpServerResponse resp, String tenantId, String alertId, Map<String, List<String>> params) { return req .receive() .publishOn(Schedulers.elastic()) .thenMany(Mono.fromSupplier(() -> { String alertIds = null; String resolvedBy = null; String resolvedNotes = null; if (params.get(PARAM_ALERT_IDS) != null) { alertIds = params.get(PARAM_ALERT_IDS).get(0); } if (alertIds == null) { alertIds = alertId; } if (params.get(PARAM_RESOLVED_BY) != null) { resolvedBy = params.get(PARAM_RESOLVED_BY).get(0); } if (params.get(PARAM_RESOLVED_NOTES) != null) { resolvedNotes = params.get(PARAM_RESOLVED_NOTES).get(0); } if (isEmpty(alertIds)) { throw new BadRequestException("AlertIds required for resolve"); } try { alertsService.resolveAlerts(tenantId, Arrays.asList(alertIds.split(",")), resolvedBy, resolvedNotes, null); log.debugf("Resolved alertIds: ", alertIds); return alertIds; } catch (IllegalArgumentException e) { throw new BadRequestException("Bad arguments: " + e.getMessage()); } catch (Exception e) { throw new InternalServerException(e.toString()); } })) .flatMap(alertIds -> ok(resp)) .onErrorResumeWith(e -> handleExceptions(resp, e)); } Publisher<Void> sendData(HttpServerRequest req, HttpServerResponse resp, String tenantId) { return req .receive() .aggregate() .asString() .publishOn(Schedulers.elastic()) .map(json -> { Collection<Data> parsed; try { parsed = collectionFromJson(json, Data.class); return parsed; } catch (Exception e) { log.errorf(e, "Error parsing Datums json: %s. Reason: %s", json, e.toString()); throw new BadRequestException(e.toString()); } }) .flatMap(datums -> { if (isEmpty(datums)) { throw new BadRequestException("Data is empty"); } try { datums.stream().forEach(d -> d.setTenantId(tenantId)); alertsService.sendData(datums); log.debugf("Datums: ", datums); return ok(resp); } catch (IllegalArgumentException e) { throw new BadRequestException("Bad arguments: " + e.getMessage()); } catch (Exception e) { throw new InternalServerException(e.toString()); } }) .onErrorResumeWith(e -> handleExceptions(resp, e)); } AlertsCriteria buildCriteria(Map<String, List<String>> params) { Long startTime = null; Long endTime = null; String alertIds = null; String triggerIds = null; String statuses = null; String severities = null; String tags = null; String tagQuery = null; Long startResolvedTime = null; Long endResolvedTime = null; Long startAckTime = null; Long endAckTime = null; Long startStatusTime = null; Long endStatusTime = null; boolean thin = false; if (params.get(PARAM_START_TIME) != null) { startTime = Long.valueOf(params.get(PARAM_START_TIME).get(0)); } if (params.get(PARAM_END_TIME) != null) { endTime = Long.valueOf(params.get(PARAM_END_TIME).get(0)); } if (params.get(PARAM_ALERT_IDS) != null) { alertIds = params.get(PARAM_ALERT_IDS).get(0); } if (params.get(PARAM_TRIGGER_IDS) != null) { triggerIds = params.get(PARAM_TRIGGER_IDS).get(0); } if (params.get(PARAM_STATUSES) != null) { statuses = params.get(PARAM_STATUSES).get(0); } if (params.get(PARAM_SEVERITIES) != null) { severities = params.get(PARAM_SEVERITIES).get(0); } if (params.get(PARAM_TAGS) != null) { tags = params.get(PARAM_TAGS).get(0); } if (params.get(PARAM_TAG_QUERY) != null) { tagQuery = params.get(PARAM_TAG_QUERY).get(0); } String unifiedTagQuery; if (!isEmpty(tags)) { unifiedTagQuery = parseTagQuery(parseTags(tags)); } else { unifiedTagQuery = tagQuery; } if (params.get(PARAM_START_RESOLVED_TIME) != null) { startResolvedTime = Long.valueOf(params.get(PARAM_START_RESOLVED_TIME).get(0)); } if (params.get(PARAM_END_RESOLVED_TIME) != null) { endResolvedTime = Long.valueOf(params.get(PARAM_END_RESOLVED_TIME).get(0)); } if (params.get(PARAM_START_ACK_TIME) != null) { startAckTime = Long.valueOf(params.get(PARAM_START_ACK_TIME).get(0)); } if (params.get(PARAM_END_ACK_TIME) != null) { endAckTime = Long.valueOf(params.get(PARAM_END_ACK_TIME).get(0)); } if (params.get(PARAM_START_STATUS_TIME) != null) { startStatusTime = Long.valueOf(params.get(PARAM_START_STATUS_TIME).get(0)); } if (params.get(PARAM_END_STATUS_TIME) != null) { endStatusTime = Long.valueOf(params.get(PARAM_END_STATUS_TIME).get(0)); } if (params.get(PARAM_THIN) != null) { thin = Boolean.valueOf(params.get(PARAM_THIN).get(0)); } return new AlertsCriteria(startTime, endTime, alertIds, triggerIds, statuses, severities, unifiedTagQuery, startResolvedTime, endResolvedTime, startAckTime, endAckTime, startStatusTime, endStatusTime, thin); } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package controllers; import controllers.exceptions.NonexistentEntityException; import java.io.Serializable; import javax.persistence.Query; import javax.persistence.EntityNotFoundException; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Root; import entities.Assures; import entities.Decomptes; import entities.Exercices; import entities.Polices; import entities.Succursales; import entities.Zonegeos; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; /** * * @author EDY TCHOKOUANI */ public class DecomptesJpaController implements Serializable { public DecomptesJpaController(EntityManagerFactory emf) { this.emf = emf; } private EntityManagerFactory emf = null; public EntityManager getEntityManager() { return emf.createEntityManager(); } public void create(Decomptes decomptes) { EntityManager em = null; try { em = getEntityManager(); em.getTransaction().begin(); Assures assureId = decomptes.getAssureId(); if (assureId != null) { assureId = em.getReference(assureId.getClass(), assureId.getId()); decomptes.setAssureId(assureId); } Exercices exerciceId = decomptes.getExerciceId(); if (exerciceId != null) { exerciceId = em.getReference(exerciceId.getClass(), exerciceId.getId()); decomptes.setExerciceId(exerciceId); } Polices policeId = decomptes.getPoliceId(); if (policeId != null) { policeId = em.getReference(policeId.getClass(), policeId.getId()); decomptes.setPoliceId(policeId); } Succursales succursaleId = decomptes.getSuccursaleId(); if (succursaleId != null) { succursaleId = em.getReference(succursaleId.getClass(), succursaleId.getId()); decomptes.setSuccursaleId(succursaleId); } Zonegeos zonegeoId = decomptes.getZonegeoId(); if (zonegeoId != null) { zonegeoId = em.getReference(zonegeoId.getClass(), zonegeoId.getId()); decomptes.setZonegeoId(zonegeoId); } em.persist(decomptes); if (assureId != null) { assureId.getDecomptesList().add(decomptes); assureId = em.merge(assureId); } if (exerciceId != null) { exerciceId.getDecomptesList().add(decomptes); exerciceId = em.merge(exerciceId); } if (policeId != null) { policeId.getDecomptesList().add(decomptes); policeId = em.merge(policeId); } if (succursaleId != null) { succursaleId.getDecomptesList().add(decomptes); succursaleId = em.merge(succursaleId); } if (zonegeoId != null) { zonegeoId.getDecomptesList().add(decomptes); zonegeoId = em.merge(zonegeoId); } em.getTransaction().commit(); } finally { if (em != null) { em.close(); } } } public void edit(Decomptes decomptes) throws NonexistentEntityException, Exception { EntityManager em = null; try { em = getEntityManager(); em.getTransaction().begin(); Decomptes persistentDecomptes = em.find(Decomptes.class, decomptes.getId()); Assures assureIdOld = persistentDecomptes.getAssureId(); Assures assureIdNew = decomptes.getAssureId(); Exercices exerciceIdOld = persistentDecomptes.getExerciceId(); Exercices exerciceIdNew = decomptes.getExerciceId(); Polices policeIdOld = persistentDecomptes.getPoliceId(); Polices policeIdNew = decomptes.getPoliceId(); Succursales succursaleIdOld = persistentDecomptes.getSuccursaleId(); Succursales succursaleIdNew = decomptes.getSuccursaleId(); Zonegeos zonegeoIdOld = persistentDecomptes.getZonegeoId(); Zonegeos zonegeoIdNew = decomptes.getZonegeoId(); if (assureIdNew != null) { assureIdNew = em.getReference(assureIdNew.getClass(), assureIdNew.getId()); decomptes.setAssureId(assureIdNew); } if (exerciceIdNew != null) { exerciceIdNew = em.getReference(exerciceIdNew.getClass(), exerciceIdNew.getId()); decomptes.setExerciceId(exerciceIdNew); } if (policeIdNew != null) { policeIdNew = em.getReference(policeIdNew.getClass(), policeIdNew.getId()); decomptes.setPoliceId(policeIdNew); } if (succursaleIdNew != null) { succursaleIdNew = em.getReference(succursaleIdNew.getClass(), succursaleIdNew.getId()); decomptes.setSuccursaleId(succursaleIdNew); } if (zonegeoIdNew != null) { zonegeoIdNew = em.getReference(zonegeoIdNew.getClass(), zonegeoIdNew.getId()); decomptes.setZonegeoId(zonegeoIdNew); } decomptes = em.merge(decomptes); if (assureIdOld != null && !assureIdOld.equals(assureIdNew)) { assureIdOld.getDecomptesList().remove(decomptes); assureIdOld = em.merge(assureIdOld); } if (assureIdNew != null && !assureIdNew.equals(assureIdOld)) { assureIdNew.getDecomptesList().add(decomptes); assureIdNew = em.merge(assureIdNew); } if (exerciceIdOld != null && !exerciceIdOld.equals(exerciceIdNew)) { exerciceIdOld.getDecomptesList().remove(decomptes); exerciceIdOld = em.merge(exerciceIdOld); } if (exerciceIdNew != null && !exerciceIdNew.equals(exerciceIdOld)) { exerciceIdNew.getDecomptesList().add(decomptes); exerciceIdNew = em.merge(exerciceIdNew); } if (policeIdOld != null && !policeIdOld.equals(policeIdNew)) { policeIdOld.getDecomptesList().remove(decomptes); policeIdOld = em.merge(policeIdOld); } if (policeIdNew != null && !policeIdNew.equals(policeIdOld)) { policeIdNew.getDecomptesList().add(decomptes); policeIdNew = em.merge(policeIdNew); } if (succursaleIdOld != null && !succursaleIdOld.equals(succursaleIdNew)) { succursaleIdOld.getDecomptesList().remove(decomptes); succursaleIdOld = em.merge(succursaleIdOld); } if (succursaleIdNew != null && !succursaleIdNew.equals(succursaleIdOld)) { succursaleIdNew.getDecomptesList().add(decomptes); succursaleIdNew = em.merge(succursaleIdNew); } if (zonegeoIdOld != null && !zonegeoIdOld.equals(zonegeoIdNew)) { zonegeoIdOld.getDecomptesList().remove(decomptes); zonegeoIdOld = em.merge(zonegeoIdOld); } if (zonegeoIdNew != null && !zonegeoIdNew.equals(zonegeoIdOld)) { zonegeoIdNew.getDecomptesList().add(decomptes); zonegeoIdNew = em.merge(zonegeoIdNew); } em.getTransaction().commit(); } catch (Exception ex) { String msg = ex.getLocalizedMessage(); if (msg == null || msg.length() == 0) { Integer id = decomptes.getId(); if (findDecomptes(id) == null) { throw new NonexistentEntityException("The decomptes with id " + id + " no longer exists."); } } throw ex; } finally { if (em != null) { em.close(); } } } public void destroy(Integer id) throws NonexistentEntityException { EntityManager em = null; try { em = getEntityManager(); em.getTransaction().begin(); Decomptes decomptes; try { decomptes = em.getReference(Decomptes.class, id); decomptes.getId(); } catch (EntityNotFoundException enfe) { throw new NonexistentEntityException("The decomptes with id " + id + " no longer exists.", enfe); } Assures assureId = decomptes.getAssureId(); if (assureId != null) { assureId.getDecomptesList().remove(decomptes); assureId = em.merge(assureId); } Exercices exerciceId = decomptes.getExerciceId(); if (exerciceId != null) { exerciceId.getDecomptesList().remove(decomptes); exerciceId = em.merge(exerciceId); } Polices policeId = decomptes.getPoliceId(); if (policeId != null) { policeId.getDecomptesList().remove(decomptes); policeId = em.merge(policeId); } Succursales succursaleId = decomptes.getSuccursaleId(); if (succursaleId != null) { succursaleId.getDecomptesList().remove(decomptes); succursaleId = em.merge(succursaleId); } Zonegeos zonegeoId = decomptes.getZonegeoId(); if (zonegeoId != null) { zonegeoId.getDecomptesList().remove(decomptes); zonegeoId = em.merge(zonegeoId); } em.remove(decomptes); em.getTransaction().commit(); } finally { if (em != null) { em.close(); } } } public List<Decomptes> findDecomptesEntities() { return findDecomptesEntities(true, -1, -1); } public List<Decomptes> findDecomptesEntities(int maxResults, int firstResult) { return findDecomptesEntities(false, maxResults, firstResult); } private List<Decomptes> findDecomptesEntities(boolean all, int maxResults, int firstResult) { EntityManager em = getEntityManager(); try { CriteriaQuery cq = em.getCriteriaBuilder().createQuery(); cq.select(cq.from(Decomptes.class)); Query q = em.createQuery(cq); if (!all) { q.setMaxResults(maxResults); q.setFirstResult(firstResult); } return q.getResultList(); } finally { em.close(); } } public Decomptes findDecomptes(Integer id) { EntityManager em = getEntityManager(); try { return em.find(Decomptes.class, id); } finally { em.close(); } } public int getDecomptesCount() { EntityManager em = getEntityManager(); try { CriteriaQuery cq = em.getCriteriaBuilder().createQuery(); Root<Decomptes> rt = cq.from(Decomptes.class); cq.select(em.getCriteriaBuilder().count(rt)); Query q = em.createQuery(cq); return ((Long) q.getSingleResult()).intValue(); } finally { em.close(); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.securityinsights.models; import com.azure.core.annotation.Fluent; import com.azure.resourcemanager.securityinsights.fluent.models.AlertRuleInner; import com.azure.resourcemanager.securityinsights.fluent.models.FusionAlertRuleProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.JsonTypeName; import java.time.OffsetDateTime; import java.util.List; /** Represents Fusion alert rule. */ @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "kind") @JsonTypeName("Fusion") @Fluent public final class FusionAlertRule extends AlertRuleInner { /* * Fusion alert rule properties */ @JsonProperty(value = "properties") private FusionAlertRuleProperties innerProperties; /** * Get the innerProperties property: Fusion alert rule properties. * * @return the innerProperties value. */ private FusionAlertRuleProperties innerProperties() { return this.innerProperties; } /** {@inheritDoc} */ @Override public FusionAlertRule withEtag(String etag) { super.withEtag(etag); return this; } /** * Get the alertRuleTemplateName property: The Name of the alert rule template used to create this rule. * * @return the alertRuleTemplateName value. */ public String alertRuleTemplateName() { return this.innerProperties() == null ? null : this.innerProperties().alertRuleTemplateName(); } /** * Set the alertRuleTemplateName property: The Name of the alert rule template used to create this rule. * * @param alertRuleTemplateName the alertRuleTemplateName value to set. * @return the FusionAlertRule object itself. */ public FusionAlertRule withAlertRuleTemplateName(String alertRuleTemplateName) { if (this.innerProperties() == null) { this.innerProperties = new FusionAlertRuleProperties(); } this.innerProperties().withAlertRuleTemplateName(alertRuleTemplateName); return this; } /** * Get the description property: The description of the alert rule. * * @return the description value. */ public String description() { return this.innerProperties() == null ? null : this.innerProperties().description(); } /** * Get the displayName property: The display name for alerts created by this alert rule. * * @return the displayName value. */ public String displayName() { return this.innerProperties() == null ? null : this.innerProperties().displayName(); } /** * Get the enabled property: Determines whether this alert rule is enabled or disabled. * * @return the enabled value. */ public Boolean enabled() { return this.innerProperties() == null ? null : this.innerProperties().enabled(); } /** * Set the enabled property: Determines whether this alert rule is enabled or disabled. * * @param enabled the enabled value to set. * @return the FusionAlertRule object itself. */ public FusionAlertRule withEnabled(Boolean enabled) { if (this.innerProperties() == null) { this.innerProperties = new FusionAlertRuleProperties(); } this.innerProperties().withEnabled(enabled); return this; } /** * Get the sourceSettings property: Configuration for all supported source signals in fusion detection. * * @return the sourceSettings value. */ public List<FusionSourceSettings> sourceSettings() { return this.innerProperties() == null ? null : this.innerProperties().sourceSettings(); } /** * Set the sourceSettings property: Configuration for all supported source signals in fusion detection. * * @param sourceSettings the sourceSettings value to set. * @return the FusionAlertRule object itself. */ public FusionAlertRule withSourceSettings(List<FusionSourceSettings> sourceSettings) { if (this.innerProperties() == null) { this.innerProperties = new FusionAlertRuleProperties(); } this.innerProperties().withSourceSettings(sourceSettings); return this; } /** * Get the scenarioExclusionPatterns property: Configuration to exclude scenarios in fusion detection. * * @return the scenarioExclusionPatterns value. */ public List<FusionScenarioExclusionPattern> scenarioExclusionPatterns() { return this.innerProperties() == null ? null : this.innerProperties().scenarioExclusionPatterns(); } /** * Set the scenarioExclusionPatterns property: Configuration to exclude scenarios in fusion detection. * * @param scenarioExclusionPatterns the scenarioExclusionPatterns value to set. * @return the FusionAlertRule object itself. */ public FusionAlertRule withScenarioExclusionPatterns( List<FusionScenarioExclusionPattern> scenarioExclusionPatterns) { if (this.innerProperties() == null) { this.innerProperties = new FusionAlertRuleProperties(); } this.innerProperties().withScenarioExclusionPatterns(scenarioExclusionPatterns); return this; } /** * Get the lastModifiedUtc property: The last time that this alert has been modified. * * @return the lastModifiedUtc value. */ public OffsetDateTime lastModifiedUtc() { return this.innerProperties() == null ? null : this.innerProperties().lastModifiedUtc(); } /** * Get the severity property: The severity for alerts created by this alert rule. * * @return the severity value. */ public AlertSeverity severity() { return this.innerProperties() == null ? null : this.innerProperties().severity(); } /** * Get the tactics property: The tactics of the alert rule. * * @return the tactics value. */ public List<AttackTactic> tactics() { return this.innerProperties() == null ? null : this.innerProperties().tactics(); } /** * Get the techniques property: The techniques of the alert rule. * * @return the techniques value. */ public List<String> techniques() { return this.innerProperties() == null ? null : this.innerProperties().techniques(); } /** * Validates the instance. * * @throws IllegalArgumentException thrown if the instance is not valid. */ @Override public void validate() { super.validate(); if (innerProperties() != null) { innerProperties().validate(); } } }
package theDragonkin.cards.Dragonkin; import basemod.interfaces.CloneablePowerInterface; import com.megacrit.cardcrawl.actions.common.ApplyPowerAction; import com.megacrit.cardcrawl.characters.AbstractPlayer; import com.megacrit.cardcrawl.dungeons.AbstractDungeon; import com.megacrit.cardcrawl.monsters.AbstractMonster; import com.megacrit.cardcrawl.powers.AbstractPower; import theDragonkin.DragonkinMod; import theDragonkin.characters.TheDefault; import static theDragonkin.DragonkinMod.makeCardPath; public class Pandemic extends AbstractDragonkinCard { public static final String ID = DragonkinMod.makeID(Pandemic.class.getSimpleName()); public static final String IMG = makeCardPath("Pandemic.png"); private static final CardRarity RARITY = CardRarity.RARE; private static final CardTarget TARGET = CardTarget.ENEMY; private static final CardType TYPE = CardType.SKILL; public static final CardColor COLOR = TheDefault.Enums.Dragonkin_Red_COLOR; private static final int COST = 2; private static final int UPGRADED_COST = 1; private static final int POTENCY = 14; private static final int UPGRADE_PLUS_POTENCY = 0; private static final int MAGIC = 1; private static final int UPGRADE_MAGIC = 0; public Pandemic() { super(ID, IMG, COST, TYPE, COLOR, RARITY, TARGET); damage = baseDamage = POTENCY; baseMagicNumber = magicNumber = MAGIC; this.exhaust = true; } @Override public void use(AbstractPlayer p, AbstractMonster m) { for (AbstractPower po : m.powers){ if (po.type == AbstractPower.PowerType.DEBUFF) { if (po instanceof CloneablePowerInterface) { for (AbstractMonster mo : AbstractDungeon.getCurrRoom().monsters.monsters) { AbstractPower temp = ((CloneablePowerInterface)po).makeCopy(); temp.owner = mo; addToBot(new ApplyPowerAction(mo, p, temp)); } } } } } @Override public void upgrade() { if (!upgraded) { upgradeName(); upgradeBaseCost(UPGRADED_COST); initializeDescription(); } } }
package it.polimi.sr.rsp.csparql.syntax; import it.polimi.yasper.core.stream.web.WebStream; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.Setter; import org.apache.jena.graph.Node; /** * Created by Riccardo on 14/08/16. */ @AllArgsConstructor public class StreamNode implements WebStream { @Getter @Setter private Node iri; @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; StreamNode stream = (StreamNode) o; return iri != null ? iri.equals(stream.iri) : stream.iri == null; } @Override public int hashCode() { return iri != null ? iri.hashCode() : 0; } @Override public String getURI() { return iri.getURI(); } @Override public String toString() { return "StreamNode{" + "iri=" + iri + '}'; } }
package ltd.chuchen.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * @Author chuchen * @Date 2022/5/4 * @Description 操作日志注解 */ @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface OperationLogger { /** * 操作描述 */ String value() default ""; }
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ package com.microsoft.graph.requests.extensions; import com.microsoft.graph.http.IRequestBuilder; import com.microsoft.graph.core.ClientException; import com.microsoft.graph.concurrency.ICallback; import com.microsoft.graph.models.extensions.UnifiedRoleDefinition; import com.microsoft.graph.requests.extensions.IUnifiedRoleDefinitionCollectionRequestBuilder; import com.microsoft.graph.requests.extensions.IUnifiedRoleDefinitionRequestBuilder; import java.util.Arrays; import java.util.EnumSet; import com.microsoft.graph.models.extensions.UnifiedRoleDefinition; // **NOTE** This file was generated by a tool and any changes will be overwritten. /** * The interface for the Unified Role Definition Reference Request Builder. */ public interface IUnifiedRoleDefinitionReferenceRequestBuilder extends IRequestBuilder { /** * Creates the request * * @param requestOptions the options for this request * @return the IUnifiedRoleDefinitionReferenceRequest instance */ IUnifiedRoleDefinitionReferenceRequest buildRequest(final com.microsoft.graph.options.Option... requestOptions); /** * Creates the request with specific options instead of the existing options * * @param requestOptions the options for this request * @return the IUnifiedRoleDefinitionReferenceRequest instance */ IUnifiedRoleDefinitionReferenceRequest buildRequest(final java.util.List<? extends com.microsoft.graph.options.Option> requestOptions); }
package com.stripe.android.model.wallets; import android.os.Parcel; import android.os.Parcelable; import android.support.annotation.NonNull; import org.json.JSONObject; import java.util.HashMap; import java.util.Map; public final class SamsungPayWallet extends Wallet { private SamsungPayWallet(@NonNull Builder builder) { super(Type.SamsungPay, builder); } private SamsungPayWallet(@NonNull Parcel in) { super(in); } @NonNull @Override Map<String, Object> getWalletTypeMap() { return new HashMap<>(); } @NonNull @Override JSONObject getWalletTypeJson() { return new JSONObject(); } @NonNull static SamsungPayWallet.Builder fromJson(@NonNull JSONObject walletJson) { return new Builder(); } public static final class Builder extends Wallet.Builder<SamsungPayWallet> { @NonNull @Override SamsungPayWallet build() { return new SamsungPayWallet(this); } } public static final Parcelable.Creator<SamsungPayWallet> CREATOR = new Parcelable.Creator<SamsungPayWallet>() { @Override public SamsungPayWallet createFromParcel(@NonNull Parcel in) { return new SamsungPayWallet(in); } @Override public SamsungPayWallet[] newArray(int size) { return new SamsungPayWallet[size]; } }; }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hbase.client; import java.io.IOException; import org.apache.hadoop.classification.InterfaceAudience; import org.apache.hadoop.classification.InterfaceStability; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.CellScanner; import org.apache.hadoop.hbase.CoprocessorEnvironment; import org.apache.hadoop.hbase.ServerName; import org.apache.hadoop.hbase.client.HConnectionManager.HConnectionImplementation; import org.apache.hadoop.hbase.coprocessor.RegionCoprocessorEnvironment; import org.apache.hadoop.hbase.ipc.PayloadCarryingRpcController; import org.apache.hadoop.hbase.ipc.RpcServerInterface; import org.apache.hadoop.hbase.monitoring.MonitoredRPCHandler; import org.apache.hadoop.hbase.monitoring.TaskMonitor; import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.ClientService; import org.apache.hadoop.hbase.regionserver.HRegionServer; import org.apache.hadoop.hbase.regionserver.RegionServerServices; import org.apache.hadoop.hbase.security.UserProvider; import org.apache.hadoop.hbase.util.EnvironmentEdgeManager; import org.apache.hadoop.hbase.util.Pair; import com.google.protobuf.BlockingRpcChannel; import com.google.protobuf.BlockingService; import com.google.protobuf.Descriptors.MethodDescriptor; import com.google.protobuf.Message; import com.google.protobuf.RpcController; import com.google.protobuf.ServiceException; /** * Connection to an HTable from within a Coprocessor. We can do some nice tricks since we know we * are on a regionserver, for instance skipping the full serialization/deserialization of objects * when talking to the server. * <p> * You should not use this class from any client - its an internal class meant for use by the * coprocessor framework. */ @InterfaceAudience.Private @InterfaceStability.Evolving public class CoprocessorHConnection extends HConnectionImplementation { /** * Create an unmanaged {@link HConnection} based on the environment in which we are running the * coprocessor. The {@link HConnection} must be externally cleaned up (we bypass the usual HTable * cleanup mechanisms since we own everything). * @param env environment hosting the {@link HConnection} * @return an unmanaged {@link HConnection}. * @throws IOException if we cannot create the connection */ public static HConnection getConnectionForEnvironment(CoprocessorEnvironment env) throws IOException { // this bit is a little hacky - just trying to get it going for the moment if (env instanceof RegionCoprocessorEnvironment) { RegionCoprocessorEnvironment e = (RegionCoprocessorEnvironment) env; RegionServerServices services = e.getRegionServerServices(); if (services instanceof HRegionServer) { return new CoprocessorHConnection((HRegionServer) services); } } return HConnectionManager.createConnection(env.getConfiguration()); } private final ServerName serverName; private final HRegionServer server; /** * Legacy constructor * @param delegate * @param server * @throws IOException if we cannot create the connection * @deprecated delegate is not used */ @Deprecated public CoprocessorHConnection(HConnection delegate, HRegionServer server) throws IOException { this(server); } /** * Constructor that uses server configuration * @param server * @throws IOException if we cannot create the connection */ public CoprocessorHConnection(HRegionServer server) throws IOException { this(server.getConfiguration(), server); } /** * Constructor that accepts custom configuration * @param conf * @param server * @throws IOException if we cannot create the connection */ public CoprocessorHConnection(Configuration conf, HRegionServer server) throws IOException { super(conf, false, null, UserProvider.instantiate(conf).getCurrent()); this.server = server; this.serverName = server.getServerName(); } @Override public org.apache.hadoop.hbase.protobuf.generated.ClientProtos.ClientService.BlockingInterface getClient(ServerName serverName) throws IOException { // client is trying to reach off-server, so we can't do anything special if (!this.serverName.equals(serverName)) { return super.getClient(serverName); } // the client is attempting to write to the same regionserver, we can short-circuit to our // local regionserver final BlockingService blocking = ClientService.newReflectiveBlockingService(this.server); final RpcServerInterface rpc = this.server.getRpcServer(); final MonitoredRPCHandler status = TaskMonitor.get().createRPCStatus(Thread.currentThread() .getName()); status.pause("Setting up server-local call"); final long timestamp = EnvironmentEdgeManager.currentTimeMillis(); BlockingRpcChannel channel = new BlockingRpcChannel() { @Override public Message callBlockingMethod(MethodDescriptor method, RpcController controller, Message request, Message responsePrototype) throws ServiceException { try { Pair<Message, CellScanner> ret = rpc.call(blocking, method, request, null, timestamp, status); if (ret.getSecond() != null) { PayloadCarryingRpcController rpcc = (PayloadCarryingRpcController) controller; rpcc.setCellScanner(ret.getSecond()); } return ret.getFirst(); } catch (IOException e) { throw new ServiceException(e); } } }; return ClientService.newBlockingStub(channel); } }
package io.bdeploy.ui.api.impl; import java.util.Collections; import java.util.Map; import jakarta.inject.Inject; import jakarta.ws.rs.core.Context; import jakarta.ws.rs.core.UriInfo; import io.bdeploy.common.security.RemoteService; import io.bdeploy.common.util.VersionHelper; import io.bdeploy.interfaces.manifest.managed.ManagedMasterDto; import io.bdeploy.interfaces.minion.MinionStatusDto; import io.bdeploy.interfaces.remote.MasterRootResource; import io.bdeploy.interfaces.remote.MinionStatusResource; import io.bdeploy.interfaces.remote.ResourceProvider; import io.bdeploy.ui.api.BackendInfoResource; import io.bdeploy.ui.api.Minion; import io.bdeploy.ui.api.MinionMode; import io.bdeploy.ui.dto.BackendInfoDto; public class BackendInfoResourceImpl implements BackendInfoResource { @Inject private Minion minion; @Context private UriInfo info; @Override public BackendInfoDto getVersion() { return new BackendInfoDto(VersionHelper.getVersion(), minion.getMode()); } @Override public ManagedMasterDto getManagedMasterIdentification() { ManagedMasterDto dto = new ManagedMasterDto(); dto.hostName = minion.getHostName(); dto.auth = minion.getSelf().getAuthPack(); dto.uri = info.getBaseUri().toString(); dto.minions = minion.getMinions(); return dto; } @Override public Map<String, MinionStatusDto> getNodeStatus() { RemoteService remote = minion.getSelf(); // Central server does not have any nodes. Thus return self only if (minion.getMode() == MinionMode.CENTRAL) { String name = minion.getMinions().values().keySet().iterator().next(); MinionStatusResource status = ResourceProvider.getVersionedResource(remote, MinionStatusResource.class, null); return Collections.singletonMap(name, status.getStatus()); } // Delegate to the master to find out all nodes and their state MasterRootResource root = ResourceProvider.getVersionedResource(remote, MasterRootResource.class, null); return root.getMinions(); } }
/* Copyright 2017 Zutubi Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.zutubi.pulse.master.events; import com.zutubi.pulse.master.agent.Agent; /** * Raised when an agent should be pinged ASAP. */ public class AgentPingRequestedEvent extends AgentEvent { public AgentPingRequestedEvent(Object source, Agent agent) { super(source, agent); } public String toString() { return ("Agent Ping Requested Event: " + getAgent().getConfig().getName()); } }
package com.sequenceiq.cloudbreak.service; import javax.inject.Inject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import com.sequenceiq.cloudbreak.api.endpoint.v4.common.DetailedStackStatus; import com.sequenceiq.cloudbreak.api.endpoint.v4.common.Status; import com.sequenceiq.cloudbreak.cloud.model.CloudPlatformVariant; import com.sequenceiq.cloudbreak.cloud.store.InMemoryStateStore; import com.sequenceiq.cloudbreak.converter.scheduler.StatusToPollGroupConverter; import com.sequenceiq.cloudbreak.domain.SecurityConfig; import com.sequenceiq.cloudbreak.domain.stack.Stack; import com.sequenceiq.cloudbreak.domain.stack.StackStatus; import com.sequenceiq.cloudbreak.domain.stack.cluster.Cluster; import com.sequenceiq.cloudbreak.service.cluster.ClusterService; import com.sequenceiq.cloudbreak.service.securityconfig.SecurityConfigService; import com.sequenceiq.cloudbreak.service.stack.StackService; import com.sequenceiq.cloudbreak.util.UsageLoggingUtil; @Component public class StackUpdater { private static final Logger LOGGER = LoggerFactory.getLogger(StackUpdater.class); @Inject private StackService stackService; @Inject private StatusToPollGroupConverter statusToPollGroupConverter; @Inject private SecurityConfigService securityConfigService; @Inject private ClusterService clusterService; @Inject private UsageLoggingUtil usageLoggingUtil; public Stack updateStackStatus(Long stackId, DetailedStackStatus detailedStatus) { return doUpdateStackStatus(stackId, detailedStatus.getStatus(), detailedStatus, ""); } public Stack updateStackStatus(Long stackId, DetailedStackStatus detailedStatus, String statusReason) { return doUpdateStackStatus(stackId, detailedStatus.getStatus(), detailedStatus, statusReason); } public Stack updateStackStatusAndSetDetailedStatusToUnknown(Long stackId, Status status, String statusReason) { return doUpdateStackStatus(stackId, status, DetailedStackStatus.UNKNOWN, statusReason); } public void updateStackSecurityConfig(Stack stack, SecurityConfig securityConfig) { securityConfig = securityConfigService.save(securityConfig); stack.setSecurityConfig(securityConfig); stackService.save(stack); } public Stack updateClusterProxyRegisteredFlag(Stack stack, boolean registered) { stack.setClusterProxyRegistered(registered); return stackService.save(stack); } public Stack updateStackVersion(Long stackId, String stackVersion) { Stack stack = stackService.getByIdWithTransaction(stackId); stack.setStackVersion(stackVersion); return stackService.save(stack); } private Stack doUpdateStackStatus(Long stackId, Status newStatus, DetailedStackStatus newDetailedStatus, String statusReason) { Stack stack = stackService.getByIdWithTransaction(stackId); StackStatus actualStackStatus = stack.getStackStatus(); LOGGER.info("Update stack status from: {}/{} to: {}/{} stack: {} reason: {}", actualStackStatus.getStatus(), actualStackStatus.getDetailedStackStatus(), newStatus, newDetailedStatus, stackId, statusReason); if (actualStackStatus.getStatus().equals(newStatus)) { LOGGER.debug("New status is the same as previous status {}/{}, skip status update.", actualStackStatus.getStatus(), actualStackStatus.getDetailedStackStatus()); return stack; } else if (!stack.isDeleteCompleted()) { stack.setStackStatus(new StackStatus(stack, newStatus, statusReason, newDetailedStatus)); Cluster cluster = stack.getCluster(); if (newStatus.isRemovableStatus()) { InMemoryStateStore.deleteStack(stackId); if (cluster != null) { InMemoryStateStore.deleteCluster(cluster.getId()); } } else { InMemoryStateStore.putStack(stackId, statusToPollGroupConverter.convert(newStatus)); if (cluster != null) { InMemoryStateStore.putCluster(cluster.getId(), statusToPollGroupConverter.convert(newStatus)); } } stack = stackService.save(stack); saveDeprecatedClusterStatus(statusReason, stack, newStatus); usageLoggingUtil.logClusterStatusChangeUsageEvent(actualStackStatus.getStatus(), newStatus, cluster); } else { LOGGER.info("Stack is in DELETE_COMPLETED status, cannot update status."); } return stack; } public void updateVariant(Long resourceId, String variant) { CloudPlatformVariant stackVariant = stackService.getPlatformVariantByStackId(resourceId); if (!variant.equals(stackVariant.getVariant().value())) { Stack stack = stackService.get(resourceId); stack.setPlatformVariant(variant); stackService.save(stack); } else { LOGGER.info("The variant was already set to {}", variant); } } private void saveDeprecatedClusterStatus(String statusReason, Stack stack, Status newStatus) { Cluster cluster = stack.getCluster(); if (cluster != null) { Status previous = cluster.getStatus(); LOGGER.debug("Update deprecated cluster status from: {} to: {} reason: {} cluster: {}", previous, newStatus, statusReason, cluster.getId()); cluster.setStatus(newStatus); cluster.setStatusReason(statusReason); clusterService.save(cluster); } } }
/******************************************************************************* * Copyright (c) 2015-2018 Skymind, Inc. * * This program and the accompanying materials are made available under the * terms of the Apache License, Version 2.0 which is available at * https://www.apache.org/licenses/LICENSE-2.0. * * 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. * * SPDX-License-Identifier: Apache-2.0 ******************************************************************************/ package org.deeplearning4j.nn.conf.layers.recurrent; import lombok.*; import org.deeplearning4j.nn.api.ParamInitializer; import org.deeplearning4j.nn.conf.GradientNormalization; import org.deeplearning4j.nn.conf.InputPreProcessor; import org.deeplearning4j.nn.conf.NeuralNetConfiguration; import org.deeplearning4j.nn.conf.RNNFormat; import org.deeplearning4j.nn.conf.inputs.InputType; import org.deeplearning4j.nn.conf.layers.BaseRecurrentLayer; import org.deeplearning4j.nn.conf.layers.FeedForwardLayer; import org.deeplearning4j.nn.conf.layers.Layer; import org.deeplearning4j.nn.conf.layers.wrapper.BaseWrapperLayer; import org.deeplearning4j.nn.conf.memory.LayerMemoryReport; import org.deeplearning4j.nn.layers.recurrent.BidirectionalLayer; import org.deeplearning4j.nn.params.BidirectionalParamInitializer; import org.deeplearning4j.optimize.api.TrainingListener; import org.deeplearning4j.util.TimeSeriesUtils; import org.nd4j.linalg.api.buffer.DataType; import org.nd4j.linalg.api.ndarray.INDArray; import org.nd4j.linalg.learning.config.IUpdater; import org.nd4j.linalg.learning.regularization.Regularization; import org.nd4j.shade.jackson.annotation.JsonIgnoreProperties; import java.util.Collection; import java.util.List; import java.util.Map; import static org.nd4j.linalg.indexing.NDArrayIndex.interval; import static org.nd4j.linalg.indexing.NDArrayIndex.point; /** * Bidirectional is a "wrapper" layer: it wraps any uni-directional RNN layer to make it bidirectional.<br> Note that * multiple different modes are supported - these specify how the activations should be combined from the forward and * backward RNN networks. See {@link Mode} javadoc for more details.<br> Parameters are not shared here - there are 2 * separate copies of the wrapped RNN layer, each with separate parameters. * <br> * Usage: {@code .layer(new Bidirectional(new LSTM.Builder()....build())} * * @author Alex Black */ @NoArgsConstructor @Data @EqualsAndHashCode(callSuper = true, exclude = {"initializer"}) @JsonIgnoreProperties({"initializer"}) public class Bidirectional extends Layer { /** * This Mode enumeration defines how the activations for the forward and backward networks should be combined.<br> * ADD: out = forward + backward (elementwise addition)<br> MUL: out = forward * backward (elementwise * multiplication)<br> AVERAGE: out = 0.5 * (forward + backward)<br> CONCAT: Concatenate the activations.<br> Where * 'forward' is the activations for the forward RNN, and 'backward' is the activations for the backward RNN. In all * cases except CONCAT, the output activations size is the same size as the standard RNN that is being wrapped by * this layer. In the CONCAT case, the output activations size (dimension 1) is 2x larger than the standard RNN's * activations array. */ public enum Mode { ADD, MUL, AVERAGE, CONCAT } private Layer fwd; private Layer bwd; private Mode mode; private transient BidirectionalParamInitializer initializer; private Bidirectional(Bidirectional.Builder builder) { super(builder); } /** * Create a Bidirectional wrapper, with the default Mode (CONCAT) for the specified layer * * @param layer layer to wrap */ public Bidirectional(@NonNull Layer layer) { this(Mode.CONCAT, layer); } /** * Create a Bidirectional wrapper for the specified layer * * @param mode Mode to use to combine activations. See {@link Mode} for details * @param layer layer to wrap */ public Bidirectional(@NonNull Mode mode, @NonNull Layer layer) { if (!(layer instanceof BaseRecurrentLayer || layer instanceof LastTimeStep || layer instanceof BaseWrapperLayer)) { throw new IllegalArgumentException("Cannot wrap a non-recurrent layer: " + "config must extend BaseRecurrentLayer or LastTimeStep " + "Got class: " + layer.getClass()); } this.fwd = layer; this.bwd = layer.clone(); this.mode = mode; } public long getNOut() { if (this.fwd instanceof LastTimeStep) { return ((FeedForwardLayer) ((LastTimeStep) this.fwd).getUnderlying()).getNOut(); } else { return ((FeedForwardLayer) this.fwd).getNOut(); } } public long getNIn() { if (this.fwd instanceof LastTimeStep) { return ((FeedForwardLayer) ((LastTimeStep) this.fwd).getUnderlying()).getNIn(); } else { return ((FeedForwardLayer) this.fwd).getNIn(); } } public RNNFormat getRNNDataFormat(){ return TimeSeriesUtils.getFormatFromRnnLayer(fwd); } @Override public org.deeplearning4j.nn.api.Layer instantiate(NeuralNetConfiguration conf, Collection<TrainingListener> trainingListeners, int layerIndex, INDArray layerParamsView, boolean initializeParams, DataType networkDataType) { NeuralNetConfiguration c1 = conf.clone(); NeuralNetConfiguration c2 = conf.clone(); c1.setLayer(fwd); c2.setLayer(bwd); long n = layerParamsView.length() / 2; INDArray fp = layerParamsView.get(interval(0,0,true), interval(0, n)); INDArray bp = layerParamsView.get(interval(0,0,true), interval(n, 2 * n)); org.deeplearning4j.nn.api.Layer f = fwd.instantiate(c1, trainingListeners, layerIndex, fp, initializeParams, networkDataType); org.deeplearning4j.nn.api.Layer b = bwd.instantiate(c2, trainingListeners, layerIndex, bp, initializeParams, networkDataType); BidirectionalLayer ret = new BidirectionalLayer(conf, f, b, layerParamsView); Map<String, INDArray> paramTable = initializer().init(conf, layerParamsView, initializeParams); ret.setParamTable(paramTable); ret.setConf(conf); return ret; } @Override public ParamInitializer initializer() { if (initializer == null) { initializer = new BidirectionalParamInitializer(this); } return initializer; } @Override public InputType getOutputType(int layerIndex, InputType inputType) { InputType outOrig = fwd.getOutputType(layerIndex, inputType); if (fwd instanceof LastTimeStep) { InputType.InputTypeFeedForward ff = (InputType.InputTypeFeedForward) outOrig; if (mode == Mode.CONCAT) { return InputType.feedForward(2 * ff.getSize()); } else { return ff; } } else { InputType.InputTypeRecurrent r = (InputType.InputTypeRecurrent) outOrig; if (mode == Mode.CONCAT) { return InputType.recurrent(2 * r.getSize(), getRNNDataFormat()); } else { return r; } } } @Override public void setNIn(InputType inputType, boolean override) { fwd.setNIn(inputType, override); bwd.setNIn(inputType, override); } @Override public InputPreProcessor getPreProcessorForInputType(InputType inputType) { return fwd.getPreProcessorForInputType(inputType); } @Override public List<Regularization> getRegularizationByParam(String paramName){ //Strip forward/backward prefix from param name return fwd.getRegularizationByParam(paramName.substring(1)); } @Override public boolean isPretrainParam(String paramName) { return fwd.isPretrainParam(paramName.substring(1)); } /** * Get the updater for the given parameter. Typically the same updater will be used for all updaters, but this is * not necessarily the case * * @param paramName Parameter name * @return IUpdater for the parameter */ public IUpdater getUpdaterByParam(String paramName) { String sub = paramName.substring(1); return fwd.getUpdaterByParam(sub); } @Override public GradientNormalization getGradientNormalization() { return fwd.getGradientNormalization(); } @Override public double getGradientNormalizationThreshold() { return fwd.getGradientNormalizationThreshold(); } @Override public void setLayerName(String layerName) { this.layerName = layerName; fwd.setLayerName(layerName); bwd.setLayerName(layerName); } @Override public LayerMemoryReport getMemoryReport(InputType inputType) { LayerMemoryReport lmr = fwd.getMemoryReport(inputType); lmr.scale(2); //Double all memory use return lmr; } @AllArgsConstructor @Getter @Setter public static class Builder extends Layer.Builder<Bidirectional.Builder> { private Mode mode; private Layer layer; public void setLayer(Layer layer) { rnnLayer(layer); } public Builder mode(Mode mode) { this.setMode(mode); return this; } public Builder rnnLayer(Layer layer) { if (!(layer instanceof BaseRecurrentLayer || layer instanceof LastTimeStep || layer instanceof BaseWrapperLayer)) { throw new IllegalArgumentException("Cannot wrap a non-recurrent layer: " + "config must extend BaseRecurrentLayer or LastTimeStep " + "Got class: " + layer.getClass()); } this.setLayer(layer); return this; } @SuppressWarnings("unchecked") public Bidirectional build() { return new Bidirectional(this); } } }
package com.culabs.unicomportal.dao; import com.culabs.unicomportal.model.db.DBSystemProperties; public interface DBSystemPropertiesMapper { /** * This method was generated by MyBatis Generator. * This method corresponds to the database table system_properties * * @mbggenerated Tue May 26 15:53:09 CST 2015 */ int deleteByPrimaryKey(Integer id); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table system_properties * * @mbggenerated Tue May 26 15:53:09 CST 2015 */ int insert(DBSystemProperties record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table system_properties * * @mbggenerated Tue May 26 15:53:09 CST 2015 */ int insertSelective(DBSystemProperties record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table system_properties * * @mbggenerated Tue May 26 15:53:09 CST 2015 */ DBSystemProperties selectByPrimaryKey(Integer id); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table system_properties * * @mbggenerated Tue May 26 15:53:09 CST 2015 */ int updateByPrimaryKeySelective(DBSystemProperties record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table system_properties * * @mbggenerated Tue May 26 15:53:09 CST 2015 */ int updateByPrimaryKey(DBSystemProperties record); }
package uk.gov.justice.digital.ndh.api.nomis; import lombok.Builder; import lombok.Value; import java.time.LocalDate; import java.util.List; @Value @Builder public class Offender { private String nomsId; private Long offenderId; private String firstName; private String middleNames; private String surname; private LocalDate dateOfBirth; private KeyValue gender; private KeyValue ethnicity; private List<OffenderAlias> aliases; private List<Booking> bookings; private List<Identifier> identifiers; }
package org.tron.core.zen; import org.tron.core.exception.CipherException; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import java.io.*; import java.nio.charset.Charset; import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class ZenUtils { public static List<String> getListFromFile(final String fileName ) { List<String> list = new ArrayList<>(); try { FileInputStream inputStream = new FileInputStream(fileName); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); String str = null; while((str = bufferedReader.readLine()) != null) { // System.out.println(str); list.add(str); } inputStream.close(); bufferedReader.close(); } catch (Exception e) { if (e.getMessage() != null) { System.out.println(e.getMessage()); } else { System.out.println(e.getClass()); } } return list; } public static boolean appendToFileTail(final String fileName, final String content) { BufferedWriter out = null; try { out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName, true))); out.write(content+"\n"); out.flush(); } catch (Exception e) { e.printStackTrace(); } finally { try { out.close(); } catch (IOException e) { e.printStackTrace(); } } return true; } public static void clearFile(String fileName) { File file = new File(fileName); try { if (file.exists()) { FileWriter fileWriter = new FileWriter(file); fileWriter.write(""); fileWriter.flush(); fileWriter.close(); } } catch (Exception e) { e.printStackTrace(); } } public static void checkFolderExist(final String filePath) { try { File file = new File(filePath); if (file.exists()) { if (file.isDirectory()) { return; } else { file.delete(); } } file.mkdir(); } catch (Exception e) { e.printStackTrace(); } } public static void checkFoldersExist(final String filePath) { try { File file = new File(filePath); if (file.exists()) { if (file.isDirectory()) { return; } else { file.delete(); } } file.mkdirs(); } catch (Exception e) { e.printStackTrace(); } } public static boolean checkFileExist(final String filePath) { try { File file = new File(filePath); if (file.exists() && !file.isDirectory()) { return true; } else { return false; } } catch (Exception e) { e.printStackTrace(); } return false; } public static String getMemo(byte[] memo) { int index = memo.length; for (; index>0; --index) { if (memo[index-1] != 0) break; } byte[] inputCheck = new byte[index]; System.arraycopy(memo, 0, inputCheck, 0, index); return new String(inputCheck, Charset.forName("UTF-8")); } public static byte[] aesCtrEncrypt(byte[] text, byte[] encryptKey) throws CipherException { try { byte[] iv = new byte[16]; new SecureRandom().nextBytes(iv); IvParameterSpec ivParameterSpec = new IvParameterSpec(iv); Cipher cipher = Cipher.getInstance("AES/CTR/NoPadding"); SecretKeySpec secretKeySpec = new SecretKeySpec(encryptKey, "AES"); cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec); byte[] cipherText = cipher.doFinal(text); byte[] result = new byte[cipherText.length + iv.length]; System.arraycopy(iv, 0, result, 0, iv.length); System.arraycopy(cipherText, 0, result, iv.length, cipherText.length); return result; } catch (NoSuchPaddingException | NoSuchAlgorithmException | InvalidAlgorithmParameterException | InvalidKeyException | BadPaddingException | IllegalBlockSizeException e) { throw new CipherException("Error performing cipher operation", e); } } public static byte[] aesCtrDecrypt(byte[] cipherText, byte[] encryptKey) throws CipherException { try { byte[] iv = Arrays.copyOfRange(cipherText, 0, 16); cipherText = Arrays.copyOfRange(cipherText, iv.length, cipherText.length); IvParameterSpec ivParameterSpec = new IvParameterSpec(iv); Cipher cipher = Cipher.getInstance("AES/CTR/NoPadding"); SecretKeySpec secretKeySpec = new SecretKeySpec(encryptKey, "AES"); cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec); return cipher.doFinal(cipherText); } catch (NoSuchPaddingException | NoSuchAlgorithmException | InvalidAlgorithmParameterException | InvalidKeyException | BadPaddingException | IllegalBlockSizeException e) { throw new CipherException("Error performing cipher operation", e); } } }
package controllers.learn.numberlearner; import controllers.LanguageController; import play.mvc.Controller; import play.mvc.Result; import play.twirl.api.Html; import views.html.numberlearn.numberlearnview; public class NumberLearn extends Controller { public static Result get() { Html content = numberlearnview.render(LanguageController.getLanguage()); return ok(content); } }
/* * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH under * one or more contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright ownership. * Licensed under the Zeebe Community License 1.0. You may not use this file * except in compliance with the Zeebe Community License 1.0. */ package io.zeebe.distributedlog.restore.log.impl; import io.zeebe.distributedlog.restore.log.LogReplicationResponse; import io.zeebe.util.buffer.BufferUtil; import org.agrona.DirectBuffer; import org.agrona.concurrent.UnsafeBuffer; public class DefaultLogReplicationResponse implements LogReplicationResponse { private long toPosition; private boolean moreAvailable; private byte[] serializedEvents; public DefaultLogReplicationResponse() {} public DefaultLogReplicationResponse( long toPosition, boolean moreAvailable, byte[] serializedEvents) { this.toPosition = toPosition; this.moreAvailable = moreAvailable; this.serializedEvents = serializedEvents; } @Override public long getToPosition() { return toPosition; } public void setToPosition(long toPosition) { this.toPosition = toPosition; } @Override public boolean hasMoreAvailable() { return moreAvailable; } @Override public byte[] getSerializedEvents() { return serializedEvents; } public void setSerializedEvents(byte[] serializedEvents) { this.serializedEvents = serializedEvents; } public void setMoreAvailable(boolean moreAvailable) { this.moreAvailable = moreAvailable; } public void setSerializedEvents(DirectBuffer buffer, int offset, int length) { final DirectBuffer wrapper = new UnsafeBuffer(buffer, offset, length); this.serializedEvents = BufferUtil.bufferAsArray(wrapper); } @Override public String toString() { return "DefaultLogReplicationResponse{" + "toPosition=" + toPosition + ", moreAvailable=" + moreAvailable + ", serializedEvents.length=" + (serializedEvents == null ? 0 : serializedEvents.length) + '}'; } }
/* * Copyright 2012 Google 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 de.dennisguse.opentracks.util; import android.annotation.SuppressLint; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.content.res.TypedArray; import android.net.Uri; import android.util.Log; import androidx.annotation.VisibleForTesting; import androidx.documentfile.provider.DocumentFile; import androidx.preference.PreferenceManager; import java.time.Duration; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import de.dennisguse.opentracks.R; import de.dennisguse.opentracks.content.data.DataField; import de.dennisguse.opentracks.content.data.Distance; import de.dennisguse.opentracks.content.data.Layout; import de.dennisguse.opentracks.io.file.TrackFileFormat; /** * Utilities to access preferences stored in {@link SharedPreferences}. * * @author Jimmy Shih */ public class PreferencesUtils { private final static String TAG = PreferencesUtils.class.getSimpleName(); private PreferencesUtils() { } @Deprecated //Should only be used to get a sharedPreference for more than one interaction! public static SharedPreferences getSharedPreferences(Context context) { SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context); PreferencesOpenHelper.newInstance(context, sharedPreferences).checkForUpgrade(); return sharedPreferences; } public static String getDefaultActivity(SharedPreferences sharedPreferences, Context context) { return getString(sharedPreferences, context, R.string.default_activity_key, context.getString(R.string.default_activity_default)); } public static void setDefaultActivity(SharedPreferences sharedPreferences, Context context, String newDefaultActivity) { setString(sharedPreferences, context, R.string.default_activity_key, newDefaultActivity); } /** * Gets a preference key * * @param context the context * @param keyId the key id */ private static String getKey(Context context, int keyId) { return context.getString(keyId); } /** * Compares if keyId and key belong to the same shared preference key. * * @param keyId The resource id of the key * @param key The key of the preference * @return true if key == null or key belongs to keyId */ public static boolean isKey(Context context, int keyId, String key) { return key == null || key.equals(getKey(context, keyId)); } public static boolean isKey(Context context, int[] keyIds, String key) { for(int keyId : keyIds) { if (isKey(context, keyId, key)) { return true; } } return false; } private static boolean getBoolean(SharedPreferences sharedPreferences, Context context, int keyId, boolean defaultValue) { return sharedPreferences.getBoolean(getKey(context, keyId), defaultValue); } static int getInt(SharedPreferences sharedPreferences, Context context, int keyId, int defaultValue) { try { return sharedPreferences.getInt(getKey(context, keyId), defaultValue); } catch (ClassCastException e) { //Ignore } //NOTE: We assume that the data was stored as String due to use of ListPreference. try { String stringValue = sharedPreferences.getString(getKey(context, keyId), null); return Integer.parseInt(stringValue); } catch (NumberFormatException e) { return defaultValue; } } private static float getFloat(SharedPreferences sharedPreferences, Context context, int keyId, float defaultValue) { try { return sharedPreferences.getFloat(getKey(context, keyId), defaultValue); } catch (ClassCastException e) { //Ignore } //NOTE: We assume that the data was stored as String due to use of ListPreference. try { String stringValue = sharedPreferences.getString(getKey(context, keyId), null); return Float.parseFloat(stringValue); } catch (NumberFormatException e) { return defaultValue; } } public static String getString(SharedPreferences sharedPreferences, Context context, int keyId, String defaultValue) { return sharedPreferences.getString(getKey(context, keyId), defaultValue); } @VisibleForTesting public static void setString(SharedPreferences sharedPreferences, Context context, int keyId, String value) { Editor editor = sharedPreferences.edit(); editor.putString(getKey(context, keyId), value); editor.apply(); } static void setInt(SharedPreferences sharedPreferences, Context context, int keyId, int value) { Editor editor = sharedPreferences.edit(); editor.putInt(getKey(context, keyId), value); editor.apply(); } public static boolean isMetricUnits(SharedPreferences sharedPreferences, Context context) { final String STATS_UNIT = context.getString(R.string.stats_units_default); return STATS_UNIT.equals(getString(sharedPreferences, context, R.string.stats_units_key, STATS_UNIT)); } public static void setMetricUnits(SharedPreferences sharedPreferences, Context context, boolean metricUnits) { String unit; if (metricUnits) { unit = context.getString(R.string.stats_units_metric); } else { unit = context.getString(R.string.stats_units_imperial); } setString(sharedPreferences, context, R.string.stats_units_key, unit); } public static boolean isReportSpeed(SharedPreferences sharedPreferences, Context context, String category) { final String STATS_RATE_DEFAULT = context.getString(R.string.stats_rate_default); String currentStatsRate = getString(sharedPreferences, context, R.string.stats_rate_key, STATS_RATE_DEFAULT); if (currentStatsRate.equals(getString(sharedPreferences, context, R.string.stats_rate_speed_or_pace_default, STATS_RATE_DEFAULT))) { return TrackIconUtils.isSpeedIcon(context, category); } return currentStatsRate.equals(context.getString(R.string.stats_rate_speed)); } private static String getBluetoothSensorAddressNone(Context context) { return context.getString(R.string.sensor_type_value_none); } public static boolean isBluetoothSensorAddressNone(Context context, String currentValue) { return getBluetoothSensorAddressNone(context).equals(currentValue); } public static String getBluetoothHeartRateSensorAddress(SharedPreferences sharedPreferences, Context context) { return getString(sharedPreferences, context, R.string.settings_sensor_bluetooth_heart_rate_key, getBluetoothSensorAddressNone(context)); } public static String getBluetoothCyclingCadenceSensorAddress(SharedPreferences sharedPreferences, Context context) { return getString(sharedPreferences, context, R.string.settings_sensor_bluetooth_cycling_cadence_key, getBluetoothSensorAddressNone(context)); } public static String getBluetoothCyclingSpeedSensorAddress(SharedPreferences sharedPreferences, Context context) { return getString(sharedPreferences, context, R.string.settings_sensor_bluetooth_cycling_speed_key, getBluetoothSensorAddressNone(context)); } public static Distance getWheelCircumference(SharedPreferences sharedPreferences, Context context) { final int DEFAULT = Integer.parseInt(context.getResources().getString(R.string.settings_sensor_bluetooth_cycling_speed_wheel_circumference_default)); return Distance.ofMM(getInt(sharedPreferences, context, R.string.settings_sensor_bluetooth_cycling_speed_wheel_circumference_key, DEFAULT)); } public static String getBluetoothCyclingPowerSensorAddress(SharedPreferences sharedPreferences, Context context) { return getString(sharedPreferences, context, R.string.settings_sensor_bluetooth_cycling_power_key, getBluetoothSensorAddressNone(context)); } public static String getBluetoothRunningSpeedAndCadenceAddress(SharedPreferences sharedPreferences, Context context) { return getString(sharedPreferences, context, R.string.settings_sensor_bluetooth_running_speed_and_cadence_key, getBluetoothSensorAddressNone(context)); } public static boolean shouldShowStatsOnLockscreen(SharedPreferences sharedPreferences, Context context) { final boolean STATS_SHOW_ON_LOCKSCREEN_DEFAULT = context.getResources().getBoolean(R.bool.stats_show_on_lockscreen_while_recording_default); return getBoolean(sharedPreferences, context, R.string.stats_show_on_lockscreen_while_recording_key, STATS_SHOW_ON_LOCKSCREEN_DEFAULT); } public static boolean shouldKeepScreenOn(SharedPreferences sharedPreferences, Context context) { final boolean DEFAULT = context.getResources().getBoolean(R.bool.stats_keep_screen_on_while_recording_default); return getBoolean(sharedPreferences, context, R.string.stats_keep_screen_on_while_recording_key, DEFAULT); } public static boolean shouldUseFullscreen(SharedPreferences sharedPreferences, Context context) { final boolean DEFAULT = context.getResources().getBoolean(R.bool.stats_fullscreen_while_recording_default); return getBoolean(sharedPreferences, context, R.string.stats_fullscreen_while_recording_key, DEFAULT); } public static Duration getVoiceAnnouncementFrequency(SharedPreferences sharedPreferences, Context context) { final int DEFAULT = Integer.parseInt(context.getResources().getString(R.string.voice_announcement_frequency_default)); int value = getInt(sharedPreferences, context, R.string.voice_announcement_frequency_key, DEFAULT); return Duration.ofSeconds(value); } /** * @return Result depends on isMetricUnits */ public static Distance getVoiceAnnouncementDistance(SharedPreferences sharedPreferences, Context context) { final float DEFAULT = Integer.parseInt(context.getResources().getString(R.string.voice_announcement_distance_default)); float value = getFloat(sharedPreferences, context, R.string.voice_announcement_distance_key, DEFAULT); return Distance.one(isMetricUnits(sharedPreferences, context)).multipliedBy(value); } public static float getVoiceSpeedRate(SharedPreferences sharedPreferences, Context context) { final float DEFAULT = Float.parseFloat(context.getResources().getString(R.string.voice_speed_rate_default)); return getFloat(sharedPreferences, context, R.string.voice_speed_rate_key, DEFAULT); } public static Distance getRecordingDistanceInterval(SharedPreferences sharedPreferences, Context context) { return Distance.of(getInt(sharedPreferences, context, R.string.recording_distance_interval_key, getRecordingDistanceIntervalDefaultInternal(context))); } public static Distance getRecordingDistanceIntervalDefault(Context context) { return Distance.of(getRecordingDistanceIntervalDefaultInternal(context)); } private static int getRecordingDistanceIntervalDefaultInternal(Context context) { return Integer.parseInt(context.getResources().getString(R.string.recording_distance_interval_default)); } public static Distance getMaxRecordingDistance(SharedPreferences sharedPreferences, Context context) { final int MAX_RECORDING_DISTANCE = Integer.parseInt(context.getResources().getString(R.string.max_recording_distance_default)); return Distance.of(getInt(sharedPreferences, context, R.string.max_recording_distance_key, MAX_RECORDING_DISTANCE)); } public static Duration getMinRecordingInterval(SharedPreferences sharedPreferences, Context context) { final Duration MIN_RECORDING_INTERVAL = getMinRecordingIntervalDefault(context); Duration interval = Duration.ofSeconds(getInt(sharedPreferences, context, R.string.min_recording_interval_key, (int) MIN_RECORDING_INTERVAL.getSeconds())); if (interval.isNegative()) { // Due to removal of adaptive listener policy; used -1, and -2 interval = getMinRecordingIntervalDefault(context); } return interval; } public static Duration getMinRecordingIntervalDefault(Context context) { return Duration.ofSeconds(Integer.parseInt(context.getResources().getString(R.string.min_recording_interval_default))); } public static Distance getThresholdHorizontalAccuracy(SharedPreferences sharedPreferences, Context context) { final int RECORDING_GPS_ACCURACY = Integer.parseInt(context.getResources().getString(R.string.recording_gps_accuracy_default)); return Distance.of(getInt(sharedPreferences, context, R.string.recording_gps_accuracy_key, RECORDING_GPS_ACCURACY)); } public static boolean shouldInstantExportAfterWorkout(SharedPreferences sharedPreferences, Context context) { final boolean INSTANT_POST_WORKOUT_EXPORT_DEFAULT = context.getResources().getBoolean(R.bool.post_workout_export_enabled_default); return getBoolean(sharedPreferences, context, R.string.post_workout_export_enabled_key, INSTANT_POST_WORKOUT_EXPORT_DEFAULT) && isDefaultExportDirectoryUri(sharedPreferences, context); } public static TrackFileFormat getExportTrackFileFormat(SharedPreferences sharedPreferences, Context context) { final String TRACKFILEFORMAT_NAME_DEFAULT = getString(sharedPreferences, context, R.string.export_trackfileformat_default, null); String trackFileFormatName = getString(sharedPreferences, context, R.string.export_trackfileformat_key, TRACKFILEFORMAT_NAME_DEFAULT); try { return TrackFileFormat.valueOf(trackFileFormatName); } catch (Exception e) { return TrackFileFormat.KMZ_WITH_TRACKDETAIL_AND_SENSORDATA; } } public static boolean getPreventReimportTracks(SharedPreferences sharedPreferences, Context context) { final boolean defaultValue = getBoolean(sharedPreferences, context, R.bool.import_prevent_reimport_default, false); return getBoolean(sharedPreferences, context, R.string.import_prevent_reimport_key, defaultValue); } /** * @return {@link androidx.appcompat.app.AppCompatDelegate}.MODE_* */ public static int getDefaultNightMode(SharedPreferences sharedPreferences, Context context) { final String defaultValue = getKey(context, R.string.night_mode_default); final String value = getString(sharedPreferences, context, R.string.night_mode_key, defaultValue); return Integer.parseInt(value); } public static SharedPreferences resetPreferences(Context context, boolean readAgain) { SharedPreferences sharedPreferences = getSharedPreferences(context); if (readAgain) { // We want to really clear settings now. sharedPreferences.edit().clear().commit(); } PreferenceManager.setDefaultValues(context, R.xml.settings, readAgain); return sharedPreferences; } public static DocumentFile getDefaultExportDirectoryUri(SharedPreferences sharedPreferences, Context context) { String singleExportDirectorySettingsKey = getString(sharedPreferences, context, R.string.settings_default_export_directory_key, null); if (singleExportDirectorySettingsKey == null) { return null; } try { return DocumentFile.fromTreeUri(context, Uri.parse(singleExportDirectorySettingsKey)); } catch (Exception e) { Log.w(TAG, "Could not decode default export directory: " + e.getMessage()); } return null; } public static void setDefaultExportDirectoryUri(SharedPreferences sharedPreferences, Context context, Uri directoryUri) { String value = directoryUri != null ? directoryUri.toString() : null; setString(sharedPreferences, context, R.string.settings_default_export_directory_key, value); } public static boolean isDefaultExportDirectoryUri(SharedPreferences sharedPreferences, Context context) { return getDefaultExportDirectoryUri(sharedPreferences, context) != null; } public static int getLayoutColumns(SharedPreferences sharedPreferences, Context context) { return getInt(sharedPreferences, context, R.string.stats_custom_layout_columns_key, context.getResources().getInteger(R.integer.stats_custom_layout_columns_default)); } public static void setLayoutColumns(SharedPreferences sharedPreferences, Context context, int columns) { setInt(sharedPreferences, context, R.string.stats_custom_layout_columns_key, columns); } private static List<TypedArray> getMultiTypedArray(Context context, String key) { List<TypedArray> typedArrays = new ArrayList<>(); try { Class<R.array> resource = R.array.class; Field field; int i = 0; do { field = resource.getField(key + context.getString(R.string.stats_custom_layout_fields_default_value_separator) + i); typedArrays.add(context.getResources().obtainTypedArray(field.getInt(null))); i++; } while (field != null); } catch (Exception e) { e.printStackTrace(); Log.e(TAG, e.getMessage()); } return typedArrays; } @SuppressLint("ResourceType") static String buildDefaultLayout(Context context) { List<TypedArray> fieldsArrays = getMultiTypedArray(context, "stats_custom_layout_fields_default_value"); return context.getString(R.string.default_activity_default) + CsvConstants.LINE_SEPARATOR + fieldsArrays.stream().map(i -> i.getString(0) + CsvConstants.ITEM_SEPARATOR + i.getString(1)).collect(Collectors.joining(CsvConstants.LINE_SEPARATOR)) + CsvConstants.LINE_SEPARATOR; } public static Layout getCustomLayout(SharedPreferences sharedPreferences, Context context) { String csvCustomLayout = getString(sharedPreferences, context, R.string.stats_custom_layout_fields_key, buildDefaultLayout(context)); List<String> csvParts = Arrays.asList(csvCustomLayout.split(CsvConstants.LINE_SEPARATOR)); Layout layout = new Layout(csvParts.get(0)); for (int i = 1; i < csvParts.size(); i++) { String[] fieldParts = csvParts.get(i).split(CsvConstants.ITEM_SEPARATOR); layout.addField(fieldParts[0], DataField.getTitleByKey(context, fieldParts[0]), fieldParts[1].equals(DataField.YES_VALUE), fieldParts[2].equals(DataField.YES_VALUE), fieldParts[0].equals(context.getString(R.string.stats_custom_layout_coordinates_key))); } return layout; } public static void setCustomLayout(SharedPreferences sharedPreferences, Context context, Layout layout) { List<DataField> fields = layout.getFields(); if (fields.isEmpty()) { return; } String csv = layout.getProfile() + CsvConstants.LINE_SEPARATOR + fields.stream().map(DataField::toCsv).collect(Collectors.joining(CsvConstants.LINE_SEPARATOR)) + CsvConstants.LINE_SEPARATOR; setString(sharedPreferences, context, R.string.stats_custom_layout_fields_key, csv); } public static void resetCustomLayoutPreferences(Context context) { SharedPreferences settings = getSharedPreferences(context); if (settings.contains(context.getString(R.string.stats_custom_layout_fields_key))) { SharedPreferences.Editor editor = settings.edit(); editor.remove(context.getString(R.string.stats_custom_layout_fields_key)); editor.commit(); } if (settings.contains(context.getString(R.string.stats_custom_layout_columns_key))) { SharedPreferences.Editor editor = settings.edit(); editor.remove(context.getString(R.string.stats_custom_layout_columns_key)); editor.commit(); } } }
package cvv.udacity.popularmovies; import android.app.Application; import com.raizlabs.android.dbflow.config.FlowConfig; import com.raizlabs.android.dbflow.config.FlowManager; /** * Created by Caro Vaquero * Date: 26.06.2016 * Project: PopularMovies */ public class PopularMoviesApplication extends Application { @Override public void onCreate() { super.onCreate(); FlowManager.init(new FlowConfig.Builder(getApplicationContext()) .openDatabasesOnInit(true) .build()); } }
package mage.cards.r; import mage.MageInt; import mage.abilities.Ability; import mage.abilities.common.SimpleStaticAbility; import mage.abilities.effects.common.cost.CostModificationEffectImpl; import mage.abilities.keyword.FlyingAbility; import mage.abilities.keyword.ForetellAbility; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.*; import mage.game.Game; import java.util.UUID; import mage.abilities.TriggeredAbilityImpl; import mage.abilities.costs.mana.ManaCostsImpl; import mage.abilities.effects.Effect; import mage.abilities.effects.common.CreateTokenEffect; import mage.abilities.keyword.VigilanceAbility; import mage.cards.Card; import mage.game.events.GameEvent; import mage.game.events.ZoneChangeGroupEvent; import mage.game.permanent.token.SpiritWhiteToken; import mage.watchers.common.ForetoldWatcher; /** * @author jeffwadsworth */ public final class RanarTheEverWatchful extends CardImpl { public RanarTheEverWatchful(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{2}{W}{U}"); this.addSuperType(SuperType.LEGENDARY); this.subtype.add(SubType.SPIRIT); this.subtype.add(SubType.WARRIOR); this.power = new MageInt(2); this.toughness = new MageInt(3); // Flying this.addAbility(FlyingAbility.getInstance()); // Vigilance this.addAbility(VigilanceAbility.getInstance()); // The first card you foretell each turn costs 0 to foretell Ability ability = new SimpleStaticAbility(new RanarTheEverWatchfulCostReductionEffect()); this.addAbility(ability); // Whenever you exile one or more cards from your hand and/or permanents from the battlefield, create a 1/1 white Spirit creature token with flying. this.addAbility(new RanarTheEverWatchfulTriggeredAbility(new CreateTokenEffect(new SpiritWhiteToken()))); } private RanarTheEverWatchful(final RanarTheEverWatchful card) { super(card); } @Override public RanarTheEverWatchful copy() { return new RanarTheEverWatchful(this); } } class RanarTheEverWatchfulCostReductionEffect extends CostModificationEffectImpl { RanarTheEverWatchfulCostReductionEffect() { super(Duration.WhileOnBattlefield, Outcome.Neutral, CostModificationType.REDUCE_COST); staticText = "The first card you foretell each turn costs {0} to foretell"; } private RanarTheEverWatchfulCostReductionEffect(RanarTheEverWatchfulCostReductionEffect effect) { super(effect); } @Override public RanarTheEverWatchfulCostReductionEffect copy() { return new RanarTheEverWatchfulCostReductionEffect(this); } @Override public boolean apply(Game game, Ability source, Ability abilityToModify) { abilityToModify.getManaCostsToPay().clear(); abilityToModify.getManaCostsToPay().addAll(new ManaCostsImpl<>("{0}")); return true; } @Override public boolean applies(Ability abilityToModify, Ability source, Game game) { ForetoldWatcher watcher = game.getState().getWatcher(ForetoldWatcher.class); return (watcher != null && watcher.countNumberForetellThisTurn() == 0 && abilityToModify.isControlledBy(source.getControllerId()) && abilityToModify instanceof ForetellAbility); } } class RanarTheEverWatchfulTriggeredAbility extends TriggeredAbilityImpl { RanarTheEverWatchfulTriggeredAbility(Effect effect) { super(Zone.BATTLEFIELD, effect, false); } RanarTheEverWatchfulTriggeredAbility(final RanarTheEverWatchfulTriggeredAbility ability) { super(ability); } @Override public RanarTheEverWatchfulTriggeredAbility copy() { return new RanarTheEverWatchfulTriggeredAbility(this); } @Override public boolean checkEventType(GameEvent event, Game game) { return event.getType() == GameEvent.EventType.ZONE_CHANGE_GROUP; } @Override public boolean checkTrigger(GameEvent event, Game game) { ZoneChangeGroupEvent zEvent = (ZoneChangeGroupEvent) event; if (zEvent != null && Zone.HAND == zEvent.getFromZone() && Zone.EXILED == zEvent.getToZone() && zEvent.getPlayerId() == controllerId && zEvent.getCards() != null) { for (Card card : zEvent.getCards()) { if (card != null) { UUID cardOwnerId = card.getOwnerId(); if (cardOwnerId != null && card.isOwnedBy(getControllerId())) { return true; } } } } if (zEvent != null && Zone.BATTLEFIELD == zEvent.getFromZone() && Zone.EXILED == zEvent.getToZone() && zEvent.getPlayerId() == controllerId && zEvent.getCards() != null) { return true; } return false; } @Override public String getRule() { return "Whenever you exile one or more cards from your hand and/or permanents from the battlefield, " + super.getRule(); } }
/* * Copyright 2013-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.storagegateway.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.protocol.StructuredPojo; import com.amazonaws.protocol.ProtocolMarshaller; /** * <p> * Describes a file share. * </p> * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/storagegateway-2013-06-30/FileShareInfo" target="_top">AWS API * Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class FileShareInfo implements Serializable, Cloneable, StructuredPojo { private String fileShareARN; private String fileShareId; private String fileShareStatus; private String gatewayARN; /** * @param fileShareARN */ public void setFileShareARN(String fileShareARN) { this.fileShareARN = fileShareARN; } /** * @return */ public String getFileShareARN() { return this.fileShareARN; } /** * @param fileShareARN * @return Returns a reference to this object so that method calls can be chained together. */ public FileShareInfo withFileShareARN(String fileShareARN) { setFileShareARN(fileShareARN); return this; } /** * @param fileShareId */ public void setFileShareId(String fileShareId) { this.fileShareId = fileShareId; } /** * @return */ public String getFileShareId() { return this.fileShareId; } /** * @param fileShareId * @return Returns a reference to this object so that method calls can be chained together. */ public FileShareInfo withFileShareId(String fileShareId) { setFileShareId(fileShareId); return this; } /** * @param fileShareStatus */ public void setFileShareStatus(String fileShareStatus) { this.fileShareStatus = fileShareStatus; } /** * @return */ public String getFileShareStatus() { return this.fileShareStatus; } /** * @param fileShareStatus * @return Returns a reference to this object so that method calls can be chained together. */ public FileShareInfo withFileShareStatus(String fileShareStatus) { setFileShareStatus(fileShareStatus); return this; } /** * @param gatewayARN */ public void setGatewayARN(String gatewayARN) { this.gatewayARN = gatewayARN; } /** * @return */ public String getGatewayARN() { return this.gatewayARN; } /** * @param gatewayARN * @return Returns a reference to this object so that method calls can be chained together. */ public FileShareInfo withGatewayARN(String gatewayARN) { setGatewayARN(gatewayARN); return this; } /** * Returns a string representation of this object; useful for testing and debugging. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getFileShareARN() != null) sb.append("FileShareARN: ").append(getFileShareARN()).append(","); if (getFileShareId() != null) sb.append("FileShareId: ").append(getFileShareId()).append(","); if (getFileShareStatus() != null) sb.append("FileShareStatus: ").append(getFileShareStatus()).append(","); if (getGatewayARN() != null) sb.append("GatewayARN: ").append(getGatewayARN()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof FileShareInfo == false) return false; FileShareInfo other = (FileShareInfo) obj; if (other.getFileShareARN() == null ^ this.getFileShareARN() == null) return false; if (other.getFileShareARN() != null && other.getFileShareARN().equals(this.getFileShareARN()) == false) return false; if (other.getFileShareId() == null ^ this.getFileShareId() == null) return false; if (other.getFileShareId() != null && other.getFileShareId().equals(this.getFileShareId()) == false) return false; if (other.getFileShareStatus() == null ^ this.getFileShareStatus() == null) return false; if (other.getFileShareStatus() != null && other.getFileShareStatus().equals(this.getFileShareStatus()) == false) return false; if (other.getGatewayARN() == null ^ this.getGatewayARN() == null) return false; if (other.getGatewayARN() != null && other.getGatewayARN().equals(this.getGatewayARN()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getFileShareARN() == null) ? 0 : getFileShareARN().hashCode()); hashCode = prime * hashCode + ((getFileShareId() == null) ? 0 : getFileShareId().hashCode()); hashCode = prime * hashCode + ((getFileShareStatus() == null) ? 0 : getFileShareStatus().hashCode()); hashCode = prime * hashCode + ((getGatewayARN() == null) ? 0 : getGatewayARN().hashCode()); return hashCode; } @Override public FileShareInfo clone() { try { return (FileShareInfo) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } @com.amazonaws.annotation.SdkInternalApi @Override public void marshall(ProtocolMarshaller protocolMarshaller) { com.amazonaws.services.storagegateway.model.transform.FileShareInfoMarshaller.getInstance().marshall(this, protocolMarshaller); } }
/* Copyright 2014-2016 Intel Corporation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package apple.avfoundation; import apple.NSObject; import apple.coregraphics.struct.CGRect; import apple.foundation.NSArray; import apple.foundation.NSMethodSignature; import apple.foundation.NSSet; import org.moe.natj.c.ann.FunctionPtr; import org.moe.natj.general.NatJ; import org.moe.natj.general.Pointer; import org.moe.natj.general.ann.ByValue; import org.moe.natj.general.ann.Generated; import org.moe.natj.general.ann.Library; import org.moe.natj.general.ann.Mapped; import org.moe.natj.general.ann.MappedReturn; import org.moe.natj.general.ann.NInt; import org.moe.natj.general.ann.NUInt; import org.moe.natj.general.ann.Owned; import org.moe.natj.general.ann.Runtime; import org.moe.natj.general.ptr.VoidPtr; import org.moe.natj.objc.Class; import org.moe.natj.objc.ObjCRuntime; import org.moe.natj.objc.SEL; import org.moe.natj.objc.ann.ObjCClassBinding; import org.moe.natj.objc.ann.Selector; import org.moe.natj.objc.map.ObjCObjectMapper; @Generated @Library("AVFoundation") @Runtime(ObjCRuntime.class) @ObjCClassBinding public class AVCaptureOutput extends NSObject { static { NatJ.register(); } @Generated protected AVCaptureOutput(Pointer peer) { super(peer); } @Generated @Selector("accessInstanceVariablesDirectly") public static native boolean accessInstanceVariablesDirectly(); @Generated @Owned @Selector("alloc") public static native AVCaptureOutput alloc(); @Generated @Selector("allocWithZone:") @MappedReturn(ObjCObjectMapper.class) public static native Object allocWithZone(VoidPtr zone); @Generated @Selector("automaticallyNotifiesObserversForKey:") public static native boolean automaticallyNotifiesObserversForKey(String key); @Generated @Selector("cancelPreviousPerformRequestsWithTarget:") public static native void cancelPreviousPerformRequestsWithTarget(@Mapped(ObjCObjectMapper.class) Object aTarget); @Generated @Selector("cancelPreviousPerformRequestsWithTarget:selector:object:") public static native void cancelPreviousPerformRequestsWithTargetSelectorObject( @Mapped(ObjCObjectMapper.class) Object aTarget, SEL aSelector, @Mapped(ObjCObjectMapper.class) Object anArgument); @Generated @Selector("classFallbacksForKeyedArchiver") public static native NSArray<String> classFallbacksForKeyedArchiver(); @Generated @Selector("classForKeyedUnarchiver") public static native Class classForKeyedUnarchiver(); @Generated @Selector("debugDescription") public static native String debugDescription_static(); @Generated @Selector("description") public static native String description_static(); @Generated @Selector("hash") @NUInt public static native long hash_static(); @Generated @Selector("instanceMethodForSelector:") @FunctionPtr(name = "call_instanceMethodForSelector_ret") public static native NSObject.Function_instanceMethodForSelector_ret instanceMethodForSelector(SEL aSelector); @Generated @Selector("instanceMethodSignatureForSelector:") public static native NSMethodSignature instanceMethodSignatureForSelector(SEL aSelector); @Generated @Selector("instancesRespondToSelector:") public static native boolean instancesRespondToSelector(SEL aSelector); @Generated @Selector("isSubclassOfClass:") public static native boolean isSubclassOfClass(Class aClass); @Generated @Selector("keyPathsForValuesAffectingValueForKey:") public static native NSSet<String> keyPathsForValuesAffectingValueForKey(String key); @Generated @Owned @Selector("new") @MappedReturn(ObjCObjectMapper.class) public static native Object new_objc(); @Generated @Selector("resolveClassMethod:") public static native boolean resolveClassMethod(SEL sel); @Generated @Selector("resolveInstanceMethod:") public static native boolean resolveInstanceMethod(SEL sel); @Generated @Selector("setVersion:") public static native void setVersion_static(@NInt long aVersion); @Generated @Selector("superclass") public static native Class superclass_static(); @Generated @Selector("version") @NInt public static native long version_static(); @Generated @Selector("connectionWithMediaType:") public native AVCaptureConnection connectionWithMediaType(String mediaType); @Generated @Selector("connections") public native NSArray<? extends AVCaptureConnection> connections(); @Generated @Selector("init") public native AVCaptureOutput init(); @Generated @Selector("metadataOutputRectOfInterestForRect:") @ByValue public native CGRect metadataOutputRectOfInterestForRect(@ByValue CGRect rectInOutputCoordinates); @Generated @Selector("rectForMetadataOutputRectOfInterest:") @ByValue public native CGRect rectForMetadataOutputRectOfInterest(@ByValue CGRect rectInMetadataOutputCoordinates); @Generated @Selector("transformedMetadataObjectForMetadataObject:connection:") public native AVMetadataObject transformedMetadataObjectForMetadataObjectConnection(AVMetadataObject metadataObject, AVCaptureConnection connection); }
/* * 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.util; import java.util.Iterator; /** * @author max */ public class UnmodifiableIterator<T> implements Iterator<T> { private final Iterator<T> myOriginalIterator; public UnmodifiableIterator(final Iterator<T> originalIterator) { myOriginalIterator = originalIterator; } public boolean hasNext() { return myOriginalIterator.hasNext(); } public T next() { return myOriginalIterator.next(); } public void remove() { throw new UnsupportedOperationException(); } }
package com.hedera.hashgraph.sdk; import com.google.common.base.Splitter; public final class IdUtil { private IdUtil() { } public static <R> R parseIdString(String id, WithIdNums<R> withIdNums) { var rawNums = Splitter.on('.') .split(id) .iterator(); R newId; try { newId = withIdNums.apply(Long.parseLong(rawNums.next()), Long.parseLong(rawNums.next()), Long.parseLong(rawNums.next())); } catch (Exception e) { throw new IllegalArgumentException("Invalid Id format, should be in format {shardNum}.{realmNum}.{idNum}"); } return newId; } @FunctionalInterface public interface WithIdNums<R> { R apply(long shardNum, long realmNum, long entityNum); } }
package com.nlf.extend.wechat.semantic.bean; /** * 语义识别:航班 * * @author 6tail * */ public class SemanticResponseFlight extends SemanticResponse{ /** 航空公司 */ private String airline; /** 出发城市名称 */ private String depCityName; /** 出发城市简称 */ private String depCityNameSimple; /** 用户输入的出发城市 */ private String dep; /** 到达城市名称 */ private String arrCityName; /** 到达城市简称 */ private String arrCityNameSimple; /** 用户输入的到达城市 */ private String arr; /** 用户输入的日期 */ private String day; /** 识别出的日期 */ private String dayInYmd; public String getAirline(){ return airline; } public void setAirline(String airline){ this.airline = airline; } public String getDepCityName(){ return depCityName; } public void setDepCityName(String depCityName){ this.depCityName = depCityName; } public String getDepCityNameSimple(){ return depCityNameSimple; } public void setDepCityNameSimple(String depCityNameSimple){ this.depCityNameSimple = depCityNameSimple; } public String getDep(){ return dep; } public void setDep(String dep){ this.dep = dep; } public String getArrCityName(){ return arrCityName; } public void setArrCityName(String arrCityName){ this.arrCityName = arrCityName; } public String getArrCityNameSimple(){ return arrCityNameSimple; } public void setArrCityNameSimple(String arrCityNameSimple){ this.arrCityNameSimple = arrCityNameSimple; } public String getArr(){ return arr; } public void setArr(String arr){ this.arr = arr; } public String getDay(){ return day; } public void setDay(String day){ this.day = day; } public String getDayInYmd(){ return dayInYmd; } public void setDayInYmd(String dayInYmd){ this.dayInYmd = dayInYmd; } }
package com.ufreedom.lubanadapter; /** * Created by UFreedom on 2019/2/17. */ public interface ModelProvider<T> { T getModel(int position); }
/* * Copyright 2008, Yahoo! 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.yahoo.zookeeper.server; import com.yahoo.zookeeper.KeeperException; /** * This is the basic interface that ZooKeeperServer uses to track sessions. The * standalone and leader ZooKeeperServer use the same SessionTracker. The * FollowerZooKeeperServer uses a SessionTracker which is basically a simple * shell to track information to be forwarded to the leader. */ public interface SessionTracker { public static interface SessionExpirer { public void expire(long sessionId); public long getServerId(); } long createSession(int sessionTimeout); void addSession(long id, int to); /** * @param sessionId * @param sessionTimeout * @return false if session is no longer active */ boolean touchSession(long sessionId, int sessionTimeout); /** * */ void shutdown(); /** * @param sessionId */ void removeSession(long sessionId); void checkSession(long sessionId) throws KeeperException; }
/* * Copyright 2014 JBoss 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 org.optaplanner.examples.nqueens.app; import java.io.File; import java.util.Collection; import org.junit.runners.Parameterized; import org.optaplanner.core.api.domain.solution.Solution; import org.optaplanner.core.config.exhaustivesearch.ExhaustiveSearchType; import org.optaplanner.examples.common.app.ExhaustiveSearchTest; import org.optaplanner.examples.common.persistence.SolutionDao; import org.optaplanner.examples.nqueens.domain.NQueens; import org.optaplanner.examples.nqueens.persistence.NQueensDao; import static org.junit.Assert.*; public class NQueensExhaustiveSearchTest extends ExhaustiveSearchTest { @Parameterized.Parameters(name = "{index}: {0} - {1}") public static Collection<Object[]> getSolutionFilesAsParameters() { return buildParameters(new NQueensDao(), "4queens.xml"); } public NQueensExhaustiveSearchTest(File unsolvedDataFile, ExhaustiveSearchType exhaustiveSearchType) { super(unsolvedDataFile, exhaustiveSearchType); } @Override protected String createSolverConfigResource() { return NQueensApp.SOLVER_CONFIG; } @Override protected SolutionDao createSolutionDao() { return new NQueensDao(); } @Override protected void assertSolution(Solution bestSolution) { super.assertSolution(bestSolution); assertEquals(0, ((NQueens) bestSolution).getScore().getScore()); } }
/** * Copyright 2016 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.rvalerio.foregroundappchecker.goodvibe.fcm; import android.util.Log; import com.google.firebase.iid.FirebaseInstanceId; import com.google.firebase.iid.FirebaseInstanceIdService; public class AppFirebaseInstanceIDService extends FirebaseInstanceIdService { private static final String TAG = "MyFirebaseIIDService"; /** * Called if InstanceID token is updated. This may occur if the security of * the previous token had been compromised. Note that this is called when the InstanceID token * is initially generated so this is where you would retrieve the token. */ // [START refresh_token] @Override public void onTokenRefresh() { // Get updated InstanceID token. String refreshedToken = FirebaseInstanceId.getInstance().getToken(); Log.d(TAG, "Refreshed token: " + refreshedToken); // If you want to send messages to this application instance or // manage this apps subscriptions on the server side, send the // Instance ID token to your app server. sendRegistrationToServer(refreshedToken); } // [END refresh_token] /** * Persist token to third-party servers. * * Modify this method to associate the user's FCM InstanceID token with any server-side account * maintained by your application. * * @param token The new token. */ private void sendRegistrationToServer(String token) { } }
package dk.ralu.springtutorial.restapi; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class FixedMessageEndpoint { @RequestMapping("/messages/fixed") public String index() { return "Hello World"; } }
package com.pacific.web.controller; import com.pacific.common.exception.ServiceException; import com.pacific.common.web.result.AjaxResult; import com.pacific.domain.entity.Application; import com.pacific.domain.entity.Machine; import com.pacific.domain.enums.StateEnums; import com.pacific.domain.query.MachineQuery; import com.pacific.mapper.MachineMapper; import com.pacific.service.ApplicationService; import com.pacific.service.MachineService; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import javax.annotation.Resource; import java.util.List; /** * Created by fe on 16/8/1. */ @Controller @RequestMapping("/machine") public class MachineController { @Resource private MachineMapper machineMapper; @Resource private MachineService machineService; @Resource private ApplicationService applicationService; @RequestMapping("/machineList.htm") public String tomMachineList() { return "machine/machineList"; } @RequestMapping("/toMachineEdit.htm") public ModelAndView toMachineEdit(Long id) { ModelAndView modelAndView = new ModelAndView(); modelAndView.setViewName("machine/machineEdit"); if (id != null) { Machine machine = machineMapper.selectByPrimaryKey(id); modelAndView.addObject("id",id); modelAndView.addObject("machine",machine); } else { List<Application> applicationList = applicationService.queryApplicationByState(StateEnums.AVAILABLE.getCode()); modelAndView.addObject("applicationList",applicationList); } return modelAndView; } @ResponseBody @RequestMapping("/machineList.json") public AjaxResult machineList(MachineQuery machineQuery) { AjaxResult ajaxResult = new AjaxResult(machineService.queryMachineDto(machineQuery)); return ajaxResult; } @ResponseBody @RequestMapping("/saveMachine.json") public AjaxResult saveMachine(Machine machine) { machineService.saveMachine(machine); return new AjaxResult(); } }
/* * 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.ingest.common; import org.elasticsearch.ingest.AbstractProcessor; import org.elasticsearch.ingest.ConfigurationUtils; import org.elasticsearch.ingest.IngestDocument; import org.elasticsearch.ingest.Processor; import java.util.Map; /** * Base class for processors that manipulate source strings and require a single "fields" array config value, which * holds a list of field names in string format. * * @param <T> The resultant type for the target field */ abstract class AbstractStringProcessor<T> extends AbstractProcessor { private final String field; private final boolean ignoreMissing; private final String targetField; AbstractStringProcessor(String tag, String field, boolean ignoreMissing, String targetField) { super(tag); this.field = field; this.ignoreMissing = ignoreMissing; this.targetField = targetField; } public String getField() { return field; } boolean isIgnoreMissing() { return ignoreMissing; } String getTargetField() { return targetField; } @Override public final IngestDocument execute(IngestDocument document) { String val = document.getFieldValue(field, String.class, ignoreMissing); if (val == null && ignoreMissing) { return document; } else if (val == null) { throw new IllegalArgumentException("field [" + field + "] is null, cannot process it."); } document.setFieldValue(targetField, process(val)); return document; } protected abstract T process(String value); abstract static class Factory implements Processor.Factory { final String processorType; protected Factory(String processorType) { this.processorType = processorType; } @Override public AbstractStringProcessor create(Map<String, Processor.Factory> registry, String tag, Map<String, Object> config) throws Exception { String field = ConfigurationUtils.readStringProperty(processorType, tag, config, "field"); boolean ignoreMissing = ConfigurationUtils.readBooleanProperty(processorType, tag, config, "ignore_missing", false); String targetField = ConfigurationUtils.readStringProperty(processorType, tag, config, "target_field", field); return newProcessor(tag, config, field, ignoreMissing, targetField); } protected abstract AbstractStringProcessor newProcessor(String processorTag, Map<String, Object> config, String field, boolean ignoreMissing, String targetField); } }
/** * Copyright (c) 2013, Anthony Schiochet and Eric Citaire * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * The names Anthony Schiochet and Eric Citaire may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL MICHAEL BOSTOCK BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.github.gwtd3.demo.client.testcases.selection; import com.github.gwtd3.api.core.Value; import com.github.gwtd3.api.core.Selection; import com.github.gwtd3.api.functions.DatumFunction; import com.google.gwt.dom.client.Element; import com.google.gwt.user.client.ui.ComplexPanel; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.Widget; public class TestSelectionHtml extends AbstractSelectionTest { @Override public void doTest(final ComplexPanel sandbox) { testGetter(); testSetterConstantString(); testSetterFunction(); } protected void testSetterFunction() { // works with single selection Selection selection = givenASimpleSelection(new Label()); final String value = "<div name=\"test\" style=\"background-color:red;\"></div>"; selection.html(new DatumFunction<String>() { @Override public String apply(final Element context, final Value datum, final int index) { return value + index; } }); assertEquals(value + "0", getElementInnerHtml(0)); // works with multiple selection selection = givenAMultipleSelection(new Label(), new Label(), new Label()); selection.html(new DatumFunction<String>() { @Override public String apply(final Element context, final Value datum, final int index) { return value + index; } }); assertEquals(value + "0", getElementInnerHtml(0)); assertEquals(value + "1", getElementInnerHtml(1)); assertEquals(value + "2", getElementInnerHtml(2)); } protected void testSetterConstantString() { // works with single selection Selection selection = givenASimpleSelection(new Label()); final String value = "<div name=\"test\" style=\"background-color:red;\"></div>"; selection.html(value); assertEquals(value, getElementInnerHtml(0)); // works with multiple selection selection = givenAMultipleSelection(new Label(), new Label(), new Label()); selection.html(value); assertEquals(value, getElementInnerHtml(0)); assertEquals(value, getElementInnerHtml(1)); assertEquals(value, getElementInnerHtml(2)); } protected void testGetter() { // with single selection Label label = new Label(); final String value = "<div name=\"test\" style=\"background-color:red;\"></div>"; label.getElement().setInnerHTML(value); Selection selection = givenASimpleSelection(label); assertEquals(value, selection.html()); // with multiple selection, should return the first element selection = givenAMultipleSelection(createLabel(value), createLabel(value), createLabel(value)); assertEquals(value, selection.html()); } private Widget createLabel(final String textValue) { Label l = new Label(); l.getElement().setInnerHTML(textValue); return l; } }
package com.eminent.usb.a3d; import android.graphics.Bitmap; import android.hardware.usb.UsbDevice; import android.hardware.usb.UsbDeviceConnection; import com.eminent.common.ImageProcess; /** * Created by kentlee on 2017/12/6. */ public class A3DControllerAE extends A3DController { private int currentIntegration = 260; private float mtcnn_brightness = 0; private float frame_brightness = 0; private int mtcnn_size = 0; private int frame_size = 0; private int proportion = 0; private float brightness_low_thre = 50; private float brightness_high_thre = 80; private static int brightness_step[] = { 25, 25, 20, 20, 15, 10, 5 }; // private static int fps = 0; // private static int integ = 0; private static float ratio = 0; private static int _step = 0; // private static Bitmap m_frame_bitmap; private boolean is_ae_mode = false; public void setThresholdLevel( double level ) { } public void setThresholds( float high, float low ) { brightness_high_thre = high; brightness_low_thre = low; } public A3DControllerAE( UsbDevice device, UsbDeviceConnection connection ) { super( device, connection ); } public A3DControllerAE( UsbDevice device, UsbDeviceConnection connection, boolean ae_mode ) { super( device, connection ); setAutoExposureMode( ae_mode ); } public void setAutoExposureMode( boolean value ) { is_ae_mode = value; if ( is_ae_mode ) { resetSettings(); } } @Override public boolean initCamera() { if ( !is_ae_mode ) return super.initCamera(); super.initCamera(); return resetSettings(); } @Override public boolean setIntegrationTime( float value ) { return !is_ae_mode && super.setIntegrationTime( value ); } @Override public boolean setFrameRate( int fps ) { return !is_ae_mode && super.setFrameRate( fps ); } @Override public boolean setCurrentPower( int miniAmp ) { return !is_ae_mode && super.setCurrentPower( miniAmp ); } public boolean resetSettings() { currentIntegration = 260; return auto_set_fps_and_integration(); } // full screen bitmap // call every frame at beginning public float calculate_frame_brightness( Bitmap bitmap ) { if ( !is_ae_mode || bitmap.getWidth()!= 144) { return 0.f; } frame_brightness = ImageProcess.averageBrightnessRGB( bitmap ); frame_size = bitmap.getWidth() * bitmap.getHeight(); return frame_brightness; } // raw face image bitmap // call while face > 0 public boolean adjust_integration_time_with_face( Bitmap bitmap ) { if ( !is_ae_mode ) return false; boolean status = false; mtcnn_brightness = ImageProcess.averageBrightnessRGB( bitmap ); mtcnn_size = bitmap.getWidth() * bitmap.getHeight(); ratio = ( (float) mtcnn_size / (float) frame_size ); proportion = (int) ( ratio * 10 ); if ( proportion <= 6 ) { _step = brightness_step[proportion]; } else { _step = brightness_step[6]; } if ( mtcnn_brightness <= brightness_low_thre ) { currentIntegration += _step; if ( currentIntegration > 402 ) currentIntegration = 402; auto_set_fps_and_integration(); status = true; } if ( mtcnn_brightness >= brightness_high_thre ) { currentIntegration -= _step; if ( currentIntegration < 1 ) currentIntegration = 1; auto_set_fps_and_integration(); status = true; } return status; } // call while no face public boolean adjust_integration_time() { if ( !is_ae_mode ) return false; boolean status = false; if ( frame_brightness > 60 ) { currentIntegration -= 50; if ( currentIntegration < 1 ) currentIntegration = 1; this.auto_set_fps_and_integration(); status = true; } if ( 10 > frame_brightness ) { currentIntegration += 50; if ( currentIntegration > 402 ) currentIntegration = 402; this.auto_set_fps_and_integration(); status = true; } return status; } // ----------------------------------------------------------------------------------------- // private boolean auto_set_fps_and_integration() { boolean result = true; if ( ( 1 <= currentIntegration ) && ( currentIntegration < 60 ) ) { result &= super.setIntegrationTimeWithRegisterValue( currentIntegration ); result &= super.setFrameRate( 60 ); } else if ( ( 60 <= currentIntegration ) && ( currentIntegration < 310 ) ) { result &= super.setIntegrationTimeWithRegisterValue( currentIntegration / 2 ); result &= super.setFrameRate( 30 ); } else if ( ( 310 <= currentIntegration ) && ( currentIntegration < 402 ) ) { result &= super.setIntegrationTimeWithRegisterValue( (int) ( currentIntegration / 2.125 ) ); result &= super.setFrameRate( 25 ); } else { result &= super.setIntegrationTimeWithRegisterValue( 161 ); result &= super.setFrameRate( 25 ); } return result; } }
/* * Copyright 2012-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.boot.actuate.autoconfigure.jolokia; import org.jolokia.http.AgentServlet; import org.junit.Test; import org.springframework.boot.actuate.autoconfigure.endpoint.web.ServletEndpointManagementContextConfiguration; import org.springframework.boot.actuate.autoconfigure.web.server.ManagementContextAutoConfiguration; import org.springframework.boot.actuate.autoconfigure.web.servlet.ServletManagementContextAutoConfiguration; import org.springframework.boot.actuate.endpoint.web.ExposableServletEndpoint; import org.springframework.boot.actuate.endpoint.web.annotation.ServletEndpointDiscoverer; import org.springframework.boot.actuate.endpoint.web.annotation.ServletEndpointsSupplier; import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.autoconfigure.web.servlet.DispatcherServletAutoConfiguration; import org.springframework.boot.test.context.assertj.AssertableWebApplicationContext; import org.springframework.boot.test.context.runner.WebApplicationContextRunner; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.test.util.ReflectionTestUtils; import java.util.Collection; import java.util.Collections; import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link JolokiaEndpointAutoConfiguration}. * * @author Christian Dupuis * @author Andy Wilkinson * @author Stephane Nicoll */ public class JolokiaEndpointAutoConfigurationTests { private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() .withConfiguration(AutoConfigurations.of(DispatcherServletAutoConfiguration.class, ManagementContextAutoConfiguration.class, ServletManagementContextAutoConfiguration.class, ServletEndpointManagementContextConfiguration.class, JolokiaEndpointAutoConfiguration.class, TestConfiguration.class)); @Test public void jolokiaServletShouldBeEnabledByDefault() { this.contextRunner.run((context) -> { ExposableServletEndpoint endpoint = getEndpoint(context); assertThat(endpoint.getRootPath()).isEqualTo("jolokia"); Object servlet = ReflectionTestUtils.getField(endpoint.getEndpointServlet(), "servlet"); assertThat(servlet).isInstanceOf(AgentServlet.class); }); } @Test public void jolokiaServletWhenDisabledShouldNotBeDiscovered() { this.contextRunner.withPropertyValues("management.endpoint.jolokia.enabled=false").run((context) -> { Collection<ExposableServletEndpoint> endpoints = context.getBean(ServletEndpointsSupplier.class) .getEndpoints(); assertThat(endpoints).isEmpty(); }); } @Test public void jolokiaServletWhenHasCustomConfigShouldApplyInitParams() { this.contextRunner.withPropertyValues("management.endpoint.jolokia.config.debug=true").run((context) -> { ExposableServletEndpoint endpoint = getEndpoint(context); assertThat(endpoint.getEndpointServlet()).extracting("initParameters") .containsOnly(Collections.singletonMap("debug", "true")); }); } private ExposableServletEndpoint getEndpoint(AssertableWebApplicationContext context) { Collection<ExposableServletEndpoint> endpoints = context.getBean(ServletEndpointsSupplier.class).getEndpoints(); return endpoints.iterator().next(); } @Configuration static class TestConfiguration { @Bean public ServletEndpointDiscoverer servletEndpointDiscoverer(ApplicationContext applicationContext) { return new ServletEndpointDiscoverer(applicationContext, null, Collections.emptyList()); } } }
import com.hedera.hashgraph.sdk.AccountCreateTransaction; import com.hedera.hashgraph.sdk.Hbar; import com.hedera.hashgraph.sdk.PrecheckStatusException; import com.hedera.hashgraph.sdk.PrivateKey; import com.hedera.hashgraph.sdk.ReceiptStatusException; import com.hedera.hashgraph.sdk.Status; import com.hedera.hashgraph.sdk.TokenAssociateTransaction; import com.hedera.hashgraph.sdk.TokenCreateTransaction; import com.hedera.hashgraph.sdk.TokenFreezeTransaction; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import java.util.Collections; import java.util.Objects; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; class TokenFreezeIntegrationTest { @Test @DisplayName("Can freeze account with token") void canFreezeAccountWithToken() throws Exception { var testEnv = new IntegrationTestEnv(1).useThrowawayAccount(); var key = PrivateKey.generateED25519(); var response = new AccountCreateTransaction() .setKey(key) .setInitialBalance(new Hbar(1)) .execute(testEnv.client); var accountId = Objects.requireNonNull(response.getReceipt(testEnv.client).accountId); var tokenId = Objects.requireNonNull( new TokenCreateTransaction() .setTokenName("ffff") .setTokenSymbol("F") .setDecimals(3) .setInitialSupply(1000000) .setTreasuryAccountId(testEnv.operatorId) .setAdminKey(testEnv.operatorKey) .setFreezeKey(testEnv.operatorKey) .setWipeKey(testEnv.operatorKey) .setKycKey(testEnv.operatorKey) .setSupplyKey(testEnv.operatorKey) .setFreezeDefault(false) .execute(testEnv.client) .getReceipt(testEnv.client) .tokenId ); new TokenAssociateTransaction() .setAccountId(accountId) .setTokenIds(Collections.singletonList(tokenId)) .freezeWith(testEnv.client) .sign(key) .execute(testEnv.client) .getReceipt(testEnv.client); new TokenFreezeTransaction() .setAccountId(accountId) .setTokenId(tokenId) .freezeWith(testEnv.client) .sign(key) .execute(testEnv.client) .getReceipt(testEnv.client); testEnv.close(tokenId, accountId, key); } @Test @DisplayName("Cannot freeze account on token when token ID is not set") void cannotFreezeAccountOnTokenWhenTokenIDIsNotSet() throws Exception { var testEnv = new IntegrationTestEnv(1).useThrowawayAccount(); var key = PrivateKey.generateED25519(); var response = new AccountCreateTransaction() .setKey(key) .setInitialBalance(new Hbar(1)) .execute(testEnv.client); var accountId = Objects.requireNonNull(response.getReceipt(testEnv.client).accountId); var error = assertThrows(PrecheckStatusException.class, () -> { new TokenFreezeTransaction() .setAccountId(accountId) .freezeWith(testEnv.client) .sign(key) .execute(testEnv.client) .getReceipt(testEnv.client); }); assertTrue(error.getMessage().contains(Status.INVALID_TOKEN_ID.toString())); testEnv.close(accountId, key); } @Test @DisplayName("Cannot freeze account on token when account ID is not set") void cannotFreezeAccountOnTokenWhenAccountIDIsNotSet() throws Exception { var testEnv = new IntegrationTestEnv(1).useThrowawayAccount(); var key = PrivateKey.generateED25519(); var response = new TokenCreateTransaction() .setTokenName("ffff") .setTokenSymbol("F") .setDecimals(3) .setInitialSupply(1000000) .setTreasuryAccountId(testEnv.operatorId) .setAdminKey(testEnv.operatorKey) .setFreezeKey(testEnv.operatorKey) .setWipeKey(testEnv.operatorKey) .setKycKey(testEnv.operatorKey) .setSupplyKey(testEnv.operatorKey) .setFreezeDefault(false) .execute(testEnv.client); var tokenId = Objects.requireNonNull(response.getReceipt(testEnv.client).tokenId); var error = assertThrows(PrecheckStatusException.class, () -> { new TokenFreezeTransaction() .setTokenId(tokenId) .freezeWith(testEnv.client) .sign(key) .execute(testEnv.client) .getReceipt(testEnv.client); }); assertTrue(error.getMessage().contains(Status.INVALID_ACCOUNT_ID.toString())); testEnv.close(tokenId); } @Test @DisplayName("Cannot freeze account on token when account was not associated with") void cannotFreezeAccountOnTokenWhenAccountWasNotAssociatedWith() throws Exception { var testEnv = new IntegrationTestEnv(1).useThrowawayAccount(); var key = PrivateKey.generateED25519(); var response = new AccountCreateTransaction() .setKey(key) .setInitialBalance(new Hbar(1)) .execute(testEnv.client); var accountId = Objects.requireNonNull(response.getReceipt(testEnv.client).accountId); var tokenId = Objects.requireNonNull( new TokenCreateTransaction() .setTokenName("ffff") .setTokenSymbol("F") .setDecimals(3) .setInitialSupply(1000000) .setTreasuryAccountId(testEnv.operatorId) .setAdminKey(testEnv.operatorKey) .setFreezeKey(testEnv.operatorKey) .setWipeKey(testEnv.operatorKey) .setKycKey(testEnv.operatorKey) .setSupplyKey(testEnv.operatorKey) .setFreezeDefault(false) .execute(testEnv.client) .getReceipt(testEnv.client) .tokenId ); var error = assertThrows(ReceiptStatusException.class, () -> { new TokenFreezeTransaction() .setAccountId(accountId) .setTokenId(tokenId) .freezeWith(testEnv.client) .sign(key) .execute(testEnv.client) .getReceipt(testEnv.client); }); assertTrue(error.getMessage().contains(Status.TOKEN_NOT_ASSOCIATED_TO_ACCOUNT.toString())); testEnv.close(tokenId, accountId, key); } }
package com.algaworks.algafood.domain.service; import java.util.Map; import java.util.Set; import lombok.Builder; import lombok.Getter; import lombok.NonNull; import lombok.Singular; public interface EnvioEmailService { void enviar(Mensagem mensagem); @Getter @Builder class Mensagem { @Singular private Set<String> destinatarios; @NonNull private String assunto; @NonNull private String corpo; @Singular("variavel") private Map<String, Object> variaveis; } }
/* * Copyright 2016-2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.greengrass.model.transform; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import com.amazonaws.Request; import com.amazonaws.http.HttpMethodName; import com.amazonaws.services.greengrass.model.*; import com.amazonaws.transform.Marshaller; import com.amazonaws.protocol.*; import com.amazonaws.protocol.Protocol; import com.amazonaws.annotation.SdkInternalApi; /** * GetConnectorDefinitionVersionRequest Marshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") @SdkInternalApi public class GetConnectorDefinitionVersionRequestProtocolMarshaller implements Marshaller<Request<GetConnectorDefinitionVersionRequest>, GetConnectorDefinitionVersionRequest> { private static final OperationInfo SDK_OPERATION_BINDING = OperationInfo.builder().protocol(Protocol.REST_JSON) .requestUri("/greengrass/definition/connectors/{ConnectorDefinitionId}/versions/{ConnectorDefinitionVersionId}").httpMethodName(HttpMethodName.GET) .hasExplicitPayloadMember(false).hasPayloadMembers(false).serviceName("AWSGreengrass").build(); private final com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory; public GetConnectorDefinitionVersionRequestProtocolMarshaller(com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory) { this.protocolFactory = protocolFactory; } public Request<GetConnectorDefinitionVersionRequest> marshall(GetConnectorDefinitionVersionRequest getConnectorDefinitionVersionRequest) { if (getConnectorDefinitionVersionRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { final ProtocolRequestMarshaller<GetConnectorDefinitionVersionRequest> protocolMarshaller = protocolFactory.createProtocolMarshaller( SDK_OPERATION_BINDING, getConnectorDefinitionVersionRequest); protocolMarshaller.startMarshalling(); GetConnectorDefinitionVersionRequestMarshaller.getInstance().marshall(getConnectorDefinitionVersionRequest, protocolMarshaller); return protocolMarshaller.finishMarshalling(); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
package dev.nicklasw.bankid.client.request; import lombok.Builder; import lombok.Getter; import lombok.NonNull; @Getter @Builder public class CollectRequest implements Request { /** * The orderRef from the response from authentication or sign. */ @NonNull private final String orderRef; @Override public String getUri() { return "collect"; } }
public class Process1 extends Template { public Process1() { } @Override void initialize() { System.out.println("Process 1 : Initialize"); } @Override void start() { System.out.println("Process 1 : Start"); } @Override void end() { System.out.println("Process 1 : End"); } }
package stevekung.mods.moreplanets.planets.diona.blocks; import micdoodle8.mods.galacticraft.api.block.IDetectableResource; import net.minecraft.block.SoundType; import net.minecraft.block.material.Material; import net.minecraft.block.state.IBlockState; import net.minecraft.util.BlockRenderLayer; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import stevekung.mods.moreplanets.utils.CompatibilityManagerMP; import stevekung.mods.moreplanets.utils.blocks.BlockBaseMP; import stevekung.mods.moreplanets.utils.blocks.EnumSortCategoryBlock; import stevekung.mods.moreplanets.utils.itemblocks.IItemRarity; import stevekung.mods.stevekunglib.utils.ColorUtils; public class BlockGlowingIronBlock extends BlockBaseMP implements IDetectableResource { public BlockGlowingIronBlock(String name) { super(Material.IRON); this.setHardness(5.0F); this.setResistance(10.0F); this.setSoundType(SoundType.METAL); this.setUnlocalizedName(name); } @Override @SideOnly(Side.CLIENT) public BlockRenderLayer getBlockLayer() { return CompatibilityManagerMP.isCTMLoaded ? BlockRenderLayer.CUTOUT : BlockRenderLayer.SOLID; } @Override public EnumSortCategoryBlock getBlockCategory() { return EnumSortCategoryBlock.INGOT_BLOCK; } @Override public ColorUtils.RGB getRarity() { return ColorUtils.stringToRGB(IItemRarity.ALIEN); } @Override public boolean isValueable(IBlockState state) { return true; } }
package components; import java.lang.annotation.Target; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Genre public @interface ChildGenre { java.lang.String value() default ""; }
// Copyright (c) 2008 The Board of Trustees of The Leland Stanford Junior University // Copyright (c) 2011, 2012 Open Networking Foundation // Copyright (c) 2012, 2013 Big Switch Networks, Inc. // This library was generated by the LoxiGen Compiler. // See the file LICENSE.txt which should have been included in the source distribution // Automatically generated by LOXI from template of_class.java // Do not modify package org.projectfloodlight.openflow.protocol.ver15; import org.projectfloodlight.openflow.protocol.*; import org.projectfloodlight.openflow.protocol.action.*; import org.projectfloodlight.openflow.protocol.actionid.*; import org.projectfloodlight.openflow.protocol.bsntlv.*; import org.projectfloodlight.openflow.protocol.errormsg.*; import org.projectfloodlight.openflow.protocol.meterband.*; import org.projectfloodlight.openflow.protocol.instruction.*; import org.projectfloodlight.openflow.protocol.instructionid.*; import org.projectfloodlight.openflow.protocol.match.*; import org.projectfloodlight.openflow.protocol.stat.*; import org.projectfloodlight.openflow.protocol.oxm.*; import org.projectfloodlight.openflow.protocol.oxs.*; import org.projectfloodlight.openflow.protocol.queueprop.*; import org.projectfloodlight.openflow.types.*; import org.projectfloodlight.openflow.util.*; import org.projectfloodlight.openflow.exceptions.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Set; import io.netty.buffer.ByteBuf; import com.google.common.hash.PrimitiveSink; import com.google.common.hash.Funnel; class OFOxmSctpDstVer15 implements OFOxmSctpDst { private static final Logger logger = LoggerFactory.getLogger(OFOxmSctpDstVer15.class); // version: 1.5 final static byte WIRE_VERSION = 6; final static int LENGTH = 6; private final static TransportPort DEFAULT_VALUE = TransportPort.NONE; // OF message fields private final TransportPort value; // // Immutable default instance final static OFOxmSctpDstVer15 DEFAULT = new OFOxmSctpDstVer15( DEFAULT_VALUE ); // package private constructor - used by readers, builders, and factory OFOxmSctpDstVer15(TransportPort value) { if(value == null) { throw new NullPointerException("OFOxmSctpDstVer15: property value cannot be null"); } this.value = value; } // Accessors for OF message fields @Override public long getTypeLen() { return 0x80002402L; } @Override public TransportPort getValue() { return value; } @Override public MatchField<TransportPort> getMatchField() { return MatchField.SCTP_DST; } @Override public boolean isMasked() { return false; } public OFOxm<TransportPort> getCanonical() { // exact match OXM is always canonical return this; } @Override public TransportPort getMask()throws UnsupportedOperationException { throw new UnsupportedOperationException("Property mask not supported in version 1.5"); } @Override public OFVersion getVersion() { return OFVersion.OF_15; } public OFOxmSctpDst.Builder createBuilder() { return new BuilderWithParent(this); } static class BuilderWithParent implements OFOxmSctpDst.Builder { final OFOxmSctpDstVer15 parentMessage; // OF message fields private boolean valueSet; private TransportPort value; BuilderWithParent(OFOxmSctpDstVer15 parentMessage) { this.parentMessage = parentMessage; } @Override public long getTypeLen() { return 0x80002402L; } @Override public TransportPort getValue() { return value; } @Override public OFOxmSctpDst.Builder setValue(TransportPort value) { this.value = value; this.valueSet = true; return this; } @Override public MatchField<TransportPort> getMatchField() { return MatchField.SCTP_DST; } @Override public boolean isMasked() { return false; } @Override public OFOxm<TransportPort> getCanonical()throws UnsupportedOperationException { throw new UnsupportedOperationException("Property canonical not supported in version 1.5"); } @Override public TransportPort getMask()throws UnsupportedOperationException { throw new UnsupportedOperationException("Property mask not supported in version 1.5"); } @Override public OFVersion getVersion() { return OFVersion.OF_15; } @Override public OFOxmSctpDst build() { TransportPort value = this.valueSet ? this.value : parentMessage.value; if(value == null) throw new NullPointerException("Property value must not be null"); // return new OFOxmSctpDstVer15( value ); } } static class Builder implements OFOxmSctpDst.Builder { // OF message fields private boolean valueSet; private TransportPort value; @Override public long getTypeLen() { return 0x80002402L; } @Override public TransportPort getValue() { return value; } @Override public OFOxmSctpDst.Builder setValue(TransportPort value) { this.value = value; this.valueSet = true; return this; } @Override public MatchField<TransportPort> getMatchField() { return MatchField.SCTP_DST; } @Override public boolean isMasked() { return false; } @Override public OFOxm<TransportPort> getCanonical()throws UnsupportedOperationException { throw new UnsupportedOperationException("Property canonical not supported in version 1.5"); } @Override public TransportPort getMask()throws UnsupportedOperationException { throw new UnsupportedOperationException("Property mask not supported in version 1.5"); } @Override public OFVersion getVersion() { return OFVersion.OF_15; } // @Override public OFOxmSctpDst build() { TransportPort value = this.valueSet ? this.value : DEFAULT_VALUE; if(value == null) throw new NullPointerException("Property value must not be null"); return new OFOxmSctpDstVer15( value ); } } final static Reader READER = new Reader(); static class Reader implements OFMessageReader<OFOxmSctpDst> { @Override public OFOxmSctpDst readFrom(ByteBuf bb) throws OFParseError { // fixed value property typeLen == 0x80002402L int typeLen = bb.readInt(); if(typeLen != (int) 0x80002402) throw new OFParseError("Wrong typeLen: Expected=0x80002402L(0x80002402L), got="+typeLen); TransportPort value = TransportPort.read2Bytes(bb); OFOxmSctpDstVer15 oxmSctpDstVer15 = new OFOxmSctpDstVer15( value ); if(logger.isTraceEnabled()) logger.trace("readFrom - read={}", oxmSctpDstVer15); return oxmSctpDstVer15; } } public void putTo(PrimitiveSink sink) { FUNNEL.funnel(this, sink); } final static OFOxmSctpDstVer15Funnel FUNNEL = new OFOxmSctpDstVer15Funnel(); static class OFOxmSctpDstVer15Funnel implements Funnel<OFOxmSctpDstVer15> { private static final long serialVersionUID = 1L; @Override public void funnel(OFOxmSctpDstVer15 message, PrimitiveSink sink) { // fixed value property typeLen = 0x80002402L sink.putInt((int) 0x80002402); message.value.putTo(sink); } } public void writeTo(ByteBuf bb) { WRITER.write(bb, this); } final static Writer WRITER = new Writer(); static class Writer implements OFMessageWriter<OFOxmSctpDstVer15> { @Override public void write(ByteBuf bb, OFOxmSctpDstVer15 message) { // fixed value property typeLen = 0x80002402L bb.writeInt((int) 0x80002402); message.value.write2Bytes(bb); } } @Override public String toString() { StringBuilder b = new StringBuilder("OFOxmSctpDstVer15("); b.append("value=").append(value); b.append(")"); return b.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; OFOxmSctpDstVer15 other = (OFOxmSctpDstVer15) obj; if (value == null) { if (other.value != null) return false; } else if (!value.equals(other.value)) return false; return true; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((value == null) ? 0 : value.hashCode()); return result; } }
package org.beetl.core; import junit.framework.TestCase; import org.beetl.core.resource.ClasspathResourceLoader; import java.io.IOException; import java.io.Reader; public class BasicTestCase extends TestCase { // 日志对象 private static ClasspathResourceLoader rs; public static boolean enableOptimize = true; public static GroupTemplate gt = null; static { Configuration cf; try { cf = new Configuration(); } catch (IOException e) { throw new RuntimeException(e); } cf.setStatementStart("<%"); cf.setStatementEnd("%>"); cf.addPkg("org.beetl.core"); cf.addPkg("org.beetl.core.nativecall"); cf.setHtmlTagSupport(true); // FileResourceLoader rs = new FileResourceLoader(home, // cf.getCharset()); rs = new ClasspathResourceLoader("template/"); gt = new GroupTemplate(rs, cf); } public BasicTestCase() { } protected String getFileContent(String path) throws IOException { Reader fr = rs.getResource(path).openReader(); StringBuilder temp = new StringBuilder(); int bufSzie = 1024; char[] cs = new char[bufSzie]; int len = -1; while ((len = fr.read(cs)) != -1) { temp.append(cs, 0, len); } return temp.toString(); } protected void bind(Template t, Object... objects) { for (int i = 0; i < objects.length; i = i + 2) { t.binding(objects[i].toString(), objects[i + 1]); } } }
/* * 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.jclouds.apis; import static org.jclouds.reflect.Reflection2.typeToken; import java.util.Properties; import org.jclouds.Context; import org.jclouds.View; import org.jclouds.util.Closeables2; import com.google.common.reflect.TypeToken; import com.google.inject.Module; public abstract class BaseViewLiveTest<V extends View> extends BaseContextLiveTest<Context> { protected volatile V view; @Override protected void initializeContext() { Closeables2.closeQuietly(context); view = createView(setupProperties(), setupModules()); context = view.unwrap(); } protected abstract TypeToken<V> viewType(); @Override protected TypeToken<Context> contextType() { return typeToken(Context.class); } protected V createView(Properties props, Iterable<Module> modules) { return newBuilder().modules(modules).overrides(props).buildView(viewType()); } }
package helper.entity; import helper.entity.model.DummySession; import helper.entity.model.DummyUser; import net.tokensmith.otter.controller.entity.StatusCode; import net.tokensmith.otter.dispatch.entity.RestBtwnRequest; import net.tokensmith.otter.dispatch.entity.RestBtwnResponse; import net.tokensmith.otter.router.entity.Method; import net.tokensmith.otter.router.entity.between.RestBetween; import net.tokensmith.otter.router.exception.HaltException; public class HaltRestBetween implements RestBetween<DummySession, DummyUser> { @Override public void process(Method method, RestBtwnRequest<DummySession, DummyUser> request, RestBtwnResponse response) throws HaltException { response.setStatusCode(StatusCode.UNAUTHORIZED); throw new HaltException("Test Halt"); } }
/* * Copyright (c) 2017, Kronos <https://github.com/KronosDesign> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package net.runelite.client.plugins.devtools; import ch.qos.logback.classic.Level; import ch.qos.logback.classic.Logger; import com.google.common.collect.ImmutableList; import com.google.common.primitives.Ints; import com.google.inject.Provides; import java.awt.image.BufferedImage; import static java.lang.Math.min; import java.util.Arrays; import java.util.List; import javax.inject.Inject; import lombok.Getter; import net.runelite.api.ChatMessageType; import net.runelite.api.Client; import net.runelite.api.Experience; import net.runelite.api.IndexedSprite; import net.runelite.api.MenuAction; import net.runelite.api.MenuEntry; import net.runelite.api.NPC; import net.runelite.api.Player; import net.runelite.api.Skill; import net.runelite.api.VarbitComposition; import net.runelite.api.coords.WorldPoint; import net.runelite.api.events.CommandExecuted; import net.runelite.api.events.MenuEntryAdded; import net.runelite.api.events.StatChanged; import net.runelite.api.events.VarbitChanged; import net.runelite.api.kit.KitType; import net.runelite.client.chat.ChatMessageBuilder; import net.runelite.client.chat.ChatMessageManager; import net.runelite.client.chat.QueuedMessage; import net.runelite.client.config.ConfigManager; import net.runelite.client.eventbus.EventBus; import net.runelite.client.eventbus.Subscribe; import net.runelite.client.plugins.Plugin; import net.runelite.client.plugins.PluginDescriptor; import net.runelite.client.ui.ClientToolbar; import net.runelite.client.ui.JagexColors; import net.runelite.client.ui.NavigationButton; import net.runelite.client.ui.overlay.OverlayManager; import net.runelite.client.util.ColorUtil; import net.runelite.client.util.ImageUtil; import org.slf4j.LoggerFactory; @PluginDescriptor( name = "Developer Tools", tags = {"panel"}, developerPlugin = true ) @Getter public class DevToolsPlugin extends Plugin { private static final List<MenuAction> EXAMINE_MENU_ACTIONS = ImmutableList.of(MenuAction.EXAMINE_ITEM, MenuAction.EXAMINE_ITEM_GROUND, MenuAction.EXAMINE_NPC, MenuAction.EXAMINE_OBJECT); @Inject private Client client; @Inject private ClientToolbar clientToolbar; @Inject private OverlayManager overlayManager; @Inject private DevToolsOverlay overlay; @Inject private LocationOverlay locationOverlay; @Inject private SceneOverlay sceneOverlay; @Inject private CameraOverlay cameraOverlay; @Inject private WorldMapLocationOverlay worldMapLocationOverlay; @Inject private WorldMapRegionOverlay mapRegionOverlay; @Inject private SoundEffectOverlay soundEffectOverlay; @Inject private EventBus eventBus; @Inject private ConfigManager configManager; @Inject private ChatMessageManager chatMessageManager; private DevToolsButton players; private DevToolsButton npcs; private DevToolsButton groundItems; private DevToolsButton groundObjects; private DevToolsButton gameObjects; private DevToolsButton graphicsObjects; private DevToolsButton walls; private DevToolsButton decorations; private DevToolsButton inventory; private DevToolsButton projectiles; private DevToolsButton location; private DevToolsButton chunkBorders; private DevToolsButton mapSquares; private DevToolsButton validMovement; private DevToolsButton movementFlags; private DevToolsButton lineOfSight; private DevToolsButton cameraPosition; private DevToolsButton worldMapLocation; private DevToolsButton tileLocation; private DevToolsButton interacting; private DevToolsButton examine; private DevToolsButton detachedCamera; private DevToolsButton logMenuActions; private DevToolsButton widgetInspector; private DevToolsButton varInspector; private DevToolsButton soundEffects; private DevToolsButton scriptInspector; private DevToolsButton inventoryInspector; private DevToolsButton roofs; private DevToolsButton shell; private NavigationButton navButton; @Provides DevToolsConfig provideConfig(ConfigManager configManager) { return configManager.getConfig(DevToolsConfig.class); } @Override protected void startUp() throws Exception { players = new DevToolsButton("Players"); npcs = new DevToolsButton("NPCs"); groundItems = new DevToolsButton("Ground Items"); groundObjects = new DevToolsButton("Ground Objects"); gameObjects = new DevToolsButton("Game Objects"); graphicsObjects = new DevToolsButton("Graphics Objects"); walls = new DevToolsButton("Walls"); decorations = new DevToolsButton("Decorations"); inventory = new DevToolsButton("Inventory"); projectiles = new DevToolsButton("Projectiles"); location = new DevToolsButton("Location"); worldMapLocation = new DevToolsButton("World Map Location"); tileLocation = new DevToolsButton("Tile Location"); cameraPosition = new DevToolsButton("Camera Position"); chunkBorders = new DevToolsButton("Chunk Borders"); mapSquares = new DevToolsButton("Map Squares"); lineOfSight = new DevToolsButton("Line Of Sight"); validMovement = new DevToolsButton("Valid Movement"); movementFlags = new DevToolsButton("Movement Flags"); interacting = new DevToolsButton("Interacting"); examine = new DevToolsButton("Examine"); detachedCamera = new DevToolsButton("Detached Camera"); logMenuActions = new DevToolsButton("Log Menu Actions"); widgetInspector = new DevToolsButton("Widget Inspector"); varInspector = new DevToolsButton("Var Inspector"); soundEffects = new DevToolsButton("Sound Effects"); scriptInspector = new DevToolsButton("Script Inspector"); inventoryInspector = new DevToolsButton("Inventory Inspector"); roofs = new DevToolsButton("Roofs"); shell = new DevToolsButton("Shell"); overlayManager.add(overlay); overlayManager.add(locationOverlay); overlayManager.add(sceneOverlay); overlayManager.add(cameraOverlay); overlayManager.add(worldMapLocationOverlay); overlayManager.add(mapRegionOverlay); overlayManager.add(soundEffectOverlay); final DevToolsPanel panel = injector.getInstance(DevToolsPanel.class); final BufferedImage icon = ImageUtil.loadImageResource(getClass(), "devtools_icon.png"); navButton = NavigationButton.builder() .tooltip("Developer Tools") .icon(icon) .priority(1) .panel(panel) .build(); clientToolbar.addNavigation(navButton); eventBus.register(soundEffectOverlay); } @Override protected void shutDown() throws Exception { eventBus.unregister(soundEffectOverlay); overlayManager.remove(overlay); overlayManager.remove(locationOverlay); overlayManager.remove(sceneOverlay); overlayManager.remove(cameraOverlay); overlayManager.remove(worldMapLocationOverlay); overlayManager.remove(mapRegionOverlay); overlayManager.remove(soundEffectOverlay); clientToolbar.removeNavigation(navButton); } @Subscribe public void onCommandExecuted(CommandExecuted commandExecuted) { String[] args = commandExecuted.getArguments(); switch (commandExecuted.getCommand()) { case "logger": { final Logger logger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME); String message; Level currentLoggerLevel = logger.getLevel(); if (args.length < 1) { message = "Logger level is currently set to " + currentLoggerLevel; } else { Level newLoggerLevel = Level.toLevel(args[0], currentLoggerLevel); logger.setLevel(newLoggerLevel); message = "Logger level has been set to " + newLoggerLevel; } client.addChatMessage(ChatMessageType.GAMEMESSAGE, "", message, null); break; } case "getvarp": { int varp = Integer.parseInt(args[0]); int[] varps = client.getVarps(); int value = varps[varp]; client.addChatMessage(ChatMessageType.GAMEMESSAGE, "", "VarPlayer " + varp + ": " + value, null); break; } case "setvarp": { int varp = Integer.parseInt(args[0]); int value = Integer.parseInt(args[1]); int[] varps = client.getVarps(); varps[varp] = value; client.queueChangedVarp(varp); client.addChatMessage(ChatMessageType.GAMEMESSAGE, "", "Set VarPlayer " + varp + " to " + value, null); VarbitChanged varbitChanged = new VarbitChanged(); varbitChanged.setIndex(varp); eventBus.post(varbitChanged); // fake event break; } case "getvarb": { int varbit = Integer.parseInt(args[0]); int value = client.getVarbitValue(client.getVarps(), varbit); client.addChatMessage(ChatMessageType.GAMEMESSAGE, "", "Varbit " + varbit + ": " + value, null); break; } case "setvarb": { int varbit = Integer.parseInt(args[0]); int value = Integer.parseInt(args[1]); client.setVarbitValue(client.getVarps(), varbit, value); VarbitComposition varbitComposition = client.getVarbit(varbit); client.queueChangedVarp(varbitComposition.getIndex()); client.addChatMessage(ChatMessageType.GAMEMESSAGE, "", "Set varbit " + varbit + " to " + value, null); eventBus.post(new VarbitChanged()); // fake event break; } case "addxp": { Skill skill = Skill.valueOf(args[0].toUpperCase()); int xp = Integer.parseInt(args[1]); int totalXp = client.getSkillExperience(skill) + xp; int level = min(Experience.getLevelForXp(totalXp), 99); client.getBoostedSkillLevels()[skill.ordinal()] = level; client.getRealSkillLevels()[skill.ordinal()] = level; client.getSkillExperiences()[skill.ordinal()] = totalXp; client.queueChangedSkill(skill); StatChanged statChanged = new StatChanged( skill, totalXp, level, level ); eventBus.post(statChanged); break; } case "setstat": { Skill skill = Skill.valueOf(args[0].toUpperCase()); int level = Integer.parseInt(args[1]); level = Ints.constrainToRange(level, 1, Experience.MAX_REAL_LEVEL); int xp = Experience.getXpForLevel(level); client.getBoostedSkillLevels()[skill.ordinal()] = level; client.getRealSkillLevels()[skill.ordinal()] = level; client.getSkillExperiences()[skill.ordinal()] = xp; client.queueChangedSkill(skill); StatChanged statChanged = new StatChanged( skill, xp, level, level ); eventBus.post(statChanged); break; } case "anim": { int id = Integer.parseInt(args[0]); Player localPlayer = client.getLocalPlayer(); localPlayer.setAnimation(id); localPlayer.setAnimationFrame(0); break; } case "gfx": { int id = Integer.parseInt(args[0]); Player localPlayer = client.getLocalPlayer(); localPlayer.setGraphic(id); localPlayer.setSpotAnimFrame(0); break; } case "transform": { int id = Integer.parseInt(args[0]); Player player = client.getLocalPlayer(); player.getPlayerComposition().setTransformedNpcId(id); player.setIdlePoseAnimation(-1); player.setPoseAnimation(-1); break; } case "cape": { int id = Integer.parseInt(args[0]); Player player = client.getLocalPlayer(); player.getPlayerComposition().getEquipmentIds()[KitType.CAPE.getIndex()] = id + 512; player.getPlayerComposition().setHash(); break; } case "sound": { int id = Integer.parseInt(args[0]); client.playSoundEffect(id); break; } case "msg": { client.addChatMessage(ChatMessageType.GAMEMESSAGE, "", String.join(" ", args), ""); break; } case "setconf": { // setconf group.key name = value String group = args[0]; String key = args[1], value = ""; for (int i = 2; i < args.length; ++i) { if (args[i].equals("=")) { value = String.join(" ", Arrays.copyOfRange(args, i + 1, args.length)); break; } key += " " + args[i]; } String current = configManager.getConfiguration(group, key); final String message; if (value.isEmpty()) { configManager.unsetConfiguration(group, key); message = String.format("Unset configuration %s.%s (was: %s)", group, key, current); } else { configManager.setConfiguration(group, key, value); message = String.format("Set configuration %s.%s to %s (was: %s)", group, key, value, current); } chatMessageManager.queue(QueuedMessage.builder() .type(ChatMessageType.GAMEMESSAGE) .runeLiteFormattedMessage(new ChatMessageBuilder().append(message).build()) .build()); break; } case "getconf": { String group = args[0], key = String.join(" ", Arrays.copyOfRange(args, 1, args.length)); String value = configManager.getConfiguration(group, key); final String message = String.format("%s.%s = %s", group, key, value); chatMessageManager.queue(QueuedMessage.builder() .type(ChatMessageType.GAMEMESSAGE) .runeLiteFormattedMessage(new ChatMessageBuilder().append(message).build()) .build()); break; } case "modicons": { final ChatMessageBuilder builder = new ChatMessageBuilder(); final IndexedSprite[] modIcons = client.getModIcons(); for (int i = 0; i < modIcons.length; i++) { builder.append(i + "=").img(i); if (i != modIcons.length - 1) { builder.append(", "); } } chatMessageManager.queue(QueuedMessage.builder() .type(ChatMessageType.GAMEMESSAGE) .runeLiteFormattedMessage(builder.build()) .build()); break; } } } @Subscribe public void onMenuEntryAdded(MenuEntryAdded event) { if (!examine.isActive()) { return; } MenuAction action = MenuAction.of(event.getType()); if (EXAMINE_MENU_ACTIONS.contains(action)) { MenuEntry[] entries = client.getMenuEntries(); MenuEntry entry = entries[entries.length - 1]; final int identifier = event.getIdentifier(); String info = "ID: "; if (action == MenuAction.EXAMINE_NPC) { NPC npc = client.getCachedNPCs()[identifier]; info += npc.getId(); } else { info += identifier; if (action == MenuAction.EXAMINE_OBJECT) { WorldPoint point = WorldPoint.fromScene(client, entry.getParam0(), entry.getParam1(), client.getPlane()); info += " X: " + point.getX() + " Y: " + point.getY(); } } entry.setTarget(entry.getTarget() + " " + ColorUtil.prependColorTag("(" + info + ")", JagexColors.MENU_TARGET)); } } }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.record.compiler; /** * Code generator for "buffer" type. */ public class JBuffer extends JCompType { class JavaBuffer extends JavaCompType { JavaBuffer() { super("org.apache.hadoop.record.Buffer", "Buffer", "org.apache.hadoop.record.Buffer", "TypeID.RIOType.BUFFER"); } String getTypeIDObjectString() { return "org.apache.hadoop.record.meta.TypeID.BufferTypeID"; } void genCompareTo(CodeBuffer cb, String fname, String other) { cb.append(Consts.RIO_PREFIX + "ret = " + fname + ".compareTo(" + other + ");\n"); } void genEquals(CodeBuffer cb, String fname, String peer) { cb.append(Consts.RIO_PREFIX + "ret = " + fname + ".equals(" + peer + ");\n"); } void genHashCode(CodeBuffer cb, String fname) { cb.append(Consts.RIO_PREFIX + "ret = " + fname + ".hashCode();\n"); } void genSlurpBytes(CodeBuffer cb, String b, String s, String l) { cb.append("{\n"); cb.append("int i = org.apache.hadoop.record.Utils.readVInt(" + b + ", " + s + ");\n"); cb .append("int z = org.apache.hadoop.record.Utils.getVIntSize(i);\n"); cb.append(s + " += z+i; " + l + " -= (z+i);\n"); cb.append("}\n"); } void genCompareBytes(CodeBuffer cb) { cb.append("{\n"); cb .append("int i1 = org.apache.hadoop.record.Utils.readVInt(b1, s1);\n"); cb .append("int i2 = org.apache.hadoop.record.Utils.readVInt(b2, s2);\n"); cb .append("int z1 = org.apache.hadoop.record.Utils.getVIntSize(i1);\n"); cb .append("int z2 = org.apache.hadoop.record.Utils.getVIntSize(i2);\n"); cb.append("s1+=z1; s2+=z2; l1-=z1; l2-=z2;\n"); cb .append("int r1 = org.apache.hadoop.record.Utils.compareBytes(b1,s1,i1,b2,s2,i2);\n"); cb.append("if (r1 != 0) { return (r1<0)?-1:0; }\n"); cb.append("s1+=i1; s2+=i2; l1-=i1; l1-=i2;\n"); cb.append("}\n"); } } class CppBuffer extends CppCompType { CppBuffer() { super(" ::std::string"); } void genGetSet(CodeBuffer cb, String fname) { cb.append("virtual const " + getType() + "& get" + toCamelCase(fname) + "() const {\n"); cb.append("return " + fname + ";\n"); cb.append("}\n"); cb.append("virtual " + getType() + "& get" + toCamelCase(fname) + "() {\n"); cb.append("return " + fname + ";\n"); cb.append("}\n"); } String getTypeIDObjectString() { return "new ::hadoop::TypeID(::hadoop::RIOTYPE_BUFFER)"; } } /** Creates a new instance of JBuffer */ public JBuffer() { setJavaType(new JavaBuffer()); setCppType(new CppBuffer()); setCType(new CCompType()); } String getSignature() { return "B"; } }
/* * Copyright (c) 2004-2021, University of Oslo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of the HISP project nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.hisp.dhis.webapi.controller; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import org.hisp.dhis.webapi.DhisControllerConvenienceTest; import org.hisp.dhis.webapi.json.JsonObject; import org.hisp.dhis.webapi.json.domain.JsonSchema; import org.junit.Test; import org.springframework.http.HttpStatus; /** * Tests the {@link SchemaController} using (mocked) REST requests. * * @author Jan Bernitt */ public class SchemaControllerTest extends DhisControllerConvenienceTest { @Test public void testValidateSchema() { assertWebMessage( "OK", 200, "OK", null, POST( "/schemas/organisationUnit", "{'name':'My Unit', 'shortName':'OU1', 'openingDate': '2020-01-01'}" ) .content( HttpStatus.OK ) ); } @Test public void testValidateSchema_NoSuchType() { assertWebMessage( "Not Found", 404, "ERROR", "404 Type xyz does not exist.", POST( "/schemas/xyz", "{}" ) .content( HttpStatus.NOT_FOUND ) ); } @Test public void testFieldFilteringNameKlass() { var schema = GET( "/schemas/organisationUnit?fields=name,klass" ).content( HttpStatus.OK ) .as( JsonSchema.class ); assertNotNull( schema.getKlass() ); assertNotNull( schema.getName() ); assertNull( schema.getSingular() ); assertNull( schema.getPlural() ); assertFalse( schema.get( "properties" ).exists() ); } @Test public void testFieldFilteringDefaultPropertiesExpansion() { var schema = GET( "/schemas/organisationUnit?fields=name,klass,properties" ).content( HttpStatus.OK ) .as( JsonSchema.class ); assertNotNull( schema.getKlass() ); assertNotNull( schema.getName() ); assertNull( schema.getSingular() ); assertNull( schema.getPlural() ); assertTrue( schema.get( "properties" ).exists() ); assertFalse( schema.getProperties().isEmpty() ); assertNotNull( schema.getProperties().get( 0 ).getName() ); assertNotNull( schema.getProperties().get( 0 ).getKlass() ); assertNotNull( schema.getProperties().get( 0 ).getFieldName() ); } @Test public void testFieldFilteringAllSchemas() { var schemas = GET( "/schemas?fields=name,klass" ).content( HttpStatus.OK ) .as( JsonObject.class ).getList( "schemas", JsonSchema.class ); for ( JsonSchema schema : schemas ) { assertNotNull( schema.getKlass() ); assertNotNull( schema.getName() ); assertNull( schema.getSingular() ); assertNull( schema.getPlural() ); } } }
package utilties; public class Die { private static final byte D_4 = 4; private static final byte D_6 = 6; private static final byte D_8 = 8; private static final byte D_10 = 10; private static final byte D_20 = 20; public static int rollD4() { return (int) (Math.random() * D_4) + 1; } public static int rollD6() { return (int) (Math.random() * D_6) + 1; } public static int rollD8() { return (int) (Math.random() * D_8) + 1; } public static int rollD10() { return (int) (Math.random() * D_10) + 1; } public static int rollD20() { return (int) (Math.random() * D_20) + 1; } }
package com.azrul.ebanking.depositaccount.config; import com.fasterxml.jackson.datatype.hibernate5.Hibernate5Module; import com.fasterxml.jackson.datatype.jdk8.Jdk8Module; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.zalando.problem.ProblemModule; import org.zalando.problem.violations.ConstraintViolationProblemModule; @Configuration public class JacksonConfiguration { /** * Support for Java date and time API. * @return the corresponding Jackson module. */ @Bean public JavaTimeModule javaTimeModule() { return new JavaTimeModule(); } @Bean public Jdk8Module jdk8TimeModule() { return new Jdk8Module(); } /* * Support for Hibernate types in Jackson. */ @Bean public Hibernate5Module hibernate5Module() { return new Hibernate5Module(); } /* * Module for serialization/deserialization of RFC7807 Problem. */ @Bean public ProblemModule problemModule() { return new ProblemModule(); } /* * Module for serialization/deserialization of ConstraintViolationProblem. */ @Bean public ConstraintViolationProblemModule constraintViolationProblemModule() { return new ConstraintViolationProblemModule(); } }
/* * Licensed to Crate under one or more contributor license agreements. * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. Crate 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. * * However, if you have executed another commercial license agreement * with Crate these terms will supersede the license and you may use the * software solely pursuant to the terms of the relevant commercial * agreement. */ package io.crate.analyze; import io.crate.analyze.relations.AnalyzedRelation; import io.crate.analyze.relations.AnalyzedRelationVisitor; import io.crate.expression.symbol.Field; import io.crate.exceptions.ColumnUnknownException; import io.crate.metadata.OutputName; import io.crate.metadata.Path; import io.crate.metadata.table.Operation; import io.crate.sql.tree.QualifiedName; import io.crate.types.DataTypes; import javax.annotation.Nonnull; import java.util.Collections; import java.util.List; public class ExplainAnalyzedStatement implements AnalyzedStatement, AnalyzedRelation { final AnalyzedStatement statement; private final List<Field> fields; public ExplainAnalyzedStatement(String columnName, AnalyzedStatement statement) { this.statement = statement; this.fields = Collections.singletonList(new Field(this, new OutputName(columnName), DataTypes.OBJECT)); } @Override public <C, R> R accept(AnalyzedStatementVisitor<C, R> analyzedStatementVisitor, C context) { return analyzedStatementVisitor.visitExplainStatement(this, context); } public AnalyzedStatement statement() { return statement; } @Override public <C, R> R accept(AnalyzedRelationVisitor<C, R> visitor, C context) { return visitor.visitExplain(this, context); } @Override public Field getField(Path path, Operation operation) throws UnsupportedOperationException, ColumnUnknownException { throw new UnsupportedOperationException("getField is not supported"); } @Override public List<Field> fields() { return fields; } @Override public boolean isWriteOperation() { return false; } @Override public QualifiedName getQualifiedName() { throw new UnsupportedOperationException("method not supported"); } @Override public void setQualifiedName(@Nonnull QualifiedName qualifiedName) { throw new UnsupportedOperationException("method not supported"); } @Override public boolean isUnboundPlanningSupported() { return true; } }
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import org.eclipse.microprofile.metrics.annotation.Timed; import javax.enterprise.context.ApplicationScoped; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; @Path("/weather") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) @ApplicationScoped public class WeatherService { @Path("/day/status") @Timed(name = "weather_day_status", absolute = true, displayName = "Weather Day Status", description = "This metric shows the weather status of the day.") @GET @Produces(MediaType.TEXT_PLAIN) public String dayStatus() { return "Hi, today is a sunny day!"; } }
/* * Copyright (C) 2014 Google 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.google.gson.functional; import java.io.IOException; import java.util.Arrays; import java.util.List; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.TypeAdapter; import com.google.gson.TypeAdapterFactory; import com.google.gson.annotations.JsonAdapter; import com.google.gson.reflect.TypeToken; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import junit.framework.TestCase; /** * Functional tests for the {@link com.google.gson.annotations.JsonAdapter} annotation on fields. */ public final class JsonAdapterAnnotationOnFieldsTest extends TestCase { public void testClassAnnotationAdapterTakesPrecedenceOverDefault() { Gson gson = new Gson(); String json = gson.toJson(new Computer(new User("Inderjeet Singh"))); assertEquals("{\"user\":\"UserClassAnnotationAdapter\"}", json); Computer computer = gson.fromJson("{'user':'Inderjeet Singh'}", Computer.class); assertEquals("UserClassAnnotationAdapter", computer.user.name); } public void testClassAnnotationAdapterFactoryTakesPrecedenceOverDefault() { Gson gson = new Gson(); String json = gson.toJson(new Gizmo(new Part("Part"))); assertEquals("{\"part\":\"GizmoPartTypeAdapterFactory\"}", json); Gizmo computer = gson.fromJson("{'part':'Part'}", Gizmo.class); assertEquals("GizmoPartTypeAdapterFactory", computer.part.name); } public void testRegisteredTypeAdapterTakesPrecedenceOverClassAnnotationAdapter() { Gson gson = new GsonBuilder() .registerTypeAdapter(User.class, new RegisteredUserAdapter()) .create(); String json = gson.toJson(new Computer(new User("Inderjeet Singh"))); assertEquals("{\"user\":\"RegisteredUserAdapter\"}", json); Computer computer = gson.fromJson("{'user':'Inderjeet Singh'}", Computer.class); assertEquals("RegisteredUserAdapter", computer.user.name); } public void testFieldAnnotationTakesPrecedenceOverRegisteredTypeAdapter() { Gson gson = new GsonBuilder() .registerTypeAdapter(Part.class, new TypeAdapter<Part>() { @Override public void write(JsonWriter out, Part part) throws IOException { throw new AssertionError(); } @Override public Part read(JsonReader in) throws IOException { throw new AssertionError(); } }).create(); String json = gson.toJson(new Gadget(new Part("screen"))); assertEquals("{\"part\":\"PartJsonFieldAnnotationAdapter\"}", json); Gadget gadget = gson.fromJson("{'part':'screen'}", Gadget.class); assertEquals("PartJsonFieldAnnotationAdapter", gadget.part.name); } public void testFieldAnnotationTakesPrecedenceOverClassAnnotation() { Gson gson = new Gson(); String json = gson.toJson(new Computer2(new User("Inderjeet Singh"))); assertEquals("{\"user\":\"UserFieldAnnotationAdapter\"}", json); Computer2 target = gson.fromJson("{'user':'Interjeet Singh'}", Computer2.class); assertEquals("UserFieldAnnotationAdapter", target.user.name); } private static final class Gadget { @JsonAdapter(PartJsonFieldAnnotationAdapter.class) final Part part; Gadget(Part part) { this.part = part; } } private static final class Gizmo { @JsonAdapter(GizmoPartTypeAdapterFactory.class) final Part part; Gizmo(Part part) { this.part = part; } } private static final class Part { final String name; public Part(String name) { this.name = name; } } private static class PartJsonFieldAnnotationAdapter extends TypeAdapter<Part> { @Override public void write(JsonWriter out, Part part) throws IOException { out.value("PartJsonFieldAnnotationAdapter"); } @Override public Part read(JsonReader in) throws IOException { in.nextString(); return new Part("PartJsonFieldAnnotationAdapter"); } } private static class GizmoPartTypeAdapterFactory implements TypeAdapterFactory { public <T> TypeAdapter<T> create(Gson gson, final TypeToken<T> type) { return new TypeAdapter<T>() { @Override public void write(JsonWriter out, T value) throws IOException { out.value("GizmoPartTypeAdapterFactory"); } @SuppressWarnings("unchecked") @Override public T read(JsonReader in) throws IOException { in.nextString(); return (T) new Part("GizmoPartTypeAdapterFactory"); } }; } } private static final class Computer { final User user; Computer(User user) { this.user = user; } } @JsonAdapter(UserClassAnnotationAdapter.class) private static class User { public final String name; private User(String name) { this.name = name; } } private static class UserClassAnnotationAdapter extends TypeAdapter<User> { @Override public void write(JsonWriter out, User user) throws IOException { out.value("UserClassAnnotationAdapter"); } @Override public User read(JsonReader in) throws IOException { in.nextString(); return new User("UserClassAnnotationAdapter"); } } private static final class Computer2 { // overrides the JsonAdapter annotation of User with this @JsonAdapter(UserFieldAnnotationAdapter.class) final User user; Computer2(User user) { this.user = user; } } private static final class UserFieldAnnotationAdapter extends TypeAdapter<User> { @Override public void write(JsonWriter out, User user) throws IOException { out.value("UserFieldAnnotationAdapter"); } @Override public User read(JsonReader in) throws IOException { in.nextString(); return new User("UserFieldAnnotationAdapter"); } } private static final class RegisteredUserAdapter extends TypeAdapter<User> { @Override public void write(JsonWriter out, User user) throws IOException { out.value("RegisteredUserAdapter"); } @Override public User read(JsonReader in) throws IOException { in.nextString(); return new User("RegisteredUserAdapter"); } } public void testJsonAdapterInvokedOnlyForAnnotatedFields() { Gson gson = new Gson(); String json = "{'part1':'name','part2':{'name':'name2'}}"; GadgetWithTwoParts gadget = gson.fromJson(json, GadgetWithTwoParts.class); assertEquals("PartJsonFieldAnnotationAdapter", gadget.part1.name); assertEquals("name2", gadget.part2.name); } private static final class GadgetWithTwoParts { @JsonAdapter(PartJsonFieldAnnotationAdapter.class) final Part part1; final Part part2; // Doesn't have the JsonAdapter annotation @SuppressWarnings("unused") GadgetWithTwoParts(Part part1, Part part2) { this.part1 = part1; this.part2 = part2; } } public void testJsonAdapterWrappedInNullSafeAsRequested() { Gson gson = new Gson(); String fromJson = "{'part':null}"; GadgetWithOptionalPart gadget = gson.fromJson(fromJson, GadgetWithOptionalPart.class); assertNull(gadget.part); String toJson = gson.toJson(gadget); assertFalse(toJson.contains("PartJsonFieldAnnotationAdapter")); } private static final class GadgetWithOptionalPart { @JsonAdapter(value = PartJsonFieldAnnotationAdapter.class) final Part part; private GadgetWithOptionalPart(Part part) { this.part = part; } } /** Regression test contributed through https://github.com/google/gson/issues/831 */ public void testNonPrimitiveFieldAnnotationTakesPrecedenceOverDefault() { Gson gson = new Gson(); String json = gson.toJson(new GadgetWithOptionalPart(new Part("foo"))); assertEquals("{\"part\":\"PartJsonFieldAnnotationAdapter\"}", json); GadgetWithOptionalPart gadget = gson.fromJson("{'part':'foo'}", GadgetWithOptionalPart.class); assertEquals("PartJsonFieldAnnotationAdapter", gadget.part.name); } /** Regression test contributed through https://github.com/google/gson/issues/831 */ public void testPrimitiveFieldAnnotationTakesPrecedenceOverDefault() { Gson gson = new Gson(); String json = gson.toJson(new GadgetWithPrimitivePart(42)); assertEquals("{\"part\":\"42\"}", json); GadgetWithPrimitivePart gadget = gson.fromJson(json, GadgetWithPrimitivePart.class); assertEquals(42, gadget.part); } private static final class GadgetWithPrimitivePart { @JsonAdapter(LongToStringTypeAdapterFactory.class) final long part; private GadgetWithPrimitivePart(long part) { this.part = part; } } private static final class LongToStringTypeAdapterFactory implements TypeAdapterFactory { static final TypeAdapter<Long> ADAPTER = new TypeAdapter<Long>() { @Override public void write(JsonWriter out, Long value) throws IOException { out.value(value.toString()); } @Override public Long read(JsonReader in) throws IOException { return in.nextLong(); } }; @SuppressWarnings("unchecked") public <T> TypeAdapter<T> create(Gson gson, final TypeToken<T> type) { Class<?> cls = type.getRawType(); if (Long.class.isAssignableFrom(cls)) { return (TypeAdapter<T>) ADAPTER; } else if (long.class.isAssignableFrom(cls)) { return (TypeAdapter<T>) ADAPTER; } throw new IllegalStateException("Non-long field of type " + type + " annotated with @JsonAdapter(LongToStringTypeAdapterFactory.class)"); } } public void testFieldAnnotationWorksForParameterizedType() { Gson gson = new Gson(); String json = gson.toJson(new Gizmo2(Arrays.asList(new Part("Part")))); assertEquals("{\"part\":\"GizmoPartTypeAdapterFactory\"}", json); Gizmo2 computer = gson.fromJson("{'part':'Part'}", Gizmo2.class); assertEquals("GizmoPartTypeAdapterFactory", computer.part.get(0).name); } private static final class Gizmo2 { @JsonAdapter(Gizmo2PartTypeAdapterFactory.class) List<Part> part; Gizmo2(List<Part> part) { this.part = part; } } private static class Gizmo2PartTypeAdapterFactory implements TypeAdapterFactory { public <T> TypeAdapter<T> create(Gson gson, final TypeToken<T> type) { return new TypeAdapter<T>() { @Override public void write(JsonWriter out, T value) throws IOException { out.value("GizmoPartTypeAdapterFactory"); } @SuppressWarnings("unchecked") @Override public T read(JsonReader in) throws IOException { in.nextString(); return (T) Arrays.asList(new Part("GizmoPartTypeAdapterFactory")); } }; } } }
/* * Copyright 2012-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.ecs.model; import javax.annotation.Generated; /** * */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public enum TaskDefinitionStatus { ACTIVE("ACTIVE"), INACTIVE("INACTIVE"); private String value; private TaskDefinitionStatus(String value) { this.value = value; } @Override public String toString() { return this.value; } /** * Use this in place of valueOf. * * @param value * real value * @return TaskDefinitionStatus corresponding to the value */ public static TaskDefinitionStatus fromValue(String value) { if (value == null || "".equals(value)) { throw new IllegalArgumentException("Value cannot be null or empty!"); } for (TaskDefinitionStatus enumEntry : TaskDefinitionStatus.values()) { if (enumEntry.toString().equals(value)) { return enumEntry; } } throw new IllegalArgumentException("Cannot create enum from " + value + " value!"); } }
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.gamelift.model.transform; import java.util.List; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import com.amazonaws.services.gamelift.model.*; import com.amazonaws.protocol.*; import com.amazonaws.annotation.SdkInternalApi; /** * DescribeMatchmakingConfigurationsRequestMarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") @SdkInternalApi public class DescribeMatchmakingConfigurationsRequestMarshaller { private static final MarshallingInfo<List> NAMES_BINDING = MarshallingInfo.builder(MarshallingType.LIST).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("Names").build(); private static final MarshallingInfo<String> RULESETNAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("RuleSetName").build(); private static final MarshallingInfo<Integer> LIMIT_BINDING = MarshallingInfo.builder(MarshallingType.INTEGER).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("Limit").build(); private static final MarshallingInfo<String> NEXTTOKEN_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("NextToken").build(); private static final DescribeMatchmakingConfigurationsRequestMarshaller instance = new DescribeMatchmakingConfigurationsRequestMarshaller(); public static DescribeMatchmakingConfigurationsRequestMarshaller getInstance() { return instance; } /** * Marshall the given parameter object. */ public void marshall(DescribeMatchmakingConfigurationsRequest describeMatchmakingConfigurationsRequest, ProtocolMarshaller protocolMarshaller) { if (describeMatchmakingConfigurationsRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(describeMatchmakingConfigurationsRequest.getNames(), NAMES_BINDING); protocolMarshaller.marshall(describeMatchmakingConfigurationsRequest.getRuleSetName(), RULESETNAME_BINDING); protocolMarshaller.marshall(describeMatchmakingConfigurationsRequest.getLimit(), LIMIT_BINDING); protocolMarshaller.marshall(describeMatchmakingConfigurationsRequest.getNextToken(), NEXTTOKEN_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
/* * Copyright 2014-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.simplesystemsmanagement.model; import javax.annotation.Generated; /** * <p> * The target is not valid or does not exist. It might not be configured for EC2 Systems Manager or you might not have * permission to perform the operation. * </p> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class InvalidTargetException extends com.amazonaws.services.simplesystemsmanagement.model.AWSSimpleSystemsManagementException { private static final long serialVersionUID = 1L; /** * Constructs a new InvalidTargetException with the specified error message. * * @param message * Describes the error encountered. */ public InvalidTargetException(String message) { super(message); } }
/*- * ============LICENSE_START======================================================= * SDC * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. 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. * ============LICENSE_END========================================================= * Modifications copyright (c) 2019 Nokia * ================================================================================ */ package org.openecomp.sdc.be.components.impl; import static org.openecomp.sdc.common.log.enums.EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR; import com.google.gson.JsonElement; import fj.data.Either; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.function.Function; import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.tuple.ImmutablePair; import org.openecomp.sdc.be.components.impl.exceptions.BusinessLogicException; import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException; import org.openecomp.sdc.be.components.impl.exceptions.ByResponseFormatComponentException; import org.openecomp.sdc.be.components.validation.UserValidations; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.dao.janusgraph.JanusGraphGenericDao; import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; import org.openecomp.sdc.be.dao.jsongraph.JanusGraphDao; import org.openecomp.sdc.be.datamodel.utils.ArtifactUtils; import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; import org.openecomp.sdc.be.datatypes.elements.PropertyRule; import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.model.ArtifactDefinition; import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.ComponentInstInputsMap; import org.openecomp.sdc.be.model.ComponentInstOutputsMap; import org.openecomp.sdc.be.model.ComponentInstance; import org.openecomp.sdc.be.model.ComponentInstanceProperty; import org.openecomp.sdc.be.model.ComponentParametersView; import org.openecomp.sdc.be.model.DataTypeDefinition; import org.openecomp.sdc.be.model.IComplexDefaultValue; import org.openecomp.sdc.be.model.IPropertyInputCommon; import org.openecomp.sdc.be.model.LifecycleStateEnum; import org.openecomp.sdc.be.model.PolicyDefinition; import org.openecomp.sdc.be.model.PropertyConstraint; import org.openecomp.sdc.be.model.PropertyDefinition; import org.openecomp.sdc.be.model.User; import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache; import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ArtifactsOperations; import org.openecomp.sdc.be.model.jsonjanusgraph.operations.InterfaceOperation; import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.StorageException; import org.openecomp.sdc.be.model.operations.api.IElementOperation; import org.openecomp.sdc.be.model.operations.api.IGraphLockOperation; import org.openecomp.sdc.be.model.operations.api.IGroupInstanceOperation; import org.openecomp.sdc.be.model.operations.api.IGroupOperation; import org.openecomp.sdc.be.model.operations.api.IGroupTypeOperation; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.operations.impl.AttributeOperation; import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter; import org.openecomp.sdc.be.model.operations.impl.InterfaceLifecycleOperation; import org.openecomp.sdc.be.model.operations.impl.PolicyTypeOperation; import org.openecomp.sdc.be.model.operations.impl.PropertyOperation; import org.openecomp.sdc.be.model.operations.utils.ComponentValidationUtils; import org.openecomp.sdc.be.model.tosca.ToscaPropertyType; import org.openecomp.sdc.be.model.tosca.ToscaType; import org.openecomp.sdc.be.model.tosca.converters.PropertyValueConverter; import org.openecomp.sdc.be.model.tosca.validators.DataTypeValidatorConverter; import org.openecomp.sdc.be.model.tosca.validators.PropertyTypeValidator; import org.openecomp.sdc.be.user.Role; import org.openecomp.sdc.be.user.UserBusinessLogic; import org.openecomp.sdc.common.api.ArtifactTypeEnum; import org.openecomp.sdc.common.datastructure.Wrapper; import org.openecomp.sdc.common.log.wrappers.Logger; import org.openecomp.sdc.exception.ResponseFormat; import org.springframework.beans.factory.annotation.Autowired; public abstract class BaseBusinessLogic { private static final String FAILED_TO_LOCK_COMPONENT_ERROR = "Failed to lock component {} error - {}"; private static final Logger log = Logger.getLogger(BaseBusinessLogic.class); private static final String EMPTY_VALUE = null; private static final String SCHEMA_DOESN_T_EXISTS_FOR_PROPERTY_OF_TYPE = "Schema doesn't exists for property of type {}"; private static final String PROPERTY_IN_SCHEMA_DEFINITION_INSIDE_PROPERTY_OF_TYPE_DOESN_T_EXIST = "Property in Schema Definition inside property of type {} doesn't exist"; private static final String ADD_PROPERTY_VALUE = "Add property value"; private static final String THE_VALUE_OF_PROPERTY_FROM_TYPE_IS_INVALID = "The value {} of property from type {} is invalid"; protected IGroupTypeOperation groupTypeOperation; protected InterfaceOperation interfaceOperation; protected IElementOperation elementDao; protected ComponentsUtils componentsUtils; protected UserBusinessLogic userAdmin; protected IGraphLockOperation graphLockOperation; protected JanusGraphDao janusGraphDao; protected JanusGraphGenericDao janusGraphGenericDao; protected PropertyOperation propertyOperation; protected AttributeOperation attributeOperation; protected ApplicationDataTypeCache applicationDataTypeCache; protected ToscaOperationFacade toscaOperationFacade; protected ApplicationDataTypeCache dataTypeCache; protected IGroupOperation groupOperation; protected IGroupInstanceOperation groupInstanceOperation; protected InterfaceLifecycleOperation interfaceLifecycleTypeOperation; protected PolicyTypeOperation policyTypeOperation; protected ArtifactsOperations artifactToscaOperation; protected UserValidations userValidations; DataTypeValidatorConverter dataTypeValidatorConverter = DataTypeValidatorConverter.getInstance(); protected BaseBusinessLogic(IElementOperation elementDao, IGroupOperation groupOperation, IGroupInstanceOperation groupInstanceOperation, IGroupTypeOperation groupTypeOperation, InterfaceOperation interfaceOperation, InterfaceLifecycleOperation interfaceLifecycleTypeOperation, ArtifactsOperations artifactToscaOperation) { this.elementDao = elementDao; this.groupOperation = groupOperation; this.groupInstanceOperation = groupInstanceOperation; this.groupTypeOperation = groupTypeOperation; this.interfaceOperation = interfaceOperation; this.interfaceLifecycleTypeOperation = interfaceLifecycleTypeOperation; this.artifactToscaOperation = artifactToscaOperation; } @SafeVarargs static <T extends Enum<T>> boolean enumHasValueFilter(String name, Function<String, T> enumGetter, T... enumValues) { T enumFound = enumGetter.apply(name); return Arrays.asList(enumValues).contains(enumFound); } @Autowired public void setUserAdmin(UserBusinessLogic userAdmin) { this.userAdmin = userAdmin; } @Autowired public void setUserValidations(UserValidations userValidations) { this.userValidations = userValidations; } @Autowired public void setComponentsUtils(ComponentsUtils componentsUtils) { this.componentsUtils = componentsUtils; } @Autowired public void setJanusGraphDao(JanusGraphDao janusGraphDao) { this.janusGraphDao = janusGraphDao; } @Autowired public void setApplicationDataTypeCache(ApplicationDataTypeCache applicationDataTypeCache) { this.applicationDataTypeCache = applicationDataTypeCache; } @Autowired public void setJanusGraphGenericDao(JanusGraphGenericDao janusGraphGenericDao) { this.janusGraphGenericDao = janusGraphGenericDao; } @Autowired public void setGraphLockOperation(IGraphLockOperation graphLockOperation) { this.graphLockOperation = graphLockOperation; } @Autowired public void setToscaOperationFacade(ToscaOperationFacade toscaOperationFacade) { this.toscaOperationFacade = toscaOperationFacade; } @Autowired void setPolicyTypeOperation(PolicyTypeOperation policyTypeOperation) { this.policyTypeOperation = policyTypeOperation; } @Autowired public void setDataTypeCache(ApplicationDataTypeCache dataTypeCache) { this.dataTypeCache = dataTypeCache; } @Autowired public void setPropertyOperation(PropertyOperation propertyOperation) { this.propertyOperation = propertyOperation; } @Autowired public void setAttributeOperation(AttributeOperation attributeOperation) { this.attributeOperation = attributeOperation; } User validateUserNotEmpty(User user, String ecompErrorContext) { return userValidations.validateUserNotEmpty(user, ecompErrorContext); } protected User validateUserExists(String userId) { return userValidations.validateUserExists(userId); } public User validateUserExists(User user) { return userValidations.validateUserExists(user); } ActionStatus validateUserExistsActionStatus(String userId) { return userValidations.validateUserExistsActionStatus(userId); } protected void validateUserRole(User user, List<Role> roles) { userValidations.validateUserRole(user, roles); } protected void lockComponent(Component component, String ecompErrorContext) { lockComponent(component.getUniqueId(), component, ecompErrorContext); } protected boolean isVolumeGroup(List<String> artifactsInGroup, List<ArtifactDefinition> deploymentArtifacts) { for (String artifactId : artifactsInGroup) { ArtifactDefinition artifactDef = ArtifactUtils.findArtifactInList(deploymentArtifacts, artifactId); if (artifactDef != null && artifactDef.getArtifactType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_VOL.getType())) { return true; } } return false; } protected void lockComponent(Component component, boolean shouldLock, String ecompErrorContext) { if (shouldLock) { lockComponent(component.getUniqueId(), component, ecompErrorContext); } } protected void lockComponent(String componentId, Component component, String ecompErrorContext) { ActionStatus lock = lockElement(componentId, component, ecompErrorContext); if (lock != ActionStatus.OK) { logAndThrowComponentException(lock, component.getUniqueId(), component.getName()); } } protected void lockComponent(String componentId, Component component, boolean needLock, String ecompErrorContext) { if (needLock) { lockComponent(componentId, component, ecompErrorContext); } } private ResponseFormat logAndThrowComponentException(ActionStatus status, String componentId, String name) { log.debug(FAILED_TO_LOCK_COMPONENT_ERROR, componentId, status); throw new ByActionStatusComponentException(status, name); } private ActionStatus lockElement(String componentId, Component component, String ecompErrorContext) { ComponentTypeEnum componentType = component.getComponentType(); NodeTypeEnum nodeType = componentType.getNodeType(); StorageOperationStatus lockResourceStatus = graphLockOperation.lockComponent(componentId, nodeType); if (lockResourceStatus == StorageOperationStatus.OK) { return ActionStatus.OK; } else { BeEcompErrorManager.getInstance().logBeFailedLockObjectError(ecompErrorContext, nodeType.getName(), componentId); return componentsUtils.convertFromStorageResponse(lockResourceStatus, componentType); } } protected void unlockComponent(boolean failed, Component component, boolean inTransaction) { if (component != null) { ComponentTypeEnum componentType = component.getComponentType(); NodeTypeEnum nodeType = componentType.getNodeType(); if (!inTransaction) { if (failed) { janusGraphDao.rollback(); } else { janusGraphDao.commit(); } } // unlock resource graphLockOperation.unlockComponent(component.getUniqueId(), nodeType); } else { log.debug("component is NULL"); } } protected void unlockComponent(boolean failed, Component component) { unlockComponent(failed, component, false); } void unlockComponentById(boolean failed, String componentId) { Either<Component, StorageOperationStatus> component = toscaOperationFacade.getToscaElement(componentId); if (component.isLeft()) { unlockComponent(failed, component.left().value(), false); } } <T> Boolean validateJsonBody(T bodyObject, Class<T> clazz) { if (bodyObject == null) { log.debug("Invalid JSON received for object of type {}", clazz.getSimpleName()); throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT); } else { return true; } } ComponentTypeEnum validateComponentType(String componentType) { ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType); if (componentTypeEnum == null) { log.debug("Invalid component type {}", componentType); throw new ByActionStatusComponentException(ActionStatus.UNSUPPORTED_ERROR, componentType); } else { return componentTypeEnum; } } Component validateComponentExists(String componentId, ComponentTypeEnum componentType, ComponentParametersView filter) { Either<Component, StorageOperationStatus> toscaElement = toscaOperationFacade .getToscaElement(componentId, filter == null ? new ComponentParametersView() : filter); if (toscaElement.isRight()) { handleGetComponentError(componentId, componentType, toscaElement.right().value()); } return validateComponentType(toscaElement.left().value(), componentType); } private Component validateComponentType(Component cmpt, ComponentTypeEnum componentType) { if (componentType != cmpt.getComponentType()) { log.debug("component {} is not of requested type {}", cmpt.getUniqueId(), componentType); throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(StorageOperationStatus.NOT_FOUND, componentType)); } return cmpt; } <T extends PropertyDataDefinition> String updateInputPropertyObjectValue(T property) { Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> allDataTypesEither = dataTypeCache.getAll(); if (allDataTypesEither.isRight()) { JanusGraphOperationStatus status = allDataTypesEither.right().value(); BeEcompErrorManager.getInstance() .logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR); throw new ByActionStatusComponentException( componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status))); } Map<String, DataTypeDefinition> allDataTypes = allDataTypesEither.left().value(); String propertyType = property.getType(); String innerType = getInnerType(property); // Specific Update Logic Either<Object, Boolean> isValid = propertyOperation .validateAndUpdatePropertyValue(propertyType, property.getValue(), true, innerType, allDataTypes); String newValue = property.getValue(); if (isValid.isRight()) { Boolean res = isValid.right().value(); if (Boolean.FALSE.equals(res)) { throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse( DaoStatusConverter.convertJanusGraphStatusToStorageStatus(JanusGraphOperationStatus.ILLEGAL_ARGUMENT))); } } else { Object object = isValid.left().value(); if (object != null) { newValue = object.toString(); } } return newValue; } <T extends PropertyDataDefinition> String getInnerType(T property) { ToscaPropertyType type = ToscaPropertyType.isValidType(property.getType()); log.debug("#getInnerType - The type of the property {} is {}", property.getUniqueId(), property.getType()); String innerType = null; if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) { if (property.getSchema() == null) { log.debug(SCHEMA_DOESN_T_EXISTS_FOR_PROPERTY_OF_TYPE, type); throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)); } PropertyDataDefinition innerProperty = property.getSchema().getProperty(); if (innerProperty == null) { log.debug(PROPERTY_IN_SCHEMA_DEFINITION_INSIDE_PROPERTY_OF_TYPE_DOESN_T_EXIST, type); throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)); } innerType = innerProperty.getType(); } return innerType; } public void validateCanWorkOnComponent(Component component, String userId) { ActionStatus actionStatus = ActionStatus.RESTRICTED_OPERATION; // verify resource is not archived if (Boolean.TRUE.equals(component.isArchived())) { actionStatus = ActionStatus.COMPONENT_IS_ARCHIVED; throw new ByActionStatusComponentException(actionStatus, component.getName()); } if (component.getLifecycleState() != LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT) { log.debug("Component {} is not checked-out", component.getName()); throw new ByActionStatusComponentException(actionStatus); } // verify userId is not null if (userId == null) { log.debug("Current user userId is null"); throw new ByActionStatusComponentException(actionStatus); } // verify component last update user is the current user String lastUpdaterUserId = component.getLastUpdaterUserId(); if (!userId.equals(lastUpdaterUserId)) { log.debug("Current user is not last updater, last updater userId: {}, current user userId: {}", lastUpdaterUserId, userId); throw new ByActionStatusComponentException(actionStatus); } // verify resource is not deleted if (Boolean.TRUE.equals(component.getIsDeleted())) { log.debug("Component {} is marked as deleted", component.getUniqueId()); throw new ByActionStatusComponentException(actionStatus); } } ComponentTypeEnum getComponentTypeByParentComponentType(ComponentTypeEnum parentComponentType) { switch (parentComponentType) { case SERVICE: case RESOURCE: return ComponentTypeEnum.RESOURCE; case PRODUCT: return ComponentTypeEnum.SERVICE; default: break; } return null; } protected Map<String, DataTypeDefinition> getAllDataTypes(ApplicationDataTypeCache applicationDataTypeCache) { Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> allDataTypes = applicationDataTypeCache.getAll(); if (allDataTypes.isRight()) { JanusGraphOperationStatus operationStatus = allDataTypes.right().value(); if (operationStatus == JanusGraphOperationStatus.NOT_FOUND) { BeEcompErrorManager.getInstance().logInternalDataError("FetchDataTypes", "Data types are not loaded", ErrorSeverity.ERROR); throw new ByActionStatusComponentException(ActionStatus.DATA_TYPE_CANNOT_BE_EMPTY); } else { BeEcompErrorManager.getInstance().logInternalFlowError("FetchDataTypes", "Failed to fetch data types", ErrorSeverity.ERROR); throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR); } } return allDataTypes.left().value(); } Either<Boolean, ResponseFormat> validatePropertyDefaultValue(IComplexDefaultValue property, Map<String, DataTypeDefinition> dataTypes) { String type; String innerType = null; if (!propertyOperation.isPropertyTypeValid(property, null)) { log.info("Invalid type for property '{}' type '{}'", property.getName(), property.getType()); ResponseFormat responseFormat = componentsUtils .getResponseFormat(ActionStatus.INVALID_PROPERTY_TYPE, property.getType(), property.getName()); return Either.right(responseFormat); } type = property.getType(); if (type.equals(ToscaPropertyType.LIST.getType()) || type.equals(ToscaPropertyType.MAP.getType())) { ImmutablePair<String, Boolean> propertyInnerTypeValid = propertyOperation.isPropertyInnerTypeValid(property, dataTypes); innerType = propertyInnerTypeValid.getLeft(); if (Boolean.FALSE.equals(propertyInnerTypeValid.getRight())) { log.info("Invalid inner type for property '{}' type '{}', dataTypeCount '{}'", property.getName(), property.getType(), dataTypes.size()); ResponseFormat responseFormat = componentsUtils .getResponseFormat(ActionStatus.INVALID_PROPERTY_INNER_TYPE, innerType, property.getName()); return Either.right(responseFormat); } } if (!propertyOperation.isPropertyDefaultValueValid(property, dataTypes)) { log.info("Invalid default value for property '{}' type '{}'", property.getName(), property.getType()); ResponseFormat responseFormat; if (type.equals(ToscaPropertyType.LIST.getType()) || type.equals(ToscaPropertyType.MAP.getType())) { responseFormat = componentsUtils .getResponseFormat(ActionStatus.INVALID_COMPLEX_DEFAULT_VALUE, property.getName(), type, innerType, property.getDefaultValue()); } else { responseFormat = componentsUtils .getResponseFormat(ActionStatus.INVALID_DEFAULT_VALUE, property.getName(), type, property.getDefaultValue()); } return Either.right(responseFormat); } return Either.left(true); } void validateComponentTypeEnum(ComponentTypeEnum componentTypeEnum, String errorContext, Wrapper<ResponseFormat> errorWrapper) { if (componentTypeEnum == null) { BeEcompErrorManager.getInstance().logInvalidInputError(errorContext, "invalid component type", ErrorSeverity.INFO); errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED)); } } protected void validateCanWorkOnComponent(String componentId, ComponentTypeEnum componentTypeEnum, String userId, Wrapper<ResponseFormat> errorWrapper) { if (!ComponentValidationUtils.canWorkOnComponent(componentId, toscaOperationFacade, userId)) { log.info("Restricted operation for user {} on {} {}", userId, componentTypeEnum.getValue(), componentId); errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); } } void validateComponentLock(String componentId, ComponentTypeEnum componentTypeEnum, Wrapper<ResponseFormat> errorWrapper) { StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType()); if (lockStatus != StorageOperationStatus.OK) { log.debug("Failed to lock {} {}", componentTypeEnum.getValue(), componentId); errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus))); } } protected ToscaPropertyType getType(String propertyType) { return ToscaPropertyType.isValidType(propertyType); } void commitOrRollback(Either<?, ResponseFormat> result) { if (result == null || result.isRight()) { log.warn("operation failed. do rollback"); janusGraphDao.rollback(); } else { log.debug("operation success. do commit"); janusGraphDao.commit(); } } protected Either<Boolean, ResponseFormat> lockComponentByName(String name, Component component, String ecompErrorContext) { ComponentTypeEnum componentType = component.getComponentType(); NodeTypeEnum nodeType = componentType.getNodeType(); StorageOperationStatus lockResourceStatus = graphLockOperation.lockComponentByName(name, nodeType); if (lockResourceStatus == StorageOperationStatus.OK) { return Either.left(true); } else { BeEcompErrorManager.getInstance().logBeFailedLockObjectError(ecompErrorContext, nodeType.getName(), name); ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(lockResourceStatus, componentType); ResponseFormat responseFormat = componentsUtils.getResponseFormat(actionStatus, component.getName()); log.debug(FAILED_TO_LOCK_COMPONENT_ERROR, name, actionStatus); return Either.right(responseFormat); } } protected Component validateComponentExistsByFilter(String componentId, ComponentTypeEnum componentType, ComponentParametersView componentParametersView) { return toscaOperationFacade.getToscaElement(componentId, componentParametersView).left() .on(err -> handleGetComponentError(componentId, componentType, err)); } private Component handleGetComponentError(String componentId, ComponentTypeEnum componentType, StorageOperationStatus getComponentError) { ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentError, componentType); log.debug("error fetching component with id {}. error status: {}", componentId, getComponentError); throw new ByActionStatusComponentException(actionStatus, componentId); } String validatePropValueBeforeCreate(IPropertyInputCommon property, String value, boolean isValidate, Map<String, DataTypeDefinition> allDataTypes) { String propertyType = property.getType(); String updatedInnerType = updateInnerType(property); Either<Object, Boolean> isValid = validateAndUpdatePropertyValue(propertyType, value, isValidate, updatedInnerType, allDataTypes); String newValue = value; if (isValid.isRight()) { Boolean res = isValid.right().value(); if (Boolean.FALSE.equals(res)) { throw new StorageException(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(JanusGraphOperationStatus.ILLEGAL_ARGUMENT)); } } else { Object object = isValid.left().value(); if (object != null) { newValue = object.toString(); } } ImmutablePair<String, Boolean> pair = validateAndUpdateRules(propertyType, property.getRules(), updatedInnerType, allDataTypes, isValidate); log.trace("After validateAndUpdateRules. pair = {}", pair); if (Boolean.FALSE.equals(pair.getRight())) { BeEcompErrorManager.getInstance().logBeInvalidValueError(ADD_PROPERTY_VALUE, pair.getLeft(), property.getName(), propertyType); throw new StorageException(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(JanusGraphOperationStatus.ILLEGAL_ARGUMENT)); } return newValue; } private String updateInnerType(IPropertyInputCommon property) { ToscaPropertyType type = ToscaPropertyType.isValidType(property.getType()); if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) { SchemaDefinition def = property.getSchema(); if (def == null) { log.debug(SCHEMA_DOESN_T_EXISTS_FOR_PROPERTY_OF_TYPE, type); failOnIllegalArgument(); } PropertyDataDefinition propDef = def.getProperty(); if (propDef == null) { log.debug(PROPERTY_IN_SCHEMA_DEFINITION_INSIDE_PROPERTY_OF_TYPE_DOESN_T_EXIST, type); failOnIllegalArgument(); } return propDef.getType(); } return null; } private void failOnIllegalArgument() { throw new ByActionStatusComponentException(componentsUtils .convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(JanusGraphOperationStatus.ILLEGAL_ARGUMENT))); } public Either<Object, Boolean> validateAndUpdatePropertyValue(String propertyType, String value, boolean isValidate, String innerType, Map<String, DataTypeDefinition> dataTypes) { log.trace("Going to validate property value and its type. type = {}, value = {}", propertyType, value); ToscaPropertyType type = getType(propertyType); if (isValidate) { if (type == null) { DataTypeDefinition dataTypeDefinition = dataTypes.get(propertyType); ImmutablePair<JsonElement, Boolean> validateResult = dataTypeValidatorConverter .validateAndUpdate(value, dataTypeDefinition, dataTypes); if (Boolean.FALSE.equals(validateResult.right)) { log.debug(THE_VALUE_OF_PROPERTY_FROM_TYPE_IS_INVALID, value, propertyType); return Either.right(false); } JsonElement jsonElement = validateResult.left; String valueFromJsonElement = getValueFromJsonElement(jsonElement); return Either.left(valueFromJsonElement); } log.trace("before validating property type {}", propertyType); boolean isValidProperty = isValidValue(type, value, innerType, dataTypes); if (!isValidProperty) { log.debug(THE_VALUE_OF_PROPERTY_FROM_TYPE_IS_INVALID, value, type); return Either.right(false); } } Object convertedValue = value; if (!isEmptyValue(value) && isValidate) { PropertyValueConverter converter = type.getConverter(); convertedValue = converter.convert(value, innerType, dataTypes); } return Either.left(convertedValue); } private ImmutablePair<String, Boolean> validateAndUpdateRules(String propertyType, List<PropertyRule> rules, String innerType, Map<String, DataTypeDefinition> dataTypes, boolean isValidate) { if (rules == null || rules.isEmpty()) { return ImmutablePair.of(null, true); } for (PropertyRule rule : rules) { String value = rule.getValue(); Either<Object, Boolean> updateResult = validateAndUpdatePropertyValue(propertyType, value, isValidate, innerType, dataTypes); if (updateResult.isRight()) { Boolean status = updateResult.right().value(); if (Boolean.FALSE.equals(status)) { return ImmutablePair.of(value, status); } } else { String newValue = null; Object object = updateResult.left().value(); if (object != null) { newValue = object.toString(); } rule.setValue(newValue); } } return ImmutablePair.of(null, true); } protected boolean isValidValue(ToscaPropertyType type, String value, String innerType, Map<String, DataTypeDefinition> dataTypes) { if (isEmptyValue(value)) { return true; } PropertyTypeValidator validator = type.getValidator(); return validator.isValid(value, innerType, dataTypes); } public boolean isEmptyValue(String value) { return value == null; } protected String getValueFromJsonElement(JsonElement jsonElement) { if (jsonElement == null || jsonElement.isJsonNull()) { return EMPTY_VALUE; } if (jsonElement.toString().isEmpty()) { return ""; } return jsonElement.toString(); } protected void rollbackWithException(ActionStatus actionStatus, String... params) { janusGraphDao.rollback(); throw new ByActionStatusComponentException(actionStatus, params); } public <T extends ToscaDataDefinition> Either<List<T>, ResponseFormat> declareProperties(final String userId, final String componentId, final ComponentTypeEnum componentTypeEnum, final ComponentInstInputsMap componentInstInputsMap) { return Either.left(new ArrayList<>()); } public <T extends ToscaDataDefinition> Either<List<T>, ResponseFormat> declareAttributes(final String userId, final String componentId, final ComponentTypeEnum componentTypeEnum, final ComponentInstOutputsMap componentInstOutputsMap) { return Either.left(new ArrayList<>()); } public <T extends PropertyDataDefinition> List<PropertyConstraint> setInputConstraint(T inputDefinition) { if (StringUtils.isNotBlank(inputDefinition.getParentPropertyType()) && StringUtils.isNotBlank(inputDefinition.getSubPropertyInputPath())) { return setConstraint(inputDefinition); } return Collections.emptyList(); } private <T extends PropertyDataDefinition> List<PropertyConstraint> setConstraint(T inputDefinition) { List<PropertyConstraint> constraints = new ArrayList<>(); String[] inputPathArr = inputDefinition.getSubPropertyInputPath().split("#"); if (inputPathArr.length > 1) { inputPathArr = ArrayUtils.remove(inputPathArr, 0); } Map<String, DataTypeDefinition> dataTypeDefinitionMap = applicationDataTypeCache.getAll().left().value(); String propertyType = inputDefinition.getParentPropertyType(); for (String anInputPathArr : inputPathArr) { if (ToscaType.isPrimitiveType(propertyType)) { constraints.addAll(dataTypeDefinitionMap.get(propertyType).getConstraints()); } else if (!ToscaType.isCollectionType(propertyType)) { propertyType = setConstraintForComplexType(dataTypeDefinitionMap, propertyType, anInputPathArr, constraints); } } return constraints; } private String setConstraintForComplexType(Map<String, DataTypeDefinition> dataTypeDefinitionMap, String propertyType, String anInputPathArr, List<PropertyConstraint> constraints) { String type = null; List<PropertyDefinition> propertyDefinitions = dataTypeDefinitionMap.get(propertyType).getProperties(); for (PropertyDefinition propertyDefinition : propertyDefinitions) { if (propertyDefinition.getName().equals(anInputPathArr)) { if (ToscaType.isPrimitiveType(propertyDefinition.getType())) { constraints.addAll(propertyDefinition.safeGetConstraints()); } else { type = propertyDefinition.getType(); } break; } } return type; } protected void unlockRollbackWithException(Component component, RuntimeException e) { janusGraphDao.rollback(); graphLockOperation.unlockComponent(component.getUniqueId(), component.getComponentType().getNodeType()); throw e; } protected void unlockWithCommit(Component component) { ComponentTypeEnum componentType = component.getComponentType(); NodeTypeEnum nodeType = componentType.getNodeType(); janusGraphDao.commit(); graphLockOperation.unlockComponent(component.getUniqueId(), nodeType); } protected ComponentInstance componentInstanceException(StorageOperationStatus storageOperationStatus) { throw new StorageException(storageOperationStatus); } protected Component componentException(StorageOperationStatus storageOperationStatus) { throw new StorageException(storageOperationStatus); } protected PolicyDefinition componentExceptionPolicyDefinition(ResponseFormat responseFormat) { throw new ByResponseFormatComponentException(responseFormat); } protected List<ComponentInstanceProperty> componentInstancePropertyListException(StorageOperationStatus storageOperationStatus) { throw new StorageException(storageOperationStatus); } protected Component getComponent(final String componentId) throws BusinessLogicException { final Either<Component, StorageOperationStatus> result = toscaOperationFacade.getToscaElement(componentId); if (result.isRight()) { final StorageOperationStatus errorStatus = result.right().value(); log.error(BUSINESS_PROCESS_ERROR, this.getClass().getName(), "Failed to fetch component information by component id, error {}", errorStatus); throw new BusinessLogicException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(errorStatus))); } return result.left().value(); } }
package io.proximax.app.recovery; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import io.reactivex.Observable; import io.vertx.core.json.JsonArray; import io.vertx.core.json.JsonObject; import io.vertx.reactivex.core.Vertx; import io.vertx.reactivex.ext.web.client.HttpResponse; import io.vertx.reactivex.ext.web.client.WebClient; import io.vertx.reactivex.ext.web.codec.BodyCodec; import java.net.MalformedURLException; import java.net.URL; /** * * @author thcao */ public class ProxiLicenseHttp { protected final WebClient client; protected final URL url; protected final ObjectMapper objectMapper = new ObjectMapper(); public ProxiLicenseHttp(String host) throws MalformedURLException { this.url = new URL(host); final Vertx vertx = Vertx.vertx(); this.client = WebClient.create(vertx); objectMapper.configure(DeserializationFeature.USE_LONG_FOR_INTS, true); objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); } static JsonObject mapJsonObjectOrError(final HttpResponse<JsonObject> response) { if (response.statusCode() < 200 || response.statusCode() > 299) { throw new RuntimeException(response.statusMessage()); } return response.body(); } static JsonArray mapJsonArrayOrError(final HttpResponse<JsonArray> response) { if (response.statusCode() < 200 || response.statusCode() > 299) { throw new RuntimeException(response.statusMessage()); } return response.body(); } public Observable<AccountInfo> getAccountInfo(String email) { return this.client .getAbs(this.url + "/api/recovery/get?email=" + email) .as(BodyCodec.jsonObject()) .rxSend() .toObservable() .map(ProxiLicenseHttp::mapJsonObjectOrError) .map(json -> objectMapper.readValue(json.toString(), AccountInfoDTO.class)) .map(AccountInfoDTO::getAccountInfo); } public Observable<AccountStatus> saveAccountInfo(AccountInfo account) { JsonObject requestBody = JsonObject.mapFrom(account); return this.client .postAbs(this.url + "/api/recovery/save") .as(BodyCodec.jsonObject()) .rxSendJson(requestBody) .toObservable() .map(ProxiLicenseHttp::mapJsonObjectOrError) .map(json -> objectMapper.readValue(json.toString(), AccountStatusDTO.class)) .map(AccountStatusDTO::getAccountStatus); } }
package com.jagex; import java.awt.Component; import java.awt.Graphics; import java.awt.Image; import java.awt.image.ColorModel; import java.awt.image.DirectColorModel; import java.awt.image.ImageConsumer; import java.awt.image.ImageObserver; import java.awt.image.ImageProducer; import sign.signlink; public class Class34 implements ImageProducer, ImageObserver { public int anInt581; public int anIntArray582[]; public int anInt583; public int anInt584; public ColorModel aColorModel585; public ImageConsumer anImageConsumer586; public Image anImage587; public Class34(Component component, int i, int j, int k) { anInt581 = 831; try { anInt583 = i; anInt584 = j; anIntArray582 = new int[i * j]; aColorModel585 = new DirectColorModel(32, 0xff0000, 65280, 255); anImage587 = component.createImage(this); method274(); if(k < 2 || k > 2) { anInt581 = 205; } component.prepareImage(anImage587, this); method274(); component.prepareImage(anImage587, this); method274(); component.prepareImage(anImage587, this); method272((byte)5); return; } catch(RuntimeException runtimeexception) { signlink.reporterror("48102, " + component + ", " + i + ", " + j + ", " + k + ", " + runtimeexception.toString()); } throw new RuntimeException(); } public void method272(byte byte0) { try { DrawingArea.method406(-78, anIntArray582, anInt583, anInt584); if(byte0 != 5) { return; } } catch(RuntimeException runtimeexception) { signlink.reporterror("43640, " + byte0 + ", " + runtimeexception.toString()); throw new RuntimeException(); } } public void method273(int i, int j, int k, Graphics g) { try { method274(); while(i >= 0) { for(int l = 1; l > 0; l++) { } } g.drawImage(anImage587, j, k, this); return; } catch(RuntimeException runtimeexception) { signlink.reporterror("14457, " + i + ", " + j + ", " + k + ", " + g + ", " + runtimeexception.toString()); } throw new RuntimeException(); } public synchronized void addConsumer(ImageConsumer imageconsumer) { anImageConsumer586 = imageconsumer; imageconsumer.setDimensions(anInt583, anInt584); imageconsumer.setProperties(null); imageconsumer.setColorModel(aColorModel585); imageconsumer.setHints(14); } public synchronized boolean isConsumer(ImageConsumer imageconsumer) { return anImageConsumer586 == imageconsumer; } public synchronized void removeConsumer(ImageConsumer imageconsumer) { if(anImageConsumer586 == imageconsumer) { anImageConsumer586 = null; } } public void startProduction(ImageConsumer imageconsumer) { addConsumer(imageconsumer); } public void requestTopDownLeftRightResend(ImageConsumer imageconsumer) { System.out.println("TDLR"); } public synchronized void method274() { if(anImageConsumer586 == null) { return; } else { anImageConsumer586.setPixels(0, 0, anInt583, anInt584, aColorModel585, anIntArray582, 0, anInt583); anImageConsumer586.imageComplete(2); return; } } public boolean imageUpdate(Image image, int i, int j, int k, int l, int i1) { return true; } }
package main.sono.ops; import java.util.ArrayList; import java.util.List; import main.phl.Matrix; import main.phl.Phone; import main.sono.Datum; import main.sono.Interpreter; import main.sono.Operator; import main.sono.Scope; import main.sono.Token; public class Find extends Binary { public Find(final Interpreter interpreter, final Token line, final Operator a, final Operator b) { super(interpreter, Type.FIND, line, a, b); } @Override public Datum evaluate(final Scope scope, final Object[] overrides) throws InterruptedException { checkInterrupted(); final Matrix matrix = a.evaluate(scope, overrides).getMatrix(line, overrides); final Datum datumB = b.evaluate(scope, overrides); final int dataSize = datumB.getVectorLength(line, overrides); final List<Phone> phones = new ArrayList<>(); for (int i = 0; i < dataSize; i++) phones.add(datumB.indexVector(i).getPhone(line, overrides)); final List<Phone> list = interpreter.getManager().getPhones(phones, matrix); final Datum[] newData = new Datum[list.size()]; for (int i = 0; i < list.size(); i++) newData[i] = new Datum(list.get(i)); return new Datum(newData); } @Override public String toString() { return "find " + a.toString(); } }
package com.tg.tgt.ui; import android.app.ProgressDialog; import android.graphics.Color; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.hyphenate.chat.EMClient; import com.tg.tgt.DemoHelper; import com.tg.tgt.R; public class OfflinePushNickActivity extends BaseActivity { private EditText inputNickName; private TextView nicknameDescription; private ProgressDialog dialog; @Override protected void onCreate(Bundle arg0) { // TODO Auto-generated method stub super.onCreate(arg0); setContentView(R.layout.em_activity_offline_push); inputNickName = (EditText) findViewById(R.id.et_input_nickname); Button saveNickName = (Button) findViewById(R.id.btn_save); nicknameDescription = (TextView) findViewById(R.id.tv_nickname_description); saveNickName.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub dialog = ProgressDialog.show(OfflinePushNickActivity.this, "update nickname...", "waiting..."); new Thread(new Runnable() { @Override public void run() { // TODO Auto-generated method stub boolean updatenick = EMClient.getInstance().pushManager().updatePushNickname( inputNickName.getText().toString()); if (!updatenick) { runOnUiThread(new Runnable() { public void run() { Toast.makeText(OfflinePushNickActivity.this, "update nickname failed!", Toast.LENGTH_SHORT).show(); dialog.dismiss(); } }); } else { runOnUiThread(new Runnable() { public void run() { boolean updatenick = DemoHelper.getInstance().getUserProfileManager().updateCurrentUserNickName(inputNickName.getText().toString()); if (!updatenick) { Toast.makeText(OfflinePushNickActivity.this, "update nickname failed!", Toast.LENGTH_SHORT).show(); dialog.dismiss(); } else { dialog.dismiss(); Toast.makeText(OfflinePushNickActivity.this, "update nickname success!", Toast.LENGTH_SHORT).show(); } } }); finish(); } } }).start(); } }); inputNickName.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { // TODO Auto-generated method stub if (s.toString().length() > 0) { nicknameDescription.setTextColor(Color.RED); }else{ nicknameDescription.setTextColor(Color.parseColor("#cccccc")); } } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { // TODO Auto-generated method stub } @Override public void afterTextChanged(Editable s) { // TODO Auto-generated method stub } }); } }
package com.github.wkennedy.pubsubly.plugins; import com.github.wkennedy.pubsubly.api.Processor; import com.github.wkennedy.pubsubly.api.Tag; import org.springframework.messaging.Message; import org.springframework.messaging.MessageHeaders; import org.springframework.messaging.handler.annotation.Headers; import org.springframework.plugin.core.Plugin; import org.springframework.stereotype.Component; @Component public class HeaderProcessorPlugin implements Plugin<String>, Processor { public String process(Message message, @Headers MessageHeaders headers, Tag tag) { if(headers.containsKey(tag.getValue())) { return (String) headers.get(tag.getValue()); } return null; } public String getName() { return HeaderProcessorPlugin.class.getSimpleName(); } public String getVersion() { return "1.0.0"; } public boolean supports(String delimiter) { return true; } }
/* * Copyright 2009 Ronnie Kolehmainen * * 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.googlecode.intelliguard.ui; import com.intellij.openapi.module.Module; import javax.swing.*; import javax.swing.filechooser.FileFilter; import java.io.File; import org.jetbrains.annotations.NotNull; /** * Created by IntelliJ IDEA. * User: Ronnie * Date: 2009-nov-01 * Time: 11:22:50 */ public class FileChooserFactory { /** * Creates a filechooser for saving jar files. * @param preferredDirectory the preferred 'current' directory/directories, in order. The first * usable directory will be used as current directory. * @return a filechooser instance */ public static JFileChooser createSaveJarChooser(String... preferredDirectory) { JFileChooser jFileChooser = new JFileChooser(); FileFilter fileFilter = new FileFilter() { @Override public boolean accept(File f) { return f.isDirectory() || f.getName().endsWith(".jar"); } @Override public String getDescription() { return "Archive files"; } }; jFileChooser.setFileFilter(fileFilter); setPreferedDirectory(jFileChooser, preferredDirectory); jFileChooser.setDialogTitle("Save Jar File"); return jFileChooser; } public static JFileChooser createPreferredDirectoryFileChooser(String dialogTitle, String... preferredDirectory) { JFileChooser jFileChooser = new JFileChooser(); setPreferedDirectory(jFileChooser, preferredDirectory); jFileChooser.setDialogTitle(dialogTitle); return jFileChooser; } private static void setPreferedDirectory(JFileChooser jFileChooser, String... preferredDirectory) { for (String f : preferredDirectory) { File file = new File(f); if (file.exists()) { jFileChooser.setCurrentDirectory(file); return; } } } public static JFileChooser createFindJarChooser(String... preferredDirectory) { final JFileChooser jFileChooser = createSaveJarChooser(preferredDirectory); jFileChooser.setDialogTitle("Open Jar File"); return jFileChooser; } /** * Creates a filechooser for files and directories within the <i>module</i>.<br> * The filechooser created prohibits ascending to a directory above the module directory.<br> * @param module the module * @return a filechooser instance */ public static JFileChooser createModuleFileChooser(@NotNull final Module module) { String moduleFilePath = module.getModuleFilePath(); final File moduleDirectory = new File(moduleFilePath).getParentFile(); JFileChooser jFileChooser = new JFileChooser() { @Override public void changeToParentDirectory() { if (getCurrentDirectory().equals(moduleDirectory)) { return; } super.changeToParentDirectory(); } }; jFileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES); jFileChooser.setDialogTitle("Choose File or Directory"); jFileChooser.setCurrentDirectory(moduleDirectory); return jFileChooser; } }
package com.archinamon.libinstantparcelable.parcel.errors; /** * TODO: Add destription * * @author archinamon on 11/05/16. */ public final class NoDefaultConstructorException extends RuntimeException { private static final String EXCEPTION_TEXT = "No valid default constructor provided for @Parcelable extension"; public NoDefaultConstructorException() { super(EXCEPTION_TEXT); } }
package com.ke.schedule.basic.model; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import java.io.Serializable; import java.util.Map; public @NoArgsConstructor @Getter @Setter class ClientPath implements Serializable { private String ip; private String identification; private String projectCode; private Map<String, String> tasks; public ClientPath(String ip, String identification, String projectCode, Map<String, String> tasks) { this.ip = ip; this.identification = identification; this.projectCode = projectCode; this.tasks = tasks; } public int getTaskSize() { return tasks == null ? 0 : tasks.size(); } public String getTasksDesc() { if (tasks == null) { return ""; } else { StringBuffer desc = new StringBuffer(); tasks.forEach((k, v) -> desc.append("key:" + k + " &nbsp; &nbsp; &nbsp; &nbsp; remark:" + v)); return desc.toString(); } } }
package controller.admin; import form.AdminForm; import io.github.yedaxia.apidocs.ApiDoc; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import result.user.AdminVO; import java.util.List; import java.util.Map; /** * 演示一些比较特殊的声明方法 * * @description 管理员接口 * @author yeguozhong yedaxia.github.com */ @Controller public class AdminController { /** * 管理员登录 * @param name 登录名 * @param password 密码 */ @RequestMapping(path = "/api/v1/admin/login", method = RequestMethod.GET) @ApiDoc(result = AdminVO.class, url = "/api/v1/admin/login2", method = "post") public void login(@RequestParam String name, @RequestParam String password){ } /** * 邮箱登录 * @param email * @param password */ @RequestMapping(path = "/api/v1/admin/emailLogin", method = RequestMethod.POST) @ApiDoc(AdminVO.class) @Deprecated public void emailLogin(@RequestParam(name = "email", required = true) String email, String password){ } /** * 添加管理员 * * @param adminForm 管理员信息 */ @PostMapping("/api/v1/admin/add") @ApiDoc(AdminVO.class) public void addAdmin(@RequestBody(required = false) AdminForm adminForm){ } /** * 添加多个管理员 * * @param adminForms 管理员信息 */ @PostMapping("/api/v1/admin/addMany") @ApiDoc(AdminVO[].class) public void addAdmins(@RequestBody List<AdminForm> adminForms){ } /** * 测试map * @return */ @ApiDoc @RequestMapping("test-map") public Map<String, Object> testMap(){ return null; } }