text
stringlengths
7
1.01M
/* * 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.action.explain; import org.apache.lucene.search.Explanation; import org.elasticsearch.ElasticsearchException; import org.elasticsearch.action.ActionListener; import org.elasticsearch.action.RoutingMissingException; import org.elasticsearch.action.support.ActionFilters; import org.elasticsearch.action.support.single.shard.TransportSingleShardAction; import org.elasticsearch.cluster.ClusterState; import org.elasticsearch.cluster.metadata.IndexNameExpressionResolver; import org.elasticsearch.cluster.routing.ShardIterator; import org.elasticsearch.cluster.service.ClusterService; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.io.stream.Writeable; import org.elasticsearch.common.lease.Releasables; import org.elasticsearch.index.IndexService; import org.elasticsearch.index.engine.Engine; import org.elasticsearch.index.get.GetResult; import org.elasticsearch.index.shard.IndexShard; import org.elasticsearch.index.shard.ShardId; import org.elasticsearch.search.SearchService; import org.elasticsearch.search.internal.AliasFilter; import org.elasticsearch.search.internal.SearchContext; import org.elasticsearch.search.internal.ShardSearchRequest; import org.elasticsearch.search.rescore.RescoreContext; import org.elasticsearch.search.rescore.Rescorer; import org.elasticsearch.tasks.Task; import org.elasticsearch.threadpool.ThreadPool; import org.elasticsearch.transport.TransportService; import java.io.IOException; import java.util.Set; /** * Explain transport action. Computes the explain on the targeted shard. */ // TODO: AggregatedDfs. Currently the idf can be different then when executing a normal search with explain. public class TransportExplainAction extends TransportSingleShardAction<ExplainRequest, ExplainResponse> { private final SearchService searchService; @Inject public TransportExplainAction(ThreadPool threadPool, ClusterService clusterService, TransportService transportService, SearchService searchService, ActionFilters actionFilters, IndexNameExpressionResolver indexNameExpressionResolver) { super(ExplainAction.NAME, threadPool, clusterService, transportService, actionFilters, indexNameExpressionResolver, ExplainRequest::new, ThreadPool.Names.GET); this.searchService = searchService; } @Override protected void doExecute(Task task, ExplainRequest request, ActionListener<ExplainResponse> listener) { request.nowInMillis = System.currentTimeMillis(); super.doExecute(task, request, listener); } @Override protected boolean resolveIndex(ExplainRequest request) { return true; } @Override protected void resolveRequest(ClusterState state, InternalRequest request) { final Set<String> indicesAndAliases = indexNameExpressionResolver.resolveExpressions(state, request.request().index()); final AliasFilter aliasFilter = searchService.buildAliasFilter(state, request.concreteIndex(), indicesAndAliases); request.request().filteringAlias(aliasFilter); // Fail fast on the node that received the request. if (request.request().routing() == null && state.getMetadata().routingRequired(request.concreteIndex())) { throw new RoutingMissingException(request.concreteIndex(), request.request().id()); } } @Override protected void asyncShardOperation(ExplainRequest request, ShardId shardId, ActionListener<ExplainResponse> listener) throws IOException { IndexService indexService = searchService.getIndicesService().indexServiceSafe(shardId.getIndex()); IndexShard indexShard = indexService.getShard(shardId.id()); indexShard.awaitShardSearchActive(b -> { try { super.asyncShardOperation(request, shardId, listener); } catch (Exception ex) { listener.onFailure(ex); } }); } @Override protected ExplainResponse shardOperation(ExplainRequest request, ShardId shardId) throws IOException { ShardSearchRequest shardSearchLocalRequest = new ShardSearchRequest(shardId, request.nowInMillis, request.filteringAlias()); SearchContext context = searchService.createSearchContext(shardSearchLocalRequest, SearchService.NO_TIMEOUT); Engine.GetResult result = null; try { // No need to check the type, IndexShard#get does it for us result = context.indexShard().get(new Engine.Get(false, false, request.id())); if (!result.exists()) { return new ExplainResponse(shardId.getIndexName(), request.id(), false); } context.parsedQuery(context.getQueryShardContext().toQuery(request.query())); context.preProcess(true); int topLevelDocId = result.docIdAndVersion().docId + result.docIdAndVersion().docBase; Explanation explanation = context.searcher().explain(context.query(), topLevelDocId); for (RescoreContext ctx : context.rescore()) { Rescorer rescorer = ctx.rescorer(); explanation = rescorer.explain(topLevelDocId, context.searcher(), ctx, explanation); } if (request.storedFields() != null || (request.fetchSourceContext() != null && request.fetchSourceContext().fetchSource())) { // Advantage is that we're not opening a second searcher to retrieve the _source. Also // because we are working in the same searcher in engineGetResult we can be sure that a // doc isn't deleted between the initial get and this call. GetResult getResult = context.indexShard().getService().get(result, request.id(), request.storedFields(), request.fetchSourceContext()); return new ExplainResponse(shardId.getIndexName(), request.id(), true, explanation, getResult); } else { return new ExplainResponse(shardId.getIndexName(), request.id(), true, explanation); } } catch (IOException e) { throw new ElasticsearchException("Could not explain", e); } finally { Releasables.close(result, context); } } @Override protected Writeable.Reader<ExplainResponse> getResponseReader() { return ExplainResponse::new; } @Override protected ShardIterator shards(ClusterState state, InternalRequest request) { return clusterService.operationRouting().getShards( clusterService.state(), request.concreteIndex(), request.request().id(), request.request().routing(), request.request().preference() ); } @Override protected String getExecutor(ExplainRequest request, ShardId shardId) { IndexService indexService = searchService.getIndicesService().indexServiceSafe(shardId.getIndex()); return indexService.getIndexSettings().isSearchThrottled() ? ThreadPool.Names.SEARCH_THROTTLED : super.getExecutor(request, shardId); } }
package com.matas.liteconstruct.config.recaptcha; import com.fasterxml.jackson.annotation.*; import java.util.Date; import java.util.HashMap; import java.util.Map; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) @JsonPropertyOrder({ "success", "challenge_ts", "hostname", "error-codes" }) public class ReCaptchaResponse { @JsonProperty("success") private boolean success; @JsonProperty("challenge_ts") private Date challengeTs; @JsonProperty("hostname") private String hostname; @JsonProperty("error-codes") private ErrorCode[] errorCodes; @JsonIgnore public boolean hasClientError() { ErrorCode[] errors = getErrorCodes(); if(errors == null) { return false; } for(ErrorCode error : errors) { switch(error) { case InvalidResponse: case MissingResponse: return true; } } return false; } static enum ErrorCode { MissingSecret, InvalidSecret, MissingResponse, InvalidResponse; private static Map<String, ErrorCode> errorsMap = new HashMap<>(4); static { errorsMap.put("missing-input-secret", MissingSecret); errorsMap.put("invalid-input-secret", InvalidSecret); errorsMap.put("missing-input-response", MissingResponse); errorsMap.put("invalid-input-response", InvalidResponse); } @JsonCreator public static ErrorCode forValue(String value) { return errorsMap.get(value.toLowerCase()); } } public boolean isSuccess() { return success; } public void setSuccess(boolean success) { this.success = success; } public Date getChallengeTs() { return challengeTs; } public void setChallengeTs(Date challengeTs) { this.challengeTs = challengeTs; } public String getHostname() { return hostname; } public void setHostname(String hostname) { this.hostname = hostname; } public ErrorCode[] getErrorCodes() { return errorCodes; } public void setErrorCodes(ErrorCode[] errorCodes) { this.errorCodes = errorCodes; } }
package com.planet_ink.coffee_mud.Items.Basic; import com.planet_ink.coffee_mud.core.interfaces.*; import com.planet_ink.coffee_mud.core.*; import com.planet_ink.coffee_mud.core.collections.*; import com.planet_ink.coffee_mud.Abilities.interfaces.*; import com.planet_ink.coffee_mud.Areas.interfaces.*; import com.planet_ink.coffee_mud.Behaviors.interfaces.*; import com.planet_ink.coffee_mud.CharClasses.interfaces.*; import com.planet_ink.coffee_mud.Commands.interfaces.*; import com.planet_ink.coffee_mud.Common.interfaces.*; import com.planet_ink.coffee_mud.Exits.interfaces.*; import com.planet_ink.coffee_mud.Items.interfaces.*; import com.planet_ink.coffee_mud.Libraries.interfaces.*; import com.planet_ink.coffee_mud.Locales.interfaces.*; import com.planet_ink.coffee_mud.MOBS.interfaces.*; import com.planet_ink.coffee_mud.Races.interfaces.*; import java.util.*; /* Copyright 2001-2022 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. */ public class GenWater extends GenDrink { @Override public String ID() { return "GenWater"; } public GenWater() { super(); readableText = ""; setName("a generic puddle of water"); basePhyStats.setWeight(2); setDisplayText("a generic puddle of water sits here."); setDescription(""); baseGoldValue=0; capacity=0; amountOfThirstQuenched=250; amountOfLiquidHeld=10000; amountOfLiquidRemaining=10000; setMaterial(RawMaterial.RESOURCE_FRESHWATER); basePhyStats().setSensesMask(PhyStats.SENSE_ITEMNOTGET); recoverPhyStats(); } }
package com.sequenceiq.cloudbreak.service.cluster.flow; import java.util.List; import com.ecwid.consul.v1.ConsulClient; import com.sequenceiq.cloudbreak.domain.Stack; import com.sequenceiq.cloudbreak.service.StackContext; public class ConsulKVCheckerContext extends StackContext { private final ConsulClient consulClient; private final List<String> keys; private final String expectedValue; private final String failValue; public ConsulKVCheckerContext(Stack stack, ConsulClient consulClient, List<String> keys, String expectedValue, String failValue) { super(stack); this.consulClient = consulClient; this.keys = keys; this.expectedValue = expectedValue; this.failValue = failValue; } public ConsulClient getConsulClient() { return consulClient; } public List<String> getKeys() { return keys; } public String getExpectedValue() { return expectedValue; } public String getFailValue() { return failValue; } }
package org.almotech.oscal.utils; import android.annotation.TargetApi; import android.content.Intent; import android.nfc.NdefMessage; import android.nfc.NfcAdapter; import android.os.Build; import android.os.Parcelable; /** * NFC helper methods for receiving data sent by NfcSenderUtils. This class wraps API 10+ code. * * @author Christophe Beyls * */ @TargetApi(Build.VERSION_CODES.GINGERBREAD_MR1) class NfcReceiverUtils { public static boolean hasAppData(Intent intent) { return NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction()); } public static byte[] extractAppData(Intent intent) { Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES); NdefMessage msg = (NdefMessage) rawMsgs[0]; return msg.getRecords()[0].getPayload(); } }
package com.github.wxiaoqi.security.auth.controller; import javax.servlet.http.HttpServletRequest; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import com.github.wxiaoqi.security.auth.service.AuthService; import com.github.wxiaoqi.security.auth.util.user.JwtAuthenticationRequest; import com.github.wxiaoqi.security.auth.util.user.JwtAuthenticationResponse; import com.github.wxiaoqi.security.auth.util.user.PhoneAuthenticationRequest; import com.github.wxiaoqi.security.auth.vo.FrontUser; import com.github.wxiaoqi.security.common.msg.AppResponse; @RestController @RequestMapping("jwt") public class AuthController { @Value("${jwt.token-header}") private String tokenHeader; @Value("${jwt.expire}") private String expire; @Autowired private AuthService authService; @RequestMapping(value = "admin/token", method = RequestMethod.POST) public ResponseEntity<?> createAdminAuthenticationToken( @RequestBody JwtAuthenticationRequest authenticationRequest) throws Exception { final String token = authService.adminLogin(authenticationRequest.getUsername(), authenticationRequest.getPassword()); return ResponseEntity.ok(new JwtAuthenticationResponse(token,expire,true)); } @RequestMapping(value = "app/token", method = RequestMethod.POST) public ResponseEntity<?> createAppAuthenticationToken( @RequestBody JwtAuthenticationRequest authenticationRequest) throws Exception { final String token = authService.appLogin(authenticationRequest.getUsername(), authenticationRequest.getPassword()); if(StringUtils.isEmpty(token)){ return ResponseEntity.ok(new AppResponse(200, "用户名密码错误", false)); } return ResponseEntity.ok(new JwtAuthenticationResponse(token,expire,true)); } @RequestMapping(value = "app/phone/token", method = RequestMethod.POST) public ResponseEntity<?> createAppAuthenticationToken( @RequestBody PhoneAuthenticationRequest authenticationRequest) throws Exception { final String token = authService.phoneLogin(authenticationRequest.getPhone(), authenticationRequest.getIdentifyCode()); if(StringUtils.isEmpty(token)){ return ResponseEntity.ok(new AppResponse(200, "验证码错误", null)); } return ResponseEntity.ok(new JwtAuthenticationResponse(token,expire,true)); } @RequestMapping(value = "refresh", method = RequestMethod.GET) public ResponseEntity<?> refreshAndGetAuthenticationToken( HttpServletRequest request) { String token = request.getHeader(tokenHeader); String refreshedToken = authService.refresh(token); if(refreshedToken == null) { return ResponseEntity.badRequest().body(null); } else { return ResponseEntity.ok(new JwtAuthenticationResponse(refreshedToken,expire,true)); } } @RequestMapping(value = "verify", method = RequestMethod.GET) public ResponseEntity<?> verify(String token) throws Exception { authService.validate(token); return ResponseEntity.ok(true); } @RequestMapping(value = "invalid", method = RequestMethod.POST) public ResponseEntity<?> invalid(@RequestHeader("access-token") String token){ authService.invalid(token); return ResponseEntity.ok(true); } @RequestMapping(value = "user", method = RequestMethod.GET) public ResponseEntity<?> getUserInfo(String token) throws Exception { FrontUser userInfo = authService.getUserInfo(token); if(userInfo==null) { return ResponseEntity.status(401).body(false); } else { return ResponseEntity.ok(userInfo); } } }
package com.jpmorrsn.fbp.examples.networks; // Change as required import java.io.File; import com.jpmorrsn.fbp.components.ReadFile; import com.jpmorrsn.fbp.components.RegExReplace; import com.jpmorrsn.fbp.components.WriteFile; import com.jpmorrsn.fbp.engine.Network; import com.jpmorrsn.fbp.examples.components.BuildBlob; /* This test tests RegExReplace */ public class TPX extends Network { static final String copyright = "Copyright 2007, 2008, 2011, ...."; @Override protected void define() { connect(component("Read", ReadFile.class), port("OUT"), component("BB", BuildBlob.class), port("IN")); initialize("C:\\Users\\Paul\\Documents\\Business\\FBP\\book_orig.xhtml,UTF8".replace("\\", File.separator), component("Read"), port("SOURCE")); component("Write", WriteFile.class); component("RER0", RegExReplace.class); component("RER1", RegExReplace.class); component("RER2", RegExReplace.class); component("RER3", RegExReplace.class); component("RER31", RegExReplace.class); component("RER32", RegExReplace.class); component("RER33", RegExReplace.class); //component("RER4", RegExReplace.class); //component("RER5", RegExReplace.class); //component("RER6", RegExReplace.class); connect("BB.OUT", "RER0.IN"); connect("RER0.OUT", "RER1.IN"); connect("RER1.OUT", "RER2.IN"); connect("RER2.OUT", "RER3.IN"); connect("RER3.OUT", "RER31.IN"); connect("RER31.OUT", "RER32.IN"); connect("RER32.OUT", "RER33.IN"); //connect("RER33.OUT", "RER4.IN"); //connect("RER4.OUT", "RER5.IN"); //connect("RER5.OUT", "RER6.IN"); connect("RER33.OUT", "Write.IN"); initialize("C:\\Users\\Paul\\Documents\\Business\\FBP\\book.html,UTF8".replace("\\", File.separator), component("Write"), port("DESTINATION")); // non-breaking blanks -> blanks initialize("|\\u00a0| ", component("RER0"), port("MASKS")); // Chapter 17 – page <a href="#refpoml">1</a> -> <a href="#refpoml">Chapter 17</a> initialize("|(Chapter\\s+\\d+)\\s+\\–\\s+page\\s*\\<a\\s(href=\"#ref\\w+\")\\>1\\<\\/a\\>|\\<a $2\\>$1\\<\\/a\\>", component("RER1"), port("MASKS")); // Chapter 17 (page <a href="#refpoml">1</a>) -> <a href="#refpoml">Chapter 17</a> ... Chapter 26  (page <a href="#refrel">1</a>) initialize("|(Chapter\\s+\\d+)\\s+\\(page\\s*\\<a\\s(href=\"#ref\\w+\")\\>1\\<\\/a\\>\\)|\\<a $2\\>$1\\<\\/a\\>", component("RER2"), port("MASKS")); // Chapter 17, page <a href="#refpoml">1</a> -> <a href="#refpoml">Chapter 17</a> initialize("|(Chapter\\s+\\d+)\\s*\\,\\s+page\\s*\\<a\\s(href=\"#ref\\w+\")\\>1\\<\\/a\\>|\\<a $2\\>$1\\<\\/a\\>", component("RER3"), port("MASKS")); //p. or pp. <a href="#reftablelookup">1<\\/a> -> <a href="#reftablelookup">click here<\\/a> initialize("|p+.\\s+\\<a\\s(href=\"#ref\\w+\")\\>1\\<\\/a\\>|\\<a $1\\>click here\\<\\/a\\>", component("RER31"), port("MASKS")); //xxxxx (page <a href="#refperform">1<\\/a>) -> <a href="#refperform">xxxxx<\\/a> initialize("|(\\w+)\\s+\\(page\\s*\\<a\\s(href=\"#ref\\w+\")\\>1\\<\\/a\\>\\)|\\<a $2\\>$1\\<\\/a\\>", component("RER32"), port("MASKS")); //xxxxx - page <a href="#refperform">1<\\/a> -> <a href="#refperform">xxxxx<\\/a> initialize("|(\\w+)\\s+\\–\\s+page\\s*\\<a\\s(href=\"#ref\\w+\")\\>1\\<\\/a\\>|\\<a $2\\>$1\\<\\/a\\>", component("RER33"), port("MASKS")); //<a href="#reftablelookup">1<\\/a> //initialize("|<a//s+(href=\"#ref\\w+\")>1<\\/a>|<a $1>click here<\\/a>", component("RER32"), port("MASKS")); // initialize("|“(.+?)”|&ldquo;$1&rdquo;", component("RER4"), port("MASKS")); // initialize("|’|&rsquo;", component("RER5"), port("MASKS")); // initialize("|–|&ndash;", component("RER6"), port("MASKS")); } public static void main(final String[] argv) throws Exception { new TPX().go(); } }
package org.onvif.ver10.schema; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for BacklightCompensationOptions20 complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="BacklightCompensationOptions20"&gt; * &lt;complexContent&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt; * &lt;sequence&gt; * &lt;element name="Mode" type="{http://www.onvif.org/ver10/schema}BacklightCompensationMode" maxOccurs="unbounded"/&gt; * &lt;element name="Level" type="{http://www.onvif.org/ver10/schema}FloatRange" minOccurs="0"/&gt; * &lt;/sequence&gt; * &lt;/restriction&gt; * &lt;/complexContent&gt; * &lt;/complexType&gt; * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "BacklightCompensationOptions20", propOrder = { "mode", "level" }) public class BacklightCompensationOptions20 { @XmlElement(name = "Mode", required = true) @XmlSchemaType(name = "string") protected List<BacklightCompensationMode> mode; @XmlElement(name = "Level") protected FloatRange level; /** * Gets the value of the mode property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the mode property. * * <p> * For example, to add a new item, do as follows: * <pre> * getMode().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link BacklightCompensationMode } * * */ public List<BacklightCompensationMode> getMode() { if (mode == null) { mode = new ArrayList<BacklightCompensationMode>(); } return this.mode; } /** * Gets the value of the level property. * * @return * possible object is * {@link FloatRange } * */ public FloatRange getLevel() { return level; } /** * Sets the value of the level property. * * @param value * allowed object is * {@link FloatRange } * */ public void setLevel(FloatRange value) { this.level = value; } }
/* * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH under * one or more contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright ownership. * Licensed under the Zeebe Community License 1.0. You may not use this file * except in compliance with the Zeebe Community License 1.0. */ package io.zeebe.db.impl; import static org.assertj.core.api.Assertions.assertThat; import org.agrona.ExpandableArrayBuffer; import org.junit.Test; public class DbByteTest { private final DbByte zbByte = new DbByte(); @Test public void shouldWrapByte() { // given zbByte.wrapByte((byte) 255); // when final ExpandableArrayBuffer buffer = new ExpandableArrayBuffer(); zbByte.write(buffer, 0); // then assertThat(zbByte.getLength()).isEqualTo(Byte.BYTES); assertThat(zbByte.getValue()).isEqualTo((byte) 255); assertThat(buffer.getByte(0)).isEqualTo((byte) 255); } @Test public void shouldWrap() { // given final ExpandableArrayBuffer valueBuffer = new ExpandableArrayBuffer(); valueBuffer.putByte(0, (byte) 255); zbByte.wrap(valueBuffer, 0, 1); // when final ExpandableArrayBuffer buffer = new ExpandableArrayBuffer(); zbByte.write(buffer, 0); // then assertThat(zbByte.getLength()).isEqualTo(Byte.BYTES); assertThat(zbByte.getValue()).isEqualTo((byte) 255); assertThat(buffer.getByte(0)).isEqualTo((byte) 255); } }
package dev.stan.plugin.listeners; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerJoinEvent; import dev.stan.plugin.RickChat; public class JoinListener implements Listener { private final RickChat plugin; public JoinListener(RickChat plugin) { this.plugin = plugin; plugin.getCustomConfig().getList("messages.respond.welcome-back"); } @EventHandler public void onJoin(PlayerJoinEvent event) { if (!event.getPlayer().hasPermission(plugin.getCustomConfig().getString("permissions.mute"))) { for (Player p : Bukkit.getOnlinePlayers()) { if (p.getName().equalsIgnoreCase(plugin.getCustomConfig().getString("special-player"))) { p.sendMessage(plugin.prefix + plugin.color + plugin.getCustomConfig().getString("messages.respond.welcome-back") + event.getPlayer().getName()); } p.sendMessage(plugin.prefix + plugin.color + plugin.getCustomConfig().getString("messages.respond.welcome-back")); } } } }
/* * TestMultipleMessagePanel.java * * Created on August 27, 2001, 2:57 PM */ package messagepaneldemo; /** * * @author administrator */ public class TestMultipleMessagePanel extends javax.swing.JApplet { /** Creates new form TestMultipleMessagePanel */ public TestMultipleMessagePanel() { initComponents(); } /** 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. */ private void initComponents() {//GEN-BEGIN:initComponents multipleMessagePanel1 = new messagepaneldemo.MultipleMessagePanel(); multipleMessagePanel1.setMessages(new String[] { "message1", "message2", "message3", "message4"}); getContentPane().add(multipleMessagePanel1, java.awt.BorderLayout.CENTER); }//GEN-END:initComponents // Variables declaration - do not modify//GEN-BEGIN:variables private messagepaneldemo.MultipleMessagePanel multipleMessagePanel1; // End of variables declaration//GEN-END:variables }
package by.home.hryhoryeu.realty.dba.dao.user; import by.home.hryhoryeu.realty.entities.model.user.User; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.transaction.annotation.Transactional; @ExtendWith(SpringExtension.class) @Transactional @ContextConfiguration({"classpath:service-config-test.xml" }) public class UserDaoTest { @Autowired private IUserDao userDao; @Test void getUserByIdTest() { User user1 = userDao.findById(1L); User user2 = UserTestData.getUser(); Assertions.assertEquals(user1, user2); } @Test void setUser() { Long expectedId = 2L; User user = UserTestData.getUser(); Long actualId = userDao.set(user); userDao.set(user); Assertions.assertEquals(expectedId, actualId); } @Test void updateUser() { Long expectedId = 1L; User expectedUserData = userDao.findById(expectedId); expectedUserData.setLogin("asdf"); expectedUserData.setSkype("Skype123"); userDao.update(expectedUserData); User actualUserData = userDao.findById(expectedId); Assertions.assertEquals(expectedUserData, actualUserData); } @Test void findByLoginUser() { String userLogin = "maxim"; User expectedUserData = UserTestData.getUser(); User actualUserData = userDao.findByLogin(userLogin); Assertions.assertEquals(expectedUserData, actualUserData); } }
package extracells.integration.waila; import appeng.api.parts.IPartHost; import cpw.mods.fml.common.Optional; import cpw.mods.fml.common.event.FMLInterModComms; import extracells.tileentity.TileEntityCertusTank; import mcp.mobius.waila.api.IWailaDataProvider; import mcp.mobius.waila.api.IWailaRegistrar; public class Waila { public static void init() { FMLInterModComms.sendMessage("Waila", "register", Waila.class.getName() + ".register"); } @Optional.Method(modid = "Waila") public static void register(IWailaRegistrar registrar) { final IWailaDataProvider partHost = new PartWailaDataProvider(); registrar.registerBodyProvider(partHost, IPartHost.class); registrar.registerNBTProvider(partHost, IPartHost.class); final IWailaDataProvider tileCertusTank = new TileCertusTankWailaDataProvider(); registrar.registerBodyProvider(tileCertusTank, TileEntityCertusTank.class); registrar.registerNBTProvider(tileCertusTank, TileEntityCertusTank.class); final IWailaDataProvider blocks = new BlockWailaDataProvider(); registrar.registerBodyProvider(blocks, IWailaTile.class); registrar.registerNBTProvider(blocks, IWailaTile.class); } }
package il.org.spartan.spartanizer.issues; import static fluent.ly.azzert.is; import org.eclipse.jdt.core.dom.ASTParser; import org.eclipse.jdt.core.dom.CompilationUnit; import org.junit.Test; import fluent.ly.azzert; import il.org.spartan.spartanizer.ast.navigate.wizard; import il.org.spartan.spartanizer.utils.tdd.enumerate; /** Test class for tdd.enumerate.methods (see issue #679) * @author Sharon Kuninin * @author Yarden Lev * @since Nov 2, 2016 */ @SuppressWarnings("static-method") public class Issue0679 { public static CompilationUnit cu(final String program) { final ASTParser $ = wizard.parser(ASTParser.K_COMPILATION_UNIT); $.setSource(program.toCharArray()); return (CompilationUnit) $.createAST(null); } @Test public void checkExistence() { enumerate.methods(null); } @Test public void checkParameterType() { enumerate.methods(null); } @Test public void checkReturnType() { enumerate.methods(null); } @Test public void methodInOutterClassAndMethodInInnerClass() { azzert.that(enumerate.methods(cu("class A { void a() {} class B { void b() {} } }")), is(2)); } @Test public void methodsInsideInnerClass() { azzert.that(enumerate.methods(cu("class A { class B { void a() {} } }")), is(1)); } @Test public void methodsWithBody() { azzert.that(enumerate.methods(cu("class A { int a1() {return 1;} int a2() {return 2;} int a3() {return 3;} }")), is(3)); } @Test public void methodsWithParameters() { azzert.that(enumerate.methods(cu("class A { int a1(int n) {return n;} int a2(int m) {return (m+1);} }")), is(2)); } @Test public void noMethodsInCompilationUnit() { azzert.that(enumerate.methods(cu("1111")), is(0)); } @Test public void oneMethodInCompilationUnit() { azzert.that(enumerate.methods(cu("class A { void a() {} }")), is(1)); } @Test public void twoMethodsInCompilationUnit() { azzert.that(enumerate.methods(cu("class A { void a1() {} void a2() {} }")), is(2)); } @Test public void zeroReturnedWhenNullIsSent() { azzert.that(enumerate.methods(null), is(0)); } }
package com.example.medicinetime.views; import android.content.Context; import android.graphics.Typeface; import androidx.appcompat.widget.AppCompatTextView; import android.util.AttributeSet; import com.example.medicinetime.utils.FontUtil; public class RobotoRegularTextView extends AppCompatTextView { public RobotoRegularTextView(Context context) { super(context); applyCustomFont(); } public RobotoRegularTextView(Context context, AttributeSet attrs) { super(context, attrs); applyCustomFont(); } public RobotoRegularTextView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); applyCustomFont(); } private void applyCustomFont() { Typeface customFont = FontUtil.getTypeface(FontUtil.ROBOTO_REGULAR); setTypeface(customFont); } }
package com.gfso.util; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; public class PasswordEncoderGenerator { public static void main(String[] args) { int i = 0; while (i < 10) { String password = "123456"; BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder(); String hashedPassword = passwordEncoder.encode(password); System.out.println(hashedPassword); i++; } } }
/* * Copyright (C) Tony Green, LitePal Framework Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.litepal.crud.async; /** * A simple async executor to run tasks in background thread. * * @author Tony Green * @since 2017/2/22 */ public abstract class AsyncExecutor { /** * Task that pending to run. */ private Runnable pendingTask; /** * Submit a task for pending executing. * @param task * The task with specific database operation. */ public void submit(Runnable task) { pendingTask = task; } /** * Run the pending task in background thread. */ void execute() { if (pendingTask != null) { new Thread(pendingTask).start(); } } }
package com.blossomproject.ui.web.administration.role; import com.google.common.base.Strings; import com.google.common.collect.Maps; import com.blossomproject.core.common.dto.AbstractDTO; import com.blossomproject.core.common.search.SearchEngineImpl; import com.blossomproject.core.common.utils.privilege.Privilege; import com.blossomproject.core.common.utils.tree.TreeNode; import com.blossomproject.core.role.RoleCreateForm; import com.blossomproject.core.role.RoleDTO; import com.blossomproject.core.role.RolePrivilegeUpdateForm; import com.blossomproject.core.role.RoleService; import com.blossomproject.core.role.RoleUpdateForm; import com.blossomproject.ui.menu.OpenedMenu; import com.blossomproject.ui.stereotype.BlossomController; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.NoSuchElementException; import java.util.Optional; import java.util.stream.Collectors; import javax.servlet.http.HttpServletRequest; import javax.validation.Valid; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.MessageSource; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.web.PageableDefault; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.servlet.ModelAndView; /** * Created by Maël Gargadennnec on 05/05/2017. */ @BlossomController @RequestMapping("/administration/roles") @OpenedMenu("roles") public class RolesController { private static final Logger logger = LoggerFactory.getLogger(RolesController.class); private final RoleService roleService; private final SearchEngineImpl<RoleDTO> searchEngine; private final MessageSource messageSource; public RolesController(RoleService roleService, SearchEngineImpl<RoleDTO> searchEngine, MessageSource messageSource) { this.roleService = roleService; this.searchEngine = searchEngine; this.messageSource = messageSource; } @GetMapping @PreAuthorize("hasAuthority('administration:roles:read')") public ModelAndView getRolesPage(@RequestParam(value = "q", required = false) String q, @PageableDefault(size = 25) Pageable pageable, Model model) { return tableView(q, pageable, model, "blossom/roles/roles"); } private ModelAndView tableView(String q, Pageable pageable, Model model, String viewName) { Page<RoleDTO> roles; if (Strings.isNullOrEmpty(q)) { roles = this.roleService.getAll(pageable); } else { roles = this.searchEngine.search(q, pageable).getPage(); } model.addAttribute("roles", roles); model.addAttribute("q", q); return new ModelAndView(viewName, model.asMap()); } @GetMapping("/_create") @PreAuthorize("hasAuthority('administration:roles:create')") public ModelAndView getRoleCreatePage(Model model, Locale locale) { return this.createView(new RoleCreateForm(), model); } @PostMapping("/_create") @PreAuthorize("hasAuthority('administration:roles:create')") public ModelAndView handleRoleCreateForm( @Valid @ModelAttribute("roleCreateForm") RoleCreateForm roleCreateForm, BindingResult bindingResult, Model model) { if (bindingResult.hasErrors()) { return this.createView(roleCreateForm, model); } try { RoleDTO role = this.roleService.create(roleCreateForm); return new ModelAndView("redirect:../roles/" + role.getId()); } catch (Exception e) { logger .error("Error on creating role, name " + roleCreateForm.getName() + " already exists ", e); return this.createView(roleCreateForm, model); } } private ModelAndView createView(RoleCreateForm roleCreateForm, Model model) { model.addAttribute("roleCreateForm", roleCreateForm); return new ModelAndView("blossom/roles/create", model.asMap()); } @GetMapping("/{id}") @PreAuthorize("hasAuthority('administration:roles:read')") public ModelAndView getRole(@PathVariable Long id, Model model, HttpServletRequest request) { RoleDTO role = this.roleService.getOne(id); if (role == null) { throw new NoSuchElementException(String.format("Role=%s not found", id)); } model.addAttribute("role", role); return new ModelAndView("blossom/roles/role", "role", role); } @PostMapping("/{id}/_delete") @PreAuthorize("hasAuthority('administration:roles:delete')") @ResponseBody public ResponseEntity<Map<Class<? extends AbstractDTO>, Long>> deleteRole( @PathVariable Long id, @RequestParam(value = "force", required = false, defaultValue = "false") Boolean force) { Optional<Map<Class<? extends AbstractDTO>, Long>> result = this.roleService .delete(this.roleService.getOne(id), force); if (!result.isPresent() || result.get().isEmpty()) { return new ResponseEntity<>(Maps.newHashMap(), HttpStatus.OK); } else { return new ResponseEntity<>(result.get(), HttpStatus.CONFLICT); } } @GetMapping("/{id}/_informations") @PreAuthorize("hasAuthority('administration:roles:read')") public ModelAndView getRoleInformations(@PathVariable Long id) { RoleDTO role = this.roleService.getOne(id); if (role == null) { throw new NoSuchElementException(String.format("Role=%s not found", id)); } return this.viewRoleInformationView(role); } @GetMapping("/{id}/_informations/_edit") @PreAuthorize("hasAuthority('administration:roles:write')") public ModelAndView getRoleInformationsForm(@PathVariable Long id, Model model, HttpServletRequest request) { RoleDTO role = this.roleService.getOne(id); if (role == null) { throw new NoSuchElementException(String.format("Role=%s not found", id)); } return this.updateRoleInformationView(new RoleUpdateForm(role), model, Optional.empty()); } @PostMapping("/{id}/_informations/_edit") @PreAuthorize("hasAuthority('administration:roles:write')") public ModelAndView handleRoleInformationsForm(@PathVariable Long id, Model model, @Valid @ModelAttribute("roleUpdateForm") RoleUpdateForm roleUpdateForm, BindingResult bindingResult) { if (bindingResult.hasErrors()) { return this .updateRoleInformationView(roleUpdateForm, model, Optional.of(HttpStatus.CONFLICT)); } RoleDTO role = this.roleService.getOne(id); if (role == null) { throw new NoSuchElementException(String.format("Role=%s not found", id)); } role.setName(roleUpdateForm.getName()); role.setDescription(roleUpdateForm.getDescription()); RoleDTO updatedRole = this.roleService.update(id, role); return this.viewRoleInformationView(updatedRole); } private ModelAndView viewRoleInformationView(RoleDTO role) { return new ModelAndView("blossom/roles/roleinformations", "role", role); } private ModelAndView updateRoleInformationView(RoleUpdateForm roleUpdateForm, Model model, Optional<HttpStatus> status) { ModelAndView modelAndView = new ModelAndView("blossom/roles/roleinformations-edit", "roleUpdateForm", roleUpdateForm); modelAndView.setStatus(status.orElse(HttpStatus.OK)); return modelAndView; } @GetMapping(value = "/privileges/tree", produces = MediaType.APPLICATION_JSON_VALUE) @ResponseBody public TreeNode<Privilege> privilegeTreeNode(Locale locale) { List<Privilege> availablePrivileges = this.roleService.getAvailablePrivileges(); TreeNode<Privilege> rootNode = new TreeNode<>("ALL", messageSource.getMessage("right.all", null, "right.all", locale), null); availablePrivileges .stream() .forEach(p -> { TreeNode<Privilege> treeNode = rootNode; String[] keyParts = p.privilege().split(":"); int i = 0; String currentKey = null; do { currentKey = currentKey != null ? currentKey + ":" + keyParts[i] : keyParts[i]; Optional<TreeNode<Privilege>> child = treeNode.findChildWithId(currentKey); if (child.isPresent()) { treeNode = child.get(); } else { String labelKey = ("right." + currentKey).replaceAll(":","."); TreeNode<Privilege> newNode = new TreeNode<>(currentKey, messageSource.getMessage(labelKey, null, labelKey, locale)); if(currentKey.equals(p.privilege())) { newNode.setData(p); } treeNode.addChild(newNode); treeNode = newNode; } i++; } while (i <= keyParts.length - 1); }); return rootNode; } @GetMapping("/{id}/_privileges") @PreAuthorize("hasAuthority('administration:roles:read')") public ModelAndView getRolePrivileges(@PathVariable Long id, Model model) { RoleDTO role = this.roleService.getOne(id); if (role == null) { throw new NoSuchElementException(String.format("Role=%s not found", id)); } return this.viewRolePrivilegeView(role, model); } @GetMapping("/{id}/_privileges/_edit") @PreAuthorize("hasAuthority('administration:roles:write')") public ModelAndView getRolePrivilegesForm(@PathVariable Long id, Model model) { RoleDTO role = this.roleService.getOne(id); if (role == null) { throw new NoSuchElementException(String.format("Role=%s not found", id)); } return this.updateRolePrivilegesView(new RolePrivilegeUpdateForm(role), model); } @PostMapping("/{id}/_privileges/_edit") @ResponseStatus(HttpStatus.OK) @PreAuthorize("hasAuthority('administration:roles:write')") public ModelAndView handleRolePrivilegesForm(@PathVariable Long id, @Valid @ModelAttribute("rolePrivilegeUpdateForm") RolePrivilegeUpdateForm rolePrivilegeUpdateForm, BindingResult bindingResult, Model model) { if (bindingResult.hasErrors()) { return this.updateRolePrivilegesView(rolePrivilegeUpdateForm, model); } RoleDTO role = this.roleService.getOne(id); List<String> availablePrivileges = this.roleService.getAvailablePrivileges().stream().map(Privilege::privilege).collect(Collectors.toList()); if (role == null) { throw new NoSuchElementException(String.format("Role=%s not found", id)); } role.setPrivileges(rolePrivilegeUpdateForm.getPrivileges().stream().filter(availablePrivileges::contains).collect(Collectors.toList())); RoleDTO updatedRole = this.roleService.update(id, role); return this.viewRolePrivilegeView(updatedRole, model); } private ModelAndView viewRolePrivilegeView(RoleDTO role, Model model) { model.addAttribute("role", role); return new ModelAndView("blossom/roles/roleprivileges", model.asMap()); } private ModelAndView updateRolePrivilegesView(RolePrivilegeUpdateForm rolePrivilegeUpdateForm, Model model) { model.addAttribute("rolePrivilegeUpdateForm", rolePrivilegeUpdateForm); ModelAndView modelAndView = new ModelAndView("blossom/roles/roleprivileges-edit", model.asMap()); return modelAndView; } }
/******************************************************************************* * Copyright 2018 Johns Hopkins University * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * This software was produced as part of the RMap Project (http://rmap-project.info), * The RMap Project was funded by the Alfred P. Sloan Foundation and is a * collaboration between Data Conservancy, Portico, and IEEE. *******************************************************************************/ package info.rmapproject.core.model; import java.util.Objects; import java.util.Optional; /** * Models the concept of an RDF Literal. Literals have a string value. * They can also optionally have a language and datatype * * @author smorrissey * Concrete class for RDF resources represented by a literal string. * @see http://www.w3.org/TR/2014/REC-rdf11-concepts-20140225/#resources-and-statements */ public class RMapLiteral implements RMapValue { /** The literal string value. */ String value; /** The language e.g. "en" or "fr". */ String language; /** The datatype of the literal e.g. http://www.w3.org/2001/XMLSchema#date (optional). */ RMapIri datatype; /** * Instantiates a new RMap literal. */ protected RMapLiteral() { super(); } /** * Instantiates a new RMap literal. * * @param value the string value * @throws IllegalArgumentException if value argument is null */ public RMapLiteral(String value){ this(); this.setValue(value); } /** * Instantiates a new RMap literal. * * @param value the value * @param language the language (can be null). */ public RMapLiteral(String value, String language){ this(); this.setValue(value); this.language = language; } /** * Instantiates a new RMap literal. * * @param value the value * @param datatype the datatype (can be null) * @throws IllegalArgumentException if value argument is null */ public RMapLiteral(String value, RMapIri datatype){ this(); this.setValue(value); this.datatype = datatype; } /** * Sets the value literal. * @param value the value * @throws IllegalArgumentException if value argument is null */ protected void setValue(String value){ if (value==null){ throw new IllegalArgumentException("Value cannot be null in RMapLiteral"); } this.value = value; } /* (non-Javadoc) * @see info.rmapproject.core.model.Resource#getStringValue() */ public String getStringValue() { return getValue(); } /** * Gets the value. * * @return the value */ public String getValue() { return value; } /** * Gets the language. * * @return the language */ public String getLanguage() { return language; } /** * Gets the datatype. * * @return the datatype */ public RMapIri getDatatype() { return datatype; } /* (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString(){ return getStringValue(); } public boolean equals(Object o) { if (o != null && o instanceof RMapLiteral) { RMapLiteral that = (RMapLiteral) o; return value.equals(that.value) && Optional.ofNullable(language) .map(l -> l.equals(that.language)) .orElse(that.language == null) && Optional.ofNullable(datatype) .map(d -> d.equals(that.datatype)) .orElse(that.datatype == null); } return false; } public int hashCode() { return Objects.hash(value, language, datatype); } }
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ package org.elasticsearch.xpack.ml.rest.datafeeds; import org.elasticsearch.client.node.NodeClient; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.common.xcontent.LoggingDeprecationHandler; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.rest.BaseRestHandler; import org.elasticsearch.rest.BytesRestResponse; import org.elasticsearch.rest.RestRequest; import org.elasticsearch.rest.RestResponse; import org.elasticsearch.rest.RestStatus; import org.elasticsearch.rest.action.RestBuilderListener; import org.elasticsearch.xpack.core.ml.action.StopDatafeedAction; import org.elasticsearch.xpack.core.ml.action.StopDatafeedAction.Request; import org.elasticsearch.xpack.core.ml.action.StopDatafeedAction.Response; import org.elasticsearch.xpack.core.ml.datafeed.DatafeedConfig; import org.elasticsearch.xpack.ml.MachineLearning; import java.io.IOException; import java.util.Collections; import java.util.List; import static org.elasticsearch.rest.RestRequest.Method.POST; public class RestStopDatafeedAction extends BaseRestHandler { @Override public List<Route> routes() { return Collections.emptyList(); } @Override public List<ReplacedRoute> replacedRoutes() { // TODO: remove deprecated endpoint in 8.0.0 return Collections.singletonList( new ReplacedRoute(POST, MachineLearning.BASE_PATH + "datafeeds/{" + DatafeedConfig.ID.getPreferredName() + "}/_stop", POST, MachineLearning.PRE_V7_BASE_PATH + "datafeeds/{" + DatafeedConfig.ID.getPreferredName() + "}/_stop") ); } @Override public String getName() { return "ml_stop_datafeed_action"; } @Override protected RestChannelConsumer prepareRequest(RestRequest restRequest, NodeClient client) throws IOException { String datafeedId = restRequest.param(DatafeedConfig.ID.getPreferredName()); Request request; if (restRequest.hasContentOrSourceParam()) { XContentParser parser = restRequest.contentOrSourceParamParser(); request = Request.parseRequest(datafeedId, parser); } else { request = new Request(datafeedId); if (restRequest.hasParam(Request.TIMEOUT.getPreferredName())) { TimeValue stopTimeout = restRequest.paramAsTime(Request.TIMEOUT.getPreferredName(), StopDatafeedAction.DEFAULT_TIMEOUT); request.setStopTimeout(stopTimeout); } if (restRequest.hasParam(Request.FORCE.getPreferredName())) { request.setForce(restRequest.paramAsBoolean(Request.FORCE.getPreferredName(), request.isForce())); } if (restRequest.hasParam(Request.ALLOW_NO_DATAFEEDS)) { LoggingDeprecationHandler.INSTANCE.usedDeprecatedName( null, () -> null, Request.ALLOW_NO_DATAFEEDS, Request.ALLOW_NO_MATCH.getPreferredName()); } request.setAllowNoMatch( restRequest.paramAsBoolean( Request.ALLOW_NO_MATCH.getPreferredName(), restRequest.paramAsBoolean(Request.ALLOW_NO_DATAFEEDS, request.allowNoMatch()))); } return channel -> client.execute(StopDatafeedAction.INSTANCE, request, new RestBuilderListener<Response>(channel) { @Override public RestResponse buildResponse(Response response, XContentBuilder builder) throws Exception { builder.startObject(); builder.field("stopped", response.isStopped()); builder.endObject(); return new BytesRestResponse(RestStatus.OK, builder); } }); } }
/* * Copyright 2017 Axway Software * * 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. */ /** * * Definition of a Monitor interface which can be used to collect statistical data about some system * */ package com.axway.ats.common.performance.monitor;
package tk.valoeghese.biomegen.api.gen; public interface WorldSettings { }
/* * This file is part of Nucleus, licensed under the MIT License (MIT). See the LICENSE.txt file * at the root of this project for more details. */ package io.github.nucleuspowered.nucleus.modules.warn.listeners; import com.google.common.collect.Maps; import io.github.nucleuspowered.nucleus.Nucleus; import io.github.nucleuspowered.nucleus.Util; import io.github.nucleuspowered.nucleus.internal.ListenerBase; import io.github.nucleuspowered.nucleus.internal.PermissionRegistry; import io.github.nucleuspowered.nucleus.internal.interfaces.Reloadable; import io.github.nucleuspowered.nucleus.internal.permissions.PermissionInformation; import io.github.nucleuspowered.nucleus.internal.permissions.SuggestedLevel; import io.github.nucleuspowered.nucleus.modules.warn.config.WarnConfigAdapter; import io.github.nucleuspowered.nucleus.modules.warn.data.WarnData; import io.github.nucleuspowered.nucleus.modules.warn.handlers.WarnHandler; import io.github.nucleuspowered.nucleus.util.PermissionMessageChannel; import org.spongepowered.api.Sponge; import org.spongepowered.api.entity.living.player.Player; import org.spongepowered.api.event.Listener; import org.spongepowered.api.event.network.ClientConnectionEvent; import org.spongepowered.api.text.action.TextActions; import org.spongepowered.api.text.channel.MutableMessageChannel; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; public class WarnListener implements Reloadable, ListenerBase { private final WarnHandler handler = getServiceUnchecked(WarnHandler.class); private final String showOnLogin = PermissionRegistry.PERMISSIONS_PREFIX + "warn.showonlogin"; private boolean isShowOnLogin = true; /** * At the time the subject joins, check to see if the subject has been warned. * * @param event The event. */ @Listener public void onPlayerLogin(final ClientConnectionEvent.Join event) { Sponge.getScheduler().createTaskBuilder().async().delay(500, TimeUnit.MILLISECONDS).execute(() -> { Player player = event.getTargetEntity(); List<WarnData> warnings = this.handler.getWarningsInternal(player, true, false); if (warnings != null && !warnings.isEmpty()) { for (WarnData warning : warnings) { warning.nextLoginToTimestamp(); if (warning.getEndTimestamp().isPresent() && warning.getEndTimestamp().get().isBefore(Instant.now())) { this.handler.removeWarning(player, warning); } else { if (this.isShowOnLogin) { if (warning.getEndTimestamp().isPresent()) { player.sendMessage(Nucleus.getNucleus().getMessageProvider().getTextMessageWithFormat("warn.playernotify.time", warning.getReason(), Util.getTimeStringFromSeconds(Instant.now().until(warning.getEndTimestamp().get(), ChronoUnit.SECONDS)))); } else { player.sendMessage( Nucleus.getNucleus().getMessageProvider().getTextMessageWithFormat("warn.playernotify.standard", warning.getReason())); } } } } // Now, let's check again if (this.isShowOnLogin) { List<WarnData> lwd = warnings.stream().filter(x -> !x.isExpired()).collect(Collectors.toList()); if (!lwd.isEmpty()) { MutableMessageChannel messageChannel = new PermissionMessageChannel(this.showOnLogin).asMutable(); messageChannel.send(Nucleus.getNucleus().getMessageProvider().getTextMessageWithFormat("warn.login.notify", player.getName(), String.valueOf(lwd.size())).toBuilder() .onHover(TextActions.showText( Nucleus.getNucleus().getMessageProvider().getTextMessageWithFormat("warn.login.view", player.getName()))) .onClick(TextActions.runCommand("/checkwarnings " + player.getName())) .build()); } } } }).submit(Nucleus.getNucleus()); } @Override public Map<String, PermissionInformation> getPermissions() { Map<String, PermissionInformation> mp = Maps.newHashMap(); mp.put(this.showOnLogin, PermissionInformation.getWithTranslation("permission.warn.showonlogin", SuggestedLevel.MOD)); return mp; } @Override public void onReload() { this.isShowOnLogin = getServiceUnchecked(WarnConfigAdapter.class).getNodeOrDefault().isShowOnLogin(); } }
package org.kilocraft.essentials.util.settings.values; import net.minecraft.nbt.NbtCompound; import org.kilocraft.essentials.util.settings.values.util.AbstractSetting; public class CategorySetting extends AbstractSetting { public CategorySetting(String id) { super(id); } @Override public void toTag(NbtCompound tag) { NbtCompound setting = new NbtCompound(); for (AbstractSetting child : this.children) { child.toTag(setting); } tag.put(this.id, setting); } @Override public void fromTag(NbtCompound tag) { if (tag.contains(this.id)) { NbtCompound setting = tag.getCompound(this.id); for (AbstractSetting child : this.children) { child.fromTag(setting); } } } }
package ru.skilanov.io.set; import ru.skilanov.io.list.SimpleArrayList; /** * Array set class. * * @param <E> E */ public class SimpleArraySet<E> extends SimpleArrayList<E> { /** * Add method. * * @param value E */ @Override public void add(E value) { if (isExist(value)) { super.add(value); } } /** * Get size method. * * @return int */ @Override public int getSize() { return super.getSize(); } /** * Is exist method. * * @param e E * @return boolean */ private boolean isExist(E e) { boolean result = true; for (int i = 0; i < size; i++) { if (container[i].equals(e)) { result = false; break; } } return result; } }
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ package org.elasticsearch.xpack.dataframe; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.action.support.PlainActionFuture; import org.elasticsearch.client.Client; import org.elasticsearch.cluster.service.ClusterService; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.xcontent.ToXContent; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentFactory; import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.common.xcontent.support.XContentMapValues; import org.elasticsearch.license.XPackLicenseState; import org.elasticsearch.search.aggregations.Aggregation; import org.elasticsearch.search.aggregations.Aggregations; import org.elasticsearch.search.aggregations.metrics.NumericMetricsAggregation; import org.elasticsearch.test.ESTestCase; import org.elasticsearch.xpack.core.XPackFeatureSet; import org.elasticsearch.xpack.core.XPackFeatureSet.Usage; import org.elasticsearch.xpack.core.dataframe.transforms.DataFrameIndexerTransformStats; import org.junit.Before; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.concurrent.ExecutionException; import static org.elasticsearch.xpack.dataframe.DataFrameFeatureSet.PROVIDED_STATS; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.core.Is.is; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class DataFrameFeatureSetTests extends ESTestCase { private XPackLicenseState licenseState; @Before public void init() { licenseState = mock(XPackLicenseState.class); } public void testAvailable() { DataFrameFeatureSet featureSet = new DataFrameFeatureSet(Settings.EMPTY, mock(ClusterService.class), mock(Client.class), licenseState); boolean available = randomBoolean(); when(licenseState.isDataFrameAllowed()).thenReturn(available); assertThat(featureSet.available(), is(available)); } public void testEnabledSetting() { boolean enabled = randomBoolean(); Settings.Builder settings = Settings.builder(); settings.put("xpack.data_frame.enabled", enabled); DataFrameFeatureSet featureSet = new DataFrameFeatureSet(settings.build(), mock(ClusterService.class), mock(Client.class), licenseState); assertThat(featureSet.enabled(), is(enabled)); } public void testEnabledDefault() { DataFrameFeatureSet featureSet = new DataFrameFeatureSet(Settings.EMPTY, mock(ClusterService.class), mock(Client.class), licenseState); assertTrue(featureSet.enabled()); } public void testParseSearchAggs() { Aggregations emptyAggs = new Aggregations(Collections.emptyList()); SearchResponse withEmptyAggs = mock(SearchResponse.class); when(withEmptyAggs.getAggregations()).thenReturn(emptyAggs); assertThat(DataFrameFeatureSet.parseSearchAggs(withEmptyAggs), equalTo(DataFrameIndexerTransformStats.withDefaultTransformId())); DataFrameIndexerTransformStats expectedStats = new DataFrameIndexerTransformStats("_all", 1, // numPages 2, // numInputDocuments 3, // numOutputDocuments 4, // numInvocations 5, // indexTime 6, // searchTime 7, // indexTotal 8, // searchTotal 9, // indexFailures 10); // searchFailures int currentStat = 1; List<Aggregation> aggs = new ArrayList<>(PROVIDED_STATS.length); for (String statName : PROVIDED_STATS) { aggs.add(buildAgg(statName, (double) currentStat++)); } Aggregations aggregations = new Aggregations(aggs); SearchResponse withAggs = mock(SearchResponse.class); when(withAggs.getAggregations()).thenReturn(aggregations); assertThat(DataFrameFeatureSet.parseSearchAggs(withAggs), equalTo(expectedStats)); } private static Aggregation buildAgg(String name, double value) { NumericMetricsAggregation.SingleValue agg = mock(NumericMetricsAggregation.SingleValue.class); when(agg.getName()).thenReturn(name); when(agg.value()).thenReturn(value); return agg; } public void testUsageDisabled() throws IOException, InterruptedException, ExecutionException { when(licenseState.isDataFrameAllowed()).thenReturn(true); Settings.Builder settings = Settings.builder(); settings.put("xpack.data_frame.enabled", false); DataFrameFeatureSet featureSet = new DataFrameFeatureSet(settings.build(), mock(ClusterService.class), mock(Client.class), licenseState); PlainActionFuture<Usage> future = new PlainActionFuture<>(); featureSet.usage(future); XPackFeatureSet.Usage usage = future.get(); assertFalse(usage.enabled()); try (XContentBuilder builder = XContentFactory.jsonBuilder()) { usage.toXContent(builder, ToXContent.EMPTY_PARAMS); XContentParser parser = createParser(builder); Map<String, Object> usageAsMap = parser.map(); assertTrue((boolean) XContentMapValues.extractValue("available", usageAsMap)); assertFalse((boolean) XContentMapValues.extractValue("enabled", usageAsMap)); // not enabled -> no transforms, no stats assertEquals(null, XContentMapValues.extractValue("transforms", usageAsMap)); assertEquals(null, XContentMapValues.extractValue("stats", usageAsMap)); } } }
/* * 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.honeycode.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.protocol.StructuredPojo; import com.amazonaws.protocol.ProtocolMarshaller; /** * <p> * An object that contains the configuration parameters for the data source of an import request. * </p> * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/honeycode-2020-03-01/ImportDataSourceConfig" target="_top">AWS * API Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class ImportDataSourceConfig implements Serializable, Cloneable, StructuredPojo { /** * <p> * The URL from which source data will be downloaded for the import request. * </p> */ private String dataSourceUrl; /** * <p> * The URL from which source data will be downloaded for the import request. * </p> * * @param dataSourceUrl * The URL from which source data will be downloaded for the import request. */ public void setDataSourceUrl(String dataSourceUrl) { this.dataSourceUrl = dataSourceUrl; } /** * <p> * The URL from which source data will be downloaded for the import request. * </p> * * @return The URL from which source data will be downloaded for the import request. */ public String getDataSourceUrl() { return this.dataSourceUrl; } /** * <p> * The URL from which source data will be downloaded for the import request. * </p> * * @param dataSourceUrl * The URL from which source data will be downloaded for the import request. * @return Returns a reference to this object so that method calls can be chained together. */ public ImportDataSourceConfig withDataSourceUrl(String dataSourceUrl) { setDataSourceUrl(dataSourceUrl); 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 (getDataSourceUrl() != null) sb.append("DataSourceUrl: ").append(getDataSourceUrl()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof ImportDataSourceConfig == false) return false; ImportDataSourceConfig other = (ImportDataSourceConfig) obj; if (other.getDataSourceUrl() == null ^ this.getDataSourceUrl() == null) return false; if (other.getDataSourceUrl() != null && other.getDataSourceUrl().equals(this.getDataSourceUrl()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getDataSourceUrl() == null) ? 0 : getDataSourceUrl().hashCode()); return hashCode; } @Override public ImportDataSourceConfig clone() { try { return (ImportDataSourceConfig) 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.honeycode.model.transform.ImportDataSourceConfigMarshaller.getInstance().marshall(this, protocolMarshaller); } }
// // Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. // package com.cloud.hypervisor.xenserver.resource.wrapper.xenbase; import com.cloud.agent.api.Answer; import com.cloud.agent.api.Command; import com.cloud.agent.api.proxy.CheckConsoleProxyLoadCommand; import com.cloud.hypervisor.xenserver.resource.CitrixResourceBase; import com.cloud.resource.ResourceWrapper; import com.cloud.resource.ServerResource; @ResourceWrapper(handles = CheckConsoleProxyLoadCommand.class) public final class CitrixCheckConsoleProxyLoadCommandWrapper extends CitrixConsoleProxyLoadCommandWrapper<CheckConsoleProxyLoadCommand, Answer, CitrixResourceBase> { @Override public Answer execute(final Command command, final ServerResource serverResource) { final CheckConsoleProxyLoadCommand cmd = (CheckConsoleProxyLoadCommand) command; final long proxyVmId = cmd.getProxyVmId(); final String proxyVmName = cmd.getProxyVmName(); final String proxyManagementIp = cmd.getProxyManagementIp(); final int cmdPort = cmd.getProxyCmdPort(); return executeProxyLoadScan(command, proxyVmId, proxyVmName, proxyManagementIp, cmdPort); } }
/* * Copyright 2017 Netflix, 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.netflix.spinnaker.orca.pipelinetemplate.v1schema.graph.transform; import com.netflix.spinnaker.orca.pipelinetemplate.v1schema.PipelineTemplateVisitor; import com.netflix.spinnaker.orca.pipelinetemplate.v1schema.model.PipelineTemplate; import com.netflix.spinnaker.orca.pipelinetemplate.v1schema.model.TemplateConfiguration; import java.util.Collections; import java.util.HashMap; import java.util.List; public class PipelineConfigInheritanceTransform implements PipelineTemplateVisitor { private TemplateConfiguration templateConfiguration; public PipelineConfigInheritanceTransform(TemplateConfiguration templateConfiguration) { this.templateConfiguration = templateConfiguration; } @Override public void visitPipelineTemplate(PipelineTemplate pipelineTemplate) { List<String> inherit = templateConfiguration.getConfiguration().getInherit(); PipelineTemplate.Configuration pc = pipelineTemplate.getConfiguration(); if (!inherit.contains("concurrentExecutions")) { pc.setConcurrentExecutions(new HashMap<>()); } if (!inherit.contains("triggers")) { pc.setTriggers(Collections.emptyList()); } if (!inherit.contains("parameters")) { pc.setParameters(Collections.emptyList()); } if (!inherit.contains("expectedArtifacts")) { pc.setExpectedArtifacts(Collections.emptyList()); } if (!inherit.contains("notifications")) { pc.setNotifications(Collections.emptyList()); } } }
package com.ironhack.reworkedgebanksystem.repository; import com.ironhack.reworkedgebanksystem.controller.DTO.UserDTO; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import java.util.Optional; @Repository public interface UserRepository extends JpaRepository<UserDTO, Long> { Optional<UserDTO> findByUsername(String username); }
package android.coolweather.com.coolweather.util; import okhttp3.OkHttpClient; import okhttp3.Request; /** * Created by Yvan on 2017/12/4. */ public class HttpUtil { public static void sendOkHttpRequest(String address,okhttp3.Callback callback){ OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder().url(address).build(); client.newCall(request).enqueue(callback); } }
package com.allen.cap4; import com.allen.cap1.Person; import com.allen.cap4.config.MainConfig; import org.junit.Test; import org.springframework.context.annotation.AnnotationConfigApplicationContext; /** * @author 周何圳 2020/3/20 新建 * @description */ public class Cap4Test { public @Test void test01(){ AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MainConfig.class); System.out.println("IOC容器创建完成……"); String[] names = context.getBeanDefinitionNames(); for(String name : names){ System.out.println(name); } System.out.println("准备获取bean对象"); Person person1 = (Person) context.getBean("person"); Person person2 = (Person) context.getBean("person"); System.out.println(person1.hashCode()); System.out.println(person2.hashCode()); } }
package slothstd.twotruthsonelie; import android.util.Log; import com.jjoe64.graphview.series.DataPoint; import java.util.ArrayList; /** * Created by Robo on 12-May-16. */ public class GraphHistory { private ArrayList<Boolean> myHistory; private ArrayList<Boolean> hisHistory; private ArrayList<Integer> lastScore; public final String matchID; private static final String TAG = "2T1L GraphHistory"; public GraphHistory(String matchID) { this.myHistory = new ArrayList<>(); this.hisHistory = new ArrayList<>(); this.lastScore = new ArrayList<>(); this.matchID = matchID; } public GraphHistory(ArrayList<Boolean> myHistory, ArrayList<Boolean> hisHistory, String matchID){ this.myHistory = myHistory; this.hisHistory = hisHistory; this.lastScore = new ArrayList<>(); this.matchID = matchID; } public GraphHistory(String source, String matchID){ this.myHistory = new ArrayList<>(); this.hisHistory = new ArrayList<>(); this.lastScore = new ArrayList<>(); this.matchID = matchID; char[] chars = source.toCharArray(); int i = 0; for (; i < chars.length; i++){ if (chars[i] == '~'){ break; } if (chars[i] == '1') myHistory.add(true); else if (chars[i] == '0') myHistory.add(false); } for (; i < chars.length; i++){ if (chars[i] == '1') hisHistory.add(true); else if (chars[i] == '0') hisHistory.add(false); } Log.d(TAG, "GraphHistory(): " + myHistory.toString() + " ; " + hisHistory.toString()); } public ArrayList<Boolean> getMyHistory() { return myHistory; } public boolean getMyHistory(int pos){ return myHistory.get(pos); } public void setMyHistory(ArrayList<Boolean> myHistory) { this.myHistory = myHistory; } public void setMyHistory(boolean isWin, int pos){ this.myHistory.set(pos, isWin); } public void addMyHistory(boolean isWin){ this.myHistory.add(isWin); Log.d(TAG, "addMyHistory(): " + myHistory.toString()); } public int myWinCount(){ int count = 0; for (int i = 0; i < myHistory.size(); i++){ if(myHistory.get(i)) count++; } return count; } public ArrayList<Boolean> getHisHistory() { return hisHistory; } public boolean getHisHistory(int pos){ return myHistory.get(pos); } public void setHisHistory(ArrayList<Boolean> hisHistory) { this.hisHistory = hisHistory; } public void setHisHistory(boolean isWin, int pos){ this.hisHistory.set(pos, isWin); } public void addHisHistory(boolean isWin){ this.hisHistory.add(isWin); Log.d(TAG, "addHisHistory(): " + hisHistory.toString()); } public int hisWinCount(){ int count = 0; for (int i = 0; i < hisHistory.size(); i++){ if(hisHistory.get(i)) count++; } return count; } public ArrayList<Integer> getLastScore() { return lastScore; } public int getLastScore(int pos){ return lastScore.get(pos); } public void setLastScore(ArrayList<Integer> lastScore) { this.lastScore = lastScore; Log.d(TAG, "setLastScore(): " + lastScore.toString()); } public void setLastScore(int pos, int value) { this.lastScore.set(pos, value); } public String encrypt(){ String s = ""; for (int i = 0; i < myHistory.size(); i++){ if (myHistory.get(i)) s = s + "1"; else s = s + "0"; } s = s + "~"; for (int i = 0; i < hisHistory.size(); i++){ if (hisHistory.get(i)) s = s + "1"; else s = s + "0"; } Log.d(TAG, "encrypt(): " + s); return s; } public void compare(ArrayList<Integer> scores, int player){ if (hisWinCount() == scores.get(Math.abs(player - 1))){ addHisHistory(false); } else { addHisHistory(true); } Log.d(TAG, "compare(): "+ hisWinCount() + " - "+ scores.get(Math.abs(player - 1)) + "; " + hisHistory.toString()); } public DataPoint[] getMyDataPoints(){ DataPoint[] dataPoints = new DataPoint[myHistory.size() + 1]; dataPoints[0] = new DataPoint(0, 0); String debug = ""; int score = 0; for (int i = 0; i < myHistory.size(); i++){ if (myHistory.get(i)){ score++; } dataPoints[i + 1] = new DataPoint(i + 1, score); debug = debug + dataPoints[i+1].toString(); } Log.d(TAG, "getMyDataPoints(): " + debug); return dataPoints; } public DataPoint[] getHisDataPoints(){ DataPoint[] dataPoints = new DataPoint[hisHistory.size() + 1]; dataPoints[0] = new DataPoint(0, 0); String debug = ""; int score = 0; for (int i = 0; i < hisHistory.size(); i++){ if (hisHistory.get(i)){ score++; } dataPoints[i + 1] = new DataPoint(i + 1, score); debug = debug + dataPoints[i+1].toString(); } Log.d(TAG, "getHisDataPoints(): " + debug); return dataPoints; } }
/* Copyright 2013 Nationale-Nederlanden 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 nl.nn.adapterframework.util; import java.io.BufferedReader; import java.io.IOException; import java.io.Reader; import nl.nn.adapterframework.core.IDataIterator; import nl.nn.adapterframework.core.SenderException; /** * Iterator that iterates over all lines in a Reader. * * @author Gerrit van Brakel * @since 4.7 */ public class ReaderLineIterator implements IDataIterator<String> { BufferedReader reader; String line; public ReaderLineIterator(Reader inputreader) throws SenderException { super(); reader = new BufferedReader(inputreader); try { line=reader.readLine(); } catch (IOException e) { throw new SenderException(e); } } @Override public boolean hasNext() { return line!=null; } @Override public String next() throws SenderException { String result=line; try { line = reader.readLine(); } catch (IOException e) { throw new SenderException(e); } return result; } @Override public void close() throws SenderException { try { reader.close(); } catch (IOException e) { throw new SenderException(e); } } }
package com.example.webflux; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import java.time.Duration; import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.Random; /** * @author MrBird */ public class FluxTest { public static void main(String[] args) throws InterruptedException { Flux.just("Hello", "World").subscribe(System.out::println); Flux.fromArray(new Integer[]{1, 2, 3}).subscribe(System.out::println); Flux.empty().subscribe(System.out::println); Flux.range(1, 4).subscribe(System.out::println); // Flux.interval(Duration.of(1, ChronoUnit.SECONDS)).subscribe(System.out::println); Flux.generate(sink -> { sink.next("Hello"); sink.complete(); }).subscribe(System.out::println); final Random random = new Random(); Flux.generate(ArrayList::new, (list, sink) -> { int value = random.nextInt(100); list.add(value); sink.next(value); if (list.size() == 10) { sink.complete(); } return list; }).subscribe(System.out::println); Flux.create(sink -> { for (int i = 0; i < 10; i++) { sink.next(i); } sink.complete(); }).subscribe(System.out::println); Flux.range(1, 10).filter(i -> i % 2 == 0).subscribe(System.out::println); Flux.range(1, 20).take(10).subscribe(System.out::println); Flux.range(1, 20).takeLast(10).subscribe(System.out::println); Flux.range(1, 20).takeWhile(i -> i < 10).subscribe(System.out::println); Flux.range(1, 20).takeUntil(i -> i == 10).subscribe(System.out::println); Flux.range(1, 10).reduce((x, y) -> x + y).subscribe(System.out::println); Flux.range(1, 10).reduceWith(() -> 10, (x, y) -> x + y).subscribe(System.out::println); Flux.merge( Flux.interval(Duration.of(500, ChronoUnit.MILLIS)).take(2), Flux.interval(Duration.of(500, ChronoUnit.MILLIS)).take(2) ).toStream().forEach(System.out::println); Flux.range(1, 100).buffer(20).subscribe(System.out::println); Flux.range(1, 10).bufferUntil(i -> i % 2 == 0).subscribe(System.out::println); Flux.range(1, 10).bufferWhile(i -> i % 2 == 0).subscribe(System.out::println); Flux.just("a", "b", "c", "d") .zipWith(Flux.just("e", "f", "g", "h", "i")) .subscribe(System.out::println); Flux.just("a", "b", "c", "d") .zipWith(Flux.just("e", "f", "g", "h", "i"), (s1, s2) -> String.format("%s-%s", s1, s2)) .subscribe(System.out::println); Flux.just(1, 2) .concatWith(Mono.error(new IllegalStateException())) .subscribe(System.out::println, System.err::println); Flux.just(1, 2) .concatWith(Mono.error(new IllegalStateException())) .onErrorReturn(0) .subscribe(System.out::println); Flux.just(1, 2) .concatWith(Mono.error(new IllegalArgumentException())) .onErrorResume(e -> { if (e instanceof IllegalStateException) { return Mono.just(0); } else if (e instanceof IllegalArgumentException) { return Mono.just(-1); } return Mono.empty(); }).subscribe(System.out::println); Thread.currentThread().join(20000); } }
/* * Copyright (c) 2021-2022 Osiris-Team. * All rights reserved. * * This software is copyrighted work, licensed under the terms * of the MIT-License. Consult the "LICENSE" file for details. */ package com.osiris.autoplug.client.tasks.backup; import com.osiris.autoplug.client.Server; import com.osiris.autoplug.client.configs.BackupConfig; import com.osiris.autoplug.client.configs.SystemConfig; import com.osiris.autoplug.client.utils.GD; import com.osiris.autoplug.client.utils.UtilsConfig; import com.osiris.autoplug.client.utils.tasks.CoolDownReport; import com.osiris.autoplug.core.logger.AL; import com.osiris.betterthread.BThread; import com.osiris.betterthread.BThreadManager; import com.osiris.betterthread.BWarning; import net.lingala.zip4j.ZipFile; import net.lingala.zip4j.model.ExcludeFileFilter; import net.lingala.zip4j.model.ZipParameters; import org.apache.commons.io.FileUtils; import org.apache.commons.io.filefilter.AgeFileFilter; import org.apache.commons.lang.time.DateUtils; import java.io.File; import java.text.SimpleDateFormat; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.List; public class TaskBackup extends BThread { private final File autoplug_backups = new File(GD.WORKING_DIR + "/autoplug/backups"); private final LocalDateTime date = LocalDateTime.now(); private final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd-HH.mm"); private final String formattedDate = date.format(formatter); public TaskBackup(String name, BThreadManager manager) { super(name, manager); } @Override public void runAtStart() throws Exception { super.runAtStart(); autoplug_backups.mkdirs(); createBackup(); } private void createBackup() throws Exception { if (Server.isRunning()) throw new Exception("Cannot perform backup while server is running!"); BackupConfig config = new BackupConfig(); SystemConfig systemConfig = new SystemConfig(); systemConfig.lockFile(); systemConfig.load(); // Do cool-down check stuff String format = "dd/MM/yyyy HH:mm:ss"; CoolDownReport coolDownReport = new UtilsConfig().getCoolDown( config.backup_cool_down.asInt(), new SimpleDateFormat(format), systemConfig.timestamp_last_backup.asString()); // Get the report first before saving any new values if (coolDownReport.isInCoolDown()) { systemConfig.unlockFile(); this.skip("Skipped. Cool-down still active (" + (((coolDownReport.getMsRemaining() / 1000) / 60)) + " minutes remaining)."); return; } // Update the cool-down with current time systemConfig.timestamp_last_backup.setValues(LocalDateTime.now().format(DateTimeFormatter.ofPattern(format))); systemConfig.save(); // Save the current timestamp to file systemConfig.unlockFile(); String server_backup_dest = autoplug_backups.getAbsolutePath() + "/" + formattedDate + "-BACKUP.zip"; int max_days_server = config.backup_max_days.asInt(); //Removes files older than user defined days if (max_days_server <= 0) { setStatus("Skipping delete of older backups..."); } else { Date oldestAllowedFileDate = DateUtils.addDays(new Date(), -max_days_server); //minus days from current date Iterator<File> filesToDelete = FileUtils.iterateFiles(autoplug_backups, new AgeFileFilter(oldestAllowedFileDate), null); //if deleting subdirs, replace null above with TrueFileFilter.INSTANCE int deleted_files = 0; while (filesToDelete.hasNext()) { deleted_files++; FileUtils.deleteQuietly(filesToDelete.next()); setStatus("Deleting backups older than " + max_days_server + " days... Deleted: " + deleted_files + " zips"); } //I don't want an exception if a file is not deleted. Otherwise use filesToDelete.next().delete() in a try/catch setStatus("Deleting backups older than " + max_days_server + " days... Deleted: " + deleted_files + " zips"); } Thread.sleep(1000); if (config.backup.asBoolean()) { setStatus("Creating backup zip..."); ZipFile zip = new ZipFile(server_backup_dest); List<File> filesToBackup = new ArrayList<>(); if (config.backup_include.asBoolean()) filesToBackup.addAll(config.getIncludedFiles()); if (config.backup_exclude.asBoolean()) { List<File> excludedFiles = config.getExcludedFiles(); for (File file : excludedFiles) { AL.debug(this.getClass(), "Excluded '" + file.getName() + "' from backup. Full path: " + file.getAbsolutePath()); } ExcludeFileFilter excludeFileFilter = excludedFiles::contains; setMax(filesToBackup.size()); for (File file : filesToBackup) { //Add each file to the zip setStatus("Backing up files... " + file.getName()); try { ZipParameters zipParameters = new ZipParameters(); zipParameters.setExcludeFileFilter(excludeFileFilter); if (file.isDirectory()) zip.addFolder(file, zipParameters); else zip.addFile(file, zipParameters); } catch (Exception e) { getWarnings().add(new BWarning(this, e, "Failed to add " + file.getName() + " to zip.")); } step(); } } else { setMax(filesToBackup.size()); for (File file : filesToBackup) { //Add each file to the zip setStatus("Backing up files... " + file.getName()); try { if (file.isDirectory()) zip.addFolder(file); else zip.addFile(file); } catch (Exception e) { getWarnings().add(new BWarning(this, e, "Failed to add " + file.getName() + " to zip.")); } step(); } } //Upload if (config.backup_upload.asBoolean()) { setStatus("Uploading server-files backup..."); Upload upload = new Upload(config.backup_upload_host.asString(), config.backup_upload_port.asInt(), config.backup_upload_user.asString(), config.backup_upload_password.asString(), config.backup_upload_path.asString(), zip.getFile()); String rsa = config.backup_upload_rsa.asString(); try { if (rsa == null || rsa.trim().isEmpty()) upload.ftps(); else upload.sftp(rsa.trim()); if (config.backup_upload_delete_on_complete.asBoolean()) zip.getFile().delete(); } catch (Exception e) { getWarnings().add(new BWarning(this, e, "Failed to upload backup.")); } if (getWarnings().size() > 0) setStatus("Completed backup & upload (" + getWarnings().size() + " warnings)."); else setStatus("Completed backup & upload."); } else { if (getWarnings().size() > 0) setStatus("Completed backup & skipped upload (" + getWarnings().size() + " warnings)."); else setStatus("Completed backup & skipped upload."); } AL.debug(this.getClass(), "Created backup at: " + server_backup_dest); } else skip(); finish(); } }
/* * Licensed to Jasig under one or more contributor license * agreements. See the NOTICE file distributed with this work * for additional information regarding copyright ownership. * Jasig licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a * copy of the License at the following location: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.jasig.cas.ticket.registry; import org.jasig.cas.ticket.ServiceTicket; import org.jasig.cas.ticket.Ticket; import org.jasig.cas.ticket.TicketGrantingTicket; import org.springframework.util.Assert; import java.util.Collection; import java.util.Collections; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * Implementation of the TicketRegistry that is backed by a ConcurrentHashMap. * * @author Scott Battaglia * @since 3.0 */ public final class DefaultTicketRegistry extends AbstractTicketRegistry { /** A HashMap to contain the tickets. */ private final Map<String, Ticket> cache; public DefaultTicketRegistry() { this.cache = new ConcurrentHashMap<String, Ticket>(); } /** * Creates a new, empty registry with the specified initial capacity, load * factor, and concurrency level. * * @param initialCapacity - the initial capacity. The implementation * performs internal sizing to accommodate this many elements. * @param loadFactor - the load factor threshold, used to control resizing. * Resizing may be performed when the average number of elements per bin * exceeds this threshold. * @param concurrencyLevel - the estimated number of concurrently updating * threads. The implementation performs internal sizing to try to * accommodate this many threads. */ public DefaultTicketRegistry(final int initialCapacity, final float loadFactor, final int concurrencyLevel) { this.cache = new ConcurrentHashMap<String, Ticket>(initialCapacity, loadFactor, concurrencyLevel); } /** * @throws IllegalArgumentException if the Ticket is null. */ public void addTicket(final Ticket ticket) { Assert.notNull(ticket, "ticket cannot be null"); log.debug("Added ticket [{}] to registry.", ticket.getId()); this.cache.put(ticket.getId(), ticket); } public Ticket getTicket(final String ticketId) { if (ticketId == null) { return null; } log.debug("Attempting to retrieve ticket [{}]", ticketId); final Ticket ticket = this.cache.get(ticketId); if (ticket != null) { log.debug("Ticket [{}] found in registry.", ticketId); } return ticket; } public boolean deleteTicket(final String ticketId) { if (ticketId == null) { return false; } log.debug("Removing ticket [{}] from registry", ticketId); return (this.cache.remove(ticketId) != null); } public Collection<Ticket> getTickets() { return Collections.unmodifiableCollection(this.cache.values()); } public int sessionCount() { int count = 0; for (Ticket t : this.cache.values()) { if (t instanceof TicketGrantingTicket) { count++; } } return count; } public int serviceTicketCount() { int count = 0; for (Ticket t : this.cache.values()) { if (t instanceof ServiceTicket) { count++; } } return count; } }
/* 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.activiti.engine.test.bpmn.event.error; import java.util.HashMap; import java.util.List; import java.util.Map; import org.activiti.engine.ActivitiException; import org.activiti.engine.delegate.BpmnError; import org.activiti.engine.history.HistoricProcessInstance; import org.activiti.engine.impl.history.HistoryLevel; import org.activiti.engine.impl.test.PluggableActivitiTestCase; import org.activiti.engine.impl.util.CollectionUtil; import org.activiti.engine.impl.util.JvmUtil; import org.activiti.engine.task.Task; import org.activiti.engine.test.Deployment; /** * @author Joram Barrez * @author Tijs Rademakers */ public class BoundaryErrorEventTest extends PluggableActivitiTestCase { @Deployment public void testCatchErrorOnEmbeddedSubprocess() { runtimeService.startProcessInstanceByKey("boundaryErrorOnEmbeddedSubprocess"); // After process start, usertask in subprocess should exist Task task = taskService.createTaskQuery().singleResult(); assertEquals("subprocessTask", task.getName()); // After task completion, error end event is reached and caught taskService.complete(task.getId()); task = taskService.createTaskQuery().singleResult(); assertEquals("task after catching the error", task.getName()); } public void testThrowErrorWithEmptyErrorCode() { try { repositoryService.createDeployment().addClasspathResource("org/activiti/engine/test/bpmn/event/error/BoundaryErrorEventTest.testThrowErrorWithEmptyErrorCode.bpmn20.xml").deploy(); fail("ActivitiException expected"); } catch (ActivitiException re) { } } @Deployment public void testCatchErrorOnEmbeddedSubprocessWithEmptyErrorCode() { testCatchErrorOnEmbeddedSubprocess(); } @Deployment public void testCatchErrorOnEmbeddedSubprocessWithoutErrorCode() { testCatchErrorOnEmbeddedSubprocess(); } @Deployment public void testCatchErrorOfInnerSubprocessOnOuterSubprocess() { runtimeService.startProcessInstanceByKey("boundaryErrorTest"); List<Task> tasks = taskService.createTaskQuery().orderByTaskName().asc().list(); assertEquals(2, tasks.size()); assertEquals("Inner subprocess task 1", tasks.get(0).getName()); assertEquals("Inner subprocess task 2", tasks.get(1).getName()); // Completing task 2, will cause the end error event to throw error with code 123 taskService.complete(tasks.get(1).getId()); taskService.createTaskQuery().list(); Task taskAfterError = taskService.createTaskQuery().singleResult(); assertEquals("task outside subprocess", taskAfterError.getName()); } @Deployment public void testCatchErrorInConcurrentEmbeddedSubprocesses() { assertErrorCaughtInConcurrentEmbeddedSubprocesses("boundaryEventTestConcurrentSubprocesses"); } @Deployment public void testCatchErrorInConcurrentEmbeddedSubprocessesThrownByScriptTask() { assertErrorCaughtInConcurrentEmbeddedSubprocesses("catchErrorInConcurrentEmbeddedSubprocessesThrownByScriptTask"); } private void assertErrorCaughtInConcurrentEmbeddedSubprocesses(String processDefinitionKey) { // Completing task A will lead to task D String procId = runtimeService.startProcessInstanceByKey(processDefinitionKey).getId(); List<Task> tasks = taskService.createTaskQuery().orderByTaskName().asc().list(); assertEquals(2, tasks.size()); assertEquals("task A", tasks.get(0).getName()); assertEquals("task B", tasks.get(1).getName()); taskService.complete(tasks.get(0).getId()); Task task = taskService.createTaskQuery().singleResult(); assertEquals("task D", task.getName()); taskService.complete(task.getId()); assertProcessEnded(procId); // Completing task B will lead to task C runtimeService.startProcessInstanceByKey(processDefinitionKey).getId(); tasks = taskService.createTaskQuery().orderByTaskName().asc().list(); assertEquals(2, tasks.size()); assertEquals("task A", tasks.get(0).getName()); assertEquals("task B", tasks.get(1).getName()); taskService.complete(tasks.get(1).getId()); tasks = taskService.createTaskQuery().orderByTaskName().asc().list(); assertEquals(2, tasks.size()); assertEquals("task A", tasks.get(0).getName()); assertEquals("task C", tasks.get(1).getName()); taskService.complete(tasks.get(1).getId()); task = taskService.createTaskQuery().singleResult(); assertEquals("task A", task.getName()); taskService.complete(task.getId()); task = taskService.createTaskQuery().singleResult(); assertEquals("task D", task.getName()); } @Deployment public void testDeeplyNestedErrorThrown() { // Input = 1 -> error1 will be thrown, which will destroy ALL BUT ONE // subprocess, which leads to an end event, which ultimately leads to // ending the process instance String procId = runtimeService.startProcessInstanceByKey("deeplyNestedErrorThrown").getId(); Task task = taskService.createTaskQuery().singleResult(); assertEquals("Nested task", task.getName()); taskService.complete(task.getId(), CollectionUtil.singletonMap("input", 1)); assertProcessEnded(procId); // Input == 2 -> error2 will be thrown, leading to a userTask outside // all subprocesses procId = runtimeService.startProcessInstanceByKey("deeplyNestedErrorThrown").getId(); task = taskService.createTaskQuery().singleResult(); assertEquals("Nested task", task.getName()); taskService.complete(task.getId(), CollectionUtil.singletonMap("input", 2)); task = taskService.createTaskQuery().singleResult(); assertEquals("task after catch", task.getName()); taskService.complete(task.getId()); assertProcessEnded(procId); } @Deployment public void testDeeplyNestedErrorThrownOnlyAutomaticSteps() { // input == 1 -> error2 is thrown -> caught on subprocess2 -> end event // in subprocess -> proc inst end 1 String procId = runtimeService.startProcessInstanceByKey("deeplyNestedErrorThrown", CollectionUtil.singletonMap("input", 1)).getId(); assertProcessEnded(procId); HistoricProcessInstance hip; if (processEngineConfiguration.getHistoryLevel().isAtLeast(HistoryLevel.ACTIVITY)) { hip = historyService.createHistoricProcessInstanceQuery().processInstanceId(procId).singleResult(); assertEquals("processEnd1", hip.getEndActivityId()); } // input == 2 -> error2 is thrown -> caught on subprocess1 -> proc inst // end 2 procId = runtimeService.startProcessInstanceByKey("deeplyNestedErrorThrown", CollectionUtil.singletonMap("input", 1)).getId(); assertProcessEnded(procId); if (processEngineConfiguration.getHistoryLevel().isAtLeast(HistoryLevel.ACTIVITY)) { hip = historyService.createHistoricProcessInstanceQuery().processInstanceId(procId).singleResult(); assertEquals("processEnd1", hip.getEndActivityId()); } } @Deployment(resources = { "org/activiti/engine/test/bpmn/event/error/BoundaryErrorEventTest.testCatchErrorOnCallActivity-parent.bpmn20.xml", "org/activiti/engine/test/bpmn/event/error/BoundaryErrorEventTest.subprocess.bpmn20.xml" }) public void testCatchErrorOnCallActivity() { String procId = runtimeService.startProcessInstanceByKey("catchErrorOnCallActivity").getId(); Task task = taskService.createTaskQuery().singleResult(); assertEquals("Task in subprocess", task.getName()); // Completing the task will reach the end error event, // which is caught on the call activity boundary taskService.complete(task.getId()); task = taskService.createTaskQuery().singleResult(); assertEquals("Escalated Task", task.getName()); // Completing the task will end the process instance taskService.complete(task.getId()); assertProcessEnded(procId); } @Deployment(resources = { "org/activiti/engine/test/bpmn/event/error/BoundaryErrorEventTest.subprocess.bpmn20.xml" }) public void testUncaughtError() { runtimeService.startProcessInstanceByKey("simpleSubProcess"); Task task = taskService.createTaskQuery().singleResult(); assertEquals("Task in subprocess", task.getName()); try { // Completing the task will reach the end error event, which is never caught in the process taskService.complete(task.getId()); fail("No catching boundary event found for error with errorCode 'myError', neither in same process nor in parent process but no Exception is thrown"); } catch (BpmnError e) { assertTextPresent("No catching boundary event found for error with errorCode 'myError', neither in same process nor in parent process", e.getMessage()); } } @Deployment(resources = { "org/activiti/engine/test/bpmn/event/error/BoundaryErrorEventTest.testUncaughtErrorOnCallActivity-parent.bpmn20.xml", "org/activiti/engine/test/bpmn/event/error/BoundaryErrorEventTest.subprocess.bpmn20.xml" }) public void testUncaughtErrorOnCallActivity() { runtimeService.startProcessInstanceByKey("uncaughtErrorOnCallActivity"); Task task = taskService.createTaskQuery().singleResult(); assertEquals("Task in subprocess", task.getName()); try { // Completing the task will reach the end error event, // which is never caught in the process taskService.complete(task.getId()); } catch (BpmnError e) { assertTextPresent("No catching boundary event found for error with errorCode 'myError', neither in same process nor in parent process", e.getMessage()); } } @Deployment(resources = { "org/activiti/engine/test/bpmn/event/error/BoundaryErrorEventTest.testCatchErrorThrownByCallActivityOnSubprocess.bpmn20.xml", "org/activiti/engine/test/bpmn/event/error/BoundaryErrorEventTest.subprocess.bpmn20.xml" }) public void testCatchErrorThrownByCallActivityOnSubprocess() { String procId = runtimeService.startProcessInstanceByKey("catchErrorOnSubprocess").getId(); Task task = taskService.createTaskQuery().singleResult(); assertEquals("Task in subprocess", task.getName()); // Completing the task will reach the end error event, // which is caught on the call activity boundary taskService.complete(task.getId()); task = taskService.createTaskQuery().singleResult(); assertEquals("Escalated Task", task.getName()); // Completing the task will end the process instance taskService.complete(task.getId()); assertProcessEnded(procId); } @Deployment(resources = { "org/activiti/engine/test/bpmn/event/error/BoundaryErrorEventTest.testCatchErrorThrownByCallActivityOnCallActivity.bpmn20.xml", "org/activiti/engine/test/bpmn/event/error/BoundaryErrorEventTest.subprocess2ndLevel.bpmn20.xml", "org/activiti/engine/test/bpmn/event/error/BoundaryErrorEventTest.subprocess.bpmn20.xml" }) public void testCatchErrorThrownByCallActivityOnCallActivity() throws InterruptedException { String procId = runtimeService.startProcessInstanceByKey("catchErrorOnCallActivity2ndLevel").getId(); Task task = taskService.createTaskQuery().singleResult(); assertEquals("Task in subprocess", task.getName()); taskService.complete(task.getId()); task = taskService.createTaskQuery().singleResult(); assertEquals("Escalated Task", task.getName()); // Completing the task will end the process instance taskService.complete(task.getId()); assertProcessEnded(procId); } @Deployment public void testCatchErrorOnParallelMultiInstance() { String procId = runtimeService.startProcessInstanceByKey("catchErrorOnParallelMi").getId(); List<Task> tasks = taskService.createTaskQuery().list(); assertEquals(5, tasks.size()); // Complete two subprocesses, just to make it a bit more complex Map<String, Object> vars = new HashMap<String, Object>(); vars.put("throwError", false); taskService.complete(tasks.get(2).getId(), vars); taskService.complete(tasks.get(3).getId(), vars); // Reach the error event vars.put("throwError", true); taskService.complete(tasks.get(1).getId(), vars); assertEquals(0, taskService.createTaskQuery().count()); assertProcessEnded(procId); } @Deployment public void testCatchErrorOnSequentialMultiInstance() { String procId = runtimeService.startProcessInstanceByKey("catchErrorOnSequentialMi").getId(); // complete one task Map<String, Object> vars = new HashMap<String, Object>(); vars.put("throwError", false); Task task = taskService.createTaskQuery().singleResult(); taskService.complete(task.getId(), vars); // complete second task and throw error vars.put("throwError", true); task = taskService.createTaskQuery().singleResult(); taskService.complete(task.getId(), vars); assertProcessEnded(procId); } @Deployment public void testCatchErrorThrownByJavaDelegateOnServiceTask() { String procId = runtimeService.startProcessInstanceByKey("catchErrorThrownByJavaDelegateOnServiceTask").getId(); assertThatErrorHasBeenCaught(procId); } @Deployment public void testCatchErrorThrownByJavaDelegateOnServiceTaskNotCancelActivity() { String procId = runtimeService.startProcessInstanceByKey("catchErrorThrownByJavaDelegateOnServiceTaskNotCancelActiviti").getId(); assertThatErrorHasBeenCaught(procId); } @Deployment public void testCatchErrorThrownByJavaDelegateOnServiceTaskWithErrorCode() { String procId = runtimeService.startProcessInstanceByKey("catchErrorThrownByJavaDelegateOnServiceTaskWithErrorCode").getId(); assertThatErrorHasBeenCaught(procId); } @Deployment public void testCatchErrorThrownByJavaDelegateOnEmbeddedSubProcess() { String procId = runtimeService.startProcessInstanceByKey("catchErrorThrownByJavaDelegateOnEmbeddedSubProcess").getId(); assertThatErrorHasBeenCaught(procId); } @Deployment public void testCatchErrorThrownByJavaDelegateOnEmbeddedSubProcessInduction() { String procId = runtimeService.startProcessInstanceByKey("catchErrorThrownByJavaDelegateOnEmbeddedSubProcessInduction").getId(); assertThatErrorHasBeenCaught(procId); } @Deployment(resources = { "org/activiti/engine/test/bpmn/event/error/BoundaryErrorEventTest.testCatchErrorThrownByJavaDelegateOnCallActivity-parent.bpmn20.xml", "org/activiti/engine/test/bpmn/event/error/BoundaryErrorEventTest.testCatchErrorThrownByJavaDelegateOnCallActivity-child.bpmn20.xml" }) public void testCatchErrorThrownByJavaDelegateOnCallActivity() { String procId = runtimeService.startProcessInstanceByKey("catchErrorThrownByJavaDelegateOnCallActivity-parent").getId(); assertThatErrorHasBeenCaught(procId); } @Deployment(resources = { "org/activiti/engine/test/bpmn/event/error/BoundaryErrorEventTest.testCatchErrorThrownByJavaDelegateOnCallActivity-child.bpmn20.xml" }) public void testUncaughtErrorThrownByJavaDelegateOnServiceTask() { try { runtimeService.startProcessInstanceByKey("catchErrorThrownByJavaDelegateOnCallActivity-child"); } catch (BpmnError e) { assertTextPresent("No catching boundary event found for error with errorCode '23', neither in same process nor in parent process", e.getMessage()); } } @Deployment(resources = { "org/activiti/engine/test/bpmn/event/error/BoundaryErrorEventTest.testUncaughtErrorThrownByJavaDelegateOnCallActivity-parent.bpmn20.xml", "org/activiti/engine/test/bpmn/event/error/BoundaryErrorEventTest.testCatchErrorThrownByJavaDelegateOnCallActivity-child.bpmn20.xml" }) public void testUncaughtErrorThrownByJavaDelegateOnCallActivity() { try { runtimeService.startProcessInstanceByKey("uncaughtErrorThrownByJavaDelegateOnCallActivity-parent"); } catch (BpmnError e) { assertTextPresent("No catching boundary event found for error with errorCode '23', neither in same process nor in parent process", e.getMessage()); } } @Deployment(resources = { "org/activiti/engine/test/bpmn/event/error/BoundaryErrorEventTest.testCatchErrorOnGroovyScriptTask.bpmn20.xml" }) public void testCatchErrorOnGroovyScriptTask() { String procId = runtimeService.startProcessInstanceByKey("catchErrorOnScriptTask").getId(); assertProcessEnded(procId); } @Deployment(resources = { "org/activiti/engine/test/bpmn/event/error/BoundaryErrorEventTest.testCatchErrorOnJavaScriptScriptTask.bpmn20.xml" }) public void testCatchErrorOnJavaScriptScriptTask() { if (JvmUtil.isAtLeastJDK7()) { String procId = runtimeService.startProcessInstanceByKey("catchErrorOnScriptTask").getId(); assertProcessEnded(procId); } } @Deployment(resources = { "org/activiti/engine/test/bpmn/event/error/BoundaryErrorEventTest.testUncaughtErrorOnScriptTaskWithEmptyErrorEventDefinition.bpmn20.xml" }) public void testUncaughtErrorOnScriptTaskWithEmptyErrorEventDefinition() { String procId = runtimeService.startProcessInstanceByKey("uncaughtErrorOnScriptTaskWithEmptyErrorEventDefinition").getId(); assertProcessEnded(procId); } @Deployment(resources = { "org/activiti/engine/test/bpmn/event/error/BoundaryErrorEventTest.testUncaughtErrorOnScriptTask.bpmn20.xml" }) public void testUncaughtErrorOnScriptTask() { try { String procId = runtimeService.startProcessInstanceByKey("uncaughtErrorOnScriptTask").getId(); fail("The script throws error event with errorCode 'errorUncaught', but no catching boundary event was defined. An exception is expected which did not occur"); assertProcessEnded(procId); } catch (BpmnError e) { assertTextPresent("No catching boundary event found for error with errorCode 'errorUncaught', neither in same process nor in parent process", e.getMessage()); } } @Deployment public void testCatchErrorThrownByJavaDelegateOnMultiInstanceServiceTaskSequential() { Map<String, Object> variables = new HashMap<String, Object>(); variables.put("executionsBeforeError", 2); String procId = runtimeService.startProcessInstanceByKey("catchErrorThrownByJavaDelegateOnMultiInstanceServiceTaskSequential", variables).getId(); assertThatErrorHasBeenCaught(procId); } @Deployment public void testCatchErrorThrownByJavaDelegateOnMultiInstanceServiceTaskParallel() { Map<String, Object> variables = new HashMap<String, Object>(); variables.put("executionsBeforeError", 2); String procId = runtimeService.startProcessInstanceByKey("catchErrorThrownByJavaDelegateOnMultiInstanceServiceTaskParallel", variables).getId(); assertThatErrorHasBeenCaught(procId); } @Deployment public void testErrorThrownByJavaDelegateNotCaughtByOtherEventType() { String procId = runtimeService.startProcessInstanceByKey("testErrorThrownByJavaDelegateNotCaughtByOtherEventType").getId(); assertThatErrorHasBeenCaught(procId); } private void assertThatErrorHasBeenCaught(String procId) { // The service task will throw an error event, // which is caught on the service task boundary assertEquals("No tasks found in task list.", 1, taskService.createTaskQuery().count()); Task task = taskService.createTaskQuery().singleResult(); assertEquals("Escalated Task", task.getName()); // Completing the task will end the process instance taskService.complete(task.getId()); assertProcessEnded(procId); } @Deployment public void testConcurrentExecutionsInterruptedOnDestroyScope() { // this test makes sure that if the first concurrent execution destroys // the scope // (due to the interrupting boundary catch), the second concurrent // execution does not // move forward. // if the test fails, it produces a constraint violation in db. runtimeService.startProcessInstanceByKey("process"); } @Deployment public void testCatchErrorThrownByExpressionOnServiceTask() { HashMap<String, Object> variables = new HashMap<String, Object>(); variables.put("bpmnErrorBean", new BpmnErrorBean()); String procId = runtimeService.startProcessInstanceByKey("testCatchErrorThrownByExpressionOnServiceTask", variables).getId(); assertThatErrorHasBeenCaught(procId); } @Deployment public void testCatchErrorThrownByDelegateExpressionOnServiceTask() { HashMap<String, Object> variables = new HashMap<String, Object>(); variables.put("bpmnErrorBean", new BpmnErrorBean()); String procId = runtimeService.startProcessInstanceByKey("testCatchErrorThrownByDelegateExpressionOnServiceTask", variables).getId(); assertThatErrorHasBeenCaught(procId); } @Deployment public void testCatchErrorThrownByJavaDelegateProvidedByDelegateExpressionOnServiceTask() { HashMap<String, Object> variables = new HashMap<String, Object>(); variables.put("bpmnErrorBean", new BpmnErrorBean()); String procId = runtimeService.startProcessInstanceByKey("testCatchErrorThrownByJavaDelegateProvidedByDelegateExpressionOnServiceTask", variables).getId(); assertThatErrorHasBeenCaught(procId); } }
package com.yoti.api.client.spi.remote.call.factory; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.net.URI; import org.junit.Test; public class PathFactoryTest { private static final String SOME_APP_ID = "someAppId"; private static final String SOME_TOKEN = "someToken"; private static final String SOME_SESSION_ID = "someSessionId"; private static final String SOME_MEDIA_ID = "someMediaId"; private static PathFactory testObj = new PathFactory(); @Test public void shouldCreateProfilePath() { String result = testObj.createProfilePath(SOME_APP_ID, SOME_TOKEN); URI uri = URI.create(result); assertEquals("/profile/" + SOME_TOKEN, uri.getPath()); assertTrue(uri.getQuery().contains("appId=" + SOME_APP_ID)); assertTrue(uri.getQuery().matches("(.*)nonce=(?i)[A-F0-9]{8}-[A-F0-9]{4}-[A-F0-9]{4}-[A-F0-9]{4}-[A-F0-9]{12}(.*)")); assertTrue(uri.getQuery().contains("timestamp=")); } @Test public void shouldCreateAmlPath() { String result = testObj.createAmlPath(SOME_APP_ID); URI uri = URI.create(result); assertEquals("/aml-check", uri.getPath()); assertTrue(uri.getQuery().contains("appId=" + SOME_APP_ID)); assertTrue(uri.getQuery().matches("(.*)nonce=(?i)[A-F0-9]{8}-[A-F0-9]{4}-[A-F0-9]{4}-[A-F0-9]{4}-[A-F0-9]{12}(.*)")); assertTrue(uri.getQuery().contains("timestamp=")); } @Test public void shouldCreateDynamicSharingPath() { String result = testObj.createDynamicSharingPath(SOME_APP_ID); URI uri = URI.create(result); assertEquals("/qrcodes/apps/" + SOME_APP_ID, uri.getPath()); assertTrue(uri.getQuery().matches("(.*)nonce=(?i)[A-F0-9]{8}-[A-F0-9]{4}-[A-F0-9]{4}-[A-F0-9]{4}-[A-F0-9]{12}(.*)")); assertTrue(uri.getQuery().contains("timestamp=")); } @Test public void shouldCreateNewYotiDocsSessionPath() { String result = testObj.createNewYotiDocsSessionPath(SOME_APP_ID); URI uri = URI.create(result); assertEquals("/sessions", uri.getPath()); assertTrue(uri.getQuery().contains("sdkId=" + SOME_APP_ID)); assertTrue(uri.getQuery().matches("(.*)nonce=(?i)[A-F0-9]{8}-[A-F0-9]{4}-[A-F0-9]{4}-[A-F0-9]{4}-[A-F0-9]{12}(.*)")); assertTrue(uri.getQuery().contains("timestamp=")); } @Test public void shouldCreateYotiDocsSessionPath() { String result = testObj.createGetYotiDocsSessionPath(SOME_APP_ID, SOME_SESSION_ID); URI uri = URI.create(result); assertEquals("/sessions/" + SOME_SESSION_ID, uri.getPath()); assertTrue(uri.getQuery().contains("sdkId=" + SOME_APP_ID)); assertTrue(uri.getQuery().matches("(.*)nonce=(?i)[A-F0-9]{8}-[A-F0-9]{4}-[A-F0-9]{4}-[A-F0-9]{4}-[A-F0-9]{12}(.*)")); assertTrue(uri.getQuery().contains("timestamp=")); } @Test public void shouldCreateMediaContentPath() { String result = testObj.createMediaContentPath(SOME_APP_ID, SOME_SESSION_ID, SOME_MEDIA_ID); URI uri = URI.create(result); assertEquals("/sessions/" + SOME_SESSION_ID + "/media/" + SOME_MEDIA_ID + "/content", uri.getPath()); assertTrue(uri.getQuery().contains("sdkId=" + SOME_APP_ID)); assertTrue(uri.getQuery().matches("(.*)nonce=(?i)[A-F0-9]{8}-[A-F0-9]{4}-[A-F0-9]{4}-[A-F0-9]{4}-[A-F0-9]{12}(.*)")); assertTrue(uri.getQuery().contains("timestamp=")); } @Test public void shouldCreateSupportedDocumentsPath() { String result = testObj.createGetSupportedDocumentsPath(); URI uri = URI.create(result); assertEquals("/supported-documents", uri.getPath()); assertTrue(uri.getQuery().matches("(.*)nonce=(?i)[A-F0-9]{8}-[A-F0-9]{4}-[A-F0-9]{4}-[A-F0-9]{4}-[A-F0-9]{12}(.*)")); assertTrue(uri.getQuery().contains("timestamp=")); } }
/* * 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.kafka.streams.integration; import java.time.Duration; import kafka.log.LogConfig; import kafka.utils.MockTime; import org.apache.kafka.clients.admin.Admin; import org.apache.kafka.clients.admin.AdminClientConfig; import org.apache.kafka.clients.admin.Config; import org.apache.kafka.clients.admin.ConfigEntry; import org.apache.kafka.clients.consumer.ConsumerConfig; import org.apache.kafka.clients.producer.ProducerConfig; import org.apache.kafka.common.config.ConfigResource; import org.apache.kafka.common.serialization.Serdes; import org.apache.kafka.common.serialization.StringSerializer; import org.apache.kafka.common.utils.Bytes; import org.apache.kafka.streams.KafkaStreams; import org.apache.kafka.streams.StreamsBuilder; import org.apache.kafka.streams.StreamsConfig; import org.apache.kafka.streams.integration.utils.EmbeddedKafkaCluster; import org.apache.kafka.streams.integration.utils.IntegrationTestUtils; import org.apache.kafka.streams.kstream.Grouped; import org.apache.kafka.streams.kstream.KStream; import org.apache.kafka.streams.kstream.KTable; import org.apache.kafka.streams.kstream.Materialized; import org.apache.kafka.streams.kstream.TimeWindows; import org.apache.kafka.streams.processor.internals.ProcessorStateManager; import org.apache.kafka.streams.state.WindowStore; import org.apache.kafka.test.IntegrationTest; import org.apache.kafka.test.MockMapper; import org.apache.kafka.test.TestUtils; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.junit.experimental.categories.Category; import java.io.IOException; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Locale; import java.util.Properties; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import static java.time.Duration.ofMillis; import static java.time.Duration.ofSeconds; import static java.util.Collections.singletonList; import static org.apache.kafka.streams.integration.utils.IntegrationTestUtils.startApplicationAndWaitUntilRunning; import static org.apache.kafka.streams.integration.utils.IntegrationTestUtils.waitForCompletion; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; /** * Tests related to internal topics in streams */ @Category({IntegrationTest.class}) public class InternalTopicIntegrationTest { public static final EmbeddedKafkaCluster CLUSTER = new EmbeddedKafkaCluster(1); @BeforeClass public static void startCluster() throws IOException, InterruptedException { CLUSTER.start(); CLUSTER.createTopics(DEFAULT_INPUT_TOPIC, DEFAULT_INPUT_TABLE_TOPIC); } @AfterClass public static void closeCluster() { CLUSTER.stop(); } private static final String APP_ID = "internal-topics-integration-test"; private static final String DEFAULT_INPUT_TOPIC = "inputTopic"; private static final String DEFAULT_INPUT_TABLE_TOPIC = "inputTable"; private final MockTime mockTime = CLUSTER.time; private Properties streamsProp; @Before public void before() { streamsProp = new Properties(); streamsProp.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, CLUSTER.bootstrapServers()); streamsProp.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass().getName()); streamsProp.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, Serdes.String().getClass().getName()); streamsProp.put(StreamsConfig.STATE_DIR_CONFIG, TestUtils.tempDirectory().getPath()); streamsProp.put(StreamsConfig.COMMIT_INTERVAL_MS_CONFIG, 100); streamsProp.put(StreamsConfig.CACHE_MAX_BYTES_BUFFERING_CONFIG, 0); streamsProp.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest"); } @After public void after() throws IOException { // Remove any state from previous test runs IntegrationTestUtils.purgeLocalStreamsState(streamsProp); } private void produceData(final List<String> inputValues) { final Properties producerProp = new Properties(); producerProp.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, CLUSTER.bootstrapServers()); producerProp.put(ProducerConfig.ACKS_CONFIG, "all"); producerProp.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class); producerProp.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class); IntegrationTestUtils.produceValuesSynchronously(DEFAULT_INPUT_TOPIC, inputValues, producerProp, mockTime); } private Properties getTopicProperties(final String changelog) { try (final Admin adminClient = createAdminClient()) { final ConfigResource configResource = new ConfigResource(ConfigResource.Type.TOPIC, changelog); try { final Config config = adminClient.describeConfigs(Collections.singletonList(configResource)).values().get(configResource).get(); final Properties properties = new Properties(); for (final ConfigEntry configEntry : config.entries()) { if (configEntry.source() == ConfigEntry.ConfigSource.DYNAMIC_TOPIC_CONFIG) { properties.put(configEntry.name(), configEntry.value()); } } return properties; } catch (final InterruptedException | ExecutionException e) { throw new RuntimeException(e); } } } private Admin createAdminClient() { final Properties adminClientConfig = new Properties(); adminClientConfig.put(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, CLUSTER.bootstrapServers()); return Admin.create(adminClientConfig); } /* * This test just ensures that that the assignor does not get stuck during partition number resolution * for internal repartition topics. See KAFKA-10689 */ @Test public void shouldGetToRunningWithWindowedTableInFKJ() throws Exception { final String appID = APP_ID + "-windowed-FKJ"; streamsProp.put(StreamsConfig.APPLICATION_ID_CONFIG, appID); final StreamsBuilder streamsBuilder = new StreamsBuilder(); final KStream<String, String> inputTopic = streamsBuilder.stream(DEFAULT_INPUT_TOPIC); final KTable<String, String> inputTable = streamsBuilder.table(DEFAULT_INPUT_TABLE_TOPIC); inputTopic .groupBy( (k, v) -> k, Grouped.with("GroupName", Serdes.String(), Serdes.String()) ) .windowedBy(TimeWindows.of(Duration.ofMinutes(10))) .aggregate( () -> "", (k, v, a) -> a + k) .leftJoin( inputTable, v -> v, (x, y) -> x + y ); final KafkaStreams streams = new KafkaStreams(streamsBuilder.build(), streamsProp); startApplicationAndWaitUntilRunning(singletonList(streams), Duration.ofSeconds(60)); } @Test public void shouldCompactTopicsForKeyValueStoreChangelogs() { final String appID = APP_ID + "-compact"; streamsProp.put(StreamsConfig.APPLICATION_ID_CONFIG, appID); // // Step 1: Configure and start a simple word count topology // final StreamsBuilder builder = new StreamsBuilder(); final KStream<String, String> textLines = builder.stream(DEFAULT_INPUT_TOPIC); textLines.flatMapValues(value -> Arrays.asList(value.toLowerCase(Locale.getDefault()).split("\\W+"))) .groupBy(MockMapper.selectValueMapper()) .count(Materialized.as("Counts")); final KafkaStreams streams = new KafkaStreams(builder.build(), streamsProp); streams.start(); // // Step 2: Produce some input data to the input topic. // produceData(Arrays.asList("hello", "world", "world", "hello world")); // // Step 3: Verify the state changelog topics are compact // waitForCompletion(streams, 2, 30000L); streams.close(); final Properties changelogProps = getTopicProperties(ProcessorStateManager.storeChangelogTopic(appID, "Counts")); assertEquals(LogConfig.Compact(), changelogProps.getProperty(LogConfig.CleanupPolicyProp())); final Properties repartitionProps = getTopicProperties(appID + "-Counts-repartition"); assertEquals(LogConfig.Delete(), repartitionProps.getProperty(LogConfig.CleanupPolicyProp())); assertEquals(4, repartitionProps.size()); } @Test public void shouldCompactAndDeleteTopicsForWindowStoreChangelogs() { final String appID = APP_ID + "-compact-delete"; streamsProp.put(StreamsConfig.APPLICATION_ID_CONFIG, appID); // // Step 1: Configure and start a simple word count topology // final StreamsBuilder builder = new StreamsBuilder(); final KStream<String, String> textLines = builder.stream(DEFAULT_INPUT_TOPIC); final int durationMs = 2000; textLines.flatMapValues(value -> Arrays.asList(value.toLowerCase(Locale.getDefault()).split("\\W+"))) .groupBy(MockMapper.selectValueMapper()) .windowedBy(TimeWindows.of(ofSeconds(1L)).grace(ofMillis(0L))) .count(Materialized.<String, Long, WindowStore<Bytes, byte[]>>as("CountWindows").withRetention(ofSeconds(2L))); final KafkaStreams streams = new KafkaStreams(builder.build(), streamsProp); streams.start(); // // Step 2: Produce some input data to the input topic. // produceData(Arrays.asList("hello", "world", "world", "hello world")); // // Step 3: Verify the state changelog topics are compact // waitForCompletion(streams, 2, 30000L); streams.close(); final Properties properties = getTopicProperties(ProcessorStateManager.storeChangelogTopic(appID, "CountWindows")); final List<String> policies = Arrays.asList(properties.getProperty(LogConfig.CleanupPolicyProp()).split(",")); assertEquals(2, policies.size()); assertTrue(policies.contains(LogConfig.Compact())); assertTrue(policies.contains(LogConfig.Delete())); // retention should be 1 day + the window duration final long retention = TimeUnit.MILLISECONDS.convert(1, TimeUnit.DAYS) + durationMs; assertEquals(retention, Long.parseLong(properties.getProperty(LogConfig.RetentionMsProp()))); final Properties repartitionProps = getTopicProperties(appID + "-CountWindows-repartition"); assertEquals(LogConfig.Delete(), repartitionProps.getProperty(LogConfig.CleanupPolicyProp())); assertEquals(4, repartitionProps.size()); } }
package com.wangtian.message.netBean; import java.io.Serializable; import java.util.List; /** * @Author Archy Wang * @Date 2019/3/20 * @Description */ public class UserListBean implements Serializable { /** * pageNum : 1 * pageSize : 10 * total : 0 * list : [] * rows : [] * where : * params : [] * id : ea28f991-9f6c-4abb-9de8-e7173de57ec0 * username : shm * password : e10adc3949ba59abbe56e057f20f883e * name : shm * gender : 女 * idCard : * attachManagerId : manager1 * mobilePhone : * officePhone : * isManage : 否 * isAppManage : 02 * status : null * loginTime : null * loginCount : 408 * createTime : null * remark : null * caCardId : * code : null * requestIP : null * inputAuthCode : null * organizationId : null * roleName : 前台用户测试版hi * email : * position : null * loginType : 混合登录 * isVisible : 可见 * isPermitOperate : 允许 * loginDirection : 前台 * loginErrorTime : 2019-03-20T07:17:16.037+0000 * userType : 长期用户 * macAddress : null * operateTime : null * loginErrorCount : 0 * passwordEditTime : 2019-03-20T07:17:16.037+0000 * portraitName : null * userPosition : * systemFlag : HNSJMT * userStatus : 启用 * roleIds : null * organizationName : 组织机构 */ private int pageNum; private int pageSize; private int total; private String where; private String id; private String username; private String password; private String name; private String gender; private String idCard; private String attachManagerId; private String mobilePhone; private String officePhone; private String isManage; private String isAppManage; private Object status; private Object loginTime; private int loginCount; private Object createTime; private String remark; private String caCardId; private Object code; private Object requestIP; private Object inputAuthCode; private Object organizationId; private String roleName; private String email; private Object position; private String loginType; private String isVisible; private String isPermitOperate; private String loginDirection; private String loginErrorTime; private String userType; private String macAddress; private Object operateTime; private int loginErrorCount; private String passwordEditTime; private String portraitName; private String userPosition; private String systemFlag; private String userStatus; private Object roleIds; private String organizationName; private List<?> list; private List<?> rows; private List<?> params; public int getPageNum() { return pageNum; } public void setPageNum(int pageNum) { this.pageNum = pageNum; } public int getPageSize() { return pageSize; } public void setPageSize(int pageSize) { this.pageSize = pageSize; } public int getTotal() { return total; } public void setTotal(int total) { this.total = total; } public String getWhere() { return where; } public void setWhere(String where) { this.where = where; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public String getIdCard() { return idCard; } public void setIdCard(String idCard) { this.idCard = idCard; } public String getAttachManagerId() { return attachManagerId; } public void setAttachManagerId(String attachManagerId) { this.attachManagerId = attachManagerId; } public String getMobilePhone() { return mobilePhone; } public void setMobilePhone(String mobilePhone) { this.mobilePhone = mobilePhone; } public String getOfficePhone() { return officePhone; } public void setOfficePhone(String officePhone) { this.officePhone = officePhone; } public String getIsManage() { return isManage; } public void setIsManage(String isManage) { this.isManage = isManage; } public String getIsAppManage() { return isAppManage; } public void setIsAppManage(String isAppManage) { this.isAppManage = isAppManage; } public Object getStatus() { return status; } public void setStatus(Object status) { this.status = status; } public Object getLoginTime() { return loginTime; } public void setLoginTime(Object loginTime) { this.loginTime = loginTime; } public int getLoginCount() { return loginCount; } public void setLoginCount(int loginCount) { this.loginCount = loginCount; } public Object getCreateTime() { return createTime; } public void setCreateTime(Object createTime) { this.createTime = createTime; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } public String getCaCardId() { return caCardId; } public void setCaCardId(String caCardId) { this.caCardId = caCardId; } public Object getCode() { return code; } public void setCode(Object code) { this.code = code; } public Object getRequestIP() { return requestIP; } public void setRequestIP(Object requestIP) { this.requestIP = requestIP; } public Object getInputAuthCode() { return inputAuthCode; } public void setInputAuthCode(Object inputAuthCode) { this.inputAuthCode = inputAuthCode; } public Object getOrganizationId() { return organizationId; } public void setOrganizationId(Object organizationId) { this.organizationId = organizationId; } public String getRoleName() { return roleName; } public void setRoleName(String roleName) { this.roleName = roleName; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public Object getPosition() { return position; } public void setPosition(Object position) { this.position = position; } public String getLoginType() { return loginType; } public void setLoginType(String loginType) { this.loginType = loginType; } public String getIsVisible() { return isVisible; } public void setIsVisible(String isVisible) { this.isVisible = isVisible; } public String getIsPermitOperate() { return isPermitOperate; } public void setIsPermitOperate(String isPermitOperate) { this.isPermitOperate = isPermitOperate; } public String getLoginDirection() { return loginDirection; } public void setLoginDirection(String loginDirection) { this.loginDirection = loginDirection; } public String getLoginErrorTime() { return loginErrorTime; } public void setLoginErrorTime(String loginErrorTime) { this.loginErrorTime = loginErrorTime; } public String getUserType() { return userType; } public void setUserType(String userType) { this.userType = userType; } public String getMacAddress() { return macAddress; } public void setMacAddress(String macAddress) { this.macAddress = macAddress; } public Object getOperateTime() { return operateTime; } public void setOperateTime(Object operateTime) { this.operateTime = operateTime; } public int getLoginErrorCount() { return loginErrorCount; } public void setLoginErrorCount(int loginErrorCount) { this.loginErrorCount = loginErrorCount; } public String getPasswordEditTime() { return passwordEditTime; } public void setPasswordEditTime(String passwordEditTime) { this.passwordEditTime = passwordEditTime; } public String getPortraitName() { return portraitName; } public void setPortraitName(String portraitName) { this.portraitName = portraitName; } public String getUserPosition() { return userPosition; } public void setUserPosition(String userPosition) { this.userPosition = userPosition; } public String getSystemFlag() { return systemFlag; } public void setSystemFlag(String systemFlag) { this.systemFlag = systemFlag; } public String getUserStatus() { return userStatus; } public void setUserStatus(String userStatus) { this.userStatus = userStatus; } public Object getRoleIds() { return roleIds; } public void setRoleIds(Object roleIds) { this.roleIds = roleIds; } public String getOrganizationName() { return organizationName; } public void setOrganizationName(String organizationName) { this.organizationName = organizationName; } public List<?> getList() { return list; } public void setList(List<?> list) { this.list = list; } public List<?> getRows() { return rows; } public void setRows(List<?> rows) { this.rows = rows; } public List<?> getParams() { return params; } public void setParams(List<?> params) { this.params = params; } }
/* * Copyright 2020 LINE Corporation * * LINE Corporation 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: * * 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.linecorp.armeria.common.auth.oauth2; import static java.util.Objects.requireNonNull; import java.nio.charset.StandardCharsets; import java.util.Base64; import java.util.Map; import java.util.function.Supplier; import com.google.common.base.MoreObjects; import com.linecorp.armeria.common.QueryParams; import com.linecorp.armeria.common.QueryParamsBuilder; import com.linecorp.armeria.common.annotation.Nullable; import com.linecorp.armeria.common.annotation.UnstableApi; import com.linecorp.armeria.internal.common.auth.oauth2.CaseUtil; /** * Provides client authorization for the OAuth 2.0 requests, * as per <a href="https://datatracker.ietf.org/doc/html/rfc6749#section-2.3">[RFC6749], Section 2.3</a>. * For example: * <pre>{@code * Authorization: Basic czZCaGRSa3F0Mzo3RmpmcDBaQnIxS3REUmJuZlZkbUl3 * }</pre> * Fetches authorization source from the designated authorization or credentials supplier, which * might be facilitated by a secure Secret provider. Will fetch the authorization source for each * request. Therefore the designated supplier must cache the value in order to avoid unnecessary * network hops. * The authorization source might either provide complete authorization token or client credentials. */ @UnstableApi public final class ClientAuthorization { private static final String DEFAULT_AUTHORIZATION_TYPE = "Basic"; private static final char AUTHORIZATION_SEPARATOR = ' '; private static final char CREDENTIALS_SEPARATOR = ':'; private static final String CLIENT_ID = "client_id"; private static final String CLIENT_SECRET = "client_secret"; private final String authorizationType; @Nullable private final Supplier<String> authorizationSupplier; @Nullable private final Supplier<? extends Map.Entry<String, String>> credentialsSupplier; /** * Provides client authorization for the OAuth 2.0 requests based on encoded authorization token and * authorization type, * as per <a href="https://datatracker.ietf.org/doc/html/rfc6749#section-2.3">[RFC6749], Section 2.3</a>. * * @param authorizationSupplier A supplier of encoded client authorization token. * @param authorizationType One of the registered HTTP authentication schemes as per * <a href="https://www.iana.org/assignments/http-authschemes/http-authschemes.xhtml"> * HTTP Authentication Scheme Registry</a>. */ public static ClientAuthorization ofAuthorization( Supplier<String> authorizationSupplier, String authorizationType) { return new ClientAuthorization(requireNonNull(authorizationSupplier, "authorizationSupplier"), null, requireNonNull(authorizationType, "authorizationType")); } /** * Provides client authorization for the OAuth 2.0 requests based on encoded authorization token and * {@code Basic} authorization type, * as per <a href="https://datatracker.ietf.org/doc/html/rfc6749#section-2.3">[RFC6749], Section 2.3</a>. * * @param authorizationSupplier A supplier of encoded client authorization token. */ public static ClientAuthorization ofBasicAuthorization( Supplier<String> authorizationSupplier) { return new ClientAuthorization(requireNonNull(authorizationSupplier, "authorizationSupplier"), null, null); } /** * Provides client authorization for the OAuth 2.0 requests based on client credentials and * authorization type, * as per <a href="https://datatracker.ietf.org/doc/html/rfc6749#section-2.3">[RFC6749], Section 2.3</a>. * * @param credentialsSupplier A supplier of client credentials. * @param authorizationType One of the registered HTTP authentication schemes as per * <a href="https://www.iana.org/assignments/http-authschemes/http-authschemes.xhtml"> * HTTP Authentication Scheme Registry</a>. */ public static ClientAuthorization ofCredentials( Supplier<? extends Map.Entry<String, String>> credentialsSupplier, String authorizationType) { return new ClientAuthorization(null, requireNonNull(credentialsSupplier, "credentialsSupplier"), requireNonNull(authorizationType, "authorizationType")); } /** * Provides client authorization for the OAuth 2.0 requests based on client credentials and * {@code Basic} authorization type, * as per <a href="https://datatracker.ietf.org/doc/html/rfc6749#section-2.3">[RFC6749], Section 2.3</a>. * * @param credentialsSupplier A supplier of client credentials. */ public static ClientAuthorization ofCredentials( Supplier<? extends Map.Entry<String, String>> credentialsSupplier) { return new ClientAuthorization(null, requireNonNull(credentialsSupplier, "credentialsSupplier"), null); } private ClientAuthorization(@Nullable Supplier<String> authorizationSupplier, @Nullable Supplier<? extends Map.Entry<String, String>> credentialsSupplier, @Nullable String authorizationType) { if (authorizationSupplier == null && credentialsSupplier == null) { throw new NullPointerException("authorizationSupplier && credentialsSupplier"); } this.authorizationSupplier = authorizationSupplier; this.credentialsSupplier = credentialsSupplier; this.authorizationType = authorizationType == null ? DEFAULT_AUTHORIZATION_TYPE : authorizationType; } private String composeAuthorizationString() { final String clientAuthorization; if (authorizationSupplier != null) { clientAuthorization = authorizationSupplier.get(); } else if (credentialsSupplier != null) { final Map.Entry<String, String> clientCredentials = credentialsSupplier.get(); clientAuthorization = encodeClientCredentials(clientCredentials.getKey(), clientCredentials.getValue()); } else { // we should not get here throw new NullPointerException("authorizationSupplier && credentialsSupplier"); } return clientAuthorization; } /** * Fetches client authorization token or client credentials from the supplier and composes client * {@code Authorization} header value, * as per <a href="https://datatracker.ietf.org/doc/html/rfc6749#section-2.3">[RFC6749], Section 2.3</a>: * <pre>{@code * Authorization: Basic czZCaGRSa3F0Mzo3RmpmcDBaQnIxS3REUmJuZlZkbUl3 * }</pre>. * * @return encoded client {@code Authorization} header value. */ public String asHeaderValue() { return CaseUtil.firstUpperAllLowerCase(authorizationType) + AUTHORIZATION_SEPARATOR + composeAuthorizationString(); } /** * Fetches client credentials from the supplier and composes required body parameters, * as per <a href="https://datatracker.ietf.org/doc/html/rfc6749#section-2.3">[RFC6749], Section 2.3</a>: * <pre>{@code * client_id=s6BhdRkqt3&client_secret=7Fjfp0ZBr1KtDRbnfVdmIw * }</pre>. * The client MAY omit the {@code client_secret} parameter if the client secret is an empty string. */ public void addAsBodyParameters(QueryParamsBuilder formBuilder) { requireNonNull(credentialsSupplier, "credentialsSupplier"); final Map.Entry<String, String> clientCredentials = credentialsSupplier.get(); formBuilder.add(CLIENT_ID, requireNonNull(clientCredentials.getKey(), CLIENT_ID)); final String clientSecret = clientCredentials.getValue(); if (clientSecret != null && !clientSecret.isEmpty()) { formBuilder.add(CLIENT_SECRET, clientSecret); } } /** * Fetches client credentials from the supplier and composes required body parameters, * as per <a href="https://datatracker.ietf.org/doc/html/rfc6749#section-2.3">[RFC6749], Section 2.3</a>: * <pre>{@code * client_id=s6BhdRkqt3&client_secret=7Fjfp0ZBr1KtDRbnfVdmIw * }</pre>. * The client MAY omit the {@code client_secret} parameter if the client secret is an empty string. * * @return encoded client credentials request body parameters as {@link QueryParams}. */ public QueryParams asBodyParameters() { final QueryParamsBuilder formBuilder = QueryParams.builder(); addAsBodyParameters(formBuilder); return formBuilder.build(); } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("type", authorizationType) .add("source", authorizationSupplier != null ? "authorization" : credentialsSupplier != null ? "credentials" : null) .toString(); } private static String encodeClientCredentials(String clientId, String clientSecret) { return Base64.getEncoder() .encodeToString( (clientId + CREDENTIALS_SEPARATOR + clientSecret) .getBytes(StandardCharsets.UTF_8)); } }
class OWnm5ripf { } class iP7qB { public Cye7[][] WF6Sv4fP_ (xtcv tYs7y, void[] Vmv, void R5a, boolean YDV, void jkc5, void ii4hHvz5cBOFLD, boolean[][][][][] P) { while ( -( true.naGbKL).AO3) ; !!false.E1ef3; { int aJL0; int[][] S; VV91QirO3iD6 e; tbH22oJugn QWZgOd; pIa47gMiA e; } if ( null[ !!false.oWVGZEuXlb9Rxw]) ; sbjI[][][] IZnSQjQ7 = !-true[ -!-!new CSsekM[ 73877.b9BN()].fKLDidab7Ug2mo()]; { int[][][][][][][][] W2cyv_k; if ( true[ false.K7VRbK]) if ( this.RHj()) ; bx9He[] Synd; void Xb7XAb; } -!new SLxNvLuJE18o().HGo85vkE(); void Hat70JZ0dLyFg = !26909[ -!-this[ -this.zY4id()]] = 0506.QGpH9ry08M(); new p8ftZmnyhkJDG()[ !!!!-null.CeqOabq()]; true[ 74469[ !!-!true.i]]; ; int[] ptAs2wJ6 = false.I6yAvClNacBt4 = !!qEY2LJSteairNB().R7Ub; boolean GW_CNT_5vsVp; } public int diF () throws ziNiwOdAZ7 { QY06pe kpN1vR0M40D; if ( false[ !true[ Nc3HIVYl6().tJL9()]]) return;else { ; } p[][] CSpt = new boolean[ -false[ 7214.iizTDTygG()]].m7KhNeQA; { zNbJ_mZSeLi yInVs3R; boolean[] m4OhOBXBnXF; void[][][] Q4wk9OoBJM; return; if ( true.n5M3zq) if ( false.MZvFxXl1pa5) !( --!-this.vzNw())[ -44.Q()]; if ( -false.RHhjnOuElA) { i[][][][] cBdxub_AAh5ZhB; } void SNt3qaSMjW; Rx[][][] h8s; boolean[][][] jG2TB; } void ipVPQ6Yw1 = !null.i4fYf4RYIEhq(); boolean[] miXGN6ksAJ = new _fPafp3JI()[ ( 7539077.K).z_iM]; { boolean[][][][] RYIqu0_; ; boolean[][][][][][] tq_5T; int qVdZy97f7e; boolean[] vXWFum5wI; boolean[] zufJRWpfOr0DI; erj KpYt; } int rjDDwwzjyV71; return -03649095.A; ; int[] DYAOn6 = !( !-new akbC().taP83QPE())[ ( !this.nBKnQc7lsiv).sXwN] = -true[ -086629[ new YuuHsO7rw8[ 9964.Isac5EOC].MHdKS()]]; { if ( !!true.W3Cy7xq2Lj()) if ( this.F()) true.LQlf0(); !!!!( this.J_3GY0)[ new NEK5ky[ eGKYFEwxVre.RMtMmvmBfsT].Sy]; if ( this.BLm7febR4uw) if ( this.ymJZ_uDd()) ; return; if ( W8xVw5HpRh().rW11RZ) if ( false.nM()) if ( false[ !!-this.jm6omYbDw21f50()]) ; void[][] oS8; !true[ !this.Ezti2u]; int LyivuOk; { int lSsw; } ( dk2uA4wrSz[ !!( new boolean[ -!!!!false.ge].T()).DhC4]).qLSbPcTu; { void[] nf61N3; } boolean UjWyjjUi2Kc; if ( false.kM) return; boolean KO16; { if ( -false.fz6) { boolean b7UEs5zdTwjkoU; } } } return; } public static void WBMfw (String[] Zf4NDgn) throws Q86GvEV { n9aEOoAVnL[][] SfpuktshG; boolean uCXyLt6ZEOhzW; mlB[][] Yn71pb5a; ; } public void L0d; public JZ7oAfpGW_FB dZS1pgfp; public static void GQu (String[] JktiBlk) throws qRDE { ; boolean rmLVcK5U = !-new BjtT3M4Gn().KT5BeHoagB(); boolean PwLuXmI; } public int l0B4vMkMWnGvPJ; public static void Nn2RRMY2W (String[] _W5yX8HNOJxrOB) throws P0kzspYD29gdK { void dzdalnH = -true[ null.dl0Tw()]; new void[ 28[ -!-!( !-!-this.XwRCgdQ())[ null.XN]]][ --null[ -hXmKaqNujjw().pLSzmq_ETsn]]; int jb = 906334166[ null[ --0[ this[ !---boK5yD.dQjKY()]]]]; while ( -this[ new aybVwO()[ !-new Ep()[ new void[ !true[ !!--this[ 5.J3YF]]][ c5MGpL2E()[ new nH()[ !157693.x_mctxW8SZTvh()]]]]]]) return; { Ce4EWx[][] HnudToj6GJyOd; -!this.T53KAFzI5mw(); ; int E; return; int[][][] HbekmzCc; LAaotqzzJ[][][][][][][] lJR9xiY; void gjtlSS7MG; BTgdz_g7rUk[] N8Ct; while ( this[ -OxllHwFzSsN.u0N()]) return; { boolean[] QlmMUKQi9; } int[] auk; int MUoDoJTwA; KPGEfWL[] Bf96YdXBD; vDIQbZ0tC9 HH9; if ( !!!!this[ false[ -!IF7EKV5RCl[ !--!--VfEEv0twtlxv0().C]]]) return; UgKuHc9zX[] pc; int[] q9H5Scvbc_np; } void[][] US; int pIDtbb9DJKMX1n = new NOEqBUf8XtqVXp().Hux() = !this[ true.ci5n2o3UkPhv1O]; TB p_TaDJ61xm = !-!!true.hM_K1UarTy5O(); void[] lKNx0E6hh = !!new YM[ 4154727.jXdD].w70_cXoOe = ---!mP().mSKxcMre(); hDFQO oEuw9lV; if ( !-!--this[ null.WCf]) if ( 9.MlpLPkUM) ;else { if ( uKm_tX98f().XewCiKi) ; } ; vhyH3hMn4OH[] oQiujwFjADUV; while ( ( mrXhDC1vMkp.iU6vpEPtYSsT).iZBwx4V) { boolean[][] S; } dJnZu().nz(); { void[][] nSigAIkJyW8b; ; return; { void[] U87Rh; } { int iAczA9UoR; } while ( false[ !!--NqIU2W4QkjPq[ ( --70.tT4ka1YUq1qF3k())[ -( !!--new I[ true.jXu7KVr6UbL2fw()].csoGkAzH3s)[ -this[ !!!!!new kMFO().J2E]]]]]) while ( ( -!!--!_().TN77LPi1OcM)[ -!-!( -null.Yvom9D()).WDvUtLLMl6KYI]) return; if ( new HRd().wNrvcZTDiU) { while ( ( false.g).Text) { int _m8PPiSVo; } } ThBtMUU79LL0[][][] BJx7FS8E; while ( !-!this.uixt5) return; { while ( !-!!( ( -!new void[ false.Q_iFKbopm].iFJbCId()).riQkC0kxa).DvF()) if ( -true.A()) -this.kPch8(); } int[][] ri; while ( -oPxim._TK5cgqv) this[ !!false.Du2HO2_Wp3s()]; int V6GHfh6qZ6Na9; int[][][][] FV; int[][][][][][] TVe_LF; return; ; boolean SdDsKfUfh09XLS; } boolean[][][][][][] iGhnS; } public boolean xZWpdf; public static void UEo0x (String[] SURs6u) throws k7Cqj { ; -( !!-olQrtNX0md()[ -S[ !null.D8X7q3H84E()]])[ ( new QWaAjIBpOIO6u().Nej4s0TbrRvCa5).ggUxI76ySyUVIK]; while ( --rWIwc03HQDh7K.Kpl280A2ppUmP) !false.odd4; C07PzZzIfl9[] Qw = !-!-V()[ new DBuXBOjQ().sA]; while ( !--null[ zqvDhYN.Z2DugHOB()]) ; return !----this.VlgS(); void WEEPg86Ixj96; boolean[] rKPUHiCgE9NvYF = this.R7() = -( false[ !!new A8ka6jo9Ev8Q2k()[ --!!V6v9[ ( xk5Mo().Sz9R6j36())[ vmaSVm0a8B[ ICnF4kkW.t6rQvYgj0Z0ix]]]]]).BNpFTOH1_GZ3; void[][][] zPkOlfF; EjNRAb o = null.dXV4UDy(); new void[ --null.yZ6ZofqoFvDw].Hm6cR0; return new NI2TcU3HIE().tXF; CD8XRg05Il fK0v8BhPA3bsf = this[ !null.JApHJ_]; ; while ( !null[ -OlixdDR().LKrTx]) return; return !--ZP()[ !dE95xrl2b8DP6[ new DEcxouOtM().Tbrc1HlPe_()]]; ( --( -false.Oy_MB6jbXCB7MS).k0QxBU())[ -new C82gCP4EZ[ --this[ !new void[ !true[ -new int[ this.wch()].rgXBW739hn]].z()]].GH_gMnP52()]; int jR1DDYuMqpPbR5 = ( ---new jT36pQQEB().m4lI1uznC3).asjgew; int RiBTEH; void x_OnSHA40i1cr; } public static void Xmcvkr4PGU (String[] nyPEY) throws lHCpvmDgiJS6f0 { boolean[] ZC2dIq2 = !!false.hAY7pAdpsI = 193326461[ null[ false[ aVCwfbv705fdF()[ -!-true[ -null.SRT42e]]]]]; void[][][][][][][] Nu7eHEE; boolean[] mfqBiso; kGG6_VFLWcSkX[][] jf1Wps = false.lZWInZM; } public UZDq_Q2rguK0F[][] TqOH5; public x[] foMF0lhaB_; } class aC3Q { }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import util.CookieFilter; import util.HTMLFilter; import javax.servlet.ServletException; import javax.servlet.http.*; import java.io.IOException; import java.io.PrintWriter; import java.util.ResourceBundle; /** * Example servlet showing request headers * * @author James Duncan Davidson <duncan@eng.sun.com> */ public class CookieExample extends HttpServlet { private static final long serialVersionUID = 1L; @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { ResourceBundle rb = ResourceBundle.getBundle("LocalStrings",request.getLocale()); String cookieName = request.getParameter("cookiename"); String cookieValue = request.getParameter("cookievalue"); Cookie aCookie = null; if (cookieName != null && cookieValue != null) { aCookie = new Cookie(cookieName, cookieValue); aCookie.setPath(request.getContextPath() + "/"); response.addCookie(aCookie); } response.setContentType("text/html"); response.setCharacterEncoding("UTF-8"); PrintWriter out = response.getWriter(); out.println("<!DOCTYPE html><html>"); out.println("<head>"); out.println("<meta charset=\"UTF-8\" />"); String title = rb.getString("cookies.title"); out.println("<title>" + title + "</title>"); out.println("</head>"); out.println("<body bgcolor=\"white\">"); // relative links // XXX // making these absolute till we work out the // addition of a PathInfo issue out.println("<a href=\"../cookies.html\">"); out.println("<img src=\"../images/code.gif\" height=24 " + "width=24 align=right border=0 alt=\"view code\"></a>"); out.println("<a href=\"../index.html\">"); out.println("<img src=\"../images/return.gif\" height=24 " + "width=24 align=right border=0 alt=\"return\"></a>"); out.println("<h3>" + title + "</h3>"); Cookie[] cookies = request.getCookies(); if ((cookies != null) && (cookies.length > 0)) { HttpSession session = request.getSession(false); String sessionId = null; if (session != null) { sessionId = session.getId(); } out.println(rb.getString("cookies.cookies") + "<br>"); for (Cookie cookie : cookies) { String cName = cookie.getName(); String cValue = cookie.getValue(); out.print("Cookie Name: " + HTMLFilter.filter(cName) + "<br>"); out.println(" Cookie Value: " + HTMLFilter.filter(CookieFilter.filter(cName, cValue, sessionId)) + "<br><br>"); } } else { out.println(rb.getString("cookies.no-cookies")); } if (aCookie != null) { out.println("<P>"); out.println(rb.getString("cookies.set") + "<br>"); out.print(rb.getString("cookies.name") + " " + HTMLFilter.filter(cookieName) + "<br>"); out.print(rb.getString("cookies.value") + " " + HTMLFilter.filter(cookieValue)); } out.println("<P>"); out.println(rb.getString("cookies.make-cookie") + "<br>"); out.print("<form action=\""); out.println("CookieExample\" method=POST>"); out.print(rb.getString("cookies.name") + " "); out.println("<input type=text length=20 name=cookiename><br>"); out.print(rb.getString("cookies.value") + " "); out.println("<input type=text length=20 name=cookievalue><br>"); out.println("<input type=submit></form>"); out.println("</body>"); out.println("</html>"); } @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { doGet(request, response); } }
/* Tipo de PILA LINEAL implementada con array estatico, ver definicions y conceptos en el word de la materia. */ package PilaLineal; import java.io.*; import java.util.EmptyStackException; public class PilaLineal <T> { private static final int TAMPILA = 49;//50 private int cima;//Puntero de la pila private Object [] listaPila; public PilaLineal(){ cima =-1;//Condicion de pila vacia listaPila = new Object [TAMPILA]; } //Operaciones que modifican la pila: public void insertar(T elemento){ if(pilaLlena()){ throw new StackOverflowError(); }else{ cima++; listaPila[cima]= elemento; } } public T quitar(){ if(pilaVacia()){ throw new EmptyStackException(); }else{ T data = (T) listaPila[cima]; listaPila [cima] = 0;//Limpio cima--; return data; } } public void limpiarPila(){ if(pilaVacia()){ throw new EmptyStackException(); }else{ for (int i = 0; i <= cima; i++) { listaPila[i]=0; } cima=-1; } } //Operacion de acceso a la pila: public T cimaPila(){ if(pilaVacia()) throw new EmptyStackException(); return (T)listaPila[cima]; } //Verificacion de estado de pila public boolean pilaVacia(){ return cima ==-1; } public boolean pilaLlena(){ return cima == TAMPILA; } public void mostrarDatos(){ if(pilaVacia()){ throw new EmptyStackException(); }else{ for (Object tipoLista : listaPila) { System.out.print("["+tipoLista+"] "); } } } }
// This file is made available under Elastic License 2.0. // This file is based on code available under the Apache license here: // https://github.com/apache/incubator-doris/blob/master/fe/fe-core/src/main/java/org/apache/doris/qe/SessionVariable.java // Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. package com.starrocks.qe; import com.starrocks.common.FeMetaVersion; import com.starrocks.common.io.Text; import com.starrocks.common.io.Writable; import com.starrocks.common.util.CompressionUtils; import com.starrocks.common.util.TimeUtils; import com.starrocks.qe.VariableMgr.VarAttr; import com.starrocks.server.GlobalStateMgr; import com.starrocks.system.BackendCoreStat; import com.starrocks.thrift.TCompressionType; import com.starrocks.thrift.TPipelineProfileLevel; import com.starrocks.thrift.TQueryOptions; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.json.JSONObject; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.io.Serializable; import java.lang.reflect.Field; // System variable public class SessionVariable implements Serializable, Writable, Cloneable { private static final Logger LOG = LogManager.getLogger(SessionVariable.class); public static final String EXEC_MEM_LIMIT = "exec_mem_limit"; /** * configure the mem limit of load process on BE. * Previously users used exec_mem_limit to set memory limits. * To maintain compatibility, the default value of load_mem_limit is 0, * which means that the load memory limit is still using exec_mem_limit. * Users can set a value greater than zero to explicitly specify the load memory limit. * This variable is mainly for INSERT operation, because INSERT operation has both query and load part. * Using only the exec_mem_limit variable does not make a good distinction of memory limit between the two parts. */ public static final String LOAD_MEM_LIMIT = "load_mem_limit"; /** * The mem limit of query on BE. It takes effects only when enabling pipeline engine. * - If `query_mem_limit` > 0, use it to limit the memory of a query. * The memory a query able to be used is just `query_mem_limit`. * - Otherwise, use `exec_mem_limit` to limit the memory of a query. * The memory a query able to be used is `exec_mem_limit * num_fragments * pipeline_dop`. * To maintain compatibility, the default value is 0. */ public static final String QUERY_MEM_LIMIT = "query_mem_limit"; public static final String QUERY_TIMEOUT = "query_timeout"; public static final String QUERY_DELIVERY_TIMEOUT = "query_delivery_timeout"; public static final String MAX_EXECUTION_TIME = "max_execution_time"; public static final String IS_REPORT_SUCCESS = "is_report_success"; public static final String PROFILING = "profiling"; public static final String SQL_MODE = "sql_mode"; /** * Because we modified the default value of sql_mode. * The default value in v1 version is 0, and in v2 we support sql mode not set only_full_group_by. * In order to ensure the consistency of logic, * the storage name of sql_mode is changed here, in order to achieve compatibility */ public static final String SQL_MODE_STORAGE_NAME = "sql_mode_v2"; public static final String RESOURCE_GROUP = "resource_group"; public static final String AUTO_COMMIT = "autocommit"; public static final String TX_ISOLATION = "tx_isolation"; public static final String CHARACTER_SET_CLIENT = "character_set_client"; public static final String CHARACTER_SET_CONNNECTION = "character_set_connection"; public static final String CHARACTER_SET_RESULTS = "character_set_results"; public static final String CHARACTER_SET_SERVER = "character_set_server"; public static final String COLLATION_CONNECTION = "collation_connection"; public static final String COLLATION_DATABASE = "collation_database"; public static final String COLLATION_SERVER = "collation_server"; public static final String SQL_AUTO_IS_NULL = "SQL_AUTO_IS_NULL"; public static final String SQL_SELECT_LIMIT = "sql_select_limit"; public static final String MAX_ALLOWED_PACKET = "max_allowed_packet"; public static final String AUTO_INCREMENT_INCREMENT = "auto_increment_increment"; public static final String QUERY_CACHE_TYPE = "query_cache_type"; public static final String INTERACTIVE_TIMTOUT = "interactive_timeout"; public static final String WAIT_TIMEOUT = "wait_timeout"; public static final String NET_WRITE_TIMEOUT = "net_write_timeout"; public static final String NET_READ_TIMEOUT = "net_read_timeout"; public static final String TIME_ZONE = "time_zone"; public static final String SQL_SAFE_UPDATES = "sql_safe_updates"; public static final String NET_BUFFER_LENGTH = "net_buffer_length"; public static final String CODEGEN_LEVEL = "codegen_level"; // mem limit can't smaller than bufferpool's default page size public static final int MIN_EXEC_MEM_LIMIT = 2097152; public static final String BATCH_SIZE = "batch_size"; public static final String CHUNK_SIZE = "chunk_size"; public static final String DISABLE_STREAMING_PREAGGREGATIONS = "disable_streaming_preaggregations"; public static final String STREAMING_PREAGGREGATION_MODE = "streaming_preaggregation_mode"; public static final String DISABLE_COLOCATE_JOIN = "disable_colocate_join"; public static final String DISABLE_BUCKET_JOIN = "disable_bucket_join"; public static final String PARALLEL_FRAGMENT_EXEC_INSTANCE_NUM = "parallel_fragment_exec_instance_num"; public static final String ENABLE_INSERT_STRICT = "enable_insert_strict"; public static final String ENABLE_SPILLING = "enable_spilling"; // if set to true, some of stmt will be forwarded to master FE to get result public static final String FORWARD_TO_MASTER = "forward_to_master"; // user can set instance num after exchange, no need to be equal to nums of before exchange public static final String PARALLEL_EXCHANGE_INSTANCE_NUM = "parallel_exchange_instance_num"; public static final String EVENT_SCHEDULER = "event_scheduler"; public static final String STORAGE_ENGINE = "storage_engine"; public static final String DIV_PRECISION_INCREMENT = "div_precision_increment"; // see comment of `starrocks_max_scan_key_num` and `max_pushdown_conditions_per_column` in BE config public static final String MAX_SCAN_KEY_NUM = "max_scan_key_num"; public static final String MAX_PUSHDOWN_CONDITIONS_PER_COLUMN = "max_pushdown_conditions_per_column"; // use new execution engine instead of the old one if enable_pipeline_engine is true, // the new execution engine split a fragment into pipelines, then create several drivers // from the pipeline for parallel executing, threads from global pool pick out the // ready-to-run drivers to execute and switch the blocked drivers off cores; // the old one put each fragment into a thread, then pull final result from the root fragment, // leaf fragments always waiting for disk IO's completion and intermediate fragments wait // for chunk arrival and blocked on receive queues of its exchange node, so among // threads allocated for a query in the old execution engine, only small number of // them do the real work on core. public static final String ENABLE_PIPELINE = "enable_pipeline"; public static final String ENABLE_PIPELINE_ENGINE = "enable_pipeline_engine"; // Use resource group. It will influence the CPU schedule, I/O scheduler, and // memory limit etc. in BE. public static final String ENABLE_RESOURCE_GROUP = "enable_resource_group"; public static final String ENABLE_TABLET_INTERNAL_PARALLEL = "enable_tablet_internal_parallel"; public static final String PIPELINE_DOP = "pipeline_dop"; public static final String PIPELINE_PROFILE_LEVEL = "pipeline_profile_level"; public static final String WORKGROUP_ID = "workgroup_id"; // hash join right table push down public static final String HASH_JOIN_PUSH_DOWN_RIGHT_TABLE = "hash_join_push_down_right_table"; // disable join reorder public static final String DISABLE_JOIN_REORDER = "disable_join_reorder"; // open predicate reorder public static final String ENABLE_PREDICATE_REORDER = "enable_predicate_reorder"; public static final String ENABLE_FILTER_UNUSED_COLUMNS_IN_SCAN_STAGE = "enable_filter_unused_columns_in_scan_stage"; // the maximum time, in seconds, waiting for an insert statement's transaction state // transfer from COMMITTED to VISIBLE. // If the time exceeded but the transaction state is not VISIBLE, the transaction will // still be considered as succeeded and an OK packet will be sent to the client, but // the affected records may not be visible to the subsequent queries, even if it's in // the same session. public static final String TRANSACTION_VISIBLE_WAIT_TIMEOUT = "tx_visible_wait_timeout"; // only for Aliyun DTS, no actual use. public static final String FOREIGN_KEY_CHECKS = "foreign_key_checks"; // force schedule local be for HybridBackendSelector // only for hive external table now public static final String FORCE_SCHEDULE_LOCAL = "force_schedule_local"; // -------- New planner session variables start -------- public static final String NEW_PLANER_AGG_STAGE = "new_planner_agg_stage"; public static final String BROADCAST_ROW_LIMIT = "broadcast_row_limit"; public static final String NEW_PLANNER_OPTIMIZER_TIMEOUT = "new_planner_optimize_timeout"; public static final String ENABLE_GROUPBY_USE_OUTPUT_ALIAS = "enable_groupby_use_output_alias"; public static final String ENABLE_QUERY_DUMP = "enable_query_dump"; public static final String CBO_MAX_REORDER_NODE_USE_EXHAUSTIVE = "cbo_max_reorder_node_use_exhaustive"; public static final String CBO_ENABLE_DP_JOIN_REORDER = "cbo_enable_dp_join_reorder"; public static final String CBO_MAX_REORDER_NODE_USE_DP = "cbo_max_reorder_node_use_dp"; public static final String CBO_ENABLE_GREEDY_JOIN_REORDER = "cbo_enable_greedy_join_reorder"; public static final String CBO_ENABLE_REPLICATED_JOIN = "cbo_enable_replicated_join"; public static final String CBO_USE_CORRELATED_JOIN_ESTIMATE = "cbo_use_correlated_join_estimate"; public static final String CBO_ENABLE_LOW_CARDINALITY_OPTIMIZE = "cbo_enable_low_cardinality_optimize"; public static final String CBO_USE_NTH_EXEC_PLAN = "cbo_use_nth_exec_plan"; public static final String CBO_CTE_REUSE = "cbo_cte_reuse"; public static final String CBO_CTE_REUSE_RATE = "cbo_cte_reuse_rate"; public static final String ENABLE_SQL_DIGEST = "enable_sql_digest"; public static final String CBO_MAX_REORDER_NODE = "cbo_max_reorder_node"; // -------- New planner session variables end -------- // Type of compression of transmitted data // Different compression algorithms may be chosen in different hardware environments. For example, // in the case of insufficient network bandwidth, but excess CPU resources, an algorithm with a // higher compression ratio may be chosen to use more CPU and make the overall query time lower. public static final String TRANSMISSION_COMPRESSION_TYPE = "transmission_compression_type"; public static final String RUNTIME_JOIN_FILTER_PUSH_DOWN_LIMIT = "runtime_join_filter_push_down_limit"; public static final String ENABLE_GLOBAL_RUNTIME_FILTER = "enable_global_runtime_filter"; public static final String GLOBAL_RUNTIME_FILTER_BUILD_MAX_SIZE = "global_runtime_filter_build_max_size"; public static final String GLOBAL_RUNTIME_FILTER_PROBE_MIN_SIZE = "global_runtime_filter_probe_min_size"; public static final String GLOBAL_RUNTIME_FILTER_PROBE_MIN_SELECTIVITY = "global_runtime_filter_probe_min_selectivity"; public static final String ENABLE_COLUMN_EXPR_PREDICATE = "enable_column_expr_predicate"; public static final String ENABLE_EXCHANGE_PASS_THROUGH = "enable_exchange_pass_through"; public static final String ENABLE_EXCHANGE_PASS_THROUGH_EXPIRE = "enable_exchange_pass_through_expire"; public static final String SINGLE_NODE_EXEC_PLAN = "single_node_exec_plan"; public static final String ALLOW_DEFAULT_PARTITION = "allow_default_partition"; public static final String ENABLE_HIVE_COLUMN_STATS = "enable_hive_column_stats"; public static final String RUNTIME_FILTER_SCAN_WAIT_TIME = "runtime_filter_scan_wait_time"; public static final String ENABLE_OPTIMIZER_TRACE_LOG = "enable_optimizer_trace_log"; public static final String JOIN_IMPLEMENTATION_MODE = "join_implementation_mode"; public static final String STATISTIC_COLLECT_PARALLEL = "statistic_collect_parallel"; @VariableMgr.VarAttr(name = ENABLE_PIPELINE, alias = ENABLE_PIPELINE_ENGINE, show = ENABLE_PIPELINE_ENGINE) private boolean enablePipelineEngine = true; @VariableMgr.VarAttr(name = RUNTIME_FILTER_SCAN_WAIT_TIME, flag = VariableMgr.INVISIBLE) private long runtimeFilterScanWaitTime = 20L; @VariableMgr.VarAttr(name = ENABLE_RESOURCE_GROUP) private boolean enableResourceGroup = false; @VariableMgr.VarAttr(name = ENABLE_TABLET_INTERNAL_PARALLEL) private boolean enableTabletInternalParallel = false; // max memory used on every backend. public static final long DEFAULT_EXEC_MEM_LIMIT = 2147483648L; @VariableMgr.VarAttr(name = EXEC_MEM_LIMIT) public long maxExecMemByte = DEFAULT_EXEC_MEM_LIMIT; @VariableMgr.VarAttr(name = LOAD_MEM_LIMIT) private long loadMemLimit = 0L; @VariableMgr.VarAttr(name = QUERY_MEM_LIMIT) private long queryMemLimit = 0L; @VariableMgr.VarAttr(name = ENABLE_SPILLING, flag = VariableMgr.INVISIBLE) public boolean enableSpilling = false; // query timeout in second. @VariableMgr.VarAttr(name = QUERY_TIMEOUT) private int queryTimeoutS = 300; // Execution of a query contains two phase. // 1. Deliver all the fragment instances to BEs. // 2. Pull data from BEs, after all the fragments are prepared and ready to execute in BEs. // queryDeliveryTimeoutS is the timeout of the first phase. @VariableMgr.VarAttr(name = QUERY_DELIVERY_TIMEOUT) private int queryDeliveryTimeoutS = 300; // query timeout in millisecond, currently nouse, only for compatible. @VariableMgr.VarAttr(name = MAX_EXECUTION_TIME) private long maxExecutionTime = 3000000; // if true, need report to coordinator when plan fragment execute successfully. @VariableMgr.VarAttr(name = IS_REPORT_SUCCESS) private boolean isReportSucc = false; // only for Aliyun DTS, useless. @Deprecated @VariableMgr.VarAttr(name = PROFILING, flag = VariableMgr.INVISIBLE) private boolean openProfile = false; // Default sqlMode is ONLY_FULL_GROUP_BY @VariableMgr.VarAttr(name = SQL_MODE_STORAGE_NAME, alias = SQL_MODE, show = SQL_MODE) private long sqlMode = 32L; // The specified resource group of this session @VariableMgr.VarAttr(name = RESOURCE_GROUP, flag = VariableMgr.SESSION_ONLY) private String resourceGroup = ""; // this is used to make mysql client happy @VariableMgr.VarAttr(name = AUTO_COMMIT) private boolean autoCommit = true; // this is used to make c3p0 library happy @VariableMgr.VarAttr(name = TX_ISOLATION) private String txIsolation = "REPEATABLE-READ"; // this is used to make c3p0 library happy @VariableMgr.VarAttr(name = CHARACTER_SET_CLIENT) private String charsetClient = "utf8"; @VariableMgr.VarAttr(name = CHARACTER_SET_CONNNECTION) private String charsetConnection = "utf8"; @VariableMgr.VarAttr(name = CHARACTER_SET_RESULTS) private String charsetResults = "utf8"; @VariableMgr.VarAttr(name = CHARACTER_SET_SERVER) private String charsetServer = "utf8"; @VariableMgr.VarAttr(name = COLLATION_CONNECTION) private String collationConnection = "utf8_general_ci"; @VariableMgr.VarAttr(name = COLLATION_DATABASE) private String collationDatabase = "utf8_general_ci"; @VariableMgr.VarAttr(name = COLLATION_SERVER) private String collationServer = "utf8_general_ci"; // this is used to make c3p0 library happy @VariableMgr.VarAttr(name = SQL_AUTO_IS_NULL) private boolean sqlAutoIsNull = false; public static final long DEFAULT_SELECT_LIMIT = 9223372036854775807L; @VariableMgr.VarAttr(name = SQL_SELECT_LIMIT) private long sqlSelectLimit = DEFAULT_SELECT_LIMIT; // this is used to make c3p0 library happy @VariableMgr.VarAttr(name = MAX_ALLOWED_PACKET) private int maxAllowedPacket = 1048576; @VariableMgr.VarAttr(name = AUTO_INCREMENT_INCREMENT) private int autoIncrementIncrement = 1; // this is used to make c3p0 library happy @VariableMgr.VarAttr(name = QUERY_CACHE_TYPE) private int queryCacheType = 0; // The number of seconds the server waits for activity on an interactive connection before closing it @VariableMgr.VarAttr(name = INTERACTIVE_TIMTOUT) private int interactiveTimeout = 3600; // The number of seconds the server waits for activity on a noninteractive connection before closing it. @VariableMgr.VarAttr(name = WAIT_TIMEOUT) private int waitTimeout = 28800; // The number of seconds to wait for a block to be written to a connection before aborting the write @VariableMgr.VarAttr(name = NET_WRITE_TIMEOUT) private int netWriteTimeout = 60; // The number of seconds to wait for a block to be written to a connection before aborting the write @VariableMgr.VarAttr(name = NET_READ_TIMEOUT) private int netReadTimeout = 60; // The current time zone @VariableMgr.VarAttr(name = TIME_ZONE) private String timeZone = TimeUtils.getSystemTimeZone().getID(); @VariableMgr.VarAttr(name = PARALLEL_EXCHANGE_INSTANCE_NUM) private int exchangeInstanceParallel = -1; @VariableMgr.VarAttr(name = SQL_SAFE_UPDATES) private int sqlSafeUpdates = 0; // only @VariableMgr.VarAttr(name = NET_BUFFER_LENGTH, flag = VariableMgr.READ_ONLY) private int netBufferLength = 16384; // if true, need report to coordinator when plan fragment execute successfully. @Deprecated @VariableMgr.VarAttr(name = CODEGEN_LEVEL, flag = VariableMgr.INVISIBLE) private int codegenLevel = 0; @VariableMgr.VarAttr(name = BATCH_SIZE, flag = VariableMgr.INVISIBLE) private int batchSize = 0; @VariableMgr.VarAttr(name = CHUNK_SIZE, flag = VariableMgr.INVISIBLE) private int chunkSize = 4096; public static final int PIPELINE_BATCH_SIZE = 4096; @VariableMgr.VarAttr(name = DISABLE_STREAMING_PREAGGREGATIONS) private boolean disableStreamPreaggregations = false; @VariableMgr.VarAttr(name = STREAMING_PREAGGREGATION_MODE) private String streamingPreaggregationMode = "auto"; // auto, force_streaming, force_preaggregation @VariableMgr.VarAttr(name = DISABLE_COLOCATE_JOIN) private boolean disableColocateJoin = false; @VariableMgr.VarAttr(name = DISABLE_BUCKET_JOIN, flag = VariableMgr.INVISIBLE) private boolean disableBucketJoin = false; @VariableMgr.VarAttr(name = CBO_USE_CORRELATED_JOIN_ESTIMATE) private boolean useCorrelatedJoinEstimate = true; @VariableMgr.VarAttr(name = CBO_USE_NTH_EXEC_PLAN, flag = VariableMgr.INVISIBLE) private int useNthExecPlan = 0; @VarAttr(name = CBO_CTE_REUSE) private boolean cboCteReuse = false; @VarAttr(name = CBO_CTE_REUSE_RATE, flag = VariableMgr.INVISIBLE) private double cboCTERuseRatio = 1.2; @VarAttr(name = ENABLE_SQL_DIGEST, flag = VariableMgr.INVISIBLE) private boolean enableSQLDigest = false; /* * the parallel exec instance num for one Fragment in one BE * 1 means disable this feature */ @VariableMgr.VarAttr(name = PARALLEL_FRAGMENT_EXEC_INSTANCE_NUM) private int parallelExecInstanceNum = 1; @VariableMgr.VarAttr(name = PIPELINE_DOP) private int pipelineDop = 0; @VariableMgr.VarAttr(name = PIPELINE_PROFILE_LEVEL) private int pipelineProfileLevel = 1; @VariableMgr.VarAttr(name = WORKGROUP_ID, flag = VariableMgr.INVISIBLE) private int workgroupId = 0; @VariableMgr.VarAttr(name = ENABLE_INSERT_STRICT) private boolean enableInsertStrict = true; @VariableMgr.VarAttr(name = FORWARD_TO_MASTER) private boolean forwardToMaster = false; // compatible with some mysql client connect, say DataGrip of JetBrains @VariableMgr.VarAttr(name = EVENT_SCHEDULER) private String eventScheduler = "OFF"; @VariableMgr.VarAttr(name = STORAGE_ENGINE) private String storageEngine = "olap"; @VariableMgr.VarAttr(name = DIV_PRECISION_INCREMENT) private int divPrecisionIncrement = 4; // -1 means unset, BE will use its config value @VariableMgr.VarAttr(name = MAX_SCAN_KEY_NUM) private int maxScanKeyNum = -1; @VariableMgr.VarAttr(name = MAX_PUSHDOWN_CONDITIONS_PER_COLUMN) private int maxPushdownConditionsPerColumn = -1; @VariableMgr.VarAttr(name = HASH_JOIN_PUSH_DOWN_RIGHT_TABLE) private boolean hashJoinPushDownRightTable = true; @VariableMgr.VarAttr(name = DISABLE_JOIN_REORDER) private boolean disableJoinReorder = false; @VariableMgr.VarAttr(name = ENABLE_PREDICATE_REORDER) private boolean enablePredicateReorder = false; @VariableMgr.VarAttr(name = ENABLE_FILTER_UNUSED_COLUMNS_IN_SCAN_STAGE) private boolean enableFilterUnusedColumnsInScanStage = false; @VariableMgr.VarAttr(name = CBO_MAX_REORDER_NODE_USE_EXHAUSTIVE) private int cboMaxReorderNodeUseExhaustive = 4; @VariableMgr.VarAttr(name = CBO_MAX_REORDER_NODE, flag = VariableMgr.INVISIBLE) private int cboMaxReorderNode = 50; @VariableMgr.VarAttr(name = CBO_ENABLE_DP_JOIN_REORDER, flag = VariableMgr.INVISIBLE) private boolean cboEnableDPJoinReorder = true; @VariableMgr.VarAttr(name = CBO_MAX_REORDER_NODE_USE_DP) private long cboMaxReorderNodeUseDP = 10; @VariableMgr.VarAttr(name = CBO_ENABLE_GREEDY_JOIN_REORDER, flag = VariableMgr.INVISIBLE) private boolean cboEnableGreedyJoinReorder = true; @VariableMgr.VarAttr(name = CBO_ENABLE_REPLICATED_JOIN, flag = VariableMgr.INVISIBLE) private boolean enableReplicationJoin = true; @VariableMgr.VarAttr(name = TRANSACTION_VISIBLE_WAIT_TIMEOUT) private long transactionVisibleWaitTimeout = 10; // only for Aliyun DTS, useless. @VariableMgr.VarAttr(name = FOREIGN_KEY_CHECKS) private boolean foreignKeyChecks = true; @VariableMgr.VarAttr(name = FORCE_SCHEDULE_LOCAL) private boolean forceScheduleLocal = false; @VariableMgr.VarAttr(name = BROADCAST_ROW_LIMIT) private long broadcastRowCountLimit = 15000000; @VariableMgr.VarAttr(name = NEW_PLANNER_OPTIMIZER_TIMEOUT) private long optimizerExecuteTimeout = 3000; @VariableMgr.VarAttr(name = ENABLE_QUERY_DUMP) private boolean enableQueryDump = false; @VariableMgr.VarAttr(name = CBO_ENABLE_LOW_CARDINALITY_OPTIMIZE) private boolean enableLowCardinalityOptimize = true; // value should be 0~4 // 0 represents automatic selection, and 1, 2, 3, and 4 represent forced selection of AGG of // corresponding stages respectively. However, stages 3 and 4 can only be generated in // single-column distinct scenarios @VariableMgr.VarAttr(name = NEW_PLANER_AGG_STAGE) private int newPlannerAggStage = 0; @VariableMgr.VarAttr(name = TRANSMISSION_COMPRESSION_TYPE) private String transmissionCompressionType = "LZ4"; @VariableMgr.VarAttr(name = RUNTIME_JOIN_FILTER_PUSH_DOWN_LIMIT) private long runtimeJoinFilterPushDownLimit = 1024000; @VariableMgr.VarAttr(name = ENABLE_GLOBAL_RUNTIME_FILTER) private boolean enableGlobalRuntimeFilter = true; @VariableMgr.VarAttr(name = GLOBAL_RUNTIME_FILTER_BUILD_MAX_SIZE, flag = VariableMgr.INVISIBLE) private long globalRuntimeFilterBuildMaxSize = 64 * 1024 * 1024; @VariableMgr.VarAttr(name = GLOBAL_RUNTIME_FILTER_PROBE_MIN_SIZE, flag = VariableMgr.INVISIBLE) private long globalRuntimeFilterProbeMinSize = 100 * 1024; @VariableMgr.VarAttr(name = GLOBAL_RUNTIME_FILTER_PROBE_MIN_SELECTIVITY, flag = VariableMgr.INVISIBLE) private float globalRuntimeFilterProbeMinSelectivity = 0.5f; //In order to be compatible with the logic of the old planner, //When the column name is the same as the alias name, //the alias will be used as the groupby column if set to true. @VariableMgr.VarAttr(name = ENABLE_GROUPBY_USE_OUTPUT_ALIAS) private boolean enableGroupbyUseOutputAlias = false; @VariableMgr.VarAttr(name = ENABLE_COLUMN_EXPR_PREDICATE) private boolean enableColumnExprPredicate = false; // Currently, if enable_exchange_pass_through is turned on. The performance has no improve on benchmark test, // and it will cause memory statistics problem of fragment instance, // It also which will introduce the problem of cross-thread memory allocate and release, // So i temporarily disable the enable_exchange_pass_through. // I will turn on int after all the above problems are solved. @VariableMgr.VarAttr(name = ENABLE_EXCHANGE_PASS_THROUGH_EXPIRE, alias = ENABLE_EXCHANGE_PASS_THROUGH, show = ENABLE_EXCHANGE_PASS_THROUGH) private boolean enableExchangePassThrough = false; // The following variables are deprecated and invisible // // ----------------------------------------------------------------------------// @VariableMgr.VarAttr(name = ALLOW_DEFAULT_PARTITION, flag = VariableMgr.INVISIBLE) private boolean allowDefaultPartition = false; @VariableMgr.VarAttr(name = "enable_cbo", flag = VariableMgr.INVISIBLE) @Deprecated private boolean enableCbo = true; @VariableMgr.VarAttr(name = "enable_vectorized_engine", alias = "vectorized_engine_enable", flag = VariableMgr.INVISIBLE) @Deprecated private boolean vectorizedEngineEnable = true; @VariableMgr.VarAttr(name = "enable_vectorized_insert", alias = "vectorized_insert_enable", flag = VariableMgr.INVISIBLE) @Deprecated private boolean vectorizedInsertEnable = true; @VariableMgr.VarAttr(name = "prefer_join_method", flag = VariableMgr.INVISIBLE) @Deprecated private String preferJoinMethod = "broadcast"; @VariableMgr.VarAttr(name = "rewrite_count_distinct_to_bitmap_hll", flag = VariableMgr.INVISIBLE) @Deprecated private boolean rewriteCountDistinct = true; @VariableMgr.VarAttr(name = SINGLE_NODE_EXEC_PLAN, flag = VariableMgr.INVISIBLE) private boolean singleNodeExecPlan = false; @VariableMgr.VarAttr(name = ENABLE_HIVE_COLUMN_STATS) private boolean enableHiveColumnStats = true; @VariableMgr.VarAttr(name = JOIN_IMPLEMENTATION_MODE) private String joinImplementationMode = "hash"; // auto, merge, hash @VariableMgr.VarAttr(name = ENABLE_OPTIMIZER_TRACE_LOG, flag = VariableMgr.INVISIBLE) private boolean enableOptimizerTraceLog = false; @VarAttr(name = STATISTIC_COLLECT_PARALLEL) private int statisticCollectParallelism = 1; public int getStatisticCollectParallelism() { return statisticCollectParallelism; } public void setStatisticCollectParallelism(int statisticCollectParallelism) { this.statisticCollectParallelism = statisticCollectParallelism; } public long getRuntimeFilterScanWaitTime() { return runtimeFilterScanWaitTime; } public boolean enableHiveColumnStats() { return enableHiveColumnStats; } public long getMaxExecMemByte() { return maxExecMemByte; } public long getLoadMemLimit() { return loadMemLimit; } public int getQueryTimeoutS() { return queryTimeoutS; } public boolean isReportSucc() { return isReportSucc; } public void setReportSuccess(boolean isReportSuccess) { this.isReportSucc = isReportSuccess; } public int getWaitTimeoutS() { return waitTimeout; } public long getSqlMode() { return sqlMode; } public void setSqlMode(long sqlMode) { this.sqlMode = sqlMode; } public String getCharsetClient() { return charsetClient; } public String getCharsetConnection() { return charsetConnection; } public String getCharsetResults() { return charsetResults; } public String getCollationDatabase() { return collationDatabase; } public String getCollationServer() { return collationServer; } public long getSqlSelectLimit() { if (sqlSelectLimit < 0) { return DEFAULT_SELECT_LIMIT; } return sqlSelectLimit; } public void setSqlSelectLimit(long limit) { if (limit < 0) { return; } this.sqlSelectLimit = limit; } public String getTimeZone() { return timeZone; } public void setTimeZone(String timeZone) { this.timeZone = timeZone; } public void setMaxExecMemByte(long maxExecMemByte) { if (maxExecMemByte < MIN_EXEC_MEM_LIMIT) { this.maxExecMemByte = MIN_EXEC_MEM_LIMIT; } else { this.maxExecMemByte = maxExecMemByte; } } public void setLoadMemLimit(long loadMemLimit) { this.loadMemLimit = loadMemLimit; } public void setQueryTimeoutS(int queryTimeoutS) { this.queryTimeoutS = queryTimeoutS; } public String getResourceGroup() { return resourceGroup; } public void setResourceGroup(String resourceGroup) { this.resourceGroup = resourceGroup; } public boolean isDisableColocateJoin() { return disableColocateJoin; } public int getParallelExecInstanceNum() { return parallelExecInstanceNum; } // when pipeline engine is enabled // in case of pipeline_dop > 0: return pipeline_dop * parallelExecInstanceNum; // in case of pipeline_dop <= 0 and avgNumCores < 2: return 1; // in case of pipeline_dop <= 0 and avgNumCores >=2; return avgNumCores/2; public int getDegreeOfParallelism() { if (enablePipelineEngine) { if (pipelineDop > 0) { return pipelineDop * parallelExecInstanceNum; } return BackendCoreStat.getDefaultDOP(); } else { return parallelExecInstanceNum; } } public void setParallelExecInstanceNum(int parallelExecInstanceNum) { this.parallelExecInstanceNum = parallelExecInstanceNum; } public int getExchangeInstanceParallel() { return exchangeInstanceParallel; } public boolean getEnableInsertStrict() { return enableInsertStrict; } public void setEnableInsertStrict(boolean enableInsertStrict) { this.enableInsertStrict = enableInsertStrict; } public boolean getForwardToMaster() { return forwardToMaster; } public void setMaxScanKeyNum(int maxScanKeyNum) { this.maxScanKeyNum = maxScanKeyNum; } public void setMaxPushdownConditionsPerColumn(int maxPushdownConditionsPerColumn) { this.maxPushdownConditionsPerColumn = maxPushdownConditionsPerColumn; } public boolean isHashJoinPushDownRightTable() { return this.hashJoinPushDownRightTable; } public String getStreamingPreaggregationMode() { return streamingPreaggregationMode; } public boolean isDisableJoinReorder() { return disableJoinReorder; } public void disableJoinReorder() { this.disableJoinReorder = true; } public void enableJoinReorder() { this.disableJoinReorder = false; } public boolean isEnablePredicateReorder() { return enablePredicateReorder; } public void disablePredicateReorder() { this.enablePredicateReorder = false; } public void enablePredicateReorder() { this.enablePredicateReorder = true; } public boolean isAbleFilterUnusedColumnsInScanStage() { return enableFilterUnusedColumnsInScanStage; } public void disableTrimOnlyFilteredColumnsInScanStage() { this.enableFilterUnusedColumnsInScanStage = false; } public void enableTrimOnlyFilteredColumnsInScanStage() { this.enableFilterUnusedColumnsInScanStage = true; } public boolean isCboEnableDPJoinReorder() { return cboEnableDPJoinReorder; } public void disableDPJoinReorder() { this.cboEnableDPJoinReorder = false; } public void enableDPJoinReorder() { this.cboEnableDPJoinReorder = true; } public long getCboMaxReorderNodeUseDP() { return cboMaxReorderNodeUseDP; } public boolean isCboEnableGreedyJoinReorder() { return cboEnableGreedyJoinReorder; } public void disableGreedyJoinReorder() { this.cboEnableGreedyJoinReorder = false; } public void enableGreedyJoinReorder() { this.cboEnableGreedyJoinReorder = true; } public int getCboMaxReorderNode() { return cboMaxReorderNode; } public long getTransactionVisibleWaitTimeout() { return transactionVisibleWaitTimeout; } public boolean isForceScheduleLocal() { return forceScheduleLocal; } public int getCboMaxReorderNodeUseExhaustive() { return cboMaxReorderNodeUseExhaustive; } public int getNewPlannerAggStage() { return newPlannerAggStage; } public void setNewPlanerAggStage(int stage) { this.newPlannerAggStage = stage; } public void setMaxTransformReorderJoins(int maxReorderNodeUseExhaustive) { this.cboMaxReorderNodeUseExhaustive = maxReorderNodeUseExhaustive; } public long getBroadcastRowCountLimit() { return broadcastRowCountLimit; } public long getOptimizerExecuteTimeout() { return optimizerExecuteTimeout; } public void setOptimizerExecuteTimeout(long optimizerExecuteTimeout) { this.optimizerExecuteTimeout = optimizerExecuteTimeout; } public boolean getEnableGroupbyUseOutputAlias() { return enableGroupbyUseOutputAlias; } public void setEnableGroupbyUseOutputAlias(boolean enableGroupbyUseOutputAlias) { this.enableGroupbyUseOutputAlias = enableGroupbyUseOutputAlias; } public boolean getEnableQueryDump() { return enableQueryDump; } public boolean getEnableGlobalRuntimeFilter() { return enableGlobalRuntimeFilter; } public void setEnableGlobalRuntimeFilter(boolean value) { enableGlobalRuntimeFilter = value; } public long getGlobalRuntimeFilterBuildMaxSize() { return globalRuntimeFilterBuildMaxSize; } public long getGlobalRuntimeFilterProbeMinSize() { return globalRuntimeFilterProbeMinSize; } public float getGlobalRuntimeFilterProbeMinSelectivity() { return globalRuntimeFilterProbeMinSelectivity; } public boolean isEnablePipelineEngine() { return enablePipelineEngine; } public boolean isPipelineDopAdaptionEnabled() { return enablePipelineEngine && pipelineDop <= 0; } public void setEnablePipelineEngine(boolean enablePipelineEngine) { this.enablePipelineEngine = enablePipelineEngine; } public boolean isEnableResourceGroup() { return enableResourceGroup; } public void setEnableResourceGroup(boolean enableResourceGroup) { this.enableResourceGroup = enableResourceGroup; } public void setPipelineDop(int pipelineDop) { this.pipelineDop = pipelineDop; } public int getPipelineDop() { return this.pipelineDop; } public int getWorkGroupId() { return workgroupId; } public int getPipelineProfileLevel() { return pipelineProfileLevel; } public void setPipelineProfileLevel(int pipelineProfileLevel) { this.pipelineProfileLevel = pipelineProfileLevel; } public boolean isEnableReplicationJoin() { return false; } public boolean isSetUseNthExecPlan() { return useNthExecPlan > 0; } public int getUseNthExecPlan() { return useNthExecPlan; } public void setUseNthExecPlan(int nthExecPlan) { this.useNthExecPlan = nthExecPlan; } public void setEnableReplicationJoin(boolean enableReplicationJoin) { this.enableReplicationJoin = enableReplicationJoin; } public boolean isUseCorrelatedJoinEstimate() { return useCorrelatedJoinEstimate; } public void setUseCorrelatedJoinEstimate(boolean useCorrelatedJoinEstimate) { this.useCorrelatedJoinEstimate = useCorrelatedJoinEstimate; } public boolean isEnableLowCardinalityOptimize() { return enableLowCardinalityOptimize; } public void setEnableLowCardinalityOptimize(boolean enableLowCardinalityOptimize) { this.enableLowCardinalityOptimize = enableLowCardinalityOptimize; } public boolean isEnableColumnExprPredicate() { return enableColumnExprPredicate; } public boolean isEnableExchangePassThrough() { return enableExchangePassThrough; } public boolean isAllowDefaultPartition() { return allowDefaultPartition; } public void setAllowDefaultPartition(boolean allowDefaultPartition) { this.allowDefaultPartition = allowDefaultPartition; } /** * check cbo_cte_reuse && enable_pipeline */ public boolean isCboCteReuse() { return cboCteReuse && enablePipelineEngine; } public void setCboCteReuse(boolean cboCteReuse) { this.cboCteReuse = cboCteReuse; } public void setSingleNodeExecPlan(boolean singleNodeExecPlan) { this.singleNodeExecPlan = singleNodeExecPlan; } public boolean isSingleNodeExecPlan() { return singleNodeExecPlan; } public double getCboCTERuseRatio() { return cboCTERuseRatio; } public void setCboCTERuseRatio(double cboCTERuseRatio) { this.cboCTERuseRatio = cboCTERuseRatio; } public boolean isEnableSQLDigest() { return enableSQLDigest; } public String getJoinImplementationMode() { return joinImplementationMode; } public void setJoinImplementationMode(String joinImplementationMode) { this.joinImplementationMode = joinImplementationMode; } public boolean isEnableOptimizerTraceLog() { return enableOptimizerTraceLog; } // Serialize to thrift object // used for rest api public TQueryOptions toThrift() { TQueryOptions tResult = new TQueryOptions(); tResult.setMem_limit(maxExecMemByte); if (queryMemLimit > 0) { tResult.setQuery_mem_limit(queryMemLimit); } tResult.setMin_reservation(0); tResult.setMax_reservation(maxExecMemByte); tResult.setInitial_reservation_total_claims(maxExecMemByte); tResult.setBuffer_pool_limit(maxExecMemByte); // Avoid integer overflow tResult.setQuery_timeout(Math.min(Integer.MAX_VALUE / 1000, queryTimeoutS)); tResult.setQuery_delivery_timeout(Math.min(Integer.MAX_VALUE / 1000, queryDeliveryTimeoutS)); tResult.setIs_report_success(isReportSucc); tResult.setCodegen_level(codegenLevel); tResult.setBatch_size(chunkSize); tResult.setDisable_stream_preaggregations(disableStreamPreaggregations); tResult.setLoad_mem_limit(loadMemLimit); if (maxScanKeyNum > -1) { tResult.setMax_scan_key_num(maxScanKeyNum); } if (maxPushdownConditionsPerColumn > -1) { tResult.setMax_pushdown_conditions_per_column(maxPushdownConditionsPerColumn); } tResult.setEnable_spilling(enableSpilling); // Compression Type TCompressionType compressionType = CompressionUtils.findTCompressionByName(transmissionCompressionType); if (compressionType != null) { tResult.setTransmission_compression_type(compressionType); } tResult.setRuntime_join_filter_pushdown_limit(runtimeJoinFilterPushDownLimit); final int global_runtime_filter_wait_timeout = 20; final int global_runtime_filter_rpc_timeout = 400; tResult.setRuntime_filter_wait_timeout_ms(global_runtime_filter_wait_timeout); tResult.setRuntime_filter_send_timeout_ms(global_runtime_filter_rpc_timeout); tResult.setRuntime_filter_scan_wait_time_ms(runtimeFilterScanWaitTime); tResult.setPipeline_dop(pipelineDop); switch (pipelineProfileLevel) { case 0: tResult.setPipeline_profile_level(TPipelineProfileLevel.CORE_METRICS); break; case 1: tResult.setPipeline_profile_level(TPipelineProfileLevel.ALL_METRICS); break; case 2: tResult.setPipeline_profile_level(TPipelineProfileLevel.DETAIL); break; default: tResult.setPipeline_profile_level(TPipelineProfileLevel.CORE_METRICS); break; } tResult.setEnable_tablet_internal_parallel(enableTabletInternalParallel); return tResult; } public String getJsonString() throws IOException { JSONObject root = new JSONObject(); try { for (Field field : SessionVariable.class.getDeclaredFields()) { VarAttr attr = field.getAnnotation(VarAttr.class); if (attr == null) { continue; } switch (field.getType().getSimpleName()) { case "boolean": case "int": case "long": case "float": case "double": case "String": root.put(attr.name(), field.get(this)); break; default: // Unsupported type variable. throw new IOException("invalid type: " + field.getType().getSimpleName()); } } } catch (Exception e) { throw new IOException("failed to write session variable: " + e.getMessage()); } return root.toString(); } @Override public void write(DataOutput out) throws IOException { Text.writeString(out, getJsonString()); } public void readFields(DataInput in) throws IOException { if (GlobalStateMgr.getCurrentStateJournalVersion() < FeMetaVersion.VERSION_67) { codegenLevel = in.readInt(); netBufferLength = in.readInt(); sqlSafeUpdates = in.readInt(); timeZone = Text.readString(in); netReadTimeout = in.readInt(); netWriteTimeout = in.readInt(); waitTimeout = in.readInt(); interactiveTimeout = in.readInt(); queryCacheType = in.readInt(); autoIncrementIncrement = in.readInt(); maxAllowedPacket = in.readInt(); sqlSelectLimit = in.readLong(); sqlAutoIsNull = in.readBoolean(); collationDatabase = Text.readString(in); collationConnection = Text.readString(in); charsetServer = Text.readString(in); charsetResults = Text.readString(in); charsetConnection = Text.readString(in); charsetClient = Text.readString(in); txIsolation = Text.readString(in); autoCommit = in.readBoolean(); // Deprecated variable, keep it just for compatibility // resourceGroup = Text.readString(in); Text.readString(in); if (GlobalStateMgr.getCurrentStateJournalVersion() >= FeMetaVersion.VERSION_65) { sqlMode = in.readLong(); } else { // read old version SQL mode Text.readString(in); sqlMode = 0L; } isReportSucc = in.readBoolean(); queryTimeoutS = in.readInt(); maxExecMemByte = in.readLong(); if (GlobalStateMgr.getCurrentStateJournalVersion() >= FeMetaVersion.VERSION_37) { collationServer = Text.readString(in); } if (GlobalStateMgr.getCurrentStateJournalVersion() >= FeMetaVersion.VERSION_38) { batchSize = in.readInt(); disableStreamPreaggregations = in.readBoolean(); parallelExecInstanceNum = in.readInt(); } if (GlobalStateMgr.getCurrentStateJournalVersion() >= FeMetaVersion.VERSION_62) { exchangeInstanceParallel = in.readInt(); } } else { readFromJson(in); } } private void readFromJson(DataInput in) throws IOException { String json = Text.readString(in); replayFromJson(json); } public void replayFromJson(String json) throws IOException { JSONObject root = new JSONObject(json); try { for (Field field : SessionVariable.class.getDeclaredFields()) { VarAttr attr = field.getAnnotation(VarAttr.class); if (attr == null) { continue; } if (!root.has(attr.name())) { continue; } // Do not restore the session_only variable if ((attr.flag() & VariableMgr.SESSION_ONLY) != 0) { continue; } switch (field.getType().getSimpleName()) { case "boolean": field.set(this, root.getBoolean(attr.name())); break; case "int": field.set(this, root.getInt(attr.name())); break; case "long": field.set(this, root.getLong(attr.name())); break; case "float": field.set(this, root.getFloat(attr.name())); break; case "double": field.set(this, root.getDouble(attr.name())); break; case "String": field.set(this, root.getString(attr.name())); break; default: // Unsupported type variable. throw new IOException("invalid type: " + field.getType().getSimpleName()); } } } catch (Exception e) { LOG.warn("failed to read session variable: {}", e.getMessage()); } } @Override public Object clone() throws CloneNotSupportedException { return super.clone(); } }
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.psi.impl.source.resolve.reference.impl; import com.intellij.codeInsight.completion.InsertHandler; import com.intellij.codeInsight.completion.InsertionContext; import com.intellij.codeInsight.completion.PrioritizedLookupElement; import com.intellij.codeInsight.lookup.LookupElement; import com.intellij.codeInsight.lookup.LookupElementBuilder; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Iconable; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.RecursionGuard; import com.intellij.openapi.util.RecursionManager; import com.intellij.psi.*; import com.intellij.psi.codeStyle.JavaCodeStyleManager; import com.intellij.psi.impl.JavaConstantExpressionEvaluator; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.util.*; import com.intellij.util.ArrayUtil; import com.intellij.util.ArrayUtilRt; import com.intellij.util.ObjectUtils; import com.intellij.util.PlatformIcons; import com.intellij.util.containers.ContainerUtil; import com.siyeh.ig.psiutils.DeclarationSearchUtils; import com.siyeh.ig.psiutils.ExpressionUtils; import com.siyeh.ig.psiutils.MethodCallUtils; import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.util.*; import java.util.function.Function; /** * @author Pavel.Dolgov */ public final class JavaReflectionReferenceUtil { // MethodHandle (Java 7) and VarHandle (Java 9) infrastructure public static final String JAVA_LANG_INVOKE_METHOD_HANDLES_LOOKUP = "java.lang.invoke.MethodHandles.Lookup"; public static final String JAVA_LANG_INVOKE_METHOD_TYPE = "java.lang.invoke.MethodType"; public static final String METHOD_TYPE = "methodType"; public static final String GENERIC_METHOD_TYPE = "genericMethodType"; public static final String FIND_VIRTUAL = "findVirtual"; public static final String FIND_STATIC = "findStatic"; public static final String FIND_SPECIAL = "findSpecial"; public static final String FIND_GETTER = "findGetter"; public static final String FIND_SETTER = "findSetter"; public static final String FIND_STATIC_GETTER = "findStaticGetter"; public static final String FIND_STATIC_SETTER = "findStaticSetter"; public static final String FIND_VAR_HANDLE = "findVarHandle"; public static final String FIND_STATIC_VAR_HANDLE = "findStaticVarHandle"; public static final String FIND_CONSTRUCTOR = "findConstructor"; public static final String FIND_CLASS = "findClass"; public static final String[] HANDLE_FACTORY_METHOD_NAMES = { FIND_VIRTUAL, FIND_STATIC, FIND_SPECIAL, FIND_GETTER, FIND_SETTER, FIND_STATIC_GETTER, FIND_STATIC_SETTER, FIND_VAR_HANDLE, FIND_STATIC_VAR_HANDLE}; // Classic reflection infrastructure public static final String GET_FIELD = "getField"; public static final String GET_DECLARED_FIELD = "getDeclaredField"; public static final String GET_METHOD = "getMethod"; public static final String GET_DECLARED_METHOD = "getDeclaredMethod"; public static final String GET_CONSTRUCTOR = "getConstructor"; public static final String GET_DECLARED_CONSTRUCTOR = "getDeclaredConstructor"; public static final String JAVA_LANG_CLASS_LOADER = "java.lang.ClassLoader"; public static final String FOR_NAME = "forName"; public static final String LOAD_CLASS = "loadClass"; public static final String GET_CLASS = "getClass"; public static final String NEW_INSTANCE = "newInstance"; public static final String TYPE = "TYPE"; // Atomic field updaters public static final String NEW_UPDATER = "newUpdater"; public static final String ATOMIC_LONG_FIELD_UPDATER = "java.util.concurrent.atomic.AtomicLongFieldUpdater"; public static final String ATOMIC_INTEGER_FIELD_UPDATER = "java.util.concurrent.atomic.AtomicIntegerFieldUpdater"; public static final String ATOMIC_REFERENCE_FIELD_UPDATER = "java.util.concurrent.atomic.AtomicReferenceFieldUpdater"; private static final RecursionGuard<PsiElement> ourGuard = RecursionManager.createGuard("JavaLangClassMemberReference"); @Contract("null -> null") public static ReflectiveType getReflectiveType(@Nullable PsiExpression context) { context = PsiUtil.skipParenthesizedExprDown(context); if (context == null) { return null; } if (context instanceof PsiClassObjectAccessExpression) { final PsiTypeElement operand = ((PsiClassObjectAccessExpression)context).getOperand(); return ReflectiveType.create(operand.getType(), true); } if (context instanceof PsiMethodCallExpression) { final PsiMethodCallExpression methodCall = (PsiMethodCallExpression)context; final String methodReferenceName = methodCall.getMethodExpression().getReferenceName(); if (FOR_NAME.equals(methodReferenceName)) { final PsiMethod method = methodCall.resolveMethod(); if (method != null && isJavaLangClass(method.getContainingClass())) { final PsiExpression[] expressions = methodCall.getArgumentList().getExpressions(); if (expressions.length == 1) { final PsiExpression argument = findDefinition(PsiUtil.skipParenthesizedExprDown(expressions[0])); final String className = computeConstantExpression(argument, String.class); if (className != null) { return ReflectiveType.create(findClass(className, context), true); } } } } else if (GET_CLASS.equals(methodReferenceName) && methodCall.getArgumentList().isEmpty()) { final PsiMethod method = methodCall.resolveMethod(); if (method != null && isJavaLangObject(method.getContainingClass())) { final PsiExpression qualifier = PsiUtil.skipParenthesizedExprDown(methodCall.getMethodExpression().getQualifierExpression()); if (qualifier instanceof PsiReferenceExpression) { final PsiExpression definition = findVariableDefinition((PsiReferenceExpression)qualifier); if (definition != null) { return getClassInstanceType(definition); } } //TODO type of the qualifier may be a supertype of the actual value - need to compute the type of the actual value // otherwise getDeclaredField and getDeclaredMethod may work not reliably if (qualifier != null) { return getClassInstanceType(qualifier); } } } } if (context instanceof PsiReferenceExpression) { PsiReferenceExpression reference = (PsiReferenceExpression)context; final PsiElement resolved = reference.resolve(); if (resolved instanceof PsiVariable) { PsiVariable variable = (PsiVariable)resolved; if (isJavaLangClass(PsiTypesUtil.getPsiClass(variable.getType()))) { final PsiExpression definition = findVariableDefinition(reference, variable); if (definition != null) { ReflectiveType result = ourGuard.doPreventingRecursion(variable, false, () -> getReflectiveType(definition)); if (result != null) { return result; } } } } } final PsiType type = context.getType(); if (type instanceof PsiClassType) { final PsiClassType.ClassResolveResult resolveResult = ((PsiClassType)type).resolveGenerics(); final PsiClass resolvedElement = resolveResult.getElement(); if (!isJavaLangClass(resolvedElement)) return null; if (context instanceof PsiReferenceExpression && TYPE.equals(((PsiReferenceExpression)context).getReferenceName())) { final PsiElement resolved = ((PsiReferenceExpression)context).resolve(); if (resolved instanceof PsiField) { final PsiField field = (PsiField)resolved; if (field.hasModifierProperty(PsiModifier.FINAL) && field.hasModifierProperty(PsiModifier.STATIC)) { final PsiType[] classTypeArguments = ((PsiClassType)type).getParameters(); final PsiPrimitiveType unboxedType = classTypeArguments.length == 1 ? PsiPrimitiveType.getUnboxedType(classTypeArguments[0]) : null; if (unboxedType != null && field.getContainingClass() == PsiUtil.resolveClassInClassTypeOnly(classTypeArguments[0])) { return ReflectiveType.create(unboxedType, true); } } } } final PsiTypeParameter[] parameters = resolvedElement.getTypeParameters(); if (parameters.length == 1) { final PsiType typeArgument = resolveResult.getSubstitutor().substitute(parameters[0]); final PsiType erasure = TypeConversionUtil.erasure(typeArgument); final PsiClass argumentClass = PsiTypesUtil.getPsiClass(erasure); if (argumentClass != null && !isJavaLangObject(argumentClass)) { return ReflectiveType.create(argumentClass, false); } } } return null; } @Nullable private static ReflectiveType getClassInstanceType(@Nullable PsiExpression expression) { expression = PsiUtil.skipParenthesizedExprDown(expression); if (expression == null) { return null; } if (expression instanceof PsiMethodCallExpression) { final PsiMethodCallExpression methodCall = (PsiMethodCallExpression)expression; final String methodReferenceName = methodCall.getMethodExpression().getReferenceName(); if (NEW_INSTANCE.equals(methodReferenceName)) { final PsiMethod method = methodCall.resolveMethod(); if (method != null) { final PsiExpression[] arguments = methodCall.getArgumentList().getExpressions(); if (arguments.length == 0 && isClassWithName(method.getContainingClass(), CommonClassNames.JAVA_LANG_CLASS)) { final PsiExpression qualifier = methodCall.getMethodExpression().getQualifierExpression(); if (qualifier != null) { return ourGuard.doPreventingRecursion(qualifier, false, () -> getReflectiveType(qualifier)); } } else if (arguments.length > 1 && isClassWithName(method.getContainingClass(), CommonClassNames.JAVA_LANG_REFLECT_ARRAY)) { final PsiExpression typeExpression = arguments[0]; if (typeExpression != null) { final ReflectiveType itemType = ourGuard.doPreventingRecursion(typeExpression, false, () -> getReflectiveType(typeExpression)); return ReflectiveType.arrayOf(itemType); } } } } } return ReflectiveType.create(expression.getType(), false); } @Contract("null,_->null") @Nullable public static <T> T computeConstantExpression(@Nullable PsiExpression expression, @NotNull Class<T> expectedType) { expression = PsiUtil.skipParenthesizedExprDown(expression); final Object computed = JavaConstantExpressionEvaluator.computeConstantExpression(expression, false); return ObjectUtils.tryCast(computed, expectedType); } @Nullable public static ReflectiveClass getReflectiveClass(PsiExpression context) { final ReflectiveType reflectiveType = getReflectiveType(context); return reflectiveType != null ? reflectiveType.getReflectiveClass() : null; } @Nullable public static PsiExpression findDefinition(@Nullable PsiExpression expression) { int preventEndlessLoop = 5; while (expression instanceof PsiReferenceExpression) { if (--preventEndlessLoop == 0) return null; expression = findVariableDefinition((PsiReferenceExpression)expression); } return expression; } @Nullable private static PsiExpression findVariableDefinition(@NotNull PsiReferenceExpression referenceExpression) { final PsiElement resolved = referenceExpression.resolve(); return resolved instanceof PsiVariable ? findVariableDefinition(referenceExpression, (PsiVariable)resolved) : null; } @Nullable private static PsiExpression findVariableDefinition(@NotNull PsiReferenceExpression referenceExpression, @NotNull PsiVariable variable) { if (variable.hasModifierProperty(PsiModifier.FINAL)) { final PsiExpression initializer = variable.getInitializer(); if (initializer != null) { return initializer; } if (variable instanceof PsiField) { return findFinalFieldDefinition(referenceExpression, (PsiField)variable); } } return DeclarationSearchUtils.findDefinition(referenceExpression, variable); } @Nullable private static PsiExpression findFinalFieldDefinition(@NotNull PsiReferenceExpression referenceExpression, @NotNull PsiField field) { if (!field.hasModifierProperty(PsiModifier.FINAL)) return null; final PsiClass psiClass = ObjectUtils.tryCast(field.getParent(), PsiClass.class); if (psiClass != null) { final boolean isStatic = field.hasModifierProperty(PsiModifier.STATIC); final List<PsiClassInitializer> initializers = ContainerUtil.filter(psiClass.getInitializers(), initializer -> initializer.hasModifierProperty(PsiModifier.STATIC) == isStatic); for (PsiClassInitializer initializer : initializers) { final PsiExpression assignedExpression = getAssignedExpression(initializer, field); if (assignedExpression != null) { return assignedExpression; } } if (!isStatic) { final PsiMethod[] constructors = psiClass.getConstructors(); if (constructors.length == 1) { return getAssignedExpression(constructors[0], field); } for (PsiMethod constructor : constructors) { if (PsiTreeUtil.isAncestor(constructor, referenceExpression, true)) { return getAssignedExpression(constructor, field); } } } } return null; } @Nullable private static PsiExpression getAssignedExpression(@NotNull PsiMember maybeContainsAssignment, @NotNull PsiField field) { final PsiAssignmentExpression assignment = SyntaxTraverser.psiTraverser(maybeContainsAssignment) .filter(PsiAssignmentExpression.class) .find(expression -> ExpressionUtils.isReferenceTo(expression.getLExpression(), field)); return assignment != null ? assignment.getRExpression() : null; } private static PsiClass findClass(@NotNull String qualifiedName, @NotNull PsiElement context) { final Project project = context.getProject(); return JavaPsiFacade.getInstance(project).findClass(qualifiedName, GlobalSearchScope.allScope(project)); } @Contract("null -> false") static boolean isJavaLangClass(@Nullable PsiClass aClass) { return isClassWithName(aClass, CommonClassNames.JAVA_LANG_CLASS); } @Contract("null -> false") static boolean isJavaLangObject(@Nullable PsiClass aClass) { return isClassWithName(aClass, CommonClassNames.JAVA_LANG_OBJECT); } @Contract("null, _ -> false") public static boolean isClassWithName(@Nullable PsiClass aClass, @NotNull String name) { return aClass != null && name.equals(aClass.getQualifiedName()); } @Contract("null -> false") static boolean isRegularMethod(@Nullable PsiMethod method) { return method != null && !method.isConstructor(); } static boolean isPublic(@NotNull PsiMember member) { return member.hasModifierProperty(PsiModifier.PUBLIC); } static boolean isAtomicallyUpdateable(@NotNull PsiField field) { if (field.hasModifierProperty(PsiModifier.STATIC) || !field.hasModifierProperty(PsiModifier.VOLATILE)) { return false; } final PsiType type = field.getType(); return !(type instanceof PsiPrimitiveType) || PsiType.INT.equals(type) || PsiType.LONG.equals(type); } @Nullable static String getParameterTypesText(@NotNull PsiMethod method) { final StringJoiner joiner = new StringJoiner(", "); for (PsiParameter parameter : method.getParameterList().getParameters()) { final String typeText = getTypeText(parameter.getType()); joiner.add(typeText + ".class"); } return joiner.toString(); } static void shortenArgumentsClassReferences(@NotNull InsertionContext context) { final PsiElement parameter = PsiUtilCore.getElementAtOffset(context.getFile(), context.getStartOffset()); final PsiExpressionList parameterList = PsiTreeUtil.getParentOfType(parameter, PsiExpressionList.class); if (parameterList != null && parameterList.getParent() instanceof PsiMethodCallExpression) { JavaCodeStyleManager.getInstance(context.getProject()).shortenClassReferences(parameterList); } } @NotNull static LookupElement withPriority(@NotNull LookupElement lookupElement, boolean hasPriority) { return hasPriority ? lookupElement : PrioritizedLookupElement.withPriority(lookupElement, -1); } @Nullable static LookupElement withPriority(@Nullable LookupElement lookupElement, int priority) { return priority == 0 || lookupElement == null ? lookupElement : PrioritizedLookupElement.withPriority(lookupElement, priority); } static int getMethodSortOrder(@NotNull PsiMethod method) { return isJavaLangObject(method.getContainingClass()) ? 1 : isPublic(method) ? -1 : 0; } @Nullable static String getMemberType(@Nullable PsiElement element) { final PsiMethodCallExpression methodCall = PsiTreeUtil.getParentOfType(element, PsiMethodCallExpression.class); return methodCall != null ? methodCall.getMethodExpression().getReferenceName() : null; } @Nullable static LookupElement lookupMethod(@NotNull PsiMethod method, @Nullable InsertHandler<LookupElement> insertHandler) { final ReflectiveSignature signature = getMethodSignature(method); return signature != null ? LookupElementBuilder.create(signature, method.getName()) .withIcon(signature.getIcon()) .withTailText(signature.getShortArgumentTypes()) .withInsertHandler(insertHandler) : null; } static void replaceText(@NotNull InsertionContext context, @NotNull String text) { final PsiElement newElement = PsiUtilCore.getElementAtOffset(context.getFile(), context.getStartOffset()); final PsiElement params = newElement.getParent().getParent(); final int end = params.getTextRange().getEndOffset() - 1; final int start = Math.min(newElement.getTextRange().getEndOffset(), end); context.getDocument().replaceString(start, end, text); context.commitDocument(); shortenArgumentsClassReferences(context); } @NotNull public static String getTypeText(@NotNull PsiType type) { final ReflectiveType reflectiveType = ReflectiveType.create(type, false); return reflectiveType.getQualifiedName(); } @Nullable public static String getTypeText(@Nullable PsiExpression argument) { final ReflectiveType reflectiveType = getReflectiveType(argument); return reflectiveType != null ? reflectiveType.getQualifiedName() : null; } @Contract("null -> null") @Nullable public static ReflectiveSignature getMethodSignature(@Nullable PsiMethod method) { if (method != null) { final List<String> types = new ArrayList<>(); final PsiType returnType = method.getReturnType(); types.add(getTypeText(returnType != null ? returnType : PsiType.VOID)); // null return type means it's a constructor for (PsiParameter parameter : method.getParameterList().getParameters()) { types.add(getTypeText(parameter.getType())); } final Icon icon = method.getIcon(Iconable.ICON_FLAG_VISIBILITY); return ReflectiveSignature.create(icon, types); } return null; } @NotNull public static String getMethodTypeExpressionText(@NotNull ReflectiveSignature signature) { final String types = signature.getText(true, type -> type + ".class"); return JAVA_LANG_INVOKE_METHOD_TYPE + "." + METHOD_TYPE + types; } public static boolean isCallToMethod(@NotNull PsiMethodCallExpression methodCall, @NotNull String className, @NotNull String methodName) { return MethodCallUtils.isCallToMethod(methodCall, className, null, methodName, (PsiType[])null); } /** * Tries to unwrap array and find its components * @param maybeArray an array to unwrap * @return list of unwrapped array components, some or all of them could be null if unknown (but the length is known); * returns null if nothing is known. */ @Nullable public static List<PsiExpression> getVarargs(@Nullable PsiExpression maybeArray) { if (ExpressionUtils.isNullLiteral(maybeArray)) { return Collections.emptyList(); } if (isVarargAsArray(maybeArray)) { final PsiExpression argumentsDefinition = findDefinition(maybeArray); if (argumentsDefinition instanceof PsiArrayInitializerExpression) { return Arrays.asList(((PsiArrayInitializerExpression)argumentsDefinition).getInitializers()); } if (argumentsDefinition instanceof PsiNewExpression) { final PsiArrayInitializerExpression arrayInitializer = ((PsiNewExpression)argumentsDefinition).getArrayInitializer(); if (arrayInitializer != null) { return Arrays.asList(arrayInitializer.getInitializers()); } final PsiExpression[] dimensions = ((PsiNewExpression)argumentsDefinition).getArrayDimensions(); if (dimensions.length == 1) { // new Object[length] or new Class<?>[length] final Integer itemCount = computeConstantExpression(findDefinition(dimensions[0]), Integer.class); if (itemCount != null && itemCount >= 0 && itemCount < 256) { return Collections.nCopies(itemCount, null); } } } } return null; } @Contract("null -> false") public static boolean isVarargAsArray(@Nullable PsiExpression maybeArray) { final PsiType type = maybeArray != null ? maybeArray.getType() : null; return type instanceof PsiArrayType && type.getArrayDimensions() == 1 && type.getDeepComponentType() instanceof PsiClassType; } /** * Take method's return type and parameter types * from arguments of MethodType.methodType(Class...) and MethodType.genericMethodType(int, boolean?) */ @Nullable public static ReflectiveSignature composeMethodSignature(@Nullable PsiExpression methodTypeExpression) { final PsiExpression typeDefinition = findDefinition(methodTypeExpression); if (typeDefinition instanceof PsiMethodCallExpression) { final PsiMethodCallExpression methodCallExpression = (PsiMethodCallExpression)typeDefinition; final String referenceName = methodCallExpression.getMethodExpression().getReferenceName(); Function<PsiExpression[], ReflectiveSignature> composer = null; if (METHOD_TYPE.equals(referenceName)) { composer = JavaReflectionReferenceUtil::composeMethodSignatureFromTypes; } else if (GENERIC_METHOD_TYPE.equals(referenceName)) { composer = JavaReflectionReferenceUtil::composeGenericMethodSignature; } if (composer != null) { final PsiMethod method = methodCallExpression.resolveMethod(); if (method != null) { final PsiClass psiClass = method.getContainingClass(); if (psiClass != null && JAVA_LANG_INVOKE_METHOD_TYPE.equals(psiClass.getQualifiedName())) { final PsiExpression[] arguments = methodCallExpression.getArgumentList().getExpressions(); return composer.apply(arguments); } } } } return null; } @Nullable private static ReflectiveSignature composeMethodSignatureFromTypes(PsiExpression @NotNull [] returnAndParameterTypes) { final List<String> typeTexts = ContainerUtil.map(returnAndParameterTypes, JavaReflectionReferenceUtil::getTypeText); return ReflectiveSignature.create(typeTexts); } @Nullable public static Pair.NonNull<Integer, Boolean> getGenericSignature(PsiExpression @NotNull [] genericSignatureShape) { if (genericSignatureShape.length == 0 || genericSignatureShape.length > 2) { return null; } final Integer objectArgCount = computeConstantExpression(genericSignatureShape[0], Integer.class); final Boolean finalArray = // there's an additional parameter which is an ellipsis or an array genericSignatureShape.length > 1 ? computeConstantExpression(genericSignatureShape[1], Boolean.class) : false; if (objectArgCount == null || objectArgCount < 0 || objectArgCount > 255) { return null; } if (finalArray == null || finalArray && objectArgCount > 254) { return null; } return Pair.createNonNull(objectArgCount, finalArray); } /** * All the types in the method signature are either unbounded type parameters or java.lang.Object (with possible vararg) */ @Nullable private static ReflectiveSignature composeGenericMethodSignature(PsiExpression @NotNull [] genericSignatureShape) { final Pair.NonNull<Integer, Boolean> signature = getGenericSignature(genericSignatureShape); if (signature == null) return null; final int objectArgCount = signature.getFirst(); final boolean finalArray = signature.getSecond(); final List<String> typeNames = new ArrayList<>(); typeNames.add(CommonClassNames.JAVA_LANG_OBJECT); // return type for (int i = 0; i < objectArgCount; i++) { typeNames.add(CommonClassNames.JAVA_LANG_OBJECT); } if (finalArray) { typeNames.add(CommonClassNames.JAVA_LANG_OBJECT + "[]"); } return ReflectiveSignature.create(typeNames); } public static final class ReflectiveType { final PsiType myType; final boolean myIsExact; private ReflectiveType(@NotNull PsiType erasedType, boolean isExact) { myType = erasedType; myIsExact = isExact; } @NotNull public String getQualifiedName() { return myType.getCanonicalText(); } @Override public String toString() { return myType.getCanonicalText(); } public boolean isEqualTo(@Nullable PsiType otherType) { return otherType != null && myType.equals(erasure(otherType)); } public boolean isAssignableFrom(@NotNull PsiType type) { return myType.isAssignableFrom(type); } public boolean isPrimitive() { return myType instanceof PsiPrimitiveType; } @NotNull public PsiType getType() { return myType; } public boolean isExact() { return myIsExact; } @Nullable public ReflectiveClass getReflectiveClass() { PsiClass psiClass = getPsiClass(); if (psiClass != null) { return new ReflectiveClass(psiClass, myIsExact); } return null; } @Nullable public ReflectiveType getArrayComponentType() { if (myType instanceof PsiArrayType) { PsiType componentType = ((PsiArrayType)myType).getComponentType(); return new ReflectiveType(componentType, myIsExact); } return null; } @Nullable public PsiClass getPsiClass() { return PsiTypesUtil.getPsiClass(myType); } @Contract("!null,_ -> !null; null,_ -> null") @Nullable public static ReflectiveType create(@Nullable PsiType originalType, boolean isExact) { if (originalType != null) { return new ReflectiveType(erasure(originalType), isExact); } return null; } @Contract("!null,_ -> !null; null,_ -> null") @Nullable public static ReflectiveType create(@Nullable PsiClass psiClass, boolean isExact) { if (psiClass != null) { final PsiElementFactory factory = JavaPsiFacade.getElementFactory(psiClass.getProject()); return new ReflectiveType(factory.createType(psiClass), isExact); } return null; } @Contract("!null -> !null; null -> null") @Nullable public static ReflectiveType arrayOf(@Nullable ReflectiveType itemType) { if (itemType != null) { return new ReflectiveType(itemType.myType.createArrayType(), itemType.myIsExact); } return null; } @NotNull private static PsiType erasure(@NotNull PsiType type) { final PsiType erasure = TypeConversionUtil.erasure(type); if (erasure instanceof PsiEllipsisType) { return ((PsiEllipsisType)erasure).toArrayType(); } return erasure; } } public static class ReflectiveClass { final PsiClass myPsiClass; final boolean myIsExact; public ReflectiveClass(@NotNull PsiClass psiClass, boolean isExact) { myPsiClass = psiClass; myIsExact = isExact; } @NotNull public PsiClass getPsiClass() { return myPsiClass; } public boolean isExact() { return myIsExact || myPsiClass.hasModifierProperty(PsiModifier.FINAL); } } public static final class ReflectiveSignature implements Comparable<ReflectiveSignature> { public static final ReflectiveSignature NO_ARGUMENT_CONSTRUCTOR_SIGNATURE = new ReflectiveSignature(null, PsiKeyword.VOID, ArrayUtilRt.EMPTY_STRING_ARRAY); private final Icon myIcon; @NotNull private final String myReturnType; private final String @NotNull [] myArgumentTypes; @Nullable public static ReflectiveSignature create(@NotNull List<String> typeTexts) { return create(null, typeTexts); } @Nullable public static ReflectiveSignature create(@Nullable Icon icon, @NotNull List<String> typeTexts) { if (!typeTexts.isEmpty() && !typeTexts.contains(null)) { final String[] argumentTypes = ArrayUtilRt.toStringArray(typeTexts.subList(1, typeTexts.size())); return new ReflectiveSignature(icon, typeTexts.get(0), argumentTypes); } return null; } private ReflectiveSignature(@Nullable Icon icon, @NotNull String returnType, String @NotNull [] argumentTypes) { myIcon = icon; myReturnType = returnType; myArgumentTypes = argumentTypes; } public String getText(boolean withReturnType, @NotNull Function<? super String, String> transformation) { return getText(withReturnType, true, transformation); } public String getText(boolean withReturnType, boolean withParentheses, @NotNull Function<? super String, String> transformation) { final StringJoiner joiner = new StringJoiner(", ", withParentheses ? "(" : "", withParentheses ? ")" : ""); if (withReturnType) { joiner.add(transformation.apply(myReturnType)); } for (String argumentType : myArgumentTypes) { joiner.add(transformation.apply(argumentType)); } return joiner.toString(); } @NotNull public String getShortReturnType() { return PsiNameHelper.getShortClassName(myReturnType); } @NotNull public String getShortArgumentTypes() { return getText(false, PsiNameHelper::getShortClassName); } @Nullable public Icon getIcon() { return myIcon != null ? myIcon : PlatformIcons.METHOD_ICON; } @Override public int compareTo(@NotNull ReflectiveSignature other) { int c = myArgumentTypes.length - other.myArgumentTypes.length; if (c != 0) return c; c = ArrayUtil.lexicographicCompare(myArgumentTypes, other.myArgumentTypes); if (c != 0) return c; return myReturnType.compareTo(other.myReturnType); } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof ReflectiveSignature)) return false; final ReflectiveSignature other = (ReflectiveSignature)o; return Objects.equals(myReturnType, other.myReturnType) && Arrays.equals(myArgumentTypes, other.myArgumentTypes); } @Override public int hashCode() { return Objects.hash(myReturnType, myArgumentTypes); } @Override public String toString() { return myReturnType + " " + Arrays.toString(myArgumentTypes); } } }
/* * Copyright 2017 Zhihu 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.zhongjh.albumcamerarecorder.album.ui.mediaselection.adapter; import android.content.Context; import android.content.res.TypedArray; import android.database.Cursor; import android.graphics.drawable.Drawable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.GridLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.zhongjh.albumcamerarecorder.R; import com.zhongjh.albumcamerarecorder.album.base.BaseRecyclerViewCursorAdapter; import com.zhongjh.albumcamerarecorder.album.entity.Album; import com.zhongjh.albumcamerarecorder.album.model.SelectedItemCollection; import com.zhongjh.albumcamerarecorder.album.widget.CheckView; import com.zhongjh.albumcamerarecorder.album.widget.MediaGrid; import com.zhongjh.albumcamerarecorder.settings.AlbumSpec; import com.zhongjh.common.entity.IncapableCause; import com.zhongjh.common.entity.MultiMedia; /** * 相册适配器 * @author zhongjh */ public class AlbumMediaAdapter extends BaseRecyclerViewCursorAdapter<RecyclerView.ViewHolder> implements MediaGrid.OnMediaGridClickListener { private static final int VIEW_TYPE_MEDIA = 0x02; private final SelectedItemCollection mSelectedCollection; private final Drawable mPlaceholder; private final AlbumSpec mAlbumSpec; private CheckStateListener mCheckStateListener; private OnMediaClickListener mOnMediaClickListener; private final RecyclerView mRecyclerView; private int mImageResize; public AlbumMediaAdapter(Context context, SelectedItemCollection selectedCollection, RecyclerView recyclerView) { super(null); mAlbumSpec = AlbumSpec.INSTANCE; mSelectedCollection = selectedCollection; TypedArray ta = context.getTheme().obtainStyledAttributes(new int[]{R.attr.item_placeholder}); mPlaceholder = ta.getDrawable(0); ta.recycle(); mRecyclerView = recyclerView; } @NonNull @Override public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { // 相片的item return new MediaViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.media_grid_item_zjh, parent, false)); } @Override protected void onBindViewHolder(final RecyclerView.ViewHolder holder, Cursor cursor) { // 相片的item MediaViewHolder mediaViewHolder = (MediaViewHolder) holder; final MultiMedia item = MultiMedia.valueOf(cursor); // 传递相关的值 mediaViewHolder.mMediaGrid.preBindMedia(new MediaGrid.PreBindInfo( getImageResize(mediaViewHolder.mMediaGrid.getContext()), mPlaceholder, mAlbumSpec.getCountable(), holder )); mediaViewHolder.mMediaGrid.bindMedia(item); mediaViewHolder.mMediaGrid.setOnMediaGridClickListener(this); setCheckStatus(item, mediaViewHolder.mMediaGrid); } /** * 设置当前选择状态 * * @param item 数据 * @param mediaGrid holder */ private void setCheckStatus(MultiMedia item, MediaGrid mediaGrid) { // 是否多选时,显示数字 if (mAlbumSpec.getCountable()) { int checkedNum = mSelectedCollection.checkedNumOf(item); if (checkedNum > 0) { // 设置启用,设置数量 mediaGrid.setCheckEnabled(true); mediaGrid.setCheckedNum(checkedNum); } else { // 判断当前数量 和 当前选择最大数量比较 是否相等,相等就设置为false,否则true if (mSelectedCollection.maxSelectableReached()) { mediaGrid.setCheckEnabled(false); mediaGrid.setCheckedNum(CheckView.UNCHECKED); } else { mediaGrid.setCheckEnabled(true); mediaGrid.setCheckedNum(checkedNum); } } } else { // 不显示字的情况 boolean selected = mSelectedCollection.isSelected(item); // 如果被选中了,就设置选择 if (selected) { mediaGrid.setCheckEnabled(true); mediaGrid.setChecked(true); } else { // 判断当前数量 和 当前选择最大数量比较 是否相等,相等就设置为false,否则true if (mSelectedCollection.maxSelectableReached()) { // 设置为false mediaGrid.setCheckEnabled(false); mediaGrid.setChecked(false); } else { // 设置为true mediaGrid.setCheckEnabled(true); mediaGrid.setChecked(false); } } } } @Override public void onThumbnailClicked(ImageView thumbnail, MultiMedia item, RecyclerView.ViewHolder holder) { if (mOnMediaClickListener != null) { mOnMediaClickListener.onMediaClick(null, item, holder.getBindingAdapterPosition()); } } @Override public void onCheckViewClicked(CheckView checkView, MultiMedia item, RecyclerView.ViewHolder holder) { // 是否多选模式,显示数字 if (mAlbumSpec.getCountable()) { // 获取当前选择的第几个 int checkedNum = mSelectedCollection.checkedNumOf(item); if (checkedNum == CheckView.UNCHECKED) { // 如果当前数据是未选状态 if (assertAddSelection(holder.itemView.getContext(), item)) { // 添加选择了当前数据 mSelectedCollection.add(item); // 刷新数据源 notifyCheckStateChanged(); } } else { // 删除当前选择 mSelectedCollection.remove(item); // 刷新数据 notifyCheckStateChanged(); } } else { // 不是多选模式 if (mSelectedCollection.isSelected(item)) { // 如果当前已经被选中,再次选择就是取消了 mSelectedCollection.remove(item); // 刷新数据源 notifyCheckStateChanged(); } else { if (assertAddSelection(holder.itemView.getContext(), item)) { mSelectedCollection.add(item); notifyCheckStateChanged(); } } } } /** * 刷新数据 */ private void notifyCheckStateChanged() { notifyDataSetChanged(); if (mCheckStateListener != null) { mCheckStateListener.onUpdate(); } } /** * 返回类型 * * @param position 索引 * @param cursor 数据源 */ @Override public int getItemViewType(int position, Cursor cursor) { return VIEW_TYPE_MEDIA; } /** * 验证当前item是否满足可以被选中的条件 * * @param context 上下文 * @param item 数据源 */ private boolean assertAddSelection(Context context, MultiMedia item) { IncapableCause cause = mSelectedCollection.isAcceptable(item); IncapableCause.handleCause(context, cause); return cause == null; } /** * 注册选择事件 * * @param listener 事件 */ public void registerCheckStateListener(CheckStateListener listener) { mCheckStateListener = listener; } /** * 注销选择事件 */ public void unregisterCheckStateListener() { mCheckStateListener = null; } /** * 注册图片点击事件 * * @param listener 事件 */ public void registerOnMediaClickListener(OnMediaClickListener listener) { mOnMediaClickListener = listener; } /** * 注销图片点击事件 */ public void unregisterOnMediaClickListener() { mOnMediaClickListener = null; } /** * 刷新所能看到的选择 */ public void refreshSelection() { GridLayoutManager layoutManager = (GridLayoutManager) mRecyclerView.getLayoutManager(); // 获取当前能看到的第一个,和最后一个 int first = 0; if (layoutManager != null) { first = layoutManager.findFirstVisibleItemPosition(); } int last = 0; if (layoutManager != null) { last = layoutManager.findLastVisibleItemPosition(); } if (first == -1 || last == -1) { // 如果是-1就直接返回 return; } // 获取数据源 Cursor cursor = getCursor(); for (int i = first; i <= last; i++) { RecyclerView.ViewHolder holder = mRecyclerView.findViewHolderForAdapterPosition(first); if (holder instanceof MediaViewHolder) { if (cursor.moveToPosition(i)) { setCheckStatus(MultiMedia.valueOf(cursor), ((MediaViewHolder) holder).mMediaGrid); } } } } /** * 返回图片调整大小 * * @param context 上下文 * @return 列表的每个格子的宽度 * 缩放比例 */ private int getImageResize(Context context) { if (mImageResize == 0) { RecyclerView.LayoutManager lm = mRecyclerView.getLayoutManager(); int spanCount = 0; if (lm != null) { spanCount = ((GridLayoutManager) lm).getSpanCount(); } int screenWidth = context.getResources().getDisplayMetrics().widthPixels; int availableWidth = screenWidth - context.getResources().getDimensionPixelSize( R.dimen.z_media_grid_spacing) * (spanCount - 1); // 图片调整后的大小:获取列表的每个格子的宽度 mImageResize = availableWidth / spanCount; // 图片调整后的大小 * 缩放比例 mImageResize = (int) (mImageResize * mAlbumSpec.getThumbnailScale()); } return mImageResize; } public interface CheckStateListener { /** * 选择选项后更新事件 */ void onUpdate(); } public interface OnMediaClickListener { /** * 点击事件 * @param album 相册集合 * @param item 选项 * @param adapterPosition 索引 */ void onMediaClick(Album album, MultiMedia item, int adapterPosition); } private static class MediaViewHolder extends RecyclerView.ViewHolder { private final MediaGrid mMediaGrid; MediaViewHolder(View itemView) { super(itemView); mMediaGrid = (MediaGrid) itemView; } } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.flink.test.recovery; import akka.actor.ActorRef; import akka.actor.ActorSystem; import akka.actor.PoisonPill; import org.apache.commons.io.FileUtils; import org.apache.curator.test.TestingServer; import org.apache.flink.api.common.functions.RichFlatMapFunction; import org.apache.flink.api.common.state.ValueState; import org.apache.flink.api.common.state.ValueStateDescriptor; import org.apache.flink.api.common.typeinfo.TypeHint; import org.apache.flink.api.common.typeinfo.TypeInformation; import org.apache.flink.api.java.functions.KeySelector; import org.apache.flink.configuration.ConfigConstants; import org.apache.flink.configuration.Configuration; import org.apache.flink.configuration.CoreOptions; import org.apache.flink.configuration.HighAvailabilityOptions; import org.apache.flink.contrib.streaming.state.RocksDBStateBackend; import org.apache.flink.runtime.akka.AkkaUtils; import org.apache.flink.runtime.akka.ListeningBehaviour; import org.apache.flink.runtime.clusterframework.types.ResourceID; import org.apache.flink.runtime.highavailability.HighAvailabilityServices; import org.apache.flink.runtime.highavailability.HighAvailabilityServicesUtils; import org.apache.flink.runtime.instance.ActorGateway; import org.apache.flink.runtime.instance.AkkaActorGateway; import org.apache.flink.runtime.jobgraph.JobGraph; import org.apache.flink.runtime.jobgraph.JobStatus; import org.apache.flink.runtime.jobgraph.JobVertex; import org.apache.flink.runtime.leaderelection.TestingListener; import org.apache.flink.runtime.leaderretrieval.LeaderRetrievalService; import org.apache.flink.runtime.minicluster.LocalFlinkMiniCluster; import org.apache.flink.runtime.state.AbstractStateBackend; import org.apache.flink.runtime.state.CheckpointListener; import org.apache.flink.runtime.state.FunctionInitializationContext; import org.apache.flink.runtime.state.FunctionSnapshotContext; import org.apache.flink.runtime.state.filesystem.FsStateBackend; import org.apache.flink.runtime.taskmanager.TaskManager; import org.apache.flink.runtime.testingUtils.TestingUtils; import org.apache.flink.runtime.testtasks.BlockingNoOpInvokable; import org.apache.flink.runtime.testutils.CommonTestUtils; import org.apache.flink.runtime.testutils.JobManagerActorTestUtils; import org.apache.flink.runtime.testutils.JobManagerProcess; import org.apache.flink.runtime.testutils.ZooKeeperTestUtils; import org.apache.flink.runtime.zookeeper.ZooKeeperTestEnvironment; import org.apache.flink.streaming.api.checkpoint.CheckpointedFunction; import org.apache.flink.streaming.api.checkpoint.ListCheckpointed; import org.apache.flink.streaming.api.environment.CheckpointConfig; import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment; import org.apache.flink.streaming.api.functions.sink.SinkFunction; import org.apache.flink.streaming.api.functions.source.RichParallelSourceFunction; import org.apache.flink.testutils.junit.RetryOnFailure; import org.apache.flink.testutils.junit.RetryRule; import org.apache.flink.util.Collector; import org.apache.flink.util.TestLogger; import org.junit.AfterClass; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import scala.Option; import scala.Some; import scala.Tuple2; import scala.concurrent.duration.Deadline; import scala.concurrent.duration.FiniteDuration; import java.io.File; import java.io.IOException; import java.util.Collections; import java.util.List; import java.util.UUID; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLongArray; import java.util.concurrent.atomic.AtomicReference; import static org.apache.flink.runtime.messages.JobManagerMessages.SubmitJob; import static org.apache.flink.util.Preconditions.checkArgument; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertTrue; public class JobManagerHACheckpointRecoveryITCase extends TestLogger { @Rule public RetryRule retryRule = new RetryRule(); private final static ZooKeeperTestEnvironment ZooKeeper = new ZooKeeperTestEnvironment(1); private final static FiniteDuration TestTimeOut = new FiniteDuration(5, TimeUnit.MINUTES); private static final File FileStateBackendBasePath; static { try { FileStateBackendBasePath = CommonTestUtils.createTempDirectory(); } catch (IOException e) { throw new RuntimeException("Error in test setup. Could not create directory.", e); } } @AfterClass public static void tearDown() throws Exception { try { ZooKeeper.shutdown(); } catch (Exception ignored) { } try { if (FileStateBackendBasePath != null) { FileUtils.deleteDirectory(FileStateBackendBasePath); } } catch (IOException ignored) { } } @Before public void cleanUp() throws Exception { if (FileStateBackendBasePath != null && FileStateBackendBasePath.exists()) { FileUtils.cleanDirectory(FileStateBackendBasePath); } ZooKeeper.deleteAll(); } // --------------------------------------------------------------------------------------------- private static final int Parallelism = 8; private static CountDownLatch CompletedCheckpointsLatch = new CountDownLatch(4); private static CountDownLatch CompletedCheckpointsLatch2 = new CountDownLatch(6); private static AtomicLongArray RecoveredStates = new AtomicLongArray(Parallelism); private static CountDownLatch FinalCountLatch = new CountDownLatch(1); private static AtomicReference<Long> FinalCount = new AtomicReference<>(); private static long LastElement = -1; private static final int retainedCheckpoints = 2; /** * Tests that the JobManager logs failures during recovery properly. * * @see <a href="https://issues.apache.org/jira/browse/FLINK-3185">FLINK-3185</a> */ @Test @RetryOnFailure(times=1) public void testCheckpointRecoveryFailure() throws Exception { final Deadline testDeadline = TestTimeOut.fromNow(); final String zooKeeperQuorum = ZooKeeper.getConnectString(); final String fileStateBackendPath = FileStateBackendBasePath.getAbsoluteFile().toString(); Configuration config = ZooKeeperTestUtils.createZooKeeperHAConfig( zooKeeperQuorum, fileStateBackendPath); config.setInteger(ConfigConstants.LOCAL_NUMBER_JOB_MANAGER, 2); JobManagerProcess[] jobManagerProcess = new JobManagerProcess[2]; LeaderRetrievalService leaderRetrievalService = null; ActorSystem taskManagerSystem = null; ActorSystem testActorSystem = null; final HighAvailabilityServices highAvailabilityServices = HighAvailabilityServicesUtils.createHighAvailabilityServices( config, TestingUtils.defaultExecutor(), HighAvailabilityServicesUtils.AddressResolution.NO_ADDRESS_RESOLUTION); try { // Test actor system testActorSystem = AkkaUtils.createActorSystem(new Configuration(), new Some<>(new Tuple2<String, Object>("localhost", 0))); // The job managers jobManagerProcess[0] = new JobManagerProcess(0, config); jobManagerProcess[1] = new JobManagerProcess(1, config); jobManagerProcess[0].startProcess(); jobManagerProcess[1].startProcess(); // Leader listener TestingListener leaderListener = new TestingListener(); leaderRetrievalService = highAvailabilityServices.getJobManagerLeaderRetriever(HighAvailabilityServices.DEFAULT_JOB_ID); leaderRetrievalService.start(leaderListener); // The task manager taskManagerSystem = AkkaUtils.createActorSystem( config, Option.apply(new Tuple2<String, Object>("localhost", 0))); TaskManager.startTaskManagerComponentsAndActor( config, ResourceID.generate(), taskManagerSystem, highAvailabilityServices, "localhost", Option.<String>empty(), false, TaskManager.class); // Get the leader leaderListener.waitForNewLeader(testDeadline.timeLeft().toMillis()); String leaderAddress = leaderListener.getAddress(); UUID leaderId = leaderListener.getLeaderSessionID(); // Get the leader ref ActorRef leaderRef = AkkaUtils.getActorRef( leaderAddress, testActorSystem, testDeadline.timeLeft()); ActorGateway leader = new AkkaActorGateway(leaderRef, leaderId); // Who's the boss? JobManagerProcess leadingJobManagerProcess; JobManagerProcess nonLeadingJobManagerProcess; if (jobManagerProcess[0].getJobManagerAkkaURL(testDeadline.timeLeft()).equals(leaderListener.getAddress())) { leadingJobManagerProcess = jobManagerProcess[0]; nonLeadingJobManagerProcess = jobManagerProcess[1]; } else { leadingJobManagerProcess = jobManagerProcess[1]; nonLeadingJobManagerProcess = jobManagerProcess[0]; } // Blocking JobGraph JobVertex blockingVertex = new JobVertex("Blocking vertex"); blockingVertex.setInvokableClass(BlockingNoOpInvokable.class); JobGraph jobGraph = new JobGraph(blockingVertex); // Submit the job in detached mode leader.tell(new SubmitJob(jobGraph, ListeningBehaviour.DETACHED)); // Wait for the job to be running JobManagerActorTestUtils.waitForJobStatus( jobGraph.getJobID(), JobStatus.RUNNING, leader, testDeadline.timeLeft()); // Remove all files FileUtils.deleteDirectory(FileStateBackendBasePath); // Kill the leader leadingJobManagerProcess.destroy(); // Verify that the job manager logs the failed recovery. We can not // do more at this point. :( boolean success = false; while (testDeadline.hasTimeLeft()) { String output = nonLeadingJobManagerProcess.getProcessOutput(); if (output != null) { if (output.contains("Failed to recover job") && output.contains("java.io.FileNotFoundException")) { success = true; break; } } else { log.warn("No process output available."); } Thread.sleep(500); } assertTrue("Did not find expected output in logs.", success); } catch (Throwable t) { // Print early (in some situations the process logs get too big // for Travis and the root problem is not shown) t.printStackTrace(); // In case of an error, print the job manager process logs. if (jobManagerProcess[0] != null) { jobManagerProcess[0].printProcessLog(); } if (jobManagerProcess[1] != null) { jobManagerProcess[1].printProcessLog(); } throw t; } finally { if (jobManagerProcess[0] != null) { jobManagerProcess[0].destroy(); } if (jobManagerProcess[1] != null) { jobManagerProcess[1].destroy(); } if (leaderRetrievalService != null) { leaderRetrievalService.stop(); } if (taskManagerSystem != null) { taskManagerSystem.shutdown(); } if (testActorSystem != null) { testActorSystem.shutdown(); } highAvailabilityServices.closeAndCleanupAllData(); } } @Test public void testCheckpointedStreamingProgramIncrementalRocksDB() throws Exception { testCheckpointedStreamingProgram( new RocksDBStateBackend( new FsStateBackend(FileStateBackendBasePath.getAbsoluteFile().toURI(), 16), true)); } private void testCheckpointedStreamingProgram(AbstractStateBackend stateBackend) throws Exception { // Config final int checkpointingInterval = 100; final int sequenceEnd = 5000; final long expectedSum = Parallelism * sequenceEnd * (sequenceEnd + 1) / 2; final ActorSystem system = ActorSystem.create("Test", AkkaUtils.getDefaultAkkaConfig()); final TestingServer testingServer = new TestingServer(); final TemporaryFolder temporaryFolder = new TemporaryFolder(); temporaryFolder.create(); LocalFlinkMiniCluster miniCluster = null; final int numJMs = 2; final int numTMs = 4; final int numSlots = 8; try { Configuration config = new Configuration(); config.setInteger(CoreOptions.MAX_RETAINED_CHECKPOINTS, retainedCheckpoints); config.setInteger(ConfigConstants.LOCAL_NUMBER_JOB_MANAGER, numJMs); config.setInteger(ConfigConstants.LOCAL_NUMBER_TASK_MANAGER, numTMs); config.setInteger(ConfigConstants.TASK_MANAGER_NUM_TASK_SLOTS, numSlots); config.setString(CoreOptions.CHECKPOINTS_DIRECTORY, temporaryFolder.newFolder().toString()); String tmpFolderString = temporaryFolder.newFolder().toString(); config.setString(HighAvailabilityOptions.HA_STORAGE_PATH, tmpFolderString); config.setString(HighAvailabilityOptions.HA_ZOOKEEPER_QUORUM, testingServer.getConnectString()); config.setString(HighAvailabilityOptions.HA_MODE, "zookeeper"); miniCluster = new LocalFlinkMiniCluster(config, true); miniCluster.start(); ActorGateway jmGateway = miniCluster.getLeaderGateway(TestingUtils.TESTING_DURATION()); StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); env.setParallelism(Parallelism); env.enableCheckpointing(checkpointingInterval); env.getCheckpointConfig() .enableExternalizedCheckpoints(CheckpointConfig.ExternalizedCheckpointCleanup.RETAIN_ON_CANCELLATION); //TODO parameterize env.setStateBackend(stateBackend); env .addSource(new CheckpointedSequenceSource(sequenceEnd, 1)) .keyBy(new KeySelector<Long, Object>() { private static final long serialVersionUID = -8572892067702489025L; @Override public Object getKey(Long value) throws Exception { return value; } }) .flatMap(new StatefulFlatMap()).setParallelism(1) .addSink(new CountingSink()) .setParallelism(1); JobGraph jobGraph = env.getStreamGraph().getJobGraph(); miniCluster.submitJobDetached(jobGraph); CompletedCheckpointsLatch.await(); jmGateway.tell(PoisonPill.getInstance()); // Wait to finish FinalCountLatch.await(); assertEquals(expectedSum, (long) FinalCount.get()); for (int i = 0; i < Parallelism; i++) { assertNotEquals(0, RecoveredStates.get(i)); } } finally { if (miniCluster != null) { miniCluster.stop(); miniCluster.awaitTermination(); } system.shutdown(); system.awaitTermination(); testingServer.stop(); testingServer.close(); } } // --------------------------------------------------------------------------------------------- /** * A checkpointed source, which emits elements from 0 to a configured number. */ public static class CheckpointedSequenceSource extends RichParallelSourceFunction<Long> implements ListCheckpointed<Tuple2<Long, Integer>> { private static final Logger LOG = LoggerFactory.getLogger(CheckpointedSequenceSource.class); private static final long serialVersionUID = 0L; private static final CountDownLatch sync = new CountDownLatch(Parallelism); private final long end; private int repeat; private long current; private volatile boolean isRunning = true; public CheckpointedSequenceSource(long end) { this(end, 1); } public CheckpointedSequenceSource(long end, int repeat) { checkArgument(end >= 0, "Negative final count"); this.current = 0; this.end = end; this.repeat = repeat; } @Override public void run(SourceContext<Long> ctx) throws Exception { while (isRunning) { synchronized (ctx.getCheckpointLock()) { if (current <= end) { ctx.collect(current++); } else if(repeat > 0) { --repeat; current = 0; } else { isRunning = false; } } // Slow down until some checkpoints are completed if (sync.getCount() != 0) { Thread.sleep(50); } } CompletedCheckpointsLatch2.await(); synchronized (ctx.getCheckpointLock()) { ctx.collect(LastElement); } } @Override public List<Tuple2<Long, Integer>> snapshotState(long checkpointId, long timestamp) throws Exception { LOG.debug("Snapshotting state {} @ ID {}.", current, checkpointId); return Collections.singletonList(new Tuple2<>(this.current, this.repeat)); } @Override public void restoreState(List<Tuple2<Long, Integer>> list) throws Exception { if (list.isEmpty() || list.size() > 1) { throw new RuntimeException("Test failed due to unexpected recovered state size " + list.size()); } Tuple2<Long, Integer> state = list.get(0); LOG.debug("Restoring state {}", state); // This is necessary to make sure that something is recovered at all. Otherwise it // might happen that the job is restarted from the beginning. RecoveredStates.set(getRuntimeContext().getIndexOfThisSubtask(), 1); sync.countDown(); current = state._1; repeat = state._2; } @Override public void cancel() { isRunning = false; } } /** * A checkpointed sink, which sums up its input and notifies the main thread after all inputs * are exhausted. */ public static class CountingSink implements SinkFunction<Long>, ListCheckpointed<CountingSink>, CheckpointListener { private static final Logger LOG = LoggerFactory.getLogger(CountingSink.class); private static final long serialVersionUID = 1436484290453629091L; private long current = 0; private int numberOfReceivedLastElements; @Override public void invoke(Long value) throws Exception { if (value == LastElement) { numberOfReceivedLastElements++; if (numberOfReceivedLastElements == Parallelism) { FinalCount.set(current); FinalCountLatch.countDown(); } else if (numberOfReceivedLastElements > Parallelism) { throw new IllegalStateException("Received more elements than parallelism."); } } else { current += value; } } @Override public List<CountingSink> snapshotState(long checkpointId, long timestamp) throws Exception { LOG.debug("Snapshotting state {}:{} @ ID {}.", current, numberOfReceivedLastElements, checkpointId); return Collections.singletonList(this); } @Override public void restoreState(List<CountingSink> state) throws Exception { if (state.isEmpty() || state.size() > 1) { throw new RuntimeException("Test failed due to unexpected recovered state size " + state.size()); } CountingSink s = state.get(0); LOG.debug("Restoring state {}:{}", s.current, s.numberOfReceivedLastElements); this.current = s.current; this.numberOfReceivedLastElements = s.numberOfReceivedLastElements; } @Override public void notifyCheckpointComplete(long checkpointId) throws Exception { LOG.debug("Checkpoint {} completed.", checkpointId); CompletedCheckpointsLatch.countDown(); CompletedCheckpointsLatch2.countDown(); } } public static class StatefulFlatMap extends RichFlatMapFunction<Long, Long> implements CheckpointedFunction { private static final long serialVersionUID = 9031079547885320663L; private transient ValueState<Integer> alreadySeen; @Override public void flatMap(Long input, Collector<Long> out) throws Exception { Integer seen = this.alreadySeen.value(); if (seen >= Parallelism || input == -1) { out.collect(input); } this.alreadySeen.update(seen + 1); } @Override public void open(Configuration config) { } @Override public void snapshotState(FunctionSnapshotContext context) throws Exception { } @Override public void initializeState(FunctionInitializationContext context) throws Exception { ValueStateDescriptor<Integer> descriptor = new ValueStateDescriptor<>( "seenCountState", TypeInformation.of(new TypeHint<Integer>() {}), 0); alreadySeen = context.getKeyedStateStore().getState(descriptor); } } }
/* * Copyright (c) 2012 Sonatype, Inc. All rights reserved. * * This program is licensed to you under the Apache License Version 2.0, * and you may not use this file except in compliance with the Apache License Version 2.0. * You may obtain a copy of the Apache License Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0. * * Unless required by applicable law or agreed to in writing, * software distributed under the Apache License Version 2.0 is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the Apache License Version 2.0 for the specific language governing permissions and limitations there under. */ package com.ning.http.client.async.grizzly; import static com.ning.http.client.providers.grizzly.GrizzlyAsyncHttpProviderConfig.Property.TRANSPORT_CUSTOMIZER; import org.glassfish.grizzly.filterchain.FilterChainBuilder; import org.glassfish.grizzly.nio.transport.TCPNIOTransport; import org.glassfish.grizzly.strategies.SameThreadIOStrategy; import com.ning.http.client.AsyncHttpClient; import com.ning.http.client.AsyncHttpClientConfig; import com.ning.http.client.AsyncHttpProviderConfig; import com.ning.http.client.async.ProviderUtil; import com.ning.http.client.async.RedirectConnectionUsageTest; import com.ning.http.client.providers.grizzly.GrizzlyAsyncHttpProviderConfig; import com.ning.http.client.providers.grizzly.TransportCustomizer; public class GrizzlyRedirectConnectionUsageTest extends RedirectConnectionUsageTest { @Override public AsyncHttpClient getAsyncHttpClient(AsyncHttpClientConfig config) { return ProviderUtil.grizzlyProvider(config); } @Override protected AsyncHttpProviderConfig getProviderConfig() { final GrizzlyAsyncHttpProviderConfig config = new GrizzlyAsyncHttpProviderConfig(); config.addProperty(TRANSPORT_CUSTOMIZER, new TransportCustomizer() { @Override public void customize(TCPNIOTransport transport, FilterChainBuilder builder) { if (System.getProperty("blockingio") != null) { transport.configureBlocking(true); } transport.setIOStrategy(SameThreadIOStrategy.getInstance()); } }); return config; } }
/** * __A class to try our game so far. You will have to download the zip file :) :) :) * @author __Naisila Puka___ * @version __30/04/2017__ */ import java.awt.*; import java.io.*; import javax.swing.*; public class Try { public static void main(String[] args) throws IOException, InterruptedException { LaunchFrame frame = new LaunchFrame(); frame.setVisible(true); } }
package com.tibco.as.spacebar.ui.preferences; import org.apache.poi.ss.SpreadsheetVersion; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.TabFolder; import com.tibco.as.convert.ConverterFactory.Blob; import com.tibco.as.spacebar.ui.Messages; public class ExcelPreferencePage extends TabbedPreferencePage { @Override protected void addTabFields(TabFolder folder) { createImport(createTab(folder, "Import")); //$NON-NLS-1$ createExport(createTab(folder, "Export")); //$NON-NLS-1$ } private Composite createImport(Composite parent) { Composite composite = createTabItemComposite(parent); addBooleanField(Preferences.IMPORT_EXCEL_HEADER, Messages.Excel_Import_Header, composite, Messages.Excel_Import_Header_Tooltip); addComboField(Preferences.IMPORT_EXCEL_FORMAT_BLOB, Messages.Formats_Blob, new String[][] { { Messages.Formats_Blob_Base64, Blob.BASE64.name() }, { Messages.Formats_Blob_Hex, Blob.HEX.name() } }, composite, Messages.Formats_Blob_Tooltip); return composite; } private Composite createExport(Composite parent) { Composite composite = createTabItemComposite(parent); addBooleanField(Preferences.EXPORT_EXCEL_HEADER, Messages.Excel_Export_Header, composite, Messages.Excel_Export_Header_Tooltip); addComboField(Preferences.EXPORT_EXCEL_VERSION, Messages.Excel_Export_Version, new String[][] { { Messages.Excel_Export_Version_97, SpreadsheetVersion.EXCEL97.name() }, { Messages.Excel_Export_Version_2007, SpreadsheetVersion.EXCEL2007.name() } }, composite, Messages.Excel_Export_Version_Tooltip); addComboField(Preferences.EXPORT_EXCEL_FORMAT_BLOB, Messages.Formats_Blob, new String[][] { { Messages.Formats_Blob_Base64, Blob.BASE64.name() }, { Messages.Formats_Blob_Hex, Blob.HEX.name() } }, composite, Messages.Formats_Blob_Tooltip); addStringField(Preferences.EXPORT_EXCEL_FORMAT_DATE, Messages.Formats_DateTime, composite, Messages.Formats_DateTime_Tooltip); return composite; } }
package com.javadude.visitor.multiple.methods; public class CEO extends CompositeEmployee { public CEO(String name) { super(name); } public void accept(EmployeeVisitor visitor) { visitor.preVisit(this); visitor.visit(this); acceptChildren(visitor); visitor.postVisit(this); } }
package com.loop54.model.request.parameters.filters; import java.util.ArrayList; import java.util.List; /** * Used for combining two or more filters using AND-logic */ public class AndFilterParameter extends FilterParameter { public AndFilterParameter() { } /** * @param filters Filters to combine using AND logic */ public AndFilterParameter(FilterParameter... filters) { for(FilterParameter filter : filters) and.add(filter); } /** * The filters that should be combined. */ public final List<FilterParameter> and = new ArrayList<>(); }
package net.endhq.remoteentities.api.thinking.goals; import net.endhq.remoteentities.api.RemoteEntity; import net.endhq.remoteentities.api.thinking.DesireBase; import net.endhq.remoteentities.api.thinking.DesireType; import net.endhq.remoteentities.persistence.ParameterData; import net.endhq.remoteentities.persistence.SerializeAs; import net.endhq.remoteentities.utilities.*; import net.minecraft.server.v1_7_R4.*; /** * Using this desire the entity will offer the nearest entity of the given type a flower. * You can also specify the entity type. * Keep in mind that this is designed for iron golems and might not work properly on other entities. */ public class DesireOfferFlower extends DesireBase { protected int m_offerTick; protected EntityLiving m_nearestEntity; @SerializeAs(pos = 1) protected Class<? extends Entity> m_toOffer; @Deprecated public DesireOfferFlower(RemoteEntity inEntity) { super(inEntity); this.m_toOffer = EntityVillager.class; this.m_type = DesireType.SUBCONSCIOUS; } @Deprecated @SuppressWarnings("unchecked") public DesireOfferFlower(RemoteEntity inEntity, Class<?> inToOffer) { this(inEntity); if(Entity.class.isAssignableFrom(inToOffer)) this.m_toOffer = (Class<? extends Entity>)inToOffer; else this.m_toOffer = (Class<? extends Entity>)NMSClassMap.getNMSClass(inToOffer); } public DesireOfferFlower() { super(); this.m_toOffer = EntityVillager.class; this.m_type = DesireType.SUBCONSCIOUS; } @SuppressWarnings("unchecked") public DesireOfferFlower(Class<?> inToOffer) { this(); if(Entity.class.isAssignableFrom(inToOffer)) this.m_toOffer = (Class<? extends Entity>)inToOffer; else this.m_toOffer = (Class<? extends Entity>)NMSClassMap.getNMSClass(inToOffer); } @Override public boolean shouldExecute() { if(this.getEntityHandle() == null || this.getEntityHandle().world.w()) return false; else if(this.getEntityHandle().aI().nextInt(8000) != 0) return false; else { this.m_nearestEntity = (EntityLiving)this.getEntityHandle().world.a(this.m_toOffer, this.getEntityHandle().boundingBox.grow(6, 2, 6), this.getEntityHandle()); return this.m_nearestEntity != null; } } @Override public boolean canContinue() { return this.m_offerTick > 0; } @Override public void startExecuting() { this.m_offerTick = 400; if(this.getEntityHandle() instanceof EntityIronGolem) ((EntityIronGolem)this.getEntityHandle()).a(true); else this.getEntityHandle().world.broadcastEntityEffect(this.getEntityHandle(), (byte)11); } @Override public void stopExecuting() { this.m_nearestEntity = null; if(this.getEntityHandle() instanceof EntityIronGolem) ((EntityIronGolem)this.getEntityHandle()).a(false); else this.getEntityHandle().world.broadcastEntityEffect(this.getEntityHandle(), (byte)11); } @Override public boolean update() { NMSUtil.getControllerLook(this.getEntityHandle()).a(this.m_nearestEntity, 30, 30); this.m_offerTick--; return true; } @Override public ParameterData[] getSerializableData() { return ReflectionUtil.getParameterDataForClass(this).toArray(new ParameterData[0]); } }
package ru.itmo.wp.controller; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import ru.itmo.wp.security.Guest; import ru.itmo.wp.service.PostService; import javax.servlet.http.HttpSession; @Controller public class IndexPage extends Page { private final PostService postService; public IndexPage(PostService postService) { this.postService = postService; } @Guest @GetMapping({"", "/"}) public String index(Model model) { model.addAttribute("posts", postService.findAll()); return "IndexPage"; } @GetMapping("/logout") public String logout(HttpSession httpSession) { unsetUser(httpSession); return "redirect:/"; } }
/* * Copyright (C) 2008 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 com.google.common.annotations.Beta; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import java.io.IOException; import java.io.InvalidObjectException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.Collection; import java.util.Comparator; import java.util.Map.Entry; import javax.annotation.Nullable; /** * A {@link ListMultimap} whose contents will never change, with many other important properties * detailed at {@link ImmutableCollection}. * * <p>See the Guava User Guide article on <a href= * "https://github.com/google/guava/wiki/ImmutableCollectionsExplained"> * immutable collections</a>. * * @author Jared Levy * @since 2.0 */ @GwtCompatible(serializable = true, emulated = true) public class ImmutableListMultimap<K, V> extends ImmutableMultimap<K, V> implements ListMultimap<K, V> { /** Returns the empty multimap. */ // Casting is safe because the multimap will never hold any elements. @SuppressWarnings("unchecked") public static <K, V> ImmutableListMultimap<K, V> of() { return (ImmutableListMultimap<K, V>) EmptyImmutableListMultimap.INSTANCE; } /** * Returns an immutable multimap containing a single entry. */ public static <K, V> ImmutableListMultimap<K, V> of(K k1, V v1) { ImmutableListMultimap.Builder<K, V> builder = ImmutableListMultimap.builder(); builder.put(k1, v1); return builder.build(); } /** * Returns an immutable multimap containing the given entries, in order. */ public static <K, V> ImmutableListMultimap<K, V> of(K k1, V v1, K k2, V v2) { ImmutableListMultimap.Builder<K, V> builder = ImmutableListMultimap.builder(); builder.put(k1, v1); builder.put(k2, v2); return builder.build(); } /** * Returns an immutable multimap containing the given entries, in order. */ public static <K, V> ImmutableListMultimap<K, V> of(K k1, V v1, K k2, V v2, K k3, V v3) { ImmutableListMultimap.Builder<K, V> builder = ImmutableListMultimap.builder(); builder.put(k1, v1); builder.put(k2, v2); builder.put(k3, v3); return builder.build(); } /** * Returns an immutable multimap containing the given entries, in order. */ public static <K, V> ImmutableListMultimap<K, V> of( K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4) { ImmutableListMultimap.Builder<K, V> builder = ImmutableListMultimap.builder(); builder.put(k1, v1); builder.put(k2, v2); builder.put(k3, v3); builder.put(k4, v4); return builder.build(); } /** * Returns an immutable multimap containing the given entries, in order. */ public static <K, V> ImmutableListMultimap<K, V> of( K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5) { ImmutableListMultimap.Builder<K, V> builder = ImmutableListMultimap.builder(); builder.put(k1, v1); builder.put(k2, v2); builder.put(k3, v3); builder.put(k4, v4); builder.put(k5, v5); return builder.build(); } // looking for of() with > 5 entries? Use the builder instead. /** * Returns a new builder. The generated builder is equivalent to the builder * created by the {@link Builder} constructor. */ public static <K, V> Builder<K, V> builder() { return new Builder<K, V>(); } /** * A builder for creating immutable {@code ListMultimap} instances, especially * {@code public static final} multimaps ("constant multimaps"). Example: * <pre> {@code * * static final Multimap<String, Integer> STRING_TO_INTEGER_MULTIMAP = * new ImmutableListMultimap.Builder<String, Integer>() * .put("one", 1) * .putAll("several", 1, 2, 3) * .putAll("many", 1, 2, 3, 4, 5) * .build();}</pre> * * <p>Builder instances can be reused; it is safe to call {@link #build} multiple * times to build multiple multimaps in series. Each multimap contains the * key-value mappings in the previously created multimaps. * * @since 2.0 */ public static final class Builder<K, V> extends ImmutableMultimap.Builder<K, V> { /** * Creates a new builder. The returned builder is equivalent to the builder * generated by {@link ImmutableListMultimap#builder}. */ public Builder() {} @Override public Builder<K, V> put(K key, V value) { super.put(key, value); return this; } /** * {@inheritDoc} * * @since 11.0 */ @Override public Builder<K, V> put(Entry<? extends K, ? extends V> entry) { super.put(entry); return this; } /** * {@inheritDoc} * * @since 19.0 */ @Beta @Override public Builder<K, V> putAll(Iterable<? extends Entry<? extends K, ? extends V>> entries) { super.putAll(entries); return this; } @Override public Builder<K, V> putAll(K key, Iterable<? extends V> values) { super.putAll(key, values); return this; } @Override public Builder<K, V> putAll(K key, V... values) { super.putAll(key, values); return this; } @Override public Builder<K, V> putAll(Multimap<? extends K, ? extends V> multimap) { super.putAll(multimap); return this; } /** * {@inheritDoc} * * @since 8.0 */ @Override public Builder<K, V> orderKeysBy(Comparator<? super K> keyComparator) { super.orderKeysBy(keyComparator); return this; } /** * {@inheritDoc} * * @since 8.0 */ @Override public Builder<K, V> orderValuesBy(Comparator<? super V> valueComparator) { super.orderValuesBy(valueComparator); return this; } /** * Returns a newly-created immutable list multimap. */ @Override public ImmutableListMultimap<K, V> build() { return (ImmutableListMultimap<K, V>) super.build(); } } /** * Returns an immutable multimap containing the same mappings as {@code * multimap}. The generated multimap's key and value orderings correspond to * the iteration ordering of the {@code multimap.asMap()} view. * * <p>Despite the method name, this method attempts to avoid actually copying * the data when it is safe to do so. The exact circumstances under which a * copy will or will not be performed are undocumented and subject to change. * * @throws NullPointerException if any key or value in {@code multimap} is * null */ public static <K, V> ImmutableListMultimap<K, V> copyOf( Multimap<? extends K, ? extends V> multimap) { if (multimap.isEmpty()) { return of(); } // TODO(lowasser): copy ImmutableSetMultimap by using asList() on the sets if (multimap instanceof ImmutableListMultimap) { @SuppressWarnings("unchecked") // safe since multimap is not writable ImmutableListMultimap<K, V> kvMultimap = (ImmutableListMultimap<K, V>) multimap; if (!kvMultimap.isPartialView()) { return kvMultimap; } } ImmutableMap.Builder<K, ImmutableList<V>> builder = new ImmutableMap.Builder<K, ImmutableList<V>>(multimap.asMap().size()); int size = 0; for (Entry<? extends K, ? extends Collection<? extends V>> entry : multimap.asMap().entrySet()) { ImmutableList<V> list = ImmutableList.copyOf(entry.getValue()); if (!list.isEmpty()) { builder.put(entry.getKey(), list); size += list.size(); } } return new ImmutableListMultimap<K, V>(builder.build(), size); } /** * Returns an immutable multimap containing the specified entries. The * returned multimap iterates over keys in the order they were first * encountered in the input, and the values for each key are iterated in the * order they were encountered. * * @throws NullPointerException if any key, value, or entry is null * @since 19.0 */ @Beta public static <K, V> ImmutableListMultimap<K, V> copyOf( Iterable<? extends Entry<? extends K, ? extends V>> entries) { return new Builder<K, V>().putAll(entries).build(); } ImmutableListMultimap(ImmutableMap<K, ImmutableList<V>> map, int size) { super(map, size); } // views /** * Returns an immutable list of the values for the given key. If no mappings * in the multimap have the provided key, an empty immutable list is * returned. The values are in the same order as the parameters used to build * this multimap. */ @Override public ImmutableList<V> get(@Nullable K key) { // This cast is safe as its type is known in constructor. ImmutableList<V> list = (ImmutableList<V>) map.get(key); return (list == null) ? ImmutableList.<V>of() : list; } private transient ImmutableListMultimap<V, K> inverse; /** * {@inheritDoc} * * <p>Because an inverse of a list multimap can contain multiple pairs with * the same key and value, this method returns an {@code * ImmutableListMultimap} rather than the {@code ImmutableMultimap} specified * in the {@code ImmutableMultimap} class. * * @since 11.0 */ @Override public ImmutableListMultimap<V, K> inverse() { ImmutableListMultimap<V, K> result = inverse; return (result == null) ? (inverse = invert()) : result; } private ImmutableListMultimap<V, K> invert() { Builder<V, K> builder = builder(); for (Entry<K, V> entry : entries()) { builder.put(entry.getValue(), entry.getKey()); } ImmutableListMultimap<V, K> invertedMultimap = builder.build(); invertedMultimap.inverse = this; return invertedMultimap; } /** * Guaranteed to throw an exception and leave the multimap unmodified. * * @throws UnsupportedOperationException always * @deprecated Unsupported operation. */ @Deprecated @Override public ImmutableList<V> removeAll(Object key) { throw new UnsupportedOperationException(); } /** * Guaranteed to throw an exception and leave the multimap unmodified. * * @throws UnsupportedOperationException always * @deprecated Unsupported operation. */ @Deprecated @Override public ImmutableList<V> replaceValues(K key, Iterable<? extends V> values) { throw new UnsupportedOperationException(); } /** * @serialData number of distinct keys, and then for each distinct key: the * key, the number of values for that key, and the key's values */ @GwtIncompatible("java.io.ObjectOutputStream") private void writeObject(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); Serialization.writeMultimap(this, stream); } @GwtIncompatible("java.io.ObjectInputStream") private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); int keyCount = stream.readInt(); if (keyCount < 0) { throw new InvalidObjectException("Invalid key count " + keyCount); } ImmutableMap.Builder<Object, ImmutableList<Object>> builder = ImmutableMap.builder(); int tmpSize = 0; for (int i = 0; i < keyCount; i++) { Object key = stream.readObject(); int valueCount = stream.readInt(); if (valueCount <= 0) { throw new InvalidObjectException("Invalid value count " + valueCount); } ImmutableList.Builder<Object> valuesBuilder = ImmutableList.builder(); for (int j = 0; j < valueCount; j++) { valuesBuilder.add(stream.readObject()); } builder.put(key, valuesBuilder.build()); tmpSize += valueCount; } ImmutableMap<Object, ImmutableList<Object>> tmpMap; try { tmpMap = builder.build(); } catch (IllegalArgumentException e) { throw (InvalidObjectException) new InvalidObjectException(e.getMessage()).initCause(e); } FieldSettersHolder.MAP_FIELD_SETTER.set(this, tmpMap); FieldSettersHolder.SIZE_FIELD_SETTER.set(this, tmpSize); } @GwtIncompatible("Not needed in emulated source") private static final long serialVersionUID = 0; }
package com.ambit.otgorithm.dto; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.TaskStackBuilder; import android.content.Context; import android.content.Intent; import android.provider.Settings; import android.support.v4.app.NotificationCompat; import com.ambit.otgorithm.R; public class Notification { private Context mContext; private NotificationManager mNotificationManager; private NotificationCompat.Builder mNotifyBuilder; public Notification(Context context) { this.mContext = context; mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); mNotifyBuilder = new NotificationCompat.Builder(mContext); mNotifyBuilder.setVibrate(new long[]{1000,1000}); mNotifyBuilder.setPriority(100); mNotifyBuilder.setSmallIcon(R.mipmap.ic_launcher); mNotifyBuilder.setSound(Settings.System.DEFAULT_NOTIFICATION_URI); } public Notification setTitle(String title){ mNotifyBuilder.setContentTitle(title); mNotifyBuilder.setTicker(title); return this; } public Notification setText(String text){ mNotifyBuilder.setContentText(text); return this; } public Notification setData(Intent intent) { TaskStackBuilder taskStackBuilder = TaskStackBuilder.create(mContext); taskStackBuilder.addNextIntent(intent); PendingIntent pendingIntent = taskStackBuilder.getPendingIntent(140, PendingIntent.FLAG_UPDATE_CURRENT); mNotifyBuilder.setContentIntent(pendingIntent); return this; } public void notification() { try { mNotificationManager.notify(1, mNotifyBuilder.build()); } catch (Exception e){ e.printStackTrace(); } } }
/* * Copyright 2018 The Data Transfer Project 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.datatransferproject.spi.cloud.types; import static com.google.common.truth.Truth.assertThat; import com.fasterxml.jackson.databind.ObjectMapper; import java.time.LocalDateTime; import org.datatransferproject.spi.cloud.types.PortabilityJob.State; import org.datatransferproject.test.types.ObjectMapperFactory; import org.junit.Test; /** Tests serialization and deserialization of a {@link PortabilityJob}. */ public class PortabilityJobTest { @Test public void verifySerializeDeserialize() throws Exception { ObjectMapper objectMapper = ObjectMapperFactory.createObjectMapper(); LocalDateTime date = LocalDateTime.of(2018, 2, 20, 12, 0); JobAuthorization jobAuthorization = JobAuthorization.builder() .setState(JobAuthorization.State.INITIAL) .setSessionSecretKey("foo") .build(); PortabilityJob job = PortabilityJob.builder() .setState(State.NEW) .setExportService("fooService") .setImportService("barService") .setTransferDataType("photos") .setCreatedTimestamp(date) .setLastUpdateTimestamp(date.plusMinutes(2)) .setJobAuthorization(jobAuthorization) .build(); String serializedJobAuthorization = objectMapper.writeValueAsString(jobAuthorization); JobAuthorization deserializedJobAuthorization = objectMapper.readValue(serializedJobAuthorization, JobAuthorization.class); assertThat(deserializedJobAuthorization).isEqualTo(jobAuthorization); String serializedJob = objectMapper.writeValueAsString(job); PortabilityJob deserializedJob = objectMapper.readValue(serializedJob, PortabilityJob.class); assertThat(deserializedJob).isEqualTo(job); } }
/* * Copyright 2020 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kie.kogito.index.service; import java.time.Duration; import java.time.ZoneOffset; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.Collection; import java.util.UUID; import javax.inject.Inject; import javax.transaction.Transactional; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.kie.kogito.index.DataIndexStorageService; import org.kie.kogito.index.event.KogitoJobCloudEvent; import org.kie.kogito.index.event.KogitoProcessCloudEvent; import org.kie.kogito.index.event.KogitoUserTaskCloudEvent; import org.kie.kogito.index.model.MilestoneStatus; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.fasterxml.jackson.databind.node.ObjectNode; import io.restassured.RestAssured; import io.restassured.http.ContentType; import static io.restassured.RestAssured.given; import static io.restassured.config.EncoderConfig.encoderConfig; import static org.awaitility.Awaitility.await; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.isA; import static org.hamcrest.CoreMatchers.not; import static org.hamcrest.CoreMatchers.nullValue; import static org.hamcrest.Matchers.emptyOrNullString; import static org.hamcrest.Matchers.hasItems; import static org.hamcrest.Matchers.hasSize; import static org.kie.kogito.index.GraphQLUtils.getJobById; import static org.kie.kogito.index.GraphQLUtils.getProcessInstanceByBusinessKey; import static org.kie.kogito.index.GraphQLUtils.getProcessInstanceById; import static org.kie.kogito.index.GraphQLUtils.getProcessInstanceByIdAndAddon; import static org.kie.kogito.index.GraphQLUtils.getProcessInstanceByIdAndErrorNode; import static org.kie.kogito.index.GraphQLUtils.getProcessInstanceByIdAndMilestoneName; import static org.kie.kogito.index.GraphQLUtils.getProcessInstanceByIdAndMilestoneStatus; import static org.kie.kogito.index.GraphQLUtils.getProcessInstanceByIdAndNullParentProcessInstanceId; import static org.kie.kogito.index.GraphQLUtils.getProcessInstanceByIdAndNullRootProcessInstanceId; import static org.kie.kogito.index.GraphQLUtils.getProcessInstanceByIdAndParentProcessInstanceId; import static org.kie.kogito.index.GraphQLUtils.getProcessInstanceByIdAndProcessId; import static org.kie.kogito.index.GraphQLUtils.getProcessInstanceByIdAndStart; import static org.kie.kogito.index.GraphQLUtils.getProcessInstanceByIdAndState; import static org.kie.kogito.index.GraphQLUtils.getProcessInstanceByParentProcessInstanceId; import static org.kie.kogito.index.GraphQLUtils.getProcessInstanceByRootProcessInstanceId; import static org.kie.kogito.index.GraphQLUtils.getUserTaskInstanceById; import static org.kie.kogito.index.GraphQLUtils.getUserTaskInstanceByIdAndActualOwner; import static org.kie.kogito.index.GraphQLUtils.getUserTaskInstanceByIdAndCompleted; import static org.kie.kogito.index.GraphQLUtils.getUserTaskInstanceByIdAndPotentialGroups; import static org.kie.kogito.index.GraphQLUtils.getUserTaskInstanceByIdAndPotentialUsers; import static org.kie.kogito.index.GraphQLUtils.getUserTaskInstanceByIdAndProcessId; import static org.kie.kogito.index.GraphQLUtils.getUserTaskInstanceByIdAndStarted; import static org.kie.kogito.index.GraphQLUtils.getUserTaskInstanceByIdAndState; import static org.kie.kogito.index.GraphQLUtils.getUserTaskInstanceByIdNoActualOwner; import static org.kie.kogito.index.TestUtils.getJobCloudEvent; import static org.kie.kogito.index.TestUtils.getProcessCloudEvent; import static org.kie.kogito.index.TestUtils.getUserTaskCloudEvent; import static org.kie.kogito.index.json.JsonUtils.getObjectMapper; import static org.kie.kogito.index.model.ProcessInstanceState.ACTIVE; import static org.kie.kogito.index.model.ProcessInstanceState.COMPLETED; import static org.kie.kogito.index.model.ProcessInstanceState.ERROR; public abstract class AbstractIndexingServiceIT extends AbstractIndexingIT { private static final Logger LOGGER = LoggerFactory.getLogger(AbstractIndexingServiceIT.class); Duration timeout = Duration.ofSeconds(30); @Inject public DataIndexStorageService cacheService; @BeforeAll static void setup() { RestAssured.config = RestAssured.config() .encoderConfig(encoderConfig().appendDefaultContentCharsetToContentTypeIfUndefined(false)); } protected String formatZonedDateTime(ZonedDateTime time) { return time.truncatedTo(ChronoUnit.MILLIS).format(DateTimeFormatter.ISO_OFFSET_DATE_TIME); } @AfterEach @Transactional void tearDown() { cacheService.getJobsCache().clear(); cacheService.getProcessInstancesCache().clear(); cacheService.getUserTaskInstancesCache().clear(); } @Test //Reproducer for KOGITO-334 void testDefaultGraphqlTypes() { given().contentType(ContentType.JSON).body("{ \"query\" : \"{ProcessInstances{ id } }\" }") .when().post("/graphql") .then().log().ifValidationFails().statusCode(200).body("data.ProcessInstances", isA(Collection.class)); given().contentType(ContentType.JSON).body("{ \"query\" : \"{UserTaskInstances{ id } }\" }") .when().post("/graphql") .then().log().ifValidationFails().statusCode(200).body("data.UserTaskInstances", isA(Collection.class)); given().contentType(ContentType.JSON).body("{ \"query\" : \"{Jobs{ id } }\" }") .when().post("/graphql") .then().log().ifValidationFails().statusCode(200).body("data.Jobs", isA(Collection.class)); } protected void validateProcessInstance(String query, KogitoProcessCloudEvent event, String childProcessInstanceId) { LOGGER.debug("GraphQL query: {}", query); await() .atMost(timeout) .untilAsserted(() -> given().contentType(ContentType.JSON).body(query) .when().post("/graphql") .then().log().ifValidationFails().statusCode(200) .body("data.ProcessInstances[0].id", is(event.getProcessInstanceId())) .body("data.ProcessInstances[0].processId", is(event.getProcessId())) .body("data.ProcessInstances[0].processName", is(event.getData().getProcessName())) .body("data.ProcessInstances[0].rootProcessId", is(event.getRootProcessId())) .body("data.ProcessInstances[0].rootProcessInstanceId", is(event.getRootProcessInstanceId())) .body("data.ProcessInstances[0].parentProcessInstanceId", is(event.getParentProcessInstanceId())) .body("data.ProcessInstances[0].parentProcessInstance.id", event.getParentProcessInstanceId() == null ? is(nullValue()) : is(event.getParentProcessInstanceId())) .body("data.ProcessInstances[0].parentProcessInstance.processName", event.getParentProcessInstanceId() == null ? is(nullValue()) : is(not(emptyOrNullString()))) .body("data.ProcessInstances[0].start", is(formatZonedDateTime(event.getData().getStart().withZoneSameInstant(ZoneOffset.UTC)))) .body("data.ProcessInstances[0].end", event.getData().getEnd() == null ? is(nullValue()) : is(formatZonedDateTime(event.getData().getEnd().withZoneSameInstant(ZoneOffset.UTC)))) .body("data.ProcessInstances[0].childProcessInstances[0].id", childProcessInstanceId == null ? is(nullValue()) : is(childProcessInstanceId)) .body("data.ProcessInstances[0].childProcessInstances[0].processName", childProcessInstanceId == null ? is(nullValue()) : is(not(emptyOrNullString()))) .body("data.ProcessInstances[0].endpoint", is(event.getSource().toString())) .body("data.ProcessInstances[0].serviceUrl", event.getSource().toString().equals("/" + event.getProcessId()) ? is(nullValue()) : is("http://localhost:8080")) .body("data.ProcessInstances[0].addons", hasItems(event.getData().getAddons().toArray())) .body("data.ProcessInstances[0].error.message", event.getData().getError() == null ? is(nullValue()) : is(event.getData().getError().getMessage())) .body("data.ProcessInstances[0].error.nodeDefinitionId", event.getData().getError() == null ? is(nullValue()) : is(event.getData().getError().getNodeDefinitionId())) .body("data.ProcessInstances[0].lastUpdate", is(formatZonedDateTime( event.getData().getLastUpdate().withZoneSameInstant(ZoneOffset.UTC)))) .body("data.ProcessInstances[0].nodes", hasSize(event.getData().getNodes().size())) .body("data.ProcessInstances[0].nodes[0].id", is(event.getData().getNodes().get(0).getId())) .body("data.ProcessInstances[0].nodes[0].name", is(event.getData().getNodes().get(0).getName())) .body("data.ProcessInstances[0].nodes[0].nodeId", is(event.getData().getNodes().get(0).getNodeId())) .body("data.ProcessInstances[0].nodes[0].type", is(event.getData().getNodes().get(0).getType())) .body("data.ProcessInstances[0].nodes[0].definitionId", is(event.getData().getNodes().get(0).getDefinitionId())) .body("data.ProcessInstances[0].nodes[0].enter", is(formatZonedDateTime(event.getData().getNodes().get(0).getEnter().withZoneSameInstant(ZoneOffset.UTC)))) .body("data.ProcessInstances[0].nodes[0].exit", event.getData().getNodes().get(0).getExit() == null ? is(nullValue()) : is(formatZonedDateTime(event.getData().getNodes().get(0).getExit().withZoneSameInstant(ZoneOffset.UTC)))) .body("data.ProcessInstances[0].milestones", hasSize(event.getData().getMilestones().size())) .body("data.ProcessInstances[0].milestones[0].id", is(event.getData().getMilestones().get(0).getId())) .body("data.ProcessInstances[0].milestones[0].name", is(event.getData().getMilestones().get(0).getName())) .body("data.ProcessInstances[0].milestones[0].status", is(event.getData().getMilestones().get(0).getStatus()))); } protected void validateProcessInstance(String query, KogitoProcessCloudEvent event) { validateProcessInstance(query, event, null); } @Test void testProcessInstanceIndex() throws Exception { String processId = "travels"; String processInstanceId = UUID.randomUUID().toString(); String subProcessId = processId + "_sub"; String subProcessInstanceId = UUID.randomUUID().toString(); KogitoProcessCloudEvent startEvent = getProcessCloudEvent(processId, processInstanceId, ACTIVE, null, null, null); indexProcessCloudEvent(startEvent); validateProcessInstance(getProcessInstanceById(processInstanceId), startEvent); validateProcessInstance(getProcessInstanceByIdAndState(processInstanceId, ACTIVE), startEvent); validateProcessInstance(getProcessInstanceByIdAndProcessId(processInstanceId, processId), startEvent); validateProcessInstance( getProcessInstanceByIdAndStart(processInstanceId, formatZonedDateTime(startEvent.getData().getStart())), startEvent); validateProcessInstance(getProcessInstanceByIdAndAddon(processInstanceId, "process-management"), startEvent); validateProcessInstance(getProcessInstanceByIdAndMilestoneName(processInstanceId, "SimpleMilestone"), startEvent); validateProcessInstance(getProcessInstanceByIdAndMilestoneStatus(processInstanceId, MilestoneStatus.AVAILABLE.name()), startEvent); validateProcessInstance(getProcessInstanceByBusinessKey(startEvent.getData().getBusinessKey()), startEvent); KogitoProcessCloudEvent endEvent = getProcessCloudEvent(processId, processInstanceId, COMPLETED, null, null, null); endEvent.getData().setEnd(ZonedDateTime.now()); endEvent.getData().setVariables((ObjectNode) getObjectMapper().readTree( "{ \"traveller\":{\"firstName\":\"Maciej\"},\"hotel\":{\"name\":\"Ibis\"},\"flight\":{\"arrival\":\"2019-08-20T22:12:57.340Z\",\"departure\":\"2019-08-20T07:12:57.340Z\",\"flightNumber\":\"QF444\"} }")); indexProcessCloudEvent(endEvent); validateProcessInstance(getProcessInstanceByIdAndState(processInstanceId, COMPLETED), endEvent); KogitoProcessCloudEvent event = getProcessCloudEvent(subProcessId, subProcessInstanceId, ACTIVE, processInstanceId, processId, processInstanceId); indexProcessCloudEvent(event); validateProcessInstance(getProcessInstanceByParentProcessInstanceId(processInstanceId), event); validateProcessInstance(getProcessInstanceByIdAndNullParentProcessInstanceId(processInstanceId, true), endEvent, subProcessInstanceId); validateProcessInstance(getProcessInstanceByRootProcessInstanceId(processInstanceId), event); validateProcessInstance(getProcessInstanceByIdAndNullRootProcessInstanceId(processInstanceId, true), endEvent, subProcessInstanceId); validateProcessInstance(getProcessInstanceById(processInstanceId), endEvent, subProcessInstanceId); validateProcessInstance(getProcessInstanceByIdAndParentProcessInstanceId(subProcessInstanceId, processInstanceId), event); KogitoProcessCloudEvent errorEvent = getProcessCloudEvent(subProcessId, subProcessInstanceId, ERROR, processInstanceId, processId, processInstanceId); indexProcessCloudEvent(errorEvent); validateProcessInstance( getProcessInstanceByIdAndErrorNode(subProcessInstanceId, errorEvent.getData().getError().getNodeDefinitionId()), errorEvent); } @Test void testUserTaskInstanceIndex() throws Exception { String taskId = UUID.randomUUID().toString(); String state = "InProgress"; String processId = "deals"; String processInstanceId = UUID.randomUUID().toString(); KogitoUserTaskCloudEvent event = getUserTaskCloudEvent(taskId, processId, processInstanceId, null, null, state); indexUserTaskCloudEvent(event); validateUserTaskInstance(getUserTaskInstanceById(taskId), event); validateUserTaskInstance(getUserTaskInstanceByIdAndActualOwner(taskId, "kogito"), event); validateUserTaskInstance(getUserTaskInstanceByIdAndProcessId(taskId, processId), event); validateUserTaskInstance( getUserTaskInstanceByIdAndPotentialGroups(taskId, new ArrayList<>(event.getData().getPotentialGroups())), event); validateUserTaskInstance( getUserTaskInstanceByIdAndPotentialUsers(taskId, new ArrayList<>(event.getData().getPotentialUsers())), event); validateUserTaskInstance(getUserTaskInstanceByIdAndState(taskId, event.getData().getState()), event); validateUserTaskInstance(getUserTaskInstanceByIdAndStarted(taskId, formatZonedDateTime(event.getData().getStarted())), event); validateUserTaskInstance( getUserTaskInstanceByIdAndCompleted(taskId, formatZonedDateTime(event.getData().getCompleted())), event); event = getUserTaskCloudEvent(taskId, processId, processInstanceId, null, null, state); event.getData().setCompleted(ZonedDateTime.now()); event.getData().setPriority("Low"); event.getData().setActualOwner("admin"); event.getData().setState("Completed"); indexUserTaskCloudEvent(event); validateUserTaskInstance(getUserTaskInstanceByIdAndActualOwner(taskId, "admin"), event); event = getUserTaskCloudEvent(taskId, processId, processInstanceId, null, null, state, null); indexUserTaskCloudEvent(event); validateUserTaskInstance(getUserTaskInstanceByIdNoActualOwner(taskId), event); } @Test void testJobIndex() { String jobId = UUID.randomUUID().toString(); String processId = "deals"; String processInstanceId = UUID.randomUUID().toString(); KogitoJobCloudEvent event = getJobCloudEvent(jobId, processId, processInstanceId, null, null, "EXECUTED"); indexJobCloudEvent(event); validateJob(getJobById(jobId), event); } protected void validateJob(String query, KogitoJobCloudEvent event) { LOGGER.debug("GraphQL query: {}", query); await() .atMost(timeout) .untilAsserted(() -> given().contentType(ContentType.JSON).body(query) .when().post("/graphql") .then().log().ifValidationFails().statusCode(200) .body("data.Jobs[0].id", is(event.getData().getId())) .body("data.Jobs[0].processId", is(event.getData().getProcessId())) .body("data.Jobs[0].processInstanceId", is(event.getData().getProcessInstanceId())) .body("data.Jobs[0].nodeInstanceId", is(event.getData().getNodeInstanceId())) .body("data.Jobs[0].rootProcessId", is(event.getData().getRootProcessId())) .body("data.Jobs[0].rootProcessInstanceId", is(event.getData().getRootProcessInstanceId())) .body("data.Jobs[0].status", is(event.getData().getStatus())) .body("data.Jobs[0].expirationTime", is(formatZonedDateTime( event.getData().getExpirationTime().withZoneSameInstant(ZoneOffset.UTC)))) .body("data.Jobs[0].priority", is(event.getData().getPriority())) .body("data.Jobs[0].callbackEndpoint", is(event.getData().getCallbackEndpoint())) .body("data.Jobs[0].repeatInterval", is(event.getData().getRepeatInterval().intValue())) .body("data.Jobs[0].repeatLimit", is(event.getData().getRepeatLimit())) .body("data.Jobs[0].scheduledId", is(event.getData().getScheduledId())) .body("data.Jobs[0].retries", is(event.getData().getRetries())) .body("data.Jobs[0].lastUpdate", is(formatZonedDateTime(event.getData().getLastUpdate().withZoneSameInstant(ZoneOffset.UTC)))) .body("data.Jobs[0].executionCounter", is(event.getData().getExecutionCounter())) .body("data.Jobs[0].endpoint", is(event.getData().getEndpoint()))); } protected void validateUserTaskInstance(String query, KogitoUserTaskCloudEvent event) { LOGGER.debug("GraphQL query: {}", query); await() .atMost(timeout) .untilAsserted(() -> given().contentType(ContentType.JSON).body(query) .when().post("/graphql") .then().log().ifValidationFails().statusCode(200) .body("data.UserTaskInstances[0].id", is(event.getUserTaskInstanceId())) .body("data.UserTaskInstances[0].processId", is(event.getProcessId())) .body("data.UserTaskInstances[0].rootProcessId", is(event.getRootProcessId())) .body("data.UserTaskInstances[0].rootProcessInstanceId", is(event.getRootProcessInstanceId())) .body("data.UserTaskInstances[0].description", is(event.getData().getDescription())) .body("data.UserTaskInstances[0].name", is(event.getData().getName())) .body("data.UserTaskInstances[0].priority", is(event.getData().getPriority())) .body("data.UserTaskInstances[0].actualOwner", is(event.getData().getActualOwner())) .body("data.UserTaskInstances[0].excludedUsers", hasItems(event.getData().getExcludedUsers().toArray())) .body("data.UserTaskInstances[0].potentialUsers", hasItems(event.getData().getPotentialUsers().toArray())) .body("data.UserTaskInstances[0].potentialGroups", hasItems(event.getData().getPotentialGroups().toArray())) .body("data.UserTaskInstances[0].started", is(formatZonedDateTime( event.getData().getStarted().withZoneSameInstant(ZoneOffset.UTC)))) .body("data.UserTaskInstances[0].completed", is(formatZonedDateTime( event.getData().getCompleted().withZoneSameInstant(ZoneOffset.UTC)))) .body("data.UserTaskInstances[0].lastUpdate", is(formatZonedDateTime(event.getTime().withZoneSameInstant(ZoneOffset.UTC)))) .body("data.UserTaskInstances[0].endpoint", is(event.getData().getEndpoint()))); } }
package org.dimdev.dimdoors.block; import net.minecraft.util.math.Vec3d; import org.dimdev.dimdoors.fluid.ModFluids; import org.dimdev.dimdoors.rift.targets.EntityTarget; import org.dimdev.dimdoors.rift.targets.EscapeTarget; import net.minecraft.block.Block; import net.minecraft.block.BlockState; import net.minecraft.block.FluidBlock; import net.minecraft.entity.Entity; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import org.dimdev.dimdoors.util.math.MathUtil; public class EternalFluidBlock extends FluidBlock { private static final EntityTarget TARGET = new EscapeTarget(true); public EternalFluidBlock(Block.Settings settings) { super(ModFluids.ETERNAL_FLUID, settings); } @Override public void onEntityCollision(BlockState blockState, World world, BlockPos blockPos, Entity entity) { if (world.isClient) { return; } try { TARGET.receiveEntity(entity, Vec3d.ZERO, MathUtil.entityEulerAngle(entity), entity.getVelocity()); } catch (Throwable e) { e.printStackTrace(); } } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.api.ads.admanager.jaxws.v202102; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for NetworkError.Reason. * * <p>The following schema fragment specifies the expected content contained within this class. * <p> * <pre> * &lt;simpleType name="NetworkError.Reason"> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;enumeration value="UNKNOWN"/> * &lt;enumeration value="MULTI_CURRENCY_NOT_SUPPORTED"/> * &lt;enumeration value="UNSUPPORTED_CURRENCY"/> * &lt;enumeration value="NETWORK_CURRENCY_CANNOT_BE_SAME_AS_SECONDARY"/> * &lt;enumeration value="CANNOT_DELETE_CURRENCY_WITH_ACTIVE_RATE_CARDS"/> * &lt;enumeration value="DELEGATION_CHILD_NETWORK_CANNOT_BECOME_A_PARENT"/> * &lt;enumeration value="DELEGATION_PARENT_NETWORK_CANNOT_BECOME_A_CHILD"/> * &lt;enumeration value="CANNOT_ADD_SAME_NETWORK_AS_DELEGATION_CHILD"/> * &lt;enumeration value="MAX_APPROVED_DELEGATION_CHILD_NETWORKS_EXCEEDED"/> * &lt;enumeration value="MAX_PENDING_DELEGATION_CHILD_NETWORKS_EXCEEDED"/> * &lt;enumeration value="CHILD_NETWORK_ALREADY_EXISTS"/> * &lt;enumeration value="IN_PARENT_DELEGATION_UNSUPPORTED_FOR_NETWORK"/> * &lt;/restriction> * &lt;/simpleType> * </pre> * */ @XmlType(name = "NetworkError.Reason") @XmlEnum public enum NetworkErrorReason { /** * * The value returned if the actual value is not exposed by the requested API version. * * */ UNKNOWN, /** * * Multi-currency support is not enabled for this network. This is an Ad Manager 360 feature. * * */ MULTI_CURRENCY_NOT_SUPPORTED, /** * * Currency provided is not supported. * * */ UNSUPPORTED_CURRENCY, /** * * The network currency cannot also be specified as a secondary currency. * * */ NETWORK_CURRENCY_CANNOT_BE_SAME_AS_SECONDARY, /** * * The currency cannot be deleted as it is still being used by active rate cards. * * */ CANNOT_DELETE_CURRENCY_WITH_ACTIVE_RATE_CARDS, /** * * An MCM child network cannot become a parent network. * * */ DELEGATION_CHILD_NETWORK_CANNOT_BECOME_A_PARENT, /** * * An MCM parent network cannot become a child of another network. * * */ DELEGATION_PARENT_NETWORK_CANNOT_BECOME_A_CHILD, /** * * In MCM, a network cannot become a parent of itself. * * */ CANNOT_ADD_SAME_NETWORK_AS_DELEGATION_CHILD, /** * * The MCM parent network has exceeded the system limit of child networks. * * */ MAX_APPROVED_DELEGATION_CHILD_NETWORKS_EXCEEDED, /** * * The MCM parent network has exceeded the system limit of child networks pending approval. * * */ MAX_PENDING_DELEGATION_CHILD_NETWORKS_EXCEEDED, /** * * The network is already being managed by the parent network for MCM. * * */ CHILD_NETWORK_ALREADY_EXISTS, /** * * Only Ad Manager 360 networks are allowed to manage the inventory of other networks. * * */ IN_PARENT_DELEGATION_UNSUPPORTED_FOR_NETWORK; public String value() { return name(); } public static NetworkErrorReason fromValue(String v) { return valueOf(v); } }
/* * 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.collections4; import java.util.Collection; import java.util.Comparator; import org.apache.commons.collections4.comparators.BooleanComparator; import org.apache.commons.collections4.comparators.ComparableComparator; import org.apache.commons.collections4.comparators.ComparatorChain; import org.apache.commons.collections4.comparators.NullComparator; import org.apache.commons.collections4.comparators.ReverseComparator; import org.apache.commons.collections4.comparators.TransformingComparator; /** * Provides convenient static utility methods for <Code>Comparator</Code> * objects. * <p> * Most of the functionality in this class can also be found in the * <code>comparators</code> package. This class merely provides a * convenient central place if you have use for more than one class * in the <code>comparators</code> subpackage. * * @since 2.1 * @version $Id: ComparatorUtils.java 1591832 2014-05-02 08:58:40Z tn $ */ public class ComparatorUtils { /** * ComparatorUtils should not normally be instantiated. */ private ComparatorUtils() {} /** * Comparator for natural sort order. * * @see ComparableComparator#comparableComparator() */ @SuppressWarnings({ "rawtypes", "unchecked" }) // explicit type needed for Java 1.5 compilation public static final Comparator NATURAL_COMPARATOR = ComparableComparator.<Comparable>comparableComparator(); /** * Gets a comparator that uses the natural order of the objects. * * @param <E> the object type to compare * @return a comparator which uses natural order */ @SuppressWarnings("unchecked") public static <E extends Comparable<? super E>> Comparator<E> naturalComparator() { return NATURAL_COMPARATOR; } /** * Gets a comparator that compares using an array of {@link Comparator}s, applied * in sequence until one returns not equal or the array is exhausted. * * @param <E> the object type to compare * @param comparators the comparators to use, not null or empty or containing nulls * @return a {@link ComparatorChain} formed from the input comparators * @throws NullPointerException if comparators array is null or contains a null * @see ComparatorChain */ public static <E> Comparator<E> chainedComparator(final Comparator<E>... comparators) { final ComparatorChain<E> chain = new ComparatorChain<E>(); for (final Comparator<E> comparator : comparators) { if (comparator == null) { throw new NullPointerException("Comparator cannot be null"); } chain.addComparator(comparator); } return chain; } /** * Gets a comparator that compares using a collection of {@link Comparator}s, * applied in (default iterator) sequence until one returns not equal or the * collection is exhausted. * * @param <E> the object type to compare * @param comparators the comparators to use, not null or empty or containing nulls * @return a {@link ComparatorChain} formed from the input comparators * @throws NullPointerException if comparators collection is null or contains a null * @throws ClassCastException if the comparators collection contains the wrong object type * @see ComparatorChain */ @SuppressWarnings("unchecked") public static <E> Comparator<E> chainedComparator(final Collection<Comparator<E>> comparators) { return chainedComparator( (Comparator<E>[]) comparators.toArray(new Comparator[comparators.size()]) ); } /** * Gets a comparator that reverses the order of the given comparator. * * @param <E> the object type to compare * @param comparator the comparator to reverse * @return a comparator that reverses the order of the input comparator * @see ReverseComparator */ public static <E> Comparator<E> reversedComparator(final Comparator<E> comparator) { return new ReverseComparator<E>(comparator); } /** * Gets a Comparator that can sort Boolean objects. * <p> * The parameter specifies whether true or false is sorted first. * <p> * The comparator throws NullPointerException if a null value is compared. * * @param trueFirst when <code>true</code>, sort * <code>true</code> {@link Boolean}s before * <code>false</code> {@link Boolean}s. * @return a comparator that sorts booleans */ public static Comparator<Boolean> booleanComparator(final boolean trueFirst) { return BooleanComparator.booleanComparator(trueFirst); } /** * Gets a Comparator that controls the comparison of <code>null</code> values. * <p> * The returned comparator will consider a null value to be less than * any nonnull value, and equal to any other null value. Two nonnull * values will be evaluated with the given comparator. * * @param <E> the object type to compare * @param comparator the comparator that wants to allow nulls * @return a version of that comparator that allows nulls * @see NullComparator */ @SuppressWarnings("unchecked") public static <E> Comparator<E> nullLowComparator(Comparator<E> comparator) { if (comparator == null) { comparator = NATURAL_COMPARATOR; } return new NullComparator<E>(comparator, false); } /** * Gets a Comparator that controls the comparison of <code>null</code> values. * <p> * The returned comparator will consider a null value to be greater than * any nonnull value, and equal to any other null value. Two nonnull * values will be evaluated with the given comparator. * * @param <E> the object type to compare * @param comparator the comparator that wants to allow nulls * @return a version of that comparator that allows nulls * @see NullComparator */ @SuppressWarnings("unchecked") public static <E> Comparator<E> nullHighComparator(Comparator<E> comparator) { if (comparator == null) { comparator = NATURAL_COMPARATOR; } return new NullComparator<E>(comparator, true); } /** * Gets a Comparator that passes transformed objects to the given comparator. * <p> * Objects passed to the returned comparator will first be transformed * by the given transformer before they are compared by the given * comparator. * * @param <I> the input object type of the transformed comparator * @param <O> the object type of the decorated comparator * @param comparator the sort order to use * @param transformer the transformer to use * @return a comparator that transforms its input objects before comparing them * @see TransformingComparator */ @SuppressWarnings("unchecked") public static <I, O> Comparator<I> transformedComparator(Comparator<O> comparator, final Transformer<? super I, ? extends O> transformer) { if (comparator == null) { comparator = NATURAL_COMPARATOR; } return new TransformingComparator<I, O>(transformer, comparator); } /** * Returns the smaller of the given objects according to the given * comparator, returning the second object if the comparator * returns equal. * * @param <E> the object type to compare * @param o1 the first object to compare * @param o2 the second object to compare * @param comparator the sort order to use * @return the smaller of the two objects */ @SuppressWarnings("unchecked") public static <E> E min(final E o1, final E o2, Comparator<E> comparator) { if (comparator == null) { comparator = NATURAL_COMPARATOR; } final int c = comparator.compare(o1, o2); return c < 0 ? o1 : o2; } /** * Returns the larger of the given objects according to the given * comparator, returning the second object if the comparator * returns equal. * * @param <E> the object type to compare * @param o1 the first object to compare * @param o2 the second object to compare * @param comparator the sort order to use * @return the larger of the two objects */ @SuppressWarnings("unchecked") public static <E> E max(final E o1, final E o2, Comparator<E> comparator) { if (comparator == null) { comparator = NATURAL_COMPARATOR; } final int c = comparator.compare(o1, o2); return c > 0 ? o1 : o2; } }
package de.pcps.jamtugether.timer; import androidx.annotation.NonNull; import de.pcps.jamtugether.timer.base.BaseJamTimer; import timber.log.Timber; public class JamCountDownTimer extends BaseJamTimer { public JamCountDownTimer(long startMillis, long interval, @NonNull OnTickCallback callback) { super(startMillis, 0, -interval, callback); Timber.d("JamCountDownTimer()"); } @Override public void start() { super.start(); Timber.d("start()"); } @Override public void stop() { super.stop(); Timber.d("stop()"); } }
package jibet.zenhao.melon.mixin.client; import melon.0d.melon.0P; import melon.3.melon.0; import melon.q.melon.c; import net.minecraft.client.gui.GuiChat; import net.minecraft.client.gui.GuiTextField; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; @Mixin({GuiChat.class}) public abstract class MixinGuiChat { @Shadow protected GuiTextField field_146415_a; @Shadow public String field_146410_g; @Shadow public int field_146416_h; @Shadow public abstract void func_73866_w_(); @Inject( method = {"Lnet/minecraft/client/gui/GuiChat;keyTyped(CI)V"}, at = {@At("RETURN")} ) public void returnKeyTyped(char var1, int var2, CallbackInfo var3) { if (0P.getMinecraft().field_71462_r instanceof GuiChat && !(0P.getMinecraft().field_71462_r instanceof c)) { if (this.field_146415_a.func_146179_b().startsWith(0.getCommandPrefix())) { 0P.getMinecraft().func_147108_a(new c(this.field_146415_a.func_146179_b(), this.field_146410_g, this.field_146416_h)); } } } }
/* * Copyright (C) 2015 Piotr Wittchen * * 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.github.pwittchen.reactivenetwork.library; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.wifi.ScanResult; import android.net.wifi.WifiManager; import android.os.Looper; import java.io.IOException; import java.net.InetSocketAddress; import java.net.Socket; import java.util.List; import java.util.concurrent.TimeUnit; import rx.Observable; import rx.Scheduler; import rx.Subscriber; import rx.Subscription; import rx.android.schedulers.AndroidSchedulers; import rx.functions.Action0; import rx.functions.Func1; import rx.schedulers.Schedulers; import rx.subscriptions.Subscriptions; /** * ReactiveNetwork is an Android library * listening network connection state and change of the WiFi signal strength * with RxJava Observables. It can be easily used with RxAndroid. */ public class ReactiveNetwork { private static final String DEFAULT_PING_HOST = "www.google.com"; private static final int DEFAULT_PING_PORT = 80; private static final int DEFAULT_PING_INTERVAL_IN_MS = 2000; private static final int DEFAULT_PING_TIMEOUT_IN_MS = 2000; private ConnectivityStatus status = ConnectivityStatus.UNKNOWN; /** * Observes ConnectivityStatus, * which can be WIFI_CONNECTED, MOBILE_CONNECTED or OFFLINE * * @param context Context of the activity or an application * @return RxJava Observable with ConnectivityStatus */ public Observable<ConnectivityStatus> observeNetworkConnectivity(final Context context) { final IntentFilter filter = new IntentFilter(); filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION); return Observable.create(new Observable.OnSubscribe<ConnectivityStatus>() { @Override public void call(final Subscriber<? super ConnectivityStatus> subscriber) { final BroadcastReceiver receiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { final ConnectivityStatus newStatus = getConnectivityStatus(context); // we need to perform check below, // because after going off-line, onReceive() is called twice if (newStatus != status) { status = newStatus; subscriber.onNext(newStatus); } } }; context.registerReceiver(receiver, filter); subscriber.add(unsubscribeInUiThread(new Action0() { @Override public void call() { context.unregisterReceiver(receiver); } })); } }).defaultIfEmpty(ConnectivityStatus.OFFLINE); } /** * Gets current network connectivity status * * @param context Application Context is recommended here * @return ConnectivityStatus, which can be WIFI_CONNECTED, MOBILE_CONNECTED or OFFLINE */ public ConnectivityStatus getConnectivityStatus(final Context context) { final String service = Context.CONNECTIVITY_SERVICE; final ConnectivityManager manager = (ConnectivityManager) context.getSystemService(service); final NetworkInfo networkInfo = manager.getActiveNetworkInfo(); if (networkInfo == null) { return ConnectivityStatus.OFFLINE; } if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) { return ConnectivityStatus.WIFI_CONNECTED; } else if (networkInfo.getType() == ConnectivityManager.TYPE_MOBILE) { return ConnectivityStatus.MOBILE_CONNECTED; } return ConnectivityStatus.OFFLINE; } /** * Observes connectivity with the Internet with default settings. It pings remote host * (www.google.com) at port 80 every 2 seconds with 2 seconds of timeout. This operation is used * for determining if device is connected to the Internet or not. Please note that this method is * less efficient than {@link #observeNetworkConnectivity(Context)} method and consumes data * transfer, but it gives you actual information if device is connected to the Internet or not. * * @return RxJava Observable with Boolean - true, when we have an access to the Internet * and false if not */ public Observable<Boolean> observeInternetConnectivity() { return observeInternetConnectivity(DEFAULT_PING_INTERVAL_IN_MS, DEFAULT_PING_HOST, DEFAULT_PING_PORT, DEFAULT_PING_TIMEOUT_IN_MS); } /** * Observes connectivity with the Internet by opening socket connection with remote host * * @param interval in milliseconds determining how often we want to check connectivity * @param host for checking Internet connectivity * @param port for checking Internet connectivity * @param timeout for pinging remote host * @return RxJava Observable with Boolean - true, when we have connection with host and false if * not */ public Observable<Boolean> observeInternetConnectivity(final int interval, final String host, final int port, final int timeout) { return Observable.interval(interval, TimeUnit.MILLISECONDS, Schedulers.io()) .map(new Func1<Long, Boolean>() { @Override public Boolean call(Long tick) { try { Socket socket = new Socket(); socket.connect(new InetSocketAddress(host, port), timeout); return socket.isConnected(); } catch (IOException e) { return Boolean.FALSE; } } }) .distinctUntilChanged(); } /** * Observes WiFi Access Points. * Returns fresh list of Access Points * whenever WiFi signal strength changes. * * @param context Context of the activity or an application * @return RxJava Observable with list of WiFi scan results */ public Observable<List<ScanResult>> observeWifiAccessPoints(final Context context) { final WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); wifiManager.startScan(); // without starting scan, we may never receive any scan results final IntentFilter filter = new IntentFilter(); filter.addAction(WifiManager.RSSI_CHANGED_ACTION); filter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION); return Observable.create(new Observable.OnSubscribe<List<ScanResult>>() { @Override public void call(final Subscriber<? super List<ScanResult>> subscriber) { final BroadcastReceiver receiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { wifiManager.startScan(); // we need to start scan again to get fresh results ASAP subscriber.onNext(wifiManager.getScanResults()); } }; context.registerReceiver(receiver, filter); subscriber.add(unsubscribeInUiThread(new Action0() { @Override public void call() { context.unregisterReceiver(receiver); } })); } }); } /** * Observes WiFi signal level with predefined max num levels. * Returns WiFi signal level as enum with information about current level * * @param context Context of the activity or an application * @return WifiSignalLevel as an enum */ public Observable<WifiSignalLevel> observeWifiSignalLevel(final Context context) { return observeWifiSignalLevel(context, WifiSignalLevel.getMaxLevel()).map( new Func1<Integer, WifiSignalLevel>() { @Override public WifiSignalLevel call(Integer level) { return WifiSignalLevel.fromLevel(level); } }); } /** * Observes WiFi signal level. * Returns WiFi signal level as an integer * * @param context Context of the activity or an application * @param numLevels The number of levels to consider in the calculated level as Integer * @return RxJava Observable with WiFi signal level */ public Observable<Integer> observeWifiSignalLevel(final Context context, final int numLevels) { final WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); final IntentFilter filter = new IntentFilter(); filter.addAction(WifiManager.RSSI_CHANGED_ACTION); return Observable.create(new Observable.OnSubscribe<Integer>() { @Override public void call(final Subscriber<? super Integer> subscriber) { final BroadcastReceiver receiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { final int rssi = wifiManager.getConnectionInfo().getRssi(); final int level = WifiManager.calculateSignalLevel(rssi, numLevels); subscriber.onNext(level); } }; context.registerReceiver(receiver, filter); subscriber.add(unsubscribeInUiThread(new Action0() { @Override public void call() { context.unregisterReceiver(receiver); } })); } }).defaultIfEmpty(0); } private Subscription unsubscribeInUiThread(final Action0 unsubscribe) { return Subscriptions.create(new Action0() { @Override public void call() { if (Looper.getMainLooper() == Looper.myLooper()) { unsubscribe.call(); } else { final Scheduler.Worker inner = AndroidSchedulers.mainThread().createWorker(); inner.schedule(new Action0() { @Override public void call() { unsubscribe.call(); inner.unsubscribe(); } }); } } }); } }
/* * Copyright 2021 Google LLC * * 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 jqweb; import java.util.stream.Collectors; import javax.inject.Singleton; import com.arakelian.jq.*; @Singleton public class JqService { private static final JqLibrary jqLib = ImmutableJqLibrary.of(); String filter(String inputJson, String jqFilter) throws Exception { final JqRequest request = ImmutableJqRequest.builder() .lib(jqLib) .input(inputJson) .filter(jqFilter) .build(); final JqResponse response = request.execute(); if(response.hasErrors()) { throw new Exception(response.getErrors().stream().collect(Collectors.joining(", "))); } final String output = response.getOutput(); System.out.println("JQ output: " + output); return output; } }
/* * Copyright (c) 2014-2020 by The Monix Project Developers. * See the project homepage at: https://monix.io * * 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 monix.execution.internal.atomic; import monix.execution.internal.InternalApi; import java.util.concurrent.atomic.AtomicIntegerFieldUpdater; /** * INTERNAL API — used in the implementation of * `monix.execution.atomic.Atomic`. * * Being internal it can always change between minor versions, * providing no backwards compatibility guarantees and is only public * because Java does not provide the capability of marking classes as * "internal" to a package and all its sub-packages. */ @InternalApi final class Right128JavaXBoxedInt extends Right128JavaXBoxedIntImpl { public volatile long p1, p2, p3, p4, p5, p6, p7, p8 = 7; public volatile long p9, p10, p11, p12, p13, p14, p15 = 7; public long sum() { return p1 + p2 + p3 + p4 + p5 + p6 + p7 + p8 + p9 + p10 + p11 + p12 + p13 + p14 + p15; } Right128JavaXBoxedInt(int initialValue) { super(initialValue); } } /** * INTERNAL API — used in the implementation of * `monix.execution.atomic.Atomic`. * * Being internal it can always change between minor versions, * providing no backwards compatibility guarantees and is only public * because Java does not provide the capability of marking classes as * "internal" to a package and all its sub-packages. */ @InternalApi abstract class Right128JavaXBoxedIntImpl implements BoxedInt { public volatile int value; private static final AtomicIntegerFieldUpdater<Right128JavaXBoxedIntImpl> UPDATER = AtomicIntegerFieldUpdater.newUpdater(Right128JavaXBoxedIntImpl.class, "value"); Right128JavaXBoxedIntImpl(int initialValue) { this.value = initialValue; } public int volatileGet() { return value; } public void volatileSet(int update) { value = update; } public void lazySet(int update) { UPDATER.lazySet(this, update); } public boolean compareAndSet(int current, int update) { return UPDATER.compareAndSet(this, current, update); } public int getAndSet(int update) { return UPDATER.getAndSet(this, update); } public int getAndAdd(int delta) { return UPDATER.getAndAdd(this, delta); } }
/** * Licensed to Jasig under one or more contributor license * agreements. See the NOTICE file distributed with this work * for additional information regarding copyright ownership. * Jasig licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a * copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.jasig.portal.portlets; import java.io.Serializable; public class BooleanAttribute implements Serializable { private static final long serialVersionUID = 1L; private boolean value; public BooleanAttribute() { } public BooleanAttribute(boolean value) { this.value = value; } /** * @return the value */ public boolean getValue() { return value; } /** * @param value the value to set */ public void setValue(boolean value) { this.value = value; } /* (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { return String.valueOf(this.value); } }
package me.jacob.Leaf.engine; import java.awt.Graphics2D; import javax.swing.JPanel; @SuppressWarnings("serial") public abstract class Object extends JPanel { public abstract void draw(Graphics2D g2); public abstract void update(double delta); public abstract double getLocX(); public abstract double getLocY(); }
/* * 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 ed.biodare2.backend.features.onto.species; import java.nio.file.Files; import java.nio.file.Path; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; import org.junit.Rule; import org.junit.rules.TemporaryFolder; /** * * @author tzielins */ public class SpeciesServiceTest { @Rule public TemporaryFolder testFolder = new TemporaryFolder(); Path configFile; SpeciesService service; public SpeciesServiceTest() { } @Before public void setUp() throws Exception { configFile = testFolder.newFile().toPath(); service = new SpeciesService(configFile.toString()); } @Test public void testSetupWork() { assertNotNull(service); } @Test public void findAllReturnsNotBackedValue() { List<String> species = service.findAll(); species.add("new one"); List<String> known = service.findAll(); assertEquals(known, service.findAll()); assertNotEquals(known, species); } @Test public void readSpeciesReadsListFromFileStripingSpacesAndOrdering() throws Exception { Path tFile = testFolder.newFile().toPath(); List<String> content = Arrays.asList("Species 1 ","Species 2",""," Species 3","A"," "); Files.write(tFile, content); List<String> expected = Arrays.asList("A","Species 1","Species 2", "Species 3"); assertEquals(expected, service.readSpecies(tFile)); } @Test public void updateReplaceKnownWithContentOfConfigFile() throws Exception { List<String> exp = Collections.emptyList(); assertEquals(exp, service.findAll()); List<String> content = Arrays.asList("Species 1","Species 2"); Files.write(configFile, content); service.updateKnown(); assertEquals(content, service.findAll()); content = Arrays.asList("Species 3"); Files.write(configFile, content); service.updateKnown(); assertEquals(content, service.findAll()); } }
package de.siphalor.spiceoffabric.client.mixin; import de.siphalor.spiceoffabric.SpiceOfFabric; import de.siphalor.spiceoffabric.config.Config; import de.siphalor.spiceoffabric.foodhistory.FoodHistoryEntry; import de.siphalor.spiceoffabric.util.IHungerManager; import net.minecraft.client.MinecraftClient; import net.minecraft.client.item.TooltipContext; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.text.Text; import net.minecraft.text.TranslatableText; import net.minecraft.world.World; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import java.util.List; @Mixin(Item.class) public abstract class MixinItem { @Shadow public abstract boolean isFood(); @Inject(method = "appendTooltip", at = @At("HEAD")) public void appendTooltip(ItemStack stack, World world, List<Text> texts, TooltipContext tooltipContext, CallbackInfo callbackInfo) { PlayerEntity playerEntity = MinecraftClient.getInstance().player; if(isFood() && Config.carrotEnabled.value && playerEntity != null && !((IHungerManager) playerEntity.getHungerManager()).spiceOfFabric_getFoodHistory().carrotHistory.contains(FoodHistoryEntry.fromItemStack(stack))) { texts.add(new TranslatableText(SpiceOfFabric.MOD_ID + ".item.tooltip.never_eaten")); } } }
/*- * #%L * athena-hbase * %% * Copyright (C) 2019 - 2020 Amazon Web Services * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ package com.amazonaws.athena.connectors.hbase.connection; import com.google.common.annotations.VisibleForTesting; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.HRegionInfo; import org.apache.hadoop.hbase.NamespaceDescriptor; import org.apache.hadoop.hbase.TableName; import org.apache.hadoop.hbase.client.Admin; import org.apache.hadoop.hbase.client.Connection; import org.apache.hadoop.hbase.client.ConnectionFactory; import org.apache.hadoop.hbase.client.ResultScanner; import org.apache.hadoop.hbase.client.Scan; import org.apache.hadoop.hbase.client.Table; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.List; import java.util.concurrent.Callable; /** * This class wraps Hbase's Connection construct and provides both a simplified facade for common operations * but also automatic retry and reconnect logic to make client reuse simpler. Some specific cases that this * construct handles are: replacement of an HBase region server, replacement of HBase master server, other * transient errors while communicating with HBase. */ public class HBaseConnection { private static final Logger logger = LoggerFactory.getLogger(HBaseConnection.class); private final Configuration config; private final int maxRetries; private int retries = 0; private Connection connection; /** * Used by HBaseConnectionFactory to construct new connections. * * @param config The HBase config to use for this connection. * @param maxRetries The max retries this connection will allow before marking itself unhealthy. */ protected HBaseConnection(Configuration config, int maxRetries) { this.config = config; this.maxRetries = maxRetries; this.connection = connect(config); } /** * Used to facilitate testing by allowing for injection of the underlying HBase connection. * * @param connection The actual Hbase connection to use. * @param maxRetries The max retries this connection will allow before marking itself unhealthy. */ @VisibleForTesting protected HBaseConnection(Connection connection, int maxRetries) { this.config = null; this.maxRetries = maxRetries; this.connection = connection; } /** * Used to determine if this connection can be reused or if it is unhealthy. * * @return True if the connection can be safely reused, false otherwise. */ public synchronized boolean isHealthy() { return retries < maxRetries; } /** * Lists the available namespaces in the HBase instance. * * @return Array of NamespaceDescriptor representing the available namespaces in the HBase instance. * @throws IOException */ public NamespaceDescriptor[] listNamespaceDescriptors() throws IOException { return callWithReconnectAndRetry(() -> { Admin admin = getConnection().getAdmin(); return admin.listNamespaceDescriptors(); }); } /** * Lists the table names present in the given schema (aka namespace) * * @param schemaName The schema name (aka hbase namespace) to list table names from. * @return An array of hbase TableName objects for the given schema name. */ public TableName[] listTableNamesByNamespace(String schemaName) { return callWithReconnectAndRetry(() -> { Admin admin = getConnection().getAdmin(); return admin.listTableNamesByNamespace(schemaName); }); } /** * Retreieves the regions for the requested TableName. * * @param tableName The fully qualified HBase TableName for which we should obtain region info. * @return List of HRegionInfo representing the regions hosting the requested table. */ public List<HRegionInfo> getTableRegions(TableName tableName) { return callWithReconnectAndRetry(() -> { Admin admin = getConnection().getAdmin(); return admin.getTableRegions(tableName); }); } /** * Used to perform a scan of the given table, scan, and resultProcessor. * * @param tableName The HBase table to scan. * @param scan The HBase scan (filters, etc...) to run. * @param resultProcessor The ResultProcessor that will be used to process the results of the scan. * @param <T> The return type of the ResultProcessor and this this method. * @return The result produced by the resultProcessor when it has completed processing all results of the scan. */ public <T> T scanTable(TableName tableName, Scan scan, ResultProcessor<T> resultProcessor) { return callWithReconnectAndRetry(() -> { try (Table table = connection.getTable(tableName); ResultScanner scanner = table.getScanner(scan)) { try { return resultProcessor.scan(scanner); } catch (RuntimeException ex) { throw new UnrecoverableException("Scanner threw exception - " + ex.getMessage(), ex); } } }); } /** * Used to close this connection by closing the underlying HBase Connection. */ protected void close() { try { if (connection != null) { connection.close(); } } catch (IOException | RuntimeException ex) { logger.warn("close: Exception while closing connection."); } } @VisibleForTesting protected int getRetries() { return retries; } /** * Used to invoke operations with HBase reconnect and retry logic. * * @param callable The callable to invoke and monitor for errors. * @param <T> The return type of the callable. * @return The result of the callable, if it was successfull. * @note This retry logic needs to be adjusted for 'write' usecases. */ private <T> T callWithReconnectAndRetry(Callable<T> callable) { while (isHealthy()) { try { return callable.call(); } catch (RuntimeException ex) { logger.warn("Exception while calling hbase, will attempt to reconnect and retry.", ex); reconnect(); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); throw new RuntimeException(ex); } catch (UnrecoverableException ex) { throw new RuntimeException(ex); } catch (Exception ex) { throw new RuntimeException(ex); } } throw new RuntimeException("Exhausted hbase retries..."); } /** * Creates a new HBase connection using the provided config. * * @param config The config to use for the new HBase connection. * @return The new connection. */ @VisibleForTesting protected synchronized Connection connect(Configuration config) { try { Connection conn = ConnectionFactory.createConnection(config); logger.info("connect: hbase.zookeeper.quorum:" + config.get("hbase.zookeeper.quorum")); logger.info("connect: hbase.zookeeper.property.clientPort:" + config.get("hbase.zookeeper.property.clientPort")); logger.info("connect: hbase.master:" + config.get("hbase.master")); return conn; } catch (IOException ex) { throw new RuntimeException(ex); } } /** * Used to reconnect to HBase by freeing existing connection resources, incrementing retry metrics, and ultimately * creating the new connection. * * @return The new connection. */ private synchronized Connection reconnect() { retries++; close(); try { connection = connect(config); } catch (RuntimeException ex) { logger.warn("reConnect: Exception while reconnecting, marking connection as unhealthy and throwing.", ex); retries = maxRetries; throw ex; } return connection; } /** * Provides access to the current connection if present and healthy. * * @return The underlying HBase connection. */ private synchronized Connection getConnection() { if (connection == null || !isHealthy()) { throw new RuntimeException("Invalid connection"); } return connection; } }
package com.kodedu.service.ui; import com.kodedu.service.PathResolverService; import javafx.scene.Node; import javafx.scene.control.Label; import org.kordamp.ikonli.fontawesome.FontAwesome; import org.kordamp.ikonli.javafx.FontIcon; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.nio.file.Files; import java.nio.file.Path; /** * Created by usta on 16.12.2014. */ @Component public class AwesomeService { private final PathResolverService pathResolver; @Autowired public AwesomeService(final PathResolverService pathResolver) { this.pathResolver = pathResolver; } public Node getIcon(final Path path) { FontIcon fontIcon = new FontIcon(FontAwesome.FILE_O); if (Files.isDirectory(path)) { fontIcon.setIconCode(FontAwesome.FOLDER_O); } else { if (pathResolver.isAsciidoc(path) || pathResolver.isMarkdown(path)) fontIcon.setIconCode(FontAwesome.FILE_TEXT_O); if (pathResolver.isXML(path) || pathResolver.isCode(path)) fontIcon.setIconCode(FontAwesome.FILE_CODE_O); if (pathResolver.isImage(path)) fontIcon.setIconCode(FontAwesome.FILE_PICTURE_O); if (pathResolver.isPDF(path)) fontIcon.setIconCode(FontAwesome.FILE_PDF_O); if (pathResolver.isHTML(path)) fontIcon.setIconCode(FontAwesome.HTML5); if (pathResolver.isArchive(path)) fontIcon.setIconCode(FontAwesome.FILE_ZIP_O); if (pathResolver.isExcel(path)) fontIcon.setIconCode(FontAwesome.FILE_EXCEL_O); if (pathResolver.isVideo(path)) fontIcon.setIconCode(FontAwesome.FILE_VIDEO_O); if (pathResolver.isWord(path)) fontIcon.setIconCode(FontAwesome.FILE_WORD_O); if (pathResolver.isPPT(path)) fontIcon.setIconCode(FontAwesome.FILE_POWERPOINT_O); if (pathResolver.isBash(path)) fontIcon.setIconCode(FontAwesome.TERMINAL); } return new Label(null, fontIcon); } }
/** * Copyright (C) 2010, FuseSource Corp. All rights reserved. */ package org.fusesource.hawtdispatch; /** * <p> * We prefer the use of Task over Runnable since the * JVM can more efficiently invoke methods of * an abstract class than a interface. * </p> * * @author <a href="http://hiramchirino.com">Hiram Chirino</a> */ public abstract class Task implements Runnable { abstract public void run(); }
/* * Copyright 2018 IntraFind Software AG. 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.intrafind.sitesearch.controller; import com.intrafind.sitesearch.dto.Hits; import com.intrafind.sitesearch.service.SearchService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.CookieValue; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import java.time.Instant; import java.util.UUID; @RestController public class SearchController { public static final String ENDPOINT = "/search"; private static final Logger LOG = LoggerFactory.getLogger(SearchController.class); private final SearchService service; @Autowired private SearchController(SearchService service) { this.service = service; } @RequestMapping(path = ENDPOINT, method = RequestMethod.GET) private ResponseEntity<Hits> searchDeprecatedAPI( @CookieValue(value = "override-site", required = false) UUID cookieSite, @RequestParam(value = "query", defaultValue = "") String query, @RequestParam(value = "siteId") UUID siteId ) { final Instant start = Instant.now(); if (query.isEmpty()) return ResponseEntity.badRequest().build(); // override siteId with cookie value for debugging & speed up the getting started experience if (cookieSite != null) { siteId = cookieSite; } Hits searchResult = service.search(query, siteId); final Instant stop = Instant.now(); final Instant searchDuration = stop.minusMillis(start.toEpochMilli()); LOG.info("siteId: " + siteId + " - query: " + query + " - results: " + searchResult.getResults().size() + " - searchDurationInMs: " + searchDuration.toEpochMilli()); return ResponseEntity.ok(searchResult); } }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hdfs.server.blockmanagement; import static org.junit.Assert.assertTrue; import java.util.Collection; import java.util.concurrent.TimeoutException; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hdfs.DFSConfigKeys; import org.apache.hadoop.hdfs.DFSTestUtil; import org.apache.hadoop.hdfs.HdfsConfiguration; import org.apache.hadoop.hdfs.MiniDFSCluster; import org.apache.hadoop.hdfs.MiniDFSCluster.DataNodeProperties; import org.apache.hadoop.hdfs.protocol.Block; import org.apache.hadoop.hdfs.protocol.ExtendedBlock; import org.apache.hadoop.hdfs.server.namenode.FSNamesystem; import org.apache.hadoop.util.Time; import org.junit.Test; /** * Test if live nodes count per node is correct * so NN makes right decision for under/over-replicated blocks */ public class TestNodeCount { final short REPLICATION_FACTOR = (short)2; final long TIMEOUT = 20000L; long timeout = 0; long failtime = 0; Block lastBlock = null; NumberReplicas lastNum = null; @Test(timeout = 60000) public void testNodeCount() throws Exception { final Configuration conf = new HdfsConfiguration(); // avoid invalidation by startup delay in order to make test non-transient conf.setInt(DFSConfigKeys.DFS_NAMENODE_STARTUP_DELAY_BLOCK_DELETION_SEC_KEY, 60); // reduce intervals to make test execution time shorter conf.setInt(DFSConfigKeys.DFS_NAMENODE_REPLICATION_INTERVAL_KEY, 1); conf.setInt(DFSConfigKeys.DFS_HEARTBEAT_INTERVAL_KEY, 1); // start a mini dfs cluster of 2 nodes final MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf).numDataNodes(REPLICATION_FACTOR).build(); try { final FSNamesystem namesystem = cluster.getNamesystem(); final BlockManager bm = namesystem.getBlockManager(); final HeartbeatManager hm = bm.getDatanodeManager().getHeartbeatManager(); final FileSystem fs = cluster.getFileSystem(); // populate the cluster with a one block file final Path FILE_PATH = new Path("/testfile"); DFSTestUtil.createFile(fs, FILE_PATH, 1L, REPLICATION_FACTOR, 1L); DFSTestUtil.waitReplication(fs, FILE_PATH, REPLICATION_FACTOR); ExtendedBlock block = DFSTestUtil.getFirstBlock(fs, FILE_PATH); // keep a copy of all datanode descriptor final DatanodeDescriptor[] datanodes = hm.getDatanodes(); // start two new nodes cluster.startDataNodes(conf, 2, true, null, null); cluster.waitActive(); // bring down first datanode DatanodeDescriptor datanode = datanodes[0]; DataNodeProperties dnprop = cluster.stopDataNode(datanode.getXferAddr()); // make sure that NN detects that the datanode is down BlockManagerTestUtil.noticeDeadDatanode( cluster.getNameNode(), datanode.getXferAddr()); // the block will be replicated DFSTestUtil.waitReplication(fs, FILE_PATH, REPLICATION_FACTOR); // restart the first datanode cluster.restartDataNode(dnprop); cluster.waitActive(); // check if excessive replica is detected initializeTimeout(TIMEOUT); while (countNodes(block.getLocalBlock(), namesystem).excessReplicas() == 0) { checkTimeout("excess replicas not detected"); } // find out a non-excess node DatanodeDescriptor nonExcessDN = null; for(DatanodeStorageInfo storage : bm.blocksMap.getStorages(block.getLocalBlock())) { final DatanodeDescriptor dn = storage.getDatanodeDescriptor(); Collection<Block> blocks = bm.excessReplicateMap.get(dn.getDatanodeUuid()); if (blocks == null || !blocks.contains(block.getLocalBlock()) ) { nonExcessDN = dn; break; } } assertTrue(nonExcessDN!=null); // bring down non excessive datanode dnprop = cluster.stopDataNode(nonExcessDN.getXferAddr()); // make sure that NN detects that the datanode is down BlockManagerTestUtil.noticeDeadDatanode( cluster.getNameNode(), nonExcessDN.getXferAddr()); // The block should be replicated initializeTimeout(TIMEOUT); while (countNodes(block.getLocalBlock(), namesystem).liveReplicas() != REPLICATION_FACTOR) { checkTimeout("live replica count not correct", 1000); } // restart the first datanode cluster.restartDataNode(dnprop); cluster.waitActive(); // check if excessive replica is detected initializeTimeout(TIMEOUT); while (countNodes(block.getLocalBlock(), namesystem).excessReplicas() != 2) { checkTimeout("excess replica count not equal to 2"); } } finally { cluster.shutdown(); } } void initializeTimeout(long timeout) { this.timeout = timeout; this.failtime = Time.now() + ((timeout <= 0) ? Long.MAX_VALUE : timeout); } void checkTimeout(String testLabel) throws TimeoutException { checkTimeout(testLabel, 10); } /* check for timeout, then wait for cycleTime msec */ void checkTimeout(String testLabel, long cycleTime) throws TimeoutException { if (Time.now() > failtime) { throw new TimeoutException("Timeout: " + testLabel + " for block " + lastBlock + " after " + timeout + " msec. Last counts: live = " + lastNum.liveReplicas() + ", excess = " + lastNum.excessReplicas() + ", corrupt = " + lastNum.corruptReplicas()); } if (cycleTime > 0) { try { Thread.sleep(cycleTime); } catch (InterruptedException ie) { //ignore } } } /* threadsafe read of the replication counts for this block */ NumberReplicas countNodes(Block block, FSNamesystem namesystem) { BlockManager blockManager = namesystem.getBlockManager(); namesystem.readLock(); try { lastBlock = block; lastNum = blockManager.countNodes(blockManager.getStoredBlock(block)); return lastNum; } finally { namesystem.readUnlock(); } } }
package com.cloud.mall.member.service.impl; import org.springframework.stereotype.Service; import java.util.Map; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.cloud.common.utils.PageUtils; import com.cloud.common.utils.Query; import com.cloud.mall.member.dao.MemberReceiveAddressDao; import com.cloud.mall.member.entity.MemberReceiveAddressEntity; import com.cloud.mall.member.service.MemberReceiveAddressService; @Service("memberReceiveAddressService") public class MemberReceiveAddressServiceImpl extends ServiceImpl<MemberReceiveAddressDao, MemberReceiveAddressEntity> implements MemberReceiveAddressService { @Override public PageUtils queryPage(Map<String, Object> params) { IPage<MemberReceiveAddressEntity> page = this.page( new Query<MemberReceiveAddressEntity>().getPage(params), new QueryWrapper<MemberReceiveAddressEntity>() ); return new PageUtils(page); } }
package com.atguigu.gulimall.search.controller; import com.atguigu.common.exception.BizCodeEnum; import com.atguigu.common.to.es.SkuEsModel; import com.atguigu.common.utils.R; import com.atguigu.gulimall.search.service.ProductSaveService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.io.IOException; import java.util.List; @RequestMapping("/search/save") @RestController public class ElasticSaveController { @Autowired private ProductSaveService productSaveService; /** * 商品上架 - 将 sku 保存到 Elasticsearch 中 */ @PostMapping("/product") public R productStatusUp(@RequestBody List<SkuEsModel> skuEsModels) { // 标识 商品是否上架成功 Boolean b = false; try { b = productSaveService.productStatusUp(skuEsModels); } catch (IOException e) { // 上架失败 return R.error(BizCodeEnum.PRODUCT_UP_EXCEPTION.getCode(), BizCodeEnum.PRODUCT_UP_EXCEPTION.getMsg()); } if (!b) { // 上架成功 return R.ok(); } else { // 上架失败 return R.error(BizCodeEnum.PRODUCT_UP_EXCEPTION.getCode(), BizCodeEnum.PRODUCT_UP_EXCEPTION.getMsg()); } } }
package com.google.ratel.deps.jackson.databind.util; import java.lang.reflect.Array; import java.util.List; /** * Helper class to use for constructing Object arrays by appending entries * to create arrays of various lengths (length that is not known a priori). */ public final class ObjectBuffer { // // // Config constants /** * Let's start with small chunks; typical usage is for small arrays anyway. */ final static int INITIAL_CHUNK_SIZE = 12; /** * Also: let's expand by doubling up until 64k chunks (which is 16k entries for * 32-bit machines) */ final static int SMALL_CHUNK_SIZE = (1 << 14); /** * Let's limit maximum size of chunks we use; helps avoid excessive allocation * overhead for huge data sets. * For now, let's limit to quarter million entries, 1 meg chunks for 32-bit * machines. */ final static int MAX_CHUNK_SIZE = (1 << 18); // // // Data storage private Node _bufferHead; private Node _bufferTail; /** * Number of total buffered entries in this buffer, counting all instances * within linked list formed by following {@link #_bufferHead}. */ private int _bufferedEntryCount; // // // Simple reuse /** * Reusable Object array, stored here after buffer has been released having * been used previously. */ private Object[] _freeBuffer; /* /********************************************************** /* Construction /********************************************************** */ public ObjectBuffer() { } /* /********************************************************** /* Public API /********************************************************** */ /** * Method called to start buffering process. Will ensure that the buffer * is empty, and then return an object array to start chunking content on */ public Object[] resetAndStart() { _reset(); if (_freeBuffer == null) { return new Object[INITIAL_CHUNK_SIZE]; } return _freeBuffer; } /** * Method called to add a full Object array as a chunk buffered within * this buffer, and to obtain a new array to fill. Caller is not to use * the array it gives; but to use the returned array for continued * buffering. * * @param fullChunk Completed chunk that the caller is requesting * to append to this buffer. It is generally chunk that was * returned by an earlier call to {@link #resetAndStart} or * {@link #appendCompletedChunk} (although this is not required or * enforced) * * @return New chunk buffer for caller to fill */ public Object[] appendCompletedChunk(Object[] fullChunk) { Node next = new Node(fullChunk); if (_bufferHead == null) { // first chunk _bufferHead = _bufferTail = next; } else { // have something already _bufferTail.linkNext(next); _bufferTail = next; } int len = fullChunk.length; _bufferedEntryCount += len; // double the size for small chunks if (len < SMALL_CHUNK_SIZE) { len += len; } else { // but by +25% for larger (to limit overhead) len += (len >> 2); } return new Object[len]; } /** * Method called to indicate that the buffering process is now * complete; and to construct a combined exactly-sized result * array. Additionally the buffer itself will be reset to * reduce memory retention. *<p> * Resulting array will be of generic <code>Object[]</code> type: * if a typed array is needed, use the method with additional * type argument. */ public Object[] completeAndClearBuffer(Object[] lastChunk, int lastChunkEntries) { int totalSize = lastChunkEntries + _bufferedEntryCount; Object[] result = new Object[totalSize]; _copyTo(result, totalSize, lastChunk, lastChunkEntries); return result; } /** * Type-safe alternative to * {@link #completeAndClearBuffer(Object[], int)}, to allow * for constructing explicitly typed result array. * * @param componentType Type of elements included in the buffer. Will be * used for constructing the result array. */ public <T> T[] completeAndClearBuffer(Object[] lastChunk, int lastChunkEntries, Class<T> componentType) { int totalSize = lastChunkEntries + _bufferedEntryCount; @SuppressWarnings("unchecked") T[] result = (T[]) Array.newInstance(componentType, totalSize); _copyTo(result, totalSize, lastChunk, lastChunkEntries); _reset(); return result; } public void completeAndClearBuffer(Object[] lastChunk, int lastChunkEntries, List<Object> resultList) { for (Node n = _bufferHead; n != null; n = n.next()) { Object[] curr = n.getData(); for (int i = 0, len = curr.length; i < len; ++i) { resultList.add(curr[i]); } } // and then the last one for (int i = 0; i < lastChunkEntries; ++i) { resultList.add(lastChunk[i]); } } /** * Helper method that can be used to check how much free capacity * will this instance start with. Can be used to choose the best * instance to reuse, based on size of reusable object chunk * buffer holds reference to. */ public int initialCapacity() { return (_freeBuffer == null) ? 0 : _freeBuffer.length; } /** * Method that can be used to check how many Objects have been buffered * within this buffer. */ public int bufferedSize() { return _bufferedEntryCount; } /* /********************************************************** /* Internal methods /********************************************************** */ protected void _reset() { // can we reuse the last (and thereby biggest) array for next time? if (_bufferTail != null) { _freeBuffer = _bufferTail.getData(); } // either way, must discard current contents _bufferHead = _bufferTail = null; _bufferedEntryCount = 0; } protected final void _copyTo(Object resultArray, int totalSize, Object[] lastChunk, int lastChunkEntries) { int ptr = 0; for (Node n = _bufferHead; n != null; n = n.next()) { Object[] curr = n.getData(); int len = curr.length; System.arraycopy(curr, 0, resultArray, ptr, len); ptr += len; } System.arraycopy(lastChunk, 0, resultArray, ptr, lastChunkEntries); ptr += lastChunkEntries; // sanity check (could have failed earlier due to out-of-bounds, too) if (ptr != totalSize) { throw new IllegalStateException("Should have gotten "+totalSize+" entries, got "+ptr); } } /* /********************************************************** /* Helper classes /********************************************************** */ /** * Helper class used to store actual data, in a linked list. */ final static class Node { /** * Data stored in this node. Array is considered to be full. */ final Object[] _data; Node _next; public Node(Object[] data) { _data = data; } public Object[] getData() { return _data; } public Node next() { return _next; } public void linkNext(Node next) { if (_next != null) { // sanity check throw new IllegalStateException(); } _next = next; } } }
package dai.hris.action.cba; import java.io.IOException; import java.math.BigDecimal; import java.sql.SQLException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.google.gson.Gson; import dai.hris.model.DisbursementVoucher; import dai.hris.service.cba.EmployeeCBAService; import dai.hris.service.cba.IEmployeeCBAService; /** * Servlet implementation class SaveDisbursementVoucherAction */ @WebServlet("/SaveDisbursementVoucherAction") public class SaveDisbursementVoucherAction extends HttpServlet { private static final long serialVersionUID = 1L; IEmployeeCBAService service = new EmployeeCBAService(); Gson gson = new Gson(); public SaveDisbursementVoucherAction() { super(); // TODO Auto-generated constructor stub } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("doPost SaveDisbursementVoucherAction"); DisbursementVoucher model = new DisbursementVoucher(); try { //BeanUtils.populate(model, request.getParameterMap()); model.setModeOfPayment(request.getParameter("modeOfPayment")); model.setFundCluster(request.getParameter("fundCluster")); model.setDisbursementDate(request.getParameter("disbursementDate")); model.setDvNo(request.getParameter("dvNo")); model.setOthersDetail(request.getParameter("othersDetail")); model.setPayee(request.getParameter("payee")); model.setTin(request.getParameter("tin")); model.setOrs(request.getParameter("ors")); model.setAddress(request.getParameter("address")); model.setParticulars(request.getParameter("particulars")); model.setResponsibilityCenter(request.getParameter("responsibilityCenter")); model.setMfo(request.getParameter("mfo")); model.setAmount(request.getParameter("amount") != null ? new BigDecimal(request.getParameter("amount")) : BigDecimal.ZERO); model.setTotalAmount(request.getParameter("amount") != null ? new BigDecimal(request.getParameter("amount")) : BigDecimal.ZERO); model.setAccountingTitle(request.getParameter("accountingTitle")); model.setUacsCode(request.getParameter("uacsCode")); model.setDebit(request.getParameter("debit") != null && request.getParameter("debit").length() > 0 ? new BigDecimal(request.getParameter("debit")) : BigDecimal.ZERO); model.setCredit(request.getParameter("credit") != null && request.getParameter("credit").length() > 0 ? new BigDecimal(request.getParameter("credit")) : BigDecimal.ZERO); model.setAmountInWords(request.getParameter("amountInWords")); model.setSignatory1(request.getParameter("signatory1")); model.setSignatory2(request.getParameter("signatory2")); model.setSignatory3(request.getParameter("signatory3")); model.setPosition1(request.getParameter("position1")); model.setPosition2(request.getParameter("position2")); model.setPosition3(request.getParameter("position3")); model.setCheckNo(request.getParameter("checkNo")); model.setCheckDate(request.getParameter("checkDate")); model.setBankDetails(request.getParameter("bankDetails")); model.setOrNo(request.getParameter("orNo")); model.setOrDate(request.getParameter("orDate")); model.setJevNo(request.getParameter("jevNo")); model.setCertifiedMethod(request.getParameter("certifiedMethod")); model.setPrintedName(request.getParameter("printedName")); model.setDisbursementVoucherId(request.getParameter("disbursementVoucherId") != null && request.getParameter("disbursementVoucherId").length() > 0 ? Integer.parseInt(request.getParameter("disbursementVoucherId")) : null); if("Y".equals(request.getParameter("forEdit"))) { service.updateDisbursementVoucher(model); } else { service.addDisbursementVoucher(model); } String json = gson.toJson(model); System.out.println("json: " + json); String jsonData = "{\"Result\":\"OK\",\"Record\":" + json + "}"; response.getWriter().print(jsonData); } catch (SQLException e) { e.printStackTrace(); String error = "{\"Result\":\"ERROR\"}"; response.getWriter().print(error); } catch (Exception e) { e.printStackTrace(); String error = "{\"Result\":\"ERROR\"}"; response.getWriter().print(error); } } }
package com.happycactus.blogminder.models; import java.util.ArrayList; import java.util.List; public class RSSFeed { public String FeedUrl; public List<RSSItem> Items; public RSSFeed(){ Items = new ArrayList<RSSItem>(); } }
package me.earth.phobos.features.modules.player; import me.earth.phobos.features.modules.Module; public class MultiTask extends Module { private static MultiTask INSTANCE = new MultiTask(); public MultiTask() { super("MultiTask", "Allows you to eat while mining.", Category.PLAYER, false, false, false); setInstance(); } private void setInstance() { INSTANCE = this; } public static MultiTask getInstance() { if(INSTANCE == null) { INSTANCE = new MultiTask(); } return INSTANCE; } }
// -------------------------------------------------------------------------------- // Copyright 2002-2021 Echo Three, LLC // // 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.echothree.control.user.club.server.command; import com.echothree.control.user.club.common.form.DeleteClubItemForm; import com.echothree.model.control.club.server.control.ClubControl; import com.echothree.model.control.item.server.control.ItemControl; import com.echothree.model.data.club.server.entity.Club; import com.echothree.model.data.club.server.entity.ClubItem; import com.echothree.model.data.club.server.entity.ClubItemType; import com.echothree.model.data.item.server.entity.Item; import com.echothree.model.data.user.common.pk.UserVisitPK; import com.echothree.util.common.message.ExecutionErrors; import com.echothree.util.common.validation.FieldDefinition; import com.echothree.util.common.validation.FieldType; import com.echothree.util.common.command.BaseResult; import com.echothree.util.server.control.BaseSimpleCommand; import com.echothree.util.server.persistence.Session; import java.util.Arrays; import java.util.Collections; import java.util.List; public class DeleteClubItemCommand extends BaseSimpleCommand<DeleteClubItemForm> { private final static List<FieldDefinition> FORM_FIELD_DEFINITIONS; static { FORM_FIELD_DEFINITIONS = Collections.unmodifiableList(Arrays.asList( new FieldDefinition("ClubName", FieldType.ENTITY_NAME, true, null, null), new FieldDefinition("ClubItemTypeName", FieldType.ENTITY_NAME, true, null, null), new FieldDefinition("ItemName", FieldType.ENTITY_NAME, true, null, null) )); } /** Creates a new instance of DeleteClubItemCommand */ public DeleteClubItemCommand(UserVisitPK userVisitPK, DeleteClubItemForm form) { super(userVisitPK, form, null, FORM_FIELD_DEFINITIONS, false); } @Override protected BaseResult execute() { var clubControl = Session.getModelController(ClubControl.class); String clubName = form.getClubName(); Club club = clubControl.getClubByName(clubName); if(club != null) { String clubItemTypeName = form.getClubItemTypeName(); ClubItemType clubItemType = clubControl.getClubItemTypeByName(clubItemTypeName); if(clubItemType != null) { var itemControl = Session.getModelController(ItemControl.class); String itemName = form.getItemName(); Item item = itemControl.getItemByName(itemName); if(item != null) { ClubItem clubItem = clubControl.getClubItemForUpdate(club, clubItemType, item); if(clubItem != null) { clubControl.deleteClubItem(clubItem, getPartyPK()); } else { addExecutionError(ExecutionErrors.UnknownClubItem.name()); } } else { addExecutionError(ExecutionErrors.UnknownItemName.name(), itemName); } } else { addExecutionError(ExecutionErrors.UnknownClubItemTypeName.name(), clubItemTypeName); } } else { addExecutionError(ExecutionErrors.UnknownClubName.name(), clubName); } return null; } }
/* * Tencent is pleased to support the open source community by making Tinker available. * * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. * * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * * https://opensource.org/licenses/BSD-3-Clause * * 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.wh.tinkerdemo.util; import android.app.Application; import android.content.Context; /** * Created by zhangshaowen on 16/8/9. */ public class SampleApplicationContext { public static Application application = null; public static Context context = null; }
/* * Copyright 2016 Red Hat 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 io.strimzi.kafka.bridge.tracker; import org.apache.kafka.clients.consumer.ConsumerRecord; import org.apache.kafka.clients.consumer.OffsetAndMetadata; import org.apache.kafka.common.TopicPartition; import java.util.Map; /** * Interface for tracking offset for all partitions read by Kafka consumer */ public interface OffsetTracker { /** * Track information about Kafka consumer record and AMQP delivery * * @param partition The Kafka partition * @param offset The offset within the partition * @param record Kafka consumer record to track */ void track(int partition, long offset, ConsumerRecord<?, ?> record); /** * Confirm delivery of AMQP message * * @param partition The Kafka partition * @param offset The offset within the partition */ void delivered(int partition, long offset); /** * Get a map with changed offsets for all partitions * * @return Map with offsets for all partitions */ Map<TopicPartition, OffsetAndMetadata> getOffsets(); /** * Mark all tracked offsets as committed * * @param offsets Map with offsets to mark as committed */ void commit(Map<TopicPartition, OffsetAndMetadata> offsets); /** * Clear all tracked offsets */ void clear(); }
package com.github.gisellevonbingen.glowestplastic.datagen; import java.util.Map; import com.github.gisellevonbingen.glowestplastic.GlowestPlastic; import com.github.gisellevonbingen.glowestplastic.common.block.GlowestPlasticBlocks; import mekanism.additions.common.MekanismAdditions; import net.minecraft.data.DataGenerator; import net.minecraft.util.IItemProvider; import net.minecraft.util.ResourceLocation; import net.minecraftforge.client.model.generators.ItemModelProvider; import net.minecraftforge.client.model.generators.ModelFile; import net.minecraftforge.common.data.ExistingFileHelper; public class ItemsModelGenerator extends ItemModelProvider { public ItemsModelGenerator(DataGenerator generator, ExistingFileHelper existingFileHelper) { super(generator, GlowestPlastic.MODID, existingFileHelper); } @Override protected void registerModels() { this.withParent(GlowestPlasticBlocks.PLASTIC_GLOWEST_BLOCKS, "block/plastic/glow"); this.withParent(GlowestPlasticBlocks.PLASTIC_GLOWEST_STAIRS, "block/plastic/glow_stairs"); this.withParent(GlowestPlasticBlocks.PLASTIC_GLOWEST_SLABS, "block/plastic/glow_slab"); } private void withParent(Map<?, ? extends IItemProvider> items, String modelName) { ResourceLocation parentName = new ResourceLocation(MekanismAdditions.MODID, modelName); ModelFile parent = this.getExistingFile(parentName); for (IItemProvider item : items.values()) { this.getBuilder(item.asItem().getRegistryName().toString()).parent(parent); } } }
package com.mageddo.thymeleaf; import org.junit.jupiter.api.Test; import org.thymeleaf.context.Context; import static org.junit.jupiter.api.Assertions.assertTrue; public class ThymeleafTest { @Test public void processHMTLTemplate() throws Exception { // arrange final Context context = new Context(); context.setVariable("name", "Joanna"); // act final String out = Thymeleafs.fromPath("/templates/index.html", context); // assert assertTrue(out.contains("<p>Joanna</p>"), out); } @Test public void mustRenderPageWithLoggedInState() throws Exception { // arrange final Context context = new Context(); context.setVariable("loggedIn", true); context.setVariable("username", "Elvis"); // act final String out = Thymeleafs.fromPath("/templates/user/index.html", context); // assert assertTrue(out.contains("username: Elvis | <a href=\"/logout\">logout</a>"), out); } @Test public void mustRenderPageWithNotLoggedInState() throws Exception { // arrange final Context context = new Context(); // act final String out = Thymeleafs.fromPath("/templates/user/index.html", context); // assert assertTrue(out.contains("<h2>You are not logged in</h2>"), out); } }
/* * 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.cassandra.index.sai.analyzer.filter; import java.text.Normalizer; import java.util.Locale; /** * Basic/General Token Filters */ public class BasicResultFilters { private static final Locale DEFAULT_LOCALE = Locale.getDefault(); public static class LowerCase extends FilterPipelineTask { private final Locale locale; public LowerCase() { this.locale = DEFAULT_LOCALE; } public String process(String input) { return input.toLowerCase(locale); } } public static class Normalize extends FilterPipelineTask { public Normalize() { } public String process(String input) { return input == null || Normalizer.isNormalized(input, Normalizer.Form.NFC) ? input : Normalizer.normalize(input, Normalizer.Form.NFC); } } public static class NoOperation extends FilterPipelineTask { public String process(String input) { return input; } } }
/* * Password Management Servlets (PWM) * http://www.pwm-project.org * * Copyright (c) 2006-2009 Novell, Inc. * Copyright (c) 2009-2019 The PWM Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package password.pwm.ldap.search; import com.novell.ldapchai.provider.ChaiProvider; import lombok.Builder; import lombok.Value; import password.pwm.PwmConstants; import password.pwm.config.value.data.FormConfiguration; import password.pwm.config.value.data.UserPermission; import password.pwm.error.ErrorInformation; import password.pwm.error.PwmError; import password.pwm.error.PwmUnrecoverableException; import java.io.Serializable; import java.util.Collections; import java.util.List; import java.util.Map; @Value @Builder( toBuilder = true ) public class SearchConfiguration implements Serializable { private String filter; private String ldapProfile; private String username; private String groupDN; private List<String> contexts; private Map<FormConfiguration, String> formValues; private transient ChaiProvider chaiProvider; private long searchTimeout; @Builder.Default private boolean enableValueEscaping = true; @Builder.Default private boolean enableContextValidation = true; @Builder.Default private boolean enableSplitWhitespace = false; void validate( ) { if ( this.username != null && this.formValues != null ) { throw new IllegalArgumentException( "username OR formRows cannot both be supplied" ); } } public static SearchConfiguration fromPermission( final UserPermission userPermission ) throws PwmUnrecoverableException { final SearchConfiguration.SearchConfigurationBuilder builder = SearchConfiguration.builder(); switch ( userPermission.getType() ) { case ldapQuery: { builder.filter( userPermission.getLdapQuery() ); if ( userPermission.getLdapBase() != null && !userPermission.getLdapBase().isEmpty() ) { builder.enableContextValidation( false ); builder.contexts( Collections.singletonList( userPermission.getLdapBase() ) ); } } break; case ldapGroup: { builder.groupDN( userPermission.getLdapBase() ); } break; default: throw new PwmUnrecoverableException( new ErrorInformation( PwmError.ERROR_INTERNAL, "unknown permission type: " + userPermission.getType() ) ); } if ( userPermission.getLdapProfileID() != null && !userPermission.getLdapProfileID().isEmpty() && !userPermission.getLdapProfileID().equals( PwmConstants.PROFILE_ID_ALL ) ) { builder.ldapProfile( userPermission.getLdapProfileID() ); } return builder.build(); } }
/* * Copyright 2018 The Bazel Authors. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.idea.blaze.java.run.fastbuild; import com.google.common.base.Stopwatch; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.idea.blaze.base.model.primitives.Kind; import com.google.idea.blaze.base.model.primitives.Label; import com.google.idea.blaze.base.run.testlogs.BlazeTestResult; import com.google.idea.blaze.base.run.testlogs.BlazeTestResult.TestStatus; import com.google.idea.blaze.base.run.testlogs.BlazeTestResultFinderStrategy; import com.google.idea.blaze.base.run.testlogs.BlazeTestResults; import com.google.idea.blaze.java.run.fastbuild.FastBuildConfigurationRunner.FastBuildLoggingData; import java.io.File; import java.util.concurrent.TimeUnit; final class FastBuildTestResultFinderStrategy implements BlazeTestResultFinderStrategy { private final Label label; private final Kind kind; private final File outputFile; private final FastBuildLoggingData loggingData; private final Stopwatch timer; FastBuildTestResultFinderStrategy( Label label, Kind kind, File outputFile, FastBuildLoggingData loggingData) { this.label = label; this.kind = kind; this.outputFile = outputFile; this.loggingData = loggingData; this.timer = Stopwatch.createStarted(); } @Override public BlazeTestResults findTestResults() { loggingData.put("run_test_class_time_ms", Long.toString(timer.elapsed(TimeUnit.MILLISECONDS))); loggingData.writeLog(); return BlazeTestResults.fromFlatList( ImmutableList.of( BlazeTestResult.create( label, kind, TestStatus.NO_STATUS, ImmutableSet.of(outputFile)))); } @Override public void deleteTemporaryOutputXmlFiles() { outputFile.delete(); } }
package io.github.shaksternano.imperishableitems.mixin.common.enchantment.imperishable; import net.minecraft.entity.projectile.PersistentProjectileEntity; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; @Mixin(PersistentProjectileEntity.class) abstract class PersistentProjectileEntityMixin extends EntityMixin { @Shadow protected boolean inGround; @Shadow public abstract boolean isNoClip(); @Shadow public abstract void setNoClip(boolean noClip); }
package br.com.zup.desafiomercadolivre.repository; import br.com.zup.desafiomercadolivre.model.Pergunta; import org.springframework.data.jpa.repository.JpaRepository; public interface PerguntaRepository extends JpaRepository<Pergunta,Long> { }
/* GnuDHPrivateKey.java -- a Diffie-Hellman private key. Copyright (C) 2005 Free Software Foundation, Inc. This file is part of GNU Classpath. GNU Classpath is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. GNU Classpath is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with GNU Classpath; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Linking this library statically or dynamically with other modules is making a combined work based on this library. Thus, the terms and conditions of the GNU General Public License cover the whole combination. As a special exception, the copyright holders of this library give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules, and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you may extend this exception to your version of the library, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ package gnu.javax.crypto; import java.math.BigInteger; import javax.crypto.interfaces.DHKey; import javax.crypto.interfaces.DHPrivateKey; import javax.crypto.spec.DHParameterSpec; /** * A Diffie-Hellman private key. * * @author Casey Marshall (csm@gnu.org) */ public class GnuDHPrivateKey implements DHPrivateKey { private final BigInteger x; private final DHParameterSpec params; public GnuDHPrivateKey (final BigInteger x, final DHParameterSpec params) { x.getClass (); params.getClass (); this.x = x; this.params = params; } public DHParameterSpec getParams() { return params; } public String getAlgorithm() { return "DiffieHellman"; } public String getFormat () { return "NONE"; } public byte[] getEncoded () { return null; } public BigInteger getX () { return x; } }
package com.stripe.android; import android.content.Context; import androidx.annotation.NonNull; import androidx.test.core.app.ApplicationProvider; import com.stripe.android.core.networking.AnalyticsRequest; import com.stripe.android.core.networking.AnalyticsRequestExecutor; import com.stripe.android.core.networking.DefaultStripeNetworkClient; import com.stripe.android.core.version.StripeSdkVersion; import com.stripe.android.exception.AuthenticationException; import com.stripe.android.exception.CardException; import com.stripe.android.core.exception.InvalidRequestException; import com.stripe.android.core.exception.StripeException; import com.stripe.android.model.AccountParams; import com.stripe.android.model.AddressFixtures; import com.stripe.android.model.BankAccount; import com.stripe.android.model.BankAccountTokenParamsFixtures; import com.stripe.android.model.Card; import com.stripe.android.model.CardBrand; import com.stripe.android.model.CardFunding; import com.stripe.android.model.CardParams; import com.stripe.android.model.CardParamsFixtures; import com.stripe.android.model.PaymentMethod; import com.stripe.android.model.PaymentMethodCreateParams; import com.stripe.android.model.PaymentMethodCreateParamsFixtures; import com.stripe.android.model.PaymentMethodFixtures; import com.stripe.android.model.PersonTokenParamsFixtures; import com.stripe.android.model.Source; import com.stripe.android.model.SourceParams; import com.stripe.android.model.SourceTypeModel; import com.stripe.android.model.StripeFile; import com.stripe.android.model.StripeFileParams; import com.stripe.android.model.StripeFilePurpose; import com.stripe.android.model.Token; import com.stripe.android.model.WeChat; import com.stripe.android.networking.PaymentAnalyticsRequestFactory; import com.stripe.android.networking.StripeApiRepository; import com.stripe.android.networking.StripeRepository; import java.io.File; import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.util.Objects; import java.util.UUID; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.robolectric.RobolectricTestRunner; import kotlin.coroutines.CoroutineContext; import kotlinx.coroutines.CoroutineDispatcher; import kotlinx.coroutines.test.TestCoroutineDispatcher; import static android.os.Looper.getMainLooper; import static com.google.common.truth.Truth.assertThat; import static com.stripe.android.utils.TestUtils.idleLooper; import static java.util.Collections.emptySet; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertThrows; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.robolectric.Shadows.shadowOf; /** * Run integration tests on Stripe. */ @RunWith(RobolectricTestRunner.class) public class StripeTest { private static final CardParams CARD_PARAMS = CardParamsFixtures.MINIMUM; private final CoroutineDispatcher testDispatcher = new TestCoroutineDispatcher(); @NonNull private final Context context = ApplicationProvider.getApplicationContext(); @NonNull private final FraudDetectionDataRepository defaultFraudDetectionDataRepository = new DefaultFraudDetectionDataRepository(context); @NonNull private final Stripe defaultStripe = createStripe(); @Mock private AnalyticsRequestExecutor analyticsRequestExecutor; @Mock private ApiResultCallback<Token> tokenCallback; @Mock private ApiResultCallback<Source> sourceCallback; @Mock private ApiResultCallback<StripeFile> stripeFileCallback; @Captor private ArgumentCaptor<AnalyticsRequest> analyticsRequestArgumentCaptor; @Captor private ArgumentCaptor<Token> tokenArgumentCaptor; @Captor private ArgumentCaptor<Source> sourceArgumentCaptor; @Captor private ArgumentCaptor<StripeFile> stripeFileArgumentCaptor; @Before public void setup() { MockitoAnnotations.openMocks(this); } @Test public void testVersion() { assertEquals( String.format(Locale.ROOT, "AndroidBindings/%s", StripeSdkVersion.VERSION_NAME), StripeSdkVersion.VERSION ); } @Test public void testApiVersion() { assertEquals("2020-03-02", Stripe.API_VERSION); } @Test public void constructorShouldFailWithNullPublishableKey() { assertThrows(NullPointerException.class, () -> { //noinspection ConstantConditions new Stripe(context, null); }); } @Test public void constructorShouldFailWithEmptyPublishableKey() { assertThrows(IllegalArgumentException.class, () -> new Stripe(context, "")); } @Test public void constructorShouldFailWithSecretKey() { assertThrows( IllegalArgumentException.class, () -> new Stripe(context, ApiKeyFixtures.FAKE_SECRET_KEY)) ; } @Test public void createCardTokenShouldCreateRealToken() { final Stripe stripe = createStripe(testDispatcher); stripe.createCardToken(CARD_PARAMS, tokenCallback); idleLooper(); verify(tokenCallback).onSuccess(tokenArgumentCaptor.capture()); final Token token = tokenArgumentCaptor.getValue(); final String tokenId = token.getId(); assertTrue(tokenId.startsWith("tok_")); } @Test public void createCardTokenSynchronous_withValidData_returnsToken() throws StripeException { final Token token = defaultStripe.createCardTokenSynchronous(CARD_PARAMS); assertNotNull(token); Card returnedCard = token.getCard(); assertNotNull(returnedCard); assertNull(token.getBankAccount()); assertEquals(Token.Type.Card, token.getType()); assertEquals(CardBrand.Visa, returnedCard.getBrand()); assertThat(returnedCard.getLast4()) .isEqualTo("4242"); assertThat(returnedCard.getExpYear()) .isEqualTo(2050); assertThat(returnedCard.getExpMonth()) .isEqualTo(1); assertEquals(CardFunding.Credit, returnedCard.getFunding()); } @Test public void createCardTokenSynchronous_withValidDataAndConnectAccount_returnsToken() throws StripeException { final Stripe stripe = new Stripe( context, ApiKeyFixtures.CONNECTED_ACCOUNT_PUBLISHABLE_KEY, "acct_1Acj2PBUgO3KuWzz" ); final Token token = stripe.createCardTokenSynchronous(CARD_PARAMS); assertNotNull(token); Card returnedCard = token.getCard(); assertNotNull(returnedCard); assertNull(token.getBankAccount()); assertEquals(Token.Type.Card, token.getType()); assertEquals(CardBrand.Visa, returnedCard.getBrand()); assertThat(returnedCard.getLast4()) .isEqualTo("4242"); assertThat(returnedCard.getExpYear()) .isEqualTo(2050); assertThat(returnedCard.getExpMonth()) .isEqualTo(1); assertEquals(CardFunding.Credit, returnedCard.getFunding()); } @Test public void createToken_createSource_returnsSource() throws StripeException { final Stripe stripe = defaultStripe; final Token token = stripe.createCardTokenSynchronous(CARD_PARAMS); assertNotNull(token); final SourceParams sourceParams = SourceParams.createSourceFromTokenParams(token.getId()); final Source source = stripe.createSourceSynchronous(sourceParams); assertNotNull(source); } @Test public void createToken_createSourceWithTokenToSourceParams_returnsSource() throws StripeException { final Stripe stripe = defaultStripe; final Token token = stripe.createCardTokenSynchronous(CARD_PARAMS); assertNotNull(token); final SourceParams sourceParams = SourceParams.createSourceFromTokenParams(token.getId()); final Source source = stripe.createSourceSynchronous(sourceParams); assertNotNull(source); } @Test public void createBankAccountToken() { createStripe().createBankAccountToken( BankAccountTokenParamsFixtures.DEFAULT, new ApiResultCallback<Token>() { @Override public void onSuccess(@NonNull Token result) { } @Override public void onError(@NonNull Exception e) { } } ); } @Test public void createPiiToken() { createStripe().createPiiToken("123-45-6789", new ApiResultCallback<Token>() { @Override public void onSuccess(@NonNull Token result) { } @Override public void onError(@NonNull Exception e) { } }); } @Test public void testCreateSource() { createStripe().createSource( SourceParams.createCardParams(CARD_PARAMS), new ApiResultCallback<Source>() { @Override public void onSuccess(@NonNull Source result) { } @Override public void onError(@NonNull Exception e) { } }); } @Test public void createCvcUpdateToken() { createStripe().createCvcUpdateToken("123", new ApiResultCallback<Token>() { @Override public void onSuccess(@NonNull Token result) { } @Override public void onError(@NonNull Exception e) { } }); } @Test public void createBankAccountTokenSynchronous_withValidBankAccount_returnsToken() throws StripeException { final Token token = defaultStripe.createBankAccountTokenSynchronous( BankAccountTokenParamsFixtures.DEFAULT ); assertNotNull(token); assertEquals(Token.Type.BankAccount, token.getType()); assertNull(token.getCard()); final BankAccount returnedBankAccount = token.getBankAccount(); assertNotNull(returnedBankAccount); final String bankAccountId = Objects.requireNonNull(returnedBankAccount.getId()); assertTrue(bankAccountId.startsWith("ba_")); assertEquals("Jenny Rosen", returnedBankAccount.getAccountHolderName()); assertEquals( BankAccount.Type.Individual, returnedBankAccount.getAccountHolderType() ); assertEquals("US", returnedBankAccount.getCountryCode()); assertEquals("usd", returnedBankAccount.getCurrency()); assertNull(returnedBankAccount.getFingerprint()); assertEquals("6789", returnedBankAccount.getLast4()); assertEquals("110000000", returnedBankAccount.getRoutingNumber()); assertEquals(BankAccount.Status.New, returnedBankAccount.getStatus()); } @Test public void createSourceSynchronous_withAlipayReusableParams_passesIntegrationTest() throws StripeException { final SourceParams alipayParams = SourceParams.createAlipayReusableParams( "usd", "Example Payer", "abc@def.com", "stripe://start" ); final Source alipaySource = defaultStripe.createSourceSynchronous(alipayParams); assertNotNull(alipaySource); assertNotNull(alipaySource.getId()); assertNotNull(alipaySource.getClientSecret()); assertEquals(Source.SourceType.ALIPAY, alipaySource.getType()); assertEquals(Source.Flow.Redirect, alipaySource.getFlow()); assertNotNull(alipaySource.getOwner()); assertEquals("Example Payer", alipaySource.getOwner().getName()); assertEquals("abc@def.com", alipaySource.getOwner().getEmail()); assertEquals("usd", alipaySource.getCurrency()); assertEquals(Source.Usage.Reusable, alipaySource.getUsage()); assertNotNull(alipaySource.getRedirect()); assertEquals("stripe://start", alipaySource.getRedirect().getReturnUrl()); } @Test public void createSourceSynchronous_withAlipaySingleUseParams_passesIntegrationTest() throws StripeException { final SourceParams alipayParams = SourceParams.createAlipaySingleUseParams( 1000L, "usd", "Example Payer", "abc@def.com", "stripe://start"); final Source alipaySource = defaultStripe.createSourceSynchronous(alipayParams); assertNotNull(alipaySource); assertNotNull(alipaySource.getId()); assertNotNull(alipaySource.getClientSecret()); assertNotNull(alipaySource.getAmount()); assertEquals(1000L, alipaySource.getAmount().longValue()); assertEquals(Source.SourceType.ALIPAY, alipaySource.getType()); assertEquals(Source.Flow.Redirect, alipaySource.getFlow()); assertNotNull(alipaySource.getOwner()); assertEquals("Example Payer", alipaySource.getOwner().getName()); assertEquals("abc@def.com", alipaySource.getOwner().getEmail()); assertEquals("usd", alipaySource.getCurrency()); assertEquals(Source.Usage.SingleUse, alipaySource.getUsage()); assertNotNull(alipaySource.getRedirect()); assertEquals("stripe://start", alipaySource.getRedirect().getReturnUrl()); } @Ignore("Flaky test") public void createSourceSynchronous_withWeChatPayParams_passesIntegrationTest() throws StripeException { final String weChatAppId = "wx65997d6307c3827d"; final Stripe stripe = createStripe("pk_live_L4KL0pF017Jgv9hBaWzk4xoB"); final SourceParams weChatPaySourceParams = SourceParams.createWeChatPayParams( 1000L, "USD", weChatAppId, "WIDGET STORE" ); final Source weChatPaySource = stripe.createSourceSynchronous(weChatPaySourceParams); assertNotNull(weChatPaySource); final WeChat weChatData = weChatPaySource.getWeChat(); assertEquals(weChatAppId, weChatData.getAppId()); assertEquals("WIDGET STORE", weChatData.getStatementDescriptor()); } @Test public void createSourceSynchronous_withWeChatPayParams_onUnactivatedAccount_throwsException() { final Stripe stripe = createStripe( "pk_live_8fFXnTeQrVqExmub4gQPOzgG001iJLyZwl" ); final SourceParams weChatPaySourceParams = SourceParams.createWeChatPayParams( 1000L, "USD", "wx65997d6307c3827d", "WIDGET STORE" ); final InvalidRequestException ex = assertThrows( InvalidRequestException.class, () -> stripe.createSourceSynchronous(weChatPaySourceParams) ); assertEquals( "payment_method_unactivated", Objects.requireNonNull(ex.getStripeError()).getCode() ); assertEquals( "This payment method (wechat) is not activated for your account. You can only create testmode wechat payment methods. You can learn more about this here https://support.stripe.com/questions/i-am-having-trouble-activating-a-payment-method", ex.getMessage() ); } @Test public void createSourceSynchronous_withBancontactParams_passesIntegrationTest() throws StripeException { final SourceParams bancontactParams = SourceParams.createBancontactParams( 1000L, "John Doe", "example://path", "a statement described", "en" ); final Map<String, String> metamap = new HashMap<String, String>() {{ put("flavor", "strawberry"); put("type", "sherbet"); }}; bancontactParams.setMetadata(metamap); final Source bancontactSource = defaultStripe.createSourceSynchronous(bancontactParams); assertNotNull(bancontactSource); assertNotNull(bancontactSource.getId()); assertNotNull(bancontactSource.getClientSecret()); assertNotNull(bancontactSource.getAmount()); assertEquals(Source.SourceType.BANCONTACT, bancontactSource.getType()); assertEquals(1000L, bancontactSource.getAmount().longValue()); assertNotNull(bancontactSource.getSourceTypeData()); assertNull(bancontactSource.getSourceTypeModel()); assertNotNull(bancontactSource.getOwner()); assertNotNull(bancontactSource.getRedirect()); assertEquals("John Doe", bancontactSource.getOwner().getName()); assertEquals("example://path", bancontactSource.getRedirect().getReturnUrl()); } @Test public void createSourceSynchronous_with3DSParams_passesIntegrationTest() throws StripeException { final Stripe stripe = defaultStripe; final SourceParams params = SourceParams.createCardParams(CARD_PARAMS); final Source cardSource = stripe.createSourceSynchronous(params); assertNotNull(cardSource); assertNotNull(cardSource.getId()); final SourceParams threeDParams = SourceParams.createThreeDSecureParams( 50000L, "brl", "example://return", cardSource.getId()); final Map<String, String> metadata = new HashMap<String, String>() {{ put("dimensions", "three"); put("type", "beach ball"); }}; threeDParams.setMetadata(metadata); final Source threeDSource = stripe.createSourceSynchronous(threeDParams); assertNotNull(threeDSource); assertNotNull(threeDSource.getAmount()); assertEquals(50000L, threeDSource.getAmount().longValue()); assertEquals("brl", threeDSource.getCurrency()); assertNotNull(threeDSource.getClientSecret()); assertNotNull(threeDSource.getId()); assertNull(threeDSource.getSourceTypeModel()); assertEquals(Source.SourceType.THREE_D_SECURE, threeDSource.getType()); assertNotNull(threeDSource.getSourceTypeData()); } @Test public void createSourceSynchronous_withGiropayParams_passesIntegrationTest() throws StripeException { final SourceParams params = SourceParams.createGiropayParams( 2000L, "Mr. X", "example://redirect", "a well-described statement"); final Map<String, String> metamap = new HashMap<String, String>() {{ put("giro", "with chicken"); put("type", "wrap"); }}; params.setMetadata(metamap); final Source giropaySource = defaultStripe.createSourceSynchronous(params); assertNotNull(giropaySource); assertNotNull(giropaySource.getClientSecret()); assertNotNull(giropaySource.getId()); assertNotNull(giropaySource.getAmount()); assertEquals("eur", giropaySource.getCurrency()); assertEquals(2000L, giropaySource.getAmount().longValue()); assertEquals(Source.SourceType.GIROPAY, giropaySource.getType()); assertNotNull(giropaySource.getSourceTypeData()); assertNull(giropaySource.getSourceTypeModel()); assertNotNull(giropaySource.getOwner()); assertNotNull(giropaySource.getRedirect()); assertEquals("Mr. X", giropaySource.getOwner().getName()); assertEquals("example://redirect", giropaySource.getRedirect().getReturnUrl()); } @Test public void createSourceSynchronous_withP24Params_passesIntegrationTest() throws StripeException { final SourceParams p24Params = SourceParams.createP24Params( 100, "eur", "Example Payer", "abc@def.com", "stripe://start"); final Source p24Source = defaultStripe.createSourceSynchronous(p24Params); assertNotNull(p24Source); assertNotNull(p24Source.getId()); assertNotNull(p24Source.getClientSecret()); assertEquals(Source.SourceType.P24, p24Source.getType()); assertEquals(Source.Flow.Redirect, p24Source.getFlow()); assertNotNull(p24Source.getOwner()); assertEquals("Example Payer", p24Source.getOwner().getName()); assertEquals("abc@def.com", p24Source.getOwner().getEmail()); assertEquals("eur", p24Source.getCurrency()); assertEquals(Source.Usage.SingleUse, p24Source.getUsage()); assertNotNull(p24Source.getRedirect()); assertEquals("stripe://start", p24Source.getRedirect().getReturnUrl()); } @Test public void createSourceSynchronous_withSepaDebitParams_passesIntegrationTest() throws StripeException { final String validIban = "DE89370400440532013000"; final SourceParams params = SourceParams.createSepaDebitParams( "Sepa Account Holder", validIban, "sepaholder@stripe.com", "123 Main St", "Eureka", "90210", "EI"); final Map<String, String> metamap = new HashMap<String, String>() {{ put("water source", "well"); put("type", "brackish"); put("value", "100000"); }}; params.setMetadata(metamap); final Source sepaDebitSource = defaultStripe.createSourceSynchronous(params); assertNotNull(sepaDebitSource); assertNotNull(sepaDebitSource.getClientSecret()); assertNotNull(sepaDebitSource.getId()); assertEquals(Source.SourceType.SEPA_DEBIT, sepaDebitSource.getType()); assertNotNull(sepaDebitSource.getSourceTypeData()); assertNotNull(sepaDebitSource.getOwner()); assertNotNull(sepaDebitSource.getOwner().getAddress()); assertNotNull(sepaDebitSource.getSourceTypeModel()); assertTrue(sepaDebitSource.getSourceTypeModel() instanceof SourceTypeModel.SepaDebit); assertEquals("eur", sepaDebitSource.getCurrency()); assertEquals("Eureka", sepaDebitSource.getOwner().getAddress().getCity()); assertEquals("90210", sepaDebitSource.getOwner().getAddress().getPostalCode()); assertEquals("123 Main St", sepaDebitSource.getOwner().getAddress().getLine1()); assertEquals("EI", sepaDebitSource.getOwner().getAddress().getCountry()); assertEquals("Sepa Account Holder", sepaDebitSource.getOwner().getName()); } @Test public void createSourceSynchronous_withSepaDebitParamsWithMinimalValues_passesIntegrationTest() throws StripeException { final String validIban = "DE89370400440532013000"; final SourceParams params = SourceParams.createSepaDebitParams( "Sepa Account Holder", validIban, null, null, null, null, null); final Map<String, String> metamap = new HashMap<String, String>() {{ put("water source", "well"); put("type", "brackish"); put("value", "100000"); }}; params.setMetadata(metamap); final Source sepaDebitSource = defaultStripe.createSourceSynchronous(params); assertNotNull(sepaDebitSource); assertNotNull(sepaDebitSource.getClientSecret()); assertNotNull(sepaDebitSource.getId()); assertEquals(Source.SourceType.SEPA_DEBIT, sepaDebitSource.getType()); } @Test public void createSourceSynchronous_withNoEmail_passesIntegrationTest() throws StripeException { String validIban = "DE89370400440532013000"; SourceParams params = SourceParams.createSepaDebitParams( "Sepa Account Holder", validIban, "123 Main St", "Eureka", "90210", "EI" ); Map<String, String> metamap = new HashMap<String, String>() {{ put("water source", "well"); put("type", "brackish"); put("value", "100000"); }}; params.setMetadata(metamap); final Source sepaDebitSource = defaultStripe.createSourceSynchronous(params); assertNotNull(sepaDebitSource); assertNotNull(sepaDebitSource.getClientSecret()); assertNotNull(sepaDebitSource.getId()); assertEquals(Source.SourceType.SEPA_DEBIT, sepaDebitSource.getType()); assertNotNull(sepaDebitSource.getSourceTypeData()); assertNotNull(sepaDebitSource.getOwner()); assertNotNull(sepaDebitSource.getOwner().getAddress()); assertNotNull(sepaDebitSource.getSourceTypeModel()); assertTrue(sepaDebitSource.getSourceTypeModel() instanceof SourceTypeModel.SepaDebit); assertEquals("eur", sepaDebitSource.getCurrency()); assertEquals("Eureka", sepaDebitSource.getOwner().getAddress().getCity()); assertEquals("90210", sepaDebitSource.getOwner().getAddress().getPostalCode()); assertEquals("123 Main St", sepaDebitSource.getOwner().getAddress().getLine1()); assertEquals("EI", sepaDebitSource.getOwner().getAddress().getCountry()); assertEquals("Sepa Account Holder", sepaDebitSource.getOwner().getName()); } @Test public void createSepaDebitSource_withNoAddress_passesIntegrationTest() throws StripeException { String validIban = "DE89370400440532013000"; SourceParams params = SourceParams.createSepaDebitParams( "Sepa Account Holder", validIban, "sepaholder@stripe.com", null, "Eureka", "90210", "EI"); final Source sepaDebitSource = defaultStripe.createSourceSynchronous(params); assertNotNull(sepaDebitSource); assertNotNull(sepaDebitSource.getClientSecret()); assertNotNull(sepaDebitSource.getId()); assertEquals(Source.SourceType.SEPA_DEBIT, sepaDebitSource.getType()); assertNotNull(sepaDebitSource.getSourceTypeData()); assertNotNull(sepaDebitSource.getOwner()); assertNotNull(sepaDebitSource.getOwner().getAddress()); assertNotNull(sepaDebitSource.getSourceTypeModel()); assertTrue(sepaDebitSource.getSourceTypeModel() instanceof SourceTypeModel.SepaDebit); assertEquals("eur", sepaDebitSource.getCurrency()); assertEquals("Eureka", sepaDebitSource.getOwner().getAddress().getCity()); assertEquals("90210", sepaDebitSource.getOwner().getAddress().getPostalCode()); assertEquals("EI", sepaDebitSource.getOwner().getAddress().getCountry()); assertEquals("Sepa Account Holder", sepaDebitSource.getOwner().getName()); } @Test public void createSourceSynchronous_withiDEALParams_passesIntegrationTest() throws StripeException { final SourceParams params = SourceParams.createIdealParams( 5500L, "Bond", "example://return", "A statement description", "rabobank"); final Map<String, String> metamap = new HashMap<String, String>() {{ put("state", "quite ideal"); put("picture", "17L"); put("arrows", "what?"); }}; params.setMetadata(metamap); final Source idealSource = defaultStripe.createSourceSynchronous(params); assertNotNull(idealSource); assertNotNull(idealSource.getClientSecret()); assertNotNull(idealSource.getId()); assertNotNull(idealSource.getAmount()); assertEquals(5500L, idealSource.getAmount().longValue()); assertEquals(Source.SourceType.IDEAL, idealSource.getType()); assertEquals("eur", idealSource.getCurrency()); assertNotNull(idealSource.getSourceTypeData()); assertNotNull(idealSource.getOwner()); assertNull(idealSource.getSourceTypeModel()); assertEquals("Bond", idealSource.getOwner().getName()); assertNotNull(idealSource.getRedirect()); assertEquals("example://return", idealSource.getRedirect().getReturnUrl()); } @Test public void createSourceSynchronous_withiDEALParamsNoStatement_doesNotIgnoreBank() throws StripeException { final String bankName = "rabobank"; final SourceParams params = SourceParams.createIdealParams( 5500L, "Bond", "example://return", null, bankName); final Map<String, String> metamap = new HashMap<String, String>() {{ put("state", "quite ideal"); put("picture", "17L"); put("arrows", "what?"); }}; params.setMetadata(metamap); final Source idealSource = defaultStripe.createSourceSynchronous(params); assertNotNull(idealSource); assertNotNull(idealSource.getClientSecret()); assertNotNull(idealSource.getId()); assertNotNull(idealSource.getAmount()); assertEquals(5500L, idealSource.getAmount().longValue()); assertEquals(Source.SourceType.IDEAL, idealSource.getType()); assertEquals("eur", idealSource.getCurrency()); assertNotNull(idealSource.getSourceTypeData()); assertNotNull(idealSource.getOwner()); assertNull(idealSource.getSourceTypeModel()); assertEquals("Bond", idealSource.getOwner().getName()); assertNotNull(idealSource.getRedirect()); assertEquals(bankName, idealSource.getSourceTypeData().get("bank")); assertEquals("example://return", idealSource.getRedirect().getReturnUrl()); } @Test public void createSourceSynchronous_withiDEALParamsNoName_passesIntegrationTest() throws StripeException { final String bankName = "rabobank"; final SourceParams params = SourceParams.createIdealParams( 5500L, null, "example://return", null, bankName); final Map<String, String> metamap = new HashMap<String, String>() {{ put("state", "quite ideal"); put("picture", "17L"); put("arrows", "what?"); }}; params.setMetadata(metamap); final Source idealSource = defaultStripe.createSourceSynchronous(params); assertNotNull(idealSource); assertNotNull(idealSource.getClientSecret()); assertNotNull(idealSource.getId()); assertNotNull(idealSource.getAmount()); assertEquals(5500L, idealSource.getAmount().longValue()); assertEquals(Source.SourceType.IDEAL, idealSource.getType()); assertEquals("eur", idealSource.getCurrency()); assertNotNull(idealSource.getSourceTypeData()); assertNotNull(idealSource.getOwner()); assertNull(idealSource.getSourceTypeModel()); assertNotNull(idealSource.getRedirect()); assertEquals(bankName, idealSource.getSourceTypeData().get("bank")); assertNull(idealSource.getOwner().getName()); assertEquals("example://return", idealSource.getRedirect().getReturnUrl()); } @Test public void createSourceSynchronous_withSofortParams_passesIntegrationTest() throws StripeException { SourceParams params = SourceParams.createSofortParams( 70000L, "example://return", "NL", "a description"); Map<String, String> metamap = new HashMap<String, String>() {{ put("state", "soforting"); put("repetitions", "400"); }}; params.setMetadata(metamap); final Source sofortSource = defaultStripe.createSourceSynchronous(params); assertNotNull(sofortSource); assertNotNull(sofortSource.getClientSecret()); assertNotNull(sofortSource.getId()); assertNotNull(sofortSource.getAmount()); assertEquals(Source.SourceType.SOFORT, sofortSource.getType()); assertEquals("eur", sofortSource.getCurrency()); assertNotNull(sofortSource.getSourceTypeData()); assertNull(sofortSource.getSourceTypeModel()); assertEquals(70000L, sofortSource.getAmount().longValue()); assertNotNull(sofortSource.getRedirect()); assertEquals("example://return", sofortSource.getRedirect().getReturnUrl()); } @Test public void retrieveSourceAsync_withValidData_passesIntegrationTest() throws StripeException { final Source source = createSource(); final Stripe stripe = createStripe(testDispatcher); stripe.retrieveSource( Objects.requireNonNull(source.getId()), Objects.requireNonNull(source.getClientSecret()), sourceCallback ); idle(); verify(sourceCallback).onSuccess(sourceArgumentCaptor.capture()); final Source capturedSource = sourceArgumentCaptor.getValue(); assertEquals( source.getId(), capturedSource.getId() ); } @Test public void retrieveSourceSynchronous_withValidData_passesIntegrationTest() throws StripeException { final Source source = createSource(); final String sourceId = source.getId(); final String clientSecret = source.getClientSecret(); assertNotNull(sourceId); assertNotNull(clientSecret); final Source retrievedSource = createStripe() .retrieveSourceSynchronous(sourceId, clientSecret); // We aren't actually updating the source on the server, so the two sources should // be identical. assertEquals(source, retrievedSource); } @Test public void createSourceFromTokenParams_withExtraParams_succeeds() throws StripeException { final Stripe stripe = defaultStripe; final Token token = stripe.createCardTokenSynchronous(CARD_PARAMS); assertNotNull(token); final SourceParams sourceParams = SourceParams.createSourceFromTokenParams(token.getId()); sourceParams.setUsage(Source.Usage.SingleUse); final Source source = stripe.createSourceSynchronous(sourceParams); assertNotNull(source); assertEquals(Source.Usage.SingleUse, source.getUsage()); } @Test public void createVisaCheckoutParams_whenUnactivated_throwsException() { final SourceParams sourceParams = SourceParams.createVisaCheckoutParams( UUID.randomUUID().toString() ); final InvalidRequestException ex = assertThrows( InvalidRequestException.class, () -> defaultStripe.createSourceSynchronous(sourceParams) ); assertEquals("visa_checkout must be activated before use.", ex.getMessage()); } @Test public void createMasterpassParams_whenUnactivated_throwsException() { final SourceParams sourceParams = SourceParams.createMasterpassParams( UUID.randomUUID().toString(), UUID.randomUUID().toString() ); final InvalidRequestException ex = assertThrows( InvalidRequestException.class, () -> defaultStripe.createSourceSynchronous(sourceParams) ); assertEquals("masterpass must be activated before use.", ex.getMessage()); } @Test public void createTokenSynchronous_withValidPersonalId_passesIntegrationTest() throws StripeException { final Token token = defaultStripe.createPiiTokenSynchronous("0123456789"); assertNotNull(token); assertEquals(Token.Type.Pii, token.getType()); assertFalse(token.getLivemode()); assertFalse(token.getUsed()); assertNotNull(token.getId()); } @Test public void createTokenSynchronous_withValidCvc_passesIntegrationTest() throws StripeException { final Token token = defaultStripe.createCvcUpdateTokenSynchronous("1234"); assertNotNull(token); assertEquals(Token.Type.CvcUpdate, token.getType()); assertFalse(token.getLivemode()); assertFalse(token.getUsed()); assertNotNull(token.getId()); assertTrue(token.getId().startsWith("cvctok_")); } @Test public void testCreatePersonToken() { final Stripe stripe = createStripe(testDispatcher); stripe.createPersonToken(PersonTokenParamsFixtures.PARAMS, tokenCallback); idle(); verify(tokenCallback).onSuccess(tokenArgumentCaptor.capture()); final Token token = tokenArgumentCaptor.getValue(); assertEquals(Token.Type.Person, Objects.requireNonNull(token).getType()); assertTrue(token.getId().startsWith("cpt_")); } @Test public void testCreatePersonTokenSynchronous() throws StripeException { final Token token = defaultStripe.createPersonTokenSynchronous(PersonTokenParamsFixtures.PARAMS); assertEquals(Token.Type.Person, Objects.requireNonNull(token).getType()); assertTrue(token.getId().startsWith("cpt_")); } @Test public void createAccountTokenSynchronous_withIndividualEntity_passesIntegrationTest() throws StripeException { final Token token = defaultStripe.createAccountTokenSynchronous( AccountParams.create( true, new AccountParams.BusinessTypeParams.Individual.Builder() .setAddress(AddressFixtures.ADDRESS) .setFirstName("Kathy") .setLastName("Sun") .setSsnLast4("1234") .build() ) ); assertNotNull(token); assertEquals(Token.Type.Account, token.getType()); assertFalse(token.getLivemode()); assertFalse(token.getUsed()); assertNotNull(token.getId()); } @Test public void createAccountTokenSynchronous_withCompanyEntity_isSuccessful() throws StripeException { final Token token = defaultStripe.createAccountTokenSynchronous( AccountParams.create( true, new AccountParams.BusinessTypeParams.Company.Builder() .setAddress(AddressFixtures.ADDRESS) .setTaxId("123-23-1234") .setName("My Corp.") .build() ) ); assertNotNull(token); assertEquals(Token.Type.Account, token.getType()); assertFalse(token.getLivemode()); assertFalse(token.getUsed()); assertNotNull(token.getId()); } @Test public void createAccountTokenSynchronous_withoutTosShown_isSuccessful() throws StripeException { final Token token = defaultStripe.createAccountTokenSynchronous( AccountParams.create(false, new AccountParams.BusinessTypeParams.Individual.Builder() .setAddress(AddressFixtures.ADDRESS) .setFirstName("Kathy") .setLastName("Sun") .setSsnLast4("1234") .build() ) ); assertNotNull(token); assertEquals(Token.Type.Account, token.getType()); assertFalse(token.getLivemode()); assertFalse(token.getUsed()); assertNotNull(token.getId()); } @Test public void createAccountTokenSynchronous_withoutBusinessData_isValid() throws StripeException { final Token token = defaultStripe.createAccountTokenSynchronous( AccountParams.create( false, AccountParams.BusinessType.Individual ) ); assertNotNull(token); assertEquals(Token.Type.Account, token.getType()); assertFalse(token.getLivemode()); assertFalse(token.getUsed()); assertNotNull(token.getId()); } @Test public void createAccountTokenSynchronous_withoutBusinessType_isValid() throws StripeException { final Token token = defaultStripe.createAccountTokenSynchronous(AccountParams.create(false)); assertNotNull(token); assertEquals(Token.Type.Account, token.getType()); assertFalse(token.getLivemode()); assertFalse(token.getUsed()); assertNotNull(token.getId()); } @Test public void createTokenSynchronous_withValidDataAndBadKey_throwsAuthenticationException() { // This key won't work for a real connection to the api. final Stripe stripe = createStripe(ApiKeyFixtures.FAKE_PUBLISHABLE_KEY); final AuthenticationException authenticationException = assertThrows( AuthenticationException.class, () -> stripe.createCardTokenSynchronous(CARD_PARAMS) ); assertEquals("Invalid API Key provided: " + ApiKeyFixtures.FAKE_PUBLISHABLE_KEY, authenticationException.getMessage()); } @Test public void createTokenSynchronous_withInvalidCardNumber_throwsCardException() { // This card is missing quite a few numbers. final CardParams cardParams = new CardParams("42424242", 12, 2050, "123"); final CardException cardException = assertThrows( CardException.class, () -> defaultStripe.createCardTokenSynchronous(cardParams) ); assertEquals("Your card number is incorrect.", cardException.getMessage()); } @Test public void retrievePaymentIntent_withInvalidClientSecret_shouldThrowException() { Locale.setDefault(Locale.GERMANY); assertThrows( IllegalArgumentException.class, () -> defaultStripe.retrievePaymentIntentSynchronous("invalid") ); } @Test public void createTokenSynchronous_withExpiredCard_throwsCardException() { // This card is missing quite a few numbers. final CardParams cardParams = new CardParams("4242424242424242", 11, 2015, "123"); final CardException cardException = assertThrows( CardException.class, () -> defaultStripe.createCardTokenSynchronous(cardParams) ); assertEquals("Your card's expiration year is invalid.", cardException.getMessage()); } @Test public void createTokenSynchronousTwice_withIdempotencyKey_returnsSameToken() throws StripeException { final Stripe stripe = createStripe( ApiKeyFixtures.DEFAULT_PUBLISHABLE_KEY, mock(AnalyticsRequestExecutor.class), new FakeFraudDetectionDataRepository() ); final String idempotencyKey = UUID.randomUUID().toString(); assertEquals( stripe.createCardTokenSynchronous(CardParamsFixtures.MINIMUM, idempotencyKey), stripe.createCardTokenSynchronous(CardParamsFixtures.MINIMUM, idempotencyKey) ); } @Test public void createTokenSynchronousTwice_withoutIdempotencyKey_returnsDifferentToken() throws StripeException { final Stripe stripe = defaultStripe; assertNotEquals( stripe.createCardTokenSynchronous(CardParamsFixtures.MINIMUM), stripe.createCardTokenSynchronous(CardParamsFixtures.MINIMUM) ); } @Test public void createPaymentMethodSynchronous_withCard() throws StripeException { final PaymentMethodCreateParams paymentMethodCreateParams = PaymentMethodCreateParamsFixtures.DEFAULT_CARD; final PaymentMethod createdPaymentMethod = defaultStripe.createPaymentMethodSynchronous( paymentMethodCreateParams); assertNotNull(createdPaymentMethod); assertEquals(PaymentMethodCreateParamsFixtures.BILLING_DETAILS, createdPaymentMethod.billingDetails); assertNotNull(createdPaymentMethod.card); assertEquals("4242", createdPaymentMethod.card.last4); } @Test public void createPaymentMethod_withCardToken() throws StripeException { final Stripe stripe = defaultStripe; final Token token = Objects.requireNonNull(stripe.createCardTokenSynchronous(CARD_PARAMS)); final PaymentMethodCreateParams paymentMethodCreateParams = PaymentMethodCreateParams.create( PaymentMethodCreateParams.Card.create(token.getId()), null ); final PaymentMethod createdPaymentMethod = stripe.createPaymentMethodSynchronous( paymentMethodCreateParams); assertNotNull(createdPaymentMethod); assertNotNull(createdPaymentMethod.card); assertEquals(CardBrand.Visa, createdPaymentMethod.card.brand); assertEquals("4242", createdPaymentMethod.card.last4); } @Test public void createPaymentMethodSynchronous_withCardAndMetadata() throws StripeException { final Map<String, String> metadata = new HashMap<>(); metadata.put("order_id", "123456789"); final PaymentMethodCreateParams paymentMethodCreateParams = PaymentMethodCreateParamsFixtures.createWith(metadata); final Stripe stripe = createStripe( ApiKeyFixtures.DEFAULT_PUBLISHABLE_KEY, analyticsRequestExecutor ); final PaymentMethod createdPaymentMethod = stripe.createPaymentMethodSynchronous( paymentMethodCreateParams); assertNotNull(createdPaymentMethod); assertEquals(PaymentMethodCreateParamsFixtures.BILLING_DETAILS, createdPaymentMethod.billingDetails); assertNotNull(createdPaymentMethod.card); assertEquals("4242", createdPaymentMethod.card.last4); verify(analyticsRequestExecutor) .executeAsync(analyticsRequestArgumentCaptor.capture()); final AnalyticsRequest analyticsRequest = analyticsRequestArgumentCaptor.getValue(); assertTrue(analyticsRequest.getUrl().startsWith(AnalyticsRequest.HOST)); assertThat( Objects.requireNonNull(analyticsRequest.getParams()) .get(PaymentAnalyticsRequestFactory.FIELD_SOURCE_TYPE) ).isEqualTo("card"); } @Test public void createPaymentMethodSynchronous_withIdeal() throws StripeException { final PaymentMethodCreateParams paymentMethodCreateParams = PaymentMethodCreateParams.create( new PaymentMethodCreateParams.Ideal("ing"), PaymentMethodFixtures.BILLING_DETAILS ); final Stripe stripe = createStripe( ApiKeyFixtures.DEFAULT_PUBLISHABLE_KEY, analyticsRequestExecutor ); final PaymentMethod createdPaymentMethod = stripe.createPaymentMethodSynchronous( paymentMethodCreateParams); assertNotNull(createdPaymentMethod); assertEquals(PaymentMethodFixtures.BILLING_DETAILS, createdPaymentMethod.billingDetails); assertNull(createdPaymentMethod.card); assertEquals( "INGBNL2A", Objects.requireNonNull(createdPaymentMethod.ideal).bankIdentifierCode ); verify(analyticsRequestExecutor) .executeAsync(analyticsRequestArgumentCaptor.capture()); final AnalyticsRequest analyticsRequest = analyticsRequestArgumentCaptor.getValue(); assertTrue(analyticsRequest.getUrl().startsWith(AnalyticsRequest.HOST)); assertThat( Objects.requireNonNull(analyticsRequest.getParams()) .get(PaymentAnalyticsRequestFactory.FIELD_SOURCE_TYPE) ).isEqualTo("ideal"); } @Test public void createPaymentMethodSynchronous_withFpx() throws StripeException { final PaymentMethodCreateParams paymentMethodCreateParams = PaymentMethodCreateParams.create( new PaymentMethodCreateParams.Fpx("hsbc"), PaymentMethodFixtures.BILLING_DETAILS ); final Stripe stripe = createStripe( ApiKeyFixtures.FPX_PUBLISHABLE_KEY, analyticsRequestExecutor ); final PaymentMethod createdPaymentMethod = stripe.createPaymentMethodSynchronous( paymentMethodCreateParams); assertNotNull(createdPaymentMethod); assertEquals(PaymentMethodFixtures.BILLING_DETAILS, createdPaymentMethod.billingDetails); assertNull(createdPaymentMethod.card); assertEquals("hsbc", Objects.requireNonNull(createdPaymentMethod.fpx).bank); verify(analyticsRequestExecutor) .executeAsync(analyticsRequestArgumentCaptor.capture()); final AnalyticsRequest analyticsRequest = analyticsRequestArgumentCaptor.getValue(); assertTrue(analyticsRequest.getUrl().startsWith(AnalyticsRequest.HOST)); assertThat( Objects.requireNonNull(analyticsRequest.getParams()) .get(PaymentAnalyticsRequestFactory.FIELD_SOURCE_TYPE) ).isEqualTo("fpx"); } @Test public void setAppInfo() { assertNull(Stripe.getAppInfo()); final AppInfo appInfo = AppInfo.create("myapp"); Stripe.setAppInfo(appInfo); assertEquals(appInfo, Stripe.getAppInfo()); } @Test public void createFile_shouldCreateFile() { final File file = new FileFactory(context).create(); final Stripe stripe = createStripe(testDispatcher); stripe.createFile( new StripeFileParams( file, StripeFilePurpose.BusinessIcon ), stripeFileCallback ); idle(); verify(stripeFileCallback).onSuccess(stripeFileArgumentCaptor.capture()); final StripeFile stripeFile = stripeFileArgumentCaptor.getValue(); assertNotNull(stripeFile.getId()); assertEquals(StripeFilePurpose.BusinessIcon, stripeFile.getPurpose()); assertEquals("png", stripeFile.getType()); assertEquals("example.png", stripeFile.getFilename()); assertEquals(976L, Objects.requireNonNull(stripeFile.getSize()).intValue()); final String url = stripeFile.getUrl(); assertNotNull(url); assertTrue(url.startsWith("https://files.stripe.com/v1/files/file_")); } @Test public void createFileSynchronous_shouldCreateFile() { final File file = new FileFactory(context).create(); final StripeFile stripeFile = createStripe().createFileSynchronous( new StripeFileParams( file, StripeFilePurpose.BusinessIcon ) ); assertNotNull(stripeFile.getId()); assertEquals(StripeFilePurpose.BusinessIcon, stripeFile.getPurpose()); assertEquals("png", stripeFile.getType()); assertEquals("example.png", stripeFile.getFilename()); assertEquals(976L, Objects.requireNonNull(stripeFile.getSize()).intValue()); final String url = stripeFile.getUrl(); assertNotNull(url); assertTrue(url.startsWith("https://files.stripe.com/v1/files/file_")); } @NonNull private Source createSource() throws StripeException { final Stripe stripe = defaultStripe; final SourceParams params = SourceParams.createCardParams(CARD_PARAMS); final Source cardSource = stripe.createSourceSynchronous(params); assertNotNull(cardSource); assertNotNull(cardSource.getId()); SourceParams threeDParams = SourceParams.createThreeDSecureParams( 5000L, "brl", "example://return", cardSource.getId() ); final Map<String, String> metamap = new HashMap<String, String>() {{ put("dimensions", "three"); put("type", "beach ball"); }}; threeDParams.setMetadata(metamap); final Source source = stripe.createSourceSynchronous(threeDParams); assertNotNull(source); return source; } @NonNull private Stripe createStripe() { return createStripe(ApiKeyFixtures.DEFAULT_PUBLISHABLE_KEY); } @NonNull private Stripe createStripe(@NonNull String publishableKey) { return createStripe( publishableKey, mock(AnalyticsRequestExecutor.class), defaultFraudDetectionDataRepository ); } @NonNull private Stripe createStripe( @NonNull String publishableKey, @NonNull AnalyticsRequestExecutor analyticsRequestExecutor ) { return createStripe( publishableKey, analyticsRequestExecutor, defaultFraudDetectionDataRepository ); } @NonNull private Stripe createStripe( @NonNull String publishableKey, @NonNull AnalyticsRequestExecutor analyticsRequestExecutor, @NonNull FraudDetectionDataRepository fraudDetectionDataRepository ) { final StripeRepository stripeRepository = createStripeRepository( publishableKey, testDispatcher, analyticsRequestExecutor, fraudDetectionDataRepository ); return new Stripe( stripeRepository, StripePaymentController.create(context, publishableKey, stripeRepository), publishableKey, null ); } @NonNull private Stripe createStripe(@NonNull CoroutineDispatcher workDispatcher) { final StripeRepository stripeRepository = createStripeRepository( ApiKeyFixtures.DEFAULT_PUBLISHABLE_KEY, workDispatcher, mock(AnalyticsRequestExecutor.class), defaultFraudDetectionDataRepository ); return new Stripe( stripeRepository, StripePaymentController.create( context, ApiKeyFixtures.DEFAULT_PUBLISHABLE_KEY, stripeRepository ), ApiKeyFixtures.DEFAULT_PUBLISHABLE_KEY, null, workDispatcher ); } @NonNull private StripeRepository createStripeRepository( @NonNull final String publishableKey, @NonNull CoroutineContext workDispatcher, @NonNull AnalyticsRequestExecutor analyticsRequestExecutor, @NonNull FraudDetectionDataRepository fraudDetectionDataRepository ) { return new StripeApiRepository( context, () -> publishableKey, null, new FakeLogger(), workDispatcher, emptySet(), new DefaultStripeNetworkClient(workDispatcher), analyticsRequestExecutor, fraudDetectionDataRepository ); } private void idle() { shadowOf(getMainLooper()).idle(); } }
/* * 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.route53resolver.model.transform; import java.math.*; import javax.annotation.Generated; import com.amazonaws.services.route53resolver.model.*; import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*; import com.amazonaws.transform.*; import com.fasterxml.jackson.core.JsonToken; import static com.fasterxml.jackson.core.JsonToken.*; /** * CreateResolverQueryLogConfigResult JSON Unmarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class CreateResolverQueryLogConfigResultJsonUnmarshaller implements Unmarshaller<CreateResolverQueryLogConfigResult, JsonUnmarshallerContext> { public CreateResolverQueryLogConfigResult unmarshall(JsonUnmarshallerContext context) throws Exception { CreateResolverQueryLogConfigResult createResolverQueryLogConfigResult = new CreateResolverQueryLogConfigResult(); 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 createResolverQueryLogConfigResult; } while (true) { if (token == null) break; if (token == FIELD_NAME || token == START_OBJECT) { if (context.testExpression("ResolverQueryLogConfig", targetDepth)) { context.nextToken(); createResolverQueryLogConfigResult.setResolverQueryLogConfig(ResolverQueryLogConfigJsonUnmarshaller.getInstance().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 createResolverQueryLogConfigResult; } private static CreateResolverQueryLogConfigResultJsonUnmarshaller instance; public static CreateResolverQueryLogConfigResultJsonUnmarshaller getInstance() { if (instance == null) instance = new CreateResolverQueryLogConfigResultJsonUnmarshaller(); return instance; } }
/** * Copyright (C) 2014-2016 LinkedIn Corp. (pinot-core@linkedin.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.linkedin.pinot.common.utils; import com.google.common.base.Preconditions; import com.linkedin.pinot.common.data.FieldSpec; import com.linkedin.pinot.common.data.Schema; import java.io.IOException; import java.net.URL; import java.util.concurrent.TimeUnit; import javax.annotation.Nonnull; import javax.annotation.Nullable; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.methods.DeleteMethod; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity; import org.apache.commons.httpclient.methods.multipart.Part; import org.apache.commons.httpclient.methods.multipart.StringPart; import org.apache.commons.httpclient.params.HttpMethodParams; import org.apache.helix.ZNRecord; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Utility class which contains {@link Schema} related operations. */ public class SchemaUtils { private static final Logger LOGGER = LoggerFactory.getLogger(SchemaUtils.class); private static final HttpClient HTTP_CLIENT = new HttpClient(); private SchemaUtils() { } /** * Fetch {@link Schema} from a {@link ZNRecord}. */ public static Schema fromZNRecord(@Nonnull ZNRecord record) throws IOException { String schemaJSON = record.getSimpleField("schemaJSON"); return Schema.fromString(schemaJSON); } /** * Wrap {@link Schema} into a {@link ZNRecord}. */ public static ZNRecord toZNRecord(@Nonnull Schema schema) throws IllegalArgumentException, IllegalAccessException { ZNRecord record = new ZNRecord(schema.getSchemaName()); record.setSimpleField("schemaJSON", schema.getJSONSchema()); return record; } /** * Given host, port and schema name, send a http GET request to download the {@link Schema}. * * @return schema on success. * <P><code>null</code> on failure. */ public static @Nullable Schema getSchema(@Nonnull String host, int port, @Nonnull String schemaName) { Preconditions.checkNotNull(host); Preconditions.checkNotNull(schemaName); try { URL url = new URL("http", host, port, "/schemas/" + schemaName); GetMethod httpGet = new GetMethod(url.toString()); try { int responseCode = HTTP_CLIENT.executeMethod(httpGet); String response = httpGet.getResponseBodyAsString(); if (responseCode >= 400) { // File not find error code. if (responseCode == 404) { LOGGER.info("Cannot find schema: {} from host: {}, port: {}", schemaName, host, port); } else { LOGGER.warn("Got error response code: {}, response: {}", responseCode, response); } return null; } return Schema.fromString(response); } finally { httpGet.releaseConnection(); } } catch (Exception e) { LOGGER.error("Caught exception while getting the schema: {} from host: {}, port: {}", schemaName, host, port, e); return null; } } /** * Given host, port and schema, send a http POST request to upload the {@link Schema}. * * @return <code>true</code> on success. * <P><code>false</code> on failure. */ public static boolean postSchema(@Nonnull String host, int port, @Nonnull Schema schema) { Preconditions.checkNotNull(host); Preconditions.checkNotNull(schema); try { URL url = new URL("http", host, port, "/schemas"); PostMethod httpPost = new PostMethod(url.toString()); try { Part[] parts = {new StringPart(schema.getSchemaName(), schema.toString())}; MultipartRequestEntity requestEntity = new MultipartRequestEntity(parts, new HttpMethodParams()); httpPost.setRequestEntity(requestEntity); int responseCode = HTTP_CLIENT.executeMethod(httpPost); if (responseCode >= 400) { String response = httpPost.getResponseBodyAsString(); LOGGER.warn("Got error response code: {}, response: {}", responseCode, response); return false; } return true; } finally { httpPost.releaseConnection(); } } catch (Exception e) { LOGGER.error("Caught exception while posting the schema: {} to host: {}, port: {}", schema.getSchemaName(), host, port, e); return false; } } /** * Given host, port and schema name, send a http DELETE request to delete the {@link Schema}. * * @return <code>true</code> on success. * <P><code>false</code> on failure. */ public static boolean deleteSchema(@Nonnull String host, int port, @Nonnull String schemaName) { Preconditions.checkNotNull(host); Preconditions.checkNotNull(schemaName); try { URL url = new URL("http", host, port, "/schemas/" + schemaName); DeleteMethod httpDelete = new DeleteMethod(url.toString()); try { int responseCode = HTTP_CLIENT.executeMethod(httpDelete); if (responseCode >= 400) { String response = httpDelete.getResponseBodyAsString(); LOGGER.warn("Got error response code: {}, response: {}", responseCode, response); return false; } return true; } finally { httpDelete.releaseConnection(); } } catch (Exception e) { LOGGER.error("Caught exception while getting the schema: {} from host: {}, port: {}", schemaName, host, port, e); return false; } } /** * Compare two schemas ignoring their version number. * * @return <code>true</code> if two schemas equal to each other. * <p><code>false</code>if two schemas do not equal to each other. */ public static boolean equalsIgnoreVersion(@Nonnull Schema schema1, @Nonnull Schema schema2) { Preconditions.checkNotNull(schema1); Preconditions.checkNotNull(schema2); return schema1.getSchemaName().equals(schema2.getSchemaName()) && schema1.getFieldSpecMap().equals(schema2.getFieldSpecMap()); } /** * An example on how to use this utility class. */ public static void main(String[] args) { Schema schema = new Schema.SchemaBuilder().setSchemaName("testSchema") .addSingleValueDimension("dimension", FieldSpec.DataType.DOUBLE) .addMetric("metric", FieldSpec.DataType.INT) .addTime("time", TimeUnit.DAYS, FieldSpec.DataType.INT) .build(); System.out.println(postSchema("localhost", 8100, schema)); Schema fetchedSchema = getSchema("localhost", 8100, "testSchema"); Preconditions.checkNotNull(fetchedSchema); System.out.println(fetchedSchema); System.out.println(equalsIgnoreVersion(schema, fetchedSchema)); System.out.println(deleteSchema("localhost", 8100, "testSchema")); } }
package org.apache.velocity.runtime.parser.node; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.util.Map; import org.apache.velocity.exception.VelocityException; import org.apache.velocity.runtime.log.Log; /** * SetExecutor that is smart about Maps. If it detects one, it does not * use Reflection but a cast to access the setter. * * @author <a href="mailto:henning@apache.org">Henning P. Schmiedehausen</a> * @version $Id$ * @since 1.5 */ public class MapSetExecutor extends SetExecutor { private final String property; public MapSetExecutor(final Log log, final Class clazz, final String property) { this.log = log; this.property = property; discover(clazz); } protected void discover (final Class clazz) { Class [] interfaces = clazz.getInterfaces(); for (int i = 0 ; i < interfaces.length; i++) { if (interfaces[i].equals(Map.class)) { try { if (property != null) { setMethod(Map.class.getMethod("put", new Class [] { Object.class, Object.class })); } } /** * pass through application level runtime exceptions */ catch( RuntimeException e ) { throw e; } catch(Exception e) { String msg = "Exception while looking for put('" + property + "') method"; log.error(msg, e); throw new VelocityException(msg, e); } break; } } } public Object execute(final Object o, final Object arg) { return ((Map) o).put(property, arg); } }
package com.orange.demo.webadmin.interceptor; import com.alibaba.fastjson.JSON; import com.orange.demo.webadmin.config.ApplicationConfig; import com.orange.demo.webadmin.upms.model.SysPermWhitelist; import com.orange.demo.webadmin.upms.service.SysPermWhitelistService; import com.orange.demo.webadmin.upms.service.SysPermService; import com.orange.demo.common.core.annotation.NoAuthInterface; import com.orange.demo.common.core.constant.ErrorCodeEnum; import com.orange.demo.common.core.object.ResponseResult; import com.orange.demo.common.core.object.TokenData; import com.orange.demo.common.core.util.ApplicationContextHolder; import com.orange.demo.common.core.util.JwtUtil; import com.orange.demo.common.core.util.RedisKeyUtil; import io.jsonwebtoken.Claims; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.redisson.api.RBucket; import org.redisson.api.RSet; import org.redisson.api.RedissonClient; import org.springframework.web.method.HandlerMethod; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; import java.util.Set; import java.util.List; import java.util.stream.Collectors; /** * 登录用户Token验证、生成和权限验证的拦截器。 * * @author Jerry * @date 2020-09-24 */ @Slf4j public class AuthenticationInterceptor implements HandlerInterceptor { private final ApplicationConfig appConfig = ApplicationContextHolder.getBean("applicationConfig"); private final RedissonClient redissonClient = ApplicationContextHolder.getBean(RedissonClient.class); private final SysPermService sysPermService = ApplicationContextHolder.getBean(SysPermService.class); private static SysPermWhitelistService sysPermWhitelistService = ApplicationContextHolder.getBean(SysPermWhitelistService.class); private static Set<String> whitelistPermSet; static { List<SysPermWhitelist> sysPermWhitelistList = sysPermWhitelistService.getAllList(); whitelistPermSet = sysPermWhitelistList.stream() .map(SysPermWhitelist::getPermUrl).collect(Collectors.toSet()); } @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { String url = request.getRequestURI(); // 如果接口方法标记NoAuthInterface注解,可以直接跳过Token鉴权验证,这里主要为了测试接口方便 if (handler instanceof HandlerMethod) { HandlerMethod hm = (HandlerMethod) handler; if (hm.getBeanType().getAnnotation(NoAuthInterface.class) != null || hm.getMethodAnnotation(NoAuthInterface.class) != null) { return true; } } String token = request.getHeader(appConfig.getTokenHeaderKey()); if (StringUtils.isBlank(token)) { token = request.getParameter(appConfig.getTokenHeaderKey()); } Claims c = JwtUtil.parseToken(token, appConfig.getTokenSigningKey()); if (JwtUtil.isNullOrExpired(c)) { response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); this.outputResponseMessage(response, ResponseResult.error(ErrorCodeEnum.UNAUTHORIZED_LOGIN, "用户会话已过期或尚未登录,请重新登录!")); return false; } String sessionId = (String) c.get("sessionId"); String sessionIdKey = RedisKeyUtil.makeSessionIdKey(sessionId); RBucket<String> sessionData = redissonClient.getBucket(sessionIdKey); TokenData tokenData = null; if (sessionData.isExists()) { tokenData = JSON.parseObject(sessionData.get(), TokenData.class); } if (tokenData == null) { response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); this.outputResponseMessage(response, ResponseResult.error(ErrorCodeEnum.UNAUTHORIZED_LOGIN, "用户会话已失效,请重新登录!")); return false; } TokenData.addToRequest(tokenData); // 如果url在权限资源白名单中,则不需要进行鉴权操作 if (Boolean.FALSE.equals(tokenData.getIsAdmin()) && !whitelistPermSet.contains(url)) { RSet<String> permSet = redissonClient.getSet(RedisKeyUtil.makeSessionPermIdKey(sessionId)); if (!permSet.contains(url)) { response.setStatus(HttpServletResponse.SC_FORBIDDEN); this.outputResponseMessage(response, ResponseResult.error(ErrorCodeEnum.NO_OPERATION_PERMISSION)); return false; } } if (JwtUtil.needToRefresh(c)) { String refreshedToken = JwtUtil.generateToken(c, appConfig.getExpiration(), appConfig.getTokenSigningKey()); response.addHeader(appConfig.getRefreshedTokenHeaderKey(), refreshedToken); } return true; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { // 这里需要空注解,否则sonar会不happy。 } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { // 这里需要空注解,否则sonar会不happy。 } private void outputResponseMessage(HttpServletResponse response, ResponseResult<Object> respObj) { PrintWriter out; try { out = response.getWriter(); } catch (IOException e) { log.error("Failed to call OutputResponseMessage.", e); return; } response.setContentType("application/json; charset=utf-8"); out.print(JSON.toJSONString(respObj)); out.flush(); out.close(); } }
package com.lohasle.baseframe.s4m3.action.spring.editor; /** * Created by fule on 14-6-12. */ import org.springframework.beans.propertyeditors.PropertiesEditor; public class IntegerEditor extends PropertiesEditor { @Override public void setAsText(String text) throws IllegalArgumentException { if (text == null || text.equals("")) { text = "0"; } setValue(Integer.parseInt(text)); } @Override public String getAsText() { return getValue().toString(); } }