text
stringlengths 7
1.01M
|
|---|
/*
*
* * *****************************************************************************
* * Copyright (C) 2020 Testsigma Technologies Inc.
* * All rights reserved.
* * ****************************************************************************
*
*/
package com.testsigma.tasks;
import com.testsigma.model.TestCaseResult;
import com.testsigma.service.VisualTestingService;
import lombok.extern.log4j.Log4j2;
@Log4j2
public class VisualTestingTask extends Thread {
private final TestCaseResult testCaseResult;
private final VisualTestingService visualTestingService;
public VisualTestingTask(TestCaseResult testCaseResult, VisualTestingService visualTestingService) {
this.testCaseResult = testCaseResult;
this.visualTestingService = visualTestingService;
}
@Override
public void run() {
try {
this.visualTestingService.initScreenshotComparison(testCaseResult);
} catch (Exception e) {
log.error(e.getMessage(), e);
log.error("Exception while handling ImageComparison for testCaseResult:" + testCaseResult, e);
}
}
}
|
package servlet;
import dao.MysqlDB;
import redis.clients.jedis.Jedis;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* Created by kunqi
* ON Apr/18/2019 16:57
*/
public class FeedServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try{
HttpSession session = request.getSession();
int user_id = Integer.valueOf(session.getAttribute("user_id").toString());
String statue = request.getParameter("statue");
String sql = "INSERT into statues (user_id, statue) values (?,?)";
MysqlDB.insertStatue(sql,user_id,statue);
sql = "select id from statues order by id desc limit 1";
ResultSet rs = MysqlDB.query(sql);
rs.first();
int record_id = rs.getInt("id");
sql = "INSERT into events (user_id, operation, table_name, record_id, type) values (?,?,?,?,?)";
MysqlDB.insertEvent(sql,user_id,"insert","statues",record_id,"createStatue");
sql = "select id from events order by id desc limit 1";
rs = MysqlDB.query(sql);
rs.first();
int event_id = rs.getInt("id");
sql = "select friend_id from friends where user_id = ? and is_faked = 0 and is_blocked = 0";
rs = MysqlDB.queryFriends(sql,user_id);
sql = "insert into follow_feeds (user_id,event_id) values(?,?)";
Jedis jedis = new Jedis("localhost");
while(rs.next()){
int friend_id = rs.getInt("friend_id");
String key = "follower_id_" + friend_id;
jedis.lpush(key,String.valueOf(event_id));
MysqlDB.insertFollowFeed(sql, friend_id, event_id);
}
RequestDispatcher rd = request.getRequestDispatcher("/index.jsp");
rd.forward(request,response);
}catch(SQLException e){
e.printStackTrace();
};
}
}
|
/*
* 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.cluster.routing.allocation;
import org.elasticsearch.Version;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.metadata.IndexMetaData;
import org.elasticsearch.cluster.metadata.MetaData;
import org.elasticsearch.cluster.node.DiscoveryNodes;
import org.elasticsearch.cluster.routing.RoutingNodes;
import org.elasticsearch.cluster.routing.RoutingTable;
import org.elasticsearch.common.logging.ESLogger;
import org.elasticsearch.common.logging.Loggers;
import org.elasticsearch.test.ESAllocationTestCase;
import static org.elasticsearch.cluster.routing.ShardRoutingState.INITIALIZING;
import static org.elasticsearch.cluster.routing.ShardRoutingState.STARTED;
import static org.elasticsearch.cluster.routing.ShardRoutingState.UNASSIGNED;
import static org.elasticsearch.common.settings.Settings.settingsBuilder;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.nullValue;
/**
*
*/
public class SingleShardOneReplicaRoutingTests extends ESAllocationTestCase {
private final ESLogger logger = Loggers.getLogger(SingleShardOneReplicaRoutingTests.class);
public void testSingleIndexFirstStartPrimaryThenBackups() {
AllocationService strategy = createAllocationService(settingsBuilder().put("cluster.routing.allocation.node_concurrent_recoveries", 10).build());
logger.info("Building initial routing table");
MetaData metaData = MetaData.builder()
.put(IndexMetaData.builder("test").settings(settings(Version.CURRENT)).numberOfShards(1).numberOfReplicas(1))
.build();
RoutingTable routingTable = RoutingTable.builder()
.addAsNew(metaData.index("test"))
.build();
ClusterState clusterState = ClusterState.builder(org.elasticsearch.cluster.ClusterName.DEFAULT).metaData(metaData).routingTable(routingTable).build();
assertThat(routingTable.index("test").shards().size(), equalTo(1));
assertThat(routingTable.index("test").shard(0).size(), equalTo(2));
assertThat(routingTable.index("test").shard(0).shards().size(), equalTo(2));
assertThat(routingTable.index("test").shard(0).shards().get(0).state(), equalTo(UNASSIGNED));
assertThat(routingTable.index("test").shard(0).shards().get(1).state(), equalTo(UNASSIGNED));
assertThat(routingTable.index("test").shard(0).shards().get(0).currentNodeId(), nullValue());
assertThat(routingTable.index("test").shard(0).shards().get(1).currentNodeId(), nullValue());
logger.info("Adding one node and performing rerouting");
clusterState = ClusterState.builder(clusterState).nodes(DiscoveryNodes.builder().put(newNode("node1"))).build();
RoutingTable prevRoutingTable = routingTable;
routingTable = strategy.reroute(clusterState, "reroute").routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
assertThat(prevRoutingTable != routingTable, equalTo(true));
assertThat(routingTable.index("test").shards().size(), equalTo(1));
assertThat(routingTable.index("test").shard(0).size(), equalTo(2));
assertThat(routingTable.index("test").shard(0).shards().size(), equalTo(2));
assertThat(routingTable.index("test").shard(0).primaryShard().state(), equalTo(INITIALIZING));
assertThat(routingTable.index("test").shard(0).primaryShard().currentNodeId(), equalTo("node1"));
assertThat(routingTable.index("test").shard(0).replicaShards().size(), equalTo(1));
assertThat(routingTable.index("test").shard(0).replicaShards().get(0).state(), equalTo(UNASSIGNED));
assertThat(routingTable.index("test").shard(0).replicaShards().get(0).currentNodeId(), nullValue());
logger.info("Add another node and perform rerouting, nothing will happen since primary shards not started");
clusterState = ClusterState.builder(clusterState).nodes(DiscoveryNodes.builder(clusterState.nodes()).put(newNode("node2"))).build();
prevRoutingTable = routingTable;
routingTable = strategy.reroute(clusterState, "reroute").routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
assertThat(prevRoutingTable == routingTable, equalTo(true));
logger.info("Start the primary shard (on node1)");
RoutingNodes routingNodes = clusterState.getRoutingNodes();
prevRoutingTable = routingTable;
routingTable = strategy.applyStartedShards(clusterState, routingNodes.node("node1").shardsWithState(INITIALIZING)).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
assertThat(prevRoutingTable != routingTable, equalTo(true));
assertThat(routingTable.index("test").shards().size(), equalTo(1));
assertThat(routingTable.index("test").shard(0).size(), equalTo(2));
assertThat(routingTable.index("test").shard(0).shards().size(), equalTo(2));
assertThat(routingTable.index("test").shard(0).primaryShard().state(), equalTo(STARTED));
assertThat(routingTable.index("test").shard(0).primaryShard().currentNodeId(), equalTo("node1"));
assertThat(routingTable.index("test").shard(0).replicaShards().size(), equalTo(1));
// backup shards are initializing as well, we make sure that they recover from primary *started* shards in the IndicesClusterStateService
assertThat(routingTable.index("test").shard(0).replicaShards().get(0).state(), equalTo(INITIALIZING));
assertThat(routingTable.index("test").shard(0).replicaShards().get(0).currentNodeId(), equalTo("node2"));
logger.info("Reroute, nothing should change");
prevRoutingTable = routingTable;
routingTable = strategy.reroute(clusterState, "reroute").routingTable();
assertThat(prevRoutingTable == routingTable, equalTo(true));
logger.info("Start the backup shard");
routingNodes = clusterState.getRoutingNodes();
prevRoutingTable = routingTable;
routingTable = strategy.applyStartedShards(clusterState, routingNodes.node("node2").shardsWithState(INITIALIZING)).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
assertThat(prevRoutingTable != routingTable, equalTo(true));
assertThat(routingTable.index("test").shards().size(), equalTo(1));
assertThat(routingTable.index("test").shard(0).size(), equalTo(2));
assertThat(routingTable.index("test").shard(0).shards().size(), equalTo(2));
assertThat(routingTable.index("test").shard(0).primaryShard().state(), equalTo(STARTED));
assertThat(routingTable.index("test").shard(0).primaryShard().currentNodeId(), equalTo("node1"));
assertThat(routingTable.index("test").shard(0).replicaShards().size(), equalTo(1));
assertThat(routingTable.index("test").shard(0).replicaShards().get(0).state(), equalTo(STARTED));
assertThat(routingTable.index("test").shard(0).replicaShards().get(0).currentNodeId(), equalTo("node2"));
logger.info("Kill node1, backup shard should become primary");
clusterState = ClusterState.builder(clusterState).nodes(DiscoveryNodes.builder(clusterState.nodes()).remove("node1")).build();
prevRoutingTable = routingTable;
routingTable = strategy.reroute(clusterState, "reroute").routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
assertThat(prevRoutingTable != routingTable, equalTo(true));
assertThat(routingTable.index("test").shards().size(), equalTo(1));
assertThat(routingTable.index("test").shard(0).size(), equalTo(2));
assertThat(routingTable.index("test").shard(0).shards().size(), equalTo(2));
assertThat(routingTable.index("test").shard(0).primaryShard().state(), equalTo(STARTED));
assertThat(routingTable.index("test").shard(0).primaryShard().currentNodeId(), equalTo("node2"));
assertThat(routingTable.index("test").shard(0).replicaShards().size(), equalTo(1));
// backup shards are initializing as well, we make sure that they recover from primary *started* shards in the IndicesClusterStateService
assertThat(routingTable.index("test").shard(0).replicaShards().get(0).state(), equalTo(UNASSIGNED));
assertThat(routingTable.index("test").shard(0).replicaShards().get(0).currentNodeId(), nullValue());
logger.info("Start another node, backup shard should start initializing");
clusterState = ClusterState.builder(clusterState).nodes(DiscoveryNodes.builder(clusterState.nodes()).put(newNode("node3"))).build();
prevRoutingTable = routingTable;
routingTable = strategy.reroute(clusterState, "reroute").routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
assertThat(prevRoutingTable != routingTable, equalTo(true));
assertThat(routingTable.index("test").shards().size(), equalTo(1));
assertThat(routingTable.index("test").shard(0).size(), equalTo(2));
assertThat(routingTable.index("test").shard(0).shards().size(), equalTo(2));
assertThat(routingTable.index("test").shard(0).primaryShard().state(), equalTo(STARTED));
assertThat(routingTable.index("test").shard(0).primaryShard().currentNodeId(), equalTo("node2"));
assertThat(routingTable.index("test").shard(0).replicaShards().size(), equalTo(1));
// backup shards are initializing as well, we make sure that they recover from primary *started* shards in the IndicesClusterStateService
assertThat(routingTable.index("test").shard(0).replicaShards().get(0).state(), equalTo(INITIALIZING));
assertThat(routingTable.index("test").shard(0).replicaShards().get(0).currentNodeId(), equalTo("node3"));
}
}
|
package tq.character.editor.data.player.attributes;
import tq.character.editor.core.errors.IllegalPlayerDataException;
public interface IAttributesData {
Integer getCharacteristicGain();
Integer getFluidGain();
Integer getUnspentAttributePoints();
void setUnspentAttributePoints(Integer attributePoints) throws IllegalPlayerDataException;
void resetAllAttributes();
Integer getStrengthAttribute();
void setStrengthAttribute(Integer attributePoints) throws IllegalPlayerDataException;
Integer getDexterityAttribute();
void setDexterityAttribute(Integer attributePoints) throws IllegalPlayerDataException;
Integer getIntelligenceAttribute();
void setIntelligenceAttribute(Integer attributePoints) throws IllegalPlayerDataException;
Integer getHealthAttribute();
void setHealthAttribute(Integer attributePoints) throws IllegalPlayerDataException;
Integer getManaAttribute();
void setManaAttribute(Integer attributePoints) throws IllegalPlayerDataException;
}
|
/*
* Copyright 2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.an9elkiss.api.spp.service.tushare;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import com.an9elkiss.api.spp.StockProphetApiBoot;
import com.an9elkiss.api.spp.command.tushare.QuotationDailyCmd;
import com.an9elkiss.api.spp.command.tushare.TushareRespCmd;
import com.an9elkiss.api.spp.service.tushare.TushareClientService;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = { StockProphetApiBoot.class })
@AutoConfigureMockMvc
public class TushareClientServiceTests {
@Autowired
private MockMvc mockMvc;
@Autowired
private TushareClientService tushareClientService;
@Test
public void testQuotationDaily() {
QuotationDailyCmd cmd = new QuotationDailyCmd();
cmd.setTs_code("000651.SZ");
cmd.setTrade_date("20200716");
TushareRespCmd respCmd = tushareClientService.quotationDaily(cmd);
Assert.assertEquals(1, respCmd.getData().getItems().length);
Assert.assertEquals(59.0, respCmd.getData().getItems()[0][2]);
}
}
|
/*
* Copyright 2010-2012 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.autoscaling.model;
/**
* <p>
* The <code>AutoScalingInstanceDetails</code> data type.
* </p>
*/
public class AutoScalingInstanceDetails {
/**
* The instance ID of the Amazon EC2 instance.
* <p>
* <b>Constraints:</b><br/>
* <b>Length: </b>1 - 16<br/>
* <b>Pattern: </b>[\u0020-\uD7FF\uE000-\uFFFD\uD800\uDC00-\uDBFF\uDFFF\r\n\t]*<br/>
*/
private String instanceId;
/**
* The name of the Auto Scaling group associated with this instance.
* <p>
* <b>Constraints:</b><br/>
* <b>Length: </b>1 - 255<br/>
* <b>Pattern: </b>[\u0020-\uD7FF\uE000-\uFFFD\uD800\uDC00-\uDBFF\uDFFF\r\n\t]*<br/>
*/
private String autoScalingGroupName;
/**
* The Availability Zone in which this instance resides.
* <p>
* <b>Constraints:</b><br/>
* <b>Length: </b>1 - 255<br/>
* <b>Pattern: </b>[\u0020-\uD7FF\uE000-\uFFFD\uD800\uDC00-\uDBFF\uDFFF\r\n\t]*<br/>
*/
private String availabilityZone;
/**
* The life cycle state of this instance.
* <p>
* <b>Constraints:</b><br/>
* <b>Length: </b>1 - 32<br/>
* <b>Pattern: </b>[\u0020-\uD7FF\uE000-\uFFFD\uD800\uDC00-\uDBFF\uDFFF\r\n\t]*<br/>
*/
private String lifecycleState;
/**
* The health status of this instance. "Healthy" means that the instance
* is healthy and should remain in service. "Unhealthy" means that the
* instance is unhealthy. Auto Scaling should terminate and replace it.
* <p>
* <b>Constraints:</b><br/>
* <b>Length: </b>1 - 32<br/>
* <b>Pattern: </b>[\u0020-\uD7FF\uE000-\uFFFD\uD800\uDC00-\uDBFF\uDFFF\r\n\t]*<br/>
*/
private String healthStatus;
/**
* The launch configuration associated with this instance.
* <p>
* <b>Constraints:</b><br/>
* <b>Length: </b>1 - 255<br/>
* <b>Pattern: </b>[\u0020-\uD7FF\uE000-\uFFFD\uD800\uDC00-\uDBFF\uDFFF\r\n\t]*<br/>
*/
private String launchConfigurationName;
/**
* The instance ID of the Amazon EC2 instance.
* <p>
* <b>Constraints:</b><br/>
* <b>Length: </b>1 - 16<br/>
* <b>Pattern: </b>[\u0020-\uD7FF\uE000-\uFFFD\uD800\uDC00-\uDBFF\uDFFF\r\n\t]*<br/>
*
* @return The instance ID of the Amazon EC2 instance.
*/
public String getInstanceId() {
return instanceId;
}
/**
* The instance ID of the Amazon EC2 instance.
* <p>
* <b>Constraints:</b><br/>
* <b>Length: </b>1 - 16<br/>
* <b>Pattern: </b>[\u0020-\uD7FF\uE000-\uFFFD\uD800\uDC00-\uDBFF\uDFFF\r\n\t]*<br/>
*
* @param instanceId The instance ID of the Amazon EC2 instance.
*/
public void setInstanceId(String instanceId) {
this.instanceId = instanceId;
}
/**
* The instance ID of the Amazon EC2 instance.
* <p>
* Returns a reference to this object so that method calls can be chained together.
* <p>
* <b>Constraints:</b><br/>
* <b>Length: </b>1 - 16<br/>
* <b>Pattern: </b>[\u0020-\uD7FF\uE000-\uFFFD\uD800\uDC00-\uDBFF\uDFFF\r\n\t]*<br/>
*
* @param instanceId The instance ID of the Amazon EC2 instance.
*
* @return A reference to this updated object so that method calls can be chained
* together.
*/
public AutoScalingInstanceDetails withInstanceId(String instanceId) {
this.instanceId = instanceId;
return this;
}
/**
* The name of the Auto Scaling group associated with this instance.
* <p>
* <b>Constraints:</b><br/>
* <b>Length: </b>1 - 255<br/>
* <b>Pattern: </b>[\u0020-\uD7FF\uE000-\uFFFD\uD800\uDC00-\uDBFF\uDFFF\r\n\t]*<br/>
*
* @return The name of the Auto Scaling group associated with this instance.
*/
public String getAutoScalingGroupName() {
return autoScalingGroupName;
}
/**
* The name of the Auto Scaling group associated with this instance.
* <p>
* <b>Constraints:</b><br/>
* <b>Length: </b>1 - 255<br/>
* <b>Pattern: </b>[\u0020-\uD7FF\uE000-\uFFFD\uD800\uDC00-\uDBFF\uDFFF\r\n\t]*<br/>
*
* @param autoScalingGroupName The name of the Auto Scaling group associated with this instance.
*/
public void setAutoScalingGroupName(String autoScalingGroupName) {
this.autoScalingGroupName = autoScalingGroupName;
}
/**
* The name of the Auto Scaling group associated with this instance.
* <p>
* Returns a reference to this object so that method calls can be chained together.
* <p>
* <b>Constraints:</b><br/>
* <b>Length: </b>1 - 255<br/>
* <b>Pattern: </b>[\u0020-\uD7FF\uE000-\uFFFD\uD800\uDC00-\uDBFF\uDFFF\r\n\t]*<br/>
*
* @param autoScalingGroupName The name of the Auto Scaling group associated with this instance.
*
* @return A reference to this updated object so that method calls can be chained
* together.
*/
public AutoScalingInstanceDetails withAutoScalingGroupName(String autoScalingGroupName) {
this.autoScalingGroupName = autoScalingGroupName;
return this;
}
/**
* The Availability Zone in which this instance resides.
* <p>
* <b>Constraints:</b><br/>
* <b>Length: </b>1 - 255<br/>
* <b>Pattern: </b>[\u0020-\uD7FF\uE000-\uFFFD\uD800\uDC00-\uDBFF\uDFFF\r\n\t]*<br/>
*
* @return The Availability Zone in which this instance resides.
*/
public String getAvailabilityZone() {
return availabilityZone;
}
/**
* The Availability Zone in which this instance resides.
* <p>
* <b>Constraints:</b><br/>
* <b>Length: </b>1 - 255<br/>
* <b>Pattern: </b>[\u0020-\uD7FF\uE000-\uFFFD\uD800\uDC00-\uDBFF\uDFFF\r\n\t]*<br/>
*
* @param availabilityZone The Availability Zone in which this instance resides.
*/
public void setAvailabilityZone(String availabilityZone) {
this.availabilityZone = availabilityZone;
}
/**
* The Availability Zone in which this instance resides.
* <p>
* Returns a reference to this object so that method calls can be chained together.
* <p>
* <b>Constraints:</b><br/>
* <b>Length: </b>1 - 255<br/>
* <b>Pattern: </b>[\u0020-\uD7FF\uE000-\uFFFD\uD800\uDC00-\uDBFF\uDFFF\r\n\t]*<br/>
*
* @param availabilityZone The Availability Zone in which this instance resides.
*
* @return A reference to this updated object so that method calls can be chained
* together.
*/
public AutoScalingInstanceDetails withAvailabilityZone(String availabilityZone) {
this.availabilityZone = availabilityZone;
return this;
}
/**
* The life cycle state of this instance.
* <p>
* <b>Constraints:</b><br/>
* <b>Length: </b>1 - 32<br/>
* <b>Pattern: </b>[\u0020-\uD7FF\uE000-\uFFFD\uD800\uDC00-\uDBFF\uDFFF\r\n\t]*<br/>
*
* @return The life cycle state of this instance.
*/
public String getLifecycleState() {
return lifecycleState;
}
/**
* The life cycle state of this instance.
* <p>
* <b>Constraints:</b><br/>
* <b>Length: </b>1 - 32<br/>
* <b>Pattern: </b>[\u0020-\uD7FF\uE000-\uFFFD\uD800\uDC00-\uDBFF\uDFFF\r\n\t]*<br/>
*
* @param lifecycleState The life cycle state of this instance.
*/
public void setLifecycleState(String lifecycleState) {
this.lifecycleState = lifecycleState;
}
/**
* The life cycle state of this instance.
* <p>
* Returns a reference to this object so that method calls can be chained together.
* <p>
* <b>Constraints:</b><br/>
* <b>Length: </b>1 - 32<br/>
* <b>Pattern: </b>[\u0020-\uD7FF\uE000-\uFFFD\uD800\uDC00-\uDBFF\uDFFF\r\n\t]*<br/>
*
* @param lifecycleState The life cycle state of this instance.
*
* @return A reference to this updated object so that method calls can be chained
* together.
*/
public AutoScalingInstanceDetails withLifecycleState(String lifecycleState) {
this.lifecycleState = lifecycleState;
return this;
}
/**
* The health status of this instance. "Healthy" means that the instance
* is healthy and should remain in service. "Unhealthy" means that the
* instance is unhealthy. Auto Scaling should terminate and replace it.
* <p>
* <b>Constraints:</b><br/>
* <b>Length: </b>1 - 32<br/>
* <b>Pattern: </b>[\u0020-\uD7FF\uE000-\uFFFD\uD800\uDC00-\uDBFF\uDFFF\r\n\t]*<br/>
*
* @return The health status of this instance. "Healthy" means that the instance
* is healthy and should remain in service. "Unhealthy" means that the
* instance is unhealthy. Auto Scaling should terminate and replace it.
*/
public String getHealthStatus() {
return healthStatus;
}
/**
* The health status of this instance. "Healthy" means that the instance
* is healthy and should remain in service. "Unhealthy" means that the
* instance is unhealthy. Auto Scaling should terminate and replace it.
* <p>
* <b>Constraints:</b><br/>
* <b>Length: </b>1 - 32<br/>
* <b>Pattern: </b>[\u0020-\uD7FF\uE000-\uFFFD\uD800\uDC00-\uDBFF\uDFFF\r\n\t]*<br/>
*
* @param healthStatus The health status of this instance. "Healthy" means that the instance
* is healthy and should remain in service. "Unhealthy" means that the
* instance is unhealthy. Auto Scaling should terminate and replace it.
*/
public void setHealthStatus(String healthStatus) {
this.healthStatus = healthStatus;
}
/**
* The health status of this instance. "Healthy" means that the instance
* is healthy and should remain in service. "Unhealthy" means that the
* instance is unhealthy. Auto Scaling should terminate and replace it.
* <p>
* Returns a reference to this object so that method calls can be chained together.
* <p>
* <b>Constraints:</b><br/>
* <b>Length: </b>1 - 32<br/>
* <b>Pattern: </b>[\u0020-\uD7FF\uE000-\uFFFD\uD800\uDC00-\uDBFF\uDFFF\r\n\t]*<br/>
*
* @param healthStatus The health status of this instance. "Healthy" means that the instance
* is healthy and should remain in service. "Unhealthy" means that the
* instance is unhealthy. Auto Scaling should terminate and replace it.
*
* @return A reference to this updated object so that method calls can be chained
* together.
*/
public AutoScalingInstanceDetails withHealthStatus(String healthStatus) {
this.healthStatus = healthStatus;
return this;
}
/**
* The launch configuration associated with this instance.
* <p>
* <b>Constraints:</b><br/>
* <b>Length: </b>1 - 255<br/>
* <b>Pattern: </b>[\u0020-\uD7FF\uE000-\uFFFD\uD800\uDC00-\uDBFF\uDFFF\r\n\t]*<br/>
*
* @return The launch configuration associated with this instance.
*/
public String getLaunchConfigurationName() {
return launchConfigurationName;
}
/**
* The launch configuration associated with this instance.
* <p>
* <b>Constraints:</b><br/>
* <b>Length: </b>1 - 255<br/>
* <b>Pattern: </b>[\u0020-\uD7FF\uE000-\uFFFD\uD800\uDC00-\uDBFF\uDFFF\r\n\t]*<br/>
*
* @param launchConfigurationName The launch configuration associated with this instance.
*/
public void setLaunchConfigurationName(String launchConfigurationName) {
this.launchConfigurationName = launchConfigurationName;
}
/**
* The launch configuration associated with this instance.
* <p>
* Returns a reference to this object so that method calls can be chained together.
* <p>
* <b>Constraints:</b><br/>
* <b>Length: </b>1 - 255<br/>
* <b>Pattern: </b>[\u0020-\uD7FF\uE000-\uFFFD\uD800\uDC00-\uDBFF\uDFFF\r\n\t]*<br/>
*
* @param launchConfigurationName The launch configuration associated with this instance.
*
* @return A reference to this updated object so that method calls can be chained
* together.
*/
public AutoScalingInstanceDetails withLaunchConfigurationName(String launchConfigurationName) {
this.launchConfigurationName = launchConfigurationName;
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 (instanceId != null) sb.append("InstanceId: " + instanceId + ", ");
if (autoScalingGroupName != null) sb.append("AutoScalingGroupName: " + autoScalingGroupName + ", ");
if (availabilityZone != null) sb.append("AvailabilityZone: " + availabilityZone + ", ");
if (lifecycleState != null) sb.append("LifecycleState: " + lifecycleState + ", ");
if (healthStatus != null) sb.append("HealthStatus: " + healthStatus + ", ");
if (launchConfigurationName != null) sb.append("LaunchConfigurationName: " + launchConfigurationName + ", ");
sb.append("}");
return sb.toString();
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getInstanceId() == null) ? 0 : getInstanceId().hashCode());
hashCode = prime * hashCode + ((getAutoScalingGroupName() == null) ? 0 : getAutoScalingGroupName().hashCode());
hashCode = prime * hashCode + ((getAvailabilityZone() == null) ? 0 : getAvailabilityZone().hashCode());
hashCode = prime * hashCode + ((getLifecycleState() == null) ? 0 : getLifecycleState().hashCode());
hashCode = prime * hashCode + ((getHealthStatus() == null) ? 0 : getHealthStatus().hashCode());
hashCode = prime * hashCode + ((getLaunchConfigurationName() == null) ? 0 : getLaunchConfigurationName().hashCode());
return hashCode;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (obj instanceof AutoScalingInstanceDetails == false) return false;
AutoScalingInstanceDetails other = (AutoScalingInstanceDetails)obj;
if (other.getInstanceId() == null ^ this.getInstanceId() == null) return false;
if (other.getInstanceId() != null && other.getInstanceId().equals(this.getInstanceId()) == false) return false;
if (other.getAutoScalingGroupName() == null ^ this.getAutoScalingGroupName() == null) return false;
if (other.getAutoScalingGroupName() != null && other.getAutoScalingGroupName().equals(this.getAutoScalingGroupName()) == false) return false;
if (other.getAvailabilityZone() == null ^ this.getAvailabilityZone() == null) return false;
if (other.getAvailabilityZone() != null && other.getAvailabilityZone().equals(this.getAvailabilityZone()) == false) return false;
if (other.getLifecycleState() == null ^ this.getLifecycleState() == null) return false;
if (other.getLifecycleState() != null && other.getLifecycleState().equals(this.getLifecycleState()) == false) return false;
if (other.getHealthStatus() == null ^ this.getHealthStatus() == null) return false;
if (other.getHealthStatus() != null && other.getHealthStatus().equals(this.getHealthStatus()) == false) return false;
if (other.getLaunchConfigurationName() == null ^ this.getLaunchConfigurationName() == null) return false;
if (other.getLaunchConfigurationName() != null && other.getLaunchConfigurationName().equals(this.getLaunchConfigurationName()) == false) return false;
return true;
}
}
|
package com.sequenceiq.cloudbreak.cloud.gcp.sql;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import javax.inject.Inject;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import com.google.api.client.googleapis.json.GoogleJsonResponseException;
import com.google.api.services.compute.Compute;
import com.google.api.services.compute.model.Subnetwork;
import com.google.api.services.sqladmin.SQLAdmin;
import com.google.api.services.sqladmin.model.BackupConfiguration;
import com.google.api.services.sqladmin.model.DatabaseInstance;
import com.google.api.services.sqladmin.model.InstancesListResponse;
import com.google.api.services.sqladmin.model.IpConfiguration;
import com.google.api.services.sqladmin.model.Operation;
import com.google.api.services.sqladmin.model.Settings;
import com.google.api.services.sqladmin.model.User;
import com.google.common.base.Strings;
import com.sequenceiq.cloudbreak.cloud.context.AuthenticatedContext;
import com.sequenceiq.cloudbreak.cloud.gcp.GcpResourceException;
import com.sequenceiq.cloudbreak.cloud.gcp.client.GcpComputeFactory;
import com.sequenceiq.cloudbreak.cloud.gcp.client.GcpSQLAdminFactory;
import com.sequenceiq.cloudbreak.cloud.gcp.poller.DatabasePollerService;
import com.sequenceiq.cloudbreak.cloud.gcp.util.GcpLabelUtil;
import com.sequenceiq.cloudbreak.cloud.gcp.util.GcpStackUtil;
import com.sequenceiq.cloudbreak.cloud.gcp.view.GcpDatabaseNetworkView;
import com.sequenceiq.cloudbreak.cloud.gcp.view.GcpDatabaseServerView;
import com.sequenceiq.cloudbreak.cloud.model.CloudResource;
import com.sequenceiq.cloudbreak.cloud.model.DatabaseStack;
import com.sequenceiq.cloudbreak.cloud.notification.PersistenceNotifier;
import com.sequenceiq.cloudbreak.cloud.template.compute.DatabaseServerLaunchService;
import com.sequenceiq.common.api.type.ResourceType;
@Component
public class GcpDatabaseServerLaunchService extends GcpDatabaseServerBaseService implements DatabaseServerLaunchService {
private static final Logger LOGGER = LoggerFactory.getLogger(GcpDatabaseServerLaunchService.class);
// PostgreSQL server port is fixed for now
private static final int POSTGRESQL_SERVER_PORT = 5432;
private static final String GCP_SQL_INSTANCE_PRIVATE_IP_TYPE = "PRIVATE";
@Inject
private DatabasePollerService databasePollerService;
@Inject
private GcpComputeFactory gcpComputeFactory;
@Inject
private GcpSQLAdminFactory gcpSQLAdminFactory;
public List<CloudResource> launch(AuthenticatedContext ac, DatabaseStack stack, PersistenceNotifier resourceNotifier) throws Exception {
GcpDatabaseServerView databaseServerView = new GcpDatabaseServerView(stack.getDatabaseServer());
String deploymentName = databaseServerView.getDbServerName();
SQLAdmin sqlAdmin = gcpSQLAdminFactory.buildSQLAdmin(ac.getCloudCredential(), ac.getCloudCredential().getName());
Compute compute = gcpComputeFactory.buildCompute(ac.getCloudCredential());
String projectId = GcpStackUtil.getProjectId(ac.getCloudCredential());
List<CloudResource> buildableResource = new ArrayList<>();
buildableResource.add(getGcpDatabase(deploymentName));
buildableResource.add(getRdsPort());
try {
InstancesListResponse list = sqlAdmin.instances().list(projectId).execute();
Optional<DatabaseInstance> first = Optional.empty();
if (!list.isEmpty()) {
first = list.getItems()
.stream()
.filter(e -> e.getName().equals(deploymentName))
.findFirst();
}
if (first.isEmpty()) {
DatabaseInstance databaseInstance = getDatabaseInstance(stack, deploymentName, compute, projectId);
SQLAdmin.Instances.Insert insert = sqlAdmin.instances().insert(projectId, databaseInstance);
insert.setPrettyPrint(Boolean.TRUE);
try {
Operation operation = insert.execute();
verifyOperation(operation, buildableResource);
CloudResource operationAwareCloudResource = createOperationAwareCloudResource(buildableResource.get(0), operation);
databasePollerService.launchDatabasePoller(ac, List.of(operationAwareCloudResource));
DatabaseInstance instance = sqlAdmin.instances().get(projectId, deploymentName).execute();
if (instance != null) {
CloudResource.Builder rdsInstance = new CloudResource.Builder();
String instanceName = instance.getName();
buildableResource.add(getRdsHostName(instance, rdsInstance, instanceName));
User rootUser = getRootUser(stack, projectId, instanceName);
operation = sqlAdmin.users()
.insert(projectId, instanceName, rootUser)
.execute();
verifyOperation(operation, buildableResource);
operationAwareCloudResource = createOperationAwareCloudResource(buildableResource.get(0), operation);
databasePollerService.insertUserPoller(ac, List.of(operationAwareCloudResource));
}
buildableResource.forEach(dbr -> resourceNotifier.notifyAllocation(dbr, ac.getCloudContext()));
return Collections.singletonList(operationAwareCloudResource);
} catch (GoogleJsonResponseException e) {
throw new GcpResourceException(checkException(e), resourceType(), buildableResource.get(0).getName());
}
} else {
LOGGER.debug("Deployment already exists: {}", deploymentName);
}
} catch (GoogleJsonResponseException e) {
throw new GcpResourceException(checkException(e), resourceType(), buildableResource.get(0).getName());
}
return List.of();
}
public CloudResource getRdsPort() {
return new CloudResource.Builder()
.type(ResourceType.RDS_PORT)
.name(Integer.toString(POSTGRESQL_SERVER_PORT))
.build();
}
public CloudResource getGcpDatabase(String deploymentName) {
return new CloudResource.Builder()
.type(ResourceType.GCP_DATABASE)
.name(deploymentName)
.build();
}
public CloudResource getRdsHostName(DatabaseInstance instance, CloudResource.Builder rdsInstance, String instanceName) {
return rdsInstance
.type(ResourceType.RDS_HOSTNAME)
.instanceId(instanceName)
.name(getPrivateIpAddressOfDbInstance(instance, instanceName))
.build();
}
private String getPrivateIpAddressOfDbInstance(DatabaseInstance instance, String instanceName) {
String ipAddress = instance.getIpAddresses()
.stream()
.filter(i -> GCP_SQL_INSTANCE_PRIVATE_IP_TYPE.equals(i.getType()))
.findFirst()
.orElseThrow(() -> new GcpResourceException(String.format("Private IP address could not be found for database instance '%s'", instanceName)))
.getIpAddress();
return ipAddress;
}
@NotNull
private DatabaseInstance getDatabaseInstance(DatabaseStack stack, String deploymentName, Compute compute, String projectId) throws java.io.IOException {
GcpDatabaseServerView databaseServerView = new GcpDatabaseServerView(stack.getDatabaseServer());
GcpDatabaseNetworkView databaseNetworkView = new GcpDatabaseNetworkView(stack.getNetwork());
Subnetwork subnetworkForRedbeams;
if (Strings.isNullOrEmpty(databaseNetworkView.getSharedProjectId())) {
subnetworkForRedbeams = compute
.subnetworks()
.get(projectId, databaseServerView.getLocation(), databaseNetworkView.getSubnetId())
.execute();
} else {
subnetworkForRedbeams = compute
.subnetworks()
.get(databaseNetworkView.getSharedProjectId(), databaseServerView.getLocation(), databaseNetworkView.getSubnetId())
.execute();
}
DatabaseInstance databaseInstance = new DatabaseInstance();
databaseInstance.setCurrentDiskSize(databaseServerView.getAllocatedStorageInMb());
databaseInstance.setName(deploymentName);
databaseInstance.setInstanceType("CLOUD_SQL_INSTANCE");
databaseInstance.setBackendType("SECOND_GEN");
databaseInstance.setRegion(databaseServerView.getLocation());
databaseInstance.setRootPassword(databaseServerView.getAdminPassword());
databaseInstance.setConnectionName(databaseServerView.getAdminLoginName());
databaseInstance.setGceZone(databaseNetworkView.getAvailabilityZone());
databaseInstance.setDatabaseVersion(databaseServerView.getDatabaseVersion());
databaseInstance.setSettings(getSettings(stack, databaseServerView, subnetworkForRedbeams));
return databaseInstance;
}
@NotNull
public Settings getSettings(DatabaseStack stack, GcpDatabaseServerView databaseServerView, Subnetwork subnetworkForRedbeams) {
return new Settings()
.setTier(stack.getDatabaseServer().getFlavor())
.setActivationPolicy("ALWAYS")
.setAvailabilityType(stack.getDatabaseServer().getHighAvailability() ? "REGIONAL" : "ZONAL")
.setStorageAutoResize(true)
.setDataDiskSizeGb(databaseServerView.getAllocatedStorageInGb())
.setDataDiskType("PD_SSD")
.setIpConfiguration(new IpConfiguration()
.setPrivateNetwork(subnetworkForRedbeams.getNetwork())
.setIpv4Enabled(false)
)
.setUserLabels(GcpLabelUtil.createLabelsFromTagsMap(stack.getTags()))
.setBackupConfiguration(
new BackupConfiguration()
.setEnabled(true)
.setBinaryLogEnabled(false)
);
}
@NotNull
private User getRootUser(DatabaseStack stack, String projectId, String instanceName) {
return new User()
.setProject(projectId)
.setInstance(instanceName)
.setName(stack.getDatabaseServer().getRootUserName())
.setPassword(stack.getDatabaseServer().getRootPassword());
}
}
|
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.component.disruptor;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
import com.lmax.disruptor.InsufficientCapacityException;
import org.apache.camel.AsyncEndpoint;
import org.apache.camel.Component;
import org.apache.camel.Consumer;
import org.apache.camel.Exchange;
import org.apache.camel.MultipleConsumersSupport;
import org.apache.camel.Processor;
import org.apache.camel.Producer;
import org.apache.camel.WaitForTaskToComplete;
import org.apache.camel.api.management.ManagedAttribute;
import org.apache.camel.api.management.ManagedResource;
import org.apache.camel.support.DefaultEndpoint;
import org.apache.camel.spi.Metadata;
import org.apache.camel.spi.UriEndpoint;
import org.apache.camel.spi.UriParam;
import org.apache.camel.spi.UriPath;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* The disruptor component provides asynchronous SEDA behavior using LMAX Disruptor.
*
* This component works much as the standard SEDA Component, but utilizes a Disruptor
* instead of a BlockingQueue utilized by the standard SEDA.
*/
@ManagedResource(description = "Managed Disruptor Endpoint")
@UriEndpoint(firstVersion = "2.12.0", scheme = "disruptor,disruptor-vm", title = "Disruptor,Disruptor VM", syntax = "disruptor:name", consumerClass = DisruptorConsumer.class, label = "endpoint")
public class DisruptorEndpoint extends DefaultEndpoint implements AsyncEndpoint, MultipleConsumersSupport {
public static final String DISRUPTOR_IGNORE_EXCHANGE = "disruptor.ignoreExchange";
private static final Logger LOGGER = LoggerFactory.getLogger(DisruptorEndpoint.class);
private final Set<DisruptorProducer> producers = new CopyOnWriteArraySet<>();
private final Set<DisruptorConsumer> consumers = new CopyOnWriteArraySet<>();
private final DisruptorReference disruptorReference;
@UriPath(description = "Name of queue") @Metadata(required = "true")
private String name;
@UriParam(label = "consumer", defaultValue = "1")
private final int concurrentConsumers;
@UriParam(label = "consumer")
private final boolean multipleConsumers;
@UriParam(label = "producer", defaultValue = "IfReplyExpected")
private WaitForTaskToComplete waitForTaskToComplete = WaitForTaskToComplete.IfReplyExpected;
@UriParam(label = "producer", defaultValue = "30000")
private long timeout = 30000;
@UriParam(defaultValue = "" + DisruptorComponent.DEFAULT_BUFFER_SIZE)
private int size;
@UriParam(label = "producer")
private boolean blockWhenFull;
@UriParam(label = "consumer", defaultValue = "Blocking")
private DisruptorWaitStrategy waitStrategy;
@UriParam(label = "producer", defaultValue = "Multi")
private DisruptorProducerType producerType;
public DisruptorEndpoint(final String endpointUri, final Component component,
final DisruptorReference disruptorReference, final int concurrentConsumers,
final boolean multipleConsumers, boolean blockWhenFull) throws Exception {
super(endpointUri, component);
this.disruptorReference = disruptorReference;
this.name = disruptorReference.getName();
this.concurrentConsumers = concurrentConsumers;
this.multipleConsumers = multipleConsumers;
this.blockWhenFull = blockWhenFull;
}
@ManagedAttribute(description = "Queue name")
public String getName() {
return name;
}
@ManagedAttribute(description = "Buffer max capacity")
public int getBufferSize() {
return disruptorReference.getBufferSize();
}
@ManagedAttribute(description = "Remaining capacity in ring buffer")
public long getRemainingCapacity() throws DisruptorNotStartedException {
return getDisruptor().getRemainingCapacity();
}
@ManagedAttribute(description = "Amount of pending exchanges waiting for consumption in ring buffer")
public long getPendingExchangeCount() throws DisruptorNotStartedException {
return getDisruptor().getPendingExchangeCount();
}
/**
* Number of concurrent threads processing exchanges.
*/
@ManagedAttribute(description = "Number of concurrent consumers")
public int getConcurrentConsumers() {
return concurrentConsumers;
}
@ManagedAttribute(description = "Option to specify whether the caller should wait for the async task to complete or not before continuing")
public WaitForTaskToComplete getWaitForTaskToComplete() {
return waitForTaskToComplete;
}
/**
* Option to specify whether the caller should wait for the async task to complete or not before continuing.
* The following three options are supported: Always, Never or IfReplyExpected. The first two values are self-explanatory.
* The last value, IfReplyExpected, will only wait if the message is Request Reply based.
*/
public void setWaitForTaskToComplete(final WaitForTaskToComplete waitForTaskToComplete) {
this.waitForTaskToComplete = waitForTaskToComplete;
}
@ManagedAttribute(description = "Timeout (in milliseconds) before a producer will stop waiting for an asynchronous task to complete")
public long getTimeout() {
return timeout;
}
/**
* Timeout (in milliseconds) before a producer will stop waiting for an asynchronous task to complete.
* You can disable timeout by using 0 or a negative value.
*/
public void setTimeout(final long timeout) {
this.timeout = timeout;
}
@ManagedAttribute(description = "The maximum capacity of the Disruptors ringbuffer")
public int getSize() {
return size;
}
/**
* The maximum capacity of the Disruptors ringbuffer
* Will be effectively increased to the nearest power of two.
* Notice: Mind if you use this option, then its the first endpoint being created with the queue name,
* that determines the size. To make sure all endpoints use same size, then configure the size option
* on all of them, or the first endpoint being created.
*/
public void setSize(int size) {
this.size = size;
}
@Override
@ManagedAttribute(description = "Specifies whether multiple consumers are allowed")
public boolean isMultipleConsumersSupported() {
return isMultipleConsumers();
}
/**
* Specifies whether multiple consumers are allowed.
* If enabled, you can use Disruptor for Publish-Subscribe messaging.
* That is, you can send a message to the queue and have each consumer receive a copy of the message.
* When enabled, this option should be specified on every consumer endpoint.
*/
public boolean isMultipleConsumers() {
return multipleConsumers;
}
/**
* Returns the current active consumers on this endpoint
*/
public Set<DisruptorConsumer> getConsumers() {
return Collections.unmodifiableSet(consumers);
}
/**
* Returns the current active producers on this endpoint
*/
public Set<DisruptorProducer> getProducers() {
return Collections.unmodifiableSet(producers);
}
@ManagedAttribute
public boolean isBlockWhenFull() {
return blockWhenFull;
}
/**
* Whether a thread that sends messages to a full Disruptor will block until the ringbuffer's capacity is no longer exhausted.
* By default, the calling thread will block and wait until the message can be accepted.
* By disabling this option, an exception will be thrown stating that the queue is full.
*/
public void setBlockWhenFull(boolean blockWhenFull) {
this.blockWhenFull = blockWhenFull;
}
@ManagedAttribute(description = "Defines the strategy used by consumer threads to wait on new exchanges to be published")
public DisruptorWaitStrategy getWaitStrategy() {
return waitStrategy;
}
/**
* Defines the strategy used by consumer threads to wait on new exchanges to be published.
* The options allowed are:Blocking, Sleeping, BusySpin and Yielding.
*/
public void setWaitStrategy(DisruptorWaitStrategy waitStrategy) {
this.waitStrategy = waitStrategy;
}
@ManagedAttribute(description = " Defines the producers allowed on the Disruptor")
public DisruptorProducerType getProducerType() {
return producerType;
}
/**
* Defines the producers allowed on the Disruptor.
* The options allowed are: Multi to allow multiple producers and Single to enable certain optimizations only
* allowed when one concurrent producer (on one thread or otherwise synchronized) is active.
*/
public void setProducerType(DisruptorProducerType producerType) {
this.producerType = producerType;
}
@Override
public boolean isSingleton() {
return true;
}
@Override
public Producer createProducer() throws Exception {
if (getProducers().size() == 1 && getDisruptor().getProducerType() == DisruptorProducerType.Single) {
throw new IllegalStateException(
"Endpoint can't support multiple producers when ProducerType SINGLE is configured");
}
return new DisruptorProducer(this, getWaitForTaskToComplete(), getTimeout(), isBlockWhenFull());
}
@Override
public Consumer createConsumer(final Processor processor) throws Exception {
return new DisruptorConsumer(this, processor);
}
@Override
protected void doStart() throws Exception {
// notify reference we are shutting down this endpoint
disruptorReference.addEndpoint(this);
super.doStart();
}
@Override
protected void doStop() throws Exception {
// notify reference we are shutting down this endpoint
disruptorReference.removeEndpoint(this);
super.doStop();
}
@Override
protected void doShutdown() throws Exception {
// notify component we are shutting down this endpoint
if (getComponent() != null) {
getComponent().onShutdownEndpoint(this);
}
super.doShutdown();
}
@Override
public DisruptorComponent getComponent() {
return (DisruptorComponent)super.getComponent();
}
void onStarted(final DisruptorConsumer consumer) throws Exception {
synchronized (this) {
// validate multiple consumers has been enabled is necessary
if (!consumers.isEmpty() && !isMultipleConsumersSupported()) {
throw new IllegalStateException(
"Multiple consumers for the same endpoint is not allowed: " + this);
}
if (consumers.add(consumer)) {
LOGGER.debug("Starting consumer {} on endpoint {}", consumer, getEndpointUri());
getDisruptor().reconfigure();
} else {
LOGGER.debug("Tried to start Consumer {} on endpoint {} but it was already started", consumer, getEndpointUri());
}
}
}
void onStopped(final DisruptorConsumer consumer) throws Exception {
synchronized (this) {
if (consumers.remove(consumer)) {
LOGGER.debug("Stopping consumer {} on endpoint {}", consumer, getEndpointUri());
getDisruptor().reconfigure();
} else {
LOGGER.debug("Tried to stop Consumer {} on endpoint {} but it was already stopped", consumer, getEndpointUri());
}
}
}
void onStarted(final DisruptorProducer producer) {
producers.add(producer);
}
void onStopped(final DisruptorProducer producer) {
producers.remove(producer);
}
Map<DisruptorConsumer, Collection<LifecycleAwareExchangeEventHandler>> createConsumerEventHandlers() {
Map<DisruptorConsumer, Collection<LifecycleAwareExchangeEventHandler>> result = new HashMap<>();
for (final DisruptorConsumer consumer : consumers) {
result.put(consumer, consumer.createEventHandlers(concurrentConsumers));
}
return result;
}
/**
* Called by DisruptorProducers to publish new exchanges on the RingBuffer, blocking when full
*/
void publish(final Exchange exchange) throws DisruptorNotStartedException {
disruptorReference.publish(exchange);
}
/**
* Called by DisruptorProducers to publish new exchanges on the RingBuffer, throwing InsufficientCapacityException
* when full
*
* @throws InsufficientCapacityException when the Ringbuffer is full.
*/
void tryPublish(final Exchange exchange) throws DisruptorNotStartedException, InsufficientCapacityException {
disruptorReference.tryPublish(exchange);
}
DisruptorReference getDisruptor() {
return disruptorReference;
}
@Override
public boolean equals(Object object) {
boolean result = super.equals(object);
return result && getCamelContext().equals(((DisruptorEndpoint)object).getCamelContext());
}
@Override
public int hashCode() {
return getEndpointUri().hashCode() * 37 + getCamelContext().hashCode();
}
}
|
package atas.logic.commands.studentlist;
import static atas.commons.core.Messages.MESSAGE_INVALID_STUDENT_DISPLAYED_INDEX;
import static atas.logic.commands.CommandTestUtil.DESC_AMY;
import static atas.logic.commands.CommandTestUtil.DESC_BOB;
import static atas.logic.commands.CommandTestUtil.VALID_MATRICULATION_BOB;
import static atas.logic.commands.CommandTestUtil.VALID_NAME_BOB;
import static atas.logic.commands.CommandTestUtil.VALID_TAG_HUSBAND;
import static atas.logic.commands.CommandTestUtil.assertCommandFailure;
import static atas.logic.commands.CommandTestUtil.assertCommandSuccess;
import static atas.logic.commands.CommandTestUtil.showStudentAtIndex;
import static atas.testutil.TypicalIndexes.INDEX_FIRST_STUDENT;
import static atas.testutil.TypicalIndexes.INDEX_SECOND_STUDENT;
import static atas.testutil.TypicalMemoContents.EMPTY_MEMO_CONTENT;
import static atas.testutil.TypicalSessions.getTypicalSessionList;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
import atas.commons.core.index.Index;
import atas.logic.commands.studentlist.EditStudentCommand.EditStudentDescriptor;
import atas.model.Model;
import atas.model.ModelManager;
import atas.model.UserPrefs;
import atas.model.student.Student;
import atas.model.student.StudentList;
import atas.testutil.EditStudentDescriptorBuilder;
import atas.testutil.ModelManagerBuilder;
import atas.testutil.StudentBuilder;
/**
* Contains integration tests (interaction with the Model, UndoCommand and RedoCommand) and unit tests for EditCommand.
*/
public class EditStudentCommandTest {
private Model model = ModelManagerBuilder.buildTypicalModelManager();
@Test
public void execute_allFieldsSpecifiedUnfilteredList_success() {
Student editedStudent = new StudentBuilder().build();
EditStudentDescriptor descriptor = new EditStudentDescriptorBuilder(editedStudent).build();
EditStudentCommand editStudentCommand = new EditStudentCommand(INDEX_FIRST_STUDENT, descriptor);
String expectedMessage = String.format(EditStudentCommand.MESSAGE_EDIT_STUDENT_SUCCESS, editedStudent);
Model expectedModel = new ModelManager(getTypicalSessionList(model.getStudentList().getStudentList()),
new StudentList(model.getStudentList()), new UserPrefs(), EMPTY_MEMO_CONTENT);
expectedModel.setStudent(model.getFilteredStudentList().get(0), editedStudent);
assertCommandSuccess(editStudentCommand, model, expectedMessage, expectedModel);
}
@Test
public void execute_someFieldsSpecifiedUnfilteredList_success() {
Index indexLastStudent = Index.fromOneBased(model.getNumberOfStudents());
Student lastStudent = model.getFilteredStudentList().get(indexLastStudent.getZeroBased());
StudentBuilder studentInList = new StudentBuilder(lastStudent);
Student editedStudent = studentInList.withName(VALID_NAME_BOB).withMatriculation(VALID_MATRICULATION_BOB)
.withTags(VALID_TAG_HUSBAND).build();
EditStudentCommand.EditStudentDescriptor descriptor = new EditStudentDescriptorBuilder()
.withName(VALID_NAME_BOB).withMatriculation(VALID_MATRICULATION_BOB)
.withTags(VALID_TAG_HUSBAND).build();
EditStudentCommand editStudentCommand = new EditStudentCommand(indexLastStudent, descriptor);
String expectedMessage = String.format(EditStudentCommand.MESSAGE_EDIT_STUDENT_SUCCESS, editedStudent);
Model expectedModel = new ModelManager(getTypicalSessionList(model.getStudentList().getStudentList()),
new StudentList(model.getStudentList()), new UserPrefs(), EMPTY_MEMO_CONTENT);
expectedModel.setStudent(lastStudent, editedStudent);
assertCommandSuccess(editStudentCommand, model, expectedMessage, expectedModel);
}
@Test
public void execute_noFieldSpecifiedUnfilteredList_success() {
EditStudentCommand editStudentCommand = new EditStudentCommand(INDEX_FIRST_STUDENT,
new EditStudentCommand.EditStudentDescriptor());
Student editedStudent = model.getFilteredStudentList().get(INDEX_FIRST_STUDENT.getZeroBased());
String expectedMessage = String.format(EditStudentCommand.MESSAGE_EDIT_STUDENT_SUCCESS, editedStudent);
Model expectedModel = new ModelManager(getTypicalSessionList(model.getStudentList().getStudentList()),
new StudentList(model.getStudentList()), new UserPrefs(), EMPTY_MEMO_CONTENT);
assertCommandSuccess(editStudentCommand, model, expectedMessage, expectedModel);
}
@Test
public void execute_filteredList_success() {
showStudentAtIndex(model, INDEX_FIRST_STUDENT);
Student studentInFilteredList = model.getFilteredStudentList().get(INDEX_FIRST_STUDENT.getZeroBased());
Student editedStudent = new StudentBuilder(studentInFilteredList).withName(VALID_NAME_BOB).build();
EditStudentCommand editStudentCommand = new EditStudentCommand(INDEX_FIRST_STUDENT,
new EditStudentDescriptorBuilder().withName(VALID_NAME_BOB).build());
String expectedMessage = String.format(EditStudentCommand.MESSAGE_EDIT_STUDENT_SUCCESS, editedStudent);
Model expectedModel = new ModelManager(getTypicalSessionList(model.getStudentList().getStudentList()),
new StudentList(model.getStudentList()), new UserPrefs(), EMPTY_MEMO_CONTENT);
expectedModel.setStudent(model.getFilteredStudentList().get(0), editedStudent);
assertCommandSuccess(editStudentCommand, model, expectedMessage, expectedModel);
}
@Test
public void execute_duplicateStudentUnfilteredList_failure() {
Student firstStudent = model.getFilteredStudentList().get(INDEX_FIRST_STUDENT.getZeroBased());
EditStudentDescriptor descriptor = new EditStudentDescriptorBuilder(firstStudent).build();
EditStudentCommand editStudentCommand = new EditStudentCommand(INDEX_SECOND_STUDENT, descriptor);
assertCommandFailure(editStudentCommand, model, EditStudentCommand.MESSAGE_DUPLICATE_STUDENT);
}
@Test
public void execute_duplicateStudentFilteredList_failure() {
showStudentAtIndex(model, INDEX_FIRST_STUDENT);
// edit student in filtered list into a duplicate in student list
Student studentInList = model.getStudentList().getStudentList().get(INDEX_SECOND_STUDENT.getZeroBased());
EditStudentDescriptor editStudentDescriptor = new EditStudentDescriptorBuilder(studentInList).build();
EditStudentCommand editStudentCommand = new EditStudentCommand(INDEX_FIRST_STUDENT,
editStudentDescriptor);
assertCommandFailure(editStudentCommand, model, EditStudentCommand.MESSAGE_DUPLICATE_STUDENT);
}
@Test
public void execute_invalidStudentIndexUnfilteredList_failure() {
Index outOfBoundIndex = Index.fromOneBased(model.getNumberOfStudents() + 1);
EditStudentCommand.EditStudentDescriptor
descriptor = new EditStudentDescriptorBuilder().withName(VALID_NAME_BOB).build();
EditStudentCommand editStudentCommand = new EditStudentCommand(outOfBoundIndex, descriptor);
assertCommandFailure(editStudentCommand, model, MESSAGE_INVALID_STUDENT_DISPLAYED_INDEX);
}
/**
* Edit filtered list where index is larger than size of filtered list,
* but smaller than size of student list
*/
@Test
public void execute_invalidStudentIndexFilteredList_failure() {
showStudentAtIndex(model, INDEX_FIRST_STUDENT);
Index outOfBoundIndex = INDEX_SECOND_STUDENT;
// ensures that outOfBoundIndex is still in bounds of student list list
assertTrue(outOfBoundIndex.getZeroBased() < model.getStudentList().getStudentList().size());
EditStudentCommand editStudentCommand = new EditStudentCommand(outOfBoundIndex,
new EditStudentDescriptorBuilder().withName(VALID_NAME_BOB).build());
assertCommandFailure(editStudentCommand, model, MESSAGE_INVALID_STUDENT_DISPLAYED_INDEX);
}
@Test
public void equals() {
final EditStudentCommand standardCommand = new EditStudentCommand(INDEX_FIRST_STUDENT, DESC_AMY);
// same values -> returns true
EditStudentCommand.EditStudentDescriptor copyDescriptor =
new EditStudentCommand.EditStudentDescriptor(DESC_AMY);
EditStudentCommand commandWithSameValues = new EditStudentCommand(INDEX_FIRST_STUDENT, copyDescriptor);
assertTrue(standardCommand.equals(commandWithSameValues));
// same object -> returns true
assertTrue(standardCommand.equals(standardCommand));
// null -> returns false
assertFalse(standardCommand.equals(null));
// different types -> returns false
assertFalse(standardCommand.equals(new ClearStudentListCommand()));
// different index -> returns false
assertFalse(standardCommand.equals(new EditStudentCommand(INDEX_SECOND_STUDENT, DESC_AMY)));
// different descriptor -> returns false
assertFalse(standardCommand.equals(new EditStudentCommand(INDEX_FIRST_STUDENT, DESC_BOB)));
}
}
|
/*
* Copyright 2011-2021 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.data.neo4j.queries.ogmgh551;
import java.util.List;
import org.springframework.data.neo4j.annotation.QueryResult;
/**
* @author Michael J. Simons
*/
@QueryResult
public class ThingResult {
private String something;
public String getSomething() {
return something;
}
private List<AnotherThing> things;
public List<AnotherThing> getThings() {
return things;
}
}
|
package Leetcode.Math;
public class RectangleArea_223 {
// respective area - overlap
public int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
int area = (C-A)*(D-B) + (G-E)*(H-F);
int left = Math.max(A, E);
int right = Math.min(C, G);
int bottom = Math.max(B, F);
int top = Math.min(D, H);
if (left < right && bottom < top) {
area -= (right - left) * (top - bottom);
}
return area;
}
}
|
/*
* 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 aplicacioncursos.mx.unam.fes.acatlan.mac.poo.frontend;
/**
*
* @author fernandov
*/
import java.awt.BorderLayout;
import java.awt.Color;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.border.TitledBorder;
public class PanelNavegacion extends JPanel {
private JButton btnSiguiente;
private JButton btnAnterior;
// constructor
public PanelNavegacion() {
setLayout(new BorderLayout());
TitledBorder border =BorderFactory.createTitledBorder("Registro");
border.setTitleColor(Color.BLUE);
setBorder(border);
btnSiguiente = new JButton(">");
btnAnterior = new JButton("<");
add(btnAnterior);
add(btnSiguiente);
}
}
|
package com.twu.biblioteca;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Scanner;
/**
* Created by alexa on 4/02/2019.
*/
public class LoginSystem {
ArrayList<Customer> customers;
Customer currentUser;
public LoginSystem() {
customers = new ArrayList<Customer>();
currentUser = null;
}
public boolean loginProcess(Scanner reader, PrintStream output) {
String libNum;
String pass;
do {
output.println("Enter library number (xxx-xxxx): ");
libNum = reader.nextLine();
output.println("Enter password: ");
pass = reader.nextLine();
currentUser = checkCredentials(libNum, pass);
if (currentUser == null)
output.println("Wrong library number and/or password inputted, please try again!");
}
while (currentUser == null);
return true;
}
public void addUser(Customer customer) {
customers.add(customer);
}
public Customer getActiveUser() {
return currentUser;
}
private Customer checkCredentials(String libraryNumber, String password) {
for (Customer cust : customers) {
if (cust.getLibraryNumber().equals(libraryNumber))
if (cust.getPassword().equals(password))
return cust;
}
return null;
}
}
|
package annotationstudy.mapper;
import org.springframework.stereotype.Repository;
@Repository
public class AppMapper {
}
|
package com.bluefireplatform.mapper;
import com.bluefireplatform.entity.OutdoorMiddleTab;
import com.bluefireplatform.entity.OutdoorMiddleTabExample;
import java.util.List;
import org.apache.ibatis.annotations.Param;
public interface OutdoorMiddleTabMapper {
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table outdoor_middle_tab
*
* @mbggenerated Mon Apr 22 14:24:57 CST 2019
*/
int countByExample(OutdoorMiddleTabExample example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table outdoor_middle_tab
*
* @mbggenerated Mon Apr 22 14:24:57 CST 2019
*/
int deleteByExample(OutdoorMiddleTabExample example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table outdoor_middle_tab
*
* @mbggenerated Mon Apr 22 14:24:57 CST 2019
*/
int deleteByPrimaryKey(Integer outdoorMiddleId);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table outdoor_middle_tab
*
* @mbggenerated Mon Apr 22 14:24:57 CST 2019
*/
int insert(OutdoorMiddleTab record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table outdoor_middle_tab
*
* @mbggenerated Mon Apr 22 14:24:57 CST 2019
*/
int insertSelective(OutdoorMiddleTab record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table outdoor_middle_tab
*
* @mbggenerated Mon Apr 22 14:24:57 CST 2019
*/
List<OutdoorMiddleTab> selectByExample(OutdoorMiddleTabExample example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table outdoor_middle_tab
*
* @mbggenerated Mon Apr 22 14:24:57 CST 2019
*/
OutdoorMiddleTab selectByPrimaryKey(Integer outdoorMiddleId);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table outdoor_middle_tab
*
* @mbggenerated Mon Apr 22 14:24:57 CST 2019
*/
int updateByExampleSelective(@Param("record") OutdoorMiddleTab record, @Param("example") OutdoorMiddleTabExample example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table outdoor_middle_tab
*
* @mbggenerated Mon Apr 22 14:24:57 CST 2019
*/
int updateByExample(@Param("record") OutdoorMiddleTab record, @Param("example") OutdoorMiddleTabExample example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table outdoor_middle_tab
*
* @mbggenerated Mon Apr 22 14:24:57 CST 2019
*/
int updateByPrimaryKeySelective(OutdoorMiddleTab record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table outdoor_middle_tab
*
* @mbggenerated Mon Apr 22 14:24:57 CST 2019
*/
int updateByPrimaryKey(OutdoorMiddleTab record);
}
|
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
package org.elasticsearch.client.ilm;
import org.elasticsearch.cluster.ClusterModule;
import org.elasticsearch.common.unit.ByteSizeValue;
import org.elasticsearch.core.TimeValue;
import org.elasticsearch.test.AbstractXContentTestCase;
import org.elasticsearch.xcontent.NamedXContentRegistry;
import org.elasticsearch.xcontent.ParseField;
import org.elasticsearch.xcontent.XContentParser;
import org.elasticsearch.xpack.core.ilm.TimeseriesLifecycleType;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import static org.hamcrest.Matchers.equalTo;
public class LifecyclePolicyTests extends AbstractXContentTestCase<LifecyclePolicy> {
private static final Set<String> VALID_HOT_ACTIONS = new HashSet<>(TimeseriesLifecycleType.ORDERED_VALID_HOT_ACTIONS);
private static final Set<String> VALID_WARM_ACTIONS = new HashSet<>(TimeseriesLifecycleType.ORDERED_VALID_WARM_ACTIONS);
private static final Set<String> VALID_COLD_ACTIONS = new HashSet<>(TimeseriesLifecycleType.ORDERED_VALID_COLD_ACTIONS);
private static final Set<String> VALID_FROZEN_ACTIONS = new HashSet<>(TimeseriesLifecycleType.ORDERED_VALID_FROZEN_ACTIONS);
private static final Set<String> VALID_DELETE_ACTIONS = new HashSet<>(TimeseriesLifecycleType.ORDERED_VALID_DELETE_ACTIONS);
private String lifecycleName;
@Override
protected LifecyclePolicy doParseInstance(XContentParser parser) {
return LifecyclePolicy.parse(parser, lifecycleName);
}
@Override
protected boolean supportsUnknownFields() {
return true;
}
@Override
protected Predicate<String> getRandomFieldsExcludeFilter() {
// these items all have some specific parsing that does not allow them to have additional objects within them.
return (field) -> field.contains("allocate.") || field.equals("phases") || field.endsWith("actions");
}
@Override
protected NamedXContentRegistry xContentRegistry() {
List<NamedXContentRegistry.Entry> entries = new ArrayList<>(ClusterModule.getNamedXWriteables());
entries.addAll(
Arrays.asList(
new NamedXContentRegistry.Entry(LifecycleAction.class, new ParseField(AllocateAction.NAME), AllocateAction::parse),
new NamedXContentRegistry.Entry(LifecycleAction.class, new ParseField(DeleteAction.NAME), DeleteAction::parse),
new NamedXContentRegistry.Entry(LifecycleAction.class, new ParseField(ForceMergeAction.NAME), ForceMergeAction::parse),
new NamedXContentRegistry.Entry(LifecycleAction.class, new ParseField(ReadOnlyAction.NAME), ReadOnlyAction::parse),
new NamedXContentRegistry.Entry(LifecycleAction.class, new ParseField(RolloverAction.NAME), RolloverAction::parse),
new NamedXContentRegistry.Entry(LifecycleAction.class, new ParseField(ShrinkAction.NAME), ShrinkAction::parse),
new NamedXContentRegistry.Entry(
LifecycleAction.class,
new ParseField(WaitForSnapshotAction.NAME),
WaitForSnapshotAction::parse
),
new NamedXContentRegistry.Entry(LifecycleAction.class, new ParseField(FreezeAction.NAME), FreezeAction::parse),
new NamedXContentRegistry.Entry(LifecycleAction.class, new ParseField(SetPriorityAction.NAME), SetPriorityAction::parse),
new NamedXContentRegistry.Entry(
LifecycleAction.class,
new ParseField(SearchableSnapshotAction.NAME),
SearchableSnapshotAction::parse
),
new NamedXContentRegistry.Entry(LifecycleAction.class, new ParseField(UnfollowAction.NAME), UnfollowAction::parse),
new NamedXContentRegistry.Entry(LifecycleAction.class, new ParseField(MigrateAction.NAME), MigrateAction::parse)
)
);
return new NamedXContentRegistry(entries);
}
@Override
protected LifecyclePolicy createTestInstance() {
lifecycleName = randomAlphaOfLength(5);
return createRandomPolicy(lifecycleName);
}
public void testValidatePhases() {
boolean invalid = randomBoolean();
String phaseName = randomFrom("hot", "warm", "cold", "delete");
if (invalid) {
phaseName += randomAlphaOfLength(5);
}
Map<String, Phase> phases = Collections.singletonMap(
phaseName,
new Phase(
phaseName,
TimeValue.ZERO,
phaseName.equals("delete") ? Collections.singletonMap(DeleteAction.NAME, new DeleteAction()) : Collections.emptyMap()
)
);
if (invalid) {
Exception e = expectThrows(IllegalArgumentException.class, () -> new LifecyclePolicy(lifecycleName, phases));
assertThat(e.getMessage(), equalTo("Lifecycle does not support phase [" + phaseName + "]"));
} else {
new LifecyclePolicy(lifecycleName, phases);
}
}
public void testValidateHotPhase() {
LifecycleAction invalidAction = null;
Map<String, LifecycleAction> actions = randomSubsetOf(VALID_HOT_ACTIONS).stream()
.map(this::getTestAction)
.collect(Collectors.toMap(LifecycleAction::getName, Function.identity()));
if (randomBoolean()) {
invalidAction = getTestAction(randomFrom("allocate", "migrate", "delete"));
actions.put(invalidAction.getName(), invalidAction);
}
Map<String, Phase> hotPhase = Collections.singletonMap("hot", new Phase("hot", TimeValue.ZERO, actions));
if (invalidAction != null) {
Exception e = expectThrows(
IllegalArgumentException.class,
"expected " + invalidAction + " to throw but it didn't",
() -> new LifecyclePolicy(lifecycleName, hotPhase)
);
assertThat(e.getMessage(), equalTo("invalid action [" + invalidAction.getName() + "] defined in phase [hot]"));
} else {
new LifecyclePolicy(lifecycleName, hotPhase);
}
}
public void testValidateWarmPhase() {
LifecycleAction invalidAction = null;
Map<String, LifecycleAction> actions = randomSubsetOf(VALID_WARM_ACTIONS).stream()
.map(this::getTestAction)
.collect(Collectors.toMap(LifecycleAction::getName, Function.identity()));
if (randomBoolean()) {
invalidAction = getTestAction(randomFrom("rollover", "delete", "searchable_snapshot"));
actions.put(invalidAction.getName(), invalidAction);
}
Map<String, Phase> warmPhase = Collections.singletonMap("warm", new Phase("warm", TimeValue.ZERO, actions));
if (invalidAction != null) {
Exception e = expectThrows(IllegalArgumentException.class, () -> new LifecyclePolicy(lifecycleName, warmPhase));
assertThat(e.getMessage(), equalTo("invalid action [" + invalidAction.getName() + "] defined in phase [warm]"));
} else {
new LifecyclePolicy(lifecycleName, warmPhase);
}
}
public void testValidateColdPhase() {
LifecycleAction invalidAction = null;
Map<String, LifecycleAction> actions = randomSubsetOf(VALID_COLD_ACTIONS).stream()
.map(this::getTestAction)
.collect(Collectors.toMap(LifecycleAction::getName, Function.identity()));
if (randomBoolean()) {
invalidAction = getTestAction(randomFrom("rollover", "delete", "forcemerge", "shrink"));
actions.put(invalidAction.getName(), invalidAction);
}
Map<String, Phase> coldPhase = Collections.singletonMap("cold", new Phase("cold", TimeValue.ZERO, actions));
if (invalidAction != null) {
Exception e = expectThrows(IllegalArgumentException.class, () -> new LifecyclePolicy(lifecycleName, coldPhase));
assertThat(e.getMessage(), equalTo("invalid action [" + invalidAction.getName() + "] defined in phase [cold]"));
} else {
new LifecyclePolicy(lifecycleName, coldPhase);
}
}
public void testValidateFrozenPhase() {
LifecycleAction invalidAction = null;
Map<String, LifecycleAction> actions = randomSubsetOf(VALID_FROZEN_ACTIONS).stream()
.map(this::getTestAction)
.collect(Collectors.toMap(LifecycleAction::getName, Function.identity()));
if (randomBoolean()) {
invalidAction = getTestAction(randomFrom("allocate", "rollover", "delete", "forcemerge", "shrink", "readonly"));
actions.put(invalidAction.getName(), invalidAction);
}
Map<String, Phase> coldPhase = Collections.singletonMap("cold", new Phase("frozen", TimeValue.ZERO, actions));
if (invalidAction != null) {
Exception e = expectThrows(IllegalArgumentException.class, () -> new LifecyclePolicy(lifecycleName, coldPhase));
assertThat(e.getMessage(), equalTo("invalid action [" + invalidAction.getName() + "] defined in phase [frozen]"));
} else {
new LifecyclePolicy(lifecycleName, coldPhase);
}
}
public void testValidateDeletePhase() {
LifecycleAction invalidAction = null;
Map<String, LifecycleAction> actions = VALID_DELETE_ACTIONS.stream()
.map(this::getTestAction)
.collect(Collectors.toMap(LifecycleAction::getName, Function.identity()));
if (randomBoolean()) {
invalidAction = getTestAction(randomFrom("allocate", "rollover", "forcemerge", "shrink"));
actions.put(invalidAction.getName(), invalidAction);
}
Map<String, Phase> deletePhase = Collections.singletonMap("delete", new Phase("delete", TimeValue.ZERO, actions));
if (invalidAction != null) {
Exception e = expectThrows(IllegalArgumentException.class, () -> new LifecyclePolicy(lifecycleName, deletePhase));
assertThat(e.getMessage(), equalTo("invalid action [" + invalidAction.getName() + "] defined in phase [delete]"));
} else {
new LifecyclePolicy(lifecycleName, deletePhase);
}
}
public void testValidateEmptyDeletePhase() {
Map<String, LifecycleAction> actions = new HashMap<>();
Phase delete = new Phase("delete", TimeValue.ZERO, actions);
Map<String, Phase> phases = Collections.singletonMap("delete", delete);
Exception e = expectThrows(IllegalArgumentException.class, () -> new LifecyclePolicy(lifecycleName, phases));
assertThat(e.getMessage(), equalTo("phase [" + delete.getName() + "] must define actions"));
}
public static LifecyclePolicy createRandomPolicy(String lifecycleName) {
List<String> phaseNames = Arrays.asList("hot", "warm", "cold", "delete");
Map<String, Phase> phases = new HashMap<>(phaseNames.size());
Function<String, Set<String>> validActions = (phase) -> {
return switch (phase) {
case "hot" -> VALID_HOT_ACTIONS;
case "warm" -> VALID_WARM_ACTIONS;
case "cold" -> VALID_COLD_ACTIONS;
case "delete" -> VALID_DELETE_ACTIONS;
default -> throw new IllegalArgumentException("invalid phase [" + phase + "]");
};
};
Function<String, Boolean> allowEmptyActions = (phase) -> {
return switch (phase) {
case "hot", "warm", "cold" -> true;
case "delete" -> false;
default -> throw new IllegalArgumentException("invalid phase [" + phase + "]");
};
};
Function<String, LifecycleAction> randomAction = (action) -> {
return switch (action) {
case AllocateAction.NAME -> AllocateActionTests.randomInstance();
case DeleteAction.NAME -> new DeleteAction();
case ForceMergeAction.NAME -> ForceMergeActionTests.randomInstance();
case ReadOnlyAction.NAME -> new ReadOnlyAction();
case RolloverAction.NAME -> RolloverActionTests.randomInstance();
case ShrinkAction.NAME -> ShrinkActionTests.randomInstance();
case FreezeAction.NAME -> new FreezeAction();
case WaitForSnapshotAction.NAME -> WaitForSnapshotActionTests.randomInstance();
case SetPriorityAction.NAME -> SetPriorityActionTests.randomInstance();
case UnfollowAction.NAME -> new UnfollowAction();
case SearchableSnapshotAction.NAME -> new SearchableSnapshotAction("repo", randomBoolean());
case MigrateAction.NAME -> new MigrateAction(randomBoolean());
default -> throw new IllegalArgumentException("invalid action [" + action + "]");
};
};
TimeValue prev = null;
boolean searchableSnapshotSeen = false;
for (String phase : phaseNames) {
TimeValue after = prev == null
? TimeValue.parseTimeValue(randomTimeValue(0, 10000, "s", "m", "h", "d"), "test_after")
: TimeValue.timeValueSeconds(prev.seconds() + randomIntBetween(60, 600));
prev = after;
Map<String, LifecycleAction> actions = new HashMap<>();
List<String> actionNames;
if (allowEmptyActions.apply(phase)) {
actionNames = randomSubsetOf(validActions.apply(phase));
} else {
actionNames = randomSubsetOf(randomIntBetween(1, validActions.apply(phase).size()), validActions.apply(phase));
}
if ("hot".equals(phase)) {
actions.put(
RolloverAction.NAME,
new RolloverAction(null, new ByteSizeValue(randomNonNegativeLong()), null, randomNonNegativeLong())
);
}
if (searchableSnapshotSeen || actionNames.contains(SearchableSnapshotAction.NAME)) {
searchableSnapshotSeen = true;
// let's make sure phases don't configure actions that conflict with the `searchable_snapshot` action
actionNames.removeAll(TimeseriesLifecycleType.ACTIONS_CANNOT_FOLLOW_SEARCHABLE_SNAPSHOT);
}
if (actionNames.contains(MigrateAction.NAME)) {
actionNames.remove(AllocateAction.NAME);
}
for (String action : actionNames) {
actions.put(action, randomAction.apply(action));
}
phases.put(phase, new Phase(phase, after, actions));
}
return new LifecyclePolicy(lifecycleName, phases);
}
private LifecycleAction getTestAction(String actionName) {
return switch (actionName) {
case AllocateAction.NAME -> AllocateActionTests.randomInstance();
case DeleteAction.NAME -> new DeleteAction();
case ForceMergeAction.NAME -> ForceMergeActionTests.randomInstance();
case ReadOnlyAction.NAME -> new ReadOnlyAction();
case RolloverAction.NAME -> RolloverActionTests.randomInstance();
case ShrinkAction.NAME -> ShrinkActionTests.randomInstance();
case FreezeAction.NAME -> new FreezeAction();
case WaitForSnapshotAction.NAME -> WaitForSnapshotActionTests.randomInstance();
case SetPriorityAction.NAME -> SetPriorityActionTests.randomInstance();
case SearchableSnapshotAction.NAME -> SearchableSnapshotActionTests.randomInstance();
case UnfollowAction.NAME -> new UnfollowAction();
case MigrateAction.NAME -> new MigrateAction(randomBoolean());
default -> throw new IllegalArgumentException("unsupported phase action [" + actionName + "]");
};
}
}
|
package jp.gr.java_conf.spica.plugin.gradle.jacoco.internal.domain.coverage.model;
public class ClassCoverageTitle {
private final ClassCoverageLimit limit;
public ClassCoverageTitle(ClassCoverageLimit limit) {
this.limit = limit;
}
@Override
public String toString() {
return "Class list with less coverage"
+ (limit.hasLimit() ? " (Worst " + limit.limit() + ")" : "");
}
}
|
package com.github.switcherapi.client.model;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import com.github.switcherapi.client.SwitcherContext;
import com.github.switcherapi.client.exception.SwitcherException;
import com.github.switcherapi.client.factory.SwitcherExecutor;
import com.github.switcherapi.client.model.response.CriteriaResponse;
/**
* Switchers are responsible for wrapping the input and output coming from the Switcher API.
* <br>To execute a criteria evaluation, use one of the available methods: {@link #isItOn()}.
*
* @author Roger Floriano (petruki)
* @since 2019-12-24
*
* @see #isItOn()
* @see #isItOn(List)
* @see #isItOn(Entry, boolean)
*
*/
public class Switcher extends SwitcherBuilder {
public static final String KEY = "key";
public static final String SHOW_REASON = "showReason";
public static final String BYPASS_METRIC = "bypassMetric";
private AsyncSwitcher asyncSwitcher;
private SwitcherExecutor context;
private String switcherKey;
private Set<CriteriaResponse> historyExecution;
private boolean bypassMetrics = Boolean.FALSE;
private boolean showReason = Boolean.FALSE;
/**
* Use {@link SwitcherContext#getSwitcher(String)} to create this object.
*
* @param switcherKey name of the key created
* @param context configuration object containing all information to start using switchers
*/
public Switcher(final String switcherKey, final SwitcherExecutor context) {
this.switcherKey = switcherKey;
this.context = context;
this.historyExecution = new HashSet<>();
}
private boolean canUseAsync() {
return super.delay > 0 && !this.historyExecution.isEmpty();
}
private CriteriaResponse getFromHistory() {
return this.historyExecution.stream()
.filter(c -> c.getEntry().equals(getEntry()))
.findFirst()
.orElse(null);
}
@Override
public Switcher prepareEntry(final List<Entry> entry) {
this.entry = entry;
return this;
}
@Override
public Switcher prepareEntry(final Entry entry, final boolean add) {
if (this.entry == null)
this.entry = new ArrayList<>();
if (!add)
this.entry.clear();
if (!this.entry.contains(entry))
this.entry.add(entry);
return this;
}
@Override
public Switcher prepareEntry(final Entry entry) {
return this.prepareEntry(entry, false);
}
@Override
public boolean isItOn(final Entry entry, final boolean add)
throws SwitcherException {
this.prepareEntry(entry, add);
return this.isItOn();
}
@Override
public boolean isItOn(final List<Entry> entry) throws SwitcherException {
this.entry = entry;
return this.isItOn();
}
@Override
public boolean isItOn() throws SwitcherException {
if (SwitcherExecutor.getBypass().containsKey(switcherKey)) {
return SwitcherExecutor.getBypass().get(switcherKey);
}
if (canUseAsync()) {
if (asyncSwitcher == null)
asyncSwitcher = new AsyncSwitcher();
asyncSwitcher.execute(this);
final CriteriaResponse response = getFromHistory();
if (response != null)
return response.isItOn();
}
final CriteriaResponse response = this.context.executeCriteria(this);
this.historyExecution.add(response);
return response.isItOn();
}
/**
* This method builds up the request made by the client to reach the Switcher API.
*
* @return json input request
*/
public GsonInputRequest getInputRequest() {
return new GsonInputRequest(
this.entry != null ?
this.entry.toArray(new Entry[this.entry.size()]) : null);
}
public boolean isBypassMetrics() {
return bypassMetrics;
}
public void setBypassMetrics(boolean bypassMetrics) {
this.bypassMetrics = bypassMetrics;
}
public boolean isShowReason() {
return showReason;
}
public void setShowReason(boolean showReason) {
this.showReason = showReason;
}
public String getSwitcherKey() {
return this.switcherKey;
}
public List<Entry> getEntry() {
return this.entry;
}
public void resetEntry() {
this.entry = new ArrayList<Entry>();
}
public Set<CriteriaResponse> getHistoryExecution() {
return this.historyExecution;
}
public SwitcherExecutor getContext() {
return context;
}
@Override
public String toString() {
return String.format("Switcher [switcherKey= %s, entry= %s, bypassMetrics= %s, showReason= %s]",
switcherKey, entry, bypassMetrics, showReason);
}
public class GsonInputRequest {
private Entry[] entry;
public GsonInputRequest(final Entry[] entry) {
this.entry = entry;
}
public Entry[] getEntry() {
return this.entry;
}
}
}
|
/*
* Copyright (c) 2018.
* Development Lead: Cryptenet Ltd.
* Developer Credit:
* Alamgir Hossain,
* Md. Rezwanur Rahman Khan,
* Ashif Mujtoba
* This project is under Apache License 2.0
*/
package com.cryptenet.thanatos.dtmweb.home.thread_msg.mvp;
import android.content.Context;
import com.cryptenet.thanatos.dtmweb.di.scopes.PerFragment;
import com.cryptenet.thanatos.dtmweb.mvp_base.BaseFragModel;
import com.cryptenet.thanatos.dtmweb.mvp_contracts.ThreadMsgFragmentContract;
@PerFragment
public class ThreadMsgFragmentModel extends BaseFragModel<ThreadMsgFragmentContract.Repository>
implements ThreadMsgFragmentContract.Model {
// private static final String TAG = TagProvider.getDebugTag(ThreadMsgFragmentModel.class);
public ThreadMsgFragmentModel(ThreadMsgFragmentContract.Repository repository) {
super(repository);
}
@Override
public void getMessageList(Context context, int threadID) {
repository.getMessageList(context, threadID);
}
@Override
public void setSendMessage(Context context, int threadID, String message) {
repository.setSendMessage(context, threadID, message);
}
}
|
/*
* Licensed to Metamarkets Group Inc. (Metamarkets) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. Metamarkets licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package io.druid.query.aggregation.variance;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeName;
import com.google.common.base.Preconditions;
import com.google.common.collect.Sets;
import io.druid.query.aggregation.AggregatorFactory;
import io.druid.query.aggregation.PostAggregator;
import io.druid.query.aggregation.post.ArithmeticPostAggregator;
import io.druid.query.aggregation.post.PostAggregatorIds;
import io.druid.query.cache.CacheKeyBuilder;
import java.util.Comparator;
import java.util.Map;
import java.util.Set;
/**
*/
@JsonTypeName("stddev")
public class StandardDeviationPostAggregator implements PostAggregator
{
protected final String name;
protected final String fieldName;
protected final String estimator;
protected final boolean isVariancePop;
@JsonCreator
public StandardDeviationPostAggregator(
@JsonProperty("name") String name,
@JsonProperty("fieldName") String fieldName,
@JsonProperty("estimator") String estimator
)
{
this.fieldName = Preconditions.checkNotNull(fieldName, "fieldName is null");
this.name = Preconditions.checkNotNull(name, "name is null");
this.estimator = estimator;
this.isVariancePop = VarianceAggregatorCollector.isVariancePop(estimator);
}
@Override
public Set<String> getDependentFields()
{
return Sets.newHashSet(fieldName);
}
@Override
public Comparator<Double> getComparator()
{
return ArithmeticPostAggregator.DEFAULT_COMPARATOR;
}
@Override
public Object compute(Map<String, Object> combinedAggregators)
{
return Math.sqrt(((VarianceAggregatorCollector) combinedAggregators.get(fieldName)).getVariance(isVariancePop));
}
@Override
@JsonProperty("name")
public String getName()
{
return name;
}
@Override
public PostAggregator decorate(Map<String, AggregatorFactory> aggregators)
{
return this;
}
@JsonProperty("fieldName")
public String getFieldName()
{
return fieldName;
}
@JsonProperty("estimator")
public String getEstimator()
{
return estimator;
}
@Override
public String toString()
{
return "StandardDeviationPostAggregator{" +
"name='" + name + '\'' +
", fieldName='" + fieldName + '\'' +
", estimator='" + estimator + '\'' +
", isVariancePop=" + isVariancePop +
'}';
}
@Override
public byte[] getCacheKey()
{
return new CacheKeyBuilder(PostAggregatorIds.VARIANCE_STANDARD_DEVIATION)
.appendString(fieldName)
.appendString(estimator)
.appendBoolean(isVariancePop)
.build();
}
}
|
/*
* 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.cloudtrail.model.transform;
import java.math.*;
import javax.annotation.Generated;
import com.amazonaws.services.cloudtrail.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;
import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;
/**
* LookupEventsResult JSON Unmarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class LookupEventsResultJsonUnmarshaller implements Unmarshaller<LookupEventsResult, JsonUnmarshallerContext> {
public LookupEventsResult unmarshall(JsonUnmarshallerContext context) throws Exception {
LookupEventsResult lookupEventsResult = new LookupEventsResult();
int originalDepth = context.getCurrentDepth();
String currentParentElement = context.getCurrentParentElement();
int targetDepth = originalDepth + 1;
JsonToken token = context.getCurrentToken();
if (token == null)
token = context.nextToken();
if (token == VALUE_NULL) {
return lookupEventsResult;
}
while (true) {
if (token == null)
break;
if (token == FIELD_NAME || token == START_OBJECT) {
if (context.testExpression("Events", targetDepth)) {
context.nextToken();
lookupEventsResult.setEvents(new ListUnmarshaller<Event>(EventJsonUnmarshaller.getInstance()).unmarshall(context));
}
if (context.testExpression("NextToken", targetDepth)) {
context.nextToken();
lookupEventsResult.setNextToken(context.getUnmarshaller(String.class).unmarshall(context));
}
} else if (token == END_ARRAY || token == END_OBJECT) {
if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {
if (context.getCurrentDepth() <= originalDepth)
break;
}
}
token = context.nextToken();
}
return lookupEventsResult;
}
private static LookupEventsResultJsonUnmarshaller instance;
public static LookupEventsResultJsonUnmarshaller getInstance() {
if (instance == null)
instance = new LookupEventsResultJsonUnmarshaller();
return instance;
}
}
|
package com.google.android.gms.internal.clearcut;
import java.io.IOException;
public interface zzan<T> {
T zzb(byte[] bArr) throws IOException;
}
|
package ru.job4j.oop;
public class Profession {
private String name;
private String surname;
private String education;
public Profession() {
}
public Profession(String name, String surname, String education) {
this.name = name;
this.surname = surname;
this.education = education;
}
public String getName() {
return this.name;
}
public String getSurname() {
return this.surname;
}
public String getEducation() {
return this.education;
}
}
|
package uk.ac.lkl.client;
import java.util.ArrayList;
import java.util.HashMap;
import uk.ac.lkl.client.composer.CustomisationPopupPanel;
import uk.ac.lkl.client.composer.MacroBehaviourView;
import uk.ac.lkl.client.composer.MicroBehaviourEnhancement;
import uk.ac.lkl.client.composer.MicroBehaviourView;
import uk.ac.lkl.shared.CommonUtils;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.ui.Anchor;
/**
* Implements links that open in resource tabs
*
* @author Ken Kahn
*
*/
public class InternalHyperlink extends Anchor {
// protected String url;
// protected BrowsePanel browsePanel;
public InternalHyperlink(final String html, final String url, final BrowsePanel browsePanel, final boolean reuseBrowsePanel) {
// if reuseBrowsePanel is false then browsePanel is considered the instigatingBrowsePanel
// reuseBrowsePanel is true when re-opening a tab via the '+' tab
super(html, true);
// this.url = url;
// this.browsePanel = browsePanel;
setStylePrimaryName("modeller-InternalHyperLink");
setTitle(Modeller.constants.clickToOpenThisInANewTab());
ensureDebugId(Integer.toString(Modeller.debugIDCounter++));
addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
// following may be needed if for example in split screen and Help tab is in other panel
Modeller.switchToResourcesPanel();
// TODO: determine if this can instead make use of openInBrowsePanel
final String urlString = CommonUtils.joinPaths(browsePanel.getCurrentURLBase(), url);
final BrowsePanel openBrowsePanel = Modeller.getOpenBrowsePanel(urlString);
final int selectedIndex = Modeller.mainTabPanel.getSelectedIndex();
if (openBrowsePanel != null) {
CustomisationPopupPanel customisationPopupPanel = Utils.getAncestorWidget(openBrowsePanel, CustomisationPopupPanel.class);
if (customisationPopupPanel != null) {
customisationPopupPanel.setVisible(false);
Timer timer = new Timer() {
@Override
public void run() {
openBrowsePanel.getMicroBehaviour().openCustomisePanel();
}
};
timer.schedule(500);
return;
}
}
HashMap<Integer, String> textAreaValues =
reuseBrowsePanel ? browsePanel.getTextAreaValues() : null;
ArrayList<MicroBehaviourEnhancement> enhancements =
reuseBrowsePanel ? browsePanel.getEnhancements() : null;
ArrayList<MacroBehaviourView> macroBehaviours =
reuseBrowsePanel ? browsePanel.getMacroBehaviourViews() : null;
String tabName = reuseBrowsePanel ? html : Utils.goodTabNameFromURL(url);
BrowsePanelCommand commandWhenLoaded =
new BrowsePanelCommand() {
@Override
public void execute(final BrowsePanel panel, String[] answer, boolean panelIsNew) {
panel.scrollToTop();
BrowsePanel.addBrowsedURLs(urlString);
if (CommonUtils.hasChangesGuid(urlString)) {
Command commandAfterUpdate = new Command() {
@Override
public void execute() {
customisationPanelOrTab(panel);
}
};
panel.fetchAndUpdate(commandAfterUpdate);
} else {
customisationPanelOrTab(panel);
}
}
/**
* If panel holds a micro-behaviour then creates a customisation panel
* otherwise selects the browse panel
*
* @param panel
*/
public void customisationPanelOrTab(final BrowsePanel panel) {
MicroBehaviourView microBehaviour = panel.getMicroBehaviour();
if (microBehaviour != null) {
Modeller.mainTabPanel.remove(panel);
CustomisationPopupPanel customisationPopupPanel = Utils.getAncestorWidget(InternalHyperlink.this, CustomisationPopupPanel.class);
if (customisationPopupPanel == null) {
BrowsePanel containingBrowsePanel = Utils.getAncestorWidget(InternalHyperlink.this, BrowsePanel.class);
if (containingBrowsePanel != null && Modeller.mainTabPanel.getWidgetIndex(containingBrowsePanel) >= 0) {
// restore panel that this link lives on
Modeller.mainTabPanel.selectTab(containingBrowsePanel);
}
} else if (Modeller.mainTabPanel.getWidgetCount() > selectedIndex) {
Modeller.mainTabPanel.selectTab(selectedIndex);
}
if (reuseBrowsePanel || Utils.urlAttributeNotZero("OpenTabsForLinks", false)) {
// reuseBrowsePanel re-opens previously closed tabs
// addresses Issue 972
microBehaviour.openInBrowsePanel(true);
} else {
CustomisationPopupPanel customisationPanel = new CustomisationPopupPanel();
microBehaviour.updateCustomisationPanel(panel, customisationPanel);
}
panel.scrollToTop();
} else {
Modeller.mainTabPanel.selectTab(panel);
}
}
};
BrowsePanel newBrowsePanel =
Modeller.browseToNewTab(
tabName,
textAreaValues,
enhancements,
macroBehaviours,
urlString,
// the following is NOT an instigating micro-behaviour
// just because it has a link to a micro-behaviour
null, // browsePanel.getMicroBehaviour(),
null,
commandWhenLoaded,
true,
false,
true,
false);
Modeller.setProtectedBrowsePanel(newBrowsePanel);
}
});
}
}
|
/**
* Copyright 2009-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ibatis.mapping;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.apache.ibatis.cache.Cache;
import org.apache.ibatis.executor.keygen.Jdbc3KeyGenerator;
import org.apache.ibatis.executor.keygen.KeyGenerator;
import org.apache.ibatis.executor.keygen.NoKeyGenerator;
import org.apache.ibatis.logging.Log;
import org.apache.ibatis.logging.LogFactory;
import org.apache.ibatis.scripting.LanguageDriver;
import org.apache.ibatis.session.Configuration;
/**
* @author Clinton Begin
*/
public final class MappedStatement {
private String resource;
private Configuration configuration;
/**
* 即:完整方法名(包括包、类名)
* mapperInterface.getName() + "." + methodName
*/
private String id;
private Integer fetchSize;
private Integer timeout;
private StatementType statementType;
private ResultSetType resultSetType;
private SqlSource sqlSource;
private Cache cache;
private ParameterMap parameterMap;
private List<ResultMap> resultMaps;
private boolean flushCacheRequired;
private boolean useCache;
private boolean resultOrdered;
private SqlCommandType sqlCommandType;
private KeyGenerator keyGenerator;
private String[] keyProperties;
private String[] keyColumns;
private boolean hasNestedResultMaps;
private String databaseId;
private Log statementLog;
private LanguageDriver lang;
private String[] resultSets;
MappedStatement() {
// constructor disabled
}
public static class Builder {
private MappedStatement mappedStatement = new MappedStatement();
public Builder(Configuration configuration, String id, SqlSource sqlSource, SqlCommandType sqlCommandType) {
mappedStatement.configuration = configuration;
mappedStatement.id = id;
mappedStatement.sqlSource = sqlSource;
mappedStatement.statementType = StatementType.PREPARED;
mappedStatement.resultSetType = ResultSetType.DEFAULT;
mappedStatement.parameterMap = new ParameterMap.Builder(configuration, "defaultParameterMap", null, new ArrayList<>()).build();
mappedStatement.resultMaps = new ArrayList<>();
mappedStatement.sqlCommandType = sqlCommandType;
mappedStatement.keyGenerator = configuration.isUseGeneratedKeys() && SqlCommandType.INSERT.equals(sqlCommandType) ? Jdbc3KeyGenerator.INSTANCE : NoKeyGenerator.INSTANCE;
String logId = id;
if (configuration.getLogPrefix() != null) {
logId = configuration.getLogPrefix() + id;
}
mappedStatement.statementLog = LogFactory.getLog(logId);
mappedStatement.lang = configuration.getDefaultScriptingLanguageInstance();
}
public Builder resource(String resource) {
mappedStatement.resource = resource;
return this;
}
/**
* <p> mapperInterface.getName() + "." + methodName。</p>
*/
public String id() {
return mappedStatement.id;
}
public Builder parameterMap(ParameterMap parameterMap) {
mappedStatement.parameterMap = parameterMap;
return this;
}
public Builder resultMaps(List<ResultMap> resultMaps) {
mappedStatement.resultMaps = resultMaps;
for (ResultMap resultMap : resultMaps) {
mappedStatement.hasNestedResultMaps = mappedStatement.hasNestedResultMaps || resultMap.hasNestedResultMaps();
}
return this;
}
public Builder fetchSize(Integer fetchSize) {
mappedStatement.fetchSize = fetchSize;
return this;
}
public Builder timeout(Integer timeout) {
mappedStatement.timeout = timeout;
return this;
}
public Builder statementType(StatementType statementType) {
mappedStatement.statementType = statementType;
return this;
}
public Builder resultSetType(ResultSetType resultSetType) {
mappedStatement.resultSetType = resultSetType == null ? ResultSetType.DEFAULT : resultSetType;
return this;
}
public Builder cache(Cache cache) {
mappedStatement.cache = cache;
return this;
}
public Builder flushCacheRequired(boolean flushCacheRequired) {
mappedStatement.flushCacheRequired = flushCacheRequired;
return this;
}
public Builder useCache(boolean useCache) {
mappedStatement.useCache = useCache;
return this;
}
public Builder resultOrdered(boolean resultOrdered) {
mappedStatement.resultOrdered = resultOrdered;
return this;
}
public Builder keyGenerator(KeyGenerator keyGenerator) {
mappedStatement.keyGenerator = keyGenerator;
return this;
}
public Builder keyProperty(String keyProperty) {
mappedStatement.keyProperties = delimitedStringToArray(keyProperty);
return this;
}
public Builder keyColumn(String keyColumn) {
mappedStatement.keyColumns = delimitedStringToArray(keyColumn);
return this;
}
public Builder databaseId(String databaseId) {
mappedStatement.databaseId = databaseId;
return this;
}
public Builder lang(LanguageDriver driver) {
mappedStatement.lang = driver;
return this;
}
public Builder resultSets(String resultSet) {
mappedStatement.resultSets = delimitedStringToArray(resultSet);
return this;
}
/**
* Resul sets.
*
* @param resultSet
* the result set
* @return the builder
* @deprecated Use {@link #resultSets}
*/
@Deprecated
public Builder resulSets(String resultSet) {
mappedStatement.resultSets = delimitedStringToArray(resultSet);
return this;
}
public MappedStatement build() {
assert mappedStatement.configuration != null;
assert mappedStatement.id != null;
assert mappedStatement.sqlSource != null;
assert mappedStatement.lang != null;
mappedStatement.resultMaps = Collections.unmodifiableList(mappedStatement.resultMaps);
return mappedStatement;
}
}
public KeyGenerator getKeyGenerator() {
return keyGenerator;
}
public SqlCommandType getSqlCommandType() {
return sqlCommandType;
}
public String getResource() {
return resource;
}
public Configuration getConfiguration() {
return configuration;
}
public String getId() {
return id;
}
public boolean hasNestedResultMaps() {
return hasNestedResultMaps;
}
public Integer getFetchSize() {
return fetchSize;
}
public Integer getTimeout() {
return timeout;
}
public StatementType getStatementType() {
return statementType;
}
public ResultSetType getResultSetType() {
return resultSetType;
}
public SqlSource getSqlSource() {
return sqlSource;
}
public ParameterMap getParameterMap() {
return parameterMap;
}
public List<ResultMap> getResultMaps() {
return resultMaps;
}
public Cache getCache() {
return cache;
}
public boolean isFlushCacheRequired() {
return flushCacheRequired;
}
public boolean isUseCache() {
return useCache;
}
public boolean isResultOrdered() {
return resultOrdered;
}
public String getDatabaseId() {
return databaseId;
}
public String[] getKeyProperties() {
return keyProperties;
}
public String[] getKeyColumns() {
return keyColumns;
}
public Log getStatementLog() {
return statementLog;
}
public LanguageDriver getLang() {
return lang;
}
public String[] getResultSets() {
return resultSets;
}
/**
* Gets the resul sets.
*
* @return the resul sets
* @deprecated Use {@link #getResultSets()}
*/
@Deprecated
public String[] getResulSets() {
return resultSets;
}
public BoundSql getBoundSql(Object parameterObject) {
BoundSql boundSql = sqlSource.getBoundSql(parameterObject);
List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
if (parameterMappings == null || parameterMappings.isEmpty()) {
boundSql = new BoundSql(configuration, boundSql.getSql(), parameterMap.getParameterMappings(), parameterObject);
}
// check for nested result maps in parameter mappings (issue #30)
for (ParameterMapping pm : boundSql.getParameterMappings()) {
String rmId = pm.getResultMapId();
if (rmId != null) {
ResultMap rm = configuration.getResultMap(rmId);
if (rm != null) {
hasNestedResultMaps |= rm.hasNestedResultMaps();
}
}
}
return boundSql;
}
private static String[] delimitedStringToArray(String in) {
if (in == null || in.trim().length() == 0) {
return null;
} else {
return in.split(",");
}
}
}
|
package main.edu.algorithm.week1;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class MaxPairwiseProduct {
public static long getMaxPairwiseProduct(int[] numbers) {
long max_product = 0;
int n = numbers.length;
for (int first = 0; first < n; ++first) {
for (int second = first + 1; second < n; ++second) {
long firstNum = numbers[first];
long secondNum = numbers[second];
max_product = Math.max(max_product, firstNum * secondNum );
}
}
return max_product;
}
public static void main(String[] args) {
FastScanner scanner = new FastScanner(System.in);
int n = scanner.nextInt();
int[] numbers = new int[n];
for (int i = 0; i < n; i++) {
numbers[i] = scanner.nextInt();
}
System.out.println(getMaxPairwiseProduct(numbers));
/* This code snippet is used to test the time needed to run the program
int [] numbers = new int[100000];
Instant start = Instant.now();
System.out.println(getMaxPairwiseProduct(numbers));
Instant end = Instant.now();
System.out.println(Duration.between(end,start)); // PT-18.426949S
*/
}
static class FastScanner {
BufferedReader br;
StringTokenizer st;
FastScanner(InputStream stream) {
try {
br = new BufferedReader(new
InputStreamReader(stream));
} catch (Exception e) {
e.printStackTrace();
}
}
String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
}
}
|
/*
* 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.dubbo.rpc;
/**
*
*/
public abstract class AbstractPostProcessFilter implements PostProcessFilter {
@Override
public Result postProcessResult(Result result, Invoker<?> invoker, Invocation invocation) {
if (result instanceof AsyncRpcResult) {
AsyncRpcResult asyncResult = (AsyncRpcResult) result;
asyncResult.thenApplyWithContext(r -> doPostProcess(r, invoker, invocation));
return asyncResult;
} else {
return doPostProcess(result, invoker, invocation);
}
}
protected abstract Result doPostProcess(Result result, Invoker<?> invoker, Invocation invocation);
}
|
package asm3.model;
public class Product {
private Integer id;
private String name;
private String description;
private Double price;
private String src;
private String type;
private String brand;
private Integer number = 1;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
public String getSrc() {
return src;
}
public void setSrc(String src) {
this.src = src;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public Integer getNumber() {
return number;
}
public void setNumber(Integer number) {
this.number = number;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof Product) {
return ((Product)obj).getId() == id;
};
return false;
}
}
|
package utilities.loggers.enums;
public enum LayoutTypes {
SIMPLE("SimpleLayout"),
XML("XmlLayout"),
TEST("TestLayout");
private final String name;
LayoutTypes(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
|
/*
* Copyright (c) 2010-2022. Axon Framework
*
* 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.axonframework.modelling.command;
import org.axonframework.common.Assert;
import org.axonframework.common.lock.Lock;
import org.axonframework.common.lock.LockFactory;
import org.axonframework.common.lock.PessimisticLockFactory;
import org.axonframework.messaging.annotation.HandlerDefinition;
import org.axonframework.messaging.annotation.ParameterResolverFactory;
import org.axonframework.messaging.unitofwork.CurrentUnitOfWork;
import org.axonframework.messaging.unitofwork.UnitOfWork;
import org.axonframework.modelling.command.inspection.AggregateModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Objects;
import java.util.concurrent.Callable;
import java.util.function.Supplier;
import javax.annotation.Nonnull;
import static org.axonframework.common.BuilderUtils.assertNonNull;
import static org.axonframework.common.ObjectUtils.sameInstanceSupplier;
/**
* Implementation of the Repository interface that takes provides a locking mechanism to prevent concurrent
* modifications of persisted aggregates. Unless there is a locking mechanism present in the underlying persistence
* environment, it is recommended to use a LockingRepository (or one of its subclasses).
* <p/>
* The LockingRepository can be initialized with a locking strategy. <em>Pessimistic Locking</em> is the default
* strategy. Pessimistic Locking requires an exclusive lock to be handed to a thread loading an aggregate before the
* aggregate is handed over. This means that, once an aggregate is loaded, it has full exclusive access to it, until it
* saves the aggregate.
* <p/>
* Important: If an exception is thrown during the saving process, any locks held are released. The calling thread may
* reattempt saving the aggregate again. If the lock is available, the thread automatically takes back the lock. If,
* however, another thread has obtained the lock first, a ConcurrencyException is thrown.
*
* @param <T> The type that this aggregate stores
* @author Allard Buijze
* @since 0.3
*/
public abstract class LockingRepository<T, A extends Aggregate<T>> extends
AbstractRepository<T, LockAwareAggregate<T, A>> {
private static final Logger logger = LoggerFactory.getLogger(LockingRepository.class);
private final LockFactory lockFactory;
/**
* Instantiate a {@link LockingRepository} based on the fields contained in the {@link Builder}.
* <p>
* A goal of the provided Builder is to create an {@link AggregateModel} specifying generic {@code T} as the
* aggregate type to be stored. All aggregates in this repository must be {@code instanceOf} this aggregate type. To
* instantiate this AggregateModel, either an {@link AggregateModel} can be provided directly or an {@code
* aggregateType} of type {@link Class} can be used. The latter will internally resolve to an AggregateModel. Thus,
* either the AggregateModel <b>or</b> the {@code aggregateType} should be provided. An {@link
* org.axonframework.common.AxonConfigurationException} is thrown if this criteria is not met.
* <p>
* Additionally will assert that the {@link LockFactory} is not {@code null}, resulting in an
* AxonConfigurationException if this is the case.
*
* @param builder the {@link Builder} used to instantiate a {@link LockingRepository} instance
*/
protected LockingRepository(Builder<T> builder) {
super(builder);
this.lockFactory = builder.lockFactory;
}
@Override
protected LockAwareAggregate<T, A> doCreateNew(Callable<T> factoryMethod) throws Exception {
UnitOfWork<?> unitOfWork = CurrentUnitOfWork.get();
A aggregate = doCreateNewForLock(factoryMethod);
final String aggregateIdentifier = aggregate.identifierAsString();
Supplier<Lock> lockSupplier;
if (!Objects.isNull(aggregateIdentifier)) {
Lock lock = lockFactory.obtainLock(aggregateIdentifier);
unitOfWork.onCleanup(u -> lock.release());
lockSupplier = () -> lock;
} else {
// The aggregate identifier hasn't been set yet, so the lock should be created in the supplier.
lockSupplier = sameInstanceSupplier(() -> {
Lock lock = lockFactory.obtainLock(aggregate.identifierAsString());
unitOfWork.onCleanup(u -> lock.release());
return lock;
});
}
return new LockAwareAggregate<>(aggregate, lockSupplier);
}
/**
* Creates a new aggregate instance using the given {@code factoryMethod}. Implementations should assume that this
* method is only called if a UnitOfWork is currently active.
*
* @param factoryMethod The method to create the aggregate's root instance
* @return an Aggregate instance describing the aggregate's state
* @throws Exception when the factoryMethod throws an exception
*/
protected abstract A doCreateNewForLock(Callable<T> factoryMethod) throws Exception;
/**
* Perform the actual loading of an aggregate. The necessary locks have been obtained.
*
* @param aggregateIdentifier the identifier of the aggregate to load
* @param expectedVersion The expected version of the aggregate
* @return the fully initialized aggregate
* @throws AggregateNotFoundException if aggregate with given id cannot be found
*/
@Override
protected LockAwareAggregate<T, A> doLoad(String aggregateIdentifier, Long expectedVersion) {
Lock lock = lockFactory.obtainLock(aggregateIdentifier);
try {
final A aggregate = doLoadWithLock(aggregateIdentifier, expectedVersion);
CurrentUnitOfWork.get().onCleanup(u -> lock.release());
return new LockAwareAggregate<>(aggregate, lock);
} catch (Throwable ex) {
logger.debug("Exception occurred while trying to load an aggregate. Releasing lock.", ex);
lock.release();
throw ex;
}
}
@Override
protected LockAwareAggregate<T, A> doLoadOrCreate(String aggregateIdentifier,
Callable<T> factoryMethod) throws Exception {
Lock lock = lockFactory.obtainLock(aggregateIdentifier);
try {
final A aggregate = doLoadWithLock(aggregateIdentifier, null);
CurrentUnitOfWork.get().onCleanup(u -> lock.release());
return new LockAwareAggregate<>(aggregate, lock);
} catch (AggregateNotFoundException ex) {
final A aggregate = doCreateNewForLock(factoryMethod);
CurrentUnitOfWork.get().onCleanup(u -> lock.release());
return new LockAwareAggregate<>(aggregate, lock);
} catch (Throwable ex) {
logger.debug("Exception occurred while trying to load/create an aggregate. Releasing lock.", ex);
lock.release();
throw ex;
}
}
@Override
protected void prepareForCommit(LockAwareAggregate<T, A> aggregate) {
Assert.state(aggregate.isLockHeld(), () -> "An aggregate is being used for which a lock is no longer held");
super.prepareForCommit(aggregate);
}
/**
* Verifies whether all locks are valid and delegates to {@link #doSaveWithLock(Aggregate)} to perform actual
* storage.
*
* @param aggregate the aggregate to store
*/
@Override
protected void doSave(LockAwareAggregate<T, A> aggregate) {
if (aggregate.version() != null && !aggregate.isLockHeld()) {
throw new ConcurrencyException(String.format(
"The aggregate of type [%s] with identifier [%s] could not be " +
"saved, as a valid lock is not held. Either another thread has saved an aggregate, or " +
"the current thread had released its lock earlier on.",
aggregate.getClass().getSimpleName(), aggregate.identifierAsString()));
}
doSaveWithLock(aggregate.getWrappedAggregate());
}
/**
* Verifies whether all locks are valid and delegates to {@link #doDeleteWithLock(Aggregate)} to perform actual
* deleting.
*
* @param aggregate the aggregate to delete
*/
@Override
protected final void doDelete(LockAwareAggregate<T, A> aggregate) {
if (aggregate.version() != null && !aggregate.isLockHeld()) {
throw new ConcurrencyException(String.format(
"The aggregate of type [%s] with identifier [%s] could not be " +
"saved, as a valid lock is not held. Either another thread has saved an aggregate, or " +
"the current thread had released its lock earlier on.",
aggregate.getClass().getSimpleName(), aggregate.identifierAsString()));
}
doDeleteWithLock(aggregate.getWrappedAggregate());
}
/**
* Perform the actual saving of the aggregate. All necessary locks have been verified.
*
* @param aggregate the aggregate to store
*/
protected abstract void doSaveWithLock(A aggregate);
/**
* Perform the actual deleting of the aggregate. All necessary locks have been verified.
*
* @param aggregate the aggregate to delete
*/
protected abstract void doDeleteWithLock(A aggregate);
/**
* Loads the aggregate with the given aggregateIdentifier. All necessary locks have been obtained.
*
* @param aggregateIdentifier the identifier of the aggregate to load
* @param expectedVersion The expected version of the aggregate to load
* @return a fully initialized aggregate
* @throws AggregateNotFoundException if the aggregate with given identifier does not exist
*/
protected abstract A doLoadWithLock(String aggregateIdentifier, Long expectedVersion);
/**
* Abstract Builder class to instantiate {@link LockingRepository} implementations.
* <p>
* The {@link LockFactory} is defaulted to a pessimistic locking strategy, implemented in the {@link
* PessimisticLockFactory}. A goal of this Builder goal is to create an {@link AggregateModel} specifying generic
* {@code T} as the aggregate type to be stored. All aggregates in this repository must be {@code instanceOf} this
* aggregate type. To instantiate this AggregateModel, either an {@link AggregateModel} can be provided directly or
* an {@code aggregateType} of type {@link Class} can be used. The latter will internally resolve to an
* AggregateModel. Thus, either the AggregateModel <b>or</b> the {@code aggregateType} should be provided.
*
* @param <T> a generic specifying the Aggregate type contained in this {@link Repository} implementation
*/
protected static abstract class Builder<T> extends AbstractRepository.Builder<T> {
private LockFactory lockFactory = PessimisticLockFactory.usingDefaults();
/**
* Creates a builder for a Repository for given {@code aggregateType}.
*
* @param aggregateType the {@code aggregateType} specifying the type of aggregate this {@link Repository} will
* store
*/
protected Builder(Class<T> aggregateType) {
super(aggregateType);
}
@Override
public Builder<T> parameterResolverFactory(@Nonnull ParameterResolverFactory parameterResolverFactory) {
super.parameterResolverFactory(parameterResolverFactory);
return this;
}
@Override
public Builder<T> handlerDefinition(@Nonnull HandlerDefinition handlerDefinition) {
super.handlerDefinition(handlerDefinition);
return this;
}
@Override
public Builder<T> aggregateModel(@Nonnull AggregateModel<T> aggregateModel) {
super.aggregateModel(aggregateModel);
return this;
}
/**
* Sets the {@link LockFactory} used to lock an aggregate. Defaults to a pessimistic locking strategy,
* implemented in the {@link PessimisticLockFactory}.
*
* @param lockFactory a {@link LockFactory} used to lock an aggregate
* @return the current Builder instance, for fluent interfacing
*/
public Builder<T> lockFactory(LockFactory lockFactory) {
assertNonNull(lockFactory, "LockFactory may not be null");
this.lockFactory = lockFactory;
return this;
}
}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ignite.internal.processors.cache;
import org.apache.ignite.IgniteCheckedException;
import static org.apache.ignite.transactions.TransactionConcurrency.OPTIMISTIC;
import static org.apache.ignite.transactions.TransactionConcurrency.PESSIMISTIC;
import static org.apache.ignite.transactions.TransactionIsolation.READ_COMMITTED;
import static org.apache.ignite.transactions.TransactionIsolation.REPEATABLE_READ;
import static org.apache.ignite.transactions.TransactionIsolation.SERIALIZABLE;
/**
* Tests for local transactions.
*/
@SuppressWarnings( {"BusyWait"})
public abstract class IgniteTxSingleThreadedAbstractTest extends IgniteTxAbstractTest {
/**
* @throws IgniteCheckedException If test failed.
*/
public void testPessimisticReadCommittedCommit() throws Exception {
checkCommit(PESSIMISTIC, READ_COMMITTED);
finalChecks();
}
/**
* @throws IgniteCheckedException If test failed.
*/
public void testPessimisticRepeatableReadCommit() throws Exception {
checkCommit(PESSIMISTIC, REPEATABLE_READ);
finalChecks();
}
/**
* @throws IgniteCheckedException If test failed.
*/
public void testPessimisticSerializableCommit() throws Exception {
checkCommit(PESSIMISTIC, SERIALIZABLE);
finalChecks();
}
/**
* @throws IgniteCheckedException If test failed.
*/
public void testOptimisticReadCommittedCommit() throws Exception {
checkCommit(OPTIMISTIC, READ_COMMITTED);
finalChecks();
}
/**
* @throws IgniteCheckedException If test failed.
*/
public void testOptimisticRepeatableReadCommit() throws Exception {
checkCommit(OPTIMISTIC, REPEATABLE_READ);
finalChecks();
}
/**
* @throws IgniteCheckedException If test failed.
*/
public void testOptimisticSerializableCommit() throws Exception {
checkCommit(OPTIMISTIC, SERIALIZABLE);
finalChecks();
}
/**
* @throws IgniteCheckedException If test failed.
*/
public void testPessimisticReadCommittedRollback() throws Exception {
checkRollback(PESSIMISTIC, READ_COMMITTED);
finalChecks();
}
/**
* @throws IgniteCheckedException If test failed.
*/
public void testPessimisticRepeatableReadRollback() throws Exception {
checkRollback(PESSIMISTIC, REPEATABLE_READ);
finalChecks();
}
/**
* @throws IgniteCheckedException If test failed.
*/
public void testPessimisticSerializableRollback() throws Exception {
checkRollback(PESSIMISTIC, SERIALIZABLE);
finalChecks();
}
/**
* @throws IgniteCheckedException If test failed.
*/
public void testOptimisticReadCommittedRollback() throws Exception {
checkRollback(OPTIMISTIC, READ_COMMITTED);
finalChecks();
}
/**
* @throws IgniteCheckedException If test failed.
*/
public void testOptimisticRepeatableReadRollback() throws Exception {
checkRollback(OPTIMISTIC, REPEATABLE_READ);
finalChecks();
}
/**
* @throws IgniteCheckedException If test failed.
*/
public void testOptimisticSerializableRollback() throws Exception {
checkRollback(OPTIMISTIC, SERIALIZABLE);
finalChecks();
}
}
|
package ca.csf.dfc.classes;
public class TransactionInteret extends Transaction {
public TransactionInteret(double p_montant) {
super(TransactionType.DEBIT, p_montant, "Application d'un intérêt");
}
}
|
package com.test;
/**
* @className: MyClassTest
* @description:
* @author SunHang
* @createTime 2021/4/13 18:42
*/
public class MyClassTest {
public static void main(String[] args) {
MyClass myClass = new MyClass();
myClass.setS(100);
Object s = myClass.getS();
MyClass<String, Integer> myClass1 = new MyClass<>();
myClass1.setS("saf");
System.out.println(myClass1.getS());
myClass1.setT(2341);
System.out.println(myClass1.getT());
}
}
|
package org.jtrim2.collections;
import java.util.Iterator;
import org.jtrim2.collections.RefList.ElementRef;
import org.junit.Test;
import static org.junit.Assert.*;
public class ElementRefIterableTest {
/**
* Test of iterator method, of class ElementRefIterable.
*/
@Test
public void testIterator() {
int[] expected = new int[]{10, 11, 13};
RefList<Integer> list = new RefLinkedList<>();
for (int i = 0; i < expected.length; i++) {
list.add(expected[i]);
}
ElementRefIterable<Integer> iterable = new ElementRefIterable<>(list);
Iterator<ElementRef<Integer>> itr = iterable.iterator();
assertTrue(itr instanceof ElementRefIterator);
for (int i = 0; i < expected.length; i++) {
assertTrue(itr.hasNext());
assertEquals(expected[i], itr.next().getElement().intValue());
}
assertFalse(itr.hasNext());
}
}
|
package com.termux.app;
import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.net.Uri;
import android.net.wifi.WifiManager;
import android.os.Binder;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.PowerManager;
import android.provider.Settings;
import android.widget.ArrayAdapter;
import androidx.annotation.Nullable;
import com.termux.R;
import com.termux.app.settings.properties.TermuxAppSharedProperties;
import com.termux.app.terminal.TermuxTerminalSessionClient;
import com.termux.app.utils.PluginUtils;
import com.termux.shared.data.IntentUtils;
import com.termux.shared.models.errors.Errno;
import com.termux.shared.shell.ShellUtils;
import com.termux.shared.shell.TermuxShellEnvironmentClient;
import com.termux.shared.shell.TermuxShellUtils;
import com.termux.shared.termux.TermuxConstants;
import com.termux.shared.termux.TermuxConstants.TERMUX_APP.TERMUX_ACTIVITY;
import com.termux.shared.termux.TermuxConstants.TERMUX_APP.TERMUX_SERVICE;
import com.termux.shared.settings.preferences.TermuxAppSharedPreferences;
import com.termux.shared.shell.TermuxSession;
import com.termux.shared.terminal.TermuxTerminalSessionClientBase;
import com.termux.shared.logger.Logger;
import com.termux.shared.notification.NotificationUtils;
import com.termux.shared.packages.PermissionUtils;
import com.termux.shared.data.DataUtils;
import com.termux.shared.models.ExecutionCommand;
import com.termux.shared.shell.TermuxTask;
import com.termux.terminal.TerminalEmulator;
import com.termux.terminal.TerminalSession;
import com.termux.terminal.TerminalSessionClient;
import java.util.ArrayList;
import java.util.List;
/**
* A service holding a list of {@link TermuxSession} in {@link #mTermuxSessions} and background {@link TermuxTask}
* in {@link #mTermuxTasks}, showing a foreground notification while running so that it is not terminated.
* The user interacts with the session through {@link TermuxActivity}, but this service may outlive
* the activity when the user or the system disposes of the activity. In that case the user may
* restart {@link TermuxActivity} later to yet again access the sessions.
* <p/>
* In order to keep both terminal sessions and spawned processes (who may outlive the terminal sessions) alive as long
* as wanted by the user this service is a foreground service, {@link Service#startForeground(int, Notification)}.
* <p/>
* Optionally may hold a wake and a wifi lock, in which case that is shown in the notification - see
* {@link #buildNotification()}.
*/
public final class TermuxService extends Service implements TermuxTask.TermuxTaskClient, TermuxSession.TermuxSessionClient {
private static int EXECUTION_ID = 1000;
/** This service is only bound from inside the same process and never uses IPC. */
class LocalBinder extends Binder {
public final TermuxService service = TermuxService.this;
}
private final IBinder mBinder = new LocalBinder();
private final Handler mHandler = new Handler();
/**
* The foreground TermuxSessions which this service manages.
* Note that this list is observed by {@link TermuxActivity#mTermuxSessionListViewController},
* so any changes must be made on the UI thread and followed by a call to
* {@link ArrayAdapter#notifyDataSetChanged()} }.
*/
final List<TermuxSession> mTermuxSessions = new ArrayList<>();
/**
* The background TermuxTasks which this service manages.
*/
final List<TermuxTask> mTermuxTasks = new ArrayList<>();
/**
* The pending plugin ExecutionCommands that have yet to be processed by this service.
*/
final List<ExecutionCommand> mPendingPluginExecutionCommands = new ArrayList<>();
/** The full implementation of the {@link TerminalSessionClient} interface to be used by {@link TerminalSession}
* that holds activity references for activity related functions.
* Note that the service may often outlive the activity, so need to clear this reference.
*/
TermuxTerminalSessionClient mTermuxTerminalSessionClient;
/** The basic implementation of the {@link TerminalSessionClient} interface to be used by {@link TerminalSession}
* that does not hold activity references.
*/
final TermuxTerminalSessionClientBase mTermuxTerminalSessionClientBase = new TermuxTerminalSessionClientBase();
/** The wake lock and wifi lock are always acquired and released together. */
private PowerManager.WakeLock mWakeLock;
private WifiManager.WifiLock mWifiLock;
/** If the user has executed the {@link TERMUX_SERVICE#ACTION_STOP_SERVICE} intent. */
boolean mWantsToStop = false;
public Integer mTerminalTranscriptRows;
private static final String LOG_TAG = "TermuxService";
@Override
public void onCreate() {
Logger.logVerbose(LOG_TAG, "onCreate");
runStartForeground();
}
@SuppressLint("Wakelock")
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Logger.logDebug(LOG_TAG, "onStartCommand");
// Run again in case service is already started and onCreate() is not called
runStartForeground();
String action = intent.getAction();
if (action != null) {
switch (action) {
case TERMUX_SERVICE.ACTION_STOP_SERVICE:
Logger.logDebug(LOG_TAG, "ACTION_STOP_SERVICE intent received");
actionStopService();
break;
case TERMUX_SERVICE.ACTION_WAKE_LOCK:
Logger.logDebug(LOG_TAG, "ACTION_WAKE_LOCK intent received");
actionAcquireWakeLock();
break;
case TERMUX_SERVICE.ACTION_WAKE_UNLOCK:
Logger.logDebug(LOG_TAG, "ACTION_WAKE_UNLOCK intent received");
actionReleaseWakeLock(true);
break;
case TERMUX_SERVICE.ACTION_SERVICE_EXECUTE:
Logger.logDebug(LOG_TAG, "ACTION_SERVICE_EXECUTE intent received");
actionServiceExecute(intent);
break;
default:
Logger.logError(LOG_TAG, "Invalid action: \"" + action + "\"");
break;
}
}
// If this service really do get killed, there is no point restarting it automatically - let the user do on next
// start of {@link Term):
return Service.START_NOT_STICKY;
}
@Override
public void onDestroy() {
Logger.logVerbose(LOG_TAG, "onDestroy");
TermuxShellUtils.clearTermuxTMPDIR(true);
actionReleaseWakeLock(false);
if (!mWantsToStop)
killAllTermuxExecutionCommands();
runStopForeground();
}
@Override
public IBinder onBind(Intent intent) {
Logger.logVerbose(LOG_TAG, "onBind");
return mBinder;
}
@Override
public boolean onUnbind(Intent intent) {
Logger.logVerbose(LOG_TAG, "onUnbind");
// Since we cannot rely on {@link TermuxActivity.onDestroy()} to always complete,
// we unset clients here as well if it failed, so that we do not leave service and session
// clients with references to the activity.
if (mTermuxTerminalSessionClient != null)
unsetTermuxTerminalSessionClient();
return false;
}
/** Make service run in foreground mode. */
private void runStartForeground() {
setupNotificationChannel();
startForeground(TermuxConstants.TERMUX_APP_NOTIFICATION_ID, buildNotification());
}
/** Make service leave foreground mode. */
private void runStopForeground() {
stopForeground(true);
}
/** Request to stop service. */
private void requestStopService() {
Logger.logDebug(LOG_TAG, "Requesting to stop service");
runStopForeground();
stopSelf();
}
/** Process action to stop service. */
private void actionStopService() {
mWantsToStop = true;
killAllTermuxExecutionCommands();
requestStopService();
}
/** Kill all TermuxSessions and TermuxTasks by sending SIGKILL to their processes.
*
* For TermuxSessions, all sessions will be killed, whether user manually exited Termux or if
* onDestroy() was directly called because of unintended shutdown. The processing of results
* will only be done if user manually exited termux or if the session was started by a plugin
* which **expects** the result back via a pending intent.
*
* For TermuxTasks, only tasks that were started by a plugin which **expects** the result
* back via a pending intent will be killed, whether user manually exited Termux or if
* onDestroy() was directly called because of unintended shutdown. The processing of results
* will always be done for the tasks that are killed. The remaining processes will keep on
* running until the termux app process is killed by android, like by OOM, so we let them run
* as long as they can.
*
* Some plugin execution commands may not have been processed and added to mTermuxSessions and
* mTermuxTasks lists before the service is killed, so we maintain a separate
* mPendingPluginExecutionCommands list for those, so that we can notify the pending intent
* creators that execution was cancelled.
*
* Note that if user didn't manually exit Termux and if onDestroy() was directly called because
* of unintended shutdown, like android deciding to kill the service, then there will be no
* guarantee that onDestroy() will be allowed to finish and termux app process may be killed before
* it has finished. This means that in those cases some results may not be sent back to their
* creators for plugin commands but we still try to process whatever results can be processed
* despite the unreliable behaviour of onDestroy().
*
* Note that if don't kill the processes started by plugins which **expect** the result back
* and notify their creators that they have been killed, then they may get stuck waiting for
* the results forever like in case of commands started by Termux:Tasker or RUN_COMMAND intent,
* since once TermuxService has been killed, no result will be sent back. They may still get
* stuck if termux app process gets killed, so for this case reasonable timeout values should
* be used, like in Tasker for the Termux:Tasker actions.
*
* We make copies of each list since items are removed inside the loop.
*/
private synchronized void killAllTermuxExecutionCommands() {
boolean processResult;
Logger.logDebug(LOG_TAG, "Killing TermuxSessions=" + mTermuxSessions.size() + ", TermuxTasks=" + mTermuxTasks.size() + ", PendingPluginExecutionCommands=" + mPendingPluginExecutionCommands.size());
List<TermuxSession> termuxSessions = new ArrayList<>(mTermuxSessions);
for (int i = 0; i < termuxSessions.size(); i++) {
ExecutionCommand executionCommand = termuxSessions.get(i).getExecutionCommand();
processResult = mWantsToStop || executionCommand.isPluginExecutionCommandWithPendingResult();
termuxSessions.get(i).killIfExecuting(this, processResult);
}
List<TermuxTask> termuxTasks = new ArrayList<>(mTermuxTasks);
for (int i = 0; i < termuxTasks.size(); i++) {
ExecutionCommand executionCommand = termuxTasks.get(i).getExecutionCommand();
if (executionCommand.isPluginExecutionCommandWithPendingResult())
termuxTasks.get(i).killIfExecuting(this, true);
}
List<ExecutionCommand> pendingPluginExecutionCommands = new ArrayList<>(mPendingPluginExecutionCommands);
for (int i = 0; i < pendingPluginExecutionCommands.size(); i++) {
ExecutionCommand executionCommand = pendingPluginExecutionCommands.get(i);
if (!executionCommand.shouldNotProcessResults() && executionCommand.isPluginExecutionCommandWithPendingResult()) {
if (executionCommand.setStateFailed(Errno.ERRNO_CANCELLED.getCode(), this.getString(com.termux.shared.R.string.error_execution_cancelled))) {
PluginUtils.processPluginExecutionCommandResult(this, LOG_TAG, executionCommand);
}
}
}
}
/** Process action to acquire Power and Wi-Fi WakeLocks. */
@SuppressLint({"WakelockTimeout", "BatteryLife"})
private void actionAcquireWakeLock() {
if (mWakeLock != null) {
Logger.logDebug(LOG_TAG, "Ignoring acquiring WakeLocks since they are already held");
return;
}
Logger.logDebug(LOG_TAG, "Acquiring WakeLocks");
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TermuxConstants.TERMUX_APP_NAME.toLowerCase() + ":service-wakelock");
mWakeLock.acquire();
// http://tools.android.com/tech-docs/lint-in-studio-2-3#TOC-WifiManager-Leak
WifiManager wm = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
mWifiLock = wm.createWifiLock(WifiManager.WIFI_MODE_FULL_HIGH_PERF, TermuxConstants.TERMUX_APP_NAME.toLowerCase());
mWifiLock.acquire();
String packageName = getPackageName();
if (!pm.isIgnoringBatteryOptimizations(packageName)) {
Intent whitelist = new Intent();
whitelist.setAction(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
whitelist.setData(Uri.parse("package:" + packageName));
whitelist.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
try {
startActivity(whitelist);
} catch (ActivityNotFoundException e) {
Logger.logStackTraceWithMessage(LOG_TAG, "Failed to call ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS", e);
}
}
updateNotification();
Logger.logDebug(LOG_TAG, "WakeLocks acquired successfully");
}
/** Process action to release Power and Wi-Fi WakeLocks. */
private void actionReleaseWakeLock(boolean updateNotification) {
if (mWakeLock == null && mWifiLock == null) {
Logger.logDebug(LOG_TAG, "Ignoring releasing WakeLocks since none are already held");
return;
}
Logger.logDebug(LOG_TAG, "Releasing WakeLocks");
if (mWakeLock != null) {
mWakeLock.release();
mWakeLock = null;
}
if (mWifiLock != null) {
mWifiLock.release();
mWifiLock = null;
}
if (updateNotification)
updateNotification();
Logger.logDebug(LOG_TAG, "WakeLocks released successfully");
}
/** Process {@link TERMUX_SERVICE#ACTION_SERVICE_EXECUTE} intent to execute a shell command in
* a foreground TermuxSession or in a background TermuxTask. */
private void actionServiceExecute(Intent intent) {
if (intent == null) {
Logger.logError(LOG_TAG, "Ignoring null intent to actionServiceExecute");
return;
}
ExecutionCommand executionCommand = new ExecutionCommand(getNextExecutionId());
executionCommand.executableUri = intent.getData();
executionCommand.inBackground = intent.getBooleanExtra(TERMUX_SERVICE.EXTRA_BACKGROUND, false);
if (executionCommand.executableUri != null) {
executionCommand.executable = executionCommand.executableUri.getPath();
executionCommand.arguments = IntentUtils.getStringArrayExtraIfSet(intent, TERMUX_SERVICE.EXTRA_ARGUMENTS, null);
if (executionCommand.inBackground)
executionCommand.stdin = IntentUtils.getStringExtraIfSet(intent, TERMUX_SERVICE.EXTRA_STDIN, null);
executionCommand.backgroundCustomLogLevel = IntentUtils.getIntegerExtraIfSet(intent, TERMUX_SERVICE.EXTRA_BACKGROUND_CUSTOM_LOG_LEVEL, null);
}
executionCommand.workingDirectory = IntentUtils.getStringExtraIfSet(intent, TERMUX_SERVICE.EXTRA_WORKDIR, null);
executionCommand.isFailsafe = intent.getBooleanExtra(TERMUX_ACTIVITY.EXTRA_FAILSAFE_SESSION, false);
executionCommand.sessionAction = intent.getStringExtra(TERMUX_SERVICE.EXTRA_SESSION_ACTION);
executionCommand.commandLabel = IntentUtils.getStringExtraIfSet(intent, TERMUX_SERVICE.EXTRA_COMMAND_LABEL, "Execution Intent Command");
executionCommand.commandDescription = IntentUtils.getStringExtraIfSet(intent, TERMUX_SERVICE.EXTRA_COMMAND_DESCRIPTION, null);
executionCommand.commandHelp = IntentUtils.getStringExtraIfSet(intent, TERMUX_SERVICE.EXTRA_COMMAND_HELP, null);
executionCommand.pluginAPIHelp = IntentUtils.getStringExtraIfSet(intent, TERMUX_SERVICE.EXTRA_PLUGIN_API_HELP, null);
executionCommand.isPluginExecutionCommand = true;
executionCommand.resultConfig.resultPendingIntent = intent.getParcelableExtra(TERMUX_SERVICE.EXTRA_PENDING_INTENT);
executionCommand.resultConfig.resultDirectoryPath = IntentUtils.getStringExtraIfSet(intent, TERMUX_SERVICE.EXTRA_RESULT_DIRECTORY, null);
if (executionCommand.resultConfig.resultDirectoryPath != null) {
executionCommand.resultConfig.resultSingleFile = intent.getBooleanExtra(TERMUX_SERVICE.EXTRA_RESULT_SINGLE_FILE, false);
executionCommand.resultConfig.resultFileBasename = IntentUtils.getStringExtraIfSet(intent, TERMUX_SERVICE.EXTRA_RESULT_FILE_BASENAME, null);
executionCommand.resultConfig.resultFileOutputFormat = IntentUtils.getStringExtraIfSet(intent, TERMUX_SERVICE.EXTRA_RESULT_FILE_OUTPUT_FORMAT, null);
executionCommand.resultConfig.resultFileErrorFormat = IntentUtils.getStringExtraIfSet(intent, TERMUX_SERVICE.EXTRA_RESULT_FILE_ERROR_FORMAT, null);
executionCommand.resultConfig.resultFilesSuffix = IntentUtils.getStringExtraIfSet(intent, TERMUX_SERVICE.EXTRA_RESULT_FILES_SUFFIX, null);
}
// Add the execution command to pending plugin execution commands list
mPendingPluginExecutionCommands.add(executionCommand);
if (executionCommand.inBackground) {
executeTermuxTaskCommand(executionCommand);
} else {
executeTermuxSessionCommand(executionCommand);
}
}
/** Execute a shell command in background {@link TermuxTask}. */
private void executeTermuxTaskCommand(ExecutionCommand executionCommand) {
if (executionCommand == null) return;
Logger.logDebug(LOG_TAG, "Executing background \"" + executionCommand.getCommandIdAndLabelLogString() + "\" TermuxTask command");
TermuxTask newTermuxTask = createTermuxTask(executionCommand);
}
/** Create a {@link TermuxTask}. */
@Nullable
public TermuxTask createTermuxTask(String executablePath, String[] arguments, String stdin, String workingDirectory) {
return createTermuxTask(new ExecutionCommand(getNextExecutionId(), executablePath, arguments, stdin, workingDirectory, true, false));
}
/** Create a {@link TermuxTask}. */
@Nullable
public synchronized TermuxTask createTermuxTask(ExecutionCommand executionCommand) {
if (executionCommand == null) return null;
Logger.logDebug(LOG_TAG, "Creating \"" + executionCommand.getCommandIdAndLabelLogString() + "\" TermuxTask");
if (!executionCommand.inBackground) {
Logger.logDebug(LOG_TAG, "Ignoring a foreground execution command passed to createTermuxTask()");
return null;
}
if (Logger.getLogLevel() >= Logger.LOG_LEVEL_VERBOSE)
Logger.logVerboseExtended(LOG_TAG, executionCommand.toString());
TermuxTask newTermuxTask = TermuxTask.execute(this, executionCommand, this, new TermuxShellEnvironmentClient(), false);
if (newTermuxTask == null) {
Logger.logError(LOG_TAG, "Failed to execute new TermuxTask command for:\n" + executionCommand.getCommandIdAndLabelLogString());
// If the execution command was started for a plugin, then process the error
if (executionCommand.isPluginExecutionCommand)
PluginUtils.processPluginExecutionCommandError(this, LOG_TAG, executionCommand, false);
else
Logger.logErrorExtended(LOG_TAG, executionCommand.toString());
return null;
}
mTermuxTasks.add(newTermuxTask);
// Remove the execution command from the pending plugin execution commands list since it has
// now been processed
if (executionCommand.isPluginExecutionCommand)
mPendingPluginExecutionCommands.remove(executionCommand);
updateNotification();
return newTermuxTask;
}
/** Callback received when a {@link TermuxTask} finishes. */
@Override
public void onTermuxTaskExited(final TermuxTask termuxTask) {
mHandler.post(() -> {
if (termuxTask != null) {
ExecutionCommand executionCommand = termuxTask.getExecutionCommand();
Logger.logVerbose(LOG_TAG, "The onTermuxTaskExited() callback called for \"" + executionCommand.getCommandIdAndLabelLogString() + "\" TermuxTask command");
// If the execution command was started for a plugin, then process the results
if (executionCommand != null && executionCommand.isPluginExecutionCommand)
PluginUtils.processPluginExecutionCommandResult(this, LOG_TAG, executionCommand);
mTermuxTasks.remove(termuxTask);
}
updateNotification();
});
}
/** Execute a shell command in a foreground {@link TermuxSession}. */
private void executeTermuxSessionCommand(ExecutionCommand executionCommand) {
if (executionCommand == null) return;
Logger.logDebug(LOG_TAG, "Executing foreground \"" + executionCommand.getCommandIdAndLabelLogString() + "\" TermuxSession command");
String sessionName = null;
// Transform executable path to session name, e.g. "/bin/do-something.sh" => "do something.sh".
if (executionCommand.executable != null) {
sessionName = ShellUtils.getExecutableBasename(executionCommand.executable).replace('-', ' ');
}
TermuxSession newTermuxSession = createTermuxSession(executionCommand, sessionName);
if (newTermuxSession == null) return;
handleSessionAction(DataUtils.getIntFromString(executionCommand.sessionAction,
TERMUX_SERVICE.VALUE_EXTRA_SESSION_ACTION_SWITCH_TO_NEW_SESSION_AND_OPEN_ACTIVITY),
newTermuxSession.getTerminalSession());
}
/**
* Create a {@link TermuxSession}.
* Currently called by {@link TermuxTerminalSessionClient#addNewSession(boolean, String)} to add a new {@link TermuxSession}.
*/
@Nullable
public TermuxSession createTermuxSession(String executablePath, String[] arguments, String stdin, String workingDirectory, boolean isFailSafe, String sessionName) {
return createTermuxSession(new ExecutionCommand(getNextExecutionId(), executablePath, arguments, stdin, workingDirectory, false, isFailSafe), sessionName);
}
/** Create a {@link TermuxSession}. */
@Nullable
public synchronized TermuxSession createTermuxSession(ExecutionCommand executionCommand, String sessionName) {
if (executionCommand == null) return null;
Logger.logDebug(LOG_TAG, "Creating \"" + executionCommand.getCommandIdAndLabelLogString() + "\" TermuxSession");
if (executionCommand.inBackground) {
Logger.logDebug(LOG_TAG, "Ignoring a background execution command passed to createTermuxSession()");
return null;
}
if (Logger.getLogLevel() >= Logger.LOG_LEVEL_VERBOSE)
Logger.logVerboseExtended(LOG_TAG, executionCommand.toString());
// If the execution command was started for a plugin, only then will the stdout be set
// Otherwise if command was manually started by the user like by adding a new terminal session,
// then no need to set stdout
executionCommand.terminalTranscriptRows = getTerminalTranscriptRows();
TermuxSession newTermuxSession = TermuxSession.execute(this, executionCommand, getTermuxTerminalSessionClient(), this, new TermuxShellEnvironmentClient(), sessionName, executionCommand.isPluginExecutionCommand);
if (newTermuxSession == null) {
Logger.logError(LOG_TAG, "Failed to execute new TermuxSession command for:\n" + executionCommand.getCommandIdAndLabelLogString());
// If the execution command was started for a plugin, then process the error
if (executionCommand.isPluginExecutionCommand)
PluginUtils.processPluginExecutionCommandError(this, LOG_TAG, executionCommand, false);
else
Logger.logErrorExtended(LOG_TAG, executionCommand.toString());
return null;
}
mTermuxSessions.add(newTermuxSession);
// Remove the execution command from the pending plugin execution commands list since it has
// now been processed
if (executionCommand.isPluginExecutionCommand)
mPendingPluginExecutionCommands.remove(executionCommand);
// Notify {@link TermuxSessionsListViewController} that sessions list has been updated if
// activity in is foreground
if (mTermuxTerminalSessionClient != null)
mTermuxTerminalSessionClient.termuxSessionListNotifyUpdated();
updateNotification();
TermuxActivity.updateTermuxActivityStyling(this);
return newTermuxSession;
}
/** Remove a TermuxSession. */
public synchronized int removeTermuxSession(TerminalSession sessionToRemove) {
int index = getIndexOfSession(sessionToRemove);
if (index >= 0)
mTermuxSessions.get(index).finish();
return index;
}
/** Callback received when a {@link TermuxSession} finishes. */
@Override
public void onTermuxSessionExited(final TermuxSession termuxSession) {
if (termuxSession != null) {
ExecutionCommand executionCommand = termuxSession.getExecutionCommand();
Logger.logVerbose(LOG_TAG, "The onTermuxSessionExited() callback called for \"" + executionCommand.getCommandIdAndLabelLogString() + "\" TermuxSession command");
// If the execution command was started for a plugin, then process the results
if (executionCommand != null && executionCommand.isPluginExecutionCommand)
PluginUtils.processPluginExecutionCommandResult(this, LOG_TAG, executionCommand);
mTermuxSessions.remove(termuxSession);
// Notify {@link TermuxSessionsListViewController} that sessions list has been updated if
// activity in is foreground
if (mTermuxTerminalSessionClient != null)
mTermuxTerminalSessionClient.termuxSessionListNotifyUpdated();
}
updateNotification();
}
/** Get the terminal transcript rows to be used for new {@link TermuxSession}. */
public Integer getTerminalTranscriptRows() {
if (mTerminalTranscriptRows == null)
setTerminalTranscriptRows();
return mTerminalTranscriptRows;
}
public void setTerminalTranscriptRows() {
// TermuxService only uses this termux property currently, so no need to load them all into
// an internal values map like TermuxActivity does
mTerminalTranscriptRows = TermuxAppSharedProperties.getTerminalTranscriptRows(this);
}
/** Process session action for new session. */
private void handleSessionAction(int sessionAction, TerminalSession newTerminalSession) {
Logger.logDebug(LOG_TAG, "Processing sessionAction \"" + sessionAction + "\" for session \"" + newTerminalSession.mSessionName + "\"");
switch (sessionAction) {
case TERMUX_SERVICE.VALUE_EXTRA_SESSION_ACTION_SWITCH_TO_NEW_SESSION_AND_OPEN_ACTIVITY:
setCurrentStoredTerminalSession(newTerminalSession);
if (mTermuxTerminalSessionClient != null)
mTermuxTerminalSessionClient.setCurrentSession(newTerminalSession);
startTermuxActivity();
break;
case TERMUX_SERVICE.VALUE_EXTRA_SESSION_ACTION_KEEP_CURRENT_SESSION_AND_OPEN_ACTIVITY:
if (getTermuxSessionsSize() == 1)
setCurrentStoredTerminalSession(newTerminalSession);
startTermuxActivity();
break;
case TERMUX_SERVICE.VALUE_EXTRA_SESSION_ACTION_SWITCH_TO_NEW_SESSION_AND_DONT_OPEN_ACTIVITY:
setCurrentStoredTerminalSession(newTerminalSession);
if (mTermuxTerminalSessionClient != null)
mTermuxTerminalSessionClient.setCurrentSession(newTerminalSession);
break;
case TERMUX_SERVICE.VALUE_EXTRA_SESSION_ACTION_KEEP_CURRENT_SESSION_AND_DONT_OPEN_ACTIVITY:
if (getTermuxSessionsSize() == 1)
setCurrentStoredTerminalSession(newTerminalSession);
break;
default:
Logger.logError(LOG_TAG, "Invalid sessionAction: \"" + sessionAction + "\". Force using default sessionAction.");
handleSessionAction(TERMUX_SERVICE.VALUE_EXTRA_SESSION_ACTION_SWITCH_TO_NEW_SESSION_AND_OPEN_ACTIVITY, newTerminalSession);
break;
}
}
/** Launch the {@link }TermuxActivity} to bring it to foreground. */
private void startTermuxActivity() {
// For android >= 10, apps require Display over other apps permission to start foreground activities
// from background (services). If it is not granted, then TermuxSessions that are started will
// show in Termux notification but will not run until user manually clicks the notification.
if (PermissionUtils.validateDisplayOverOtherAppsPermissionForPostAndroid10(this, true)) {
TermuxActivity.startTermuxActivity(this);
} else {
TermuxAppSharedPreferences preferences = TermuxAppSharedPreferences.build(this);
if (preferences == null) return;
if (preferences.arePluginErrorNotificationsEnabled())
Logger.showToast(this, this.getString(R.string.error_display_over_other_apps_permission_not_granted), true);
}
}
/** If {@link TermuxActivity} has not bound to the {@link TermuxService} yet or is destroyed, then
* interface functions requiring the activity should not be available to the terminal sessions,
* so we just return the {@link #mTermuxTerminalSessionClientBase}. Once {@link TermuxActivity} bind
* callback is received, it should call {@link #setTermuxTerminalSessionClient} to set the
* {@link TermuxService#mTermuxTerminalSessionClient} so that further terminal sessions are directly
* passed the {@link TermuxTerminalSessionClient} object which fully implements the
* {@link TerminalSessionClient} interface.
*
* @return Returns the {@link TermuxTerminalSessionClient} if {@link TermuxActivity} has bound with
* {@link TermuxService}, otherwise {@link TermuxTerminalSessionClientBase}.
*/
public synchronized TermuxTerminalSessionClientBase getTermuxTerminalSessionClient() {
if (mTermuxTerminalSessionClient != null)
return mTermuxTerminalSessionClient;
else
return mTermuxTerminalSessionClientBase;
}
/** This should be called when {@link TermuxActivity#onServiceConnected} is called to set the
* {@link TermuxService#mTermuxTerminalSessionClient} variable and update the {@link TerminalSession}
* and {@link TerminalEmulator} clients in case they were passed {@link TermuxTerminalSessionClientBase}
* earlier.
*
* @param termuxTerminalSessionClient The {@link TermuxTerminalSessionClient} object that fully
* implements the {@link TerminalSessionClient} interface.
*/
public synchronized void setTermuxTerminalSessionClient(TermuxTerminalSessionClient termuxTerminalSessionClient) {
mTermuxTerminalSessionClient = termuxTerminalSessionClient;
for (int i = 0; i < mTermuxSessions.size(); i++)
mTermuxSessions.get(i).getTerminalSession().updateTerminalSessionClient(mTermuxTerminalSessionClient);
}
/** This should be called when {@link TermuxActivity} has been destroyed and in {@link #onUnbind(Intent)}
* so that the {@link TermuxService} and {@link TerminalSession} and {@link TerminalEmulator}
* clients do not hold an activity references.
*/
public synchronized void unsetTermuxTerminalSessionClient() {
for (int i = 0; i < mTermuxSessions.size(); i++)
mTermuxSessions.get(i).getTerminalSession().updateTerminalSessionClient(mTermuxTerminalSessionClientBase);
mTermuxTerminalSessionClient = null;
}
private Notification buildNotification() {
Resources res = getResources();
// Set pending intent to be launched when notification is clicked
Intent notificationIntent = TermuxActivity.newInstance(this);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
// Set notification text
int sessionCount = getTermuxSessionsSize();
int taskCount = mTermuxTasks.size();
String notificationText = sessionCount + " session" + (sessionCount == 1 ? "" : "s");
if (taskCount > 0) {
notificationText += ", " + taskCount + " task" + (taskCount == 1 ? "" : "s");
}
final boolean wakeLockHeld = mWakeLock != null;
if (wakeLockHeld) notificationText += " (wake lock held)";
// Set notification priority
// If holding a wake or wifi lock consider the notification of high priority since it's using power,
// otherwise use a low priority
int priority = (wakeLockHeld) ? Notification.PRIORITY_HIGH : Notification.PRIORITY_LOW;
// Build the notification
Notification.Builder builder = NotificationUtils.geNotificationBuilder(this,
TermuxConstants.TERMUX_APP_NOTIFICATION_CHANNEL_ID, priority,
TermuxConstants.TERMUX_APP_NAME, notificationText, null,
contentIntent, null, NotificationUtils.NOTIFICATION_MODE_SILENT);
if (builder == null) return null;
// No need to show a timestamp:
builder.setShowWhen(false);
// Set notification icon
builder.setSmallIcon(R.drawable.ic_service_notification);
// Set background color for small notification icon
builder.setColor(0xFF607D8B);
// TermuxSessions are always ongoing
builder.setOngoing(true);
// Set Exit button action
Intent exitIntent = new Intent(this, TermuxService.class).setAction(TERMUX_SERVICE.ACTION_STOP_SERVICE);
builder.addAction(android.R.drawable.ic_delete, res.getString(R.string.notification_action_exit), PendingIntent.getService(this, 0, exitIntent, 0));
// Set Wakelock button actions
String newWakeAction = wakeLockHeld ? TERMUX_SERVICE.ACTION_WAKE_UNLOCK : TERMUX_SERVICE.ACTION_WAKE_LOCK;
Intent toggleWakeLockIntent = new Intent(this, TermuxService.class).setAction(newWakeAction);
String actionTitle = res.getString(wakeLockHeld ? R.string.notification_action_wake_unlock : R.string.notification_action_wake_lock);
int actionIcon = wakeLockHeld ? android.R.drawable.ic_lock_idle_lock : android.R.drawable.ic_lock_lock;
builder.addAction(actionIcon, actionTitle, PendingIntent.getService(this, 0, toggleWakeLockIntent, 0));
return builder.build();
}
private void setupNotificationChannel() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return;
NotificationUtils.setupNotificationChannel(this, TermuxConstants.TERMUX_APP_NOTIFICATION_CHANNEL_ID,
TermuxConstants.TERMUX_APP_NOTIFICATION_CHANNEL_NAME, NotificationManager.IMPORTANCE_LOW);
}
/** Update the shown foreground service notification after making any changes that affect it. */
private synchronized void updateNotification() {
if (mWakeLock == null && mTermuxSessions.isEmpty() && mTermuxTasks.isEmpty()) {
// Exit if we are updating after the user disabled all locks with no sessions or tasks running.
requestStopService();
} else {
((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).notify(TermuxConstants.TERMUX_APP_NOTIFICATION_ID, buildNotification());
}
}
private void setCurrentStoredTerminalSession(TerminalSession session) {
if (session == null) return;
// Make the newly created session the current one to be displayed
TermuxAppSharedPreferences preferences = TermuxAppSharedPreferences.build(this);
if (preferences == null) return;
preferences.setCurrentSession(session.mHandle);
}
public synchronized boolean isTermuxSessionsEmpty() {
return mTermuxSessions.isEmpty();
}
public synchronized int getTermuxSessionsSize() {
return mTermuxSessions.size();
}
public synchronized List<TermuxSession> getTermuxSessions() {
return mTermuxSessions;
}
@Nullable
public synchronized TermuxSession getTermuxSession(int index) {
if (index >= 0 && index < mTermuxSessions.size())
return mTermuxSessions.get(index);
else
return null;
}
public synchronized TermuxSession getLastTermuxSession() {
return mTermuxSessions.isEmpty() ? null : mTermuxSessions.get(mTermuxSessions.size() - 1);
}
public synchronized int getIndexOfSession(TerminalSession terminalSession) {
for (int i = 0; i < mTermuxSessions.size(); i++) {
if (mTermuxSessions.get(i).getTerminalSession().equals(terminalSession))
return i;
}
return -1;
}
public synchronized TerminalSession getTerminalSessionForHandle(String sessionHandle) {
TerminalSession terminalSession;
for (int i = 0, len = mTermuxSessions.size(); i < len; i++) {
terminalSession = mTermuxSessions.get(i).getTerminalSession();
if (terminalSession.mHandle.equals(sessionHandle))
return terminalSession;
}
return null;
}
public static synchronized int getNextExecutionId() {
return EXECUTION_ID++;
}
public boolean wantsToStop() {
return mWantsToStop;
}
}
|
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.buck.android;
import com.facebook.buck.core.build.buildable.context.BuildableContext;
import com.facebook.buck.core.build.context.BuildContext;
import com.facebook.buck.core.build.execution.context.ExecutionContext;
import com.facebook.buck.core.exceptions.HumanReadableException;
import com.facebook.buck.core.model.BuildTarget;
import com.facebook.buck.core.model.OutputLabel;
import com.facebook.buck.core.model.impl.BuildTargetPaths;
import com.facebook.buck.core.rulekey.AddToRuleKey;
import com.facebook.buck.core.rules.BuildRule;
import com.facebook.buck.core.rules.BuildRuleParams;
import com.facebook.buck.core.rules.impl.AbstractBuildRuleWithDeclaredAndExtraDeps;
import com.facebook.buck.core.rules.tool.BinaryBuildRule;
import com.facebook.buck.core.sourcepath.ExplicitBuildTargetSourcePath;
import com.facebook.buck.core.sourcepath.SourcePath;
import com.facebook.buck.core.sourcepath.resolver.SourcePathResolverAdapter;
import com.facebook.buck.io.BuildCellRelativePath;
import com.facebook.buck.io.filesystem.ProjectFilesystem;
import com.facebook.buck.shell.ShellStep;
import com.facebook.buck.step.Step;
import com.facebook.buck.step.StepExecutionResult;
import com.facebook.buck.step.StepExecutionResults;
import com.facebook.buck.step.fs.MakeCleanDirectoryStep;
import com.google.common.base.Joiner;
import com.google.common.base.Preconditions;
import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSortedMap;
import com.google.common.collect.ImmutableSortedSet;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.nio.file.Path;
import java.util.Map;
/**
* Rule to write the results of library merging to disk and run a user-supplied code generator on
* it.
*/
class GenerateCodeForMergedLibraryMap extends AbstractBuildRuleWithDeclaredAndExtraDeps {
@AddToRuleKey private final ImmutableSortedMap<String, String> mergeResult;
@AddToRuleKey private final BuildRule codeGenerator;
@AddToRuleKey
private final ImmutableSortedMap<String, ImmutableSortedSet<String>> sharedObjectTargets;
GenerateCodeForMergedLibraryMap(
BuildTarget buildTarget,
ProjectFilesystem projectFilesystem,
BuildRuleParams buildRuleParams,
ImmutableSortedMap<String, String> mergeResult,
ImmutableSortedMap<String, ImmutableSortedSet<String>> sharedObjectTargets,
BuildRule codeGenerator) {
super(buildTarget, projectFilesystem, buildRuleParams);
this.mergeResult = mergeResult;
this.sharedObjectTargets = sharedObjectTargets;
this.codeGenerator = codeGenerator;
if (!(codeGenerator instanceof BinaryBuildRule)) {
throw new HumanReadableException(
String.format(
"For build rule %s, code generator %s is not executable but must be",
getBuildTarget(), codeGenerator.getBuildTarget()));
}
}
@Override
public ImmutableList<Step> getBuildSteps(
BuildContext context, BuildableContext buildableContext) {
Path output = context.getSourcePathResolver().getRelativePath(getSourcePathToOutput());
buildableContext.recordArtifact(output);
buildableContext.recordArtifact(getMappingPath());
buildableContext.recordArtifact(getTargetsPath());
return new ImmutableList.Builder<Step>()
.addAll(
MakeCleanDirectoryStep.of(
BuildCellRelativePath.fromCellRelativePath(
context.getBuildCellRootPath(), getProjectFilesystem(), output.getParent())))
.add(new WriteMapDataStep())
.add(new WriteTargetsFileStep())
.add(new RunCodeGenStep(context.getSourcePathResolver()))
.build();
}
@Override
public SourcePath getSourcePathToOutput() {
return ExplicitBuildTargetSourcePath.of(
getBuildTarget(),
BuildTargetPaths.getGenPath(
getProjectFilesystem(), getBuildTarget(), "%s/MergedLibraryMapping.java"));
}
private Path getMappingPath() {
return BuildTargetPaths.getGenPath(
getProjectFilesystem(), getBuildTarget(), "%s/merged_library_map.txt");
}
/**
* This file shows which targets went into which libraries. It's just meant for human consumption
* when writing merge configs.
*/
private Path getTargetsPath() {
return BuildTargetPaths.getGenPath(
getProjectFilesystem(), getBuildTarget(), "%s/shared_object_targets.txt");
}
private class WriteMapDataStep implements Step {
@Override
public StepExecutionResult execute(ExecutionContext context) throws IOException {
ProjectFilesystem projectFilesystem = getProjectFilesystem();
try (Writer out =
new BufferedWriter(
new OutputStreamWriter(projectFilesystem.newFileOutputStream(getMappingPath())))) {
for (Map.Entry<String, String> entry : mergeResult.entrySet()) {
out.write(entry.getKey());
out.write(' ');
out.write(entry.getValue());
out.write('\n');
}
}
return StepExecutionResults.SUCCESS;
}
@Override
public String getShortName() {
return "write_merged_library_map";
}
@Override
public String getDescription(ExecutionContext context) {
return String.format("%s > %s", getShortName(), getMappingPath());
}
}
private class WriteTargetsFileStep implements Step {
@Override
public StepExecutionResult execute(ExecutionContext context) throws IOException {
ProjectFilesystem projectFilesystem = getProjectFilesystem();
try (Writer out =
new BufferedWriter(
new OutputStreamWriter(projectFilesystem.newFileOutputStream(getTargetsPath())))) {
for (Map.Entry<String, ImmutableSortedSet<String>> entry : sharedObjectTargets.entrySet()) {
out.write(entry.getKey());
for (String target : entry.getValue()) {
out.write(' ');
out.write(target);
}
out.write('\n');
}
}
return StepExecutionResults.SUCCESS;
}
@Override
public String getShortName() {
return "write_shared_objects_target";
}
@Override
public String getDescription(ExecutionContext context) {
return String.format("%s > %s", getShortName(), getMappingPath());
}
}
private class RunCodeGenStep extends ShellStep {
private final SourcePathResolverAdapter pathResolver;
RunCodeGenStep(SourcePathResolverAdapter pathResolver) {
super(getProjectFilesystem().getRootPath());
this.pathResolver = pathResolver;
}
@Override
protected ImmutableList<String> getShellCommandInternal(ExecutionContext context) {
Preconditions.checkState(
GenerateCodeForMergedLibraryMap.this.codeGenerator instanceof BinaryBuildRule);
String executableCommand =
Joiner.on(" ")
.join(
((BinaryBuildRule) GenerateCodeForMergedLibraryMap.this.codeGenerator)
.getExecutableCommand(OutputLabel.defaultLabel())
.getCommandPrefix(pathResolver));
return ImmutableList.<String>builder()
.addAll(Splitter.on(' ').split(executableCommand))
.add(getMappingPath().toString())
.add(pathResolver.getRelativePath(getSourcePathToOutput()).toString())
.build();
}
@Override
public String getShortName() {
return "run_merged_lib_code_generator";
}
}
}
|
/*
* 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 hawaiianhanafuda;
import java.util.ArrayList;
/**
*
* @author HentaiNeko
*/
public class HandCards extends Deck {
ArrayList<String> playerOneHand = new ArrayList<>();
ArrayList<String> playerTwoHand = new ArrayList<>();
ArrayList<String> playerOneMatches = new ArrayList<>();
ArrayList<String> playerTwoMatches = new ArrayList<>();
ArrayList<String> fieldCards = new ArrayList<>();
public ArrayList<String> getPlayerOneHand(){
return playerOneHand;
}
public ArrayList<String> getplayerTwoHand(){
return playerTwoHand;
}
public ArrayList<String> getplayerOneMatches(){
return playerOneMatches;
}
public ArrayList<String> getplayerTwoMatches(){
return playerTwoMatches;
}
public ArrayList<String> getfieldCards(){
return fieldCards;
}
public void CardDealer(){
for (int i=0; i<24; i++){
if ((i%3)==0){
playerOneHand.add(deckCards.remove(0));
}
else if ((i%3)==1){
playerTwoHand.add(deckCards.remove(0));
}
else{
fieldCards.add(deckCards.remove(0));
}
}
}
}
|
/*
* Copyright 2020 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.template.soy.data.internal;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;
import com.google.template.soy.data.LoggingAdvisingAppendable;
import com.google.template.soy.data.SoyAbstractValue;
import com.google.template.soy.data.SoyDataException;
import com.google.template.soy.data.SoyLegacyObjectMap;
import com.google.template.soy.data.SoyValue;
import com.google.template.soy.data.SoyValueProvider;
import com.google.template.soy.data.restricted.StringData;
import java.io.IOException;
import java.util.Map;
/**
* A simple legacy_object_map implementation.
*
* <p>Important: Do not use outside of Soy code (treat as superpackage-private).
*/
public final class SoyLegacyObjectMapImpl extends SoyAbstractValue implements SoyLegacyObjectMap {
private final ImmutableMap<String, SoyValueProvider> map;
public SoyLegacyObjectMapImpl(ImmutableMap<String, SoyValueProvider> map) {
this.map = checkNotNull(map);
}
@Override
public int getItemCnt() {
return map.size();
}
@Override
public Iterable<? extends SoyValue> getItemKeys() {
return Iterables.transform(map.keySet(), StringData::forValue);
}
@Override
public boolean hasItem(SoyValue key) {
return map.containsKey(getStringKey(key));
}
@Override
public SoyValue getItem(SoyValue key) {
SoyValueProvider provider = getItemProvider(key);
return provider != null ? provider.resolve() : null;
}
@Override
public SoyValueProvider getItemProvider(SoyValue key) {
return map.get(getStringKey(key));
}
@Override
public boolean coerceToBoolean() {
return true;
}
@Override
public String coerceToString() {
LoggingAdvisingAppendable mapStr = LoggingAdvisingAppendable.buffering();
try {
render(mapStr);
} catch (IOException e) {
throw new AssertionError(e); // impossible
}
return mapStr.toString();
}
@Override
public void render(LoggingAdvisingAppendable appendable) throws IOException {
appendable.append('{');
boolean isFirst = true;
for (Map.Entry<String, SoyValueProvider> entry : map.entrySet()) {
if (isFirst) {
isFirst = false;
} else {
appendable.append(", ");
}
appendable.append(entry.getKey()).append(": ");
entry.getValue().resolve().render(appendable);
}
appendable.append('}');
}
@Override
public final boolean equals(Object other) {
return this == other;
}
@Override
public final int hashCode() {
return System.identityHashCode(this);
}
private static String getStringKey(SoyValue key) {
try {
return key.stringValue();
} catch (SoyDataException e) {
throw new SoyDataException(
"SoyLegacyObjectMap accessed with non-string key (got key type "
+ key.getClass().getName()
+ ").",
e);
}
}
}
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.cosmos.implementation.query;
import com.azure.cosmos.model.SqlQuerySpec;
import com.azure.cosmos.implementation.BackoffRetryUtility;
import com.azure.cosmos.implementation.DocumentClientRetryPolicy;
import com.azure.cosmos.implementation.HttpConstants;
import com.azure.cosmos.implementation.OperationType;
import com.azure.cosmos.implementation.ResourceType;
import com.azure.cosmos.implementation.RuntimeConstants;
import com.azure.cosmos.implementation.RxDocumentServiceRequest;
import reactor.core.publisher.Mono;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
class QueryPlanRetriever {
private static final String TRUE = "True";
private static final String SUPPORTED_QUERY_FEATURES = QueryFeature.Aggregate.name() + ", " +
QueryFeature.CompositeAggregate.name() + ", " +
QueryFeature.MultipleOrderBy.name() + ", " +
QueryFeature.OrderBy.name() + ", " +
QueryFeature.OffsetAndLimit.name() + ", " +
QueryFeature.Top.name();
static Mono<PartitionedQueryExecutionInfo> getQueryPlanThroughGatewayAsync(IDocumentQueryClient queryClient,
SqlQuerySpec sqlQuerySpec,
String resourceLink) {
final Map<String, String> requestHeaders = new HashMap<>();
requestHeaders.put(HttpConstants.HttpHeaders.CONTENT_TYPE, RuntimeConstants.MediaTypes.JSON);
requestHeaders.put(HttpConstants.HttpHeaders.IS_QUERY_PLAN_REQUEST, TRUE);
requestHeaders.put(HttpConstants.HttpHeaders.SUPPORTED_QUERY_FEATURES, SUPPORTED_QUERY_FEATURES);
requestHeaders.put(HttpConstants.HttpHeaders.QUERY_VERSION, HttpConstants.Versions.QUERY_VERSION);
final RxDocumentServiceRequest request = RxDocumentServiceRequest.create(OperationType.QueryPlan,
ResourceType.Document,
resourceLink,
requestHeaders);
request.UseGatewayMode = true;
request.setByteBuffer(sqlQuerySpec.serializeJsonToByteBuffer());
final DocumentClientRetryPolicy retryPolicyInstance =
queryClient.getResetSessionTokenRetryPolicy().getRequestPolicy();
Function<RxDocumentServiceRequest, Mono<PartitionedQueryExecutionInfo>> executeFunc = req -> {
return BackoffRetryUtility.executeRetry(() -> {
retryPolicyInstance.onBeforeSendRequest(req);
return queryClient.executeQueryAsync(request).flatMap(rxDocumentServiceResponse -> {
PartitionedQueryExecutionInfo partitionedQueryExecutionInfo =
new PartitionedQueryExecutionInfo(rxDocumentServiceResponse.getResponseBodyAsByteArray());
return Mono.just(partitionedQueryExecutionInfo);
});
}, retryPolicyInstance);
};
return executeFunc.apply(request);
}
}
|
/*
* Copyright 2019, Momentum Ideas, Co. All rights reserved.
*
* Source and object computer code contained herein is the private intellectual
* property of Momentum Ideas Co., a Delaware Corporation. Use of this
* code in source form requires permission in writing before use or the
* assembly, distribution, or publishing of derivative works, for commercial
* purposes or any other purpose, from a duly authorized officer of Momentum
* Ideas Co.
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.bloombox.schema.services.devices.v1beta1;
import static io.grpc.MethodDescriptor.generateFullMethodName;
import static io.grpc.stub.ClientCalls.asyncBidiStreamingCall;
import static io.grpc.stub.ClientCalls.asyncClientStreamingCall;
import static io.grpc.stub.ClientCalls.asyncServerStreamingCall;
import static io.grpc.stub.ClientCalls.asyncUnaryCall;
import static io.grpc.stub.ClientCalls.blockingServerStreamingCall;
import static io.grpc.stub.ClientCalls.blockingUnaryCall;
import static io.grpc.stub.ClientCalls.futureUnaryCall;
import static io.grpc.stub.ServerCalls.asyncBidiStreamingCall;
import static io.grpc.stub.ServerCalls.asyncClientStreamingCall;
import static io.grpc.stub.ServerCalls.asyncServerStreamingCall;
import static io.grpc.stub.ServerCalls.asyncUnaryCall;
import static io.grpc.stub.ServerCalls.asyncUnimplementedStreamingCall;
import static io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall;
/**
* <pre>
* Specifies the devices service, which enables managed devices to check-in, authorize themselves, and discover their
* identity/role.
* </pre>
*/
@javax.annotation.Generated(
value = "by gRPC proto compiler (version 1.18.0)",
comments = "Source: devices/v1beta1/DevicesService_Beta1.proto")
public final class DevicesGrpc {
private DevicesGrpc() {}
public static final String SERVICE_NAME = "bloombox.services.devices.v1beta1.Devices";
// Static method descriptors that strictly reflect the proto.
private static volatile io.grpc.MethodDescriptor<io.bloombox.schema.services.devices.v1beta1.Ping.Request,
io.bloombox.schema.services.devices.v1beta1.Ping.Response> getPingMethod;
@io.grpc.stub.annotations.RpcMethod(
fullMethodName = SERVICE_NAME + '/' + "Ping",
requestType = io.bloombox.schema.services.devices.v1beta1.Ping.Request.class,
responseType = io.bloombox.schema.services.devices.v1beta1.Ping.Response.class,
methodType = io.grpc.MethodDescriptor.MethodType.UNARY)
public static io.grpc.MethodDescriptor<io.bloombox.schema.services.devices.v1beta1.Ping.Request,
io.bloombox.schema.services.devices.v1beta1.Ping.Response> getPingMethod() {
io.grpc.MethodDescriptor<io.bloombox.schema.services.devices.v1beta1.Ping.Request, io.bloombox.schema.services.devices.v1beta1.Ping.Response> getPingMethod;
if ((getPingMethod = DevicesGrpc.getPingMethod) == null) {
synchronized (DevicesGrpc.class) {
if ((getPingMethod = DevicesGrpc.getPingMethod) == null) {
DevicesGrpc.getPingMethod = getPingMethod =
io.grpc.MethodDescriptor.<io.bloombox.schema.services.devices.v1beta1.Ping.Request, io.bloombox.schema.services.devices.v1beta1.Ping.Response>newBuilder()
.setType(io.grpc.MethodDescriptor.MethodType.UNARY)
.setFullMethodName(generateFullMethodName(
"bloombox.services.devices.v1beta1.Devices", "Ping"))
.setSampledToLocalTracing(true)
.setRequestMarshaller(io.grpc.protobuf.ProtoUtils.marshaller(
io.bloombox.schema.services.devices.v1beta1.Ping.Request.getDefaultInstance()))
.setResponseMarshaller(io.grpc.protobuf.ProtoUtils.marshaller(
io.bloombox.schema.services.devices.v1beta1.Ping.Response.getDefaultInstance()))
.setSchemaDescriptor(new DevicesMethodDescriptorSupplier("Ping"))
.build();
}
}
}
return getPingMethod;
}
private static volatile io.grpc.MethodDescriptor<io.bloombox.schema.services.devices.v1beta1.Activation.Request,
io.bloombox.schema.services.devices.v1beta1.Activation.Response> getActivateMethod;
@io.grpc.stub.annotations.RpcMethod(
fullMethodName = SERVICE_NAME + '/' + "Activate",
requestType = io.bloombox.schema.services.devices.v1beta1.Activation.Request.class,
responseType = io.bloombox.schema.services.devices.v1beta1.Activation.Response.class,
methodType = io.grpc.MethodDescriptor.MethodType.UNARY)
public static io.grpc.MethodDescriptor<io.bloombox.schema.services.devices.v1beta1.Activation.Request,
io.bloombox.schema.services.devices.v1beta1.Activation.Response> getActivateMethod() {
io.grpc.MethodDescriptor<io.bloombox.schema.services.devices.v1beta1.Activation.Request, io.bloombox.schema.services.devices.v1beta1.Activation.Response> getActivateMethod;
if ((getActivateMethod = DevicesGrpc.getActivateMethod) == null) {
synchronized (DevicesGrpc.class) {
if ((getActivateMethod = DevicesGrpc.getActivateMethod) == null) {
DevicesGrpc.getActivateMethod = getActivateMethod =
io.grpc.MethodDescriptor.<io.bloombox.schema.services.devices.v1beta1.Activation.Request, io.bloombox.schema.services.devices.v1beta1.Activation.Response>newBuilder()
.setType(io.grpc.MethodDescriptor.MethodType.UNARY)
.setFullMethodName(generateFullMethodName(
"bloombox.services.devices.v1beta1.Devices", "Activate"))
.setSampledToLocalTracing(true)
.setRequestMarshaller(io.grpc.protobuf.ProtoUtils.marshaller(
io.bloombox.schema.services.devices.v1beta1.Activation.Request.getDefaultInstance()))
.setResponseMarshaller(io.grpc.protobuf.ProtoUtils.marshaller(
io.bloombox.schema.services.devices.v1beta1.Activation.Response.getDefaultInstance()))
.setSchemaDescriptor(new DevicesMethodDescriptorSupplier("Activate"))
.build();
}
}
}
return getActivateMethod;
}
/**
* Creates a new async stub that supports all call types for the service
*/
public static DevicesStub newStub(io.grpc.Channel channel) {
return new DevicesStub(channel);
}
/**
* Creates a new blocking-style stub that supports unary and streaming output calls on the service
*/
public static DevicesBlockingStub newBlockingStub(
io.grpc.Channel channel) {
return new DevicesBlockingStub(channel);
}
/**
* Creates a new ListenableFuture-style stub that supports unary calls on the service
*/
public static DevicesFutureStub newFutureStub(
io.grpc.Channel channel) {
return new DevicesFutureStub(channel);
}
/**
* <pre>
* Specifies the devices service, which enables managed devices to check-in, authorize themselves, and discover their
* identity/role.
* </pre>
*/
public static abstract class DevicesImplBase implements io.grpc.BindableService {
/**
* <pre>
* Ping the device server.
* </pre>
*/
public void ping(io.bloombox.schema.services.devices.v1beta1.Ping.Request request,
io.grpc.stub.StreamObserver<io.bloombox.schema.services.devices.v1beta1.Ping.Response> responseObserver) {
asyncUnimplementedUnaryCall(getPingMethod(), responseObserver);
}
/**
* <pre>
* Setup and enable a device for live use. If this is the first time the subject device has activated itself,
* initialize or otherwise provision any requisite objects or resources.
* </pre>
*/
public void activate(io.bloombox.schema.services.devices.v1beta1.Activation.Request request,
io.grpc.stub.StreamObserver<io.bloombox.schema.services.devices.v1beta1.Activation.Response> responseObserver) {
asyncUnimplementedUnaryCall(getActivateMethod(), responseObserver);
}
@java.lang.Override public final io.grpc.ServerServiceDefinition bindService() {
return io.grpc.ServerServiceDefinition.builder(getServiceDescriptor())
.addMethod(
getPingMethod(),
asyncUnaryCall(
new MethodHandlers<
io.bloombox.schema.services.devices.v1beta1.Ping.Request,
io.bloombox.schema.services.devices.v1beta1.Ping.Response>(
this, METHODID_PING)))
.addMethod(
getActivateMethod(),
asyncUnaryCall(
new MethodHandlers<
io.bloombox.schema.services.devices.v1beta1.Activation.Request,
io.bloombox.schema.services.devices.v1beta1.Activation.Response>(
this, METHODID_ACTIVATE)))
.build();
}
}
/**
* <pre>
* Specifies the devices service, which enables managed devices to check-in, authorize themselves, and discover their
* identity/role.
* </pre>
*/
public static final class DevicesStub extends io.grpc.stub.AbstractStub<DevicesStub> {
private DevicesStub(io.grpc.Channel channel) {
super(channel);
}
private DevicesStub(io.grpc.Channel channel,
io.grpc.CallOptions callOptions) {
super(channel, callOptions);
}
@java.lang.Override
protected DevicesStub build(io.grpc.Channel channel,
io.grpc.CallOptions callOptions) {
return new DevicesStub(channel, callOptions);
}
/**
* <pre>
* Ping the device server.
* </pre>
*/
public void ping(io.bloombox.schema.services.devices.v1beta1.Ping.Request request,
io.grpc.stub.StreamObserver<io.bloombox.schema.services.devices.v1beta1.Ping.Response> responseObserver) {
asyncUnaryCall(
getChannel().newCall(getPingMethod(), getCallOptions()), request, responseObserver);
}
/**
* <pre>
* Setup and enable a device for live use. If this is the first time the subject device has activated itself,
* initialize or otherwise provision any requisite objects or resources.
* </pre>
*/
public void activate(io.bloombox.schema.services.devices.v1beta1.Activation.Request request,
io.grpc.stub.StreamObserver<io.bloombox.schema.services.devices.v1beta1.Activation.Response> responseObserver) {
asyncUnaryCall(
getChannel().newCall(getActivateMethod(), getCallOptions()), request, responseObserver);
}
}
/**
* <pre>
* Specifies the devices service, which enables managed devices to check-in, authorize themselves, and discover their
* identity/role.
* </pre>
*/
public static final class DevicesBlockingStub extends io.grpc.stub.AbstractStub<DevicesBlockingStub> {
private DevicesBlockingStub(io.grpc.Channel channel) {
super(channel);
}
private DevicesBlockingStub(io.grpc.Channel channel,
io.grpc.CallOptions callOptions) {
super(channel, callOptions);
}
@java.lang.Override
protected DevicesBlockingStub build(io.grpc.Channel channel,
io.grpc.CallOptions callOptions) {
return new DevicesBlockingStub(channel, callOptions);
}
/**
* <pre>
* Ping the device server.
* </pre>
*/
public io.bloombox.schema.services.devices.v1beta1.Ping.Response ping(io.bloombox.schema.services.devices.v1beta1.Ping.Request request) {
return blockingUnaryCall(
getChannel(), getPingMethod(), getCallOptions(), request);
}
/**
* <pre>
* Setup and enable a device for live use. If this is the first time the subject device has activated itself,
* initialize or otherwise provision any requisite objects or resources.
* </pre>
*/
public io.bloombox.schema.services.devices.v1beta1.Activation.Response activate(io.bloombox.schema.services.devices.v1beta1.Activation.Request request) {
return blockingUnaryCall(
getChannel(), getActivateMethod(), getCallOptions(), request);
}
}
/**
* <pre>
* Specifies the devices service, which enables managed devices to check-in, authorize themselves, and discover their
* identity/role.
* </pre>
*/
public static final class DevicesFutureStub extends io.grpc.stub.AbstractStub<DevicesFutureStub> {
private DevicesFutureStub(io.grpc.Channel channel) {
super(channel);
}
private DevicesFutureStub(io.grpc.Channel channel,
io.grpc.CallOptions callOptions) {
super(channel, callOptions);
}
@java.lang.Override
protected DevicesFutureStub build(io.grpc.Channel channel,
io.grpc.CallOptions callOptions) {
return new DevicesFutureStub(channel, callOptions);
}
/**
* <pre>
* Ping the device server.
* </pre>
*/
public com.google.common.util.concurrent.ListenableFuture<io.bloombox.schema.services.devices.v1beta1.Ping.Response> ping(
io.bloombox.schema.services.devices.v1beta1.Ping.Request request) {
return futureUnaryCall(
getChannel().newCall(getPingMethod(), getCallOptions()), request);
}
/**
* <pre>
* Setup and enable a device for live use. If this is the first time the subject device has activated itself,
* initialize or otherwise provision any requisite objects or resources.
* </pre>
*/
public com.google.common.util.concurrent.ListenableFuture<io.bloombox.schema.services.devices.v1beta1.Activation.Response> activate(
io.bloombox.schema.services.devices.v1beta1.Activation.Request request) {
return futureUnaryCall(
getChannel().newCall(getActivateMethod(), getCallOptions()), request);
}
}
private static final int METHODID_PING = 0;
private static final int METHODID_ACTIVATE = 1;
private static final class MethodHandlers<Req, Resp> implements
io.grpc.stub.ServerCalls.UnaryMethod<Req, Resp>,
io.grpc.stub.ServerCalls.ServerStreamingMethod<Req, Resp>,
io.grpc.stub.ServerCalls.ClientStreamingMethod<Req, Resp>,
io.grpc.stub.ServerCalls.BidiStreamingMethod<Req, Resp> {
private final DevicesImplBase serviceImpl;
private final int methodId;
MethodHandlers(DevicesImplBase serviceImpl, int methodId) {
this.serviceImpl = serviceImpl;
this.methodId = methodId;
}
@java.lang.Override
@java.lang.SuppressWarnings("unchecked")
public void invoke(Req request, io.grpc.stub.StreamObserver<Resp> responseObserver) {
switch (methodId) {
case METHODID_PING:
serviceImpl.ping((io.bloombox.schema.services.devices.v1beta1.Ping.Request) request,
(io.grpc.stub.StreamObserver<io.bloombox.schema.services.devices.v1beta1.Ping.Response>) responseObserver);
break;
case METHODID_ACTIVATE:
serviceImpl.activate((io.bloombox.schema.services.devices.v1beta1.Activation.Request) request,
(io.grpc.stub.StreamObserver<io.bloombox.schema.services.devices.v1beta1.Activation.Response>) responseObserver);
break;
default:
throw new AssertionError();
}
}
@java.lang.Override
@java.lang.SuppressWarnings("unchecked")
public io.grpc.stub.StreamObserver<Req> invoke(
io.grpc.stub.StreamObserver<Resp> responseObserver) {
switch (methodId) {
default:
throw new AssertionError();
}
}
}
private static abstract class DevicesBaseDescriptorSupplier
implements io.grpc.protobuf.ProtoFileDescriptorSupplier, io.grpc.protobuf.ProtoServiceDescriptorSupplier {
DevicesBaseDescriptorSupplier() {}
@java.lang.Override
public com.google.protobuf.Descriptors.FileDescriptor getFileDescriptor() {
return io.bloombox.schema.services.devices.v1beta1.DevicesServiceBeta1.getDescriptor();
}
@java.lang.Override
public com.google.protobuf.Descriptors.ServiceDescriptor getServiceDescriptor() {
return getFileDescriptor().findServiceByName("Devices");
}
}
private static final class DevicesFileDescriptorSupplier
extends DevicesBaseDescriptorSupplier {
DevicesFileDescriptorSupplier() {}
}
private static final class DevicesMethodDescriptorSupplier
extends DevicesBaseDescriptorSupplier
implements io.grpc.protobuf.ProtoMethodDescriptorSupplier {
private final String methodName;
DevicesMethodDescriptorSupplier(String methodName) {
this.methodName = methodName;
}
@java.lang.Override
public com.google.protobuf.Descriptors.MethodDescriptor getMethodDescriptor() {
return getServiceDescriptor().findMethodByName(methodName);
}
}
private static volatile io.grpc.ServiceDescriptor serviceDescriptor;
public static io.grpc.ServiceDescriptor getServiceDescriptor() {
io.grpc.ServiceDescriptor result = serviceDescriptor;
if (result == null) {
synchronized (DevicesGrpc.class) {
result = serviceDescriptor;
if (result == null) {
serviceDescriptor = result = io.grpc.ServiceDescriptor.newBuilder(SERVICE_NAME)
.setSchemaDescriptor(new DevicesFileDescriptorSupplier())
.addMethod(getPingMethod())
.addMethod(getActivateMethod())
.build();
}
}
}
return result;
}
}
|
package com.example.denaun.aoc2021.day09;
import static com.example.denaun.aoc2021.parsers.AocParsers.LEVEL_MAP;
import com.example.denaun.aoc2021.Coordinate;
import java.util.Collection;
import java.util.Comparator;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import org.jparsec.Parser;
class Day09 {
private Day09() {}
private static final Parser<HeightMap> PARSER = LEVEL_MAP.map(HeightMap::new);
static int part1(String input) {
var map = PARSER.parse(input);
return lowPoints(map)
.mapToInt(map::get)
.map(Day09::riskLevel)
.sum();
}
static int part2(String input) {
var map = PARSER.parse(input);
return lowPoints(map)
.map(map::expandBasin)
.sorted(Comparator.comparingInt(Collection<Coordinate>::size)
.reversed())
.limit(3)
.mapToInt(Collection::size)
.reduce(1, (a, b) -> a * b);
}
static Stream<Coordinate> lowPoints(HeightMap map) {
return IntStream.range(0, map.rows())
.boxed()
.flatMap(y -> IntStream.range(0, map.columns())
.mapToObj(x -> new Coordinate(x, y))
.filter(map::isLowPoint));
}
static int riskLevel(int height) {
return height + 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.apache.geode.management.internal;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import org.apache.logging.log4j.Logger;
import org.apache.geode.CancelException;
import org.apache.geode.DataSerializer;
import org.apache.geode.SystemFailure;
import org.apache.geode.distributed.internal.ClusterDistributionManager;
import org.apache.geode.distributed.internal.DistributionAdvisee;
import org.apache.geode.distributed.internal.DistributionAdvisor;
import org.apache.geode.distributed.internal.DistributionManager;
import org.apache.geode.distributed.internal.HighPriorityDistributionMessage;
import org.apache.geode.distributed.internal.membership.InternalDistributedMember;
import org.apache.geode.internal.cache.InternalCache;
import org.apache.geode.internal.serialization.DeserializationContext;
import org.apache.geode.internal.serialization.SerializationContext;
import org.apache.geode.logging.internal.log4j.api.LogService;
/**
* @since GemFire 7.0
*/
public class JmxManagerAdvisor extends DistributionAdvisor {
private static final Logger logger = LogService.getLogger();
private JmxManagerAdvisor(DistributionAdvisee advisee) {
super(advisee);
JmxManagerProfile p =
new JmxManagerProfile(getDistributionManager().getId(), incrementAndGetVersion());
advisee.fillInProfile(p);
((JmxManagerAdvisee) advisee).initProfile(p);
}
public static JmxManagerAdvisor createJmxManagerAdvisor(DistributionAdvisee advisee) {
JmxManagerAdvisor advisor = new JmxManagerAdvisor(advisee);
advisor.initialize();
return advisor;
}
@Override
public String toString() {
return "JmxManagerAdvisor for " + getAdvisee();
}
public void broadcastChange() {
try {
Set<InternalDistributedMember> recips = adviseGeneric(); // for now just tell everyone
JmxManagerProfile p =
new JmxManagerProfile(getDistributionManager().getId(), incrementAndGetVersion());
getAdvisee().fillInProfile(p);
JmxManagerProfileMessage.send(getAdvisee().getSystem().getDistributionManager(), recips, p);
} catch (CancelException ignore) {
}
}
@SuppressWarnings("unchecked")
public List<JmxManagerProfile> adviseAlreadyManaging() {
return fetchProfiles(profile -> {
assert profile instanceof JmxManagerProfile;
JmxManagerProfile jmxProfile = (JmxManagerProfile) profile;
return jmxProfile.isJmxManagerRunning();
});
}
@SuppressWarnings("unchecked")
public List<JmxManagerProfile> adviseWillingToManage() {
return fetchProfiles(profile -> {
assert profile instanceof JmxManagerProfile;
JmxManagerProfile jmxProfile = (JmxManagerProfile) profile;
return jmxProfile.isJmxManager();
});
}
@Override
protected Profile instantiateProfile(InternalDistributedMember memberId, int version) {
return new JmxManagerProfile(memberId, version);
}
/**
* Overridden to also include our profile. If our profile is included it will always be first.
*/
@Override
protected List/* <Profile> */ fetchProfiles(Filter f) {
initializationGate();
List result = null;
{
JmxManagerAdvisee advisee = (JmxManagerAdvisee) getAdvisee();
Profile myp = advisee.getMyMostRecentProfile();
if (f == null || f.include(myp)) {
if (result == null) {
result = new ArrayList();
}
result.add(myp);
}
}
Profile[] locProfiles = profiles; // grab current profiles
for (Profile profile : locProfiles) {
if (f == null || f.include(profile)) {
if (result == null) {
result = new ArrayList(locProfiles.length);
}
result.add(profile);
}
}
if (result == null) {
result = Collections.EMPTY_LIST;
} else {
result = Collections.unmodifiableList(result);
}
return result;
}
/**
* Message used to push event updates to remote VMs
*/
public static class JmxManagerProfileMessage extends HighPriorityDistributionMessage {
private volatile JmxManagerProfile profile;
private volatile int processorId;
/**
* Default constructor used for de-serialization (used during receipt)
*/
public JmxManagerProfileMessage() {}
@Override
public boolean sendViaUDP() {
return true;
}
/**
* Constructor used to send
*
*/
private JmxManagerProfileMessage(final Set<InternalDistributedMember> recips,
final JmxManagerProfile p) {
setRecipients(recips);
processorId = 0;
profile = p;
}
@Override
protected void process(ClusterDistributionManager dm) {
Throwable thr = null;
JmxManagerProfile p = null;
try {
final InternalCache cache = dm.getCache();
if (cache != null && !cache.isClosed()) {
final JmxManagerAdvisor adv = cache.getJmxManagerAdvisor();
p = profile;
if (p != null) {
adv.putProfile(p);
}
} else {
if (logger.isDebugEnabled()) {
logger.debug("No cache {}", this);
}
}
} catch (CancelException e) {
if (logger.isDebugEnabled()) {
logger.debug("Cache closed, {}", this);
}
} catch (VirtualMachineError err) {
SystemFailure.initiateFailure(err);
// If this ever returns, rethrow the error. We're poisoned
// now, so don't let this thread continue.
throw err;
} catch (Throwable t) {
// Whenever you catch Error or Throwable, you must also
// catch VirtualMachineError (see above). However, there is
// _still_ a possibility that you are dealing with a cascading
// error condition, so you also need to check to see if the JVM
// is still usable:
SystemFailure.checkFailure();
thr = t;
} finally {
if (thr != null) {
dm.getCancelCriterion().checkCancelInProgress(null);
logger.info(String.format("This member caught exception processing profile %s %s",
p, this), thr);
}
}
}
@Override
public int getDSFID() {
return JMX_MANAGER_PROFILE_MESSAGE;
}
@Override
public void fromData(DataInput in,
DeserializationContext context) throws IOException, ClassNotFoundException {
super.fromData(in, context);
processorId = in.readInt();
profile = DataSerializer.readObject(in);
}
@Override
public void toData(DataOutput out,
SerializationContext context) throws IOException {
super.toData(out, context);
out.writeInt(processorId);
DataSerializer.writeObject(profile, out);
}
/**
* Send profile to the provided members
*
* @param recips The recipients of the message
*/
public static void send(final DistributionManager dm, Set<InternalDistributedMember> recips,
JmxManagerProfile profile) {
JmxManagerProfileMessage r = new JmxManagerProfileMessage(recips, profile);
dm.putOutgoing(r);
}
@Override
public String getShortClassName() {
return "JmxManagerProfileMessage";
}
@Override
public String toString() {
return getShortClassName() + " (processorId=" + processorId
+ "; profile=" + profile
+ ")";
}
}
public static class JmxManagerProfile extends Profile {
private boolean jmxManager;
private String host;
private int port;
private boolean ssl;
private boolean started;
// Constructor for de-serialization
public JmxManagerProfile() {}
public boolean isJmxManager() {
return jmxManager;
}
public boolean isJmxManagerRunning() {
return started;
}
public void setInfo(boolean jmxManager2, String host2, int port2, boolean ssl2,
boolean started2) {
jmxManager = jmxManager2;
host = host2;
port = port2;
ssl = ssl2;
started = started2;
}
public String getHost() {
return host;
}
public int getPort() {
return port;
}
public boolean getSsl() {
return ssl;
}
// Constructor for sending purposes
public JmxManagerProfile(InternalDistributedMember memberId, int version) {
super(memberId, version);
}
@Override
public StringBuilder getToStringHeader() {
return new StringBuilder("JmxManagerAdvisor.JmxManagerProfile");
}
@Override
public void fillInToString(StringBuilder sb) {
super.fillInToString(sb);
synchronized (this) {
if (jmxManager) {
sb.append("; jmxManager");
}
sb.append("; host=").append(host).append("; port=").append(port);
if (ssl) {
sb.append("; ssl");
}
if (started) {
sb.append("; started");
}
}
}
@Override
public void processIncoming(ClusterDistributionManager dm, String adviseePath,
boolean removeProfile, boolean exchangeProfiles, final List<Profile> replyProfiles) {
final InternalCache cache = dm.getCache();
if (cache != null && !cache.isClosed()) {
handleDistributionAdvisee(cache.getJmxManagerAdvisor().getAdvisee(), removeProfile,
exchangeProfiles, replyProfiles);
}
}
@Override
public void fromData(DataInput in,
DeserializationContext context) throws IOException, ClassNotFoundException {
super.fromData(in, context);
jmxManager = DataSerializer.readPrimitiveBoolean(in);
host = DataSerializer.readString(in);
port = DataSerializer.readPrimitiveInt(in);
ssl = DataSerializer.readPrimitiveBoolean(in);
started = DataSerializer.readPrimitiveBoolean(in);
}
@Override
public void toData(DataOutput out,
SerializationContext context) throws IOException {
boolean tmpJmxManager;
String tmpHost;
int tmpPort;
boolean tmpSsl;
boolean tmpStarted;
synchronized (this) {
tmpJmxManager = jmxManager;
tmpHost = host;
tmpPort = port;
tmpSsl = ssl;
tmpStarted = started;
}
super.toData(out, context);
DataSerializer.writePrimitiveBoolean(tmpJmxManager, out);
DataSerializer.writeString(tmpHost, out);
DataSerializer.writePrimitiveInt(tmpPort, out);
DataSerializer.writePrimitiveBoolean(tmpSsl, out);
DataSerializer.writePrimitiveBoolean(tmpStarted, out);
}
@Override
public int getDSFID() {
return JMX_MANAGER_PROFILE;
}
}
}
|
/**********************************************************************************
* $URL: https://source.sakaiproject.org/svn/sam/trunk/samigo-app/src/java/org/sakaiproject/tool/assessment/ui/listener/evaluation/TotalScoreListener.java $
* $Id: EmailListener.java 17372 2006-10-25 02:27:49Z daisyf@stanford.edu $
***********************************************************************************
*
* Copyright (c) 2006, 2007, 2008 The Sakai Foundation
*
* Licensed under the Educational Community 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.osedu.org/licenses/ECL-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.sakaiproject.tool.assessment.ui.listener.util;
import javax.faces.event.AbortProcessingException;
import javax.faces.event.ActionEvent;
import javax.faces.event.ActionListener;
import lombok.extern.slf4j.Slf4j;
import org.sakaiproject.tool.assessment.facade.AgentFacade;
import org.sakaiproject.tool.assessment.ui.bean.evaluation.TotalScoresBean;
import org.sakaiproject.tool.assessment.ui.bean.util.EmailBean;
@Slf4j
public class EmailListener implements ActionListener {
/**
* Standard process action method.
*
* @param ae
* ActionEvent
* @throws AbortProcessingException
*/
public void processAction(ActionEvent ae) throws AbortProcessingException {
log.debug("Email Action Listener.");
EmailBean emailBean = (EmailBean) ContextUtil.lookupBean("email");
TotalScoresBean totalScoreBean = (TotalScoresBean) ContextUtil.lookupBean("totalScores");
emailBean.setMessage(null);
emailBean.setAttachmentList(null);
emailBean.setHasAttachment(false);
emailBean.setCcMe("no");
// From Name and email are set in TotalScoreListener
// To
String toUserId = ContextUtil.lookupParam("toUserId");
AgentFacade agent = new AgentFacade(toUserId);
String toFirstName = agent.getFirstName();
String toName = toFirstName + " " + agent.getLastName();
String toEmailAddress = agent.getEmail();
emailBean.setToFirstName(toFirstName);
emailBean.setToName(toName);
emailBean.setToEmailAddress(toEmailAddress);
// AssessmentName
emailBean.setAssessmentName(totalScoreBean.getAssessmentName());
// Subject
StringBuilder sb = new StringBuilder(totalScoreBean.getAssessmentName());
sb.append(" ");
sb.append(ContextUtil.getLocalizedString("org.sakaiproject.tool.assessment.bundle.EvaluationMessages", "feedback"));
emailBean.setSubject(sb.toString());
}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.artemis.jms.transaction;
import javax.transaction.xa.Xid;
import java.util.Map;
import org.apache.activemq.artemis.api.core.ICoreMessage;
import org.apache.activemq.artemis.api.core.Message;
import org.apache.activemq.artemis.core.transaction.Transaction;
import org.apache.activemq.artemis.core.transaction.TransactionDetail;
import org.apache.activemq.artemis.jms.client.ActiveMQBytesMessage;
import org.apache.activemq.artemis.jms.client.ActiveMQMapMessage;
import org.apache.activemq.artemis.jms.client.ActiveMQMessage;
import org.apache.activemq.artemis.jms.client.ActiveMQObjectMessage;
import org.apache.activemq.artemis.jms.client.ActiveMQStreamMessage;
import org.apache.activemq.artemis.jms.client.ActiveMQTextMessage;
public class JMSTransactionDetail extends TransactionDetail {
public JMSTransactionDetail(Xid xid, Transaction tx, Long creation) {
super(xid, tx, creation);
}
@Override
public String decodeMessageType(Message msg) {
if (!(msg instanceof ICoreMessage)) {
return "N/A";
}
int type = ((ICoreMessage) msg).getType();
switch (type) {
case ActiveMQMessage.TYPE: // 0
return "Default";
case ActiveMQObjectMessage.TYPE: // 2
return "ObjectMessage";
case ActiveMQTextMessage.TYPE: // 3
return "TextMessage";
case ActiveMQBytesMessage.TYPE: // 4
return "ByteMessage";
case ActiveMQMapMessage.TYPE: // 5
return "MapMessage";
case ActiveMQStreamMessage.TYPE: // 6
return "StreamMessage";
default:
return "(Unknown Type)";
}
}
@Override
public Map<String, Object> decodeMessageProperties(Message msg) {
try {
return ActiveMQMessage.coreMaptoJMSMap(msg.toMap());
} catch (Throwable t) {
return null;
}
}
}
|
/*
* Copyright (c) 2002-2020 Gargoyle Software 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.gargoylesoftware.htmlunit.javascript.background;
import java.lang.ref.WeakReference;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.WebWindow;
/**
* An event loop to execute all the JavaScript jobs.
*
* @author Amit Manjhi
* @author Kostadin Chikov
* @author Ronald Brill
*/
public class DefaultJavaScriptExecutor implements JavaScriptExecutor {
private final transient WeakReference<WebClient> webClient_;
private final transient List<WeakReference<JavaScriptJobManager>> jobManagerList_;
private final transient AtomicBoolean shutdown_;
private transient Thread eventLoopThread_;
/** Logging support. */
private static final Log LOG = LogFactory.getLog(DefaultJavaScriptExecutor.class);
/** Creates an EventLoop for the webClient.
*
* @param webClient the provided webClient
*/
public DefaultJavaScriptExecutor(final WebClient webClient) {
webClient_ = new WeakReference<>(webClient);
jobManagerList_ = new LinkedList<>();
shutdown_ = new AtomicBoolean();
}
/**
* Starts the eventLoopThread_.
*/
protected void startThreadIfNeeded() {
if (eventLoopThread_ == null) {
eventLoopThread_ = new Thread(this, getThreadName());
eventLoopThread_.setDaemon(true);
eventLoopThread_.start();
}
}
/**
* Defines the thread name; overload if needed.
* @return the name of the js executor thread
*/
protected String getThreadName() {
return "JS executor for " + webClient_.get();
}
@SuppressWarnings("deprecation")
private void killThread() {
if (eventLoopThread_ == null) {
return;
}
try {
eventLoopThread_.interrupt();
eventLoopThread_.join(10_000);
}
catch (final InterruptedException e) {
LOG.warn("InterruptedException while waiting for the eventLoop thread to join ", e);
// ignore, this doesn't matter, we want to stop it
}
if (eventLoopThread_.isAlive()) {
if (LOG.isWarnEnabled()) {
LOG.warn("Event loop thread "
+ eventLoopThread_.getName()
+ " still alive at "
+ System.currentTimeMillis());
LOG.warn("Event loop thread will be stopped");
}
// Stop the thread
eventLoopThread_.stop();
}
}
/**
* Returns the JobExecutor corresponding to the earliest job.
* @return the JobExectuor with the earliest job.
*/
protected JavaScriptJobManager getJobManagerWithEarliestJob() {
JavaScriptJobManager javaScriptJobManager = null;
JavaScriptJob earliestJob = null;
synchronized (jobManagerList_) {
// iterate over the list and find the earliest job to run.
for (WeakReference<JavaScriptJobManager> weakReference : jobManagerList_) {
final JavaScriptJobManager jobManager = weakReference.get();
if (jobManager != null) {
final JavaScriptJob newJob = jobManager.getEarliestJob();
if (newJob != null && (earliestJob == null || earliestJob.compareTo(newJob) > 0)) {
earliestJob = newJob;
javaScriptJobManager = jobManager;
}
}
}
}
return javaScriptJobManager;
}
/** Runs the eventLoop. */
@Override
public void run() {
final boolean trace = LOG.isTraceEnabled();
// this has to be a multiple of 10ms
// otherwise the VM has to fight with the OS to get such small periods
final long sleepInterval = 10;
while (!shutdown_.get() && !Thread.currentThread().isInterrupted() && webClient_.get() != null) {
final JavaScriptJobManager jobManager = getJobManagerWithEarliestJob();
if (jobManager != null) {
final JavaScriptJob earliestJob = jobManager.getEarliestJob();
if (earliestJob != null) {
final long waitTime = earliestJob.getTargetExecutionTime() - System.currentTimeMillis();
// do we have to execute the earliest job
if (waitTime < 1) {
// execute the earliest job
if (trace) {
LOG.trace("started executing job at " + System.currentTimeMillis());
}
jobManager.runSingleJob(earliestJob);
if (trace) {
LOG.trace("stopped executing job at " + System.currentTimeMillis());
}
// job is done, have a look for another one
continue;
}
}
}
// check for cancel
if (shutdown_.get() || Thread.currentThread().isInterrupted() || webClient_.get() == null) {
break;
}
// nothing to do, let's sleep a bit
try {
Thread.sleep(sleepInterval);
}
catch (final InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
/**
* Register a window with the eventLoop.
* @param newWindow the new web window
*/
@Override
public void addWindow(final WebWindow newWindow) {
final JavaScriptJobManager jobManager = newWindow.getJobManager();
if (jobManager != null) {
updateJobMangerList(jobManager);
startThreadIfNeeded();
}
}
private void updateJobMangerList(final JavaScriptJobManager newJobManager) {
final List<WeakReference<JavaScriptJobManager>> managers = new LinkedList<>();
synchronized (jobManagerList_) {
for (WeakReference<JavaScriptJobManager> weakReference : jobManagerList_) {
final JavaScriptJobManager manager = weakReference.get();
if (newJobManager == manager) {
return;
}
if (null != weakReference.get()) {
managers.add(weakReference);
}
}
managers.add(new WeakReference<>(newJobManager));
jobManagerList_.clear();
jobManagerList_.addAll(managers);
}
}
/** Notes that this thread has been shutdown. */
@Override
public void shutdown() {
shutdown_.set(true);
killThread();
webClient_.clear();
synchronized (jobManagerList_) {
jobManagerList_.clear();
}
}
}
|
/*
* Copyright (C) 2012 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtCompatible;
import javax.annotation.Nullable;
/**
* An implementation of an immutable sorted map with one or more entries.
*
* @author Louis Wasserman
*/
@GwtCompatible(emulated = true)
@SuppressWarnings("serial") // uses writeReplace, not default serialization
final class RegularImmutableSortedMap<K, V> extends ImmutableSortedMap<K, V> {
private final transient RegularImmutableSortedSet<K> keySet;
private final transient ImmutableList<V> valueList;
RegularImmutableSortedMap(RegularImmutableSortedSet<K> keySet, ImmutableList<V> valueList) {
this.keySet = keySet;
this.valueList = valueList;
}
RegularImmutableSortedMap(
RegularImmutableSortedSet<K> keySet,
ImmutableList<V> valueList,
ImmutableSortedMap<K, V> descendingMap) {
super(descendingMap);
this.keySet = keySet;
this.valueList = valueList;
}
@Override
ImmutableSet<Entry<K, V>> createEntrySet() {
return new EntrySet();
}
private class EntrySet extends ImmutableMapEntrySet<K, V> {
@Override
public UnmodifiableIterator<Entry<K, V>> iterator() {
return asList().iterator();
}
@Override
ImmutableList<Entry<K, V>> createAsList() {
return new ImmutableAsList<Entry<K, V>>() {
// avoid additional indirection
private final ImmutableList<K> keyList = keySet().asList();
@Override
public Entry<K, V> get(int index) {
return Maps.immutableEntry(keyList.get(index), valueList.get(index));
}
@Override
ImmutableCollection<Entry<K, V>> delegateCollection() {
return EntrySet.this;
}
};
}
@Override
ImmutableMap<K, V> map() {
return RegularImmutableSortedMap.this;
}
}
@Override
public ImmutableSortedSet<K> keySet() {
return keySet;
}
@Override
public ImmutableCollection<V> values() {
return valueList;
}
@Override
public V get(@Nullable Object key) {
int index = keySet.indexOf(key);
return (index == -1) ? null : valueList.get(index);
}
private ImmutableSortedMap<K, V> getSubMap(int fromIndex, int toIndex) {
if (fromIndex == 0 && toIndex == size()) {
return this;
} else if (fromIndex == toIndex) {
return emptyMap(comparator());
} else {
return from(
keySet.getSubSet(fromIndex, toIndex),
valueList.subList(fromIndex, toIndex));
}
}
@Override
public ImmutableSortedMap<K, V> headMap(K toKey, boolean inclusive) {
return getSubMap(0, keySet.headIndex(checkNotNull(toKey), inclusive));
}
@Override
public ImmutableSortedMap<K, V> tailMap(K fromKey, boolean inclusive) {
return getSubMap(keySet.tailIndex(checkNotNull(fromKey), inclusive), size());
}
@Override
ImmutableSortedMap<K, V> createDescendingMap() {
return new RegularImmutableSortedMap<K, V>(
(RegularImmutableSortedSet<K>) keySet.descendingSet(),
valueList.reverse(),
this);
}
}
|
package com.networknt.eventuate.jdbc;
import com.networknt.eventuate.common.Int128;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
public class IdGeneratorImpl implements IdGenerator {
private Logger logger = LoggerFactory.getLogger(getClass());
private static final long MAX_COUNTER = 1 << 16;
private Long macAddress;
private long currentPeriod = timeNow();
private long counter = 0;
public IdGeneratorImpl() {
try {
Enumeration<NetworkInterface> ifaces = NetworkInterface.getNetworkInterfaces();
while (ifaces.hasMoreElements()) {
NetworkInterface iface = ifaces.nextElement();
if (iface.getHardwareAddress() != null) {
macAddress = toLong(iface.getHardwareAddress());
logger.debug("Mac address {}", macAddress);
break;
}
}
if (macAddress == null)
throw new RuntimeException("Cannot find mac address");
} catch (SocketException e) {
throw new RuntimeException(e);
}
}
private Long toLong(byte[] bytes) {
long result = 0L;
for (byte b : bytes) {
result = (result << 8) + (b & 0xff);
}
return result;
}
private long timeNow() {
return System.currentTimeMillis();
}
private Int128 makeId() {
return new Int128(currentPeriod, (macAddress << 16) + counter);
}
public Int128 genIdInternal() {
long now = timeNow();
if (currentPeriod != now || counter == MAX_COUNTER) {
long oldPeriod = this.currentPeriod;
while ((this.currentPeriod = timeNow()) <= oldPeriod) {
// Just do nothing
}
counter = 0;
}
Int128 id = makeId();
counter = counter + 1;
return id;
}
@Override
public synchronized Int128 genId() {
return genIdInternal();
}
}
|
package org.develnext.jphp.core.compiler.jvm;
import org.junit.Assert;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.runners.MethodSorters;
import php.runtime.Memory;
@RunWith(JUnit4.class)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class NamespacesTest extends JvmCompilerCase {
@Test
public void testSimple(){
Memory memory = includeResource("namespaces/simple.php");
Assert.assertEquals("success", memory.toString());
}
@Test
public void testUse(){
Memory memory = includeResource("namespaces/use.php");
Assert.assertEquals("success", memory.toString());
}
@Test
public void testUseAs(){
Memory memory = includeResource("namespaces/use_as.php");
Assert.assertEquals("success", memory.toString());
}
@Test
public void testGlobals() {
check("namespaces/globals.php");
}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.linkis.cli.application.data;
import org.apache.linkis.cli.common.entity.properties.ClientProperties;
import java.util.Map;
public class PreparedData {
Map<String, ClientProperties> propertiesMap;
public PreparedData(Map<String, ClientProperties> propertiesMap) {
this.propertiesMap = propertiesMap;
}
public Map<String, ClientProperties> getPropertiesMap() {
return propertiesMap;
}
}
|
/*Copyright ©2016 TommyLemon(https://github.com/TommyLemon)
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 apijson.demo.client.server.model;
import zuo.biao.apijson.APIJSONRequest;
import zuo.biao.apijson.BaseModel;
import zuo.biao.apijson.RequestMethod;
/**评论类
* @author Lemon
*/
@APIJSONRequest(
method = {RequestMethod.GET, RequestMethod.HEAD, RequestMethod.POST, RequestMethod.PUT, RequestMethod.DELETE},
DELETE = "{necessaryColumns:id}"
)
public class Comment extends BaseModel {
private static final long serialVersionUID = -1011007127735372824L;
private Long toId;
private Long userId;
private Long momentId;
private String content;
public Comment() {
super();
}
public Comment(long id) {
this();
setId(id);
}
public Long getToId() {
return toId;
}
public Comment setToId(Long toId) {
this.toId = toId;
return this;
}
public Long getUserId() {
return userId;
}
public Comment setUserId(Long userId) {
this.userId = userId;
return this;
}
public Long getMomentId() {
return momentId;
}
public Comment setMomentId(Long momentId) {
this.momentId = momentId;
return this;
}
public String getContent() {
return content;
}
public Comment setContent(String content) {
this.content = content;
return this;
}
}
|
package brown.tracingplane.baggageprotocol;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.nio.ByteBuffer;
import org.junit.Test;
import com.google.common.collect.Lists;
import brown.tracingplane.atomlayer.ByteBuffers;
import brown.tracingplane.baggageprotocol.BaggageLayerException.BaggageLayerRuntimeException;
/**
* Tests a simple baggage containing one child bags and some data elements in the bag
*/
public class TestBaggage04_OneChild extends BaggageTestCase {
private final BagKey.Indexed bagKey = indexed(4);
private final ByteBuffer[] payloads = { randomBytes(3), randomBytes(1), randomBytes(0) };
private final ByteBuffer[] allAtoms =
{ headerAtom(bagKey, 0), dataAtom(payloads[0]), dataAtom(payloads[1]), dataAtom(payloads[2]) };
private BaggageReader makeBaggage() {
BaggageWriter writer = BaggageWriter.create();
writer.enter(bagKey);
for (ByteBuffer payload : payloads) {
ByteBuffers.copyTo(payload, writer.newDataAtom(payload.remaining()));
}
writer.exit();
return BaggageReader.create(writer.atoms());
}
@Test
public void testExplicitEnter() {
BaggageReader reader = makeBaggage();
assertTrue(reader.enter(bagKey));
assertFalse(reader.enter(bagKey));
reader.exit();
assertFalse(reader.enter(bagKey));
}
@Test
public void testImplicitEnter() {
BaggageReader reader = makeBaggage();
assertEquals(bagKey, reader.enter());
assertNull(reader.enter());
reader.exit();
assertNull(reader.enter());
}
@Test
public void testNextDataExplicitEntry() {
BaggageReader reader = makeBaggage();
assertNull(reader.nextData());
reader.enter(bagKey);
for (ByteBuffer payload : payloads) {
assertEquals(payload, reader.nextData());
}
assertNull(reader.nextData());
reader.exit();
assertNull(reader.nextData());
}
@Test
public void testNextDataImplicitEntry() {
BaggageReader reader = makeBaggage();
assertNull(reader.nextData());
reader.enter();
for (ByteBuffer payload : payloads) {
assertEquals(payload, reader.nextData());
}
assertNull(reader.nextData());
reader.exit();
assertNull(reader.nextData());
}
@Test
public void testHasNext() {
BaggageReader reader = makeBaggage();
assertTrue(reader.hasNext());
reader.enter(bagKey);
for (int i = 0; i < payloads.length; i++) {
assertTrue(reader.hasNext());
reader.nextData();
}
assertFalse(reader.hasNext());
reader.exit();
assertFalse(reader.hasNext());
}
@Test
public void testHasData() {
BaggageReader reader = makeBaggage();
assertFalse(reader.hasData());
reader.enter(bagKey);
for (int i = 0; i < payloads.length; i++) {
assertTrue(reader.hasData());
reader.nextData();
}
assertFalse(reader.hasData());
reader.exit();
assertFalse(reader.hasData());
}
@Test
public void testHasChild() {
BaggageReader reader = makeBaggage();
assertTrue(reader.hasChild());
reader.enter(bagKey);
for (int i = 0; i < payloads.length; i++) {
assertFalse(reader.hasChild());
reader.nextData();
}
assertFalse(reader.hasChild());
reader.exit();
assertFalse(reader.hasChild());
}
@Test
public void testEnterEarlierBagExplicit() {
BaggageReader reader = makeBaggage();
assertFalse(reader.enter(indexed(bagKey.index - 1)));
assertTrue(reader.enter(bagKey));
}
@Test
public void testEnterEarlierBagImplicit() {
BaggageReader reader = makeBaggage();
assertFalse(reader.enter(indexed(bagKey.index - 1)));
assertEquals(bagKey, reader.enter());
}
@Test
public void testEnterLaterBagExplicit() {
BaggageReader reader = makeBaggage();
assertFalse(reader.enter(indexed(bagKey.index + 1)));
assertFalse(reader.enter(bagKey));
}
@Test
public void testEnterLaterBagImplicit() {
BaggageReader reader = makeBaggage();
assertFalse(reader.enter(indexed(bagKey.index + 1)));
assertNull(reader.enter());
}
@Test
public void testEnterSkipsChildData() {
BaggageReader reader = makeBaggage();
assertEquals(bagKey, reader.enter());
assertNull(reader.enter());
assertFalse(reader.hasData());
assertNull(reader.nextData());
}
@Test
public void testFinishClearsBag() {
BaggageReader reader = makeBaggage();
assertTrue(reader.hasChild());
reader.finish();
assertFalse(reader.hasChild());
}
@Test
public void testExitThrowsException() {
BaggageReader reader = makeBaggage();
reader.enter();
reader.exit();
exception.expect(BaggageLayerRuntimeException.class);
reader.exit();
}
@Test
public void testFinishMarksAllAtomsUnprocessed() {
BaggageReader reader = makeBaggage();
reader.finish();
assertEquals(Lists.newArrayList(allAtoms), reader.unprocessedAtoms());
}
@Test
public void testFinishMarksAllAtomsUnprocessedEvenWithEnter() {
BaggageReader reader = makeBaggage();
reader.enter(bagKey);
reader.finish();
assertEquals(Lists.newArrayList(allAtoms), reader.unprocessedAtoms());
}
@Test
public void testEnterLaterBagMarksAllAtomsUnprocessed() {
BaggageReader reader = makeBaggage();
reader.enter(indexed(bagKey.index + 1));
reader.finish();
assertEquals(Lists.newArrayList(allAtoms), reader.unprocessedAtoms());
}
@Test
public void testPartiallyProcessedDataIsNotMarkedAsUnprocessed() {
BaggageReader reader = makeBaggage();
reader.enter();
reader.nextData();
reader.exit();
reader.finish();
assertNull(reader.unprocessedAtoms());
assertFalse(reader.hasNext());
}
@Test
public void testDidNotOverflow() {
BaggageReader reader = makeBaggage();
assertFalse(reader.didOverflow());
reader.enter();
for (int i = 0; i < payloads.length; i++) {
assertFalse(reader.didOverflow());
reader.nextData();
}
assertFalse(reader.didOverflow());
}
@Test
public void testNoOverflow() {
BaggageReader reader = makeBaggage();
for (int i = 0; i < payloads.length; i++) {
reader.nextData();
}
assertNull(reader.overflowAtoms());
}
}
|
/**
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.streamnative.pulsar.handlers.mqtt.mqtt3.fusesource.proxy;
import static org.mockito.Mockito.verify;
import com.google.common.util.concurrent.AtomicDouble;
import com.google.gson.Gson;
import com.google.gson.internal.LinkedTreeMap;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.streamnative.pulsar.handlers.mqtt.MQTTServerConfiguration;
import io.streamnative.pulsar.handlers.mqtt.TopicFilterImpl;
import io.streamnative.pulsar.handlers.mqtt.base.MQTTTestBase;
import io.streamnative.pulsar.handlers.mqtt.mqtt3.fusesource.psk.PSKClient;
import java.io.BufferedReader;
import java.io.EOFException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.pulsar.client.impl.PulsarClientImpl;
import org.apache.pulsar.common.api.proto.CommandGetTopicsOfNamespace;
import org.apache.pulsar.common.naming.NamespaceName;
import org.apache.pulsar.common.naming.TopicName;
import org.awaitility.Awaitility;
import org.fusesource.mqtt.client.BlockingConnection;
import org.fusesource.mqtt.client.MQTT;
import org.fusesource.mqtt.client.Message;
import org.fusesource.mqtt.client.QoS;
import org.fusesource.mqtt.client.Topic;
import org.mockito.Mockito;
import org.testng.Assert;
import org.testng.annotations.Test;
/**
* Integration tests for MQTT protocol handler with proxy.
*/
@Slf4j
public class ProxyTest extends MQTTTestBase {
@Override
protected MQTTServerConfiguration initConfig() throws Exception {
MQTTServerConfiguration mqtt = super.initConfig();
mqtt.setMqttProxyEnabled(true);
mqtt.setMqttProxyTlsPskEnabled(true);
mqtt.setTlsPskIdentityHint("alpha");
mqtt.setTlsPskIdentity("mqtt:mqtt123");
return mqtt;
}
@Test(dataProvider = "mqttTopicNames", timeOut = TIMEOUT, priority = 4)
public void testSendAndConsume(String topicName) throws Exception {
MQTT mqtt = createMQTTProxyClient();
BlockingConnection connection = mqtt.blockingConnection();
connection.connect();
Topic[] topics = { new Topic(topicName, QoS.AT_MOST_ONCE) };
connection.subscribe(topics);
String message = "Hello MQTT Proxy";
connection.publish(topicName, message.getBytes(), QoS.AT_MOST_ONCE, false);
Message received = connection.receive();
Assert.assertEquals(received.getTopic(), topicName);
Assert.assertEquals(new String(received.getPayload()), message);
received.ack();
connection.disconnect();
}
@Test(expectedExceptions = {EOFException.class, IllegalStateException.class}, priority = 3)
public void testInvalidClientId() throws Exception {
MQTT mqtt = createMQTTProxyClient();
mqtt.setConnectAttemptsMax(1);
// ClientId is invalid, for max length is 23 in mqtt 3.1
mqtt.setClientId(UUID.randomUUID().toString().replace("-", ""));
BlockingConnection connection = Mockito.spy(mqtt.blockingConnection());
connection.connect();
verify(connection, Mockito.times(2)).connect();
}
@Test(timeOut = TIMEOUT, priority = 2)
public void testSendAndConsumeAcrossProxy() throws Exception {
int numMessage = 3;
String topicName = "a/b/c";
MQTT mqtt0 = new MQTT();
mqtt0.setHost("127.0.0.1", mqttProxyPortList.get(0));
BlockingConnection connection0 = mqtt0.blockingConnection();
connection0.connect();
Topic[] topics = { new Topic(topicName, QoS.AT_MOST_ONCE) };
connection0.subscribe(topics);
String message = "Hello MQTT Proxy";
MQTT mqtt1 = new MQTT();
mqtt1.setHost("127.0.0.1", mqttProxyPortList.get(1));
BlockingConnection connection1 = mqtt1.blockingConnection();
connection1.connect();
connection1.publish(topicName, message.getBytes(), QoS.AT_MOST_ONCE, false);
MQTT mqtt2 = new MQTT();
mqtt2.setHost("127.0.0.1", mqttProxyPortList.get(2));
BlockingConnection connection2 = mqtt2.blockingConnection();
connection2.connect();
connection2.publish(topicName, message.getBytes(), QoS.AT_MOST_ONCE, false);
MQTT mqtt3 = new MQTT();
mqtt3.setHost("127.0.0.1", mqttProxyPortList.get(0));
BlockingConnection connection3 = mqtt3.blockingConnection();
connection3.connect();
connection3.publish(topicName, message.getBytes(), QoS.AT_MOST_ONCE, false);
for (int i = 0; i < numMessage; i++) {
Message received = connection0.receive();
Assert.assertEquals(received.getTopic(), topicName);
Assert.assertEquals(new String(received.getPayload()), message);
received.ack();
}
connection3.disconnect();
connection2.disconnect();
connection1.disconnect();
connection0.disconnect();
}
@Test(dataProvider = "mqttTopicNameAndFilter", timeOut = 30000, priority = 1)
@SneakyThrows
public void testSendAndConsumeWithFilter(String topic, String filter) {
MQTT mqtt0 = createMQTTProxyClient();
BlockingConnection connection0 = mqtt0.blockingConnection();
connection0.connect();
Topic[] topics = { new Topic(filter, QoS.AT_MOST_ONCE) };
String message = "Hello MQTT Proxy";
MQTT mqtt1 = createMQTTProxyClient();
BlockingConnection connection1 = mqtt1.blockingConnection();
connection1.connect();
connection1.publish(topic, message.getBytes(), QoS.AT_MOST_ONCE, false);
// wait for the publish topic has been stored
Awaitility.await().untilAsserted(() -> {
CompletableFuture<List<String>> listOfTopics = pulsarServiceList.get(0).getNamespaceService()
.getListOfTopics(NamespaceName.get("public/default"), CommandGetTopicsOfNamespace.Mode.PERSISTENT);
Assert.assertTrue(listOfTopics.join().size() >= 1);
});
connection0.subscribe(topics);
connection1.publish(topic, message.getBytes(), QoS.AT_MOST_ONCE, false);
Message received = connection0.receive();
Assert.assertTrue(new TopicFilterImpl(filter).test(received.getTopic()));
Assert.assertEquals(new String(received.getPayload()), message);
connection1.disconnect();
connection0.disconnect();
}
@Test
@SneakyThrows
public void testTlsPskWithTlsv1() {
Bootstrap client = new Bootstrap();
EventLoopGroup group = new NioEventLoopGroup();
client.group(group);
client.channel(NioSocketChannel.class);
client.handler(new PSKClient("alpha", "mqtt", "mqtt123"));
AtomicBoolean connected = new AtomicBoolean(false);
CountDownLatch latch = new CountDownLatch(1);
client.connect("localhost", mqttProxyPortTlsPskList.get(0)).addListener((ChannelFutureListener) future -> {
connected.set(future.isSuccess());
latch.countDown();
});
latch.await();
Assert.assertTrue(connected.get());
}
@Test
@SneakyThrows
public void testProxyProcessPingReq() {
String topic = "persistent://public/default/a";
// Producer
MQTT mqttProducer = createMQTTProxyClient();
mqttProducer.setKeepAlive((short) 2);
mqttProducer.setConnectAttemptsMax(0);
mqttProducer.setReconnectAttemptsMax(0);
BlockingConnection producer = mqttProducer.blockingConnection();
producer.connect();
producer.publish(topic, "Hello MQTT".getBytes(StandardCharsets.UTF_8), QoS.AT_MOST_ONCE, false);
Thread.sleep(4000); // Sleep 2 times of setKeepAlive.
Assert.assertTrue(producer.isConnected());
// Check for broker
CompletableFuture<Pair<InetSocketAddress, InetSocketAddress>> broker =
((PulsarClientImpl) pulsarClient).getLookup().getBroker(TopicName.get(topic));
AtomicDouble active = new AtomicDouble(0);
AtomicDouble total = new AtomicDouble(0);
CompletableFuture<Void> result = new CompletableFuture<>();
broker.thenAccept(pair -> {
try {
HttpClient httpClient = HttpClientBuilder.create().build();
final String mopEndPoint = "http://localhost:" + (pair.getLeft().getPort() + 2) + "/mop-stats";
HttpResponse response = httpClient.execute(new HttpGet(mopEndPoint));
InputStream inputStream = response.getEntity().getContent();
InputStreamReader isReader = new InputStreamReader(inputStream);
BufferedReader reader = new BufferedReader(isReader);
StringBuffer buffer = new StringBuffer();
String str;
while ((str = reader.readLine()) != null){
buffer.append(str);
}
String ret = buffer.toString();
LinkedTreeMap treeMap = new Gson().fromJson(ret, LinkedTreeMap.class);
LinkedTreeMap clients = (LinkedTreeMap) treeMap.get("clients");
active.set((Double) clients.get("active"));
total.set((Double) clients.get("total"));
result.complete(null);
} catch (Throwable ex) {
result.completeExceptionally(ex);
}
});
result.get(1, TimeUnit.MINUTES);
Assert.assertEquals(active.get(), 1.0);
Assert.assertEquals(total.get(), 1.0);
}
@Test
@SneakyThrows
public void testPubAndSubWithDifferentTopics() {
MQTT mqtt = createMQTTProxyClient();
BlockingConnection connection = mqtt.blockingConnection();
connection.connect();
Topic[] topics = { new Topic("subTopic2", QoS.AT_LEAST_ONCE) };
connection.subscribe(topics);
MQTT mqtt2 = createMQTTProxyClient();
BlockingConnection connection2 = mqtt2.blockingConnection();
connection2.connect();
Topic[] topics2 = { new Topic("subTopic1", QoS.AT_LEAST_ONCE) };
connection2.subscribe(topics2);
connection.publish("subTopic1", "mqtt1".getBytes(StandardCharsets.UTF_8), QoS.AT_MOST_ONCE, false);
connection2.publish("subTopic2", "mqtt2".getBytes(StandardCharsets.UTF_8), QoS.AT_MOST_ONCE, false);
Message msg1 = connection2.receive();
Message msg2 = connection.receive();
Assert.assertEquals(new String(msg1.getPayload()), "mqtt1");
Assert.assertEquals(new String(msg2.getPayload()), "mqtt2");
//
connection.disconnect();
connection2.disconnect();
}
}
|
package org.freebencher;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
/**
* A job made up of a number of concurrent tests
*
* @author chenjianjx@gmail.com
*
*/
public class FbJob {
private FbTarget target;
private FbJobOptions options;
private FbJobResult result;
public FbTarget getTarget() {
return target;
}
public void setTarget(FbTarget target) {
this.target = target;
}
public FbJobOptions getOptions() {
return options;
}
public void setOptions(FbJobOptions options) {
this.options = options;
}
public FbJobResult getResult() {
return result;
}
public void setResult(FbJobResult result) {
this.result = result;
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this,
ToStringStyle.MULTI_LINE_STYLE);
}
}
|
package com.github.loki4j.logback;
import com.github.loki4j.client.pipeline.PipelineConfig;
import ch.qos.logback.core.joran.spi.NoAutoStart;
/**
* Encoder that converts log batches into Protobuf format specified by Loki API
*/
@NoAutoStart
public class ProtobufEncoder extends AbstractLoki4jEncoder {
@Override
public PipelineConfig.WriterFactory getWriterFactory() {
return PipelineConfig.protobuf;
}
}
|
package io.jboot.admin.controller.app;
import com.alibaba.dubbo.common.utils.StringUtils;
import com.jfinal.aop.Before;
import com.jfinal.ext.interceptor.GET;
import com.jfinal.ext.interceptor.POST;
import com.jfinal.plugin.activerecord.Page;
import io.jboot.admin.base.common.BaseStatus;
import io.jboot.admin.base.common.RestResult;
import io.jboot.admin.base.common.ResultCode;
import io.jboot.admin.base.exception.BusinessException;
import io.jboot.admin.base.interceptor.NotNullPara;
import io.jboot.admin.base.rest.datatable.DataTable;
import io.jboot.admin.base.web.base.BaseController;
import io.jboot.admin.service.api.*;
import io.jboot.admin.service.entity.model.*;
import io.jboot.admin.service.entity.status.system.ProjectUndertakeStatus;
import io.jboot.admin.support.auth.AuthUtils;
import io.jboot.core.rpc.annotation.JbootrpcService;
import io.jboot.web.controller.annotation.RequestMapping;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
/**
* -----------------------------
*
* @author EchoLZY
* @version 2.0
* -----------------------------
* @date 16:35 2018/7/25
*/
@RequestMapping("/app/information")
public class InformationController extends BaseController {
@JbootrpcService
private UserService userService;
@JbootrpcService
private PersonService personService;
@JbootrpcService
private ExpertGroupService expertGroupService;
@JbootrpcService
private ImpTeamService impTeamService;
@JbootrpcService
private ProjectService projectService;
@JbootrpcService
private ProjectFileTypeService projectFileTypeService;
@JbootrpcService
private RoleService roleService;
@JbootrpcService
private OrganizationService organizationService;
@JbootrpcService
private FacAgencyService facAgencyService;
@JbootrpcService
private ProjectUndertakeService projectUndertakeService;
@JbootrpcService
private AffectedGroupService affectedGroupService;
@JbootrpcService
private OccupationService occupationService;
@JbootrpcService
private PostService postService;
@JbootrpcService
private SiteSurveyExpertAdviceService siteSurveyExpertAdviceService;
@JbootrpcService
private UserRoleService userRoleService;
@JbootrpcService
private FileProjectService fileProjectService;
@JbootrpcService
private FilesService filesService;
@JbootrpcService
private DiagnosesService diagnosesService;
@JbootrpcService
private NationService nationService;
@JbootrpcService
private EducationalService educationalService;
@JbootrpcService
private QuestionnaireService questionnaireService;
@JbootrpcService
private QuestionnaireContentService questionnaireContentService;
@JbootrpcService
private QuestionnaireContentLinkService questionnaireContentLinkService;
@JbootrpcService
private InitialRiskExpertiseService initialRiskExpertiseService;
@JbootrpcService
private ManagementService managementService;
/**
* 文件上传页面
*/
@NotNullPara({"id", "projectId", "questionnaireId"})
public void fileUploading() {
Long id = getParaToLong("id");
String questionnaireId = getPara("questionnaireId");
ProjectFileType model = projectFileTypeService.findById(id);
setAttr("projectId", getParaToLong("projectId"))
.setAttr("model", model)
.setAttr("questionnaireId", questionnaireId)
.render("fileUploading.html");
}
/**
* 资料编辑页面
*/
@NotNullPara("id")
public void edit() {
setAttr("projectId", getParaToLong("id"))
.setAttr("percent", getParaToLong("percent"))
.setAttr("flag", getPara("flag", "false"))
.render("edit.html");
}
/**
* edit 下的欢迎页面
*/
public void welcome() {
List<ProjectFileType> list = projectFileTypeService.findListByParentId(projectFileTypeService.findByName("评估").getId());
ProjectFileType projectFileType = new ProjectFileType();
projectFileType.setName("稳评方案");
list.add(0, projectFileType);
setAttr("projectId", getParaToLong("id"))
.setAttr("list", list)
.setAttr("flag", getPara("flag", "false"))
.render("welcome.html");
}
/**
* 个人资料填写,加载当前可以填写的项目
*/
@NotNullPara("id")
public void editData() {
Long id = getParaToLong("id");
Project project = projectService.findById(id);
if (project == null) {
renderJson(RestResult.buildError("项目不存在"));
throw new BusinessException("项目不存在");
}
// User user = AuthUtils.getLoginUser();
// Person person = personService.findByUser(user);
// ExpertGroup expertGroup = expertGroupService.findByPersonId(person.getId());
// ImpTeam impTeam = impTeamService.findByProjectId(project.getId());
// if (!impTeam.getExpertGroupIDs().contains(String.valueOf(expertGroup.getId()))){
// renderJson(RestResult.buildError("关系不对应"));
// throw new BusinessException("关系不对应");
// }
// List<InformationFill> informationFills = informationFillService.findByRoleId(roleService.findByName("专家团体").getId());
Long parentId = projectFileTypeService.findByName("评估").getId();
List<ProjectFileType> projectFileTypeList = projectFileTypeService.findListByParentId(parentId);
Map<String, Object> res = new ConcurrentHashMap<>();
res.put("list", projectFileTypeList);
res.put("code", ResultCode.SUCCESS);
res.put("projectId", project.getId());
renderJson(res);
}
/**
* 通用表格页面渲染
*/
public void list() {
String url = getPara("url");
Long projectId = getParaToLong("id");
String flag = getPara("flag");
setAttr("url", url)
.setAttr("projectId", projectId)
.setAttr("flag", flag)
.render("tableView.html");
}
/**
* 调查问卷
*/
@NotNullPara("projectID")
public void questionnaireList() {
String url = getPara("url");
Long projectID = getParaToLong("projectID");
setAttr("url", url)
.setAttr("flag", getPara("flag", "false"))
.setAttr("projectID", projectID)
.render("questionnaireList.html");
}
/**
* 5. 初始风险因素及其风险程度
*/
@NotNullPara("projectID")
public void riskDegreeList() {
String url = getPara("url");
Long projectID = getParaToLong("projectID");
setAttr("url", url)
.setAttr("flag", getPara("flag", "false"))
.setAttr("projectID", projectID)
.render("riskDegreeList.html");
}
/**
* 调查问卷
*/
@NotNullPara("projectID")
public void expertAdviceList() {
String url = getPara("url");
Long projectID = getParaToLong("projectID");
setAttr("url", url)
.setAttr("flag", getPara("flag", "false"))
.setAttr("projectID", projectID)
.render("expertAdviceList.html");
}
/**
* 调查问卷
*/
@NotNullPara("projectID")
public void diagnosesList() {
String url = getPara("url");
Long projectID = getParaToLong("projectID");
setAttr("url", url)
.setAttr("flag", getPara("flag", "false"))
.setAttr("projectID", projectID)
.render("diagnosesList.html");
}
/**
* 专家数据
*/
public void expertAdviceDataTable() {
int pageNumber = getParaToInt("pageNumber", 1);
int pageSize = getParaToInt("pageSize", 30);
Long projectId = getParaToLong("projectID");
SiteSurveyExpertAdvice model = new SiteSurveyExpertAdvice();
model.setProjectID(projectId);
Page<SiteSurveyExpertAdvice> page = siteSurveyExpertAdviceService.findPage(model, pageNumber, pageSize);
renderJson(new DataTable<SiteSurveyExpertAdvice>(page));
}
/**
* 现场踏勘专家意见
*/
@NotNullPara("projectID")
public void expertAdvice() {
Long projectID = getParaToLong("projectID");
Long id = getParaToLong("id");
Project project = projectService.findById(projectID);
User user = AuthUtils.getLoginUser();
List<ExpertGroup> expertGroups = expertGroupService.findAll();
String assessmentMode = project.getAssessmentMode();
String name = null;
if ("自评".equals(assessmentMode)) {
Organization organization = organizationService.findById(userService.findById(project.getUserId()).getUserID());
name = organization.getName();
} else {
ProjectUndertake projectUndertake = projectUndertakeService.findListByProjectAndStatus(projectID, ProjectUndertakeStatus.ACCEPT).get(0);
if (projectUndertake == null) {
renderJson(RestResult.buildError("項目还不能填写资料"));
throw new BusinessException("項目还不能填写资料");
}
Organization organization = organizationService.findById(user.getUserID());
FacAgency facAgency = facAgencyService.findByOrgId(organization.getId());
if (facAgency == null) {
facAgency = projectUndertake.getFacAgency();
}
name = facAgency.getName();
}
SiteSurveyExpertAdvice model = new SiteSurveyExpertAdvice();
ExpertGroup expertGroup = null;
if (id != null) {
model = siteSurveyExpertAdviceService.findById(id);
expertGroup = expertGroupService.findById(model.getExpertID());
}
String date = new SimpleDateFormat("YYYY-MM-dd").format(new Date());
String para = getPara("flag", "false");
setAttr("expertGroups", expertGroups)
.setAttr("flag", para)
.setAttr("thisId", id)
.setAttr("expertGroup", expertGroup)
.setAttr("phone", user.getPhone())
.setAttr("projectID", project.getId())
.setAttr("name", name)
.setAttr("date", date)
.setAttr("model", model)
.setAttr("otherComments", model.getOtherComments())
.setAttr("resolving", model.getResolving())
.setAttr("riskFactor", model.getRiskFactor())
.render("expertAdvice.html");
}
/**
* 现场踏勘专家意见提交
*/
@Before(POST.class)
@NotNullPara("projectID")
public void expertAdvicePost() {
Long projectID = getParaToLong("projectID");
Long expertGroupId = getParaToLong("expertGroupId");
String riskFactor = getPara("riskFactor");
String resolving = getPara("resolving");
String content = getPara("content");
Long id = getParaToLong("id");
User user = AuthUtils.getLoginUser();
SiteSurveyExpertAdvice model = new SiteSurveyExpertAdvice();
model.setName("现场踏勘专家意见");
model.setProjectID(projectID);
model.setExpertID(expertGroupId);
model.setCreateTime(new Date());
model.setIsEnable(true);
model.setLastAccessTime(new Date());
model.setLastUpdateUserID(user.getId());
model.setCreateUserID(user.getId());
model.setRiskFactor(riskFactor);
model.setResolving(resolving);
model.setOtherComments(content);
model.setSort(1);
if (id != null) {
model.setId(id);
}
if (!siteSurveyExpertAdviceService.saveOrUpdate(model)) {
renderJson(RestResult.buildError("啊哦,保存失败,请重新尝试!"));
throw new BusinessException("啊哦,保存失败,请重新尝试!");
}
renderJson(RestResult.buildSuccess());
}
/**
* 删除
*/
@Before(POST.class)
@NotNullPara("id")
public void expertAdviceDelete() {
Long id = getParaToLong("id");
SiteSurveyExpertAdvice model = siteSurveyExpertAdviceService.findById(id);
if (model == null) {
throw new BusinessException("删除失败!");
}
if (!siteSurveyExpertAdviceService.delete(model)) {
throw new BusinessException("删除失败!");
}
renderJson(RestResult.buildSuccess());
}
/**
* 调查分析
*/
@Before(GET.class)
@NotNullPara("projectID")
public void diagnoses() {
Long diagnosesID = getParaToLong("id");
Diagnoses diagnoses;
if (diagnosesID == null) {
diagnoses = new Diagnoses();
} else {
diagnoses = diagnosesService.findById(diagnosesID);
}
setAttr("diagnoses", diagnoses);
Project project = projectService.findById(getParaToLong("projectID"));
if (project == null) {
throw new BusinessException("没有此项目");
}
setAttr("project", project);
FileProject fileProject = fileProjectService.findByProjectID(project.getId());
Files files = null;
if(null != fileProject)
files = filesService.findById(fileProject.getFileID());
if(null == files)
files = new Files();
setAttr("files", files);
ProjectUndertake projectUndertake = projectUndertakeService.findByProjectIdAndStatus(project.getId(), ProjectUndertakeStatus.ACCEPT);
User user = AuthUtils.getLoginUser();
Organization organization;
/**
* 自评的时候
* projectUndertake的facAgencyID是
*/
if ("自评".equals(project.getAssessmentMode())) {
user = userService.findById(projectUndertake.getFacAgencyID());
organization = organizationService.findById(user.getUserID());
} else if ("委评".equals(project.getAssessmentMode())) {
if (projectUndertake.getApplyOrInvite()) {
FacAgency facAgency = facAgencyService.findById(projectUndertake.getFacAgencyID());
organization = organizationService.findById(facAgency.getOrgID());
user = userService.findByUserIdAndUserSource(organization.getId(), 1);
} else {
user = userService.findById(projectUndertake.getCreateUserID());
organization = organizationService.findById(user.getUserID());
}
} else {
throw new BusinessException("请求错误");
}
ImpTeam impTeam = impTeamService.findByUserIDAndProjectID(user.getId(), project.getId());
String invTeamIDs = impTeam.getInvTeamIDs();
String[] invTeamIDList = invTeamIDs.split(",");
Map<String, String> invTeamMap = new ConcurrentHashMap<String, String>();
for (String invTeamID : invTeamIDList) {
Person person = personService.findById(invTeamID);
if (person != null){
invTeamMap.put(invTeamID, person.getName());
}
}
setAttr("invTeamMap", invTeamMap);
setAttr("organization", organization)
.setAttr("flag", getPara("flag", "false"));
render("diagnose.html");
}
/**
* 调查分析数据表格
*/
public void diagnosesDataTable() {
int pageNumber = getParaToInt("pageNumber", 1);
int pageSize = getParaToInt("pageSize", 30);
Long projectId = getParaToLong("projectID");
Diagnoses diagnoses = new Diagnoses();
diagnoses.setProject(projectId);
Page<Diagnoses> page = diagnosesService.findPage(diagnoses, pageNumber, pageSize);
page.getList().forEach(p -> p.setRemark("调查群体:" + p.getSurveyGroup()));
renderJson(new DataTable<Diagnoses>(page));
}
/**
* 调查分析保存
*/
@Before(POST.class)
@NotNullPara({"staffArrangements", "surveyWays"})
public void diagnosesSave() {
Diagnoses diagnoses = getBean(Diagnoses.class, "diagnoses");
String[] idList = getParaValues("staffArrangements");
String file = getPara("file");
if (StringUtils.isNotEmpty(file)) {
Files files = filesService.findById(file);
files.setIsEnable(true);
if (!filesService.update(files)) {
throw new BusinessException("保存失败");
}
diagnoses.setRemark(file);
}
diagnoses.setStaffArrangements(StringUtils.join(idList, ","));
String[] surveyWayList = getParaValues("surveyWays");
diagnoses.setSurveyWay(StringUtils.join(surveyWayList, ","));
diagnoses.setCreateUserID(AuthUtils.getLoginUser().getId());
diagnoses.setLastUpdateUserID(AuthUtils.getLoginUser().getId());
// 没有字段存放“社会稳定风险评估调查分析表”,使用reamrk字段
if (!diagnosesService.saveOrUpdate(diagnoses)) {
throw new BusinessException("保存失败");
}
renderJson(RestResult.buildSuccess());
}
@NotNullPara("id")
public void diagnosesDelete() {
Long id = getParaToLong("id");
Diagnoses diagnoses = diagnosesService.findById(id);
if (diagnoses == null) {
throw new BusinessException("删除失败");
}
if (!diagnosesService.delete(diagnoses)) {
throw new BusinessException("删除失败");
}
renderJson(RestResult.buildSuccess());
}
/**
* 调查问卷数据表格
*/
public void questionnaireDataTable() {
int pageNumber = getParaToInt("pageNumber", 1);
int pageSize = getParaToInt("pageSize", 30);
Long projectId = getParaToLong("projectID");
Questionnaire questionnaire = new Questionnaire();
questionnaire.setProjectID(projectId);
questionnaire.setIsEnable(true);
Page<Questionnaire> page = questionnaireService.findPage(questionnaire, pageNumber, pageSize);
page.getList().forEach(p -> {
StringBuilder sb = new StringBuilder();
if (p.getType() == 1) {
sb.append("调查对象:单位");
} else {
sb.append("调查对象:个人");
}
p.setRemark(sb.toString());
p.setName("调查问卷");
});
renderJson(new DataTable<Questionnaire>(page));
}
/**
* personOrOrganization
*/
@NotNullPara("projectID")
public void personOrOrganization() {
Project project = projectService.findById(getPara("projectID"));
Questionnaire questionnaire = new Questionnaire();
questionnaire.setType(getParaToInt("type"));
setAttr("flag", getPara("flag", "false"));
setAttr("questionnaire", questionnaire).
setAttr("project", project).
setAttr("projectID", project.getId());
//判断跳转的页面是哪一个
if (questionnaire.getType() == 0) {
render("personMain.html");
} else {
render("organizationMain.html");
}
}
/**
* questionnaire (有内容则修改 无内容则创建)
*/
@NotNullPara("projectID")
public void questionnaire() {
User loginUser = AuthUtils.getLoginUser();
Project project = projectService.findById(getParaToLong("projectID"));
Questionnaire questionnaire = questionnaireService.findById(getParaToLong("id"));
setAttr("flag", getPara("flag", "false"));
//选择问卷为空则是创建
setAttr("projectID", project.getId())
.setAttr("project", project);
if (questionnaire == null) {
render("personOrOrganization.html");
} else {
setAttr("questionnaire", questionnaire);
if (questionnaire.getType() == 0) {
render("personMain.html");
} else {
render("organizationMain.html");
}
}
}
/**
* 修改或者保存调查问卷
*/
public void questionnaireAdd() {
User loginUser = AuthUtils.getLoginUser();
//项目资料
Project project = getBean(Project.class, "project");
String questionnaireId= getPara("questionnaireId");
//project.setLastUpdateUserID(loginUser.getId());
//调查问卷
Questionnaire questionnaire = getBean(Questionnaire.class, "questionnaire");
//修改则有问卷id 创建则没有
if (questionnaire.getProjectID() == null) {
questionnaire.setProjectID(project.getId());
}
if (questionnaire.getCreateUserID() == null) {
questionnaire.setCreateUserID(loginUser.getId());
}
questionnaire.setLastUpdateUserID(loginUser.getId());
if (!questionnaireService.saveQuestionnaire(questionnaire, questionnaireId)) {
throw new BusinessException("保存失败!");
}
renderJson(RestResult.buildSuccess());
}
/**
* 删除调查问卷以及内容
*/
@NotNullPara("id")
public void questionnaireDelete() {
Questionnaire questionnaire = questionnaireService.findById(getParaToLong("id"));
if (questionnaire != null) {
if (!questionnaireService.deleteQuestionnaire(questionnaire)) {
throw new BusinessException("删除失败!");
}
} else {
throw new BusinessException("删除的数据不存在!");
}
renderJson(RestResult.buildSuccess());
}
/**
* 选择添加的风险因素界面
*/
@NotNullPara("projectID")
public void chooseRiskExpertise() {
setAttr("projectId", getPara("projectID")).render("chooseRiskExpertise.html");
}
/**
* 查看风险因素及影响概率
*/
@NotNullPara({"projectID", "id"})
public void riskExpertise() {
String managementName = null;
String riskExpertise = null;
String riskProbability = "0%";
String incidenceExpertise = null;
String incidenceProbability = "0%";
ExpertGroup expertGroup = new ExpertGroup();
InitialRiskExpertise initialRiskExpertise = initialRiskExpertiseService.findById(getParaToLong("id"));
Project project = projectService.findById(getParaToLong("projectID"));
if (project != null) {
Management management = managementService.findById(project.getManagementID());
if (management != null) {
managementName = management.getName();
}
}
if (initialRiskExpertise != null) {
ExpertGroup tmp = expertGroupService.findById(initialRiskExpertise.getExpertID());
if (tmp != null) {
expertGroup = tmp;
}
int n = initialRiskExpertise.getRiskExpertise();
switch (n) {
case 1:
riskExpertise = "很低";
case 2:
riskExpertise = "较低";
case 3:
riskExpertise = "中等";
case 4:
riskExpertise = "较高";
case 5:
riskExpertise = "很高";
}
n = initialRiskExpertise.getIncidenceExpertise();
switch (n) {
case 1:
incidenceExpertise = "可忽略";
case 2:
incidenceExpertise = "较小";
case 3:
incidenceExpertise = "中等";
case 4:
incidenceExpertise = "较大";
case 5:
incidenceExpertise = "严重";
}
riskProbability = initialRiskExpertise.getRiskProbability() + "%";
incidenceProbability = initialRiskExpertise.getIncidenceProbability() + "%";
}
setAttr("project", project)
.setAttr("managementName", managementName)
.setAttr("expertGroup", expertGroup)
.setAttr("initialRiskExpertise", initialRiskExpertise)
.setAttr("riskProbability", riskProbability)
.setAttr("riskExpertise", riskExpertise)
.setAttr("incidenceProbability", incidenceProbability)
.setAttr("incidenceExpertise", incidenceExpertise)
.render("riskExpertise.html");
}
/**
* 项目风险因素影响程度及概率
* type
* 0: 初始风险
* 1: 採取措施后的风险
*/
@NotNullPara({"projectID", "type"})
public void toRiskExpertise() {
Long projectId = getParaToLong("projectID");
String type = getPara("type", "initial");
// 获取到当前行的id
Long id = getParaToLong("id");
// 设置必要的标识
setAttr("flag", getPara("flag", "false"))
.setAttr("project", projectService.findById(projectId))
.setAttr("projectId", projectId);
// 如果为空,就是添加,否则为查看
if (id == null) {//根据当前登录用户所属组织查询所有专家
//setAttr("expertGroups", expertGroupService.findAll());
setAttr("expertGroups", expertGroupService.findAllByOrgId(AuthUtils.getLoginUser().getUserID()));
if(type.equals("initial")){
render("initialRiskExpertise.html");
}else if(type.equals("result")){
render("resultRiskExpertise.html");
}
} else {
InitialRiskExpertise initialRiskExpertise = initialRiskExpertiseService.findById(id);
ExpertGroup expertGroup = expertGroupService.findById(initialRiskExpertise.getExpertID());
setAttr("initialRiskExpertise", initialRiskExpertise).setAttr("expertGroup", expertGroup);
if(type.equals("initial")){
render("initialRiskExpertise.html");
}else if(type.equals("result")){
render("resultRiskExpertise.html");
}
}
}
/**
* 表格数据
*/
public void toInitialRiskExpertiseDataTable() {
int pageNumber = getParaToInt("pageNumber", 1);
int pageSize = getParaToInt("pageSize", 30);
Long projectId = getParaToLong("projectID");
InitialRiskExpertise initialRiskExpertise = new InitialRiskExpertise();
initialRiskExpertise.setProjectID(projectId);
Page<InitialRiskExpertise> pages = initialRiskExpertiseService.findPage(initialRiskExpertise, pageNumber, pageSize);
pages.getList().forEach(model -> {
if (model.getRemark().equals("initial")) {
model.setRemark("初始");
} else if (model.getRemark().equals("result")) {
model.setRemark("采取措施后");
}
ExpertGroup expertGroup = expertGroupService.findById(model.getExpertID());
if (expertGroup != null) {
//model.setRemark("专家名称:" + expertGroup.getName());
model.setExpertName(expertGroup.getName());
}
});
renderJson(new DataTable<InitialRiskExpertise>(pages));
}
/**
* 风险因素影响程度数据表格
*/
public void chooseRiskExpertiseDataTable() {
int pageNumber = getParaToInt("pageNumber", 1);
int pageSize = getParaToInt("pageSize", 30);
Long projectId = getParaToLong("id");
InitialRiskExpertise initialRiskExpertise = new InitialRiskExpertise();
initialRiskExpertise.setProjectID(projectId);
initialRiskExpertise.setIsEnable(true);
Page<InitialRiskExpertise> page = initialRiskExpertiseService.findPage(initialRiskExpertise, pageNumber, pageSize);
page.getList().forEach(p -> {
StringBuilder sb = new StringBuilder();
if (p.getRemark().equals("initial")) {
sb.append("初始风险程度");
p.setRemark("初始风险程度");
} else if (p.getRemark().equals("result")) {
sb.append("采取措施后的风险程度");
p.setRemark("采取措施后的风险程度");
}
p.setName("风险因素及风险程度");
});
renderJson(new DataTable<InitialRiskExpertise>(page));
}
/**
* 项目风险因素影响程度及概率数据提交
* type
* 0: 初始风险
* 1: 採取措施后的风险
*/
@Before(POST.class)
@NotNullPara({"projectId", "expertId", "type"})
public void initialRiskExpertise() {
User user = AuthUtils.getLoginUser();
int type = getParaToInt("type");
InitialRiskExpertise model = new InitialRiskExpertise();
ExpertGroup expertGroup = expertGroupService.findById(getParaToLong("expertId"));
if (expertGroup == null) {
throw new BusinessException("专家团体不存在!");
}
model.setProjectID(getParaToLong("projectId"));
model.setExpertID(expertGroup.getId());
model.setIncidenceExpertise(getParaToInt("incidenceExpertise"));
model.setRiskExpertise(getParaToInt("riskExpertise"));
if (getPara("riskProbability") != null && getPara("incidenceProbability") != null) {
model.setIncidenceProbability(Float.parseFloat(getPara("incidenceProbability")));
model.setRiskProbability(Float.parseFloat(getPara("riskProbability")));
model.setRiskLevel(Float.parseFloat(getPara("incidenceProbability")) * Float.parseFloat(getPara("riskProbability")));
}
model.setRiskFactor(getPara("riskFactor"));
model.setCreateUserID(user.getId());
model.setCreateTime(new Date());
model.setLastAccessTime(new Date());
model.setLastUpdateUserID(user.getId());
model.setStatus(3);
if (type == 0) {
model.setRemark("initial");
} else {
model.setRemark("result");
}
model.setIsEnable(true);
if (!initialRiskExpertiseService.save(model)) {
renderJson(RestResult.buildError("保存失败"));
throw new BusinessException("保存失败");
}
renderJson(RestResult.buildSuccess());
}
/**
* 项目风险因素影响程度及概率数据删除
*/
@NotNullPara("id")
public void chooseRiskExpertiseDelete() {
Long id = getParaToLong("id");
InitialRiskExpertise model = initialRiskExpertiseService.findById(id);
if (model == null || !initialRiskExpertiseService.delete(model)) {
throw new BusinessException("删除失败");
}
renderJson(RestResult.buildSuccess());
}
/**
* 6. 风险等级综合评估
*/
public void toRiskLevel() {
String riskLevels = projectService.findById(getParaToLong("id")).getRiskLevels();
if (StringUtils.isEmpty(riskLevels)) {
riskLevels = "";
}
setAttr("projectID", getParaToLong("id"))
.setAttr("percent", getParaToLong("percent"))
.setAttr("flag", getPara("flag", "false"))
.setAttr("riskLevels", riskLevels)
.render("riskLevel.html");
}
@NotNullPara({"projectId","riskLevels"})
public void updateRiskLevels(){
Integer projectId = getParaToInt("projectId");
Project project = projectService.findById(projectId);
project.setRiskLevels(getPara("riskLevels",project.getRiskLevels()));
if (!projectService.update(project)){
throw new BusinessException("更新失败");
}
renderJson(RestResult.buildSuccess());
}
}
|
package hudson.plugins.claim;
import groovy.lang.Binding;
import hudson.model.BuildBadgeAction;
import hudson.model.ProminentProjectAction;
import hudson.model.Run;
import hudson.model.Saveable;
import hudson.model.Hudson;
import hudson.model.User;
import java.io.IOException;
import java.util.Collections;
import java.util.Date;
import java.util.Optional;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.mail.MessagingException;
import javax.servlet.ServletException;
import hudson.plugins.claim.http.PreventRefreshFilter;
import jenkins.model.Jenkins;
import org.acegisecurity.Authentication;
import org.apache.commons.lang.StringUtils;
import org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SecureGroovyScript;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.DoNotUse;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import org.kohsuke.stapler.bind.JavaScriptMethod;
import org.kohsuke.stapler.export.Exported;
import org.kohsuke.stapler.export.ExportedBean;
@ExportedBean(defaultVisibility = 2)
public abstract class AbstractClaimBuildAction<T extends Saveable>
extends DescribableTestAction
implements BuildBadgeAction, ProminentProjectAction {
private static final long serialVersionUID = 1L;
private static final Logger LOGGER = Logger.getLogger("claim-plugin");
private boolean claimed;
private String claimedBy;
private String assignedBy;
private Date claimDate;
private boolean transientClaim = !ClaimConfig.get().isStickyByDefault();
@Deprecated
private transient boolean reclaim;
private ClaimBuildFailureAnalyzer bfaClaimer = null;
private String reason;
protected abstract T getOwner();
AbstractClaimBuildAction() {
}
// jelly
public final CommonMessagesProvider getMessageProvider() {
return CommonMessagesProvider.build(this);
}
/**
* Indicates if the {@link Saveable} is claimed.
*
* @deprecated use {@link #isClaimed()} instead
* @return true if the {@link Saveable} is claimed, else false
*/
@Deprecated
public final boolean isReclaim() {
return isClaimed();
}
public final ClaimBuildFailureAnalyzer getBfaClaimer() {
return bfaClaimer;
}
public final String getIconFileName() {
return null;
}
public final String getUrlName() {
return "claim";
}
abstract String getUrl();
public final void doClaim(StaplerRequest req, StaplerResponse resp)
throws Exception {
Authentication authentication = Hudson.getAuthentication();
String currentUser = authentication.getName();
String claimedUser = currentUser; // Default to self-assignment
String assignee = req.getSubmittedForm().getString("assignee");
if (!StringUtils.isEmpty(assignee) && !claimedUser.equals(assignee)) {
// Validate the specified assignee.
User resolvedAssignee = User.get(assignee, false, Collections.EMPTY_MAP);
if (resolvedAssignee == null) {
LOGGER.log(Level.WARNING, "Invalid username specified for assignment: {0}", assignee);
resp.forwardToPreviousPage(req);
return;
}
claimedUser = assignee;
}
String reasonProvided = req.getSubmittedForm().getString("reason");
if (ClaimBuildFailureAnalyzer.isBFAEnabled()) {
String error = req.getSubmittedForm().getString("errors");
bfaClaimer = new ClaimBuildFailureAnalyzer(error);
if (getOwner() instanceof Run) {
Run run = (Run) getOwner();
if (!bfaClaimer.isDefaultError()) {
try {
bfaClaimer.createFailAction(run);
} catch (IndexOutOfBoundsException e) {
LOGGER.log(Level.WARNING, "No FailureCauseBuildAction detected for this build");
resp.forwardToPreviousPage(req);
return;
}
} else {
bfaClaimer.removeFailAction(run);
}
}
}
boolean sticky = req.getSubmittedForm().getBoolean("sticky");
boolean propagated = req.getSubmittedForm().getBoolean("propagateToFollowingBuilds");
if (StringUtils.isEmpty(reasonProvided)) {
reasonProvided = null;
}
claim(claimedUser, reasonProvided, currentUser, new Date(), sticky, propagated, true);
this.getOwner().save();
evalGroovyScript();
resp.forwardToPreviousPage(req);
}
/**
* Claims a {@link Saveable}.
* @param claimedByUser name of the claiming user
* @param providedReason reason for the claim
* @param assignedByUser name of the assigned user
* @param isSticky true if the claim has to be kept until resolution
* @deprecated use {@link #claim(String, String, String, Date, boolean, boolean, boolean)}
*/
@Deprecated
public final void claim(String claimedByUser, String providedReason, String assignedByUser, boolean isSticky) {
claim(claimedByUser, providedReason, assignedByUser, new Date(), isSticky,
ClaimConfig.get().isPropagateToFollowingBuildsByDefault(), false);
}
/**
* Claims a {@link Saveable}, and optionally notifies of the claim.
* @param claimedByUser name of the claiming user
* @param providedReason reason for the claim
* @param assignedByUser name of the assigner user
* @param date date of the claim
* @param isSticky true if the claim has to be kept until resolution
* @param isPropagated true if the claim has to be propagated to following builds
* @param notify true if notifications have to be sent
*/
public final void claim(String claimedByUser, String providedReason, String assignedByUser, Date date,
boolean isSticky, boolean isPropagated, boolean notify) {
applyClaim(claimedByUser, providedReason, assignedByUser, date, isSticky, isPropagated);
if (notify) {
try {
ClaimEmailer.sendEmailIfConfigured(
claimedByUser,
assignedByUser,
getOwner().toString(),
providedReason,
getUrl());
} catch (IOException | MessagingException e) {
LOGGER.log(Level.WARNING, "Exception encountered sending assignment email: " + e.getMessage());
} catch (InterruptedException e) {
LOGGER.log(Level.WARNING, "Interrupted when sending assignment email", e);
}
}
}
/**
* Applies the claim data to the {@link AbstractClaimBuildAction}.
* @param claimedByUser name of the claiming user
* @param providedReason reason for the claim
* @param assignedByUser name of the assigner user
* @param date date of the claim
* @param isSticky true if the claim has to be kept until resolution
* @param isPropagated true if the claim has to be propagated to following builds
*/
protected void applyClaim(String claimedByUser, String providedReason, String assignedByUser, Date date,
boolean isSticky, boolean isPropagated) {
this.claimed = true;
this.claimedBy = claimedByUser;
this.reason = providedReason;
this.transientClaim = !isSticky;
this.claimDate = date;
this.assignedBy = assignedByUser;
if (isPropagated) {
getNextAction().ifPresent(action -> {
if (!action.isClaimed()) {
action.applyClaim(claimedByUser, providedReason, assignedByUser, date, isSticky, true);
try {
action.getOwner().save();
} catch (IOException e) {
// ignore
}
}
});
}
}
protected abstract Optional<AbstractClaimBuildAction> getNextAction();
// jelly
public final void doUnclaim(StaplerRequest req, StaplerResponse resp)
throws ServletException, IOException {
unclaim();
if (ClaimBuildFailureAnalyzer.isBFAEnabled() && bfaClaimer != null) {
bfaClaimer.removeFailAction((Run) getOwner());
}
getOwner().save();
evalGroovyScript();
resp.forwardToPreviousPage(req);
}
/**
* Unclaims a {@link Saveable}.
* @deprecated use {@link #unclaim(boolean)}
*/
@Deprecated
public final void unclaim() {
unclaim(false);
}
/**
* Unclaims a {@link Saveable}, and optionally notifies of the unclaim.
* @param notify true if notifications have to be sent
* @deprecated use {@link #unclaim(boolean)}
*/
public final void unclaim(boolean notify) {
//TODO actually notify
applyUnclaim();
}
/**
* Removes the claim data to the {@link AbstractClaimBuildAction}.
*/
protected void applyUnclaim() {
this.claimed = false;
this.claimedBy = null;
this.transientClaim = false;
this.claimDate = null;
this.assignedBy = null;
// we remember the reason to show it if someone reclaims this build.
}
@Exported
public final String getClaimedBy() {
return claimedBy;
}
@Exported
public final String getAssignedBy() {
return assignedBy;
}
// used by groovy scripts ?
public final String getClaimedByName() {
User user = User.get(claimedBy, false, Collections.EMPTY_MAP);
if (user != null) {
return user.getDisplayName();
} else {
return claimedBy;
}
}
// used by groovy scripts ?
public final String getAssignedByName() {
User user = User.get(assignedBy, false, Collections.EMPTY_MAP);
if (user != null) {
return user.getDisplayName();
} else {
return assignedBy;
}
}
// used by groovy scripts ?
public final void setClaimedBy(String claimedBy) {
this.claimedBy = claimedBy;
}
// used by groovy scripts ?
public final void setAssignedBy(String assignedBy) {
this.assignedBy = assignedBy;
}
@Exported
public final boolean isClaimed() {
return claimed;
}
/**
* Claim a new {@link Saveable} with the same settings as this one.
* @param other the source data
*/
protected void copyTo(AbstractClaimBuildAction<T> other) {
other.applyClaim(getClaimedBy(), getReason(), getAssignedBy(), getClaimDate(), isSticky(), false);
}
public final boolean isClaimedByMe() {
return !isUserAnonymous()
&& Hudson.getAuthentication().getName().equals(claimedBy);
}
// jelly
public final boolean canReassign() {
return !isUserAnonymous() && isClaimed();
}
// jelly
public final boolean canClaim() {
return !isUserAnonymous() && !isClaimedByMe();
}
// jelly
public final boolean canRelease() {
return !isUserAnonymous() && isClaimedByMe();
}
public final boolean isUserAnonymous() {
return Hudson.getAuthentication().getName().equals("anonymous");
}
@Exported
public final String getReason() {
return reason;
}
@JavaScriptMethod
public final String getReason(String error) throws Exception {
final String defaultValue = "";
if (!ClaimBuildFailureAnalyzer.isBFAEnabled()) {
return defaultValue;
}
if (error == null || ClaimBuildFailureAnalyzer.DEFAULT_ERROR.equals(error)) {
return defaultValue;
}
return ClaimBuildFailureAnalyzer.getFillReasonMap().getOrDefault(error, defaultValue);
}
@Restricted(DoNotUse.class) // jelly
@SuppressWarnings("unused")
public final void preventRefresh(StaplerResponse response) {
PreventRefreshFilter.preventRefresh(response);
}
// used by groovy scripts ?
public final void setReason(String reason) {
this.reason = reason;
}
// jelly
public final boolean hasReason() {
return !StringUtils.isEmpty(reason);
}
// used by groovy scripts ?
public final boolean isTransientClaim() {
return transientClaim;
}
// used by groovy scripts ?
public final void setTransientClaim(boolean transientClaim) {
this.transientClaim = transientClaim;
}
// used by groovy scripts ?
public final boolean isSticky() {
return !transientClaim;
}
// used by groovy scripts ?
public final void setSticky(boolean sticky) {
this.transientClaim = !sticky;
}
@Restricted(DoNotUse.class)
@SuppressWarnings("unused")
// groovy
public final boolean isPropagateToFollowingBuildsByDefault() {
return ClaimConfig.get().isPropagateToFollowingBuildsByDefault();
}
// used by groovy scripts ?
public final String getError() {
if (bfaClaimer == null) {
return null;
}
return bfaClaimer.getError();
}
// used by groovy scripts ?
public final boolean isBFAEnabled() {
return ClaimBuildFailureAnalyzer.isBFAEnabled();
}
@Exported
public final Date getClaimDate() {
if (this.claimDate == null) {
return null;
}
return (Date) this.claimDate.clone();
}
// used by groovy scripts ?
public final boolean hasClaimDate() {
return this.claimDate != null;
}
/**
* Was the action claimed by someone to themselves?
* @return true if the item was claimed by the user to themselves, false otherwise
*/
// used by groovy scripts ?
public boolean isSelfAssigned() {
boolean ret = true;
if (!isClaimed()) {
ret = false;
} else if (getClaimedBy() == null) {
ret = false;
} else if (!getClaimedBy().equals(getAssignedBy())) {
ret = false;
}
return ret;
}
// jelly
public abstract String getNoun();
protected final void evalGroovyScript() {
ClaimConfig config = ClaimConfig.get();
if (config.hasGroovyTrigger()) {
SecureGroovyScript groovyScript = config.getGroovyTrigger();
Binding binding = new Binding();
binding.setVariable("action", this);
try {
groovyScript.evaluate(Jenkins.getInstance().getPluginManager().uberClassLoader, binding);
} catch (Exception e) {
LOGGER.log(Level.WARNING, "Error evaluating Groovy script", e);
}
}
}
}
|
/*
* Copyright (c) 2020 Karl Oczadly (karl@oczadly.uk)
* Licensed under the MIT License
*/
package uk.oczadly.karl.jnano.internal.gsonadapters;
import com.google.gson.*;
import java.lang.reflect.Type;
/**
* @author Karl Oczadly
*/
public class UnsignedLongAdapter implements JsonSerializer<Long>, JsonDeserializer<Long> {
@Override
public Long deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
try {
return Long.parseUnsignedLong(json.getAsString());
} catch (NumberFormatException e) {
throw new JsonSyntaxException(e);
}
}
@Override
public JsonElement serialize(Long src, Type typeOfSrc, JsonSerializationContext context) {
return new JsonPrimitive(Long.toUnsignedString(src));
}
}
|
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.fr.swift.jdbc.druid.sql.ast;
import com.fr.swift.jdbc.druid.sql.visitor.SQLASTVisitor;
import java.util.List;
import java.util.Map;
public interface SQLObject {
void accept(SQLASTVisitor visitor);
SQLObject clone();
SQLObject getParent();
void setParent(SQLObject parent);
Map<String, Object> getAttributes();
Object getAttribute(String name);
void putAttribute(String name, Object value);
Map<String, Object> getAttributesDirect();
void output(StringBuffer buf);
void addBeforeComment(String comment);
void addBeforeComment(List<String> comments);
List<String> getBeforeCommentsDirect();
void addAfterComment(String comment);
void addAfterComment(List<String> comments);
List<String> getAfterCommentsDirect();
boolean hasBeforeComment();
boolean hasAfterComment();
}
|
package ru.renbou;
import java.util.*;
/* Self-resizing list structure which compactly stores primitive ints
* and can be used the same way as ArrayList<Integer>
*/
public class IntList extends AbstractList<Integer> implements RandomAccess {
private static final int DEFAULT_CAPACITY = 2;
private static final int DEFAULT_SHRINK_MINIMUM_CAPACITY = DEFAULT_CAPACITY * 4;
/* Underlying array used for the list. */
private int[] array;
/* We store the currently used size as well as the capacity of the array */
private int size = 0;
private int capacity = 0;
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Private functions that are often used for this class' functionality *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/* Search for element either from the left or from the right */
private int find(int value, boolean fromRight) {
if (!fromRight) {
for (int i = 0; i < size; i++)
if (array[i] == value)
return i;
} else {
for (int i = size - 1; i >= 0; i--)
if (array[i] == value)
return i;
}
return -1;
}
/* Resizes the list if needed. Finds the closest power of 2 that's higher than the requested
* size in order to maintain amortized O(1) operation time complexity.
*/
private void optimalResize(int newSize) {
if (newSize < capacity)
return;
while ((newSize & (newSize - 1)) != 0) {
newSize &= (newSize - 1);
}
// if we previously had a null array, just allocate a new one
if (capacity > 0) {
array = Arrays.copyOf(array, newSize * 2);
} else {
array = new int[newSize * 2];
}
capacity = newSize * 2;
}
/* Shrinks the underlying when needed in order to save memory space.
* When the used size is less than one quarter of the capacity, then there's no need for us
* to keep this much memory, so we can just shrink it. However if the array is too small then there's
* also no point in constantly calling the gc and allocator, so we define some arbitrary limit.
*/
private void shrinkIfNeeded() {
if (capacity > DEFAULT_SHRINK_MINIMUM_CAPACITY && (size < capacity / 4)) {
capacity /= 2;
array = Arrays.copyOf(array, capacity);
}
}
/* Removes all elements in the specified range by shifting the rest of the array to their position.
* This is used by AbstractList for implementing subList and other methods, overriding the base
* implementation makes it so much faster...
*s
* Range is [from; to) just like AbstractList's removeRange
*/
protected void removeRange(int from, int to) {
if (to < from || from < 0 || to > size)
throw new IndexOutOfBoundsException("Can't delete range of elements at invalid position");
System.arraycopy(array, to, array, from, size - to);
size -= (to - from);
shrinkIfNeeded();
}
/* Remove element at index, shifting the rest of the array if needed */
private int removeAt(int index) {
if (index < 0 || index >= size)
throw new IndexOutOfBoundsException("Can't delete element at non-existent index");
int result = array[index];
if (index < size - 1) {
System.arraycopy(array, index + 1, array, index, size - index);
}
size--;
shrinkIfNeeded();
return result;
}
/* Insert an element at an arbitrary position of the list, shifting the array elements if needed */
private void addAt(int index, int element) {
if (index < 0 || index > size)
throw new IndexOutOfBoundsException("Can't insert element at negative index or index bigger than current size");
if (capacity == size) {
optimalResize(size + 1);
}
if (index < size)
System.arraycopy(array, index, array, index + 1, size - index);
array[index] = element;
size++;
}
/* * * * * * * * * * * *
* Simple constructors *
* * * * * * * * * * * */
public IntList(int[] array) {
optimalResize(array.length);
System.arraycopy(array, 0, this.array, 0, array.length);
size = array.length;
}
public IntList(Integer[] array) {
optimalResize(array.length);
for (int i = 0; i < array.length; i++) {
this.array[i] = array[i];
}
size = array.length;
}
public IntList(Collection<Integer> c) {
optimalResize(c.size());
int i = 0;
for (Integer item : c) {
array[i++] = item;
}
size = c.size();
}
public IntList(int baseArraySize) {
optimalResize(baseArraySize);
}
public IntList() {
this(DEFAULT_CAPACITY);
}
/* * * * * * * * * * * * * * * * * * * * * * * * * * * *
* The basic functions for interacting with the class *
* * * * * * * * * * * * * * * * * * * * * * * * * * * */
public int size() {
return this.size;
}
public boolean isEmpty() {
return size == 0;
}
public boolean contains(Object o) {
if (o instanceof Integer) {
int value = (Integer) o;
return find(value, false) != -1;
}
return false;
}
public int indexOf(Object o) {
if (o instanceof Integer) {
int value = (Integer) o;
return find(value, false);
}
return -1;
}
public int lastIndexOf(Object o) {
if (o instanceof Integer) {
int value = (Integer) o;
return find(value, true);
}
return -1;
}
public void add(int index, Integer element) {
addAt(index, element);
}
public boolean add(Integer e) {
addAt(size, e);
return true;
}
public Integer remove(int index) {
return removeAt(index);
}
public boolean remove(Object o) {
if (o instanceof Integer) {
int value = (Integer) o;
int location = find(value, false);
if (location != -1) {
removeAt(location);
return true;
}
}
return false;
}
public Integer get(int index) {
if (index < 0 || index >= size)
throw new IndexOutOfBoundsException("Can't get element at non-existent index");
return array[index];
}
public Integer set(int index, Integer element) {
if (index < 0 || index >= size)
throw new IndexOutOfBoundsException("Can't change element at non-existent index");
Integer previous = array[index];
array[index] = element;
return previous;
}
/* * * * * * *
* Iterators *
* * * * * * */
public Iterator<Integer> iterator() {
return new Iterator<>() {
int index = 0;
int prevValidIndex = -1;
@Override
public boolean hasNext() {
return index < size;
}
@Override
public Integer next() {
if (index < size) {
prevValidIndex = index;
return array[index++];
}
prevValidIndex = -1;
throw new NoSuchElementException("Iterator points to end of list, no more elements available");
}
@Override
public void remove() {
if (prevValidIndex == -1)
throw new IllegalStateException("Can't remove element before next call");
removeAt(prevValidIndex);
prevValidIndex = -1;
}
};
}
@Override
public ListIterator<Integer> listIterator() {
return listIterator(0);
}
public ListIterator<Integer> listIterator(int index_) {
if (index_ < 0 || index_ >= size)
throw new IndexOutOfBoundsException("Can't create list iterator which points to an invalid location");
return new ListIterator<>() {
int index = index_;
int prevValidIndex = -1;
// this is needed to identify where to insert element on "add", there's no good way to avoid this
boolean prevWasNext = false;
@Override
public boolean hasNext() {
return index < size;
}
@Override
public Integer next() {
if (index < size) {
prevValidIndex = index;
prevWasNext = true;
return array[index++];
}
prevValidIndex = -1;
throw new NoSuchElementException("Iterator points to end of list, no more elements available");
}
@Override
public boolean hasPrevious() {
return index > 0;
}
@Override
public Integer previous() {
if (index > 0) {
index--;
prevValidIndex = index;
prevWasNext = false;
return array[index];
}
prevValidIndex = -1;
throw new NoSuchElementException("Iterator points to end of list, no more elements available");
}
@Override
public int nextIndex() {
return index;
}
@Override
public int previousIndex() {
return index - 1;
}
@Override
public void remove() {
if (prevValidIndex == -1)
throw new IllegalStateException("Can't remove element before next or previous call");
removeAt(prevValidIndex);
prevValidIndex = -1;
}
@Override
public void set(Integer integer) {
if (prevValidIndex == -1)
throw new IllegalStateException("Can't change element value before next or previous call");
array[prevValidIndex] = integer;
}
@Override
public void add(Integer integer) {
if (prevValidIndex == -1)
throw new IllegalStateException("Can't add element before next or previous call");
addAt(prevValidIndex + (prevWasNext ? 0 : 1), integer);
}
};
}
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Collection-based functions which work on multiple elements instead of one *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
public boolean addAll(Collection<? extends Integer> c) {
return addAll(size, c);
}
public boolean addAll(int index, Collection<? extends Integer> c) {
if (index > size)
throw new IndexOutOfBoundsException("Can't add new elements to positions after the end of the list");
Integer[] cArray = c.toArray(new Integer[0]);
if (cArray.length == 0)
return false;
if (size + cArray.length >= capacity) {
optimalResize(size + cArray.length);
}
System.arraycopy(array, index, array, index + cArray.length, size - index);
for (int i = 0; i < cArray.length; i++) {
array[index + i] = cArray[i];
}
size += cArray.length;
return true;
}
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Static functions for working with lists of this type *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/* The use of these functions is to make this class usable with functions such as
* Map<T> merge, or make calls to instances of this class chainable etc.
*/
public static IntList append(IntList integers, Integer value) {
integers.add(value);
return integers;
}
public static IntList append(IntList integers, IntList integers1) {
integers.optimalResize(integers.size + integers1.size);
System.arraycopy(integers1.array, 0, integers.array, integers.size, integers1.size);
integers.size += integers1.size;
return integers;
}
public static IntList mergeLists(IntList integers, IntList integers1) {
IntList result = new IntList(integers.size + integers1.size);
System.arraycopy(integers.array, 0, result.array, 0, integers.size);
System.arraycopy(integers1.array, 0, result.array, integers.size, integers1.size);
result.size = integers.size + integers1.size;
return result;
}
public static IntList intListOf(int ...vals) {
IntList result = new IntList(vals.length);
for (int v: vals) {
result.array[result.size++] = v;
}
return result;
}
/* Stuff for testing the implementation */
private static void printList(List<Integer> l) {
System.out.print("List: ");
for (Integer i : l) {
System.out.print(i + " ");
}
System.out.println();
}
public static void main(String[] args) {
System.out.println("IntList insertion test #1");
IntList a = new IntList();
ArrayList<Integer> al = new ArrayList<>();
System.out.println("Adding values from 1 to 10 to list a");
for (int i = 1; i <= 10; i++) {
a.add(i);
al.add(i);
}
printList(a);
System.out.println("Adding values from ArrayList al containing [1; 10] into list a at index 2");
a.addAll(2, al);
printList(a);
System.out.println("Adding values from ArrayList al containing [1; 10] into list a");
a.addAll(al);
printList(a);
System.out.println("IntList insertion test #2");
IntList b = new IntList();
ArrayList<Integer> bl = new ArrayList<>();
System.out.println("Adding values from 1 to 100 to list b");
for (int i = 1; i <= 100; i++) {
b.add(i);
bl.add(i);
}
printList(b);
System.out.println("Adding values from ArrayList bl containing [1; 100] into list b at index 99");
b.addAll(99, bl);
printList(b);
System.out.println("Adding values from ArrayList bl containing [1; 100] into list b");
b.addAll(bl);
printList(b);
System.out.println("IntList remove test #1");
System.out.println("Removing values at indexes 0, 4, 7 in list a");
a.remove(0);
a.remove(4);
a.remove(7);
printList(a);
System.out.println("Removing value 3 from list a");
a.remove(Integer.valueOf(3));
printList(a);
System.out.println("Removing range [10; 25) from list a");
a.removeRange(10, 25);
printList(a);
System.out.println("IntList subList test #1");
System.out.println("List b:");
printList(b);
System.out.println("Sublist of b in [10; 35]");
List<Integer> subb = b.subList(10, 35);
printList(subb);
System.out.println("Inserting 5 to position 4 in subb");
subb.add(4, 5);
System.out.println("List b and subb:");
printList(b);
printList(subb);
System.out.println("Clearing the sublist");
subb.clear();
printList(b);
printList(subb);
}
}
|
/*
* Copyright (c) 2016 Vivid Solutions.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License 2.0
* and Eclipse Distribution License v. 1.0 which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v20.html
* and the Eclipse Distribution License is available at
*
* http://www.eclipse.org/org/documents/edl-v10.php.
*/
/**
* Contains classes that implement topology graphs.
* <P>
* The Java Topology Suite (JTS) is a Java API that implements a core set of spatial data operations using an explicit precision model and robust geometric algorithms. JTS is intended to be used in the development of applications that support the validation, cleaning, integration and querying of spatial datasets.
* <P>
* JTS attempts to implement the OpenGIS Simple Features Specification (SFS) as accurately as possible. In some cases the SFS is unclear or omits a specification; in this case JTS attempts to choose a reasonable and consistent alternative. Differences from and elaborations of the SFS are documented in this specification.
* <h2>Package Specification</h2>
* <ul>
* <li>Java Topology Suite Technical Specifications
* <li><A HREF="http://www.opengis.org/techno/specs.htm">
* OpenGIS Simple Features Specification for SQL</A>
* </ul>
*/
package org.locationtech.jts.geomgraph;
|
package com.crazy.demo.other;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.BlurMaskFilter;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PixelFormat;
import android.graphics.PointF;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import androidx.annotation.ColorInt;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
/**
* author : 王浩 & NG_crazy
* github : https://github.com/bingoogolapple/BGATransformersTip-Android
* time : 2019/08/19
* desc : 带箭头背景的 Drawable
*/
@SuppressLint("RtlHardcoded")
public final class ArrowDrawable extends Drawable {
private final Builder mBuilder;
private final Paint mPaint;
private Path mPath;
private ArrowDrawable(Builder builder) {
mBuilder = builder;
mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mPaint.setAntiAlias(true);
}
@Override
public void draw(@NonNull Canvas canvas) {
if (mPath != null) {
if (mBuilder.mShadowSize > 0) {
mPaint.setMaskFilter(new BlurMaskFilter(mBuilder.mShadowSize, BlurMaskFilter.Blur.OUTER));
mPaint.setColor(mBuilder.mShadowColor);
canvas.drawPath(mPath, mPaint);
}
mPaint.setMaskFilter(null);
mPaint.setColor(mBuilder.mBackgroundColor);
canvas.drawPath(mPath, mPaint);
}
}
@Override
public void setAlpha(int alpha) {
mPaint.setAlpha(alpha);
}
@Override
public void setColorFilter(@Nullable ColorFilter colorFilter) {
mPaint.setColorFilter(colorFilter);
}
@Override
public int getOpacity() {
return PixelFormat.TRANSLUCENT;
}
@SuppressWarnings("SuspiciousNameCombination")
@Override
protected void onBoundsChange(Rect viewRect) {
if (mPath == null) {
mPath = new Path();
} else {
mPath.reset();
}
RectF excludeShadowRectF = new RectF(viewRect);
excludeShadowRectF.inset(mBuilder.mShadowSize, mBuilder.mShadowSize);
PointF centerPointF = new PointF();
// 判断箭头的位置
switch (mBuilder.mArrowOrientation) {
case Gravity.LEFT:
excludeShadowRectF.left += mBuilder.mArrowHeight;
centerPointF.x = excludeShadowRectF.left;
break;
case Gravity.RIGHT:
excludeShadowRectF.right -= mBuilder.mArrowHeight;
centerPointF.x = excludeShadowRectF.right;
break;
case Gravity.TOP:
excludeShadowRectF.top += mBuilder.mArrowHeight;
centerPointF.y = excludeShadowRectF.top;
break;
case Gravity.BOTTOM:
excludeShadowRectF.bottom -= mBuilder.mArrowHeight;
centerPointF.y = excludeShadowRectF.bottom;
break;
default:
break;
}
// 判断箭头的重心
switch (mBuilder.mArrowGravity) {
case Gravity.LEFT:
centerPointF.x = excludeShadowRectF.left + mBuilder.mArrowHeight;
break;
case Gravity.CENTER_HORIZONTAL:
centerPointF.x = viewRect.width() / 2f;
break;
case Gravity.RIGHT:
centerPointF.x = excludeShadowRectF.right - mBuilder.mArrowHeight;
break;
case Gravity.TOP:
centerPointF.y = excludeShadowRectF.top + mBuilder.mArrowHeight;
break;
case Gravity.CENTER_VERTICAL:
centerPointF.y = viewRect.height() / 2f;
break;
case Gravity.BOTTOM:
centerPointF.y = excludeShadowRectF.bottom - mBuilder.mArrowHeight;
break;
default:
break;
}
// 更新箭头偏移量
centerPointF.x += mBuilder.mArrowOffsetX;
centerPointF.y += mBuilder.mArrowOffsetY;
switch (mBuilder.mArrowGravity) {
case Gravity.LEFT:
case Gravity.RIGHT:
case Gravity.CENTER_HORIZONTAL:
centerPointF.x = Math.max(centerPointF.x, excludeShadowRectF.left + mBuilder.mRadius + mBuilder.mArrowHeight);
centerPointF.x = Math.min(centerPointF.x, excludeShadowRectF.right - mBuilder.mRadius - mBuilder.mArrowHeight);
break;
case Gravity.TOP:
case Gravity.BOTTOM:
case Gravity.CENTER_VERTICAL:
centerPointF.y = Math.max(centerPointF.y, excludeShadowRectF.top + mBuilder.mRadius + mBuilder.mArrowHeight);
centerPointF.y = Math.min(centerPointF.y, excludeShadowRectF.bottom - mBuilder.mRadius - mBuilder.mArrowHeight);
break;
default:
break;
}
switch (mBuilder.mArrowOrientation) {
case Gravity.LEFT:
case Gravity.RIGHT:
centerPointF.x = Math.max(centerPointF.x, excludeShadowRectF.left);
centerPointF.x = Math.min(centerPointF.x, excludeShadowRectF.right);
break;
case Gravity.TOP:
case Gravity.BOTTOM:
centerPointF.y = Math.max(centerPointF.y, excludeShadowRectF.top);
centerPointF.y = Math.min(centerPointF.y, excludeShadowRectF.bottom);
break;
default:
break;
}
// 箭头区域(其实是旋转了 90 度后的正方形区域)
Path arrowPath = new Path();
arrowPath.moveTo(centerPointF.x - mBuilder.mArrowHeight, centerPointF.y);
arrowPath.lineTo(centerPointF.x, centerPointF.y - mBuilder.mArrowHeight);
arrowPath.lineTo(centerPointF.x + mBuilder.mArrowHeight, centerPointF.y);
arrowPath.lineTo(centerPointF.x, centerPointF.y + mBuilder.mArrowHeight);
arrowPath.close();
mPath.addRoundRect(excludeShadowRectF, mBuilder.mRadius, mBuilder.mRadius, Path.Direction.CW);
mPath.addPath(arrowPath);
invalidateSelf();
}
public static final class Builder {
/** 上下文对象 */
private final Context mContext;
/** 箭头高度 */
private int mArrowHeight;
/** 背景圆角大小 */
private int mRadius;
/** 箭头方向 */
private int mArrowOrientation;
/** 箭头重心 */
private int mArrowGravity;
/** 箭头水平方向偏移 */
private int mArrowOffsetX;
/** 箭头垂直方向偏移 */
private int mArrowOffsetY;
/** 阴影大小 */
private int mShadowSize;
/** 背景颜色 */
private int mBackgroundColor;
/** 阴影颜色 */
private int mShadowColor;
public Builder(Context context) {
mContext = context;
mBackgroundColor = 0xFF000000;
mShadowColor = 0x33000000;
mArrowHeight = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 6, mContext.getResources().getDisplayMetrics());
mRadius = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 4, mContext.getResources().getDisplayMetrics());
mShadowSize = 0;
mArrowOffsetX = 0;
mArrowOffsetY = 0;
mArrowOrientation = Gravity.NO_GRAVITY;
mArrowGravity = Gravity.NO_GRAVITY;
}
/**
* 设置背景色
*/
public Builder setBackgroundColor(@ColorInt int color) {
mBackgroundColor = color;
return this;
}
/**
* 设置阴影色
*/
public Builder setShadowColor(@ColorInt int color) {
mShadowColor = color;
return this;
}
/**
* 设置箭头高度
*/
public Builder setArrowHeight(int height) {
mArrowHeight = height;
return this;
}
/**
* 设置浮窗圆角半径
*/
public Builder setRadius(int radius) {
mRadius = radius;
return this;
}
/**
* 设置箭头方向(左上右下)
*/
public Builder setArrowOrientation(int orientation) {
switch (orientation = Gravity.getAbsoluteGravity(orientation, mContext.getResources().getConfiguration().getLayoutDirection())) {
case Gravity.LEFT:
case Gravity.TOP:
case Gravity.RIGHT:
case Gravity.BOTTOM:
mArrowOrientation = orientation;
break;
default:
// 箭头只能在左上右下这四个位置
throw new IllegalArgumentException("are you ok?");
}
return this;
}
/**
* 设置箭头布局重心
*/
public Builder setArrowGravity(int gravity) {
gravity = Gravity.getAbsoluteGravity(gravity, mContext.getResources().getConfiguration().getLayoutDirection());
if (gravity == Gravity.CENTER) {
switch (mArrowOrientation) {
case Gravity.LEFT:
case Gravity.RIGHT:
gravity = Gravity.CENTER_VERTICAL;
break;
case Gravity.TOP:
case Gravity.BOTTOM:
gravity = Gravity.CENTER_HORIZONTAL;
break;
default:
break;
}
}
switch (gravity) {
case Gravity.LEFT:
case Gravity.RIGHT:
if (mArrowOrientation == Gravity.LEFT || mArrowOrientation == Gravity.RIGHT) {
throw new IllegalArgumentException("are you ok?");
}
break;
case Gravity.TOP:
case Gravity.BOTTOM:
if (mArrowOrientation == Gravity.TOP || mArrowOrientation == Gravity.BOTTOM) {
throw new IllegalArgumentException("are you ok?");
}
break;
case Gravity.CENTER_VERTICAL:
case Gravity.CENTER_HORIZONTAL:
break;
default:
// 箭头只能在左上右下这四个位置
throw new IllegalArgumentException("are you ok?");
}
mArrowGravity = gravity;
return this;
}
/**
* 设置箭头在 x 轴的偏移量
*/
public Builder setArrowOffsetX(int offsetX) {
mArrowOffsetX = offsetX;
return this;
}
/**
* 设置箭头在 y 轴的偏移量
*/
public Builder setArrowOffsetY(int offsetY) {
mArrowOffsetY = offsetY;
return this;
}
/**
* 设置阴影宽度
*/
public Builder setShadowSize(int size) {
mShadowSize = size;
return this;
}
/**
* 构建 Drawable
*/
public Drawable build() {
if (mArrowOrientation == Gravity.NO_GRAVITY || mArrowGravity == Gravity.NO_GRAVITY) {
// 必须要先设置箭头的方向及重心
throw new IllegalArgumentException("are you ok?");
}
return new ArrowDrawable(this);
}
/**
* 应用到 View
*/
public void apply(View view) {
view.setBackground(build());
if (mShadowSize > 0 || mArrowHeight > 0) {
if (view.getPaddingTop() == 0 && view.getBottom() == 0 &&
view.getPaddingLeft() == 0 && view.getPaddingRight() == 0) {
view.setPadding(mShadowSize, mShadowSize + mArrowHeight, mShadowSize, mShadowSize);
}
}
}
}
}
|
/**
* Copyright © 2020 ForgeRock AS (obst@forgerock.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.
*/
/*
* Account and Transaction API Specification
* Swagger for Account and Transaction API Specification
*
* OpenAPI spec version: v3.1.2-RC1
* Contact: ServiceDesk@openbanking.org.uk
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
package uk.org.openbanking.datamodel.account;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonValue;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.util.Objects;
/**
* Product details associated with the Account
*/
@ApiModel(description = "Product details associated with the Account")
@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2019-06-13T15:59:01.633+01:00")
public class OBReadProduct2DataProduct {
@JsonProperty("ProductName")
private String productName = null;
@JsonProperty("ProductId")
private String productId = null;
@JsonProperty("AccountId")
private String accountId = null;
@JsonProperty("SecondaryProductId")
private String secondaryProductId = null;
@JsonProperty("ProductType")
private ProductTypeEnum productType = null;
@JsonProperty("MarketingStateId")
private String marketingStateId = null;
@JsonProperty("OtherProductType")
private OBReadProduct2DataOtherProductType otherProductType = null;
@JsonProperty("BCA")
private BCA BCA = null;
@JsonProperty("PCA")
private PCA PCA = null;
public OBReadProduct2DataProduct productName(String productName) {
this.productName = productName;
return this;
}
/**
* The name of the Product used for marketing purposes from a customer perspective. I.e. what the customer would recognise.
*
* @return productName
**/
@Size(min = 1, max = 350)
@ApiModelProperty(value = "The name of the Product used for marketing purposes from a customer perspective. I.e. what the customer would recognise.")
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public OBReadProduct2DataProduct productId(String productId) {
this.productId = productId;
return this;
}
/**
* The unique ID that has been internally assigned by the financial institution to each of the current account banking products they market to their retail and/or small to medium enterprise (SME) customers.
*
* @return productId
**/
@Size(min = 1, max = 40)
@ApiModelProperty(value = "The unique ID that has been internally assigned by the financial institution to each of the current account banking products they market to their retail and/or small to medium enterprise (SME) customers.")
public String getProductId() {
return productId;
}
public void setProductId(String productId) {
this.productId = productId;
}
public OBReadProduct2DataProduct accountId(String accountId) {
this.accountId = accountId;
return this;
}
/**
* Account Identification of the customer for Product Details
*
* @return accountId
**/
@NotNull
@Size(min = 1, max = 40)
@ApiModelProperty(required = true, value = "Account Identification of the customer for Product Details")
public String getAccountId() {
return accountId;
}
public void setAccountId(String accountId) {
this.accountId = accountId;
}
public OBReadProduct2DataProduct secondaryProductId(String secondaryProductId) {
this.secondaryProductId = secondaryProductId;
return this;
}
/**
* Any secondary Identification which supports Product Identifier to uniquely identify the current account banking products.
*
* @return secondaryProductId
**/
@Size(min = 1, max = 70)
@ApiModelProperty(value = "Any secondary Identification which supports Product Identifier to uniquely identify the current account banking products.")
public String getSecondaryProductId() {
return secondaryProductId;
}
public void setSecondaryProductId(String secondaryProductId) {
this.secondaryProductId = secondaryProductId;
}
public OBReadProduct2DataProduct productType(ProductTypeEnum productType) {
this.productType = productType;
return this;
}
/**
* Product type : Personal Current Account, Business Current Account
*
* @return productType
**/
@NotNull
@ApiModelProperty(required = true, value = "Product type : Personal Current Account, Business Current Account")
public ProductTypeEnum getProductType() {
return productType;
}
public void setProductType(ProductTypeEnum productType) {
this.productType = productType;
}
public OBReadProduct2DataProduct marketingStateId(String marketingStateId) {
this.marketingStateId = marketingStateId;
return this;
}
/**
* Unique and unambiguous identification of a Product Marketing State.
*
* @return marketingStateId
**/
@Size(min = 1, max = 35)
@ApiModelProperty(value = "Unique and unambiguous identification of a Product Marketing State.")
public String getMarketingStateId() {
return marketingStateId;
}
public void setMarketingStateId(String marketingStateId) {
this.marketingStateId = marketingStateId;
}
public OBReadProduct2DataProduct otherProductType(OBReadProduct2DataOtherProductType otherProductType) {
this.otherProductType = otherProductType;
return this;
}
/**
* Get otherProductType
*
* @return otherProductType
**/
@Valid
@ApiModelProperty(value = "")
public OBReadProduct2DataOtherProductType getOtherProductType() {
return otherProductType;
}
public void setOtherProductType(OBReadProduct2DataOtherProductType otherProductType) {
this.otherProductType = otherProductType;
}
public OBReadProduct2DataProduct BCA(BCA BCA) {
this.BCA = BCA;
return this;
}
/**
* Get BCA
*
* @return BCA
**/
@Valid
@ApiModelProperty(value = "")
public BCA getBCA() {
return BCA;
}
public void setBCA(BCA BCA) {
this.BCA = BCA;
}
public OBReadProduct2DataProduct PCA(PCA PCA) {
this.PCA = PCA;
return this;
}
/**
* Get PCA
*
* @return PCA
**/
@Valid
@ApiModelProperty(value = "")
public PCA getPCA() {
return PCA;
}
public void setPCA(PCA PCA) {
this.PCA = PCA;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
OBReadProduct2DataProduct obReadProduct2DataProduct = (OBReadProduct2DataProduct) o;
return Objects.equals(this.productName, obReadProduct2DataProduct.productName) &&
Objects.equals(this.productId, obReadProduct2DataProduct.productId) &&
Objects.equals(this.accountId, obReadProduct2DataProduct.accountId) &&
Objects.equals(this.secondaryProductId, obReadProduct2DataProduct.secondaryProductId) &&
Objects.equals(this.productType, obReadProduct2DataProduct.productType) &&
Objects.equals(this.marketingStateId, obReadProduct2DataProduct.marketingStateId) &&
Objects.equals(this.otherProductType, obReadProduct2DataProduct.otherProductType) &&
Objects.equals(this.BCA, obReadProduct2DataProduct.BCA) &&
Objects.equals(this.PCA, obReadProduct2DataProduct.PCA);
}
@Override
public int hashCode() {
return Objects.hash(productName, productId, accountId, secondaryProductId, productType, marketingStateId, otherProductType, BCA, PCA);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class OBReadProduct2DataProduct {\n");
sb.append(" productName: ").append(toIndentedString(productName)).append("\n");
sb.append(" productId: ").append(toIndentedString(productId)).append("\n");
sb.append(" accountId: ").append(toIndentedString(accountId)).append("\n");
sb.append(" secondaryProductId: ").append(toIndentedString(secondaryProductId)).append("\n");
sb.append(" productType: ").append(toIndentedString(productType)).append("\n");
sb.append(" marketingStateId: ").append(toIndentedString(marketingStateId)).append("\n");
sb.append(" otherProductType: ").append(toIndentedString(otherProductType)).append("\n");
sb.append(" BCA: ").append(toIndentedString(BCA)).append("\n");
sb.append(" PCA: ").append(toIndentedString(PCA)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
/**
* Product type : Personal Current Account, Business Current Account
*/
public enum ProductTypeEnum {
BUSINESSCURRENTACCOUNT("BusinessCurrentAccount"),
COMMERCIALCREDITCARD("CommercialCreditCard"),
OTHER("Other"),
PERSONALCURRENTACCOUNT("PersonalCurrentAccount"),
SMELOAN("SMELoan");
private String value;
ProductTypeEnum(String value) {
this.value = value;
}
@JsonCreator
public static ProductTypeEnum fromValue(String text) {
for (ProductTypeEnum b : ProductTypeEnum.values()) {
if (String.valueOf(b.value).equals(text)) {
return b;
}
}
return null;
}
@JsonValue
public String getValue() {
return value;
}
@Override
public String toString() {
return String.valueOf(value);
}
}
}
|
// I believe in you. You can do the thing!
/*
* Copyright © 2018 Atomist, 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.example.vm2018;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import java.util.Collection;
import java.util.stream.Stream;
@SpringBootApplication
public class Vm2018Application {
@Bean
ApplicationRunner runner(ReservationRepository reservationRepository) {
return args -> Stream.of("Rod", "Josh").forEach(name -> reservationRepository.save(new Reservation(null, name)));
}
public static void main(String[] args) {
SpringApplication.run(Vm2018Application.class, args);
}
}
@RestController
class ReservationRestController {
private final ReservationRepository reservationRepository;
ReservationRestController(ReservationRepository reservationRepository) {
this.reservationRepository = reservationRepository;
}
@GetMapping("/")
String hi() {
return "hi" ;
}
@GetMapping("/reservations")
Collection<Reservation> reservations() {
return this.reservationRepository.findAll();
}
}
interface ReservationRepository extends JpaRepository<Reservation, Long> {
}
@Entity
@Data
@AllArgsConstructor
@NoArgsConstructor
class Reservation {
@Id
@GeneratedValue
private Long id;
private String name;
}
|
/*
* 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.commons.beanutils.expression;
/**
* Default Property Name Expression {@link Resolver} Implementation.
* <p>
* This class assists in resolving property names in the following five formats,
* with the layout of an identifying String in parentheses:
* <ul>
* <li><strong>Simple (<code>name</code>)</strong> - The specified
* <code>name</code> identifies an individual property of a particular
* JavaBean. The name of the actual getter or setter method to be used
* is determined using standard JavaBeans instrospection, so that (unless
* overridden by a <code>BeanInfo</code> class, a property named "xyz"
* will have a getter method named <code>getXyz()</code> or (for boolean
* properties only) <code>isXyz()</code>, and a setter method named
* <code>setXyz()</code>.</li>
* <li><strong>Nested (<code>name1.name2.name3</code>)</strong> The first
* name element is used to select a property getter, as for simple
* references above. The object returned for this property is then
* consulted, using the same approach, for a property getter for a
* property named <code>name2</code>, and so on. The property value that
* is ultimately retrieved or modified is the one identified by the
* last name element.</li>
* <li><strong>Indexed (<code>name[index]</code>)</strong> - The underlying
* property value is assumed to be an array, or this JavaBean is assumed
* to have indexed property getter and setter methods. The appropriate
* (zero-relative) entry in the array is selected. <code>List</code>
* objects are now also supported for read/write. You simply need to define
* a getter that returns the <code>List</code></li>
* <li><strong>Mapped (<code>name(key)</code>)</strong> - The JavaBean
* is assumed to have an property getter and setter methods with an
* additional attribute of type <code>java.lang.String</code>.</li>
* <li><strong>Combined (<code>name1.name2[index].name3(key)</code>)</strong> -
* Combining mapped, nested, and indexed references is also
* supported.</li>
* </ul>
*
* @version $Id: DefaultResolver.java 1632171 2014-10-15 20:15:17Z ggregory $
* @since 1.8.0
*/
public class DefaultResolver implements Resolver {
private static final char NESTED = '.';
private static final char MAPPED_START = '(';
private static final char MAPPED_END = ')';
private static final char INDEXED_START = '[';
private static final char INDEXED_END = ']';
/**
* Default Constructor.
*/
public DefaultResolver() {
}
/**
* Return the index value from the property expression or -1.
*
* @param expression The property expression
* @return The index value or -1 if the property is not indexed
* @throws IllegalArgumentException If the indexed property is illegally
* formed or has an invalid (non-numeric) value.
*/
public int getIndex(final String expression) {
if (expression == null || expression.length() == 0) {
return -1;
}
for (int i = 0; i < expression.length(); i++) {
final char c = expression.charAt(i);
if (c == NESTED || c == MAPPED_START) {
return -1;
} else if (c == INDEXED_START) {
final int end = expression.indexOf(INDEXED_END, i);
if (end < 0) {
throw new IllegalArgumentException("Missing End Delimiter");
}
final String value = expression.substring(i + 1, end);
if (value.length() == 0) {
throw new IllegalArgumentException("No Index Value");
}
int index = 0;
try {
index = Integer.parseInt(value, 10);
} catch (final Exception e) {
throw new IllegalArgumentException("Invalid index value '"
+ value + "'");
}
return index;
}
}
return -1;
}
/**
* Return the map key from the property expression or <code>null</code>.
*
* @param expression The property expression
* @return The index value
* @throws IllegalArgumentException If the mapped property is illegally formed.
*/
public String getKey(final String expression) {
if (expression == null || expression.length() == 0) {
return null;
}
for (int i = 0; i < expression.length(); i++) {
final char c = expression.charAt(i);
if (c == NESTED || c == INDEXED_START) {
return null;
} else if (c == MAPPED_START) {
final int end = expression.indexOf(MAPPED_END, i);
if (end < 0) {
throw new IllegalArgumentException("Missing End Delimiter");
}
return expression.substring(i + 1, end);
}
}
return null;
}
/**
* Return the property name from the property expression.
*
* @param expression The property expression
* @return The property name
*/
public String getProperty(final String expression) {
if (expression == null || expression.length() == 0) {
return expression;
}
for (int i = 0; i < expression.length(); i++) {
final char c = expression.charAt(i);
if (c == NESTED) {
return expression.substring(0, i);
} else if (c == MAPPED_START || c == INDEXED_START) {
return expression.substring(0, i);
}
}
return expression;
}
/**
* Indicates whether or not the expression
* contains nested property expressions or not.
*
* @param expression The property expression
* @return The next property expression
*/
public boolean hasNested(final String expression) {
if (expression == null || expression.length() == 0) {
return false;
} else {
return (remove(expression) != null);
}
}
/**
* Indicate whether the expression is for an indexed property or not.
*
* @param expression The property expression
* @return <code>true</code> if the expresion is indexed,
* otherwise <code>false</code>
*/
public boolean isIndexed(final String expression) {
if (expression == null || expression.length() == 0) {
return false;
}
for (int i = 0; i < expression.length(); i++) {
final char c = expression.charAt(i);
if (c == NESTED || c == MAPPED_START) {
return false;
} else if (c == INDEXED_START) {
return true;
}
}
return false;
}
/**
* Indicate whether the expression is for a mapped property or not.
*
* @param expression The property expression
* @return <code>true</code> if the expresion is mapped,
* otherwise <code>false</code>
*/
public boolean isMapped(final String expression) {
if (expression == null || expression.length() == 0) {
return false;
}
for (int i = 0; i < expression.length(); i++) {
final char c = expression.charAt(i);
if (c == NESTED || c == INDEXED_START) {
return false;
} else if (c == MAPPED_START) {
return true;
}
}
return false;
}
/**
* Extract the next property expression from the
* current expression.
*
* @param expression The property expression
* @return The next property expression
*/
public String next(final String expression) {
if (expression == null || expression.length() == 0) {
return null;
}
boolean indexed = false;
boolean mapped = false;
for (int i = 0; i < expression.length(); i++) {
final char c = expression.charAt(i);
if (indexed) {
if (c == INDEXED_END) {
return expression.substring(0, i + 1);
}
} else if (mapped) {
if (c == MAPPED_END) {
return expression.substring(0, i + 1);
}
} else {
if (c == NESTED) {
return expression.substring(0, i);
} else if (c == MAPPED_START) {
mapped = true;
} else if (c == INDEXED_START) {
indexed = true;
}
}
}
return expression;
}
/**
* Remove the last property expresson from the
* current expression.
*
* @param expression The property expression
* @return The new expression value, with first property
* expression removed - null if there are no more expressions
*/
public String remove(final String expression) {
if (expression == null || expression.length() == 0) {
return null;
}
final String property = next(expression);
if (expression.length() == property.length()) {
return null;
}
int start = property.length();
if (expression.charAt(start) == NESTED) {
start++;
}
return expression.substring(start);
}
}
|
/**
* Copyright 1999-2015 dangdang.com.
* <p>
* 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.
* </p>
*/
package com.dangdang.ddframe.rdb.sharding.merger.orderby;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.dangdang.ddframe.rdb.sharding.jdbc.AbstractShardingResultSet;
import com.dangdang.ddframe.rdb.sharding.parser.result.merger.MergeContext;
import com.dangdang.ddframe.rdb.sharding.parser.result.merger.OrderByColumn;
/**
* 排序结果集处理.
*
* @author gaohongtao, zhangliang
*/
public final class OrderByResultSet extends AbstractShardingResultSet {
private final List<OrderByColumn> orderByColumns;
private final List<ResultSet> effectiveResultSets;
private boolean initial;
public OrderByResultSet(final List<ResultSet> resultSets, final MergeContext mergeContext) {
super(resultSets, mergeContext.getLimit());
orderByColumns = mergeContext.getOrderByColumns();
effectiveResultSets = new ArrayList<>(resultSets.size());
}
@Override
public boolean nextForSharding() throws SQLException {
if (!initial) {
initialEffectiveResultSets();
} else {
nextEffectiveResultSets();
}
OrderByValue chosenOrderByValue = null;
for (ResultSet each : effectiveResultSets) {
OrderByValue eachOrderByValue = new OrderByValue(orderByColumns, each);
if (null == chosenOrderByValue || chosenOrderByValue.compareTo(eachOrderByValue) > 0) {
chosenOrderByValue = eachOrderByValue;
setCurrentResultSet(each);
}
}
return !effectiveResultSets.isEmpty();
}
private void initialEffectiveResultSets() throws SQLException {
for (ResultSet each : getResultSets()) {
if (each.next()) {
effectiveResultSets.add(each);
}
}
initial = true;
}
private void nextEffectiveResultSets() throws SQLException {
boolean next = getCurrentResultSet().next();
if (!next) {
effectiveResultSets.remove(getCurrentResultSet());
}
}
}
|
// ------------------------------------------------------------------------------
// 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.AccessReviewScheduleDefinition;
import com.microsoft.graph.requests.extensions.IAccessReviewInstanceCollectionRequestBuilder;
import com.microsoft.graph.requests.extensions.IAccessReviewInstanceRequestBuilder;
import java.util.Arrays;
import java.util.EnumSet;
import com.microsoft.graph.models.extensions.AccessReviewScheduleDefinition;
import com.microsoft.graph.http.IHttpRequest;
import com.microsoft.graph.serializer.IJsonBackedObject;
// **NOTE** This file was generated by a tool and any changes will be overwritten.
/**
* The interface for the Access Review Schedule Definition With Reference Request.
*/
public interface IAccessReviewScheduleDefinitionWithReferenceRequest extends IHttpRequest {
void post(final AccessReviewScheduleDefinition newAccessReviewScheduleDefinition, final IJsonBackedObject payload, final ICallback<? super AccessReviewScheduleDefinition> callback);
AccessReviewScheduleDefinition post(final AccessReviewScheduleDefinition newAccessReviewScheduleDefinition, final IJsonBackedObject payload) throws ClientException;
void get(final ICallback<? super AccessReviewScheduleDefinition> callback);
AccessReviewScheduleDefinition get() throws ClientException;
void delete(final ICallback<? super AccessReviewScheduleDefinition> callback);
void delete() throws ClientException;
void patch(final AccessReviewScheduleDefinition sourceAccessReviewScheduleDefinition, final ICallback<? super AccessReviewScheduleDefinition> callback);
AccessReviewScheduleDefinition patch(final AccessReviewScheduleDefinition sourceAccessReviewScheduleDefinition) throws ClientException;
IAccessReviewScheduleDefinitionWithReferenceRequest select(final String value);
IAccessReviewScheduleDefinitionWithReferenceRequest expand(final String value);
}
|
package ch.nblotti.leonidas.entry.security;
import ch.nblotti.leonidas.entry.EntryPO;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.validation.constraints.NotNull;
@Entity(name = "SECURITY_ENTRY")
public class SecurityEntryPO extends EntryPO {
@NotNull(message = "Account is mandatory")
@Column(name = "SECURITY_ACCOUNT")
private int account;
@NotNull(message = "Quantity is mandatory")
@Column(name = "QUANTITY")
private Float quantity;
@Column(name = "EXCHANGE")
private String exchange;
@NotNull(message = "Quantity is mandatory")
@Column(name = "SECURITY_ID")
private String securityID;
public int getAccount() {
return account;
}
public void setAccount(int account) {
this.account = account;
}
public Float getQuantity() {
return quantity;
}
public void setQuantity(Float quantity) {
this.quantity = quantity;
}
public String getExchange() {
return exchange;
}
public void setExchange(String exchange) {
this.exchange = exchange;
}
public String getSecurityID() {
return securityID;
}
public void setSecurityID(String securityID) {
this.securityID = securityID;
}
}
|
package tonius.thecorruptedsector.world;
import net.minecraft.entity.Entity;
import net.minecraft.util.Vec3;
import net.minecraft.world.WorldProvider;
import net.minecraft.world.chunk.IChunkProvider;
import net.minecraftforge.client.ForgeHooksClient;
import tonius.thecorruptedsector.config.TCSConfig;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
public class WorldProviderMining extends WorldProvider {
@Override
protected void registerWorldChunkManager() {
this.worldChunkMgr = new WorldChunkManagerMining(this.worldObj);
}
@Override
public IChunkProvider createChunkGenerator() {
return new ChunkProviderMining(this.worldObj);
}
@Override
public boolean canRespawnHere() {
return false;
}
@Override
public float calculateCelestialAngle(long worldTime, float partialTicks) {
int temp;
switch (TCSConfig.dayNightCycleMode) {
default:
case NORMAL:
return super.calculateCelestialAngle(worldTime, partialTicks);
case ETERNAL_DAY:
temp = (int) (worldTime % 24000L);
return (float) (Math.cos((temp + partialTicks) * (10F / 60000F) * Math.PI) * 0.2F);
case ETERNAL_NIGHT:
temp = (int) (worldTime % 24000L);
return (float) (Math.cos((temp + partialTicks) * (10F / 60000F) * Math.PI) * 0.2F + 0.5F);
}
}
@Override
public int getMoonPhase(long worldTime) {
return 0;
}
@Override
@SideOnly(Side.CLIENT)
public float getCloudHeight() {
if (!TCSConfig.clouds) {
return Float.MAX_VALUE;
}
return super.getCloudHeight();
}
@Override
@SideOnly(Side.CLIENT)
public Vec3 getSkyColor(Entity cameraEntity, float partialTicks) {
float celestialAngle = this.worldObj.getCelestialAngle(partialTicks);
float daylight = (float) (Math.cos(celestialAngle * Math.PI * 2.0F) * 2.0F + 0.5F);
if (daylight < 0.1F) {
daylight = 0.1F;
}
if (daylight > 1.0F) {
daylight = 1.0F;
}
int posX = (int) Math.floor(cameraEntity.posX);
int posY = (int) Math.floor(cameraEntity.posY);
int posZ = (int) Math.floor(cameraEntity.posZ);
int skyBlendColor = ForgeHooksClient.getSkyBlendColour(this.worldObj, posX, posY, posZ);
float skyRed = (skyBlendColor >> 16 & 255) / 255.0F;
float skyGreen = (skyBlendColor >> 8 & 255) / 255.0F;
float skyBlue = (skyBlendColor & 255) / 255.0F;
skyRed *= daylight;
skyGreen *= daylight;
skyBlue *= daylight;
float rainStrength = this.worldObj.getRainStrength(partialTicks);
float temp1, temp2;
if (rainStrength > 0.0F) {
temp1 = (skyRed * 0.3F + skyGreen * 0.59F + skyBlue * 0.11F) * 0.6F;
temp2 = 1.0F - rainStrength * 0.75F;
skyRed = skyRed * temp2 + temp1 * (1.0F - temp2);
skyGreen = skyGreen * temp2 + temp1 * (1.0F - temp2);
skyBlue = skyBlue * temp2 + temp1 * (1.0F - temp2);
}
temp1 = this.worldObj.getWeightedThunderStrength(partialTicks);
if (temp1 > 0.0F) {
temp2 = (skyRed * 0.3F + skyGreen * 0.59F + skyBlue * 0.11F) * 0.2F;
float temp3 = 1.0F - temp1 * 0.75F;
skyRed = skyRed * temp3 + temp2 * (1.0F - temp3);
skyGreen = skyGreen * temp3 + temp2 * (1.0F - temp3);
skyBlue = skyBlue * temp3 + temp2 * (1.0F - temp3);
}
if (this.worldObj.lastLightningBolt > 0) {
temp2 = this.worldObj.lastLightningBolt - partialTicks;
if (temp2 > 1.0F) {
temp2 = 1.0F;
}
temp2 *= 0.45F;
skyRed = skyRed * (1.0F - temp2) + 0.8F * temp2;
skyGreen = skyGreen * (1.0F - temp2) + 0.8F * temp2;
skyBlue = skyBlue * (1.0F - temp2) + 1.0F * temp2;
}
skyRed *= 2.0F;
skyGreen *= 4.0F;
skyBlue *= 0.5F;
return Vec3.createVectorHelper(skyRed, skyGreen, skyBlue);
}
@Override
public String getDimensionName() {
return "The Corrupted Sector";
}
public static enum DayNightCycleMode {
NORMAL, ETERNAL_DAY, ETERNAL_NIGHT
}
}
|
package dev_Experiments;
import java.awt.Color;
import java.awt.GridLayout;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.ClientInfoStatus;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Vector;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JSplitPane;
import org.apache.commons.collections15.Transformer;
import measure.MeasuresUtil;
import measure.cluster.agreement.ClusteringAgreement;
import measure.cluster.agreement.partitioning.PartiotioningAgreement;
import measure.graph.criteria.Modularity;
import ui.PartitionView;
import util.DatasetUtils;
import util.DatasetUtils.ClassicDataset;
import io.graph.gml.GMLGraphWriter;
import algorithms.AlgorithmUtils;
import algorithms.AlgorithmUtils.Method;
import algorithms.communityMining.CommunityMiner;
import algorithms.communityMining.data.Grouping;
import algorithms.communityMining.topleaders.data.Partitioning;
import data.GraphDataSet;
import edu.uci.ics.jung.algorithms.metrics.Metrics;
import edu.uci.ics.jung.graph.Graph;
public class ExternalExperiment {
DecimalFormat df = new DecimalFormat("#.###");
DateFormat formatter = new SimpleDateFormat("mm:ss:SSS");
public <V,E> void compareMethods(Vector<GraphDataSet<V, E>> datasets, String runname) throws IOException{
// communityMiners.addAll(minerUtils.getAllCommunititMiners());
//communityMiners.add(new communityMinerIGraph<V,E>());
// communityMiners.addAll( minerUtils.getVariant(Method.BP));
// FileOutputStream out = new FileOutputStream("comparRes"+runName+".csv");
FileOutputStream outTime = new FileOutputStream(runname+"res"+".csv");
System.err.println("Comparing methods on "+datasets.size()+" datasets ");
for (GraphDataSet<V, E> dataset : datasets) {
// dataset.printStats();
System.out.print("------> Graph "+dataset.name+" : ");
System.out.print(dataset.graph.getVertexCount()+" nodes and " + dataset.graph.getEdgeCount() + " Edges");
Vector<CommunityMiner<V, E>> communityMiners = new Vector<CommunityMiner<V,E>>();
// communityMiners.add(minerUtils.getCommunititMiner(Method.FastModularity));
// communityMiners.addAll(minerUtils.getModularityBasedCommunititMiners());
communityMiners.add( AlgorithmUtils.<V, E>getCommunititMiner(Method.Louvain));
// communityMiners.add(new communityMinerIGraph<V,E>(communityMinerIGraph.Method.fastgreedy));
// communityMiners.add(new communityMinerIGraph<V,E>(communityMinerIGraph.Method.spinglass));
// communityMiners.add(new communityMinerIGraph<V,E>(communityMinerIGraph.Method.leading_eigenvector));
//
// communityMiners.add(new communityMinerIGraph<V,E>(communityMinerIGraph.Method.infomap));
// communityMiners.add(new communityMinerIGraph<V,E>(communityMinerIGraph.Method.walktrap));
// communityMiners.add(new communityMinerIGraph<V,E>(communityMinerIGraph.Method.label_propagation));
initializePlot(dataset.name, communityMiners.size());
Modularity<V, E> modularity = new Modularity<V, E>(dataset.graph,dataset.getWeightsTransformer());
for (CommunityMiner<V, E> communityMiner : communityMiners) {
Map<String , String> evalMetrics = new HashMap<String , String>();
System.err.println("Method: " + communityMiner.getName());
long startTime = System.nanoTime();
Grouping<V> grouping = communityMiner.findCommunities(dataset.graph, dataset.weights );
System.err.println(grouping);
long endTime = System.nanoTime();
long duration = (endTime - startTime)/1000000; //from nano to milisecond
// FileOutputStream outComm = new FileOutputStream("res/"+dataset.name+"."+communityMiner+"."+runname+".com");
// outComm.write(grouping.getGroups().toString().getBytes());
// outComm.close();
dataset.addPartitioingAttribute(communityMiner.getName(), grouping.getGroups());
GMLGraphWriter<V, E> gmlGraphWriter = new GMLGraphWriter<V, E>();
gmlGraphWriter.writeGraph("res/"+dataset.name+"."+communityMiner+"."+runname+".gml",
dataset.graph, null, dataset.weights, null, dataset.attributes);
System.err.print("done! in " + duration+ " q = ");
double q = modularity.evaluate(grouping.getGroups());
System.out.println(q);
//w,n, e, m , q, t
int n = dataset.graph.getVertexCount();
outTime.write((dataset.name+( (dataset.weights== null)?" , n":" , y") +" , "+n+" , "+dataset.graph.getEdgeCount()
+" , "+ communityMiner.getName()+
" , " + df.format(q) + " , " + duration*0.001 + " , " +
" , "+ grouping.getNumberOfGroups()).getBytes());
evalMetrics.put("time", formatter.format(new Date(duration)));
evalMetrics.put("Q", df.format(q));
Vector<String> atts = new Vector<String>();
if(dataset.attributes!=null && dataset.attributes.values().size()>0){
for (Object att : dataset.attributes.values().iterator().next().keySet() ){
String attName = att.toString().toLowerCase();
if(attName.equals("id") || attName.equals("label")) continue;
atts.add(attName);
}
}
// String [] atts = {"value"};
// String [] atts ={"label","major",
// "second major/minor (if applicable)",
// "dorm/house","gender","a student/faculty status flag" ,"high school", "year"};
Map<V,String> labels = null;
Grouping<V> groundth = null;
for(String att: atts){
Grouping< V> attClustering = dataset.getGrouping(att, new Transformer<Object, Integer>() {
Vector<Object> clusters = new Vector<>();
@Override
public Integer transform(Object obj) {
if (!clusters.contains(obj)) clusters.add(obj);
return clusters.indexOf(obj);
}
});
if(att.equals("label")) labels = dataset.getAttMap("label");
if(att.equals("value")) groundth = attClustering;
Vector< ClusteringAgreement<V>> res = MeasuresUtil.<V,E>getAgreementAlternatives(dataset.graph, dataset.getWeightsTransformer());
for (ClusteringAgreement<V> partiotioningAgreement : res) {
System.err.println(partiotioningAgreement);
double accu = partiotioningAgreement.getAgreement(grouping.getGroups(), attClustering.getGroups());
System.err.println(att+":"+accu+":"+"."+partiotioningAgreement);
outTime.write(( " , " + accu ).getBytes());
evalMetrics.put((partiotioningAgreement.toString()+(att.equals("value")?"":("."+att))), df.format(accu));
}
}
outTime.write(("\n").getBytes());
evalMetrics.put("k", grouping.getNumberOfGroups()+"");
plotCommunities(dataset.name //.substring(0,dataset.name.indexOf('.'))
+" "+ communityMiner.getName() + " k="+ evalMetrics.get("k") +
" Q="+ evalMetrics.get("Q") + " NMI="+ evalMetrics.get("NMI") // toString()
, dataset.graph,dataset.weights, labels, groundth, grouping);
}
}
// out.close();
outTime.close();
}
JFrame jf;
private void initializePlot(String title, int n){
jf = new JFrame(title);
// jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
if(n>4)
jf.setLayout( new GridLayout( n/2 +n%2,2));
else jf.setLayout( new GridLayout( n,1));
jf.setBackground(Color.white);
}
public <V,E> void plotCommunities(String title,Graph<V,E> graph,
Map<E, Double> edgeWeights ,Map<V,String> labels ,Grouping<V> colourGroup, Grouping<V> shapeGroup){
if (graph.getVertexCount()>500) return;
PartitionView< V, E> partitionView = new PartitionView< V, E>(graph,
edgeWeights,labels,
colourGroup,
shapeGroup);
partitionView.setSize(200, 200);
JSplitPane pane = new JSplitPane(0, new JLabel(title,JLabel.CENTER) ,partitionView);
pane.setBackground(Color.white);
pane.setDividerSize(0);
jf.getContentPane().add(pane);
jf.pack();
jf.setVisible(true);
partitionView.saveAsFigure("./img/"+title);
//Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
//jf.setLocation((int)screenSize.getWidth()/6, (int)screenSize.getHeight()/6);
//jf.setSize((int)screenSize.getWidth()*2/3,(int)screenSize.getHeight()*2/3);
}
public static void main(String[] args){
new File("res").mkdir();
new File("img").mkdir();
Vector<GraphDataSet<Integer, Integer>> datasets = new Vector<GraphDataSet<Integer,Integer>>();
// --------------- TEST -------------------------
datasets.add(DatasetUtils.<Integer,Integer>loadClassic(ClassicDataset.wkarate));
// --------------- EXP 1 -------------------------
// for (GraphDataSet<Integer, Integer> dataset: DatasetUtils.<Integer,Integer>loadAll("../Datasets/classics/")){
// if (dataset.graph.getEdgeCount()<20000){
// dataset.printStats();
// datasets.add(dataset);
// }
// }
// --------------- EXP 2 -------------------------
// for (GraphDataSet<Integer, Integer> dataset: DatasetUtils.<Integer,Integer>loadAllDataSets("../Datasets/SNAP/facebook/")){
// if (dataset.graph.getEdgeCount()<20000){
// dataset.printStats();
// datasets.add(dataset);
// }
// }
//
// for (GraphDataSet<Integer, Integer> dataset: DatasetUtils.<Integer,Integer>loadAll("../Datasets/Biological/linkGroup/")){
// {dataset.printStats();
// datasets.add(dataset);}
// }
// for (GraphDataSet<Integer, Integer> dataset: DatasetUtils.<Integer,Integer>loadAll("src/models/generative/iGraph/")){
// if (dataset.graph.getEdgeCount()<20000){
// dataset.printStats();
// datasets.add(dataset);
// }
// }
// datasets.addAll(DatasetUtils.<Integer,Integer>loadAll("../Datasets/classics/power/")) ;
// datasets.add(DatasetUtils.<Integer,Integer>load("ff.gml")) ;
// datasets.addAll(DatasetUtils.loadAllClassics());
// datasets.add(DatasetUtils.<Integer,Integer>load(new File("Rice31.gml")));/home/reihaneh/projects/Datasets/SNAP/facebook
//datasets.addAll(ClassicDatasetLoader.loadLFR(false));
// datasets.add(ClassicDatasetLoader.loadFacebook(false));
ExternalExperiment test = new ExternalExperiment();
try {
test.compareMethods(datasets, "ForestFireTestTest");
} catch (IOException e) {
e.printStackTrace();
}
}
}
|
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
package io.opentelemetry.instrumentation.apachedubbo.v2_7;
import static io.opentelemetry.api.trace.Span.Kind.CLIENT;
import static io.opentelemetry.api.trace.Span.Kind.SERVER;
import io.opentelemetry.api.trace.Span;
import io.opentelemetry.api.trace.SpanBuilder;
import io.opentelemetry.api.trace.Tracer;
import io.opentelemetry.context.Context;
import io.opentelemetry.context.propagation.TextMapPropagator.Getter;
import io.opentelemetry.instrumentation.api.tracer.RpcServerTracer;
import io.opentelemetry.instrumentation.api.tracer.utils.NetPeerUtils;
import io.opentelemetry.semconv.trace.attributes.SemanticAttributes;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcContext;
import org.apache.dubbo.rpc.RpcInvocation;
class DubboTracer extends RpcServerTracer<RpcInvocation> {
protected DubboTracer() {}
DubboTracer(Tracer tracer) {
super(tracer);
}
public Context startServerSpan(
String interfaceName, String methodName, RpcInvocation rpcInvocation) {
SpanBuilder spanBuilder =
tracer
.spanBuilder(DubboHelper.getSpanName(interfaceName, methodName))
.setSpanKind(SERVER)
.setParent(extract(rpcInvocation, getGetter()));
spanBuilder.setAttribute(SemanticAttributes.RPC_SYSTEM, "dubbo");
Span span = spanBuilder.startSpan();
DubboHelper.prepareSpan(span, interfaceName, methodName);
NetPeerUtils.INSTANCE.setNetPeer(span, RpcContext.getContext().getRemoteAddress());
return withServerSpan(Context.current(), span);
}
public Context startClientSpan(String interfaceName, String methodName) {
SpanBuilder spanBuilder =
tracer.spanBuilder(DubboHelper.getSpanName(interfaceName, methodName)).setSpanKind(CLIENT);
spanBuilder.setAttribute(SemanticAttributes.RPC_SYSTEM, "dubbo");
Span span = spanBuilder.startSpan();
DubboHelper.prepareSpan(span, interfaceName, methodName);
NetPeerUtils.INSTANCE.setNetPeer(span, RpcContext.getContext().getRemoteAddress());
return withClientSpan(Context.current(), span);
}
public void endSpan(Span span, Result result) {
span.setStatus(DubboHelper.statusFromResult(result));
end(span);
}
@Override
protected String getInstrumentationName() {
return "io.opentelemetry.javaagent.apache-dubbo";
}
@Override
protected Getter<RpcInvocation> getGetter() {
return DubboExtractAdapter.GETTER;
}
}
|
package com.ajts.androidmads.sqlite2xlDemo.db;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import com.ajts.androidmads.sqlite2xlDemo.model.Users;
import java.util.ArrayList;
public class DBQueries {
private Context context;
private SQLiteDatabase database;
private DBHelper dbHelper;
public DBQueries(Context context) {
this.context = context;
}
public DBQueries open() throws SQLException {
dbHelper = new DBHelper(context);
database = dbHelper.getWritableDatabase();
return this;
}
public void close() {
dbHelper.close();
}
// Users
public boolean insertUser(Users users) {
ContentValues values = new ContentValues();
values.put(DBConstants.CONTACT_PERSON_NAME, users.getContactPersonName());
values.put(DBConstants.CONTACT_NO, users.getContactNumber());
values.put(DBConstants.CONTACT_PHOTO, users.getContactPhoto());
return database.insert(DBConstants.USER_TABLE, null, values) > -1;
}
public ArrayList<Users> readUsers() {
ArrayList<Users> list = new ArrayList<>();
try {
Cursor cursor;
database = dbHelper.getReadableDatabase();
cursor = database.rawQuery(DBConstants.SELECT_QUERY, null);
list.clear();
if (cursor.getCount() > 0) {
if (cursor.moveToFirst()) {
do {
String contactId = cursor.getString(cursor.getColumnIndex(DBConstants.CONTACT_ID));
String conPerson = cursor.getString(cursor.getColumnIndex(DBConstants.CONTACT_PERSON_NAME));
String conNo = cursor.getString(cursor.getColumnIndex(DBConstants.CONTACT_NO));
byte[] conPhoto = cursor.getBlob(cursor.getColumnIndex(DBConstants.CONTACT_NO));
Users users = new Users(contactId, conPerson, conNo, conPhoto);
list.add(users);
} while (cursor.moveToNext());
}
}
cursor.close();
} catch (Exception e) {
Log.v("Exception", e.getMessage());
}
return list;
}
}
|
package com.tesco.aqueduct.pipe.logger;
import com.tesco.aqueduct.pipe.api.Message;
import com.tesco.aqueduct.pipe.api.OffsetEntity;
import com.tesco.aqueduct.pipe.api.PipeState;
import org.slf4j.Logger;
import org.slf4j.MDC;
import java.util.*;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
public class PipeLogger {
private final Logger log;
private final Map<String, String> fields;
public PipeLogger(final Logger logger) {
this.log = logger;
this.fields = new HashMap<>();
}
private PipeLogger(final PipeLogger logger, final Map<String, String> logFields) {
this.log = logger.log;
this.fields = new HashMap<>();
this.fields.putAll(logger.fields);
this.fields.putAll(logFields);
}
public PipeLogger withMessage(final Message message) {
final Map<String, String> fields = new HashMap<>();
fields.put("type", message.getType());
fields.put("key", message.getKey());
fields.put("contentType", message.getContentType());
fields.put("offset", String.valueOf(message.getOffset()));
return new PipeLogger(this, fields);
}
public PipeLogger withTypes(final List<String> types) {
if (!log.isDebugEnabled() || types == null) {
return this;
}
final Map<String, String> fields = Collections.singletonMap(
"types",
Arrays.toString(types.toArray())
);
return new PipeLogger(this, fields);
}
public PipeLogger withOffset(final long offset) {
final Map<String, String> fields = Collections.singletonMap(
"offset",
String.valueOf(offset)
);
return new PipeLogger(this, fields);
}
public PipeLogger withLocation(final String location) {
final Map<String, String> fields = Collections.singletonMap(
"location",
location
);
return new PipeLogger(this, fields);
}
public void error(final String where, final String what, final String why) {
log(where, what, why, log::error);
}
public void error(final String where, final String what, final Throwable why) {
log(where, what, why, log::error);
}
public void info(final String where, final String what) {
if (log.isInfoEnabled()) {
log(where, what, log::info);
}
}
public void info(final String where, final String what, final Throwable why) {
if (log.isInfoEnabled()) {
log(where, what, why, log::info);
}
}
public void debug(final String where, final String what) {
if (log.isDebugEnabled()) {
log(where, what, log::debug);
}
}
public void debug(final String where, final String what, final Throwable why) {
if (log.isDebugEnabled()) {
log(where, what, why, log::debug);
}
}
private void log(final String where, final String what, final Consumer<String> loggerFunc) {
log(where, () -> loggerFunc.accept(what));
}
private void log(final String where, final String what, final Object why, final BiConsumer<String, Object> loggerFunc) {
log(where, () -> loggerFunc.accept(what, why));
}
private void log(String where, Runnable logger) {
final Map<String, String> previousContextMap = MDC.getCopyOfContextMap();
try {
if (previousContextMap != null) {
fields.putAll(previousContextMap);
}
fields.put("method", where);
MDC.setContextMap(fields);
logger.run();
} finally {
// recover MDC state as before
if (previousContextMap != null) {
MDC.setContextMap(previousContextMap);
} else {
MDC.clear();
}
}
}
public boolean isDebugEnabled() {
return log.isDebugEnabled();
}
public PipeLogger withOffset(OffsetEntity offset) {
final Map<String, String> fields = new HashMap<>();
fields.put("name", offset.getName().toString());
fields.put("value", offset.getValue().toString());
return new PipeLogger(this, fields);
}
public PipeLogger withPipeState(PipeState pipeState) {
final Map<String, String> fields = new HashMap<>();
fields.put("name", "pipeState");
fields.put("value", pipeState.toString());
return new PipeLogger(this, fields);
}
}
|
package cn.ucai.superwechat.activity;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import android.os.Bundle;
import android.text.TextUtils;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.easemob.EMCallBack;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.FileMessageBody;
import cn.ucai.superwechat.R;
import com.easemob.util.FileUtils;
public class ShowNormalFileActivity extends BaseActivity {
private ProgressBar progressBar;
private File file;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_file);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
final FileMessageBody messageBody = getIntent().getParcelableExtra("msgbody");
file = new File(messageBody.getLocalUrl());
//set head map
final Map<String, String> maps = new HashMap<String, String>();
if (!TextUtils.isEmpty(messageBody.getSecret())) {
maps.put("share-secret", messageBody.getSecret());
}
//下载文件
EMChatManager.getInstance().downloadFile(messageBody.getRemoteUrl(), messageBody.getLocalUrl(), maps,
new EMCallBack() {
@Override
public void onSuccess() {
runOnUiThread(new Runnable() {
public void run() {
FileUtils.openFile(file, ShowNormalFileActivity.this);
finish();
}
});
}
@Override
public void onProgress(final int progress,String status) {
runOnUiThread(new Runnable() {
public void run() {
progressBar.setProgress(progress);
}
});
}
@Override
public void onError(int error, final String msg) {
runOnUiThread(new Runnable() {
public void run() {
if(file != null && file.exists()&&file.isFile())
file.delete();
String str4 = getResources().getString(R.string.Failed_to_download_file);
Toast.makeText(ShowNormalFileActivity.this, str4+msg, Toast.LENGTH_SHORT).show();
finish();
}
});
}
});
}
}
|
/*
* Copyright 2002-2014 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.http.client;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.http.HttpMethod;
/**
* @author Arjen Poutsma
*/
public class Netty4ClientHttpRequestFactoryTests extends AbstractHttpRequestFactoryTestCase {
private static EventLoopGroup eventLoopGroup;
@BeforeClass
public static void createEventLoopGroup() {
eventLoopGroup = new NioEventLoopGroup();
}
@AfterClass
public static void shutdownEventLoopGroup() throws InterruptedException {
eventLoopGroup.shutdownGracefully().sync();
}
@Override
@SuppressWarnings("deprecation")
protected ClientHttpRequestFactory createRequestFactory() {
return new Netty4ClientHttpRequestFactory(eventLoopGroup);
}
@Override
@Test
public void httpMethods() throws Exception {
super.httpMethods();
assertHttpMethod("patch", HttpMethod.PATCH);
}
}
|
/*
* Autopsy Forensic Browser
*
* Copyright 2011-2016 Basis Technology Corp.
* Contact: carrier <at> sleuthkit <dot> org
*
* 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.sleuthkit.autopsy.casemodule;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.io.File;
import java.util.logging.Level;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.AbstractTableModel;
import org.openide.util.NbBundle;
import org.sleuthkit.autopsy.coreutils.Logger;
import org.openide.windows.WindowManager;
import java.awt.Cursor;
/**
* Panel used by the the open recent case option of the start window.
*/
class OpenRecentCasePanel extends javax.swing.JPanel {
private static final long serialVersionUID = 1L;
private static final Logger logger = Logger.getLogger(OpenRecentCasePanel.class.getName());
private static OpenRecentCasePanel instance;
private static String[] caseNames;
private static String[] casePaths;
private RecentCasesTableModel model;
/**
* Constructs a panel used by the the open recent case option of the start
* window.
*/
private OpenRecentCasePanel() {
initComponents();
}
/*
* Gets the singleton instance of the panel used by the the open recent case
* option of the start window.
*/
static OpenRecentCasePanel getInstance() {
if (instance == null) {
instance = new OpenRecentCasePanel();
}
instance.refreshRecentCasesTable();
return instance;
}
/**
* Adds an action listener to the cancel button.
*
* @param listener An action listener.
*/
void setCloseButtonActionListener(ActionListener listener) {
this.cancelButton.addActionListener(listener);
}
/**
* Retrieves all the recent cases and adds them to the table.
*/
private void refreshRecentCasesTable() {
caseNames = RecentCases.getInstance().getRecentCaseNames();
casePaths = RecentCases.getInstance().getRecentCasePaths();
model = new RecentCasesTableModel();
imagesTable.setAutoResizeMode(JTable.AUTO_RESIZE_LAST_COLUMN);
imagesTable.setModel(model);
int width = tableScrollPane.getPreferredSize().width;
imagesTable.getColumnModel().getColumn(0).setPreferredWidth((int) (.30 * width));
imagesTable.getColumnModel().getColumn(1).setPreferredWidth((int) (.70 * width));
// If there are any images, let's select the first one
if (imagesTable.getRowCount() > 0) {
imagesTable.setRowSelectionInterval(0, 0);
openButton.setEnabled(true);
} else {
openButton.setEnabled(false);
}
}
/*
* Opens the selected case.
*/
private void openCase() {
if (casePaths.length < 1) {
return;
}
final String casePath = casePaths[imagesTable.getSelectedRow()];
final String caseName = caseNames[imagesTable.getSelectedRow()];
if (!casePath.equals("")) {
try {
StartupWindowProvider.getInstance().close();
CueBannerPanel.closeOpenRecentCasesWindow();
} catch (Exception ex) {
logger.log(Level.SEVERE, "Error closing start up window", ex); //NON-NLS
}
/*
* Open the case.
*/
if (caseName.equals("") || casePath.equals("") || (!new File(casePath).exists())) {
JOptionPane.showMessageDialog(WindowManager.getDefault().getMainWindow(),
NbBundle.getMessage(this.getClass(), "RecentItems.openRecentCase.msgDlg.text", caseName),
NbBundle.getMessage(this.getClass(), "CaseOpenAction.msgDlg.cantOpenCase.title"),
JOptionPane.ERROR_MESSAGE);
RecentCases.getInstance().removeRecentCase(caseName, casePath); // remove the recent case if it doesn't exist anymore
if (Case.isCaseOpen() == false) {
StartupWindowProvider.getInstance().open();
}
} else {
SwingUtilities.invokeLater(() -> {
WindowManager.getDefault().getMainWindow().setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
});
new Thread(() -> {
try {
Case.open(casePath);
} catch (CaseActionException ex) {
SwingUtilities.invokeLater(() -> {
logger.log(Level.SEVERE, String.format("Error opening case with metadata file path %s", casePath), ex); //NON-NLS
WindowManager.getDefault().getMainWindow().setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
JOptionPane.showMessageDialog(
WindowManager.getDefault().getMainWindow(),
ex.getMessage(), // Should be user-friendly
NbBundle.getMessage(this.getClass(), "CaseOpenAction.msgDlg.cantOpenCase.title"), //NON-NLS
JOptionPane.ERROR_MESSAGE);
if (!Case.isCaseOpen()) {
StartupWindowProvider.getInstance().open();
}
});
}
}).start();
}
}
}
/**
* Table model to keep track of recent cases.
*/
private class RecentCasesTableModel extends AbstractTableModel {
private static final long serialVersionUID = 1L;
@Override
public int getRowCount() {
int count = 0;
for (String s : caseNames) {
if (!s.equals("")) {
count++;
}
}
return count;
}
@Override
public int getColumnCount() {
return 2;
}
@Override
public String getColumnName(int column) {
String colName = null;
switch (column) {
case 0:
colName = NbBundle.getMessage(OpenRecentCasePanel.class, "OpenRecentCasePanel.colName.caseName");
break;
case 1:
colName = NbBundle.getMessage(OpenRecentCasePanel.class, "OpenRecentCasePanel.colName.path");
break;
default:
break;
}
return colName;
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
Object ret = null;
switch (columnIndex) {
case 0:
ret = caseNames[rowIndex];
break;
case 1:
ret = shortenPath(casePaths[rowIndex]);
break;
default:
logger.log(Level.SEVERE, "Invalid table column index: {0}", columnIndex); //NON-NLS
break;
}
return ret;
}
@Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
return false;
}
@Override
public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
}
/**
* Shortens a path to fit the display.
*
* @param path The path to shorten.
*
* @return The shortened path.
*/
private String shortenPath(String path) {
String shortenedPath = path;
if (shortenedPath.length() > 50) {
shortenedPath = path.substring(0, 10 + path.substring(10).indexOf(File.separator) + 1) + "..."
+ path.substring((path.length() - 20) + path.substring(path.length() - 20).indexOf(File.separator));
}
return shortenedPath;
}
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
cancelButton = new javax.swing.JButton();
openButton = new javax.swing.JButton();
tableScrollPane = new javax.swing.JScrollPane();
imagesTable = new javax.swing.JTable();
jLabel1.setText(org.openide.util.NbBundle.getMessage(OpenRecentCasePanel.class, "OpenRecentCasePanel.jLabel1.text")); // NOI18N
cancelButton.setText(org.openide.util.NbBundle.getMessage(OpenRecentCasePanel.class, "OpenRecentCasePanel.cancelButton.text")); // NOI18N
openButton.setText(org.openide.util.NbBundle.getMessage(OpenRecentCasePanel.class, "OpenRecentCasePanel.openButton.text")); // NOI18N
openButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
openButtonActionPerformed(evt);
}
});
imagesTable.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
}
));
imagesTable.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);
imagesTable.setShowHorizontalLines(false);
imagesTable.setShowVerticalLines(false);
imagesTable.getTableHeader().setReorderingAllowed(false);
imagesTable.setUpdateSelectionOnSort(false);
imagesTable.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
imagesTableMouseClicked(evt);
}
});
imagesTable.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
imagesTableKeyPressed(evt);
}
});
tableScrollPane.setViewportView(imagesTable);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel1)
.addGap(292, 414, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(tableScrollPane)
.addGroup(layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(openButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(cancelButton)))
.addContainerGap())))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(tableScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 168, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(cancelButton)
.addComponent(openButton))
.addContainerGap())
);
}// </editor-fold>//GEN-END:initComponents
private void openButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_openButtonActionPerformed
openCase();
}//GEN-LAST:event_openButtonActionPerformed
private void imagesTableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_imagesTableMouseClicked
// If it's a doubleclick
if (evt.getClickCount() == 2) {
openCase();
}
}//GEN-LAST:event_imagesTableMouseClicked
private void imagesTableKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_imagesTableKeyPressed
if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
openCase();
}
}//GEN-LAST:event_imagesTableKeyPressed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton cancelButton;
private javax.swing.JTable imagesTable;
private javax.swing.JLabel jLabel1;
private javax.swing.JButton openButton;
private javax.swing.JScrollPane tableScrollPane;
// End of variables declaration//GEN-END:variables
}
|
package com.planet_ink.coffee_web.servlets;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import com.planet_ink.coffee_web.http.HTTPMethod;
import com.planet_ink.coffee_web.http.HTTPStatus;
import com.planet_ink.coffee_web.http.MIMEType;
import com.planet_ink.coffee_web.interfaces.SimpleServlet;
import com.planet_ink.coffee_web.interfaces.SimpleServletRequest;
import com.planet_ink.coffee_web.interfaces.SimpleServletResponse;
/*
Copyright 2012-2017 Bo Zimmerman
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/**
* Tests both simple get request, and is also a fun way to examine
* the cookies and form data posted to this servlet, as the data is
* returned in the headers.
* @author Bo Zimmerman
*
*/
public class HelloWorldServlet implements SimpleServlet
{
public static final String helloResponseStart="<html><body><h1>";
public static final String defaultResponseBody="Hello World!";
public static final String helloResponseEnd="</h1></body></html>";
public static final String helloResponse=helloResponseStart+defaultResponseBody+helloResponseEnd;
@Override
public void doGet(SimpleServletRequest request, SimpleServletResponse response)
{
try
{
response.setMimeType(MIMEType.All.html.getType());
response.getOutputStream().write(helloResponseStart.getBytes());
response.getOutputStream().write(defaultResponseBody.getBytes());
response.getOutputStream().write(helloResponseEnd.getBytes());
}
catch (final IOException e)
{
response.setStatusCode(500);
}
}
public void doDynamicPost(SimpleServletRequest request, SimpleServletResponse response)
{
try
{
response.setMimeType(MIMEType.All.html.getType());
response.getOutputStream().write(helloResponseStart.getBytes());
final InputStream in = request.getBody();
final ByteArrayOutputStream bout=new ByteArrayOutputStream();
int c;
while((c=in.read())>=0)
bout.write((byte)c);
String submitted=new String(bout.toByteArray(),Charset.forName("UTF-8"));
if(submitted.length()==0)
response.getOutputStream().write(defaultResponseBody.getBytes());
else
response.getOutputStream().write(submitted.getBytes());
response.getOutputStream().write(helloResponseEnd.getBytes());
}
catch (final IOException e)
{
response.setStatusCode(500);
}
}
@Override
public void doPost(SimpleServletRequest request, SimpleServletResponse response)
{
if(request.getHeader("X-DynamicPost")!=null)
this.doDynamicPost(request, response);
else
{
for(final String cookieName : request.getCookieNames())
response.setCookie(cookieName, request.getCookie(cookieName));
for(final String field : request.getUrlParameters())
response.setHeader("X-"+field, request.getUrlParameter(field));
response.setStatusCode(HTTPStatus.S204_NO_CONTENT.getStatusCode());
}
}
@Override
public void init()
{
}
@Override
public void service(HTTPMethod method, SimpleServletRequest request, SimpleServletResponse response)
{
if((method != HTTPMethod.POST) && (method!=HTTPMethod.GET))
response.setStatusCode(HTTPStatus.S405_METHOD_NOT_ALLOWED.getStatusCode());
}
}
|
package com.thalmic.myo.enums;
public enum XDirection {
X_DIRECTION_TOWARDS_WRIST,
X_DIRECTION_TOWARDS_ELBOW,
X_DIRECTION_UNKNOWN
}
|
/*
* Copyright 2013, Unitils.org
*
* 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.unitils.mock.core.proxy;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
/**
* @author Tim Ducheyne
*/
public class ArgumentGetValueTest {
private Argument<String> argument;
@Test
public void getValue() {
argument = new Argument<String>("value", null, String.class);
String value = argument.getValue();
assertEquals("value", value);
}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package opennlp.tools.chunker;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import opennlp.tools.util.Span;
/**
* Class for holding chunks for a single unit of text.
*/
public class ChunkSample implements Serializable {
private final List<String> sentence;
private final List<String> tags;
private final List<String> preds;
/**
* Initializes the current instance.
*
* @param sentence
* training sentence
* @param tags
* POS Tags for the sentence
* @param preds
* Chunk tags in B-* I-* notation
*/
public ChunkSample(String[] sentence, String[] tags, String[] preds) {
validateArguments(sentence.length, tags.length, preds.length);
this.sentence = Collections.unmodifiableList(new ArrayList<>(Arrays.asList(sentence)));
this.tags = Collections.unmodifiableList(new ArrayList<>(Arrays.asList(tags)));
this.preds = Collections.unmodifiableList(new ArrayList<>(Arrays.asList(preds)));
}
/**
* Initializes the current instance.
*
* @param sentence
* training sentence
* @param tags
* POS Tags for the sentence
* @param preds
* Chunk tags in B-* I-* notation
*/
public ChunkSample(List<String> sentence, List<String> tags, List<String> preds) {
validateArguments(sentence.size(), tags.size(), preds.size());
this.sentence = Collections.unmodifiableList(new ArrayList<>(sentence));
this.tags = Collections.unmodifiableList(new ArrayList<>(tags));
this.preds = Collections.unmodifiableList(new ArrayList<>(preds));
}
/** Gets the training sentence */
public String[] getSentence() {
return sentence.toArray(new String[sentence.size()]);
}
/** Gets the POS Tags for the sentence */
public String[] getTags() {
return tags.toArray(new String[tags.size()]);
}
/** Gets the Chunk tags in B-* I-* notation */
public String[] getPreds() {
return preds.toArray(new String[preds.size()]);
}
/** Gets the phrases as an array of spans */
public Span[] getPhrasesAsSpanList() {
return phrasesAsSpanList(getSentence(), getTags(), getPreds());
}
/**
* Static method to create arrays of spans of phrases
*
* @param aSentence
* training sentence
* @param aTags
* POS Tags for the sentence
* @param aPreds
* Chunk tags in B-* I-* notation
*
* @return the phrases as an array of spans
*/
public static Span[] phrasesAsSpanList(String[] aSentence, String[] aTags,
String[] aPreds) {
validateArguments(aSentence.length, aTags.length, aPreds.length);
// initialize with the list maximum size
List<Span> phrases = new ArrayList<>(aSentence.length);
String startTag = "";
int startIndex = 0;
boolean foundPhrase = false;
for (int ci = 0, cn = aPreds.length; ci < cn; ci++) {
String pred = aPreds[ci];
if (pred.startsWith("B-")
|| !pred.equals("I-" + startTag) && !pred.equals("O")) { // start
if (foundPhrase) { // handle the last
phrases.add(new Span(startIndex, ci, startTag));
}
startIndex = ci;
startTag = pred.substring(2);
foundPhrase = true;
} else if (pred.equals("I-" + startTag)) { // middle
// do nothing
} else if (foundPhrase) { // end
phrases.add(new Span(startIndex, ci, startTag));
foundPhrase = false;
startTag = "";
}
}
if (foundPhrase) { // leftover
phrases.add(new Span(startIndex, aPreds.length, startTag));
}
return phrases.toArray(new Span[phrases.size()]);
}
private static void validateArguments(int sentenceSize, int tagsSize, int predsSize)
throws IllegalArgumentException {
if (sentenceSize != tagsSize || tagsSize != predsSize)
throw new IllegalArgumentException(
"All arrays must have the same length: " +
"sentenceSize: " + sentenceSize +
", tagsSize: " + tagsSize +
", predsSize: " + predsSize + "!");
}
/**
* Creates a nice to read string for the phrases formatted as following: <br>
* <code>
* [NP Rockwell_NNP ] [VP said_VBD ] [NP the_DT agreement_NN ] [VP calls_VBZ ] [SBAR for_IN ]
* [NP it_PRP ] [VP to_TO supply_VB ] [NP 200_CD additional_JJ so-called_JJ shipsets_NNS ]
* [PP for_IN ] [NP the_DT planes_NNS ] ._.
* </code>
*
* @return a nice to read string representation of the chunk phases
*/
public String nicePrint() {
Span[] spans = getPhrasesAsSpanList();
StringBuilder result = new StringBuilder(" ");
for (int tokenIndex = 0; tokenIndex < sentence.size(); tokenIndex++) {
for (Span span : spans) {
if (span.getStart() == tokenIndex) {
result.append("[").append(span.getType()).append(" ");
}
if (span.getEnd() == tokenIndex) {
result.append("]").append(' ');
}
}
result.append(sentence.get(tokenIndex)).append("_").append(tags.get(tokenIndex)).append(' ');
}
if (sentence.size() > 1)
result.setLength(result.length() - 1);
for (Span span : spans) {
if (span.getEnd() == sentence.size()) {
result.append(']');
}
}
return result.toString();
}
@Override
public String toString() {
StringBuilder chunkString = new StringBuilder();
for (int ci = 0; ci < preds.size(); ci++) {
chunkString.append(sentence.get(ci)).append(" ").append(tags.get(ci))
.append(" ").append(preds.get(ci)).append("\n");
}
return chunkString.toString();
}
@Override
public int hashCode() {
return Objects.hash(Arrays.hashCode(getSentence()),
Arrays.hashCode(getTags()), Arrays.hashCode(getPreds()));
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj instanceof ChunkSample) {
ChunkSample a = (ChunkSample) obj;
return Arrays.equals(getSentence(), a.getSentence())
&& Arrays.equals(getTags(), a.getTags())
&& Arrays.equals(getPreds(), a.getPreds());
}
return false;
}
}
|
/*
* 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.gluedatabrew.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;
/**
* <p>
* Represents one run of a DataBrew job.
* </p>
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/databrew-2017-07-25/JobRun" target="_top">AWS API
* Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class JobRun implements Serializable, Cloneable, StructuredPojo {
/**
* <p>
* The number of times that DataBrew has attempted to run the job.
* </p>
*/
private Integer attempt;
/**
* <p>
* The date and time when the job completed processing.
* </p>
*/
private java.util.Date completedOn;
/**
* <p>
* The name of the dataset for the job to process.
* </p>
*/
private String datasetName;
/**
* <p>
* A message indicating an error (if any) that was encountered when the job ran.
* </p>
*/
private String errorMessage;
/**
* <p>
* The amount of time, in seconds, during which a job run consumed resources.
* </p>
*/
private Integer executionTime;
/**
* <p>
* The name of the job being processed during this run.
* </p>
*/
private String jobName;
/**
* <p>
* The unique identifier of the job run.
* </p>
*/
private String runId;
/**
* <p>
* The current state of the job run entity itself.
* </p>
*/
private String state;
/**
* <p>
* The current status of Amazon CloudWatch logging for the job run.
* </p>
*/
private String logSubscription;
/**
* <p>
* The name of an Amazon CloudWatch log group, where the job writes diagnostic messages when it runs.
* </p>
*/
private String logGroupName;
/**
* <p>
* One or more output artifacts from a job run.
* </p>
*/
private java.util.List<Output> outputs;
/**
* <p>
* The set of steps processed by the job.
* </p>
*/
private RecipeReference recipeReference;
/**
* <p>
* The Amazon Resource Name (ARN) of the user who initiated the job run.
* </p>
*/
private String startedBy;
/**
* <p>
* The date and time when the job run began.
* </p>
*/
private java.util.Date startedOn;
/**
* <p>
* The number of times that DataBrew has attempted to run the job.
* </p>
*
* @param attempt
* The number of times that DataBrew has attempted to run the job.
*/
public void setAttempt(Integer attempt) {
this.attempt = attempt;
}
/**
* <p>
* The number of times that DataBrew has attempted to run the job.
* </p>
*
* @return The number of times that DataBrew has attempted to run the job.
*/
public Integer getAttempt() {
return this.attempt;
}
/**
* <p>
* The number of times that DataBrew has attempted to run the job.
* </p>
*
* @param attempt
* The number of times that DataBrew has attempted to run the job.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public JobRun withAttempt(Integer attempt) {
setAttempt(attempt);
return this;
}
/**
* <p>
* The date and time when the job completed processing.
* </p>
*
* @param completedOn
* The date and time when the job completed processing.
*/
public void setCompletedOn(java.util.Date completedOn) {
this.completedOn = completedOn;
}
/**
* <p>
* The date and time when the job completed processing.
* </p>
*
* @return The date and time when the job completed processing.
*/
public java.util.Date getCompletedOn() {
return this.completedOn;
}
/**
* <p>
* The date and time when the job completed processing.
* </p>
*
* @param completedOn
* The date and time when the job completed processing.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public JobRun withCompletedOn(java.util.Date completedOn) {
setCompletedOn(completedOn);
return this;
}
/**
* <p>
* The name of the dataset for the job to process.
* </p>
*
* @param datasetName
* The name of the dataset for the job to process.
*/
public void setDatasetName(String datasetName) {
this.datasetName = datasetName;
}
/**
* <p>
* The name of the dataset for the job to process.
* </p>
*
* @return The name of the dataset for the job to process.
*/
public String getDatasetName() {
return this.datasetName;
}
/**
* <p>
* The name of the dataset for the job to process.
* </p>
*
* @param datasetName
* The name of the dataset for the job to process.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public JobRun withDatasetName(String datasetName) {
setDatasetName(datasetName);
return this;
}
/**
* <p>
* A message indicating an error (if any) that was encountered when the job ran.
* </p>
*
* @param errorMessage
* A message indicating an error (if any) that was encountered when the job ran.
*/
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
/**
* <p>
* A message indicating an error (if any) that was encountered when the job ran.
* </p>
*
* @return A message indicating an error (if any) that was encountered when the job ran.
*/
public String getErrorMessage() {
return this.errorMessage;
}
/**
* <p>
* A message indicating an error (if any) that was encountered when the job ran.
* </p>
*
* @param errorMessage
* A message indicating an error (if any) that was encountered when the job ran.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public JobRun withErrorMessage(String errorMessage) {
setErrorMessage(errorMessage);
return this;
}
/**
* <p>
* The amount of time, in seconds, during which a job run consumed resources.
* </p>
*
* @param executionTime
* The amount of time, in seconds, during which a job run consumed resources.
*/
public void setExecutionTime(Integer executionTime) {
this.executionTime = executionTime;
}
/**
* <p>
* The amount of time, in seconds, during which a job run consumed resources.
* </p>
*
* @return The amount of time, in seconds, during which a job run consumed resources.
*/
public Integer getExecutionTime() {
return this.executionTime;
}
/**
* <p>
* The amount of time, in seconds, during which a job run consumed resources.
* </p>
*
* @param executionTime
* The amount of time, in seconds, during which a job run consumed resources.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public JobRun withExecutionTime(Integer executionTime) {
setExecutionTime(executionTime);
return this;
}
/**
* <p>
* The name of the job being processed during this run.
* </p>
*
* @param jobName
* The name of the job being processed during this run.
*/
public void setJobName(String jobName) {
this.jobName = jobName;
}
/**
* <p>
* The name of the job being processed during this run.
* </p>
*
* @return The name of the job being processed during this run.
*/
public String getJobName() {
return this.jobName;
}
/**
* <p>
* The name of the job being processed during this run.
* </p>
*
* @param jobName
* The name of the job being processed during this run.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public JobRun withJobName(String jobName) {
setJobName(jobName);
return this;
}
/**
* <p>
* The unique identifier of the job run.
* </p>
*
* @param runId
* The unique identifier of the job run.
*/
public void setRunId(String runId) {
this.runId = runId;
}
/**
* <p>
* The unique identifier of the job run.
* </p>
*
* @return The unique identifier of the job run.
*/
public String getRunId() {
return this.runId;
}
/**
* <p>
* The unique identifier of the job run.
* </p>
*
* @param runId
* The unique identifier of the job run.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public JobRun withRunId(String runId) {
setRunId(runId);
return this;
}
/**
* <p>
* The current state of the job run entity itself.
* </p>
*
* @param state
* The current state of the job run entity itself.
* @see JobRunState
*/
public void setState(String state) {
this.state = state;
}
/**
* <p>
* The current state of the job run entity itself.
* </p>
*
* @return The current state of the job run entity itself.
* @see JobRunState
*/
public String getState() {
return this.state;
}
/**
* <p>
* The current state of the job run entity itself.
* </p>
*
* @param state
* The current state of the job run entity itself.
* @return Returns a reference to this object so that method calls can be chained together.
* @see JobRunState
*/
public JobRun withState(String state) {
setState(state);
return this;
}
/**
* <p>
* The current state of the job run entity itself.
* </p>
*
* @param state
* The current state of the job run entity itself.
* @return Returns a reference to this object so that method calls can be chained together.
* @see JobRunState
*/
public JobRun withState(JobRunState state) {
this.state = state.toString();
return this;
}
/**
* <p>
* The current status of Amazon CloudWatch logging for the job run.
* </p>
*
* @param logSubscription
* The current status of Amazon CloudWatch logging for the job run.
* @see LogSubscription
*/
public void setLogSubscription(String logSubscription) {
this.logSubscription = logSubscription;
}
/**
* <p>
* The current status of Amazon CloudWatch logging for the job run.
* </p>
*
* @return The current status of Amazon CloudWatch logging for the job run.
* @see LogSubscription
*/
public String getLogSubscription() {
return this.logSubscription;
}
/**
* <p>
* The current status of Amazon CloudWatch logging for the job run.
* </p>
*
* @param logSubscription
* The current status of Amazon CloudWatch logging for the job run.
* @return Returns a reference to this object so that method calls can be chained together.
* @see LogSubscription
*/
public JobRun withLogSubscription(String logSubscription) {
setLogSubscription(logSubscription);
return this;
}
/**
* <p>
* The current status of Amazon CloudWatch logging for the job run.
* </p>
*
* @param logSubscription
* The current status of Amazon CloudWatch logging for the job run.
* @return Returns a reference to this object so that method calls can be chained together.
* @see LogSubscription
*/
public JobRun withLogSubscription(LogSubscription logSubscription) {
this.logSubscription = logSubscription.toString();
return this;
}
/**
* <p>
* The name of an Amazon CloudWatch log group, where the job writes diagnostic messages when it runs.
* </p>
*
* @param logGroupName
* The name of an Amazon CloudWatch log group, where the job writes diagnostic messages when it runs.
*/
public void setLogGroupName(String logGroupName) {
this.logGroupName = logGroupName;
}
/**
* <p>
* The name of an Amazon CloudWatch log group, where the job writes diagnostic messages when it runs.
* </p>
*
* @return The name of an Amazon CloudWatch log group, where the job writes diagnostic messages when it runs.
*/
public String getLogGroupName() {
return this.logGroupName;
}
/**
* <p>
* The name of an Amazon CloudWatch log group, where the job writes diagnostic messages when it runs.
* </p>
*
* @param logGroupName
* The name of an Amazon CloudWatch log group, where the job writes diagnostic messages when it runs.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public JobRun withLogGroupName(String logGroupName) {
setLogGroupName(logGroupName);
return this;
}
/**
* <p>
* One or more output artifacts from a job run.
* </p>
*
* @return One or more output artifacts from a job run.
*/
public java.util.List<Output> getOutputs() {
return outputs;
}
/**
* <p>
* One or more output artifacts from a job run.
* </p>
*
* @param outputs
* One or more output artifacts from a job run.
*/
public void setOutputs(java.util.Collection<Output> outputs) {
if (outputs == null) {
this.outputs = null;
return;
}
this.outputs = new java.util.ArrayList<Output>(outputs);
}
/**
* <p>
* One or more output artifacts from a job run.
* </p>
* <p>
* <b>NOTE:</b> This method appends the values to the existing list (if any). Use
* {@link #setOutputs(java.util.Collection)} or {@link #withOutputs(java.util.Collection)} if you want to override
* the existing values.
* </p>
*
* @param outputs
* One or more output artifacts from a job run.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public JobRun withOutputs(Output... outputs) {
if (this.outputs == null) {
setOutputs(new java.util.ArrayList<Output>(outputs.length));
}
for (Output ele : outputs) {
this.outputs.add(ele);
}
return this;
}
/**
* <p>
* One or more output artifacts from a job run.
* </p>
*
* @param outputs
* One or more output artifacts from a job run.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public JobRun withOutputs(java.util.Collection<Output> outputs) {
setOutputs(outputs);
return this;
}
/**
* <p>
* The set of steps processed by the job.
* </p>
*
* @param recipeReference
* The set of steps processed by the job.
*/
public void setRecipeReference(RecipeReference recipeReference) {
this.recipeReference = recipeReference;
}
/**
* <p>
* The set of steps processed by the job.
* </p>
*
* @return The set of steps processed by the job.
*/
public RecipeReference getRecipeReference() {
return this.recipeReference;
}
/**
* <p>
* The set of steps processed by the job.
* </p>
*
* @param recipeReference
* The set of steps processed by the job.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public JobRun withRecipeReference(RecipeReference recipeReference) {
setRecipeReference(recipeReference);
return this;
}
/**
* <p>
* The Amazon Resource Name (ARN) of the user who initiated the job run.
* </p>
*
* @param startedBy
* The Amazon Resource Name (ARN) of the user who initiated the job run.
*/
public void setStartedBy(String startedBy) {
this.startedBy = startedBy;
}
/**
* <p>
* The Amazon Resource Name (ARN) of the user who initiated the job run.
* </p>
*
* @return The Amazon Resource Name (ARN) of the user who initiated the job run.
*/
public String getStartedBy() {
return this.startedBy;
}
/**
* <p>
* The Amazon Resource Name (ARN) of the user who initiated the job run.
* </p>
*
* @param startedBy
* The Amazon Resource Name (ARN) of the user who initiated the job run.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public JobRun withStartedBy(String startedBy) {
setStartedBy(startedBy);
return this;
}
/**
* <p>
* The date and time when the job run began.
* </p>
*
* @param startedOn
* The date and time when the job run began.
*/
public void setStartedOn(java.util.Date startedOn) {
this.startedOn = startedOn;
}
/**
* <p>
* The date and time when the job run began.
* </p>
*
* @return The date and time when the job run began.
*/
public java.util.Date getStartedOn() {
return this.startedOn;
}
/**
* <p>
* The date and time when the job run began.
* </p>
*
* @param startedOn
* The date and time when the job run began.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public JobRun withStartedOn(java.util.Date startedOn) {
setStartedOn(startedOn);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getAttempt() != null)
sb.append("Attempt: ").append(getAttempt()).append(",");
if (getCompletedOn() != null)
sb.append("CompletedOn: ").append(getCompletedOn()).append(",");
if (getDatasetName() != null)
sb.append("DatasetName: ").append(getDatasetName()).append(",");
if (getErrorMessage() != null)
sb.append("ErrorMessage: ").append(getErrorMessage()).append(",");
if (getExecutionTime() != null)
sb.append("ExecutionTime: ").append(getExecutionTime()).append(",");
if (getJobName() != null)
sb.append("JobName: ").append(getJobName()).append(",");
if (getRunId() != null)
sb.append("RunId: ").append(getRunId()).append(",");
if (getState() != null)
sb.append("State: ").append(getState()).append(",");
if (getLogSubscription() != null)
sb.append("LogSubscription: ").append(getLogSubscription()).append(",");
if (getLogGroupName() != null)
sb.append("LogGroupName: ").append(getLogGroupName()).append(",");
if (getOutputs() != null)
sb.append("Outputs: ").append(getOutputs()).append(",");
if (getRecipeReference() != null)
sb.append("RecipeReference: ").append(getRecipeReference()).append(",");
if (getStartedBy() != null)
sb.append("StartedBy: ").append(getStartedBy()).append(",");
if (getStartedOn() != null)
sb.append("StartedOn: ").append(getStartedOn());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof JobRun == false)
return false;
JobRun other = (JobRun) obj;
if (other.getAttempt() == null ^ this.getAttempt() == null)
return false;
if (other.getAttempt() != null && other.getAttempt().equals(this.getAttempt()) == false)
return false;
if (other.getCompletedOn() == null ^ this.getCompletedOn() == null)
return false;
if (other.getCompletedOn() != null && other.getCompletedOn().equals(this.getCompletedOn()) == false)
return false;
if (other.getDatasetName() == null ^ this.getDatasetName() == null)
return false;
if (other.getDatasetName() != null && other.getDatasetName().equals(this.getDatasetName()) == false)
return false;
if (other.getErrorMessage() == null ^ this.getErrorMessage() == null)
return false;
if (other.getErrorMessage() != null && other.getErrorMessage().equals(this.getErrorMessage()) == false)
return false;
if (other.getExecutionTime() == null ^ this.getExecutionTime() == null)
return false;
if (other.getExecutionTime() != null && other.getExecutionTime().equals(this.getExecutionTime()) == false)
return false;
if (other.getJobName() == null ^ this.getJobName() == null)
return false;
if (other.getJobName() != null && other.getJobName().equals(this.getJobName()) == false)
return false;
if (other.getRunId() == null ^ this.getRunId() == null)
return false;
if (other.getRunId() != null && other.getRunId().equals(this.getRunId()) == false)
return false;
if (other.getState() == null ^ this.getState() == null)
return false;
if (other.getState() != null && other.getState().equals(this.getState()) == false)
return false;
if (other.getLogSubscription() == null ^ this.getLogSubscription() == null)
return false;
if (other.getLogSubscription() != null && other.getLogSubscription().equals(this.getLogSubscription()) == false)
return false;
if (other.getLogGroupName() == null ^ this.getLogGroupName() == null)
return false;
if (other.getLogGroupName() != null && other.getLogGroupName().equals(this.getLogGroupName()) == false)
return false;
if (other.getOutputs() == null ^ this.getOutputs() == null)
return false;
if (other.getOutputs() != null && other.getOutputs().equals(this.getOutputs()) == false)
return false;
if (other.getRecipeReference() == null ^ this.getRecipeReference() == null)
return false;
if (other.getRecipeReference() != null && other.getRecipeReference().equals(this.getRecipeReference()) == false)
return false;
if (other.getStartedBy() == null ^ this.getStartedBy() == null)
return false;
if (other.getStartedBy() != null && other.getStartedBy().equals(this.getStartedBy()) == false)
return false;
if (other.getStartedOn() == null ^ this.getStartedOn() == null)
return false;
if (other.getStartedOn() != null && other.getStartedOn().equals(this.getStartedOn()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getAttempt() == null) ? 0 : getAttempt().hashCode());
hashCode = prime * hashCode + ((getCompletedOn() == null) ? 0 : getCompletedOn().hashCode());
hashCode = prime * hashCode + ((getDatasetName() == null) ? 0 : getDatasetName().hashCode());
hashCode = prime * hashCode + ((getErrorMessage() == null) ? 0 : getErrorMessage().hashCode());
hashCode = prime * hashCode + ((getExecutionTime() == null) ? 0 : getExecutionTime().hashCode());
hashCode = prime * hashCode + ((getJobName() == null) ? 0 : getJobName().hashCode());
hashCode = prime * hashCode + ((getRunId() == null) ? 0 : getRunId().hashCode());
hashCode = prime * hashCode + ((getState() == null) ? 0 : getState().hashCode());
hashCode = prime * hashCode + ((getLogSubscription() == null) ? 0 : getLogSubscription().hashCode());
hashCode = prime * hashCode + ((getLogGroupName() == null) ? 0 : getLogGroupName().hashCode());
hashCode = prime * hashCode + ((getOutputs() == null) ? 0 : getOutputs().hashCode());
hashCode = prime * hashCode + ((getRecipeReference() == null) ? 0 : getRecipeReference().hashCode());
hashCode = prime * hashCode + ((getStartedBy() == null) ? 0 : getStartedBy().hashCode());
hashCode = prime * hashCode + ((getStartedOn() == null) ? 0 : getStartedOn().hashCode());
return hashCode;
}
@Override
public JobRun clone() {
try {
return (JobRun) 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.gluedatabrew.model.transform.JobRunMarshaller.getInstance().marshall(this, protocolMarshaller);
}
}
|
/*
* Copyright (C) 2006 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.opensearch.common.inject.internal;
/**
* String utilities.
*
* @author crazybob@google.com (Bob Lee)
*/
public class Strings {
private Strings() {
}
/**
* Returns a string that is equivalent to the specified string with its
* first character converted to uppercase as by {@link String#toUpperCase}.
* The returned string will have the same value as the specified string if
* its first character is non-alphabetic, if its first character is already
* uppercase, or if the specified string is of length 0.
* <p>
* For example:
* <pre>
* capitalize("foo bar").equals("Foo bar");
* capitalize("2b or not 2b").equals("2b or not 2b")
* capitalize("Foo bar").equals("Foo bar");
* capitalize("").equals("");
* </pre>
*
* @param s the string whose first character is to be uppercased
* @return a string equivalent to {@code s} with its first character
* converted to uppercase
* @throws NullPointerException if {@code s} is null
*/
public static String capitalize(String s) {
if (s.length() == 0) {
return s;
}
char first = s.charAt(0);
char capitalized = Character.toUpperCase(first);
return (first == capitalized)
? s
: capitalized + s.substring(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.apache.doris.backup;
import org.apache.doris.analysis.StorageBackend;
import org.apache.doris.catalog.Catalog;
import org.apache.doris.catalog.FsBroker;
import org.apache.doris.common.AnalysisException;
import org.apache.doris.common.ClientPool;
import org.apache.doris.common.Pair;
import org.apache.doris.common.util.BrokerUtil;
import org.apache.doris.service.FrontendOptions;
import org.apache.doris.thrift.TBrokerCheckPathExistRequest;
import org.apache.doris.thrift.TBrokerCheckPathExistResponse;
import org.apache.doris.thrift.TBrokerCloseReaderRequest;
import org.apache.doris.thrift.TBrokerCloseWriterRequest;
import org.apache.doris.thrift.TBrokerDeletePathRequest;
import org.apache.doris.thrift.TBrokerFD;
import org.apache.doris.thrift.TBrokerFileStatus;
import org.apache.doris.thrift.TBrokerListPathRequest;
import org.apache.doris.thrift.TBrokerListResponse;
import org.apache.doris.thrift.TBrokerOpenMode;
import org.apache.doris.thrift.TBrokerOpenReaderRequest;
import org.apache.doris.thrift.TBrokerOpenReaderResponse;
import org.apache.doris.thrift.TBrokerOpenWriterRequest;
import org.apache.doris.thrift.TBrokerOpenWriterResponse;
import org.apache.doris.thrift.TBrokerOperationStatus;
import org.apache.doris.thrift.TBrokerOperationStatusCode;
import org.apache.doris.thrift.TBrokerPReadRequest;
import org.apache.doris.thrift.TBrokerPWriteRequest;
import org.apache.doris.thrift.TBrokerReadResponse;
import org.apache.doris.thrift.TBrokerRenamePathRequest;
import org.apache.doris.thrift.TBrokerVersion;
import org.apache.doris.thrift.TNetworkAddress;
import org.apache.doris.thrift.TPaloBrokerService;
import com.google.common.base.Preconditions;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.thrift.TException;
import org.apache.thrift.transport.TTransportException;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileVisitOption;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
public class BrokerStorage extends BlobStorage {
private static final Logger LOG = LogManager.getLogger(BrokerStorage.class);
public BrokerStorage(String brokerName, Map<String, String> properties) {
setName(brokerName);
setProperties(properties);
setType(StorageBackend.StorageType.BROKER);
}
public String getBrokerName() {
return getName();
}
@Override
public Status downloadWithFileSize(String remoteFilePath, String localFilePath, long fileSize) {
LOG.debug("download from {} to {}, file size: {}.", remoteFilePath, localFilePath, fileSize);
long start = System.currentTimeMillis();
// 1. get a proper broker
Pair<TPaloBrokerService.Client, TNetworkAddress> pair = getBroker();
if (pair == null) {
return new Status(Status.ErrCode.COMMON_ERROR, "failed to get broker client");
}
TPaloBrokerService.Client client = pair.first;
TNetworkAddress address = pair.second;
// 2. open file reader with broker
TBrokerFD fd;
try {
TBrokerOpenReaderRequest req = new TBrokerOpenReaderRequest(TBrokerVersion.VERSION_ONE, remoteFilePath,
0, clientId(), getProperties());
TBrokerOpenReaderResponse rep = client.openReader(req);
TBrokerOperationStatus opst = rep.getOpStatus();
if (opst.getStatusCode() != TBrokerOperationStatusCode.OK) {
return new Status(Status.ErrCode.COMMON_ERROR,
"failed to open reader on broker " + BrokerUtil.printBroker(getName(), address)
+ " for file: " + remoteFilePath + ". msg: " + opst.getMessage());
}
fd = rep.getFd();
LOG.info("finished to open reader. fd: {}. download {} to {}.",
fd, remoteFilePath, localFilePath);
} catch (TException e) {
return new Status(Status.ErrCode.COMMON_ERROR,
"failed to open reader on broker " + BrokerUtil.printBroker(getName(), address)
+ " for file: " + remoteFilePath + ". msg: " + e.getMessage());
}
Preconditions.checkNotNull(fd);
// 3. delete local file if exist
File localFile = new File(localFilePath);
if (localFile.exists()) {
try {
Files.walk(Paths.get(localFilePath), FileVisitOption.FOLLOW_LINKS)
.sorted(Comparator.reverseOrder()).map(Path::toFile).forEach(File::delete);
} catch (IOException e) {
return new Status(Status.ErrCode.COMMON_ERROR, "failed to delete exist local file: " + localFilePath);
}
}
// 4. create local file
Status status = Status.OK;
try {
if (!localFile.createNewFile()) {
return new Status(Status.ErrCode.COMMON_ERROR, "failed to create local file: " + localFilePath);
}
} catch (IOException e) {
return new Status(Status.ErrCode.COMMON_ERROR, "failed to create local file: "
+ localFilePath + ", msg: " + e.getMessage());
}
// 5. read remote file with broker and write to local
String lastErrMsg = null;
try (BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(localFile))) {
final long bufSize = 1024 * 1024; // 1MB
long leftSize = fileSize;
long readOffset = 0;
while (leftSize > 0) {
long readLen = Math.min(leftSize, bufSize);
TBrokerReadResponse rep = null;
// We only retry if we encounter a timeout thrift exception.
int tryTimes = 0;
while (tryTimes < 3) {
try {
TBrokerPReadRequest req = new TBrokerPReadRequest(TBrokerVersion.VERSION_ONE,
fd, readOffset, readLen);
rep = client.pread(req);
if (rep.getOpStatus().getStatusCode() != TBrokerOperationStatusCode.OK) {
// pread return failure.
lastErrMsg = String.format("failed to read via broker %s. "
+ "current read offset: %d, read length: %d,"
+ " file size: %d, file: %s, err code: %d, msg: %s",
BrokerUtil.printBroker(getName(), address),
readOffset, readLen, fileSize,
remoteFilePath, rep.getOpStatus().getStatusCode().getValue(),
rep.getOpStatus().getMessage());
LOG.warn(lastErrMsg);
status = new Status(Status.ErrCode.COMMON_ERROR, lastErrMsg);
}
if (rep.opStatus.statusCode != TBrokerOperationStatusCode.END_OF_FILE) {
LOG.debug("download. readLen: {}, read data len: {}, left size:{}. total size: {}",
readLen, rep.getData().length, leftSize, fileSize);
} else {
LOG.debug("read eof: " + remoteFilePath);
}
break;
} catch (TTransportException e) {
if (e.getType() == TTransportException.TIMED_OUT) {
// we only retry when we encounter timeout exception.
lastErrMsg = String.format("failed to read via broker %s. "
+ "current read offset: %d, read length: %d,"
+ " file size: %d, file: %s, timeout.",
BrokerUtil.printBroker(getName(), address),
readOffset, readLen, fileSize,
remoteFilePath);
tryTimes++;
continue;
}
lastErrMsg = String.format("failed to read via broker %s. "
+ "current read offset: %d, read length: %d,"
+ " file size: %d, file: %s. msg: %s",
BrokerUtil.printBroker(getName(), address),
readOffset, readLen, fileSize,
remoteFilePath, e.getMessage());
LOG.warn(lastErrMsg);
status = new Status(Status.ErrCode.COMMON_ERROR, lastErrMsg);
break;
} catch (TException e) {
lastErrMsg = String.format("failed to read via broker %s. "
+ "current read offset: %d, read length: %d,"
+ " file size: %d, file: %s. msg: %s",
BrokerUtil.printBroker(getName(), address),
readOffset, readLen, fileSize,
remoteFilePath, e.getMessage());
LOG.warn(lastErrMsg);
status = new Status(Status.ErrCode.COMMON_ERROR, lastErrMsg);
break;
}
} // end of retry loop
if (status.ok() && tryTimes < 3) {
// read succeed, write to local file
Preconditions.checkNotNull(rep);
// NOTICE(cmy): Sometimes the actual read length does not equal to the expected read length,
// even if the broker's read buffer size is large enough.
// I don't know why, but have to adapt to it.
if (rep.getData().length != readLen) {
LOG.warn("the actual read length does not equal to "
+ "the expected read length: {} vs. {}, file: {}, broker: {}",
rep.getData().length, readLen, remoteFilePath,
BrokerUtil.printBroker(getName(), address));
}
out.write(rep.getData());
readOffset += rep.getData().length;
leftSize -= rep.getData().length;
} else {
status = new Status(Status.ErrCode.COMMON_ERROR, lastErrMsg);
break;
}
} // end of reading remote file
} catch (IOException e) {
return new Status(Status.ErrCode.COMMON_ERROR, "Got exception: " + e.getMessage() + ", broker: "
+ BrokerUtil.printBroker(getName(), address));
} finally {
// close broker reader
Status closeStatus = closeReader(client, address, fd);
if (!closeStatus.ok()) {
LOG.warn(closeStatus.getErrMsg());
if (status.ok()) {
// we return close write error only if no other error has been encountered.
status = closeStatus;
}
ClientPool.brokerPool.invalidateObject(address, client);
} else {
ClientPool.brokerPool.returnObject(address, client);
}
}
LOG.info("finished to download from {} to {} with size: {}. cost {} ms",
remoteFilePath, localFilePath, fileSize, (System.currentTimeMillis() - start));
return status;
}
// directly upload the content to remote file
@Override
public Status directUpload(String content, String remoteFile) {
// 1. get a proper broker
Pair<TPaloBrokerService.Client, TNetworkAddress> pair = getBroker();
if (pair == null) {
return new Status(Status.ErrCode.COMMON_ERROR, "failed to get broker client");
}
TPaloBrokerService.Client client = pair.first;
TNetworkAddress address = pair.second;
TBrokerFD fd = new TBrokerFD();
Status status = Status.OK;
try {
// 2. open file writer with broker
status = openWriter(client, address, remoteFile, fd);
if (!status.ok()) {
return status;
}
// 3. write content
try {
ByteBuffer bb = ByteBuffer.wrap(content.getBytes(StandardCharsets.UTF_8));
TBrokerPWriteRequest req = new TBrokerPWriteRequest(TBrokerVersion.VERSION_ONE, fd, 0, bb);
TBrokerOperationStatus opst = client.pwrite(req);
if (opst.getStatusCode() != TBrokerOperationStatusCode.OK) {
// pwrite return failure.
status = new Status(Status.ErrCode.COMMON_ERROR, "write failed: " + opst.getMessage()
+ ", broker: " + BrokerUtil.printBroker(getName(), address));
}
} catch (TException e) {
status = new Status(Status.ErrCode.BAD_CONNECTION, "write exception: " + e.getMessage()
+ ", broker: " + BrokerUtil.printBroker(getName(), address));
}
} finally {
Status closeStatus = closeWriter(client, address, fd);
if (closeStatus.getErrCode() == Status.ErrCode.BAD_CONNECTION
|| status.getErrCode() == Status.ErrCode.BAD_CONNECTION) {
ClientPool.brokerPool.invalidateObject(address, client);
} else {
ClientPool.brokerPool.returnObject(address, client);
}
}
return status;
}
@Override
public Status upload(String localPath, String remotePath) {
long start = System.currentTimeMillis();
// 1. get a proper broker
Pair<TPaloBrokerService.Client, TNetworkAddress> pair = getBroker();
if (pair == null) {
return new Status(Status.ErrCode.COMMON_ERROR, "failed to get broker client");
}
TPaloBrokerService.Client client = pair.first;
TNetworkAddress address = pair.second;
// 2. open file write with broker
TBrokerFD fd = new TBrokerFD();
Status status = openWriter(client, address, remotePath, fd);
if (!status.ok()) {
return status;
}
// 3. read local file and write to remote with broker
File localFile = new File(localPath);
long fileLength = localFile.length();
byte[] readBuf = new byte[1024];
try (BufferedInputStream in = new BufferedInputStream(new FileInputStream(localFile))) {
// save the last err msg
String lastErrMsg = null;
// save the current write offset of remote file
long writeOffset = 0;
// read local file, 1MB at a time
int bytesRead;
while ((bytesRead = in.read(readBuf)) != -1) {
ByteBuffer bb = ByteBuffer.wrap(readBuf, 0, bytesRead);
// We only retry if we encounter a timeout thrift exception.
int tryTimes = 0;
while (tryTimes < 3) {
try {
TBrokerPWriteRequest req
= new TBrokerPWriteRequest(TBrokerVersion.VERSION_ONE, fd, writeOffset, bb);
TBrokerOperationStatus opst = client.pwrite(req);
if (opst.getStatusCode() != TBrokerOperationStatusCode.OK) {
// pwrite return failure.
lastErrMsg = String.format("failed to write via broker %s. "
+ "current write offset: %d, write length: %d,"
+ " file length: %d, file: %s, err code: %d, msg: %s",
BrokerUtil.printBroker(getName(), address),
writeOffset, bytesRead, fileLength,
remotePath, opst.getStatusCode().getValue(), opst.getMessage());
LOG.warn(lastErrMsg);
status = new Status(Status.ErrCode.COMMON_ERROR, lastErrMsg);
}
break;
} catch (TTransportException e) {
if (e.getType() == TTransportException.TIMED_OUT) {
// we only retry when we encounter timeout exception.
lastErrMsg = String.format("failed to write via broker %s. "
+ "current write offset: %d, write length: %d,"
+ " file length: %d, file: %s. timeout",
BrokerUtil.printBroker(getName(), address),
writeOffset, bytesRead, fileLength,
remotePath);
tryTimes++;
continue;
}
lastErrMsg = String.format("failed to write via broker %s. "
+ "current write offset: %d, write length: %d,"
+ " file length: %d, file: %s. encounter TTransportException: %s",
BrokerUtil.printBroker(getName(), address),
writeOffset, bytesRead, fileLength,
remotePath, e.getMessage());
LOG.warn(lastErrMsg, e);
status = new Status(Status.ErrCode.COMMON_ERROR, lastErrMsg);
break;
} catch (TException e) {
lastErrMsg = String.format("failed to write via broker %s. "
+ "current write offset: %d, write length: %d,"
+ " file length: %d, file: %s. encounter TException: %s",
BrokerUtil.printBroker(getName(), address),
writeOffset, bytesRead, fileLength,
remotePath, e.getMessage());
LOG.warn(lastErrMsg, e);
status = new Status(Status.ErrCode.COMMON_ERROR, lastErrMsg);
break;
}
}
if (status.ok() && tryTimes < 3) {
// write succeed, update current write offset
writeOffset += bytesRead;
} else {
status = new Status(Status.ErrCode.COMMON_ERROR, lastErrMsg);
break;
}
} // end of read local file loop
} catch (FileNotFoundException e1) {
return new Status(Status.ErrCode.COMMON_ERROR, "encounter file not found exception: " + e1.getMessage()
+ ", broker: " + BrokerUtil.printBroker(getName(), address));
} catch (IOException e1) {
return new Status(Status.ErrCode.COMMON_ERROR, "encounter io exception: " + e1.getMessage()
+ ", broker: " + BrokerUtil.printBroker(getName(), address));
} finally {
// close write
Status closeStatus = closeWriter(client, address, fd);
if (!closeStatus.ok()) {
LOG.warn(closeStatus.getErrMsg());
if (status.ok()) {
// we return close write error only if no other error has been encountered.
status = closeStatus;
}
ClientPool.brokerPool.invalidateObject(address, client);
} else {
ClientPool.brokerPool.returnObject(address, client);
}
}
if (status.ok()) {
LOG.info("finished to upload {} to remote path {}. cost: {} ms",
localPath, remotePath, (System.currentTimeMillis() - start));
}
return status;
}
@Override
public Status rename(String origFilePath, String destFilePath) {
long start = System.currentTimeMillis();
// 1. get a proper broker
Pair<TPaloBrokerService.Client, TNetworkAddress> pair = getBroker();
if (pair == null) {
return new Status(Status.ErrCode.COMMON_ERROR, "failed to get broker client");
}
TPaloBrokerService.Client client = pair.first;
TNetworkAddress address = pair.second;
// 2. rename
boolean needReturn = true;
try {
TBrokerRenamePathRequest req = new TBrokerRenamePathRequest(TBrokerVersion.VERSION_ONE,
origFilePath, destFilePath, getProperties());
TBrokerOperationStatus ost = client.renamePath(req);
if (ost.getStatusCode() != TBrokerOperationStatusCode.OK) {
return new Status(Status.ErrCode.COMMON_ERROR,
"failed to rename " + origFilePath + " to " + destFilePath + ", msg: " + ost.getMessage()
+ ", broker: " + BrokerUtil.printBroker(getName(), address));
}
} catch (TException e) {
needReturn = false;
return new Status(Status.ErrCode.COMMON_ERROR,
"failed to rename " + origFilePath + " to " + destFilePath + ", msg: " + e.getMessage()
+ ", broker: " + BrokerUtil.printBroker(getName(), address));
} finally {
if (needReturn) {
ClientPool.brokerPool.returnObject(address, client);
} else {
ClientPool.brokerPool.invalidateObject(address, client);
}
}
LOG.info("finished to rename {} to {}. cost: {} ms",
origFilePath, destFilePath, (System.currentTimeMillis() - start));
return Status.OK;
}
@Override
public Status delete(String remotePath) {
// get a proper broker
Pair<TPaloBrokerService.Client, TNetworkAddress> pair = getBroker();
if (pair == null) {
return new Status(Status.ErrCode.COMMON_ERROR, "failed to get broker client");
}
TPaloBrokerService.Client client = pair.first;
TNetworkAddress address = pair.second;
// delete
boolean needReturn = true;
try {
TBrokerDeletePathRequest req = new TBrokerDeletePathRequest(TBrokerVersion.VERSION_ONE,
remotePath, getProperties());
TBrokerOperationStatus opst = client.deletePath(req);
if (opst.getStatusCode() != TBrokerOperationStatusCode.OK) {
return new Status(Status.ErrCode.COMMON_ERROR,
"failed to delete remote path: " + remotePath + ". msg: " + opst.getMessage()
+ ", broker: " + BrokerUtil.printBroker(getName(), address));
}
LOG.info("finished to delete remote path {}.", remotePath);
} catch (TException e) {
needReturn = false;
return new Status(Status.ErrCode.COMMON_ERROR,
"failed to delete remote path: " + remotePath + ". msg: " + e.getMessage()
+ ", broker: " + BrokerUtil.printBroker(getName(), address));
} finally {
if (needReturn) {
ClientPool.brokerPool.returnObject(address, client);
} else {
ClientPool.brokerPool.invalidateObject(address, client);
}
}
return Status.OK;
}
// List files in remotePath
// The remote file name will only contains file name only(Not full path)
@Override
public Status list(String remotePath, List<RemoteFile> result) {
// get a proper broker
Pair<TPaloBrokerService.Client, TNetworkAddress> pair = getBroker();
if (pair == null) {
return new Status(Status.ErrCode.COMMON_ERROR, "failed to get broker client");
}
TPaloBrokerService.Client client = pair.first;
TNetworkAddress address = pair.second;
// list
boolean needReturn = true;
try {
TBrokerListPathRequest req = new TBrokerListPathRequest(TBrokerVersion.VERSION_ONE, remotePath,
false /* not recursive */, getProperties());
req.setFileNameOnly(true);
TBrokerListResponse rep = client.listPath(req);
TBrokerOperationStatus opst = rep.getOpStatus();
if (opst.getStatusCode() != TBrokerOperationStatusCode.OK) {
return new Status(Status.ErrCode.COMMON_ERROR,
"failed to list remote path: " + remotePath + ". msg: " + opst.getMessage()
+ ", broker: " + BrokerUtil.printBroker(getName(), address));
}
List<TBrokerFileStatus> fileStatus = rep.getFiles();
for (TBrokerFileStatus tFile : fileStatus) {
RemoteFile file = new RemoteFile(tFile.path, !tFile.isDir, tFile.size);
result.add(file);
}
LOG.info("finished to list remote path {}. get files: {}", remotePath, result);
} catch (TException e) {
needReturn = false;
return new Status(Status.ErrCode.COMMON_ERROR,
"failed to list remote path: " + remotePath + ". msg: " + e.getMessage()
+ ", broker: " + BrokerUtil.printBroker(getName(), address));
} finally {
if (needReturn) {
ClientPool.brokerPool.returnObject(address, client);
} else {
ClientPool.brokerPool.invalidateObject(address, client);
}
}
return Status.OK;
}
@Override
public Status makeDir(String remotePath) {
return new Status(Status.ErrCode.COMMON_ERROR, "mkdir is not implemented.");
}
@Override
public Status checkPathExist(String remotePath) {
// 1. get a proper broker
Pair<TPaloBrokerService.Client, TNetworkAddress> pair = getBroker();
if (pair == null) {
return new Status(Status.ErrCode.COMMON_ERROR, "failed to get broker client");
}
TPaloBrokerService.Client client = pair.first;
TNetworkAddress address = pair.second;
// check path
boolean needReturn = true;
try {
TBrokerCheckPathExistRequest req = new TBrokerCheckPathExistRequest(TBrokerVersion.VERSION_ONE,
remotePath, getProperties());
TBrokerCheckPathExistResponse rep = client.checkPathExist(req);
TBrokerOperationStatus opst = rep.getOpStatus();
if (opst.getStatusCode() != TBrokerOperationStatusCode.OK) {
return new Status(Status.ErrCode.COMMON_ERROR,
"failed to check remote path exist: " + remotePath
+ ", broker: " + BrokerUtil.printBroker(getName(), address)
+ ". msg: " + opst.getMessage());
}
if (!rep.isIsPathExist()) {
return new Status(Status.ErrCode.NOT_FOUND, "remote path does not exist: " + remotePath);
}
return Status.OK;
} catch (TException e) {
needReturn = false;
return new Status(Status.ErrCode.COMMON_ERROR,
"failed to check remote path exist: " + remotePath
+ ", broker: " + BrokerUtil.printBroker(getName(), address)
+ ". msg: " + e.getMessage());
} finally {
if (needReturn) {
ClientPool.brokerPool.returnObject(address, client);
} else {
ClientPool.brokerPool.invalidateObject(address, client);
}
}
}
@Override
public StorageBackend.StorageType getStorageType() {
return StorageBackend.StorageType.BROKER;
}
public Pair<TPaloBrokerService.Client, TNetworkAddress> getBroker() {
Pair<TPaloBrokerService.Client, TNetworkAddress> result = new Pair<>(null, null);
FsBroker broker;
try {
String localIP = FrontendOptions.getLocalHostAddress();
broker = Catalog.getCurrentCatalog().getBrokerMgr().getBroker(getName(), localIP);
} catch (AnalysisException e) {
LOG.warn("failed to get a broker address: " + e.getMessage());
return null;
}
TNetworkAddress address = new TNetworkAddress(broker.ip, broker.port);
TPaloBrokerService.Client client;
try {
client = ClientPool.brokerPool.borrowObject(address);
} catch (Exception e) {
LOG.warn("failed to get broker client: " + e.getMessage());
return null;
}
result.first = client;
result.second = address;
LOG.info("get broker: {}", BrokerUtil.printBroker(getName(), address));
return result;
}
private Status openWriter(TPaloBrokerService.Client client, TNetworkAddress address, String remoteFile,
TBrokerFD fd) {
try {
TBrokerOpenWriterRequest req = new TBrokerOpenWriterRequest(TBrokerVersion.VERSION_ONE,
remoteFile, TBrokerOpenMode.APPEND, clientId(), getProperties());
TBrokerOpenWriterResponse rep = client.openWriter(req);
TBrokerOperationStatus opst = rep.getOpStatus();
if (opst.getStatusCode() != TBrokerOperationStatusCode.OK) {
return new Status(Status.ErrCode.COMMON_ERROR,
"failed to open writer on broker " + BrokerUtil.printBroker(getName(), address)
+ " for file: " + remoteFile + ". msg: " + opst.getMessage());
}
fd.setHigh(rep.getFd().getHigh());
fd.setLow(rep.getFd().getLow());
LOG.info("finished to open writer. fd: {}. directly upload to remote path {}.", fd, remoteFile);
} catch (TException e) {
return new Status(Status.ErrCode.BAD_CONNECTION,
"failed to open writer on broker " + BrokerUtil.printBroker(getName(), address)
+ ", err: " + e.getMessage());
}
return Status.OK;
}
private Status closeWriter(TPaloBrokerService.Client client, TNetworkAddress address, TBrokerFD fd) {
try {
TBrokerCloseWriterRequest req = new TBrokerCloseWriterRequest(TBrokerVersion.VERSION_ONE, fd);
TBrokerOperationStatus st = client.closeWriter(req);
if (st.getStatusCode() != TBrokerOperationStatusCode.OK) {
return new Status(Status.ErrCode.COMMON_ERROR,
"failed to close writer on broker " + BrokerUtil.printBroker(getName(), address)
+ " for fd: " + fd);
}
LOG.info("finished to close writer. fd: {}.", fd);
} catch (TException e) {
return new Status(Status.ErrCode.BAD_CONNECTION,
"failed to close writer on broker " + BrokerUtil.printBroker(getName(), address)
+ ", fd " + fd + ", msg: " + e.getMessage());
}
return Status.OK;
}
private Status closeReader(TPaloBrokerService.Client client, TNetworkAddress address, TBrokerFD fd) {
try {
TBrokerCloseReaderRequest req = new TBrokerCloseReaderRequest(TBrokerVersion.VERSION_ONE, fd);
TBrokerOperationStatus st = client.closeReader(req);
if (st.getStatusCode() != TBrokerOperationStatusCode.OK) {
return new Status(Status.ErrCode.COMMON_ERROR,
"failed to close reader on broker " + BrokerUtil.printBroker(getName(), address)
+ " for fd: " + fd);
}
LOG.info("finished to close reader. fd: {}.", fd);
} catch (TException e) {
return new Status(Status.ErrCode.BAD_CONNECTION,
"failed to close reader on broker " + BrokerUtil.printBroker(getName(), address)
+ ", fd " + fd + ", msg: " + e.getMessage());
}
return Status.OK;
}
}
|
package com.slipper.shiro.token;
import org.apache.shiro.authc.AuthenticationToken;
public class OAuth2Token implements AuthenticationToken {
private String token;
public OAuth2Token(String token){
this.token = token;
}
@Override
public Object getPrincipal() {
return token;
}
@Override
public Object getCredentials() {
return token;
}
}
|
package com.qa.services;
public interface GetItemId<T> {
long getItemId(T t);
}
|
package org.ontosoft.client.components.form.formgroup.input;
import java.util.ArrayList;
import java.util.List;
import org.gwtbootstrap3.client.ui.form.error.BasicEditorError;
import org.gwtbootstrap3.client.ui.form.validator.Validator;
import com.google.gwt.editor.client.Editor;
import com.google.gwt.editor.client.EditorError;
import com.google.gwt.regexp.shared.RegExp;
public class Validators {
public static Validator<String> NO_BLANK_STRINGS = new Validator<String>() {
@Override
public List<EditorError> validate(Editor<String> editor, String value) {
List<EditorError> result = new ArrayList<EditorError>();
if (value == null || value.equals(""))
result.add(new BasicEditorError(editor, value, null));
return result;
}
@Override
public int getPriority() {
return Priority.LOW;
}
};
public static Validator<Double> DOUBLE = new Validator<Double>() {
@Override
public List<EditorError> validate(Editor<Double> editor, Double value) {
List<EditorError> result = new ArrayList<EditorError>();
if (value == null)
result.add(new BasicEditorError(editor, value, "Not a valid number"));
return result;
}
@Override
public int getPriority() {
return Priority.MEDIUM;
}
};
public static Validator<String> URL = new Validator<String>() {
@Override
public List<EditorError> validate(Editor<String> editor, String value) {
List<EditorError> result = new ArrayList<EditorError>();
if (value != null && !isValidUrl(value, true)) {
result.add(new BasicEditorError(editor, value, "Not a valid url"));
}
return result;
}
@Override
public int getPriority() {
return Priority.MEDIUM;
}
};
// Helper functions;
private static RegExp urlValidator;
private static RegExp urlPlusTldValidator;
private static boolean isValidUrl(String url, boolean topLevelDomainRequired) {
if (urlValidator == null || urlPlusTldValidator == null) {
urlValidator = RegExp
.compile("^((ftp|http|https)://[\\w@.\\-\\_]+(:\\d{1,5})?(/[\\w#!:.?+=&%@!~\\_\\-/]+)*){1}$");
urlPlusTldValidator = RegExp
.compile("^((ftp|http|https)://[\\w@.\\-\\_]+\\.[a-zA-Z]{2,}(:\\d{1,5})?(/[\\w#!:.?+=&%@!~\\_\\-/]+)*){1}$");
}
return (topLevelDomainRequired ? urlPlusTldValidator : urlValidator)
.exec(url) != null;
}
}
|
package me.dkzwm.widget.srl.sample.ui;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import me.dkzwm.widget.srl.RefreshingListenerAdapter;
import me.dkzwm.widget.srl.SmoothRefreshLayout;
import me.dkzwm.widget.srl.config.Constants;
import me.dkzwm.widget.srl.extra.IRefreshView;
import me.dkzwm.widget.srl.indicator.IIndicator;
import me.dkzwm.widget.srl.sample.BuildConfig;
import me.dkzwm.widget.srl.sample.R;
import me.dkzwm.widget.srl.sample.widget.WaveSmoothRefreshLayout;
import me.dkzwm.widget.srl.utils.SRLog;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Handler mHandler = new Handler();
private WaveSmoothRefreshLayout mRefreshLayout;
private Button mButtonDebug;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRefreshLayout = findViewById(R.id.smoothRefreshLayout_main);
//设置刷新回调
mRefreshLayout.setOnRefreshListener(new RefreshingListenerAdapter() {
@Override
public void onRefreshBegin(boolean isRefresh) {
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
mRefreshLayout.refreshComplete(800);
}
}, 4000);
}
});
mRefreshLayout.addOnUIPositionChangedListener(new SmoothRefreshLayout
.OnUIPositionChangedListener() {
@Override
public void onChanged(byte status, IIndicator indicator) {
if (!mRefreshLayout.isOverScrolling() && mRefreshLayout.isMovingFooter()) {
mRefreshLayout.resetScrollerInterpolator();
}
}
});
mRefreshLayout.setDisableLoadMore(false);
mRefreshLayout.setDisablePerformLoadMore(true);
mRefreshLayout.setEnableHideFooterView(true);
mRefreshLayout.getDefaultHeader().setWaveColor(ContextCompat.getColor(this, R.color.colorPrimary));
mRefreshLayout.getDefaultHeader().setBackgroundColor(ContextCompat.getColor(this, R.color.colorAccent));
mRefreshLayout.getDefaultHeader().setStyle(IRefreshView.STYLE_PIN);
//自动刷新
mRefreshLayout.autoRefresh(Constants.ACTION_AT_ONCE, true);
findViewById(R.id.imageView_main_bottom_icon).setOnClickListener(this);
findViewById(R.id.button_main_with_frameLayout).setOnClickListener(this);
findViewById(R.id.button_main_with_listView).setOnClickListener(this);
findViewById(R.id.button_main_with_gridView).setOnClickListener(this);
findViewById(R.id.button_main_with_recyclerView).setOnClickListener(this);
findViewById(R.id.button_main_with_recyclerView_in_coordinatorLayout).setOnClickListener
(this);
findViewById(R.id.button_main_test_enable_next_pull_to_refresh_at_once)
.setOnClickListener(this);
findViewById(R.id.button_main_test_material_style)
.setOnClickListener(this);
findViewById(R.id.button_main_test_nested).setOnClickListener(this);
findViewById(R.id.button_main_test_pull_to_refresh).setOnClickListener(this);
findViewById(R.id.button_main_test_release_to_refresh).setOnClickListener(this);
findViewById(R.id.button_main_with_viewPager).setOnClickListener(this);
findViewById(R.id.button_main_with_webView).setOnClickListener(this);
findViewById(R.id.button_main_with_textView).setOnClickListener(this);
findViewById(R.id.button_main_test_over_scroll).setOnClickListener(this);
findViewById(R.id.button_main_test_two_level_refresh).setOnClickListener(this);
findViewById(R.id.button_main_test_QQ_activity_style).setOnClickListener(this);
findViewById(R.id.button_main_test_QQ_web_style).setOnClickListener(this);
findViewById(R.id.button_main_test_nested_view_pager).setOnClickListener(this);
findViewById(R.id.button_main_test_base_recyclerView_adapter).setOnClickListener(this);
findViewById(R.id.button_main_test_nested_horizontal_views).setOnClickListener(this);
findViewById(R.id.button_main_test_horizontal_refresh).setOnClickListener(this);
findViewById(R.id.button_main_test_horizontal_recyclerView).setOnClickListener(this);
findViewById(R.id.button_main_test_multi_direction_views).setOnClickListener(this);
findViewById(R.id.button_main_test_scroll_to_auto_refresh).setOnClickListener(this);
findViewById(R.id.button_main_test_scale_effect).setOnClickListener(this);
findViewById(R.id.button_main_test_horizontal_scale_effect).setOnClickListener(this);
mButtonDebug = findViewById(R.id.button_main_debug);
mButtonDebug.setOnClickListener(this);
}
@Override
protected void onDestroy() {
super.onDestroy();
mHandler.removeCallbacksAndMessages(null);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button_main_with_frameLayout:
startActivity(new Intent(MainActivity.this, WithFrameLayoutActivity.class));
break;
case R.id.button_main_with_textView:
startActivity(new Intent(MainActivity.this, WithTextViewActivity.class));
break;
case R.id.button_main_with_webView:
startActivity(new Intent(MainActivity.this, WithWebViewActivity.class));
break;
case R.id.button_main_with_listView:
startActivity(new Intent(MainActivity.this, WithListViewActivity.class));
break;
case R.id.button_main_with_gridView:
startActivity(new Intent(MainActivity.this, WithGridViewActivity.class));
break;
case R.id.button_main_with_recyclerView:
startActivity(new Intent(MainActivity.this, WithRecyclerViewActivity.class));
break;
case R.id.button_main_with_recyclerView_in_coordinatorLayout:
startActivity(new Intent(MainActivity.this, WithRecyclerViewInCoordinatorLayoutActivity.class));
break;
case R.id.button_main_test_over_scroll:
startActivity(new Intent(MainActivity.this, TestOverScrollActivity.class));
break;
case R.id.button_main_with_viewPager:
startActivity(new Intent(MainActivity.this, WithViewPagerActivity.class));
break;
case R.id.button_main_test_pull_to_refresh:
startActivity(new Intent(MainActivity.this, TestPullToRefreshActivity.class));
break;
case R.id.button_main_test_release_to_refresh:
startActivity(new Intent(MainActivity.this, TestReleaseToRefreshActivity.class));
break;
case R.id.button_main_test_enable_next_pull_to_refresh_at_once:
startActivity(new Intent(MainActivity.this, TestNextRefreshAtOnceActivity.class));
break;
case R.id.button_main_test_material_style:
startActivity(new Intent(MainActivity.this, TestMaterialStyleActivity.class));
break;
case R.id.button_main_test_two_level_refresh:
startActivity(new Intent(MainActivity.this, TestTwoLevelRefreshActivity.class));
break;
case R.id.button_main_test_QQ_activity_style:
startActivity(new Intent(MainActivity.this, TestQQActivityStyleActivity.class));
break;
case R.id.button_main_test_nested:
startActivity(new Intent(MainActivity.this, TestNestedActivity.class));
break;
case R.id.button_main_test_QQ_web_style:
startActivity(new Intent(MainActivity.this, TestQQWebStyleActivity.class));
break;
case R.id.button_main_test_nested_view_pager:
startActivity(new Intent(MainActivity.this, TestNestedViewPagerActivity.class));
break;
case R.id.button_main_test_base_recyclerView_adapter:
startActivity(new Intent(MainActivity.this, TestBaseRecyclerViewAdapterActivity.class));
break;
case R.id.button_main_test_nested_horizontal_views:
startActivity(new Intent(MainActivity.this, TestNestedHorizontalViewsActivity.class));
break;
case R.id.button_main_test_horizontal_recyclerView:
startActivity(new Intent(MainActivity.this, TestHorizontalRecyclerViewActivity.class));
break;
case R.id.button_main_test_multi_direction_views:
startActivity(new Intent(MainActivity.this, TestMultiDirectionViewsActivity.class));
break;
case R.id.button_main_test_scroll_to_auto_refresh:
startActivity(new Intent(MainActivity.this, TestScrollToAutoRefreshActivity.class));
break;
case R.id.imageView_main_bottom_icon:
Toast.makeText(this, getString(R.string.current_version) + BuildConfig.VERSION_NAME,
Toast.LENGTH_SHORT).show();
break;
case R.id.button_main_test_horizontal_refresh:
startActivity(new Intent(MainActivity.this, TestHorizontalRefreshActivity.class));
break;
case R.id.button_main_test_scale_effect:
startActivity(new Intent(MainActivity.this, TestScaleEffectActivity.class));
break;
case R.id.button_main_test_horizontal_scale_effect:
startActivity(new Intent(MainActivity.this, TestHorizontalScaleEffectActivity.class));
break;
case R.id.button_main_debug:
SmoothRefreshLayout.debug(!SmoothRefreshLayout.isDebug());
if (SmoothRefreshLayout.isDebug()) {
mButtonDebug.setText(R.string.debug_off);
} else {
mButtonDebug.setText(R.string.debug_on);
}
break;
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(Menu.NONE, Menu.FIRST, Menu.NONE, R.string.change_style);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == Menu.FIRST) {
if (mRefreshLayout.getDefaultHeader().getStyle() == IRefreshView.STYLE_SCALE)
mRefreshLayout.getDefaultHeader().setStyle(IRefreshView.STYLE_PIN);
else
mRefreshLayout.getDefaultHeader().setStyle(IRefreshView.STYLE_SCALE);
return true;
}
return false;
}
}
|
package com.twu.biblioteca;
import org.junit.Test;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import static org.junit.Assert.assertEquals;
/**
* Created by parvez on 21/12/16.
*/
public class BibliotecaTest {
private ByteArrayOutputStream outContent = new ByteArrayOutputStream();
Biblioteca biblioteca;
Library library;
@Test
public void testWelcome() {
assertEquals("Welcome to Biblioteca\n", biblioteca.welcome());
}
}
|
package com.agile.spirit.components;
import com.agile.spirit.componentsinfo.SearchInfo;
import org.hippoecm.hst.content.beans.standard.HippoBean;
import org.hippoecm.hst.core.component.HstComponentException;
import org.hippoecm.hst.core.component.HstRequest;
import org.hippoecm.hst.core.component.HstResponse;
import org.hippoecm.hst.core.parameters.ParametersInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ParametersInfo(type = SearchInfo.class)
public class Search extends BaseComponent {
public static final Logger log = LoggerFactory.getLogger(Search.class);
@Override
public void doBeforeRender(final HstRequest request, final HstResponse response) throws HstComponentException {
SearchInfo info = getComponentParametersInfo(request);
HippoBean scope = request.getRequestContext().getSiteContentBaseBean();
String query = getPublicRequestParameter(request, "query");
createAndExecuteSearch(request, info, scope, query);
}
}
|
/*
* 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.redshift.model;
import java.io.Serializable;
import javax.annotation.Generated;
/**
* <p>
* Describes a resize operation.
* </p>
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/redshift-2012-12-01/ResizeInfo" target="_top">AWS API
* Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class ResizeInfo implements Serializable, Cloneable {
/**
* <p>
* Returns the value <code>ClassicResize</code>.
* </p>
*/
private String resizeType;
/**
* <p>
* A boolean value indicating if the resize operation can be cancelled.
* </p>
*/
private Boolean allowCancelResize;
/**
* <p>
* Returns the value <code>ClassicResize</code>.
* </p>
*
* @param resizeType
* Returns the value <code>ClassicResize</code>.
*/
public void setResizeType(String resizeType) {
this.resizeType = resizeType;
}
/**
* <p>
* Returns the value <code>ClassicResize</code>.
* </p>
*
* @return Returns the value <code>ClassicResize</code>.
*/
public String getResizeType() {
return this.resizeType;
}
/**
* <p>
* Returns the value <code>ClassicResize</code>.
* </p>
*
* @param resizeType
* Returns the value <code>ClassicResize</code>.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ResizeInfo withResizeType(String resizeType) {
setResizeType(resizeType);
return this;
}
/**
* <p>
* A boolean value indicating if the resize operation can be cancelled.
* </p>
*
* @param allowCancelResize
* A boolean value indicating if the resize operation can be cancelled.
*/
public void setAllowCancelResize(Boolean allowCancelResize) {
this.allowCancelResize = allowCancelResize;
}
/**
* <p>
* A boolean value indicating if the resize operation can be cancelled.
* </p>
*
* @return A boolean value indicating if the resize operation can be cancelled.
*/
public Boolean getAllowCancelResize() {
return this.allowCancelResize;
}
/**
* <p>
* A boolean value indicating if the resize operation can be cancelled.
* </p>
*
* @param allowCancelResize
* A boolean value indicating if the resize operation can be cancelled.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ResizeInfo withAllowCancelResize(Boolean allowCancelResize) {
setAllowCancelResize(allowCancelResize);
return this;
}
/**
* <p>
* A boolean value indicating if the resize operation can be cancelled.
* </p>
*
* @return A boolean value indicating if the resize operation can be cancelled.
*/
public Boolean isAllowCancelResize() {
return this.allowCancelResize;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getResizeType() != null)
sb.append("ResizeType: ").append(getResizeType()).append(",");
if (getAllowCancelResize() != null)
sb.append("AllowCancelResize: ").append(getAllowCancelResize());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof ResizeInfo == false)
return false;
ResizeInfo other = (ResizeInfo) obj;
if (other.getResizeType() == null ^ this.getResizeType() == null)
return false;
if (other.getResizeType() != null && other.getResizeType().equals(this.getResizeType()) == false)
return false;
if (other.getAllowCancelResize() == null ^ this.getAllowCancelResize() == null)
return false;
if (other.getAllowCancelResize() != null && other.getAllowCancelResize().equals(this.getAllowCancelResize()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getResizeType() == null) ? 0 : getResizeType().hashCode());
hashCode = prime * hashCode + ((getAllowCancelResize() == null) ? 0 : getAllowCancelResize().hashCode());
return hashCode;
}
@Override
public ResizeInfo clone() {
try {
return (ResizeInfo) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
}
|
/*
* Copyright 2017 Apereo
*
* 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.tle.web.sections.standard.renderers;
import java.io.IOException;
import java.util.Map;
import com.tle.web.sections.SectionWriter;
import com.tle.web.sections.events.js.JSHandler;
import com.tle.web.sections.render.SectionRenderable;
import com.tle.web.sections.render.TagRenderer;
import com.tle.web.sections.standard.model.HtmlComponentState;
public abstract class AbstractComponentRenderer extends TagRenderer
{
protected HtmlComponentState state;
public AbstractComponentRenderer(HtmlComponentState state)
{
super(null, state);
this.state = state;
}
@SuppressWarnings("nls")
@Override
protected void prepareFirstAttributes(SectionWriter writer, Map<String, String> attrs) throws IOException
{
if( isDisabled() )
{
attrs.put("disabled", "disabled");
}
}
public boolean isDisabled()
{
return state.isDisabled();
}
@Override
public void realRender(SectionWriter writer) throws IOException
{
state.setBeenRendered(true);
super.realRender(writer);
}
protected boolean isStillAddClickHandler()
{
return true;
}
@Override
protected void processHandler(SectionWriter writer, Map<String, String> attrs, String event, JSHandler handler)
{
if( !isStillAddClickHandler() && isDisabled() && JSHandler.EVENT_CLICK.equals(event) )
{
return;
}
super.processHandler(writer, attrs, event, handler);
}
@Override
public SectionRenderable getNestedRenderable()
{
if( nestedRenderable != null )
{
return nestedRenderable;
}
else if( state.getLabel() != null )
{
nestedRenderable = state.createLabelRenderer();
}
return nestedRenderable;
}
public String getLabelText()
{
return state.getLabelText();
}
@Override
protected abstract String getTag();
public HtmlComponentState getHtmlState()
{
return state;
}
}
|
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/tasks/v2beta3/cloudtasks.proto
package com.google.cloud.tasks.v2beta3;
/**
* <pre>
* Request message for [CreateQueue][google.cloud.tasks.v2beta3.CloudTasks.CreateQueue].
* </pre>
*
* Protobuf type {@code google.cloud.tasks.v2beta3.CreateQueueRequest}
*/
public final class CreateQueueRequest extends
com.google.protobuf.GeneratedMessageV3 implements
// @@protoc_insertion_point(message_implements:google.cloud.tasks.v2beta3.CreateQueueRequest)
CreateQueueRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use CreateQueueRequest.newBuilder() to construct.
private CreateQueueRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private CreateQueueRequest() {
parent_ = "";
}
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet
getUnknownFields() {
return this.unknownFields;
}
private CreateQueueRequest(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
this();
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
int mutable_bitField0_ = 0;
com.google.protobuf.UnknownFieldSet.Builder unknownFields =
com.google.protobuf.UnknownFieldSet.newBuilder();
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10: {
java.lang.String s = input.readStringRequireUtf8();
parent_ = s;
break;
}
case 18: {
com.google.cloud.tasks.v2beta3.Queue.Builder subBuilder = null;
if (queue_ != null) {
subBuilder = queue_.toBuilder();
}
queue_ = input.readMessage(com.google.cloud.tasks.v2beta3.Queue.parser(), extensionRegistry);
if (subBuilder != null) {
subBuilder.mergeFrom(queue_);
queue_ = subBuilder.buildPartial();
}
break;
}
default: {
if (!parseUnknownFieldProto3(
input, unknownFields, extensionRegistry, tag)) {
done = true;
}
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(
e).setUnfinishedMessage(this);
} finally {
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.cloud.tasks.v2beta3.CloudTasksProto.internal_static_google_cloud_tasks_v2beta3_CreateQueueRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.tasks.v2beta3.CloudTasksProto.internal_static_google_cloud_tasks_v2beta3_CreateQueueRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.tasks.v2beta3.CreateQueueRequest.class, com.google.cloud.tasks.v2beta3.CreateQueueRequest.Builder.class);
}
public static final int PARENT_FIELD_NUMBER = 1;
private volatile java.lang.Object parent_;
/**
* <pre>
* Required.
* The location name in which the queue will be created.
* For example: `projects/PROJECT_ID/locations/LOCATION_ID`
* The list of allowed locations can be obtained by calling Cloud
* Tasks' implementation of
* [ListLocations][google.cloud.location.Locations.ListLocations].
* </pre>
*
* <code>string parent = 1;</code>
*/
public java.lang.String getParent() {
java.lang.Object ref = parent_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
parent_ = s;
return s;
}
}
/**
* <pre>
* Required.
* The location name in which the queue will be created.
* For example: `projects/PROJECT_ID/locations/LOCATION_ID`
* The list of allowed locations can be obtained by calling Cloud
* Tasks' implementation of
* [ListLocations][google.cloud.location.Locations.ListLocations].
* </pre>
*
* <code>string parent = 1;</code>
*/
public com.google.protobuf.ByteString
getParentBytes() {
java.lang.Object ref = parent_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
parent_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int QUEUE_FIELD_NUMBER = 2;
private com.google.cloud.tasks.v2beta3.Queue queue_;
/**
* <pre>
* Required.
* The queue to create.
* [Queue's name][google.cloud.tasks.v2beta3.Queue.name] cannot be the same as an existing queue.
* </pre>
*
* <code>.google.cloud.tasks.v2beta3.Queue queue = 2;</code>
*/
public boolean hasQueue() {
return queue_ != null;
}
/**
* <pre>
* Required.
* The queue to create.
* [Queue's name][google.cloud.tasks.v2beta3.Queue.name] cannot be the same as an existing queue.
* </pre>
*
* <code>.google.cloud.tasks.v2beta3.Queue queue = 2;</code>
*/
public com.google.cloud.tasks.v2beta3.Queue getQueue() {
return queue_ == null ? com.google.cloud.tasks.v2beta3.Queue.getDefaultInstance() : queue_;
}
/**
* <pre>
* Required.
* The queue to create.
* [Queue's name][google.cloud.tasks.v2beta3.Queue.name] cannot be the same as an existing queue.
* </pre>
*
* <code>.google.cloud.tasks.v2beta3.Queue queue = 2;</code>
*/
public com.google.cloud.tasks.v2beta3.QueueOrBuilder getQueueOrBuilder() {
return getQueue();
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
if (!getParentBytes().isEmpty()) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, parent_);
}
if (queue_ != null) {
output.writeMessage(2, getQueue());
}
unknownFields.writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (!getParentBytes().isEmpty()) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, parent_);
}
if (queue_ != null) {
size += com.google.protobuf.CodedOutputStream
.computeMessageSize(2, getQueue());
}
size += unknownFields.getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.tasks.v2beta3.CreateQueueRequest)) {
return super.equals(obj);
}
com.google.cloud.tasks.v2beta3.CreateQueueRequest other = (com.google.cloud.tasks.v2beta3.CreateQueueRequest) obj;
boolean result = true;
result = result && getParent()
.equals(other.getParent());
result = result && (hasQueue() == other.hasQueue());
if (hasQueue()) {
result = result && getQueue()
.equals(other.getQueue());
}
result = result && unknownFields.equals(other.unknownFields);
return result;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (37 * hash) + PARENT_FIELD_NUMBER;
hash = (53 * hash) + getParent().hashCode();
if (hasQueue()) {
hash = (37 * hash) + QUEUE_FIELD_NUMBER;
hash = (53 * hash) + getQueue().hashCode();
}
hash = (29 * hash) + unknownFields.hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.tasks.v2beta3.CreateQueueRequest parseFrom(
java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.tasks.v2beta3.CreateQueueRequest parseFrom(
java.nio.ByteBuffer data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.tasks.v2beta3.CreateQueueRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.tasks.v2beta3.CreateQueueRequest parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.tasks.v2beta3.CreateQueueRequest parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.tasks.v2beta3.CreateQueueRequest parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.tasks.v2beta3.CreateQueueRequest parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.cloud.tasks.v2beta3.CreateQueueRequest parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
public static com.google.cloud.tasks.v2beta3.CreateQueueRequest parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.tasks.v2beta3.CreateQueueRequest parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input, extensionRegistry);
}
public static com.google.cloud.tasks.v2beta3.CreateQueueRequest parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.cloud.tasks.v2beta3.CreateQueueRequest parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(com.google.cloud.tasks.v2beta3.CreateQueueRequest prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE
? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
* <pre>
* Request message for [CreateQueue][google.cloud.tasks.v2beta3.CloudTasks.CreateQueue].
* </pre>
*
* Protobuf type {@code google.cloud.tasks.v2beta3.CreateQueueRequest}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:google.cloud.tasks.v2beta3.CreateQueueRequest)
com.google.cloud.tasks.v2beta3.CreateQueueRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.cloud.tasks.v2beta3.CloudTasksProto.internal_static_google_cloud_tasks_v2beta3_CreateQueueRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.tasks.v2beta3.CloudTasksProto.internal_static_google_cloud_tasks_v2beta3_CreateQueueRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.tasks.v2beta3.CreateQueueRequest.class, com.google.cloud.tasks.v2beta3.CreateQueueRequest.Builder.class);
}
// Construct using com.google.cloud.tasks.v2beta3.CreateQueueRequest.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3
.alwaysUseFieldBuilders) {
}
}
@java.lang.Override
public Builder clear() {
super.clear();
parent_ = "";
if (queueBuilder_ == null) {
queue_ = null;
} else {
queue_ = null;
queueBuilder_ = null;
}
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return com.google.cloud.tasks.v2beta3.CloudTasksProto.internal_static_google_cloud_tasks_v2beta3_CreateQueueRequest_descriptor;
}
@java.lang.Override
public com.google.cloud.tasks.v2beta3.CreateQueueRequest getDefaultInstanceForType() {
return com.google.cloud.tasks.v2beta3.CreateQueueRequest.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.tasks.v2beta3.CreateQueueRequest build() {
com.google.cloud.tasks.v2beta3.CreateQueueRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.tasks.v2beta3.CreateQueueRequest buildPartial() {
com.google.cloud.tasks.v2beta3.CreateQueueRequest result = new com.google.cloud.tasks.v2beta3.CreateQueueRequest(this);
result.parent_ = parent_;
if (queueBuilder_ == null) {
result.queue_ = queue_;
} else {
result.queue_ = queueBuilder_.build();
}
onBuilt();
return result;
}
@java.lang.Override
public Builder clone() {
return (Builder) super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return (Builder) super.setField(field, value);
}
@java.lang.Override
public Builder clearField(
com.google.protobuf.Descriptors.FieldDescriptor field) {
return (Builder) super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(
com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return (Builder) super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
int index, java.lang.Object value) {
return (Builder) super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return (Builder) super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.tasks.v2beta3.CreateQueueRequest) {
return mergeFrom((com.google.cloud.tasks.v2beta3.CreateQueueRequest)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.tasks.v2beta3.CreateQueueRequest other) {
if (other == com.google.cloud.tasks.v2beta3.CreateQueueRequest.getDefaultInstance()) return this;
if (!other.getParent().isEmpty()) {
parent_ = other.parent_;
onChanged();
}
if (other.hasQueue()) {
mergeQueue(other.getQueue());
}
this.mergeUnknownFields(other.unknownFields);
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
com.google.cloud.tasks.v2beta3.CreateQueueRequest parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (com.google.cloud.tasks.v2beta3.CreateQueueRequest) e.getUnfinishedMessage();
throw e.unwrapIOException();
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private java.lang.Object parent_ = "";
/**
* <pre>
* Required.
* The location name in which the queue will be created.
* For example: `projects/PROJECT_ID/locations/LOCATION_ID`
* The list of allowed locations can be obtained by calling Cloud
* Tasks' implementation of
* [ListLocations][google.cloud.location.Locations.ListLocations].
* </pre>
*
* <code>string parent = 1;</code>
*/
public java.lang.String getParent() {
java.lang.Object ref = parent_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
parent_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <pre>
* Required.
* The location name in which the queue will be created.
* For example: `projects/PROJECT_ID/locations/LOCATION_ID`
* The list of allowed locations can be obtained by calling Cloud
* Tasks' implementation of
* [ListLocations][google.cloud.location.Locations.ListLocations].
* </pre>
*
* <code>string parent = 1;</code>
*/
public com.google.protobuf.ByteString
getParentBytes() {
java.lang.Object ref = parent_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
parent_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <pre>
* Required.
* The location name in which the queue will be created.
* For example: `projects/PROJECT_ID/locations/LOCATION_ID`
* The list of allowed locations can be obtained by calling Cloud
* Tasks' implementation of
* [ListLocations][google.cloud.location.Locations.ListLocations].
* </pre>
*
* <code>string parent = 1;</code>
*/
public Builder setParent(
java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
parent_ = value;
onChanged();
return this;
}
/**
* <pre>
* Required.
* The location name in which the queue will be created.
* For example: `projects/PROJECT_ID/locations/LOCATION_ID`
* The list of allowed locations can be obtained by calling Cloud
* Tasks' implementation of
* [ListLocations][google.cloud.location.Locations.ListLocations].
* </pre>
*
* <code>string parent = 1;</code>
*/
public Builder clearParent() {
parent_ = getDefaultInstance().getParent();
onChanged();
return this;
}
/**
* <pre>
* Required.
* The location name in which the queue will be created.
* For example: `projects/PROJECT_ID/locations/LOCATION_ID`
* The list of allowed locations can be obtained by calling Cloud
* Tasks' implementation of
* [ListLocations][google.cloud.location.Locations.ListLocations].
* </pre>
*
* <code>string parent = 1;</code>
*/
public Builder setParentBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
parent_ = value;
onChanged();
return this;
}
private com.google.cloud.tasks.v2beta3.Queue queue_ = null;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.tasks.v2beta3.Queue, com.google.cloud.tasks.v2beta3.Queue.Builder, com.google.cloud.tasks.v2beta3.QueueOrBuilder> queueBuilder_;
/**
* <pre>
* Required.
* The queue to create.
* [Queue's name][google.cloud.tasks.v2beta3.Queue.name] cannot be the same as an existing queue.
* </pre>
*
* <code>.google.cloud.tasks.v2beta3.Queue queue = 2;</code>
*/
public boolean hasQueue() {
return queueBuilder_ != null || queue_ != null;
}
/**
* <pre>
* Required.
* The queue to create.
* [Queue's name][google.cloud.tasks.v2beta3.Queue.name] cannot be the same as an existing queue.
* </pre>
*
* <code>.google.cloud.tasks.v2beta3.Queue queue = 2;</code>
*/
public com.google.cloud.tasks.v2beta3.Queue getQueue() {
if (queueBuilder_ == null) {
return queue_ == null ? com.google.cloud.tasks.v2beta3.Queue.getDefaultInstance() : queue_;
} else {
return queueBuilder_.getMessage();
}
}
/**
* <pre>
* Required.
* The queue to create.
* [Queue's name][google.cloud.tasks.v2beta3.Queue.name] cannot be the same as an existing queue.
* </pre>
*
* <code>.google.cloud.tasks.v2beta3.Queue queue = 2;</code>
*/
public Builder setQueue(com.google.cloud.tasks.v2beta3.Queue value) {
if (queueBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
queue_ = value;
onChanged();
} else {
queueBuilder_.setMessage(value);
}
return this;
}
/**
* <pre>
* Required.
* The queue to create.
* [Queue's name][google.cloud.tasks.v2beta3.Queue.name] cannot be the same as an existing queue.
* </pre>
*
* <code>.google.cloud.tasks.v2beta3.Queue queue = 2;</code>
*/
public Builder setQueue(
com.google.cloud.tasks.v2beta3.Queue.Builder builderForValue) {
if (queueBuilder_ == null) {
queue_ = builderForValue.build();
onChanged();
} else {
queueBuilder_.setMessage(builderForValue.build());
}
return this;
}
/**
* <pre>
* Required.
* The queue to create.
* [Queue's name][google.cloud.tasks.v2beta3.Queue.name] cannot be the same as an existing queue.
* </pre>
*
* <code>.google.cloud.tasks.v2beta3.Queue queue = 2;</code>
*/
public Builder mergeQueue(com.google.cloud.tasks.v2beta3.Queue value) {
if (queueBuilder_ == null) {
if (queue_ != null) {
queue_ =
com.google.cloud.tasks.v2beta3.Queue.newBuilder(queue_).mergeFrom(value).buildPartial();
} else {
queue_ = value;
}
onChanged();
} else {
queueBuilder_.mergeFrom(value);
}
return this;
}
/**
* <pre>
* Required.
* The queue to create.
* [Queue's name][google.cloud.tasks.v2beta3.Queue.name] cannot be the same as an existing queue.
* </pre>
*
* <code>.google.cloud.tasks.v2beta3.Queue queue = 2;</code>
*/
public Builder clearQueue() {
if (queueBuilder_ == null) {
queue_ = null;
onChanged();
} else {
queue_ = null;
queueBuilder_ = null;
}
return this;
}
/**
* <pre>
* Required.
* The queue to create.
* [Queue's name][google.cloud.tasks.v2beta3.Queue.name] cannot be the same as an existing queue.
* </pre>
*
* <code>.google.cloud.tasks.v2beta3.Queue queue = 2;</code>
*/
public com.google.cloud.tasks.v2beta3.Queue.Builder getQueueBuilder() {
onChanged();
return getQueueFieldBuilder().getBuilder();
}
/**
* <pre>
* Required.
* The queue to create.
* [Queue's name][google.cloud.tasks.v2beta3.Queue.name] cannot be the same as an existing queue.
* </pre>
*
* <code>.google.cloud.tasks.v2beta3.Queue queue = 2;</code>
*/
public com.google.cloud.tasks.v2beta3.QueueOrBuilder getQueueOrBuilder() {
if (queueBuilder_ != null) {
return queueBuilder_.getMessageOrBuilder();
} else {
return queue_ == null ?
com.google.cloud.tasks.v2beta3.Queue.getDefaultInstance() : queue_;
}
}
/**
* <pre>
* Required.
* The queue to create.
* [Queue's name][google.cloud.tasks.v2beta3.Queue.name] cannot be the same as an existing queue.
* </pre>
*
* <code>.google.cloud.tasks.v2beta3.Queue queue = 2;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.tasks.v2beta3.Queue, com.google.cloud.tasks.v2beta3.Queue.Builder, com.google.cloud.tasks.v2beta3.QueueOrBuilder>
getQueueFieldBuilder() {
if (queueBuilder_ == null) {
queueBuilder_ = new com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.tasks.v2beta3.Queue, com.google.cloud.tasks.v2beta3.Queue.Builder, com.google.cloud.tasks.v2beta3.QueueOrBuilder>(
getQueue(),
getParentForChildren(),
isClean());
queue_ = null;
}
return queueBuilder_;
}
@java.lang.Override
public final Builder setUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFieldsProto3(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.tasks.v2beta3.CreateQueueRequest)
}
// @@protoc_insertion_point(class_scope:google.cloud.tasks.v2beta3.CreateQueueRequest)
private static final com.google.cloud.tasks.v2beta3.CreateQueueRequest DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.tasks.v2beta3.CreateQueueRequest();
}
public static com.google.cloud.tasks.v2beta3.CreateQueueRequest getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<CreateQueueRequest>
PARSER = new com.google.protobuf.AbstractParser<CreateQueueRequest>() {
@java.lang.Override
public CreateQueueRequest parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new CreateQueueRequest(input, extensionRegistry);
}
};
public static com.google.protobuf.Parser<CreateQueueRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<CreateQueueRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.tasks.v2beta3.CreateQueueRequest getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
package ua.training.repository;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import ua.training.entity.order.Destination;
import java.util.Optional;
@Repository
public interface DestinationRepository extends CrudRepository<Destination, Long> {
Optional<Destination> findByCityFromAndCityTo(String cityFrom, String cityTo);
}
|
package com.sap.iot.edgeservices.customhttpserver.http;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.MultiValueMap;
import java.net.URI;
public class CustomResponseEntity extends ResponseEntity {
public CustomResponseEntity(HttpStatus status) {
super(status);
}
public CustomResponseEntity(Object body, HttpStatus status) {
super(body, status);
}
public CustomResponseEntity(MultiValueMap headers, HttpStatus status) {
super(headers, status);
}
public CustomResponseEntity(Object body, MultiValueMap headers, HttpStatus status) {
super(body, headers, status);
}
public CustomResponseEntity(Object body, MultiValueMap headers, int rawStatus) {
super(body, headers, rawStatus);
}
public static ResponseEntity<java.lang.String> badReturn(String body) {
return badRequest().body(body);
}
public static ResponseEntity<String> created(String message) {
return status(HttpStatus.CREATED).body(message);
}
}
|
/*
* Copyright 2015 Adaptris 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.adaptris.core;
import static org.junit.Assert.assertEquals;
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 static org.junit.Assert.fail;
import java.util.Arrays;
import java.util.ListIterator;
import java.util.Set;
import javax.validation.ConstraintViolation;
import org.apache.log4j.Logger;
import org.junit.Before;
import org.junit.Test;
import com.adaptris.util.IdGenerator;
import com.adaptris.util.PlainIdGenerator;
public class ChannelListTest extends BaseCase {
private IdGenerator idGenerator;
private Logger log = Logger.getLogger(this.getClass());
public ChannelListTest() {
}
@Before
public void setUp() throws Exception {
idGenerator = new PlainIdGenerator();
}
@Override
public boolean isAnnotatedForJunit4() {
return true;
}
@Test
public void testRemoveThenAddAgain() throws Exception {
ChannelList channelList = new ChannelList();
Channel c = new Channel();
c.setUniqueId(getName());
channelList.add(c);
assertEquals(1, channelList.size());
assertTrue(channelList.removeChannel(c));
assertEquals(0, channelList.size());
channelList.add(c);
assertEquals(1, channelList.size());
}
@Test
public void testRemoveByObject() throws Exception {
ChannelList channelList = new ChannelList();
Channel c = new Channel();
c.setUniqueId(getName());
channelList.add(c);
assertEquals(1, channelList.size());
assertTrue(channelList.remove(c));
assertEquals(0, channelList.size());
}
@Test
public void testRedmine5407() throws Exception {
testRemoveThenAddAgain();
}
@Test
public void testRemoveNull() throws Exception {
ChannelList channelList = new ChannelList();
assertFalse(channelList.remove(null));
assertFalse(channelList.removeChannel(null));
}
@Test
public void testRemovePlainObject() throws Exception {
ChannelList channelList = new ChannelList();
assertFalse(channelList.remove(new Object()));
}
@Test
public void testAddDuplicate() {
ChannelList channelList = new ChannelList();
Channel toAdd = new Channel();
channelList.add(toAdd);
channelList.add(toAdd);
assertEquals(2, channelList.size());
}
@Test
public void testCollectionConstructor() {
ChannelList channelList = new ChannelList();
Channel channel1 = new Channel();
Channel channel2 = new Channel();
channelList.add(channel1);
channelList.add(channel2);
ChannelList channelList2 = new ChannelList(channelList);
assertEquals(2, channelList2.size());
assertTrue(channelList2.contains(channel1));
assertTrue(channelList2.contains(channel1));
}
@Test
public void testAddAllAtPosition() {
ChannelList channelList = new ChannelList();
Channel channel1 = new Channel();
Channel channel2 = new Channel();
channelList.add(channel1);
channelList.add(channel2);
ChannelList channelList2 = new ChannelList();
channelList2.add(new Channel());
channelList2.add(new Channel());
channelList2.addAll(1, channelList);
assertEquals(4, channelList2.size());
assertTrue(channelList2.contains(channel1));
assertTrue(channelList2.contains(channel1));
}
@Test
public void testAdd() {
ChannelList channelList = new ChannelList();
channelList.add(new Channel());
assertEquals(1, channelList.size());
try {
channelList.addChannel(null);
}
catch (IllegalArgumentException expected) {
}
assertEquals(1, channelList.size());
}
@Test
public void testAddAtPosition() {
ChannelList channelList = new ChannelList();
channelList.add(new Channel());
channelList.add(new Channel());
Channel toAdd = new Channel();
channelList.add(1, toAdd);
assertEquals(3, channelList.size());
assertEquals(toAdd, channelList.get(1));
}
@Test
public void testGetByInt() {
ChannelList wl = new ChannelList();
Channel toAdd = new Channel();
wl.add(new Channel());
wl.add(toAdd);
assertEquals(toAdd, wl.get(1));
}
@Test
public void testGetChannels() {
ChannelList wl = new ChannelList();
wl.add(new Channel());
assertNotNull(wl.getChannels());
assertEquals(1, wl.getChannels().size());
}
@Test
public void testIndexOf() {
ChannelList wl = new ChannelList();
wl.add(new Channel());
wl.add(new Channel());
Channel toAdd = new Channel();
wl.add(toAdd);
assertEquals(3, wl.size());
assertEquals(2, wl.indexOf(toAdd));
}
@Test
public void testIterator() {
ChannelList wl = new ChannelList();
wl.add(new Channel());
wl.add(new Channel());
assertNotNull(wl.iterator());
assertTrue(wl.iterator().hasNext());
}
@Test
public void testListIterator_HasPreviousNext() {
ChannelList list = new ChannelList();
list.add(new Channel());
list.add(new Channel());
list.add(new Channel());
list.add(new Channel());
list.add(new Channel());
int count = 0;
for (ListIterator<Channel> i = list.listIterator(); i.hasNext();) {
switch (count) {
case 0: {
assertEquals(-1, i.previousIndex());
assertFalse(i.hasPrevious());
assertTrue(i.hasNext());
break;
}
case 5: {
assertEquals(5, i.nextIndex());
assertTrue(i.hasPrevious());
assertFalse(i.hasNext());
break;
}
default: {
assertEquals(count, i.nextIndex());
assertNotNull(i.previous());
assertNotNull(i.next());
assertTrue(i.hasPrevious());
assertTrue(i.hasNext());
}
}
i.next();
count++;
}
}
@Test
public void testLastIndexOf() {
ChannelList wl = new ChannelList();
Channel toAdd = new Channel();
wl.add(toAdd);
wl.add(toAdd);
wl.add(toAdd);
assertEquals(2, wl.lastIndexOf(toAdd));
}
@Test
public void testListIterator() {
ChannelList wl = new ChannelList();
wl.add(new Channel());
wl.add(new Channel());
wl.add(new Channel());
wl.add(new Channel());
assertNotNull(wl.listIterator());
assertNotNull(wl.listIterator(1));
}
@Test
public void testRemove() {
ChannelList list = new ChannelList();
list.add(new Channel());
list.add(new Channel());
Channel channel = new Channel();
channel.setUniqueId("channel");
list.add(channel);
list.add(new Channel());
list.add(new Channel());
assertEquals(5, list.size());
list.remove(4); // Remove a channel w/o an id.
assertEquals(4, list.size());
list.remove(2);
assertFalse(list.contains(channel));
assertNull(list.getChannel("channel"));
assertEquals(3, list.size());
}
@Test
public void testSubList() {
ChannelList list = new ChannelList();
list.add(new Channel());
list.add(new Channel());
list.add(new Channel());
list.add(new Channel());
assertNotNull(list.subList(0, 2));
assertEquals(2, list.subList(0, 2).size());
}
@Test
public void testAddChannelUniqueIds() throws CoreException {
Channel ch1 = new Channel();
Channel ch2 = new Channel();
ChannelList list = new ChannelList();
list.addChannel(ch1);
list.addChannel(ch2);
Channel ch3 = new Channel();
ch3.setUniqueId("ch3");
list.add(ch3);
try {
list.add(ch3);
fail();
}
catch (IllegalArgumentException expected) {
}
assertEquals(3, list.size());
Channel ch4 = new Channel();
ch4.setUniqueId("ch4");
list.add(ch4);
assertEquals(4, list.size());
list.remove(3);
list.add(ch4);
assertEquals(4, list.size());
}
@Test
public void testSetChannels() throws Exception {
ChannelList list = new ChannelList();
try {
list.setChannels(null);
}
catch (IllegalArgumentException expected) {
}
list.setChannels(Arrays.asList(new Channel[]
{
new Channel()
}));
assertEquals(1, list.size());
}
@Test
public void testSetChannelsWithDuplicateID() {
ChannelList list = new ChannelList();
try {
list.setChannels(Arrays.asList(new Channel[]
{
new Channel() {
@Override
public String getUniqueId() {
return "channel1";
}
}, new Channel() {
@Override
public String getUniqueId() {
return "channel1";
}
}
}));
fail();
}
catch (IllegalArgumentException expected) {
}
}
@Test
public void testAddAllChannelsWithDuplicateID() {
ChannelList list = new ChannelList();
try {
list.addAll(Arrays.asList(new Channel[]
{
new Channel() {
@Override
public String getUniqueId() {
return "channel1";
}
}, new Channel() {
@Override
public String getUniqueId() {
return "channel1";
}
}
}));
fail();
}
catch (IllegalArgumentException expected) {
}
}
@Test
public void testSetByInt() {
ChannelList list = new ChannelList();
list.add(new Channel());
list.add(new Channel() {
@Override
public String getUniqueId() {
return "replacedChannel";
}
});
list.add(new Channel());
Channel toAdd = new Channel();
list.set(1, toAdd);
assertEquals(toAdd, list.get(1));
assertNull(list.getChannel("replacedChannel"));
}
@Test
public void testGetChannelByUniqueId() throws Exception {
ChannelList list = new ChannelList();
list.setChannels(Arrays.asList(new Channel[]
{
new Channel() {
@Override
public String getUniqueId() {
return "channel1";
}
}, new Channel() {
@Override
public String getUniqueId() {
return "channel2";
}
}
}));
assertEquals(2, list.size());
assertNotNull(list.getChannel("channel1"));
assertNotNull(list.getChannel("channel2"));
assertNull(list.getChannel("channel99"));
try {
list.getChannel("");
fail();
}
catch (IllegalArgumentException expected) {
}
try {
list.getChannel(null);
fail();
}
catch (IllegalArgumentException expected) {
}
}
@Test
public void testGetChannelByPosition() throws Exception {
ChannelList list = new ChannelList();
list.setChannels(Arrays.asList(new Channel[]
{
new Channel() {
@Override
public String getUniqueId() {
return "channel1";
}
}, new Channel() {
@Override
public String getUniqueId() {
return "channel2";
}
}
}));
assertEquals(2, list.size());
assertNotNull(list.getChannel(0));
try {
list.getChannel(15);
}
catch (ArrayIndexOutOfBoundsException expected) {
;
}
try {
list.getChannel(-1);
}
catch (ArrayIndexOutOfBoundsException expected) {
;
}
}
@Test
public void testChannelAutoStartFalse() throws Exception {
ChannelList list = new ChannelList();
Channel testChannel = new Channel();
testChannel.setUniqueId("testAutoStart");
testChannel.setAutoStart(Boolean.FALSE);
list.setChannels(Arrays.asList(new Channel[]
{
testChannel
}));
list.prepare();
start(list);
assertEquals(ClosedState.getInstance(), testChannel.retrieveComponentState());
}
@Test
public void testChannelAutoStartTrue() throws Exception {
ChannelList list = new ChannelList();
Channel testChannel = new Channel();
testChannel.setUniqueId("testAutoStart");
testChannel.setAutoStart(Boolean.TRUE);
list.setChannels(Arrays.asList(new Channel[]
{
testChannel
}));
list.prepare();
start(list);
assertEquals(StartedState.getInstance(), testChannel.retrieveComponentState());
}
// No ID means that we always start regardless of auto-start being false.
@Test
public void testChannelAutoStartFalseNoUniqueId() throws Exception {
ChannelList list = new ChannelList();
Channel testChannel = new Channel();
testChannel.setAutoStart(Boolean.FALSE);
list.setChannels(Arrays.asList(new Channel[]
{
testChannel
}));
list.prepare();
start(list);
assertEquals(StartedState.getInstance(), testChannel.retrieveComponentState());
}
@Test
public void testChannelAutoStartTrueNoUniqueId() throws Exception {
ChannelList list = new ChannelList();
Channel testChannel = new Channel();
testChannel.setAutoStart(Boolean.TRUE);
list.setChannels(Arrays.asList(new Channel[]
{
testChannel
}));
list.prepare();
start(list);
assertEquals(StartedState.getInstance(), testChannel.retrieveComponentState());
}
@Test
public void testChannelAutoStartNotSpecified() throws Exception {
ChannelList list = new ChannelList();
Channel testChannel = new Channel();
list.setChannels(Arrays.asList(new Channel[]
{
testChannel
}));
list.prepare();
start(list);
assertEquals(StartedState.getInstance(), testChannel.retrieveComponentState());
}
@Test
public void testJavaxValidation() throws Exception {
Adapter adapter = new Adapter();
adapter.setUniqueId("testJavaxValidation");
ChannelList list = new ChannelList();
list.add(new Channel()); // this is invalid, cos no UID.
adapter.setChannelList(list);
Set<ConstraintViolation<Object>> violations = validate(null, adapter);
logViolations(violations);
// We expect 2 violations, one from adapter, one from channeList
assertEquals(2, violations.size());
list.clear();
violations = validate(null, adapter);
assertEquals(0, violations.size());
}
}
|
package com.joojet.plugins.mobs.equipment.head;
import org.bukkit.ChatColor;
import org.bukkit.enchantments.Enchantment;
import com.joojet.plugins.mobs.enums.EquipmentType;
import com.joojet.plugins.mobs.enums.PlayerHead;
import com.joojet.plugins.mobs.equipment.Equipment;
import com.joojet.plugins.mobs.monsters.factions.UCLAFaction;
public class BruinHead extends Equipment
{
public BruinHead ()
{
super (EquipmentType.BRUIN_HEAD, PlayerHead.UCLA_BRUIN, ChatColor.AQUA);
this.wordsPerLine = 6;
this.loreColor = ChatColor.GOLD;
this.setDisplayName(UCLAFaction.generateUCLADisplayName("Football Helmet"));
this.addLoreToItemMeta("This is one school you definitely don't want to see winnin'");
this.addUnsafeEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 3);
this.addDefenseAttributes(3.0, 2.0, 0.15);
this.addAttackAttributes(2.0, 0.0);
}
}
|
package com.ecommerce.vojo.browse;
import com.ecommerce.dto.product.browse.ProductBrowseDTO;
import lombok.Getter;
import lombok.Setter;
import java.util.List;
@Setter
@Getter
public class ProductBrowseWithCatVO {
private String catName;
private List<ProductBrowseDTO> products;
}
|
/*
* 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.skywalking.apm.plugin.spring.patch;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import org.apache.skywalking.apm.agent.core.plugin.interceptor.enhance.EnhancedInstance;
import org.apache.skywalking.apm.agent.core.plugin.interceptor.enhance.InstanceMethodsAroundInterceptor;
import org.apache.skywalking.apm.agent.core.plugin.interceptor.enhance.MethodInterceptResult;
import org.springframework.beans.BeanWrapperImpl;
public class GetPropertyDescriptorsInterceptor implements InstanceMethodsAroundInterceptor {
@Override
public void beforeMethod(EnhancedInstance objInst, Method method, Object[] allArguments, Class<?>[] argumentsTypes,
MethodInterceptResult result) throws Throwable {
}
@Override
public Object afterMethod(EnhancedInstance objInst, Method method, Object[] allArguments, Class<?>[] argumentsTypes,
Object ret) throws Throwable {
PropertyDescriptor[] propertyDescriptors = (PropertyDescriptor[])ret;
if (EnhancedInstance.class.isAssignableFrom(((BeanWrapperImpl)objInst).getRootClass())) {
List<PropertyDescriptor> newPropertyDescriptors = new ArrayList<PropertyDescriptor>();
for (PropertyDescriptor descriptor : propertyDescriptors) {
if (!descriptor.getName().equals("skyWalkingDynamicField")) {
newPropertyDescriptors.add(descriptor);
}
}
return newPropertyDescriptors.toArray(new PropertyDescriptor[newPropertyDescriptors.size()]);
}
return ret;
}
@Override public void handleMethodException(EnhancedInstance objInst, Method method, Object[] allArguments,
Class<?>[] argumentsTypes, Throwable t) {
}
}
|
package fdmc.web.mbeans;
import fdmc.domain.model.binding.CatCreateBindingModel;
import fdmc.domain.model.service.CatServiceModel;
import fdmc.service.CatService;
import org.modelmapper.ModelMapper;
import javax.enterprise.context.RequestScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.inject.Named;
import java.io.IOException;
@Named
@RequestScoped
public class CreateCatBean {
private CatCreateBindingModel catCreateBindingModel;
private ModelMapper modelMapper;
private CatService catService;
public CreateCatBean() {
this.catCreateBindingModel = new CatCreateBindingModel();
}
@Inject
public CreateCatBean(ModelMapper modelMapper, CatService catService) {
this();
this.modelMapper = modelMapper;
this.catService = catService;
}
public void createCat() throws IOException {
boolean isSaved = this.catService
.save(this.modelMapper.map(this.catCreateBindingModel, CatServiceModel.class));
ExternalContext context = FacesContext.getCurrentInstance().getExternalContext();
if (isSaved) {
context.redirect("/");
}
}
public CatCreateBindingModel getCatCreateBindingModel() {
return catCreateBindingModel;
}
public void setCatCreateBindingModel(CatCreateBindingModel catCreateBindingModel) {
this.catCreateBindingModel = catCreateBindingModel;
}
}
|
/*
* 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.live.v20180801.models;
import com.tencentcloudapi.common.AbstractModel;
import com.google.gson.annotations.SerializedName;
import com.google.gson.annotations.Expose;
import java.util.HashMap;
public class DescribeLiveCertResponse extends AbstractModel{
/**
* Certificate information.
*/
@SerializedName("CertInfo")
@Expose
private CertInfo CertInfo;
/**
* The unique request ID, which is returned for each request. RequestId is required for locating a problem.
*/
@SerializedName("RequestId")
@Expose
private String RequestId;
/**
* Get Certificate information.
* @return CertInfo Certificate information.
*/
public CertInfo getCertInfo() {
return this.CertInfo;
}
/**
* Set Certificate information.
* @param CertInfo Certificate information.
*/
public void setCertInfo(CertInfo CertInfo) {
this.CertInfo = CertInfo;
}
/**
* Get The unique request ID, which is returned for each request. RequestId is required for locating a problem.
* @return RequestId The unique request ID, which is returned for each request. RequestId is required for locating a problem.
*/
public String getRequestId() {
return this.RequestId;
}
/**
* Set The unique request ID, which is returned for each request. RequestId is required for locating a problem.
* @param RequestId The unique request ID, which is returned for each request. RequestId is required for locating a problem.
*/
public void setRequestId(String RequestId) {
this.RequestId = RequestId;
}
public DescribeLiveCertResponse() {
}
/**
* 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 DescribeLiveCertResponse(DescribeLiveCertResponse source) {
if (source.CertInfo != null) {
this.CertInfo = new CertInfo(source.CertInfo);
}
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.setParamObj(map, prefix + "CertInfo.", this.CertInfo);
this.setParamSimple(map, prefix + "RequestId", this.RequestId);
}
}
|
package org.jhipster.health.web.rest;
import org.jhipster.health.service.AuditEventService;
import org.jhipster.health.web.propertyeditors.LocaleDateTimeEditor;
import org.joda.time.LocalDateTime;
import org.springframework.boot.actuate.audit.AuditEvent;
import org.springframework.http.MediaType;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import javax.inject.Inject;
import java.util.List;
/**
* REST controller for getting the audit events.
*/
@RestController
@RequestMapping("/api")
public class AuditResource {
@Inject
private AuditEventService auditEventService;
@InitBinder
public void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(LocalDateTime.class, new LocaleDateTimeEditor("yyyy-MM-dd", false));
}
@RequestMapping(value = "/audits/all",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
public List<AuditEvent> findAll() {
return auditEventService.findAll();
}
@RequestMapping(value = "/audits/byDates",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
public List<AuditEvent> findByDates(@RequestParam(value = "fromDate") LocalDateTime fromDate,
@RequestParam(value = "toDate") LocalDateTime toDate) {
return auditEventService.findByDates(fromDate, toDate);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.