text stringlengths 65 6.05M | lang stringclasses 8 values | type stringclasses 2 values | id stringlengths 64 64 |
|---|---|---|---|
package com.example.semestrovka.models;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*;
import java.time.LocalDateTime;
@Entity
@Table(name="chat_messages")
@AllArgsConstructor
@NoArgsConstructor
@Builder
@Data
public class Message {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@Column(length = 10000, nullable=false, updatable=false)
private String text;
//TODO: стринг сендер заменить на юзер сендер, но это когда настрою секьюрити и смогу в сообщение кидать ник пользователя
@Column(nullable=false, updatable=false)
private String sender;
@Column(nullable=false, updatable=false)
private LocalDateTime createdAt;
}
| Java | CL | 51f1f7652ebbd660c39351d0fb660ccb2b9922395b972fb50d6d15b93c344332 |
/*
* 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.knox.gateway.util;
import java.util.HashSet;
import java.util.Locale;
import java.util.Set;
public class Tokens {
/**
* Get a String derived from a JWT String, which is suitable for presentation (e.g., logging) without compromising
* security.
*
* @param token A BASE64-encoded JWT String.
*
* @return An abbreviated form of the specified JWT String.
*/
public static String getTokenDisplayText(final String token) {
String displayText = null;
if (token !=null) {
if (token.length() >= 7) { // Avoid empty or otherwise invalid values that would break this
displayText =
String.format(Locale.ROOT, "%s...%s", token.substring(0, 6), token.substring(token.length() - 6));
}
}
return displayText;
}
/**
* Get a String derived from a Knox token UUID String, which is suitable for presentation (e.g., logging) without
* compromising security.
*
* @param uuid A Knox token UUID String.
*
* @return An abbreviated form of the specified UUID String.
*/
public static String getTokenIDDisplayText(final String uuid) {
String displayText = null;
if (uuid != null && uuid.length() == 36 && uuid.contains("-")) {
displayText = String.format(Locale.ROOT,
"%s...%s",
uuid.substring(0, uuid.indexOf('-')),
uuid.substring(uuid.lastIndexOf('-') + 1));
}
return displayText;
}
public static Set<String> getDisplayableTokenIDsText(final Set<String> tokenIds) {
Set<String> displayableTokenIds = new HashSet<>();
for (String tokenId : tokenIds) {
displayableTokenIds.add(Tokens.getTokenIDDisplayText(tokenId));
}
return displayableTokenIds;
}
}
| Java | CL | d1816e786fadf334c6a89310fb20e1b06d4bfd422cb8e8b0c96c0d293103ac10 |
// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3)
// Source File Name: WaitUntilFollowersArrive.java
package zombie.behaviors.survivor.orders;
import zombie.behaviors.Behavior;
import zombie.behaviors.survivor.SatisfyIdleBehavior;
import zombie.characters.*;
import zombie.core.Collections.NulledArrayList;
// Referenced classes of package zombie.behaviors.survivor.orders:
// Order, FollowOrder
public class WaitUntilFollowersArrive extends Order
{
public WaitUntilFollowersArrive(IsoGameCharacter chr)
{
super(chr);
timeout = 600;
idle = new SatisfyIdleBehavior();
}
public zombie.behaviors.Behavior.BehaviorResult process()
{
idle.process(null, character);
timeout--;
return zombie.behaviors.Behavior.BehaviorResult.Working;
}
public boolean complete()
{
if(timeout <= 0)
return true;
for(int n = 0; n < character.getDescriptor().getGroup().Members.size(); n++)
{
SurvivorDesc desc = (SurvivorDesc)character.getDescriptor().getGroup().Members.get(n);
if(desc.getInstance() != null && desc.getInstance() != character && !desc.getInstance().isDead() && (desc.getInstance().getOrder() instanceof FollowOrder) && ((FollowOrder)desc.getInstance().getOrder()).target == character && !desc.getInstance().InBuildingWith(character))
return false;
}
return true;
}
public void update()
{
}
SatisfyIdleBehavior idle;
int timeout;
}
| Java | CL | af1b77624173979da2a86a1f42833bb5cdc34c7f59c05c24b8e70402cb771718 |
package com.bytecub.mqtt.service.protocol;
import com.bytecub.common.constants.BCConstants;
import com.bytecub.common.domain.gateway.mq.DeviceUpMessageBo;
import com.bytecub.gateway.mq.producer.DeviceReplyMessageProducer;
import com.bytecub.gateway.mq.producer.DeviceUpMessageProducer;
import com.bytecub.mqtt.domain.bo.ContextBo;
import com.bytecub.mqtt.service.network.SendManager;
import com.bytecub.mqtt.service.state.ClientManager;
import com.bytecub.mqtt.service.state.RetainMsgManager;
import io.netty.buffer.ByteBufUtil;
import io.netty.handler.codec.mqtt.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
/**
* @author songbin
* @version Id: PublishHandle.java, v 0.1 2019/1/16 Exp $$
*/
@Component
public class PublishHandler {
private static final Logger logger = LoggerFactory.getLogger(PublishHandler.class);
public void onPublish(ContextBo contextBo, MqttPublishMessage msg) {
try{
logger.debug("接收到publish请求:{}", msg);
this.retainMsg(msg);
this.pubAck(contextBo, msg);
this.sendMsgToClient(msg);
this.sendMq(msg);
}catch (Exception e){
logger.warn("发消息异常:{}",msg, e);
}
}
private void sendMq(MqttPublishMessage msg){
String topic = msg.variableHeader().topicName();
if(!topic.startsWith(BCConstants.MQTT.GLOBAL_UP_PREFIX)){
/**只处理上行*/
return;
}
DeviceUpMessageBo deviceUpMessageBo = new DeviceUpMessageBo();
deviceUpMessageBo.setTopic(topic);
deviceUpMessageBo.setPacketId((long)msg.variableHeader().packetId());
deviceUpMessageBo.setSourceMsg(ByteBufUtil.getBytes(msg.content()));
if(topic.endsWith(BCConstants.TOPIC.MSG_REPLY) || topic.endsWith(BCConstants.TOPIC.PROP_GET_REPLY)){
DeviceReplyMessageProducer.send(deviceUpMessageBo);
}else{
DeviceUpMessageProducer.send(deviceUpMessageBo);
}
}
/**先给发送的人反馈下收到了*/
private void pubAck(ContextBo contextBo, MqttPublishMessage msg){
MqttQoS mqttQoS = msg.fixedHeader().qosLevel();
MqttFixedHeader fixedHeader = null;
if (mqttQoS.value() <= 1) {
// 不是级别最高的QOS 返回 puback 即可
fixedHeader = new MqttFixedHeader(MqttMessageType.PUBACK, false, mqttQoS, false, 0);
} else {
// 否则发送发布收到 QOS级别会2
fixedHeader = new MqttFixedHeader(MqttMessageType.PUBREC, false, MqttQoS.AT_MOST_ONCE, false, 0);
}
String topicName = msg.variableHeader().topicName();
int msgId = msg.variableHeader().packetId();
MqttMessageIdVariableHeader msgIdVariableHeader = null;
if(msgId > 0){
msgIdVariableHeader = MqttMessageIdVariableHeader.from(msgId);
}
MqttPubAckMessage ackMessage = new MqttPubAckMessage(fixedHeader, msgIdVariableHeader);
if(mqttQoS.value() < 1){
//是0不需要确认
}else{
SendManager.responseMsg(contextBo, ackMessage, msgId, true);
}
}
/**
* 将publish接收到的消息主动推送到该topic下所有终端上去
* */
private void sendMsgToClient(MqttPublishMessage msg){
try{
ClientManager.pubTopic(msg);
}catch (Exception e){
logger.warn("发消息异常:{}",e);
}
}
private void retainMsg( MqttPublishMessage msg){
try{
RetainMsgManager.pushRetain(msg);
}catch (Exception e){
logger.warn("遗留消息处理异常",msg, e);
}
}
}
| Java | CL | 0ab54a9ca23a3368689f3b164e40995c28b275a1d710e6ee2f630ffba2b0d081 |
package org.discontinuous.discgame.abilities;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import org.discontinuous.discgame.Contestant;
import org.discontinuous.discgame.SympGame;
import java.util.ArrayList;
/**
* Created by Urk on 4/9/14.
*/
public class AbilityList {
public static void init_abilities(Contestant contestant, ArrayList<Ability> abilities, BitmapFont font) {
Ability strawman = new Ability(contestant, font, 64, 64, 1, 1, 0, 0,
AbilityTarget.targets.adjacent_square_fresh,
new AbilityEffect(AbilityEffect.effects.multiply, 2, true),
"~ Strawman ~\nConsume an unconsumed adjacent argument for 2x the points and gain.",
"That's a horrible example. What you failed to consider is the following situation...");
strawman.setImg(SympGame.manager.get("img/strawman.png", Texture.class));
abilities.add(strawman);
// Ability tableflip
Ability tableflip = new Ability(contestant, font, 64, 64, 0, 0, 1, 1,
AbilityTarget.targets.self,
new AbilityEffect(AbilityEffect.effects.damage, 3, false),
"~ Tableflip ~\nFlip a table at your opponent, damaging your opponent's argument by 3x type you are on.",
"I will now proceed to flip the everlasting shit out of this table here.");
tableflip.setImg(SympGame.manager.get("img/tableflip.png", Texture.class));
abilities.add(tableflip);
// Ability non sequitur
Ability nonsequitur = new Ability(contestant, font, 64, 64, 1, 1, 1, 1,
AbilityTarget.targets.any_square,
new AbilityEffect(AbilityEffect.effects.multiply, 1, true),
"~ Non Sequitur ~\nDiscreetly move the conversation elsewhere; teleport to and consume any square.",
"If you think about it, you're actually talking about something else, such as this.");
nonsequitur.setImg(SympGame.manager.get("img/nonsequitur.png", Texture.class));
abilities.add(nonsequitur);
// Ability reasonable doubt - surrounding AoE opponent squares consumed
Ability reasonable_doubt = new Ability(contestant, font, 64, 64, 1, 1, 1, 1,
AbilityTarget.targets.self,
new AbilityEffect(AbilityEffect.effects.aoe_consume, 1, false),
"~ Reasonable Doubt ~\nSow doubt and make your opponent's adjacent squares consumed.",
"Are you sure about that? I think you're making a bad assumption.");
reasonable_doubt.setImg(SympGame.manager.get("img/reasonabledoubt.png", Texture.class));
abilities.add(reasonable_doubt);
// Ability double down - refresh and consume an adjacent consumed argument
Ability double_down = new Ability(contestant, font,64, 64, 1, 0, 0, 1,
AbilityTarget.targets.adjacent_square_consumed,
new AbilityEffect(AbilityEffect.effects.refresh_consume, 1, true),
"~ Double Down ~\nRefuse to be wrong and repeat an adjacent, consumed square without penalties.",
"No. Let me repeat it again, just slower and louder, until you understand.");
double_down.setImg(SympGame.manager.get("img/doubledown.png", Texture.class));
abilities.add(double_down);
}
public void AddAbilities(Contestant contestant, Ability[] AbilityList) {
for (Ability ability : AbilityList) {
}
}
}
| Java | CL | 51c9c8ab779eb5a6254fc2d19076be00036f4754a5d9147abf31b68fa73807d6 |
package com.iflytek.aiuiproduct.handler.disposer;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.iflytek.aiui.utils.log.DebugLog;
import com.iflytek.aiuiproduct.constant.ProductConstant;
import com.iflytek.aiuiproduct.handler.entity.SemanticResult;
import com.iflytek.aiuiproduct.handler.entity.ServiceType;
import com.iflytek.aiuiproduct.player.InsType;
import com.iflytek.aiuiproduct.player.entity.SongPlayInfo;
import com.iflytek.aiuiproduct.utils.AppTimeLogger;
import android.content.Context;
import android.content.Intent;
/**
* 音乐结果处理器。
*
* @author <a href="http://www.xfyun.cn">讯飞开放平台</a>
* @date 2016年6月21日 下午4:29:54
*
*/
public class MusicDisposer extends Disposer {
private final static String INSTYPE_SLEEP = "sleep";
private final static String INSTYPE_BROADCAST = "broadcast";
private final static String INSTYPE_BROADCASTSINGER = "broadcastsinger";
public MusicDisposer(Context context) {
super(context);
}
@Override
public void disposeResult(final SemanticResult result) {
JSONObject resultJson = result.getJson();
String operation = resultJson.optString(KEY_OPERATION);
if (OPERATION_INS.equals(operation)) {
parseMusicCommand(result);
} else {
parseMusicResult(result);
}
}
public boolean canHandle(ServiceType type){
if(type == ServiceType.MUSICX){
return true;
}else{
return false;
}
}
public void parseMusicResult(SemanticResult result) {
String uuid = result.getUUID();
AppTimeLogger.onMusicParseStart(uuid);
List<SongPlayInfo> songInfos = parseMusicJson(result);
if (null == songInfos || songInfos.size() <= 0) {
return;
}
AppTimeLogger.onMusicParseEnd(uuid);
if (null != songInfos) {
getPlayController().playSongList(result.getUUID(), songInfos, true);
}
}
public void parseMusicCommand(SemanticResult result) {
JSONObject resultJson = result.getJson();
try {
// 控制语义
JSONObject semantic = resultJson.getJSONObject(KEY_SEMANTIC);
String insType = semantic.getJSONObject(KEY_SLOTS).getString(KEY_INSTYPE);
String uuid = result.getUUID();
AppTimeLogger.setInsType(uuid, insType);
DebugLog.LogD(TAG, "insType" + insType);
if (INSTYPE_SLEEP.equals(insType)) {
Intent intent = new Intent(ProductConstant.ACTION_SLEEP);
intent.putExtra(SemanticResult.KEY_UUID, uuid);
mContext.sendBroadcast(intent);
return;
} else if (INSTYPE_BROADCAST.equals(insType)) {
getPlayController().playCurrentMusicInfo(result.getUUID());
return;
} else if (INSTYPE_BROADCASTSINGER.equals(insType)) {
getPlayController().playCurrentMusicSinger(result.getUUID());
return;
} else {
getPlayController().onMusicCommand(uuid, InsType.parseInsType(insType));
return;
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
private List<SongPlayInfo> parseMusicJson(SemanticResult semanticResult) {
try {
JSONObject jsonObject = semanticResult.getJson();
JSONObject data = jsonObject.getJSONObject(KEY_DATA);
JSONArray result = data.getJSONArray(KEY_RESULT);
if (null != result && result.length() > 0) {
List<SongPlayInfo> songPlayInfos = new ArrayList<SongPlayInfo>();
for (int i = 0; i < result.length(); i++) {
JSONObject songInfoJson = result.getJSONObject(i);
SongPlayInfo playInfo = new SongPlayInfo();
playInfo.setSongName(songInfoJson.optString("songname"));
playInfo.setPlayUrl(songInfoJson.optString("audiopath"));
JSONArray singernames = songInfoJson.optJSONArray("singernames");
if (singernames != null && singernames.length() > 0) {
StringBuffer singerName = new StringBuffer();
for (int j = 0; j < singernames.length(); j++) {
singerName.append(singernames.optString(j) + ",");
}
playInfo.setSingerName(singerName.toString());
}
if(i == 0){
playInfo.setAnswerText(semanticResult.getAnswerText());
}
songPlayInfos.add(playInfo);
}
return songPlayInfos;
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
| Java | CL | 837689e7745f18ced1bb5b2c02d667fa5678d9dedb5b41f05e4a4cd516610cee |
package com.sld.security;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.provider.token.store.InMemoryTokenStore;
/**
* Created by diwu.sld on 2017/6/14.
*/
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfigurer extends AuthorizationServerConfigurerAdapter {
@Autowired
@Qualifier("authenticationManagerBean")
private AuthenticationManager authenticationManager;
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory() // 使用in-memory存储
.withClient("client") // client_id
.secret("secret") // client_secret
.authorizedGrantTypes("password","authorization_code") // 该client允许的授权类型
.scopes("app"); // 允许的授权范围
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.tokenStore(new InMemoryTokenStore())
.authenticationManager(this.authenticationManager);
}
}
| Java | CL | 0053e121040a0d82f39641e1b264ed03cb9d70bb2efff534f9b529a9370fd7ee |
package io.toolisticon.annotationconstraints.processor;
import io.toolisticon.annotationconstraints.processor.testconstraint.SucceedingTestConstraintOnAnnotationAttribute;
@SucceedingTestConstraintOnAnnotationAttribute("OK")
public class SuccessfulConstraintOnAnnotationAttribute {
}
| Java | CL | 1f5b2b8a3f5a6aa2b7ac91b3f2027701ec73a85155421d1ed0c8a0ccf735cb82 |
package com.contatos.revisao.view;
import javax.swing.JDesktopPane;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
public class PrincipalView extends JFrame {
/**
* Creates new form Principal
*/
public PrincipalView() {
initComponents();
setState(JFrame.ICONIFIED);
this.setLocationRelativeTo(this.getParent());
this.setExtendedState(MAXIMIZED_BOTH);
setVisible(true);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
desktop = new javax.swing.JDesktopPane();
mbPrincipal = new javax.swing.JMenuBar();
menuOpcoes = new javax.swing.JMenu();
itemIncluirContatos = new javax.swing.JMenuItem();
itemConsultarContatos = new javax.swing.JMenuItem();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Gestão de Contatos");
menuOpcoes.setText("Opções");
itemIncluirContatos.setText("Incluir contatos");
itemIncluirContatos.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
itemIncluirContatosActionPerformed(evt);
}
});
menuOpcoes.add(itemIncluirContatos);
itemConsultarContatos.setText("Consultar contatos");
itemConsultarContatos.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
itemConsultarContatosActionPerformed(evt);
}
});
menuOpcoes.add(itemConsultarContatos);
mbPrincipal.add(menuOpcoes);
setJMenuBar(mbPrincipal);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(desktop, javax.swing.GroupLayout.DEFAULT_SIZE, 739, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(desktop, javax.swing.GroupLayout.DEFAULT_SIZE, 368, Short.MAX_VALUE)
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void itemConsultarContatosActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_itemConsultarContatosActionPerformed
}//GEN-LAST:event_itemConsultarContatosActionPerformed
private void itemIncluirContatosActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_itemIncluirContatosActionPerformed
}//GEN-LAST:event_itemIncluirContatosActionPerformed
/**
* @param args the command line arguments
*/
public JDesktopPane getDesktop() {
return desktop;
}
public JMenuItem getItemConsultarContatos() {
return itemConsultarContatos;
}
public JMenuItem getItemIncluirContatos() {
return itemIncluirContatos;
}
public JMenuBar getMbPrincipal() {
return mbPrincipal;
}
public JMenu getMenuOpcoes() {
return menuOpcoes;
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JDesktopPane desktop;
private javax.swing.JMenuItem itemConsultarContatos;
private javax.swing.JMenuItem itemIncluirContatos;
private javax.swing.JMenuBar mbPrincipal;
private javax.swing.JMenu menuOpcoes;
// End of variables declaration//GEN-END:variables
}
| Java | CL | 3062b2e1947b79e0e31e02dadc0fba807238749bf2ee599b46ed26f21de21b12 |
package com.github.kakusuke.type;
import java.util.Collection;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.stream.Stream;
/**
* Created by kakusuke on 2014/11/30.
*/
public interface JsonValue {
public static JsonValue valueOf(Object value) {
if (value == null) return JsonPrimitive.nullValue;
if (value instanceof JsonValue) return (JsonValue) value;
if (value instanceof Boolean) return new JsonPrimitive<Boolean>((Boolean) value);
if (value instanceof Number) return new JsonPrimitive<Number>((Number) value);
if (value instanceof String) return new JsonPrimitive<String>((String) value);
if (value instanceof Collection) return new JsonArray<>((Collection<?>) value);
if (value instanceof Stream) return new JsonArray<>((Stream<?>) value);
if (value instanceof Consumer) return new JsonObject((Consumer<JsonObject>) value);
return JsonPrimitive.nullValue;
}
public static <E> JsonValue valueOf(Collection value, BiConsumer<JsonObject, E> biConsumer) {
if (value == null) return JsonPrimitive.nullValue;
return valueOf(value.stream(), biConsumer);
}
public static <E> JsonValue valueOf(Stream<E> value, BiConsumer<JsonObject, E> biConsumer) {
if (value == null) return JsonPrimitive.nullValue;
return JsonValue.valueOf(value.map((v) -> new JsonObject(biConsumer, v)));
}
}
| Java | CL | 6512a5dc604d0e8f3bb37375847645ef74bfc64fbfed0818186bb47542386b44 |
package main.pluralsight.set;
import java.util.Collection;
import java.util.SortedSet;
import java.util.TreeSet;
import main.pluralsight.Product;
import main.pluralsight.comparator.WeightComparator;
import main.pluralsight.list.ShipableItem;
/**
* The catalogue can contain more than one type of items from the ShipableItem
* interface, unlike the Shipment class that takes only a specific type
*
* @author Sophie
*
*/
public class ProductCatalogue {
// no duplicates
private final SortedSet<ShipableItem> catalogue;
public ProductCatalogue() {
catalogue = new TreeSet<>(new WeightComparator());
}
public void isSuppliedBy(Supplier supplier) {
catalogue.addAll(supplier.products());
}
//
public boolean contains(Collection<? super ShipableItem> items) {
return catalogue.containsAll(items);
}
public SortedSet<ShipableItem> getLightProducts() {
// exclusive of that break point
return catalogue.headSet(findBreakPoint());
}
public SortedSet<ShipableItem> getHeavyProducts() throws NullPointerException {
// inclusive
return catalogue.tailSet(findBreakPoint());
}
private ShipableItem findBreakPoint() {
for (ShipableItem product : catalogue) {
if (product.getWeight() > 20) {
return product;
}
}
return null;
}
}
| Java | CL | 331e10cea2afa07f29f0f105f0dd83b3d4715a857c47abcde408f5669ebabbd7 |
/**
* Copyright 2013-2014 Guoqiang Chen, Shanghai, China. All rights reserved.
*
* Email: subchen@gmail.com
* URL: http://subchen.github.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 jetbrick.samples.controller;
import jetbrick.util.fastjson.JSON;
import jetbrick.web.mvc.Model;
import jetbrick.web.mvc.action.Action;
import jetbrick.web.mvc.action.Controller;
import jetbrick.web.mvc.action.annotation.RequestParam;
import com.alibaba.fastjson.JSONAware;
@Controller("/param")
public class RequestParamController {
@Action
public JSONAware name(Model model, @RequestParam("id") int id, @RequestParam("name") String name) {
model.add("id", id);
model.add("name", name);
return JSON.toJSON(model);
}
@Action
public JSONAware auto(Model model, @RequestParam int id, @RequestParam String name) {
model.add("id", id);
model.add("name", name);
return JSON.toJSON(model);
}
@Action
public JSONAware ids(Model model, @RequestParam int[] id) {
model.add("id", id);
return JSON.toJSON(model);
}
@Action
public JSONAware names(Model model, @RequestParam String[] name) {
model.add("name", name);
return JSON.toJSON(model);
}
}
| Java | CL | fbcf8ad83e199cd843c54da050545915b279289bc24288290d964a54a74abec9 |
/*******************************************************************************
* This files was developed for CS4233: Object-Oriented Analysis & Design.
* The course was taken at Worcester Polytechnic Institute.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Copyright ©2020 Gary F. Pollice
*******************************************************************************/
package escape;
import java.io.*;
import javax.xml.bind.*;
import javax.xml.transform.stream.StreamSource;
import org.antlr.v4.runtime.CharStreams;
import econfig.EscapeConfigurator;
import escape.board.*;
import escape.coordinate.*;
import escape.exception.EscapeGameInitializationException;
import escape.location.LocationInitializer;
import escape.piece.*;
import escape.util.*;
import static escape.piece.EscapePiece.PieceAttributeID.*;
/**
* This class builds an instance of an EscapeGameManager from a configuration
* file (.egc). This uses the EscapeConfigurator for XML to turnthe .egc file
* into a valid XML string that is then unmarshalled into an EscapeGameInitializer
* file.
*
* MODIFIABLE: YES
* MOVEABLE: NO
* REQUIRED: YES
*
* >>>THIS IS AN EXAMPLE STARTER FILE<<<
* You must change this class to be able to get the data from the configurtion
* file and implement the makeGameManager() method. You may not change the signature
* of that method or the constructor for this class. You can change the file any
* other way that you need to.
*
* You do not have to use JAXB to create XML. You might use GSON if you are more
* familiar with it. You also don't have to use the EscapeGameInitializer object if
* you have a way that better suits your design and capabilities. Don't go down
* a rathole, however, in order to use something different. This implementation
* works and will not take much time to modify the EscapeGameInitializer to create
* your game instance.
*/
public class EscapeGameBuilder
{
private final EscapeGameInitializer gameInitializer;
private PieceMovementMissMatch pmmm;
/**
* The constructor takes a file that points to the Escape game
* configuration file. It should get the necessary information
* to be ready to create the game manager specified by the configuration
* file and other configuration files that it links to.
* @param fileName the file for the Escape game configuration file (.egc).
* @throws Exception on any errors
*/
public EscapeGameBuilder(String fileName) throws Exception
{
String xmlConfiguration = getXmlConfiguration(fileName);
// Uncomment the next instruction if you want to see the XML
// System.err.println(xmlConfiguration);
gameInitializer = unmarshalXml(xmlConfiguration);
}
/**
* Take the .egc file contents and turn it into XML.
* If you want to use JSON, you should change the name of this method and
* initizlize the EscapeConfigurator with this code:
* EscapeConfigurator configurator = new EscapeConfigurator(EscapeConfigurationJsonMaker());
* @param fileName
* @return the XML data needed to
* @throws IOException
*/
private String getXmlConfiguration(String fileName) throws IOException
{
EscapeConfigurator configurator = new EscapeConfigurator();
return configurator.makeConfiguration(CharStreams.fromFileName(fileName));
}
/**
* Unmarshal the XML into an EscapeGameInitializer object.
* @param xmlConfiguration
* @throws JAXBException
*/
private EscapeGameInitializer unmarshalXml(String xmlConfiguration) throws JAXBException
{
JAXBContext contextObj = JAXBContext.newInstance(EscapeGameInitializer.class);
Unmarshaller mub = contextObj.createUnmarshaller();
return (EscapeGameInitializer)mub.unmarshal(
new StreamSource(new StringReader(xmlConfiguration)));
}
/**
* Getter for the gameInitializer. Can be used to examine it after the builder
* creates it.
* @return the gameInitializer
*/
public EscapeGameInitializer getGameInitializer()
{
return gameInitializer;
}
/**
* Once the builder is constructed, this method creates the
* EscapeGameManager instance. For this example, you would use the
* gameInitializer object to get all of the information you need to create
* your game.
* @return the game instance
*/
public EscapeGameManager makeGameManager()
{
// >>> YOU MUST IMPLEMENT THIS METHOD<<<
//escapgeGeameManagerImpl EscapeGameManagerImpl<C extends EscapeCoordinate> implements EscapeGameManager<C>
EscapeGameManagerImpl<EscapeCoordinate> egm =
new EscapeGameManagerImpl<EscapeCoordinate>(gameInitializer.getCoordinateType());
//EscpabeBoard
//egm.setboard(board);
//initializeboard(board, egm ...
// return egm
// Now make the board with the pieces on it
EscapeBoard board = new EscapeBoard( // gameInitializer.getCoordinateType(),
gameInitializer.getxMax(), gameInitializer.getyMax());
egm.setBoard(board);
initializeBoard(board, egm.getCoordinateFactory());
return egm;
}
//go trhoug and initialize all objects from in gameInitializer.
//initializeboard(board, CoordinateFactory)
/**
* Initialize the board by setting the location types and place the pieces on the board.
* @param board
*/
private void initializeBoard(GameBoard board, CoordinateFactory factory)
{
PieceTypeDescriptorArray ptdp = new PieceTypeDescriptorArray(gameInitializer.getPieceTypes());
for (LocationInitializer li : gameInitializer.getLocationInitializers()) {
EscapeCoordinate c = factory.makeCoordinate(li.x, li.y);
if (li.locationType != null) {
board.setLocationType(c, li.locationType);
}
if (li.player != null && li.pieceName != null) {
EscapePieceImpl p = new EscapePieceImpl(li.player, li.pieceName);
PieceTypeDescriptor ptd = ptdp.getDescriptor(li.pieceName);
if (ptd == null) {
throw new EscapeGameInitializationException(
"No piece type descriptor for " + li.pieceName);
}
pmmm = new PieceMovementMissMatch(c,p); //Throw if the movmentpattern in p is not alllowed for given board shape
p.setDescriptor(ptd);
if (p.hasAttribute(VALUE)) {
p.setValue(p.getAttribute(VALUE).getValue());
}
board.putPieceAt(c, p);
} else if (li.player != null) {
throw new EscapeGameInitializationException(
"Missing piece name in location initializer");
} else if (li.pieceName != null) {
throw new EscapeGameInitializationException(
"Missing player name in location initializer");
}
}
}
}
| Java | CL | 58d8ffc59f7cc429d197fbe111c9662fdde00a4aa05c5510acfa1074818030b9 |
package com.artilligence.auth_server.oauth;
import com.artilligence.auth_server.domains.OauthClient;
import com.artilligence.auth_server.domains.OauthSession;
import com.artilligence.auth_server.domains.User;
import com.artilligence.auth_server.exceptions.NotFoundException;
import com.artilligence.auth_server.repositories.UserRepository;
import com.artilligence.auth_server.services.SessionManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
@RestController
public class Controller {
@Autowired
SessionManager sessionManager;
@Autowired
private Repository repository;
@Autowired
private UserRepository userRepository;
@GetMapping("/authorize")
public void Authorize(
HttpServletResponse response,
@RequestParam(value = "client_id") String clientId,
@RequestParam(value = "client_secret") String clientSecret,
@RequestParam(value = "redirect_url") String redirectUrl,
@RequestParam(value = "password") String password,
@RequestParam(value = "email") String email
) throws IOException, NotFoundException, NoSuchAlgorithmException {
OauthClient oauthClient = repository.getClient(clientId);
oauthClient.hasScopes(new String[] {"oauth"});
oauthClient.hisUrl(redirectUrl);
User user = userRepository.getByEmailAndPassword(email, password, true);
OauthSession session = sessionManager.startSession(oauthClient, user);
String url = String.format("%s?code=%s", redirectUrl, session.getPojo().getCode());
response.sendRedirect(url);
}
}
| Java | CL | ad1513357d75ce6d0e471646accc2e1264468d47c0e5a1addfd56e5b0df73755 |
/**
* Postmultiplies this matrix by a translation matrix.
* @param trn The translation vector.
* @return This matrix for the purpose of chaining.
*/
public Affine2 translate(Vector2 trn) {
return translate(trn.x, trn.y);
}
| Java | CL | a09c92c5e7f9eba892e08f09f8593d83dec2b535b8f08b8dad03aea780710d1d |
/**
* j-Interop (Pure Java implementation of DCOM protocol)
*
* Copyright (c) 2013 Vikram Roopchand
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Vikram Roopchand - Moving to EPL from LGPL v3.
*
*/
package org.jinterop.dcom.core;
/** Class representing various flags used in the system.
*
* @since 1.0
*/
public final class JIFlags {
private JIFlags(){}
/**
* FLAG representing nothing. Use this if no other flag is to be set.
*/
public static final int FLAG_NULL = 0;
//bstr string
/**
* FLAG representing a <code>BSTR</code> string .
**/
public static final int FLAG_REPRESENTATION_STRING_BSTR = 1;
/**
* FLAG representing a normal String.
*/
public static final int FLAG_REPRESENTATION_STRING_LPCTSTR = 2;
/**
* FLAG representing a Wide Char (16 bit characters)
*/
public static final int FLAG_REPRESENTATION_STRING_LPWSTR = 4;
/**
* @exclude
*/
//flag representing an array
public static final int FLAG_REPRESENTATION_ARRAY = 8;
/**
* @exclude
*/
//flag representing that this is a pointer
static final int FLAG_REPRESENTATION_POINTER = 16;
/**
* @exclude
*/
//flag representing that this is a reference
static final int FLAG_REPRESENTATION_REFERENCE = 32;
/**
* @exclude
*/
//flag representing that this is a IDispatch invoke call
public static final int FLAG_REPRESENTATION_IDISPATCH_INVOKE = 64;
/**
* @exclude
*/
//flag representing that this is a IDispatch invoke call
static final int FLAG_REPRESENTATION_NESTED_POINTER = 128;
/**
* Flag representing unsigned byte.
*/
public static final int FLAG_REPRESENTATION_UNSIGNED_BYTE = 256;
/**
* Flag representing unsigned short.
*/
public static final int FLAG_REPRESENTATION_UNSIGNED_SHORT = 512;
/**
* Flag representing unsigned integer.
*/
public static final int FLAG_REPRESENTATION_UNSIGNED_INT = 1024;
/**
* Flag representing integer of the type VT_INT.
*/
public static final int FLAG_REPRESENTATION_VT_INT = 2048;
/**
* Flag representing (unsigned) integer of the type VT_UINT.
*/
public static final int FLAG_REPRESENTATION_VT_UINT = 4096;
/**
* Flag representing <code>VARIANT_BOOL</code>, a <code>boolean</code> is
* 2 bytes for a <code>VARIANT</code> and 1 byte for normal calls.
* Use this when setting array of <code>boolean</code>s within <code>VARIANT</code>s.
*/
public static final int FLAG_REPRESENTATION_VARIANT_BOOL = 8192;
/**
* Represents an internal flag, which will disallow direct Strings from being marshalled or unmarshalled. Come via JIString only.
*/
static final int FLAG_REPRESENTATION_VALID_STRING = 16384;
/**
* Used from within JIInterfacePointer to use decode2 API.
*/
static final int FLAG_REPRESENTATION_INTERFACEPTR_DECODE2 = 32768;
/**
* Used in JIVariant when sending a IUnknown Pointer. This is also how COM runtime does it.
* A little strange to expect this behaviour since essentially all objects derieve from IUnknown so why replace the
* IID ?
*/
static final int FLAG_REPRESENTATION_USE_IUNKNOWN_IID = 65536;
/**
* Used in JIVariant when sending a IDispatch Pointer. This is also how COM runtime does it.
*/
static final int FLAG_REPRESENTATION_USE_IDISPATCH_IID = 131072;
/**
* Used in JIVariant to identify an ([out] IUnknown*) variable.
*/
static final int FLAG_REPRESENTATION_IUNKNOWN_NULL_FOR_OUT = 262144;
/**
* Used in JIVariant to identify an ([out] IDispatch*) variable.
*/
static final int FLAG_REPRESENTATION_IDISPATCH_NULL_FOR_OUT = 524288;
/**
* Used in JIVariant to send JIInterfacePointer as null.
*/
static final int FLAG_REPRESENTATION_SET_JIINTERFACEPTR_NULL_FOR_VARIANT = 1048576;
}
| Java | CL | c6b3255e63b693d652bdb9ec27ed447813833e6d1ab909dc735f82285109e11e |
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// This file is autogenerated by:
// mojo/public/tools/bindings/mojom_bindings_generator.py
// For:
// mojo/shell/public/interfaces/shell_resolver.mojom
//
package org.chromium.mojom.mojo.shell.mojom;
import org.chromium.base.annotations.SuppressFBWarnings;
class ShellResolver_Internal {
public static final org.chromium.mojo.bindings.Interface.Manager<ShellResolver, ShellResolver.Proxy> MANAGER =
new org.chromium.mojo.bindings.Interface.Manager<ShellResolver, ShellResolver.Proxy>() {
public String getName() {
return "mojo::shell::mojom::ShellResolver";
}
public int getVersion() {
return 0;
}
public Proxy buildProxy(org.chromium.mojo.system.Core core,
org.chromium.mojo.bindings.MessageReceiverWithResponder messageReceiver) {
return new Proxy(core, messageReceiver);
}
public Stub buildStub(org.chromium.mojo.system.Core core, ShellResolver impl) {
return new Stub(core, impl);
}
public ShellResolver[] buildArray(int size) {
return new ShellResolver[size];
}
};
private static final int RESOLVE_MOJO_NAME_ORDINAL = 0;
static final class Proxy extends org.chromium.mojo.bindings.Interface.AbstractProxy implements ShellResolver.Proxy {
Proxy(org.chromium.mojo.system.Core core,
org.chromium.mojo.bindings.MessageReceiverWithResponder messageReceiver) {
super(core, messageReceiver);
}
@Override
public void resolveMojoName(
String mojoName,
ResolveMojoNameResponse callback) {
ShellResolverResolveMojoNameParams _message = new ShellResolverResolveMojoNameParams();
_message.mojoName = mojoName;
getProxyHandler().getMessageReceiver().acceptWithResponder(
_message.serializeWithHeader(
getProxyHandler().getCore(),
new org.chromium.mojo.bindings.MessageHeader(
RESOLVE_MOJO_NAME_ORDINAL,
org.chromium.mojo.bindings.MessageHeader.MESSAGE_EXPECTS_RESPONSE_FLAG,
0)),
new ShellResolverResolveMojoNameResponseParamsForwardToCallback(callback));
}
}
static final class Stub extends org.chromium.mojo.bindings.Interface.Stub<ShellResolver> {
Stub(org.chromium.mojo.system.Core core, ShellResolver impl) {
super(core, impl);
}
@Override
public boolean accept(org.chromium.mojo.bindings.Message message) {
try {
org.chromium.mojo.bindings.ServiceMessage messageWithHeader =
message.asServiceMessage();
org.chromium.mojo.bindings.MessageHeader header = messageWithHeader.getHeader();
if (!header.validateHeader(org.chromium.mojo.bindings.MessageHeader.NO_FLAG)) {
return false;
}
switch(header.getType()) {
case org.chromium.mojo.bindings.InterfaceControlMessagesConstants.RUN_OR_CLOSE_PIPE_MESSAGE_ID:
return org.chromium.mojo.bindings.InterfaceControlMessagesHelper.handleRunOrClosePipe(
ShellResolver_Internal.MANAGER, messageWithHeader);
default:
return false;
}
} catch (org.chromium.mojo.bindings.DeserializationException e) {
System.err.println(e.toString());
return false;
}
}
@Override
public boolean acceptWithResponder(org.chromium.mojo.bindings.Message message, org.chromium.mojo.bindings.MessageReceiver receiver) {
try {
org.chromium.mojo.bindings.ServiceMessage messageWithHeader =
message.asServiceMessage();
org.chromium.mojo.bindings.MessageHeader header = messageWithHeader.getHeader();
if (!header.validateHeader(org.chromium.mojo.bindings.MessageHeader.MESSAGE_EXPECTS_RESPONSE_FLAG)) {
return false;
}
switch(header.getType()) {
case org.chromium.mojo.bindings.InterfaceControlMessagesConstants.RUN_MESSAGE_ID:
return org.chromium.mojo.bindings.InterfaceControlMessagesHelper.handleRun(
getCore(), ShellResolver_Internal.MANAGER, messageWithHeader, receiver);
case RESOLVE_MOJO_NAME_ORDINAL: {
ShellResolverResolveMojoNameParams data =
ShellResolverResolveMojoNameParams.deserialize(messageWithHeader.getPayload());
getImpl().resolveMojoName(data.mojoName, new ShellResolverResolveMojoNameResponseParamsProxyToResponder(getCore(), receiver, header.getRequestId()));
return true;
}
default:
return false;
}
} catch (org.chromium.mojo.bindings.DeserializationException e) {
System.err.println(e.toString());
return false;
}
}
}
static final class ShellResolverResolveMojoNameParams extends org.chromium.mojo.bindings.Struct {
private static final int STRUCT_SIZE = 16;
private static final org.chromium.mojo.bindings.DataHeader[] VERSION_ARRAY = new org.chromium.mojo.bindings.DataHeader[] {new org.chromium.mojo.bindings.DataHeader(16, 0)};
private static final org.chromium.mojo.bindings.DataHeader DEFAULT_STRUCT_INFO = VERSION_ARRAY[0];
public String mojoName;
private ShellResolverResolveMojoNameParams(int version) {
super(STRUCT_SIZE, version);
}
public ShellResolverResolveMojoNameParams() {
this(0);
}
public static ShellResolverResolveMojoNameParams deserialize(org.chromium.mojo.bindings.Message message) {
return decode(new org.chromium.mojo.bindings.Decoder(message));
}
@SuppressWarnings("unchecked")
public static ShellResolverResolveMojoNameParams decode(org.chromium.mojo.bindings.Decoder decoder0) {
if (decoder0 == null) {
return null;
}
org.chromium.mojo.bindings.DataHeader mainDataHeader = decoder0.readAndValidateDataHeader(VERSION_ARRAY);
ShellResolverResolveMojoNameParams result = new ShellResolverResolveMojoNameParams(mainDataHeader.elementsOrVersion);
if (mainDataHeader.elementsOrVersion >= 0) {
result.mojoName = decoder0.readString(8, false);
}
return result;
}
@SuppressWarnings("unchecked")
@Override
protected final void encode(org.chromium.mojo.bindings.Encoder encoder) {
org.chromium.mojo.bindings.Encoder encoder0 = encoder.getEncoderAtDataOffset(DEFAULT_STRUCT_INFO);
encoder0.encode(mojoName, 8, false);
}
/**
* @see Object#equals(Object)
*/
@Override
public boolean equals(Object object) {
if (object == this)
return true;
if (object == null)
return false;
if (getClass() != object.getClass())
return false;
ShellResolverResolveMojoNameParams other = (ShellResolverResolveMojoNameParams) object;
if (!org.chromium.mojo.bindings.BindingsHelper.equals(this.mojoName, other.mojoName))
return false;
return true;
}
/**
* @see Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = prime + getClass().hashCode();
result = prime * result + org.chromium.mojo.bindings.BindingsHelper.hashCode(mojoName);
return result;
}
}
static final class ShellResolverResolveMojoNameResponseParams extends org.chromium.mojo.bindings.Struct {
private static final int STRUCT_SIZE = 16;
private static final org.chromium.mojo.bindings.DataHeader[] VERSION_ARRAY = new org.chromium.mojo.bindings.DataHeader[] {new org.chromium.mojo.bindings.DataHeader(16, 0)};
private static final org.chromium.mojo.bindings.DataHeader DEFAULT_STRUCT_INFO = VERSION_ARRAY[0];
public ResolveResult result;
private ShellResolverResolveMojoNameResponseParams(int version) {
super(STRUCT_SIZE, version);
}
public ShellResolverResolveMojoNameResponseParams() {
this(0);
}
public static ShellResolverResolveMojoNameResponseParams deserialize(org.chromium.mojo.bindings.Message message) {
return decode(new org.chromium.mojo.bindings.Decoder(message));
}
@SuppressWarnings("unchecked")
public static ShellResolverResolveMojoNameResponseParams decode(org.chromium.mojo.bindings.Decoder decoder0) {
if (decoder0 == null) {
return null;
}
org.chromium.mojo.bindings.DataHeader mainDataHeader = decoder0.readAndValidateDataHeader(VERSION_ARRAY);
ShellResolverResolveMojoNameResponseParams result = new ShellResolverResolveMojoNameResponseParams(mainDataHeader.elementsOrVersion);
if (mainDataHeader.elementsOrVersion >= 0) {
org.chromium.mojo.bindings.Decoder decoder1 = decoder0.readPointer(8, false);
result.result = ResolveResult.decode(decoder1);
}
return result;
}
@SuppressWarnings("unchecked")
@Override
protected final void encode(org.chromium.mojo.bindings.Encoder encoder) {
org.chromium.mojo.bindings.Encoder encoder0 = encoder.getEncoderAtDataOffset(DEFAULT_STRUCT_INFO);
encoder0.encode(result, 8, false);
}
/**
* @see Object#equals(Object)
*/
@Override
public boolean equals(Object object) {
if (object == this)
return true;
if (object == null)
return false;
if (getClass() != object.getClass())
return false;
ShellResolverResolveMojoNameResponseParams other = (ShellResolverResolveMojoNameResponseParams) object;
if (!org.chromium.mojo.bindings.BindingsHelper.equals(this.result, other.result))
return false;
return true;
}
/**
* @see Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = prime + getClass().hashCode();
result = prime * result + org.chromium.mojo.bindings.BindingsHelper.hashCode(result);
return result;
}
}
static class ShellResolverResolveMojoNameResponseParamsForwardToCallback extends org.chromium.mojo.bindings.SideEffectFreeCloseable
implements org.chromium.mojo.bindings.MessageReceiver {
private final ShellResolver.ResolveMojoNameResponse mCallback;
ShellResolverResolveMojoNameResponseParamsForwardToCallback(ShellResolver.ResolveMojoNameResponse callback) {
this.mCallback = callback;
}
@Override
public boolean accept(org.chromium.mojo.bindings.Message message) {
try {
org.chromium.mojo.bindings.ServiceMessage messageWithHeader =
message.asServiceMessage();
org.chromium.mojo.bindings.MessageHeader header = messageWithHeader.getHeader();
if (!header.validateHeader(RESOLVE_MOJO_NAME_ORDINAL,
org.chromium.mojo.bindings.MessageHeader.MESSAGE_IS_RESPONSE_FLAG)) {
return false;
}
ShellResolverResolveMojoNameResponseParams response = ShellResolverResolveMojoNameResponseParams.deserialize(messageWithHeader.getPayload());
mCallback.call(response.result);
return true;
} catch (org.chromium.mojo.bindings.DeserializationException e) {
return false;
}
}
}
static class ShellResolverResolveMojoNameResponseParamsProxyToResponder implements ShellResolver.ResolveMojoNameResponse {
private final org.chromium.mojo.system.Core mCore;
private final org.chromium.mojo.bindings.MessageReceiver mMessageReceiver;
private final long mRequestId;
ShellResolverResolveMojoNameResponseParamsProxyToResponder(
org.chromium.mojo.system.Core core,
org.chromium.mojo.bindings.MessageReceiver messageReceiver,
long requestId) {
mCore = core;
mMessageReceiver = messageReceiver;
mRequestId = requestId;
}
@Override
public void call(ResolveResult result) {
ShellResolverResolveMojoNameResponseParams _response = new ShellResolverResolveMojoNameResponseParams();
_response.result = result;
org.chromium.mojo.bindings.ServiceMessage _message =
_response.serializeWithHeader(
mCore,
new org.chromium.mojo.bindings.MessageHeader(
RESOLVE_MOJO_NAME_ORDINAL,
org.chromium.mojo.bindings.MessageHeader.MESSAGE_IS_RESPONSE_FLAG,
mRequestId));
mMessageReceiver.accept(_message);
}
}
}
| Java | CL | c07ee8e438e593c2433431f968225c0761533d42afe8848a7632a71ac672f7f0 |
/* SPDX-License-Identifier: Apache-2.0 */
/* Copyright Contributors to the ODPi Egeria project. */
package org.odpi.openmetadata.adapters.adminservices.configurationstore.encryptedfile;
import org.odpi.openmetadata.adminservices.store.OMAGServerConfigStoreProviderBase;
import org.odpi.openmetadata.frameworks.connectors.properties.beans.ConnectorType;
/**
* EncryptedFileBasedUIServerConfigStoreProvider is the OCF connector provider for the encrypted file based UI server
* configuration store.
*/
public class EncryptedFileBasedUIServerConfigStoreProvider extends OMAGServerConfigStoreProviderBase {
static final String connectorTypeGUID = "0de0edb0-9ca9-464d-b40b-5cd964668140";
static final String connectorTypeName = "Encrypted File Based UI Server Config Store Connector";
static final String connectorTypeDescription = "Connector supports storing of UI Server configuration document in an encrypted file.";
/**
* Constructor used to initialize the ConnectorProviderBase with the Java class name of the specific
* configuration store implementation.
*/
public EncryptedFileBasedUIServerConfigStoreProvider() {
Class connectorClass = EncryptedFileBasedUIServerConfigStoreConnector.class;
super.setConnectorClassName(connectorClass.getName());
ConnectorType connectorType = new ConnectorType();
connectorType.setType(ConnectorType.getConnectorTypeType());
connectorType.setGUID(connectorTypeGUID);
connectorType.setQualifiedName(connectorTypeName);
connectorType.setDisplayName(connectorTypeName);
connectorType.setDescription(connectorTypeDescription);
connectorType.setConnectorProviderClassName(this.getClass().getName());
super.connectorTypeBean = connectorType;
}
}
| Java | CL | 9d20e6c1ae705f0200d6ae2727473d90677aab98f1f220cdfd0bfe4234ed4c97 |
package org.jboss.pressgang.ccms.utils.common;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
/**
* A set of utilities to read from the local application resources.
*/
public class ResourceUtilities {
private static final Logger LOG = LoggerFactory.getLogger(ResourceUtilities.class);
/**
* Reads a resource file and converts it into a String
*
* @param location The location of the resource file.
* @param fileName The name of the file.
* @return The string that represents the contents of the file or null if an error occurred.
*/
public static String resourceFileToString(final String location, final String fileName) {
if (location == null || fileName == null) return null;
final InputStream in = ResourceUtilities.class.getResourceAsStream(location + fileName);
if (in == null) return null;
final BufferedReader br = new BufferedReader(new InputStreamReader(in));
String line;
final StringBuilder output = new StringBuilder("");
try {
while ((line = br.readLine()) != null) {
output.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
in.close();
} catch (IOException e) {
LOG.error("Failed to close the InputStream", e);
}
try {
br.close();
} catch (IOException e) {
LOG.error("Failed to close the BufferedReader", e);
}
}
return output.toString();
}
/**
* Reads a resource file and converts it into a XML based Document object.
*
* @param location The location of the resource file.
* @param fileName The name of the file.
* @return The Document that represents the contents of the file or null if an error occurred.
*/
public static Document resourceFileToXMLDocument(final String location, final String fileName) {
if (location == null || fileName == null) return null;
final InputStream in = ResourceUtilities.class.getResourceAsStream(location + fileName);
if (in == null) return null;
final DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
final DocumentBuilder dBuilder;
Document doc = null;
try {
dBuilder = dbFactory.newDocumentBuilder();
doc = dBuilder.parse(in);
} catch (Exception e) {
LOG.error("Failed to parse the resource as XML.", e);
} finally {
try {
in.close();
} catch (IOException e) {
LOG.error("Failed to close the InputStream", e);
}
}
return doc;
}
/**
* Reads a resource file and converts it into a String
*
* @param location The location of the resource file.
* @param fileName The name of the file.
* @return The string that represents the contents of the file or null if an error occurred.
*/
public static byte[] resourceFileToByteArray(final String location, final String fileName) {
if (location == null || fileName == null) return null;
final InputStream in = ResourceUtilities.class.getResourceAsStream(location + fileName);
if (in == null) return null;
final ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
// Create the byte array to hold the data
final byte[] buffer = new byte[1024];
// Read in the bytes
int numRead = 0;
while((numRead = in.read(buffer)) > 0) {
out.write(buffer, 0, numRead);
}
} catch (final Exception ex) {
LOG.error("An error occurred while reading the file contents", ex);
} finally {
try {
in.close();
} catch (final Exception ex) {
LOG.error("Failed to close the InputStream", ex);
}
}
return out.toByteArray();
}
}
| Java | CL | 3362d4a0706c50ed2e2b598ac6512106244be8a06c04f27fef6d1ab69a2b22b3 |
package com.lakeacr.asoms.dao;
import java.util.List;
import com.lakeacr.asoms.domain.Examiner;
/**
*
* @author SURAJ CHANDEL
*
*/
public interface ExaminerDao {
/**
*
* @param id
* @return
*/
public Examiner findById(long id);
/**
*
* @param examiner
* @return
*/
public Examiner saveOrUpdate(Examiner examiner);
/**
* @param examiners
* @return
*/
public List<Examiner> saveAll(List<Examiner> examiners);
/**
*
* @param userId
* @return
*/
public void deleteById(long id);
/**
*
* @return
*/
public List<Examiner> findAll();
/**
*
* @return
*/
public int countActive();
}
| Java | CL | 7845b94d29e9c6bb1eaada48400f9854572b5f8eeabc38039dd1647f26b1b51e |
package dev.xdark.clientapi.item;
import dev.xdark.clientapi.Side;
import dev.xdark.clientapi.SidedApi;
import dev.xdark.clientapi.block.state.BlockState;
import dev.xdark.clientapi.gui.CreativeTab;
import dev.xdark.clientapi.resource.ResourceLocation;
import dev.xdark.clientapi.util.CompileStub;
import java.util.UUID;
import static dev.xdark.clientapi.util.SideEffects.objectValue;
@SidedApi(Side.SERVER)
public interface Item {
UUID ATTACK_DAMAGE_MODIFIER = objectValue(), ATTACK_SPEED_MODIFIER = objectValue();
static Item of(int id) {
throw CompileStub.create();
}
static Item of(String idOrLocation) {
throw CompileStub.create();
}
ResourceLocation getLocation();
int getId();
boolean hasCustomProperties();
int getItemStackLimit();
boolean hasSubtypes();
int getMaxDamage();
boolean isDamageable();
boolean isFull3D();
boolean shouldRotateAroundWhenRendering();
String getTranslationKey();
String getTranslationKey(ItemStack stack);
Item getContainerItem();
ItemStack newStack(int amount, int damage);
ItemProperty getPropertyOverride(ResourceLocation location);
float getDestroySpeed(ItemStack stack, BlockState state);
int getMetadata(int i);
boolean canHarvestBlock(BlockState state);
boolean hasContainerItem();
UseAction getUseAction(ItemStack stack);
int getMaxUseDuration(ItemStack stack);
boolean hasEffect(ItemStack stack);
Rarity getRarity(ItemStack stack);
boolean isEnchantable(ItemStack stack);
CreativeTab getCreativeTab();
boolean isRepairable(ItemStack toRepair, ItemStack repair);
int getEnchantability();
@SidedApi(Side.SERVER)
interface Builder {
static Builder builder() {
throw CompileStub.create();
}
Builder destroyHandler(BlockDestroyHandler destroyHandler);
Builder harvestHandler(BlockHarvestHandler harvestHandler);
Builder hitHandler(EntityHitHandler hitHandler);
Builder interactHandler(EntityInteractHandler interactHandler);
Builder stoppedUsingHandler(EntityStoppedUsingHandler stoppedUsingHandler);
Builder createHandler(ItemCreateHandler createHandler);
Builder informationHandler(ItemInformationHandler informationHandler);
Builder rightClickHandler(ItemRightClickHandler rightClickHandler);
Builder useHandler(ItemUseHandler useHandler);
Builder useFinishHandler(ItemUseFinishHandler useFinishHandler);
Builder useActionHandler(ItemUseActionHandler useActionHandler);
Builder destroySpeedHandler(BlockDestroySpeedHandler destroySpeedHandler);
Builder metadataHandler(ItemMetadataHandler metadataHandler);
Builder effectHandler(ItemEffectHandler effectHandler);
Builder rarityHandler(ItemRarityHandler rarityHandler);
Builder enchantHandler(ItemEnchantHandler enchantHandler);
Builder attributeHandler(ItemAttributeHandler attributeHandler);
Builder repairHandler(ItemRepairHandler repairHandler);
Builder creativeTab(CreativeTab creativeTab);
Builder property(ResourceLocation location, ItemProperty property);
Builder maxStackSize(int maxStackSize);
Builder hasSubtypes(boolean hasSubtypes);
Builder maxDamage(int maxDamage);
Builder full3d(boolean full3d);
Builder rotateAroundWhenRendering(boolean rotateAroundWhenRendering);
Builder containerItem(Item item);
Builder translationKey(String translationKey);
Item build();
}
}
| Java | CL | 3cbd45649986734593107b0dc38c89a6f407759892f9a1ee87c665d6498fceae |
package ua.com.fielden.platform.web.test.server;
import java.io.IOException;
import java.util.Properties;
import java.util.function.Function;
import org.apache.log4j.Logger;
import ua.com.fielden.platform.types.tuples.T3;
import ua.com.fielden.platform.web.vulcanizer.VulcanizingUtility;
/**
* Web UI vulcanization launching class for TG example web server.
*
* @author TG Team
*
*/
public class Vulcanize extends VulcanizingUtility {
/**
* The procedure of vulcanization all-in-one.
*
* @param args
* @throws IOException
*/
public static void main(final String[] args) throws IOException {
final T3<Properties, String[], String[]> propsAndAdditionalPaths = processVmArguments(args);
final Logger logger = Logger.getLogger(Vulcanize.class);
logger.info("Starting app...");
final TgTestApplicationConfiguration component = new TgTestApplicationConfiguration(propsAndAdditionalPaths._1);
logger.info("Started app.");
final String platformVendorResourcesPath = "../platform-web-ui/src/main/resources";
final String platformWebUiResourcesPath = "../platform-web-ui/src/main/web/ua/com/fielden/platform/web";
final String appVendorResourcesPath = null;
final String appWebUiResourcesPath = null;
final String loginTargetPlatformSpecificPath = "../platform-web-ui/src/main/web/ua/com/fielden/platform/web/";
final String mobileAndDesktopAppSpecificPath = "../platform-web-ui/src/main/web/ua/com/fielden/platform/web/";
final Function<String, String[]> commandMaker = System.getProperty("os.name").toLowerCase().contains("windows") ? Vulcanize::windowsCommands : Vulcanize::unixCommands;
vulcanize(
component.injector(),
platformVendorResourcesPath,
platformWebUiResourcesPath,
appVendorResourcesPath,
appWebUiResourcesPath,
loginTargetPlatformSpecificPath,
mobileAndDesktopAppSpecificPath,
commandMaker,
propsAndAdditionalPaths._2,
propsAndAdditionalPaths._3);
}
} | Java | CL | c64321e967d1a67afe91fd3aa70335e54a49ba47a88317a9e87c5bd3cff50e53 |
package com.moneysupermarket.componentcatalog.service.scanners.models;
import com.moneysupermarket.componentcatalog.sdk.models.Component;
import com.moneysupermarket.componentcatalog.sdk.models.ScannerError;
import lombok.Value;
import org.junit.jupiter.api.Test;
import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.function.UnaryOperator;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowable;
public class OutputTest {
private final UnaryOperator<Component> componentTransformer = component -> component;
private final TestOutput output = new TestOutput("output");
private final ScannerError error = new ScannerError("test_scanner", "test_message", null);
private final List<ScannerError> errors = List.of(error);
@Test
public void ofWithComponentTransformerShouldSetComponentTransformer() {
// When
Output<TestOutput> underTest = Output.of(componentTransformer);
// Then
assertThat(underTest.getComponentTransformer()).isSameAs(componentTransformer);
assertThat(underTest.getOutput()).isNull();
assertThat(underTest.getErrors()).isEmpty();
}
@Test
public void ofWithComponentTransformerShouldCheckComponentTransformerIsNotNull() {
// When
Throwable thrown = catchThrowable(() -> Output.of((UnaryOperator<Component>) null));
// Then
assertThat(thrown).isInstanceOf(NullPointerException.class);
assertThat(thrown).hasMessage("componentTransformer");
}
@Test
public void ofWithComponentTransformerAndErrorShouldSetComponentTransformerAndError() {
// When
Output<TestOutput> underTest = Output.of(componentTransformer, error);
// Then
assertThat(underTest.getComponentTransformer()).isSameAs(componentTransformer);
assertThat(underTest.getOutput()).isNull();
assertThat(underTest.getErrors()).containsExactly(error);
assertIsUnmodifiable(underTest.getErrors());
}
@Test
public void ofWithComponentTransformerAndErrorShouldCheckComponentTransformerIsNotNull() {
// When
Throwable thrown = catchThrowable(() -> Output.of(null, error));
// Then
assertThat(thrown).isInstanceOf(NullPointerException.class);
assertThat(thrown).hasMessage("componentTransformer");
}
@Test
public void ofWithComponentTransformerAndErrorShouldCheckErrorIsNotNull() {
// When
Throwable thrown = catchThrowable(() -> Output.of(componentTransformer, (ScannerError) null));
// Then
assertThat(thrown).isInstanceOf(NullPointerException.class);
assertThat(thrown).hasMessage("error");
}
@Test
public void ofWithComponentTransformerAndErrorsShouldSetComponentTransformerAndErrors() {
// When
Output<TestOutput> underTest = Output.of(componentTransformer, errors);
// Then
assertThat(underTest.getComponentTransformer()).isSameAs(componentTransformer);
assertThat(underTest.getOutput()).isNull();
assertThat(underTest.getErrors()).containsExactlyElementsOf(errors);
assertIsUnmodifiable(underTest.getErrors());
}
@Test
public void ofWithComponentTransformerAndErrorsShouldCheckComponentTransformerIsNotNull() {
// When
Throwable thrown = catchThrowable(() -> Output.of(null, List.of(error)));
// Then
assertThat(thrown).isInstanceOf(NullPointerException.class);
assertThat(thrown).hasMessage("componentTransformer");
}
@Test
public void ofWithComponentTransformerAndErrorsShouldCheckErrorsIsNotNull() {
// When
Throwable thrown = catchThrowable(() -> Output.of(componentTransformer, (List<ScannerError>) null));
// Then
assertThat(thrown).isInstanceOf(NullPointerException.class);
assertThat(thrown).hasMessage("errors");
}
// Here
@Test
public void ofWithComponentTransformerAndOutputShouldSetComponentTransformerAndOutput() {
// When
Output<TestOutput> underTest = Output.of(componentTransformer, output);
// Then
assertThat(underTest.getComponentTransformer()).isSameAs(componentTransformer);
assertThat(underTest.getOutput()).isSameAs(output);
assertThat(underTest.getErrors()).isEmpty();
}
@Test
public void ofWithComponentTransformerAndOutputShouldCheckComponentTransformerIsNotNull() {
// When
Throwable thrown = catchThrowable(() -> Output.of(null, output));
// Then
assertThat(thrown).isInstanceOf(NullPointerException.class);
assertThat(thrown).hasMessage("componentTransformer");
}
@Test
public void ofWithComponentTransformerAndOutputShouldCheckOutputIsNotNull() {
// When
Throwable thrown = catchThrowable(() -> Output.of(componentTransformer, (TestOutput) null));
// Then
assertThat(thrown).isInstanceOf(NullPointerException.class);
assertThat(thrown).hasMessage("output");
}
@Test
public void ofWithComponentTransformerAndOutputAndErrorShouldSetComponentTransformerAndOutputAndError() {
// When
Output<TestOutput> underTest = Output.of(componentTransformer, output, error);
// Then
assertThat(underTest.getComponentTransformer()).isSameAs(componentTransformer);
assertThat(underTest.getOutput()).isSameAs(output);
assertThat(underTest.getErrors()).containsExactly(error);
assertIsUnmodifiable(underTest.getErrors());
}
@Test
public void ofWithComponentTransformerAndOutputAndErrorShouldCheckComponentTransformerIsNotNull() {
// When
Throwable thrown = catchThrowable(() -> Output.of(null, output, error));
// Then
assertThat(thrown).isInstanceOf(NullPointerException.class);
assertThat(thrown).hasMessage("componentTransformer");
}
@Test
public void ofWithComponentTransformerAndOutputAndErrorShouldCheckOutputIsNotNull() {
// When
Throwable thrown = catchThrowable(() -> Output.of(componentTransformer, null, error));
// Then
assertThat(thrown).isInstanceOf(NullPointerException.class);
assertThat(thrown).hasMessage("output");
}
@Test
public void ofWithComponentTransformerAndOutputAndErrorShouldCheckErrorIsNotNull() {
// When
Throwable thrown = catchThrowable(() -> Output.of(componentTransformer, output, (ScannerError) null));
// Then
assertThat(thrown).isInstanceOf(NullPointerException.class);
assertThat(thrown).hasMessage("error");
}
@Test
public void ofWithComponentTransformerAndOutputAndErrorsShouldSetComponentTransformerAndOutputAndErrors() {
// When
Output<TestOutput> underTest = Output.of(componentTransformer, output, errors);
// Then
assertThat(underTest.getComponentTransformer()).isSameAs(componentTransformer);
assertThat(underTest.getOutput()).isSameAs(output);
assertThat(underTest.getErrors()).containsExactlyElementsOf(errors);
assertIsUnmodifiable(underTest.getErrors());
}
@Test
public void ofWithComponentTransformerAndOutputAndErrorsShouldCheckComponentTransformerIsNotNull() {
// When
Throwable thrown = catchThrowable(() -> Output.of(null, output, List.of(error)));
// Then
assertThat(thrown).isInstanceOf(NullPointerException.class);
assertThat(thrown).hasMessage("componentTransformer");
}
@Test
public void ofWithComponentTransformerAndOutputAndErrorsShouldCheckOutputIsNotNull() {
// When
Throwable thrown = catchThrowable(() -> Output.of(componentTransformer, null, List.of(error)));
// Then
assertThat(thrown).isInstanceOf(NullPointerException.class);
assertThat(thrown).hasMessage("output");
}
@Test
public void ofWithComponentTransformerAndOutputAndErrorsShouldCheckErrorsIsNotNull() {
// When
Throwable thrown = catchThrowable(() -> Output.of(componentTransformer, output, (List<ScannerError>) null));
// Then
assertThat(thrown).isInstanceOf(NullPointerException.class);
assertThat(thrown).hasMessage("errors");
}
@Test
public void ofWithErrorShouldSetError() {
// When
Output<Void> underTest = Output.of(errors);
// Then
assertThat(underTest.getComponentTransformer()).isNull();
assertThat(underTest.getOutput()).isNull();
assertThat(underTest.getErrors()).containsExactlyElementsOf(errors);
assertIsUnmodifiable(underTest.getErrors());
}
@Test
public void ofWithErrorShouldCheckErrorIsNotNull() {
// When
Throwable thrown = catchThrowable(() -> Output.of((ScannerError) null));
// Then
assertThat(thrown).isInstanceOf(NullPointerException.class);
assertThat(thrown).hasMessage("error");
}
@Test
public void ofWithErrorsShouldSetErrors() {
// When
Output<Void> underTest = Output.of(error);
// Then
assertThat(underTest.getComponentTransformer()).isNull();
assertThat(underTest.getOutput()).isNull();
assertThat(underTest.getErrors()).containsExactly(error);
assertIsUnmodifiable(underTest.getErrors());
}
@Test
public void ofWithErrorsShouldCheckErrorsIsNotNull() {
// When
Throwable thrown = catchThrowable(() -> Output.of((List<ScannerError>) null));
// Then
assertThat(thrown).isInstanceOf(NullPointerException.class);
assertThat(thrown).hasMessage("errors");
}
@Test
public void successReturnsTrueAndFailedReturnsFalseWhenComponentTransformerIsNullAndOutputIsNullAndErrorsIsEmpty() {
// When
Output<Void> underTest = Output.of(List.of());
// Then
assertThat(underTest.getComponentTransformer()).isNull();
assertThat(underTest.getOutput()).isNull();
assertThat(underTest.success()).isTrue();
assertThat(underTest.failed()).isFalse();
}
@Test
public void successReturnsTrueAndFailedReturnsFalseWhenComponentTransformerIsNonNullAndOutputIsNonNullAndErrorsIsEmpty() {
// When
Output<TestOutput> underTest = Output.of(componentTransformer, output, List.of());
// Then
assertThat(underTest.getComponentTransformer()).isSameAs(componentTransformer);
assertThat(underTest.getOutput()).isSameAs(output);
assertThat(underTest.success()).isTrue();
assertThat(underTest.failed()).isFalse();
}
@Test
public void successReturnsFalseAndFailedReturnsTrueWhenComponentTransformerIsNullAndOutputIsNullAndErrorsIsNonEmpty() {
// When
Output<Void> underTest = Output.of(errors);
// Then
assertThat(underTest.getComponentTransformer()).isNull();
assertThat(underTest.getOutput()).isNull();
assertThat(underTest.success()).isFalse();
assertThat(underTest.failed()).isTrue();
}
@Test
public void successReturnsFalseAndFailedReturnsTrueWhenComponentTransformerIsNonNullAndOutputIsNonNullAndErrorsIsEmpty() {
// When
Output<TestOutput> underTest = Output.of(componentTransformer, output, errors);
// Then
assertThat(underTest.getComponentTransformer()).isSameAs(componentTransformer);
assertThat(underTest.getOutput()).isSameAs(output);
assertThat(underTest.success()).isFalse();
assertThat(underTest.failed()).isTrue();
}
private void assertIsUnmodifiable(@NotNull List<ScannerError> value) {
Throwable thrown = catchThrowable(() -> value.add(new ScannerError("test_scanner", "test_message", null)));
assertThat(thrown).isInstanceOf(UnsupportedOperationException.class);
}
@Value
private static class TestOutput {
String value;
}
}
| Java | CL | 38f1d69761d463996c65f2cd3d3193828b130d8bc6a3b8286377f8870a04969b |
package org.jcarvajal.webapp.servlet;
import java.util.List;
import org.jcarvajal.webapp.utils.IOUtils;
import org.jcarvajal.webapp.utils.ImmutableObservable;
import org.jcarvajal.webapp.utils.StringUtils;
import org.jcarvajal.webapp.server.RequestContext;
import org.jcarvajal.webapp.server.Response;
import org.jcarvajal.webapp.servlet.controllers.ControllerManager;
import org.jcarvajal.webapp.servlet.controllers.handlers.RequestHandler;
import org.jcarvajal.webapp.servlet.controllers.impl.AnnotationControllerManager;
/**
* Dispatcher base class to register controllers.
*
* @author JoseCH
*
*/
public abstract class DispatcherServlet extends ImmutableObservable {
private static final String REDIRECT = "redirect";
private String viewPath;
private String redirectToLogin;
private ControllerManager controllerManager = new AnnotationControllerManager();
public DispatcherServlet setViewPath(String viewPath) {
this.viewPath = viewPath;
return this;
}
public DispatcherServlet setRedirectToLogin(String redirectToLogin) {
this.redirectToLogin = redirectToLogin;
return this;
}
public DispatcherServlet setControllerManager(ControllerManager controllerManager) {
this.controllerManager = controllerManager;
return this;
}
/**
* Handle the response into a Response entity.
* @param response
* @return
*/
protected abstract Response handleResponse(Object response) throws Exception;
/**
* Handle an incoming HTTP request and returns a response.
* @return
* @throws Exception
* @throws OnRequestException
*/
public final Response handle(RequestContext context) throws Exception {
RequestHandler handler = controllerManager.getHandler(
context.getRequestURI().toString(),
context.getRequestMethod());
if (handler != null) {
// Notify observers
notifyObservers(context);
// Authorization
Response redirect = checkAuthorization(handler, context);
if (redirect != null) {
return redirect;
}
// Handle response
return handleResponseInternal(context, handler.invoke(context));
}
return null;
}
/**
* Init controllers.
* @param controllers
*/
public final void initControllers(List<Object> controllers) {
if (controllers != null) {
for (Object controller : controllers) {
controllerManager.register(controller);
}
}
}
/**
* Parse the target view.
* @param viewName
* @return
*/
protected String getView(String viewName) {
return IOUtils.toString(this.getClass().getResourceAsStream(viewPath + "/" + viewName + ".html"));
}
/**
* Handle the response redirecting to the proper page if required.
* @param context
* @param response
* @return
* @throws Exception
*/
private Response handleResponseInternal(RequestContext context, Object response)
throws Exception {
String redirectIfAuth = context.getCookie(REDIRECT);
if (StringUtils.isNotEmpty(redirectIfAuth) && context.getPrincipal() != null) {
Response redirect = new Response();
redirect.setRedirect(redirectIfAuth);
context.clearCookie(REDIRECT);
return redirect;
} else {
return handleResponse(response);
}
}
/**
* Chech whether the principal user has credentials to view the request.
* @param handler
* @param context
* @return
*/
private Response checkAuthorization(RequestHandler handler, RequestContext context) {
Response response = null;
if (handler.requiresRole()) {
if (context.getPrincipal() == null) {
// go to login
response = new Response();
response.setRedirect(redirectToLogin);
if (context.getRequestURI() != null) {
context.setCookie(REDIRECT, context.getRequestURI().getPath());
}
} else if (!handler.getRequiredRole().equals(context.getUserRole())) {
response = new Response();
response.setCode(403);
}
}
return response;
}
}
| Java | CL | 3d0ee433b286a2b7b776454a813b93802caee07e35ae819415ff356419e7f212 |
/*
* 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.tuweni.plumtree.vertx;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.apache.tuweni.bytes.Bytes;
import org.apache.tuweni.junit.VertxExtension;
import org.apache.tuweni.junit.VertxInstance;
import org.apache.tuweni.plumtree.EphemeralPeerRepository;
import org.apache.tuweni.plumtree.MessageListener;
import org.apache.tuweni.plumtree.Peer;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.Map;
import io.vertx.core.Vertx;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
@ExtendWith(VertxExtension.class)
class VertxGossipServerTest {
private static class MessageListenerImpl implements MessageListener {
public Bytes message;
@Override
public void listen(Bytes messageBody, Map<String, Bytes> attributes, Peer peer) {
message = messageBody;
}
}
@Test
void gossipDeadBeefToOtherNode(@VertxInstance Vertx vertx) throws Exception {
MessageListenerImpl messageReceived1 = new MessageListenerImpl();
MessageListenerImpl messageReceived2 = new MessageListenerImpl();
VertxGossipServer server1 = new VertxGossipServer(
vertx,
"127.0.0.1",
10000,
bytes -> bytes,
new EphemeralPeerRepository(),
messageReceived1,
(message, peer) -> true,
null,
200,
200);
VertxGossipServer server2 = new VertxGossipServer(
vertx,
"127.0.0.1",
10001,
bytes -> bytes,
new EphemeralPeerRepository(),
messageReceived2,
(message, peer) -> true,
null,
200,
200);
server1.start().join();
server2.start().join();
server1.connectTo("127.0.0.1", 10001).join();
Map<String, Bytes> attributes =
Collections.singletonMap("message_type", Bytes.wrap("BLOCK".getBytes(StandardCharsets.UTF_8)));
server1.gossip(attributes, Bytes.fromHexString("deadbeef"));
for (int i = 0; i < 10; i++) {
Thread.sleep(500);
if (Bytes.fromHexString("deadbeef").equals(messageReceived2.message)) {
break;
}
}
assertEquals(Bytes.fromHexString("deadbeef"), messageReceived2.message);
server1.stop().join();
server2.stop().join();
}
@Test
void gossipDeadBeefToTwoOtherNodes(@VertxInstance Vertx vertx) throws Exception {
MessageListenerImpl messageReceived1 = new MessageListenerImpl();
MessageListenerImpl messageReceived2 = new MessageListenerImpl();
MessageListenerImpl messageReceived3 = new MessageListenerImpl();
VertxGossipServer server1 = new VertxGossipServer(
vertx,
"127.0.0.1",
10000,
bytes -> bytes,
new EphemeralPeerRepository(),
messageReceived1,
(message, peer) -> true,
null,
200,
200);
VertxGossipServer server2 = new VertxGossipServer(
vertx,
"127.0.0.1",
10001,
bytes -> bytes,
new EphemeralPeerRepository(),
messageReceived2,
(message, peer) -> true,
null,
200,
200);
VertxGossipServer server3 = new VertxGossipServer(
vertx,
"127.0.0.1",
10002,
bytes -> bytes,
new EphemeralPeerRepository(),
messageReceived3,
(message, peer) -> true,
null,
200,
200);
server1.start().join();
server2.start().join();
server3.start().join();
server1.connectTo("127.0.0.1", 10001).join();
server3.connectTo("127.0.0.1", 10001).join();
Map<String, Bytes> attributes =
Collections.singletonMap("message_type", Bytes.wrap("BLOCK".getBytes(StandardCharsets.UTF_8)));
server1.gossip(attributes, Bytes.fromHexString("deadbeef"));
for (int i = 0; i < 10; i++) {
Thread.sleep(500);
if (Bytes.fromHexString("deadbeef").equals(messageReceived2.message)
&& Bytes.fromHexString("deadbeef").equals(messageReceived3.message)) {
break;
}
}
assertEquals(Bytes.fromHexString("deadbeef"), messageReceived2.message);
assertEquals(Bytes.fromHexString("deadbeef"), messageReceived3.message);
assertNull(messageReceived1.message);
server1.stop().join();
server2.stop().join();
server3.stop().join();
}
@Test
void gossipCollision(@VertxInstance Vertx vertx) throws Exception {
MessageListenerImpl messageReceived1 = new MessageListenerImpl();
MessageListenerImpl messageReceived2 = new MessageListenerImpl();
EphemeralPeerRepository peerRepository1 = new EphemeralPeerRepository();
EphemeralPeerRepository peerRepository3 = new EphemeralPeerRepository();
VertxGossipServer server1 = new VertxGossipServer(
vertx,
"127.0.0.1",
10000,
bytes -> bytes,
peerRepository1,
messageReceived1,
(message, peer) -> true,
null,
200,
200);
VertxGossipServer server2 = new VertxGossipServer(
vertx,
"127.0.0.1",
10001,
bytes -> bytes,
new EphemeralPeerRepository(),
messageReceived2,
(message, peer) -> true,
null,
200,
200);
VertxGossipServer server3 = new VertxGossipServer(
vertx,
"127.0.0.1",
10002,
bytes -> bytes,
peerRepository3,
messageReceived2,
(message, peer) -> true,
null,
200,
200);
server1.start().join();
server2.start().join();
server3.start().join();
server1.connectTo("127.0.0.1", 10001).join();
server2.connectTo("127.0.0.1", 10002).join();
server1.connectTo("127.0.0.1", 10002).join();
assertEquals(2, peerRepository1.eagerPushPeers().size());
Map<String, Bytes> attributes =
Collections.singletonMap("message_type", Bytes.wrap("BLOCK".getBytes(StandardCharsets.UTF_8)));
server1.gossip(attributes, Bytes.fromHexString("deadbeef"));
Thread.sleep(1000);
assertEquals(Bytes.fromHexString("deadbeef"), messageReceived2.message);
Thread.sleep(1000);
assertTrue(peerRepository1.lazyPushPeers().size() > 0 || peerRepository3.lazyPushPeers().size() > 0);
server1.stop().join();
server2.stop().join();
server3.stop().join();
}
@Test
void sendMessages(@VertxInstance Vertx vertx) throws Exception {
MessageListenerImpl messageReceived1 = new MessageListenerImpl();
MessageListenerImpl messageReceived2 = new MessageListenerImpl();
EphemeralPeerRepository peerRepository1 = new EphemeralPeerRepository();
VertxGossipServer server1 = new VertxGossipServer(
vertx,
"127.0.0.1",
10000,
bytes -> bytes,
peerRepository1,
messageReceived1,
(message, peer) -> true,
null,
200,
200);
VertxGossipServer server2 = new VertxGossipServer(
vertx,
"127.0.0.1",
10001,
bytes -> bytes,
new EphemeralPeerRepository(),
messageReceived2,
(message, peer) -> true,
null,
200,
200);
server1.start().join();
server2.start().join();
server1.connectTo("127.0.0.1", 10001).join();
assertEquals(1, peerRepository1.eagerPushPeers().size());
Map<String, Bytes> attributes =
Collections.singletonMap("message_type", Bytes.wrap("BLOCK".getBytes(StandardCharsets.UTF_8)));
server1.send(peerRepository1.peers().iterator().next(), attributes, Bytes.fromHexString("deadbeef"));
Thread.sleep(1000);
assertEquals(Bytes.fromHexString("deadbeef"), messageReceived2.message);
Thread.sleep(1000);
server1.stop().join();
server2.stop().join();
}
}
| Java | CL | 2676ae705df4942896198f7e65dcd9befaf3ee8614c508f4d51da6131583c581 |
/*
* 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 p0014.linhmd.servlet;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.sql.SQLException;
import java.util.Properties;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import p0014.linhmd.dao.UserDAO;
import p0014.linhmd.dto.User;
import p0014.linhmd.ultilities.Sha256;
import p0014.linhmd.ultilities.UserError;
/**
*
* @author USER
*/
public class RegisterServlet extends HttpServlet {
private static final Logger LOGGER = Logger.getLogger(RegisterServlet.class);
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
request.setCharacterEncoding("UTF-8");
String url = null;
Properties action = (Properties)this.getServletContext().getAttribute("ACTION");
url = action.getProperty("LoginPage");
String email = request.getParameter("email").trim();
String password = request.getParameter("password").trim();
String comfirm = request.getParameter("comfirm").trim();
String username = request.getParameter("username").trim();
UserError error = new UserError();
try {
this.validate(email, password, comfirm, username, error);
if(error.isError()){
request.setAttribute("registerError", error);
}else{
password = Sha256.encrypt(password);
User user = new User(email, username, false);
if(new UserDAO().registerNewUser(user, password)){
request.setAttribute("regisMessage", "Sign up successfully");
request.setAttribute("email", email);
request.setAttribute("username" , username);
}
}
} catch (UnsupportedEncodingException | NoSuchAlgorithmException ex) {
LOGGER.fatal(ex.getMessage());
} catch (SQLException ex) {
if(ex.getMessage().contains("duplicate")){
request.setAttribute("regisMessage", "Email already existed!!!");
}else
LOGGER.error(ex.getMessage() + " Cause by: " + ex.getCause().toString());
} catch (NullPointerException ignore){
}catch (Exception e){
LOGGER.error(e.getMessage());
}finally{
request.setAttribute("isSignUp", true);
request.getRequestDispatcher(url).forward(request, response);
}
}
private void validate(String email, String password, String comfirm, String name, UserError error) throws UnsupportedEncodingException, NoSuchAlgorithmException{
if (email.trim().isEmpty()) {
error.put("email", "email can not be empty!!");
}else if(email.trim().length() > 255)
error.put("email", "Email too long");
if (password.trim().isEmpty()) {
error.put("password", "password can not be empty!!");
}else if(password.trim().length() < 2){
error.put("password", "password too short!!");
} else if (!password.equals(comfirm)) {
error.put("comfirm", "Comfirm must match password!!");
}
if (name.trim().isEmpty()) {
error.put("name", "Name can not be empty!!");
}else if(name.trim().length() > 50)
error.put("name", "Name too long!!");
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
| Java | CL | 9131b3df07b82051e623202df2efa3982afd4ac07409f5c0d95ea02b08020e08 |
package com.yx.game.controller;
import com.github.xiaoymin.knife4j.annotations.ApiSort;
import com.yx.common.base.restful.GlobalResponse;
import com.yx.common.mvc.utils.ResponseUtil;
import com.yx.game.handler.DynamicValueHandler;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
/**
* @Author jesse
* @Date 4/4/20 9:57 下午
**/
@Slf4j
@Api(tags = "nocos测试")
@ApiSort(4)//接口分组排序
@RestController
public class NacosTestController {
@Resource
private DynamicValueHandler dynamicValueHandler;
@GetMapping(value = "/testNacos")
@ApiOperation(value = "参数动态获取")
public GlobalResponse printgetsql() {
log.info("===>>aSwitch2:{}", dynamicValueHandler.isASwitch());
log.info("===>>bSwitch2:{}", dynamicValueHandler.isBSwitch());
log.info("===>>url:{}", dynamicValueHandler.getUrl());
return ResponseUtil.success();
}
}
| Java | CL | 0e38a19ee22472a5b0d91382d4f1fde19873bfd27f2ff33eefc51ee02a774d1f |
package com.trilobiet.graphqlweb.implementations.aexpgraphql2.service.html;
import java.util.List;
import java.util.Optional;
import com.trilobiet.graphqlweb.dao.DaoException;
import com.trilobiet.graphqlweb.dao.FileDao;
import com.trilobiet.graphqlweb.datamodel.File;
import com.trilobiet.graphqlweb.implementations.aexpgraphql2.GraphQLFieldValueQuery;
import com.trilobiet.graphqlweb.implementations.aexpgraphql2.file.FileImp;
import com.trilobiet.graphqlweb.implementations.aexpgraphql2.file.FileList;
import com.trilobiet.graphqlweb.implementations.aexpgraphql2.file.GenericFileDao;
import com.trilobiet.graphqlweb.implementations.aexpgraphql2.service.FileService;
public class HtmlFileService<T extends File> implements FileService<T> {
private final FileDao<T> fileDao;
/**
* Generic constructor
*
* @param fileDao
*/
public HtmlFileService(FileDao<T> fileDao) {
this.fileDao = fileDao;
}
/**
* Convenience constructor for use with default FileImp and FileList
*
* @param host
*/
@SuppressWarnings("all")
public HtmlFileService(String host) {
this(new GenericFileDao(host, FileImp.class, FileList.class));
}
@Override
public Optional<T> get(String id) throws DaoException {
return fileDao.get(id);
}
@Override
public List<T> getByName(String name) throws DaoException {
return fileDao.getByName( name );
}
@Override
public Optional<T> getFirstWithName(String name) throws DaoException {
List<T> files = fileDao.getByName( name );
if (!files.isEmpty()) return Optional.of(files.get(0));
else return Optional.empty();
}
@Override
public List<T> getByFieldValue(String field, String value) throws DaoException {
GraphQLFieldValueQuery q =
new GraphQLFieldValueQuery.Builder(field,value)
.build();
return fileDao.find(q);
}
}
| Java | CL | ada41b4ab18291919a6861d81068538645110fc023b1f3d82a0bd7140d6640de |
package uk.ac.shef.oak.com4510.model.repositry;
import android.os.AsyncTask;
import android.util.Log;
import androidx.lifecycle.MutableLiveData;
import java.util.List;
import uk.ac.shef.oak.com4510.model.datebase.MyDatabase;
import uk.ac.shef.oak.com4510.model.datebase.VisitDao;
import uk.ac.shef.oak.com4510.model.models.Visit;
import uk.ac.shef.oak.com4510.model.models.VisitImages;
/**
* InsertVisitRepository this class is repository which use to connect with the database and get object of visitdao
* @author Areej
*/
public class InsertVisitRepository {
// return id of the visit
public MutableLiveData<Long>visitInsert=new MutableLiveData<>();
// return ids of images
public MutableLiveData<Long[]>visitImagesInsert=new MutableLiveData<>();
/**
*
* this function return object of dao
* @return VisitDao
*/
public static VisitDao getDao(){
MyDatabase db = MyDatabase.getDatabase();
return db.dao();
}
/**
* this function insert object of visit into the database
* @param visit
* @return MutableLiveData<Long>
*/
public MutableLiveData<Long> insertVisit(final Visit visit) {
/// here I create object of asynctask to insert data in the background thread
InsertVistAsyncTask insertVistAsyncTask=new InsertVistAsyncTask();
insertVistAsyncTask.execute(visit);
return visitInsert;
}
/**
* this function insert list of images for particular visit
* @param images
* @return
*/
public MutableLiveData<Long[]> insertVisitImage(final List<VisitImages> images) {
new InsertVistImagesAsyncTask().execute(images);
return visitImagesInsert;
}
/**
* this aasyncktask class insert visit images into the database using background thread
* @author Areej
*/
private class InsertVistImagesAsyncTask extends AsyncTask<List<VisitImages>, Void, Long[]> {
@Override
protected Long[] doInBackground(List<VisitImages>... visitImages) {
try {
return getDao().insertVisitImage(visitImages[0]);
}
catch (Exception e){
return null;
}
}
@Override
protected void onPostExecute(Long []lon) {
// return ids of images
visitImagesInsert.setValue(lon);
}
}
/**
* this aasyncktask class insert visit into the database by using background thread
* @author Areej
*/
private class InsertVistAsyncTask extends AsyncTask<Visit, Void, Long> {
@Override
protected Long doInBackground(Visit... models) {
try {
return getDao().insertVisit(models[0]);
}
catch (Exception e){
Log.v("rrrr",e.getMessage());
return Long.valueOf(0);
}
}
@Override
protected void onPostExecute(Long lon) {
visitInsert.setValue(lon);
}
}
}
| Java | CL | f1d1f9031aa281e884b41c1df89890149d927d019752ce7060057f3dd33c34cb |
/**
* Copyright (c) 2018 BITPlan GmbH
*
* http://www.bitplan.com
*
* This file is part of the Opensource project at:
* https://github.com/BITPlan/com.bitplan.simplegraph
*
* 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.bitplan.simplegraph.impl;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import com.bitplan.simplegraph.core.Keys;
/**
* default implementation for property keys
* @author wf
*
*/
public class KeysImpl implements Keys {
protected List<String> keysList;
protected String[] keys;
/**
* initialize me from an array of keys
* @param keys
*/
public KeysImpl(String... keys) {
this.keys=keys;
this.keysList = Arrays.asList(keys);
}
@Override
public boolean hasKey(String key) {
if (keysList.size() == 0)
return true;
else
return keysList.contains(key);
}
@Override
public Optional<List<String>> getKeysList() {
if (keysList.size()==0)
return Optional.empty();
else
return Optional.of(keysList);
}
@Override
public String[] getKeys() {
return keys;
}
}
| Java | CL | dcd096f7f7b9aaee3d997d22b9f26ede82e87e27b2fced92ec4e620c0b67c7f7 |
package edu.utdallas.utdesign.teach4service;
import io.dropwizard.Configuration;
import io.dropwizard.db.DataSourceFactory;
import io.dropwizard.flyway.FlywayFactory;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.hibernate.validator.constraints.NotBlank;
import javax.validation.Valid;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
@Data
@EqualsAndHashCode(callSuper = true)
public class T4SConfiguration extends Configuration
{
@Valid
private DataSourceFactory database = new DataSourceFactory();
@Valid
private FlywayFactory flyway = new FlywayFactory();
@Valid
private AuthConfig auth = new AuthConfig();
@Valid
private OpenTokConfig opentok = new OpenTokConfig();
@Data
public static class AuthConfig
{
@NotBlank
private String cookieSecret;
@Min(600)
@Max(86400)
private int cookieAge = 3600;
@NotNull
private SystemUserConfig systemUser;
}
@Data
public static class SystemUserConfig
{
private boolean enabled = false;
@NotBlank
private String password;
}
@Data
public static class OpenTokConfig
{
@Min(10000000)
@Max(100000000)
private int apiKey;
@NotBlank
private String secret;
}
}
| Java | CL | e30cafabe2c356531b4c1375d736c3abf3841f931a7975c22f55c4a0f9f5433f |
package com.github.filipebezerra.podcastsdabel.api.models;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import org.parceler.Parcel;
@Parcel
public class Track {
@SerializedName("id")
@Expose
public Long id;
@SerializedName("created_at")
@Expose
public String createdAt;
@SerializedName("duration")
@Expose
public Long duration;
@SerializedName("commentable")
@Expose
public Boolean commentable;
@SerializedName("state")
@Expose
public String state;
@SerializedName("original_content_size")
@Expose
public Long originalContentSize;
@SerializedName("last_modified")
@Expose
public String lastModified;
@SerializedName("tag_list")
@Expose
public String tagList;
@SerializedName("streamable")
@Expose
public Boolean streamable;
@SerializedName("downloadable")
@Expose
public Boolean downloadable;
@SerializedName("genre")
@Expose
public String genre;
@SerializedName("title")
@Expose
public String title;
@SerializedName("description")
@Expose
public String description;
@SerializedName("original_format")
@Expose
public String originalFormat;
@SerializedName("license")
@Expose
public String license;
@SerializedName("uri")
@Expose
public String uri;
@SerializedName("permalink_url")
@Expose
public String permalinkUrl;
@SerializedName("artwork_url")
@Expose
public String artworkUrl;
@SerializedName("waveform_url")
@Expose
public String waveformUrl;
@SerializedName("stream_url")
@Expose
public String streamUrl;
@SerializedName("playback_count")
@Expose
public Integer playbackCount;
@SerializedName("download_count")
@Expose
public Integer downloadCount;
@SerializedName("favoritings_count")
@Expose
public Integer favoritingsCount;
@SerializedName("comment_count")
@Expose
public Integer commentCount;
@SerializedName("attachments_uri")
@Expose
public String attachmentsUri;
public Track() {
// no args
}
}
| Java | CL | 27633dbed4786b1ab7fd38b8b2549d5c4cecbb4b5b438ae12fad6f5aa1177a81 |
package rest.resources;
import model.SnapshotDB;
import model.facade.BusinessFacade;
import rest.converters.AuthorConverter;
import rest.converters.AuthorsConverter;
import rest.converters.MetaDataConverter;
import rest.entities.Author;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* NICE COMMENT
*/
@Path("/v1/metadata")
public class MetaDataResource {
@GET
@Produces(MediaType.APPLICATION_XML)
public Response get() {
BusinessFacade bf = new BusinessFacade();
List<AuthorConverter> authorsList = new ArrayList<AuthorConverter>();
AuthorsConverter authors = new AuthorsConverter(authorsList);
authorsList.add(new AuthorConverter(new Author("Miloš Pensimus", "Uhelná Příbram")));
authorsList.add(new AuthorConverter(new Author("Luboš Helcl", "Černý Dub")));
authorsList.add(new AuthorConverter(new Author("Jaroslav Málek", "Praha")));
SnapshotDB lastSnapshot = bf.getLastSnapshot();
MetaDataConverter mdc = new MetaDataConverter(authors, (lastSnapshot == null ? new Date() : lastSnapshot.getDate()));
return Response.ok().entity(mdc).build();
}
}
| Java | CL | 33374cff5a9c66fca3d0770d43cbae6c553781290854d1d5ca2c5ce41f3f5cbd |
/**
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.autoconfigure.flyway;
import org.junit.Test;
import org.springframework.boot.diagnostics.FailureAnalysis;
/**
* Tests for {@link FlywayMigrationScriptMissingFailureAnalyzer}.
*
* @author Anand Shastri
*/
public class FlywayMigrationScriptMissingFailureAnalyzerTests {
@Test
public void analysisForMissingScriptLocation() {
FailureAnalysis failureAnalysis = performAnalysis();
assertThat(failureAnalysis.getDescription()).contains("no migration scripts location is configured");
assertThat(failureAnalysis.getAction()).contains("Check your Flyway configuration");
}
@Test
public void analysisForScriptLocationsNotFound() {
FailureAnalysis failureAnalysis = performAnalysis("classpath:db/migration");
assertThat(failureAnalysis.getDescription()).contains("none of the following migration scripts locations could be found").contains("classpath:db/migration");
assertThat(failureAnalysis.getAction()).contains("Review the locations above or check your Flyway configuration");
}
}
| Java | CL | ff4f556a243323d4949fc98e19fb3fede3c428d7a77e8df586ff87ac3062170d |
package domain;
import java.util.ArrayList;
import java.util.stream.Collectors;
import exceptions.InvalidNameException;
/**
* Class containing a Table.
* A Table is a collection of Columns with a name
* and comes in two variants: Stored and Computed.
*
*/
public abstract class Table {
/**
* Creates a new empty stored Table
* @param name The name of this table
*/
public Table(String name) {
setName(name);
}
/**
* The table's name
*/
private String name;
/**
* This method returns the name of the current Table.
* @return
*/
public String getName() {
return name;
}
/**
* This method sets the name of the current Table.
* @param name The name to be set.
*/
public void setName(String name) {
this.name = name;
}
/**
* Returns the query associated with this Table.
* Computed Tables will always have have a valid SQL query,
* while Stored Tables will always have a query "".
*/
public abstract String getQueryString();
/**
* A list of tables whose queries reference this table
*/
private ArrayList<ComputedTable> derivedTables = new ArrayList<ComputedTable>();
/**
* Adds a table to the list of derived tables
* @param t Table
*/
public void addDerivedTable(ComputedTable t) {
derivedTables.add(t);
}
/**
* Removes a table from the list of derived tables
* @param t Table
*/
public void removeDerivedTable(ComputedTable t){
derivedTables.remove(t);
}
/**
* Removes a list of tables from the list of derived tables.
* @return List of tables
*/
public ArrayList<ComputedTable> removeDerivedTables() {
ArrayList<ComputedTable> references = new ArrayList<ComputedTable>(getDerivedTables());
for (ComputedTable ref : getDerivedTables()) {
removeDerivedTable(ref);
}
return references;
}
/**
* Adds a list of tables to the list of derived tables.
* @param references List of Tables
*/
public void addDerivedTables(ArrayList<ComputedTable> references) {
derivedTables.addAll(references);
}
/**
* Returns a list of all tables that are derived
* from this Table
*/
public ArrayList<ComputedTable> getDerivedTables(){
return new ArrayList<ComputedTable>(derivedTables);
}
/**
* Loads a list of Columns into this StoredTable
* @param c List<> of Columns
*/
public void addAllColumns(ArrayList<Column> c) {
this.columns = new ArrayList<Column>(c);
}
/**
* The table's columns from left to right
*/
protected ArrayList<Column> columns = new ArrayList<Column>();
/**
* This method returns the columns of the current Table.
* @return A Collection of Columns where each column is guaranteed to have this table set as its table.
*/
public ArrayList<Column> getColumns() {
return columns;
}
/**
* The number of rows in this table.
*/
protected int nbOfRows;
/**
* This method returns the number of rows of the current Table.
*/
public int getRows() {
//return nbOfRows;
return getColumns().isEmpty() ? nbOfRows : getColumns().get(0).getCells().size();
}
/**
* This method returns an ArrayList of all the names of the columns of the current Table.
*/
public ArrayList<String> getColumnNames() {
ArrayList<String> names = new ArrayList<String>();
for (Column column: this.getColumns()){
names.add(column.getName());
}
return names;
}
/**
* This method removes a Column from the current table based on an index.
* @param index The index of the column which is to be removed.
* @return The removed Column.
*/
public Column removeColumn(int index){
Column column = columns.get(index);
columns.remove(column);
column.setTable(null);
return column;
}
/**
* This method removes a Column from the current table.
* @param column Reference to the column to delete
*/
public void removeColumn(Column column) {
removeColumn(columns.indexOf(column));
}
/**
* Returns whether this table is a Stored Table.
*/
public boolean isStoredTable() {
return this.getQueryString().equals("");
}
/**
* Returns whether this table is a Computed Table.
*
*/
public boolean isComputedTable() {
return (!isStoredTable());
}
/**
* Clones this table
*/
public StoredTable clone(String newName) {
StoredTable t = new StoredTable(newName);
t.addAllColumns(getColumns());
return t;
}
/**
* Returns the Cells that occur at a certain index
* @param i Index
* @param ignoreCol Ignore the cells of this column
*/
public ArrayList<Cell> getRowByIndex(int i,String ignoreCol) {
return new ArrayList<Cell>(
getColumns()
.stream()
.filter((c)->!c.getName().equals(ignoreCol))
.map((c)->c.getCell(i))
.collect(Collectors.toList()));
}
/**
* Prints the table in a somewhat readable form
*/
public void printTable() {
System.out.println(getName());
getColumnNames().stream().forEach((name)->System.out.print(String.format("%15s",name+" ")));
System.out.println("");
for (int i=0;i<getColumns().get(0).getCells().size();i++) {
for (int j=0;j<getColumns().size();j++) {
Object val = getColumns().get(j).getCells().get(i).getValue();
String valString = val == null ? "null" : val.toString();
valString = valString.isEmpty() ? "BLANK" : valString;
System.out.print(String.format("%15s", valString+" "));
}
System.out.println("");
}
System.out.println("");
}
/**
* checks if any of the tables that reference this table are referencing a certain column
* @param column: the column to check out
* @return
*/
public abstract boolean queryContainsColumn(Column column);
}
| Java | CL | bec0fc1837f439edf0b3ce12c0369b163b8572759cc27a4eb602e155c187dcbc |
package com.openapisession.ringmyiphonebff.config;
import org.apache.http.client.HttpClient;
import org.apache.http.client.HttpRequestRetryHandler;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.web.servlet.ServletListenerRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.ServletListenerRegistrationBean;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.*;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.client.BufferingClientHttpRequestFactory;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.converter.ByteArrayHttpMessageConverter;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.ResourceHttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.http.converter.xml.MarshallingHttpMessageConverter;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextListener;
import java.util.Map;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
@Configuration
public class ApplicationConfig {
private static final Logger LOGGER = LoggerFactory.getLogger(HttpRequestRetryHandler.class);
//
// @Bean
// public ClientHttpRequestFactory clientHttpRequestFactory(
// final ScheduledExecutorService scheduledExecutorService, ConfigValues configValues) {
// PoolingHttpClientConnectionManager poolingClientConnectionManager =
// new PoolingHttpClientConnectionManager(
// configValues.getActiveConnectionMaxSecondsToLive(), TimeUnit.SECONDS);
// poolingClientConnectionManager.setDefaultMaxPerRoute(1000);
// poolingClientConnectionManager.setMaxTotal(1000);
//
// // Make sure to evict expired connections and connections that are idle for too long
// IdleHttpConnectionCleaner cleaner =
// new IdleHttpConnectionCleaner(
// poolingClientConnectionManager, configValues.getIdleConnectionMaxIdleTime());
// scheduledExecutorService.scheduleAtFixedRate(
// cleaner,
// configValues.getIdleConnectionCleanupInterval(),
// configValues.getIdleConnectionCleanupInterval(),
// TimeUnit.SECONDS);
//
// HttpClientBuilder clientBuilder =
// HttpClientBuilder.create()
// .disableCookieManagement()
// .setConnectionManager(poolingClientConnectionManager);
//
// HttpRequestRetryHandler retryHandler = buildRetryHandler();
// clientBuilder.setRetryHandler(retryHandler);
//
// HttpClient httpClient = clientBuilder.build();
// HttpComponentsClientHttpRequestFactory httpComponentsClientHttpRequestFactory =
// new HttpComponentsClientHttpRequestFactory(httpClient);
// httpComponentsClientHttpRequestFactory.setReadTimeout(configValues.getHttpSocketTimeout());
// httpComponentsClientHttpRequestFactory.setConnectionRequestTimeout(
// configValues.getHttpSocketTimeout());
// httpComponentsClientHttpRequestFactory.setConnectTimeout(configValues.getHttpSocketTimeout());
// return new BufferingClientHttpRequestFactory(httpComponentsClientHttpRequestFactory);
// }
//
// @Bean
// public Map<String, String> webAppJars(ServletContext servletContext) {
// return JarsCollector.getJars(servletContext.getRealPath("/WEB-INF/lib"));
// }
//
// @Bean
// public HeaderValueEncoder headerValueEncoder() {
// return new Base64HeaderEncoder();
// }
}
| Java | CL | 4d2aed9587c6790ae6bcf99bbf158a37a516701b6c364e46db615f903ecd92a1 |
/**
* Copyright (c) 2014, Regents of the University of California
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holder nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package edu.ucla.wise.commons;
import org.apache.log4j.Logger;
import org.w3c.dom.DOMException;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
* This class represents our email prompts
*/
public class Message {
public static final Logger LOGGER = Logger.getLogger(Message.class);
/** Email Image File Names */
private static final String HEADER_IMAGE_FILENAME = "email_header_img.jpg";
private static final String FOOTER_IMAGE_FILENAME_1 = "email_bottom_img1.jpg";
private static final String FOOTER_IMAGE_FILENAME_2 = "email_bottom_img2.jpg";
private static final String WISE_SHARED = "WiseShared";
private static final String HTML_OPEN = "<html><head><meta http-equiv='Content-Type' content='text/html; charset=UTF-8'></head>"
+ "<body bgcolor=#FFFFFF text=#000000><center>";
private static final String htmlClose = "</center></body></html>";
/** Instance Variables */
public String id, subject;
public String mainBody, htmlBody, htmlHeader, htmlTail, htmlSignature;
private boolean htmlFormat = false;
public boolean hasLink = false, hasDLink = false;
public String msgRef = null;
private String servletPath = null;
// TODO: should ideally be customizable for survey/irb; should use xlst
/**
* Constructor for Message
*
* @param n
* XML DOM for the message from the preface file.
*/
public Message(Node n) {
try {
/*
* parse out the reminder attributes: ID, subject, format, trigger
* days and max count
*/
this.id = "";
this.subject = "";
/* ID, subject, trigger days and maximum count are required */
this.id = n.getAttributes().getNamedItem("ID").getNodeValue();
this.subject = n.getAttributes().getNamedItem("Subject").getNodeValue();
/* email format is optional */
Node node = n.getAttributes().getNamedItem("Format");
if (node != null) {
this.htmlFormat = node.getNodeValue().equalsIgnoreCase("html");
}
/* read out the contents of the email message */
NodeList nodeP = n.getChildNodes();
boolean hasRef = false;
this.mainBody = "";
this.htmlHeader = "";
this.htmlBody = "";
this.htmlTail = "";
this.htmlSignature = "";
for (int j = 0; j < nodeP.getLength(); j++) {
if (nodeP.item(j).getNodeName().equalsIgnoreCase("Message_Ref") && !hasRef) {
/* check prevents a 2nd ref (that's invalid) */
this.msgRef = nodeP.item(j).getAttributes().getNamedItem("ID").getNodeValue();
hasRef = true;
break;
} else {
if (nodeP.item(j).getNodeName().equalsIgnoreCase("p")) {
this.mainBody += nodeP.item(j).getFirstChild().getNodeValue() + "\n\n";
this.htmlBody += "<p>" + nodeP.item(j).getFirstChild().getNodeValue() + "</p>\n";
}
if (nodeP.item(j).getNodeName().equalsIgnoreCase("s")) {
if (this.htmlFormat) {
this.htmlSignature += "<p>" + nodeP.item(j).getFirstChild().getNodeValue() + "</p>\n";
} else {
this.mainBody += nodeP.item(j).getFirstChild().getNodeValue() + "\n\n";
this.htmlBody += "<p>" + nodeP.item(j).getFirstChild().getNodeValue() + "</p>\n";
}
}
/* mark the URL link */
if (nodeP.item(j).getNodeName().equalsIgnoreCase("link")) {
this.hasLink = true;
this.mainBody = this.mainBody + "URL LINK\n\n";
this.htmlBody += "<p align=center><font color='blue'>[<u>URL Link to Start the Survey</u>]</font></p>\n";
}
/* mark the decline URL link */
if (nodeP.item(j).getNodeName().equalsIgnoreCase("declineLink")) {
this.hasDLink = true;
this.mainBody = this.mainBody + "DECLINE LINK\n\n";
LOGGER.info("########The Body of the email is: " + this.mainBody);
this.htmlBody += "<p align=center><font color='blue'>[<u>URL Link to Decline the Survey</u>]</font></p>\n";
}
}
}
} catch (DOMException e) {
LOGGER.error(
"WISE - TYPE MESSAGE: ID = " + this.id + "; Subject = " + this.subject + " --> " + e.toString(), e);
return;
}
}
/**
* Resolve message references. Do this after construct-time so that order of
* messages in file won't matter.
*
* @param myPreface
* preface object on which the resolve is performed.
*/
public void resolveRef(Preface myPreface) {
if (this.msgRef != null) {
Message refdMsg = myPreface.getMessage(this.msgRef);
if (refdMsg.msgRef == null) {
this.mainBody = refdMsg.mainBody;
this.hasLink = refdMsg.hasLink;
this.hasDLink = refdMsg.hasDLink;
this.htmlTail = refdMsg.htmlTail;
this.htmlHeader = refdMsg.htmlHeader;
} else {
LOGGER.error("MESSAGE: ID = " + this.id + "; Subject = " + this.subject
+ " refernces a message that itself has a message ref. Double-indirection not supported. ",
null);
}
}
}
/**
* Sets the HTML header and footer of the email.
*
* @param servletPath
* Servlet path to be set.
* @param imgRootPath
* image root path for Email
*/
public void setHrefs(String servletPath, String imgRootPath) {
this.servletPath = servletPath;
if (this.htmlFormat) {
/* compose the html header and tail */
this.htmlHeader = "<table width=510 border=0 cellpadding=0 cellspacing=0>"
+ "<tr><td rowspan=5 width=1 bgcolor='#996600'></td>"
+ "<td width=500 height=1 bgcolor='#996600'></td>"
+ "<td rowspan=5 width=1 bgcolor='#996600'></td></tr>"
+ "<tr><td height=120 align=center><img src='"
+ WISEApplication.getInstance().getWiseProperties().getServerRootUrl() + "/" + WISE_SHARED
+ "/image?img=" + HEADER_IMAGE_FILENAME + "'></td></tr>" + "<tr><td>"
+ "<table width=100% border=0 cellpadding=0 cellspacing=0>" + "<tr><td width=20> </td>"
+ "<td width=460><font size=1 face='Verdana'>\n\n";
/* NOTE: signature included in the tail */
this.htmlTail = "</font></td><td width=20> </td>" + "</tr></table></td></tr>" + "<tr><td>"
+ "<table width=100% border=0 cellpadding=0 cellspacing=0>"
+ "<tr><td rowspan=2 width=25> </td>" + "<td height=80 width=370><font size=1 face='Verdana'>"
+ this.htmlSignature + "</font></td>"
+ "<td rowspan=2 height=110 width=105 align=left valign=bottom><img src=\""
+ WISEApplication.getInstance().getWiseProperties().getServerRootUrl() + "/" + WISE_SHARED
+ "/image?img=" + FOOTER_IMAGE_FILENAME_2 + "\"></td></tr>"
+ "<tr><td height=30 width=370 align=center valign=bottom><img src='"
+ WISEApplication.getInstance().getWiseProperties().getServerRootUrl() + "/" + WISE_SHARED
+ "/image?img=" + FOOTER_IMAGE_FILENAME_1 + "'></td></tr>" + "</table></td></tr>"
+ "<tr><td width=500 height=1 bgcolor='#996600'></td></tr></table>\n\n";
}
}
/**
* Composes the body of email in text format.
*
* @param salutation
* Salutation to address the invitee to whom email has to be
* sent.
* @param lastname
* Last name of the invitee.
* @param ssid
* Studyspace id for generation of the URL.
* @param msgIndex
* Id to identify the invitee.
* @return String Body of the email in text format.
*/
public String composeTextBody(String salutation, String lastname, String ssid, String msgIndex) {
String textBody = null;
/* compose the text body */
textBody = "Dear " + salutation + " " + lastname + ":\n\n" + this.mainBody;
if (this.hasLink) {
String reminderLink = this.servletPath + "survey?msg=" + msgIndex + "&t=" + WISEApplication.encode(ssid);
String declineLink = this.servletPath + "survey/declineNOW?m=" + msgIndex + "&t="
+ WISEApplication.encode(ssid);
textBody = textBody.replaceAll("URL LINK", reminderLink + "\n");
if (this.hasDLink) {
textBody = textBody.replaceAll("DECLINE LINK", declineLink + "\n");
}
}
return textBody;
}
/**
* The URL for anonymous user to use.
*
* @param servletPath
* Root path of the URL being generated.
* @param msgIndex
* Index to identify a particular user.
* @param studySpaceId
* Study space id for which link has to be generated.
* @param surveyId
* Survey in the study space for which URL is generated.
* @return String URL for accessing the survey by anonymous users.
*/
public static String buildInviteUrl(String servletPath, String msgIndex, String studySpaceId, String surveyId) {
/*
* t = xxxx -> study space m = yyyy -> survey_user_message_space s =
* zzzz -> survey id for anonymous user we do not have survey message
* user and it is not possible to get survey from study space while
* knowing the survey for annonymous users because study space can have
* multiple surveys.
*/
if (msgIndex == null) {
return servletPath + "survey?t=" + WISEApplication.encode(studySpaceId) + "&s="
+ CommonUtils.base64Encode(surveyId);
}
return servletPath + "survey?msg=" + msgIndex + "&t=" + WISEApplication.encode(surveyId);
}
/**
* Composes the body of email in text format.
*
* @param salutation
* Salutation to address the invitee to whom email has to be
* sent.
* @param lastname
* Last name of the invitee.
* @param ssid
* Studyspace id for generation of the URL.
* @param msgIndex
* Id to identify the invitee.
* @return String Body of the email in text format.
*/
public String composeHtmlBody(String salutation, String lastname, String ssid, String msgIndex) {
if (!this.htmlFormat) {
/*
* null return is the external signal the message doesn't have an
* HTML version
*/
return null;
}
/*
* this overrides the iVar TODO: FIX so that we can actually use it here
* and for overview display
*/
String htmlBody = null;
/* add the html header & the top of the body to the html body */
htmlBody = HTML_OPEN + this.htmlHeader;
htmlBody += "<p><b>Dear " + salutation + " " + lastname + ":</b></p>" + this.mainBody;
htmlBody = htmlBody.replaceAll("\n", "<br>");
if (this.hasLink) {
String reminderLink = this.servletPath + "survey?msg=" + msgIndex + "&t=" + WISEApplication.encode(ssid);
String declineLink = this.servletPath + "declineNOW?m=" + msgIndex + "&t=" + WISEApplication.encode(ssid);
htmlBody = htmlBody.replaceAll("URL LINK", "<p align=center><a href='" + reminderLink + "'>" + reminderLink
+ "</a></p>");
if (this.hasDLink) {
htmlBody = htmlBody.replaceAll("DECLINE LINK", "<p align=center><a href='" + declineLink + "'>"
+ declineLink + "</a></p>");
}
}
/* append the bottom part of body for the html email */
htmlBody += this.htmlTail + htmlClose;
return htmlBody;
}
/**
* Renders html table rows to complete sample display page (used by Admin)
*
* @return String HTML format of the mail.
*/
public String renderSampleAsHtmlRows() {
String outputString = "<tr><td class=sfon>Subject: </td>";
outputString += "<td>" + this.subject + "</td></tr>";
outputString += "<tr><td colspan=2>";
/* add the the bottom imag & signature to the html body */
if (this.htmlFormat) {
outputString += this.htmlHeader;
outputString += "<p>Dear [Salutation] [Name]:</p>";
outputString += this.htmlBody;
outputString += this.htmlTail; // note: includes signature
} else {
outputString += "<table width=100% border=0 cellpadding=0 cellspacing=0>";
outputString += "<tr><td> </td></tr>";
outputString += "<tr><td colspan=2><font size=1 face='Verdana'><p>Dear [Salutation] [Name],</p>\n";
outputString += this.mainBody + "<p> </p></font></td></tr></table>\n\n";
}
outputString += "</td></tr>";
return outputString;
}
@Override
public String toString() {
return "<P><B>Message</b> ID: " + this.id + "<br>\n" + "References: " + this.msgRef + "<br>\n" + "Subject: "
+ this.subject + "<br>\n" + "Body: " + this.mainBody + "</p>\n";
}
}
| Java | CL | 4752727b0c170f5dc214c48b8ea7da71f7415a7c37eb36a19fb515f78bc7ddaf |
package at.scch.securitylibary.config.httpclient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.security.oauth2.client.OAuth2ClientContext;
import org.springframework.security.oauth2.client.OAuth2RestTemplate;
import org.springframework.security.oauth2.client.resource.OAuth2ProtectedResourceDetails;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.context.annotation.RequestScope;
@Configuration
public class RestTemplateConfig {
@Bean
@Primary
public OAuth2RestTemplate restTemplate(OAuth2ProtectedResourceDetails resource, OAuth2ClientContext context, LoadBalancerInterceptor interceptor) {
OAuth2RestTemplate restTemplate = new OAuth2RestTemplate(resource, context);
restTemplate.getInterceptors().add(interceptor);
return restTemplate;
}
@Bean
@RequestScope
RestTemplate simpleRestTemplate(LoadBalancerInterceptor interceptor) {
RestTemplate restTemplate = new RestTemplate();
restTemplate.getInterceptors().add(interceptor);
return restTemplate;
}
}
| Java | CL | 98b3410e719382b871c2823888b9573f259f12fc7fe46ca04b52a03917000c0d |
package pl.edu.ug.inf.am.adventure.fight.logic;
import pl.aml.impl.opponent.OpponentType;
import pl.edu.ug.inf.am.adventure.dagger.PerAdventureStage;
import javax.inject.Inject;
import java.util.List;
@PerAdventureStage
public class FightPreparation {
private final SkillsLogic skillsLogic;
private final FightOpponentsManager opponentsManager;
@Inject
public FightPreparation(SkillsLogic skillsLogic, FightOpponentsManager opponentsManager) {
this.skillsLogic = skillsLogic;
this.opponentsManager = opponentsManager;
}
public void prepare(List<OpponentType> opponents) {
opponentsManager.setOpponentsToKill(opponents);
skillsLogic.createSkillsList();
}
}
| Java | CL | 7ae4b40d8554761959960388b6a3f44af1c21dbfe0094d3d248bdff59056180a |
/**
* <p> DAODB - Implements the DAO package interface in the DB using JDBC connection and SQL query.
* The DAO Package consist of interface Classes describing C.R.U.D (Create,Read,Update,Delete)
* actions,for Company ,Customer and Coupon
* </p>
* <img src="{@docRoot}/images/DAOandDAODB.jpg" alt="DAOandDAODB" style="width:850px">
*/
package f_coupon.sys.core.dao.db; | Java | CL | 36a9580c87a85c1e538ba4c986cf4feaef21ba177a3307fbc9a44701092bc8a4 |
// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3) annotate
// Source File Name: TrainingSetListener.java
package rm.gui.beans;
import java.util.EventListener;
// Referenced classes of package rm.gui.beans:
// TrainingSetEvent
public interface TrainingSetListener
extends EventListener
{
public abstract void acceptTrainingSet(TrainingSetEvent trainingsetevent);
}
| Java | CL | fa856f875c52375d12d968c314b03dd977ffa288fa878939b5722835f7b044d4 |
package com.morganstanley.stocklending.approval;
/**
* ApprovalDecisionServiceFactory is the factory to instantiate concrete class
* that implements AbstractApprovalService.
*
* Assumption: In this assignment it will create an instance of
* StockLendingDecisionService
*
* @author Richard Wu
*/
public class ApprovalDecisionServiceFactory extends AbstractApprovalServiceFactory {
/**
* Get the class instance that implements ApprovalDecisionService interface
*
* @param approvalResponseServiceName
* service name
*/
@Override
public ApprovalDecisionService getApprovalDecisionService(String approvalDecisionServiceName) {
if (approvalDecisionServiceName == null)
throw new IllegalArgumentException("Argument \"decisionServiceName\" is null");
switch (approvalDecisionServiceName) {
case StockLendingDecisionService.SERVICE_NAME:
return new StockLendingDecisionService();
/*
* please add other types of concrete ApprovalDescisionService here
*/
default:
return null;
}
}
@Override
public ApprovalResponseService getApprovalResponseService(String approvalResponseServiceName) {
return null;
}
}
| Java | CL | 496c2d6d186f922f1a5db82da9f3233c3248fa08a89b7eb615b0eabb896b39f4 |
package org.kuali.ole.docstore.model.xstream.work.bib.marc;
import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import org.kuali.ole.docstore.model.xmlpojo.work.bib.marc.SubField;
/**
* Created by IntelliJ IDEA.
* User: pvsubrah
* Date: 10/5/11
* Time: 5:53 PM
* To change this template use File | Settings | File Templates.
*/
public class SubFieldConverter
implements Converter {
@Override
public void marshal(Object o, HierarchicalStreamWriter hierarchicalStreamWriter,
MarshallingContext marshallingContext) {
SubField marcSubField = (SubField) o;
hierarchicalStreamWriter.addAttribute("code", marcSubField.getCode());
hierarchicalStreamWriter.setValue(marcSubField.getValue());
}
@Override
public Object unmarshal(HierarchicalStreamReader hierarchicalStreamReader,
UnmarshallingContext unmarshallingContext) {
SubField marcSubField = new SubField();
marcSubField.setCode(hierarchicalStreamReader.getAttribute("code"));
marcSubField.setValue(hierarchicalStreamReader.getValue());
return marcSubField;
}
@Override
public boolean canConvert(Class aClass) {
return aClass.equals(SubField.class);
}
}
| Java | CL | a10765d03522d535e0057f210e2141c1c130e31192b4e8f0246bb8a338061846 |
package au.edu.unimelb.eldercare.messaging;
import android.support.v7.widget.RecyclerView;
import android.view.View;
/**
* The base view holder class from which each new
* concrete message view holder class extends
*/
public abstract class MessageViewHolder extends RecyclerView.ViewHolder {
MessageViewHolder(View view) {
super(view);
}
/**
* Binds message object contents to different
* item view components in the view holder
* @param message the message to bind
*/
public abstract void bind(Message message);
}
| Java | CL | 4d159dfa33a7974a370c7f62885570274fdfc0f2aab2745f94fb09151f146fcb |
package com.vt.gameobjects.actionqueue;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.utils.Queue;
import com.vt.game.Constants;
import com.vt.gameobjects.TouchHandler;
import com.vt.gameobjects.actionqueue.actions.PlaceMovementPointer;
import com.vt.gameobjects.actionqueue.actions.PlaceViewPointer;
import com.vt.gameobjects.characters.CharacterObject;
import com.vt.gameobjects.pointers.PointerSwitcher;
/**
* Created by Fck.r.sns on 22.08.2015.
*/
public class ActionQueue {
private PlayerVirtualState m_virtualState;
private CharacterObject m_character;
private Context m_context;
private AbstractQueueableAction m_candidate;
private Queue<Queue<AbstractQueueableAction>> m_actions = new Queue<Queue<AbstractQueueableAction>>(128);
private AbstractQueueableAction m_currentAction;
public ActionQueue(CharacterObject character) {
m_character = character;
m_virtualState = new PlayerVirtualState(
m_character.getMovementPointer().getPosition(),
m_character.getViewPointer().getPosition()
);
m_context = new Context(m_character, m_virtualState);
}
public void act(float delta) {
if (m_actions.size != 0) {
// dispatch next action
Queue<AbstractQueueableAction> subqueue = m_actions.first();
AbstractQueueableAction next = subqueue.first();
if (m_currentAction == null) {
m_currentAction = next;
if (m_currentAction.start(m_context)) {
m_currentAction.stop(m_context);
m_currentAction = null;
}
subqueue.removeFirst();
if (subqueue.size == 0)
m_actions.removeFirst();
}
}
if (m_currentAction != null) {
if (m_currentAction.execute(m_context)) {
m_currentAction.stop(m_context);
m_currentAction = null;
}
}
}
public void draw(SpriteBatch batch) {
if (m_currentAction != null)
m_currentAction.draw(batch);
if (m_candidate != null)
m_candidate.draw(batch);
for (Queue<AbstractQueueableAction> subqueue : m_actions)
for (QueueableAction action : subqueue)
action.draw(batch);
}
public void addAction(AbstractQueueableAction action) {
if (action == null)
return;
Queue<AbstractQueueableAction> subQueue = new Queue<AbstractQueueableAction>(1);
subQueue.addLast(action);
m_actions.addLast(subQueue);
action.onAdd(m_context);
}
public void addAction(Queue<AbstractQueueableAction> subqueue, AbstractQueueableAction action) {
if (action == null)
return;
subqueue.addLast(action);
action.onAdd(m_context);
}
public void clear() {
m_actions.clear();
m_currentAction = null;
m_candidate = null;
}
public void removeLast() {
m_actions.removeLast();
}
public class Controller implements TouchHandler {
private PointerSwitcher m_pointerSwitcher = new PointerSwitcher();
private Queue<AbstractQueueableAction> nearestSubqueue;
private float lastX;
private float lastY;
public void setCurrentPointerToMovement() {
m_pointerSwitcher.setCurrentPointerToMovement();
}
public void setCurrentPointerToView() {
m_pointerSwitcher.setCurrentPointerToView();
}
@Override
public boolean handleTouchDown(InputEvent event, float x, float y, int pointer, int button) {
lastX = x;
lastY = y;
if (m_actions.size == 0) {
float xChar = m_character.getX(Constants.ALIGN_ORIGIN);
float yChar = m_character.getY(Constants.ALIGN_ORIGIN);
m_virtualState.changeMovementPtrPos(xChar, yChar);
m_virtualState.changeViewPtrPos(xChar, yChar);
addAction(new PlaceMovementPointer(xChar, yChar, m_context, true));
}
if (m_pointerSwitcher.isCurrentPointerMovement()) {
m_candidate = new PlaceMovementPointer(x, y, m_context);
} else {
nearestSubqueue = null;
float dst2 = Float.MAX_VALUE;
float xOrig = x, yOrig = y;
for (Queue<AbstractQueueableAction> subqueue : m_actions) {
for (AbstractQueueableAction action : subqueue) {
if (!action.getFlags().CHANGE_MOVE_PTR)
continue;
float newDst2 = action.getPosition().dst2(x, y);
if (newDst2 < dst2) {
nearestSubqueue = subqueue;
dst2 = newDst2;
xOrig = action.getX();
yOrig = action.getY();
}
}
}
if (nearestSubqueue != null)
m_candidate = new PlaceViewPointer(xOrig, yOrig, x, y, m_context);
else
m_candidate = new PlaceViewPointer(x, y, m_context);
}
return true;
}
@Override
public void handleTouchUp(InputEvent event, float x, float y, int pointer, int button) {
if (m_pointerSwitcher.isCurrentPointerMovement() || nearestSubqueue == null) {
addAction(m_candidate);
} else {
addAction(nearestSubqueue, m_candidate);
nearestSubqueue = null;
}
m_candidate = null;
}
@Override
public void handleTouchDragged(InputEvent event, float x, float y, int pointer) {
if (m_pointerSwitcher.isCurrentPointerMovement()) {
float dst = new Vector2(x, y).dst2(lastX, lastY);
if (dst > 0.4f) {
handleTouchUp(event, x, y, pointer, 0);
handleTouchDown(event, x, y, pointer, 0);
lastX = x;
lastY = y;
}
}
m_candidate.setPosition(x, y);
}
}
}
| Java | CL | 4337bd2ad195b08666d612eaffb42fa148a5d47fbec4004d2dccb5d38db60e34 |
/*******************************************************************************
* Fraco - Eclipse plug-in to detect fragile comments
*
* Copyright (C) 2019 McGill University
*
* Eclipse Public License - v 2.0
*
* THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE
* PUBLIC LICENSE v2.0. ANY USE, REPRODUCTION OR DISTRIBUTION
* OF THE PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT.
*******************************************************************************/
/**
*
*/
package fraco.rules;
/**
* Enum used for the type of matching ca.mcgill.cs.stg.fraco.rules used.
*
* @author inder
*
*/
public enum RuleTypes {
IDENTICAL_MATCH, FUZZY_MATCH, LEXICAL_TOKENS_MATCH, SEMANTIC_TOKENS_MATCH, LEMMA_TOKENS_LEXICAL, LEMMA_TOKENS_SEMANTIC
}
| Java | CL | 167ab797609b152b24ad4cd44a78026c060bedc5553a4d4c30895aff3aac1924 |
/**
* 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.fs.azure;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;
import java.util.Random;
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.Semaphore;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import org.apache.hadoop.fs.impl.StoreImplementationUtils;
import org.apache.hadoop.classification.VisibleForTesting;
import org.apache.hadoop.util.Preconditions;
import org.apache.commons.lang3.StringUtils;
import org.apache.hadoop.fs.FSExceptionMessages;
import org.apache.commons.codec.binary.Base64;
import org.apache.hadoop.fs.StreamCapabilities;
import org.apache.hadoop.fs.Syncable;
import org.apache.hadoop.fs.azure.StorageInterface.CloudBlockBlobWrapper;
import org.apache.hadoop.io.ElasticByteBufferPool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.microsoft.azure.storage.AccessCondition;
import com.microsoft.azure.storage.OperationContext;
import com.microsoft.azure.storage.StorageException;
import com.microsoft.azure.storage.StorageErrorCodeStrings;
import com.microsoft.azure.storage.blob.BlobRequestOptions;
import com.microsoft.azure.storage.blob.BlockEntry;
import com.microsoft.azure.storage.blob.BlockListingFilter;
import com.microsoft.azure.storage.blob.BlockSearchMode;
/**
* Stream object that implements append for Block Blobs in WASB.
*
* The stream object implements hflush/hsync and block compaction. Block
* compaction is the process of replacing a sequence of small blocks with one
* big block. Azure Block blobs supports up to 50000 blocks and every
* hflush/hsync generates one block. When the number of blocks is above 32000,
* the process of compaction decreases the total number of blocks, if possible.
* If compaction is disabled, hflush/hsync are empty functions.
*
* The stream object uses background threads for uploading the blocks and the
* block blob list. Blocks can be uploaded concurrently. However, when the block
* list is uploaded, block uploading should stop. If a block is uploaded before
* the block list and the block id is not in the list, the block will be lost.
* If the block is uploaded after the block list and the block id is in the
* list, the block list upload will fail. The exclusive access for the block
* list upload is managed by uploadingSemaphore.
*/
public class BlockBlobAppendStream extends OutputStream implements Syncable,
StreamCapabilities {
/**
* The name of the blob/file.
*/
private final String key;
/**
* This variable tracks if this is new blob or existing one.
*/
private boolean blobExist;
/**
* When the blob exist, to to prevent concurrent write we take a lease.
* Taking a lease is not necessary for new blobs.
*/
private SelfRenewingLease lease = null;
/**
* The support for process of compaction is optional.
*/
private final boolean compactionEnabled;
/**
* The number of blocks above each block compaction is triggered.
*/
private static final int DEFAULT_ACTIVATE_COMPACTION_BLOCK_COUNT = 32000;
/**
* The number of blocks above each block compaction is triggered.
*/
private int activateCompactionBlockCount
= DEFAULT_ACTIVATE_COMPACTION_BLOCK_COUNT;
/**
* The size of the output buffer. Writes store the data in outBuffer until
* either the size is above maxBlockSize or hflush/hsync is called.
*/
private final AtomicInteger maxBlockSize;
/**
* The current buffer where writes are stored.
*/
private ByteBuffer outBuffer;
/**
* The size of the blob that has been successfully stored in the Azure Blob
* service.
*/
private final AtomicLong committedBlobLength = new AtomicLong(0);
/**
* Position of last block in the blob.
*/
private volatile long blobLength = 0;
/**
* Minutes waiting before the close operation timed out.
*/
private static final int CLOSE_UPLOAD_DELAY = 10;
/**
* Keep alive time for the threadpool.
*/
private static final int THREADPOOL_KEEP_ALIVE = 30;
/**
* Azure Block Blob used for the stream.
*/
private final CloudBlockBlobWrapper blob;
/**
* Azure Storage operation context.
*/
private final OperationContext opContext;
/**
* Commands send from client calls to the background thread pool.
*/
private abstract class UploadCommand {
// the blob offset for the command
private final long commandBlobOffset;
// command completion latch
private final CountDownLatch completed = new CountDownLatch(1);
UploadCommand(long offset) {
this.commandBlobOffset = offset;
}
long getCommandBlobOffset() {
return commandBlobOffset;
}
void await() throws InterruptedException {
completed.await();
}
void awaitAsDependent() throws InterruptedException {
await();
}
void setCompleted() {
completed.countDown();
}
void execute() throws InterruptedException, IOException {}
void dump() {}
}
/**
* The list of recent commands. Before block list is committed, all the block
* listed in the list must be uploaded. activeBlockCommands is used for
* enumerating the blocks and waiting on the latch until the block is
* uploaded.
*/
private final ConcurrentLinkedQueue<UploadCommand> activeBlockCommands
= new ConcurrentLinkedQueue<>();
/**
* Variable to track if the stream has been closed.
*/
private volatile boolean closed = false;
/**
* First IOException encountered.
*/
private final AtomicReference<IOException> firstError
= new AtomicReference<>();
/**
* Flag set when the first error has been thrown.
*/
private boolean firstErrorThrown = false;
/**
* Semaphore for serializing block uploads with NativeAzureFileSystem.
*
* The semaphore starts with number of permits equal to the number of block
* upload threads. Each block upload thread needs one permit to start the
* upload. The put block list acquires all the permits before the block list
* is committed.
*/
private final Semaphore uploadingSemaphore = new Semaphore(
MAX_NUMBER_THREADS_IN_THREAD_POOL,
true);
/**
* Queue storing buffers with the size of the Azure block ready for
* reuse. The pool allows reusing the blocks instead of allocating new
* blocks. After the data is sent to the service, the buffer is returned
* back to the queue
*/
private final ElasticByteBufferPool poolReadyByteBuffers
= new ElasticByteBufferPool();
/**
* The blob's block list.
*/
private final List<BlockEntry> blockEntries = new ArrayList<>(
DEFAULT_CAPACITY_BLOCK_ENTRIES);
private static final int DEFAULT_CAPACITY_BLOCK_ENTRIES = 1024;
/**
* The uncommitted blob's block list.
*/
private final ConcurrentLinkedDeque<BlockEntry> uncommittedBlockEntries
= new ConcurrentLinkedDeque<>();
/**
* Variable to hold the next block id to be used for azure storage blocks.
*/
private static final int UNSET_BLOCKS_COUNT = -1;
private long nextBlockCount = UNSET_BLOCKS_COUNT;
/**
* Variable to hold the block id prefix to be used for azure storage blocks.
*/
private String blockIdPrefix = null;
/**
* Maximum number of threads in block upload thread pool.
*/
private static final int MAX_NUMBER_THREADS_IN_THREAD_POOL = 4;
/**
* Number of times block upload needs is retried.
*/
private static final int MAX_BLOCK_UPLOAD_RETRIES = 3;
/**
* Wait time between block upload retries in milliseconds.
*/
private static final int BLOCK_UPLOAD_RETRY_INTERVAL = 1000;
/**
* Logger.
*/
private static final Logger LOG =
LoggerFactory.getLogger(BlockBlobAppendStream.class);
/**
* The absolute maximum of blocks for a blob. It includes committed and
* temporary blocks.
*/
private static final int MAX_BLOCK_COUNT = 100000;
/**
* The upload thread pool executor.
*/
private ThreadPoolExecutor ioThreadPool;
/**
* Azure Storage access conditions for the blob.
*/
private final AccessCondition accessCondition = new AccessCondition();
/**
* Atomic integer to provide thread id for thread names for uploader threads.
*/
private final AtomicInteger threadSequenceNumber;
/**
* Prefix to be used for thread names for uploader threads.
*/
private static final String THREAD_ID_PREFIX = "append-blockblob";
/**
* BlockBlobAppendStream constructor.
*
* @param blob
* Azure Block Blob
* @param aKey
* blob's name
* @param bufferSize
* the maximum size of a blob block.
* @param compactionEnabled
* is the compaction process enabled for this blob
* @param opContext
* Azure Store operation context for the blob
* @throws IOException
* if an I/O error occurs. In particular, an IOException may be
* thrown if the output stream cannot be used for append operations
*/
public BlockBlobAppendStream(final CloudBlockBlobWrapper blob,
final String aKey,
final int bufferSize,
final boolean compactionEnabled,
final OperationContext opContext)
throws IOException {
Preconditions.checkArgument(StringUtils.isNotEmpty(aKey));
Preconditions.checkArgument(bufferSize >= 0);
this.blob = blob;
this.opContext = opContext;
this.key = aKey;
this.maxBlockSize = new AtomicInteger(bufferSize);
this.threadSequenceNumber = new AtomicInteger(0);
this.blockIdPrefix = null;
this.compactionEnabled = compactionEnabled;
this.blobExist = true;
this.outBuffer = poolReadyByteBuffers.getBuffer(false, maxBlockSize.get());
try {
// download the block list
blockEntries.addAll(
blob.downloadBlockList(
BlockListingFilter.COMMITTED,
new BlobRequestOptions(),
opContext));
blobLength = blob.getProperties().getLength();
committedBlobLength.set(blobLength);
// Acquiring lease on the blob.
lease = new SelfRenewingLease(blob, true);
accessCondition.setLeaseID(lease.getLeaseID());
} catch (StorageException ex) {
if (ex.getErrorCode().equals(StorageErrorCodeStrings.BLOB_NOT_FOUND)) {
blobExist = false;
}
else if (ex.getErrorCode().equals(
StorageErrorCodeStrings.LEASE_ALREADY_PRESENT)) {
throw new AzureException(
"Unable to set Append lease on the Blob: " + ex, ex);
}
else {
LOG.debug(
"Encountered storage exception."
+ " StorageException : {} ErrorCode : {}",
ex,
ex.getErrorCode());
throw new AzureException(ex);
}
}
setBlocksCountAndBlockIdPrefix(blockEntries);
this.ioThreadPool = new ThreadPoolExecutor(
MAX_NUMBER_THREADS_IN_THREAD_POOL,
MAX_NUMBER_THREADS_IN_THREAD_POOL,
THREADPOOL_KEEP_ALIVE,
TimeUnit.SECONDS,
new LinkedBlockingQueue<>(),
new UploaderThreadFactory());
}
/**
* Set payload size of the stream.
* It is intended to be used for unit testing purposes only.
*/
@VisibleForTesting
synchronized void setMaxBlockSize(int size) {
maxBlockSize.set(size);
// it is for testing only so we can abandon the previously allocated
// payload
this.outBuffer = ByteBuffer.allocate(maxBlockSize.get());
}
/**
* Set compaction parameters.
* It is intended to be used for unit testing purposes only.
*/
@VisibleForTesting
void setCompactionBlockCount(int activationCount) {
activateCompactionBlockCount = activationCount;
}
/**
* Get the list of block entries. It is used for testing purposes only.
* @return List of block entries.
*/
@VisibleForTesting
List<BlockEntry> getBlockList() throws StorageException, IOException {
return blob.downloadBlockList(
BlockListingFilter.COMMITTED,
new BlobRequestOptions(),
opContext);
}
/**
* Writes the specified byte to this output stream. The general contract for
* write is that one byte is written to the output stream. The byte to be
* written is the eight low-order bits of the argument b. The 24 high-order
* bits of b are ignored.
*
* @param byteVal
* the byteValue to write.
* @throws IOException
* if an I/O error occurs. In particular, an IOException may be
* thrown if the output stream has been closed.
*/
@Override
public void write(final int byteVal) throws IOException {
write(new byte[] { (byte) (byteVal & 0xFF) });
}
/**
* Writes length bytes from the specified byte array starting at offset to
* this output stream.
*
* @param data
* the byte array to write.
* @param offset
* the start offset in the data.
* @param length
* the number of bytes to write.
* @throws IOException
* if an I/O error occurs. In particular, an IOException may be
* thrown if the output stream has been closed.
*/
@Override
public synchronized void write(final byte[] data, int offset, int length)
throws IOException {
Preconditions.checkArgument(data != null, "null data");
if (offset < 0 || length < 0 || length > data.length - offset) {
throw new IndexOutOfBoundsException();
}
if (closed) {
throw new IOException(FSExceptionMessages.STREAM_IS_CLOSED);
}
while (outBuffer.remaining() < length) {
int remaining = outBuffer.remaining();
outBuffer.put(data, offset, remaining);
// upload payload to azure storage
addBlockUploadCommand();
offset += remaining;
length -= remaining;
}
outBuffer.put(data, offset, length);
}
/**
* Flushes this output stream and forces any buffered output bytes to be
* written out. If any data remains in the payload it is committed to the
* service. Data is queued for writing and forced out to the service
* before the call returns.
*/
@Override
public void flush() throws IOException {
if (closed) {
// calling close() after the stream is closed starts with call to flush()
return;
}
addBlockUploadCommand();
if (committedBlobLength.get() < blobLength) {
try {
// wait until the block list is committed
addFlushCommand().await();
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
}
}
}
/**
* Force all data in the output stream to be written to Azure storage.
* Wait to return until this is complete.
*/
@Override
public void hsync() throws IOException {
// when block compaction is disabled, hsync is empty function
if (compactionEnabled) {
flush();
}
}
/**
* Force all data in the output stream to be written to Azure storage.
* Wait to return until this is complete.
*/
@Override
public void hflush() throws IOException {
// when block compaction is disabled, hflush is empty function
if (compactionEnabled) {
flush();
}
}
/**
* The Synchronization capabilities of this stream depend upon the compaction
* policy.
* @param capability string to query the stream support for.
* @return true for hsync and hflush when compaction is enabled.
*/
@Override
public boolean hasCapability(String capability) {
if (!compactionEnabled) {
return false;
}
return StoreImplementationUtils.isProbeForSyncable(capability);
}
/**
* Force all data in the output stream to be written to Azure storage.
* Wait to return until this is complete. Close the access to the stream and
* shutdown the upload thread pool.
* If the blob was created, its lease will be released.
* Any error encountered caught in threads and stored will be rethrown here
* after cleanup.
*/
@Override
public synchronized void close() throws IOException {
LOG.debug("close {} ", key);
if (closed) {
return;
}
// Upload the last block regardless of compactionEnabled flag
flush();
// Initiates an orderly shutdown in which previously submitted tasks are
// executed.
ioThreadPool.shutdown();
try {
// wait up to CLOSE_UPLOAD_DELAY minutes to upload all the blocks
if (!ioThreadPool.awaitTermination(CLOSE_UPLOAD_DELAY, TimeUnit.MINUTES)) {
LOG.error("Time out occurred while close() is waiting for IO request to"
+ " finish in append"
+ " for blob : {}",
key);
NativeAzureFileSystemHelper.logAllLiveStackTraces();
throw new AzureException("Timed out waiting for IO requests to finish");
}
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
// release the lease
if (firstError.get() == null && blobExist) {
try {
lease.free();
} catch (StorageException ex) {
LOG.debug("Lease free update blob {} encountered Storage Exception:"
+ " {} Error Code : {}",
key,
ex,
ex.getErrorCode());
maybeSetFirstError(new AzureException(ex));
}
}
closed = true;
// finally, throw the first exception raised if it has not
// been thrown elsewhere.
if (firstError.get() != null && !firstErrorThrown) {
throw firstError.get();
}
}
/**
* Helper method used to generate the blockIDs. The algorithm used is similar
* to the Azure storage SDK.
*/
private void setBlocksCountAndBlockIdPrefix(List<BlockEntry> blockEntries) {
if (nextBlockCount == UNSET_BLOCKS_COUNT && blockIdPrefix == null) {
Random sequenceGenerator = new Random();
String blockZeroBlockId = (!blockEntries.isEmpty())
? blockEntries.get(0).getId()
: "";
String prefix = UUID.randomUUID().toString() + "-";
String sampleNewerVersionBlockId = generateNewerVersionBlockId(prefix,
0);
if (!blockEntries.isEmpty()
&& blockZeroBlockId.length() < sampleNewerVersionBlockId.length()) {
// If blob has already been created with 2.2.0, append subsequent blocks
// with older version (2.2.0) blockId compute nextBlockCount, the way it
// was done before; and don't use blockIdPrefix
this.blockIdPrefix = "";
nextBlockCount = (long) (sequenceGenerator.nextInt(Integer.MAX_VALUE))
+ sequenceGenerator.nextInt(
Integer.MAX_VALUE - MAX_BLOCK_COUNT);
nextBlockCount += blockEntries.size();
} else {
// If there are no existing blocks, create the first block with newer
// version (4.2.0) blockId. If blob has already been created with 4.2.0,
// append subsequent blocks with newer version (4.2.0) blockId
this.blockIdPrefix = prefix;
nextBlockCount = blockEntries.size();
}
}
}
/**
* Helper method that generates the next block id for uploading a block to
* azure storage.
* @return String representing the block ID generated.
* @throws IOException if the stream is in invalid state
*/
private String generateBlockId() throws IOException {
if (nextBlockCount == UNSET_BLOCKS_COUNT || blockIdPrefix == null) {
throw new AzureException(
"Append Stream in invalid state. nextBlockCount not set correctly");
}
return (!blockIdPrefix.isEmpty())
? generateNewerVersionBlockId(blockIdPrefix, nextBlockCount++)
: generateOlderVersionBlockId(nextBlockCount++);
}
/**
* Helper method that generates an older (2.2.0) version blockId.
* @return String representing the block ID generated.
*/
private String generateOlderVersionBlockId(long id) {
byte[] blockIdInBytes = new byte[8];
for (int m = 0; m < 8; m++) {
blockIdInBytes[7 - m] = (byte) ((id >> (8 * m)) & 0xFF);
}
return new String(
Base64.encodeBase64(blockIdInBytes),
StandardCharsets.UTF_8);
}
/**
* Helper method that generates an newer (4.2.0) version blockId.
* @return String representing the block ID generated.
*/
private String generateNewerVersionBlockId(String prefix, long id) {
String blockIdSuffix = String.format("%06d", id);
byte[] blockIdInBytes =
(prefix + blockIdSuffix).getBytes(StandardCharsets.UTF_8);
return new String(Base64.encodeBase64(blockIdInBytes), StandardCharsets.UTF_8);
}
/**
* This is shared between upload block Runnable and CommitBlockList. The
* method captures retry logic
* @param blockId block name
* @param dataPayload block content
*/
private void writeBlockRequestInternal(String blockId,
ByteBuffer dataPayload,
boolean bufferPoolBuffer) {
IOException lastLocalException = null;
int uploadRetryAttempts = 0;
while (uploadRetryAttempts < MAX_BLOCK_UPLOAD_RETRIES) {
try {
long startTime = System.nanoTime();
blob.uploadBlock(blockId, accessCondition, new ByteArrayInputStream(
dataPayload.array()), dataPayload.position(),
new BlobRequestOptions(), opContext);
LOG.debug("upload block finished for {} ms. block {} ",
TimeUnit.NANOSECONDS.toMillis(
System.nanoTime() - startTime), blockId);
break;
} catch(Exception ioe) {
LOG.debug("Encountered exception during uploading block for Blob {}"
+ " Exception : {}", key, ioe);
uploadRetryAttempts++;
lastLocalException = new AzureException(
"Encountered Exception while uploading block: " + ioe, ioe);
try {
Thread.sleep(
BLOCK_UPLOAD_RETRY_INTERVAL * (uploadRetryAttempts + 1));
} catch(InterruptedException ie) {
Thread.currentThread().interrupt();
break;
}
}
}
if (bufferPoolBuffer) {
poolReadyByteBuffers.putBuffer(dataPayload);
}
if (uploadRetryAttempts == MAX_BLOCK_UPLOAD_RETRIES) {
maybeSetFirstError(lastLocalException);
}
}
/**
* Set {@link #firstError} to the exception if it is not already set.
* @param exception exception to save
*/
private void maybeSetFirstError(IOException exception) {
firstError.compareAndSet(null, exception);
}
/**
* Throw the first error caught if it has not been raised already
* @throws IOException if one is caught and needs to be thrown.
*/
private void maybeThrowFirstError() throws IOException {
if (firstError.get() != null) {
firstErrorThrown = true;
throw firstError.get();
}
}
/**
* Write block list. The method captures retry logic
*/
private void writeBlockListRequestInternal() {
IOException lastLocalException = null;
int uploadRetryAttempts = 0;
while (uploadRetryAttempts < MAX_BLOCK_UPLOAD_RETRIES) {
try {
long startTime = System.nanoTime();
blob.commitBlockList(blockEntries, accessCondition,
new BlobRequestOptions(), opContext);
LOG.debug("Upload block list took {} ms for blob {} ",
TimeUnit.NANOSECONDS.toMillis(
System.nanoTime() - startTime), key);
break;
} catch(Exception ioe) {
LOG.debug("Encountered exception during uploading block for Blob {}"
+ " Exception : {}", key, ioe);
uploadRetryAttempts++;
lastLocalException = new AzureException(
"Encountered Exception while uploading block: " + ioe, ioe);
try {
Thread.sleep(
BLOCK_UPLOAD_RETRY_INTERVAL * (uploadRetryAttempts + 1));
} catch(InterruptedException ie) {
Thread.currentThread().interrupt();
break;
}
}
}
if (uploadRetryAttempts == MAX_BLOCK_UPLOAD_RETRIES) {
maybeSetFirstError(lastLocalException);
}
}
/**
* A ThreadFactory that creates uploader thread with
* meaningful names helpful for debugging purposes.
*/
class UploaderThreadFactory implements ThreadFactory {
@Override
public Thread newThread(Runnable r) {
Thread t = new Thread(r);
t.setName(String.format("%s-%d", THREAD_ID_PREFIX,
threadSequenceNumber.getAndIncrement()));
return t;
}
}
/**
* Upload block commands.
*/
private class UploadBlockCommand extends UploadCommand {
// the block content for upload
private final ByteBuffer payload;
// description of the block
private final BlockEntry entry;
UploadBlockCommand(String blockId, ByteBuffer payload) {
super(blobLength);
BlockEntry blockEntry = new BlockEntry(blockId);
blockEntry.setSize(payload.position());
blockEntry.setSearchMode(BlockSearchMode.LATEST);
this.payload = payload;
this.entry = blockEntry;
uncommittedBlockEntries.add(blockEntry);
}
/**
* Execute command.
*/
void execute() throws InterruptedException {
uploadingSemaphore.acquire(1);
writeBlockRequestInternal(entry.getId(), payload, true);
uploadingSemaphore.release(1);
}
void dump() {
LOG.debug("upload block {} size: {} for blob {}",
entry.getId(),
entry.getSize(),
key);
}
}
/**
* Upload blob block list commands.
*/
private class UploadBlockListCommand extends UploadCommand {
private BlockEntry lastBlock = null;
UploadBlockListCommand() {
super(blobLength);
if (!uncommittedBlockEntries.isEmpty()) {
lastBlock = uncommittedBlockEntries.getLast();
}
}
void awaitAsDependent() throws InterruptedException {
// empty. later commit block does not need to wait previous commit block
// lists.
}
void dump() {
LOG.debug("commit block list with {} blocks for blob {}",
uncommittedBlockEntries.size(), key);
}
/**
* Execute command.
*/
public void execute() throws InterruptedException, IOException {
if (committedBlobLength.get() >= getCommandBlobOffset()) {
LOG.debug("commit already applied for {}", key);
return;
}
if (lastBlock == null) {
LOG.debug("nothing to commit for {}", key);
return;
}
LOG.debug("active commands: {} for {}", activeBlockCommands.size(), key);
for (UploadCommand activeCommand : activeBlockCommands) {
if (activeCommand.getCommandBlobOffset() < getCommandBlobOffset()) {
activeCommand.dump();
activeCommand.awaitAsDependent();
} else {
break;
}
}
// stop all uploads until the block list is committed
uploadingSemaphore.acquire(MAX_NUMBER_THREADS_IN_THREAD_POOL);
BlockEntry uncommittedBlock;
do {
uncommittedBlock = uncommittedBlockEntries.poll();
blockEntries.add(uncommittedBlock);
} while (uncommittedBlock != lastBlock);
if (blockEntries.size() > activateCompactionBlockCount) {
LOG.debug("Block compaction: activated with {} blocks for {}",
blockEntries.size(), key);
// Block compaction
long startCompaction = System.nanoTime();
blockCompaction();
LOG.debug("Block compaction finished for {} ms with {} blocks for {}",
TimeUnit.NANOSECONDS.toMillis(
System.nanoTime() - startCompaction),
blockEntries.size(), key);
}
writeBlockListRequestInternal();
uploadingSemaphore.release(MAX_NUMBER_THREADS_IN_THREAD_POOL);
// remove blocks previous commands
for (Iterator<UploadCommand> it = activeBlockCommands.iterator();
it.hasNext();) {
UploadCommand activeCommand = it.next();
if (activeCommand.getCommandBlobOffset() <= getCommandBlobOffset()) {
it.remove();
} else {
break;
}
}
committedBlobLength.set(getCommandBlobOffset());
}
/**
* Internal output stream with read access to the internal buffer.
*/
private class ByteArrayOutputStreamInternal extends ByteArrayOutputStream {
ByteArrayOutputStreamInternal(int size) {
super(size);
}
byte[] getByteArray() {
return buf;
}
}
/**
* Block compaction process.
*
* Block compaction is only enabled when the number of blocks exceeds
* activateCompactionBlockCount. The algorithm searches for the longest
* segment [b..e) where (e-b) > 2 && |b| + |b+1| ... |e-1| < maxBlockSize
* such that size(b1) + size(b2) + ... + size(bn) < maximum-block-size.
* It then downloads the blocks in the sequence, concatenates the data to
* form a single block, uploads this new block, and updates the block
* list to replace the sequence of blocks with the new block.
*/
private void blockCompaction() throws IOException {
//current segment [segmentBegin, segmentEnd) and file offset/size of the
// current segment
int segmentBegin = 0, segmentEnd = 0;
long segmentOffsetBegin = 0, segmentOffsetEnd = 0;
//longest segment [maxSegmentBegin, maxSegmentEnd) and file offset/size of
// the longest segment
int maxSegmentBegin = 0, maxSegmentEnd = 0;
long maxSegmentOffsetBegin = 0, maxSegmentOffsetEnd = 0;
for (BlockEntry block : blockEntries) {
segmentEnd++;
segmentOffsetEnd += block.getSize();
if (segmentOffsetEnd - segmentOffsetBegin > maxBlockSize.get()) {
if (segmentEnd - segmentBegin > 2) {
if (maxSegmentEnd - maxSegmentBegin < segmentEnd - segmentBegin) {
maxSegmentBegin = segmentBegin;
maxSegmentEnd = segmentEnd;
maxSegmentOffsetBegin = segmentOffsetBegin;
maxSegmentOffsetEnd = segmentOffsetEnd - block.getSize();
}
}
segmentBegin = segmentEnd - 1;
segmentOffsetBegin = segmentOffsetEnd - block.getSize();
}
}
if (maxSegmentEnd - maxSegmentBegin > 1) {
LOG.debug("Block compaction: {} blocks for {}",
maxSegmentEnd - maxSegmentBegin, key);
// download synchronously all the blocks from the azure storage
ByteArrayOutputStreamInternal blockOutputStream
= new ByteArrayOutputStreamInternal(maxBlockSize.get());
try {
long length = maxSegmentOffsetEnd - maxSegmentOffsetBegin;
blob.downloadRange(maxSegmentOffsetBegin, length, blockOutputStream,
new BlobRequestOptions(), opContext);
} catch(StorageException ex) {
LOG.error(
"Storage exception encountered during block compaction phase"
+ " : {} Storage Exception : {} Error Code: {}",
key, ex, ex.getErrorCode());
throw new AzureException(
"Encountered Exception while committing append blocks " + ex, ex);
}
// upload synchronously new block to the azure storage
String blockId = generateBlockId();
ByteBuffer byteBuffer = ByteBuffer.wrap(
blockOutputStream.getByteArray());
byteBuffer.position(blockOutputStream.size());
writeBlockRequestInternal(blockId, byteBuffer, false);
// replace blocks from the longest segment with new block id
blockEntries.subList(maxSegmentBegin + 1, maxSegmentEnd - 1).clear();
BlockEntry newBlock = blockEntries.get(maxSegmentBegin);
newBlock.setId(blockId);
newBlock.setSearchMode(BlockSearchMode.LATEST);
newBlock.setSize(maxSegmentOffsetEnd - maxSegmentOffsetBegin);
}
}
}
/**
* Prepare block upload command and queue the command in thread pool executor.
*/
private synchronized void addBlockUploadCommand() throws IOException {
maybeThrowFirstError();
if (blobExist && lease.isFreed()) {
throw new AzureException(String.format(
"Attempting to upload a block on blob : %s "
+ " that does not have lease on the Blob. Failing upload", key));
}
int blockSize = outBuffer.position();
if (blockSize > 0) {
UploadCommand command = new UploadBlockCommand(generateBlockId(),
outBuffer);
activeBlockCommands.add(command);
blobLength += blockSize;
outBuffer = poolReadyByteBuffers.getBuffer(false, maxBlockSize.get());
ioThreadPool.execute(new WriteRequest(command));
}
}
/**
* Prepare block list commit command and queue the command in thread pool
* executor.
*/
private synchronized UploadCommand addFlushCommand() throws IOException {
maybeThrowFirstError();
if (blobExist && lease.isFreed()) {
throw new AzureException(
String.format("Attempting to upload block list on blob : %s"
+ " that does not have lease on the Blob. Failing upload", key));
}
UploadCommand command = new UploadBlockListCommand();
activeBlockCommands.add(command);
ioThreadPool.execute(new WriteRequest(command));
return command;
}
/**
* Runnable instance that uploads the block of data to azure storage.
*/
private class WriteRequest implements Runnable {
private final UploadCommand command;
WriteRequest(UploadCommand command) {
this.command = command;
}
@Override
public void run() {
try {
command.dump();
long startTime = System.nanoTime();
command.execute();
command.setCompleted();
LOG.debug("command finished for {} ms",
TimeUnit.NANOSECONDS.toMillis(
System.nanoTime() - startTime));
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
} catch (Exception ex) {
LOG.debug(
"Encountered exception during execution of command for Blob :"
+ " {} Exception : {}", key, ex);
firstError.compareAndSet(null, new AzureException(ex));
}
}
}
}
| Java | CL | 2aeef8366e56405535cdf297d5061c365f0791ed85b731d18624f911f599ac21 |
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1
begin_comment
comment|/* * 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. */
end_comment
begin_package
DECL|package|org.elasticsearch.index.reindex
package|package
name|org
operator|.
name|elasticsearch
operator|.
name|index
operator|.
name|reindex
package|;
end_package
begin_import
import|import
name|org
operator|.
name|elasticsearch
operator|.
name|action
operator|.
name|IndicesRequest
import|;
end_import
begin_import
import|import
name|org
operator|.
name|elasticsearch
operator|.
name|action
operator|.
name|search
operator|.
name|SearchRequest
import|;
end_import
begin_import
import|import
name|org
operator|.
name|elasticsearch
operator|.
name|action
operator|.
name|support
operator|.
name|IndicesOptions
import|;
end_import
begin_import
import|import
name|org
operator|.
name|elasticsearch
operator|.
name|common
operator|.
name|io
operator|.
name|stream
operator|.
name|StreamInput
import|;
end_import
begin_import
import|import
name|org
operator|.
name|elasticsearch
operator|.
name|common
operator|.
name|io
operator|.
name|stream
operator|.
name|StreamOutput
import|;
end_import
begin_import
import|import
name|org
operator|.
name|elasticsearch
operator|.
name|tasks
operator|.
name|TaskId
import|;
end_import
begin_import
import|import
name|java
operator|.
name|io
operator|.
name|IOException
import|;
end_import
begin_comment
comment|/** * Request to update some documents. That means you can't change their type, id, index, or anything like that. This implements * CompositeIndicesRequest but in a misleading way. Rather than returning all the subrequests that it will make it tries to return a * representative set of subrequests. This is best-effort but better than {@linkplain ReindexRequest} because scripts can't change the * destination index and things. */
end_comment
begin_class
DECL|class|UpdateByQueryRequest
specifier|public
class|class
name|UpdateByQueryRequest
extends|extends
name|AbstractBulkIndexByScrollRequest
argument_list|<
name|UpdateByQueryRequest
argument_list|>
implements|implements
name|IndicesRequest
operator|.
name|Replaceable
block|{
comment|/** * Ingest pipeline to set on index requests made by this action. */
DECL|field|pipeline
specifier|private
name|String
name|pipeline
decl_stmt|;
DECL|method|UpdateByQueryRequest
specifier|public
name|UpdateByQueryRequest
parameter_list|()
block|{ }
DECL|method|UpdateByQueryRequest
specifier|public
name|UpdateByQueryRequest
parameter_list|(
name|SearchRequest
name|search
parameter_list|)
block|{
name|this
argument_list|(
name|search
argument_list|,
literal|true
argument_list|)
expr_stmt|;
block|}
DECL|method|UpdateByQueryRequest
specifier|private
name|UpdateByQueryRequest
parameter_list|(
name|SearchRequest
name|search
parameter_list|,
name|boolean
name|setDefaults
parameter_list|)
block|{
name|super
argument_list|(
name|search
argument_list|,
name|setDefaults
argument_list|)
expr_stmt|;
block|}
comment|/** * Set the ingest pipeline to set on index requests made by this action. */
DECL|method|setPipeline
specifier|public
name|void
name|setPipeline
parameter_list|(
name|String
name|pipeline
parameter_list|)
block|{
name|this
operator|.
name|pipeline
operator|=
name|pipeline
expr_stmt|;
block|}
comment|/** * Ingest pipeline to set on index requests made by this action. */
DECL|method|getPipeline
specifier|public
name|String
name|getPipeline
parameter_list|()
block|{
return|return
name|pipeline
return|;
block|}
annotation|@
name|Override
DECL|method|self
specifier|protected
name|UpdateByQueryRequest
name|self
parameter_list|()
block|{
return|return
name|this
return|;
block|}
annotation|@
name|Override
DECL|method|forSlice
specifier|public
name|UpdateByQueryRequest
name|forSlice
parameter_list|(
name|TaskId
name|slicingTask
parameter_list|,
name|SearchRequest
name|slice
parameter_list|)
block|{
name|UpdateByQueryRequest
name|request
init|=
name|doForSlice
argument_list|(
operator|new
name|UpdateByQueryRequest
argument_list|(
name|slice
argument_list|,
literal|false
argument_list|)
argument_list|,
name|slicingTask
argument_list|)
decl_stmt|;
name|request
operator|.
name|setPipeline
argument_list|(
name|pipeline
argument_list|)
expr_stmt|;
return|return
name|request
return|;
block|}
annotation|@
name|Override
DECL|method|toString
specifier|public
name|String
name|toString
parameter_list|()
block|{
name|StringBuilder
name|b
init|=
operator|new
name|StringBuilder
argument_list|()
decl_stmt|;
name|b
operator|.
name|append
argument_list|(
literal|"update-by-query "
argument_list|)
expr_stmt|;
name|searchToString
argument_list|(
name|b
argument_list|)
expr_stmt|;
return|return
name|b
operator|.
name|toString
argument_list|()
return|;
block|}
comment|//update by query updates all documents that match a query. The indices and indices options that affect how
comment|//indices are resolved depend entirely on the inner search request. That's why the following methods delegate to it.
annotation|@
name|Override
DECL|method|indices
specifier|public
name|IndicesRequest
name|indices
parameter_list|(
name|String
modifier|...
name|indices
parameter_list|)
block|{
assert|assert
name|getSearchRequest
argument_list|()
operator|!=
literal|null
assert|;
name|getSearchRequest
argument_list|()
operator|.
name|indices
argument_list|(
name|indices
argument_list|)
expr_stmt|;
return|return
name|this
return|;
block|}
annotation|@
name|Override
DECL|method|indices
specifier|public
name|String
index|[]
name|indices
parameter_list|()
block|{
assert|assert
name|getSearchRequest
argument_list|()
operator|!=
literal|null
assert|;
return|return
name|getSearchRequest
argument_list|()
operator|.
name|indices
argument_list|()
return|;
block|}
annotation|@
name|Override
DECL|method|indicesOptions
specifier|public
name|IndicesOptions
name|indicesOptions
parameter_list|()
block|{
assert|assert
name|getSearchRequest
argument_list|()
operator|!=
literal|null
assert|;
return|return
name|getSearchRequest
argument_list|()
operator|.
name|indicesOptions
argument_list|()
return|;
block|}
annotation|@
name|Override
DECL|method|readFrom
specifier|public
name|void
name|readFrom
parameter_list|(
name|StreamInput
name|in
parameter_list|)
throws|throws
name|IOException
block|{
name|super
operator|.
name|readFrom
argument_list|(
name|in
argument_list|)
expr_stmt|;
name|pipeline
operator|=
name|in
operator|.
name|readOptionalString
argument_list|()
expr_stmt|;
block|}
annotation|@
name|Override
DECL|method|writeTo
specifier|public
name|void
name|writeTo
parameter_list|(
name|StreamOutput
name|out
parameter_list|)
throws|throws
name|IOException
block|{
name|super
operator|.
name|writeTo
argument_list|(
name|out
argument_list|)
expr_stmt|;
name|out
operator|.
name|writeOptionalString
argument_list|(
name|pipeline
argument_list|)
expr_stmt|;
block|}
block|}
end_class
end_unit
| Java | CL | fc80e719e117b76369c5c332346966ab8a791922bb6867536d5de161a54dcdf0 |
package org.nuaa.tomax.mailclient.controller;
import org.nuaa.tomax.mailclient.entity.Response;
import org.nuaa.tomax.mailclient.service.IUserService;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpSession;
/**
* @Name: UserController
* @Description: TODO
* @Author: tomax
* @Date: 2019-04-20 16:42
* @Version: 1.0
*/
@RequestMapping("/user")
@RestController
@CrossOrigin
public class UserController {
private final IUserService userService;
public UserController(IUserService userService) {
this.userService = userService;
}
@PostMapping("/login")
public Response login(String username, String password, HttpSession session) {
Response response = userService.signin(username, password);
if (response.getCode() == Response.SUCCESS_CODE) {
session.setAttribute("username", username);
}
return response;
}
@PostMapping("/signup")
public Response signUp(String username, String password) {
return userService.signup(username, password);
}
}
| Java | CL | b362c4257eb5973c7b3e75040c7533ef6fb43682203fd3ef11868ea176688257 |
package club.codedemo.springprofiles;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.core.env.AbstractEnvironment;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
@SpringBootApplication
public class SpringProfilesApplication {
/**
* 在执行SpringApplication.run方法以前,我们是有机会通过变更spring.profiles.active的值来达到变更项目情景的目的
* 本例中展示了两种方法
* 可以任选其一
* <p>
* 注意:单元测试时并不会运行此main方法,所以此方法中对情景的设置并不会在单元测试中生效
* <p>
* 本例中展示的方法直接修改了Spring项目的情景值,并且间接的变更了Environment中的情景值
* <h2>不同点</h2>
* <ol>
* <li>方法一将<b>覆盖</b>原情景模式</li>
* <li>方法二将在原情景模式下进行<b>追加</b></li>
* </ol>
*
* @param args
*/
public static void main(String[] args) {
// 方法一:在run方法执行前,设置spring.profiles.active
System.setProperty(AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME, "dev");
// 方法二:将原SpringApplication.run(SpringProfilesApplication.class, args)拆分
// 在执行run方法前执行setAdditionalProfiles方法,来达到变更项目情景的目的
SpringApplication application = new SpringApplication(SpringProfilesApplication.class);
// application.setAdditionalProfiles("pro");
application.run(args);
}
}
| Java | CL | 69488e05a24b7c1f5ee0b5a47d71c1a715644b7309814e556e32633c9f31497e |
package com.orlando.java.self001.from151to200;
/*
* Read N Characters Given Read4
*
* Given a file and assume that you can only read the file using a given method read4, implement a method to
* read n characters.
*
* The API: int read4(char *buf) reads 4 characters at a time from a file.
*
* The return value is the actual number of characters read. For example, it returns 3 if there is only 3 characters
* left in the file.
*
* By using the read4 API, implement the function int read(char *buf, int n) that reads n characters from the file.
*
* Note: The read function will only be called once for each test case.
*
*/
public class Solution0157 {
public class Solution extends Reader4 {
public int read(char[] buf, int n) {
char[] temp = new char[4];
int total = 0;
while (true) {
int read = Math.min(n - total, read4(temp));
if (read == 0) break;
for (int i = 0; i < read; i++) {
buf[total +i] = temp[i];
}
total += read;
}
return total;
}
}
private class Reader4 {
public int read4(char[] buf4) {
return 1;
}
}
}
| Java | CL | c115ece5ec753830d9d68c6751c86373ac5d35af1beadce70c2fff98af669451 |
/*
* 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.sshd.common.io.nio2;
import java.io.IOException;
import java.net.ConnectException;
import java.net.SocketAddress;
import java.nio.channels.AsynchronousChannelGroup;
import java.nio.channels.AsynchronousSocketChannel;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.apache.sshd.common.AttributeRepository;
import org.apache.sshd.common.PropertyResolver;
import org.apache.sshd.common.future.CancelFuture;
import org.apache.sshd.common.io.DefaultIoConnectFuture;
import org.apache.sshd.common.io.IoConnectFuture;
import org.apache.sshd.common.io.IoConnector;
import org.apache.sshd.common.io.IoHandler;
import org.apache.sshd.common.io.IoServiceEventListener;
import org.apache.sshd.common.io.IoSession;
import org.apache.sshd.common.util.ExceptionUtils;
import org.apache.sshd.common.util.ValidateUtils;
import org.apache.sshd.core.CoreModuleProperties;
/**
* TODO Add javadoc
*
* @author <a href="mailto:dev@mina.apache.org">Apache MINA SSHD Project</a>
*/
public class Nio2Connector extends Nio2Service implements IoConnector {
public Nio2Connector(PropertyResolver propertyResolver, IoHandler handler, AsynchronousChannelGroup group,
ExecutorService resumeTasks) {
super(propertyResolver, handler, group, resumeTasks);
}
@Override
public IoConnectFuture connect(
SocketAddress address, AttributeRepository context, SocketAddress localAddress) {
boolean debugEnabled = log.isDebugEnabled();
if (debugEnabled) {
log.debug("Connecting to {}", address);
}
IoConnectFuture future = new DefaultIoConnectFuture(address, null);
AsynchronousSocketChannel channel = null;
AsynchronousSocketChannel socket = null;
try {
AsynchronousChannelGroup group = getChannelGroup();
channel = openAsynchronousSocketChannel(address, group);
socket = setSocketOptions(channel);
if (localAddress != null) {
socket.bind(localAddress);
}
Nio2CompletionHandler<Void, Object> completionHandler = ValidateUtils.checkNotNull(
createConnectionCompletionHandler(
future, socket, context, propertyResolver, getIoHandler()),
"No connection completion handler created for %s",
address);
// With a completion handler there is no way to cancel an ongoing connection attempt. We could only let
// the attempt proceed to failure or success, and if successful, close the established channel again. With a
// future, we can cancel the future to abort the connection attempt, but we need to use our own thread pool
// for waiting on the future and invoking the completion handler.
Future<Void> cf = socket.connect(address);
Long connectTimeout = CoreModuleProperties.IO_CONNECT_TIMEOUT.get(propertyResolver).map(d -> {
if (d.isZero() || d.isNegative()) {
return null;
}
long millis;
try {
millis = d.toMillis();
} catch (ArithmeticException e) {
millis = Long.MAX_VALUE;
}
return Long.valueOf(millis);
}).orElse(null);
Future<?> rf = getExecutorService().submit(() -> {
try {
if (connectTimeout != null) {
log.debug("connect({}): waiting for connection (timeout={}ms)", address, connectTimeout);
cf.get(connectTimeout.longValue(), TimeUnit.MILLISECONDS);
} else {
log.debug("connect({}): waiting for connection", address);
cf.get();
}
completionHandler.onCompleted(null, null);
} catch (CancellationException e) {
CancelFuture cancellation = future.cancel();
if (cancellation != null) {
cancellation.setCanceled(e);
}
} catch (TimeoutException e) {
cf.cancel(true);
ConnectException c = new ConnectException("I/O connection time-out of " + connectTimeout + "ms expired");
c.initCause(e);
completionHandler.onFailed(c, null);
} catch (ExecutionException e) {
completionHandler.onFailed(e, null);
} catch (InterruptedException e) {
completionHandler.onFailed(e, null);
Thread.currentThread().interrupt();
}
});
future.addListener(f -> {
if (f.isCanceled()) {
// Don't interrupt if already running; if inside completionHandler.onCompleted() it might cause
// general confusion.
rf.cancel(false);
cf.cancel(true);
}
});
} catch (Throwable exc) {
Throwable t = ExceptionUtils.peelException(exc);
debug("connect({}) failed ({}) to schedule connection: {}",
address, t.getClass().getSimpleName(), t.getMessage(), t);
try {
if (socket != null) {
socket.close();
}
} catch (IOException err) {
if (debugEnabled) {
log.debug("connect({}) - failed ({}) to close socket: {}",
address, err.getClass().getSimpleName(), err.getMessage());
}
}
try {
if (channel != null) {
channel.close();
}
} catch (IOException err) {
if (debugEnabled) {
log.debug("connect({}) - failed ({}) to close channel: {}",
address, err.getClass().getSimpleName(), err.getMessage());
}
}
future.setException(t);
}
return future;
}
protected AsynchronousSocketChannel openAsynchronousSocketChannel(
SocketAddress address, AsynchronousChannelGroup group)
throws IOException {
return AsynchronousSocketChannel.open(group);
}
protected Nio2CompletionHandler<Void, Object> createConnectionCompletionHandler(
IoConnectFuture future, AsynchronousSocketChannel socket,
AttributeRepository context, PropertyResolver propertyResolver, IoHandler handler) {
return new ConnectionCompletionHandler(future, socket, context, propertyResolver, handler);
}
protected class ConnectionCompletionHandler extends Nio2CompletionHandler<Void, Object> {
protected final IoConnectFuture future;
protected final AsynchronousSocketChannel socket;
protected final AttributeRepository context;
protected final PropertyResolver propertyResolver;
protected final IoHandler handler;
protected ConnectionCompletionHandler(IoConnectFuture future, AsynchronousSocketChannel socket,
AttributeRepository context, PropertyResolver propertyResolver,
IoHandler handler) {
this.future = future;
this.socket = socket;
this.context = context;
this.propertyResolver = propertyResolver;
this.handler = handler;
}
@Override
@SuppressWarnings("synthetic-access")
protected void onCompleted(Void result, Object attachment) {
Long sessionId = null;
IoServiceEventListener listener = getIoServiceEventListener();
try {
if (listener != null) {
SocketAddress local = socket.getLocalAddress();
SocketAddress remote = socket.getRemoteAddress();
listener.connectionEstablished(Nio2Connector.this, local, context, remote);
}
Nio2Session session = createSession(propertyResolver, handler, socket);
if (context != null) {
session.setAttribute(AttributeRepository.class, context);
}
handler.sessionCreated(session);
sessionId = session.getId();
sessions.put(sessionId, session);
future.setSession(session);
if (session != future.getSession()) {
session.close(true);
throw new CancellationException();
} else if (session.isClosing()) {
try {
handler.sessionClosed(session);
} finally {
unmapSession(sessionId);
}
} else {
session.startReading();
}
} catch (CancellationException e) {
throw e;
} catch (Throwable exc) {
Throwable t = ExceptionUtils.peelException(exc);
boolean debugEnabled = log.isDebugEnabled();
if (listener != null) {
try {
SocketAddress localAddress = socket.getLocalAddress();
SocketAddress remoteAddress = socket.getRemoteAddress();
listener.abortEstablishedConnection(
Nio2Connector.this, localAddress, context, remoteAddress, t);
} catch (Exception e) {
if (debugEnabled) {
log.debug("onCompleted() listener=" + listener + " ignoring abort event exception", e);
}
}
}
log.debug("onCompleted - failed to start session: {} {}", t.getClass().getSimpleName(), t.getMessage(), t);
IoSession session = future.getSession();
if (session != null) {
try {
session.close(true);
} finally {
future.setException(t);
}
} else {
try {
socket.close();
} catch (IOException err) {
if (debugEnabled) {
log.debug("onCompleted - failed to close socket: {} {}", err.getClass().getSimpleName(),
err.getMessage());
}
}
future.setException(t);
unmapSession(sessionId);
}
}
}
@Override
protected void onFailed(Throwable exc, Object attachment) {
future.setException(exc);
}
}
protected Nio2Session createSession(
PropertyResolver propertyResolver, IoHandler handler, AsynchronousSocketChannel socket)
throws Throwable {
return new Nio2Session(this, propertyResolver, handler, socket, null);
}
}
| Java | CL | 72afc0dbfc0135ece5aa06e340bcba9a564ef5e05adf73c2b36d1a7d090689c4 |
package com.breakfast.main;
/*
* This renders the splash screen.
*
* @author Cameron Teed
* @version 1.0
* @since 2021-05-26
*/
import java.awt.Graphics;
/** */
public class SplashScreen {
/** Initializes width. */
private final int width = 740;
/** Initializes height. */
private final int height = 550;
/** Initializes width the background. */
private Backgrounds background = new Backgrounds();
/**
* Renders the splash screen.
*
* @param g
*/
public void render(final Graphics g) {
background.loadBackground3(g);
}
/**
* Clears the splash screen and sets the game state to the menu.
*
* @param g
*/
public void clearSplash(final Graphics g) {
g.clearRect(0, 0, width, height);
Main.setState(Main.STATE.MENU);
}
}
| Java | CL | 32251232c68617df1fae19cb24381a89a697088f034834833caf633b3d90a2b2 |
package p005cm.aptoide.p006pt.dataprovider.p010ws.p076v1;
import android.content.SharedPreferences;
import com.mopub.common.Constants;
import okhttp3.OkHttpClient;
import p005cm.aptoide.p006pt.dataprovider.BuildConfig;
import p005cm.aptoide.p006pt.dataprovider.WebService;
import p005cm.aptoide.p006pt.preferences.toolbox.ToolboxManager;
import retrofit2.Converter.Factory;
/* renamed from: cm.aptoide.pt.dataprovider.ws.v1.PnpV1WebService */
public abstract class PnpV1WebService<U> extends WebService<Service, U> {
protected PnpV1WebService(OkHttpClient httpClient, Factory converterFactory, SharedPreferences sharedPreferences) {
super(Service.class, httpClient, converterFactory, getHost(sharedPreferences));
}
public static String getHost(SharedPreferences sharedPreferences) {
StringBuilder sb = new StringBuilder();
sb.append(ToolboxManager.isToolboxEnableHttpScheme(sharedPreferences) ? Constants.HTTP : "https");
sb.append("://");
sb.append(BuildConfig.APTOIDE_WEB_SERVICES_NOTIFICATION_HOST);
sb.append("/pnp/v1/");
return sb.toString();
}
}
| Java | CL | 85158e7619880ebc103cfd8e40c2a5a98b2dd6a943c9198ece8c16458e44b803 |
package fr.lteconsulting.hexa.databinding.gwt;
import com.google.gwt.user.client.ui.HasValue;
import com.google.gwt.user.client.ui.ListBox;
import fr.lteconsulting.hexa.databinding.Converter;
import fr.lteconsulting.hexa.databinding.Mode;
import fr.lteconsulting.hexa.databinding.propertyadapters.PropertyAdapter;
import fr.lteconsulting.hexa.databinding.gwt.propertyadapters.ListBoxPropertyAdapter;
import fr.lteconsulting.hexa.databinding.gwt.propertyadapters.ValuePropertyAdapter;
/**
* Second part of the fluent API for Data Binding. When a binding is
* prepared by calling a method on the Binder class, an instance of
* this class is returned to finish the binding creation process.
*
* @author Arnaud Tournier
* (c) LTE Consulting - 2015
* http://www.lteconsulting.fr
*
*/
public class BindingCreation extends fr.lteconsulting.hexa.databinding.BindingCreation
{
protected boolean deferActivate;
public BindingCreation( PropertyAdapter source )
{
super(source);
}
/**
* Final step, defines the data binding destination and activates the
* binding.
*
* The object used as the binding's destination is a HasValue widget, like a
* TextBox. The binding system will the use setValue, getValue and
* addValueChangeHandler methods to set, get and get change notifications on
* the @param widget parameter.
*
* @param hasValue
* The {@link HasValue} object
* @return The DataBinding object
*/
public DataBinding to( HasValue<?> hasValue )
{
return to(new ValuePropertyAdapter(hasValue));
}
/**
* Final step, defines the data binding destination and activates the
* binding.
*
* The object used as the binding's destination is a ListBox widget.
* The binding system will the use setValue, getValue and addChangeHandler
* methods to set, get and get change notifications on the @param widget parameter.
*
* @param listBox
* The widget
* @return The DataBinding object
*/
public DataBinding to( ListBox listBox )
{
return to(new ListBoxPropertyAdapter(listBox));
}
@Override
public BindingCreation log(String prefix) {
super.log(prefix);
return this;
}
/**
* Second step, parameters.
*
* The created data binding will be activated at the next event loop. The
* Scheduler.get().scheduleDeferred() method will be used.
*
* @return The Binder to continue specifying the data binding
*/
public BindingCreation deferActivate()
{
deferActivate = true;
return this;
}
@Override
public BindingCreation mode(Mode mode) {
super.mode(mode);
return this;
}
@Override
public BindingCreation withConverter(Converter converter) {
super.withConverter(converter);
return this;
}
@Override
public DataBinding to( PropertyAdapter destination )
{
// create the binding according to the parameters
DataBinding binding = new DataBinding( source, destination, mode, converter, logPrefix );
// activate the binding : launch a value event
if(deferActivate)
binding.deferActivate();
else
binding.activate();
return binding;
}
}
| Java | CL | ebd7701929c2daae95715843327929e5ade0d876adb26f9e4af43b0e2594f054 |
package com.yicj.study.plugins;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.SystemMetaObject;
import java.sql.Connection;
@Slf4j
@Intercepts({
@Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class, Integer.class})
})
public class MyStatementHandlerPlugin implements Interceptor {
// 拦截目标对象的目标方法的执行,将自定义逻辑写在该方法中
@Override
public Object intercept(Invocation invocation) throws Throwable {
log.info("MyStatementHandlerPlugin ... intercept : " + invocation.getMethod());
MetaObject metaObject = SystemMetaObject.forObject(invocation);
log.info("当前拦截到的方法: {}", metaObject.getValue("target"));
log.info("SQL语句: {}", metaObject.getValue("target.delegate.boundSql.sql"));
log.info("SQL语句入参: {}", metaObject.getValue("target.delegate.parameterHandler.parameterObject"));
log.info("SQL语句类型:{}", metaObject.getValue("target.delegate.parameterHandler.mappedStatement.sqlCommandType"));
log.info("Mapper方法全路劲名: {}", metaObject.getValue("target.delegate.parameterHandler.mappedStatement.id"));
// 修改sql语句
String newSql = metaObject.getValue("target.delegate.boundSql.sql").toString() ; //这里可以修改sql
metaObject.setValue("target.delegate.boundSql.sql", newSql);
return invocation.proceed();
}
}
| Java | CL | 40abcb7a6a5dab18eec66f2a65e2240ee45700a3b7d6793d79b9c095c833cabe |
/*******************************************************************************
* Copyright 2010 Simon Mieth
*
* 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.kabeja.dxf.parser.entities;
import org.kabeja.dxf.parser.DXFValue;
import org.kabeja.entities.Entity;
import org.kabeja.entities.Text;
import org.kabeja.util.Constants;
/**
* @author <a href="mailto:simon.mieth@gmx.de">Simon Mieth</a>
*
*/
public class DXFTextHandler extends AbstractEntityHandler {
public static final int TEXT_VALUE = 1;
public static final int TEXT_HEIGHT = 40;
public static final int TEXT_SCALE_X = 41;
public static final int TEXT_GENERATION_FLAG = 71;
public static final int TEXT_ALIGN = 72;
public static final int TEXT_VALIGN = 73;
public static final int TEXT_ALIGN_X = 11;
public static final int TEXT_ALIGN_Y = 21;
public static final int TEXT_ALIGN_Z = 31;
public static final int TEXT_STYLE = 7;
public static final int TEXT_OBLIQUEANGLE = 51;
public static final int TEXT_ROTATION = 50;
protected Text text;
protected String content;
/**
*
*/
public DXFTextHandler() {
super();
}
/*
* (non-Javadoc)
*
* @see org.dxf2svg.parser.entities.EntityHandler#endParsing()
*/
public void endDXFEntity() {
text.setText(this.content);
this.content = "";
}
/*
* (non-Javadoc)
*
* @see org.dxf2svg.parser.entities.EntityHandler#getEntity()
*/
public Entity getDXFEntity() {
return text;
}
/*
* (non-Javadoc)
*
* @see org.dxf2svg.parser.entities.EntityHandler#getEntityName()
*/
public String getDXFEntityType() {
return Constants.ENTITY_TYPE_TEXT;
}
/*
* (non-Javadoc)
*
* @see org.dxf2svg.parser.entities.EntityHandler#isFollowSequence()
*/
public boolean isFollowSequence() {
// TODO Auto-generated method stub
return false;
}
/*
* (non-Javadoc)
*
* @see org.dxf2svg.parser.entities.EntityHandler#parseGroup(int,
* org.dxf2svg.parser.DXFValue)
*/
public void parseGroup(int groupCode, DXFValue value) {
switch (groupCode) {
case TEXT_VALUE:
//we set the content after the
//parsing is finished, so the
//DXFParser will get all infos
this.content = value.getValue();
break;
case TEXT_ALIGN:
text.setAlign(value.getIntegerValue());
break;
case TEXT_VALIGN:
text.setValign(value.getIntegerValue());
break;
case GROUPCODE_START_X:
text.getInsertPoint().setX(value.getDoubleValue());
break;
case GROUPCODE_START_Y:
text.getInsertPoint().setY(value.getDoubleValue());
break;
case GROUPCODE_START_Z:
text.getInsertPoint().setZ(value.getDoubleValue());
break;
case TEXT_ALIGN_X:
text.getAlignmentPoint().setX(value.getDoubleValue());
text.setAlignmentPoint(true);
break;
case TEXT_ALIGN_Y:
text.getAlignmentPoint().setY(value.getDoubleValue());
break;
case TEXT_ALIGN_Z:
text.getAlignmentPoint().setZ(value.getDoubleValue());
break;
case TEXT_HEIGHT:
text.setHeight(value.getDoubleValue());
break;
case TEXT_GENERATION_FLAG:
text.setTextGenerationFlag(value.getIntegerValue());
break;
case TEXT_STYLE:
text.setTextStyle(value.getValue());
break;
case TEXT_ROTATION:
text.setRotation(value.getDoubleValue());
break;
case TEXT_SCALE_X:
text.setScaleX(value.getDoubleValue());
break;
case TEXT_OBLIQUEANGLE:
text.setObliqueAngle(value.getDoubleValue());
break;
default:
super.parseCommonProperty(groupCode, value, text);
break;
}
}
/*
* (non-Javadoc)
*
* @see org.dxf2svg.parser.entities.EntityHandler#startParsing()
*/
public void startDXFEntity() {
text = new Text();
text.setDocument(this.doc);
}
}
| Java | CL | a9fe3c5ca22aba419c57c5784806241dcbab95d7f7296d4d9f59bd53189b2ed6 |
package org.gorilla.hokieplanner.guerilla;
// -------------------------------------------------------------------------
/**
* A class to represent the cle's. It extends RequiredItem so it can be added to
* the tree
*
* @author Anirudh Bagde (anibagde)
* @author Weyland Chiang (chiangw)
* @author Sayan Ekambarapu (sayan96)
* @version Dec 1, 2014
*/
public class Cle
extends RequiredItem
{
private int area;
private int total;
// ----------------------------------------------------------
/**
* Create a new Cle object.
* @param area the area number of the cle
* @param total the total number of credits required from that cle area
*/
public Cle(int area, int total)
{
this.area = area;
this.total = total;
}
// ----------------------------------------------------------
/**
* Returns the area number of the cle
* @return the area number of the cle
*/
public int getArea()
{
return area;
}
// ----------------------------------------------------------
/**
* sets the area of the cle to the specified number
* @param area this becomes the area of the cle
*/
public void setArea(int area)
{
this.area = area;
}
// ----------------------------------------------------------
/**
* returns the total number of credits required from the cle
* @return the total number of credits required from the cle
*/
public int getTotal()
{
return total;
}
// ----------------------------------------------------------
/**
* sets the total number of credits
* @param total sets the number of credits required to the specified number
*/
public void setTotal(int total)
{
this.total = total;
}
}
| Java | CL | 15c16592cbd7c42dd673c39ddd44727278121fa579d4e137c7558e471eb6ddaa |
package sg.bigo.common.customcapture;
import android.app.Activity;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.ImageFormat;
import android.graphics.SurfaceTexture;
import android.hardware.Camera;
import android.opengl.GLES11Ext;
import android.opengl.GLES20;
import android.opengl.GLSurfaceView;
import android.opengl.GLUtils;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.SystemClock;
import android.util.Log;
import android.view.TextureView;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.CountDownLatch;
import sg.bigo.common.LiveApplication;
import sg.bigo.common.customcapture.ve_gl.EglBase;
import sg.bigo.common.customcapture.ve_gl.GlRectDrawer;
public class CameraController implements SurfaceTexture.OnFrameAvailableListener{
private final String TAG = "CameraController";
private int mDisplayOrientation;//旋转角度
private int mRotation;
private CameraPosion mPosion;//前置摄像头和后置摄像头
private int mPreViewWidth;//预览宽度
private int mPreViewHeight;//预览高度
private int mPreViewFps;//帧率
private Camera.Size mPreviewSize;
private Camera mCamera;
private Camera.CameraInfo mCameraInfo;
private GLSurfaceView mGlsurfaceView;
private SurfaceTexture mSurfaceTexture;
private int mSurfaceTextureId;
private boolean updateSurface;
private final float[] mTexMtx = GlUtil.createIdentityMtx();
private RenderScreen mRenderScreen = null;
//frameBufferId
private RgbaRenderFilter mRenderFilter = null;
private int mFrameBufferId = 0;
private int mPreviewTextureId = 0;
private EglBase previewEglBase;
private static CameraController instance;
private Bitmap mBitmap;
private TextureView mTextureView;
private HandlerThread mThread;
private Handler mHandler;
public enum CameraPosion {
FRONT,
BACK
}
private CameraController() {
mDisplayOrientation = 0;
mRotation = 0;
mPosion = CameraPosion.FRONT;
mPreViewWidth = 720;
mPreViewHeight = 1280;
mPreViewFps = 30;
mThread = new HandlerThread("CameraController" + hashCode());
mThread.start();
mHandler = new Handler(mThread.getLooper());
}
public static synchronized CameraController getInstance() {
if (instance == null) {
instance = new CameraController();
}
return instance;
}
private int openCommonCamera() {
int cameraId = mPosion == CameraPosion.FRONT ? Camera.CameraInfo.CAMERA_FACING_FRONT : Camera.CameraInfo.CAMERA_FACING_BACK;
int numberOfCameras = Camera.getNumberOfCameras();
mCameraInfo = new Camera.CameraInfo();
for (int i = 0; i < numberOfCameras; i++) {
Camera.getCameraInfo(i, mCameraInfo);
if (mCameraInfo.facing == cameraId) {
mCamera = Camera.open(i);
}
}
return cameraId;
}
private Activity mActivity;
public boolean openCamera(Activity activity, GLSurfaceView glSurfaceView, TextureView aux_view) {
mActivity = activity;
mBitmap = createBitmapFromAsset();
boolean b = true;
mGlsurfaceView = glSurfaceView;
mTextureView = aux_view;
mTextureView.setSurfaceTextureListener(new TextureView.SurfaceTextureListener() {
@Override
public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
Log.e(TAG, "onSurfaceTextureAvailable: " + Thread.currentThread().getName() + "" + Thread.currentThread().getId());
}
@Override
public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {
Log.e(TAG, "onSurfaceTextureSizeChanged: " + Thread.currentThread().getName() + "" + Thread.currentThread().getId());
}
@Override
public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
Log.e(TAG, "onSurfaceTextureDestroyed: " + Thread.currentThread().getName() + "" + Thread.currentThread().getId());
closeCamera();
return false;
}
@Override
public void onSurfaceTextureUpdated(SurfaceTexture surface) {
Log.e(TAG, "onSurfaceTextureUpdated: ===== " + Thread.currentThread().getName() + "" + Thread.currentThread().getId());
}
});
initSurfaceTexture();
return b;
}
public void closeCamera() {
try {
if (mRenderFilter != null) {
mRenderFilter.destroy();
mRenderFilter = null;
}
if (mCamera != null) {
mCamera.stopPreview();
mCamera.release();
mCamera = null;
}
} catch (Exception e) {
Log.e(TAG, "closeCamera: " + e);
} finally {
final CountDownLatch barrier = new CountDownLatch(1);
mHandler.post(() -> {
previewEglBase.makeCurrent();
if(mFrameBufferId != 0) {
int[] fbos = new int[] { mFrameBufferId };
GLES20.glDeleteFramebuffers(1,fbos,0);
mFrameBufferId = 0;
}
if(mPreviewTextureId != 0) {
int[] textureIds = new int[] { mPreviewTextureId };
GLES20.glDeleteTextures(1,textureIds, 0);
mPreviewTextureId = 0;
}
if(mSurfaceTextureId != 0) {
int[] textureIds = new int[] { mSurfaceTextureId };
GLES20.glDeleteTextures(1,textureIds, 0);
mSurfaceTextureId = 0;
}
mRenderScreen = null;
previewEglBase.detachCurrent();
if(previewEglBase != null) {
previewEglBase.release();
previewEglBase = null;
}
barrier.countDown();
});
try {
barrier.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public Camera.Size getmPreviewSize() {
return mPreviewSize;
}
private Bitmap createBitmapFromAsset() {
Bitmap bitmap = null;
try {
AssetManager assetManager = LiveApplication.Companion.getAppContext().getAssets();
InputStream is = assetManager.open("output.png");
bitmap = BitmapFactory.decodeStream(is);
if (bitmap != null) {
System.out.println("测试一:width=" + bitmap.getWidth() + " ,height=" + bitmap.getHeight());
} else {
System.out.println("bitmap == null");
}
} catch (Exception e) {
System.out.println("异常信息:" + e.toString());
}
return bitmap;
}
float[] transformationMatrix = new float[]{1.0f, 0.0f, 0.0f, 0.0f,
0.0f, 1.0f, 0.0f, 0.0f,
0.0f, 0.0f, 1.0f, 0.0f,
0.0f, 0.0f, 0.0f, 1.0f};
/**
* 是否横屏
*
* @return
*/
public boolean isLandscape() {
return false;
}
private void setPameras(int cameraId) {
mDisplayOrientation = cameraId == Camera.CameraInfo.CAMERA_FACING_FRONT ? (mCameraInfo.orientation + mRotation) % 360
: (mCameraInfo.orientation - mRotation + 360) % 360;
boolean portrait = false;
boolean upsideDown = false;
if (mDisplayOrientation == 0) {
portrait = true;
upsideDown = false;
} else if (mDisplayOrientation == 90) {
portrait = false;
upsideDown = false;
} else if (mDisplayOrientation == 180) {
portrait = true;
upsideDown = true;
} else if (mDisplayOrientation == 270) {
portrait = false;
upsideDown = true;
}
Camera.Size preViewSize = CameraUtils.getOptimalPreviewSize(mCamera, mPreViewWidth, mPreViewHeight, portrait);
Log.i(TAG, "setPameras: preViewSize width " + preViewSize.width + " height " + preViewSize.height + " ,mDisplayOrientation " + mDisplayOrientation);
Camera.Parameters parameters = mCamera.getParameters();
//parameters.setRotation(mRotation);
parameters.setPreviewFormat(ImageFormat.NV21);
parameters.set("orientation", "portrait");
parameters.setPreviewSize(preViewSize.width, preViewSize.height);
if (upsideDown) {
mCamera.setDisplayOrientation(180);
}
int[] range = CameraUtils.adaptPreviewFps(mPreViewFps, parameters.getSupportedPreviewFpsRange());
parameters.setPreviewFpsRange(range[0], range[1]);
mCamera.setParameters(parameters);
mPreviewSize = preViewSize;
}
private GlRectDrawer previewDrawer;
private void initSurfaceTexture() {
final CountDownLatch barrier = new CountDownLatch(1);
mHandler.post(() -> {
previewEglBase = EglBase.create(null, EglBase.CONFIG_RGBA);
if (!mTextureView.isAvailable()) {
return;
}
try {
// 创建用于预览的EGLSurface
previewEglBase.createSurface(mTextureView.getSurfaceTexture());
} catch (RuntimeException e) {
previewEglBase.releaseSurface();
}
previewDrawer = new GlRectDrawer();
barrier.countDown();
});
try {
barrier.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
mHandler.post(() -> {
previewEglBase.makeCurrent();
int[] textures = new int[1];
GLES20.glGenTextures(1, textures, 0);
//摄像头纹理
mSurfaceTextureId = textures[0];
mSurfaceTexture = new SurfaceTexture(mSurfaceTextureId);
mSurfaceTexture.setOnFrameAvailableListener(CameraController.this);
GLES20.glDisable(GLES20.GL_DEPTH_TEST);
GLES20.glDisable(GLES20.GL_CULL_FACE);
GLES20.glDisable(GLES20.GL_BLEND);
GLES20.glActiveTexture(GLES20.GL_TEXTURE0);
GLES20.glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, mSurfaceTextureId);
GLES20.glTexParameterf(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_LINEAR);
GLES20.glTexParameterf(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR);
GLES20.glTexParameteri(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_WRAP_S, GLES20.GL_CLAMP_TO_EDGE);
GLES20.glTexParameteri(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_WRAP_T, GLES20.GL_CLAMP_TO_EDGE);
stopCamera();
startCamera();
previewEglBase.detachCurrent();
});
}
public void startCamera() {
int cameraId = openCommonCamera();
try {
mCamera.setPreviewTexture(mSurfaceTexture);
} catch (IOException e) {
e.printStackTrace();
}
setPameras(cameraId);
Log.i(TAG, "onSurfaceChanged");
try {
} catch (Exception e) {
Log.e(TAG, "onSurfaceChanged: " + e);
}
mCamera.startPreview();
}
public void stopCamera() {
if (mCamera != null) {
mCamera.stopPreview();
mCamera.release();
mCamera = null;
}
}
private int mBitmapTextureId = 0;
@Override
public void onFrameAvailable(SurfaceTexture surfaceTexture) {
Log.i(TAG, "onFrameAvailable");
synchronized (this) {
updateSurface = true;
}
mHandler.post(() -> {
if (previewEglBase == null) return;
previewEglBase.makeCurrent();
synchronized (CameraController.this) {
if (updateSurface) {
//把数据给了mSurfaceTextureId
mSurfaceTexture.updateTexImage();
mSurfaceTexture.getTransformMatrix(mTexMtx);
updateSurface = false;
}
}
if (mRenderScreen == null) {
mRenderScreen = new RenderScreen(mSurfaceTextureId, true);
mRenderScreen.setSreenSize(mPreViewWidth, mPreViewHeight);
}
if (mPreviewTextureId == 0) {
GLES20.glActiveTexture(GLES20.GL_TEXTURE1);
mPreviewTextureId = GlUtil.generateTexture(GLES20.GL_TEXTURE_2D);
GLES20.glTexImage2D(GLES20.GL_TEXTURE_2D, 0, GLES20.GL_RGBA, mPreViewWidth, mPreViewHeight, 0, GLES20.GL_RGBA, GLES20.GL_UNSIGNED_BYTE, null);
mFrameBufferId = GlUtil.generateFrameBuffer(mPreviewTextureId);
} else {
GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, mFrameBufferId);
}
GlUtil.rotateTextureMatrix(mTexMtx, mDisplayOrientation);
mRenderScreen.draw(mTexMtx);
GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, 0);
LiveApplication.Companion.avEngine().sendCustomVideoCaptureTextureData(mPreviewTextureId, mPreViewWidth, mPreViewHeight,
LiveApplication.Companion.getNeedCustomUpsideDown(), LiveApplication.Companion.getNeedCustomMirror(), SystemClock.elapsedRealtime());
// sendStaticImage();
previewEglBase.detachCurrent();
});
}
private void sendStaticImage() {
if (mBitmapTextureId == 0) {
GLES20.glActiveTexture(GLES20.GL_TEXTURE2);
mBitmapTextureId = GlUtil.generateTexture(GLES20.GL_TEXTURE_2D);
GLUtils.texImage2D(GLES20.GL_TEXTURE_2D, 0, mBitmap, 0);
}
if (mPreviewTextureId == 0) {
GLES20.glActiveTexture(GLES20.GL_TEXTURE1);
mPreviewTextureId = GlUtil.generateTexture(GLES20.GL_TEXTURE_2D);
GLES20.glTexImage2D(GLES20.GL_TEXTURE_2D, 0, GLES20.GL_RGBA, mPreviewSize.width, mPreviewSize.height, 0, GLES20.GL_RGBA, GLES20.GL_UNSIGNED_BYTE, null);
mFrameBufferId = GlUtil.generateFrameBuffer(mPreviewTextureId);
} else {
// 绑定帧缓冲区fbo
// Bind frame buffer
GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, mFrameBufferId);
}
if (previewDrawer == null) {
previewDrawer = new GlRectDrawer();
}
GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT);
previewDrawer.drawRgb(mBitmapTextureId, transformationMatrix,
720, 1280,
0, 0,
720, 1280);
LiveApplication.Companion.avEngine().sendCustomVideoCaptureTextureData(mPreviewTextureId, 720, 1280, 0, true, SystemClock.elapsedRealtime());
}
}
| Java | CL | f79a7cd6504ac7c5e4cd5110c8ed5773bffd92c62ecc092930a590fcdec48126 |
package com.ufgov.zc.client.console.elementrule.accounter;
import com.ufgov.zc.client.common.LangTransMeta;
import com.ufgov.zc.client.console.elementrule.base.BaseElementInfoSetPanel;
import com.ufgov.zc.client.console.elementrule.base.BaseElementSelectPanel;
import com.ufgov.zc.client.console.elementrule.event.ElementRelationEvent;
import com.ufgov.zc.common.commonbiz.model.MaElementRelationRuleDetail;
public class AccounterRuleInfoPanel extends BaseElementInfoSetPanel {
public AccounterRuleInfoPanel() {
super(MaElementRelationRuleDetail.DIRECTION_SRC);
}
public void addedSrcElementRelation(ElementRelationEvent event) {
// TCJLODO Auto-generated method stub
MaElementRelationRuleDetail relation = (MaElementRelationRuleDetail) event.getSource();
BaseElementSelectPanel panel = generateRulePanel(relation);
tabbedPane.add(LangTransMeta.translate(relation.getElement()), panel);
}
public void removedSrcElementRelation(ElementRelationEvent event) {
// TCJLODO Auto-generated method stub
MaElementRelationRuleDetail relation = (MaElementRelationRuleDetail) event.getSource();
BaseElementSelectPanel panel = (BaseElementSelectPanel) elementPanel.get(relation.getElement());
panel.clear();
tabbedPane.remove(panel);
}
}
| Java | CL | d41214452ba6b3d00860af8f3cade3c7a39247f126f989bbd07b97cdb9d322bb |
/**
* File : Database.java
* Desc : Database Connection controller.
* @author Sebastián Turén Croquevielle(seba@turensoft.com)
*/
package com.blizzardPanel.dbConnect;
import com.blizzardPanel.DataException;
import java.sql.Connection;
import java.sql.SQLException;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
public class Database {
public static final String DB_CONTROLLER_NAME = "jdbc/db";
private DataSource dataSource;
public Database(String jndiname) {
try {
dataSource = (DataSource) new InitialContext().lookup("java:comp/env/" + jndiname);
} catch (NamingException e) {
// Handle error that it's not configured in JNDI.
throw new IllegalStateException(jndiname + " is missing in JNDI!", e);
}
}
public Connection getConnection() throws DataException {
try {
return dataSource.getConnection();
} catch (SQLException ex) {
throw new DataException("DB can't connect");
}
}
}
| Java | CL | 537d046d14a7d61340ce3a00b1f7bd2e99fc755d0ab05b7659a1e57c823824b1 |
package org.loosefx.eventbus;
/**
The status of an event as it makes its way from publication through processing by subscribers.
<p/>
EventServices are required to stamp any event object or payload that implements the EventStatusTracker with the
corresponding EventStatus as the event object is processed. The EventService is not required to set the
Unpublished state.
*/
public enum PublicationStatus {
/** Recommended default. */
Unpublished,
/** Set directly after publication on an EventService. */
Initiated,
/** End status for events that are vetoed and never sent to subscribers. */
Vetoed,
/** State set after veto test is passed before the event is send to any subscribers. */
Queued,
/**
Set while the event is sent to it's subscribers. EventService implementations such as the
ThreadSafeEventService and the SwingEventService will transition from Queued to Publishing immediately. Others
implementations that call subscribers on threads different from veto subscribers are free to leave an event in
the Queued state and wait until the event is passed to the thread(s) that subscribers are called on to set the
Publishing state
*/
Publishing,
/**
Called when all subscribers have finished handling the event publication.
*/
Completed
}
| Java | CL | 50b3538f20a40bfd1f23270f3b4cd85d5589c9bc47edc85a37b03c3466a6afb5 |
/******************************************************
* Copyright 2011-2012 by Ustok.org.
* All rights reserved.
******************************************************/
package org.ustok.swtbot.internal.spy;
/**
* Constants to use for this plugin.
*
* @author Ingo Mohr
* @created Dec 23, 2012
*/
public final class SwtBotSpyPlatformConstants {
/** Key for SWTBot widget ids */
public static final String WIDGET_ID_KEY = "org.eclipse.swtbot.widget.key";
private SwtBotSpyPlatformConstants() {
}
}
| Java | CL | df8b9094f8f85d39cc22bd2a4cb22f660cdb1e4d6a9a887f6e68899581b08c25 |
package com.amazon.emr.logs;
import com.amazon.emr.logs.objectmappers.CloudWatchLogEntry;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.mapred.FileSplit;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import static org.apache.hadoop.mapred.Reporter.NULL;
import static org.junit.Assert.assertEquals;
public class TestLogsRecordReader {
public static final Log LOG = LogFactory.getLog(TestLogsRecordReader.class);
private static Path workDir = new Path(new Path(System.getProperty(
"test.build.data", "target"), "data"), "TestTextInputFormat");
private static Path inputDir = new Path(workDir, "input");
public ArrayList<String> readRecords(URL testFileUrl, int splitSize, Boolean forceGzip)
throws IOException
{
// Set up context
File testFile = new File(testFileUrl.getFile());
long testFileSize = testFile.length();
Path testFilePath = new Path(testFile.getAbsolutePath());
Configuration conf = new Configuration();
conf.setInt("io.file.buffer.size", 1);
conf.set("io.compression.codecs", "org.apache.hadoop.io.compress.SplittableGzipCodec,org.apache.hadoop.io.compress.GzipCodec");
if (forceGzip)
{
conf.set("codec.force", "splittablegzip");
}
ArrayList<String> records = new ArrayList<String>();
long offset = 0;
LongWritable key = new LongWritable();
CloudWatchLogEntry value = new CloudWatchLogEntry();
while (offset < testFileSize) {
FileSplit split = new FileSplit(testFilePath, offset, splitSize, (String[]) null);
LogsRecordReader reader = new LogsRecordReader(split, conf, NULL);
while (reader.next(key, value)) {
records.add(value.toString());
}
offset += splitSize;
}
return records;
}
private void checkSampleRecord(String testFile, int eventCount, Boolean forceGzip)
throws IOException
{
URL testFileUrl = getClass().getClassLoader().getResource(testFile);
ArrayList<String> records = readRecords(testFileUrl, 64 * 1024, forceGzip);
assertEquals("Wrong number of records", eventCount, records.size());
for (String record: records) {
LOG.info(record);
}
}
@Test
public void testLoadingSampleRecords()
throws IOException
{
checkSampleRecord("CloudWatchLogsRecord.json", 2, false);
}
@Test
public void testLoadingCompressedRecords()
throws IOException
{
checkSampleRecord("CloudWatchLogsRecord.json.gz", 2, false);
}
@Test
public void testLoadingMultipleCompressedRecords()
throws IOException
{
checkSampleRecord("CloudWatchLogsRecordsMultiGzip", 4, true);
}
}
| Java | CL | 69a4f06e72fe86108b409004ba0b5979458b5ea8e6dd50ab3aae30d2c72131bf |
/*
* Copyright © 2015 Cask Data, 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.cdap.cdap.cli.command.app;
import com.google.inject.Inject;
import io.cdap.cdap.cli.ArgumentName;
import io.cdap.cdap.cli.CLIConfig;
import io.cdap.cdap.client.ApplicationClient;
import io.cdap.cdap.client.ProgramClient;
import io.cdap.cdap.proto.BatchProgram;
import io.cdap.cdap.proto.BatchProgramStart;
import io.cdap.cdap.proto.ProgramRecord;
import io.cdap.cdap.proto.id.NamespaceId;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.List;
/**
* Restarts one or more programs in an application.
*/
public class RestartProgramsCommand extends BaseBatchCommand<BatchProgram> {
private final ProgramClient programClient;
@Inject
public RestartProgramsCommand(ApplicationClient appClient, ProgramClient programClient,
CLIConfig cliConfig) {
super(appClient, cliConfig);
this.programClient = programClient;
}
@Override
protected BatchProgram createProgram(ProgramRecord programRecord) {
return new BatchProgram(programRecord.getApp(), programRecord.getType(),
programRecord.getName());
}
@Override
protected void runBatchCommand(PrintStream printStream, Args<BatchProgram> args)
throws Exception {
NamespaceId namespace = args.appId.getParent();
printStream.print("Stopping programs...\n");
programClient.stop(namespace, args.programs);
printStream.print("Starting programs...\n");
List<BatchProgramStart> startList = new ArrayList<>(args.programs.size());
for (BatchProgram program : args.programs) {
startList.add(new BatchProgramStart(program));
}
programClient.start(namespace, startList);
}
@Override
public String getPattern() {
return String.format("restart app <%s> programs [of type <%s>]", ArgumentName.APP,
ArgumentName.PROGRAM_TYPES);
}
@Override
public String getDescription() {
return getDescription("restart", "restarts");
}
}
| Java | CL | a2b0f83d37822bc1e10c95923511ccb404849593fe55881253fda7a515a68448 |
/*-
*******************************************************************************
* Copyright (c) 2011, 2014 Diamond Light Source Ltd.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Peter Chang - initial API and implementation and/or initial documentation
*******************************************************************************/
package uk.ac.diamond.json.roimixins;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
public abstract class LinearROIMixIn {
@JsonIgnore abstract void setPointKeepEndPoint(int[] pt);
@JsonIgnore abstract void setPointKeepEndPoint(double[] pt);
@JsonIgnore abstract double[] getEndPoint();
@JsonIgnore abstract int[] getIntEndPoint();
@JsonIgnore abstract void setEndPoint(double eptx, double epty);
@JsonIgnore abstract void setEndPoint(double[] ept);
@JsonIgnore abstract void setEndPoint(int[] ept);
@JsonIgnore abstract double[] getMidPoint();
@JsonIgnore abstract void setMidPoint(double[] mpt);
@JsonProperty abstract void setLength(double len);
@JsonProperty abstract double getLength();
@JsonIgnore abstract void setCrossHair(boolean crossHair);
@JsonIgnore abstract boolean isCrossHair();
}
| Java | CL | 3f164076603cb9d64e5d0c1585e289268b1b69ce717b3d8ece7061ffd3ad5829 |
// Copyright (c) YugaByte, Inc.
package com.yugabyte.yw.controllers;
import static com.yugabyte.yw.common.AssertHelper.assertAuditEntry;
import static com.yugabyte.yw.common.AssertHelper.assertBadRequest;
import static com.yugabyte.yw.common.AssertHelper.assertErrorNodeValue;
import static com.yugabyte.yw.common.AssertHelper.assertErrorResponse;
import static com.yugabyte.yw.common.AssertHelper.assertInternalServerError;
import static com.yugabyte.yw.common.AssertHelper.assertOk;
import static com.yugabyte.yw.common.AssertHelper.assertPlatformException;
import static com.yugabyte.yw.common.AssertHelper.assertValue;
import static com.yugabyte.yw.common.TestHelper.createTempFile;
import static org.hamcrest.CoreMatchers.allOf;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static play.mvc.Http.Status.BAD_REQUEST;
import static play.mvc.Http.Status.OK;
import static play.test.Helpers.INTERNAL_SERVER_ERROR;
import static play.test.Helpers.contentAsString;
import akka.stream.javadsl.FileIO;
import akka.stream.javadsl.Source;
import akka.util.ByteString;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.google.common.collect.ImmutableList;
import com.yugabyte.yw.commissioner.Common;
import com.yugabyte.yw.common.AccessManager;
import com.yugabyte.yw.common.FakeDBApplication;
import com.yugabyte.yw.common.ModelFactory;
import com.yugabyte.yw.common.PlatformServiceException;
import com.yugabyte.yw.models.AccessKey;
import com.yugabyte.yw.models.AccessKey.KeyInfo;
import com.yugabyte.yw.models.Customer;
import com.yugabyte.yw.models.Provider;
import com.yugabyte.yw.models.Region;
import com.yugabyte.yw.models.Users;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
import lombok.extern.slf4j.Slf4j;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import play.libs.Json;
import play.mvc.Http;
import play.mvc.Result;
@Slf4j
public class AccessKeyControllerTest extends FakeDBApplication {
Provider defaultProvider;
Customer defaultCustomer;
Users defaultUser;
Region defaultRegion;
static final Integer SSH_PORT = 12345;
static final String DEFAULT_SUDO_SSH_USER = "ssh-user";
@Before
public void before() {
defaultCustomer = ModelFactory.testCustomer();
defaultUser = ModelFactory.testUser(defaultCustomer);
defaultProvider = ModelFactory.onpremProvider(defaultCustomer);
defaultRegion = Region.create(defaultProvider, "us-west-2", "us-west-2", "yb-image");
when(mockFileHelperService.createTempFile(anyString(), anyString()))
.thenAnswer(
i -> {
String fileName = i.getArgument(0);
String fileExtension = i.getArgument(1);
return Files.createTempFile(Paths.get("/tmp"), fileName, fileExtension);
});
}
private Result getAccessKey(UUID providerUUID, String keyCode) {
String uri =
"/api/customers/"
+ defaultCustomer.getUuid()
+ "/providers/"
+ providerUUID
+ "/access_keys/"
+ keyCode;
return doRequestWithAuthToken("GET", uri, defaultUser.createAuthToken());
}
private Result listAccessKey(UUID providerUUID) {
String uri =
"/api/customers/"
+ defaultCustomer.getUuid()
+ "/providers/"
+ providerUUID
+ "/access_keys";
return doRequestWithAuthToken("GET", uri, defaultUser.createAuthToken());
}
private Result listAccessKeyForAllProviders() {
String uri = "/api/customers/" + defaultCustomer.getUuid() + "/access_keys";
return doRequestWithAuthToken("GET", uri, defaultUser.createAuthToken());
}
private Result createAccessKey(
UUID providerUUID, String keyCode, boolean uploadFile, boolean useRawString) {
return createAccessKey(
providerUUID,
keyCode,
uploadFile,
useRawString,
defaultRegion,
true,
true,
false,
false,
Collections.emptyList());
}
private Result createAccessKey(
UUID providerUUID,
String keyCode,
boolean uploadFile,
boolean useRawString,
Region region,
boolean airGapInstall,
boolean passwordlessSudoAccess,
boolean skipProvisioning,
boolean setUpChrony,
List<String> ntpServers) {
return createAccessKey(
providerUUID,
keyCode,
uploadFile,
useRawString,
region,
airGapInstall,
passwordlessSudoAccess,
skipProvisioning,
setUpChrony,
ntpServers,
true,
null);
}
private Result createAccessKey(
UUID providerUUID,
String keyCode,
boolean uploadFile,
boolean useRawString,
Region region,
boolean airGapInstall,
boolean passwordlessSudoAccess,
boolean skipProvisioning,
boolean setUpChrony,
List<String> ntpServers,
boolean showSetUpChrony,
Integer expirationThresholdDays) {
String uri =
"/api/customers/"
+ defaultCustomer.getUuid()
+ "/providers/"
+ providerUUID
+ "/access_keys";
if (uploadFile) {
List<Http.MultipartFormData.Part<Source<ByteString, ?>>> bodyData = new ArrayList<>();
if (keyCode != null) {
bodyData.add(new Http.MultipartFormData.DataPart("keyCode", keyCode));
bodyData.add(
new Http.MultipartFormData.DataPart("regionUUID", region.getUuid().toString()));
bodyData.add(new Http.MultipartFormData.DataPart("keyType", "PRIVATE"));
bodyData.add(new Http.MultipartFormData.DataPart("sshUser", "ssh-user"));
bodyData.add(new Http.MultipartFormData.DataPart("sshPort", SSH_PORT.toString()));
bodyData.add(new Http.MultipartFormData.DataPart("airGapInstall", "false"));
String tmpFile = createTempFile("PRIVATE KEY DATA");
Source<ByteString, ?> keyFile = FileIO.fromFile(new File(tmpFile));
bodyData.add(
new Http.MultipartFormData.FilePart<>(
"keyFile", "test.pem", "application/octet-stream", keyFile));
}
return doRequestWithAuthTokenAndMultipartData(
"POST", uri, defaultUser.createAuthToken(), bodyData, mat);
} else {
ObjectNode bodyJson = Json.newObject();
if (keyCode != null) {
bodyJson.put("keyCode", keyCode);
bodyJson.put("regionUUID", region.getUuid().toString());
}
if (useRawString) {
bodyJson.put("keyType", AccessManager.KeyType.PRIVATE.toString());
bodyJson.put("keyContent", "PRIVATE KEY DATA");
}
bodyJson.put("airGapInstall", airGapInstall);
bodyJson.put("sshUser", DEFAULT_SUDO_SSH_USER);
bodyJson.put("sshPort", SSH_PORT);
bodyJson.put("passwordlessSudoAccess", passwordlessSudoAccess);
bodyJson.put("skipProvisioning", skipProvisioning);
bodyJson.put("setUpChrony", setUpChrony);
bodyJson.put("showSetUpChrony", showSetUpChrony);
bodyJson.put("expirationThresholdDays", expirationThresholdDays);
if (ntpServers != null) {
ArrayNode arrayNode = Json.newArray();
for (String server : ntpServers) {
arrayNode.add(server);
}
bodyJson.putArray("ntpServers").addAll(arrayNode);
}
return doRequestWithAuthTokenAndBody("POST", uri, defaultUser.createAuthToken(), bodyJson);
}
}
private Result deleteAccessKey(UUID providerUUID, String keyCode) {
String uri =
"/api/customers/"
+ defaultCustomer.getUuid()
+ "/providers/"
+ providerUUID
+ "/access_keys/"
+ keyCode;
return doRequestWithAuthToken("DELETE", uri, defaultUser.createAuthToken());
}
@Test
public void testGetAccessKeyWithInvalidProviderUUID() {
UUID invalidProviderUUID = UUID.randomUUID();
Result result = assertPlatformException(() -> getAccessKey(invalidProviderUUID, "foo"));
assertBadRequest(result, "Invalid Provider UUID: " + invalidProviderUUID);
assertAuditEntry(0, defaultCustomer.getUuid());
}
@Test
public void testGetAccessKeyWithInvalidKeyCode() {
Result result = assertPlatformException(() -> getAccessKey(defaultProvider.getUuid(), "foo"));
assertEquals(BAD_REQUEST, result.status());
assertBadRequest(result, "KeyCode not found: foo");
assertAuditEntry(0, defaultCustomer.getUuid());
}
@Test
public void testGetAccessKeyWithValidKeyCode() {
AccessKey accessKey =
AccessKey.create(defaultProvider.getUuid(), "foo", new AccessKey.KeyInfo());
Result result = getAccessKey(defaultProvider.getUuid(), accessKey.getKeyCode());
JsonNode json = Json.parse(contentAsString(result));
assertOk(result);
JsonNode idKey = json.get("idKey");
assertValue(idKey, "keyCode", accessKey.getKeyCode());
assertValue(idKey, "providerUUID", accessKey.getProviderUUID().toString());
assertAuditEntry(0, defaultCustomer.getUuid());
}
@Test
public void testListAccessKeyWithInvalidProviderUUID() {
UUID invalidProviderUUID = UUID.randomUUID();
Result result = assertPlatformException(() -> listAccessKey(invalidProviderUUID));
assertBadRequest(result, "Invalid Provider UUID: " + invalidProviderUUID);
assertAuditEntry(0, defaultCustomer.getUuid());
}
@Test
public void testListAccessKeyWithEmptyData() {
Result result = listAccessKey(defaultProvider.getUuid());
JsonNode json = Json.parse(contentAsString(result));
assertOk(result);
assertEquals(json.size(), 0);
assertAuditEntry(0, defaultCustomer.getUuid());
}
@Test
public void testListAccessKeyWithValidData() {
AccessKey.create(defaultProvider.getUuid(), "key-1", new AccessKey.KeyInfo());
AccessKey.create(defaultProvider.getUuid(), "key-2", new AccessKey.KeyInfo());
Result result = listAccessKey(defaultProvider.getUuid());
JsonNode json = Json.parse(contentAsString(result));
assertOk(result);
assertEquals(json.size(), 2);
json.forEach(
(key) -> {
assertThat(
key.get("idKey").get("keyCode").asText(),
allOf(notNullValue(), containsString("key-")));
assertThat(
key.get("idKey").get("providerUUID").asText(),
allOf(notNullValue(), equalTo(defaultProvider.getUuid().toString())));
});
assertAuditEntry(0, defaultCustomer.getUuid());
}
@Test
public void testListForAllProvidersAccessKeyWithEmptyData() {
Result result = listAccessKeyForAllProviders();
JsonNode json = Json.parse(contentAsString(result));
assertOk(result);
assertEquals(json.size(), 0);
assertAuditEntry(0, defaultCustomer.getUuid());
}
@Test
public void testListForAllProvidersAccessKeyWithValidData() {
Provider newProvider = ModelFactory.gcpProvider(defaultCustomer);
AccessKey.create(defaultProvider.getUuid(), "key-1", new AccessKey.KeyInfo());
AccessKey.create(defaultProvider.getUuid(), "key-2", new AccessKey.KeyInfo());
AccessKey.create(newProvider.getUuid(), "key-3", new AccessKey.KeyInfo());
Result result = listAccessKeyForAllProviders();
JsonNode json = Json.parse(contentAsString(result));
assertOk(result);
assertEquals(json.size(), 3);
assertAuditEntry(0, defaultCustomer.getUuid());
}
@Test
public void testCreateAccessKeyWithInvalidProviderUUID() {
Result result =
assertPlatformException(() -> createAccessKey(UUID.randomUUID(), "foo", false, false));
assertBadRequest(result, "provider");
assertAuditEntry(0, defaultCustomer.getUuid());
}
@Test
public void testCreateAccessKeyWithInvalidParams() {
Result result =
assertPlatformException(
() -> createAccessKey(defaultProvider.getUuid(), null, false, false));
JsonNode node = Json.parse(contentAsString(result));
assertErrorNodeValue(node, "keyCode", "This field is required");
assertAuditEntry(0, defaultCustomer.getUuid());
}
@Test
public void testCreateAccessKeyWithZewroRegionProvider() {
Provider differentProvider =
ModelFactory.onpremProvider(ModelFactory.testCustomer("fb", "foo@bar.com"));
Result result =
assertPlatformException(
() -> createAccessKey(differentProvider.getUuid(), "key-code", false, false));
assertInternalServerError(result, "No regions.");
assertAuditEntry(0, defaultCustomer.getUuid());
}
@Test
public void testCreateAccessKeyInDifferentRegion() {
when(mockAccessManager.addKey(
defaultRegion.getUuid(),
"key-code",
null,
DEFAULT_SUDO_SSH_USER,
SSH_PORT,
true,
false,
false,
Collections.emptyList(),
true))
.thenAnswer(
invocation ->
AccessKey.create(defaultProvider.getUuid(), "key-code", new AccessKey.KeyInfo()));
Result result = createAccessKey(defaultProvider.getUuid(), "key-code", false, false);
JsonNode json = Json.parse(contentAsString(result));
assertOk(result);
assertAuditEntry(1, defaultCustomer.getUuid());
assertValue(json.get("idKey"), "keyCode", "key-code");
assertValue(json.get("idKey"), "providerUUID", defaultProvider.getUuid().toString());
}
@Test
public void testCreateAccessKeyWithoutKeyFile() {
when(mockAccessManager.addKey(
defaultRegion.getUuid(),
"key-code-1",
null,
DEFAULT_SUDO_SSH_USER,
SSH_PORT,
true,
false,
false,
Collections.emptyList(),
true))
.thenAnswer(i -> AccessKey.create(defaultProvider.getUuid(), "key-code-1", new KeyInfo()));
Result result = createAccessKey(defaultProvider.getUuid(), "key-code-1", false, false);
JsonNode json = Json.parse(contentAsString(result));
assertOk(result);
assertAuditEntry(1, defaultCustomer.getUuid());
assertValue(json.get("idKey"), "keyCode", "key-code-1");
assertValue(json.get("idKey"), "providerUUID", defaultProvider.getUuid().toString());
}
@Test
public void testCreateAccessKeyWithKeyFile() throws IOException {
AccessKey.KeyInfo keyInfo = new AccessKey.KeyInfo();
keyInfo.publicKey = "/path/to/public.key";
keyInfo.privateKey = "/path/to/private.key";
ArgumentCaptor<Path> updatedFile = ArgumentCaptor.forClass(Path.class);
when(mockAccessManager.uploadKeyFile(
eq(defaultRegion.getUuid()),
any(Path.class),
eq("key-code-1"),
eq(AccessManager.KeyType.PRIVATE),
eq("ssh-user"),
eq(SSH_PORT),
eq(false),
eq(false),
eq(false),
eq(Collections.emptyList()),
eq(true),
eq(true),
eq(false)))
.thenAnswer(i -> AccessKey.create(defaultProvider.getUuid(), "key-code-1", keyInfo));
Result result = createAccessKey(defaultProvider.getUuid(), "key-code-1", true, false);
verify(mockAccessManager, times(1))
.uploadKeyFile(
eq(defaultRegion.getUuid()),
updatedFile.capture(),
eq("key-code-1"),
eq(AccessManager.KeyType.PRIVATE),
eq("ssh-user"),
eq(SSH_PORT),
eq(false),
eq(false),
eq(false),
eq(Collections.emptyList()),
eq(true),
eq(true),
eq(false));
JsonNode json = Json.parse(contentAsString(result));
assertOk(result);
assertAuditEntry(1, defaultCustomer.getUuid());
assertNotNull(json);
try {
List<String> lines = Files.readAllLines(updatedFile.getValue());
assertEquals(1, lines.size());
assertThat(lines.get(0), allOf(notNullValue(), equalTo("PRIVATE KEY DATA")));
} catch (IOException e) {
assertNull(e.getMessage());
}
}
@Test
public void testCreateAccessKeyWithKeyString() throws IOException {
AccessKey.KeyInfo keyInfo = new AccessKey.KeyInfo();
keyInfo.publicKey = "/path/to/public.key";
keyInfo.privateKey = "/path/to/private.key";
ArgumentCaptor<Path> updatedFile = ArgumentCaptor.forClass(Path.class);
when(mockAccessManager.uploadKeyFile(
eq(defaultRegion.getUuid()),
any(Path.class),
eq("key-code-1"),
eq(AccessManager.KeyType.PRIVATE),
eq(DEFAULT_SUDO_SSH_USER),
eq(SSH_PORT),
eq(true),
eq(false),
eq(false),
eq(Collections.emptyList()),
eq(true),
eq(true),
eq(false)))
.thenAnswer(i -> AccessKey.create(defaultProvider.getUuid(), "key-code-1", keyInfo));
Result result = createAccessKey(defaultProvider.getUuid(), "key-code-1", false, true);
verify(mockAccessManager, times(1))
.uploadKeyFile(
eq(defaultRegion.getUuid()),
updatedFile.capture(),
eq("key-code-1"),
eq(AccessManager.KeyType.PRIVATE),
eq(DEFAULT_SUDO_SSH_USER),
eq(SSH_PORT),
eq(true),
eq(false),
eq(false),
eq(Collections.emptyList()),
eq(true),
eq(true),
eq(false));
JsonNode json = Json.parse(contentAsString(result));
assertOk(result);
assertAuditEntry(1, defaultCustomer.getUuid());
assertNotNull(json);
try {
List<String> lines = Files.readAllLines(updatedFile.getValue());
assertEquals(1, lines.size());
assertThat(lines.get(0), allOf(notNullValue(), equalTo("PRIVATE KEY DATA")));
} catch (IOException e) {
assertNull(e.getMessage());
}
}
@Test
@Ignore
public void testCreateAccessKeyWithException() {
when(mockAccessManager.addKey(
defaultRegion.getUuid(),
"key-code-1",
null,
DEFAULT_SUDO_SSH_USER,
SSH_PORT,
true,
false,
false,
Collections.emptyList(),
true))
.thenThrow(new PlatformServiceException(INTERNAL_SERVER_ERROR, "Something went wrong!!"));
Result result =
assertPlatformException(
() -> createAccessKey(defaultProvider.getUuid(), "key-code-1", false, false));
assertErrorResponse(result, "Something went wrong!!");
assertAuditEntry(0, defaultCustomer.getUuid());
}
@Test
public void testCreateAccessKeyWithoutPasswordlessSudoAccessSuccess() {
Provider onpremProvider = ModelFactory.newProvider(defaultCustomer, Common.CloudType.onprem);
Region onpremRegion = Region.create(onpremProvider, "onprem-a", "onprem-a", "yb-image");
when(mockAccessManager.addKey(
onpremRegion.getUuid(),
"key-code-1",
null,
DEFAULT_SUDO_SSH_USER,
SSH_PORT,
true,
false,
false,
Collections.emptyList(),
true))
.thenAnswer(
i -> AccessKey.create(onpremProvider.getUuid(), "key-code-1", new AccessKey.KeyInfo()));
Result result =
createAccessKey(
onpremProvider.getUuid(),
"key-code-1",
false,
false,
onpremRegion,
true,
false,
false,
false,
Collections.emptyList());
assertOk(result);
assertAuditEntry(1, defaultCustomer.getUuid());
verify(mockTemplateManager, times(1))
.createProvisionTemplate(
AccessKey.getLatestKey(onpremProvider.getUuid()),
true,
false,
true,
9300,
"prometheus",
false,
Collections.emptyList());
}
@Test
public void testCreateAccessKeyWithoutPasswordlessSudoAccessError() {
when(mockAccessManager.addKey(
defaultRegion.getUuid(),
"key-code-1",
null,
DEFAULT_SUDO_SSH_USER,
SSH_PORT,
false,
false,
false,
Collections.emptyList(),
true))
.thenAnswer(
i ->
AccessKey.create(defaultProvider.getUuid(), "key-code-1", new AccessKey.KeyInfo()));
doThrow(
new PlatformServiceException(
INTERNAL_SERVER_ERROR, "Unable to create access key: key-code-1"))
.when(mockTemplateManager)
.createProvisionTemplate(
any(AccessKey.class),
eq(false),
eq(false),
eq(true),
eq(9300),
eq("prometheus"),
eq(false),
eq(Collections.emptyList()));
Result result =
assertPlatformException(
() ->
createAccessKey(
defaultProvider.getUuid(),
"key-code-1",
false,
false,
defaultRegion,
false,
false,
false,
false,
Collections.emptyList()));
assertErrorResponse(result, "Unable to create access key: key-code-1");
assertAuditEntry(0, defaultCustomer.getUuid());
}
@Test
public void testCreateAccessKeySkipProvisioning() {
Provider onpremProvider = ModelFactory.newProvider(defaultCustomer, Common.CloudType.onprem);
Region onpremRegion = Region.create(onpremProvider, "onprem-a", "onprem-a", "yb-image");
when(mockAccessManager.addKey(
onpremRegion.getUuid(),
"key-code-1",
null,
DEFAULT_SUDO_SSH_USER,
SSH_PORT,
true,
true,
false,
Collections.emptyList(),
true))
.thenAnswer(
invocation ->
AccessKey.create(onpremProvider.getUuid(), "key-code-1", new AccessKey.KeyInfo()));
Result result =
createAccessKey(
onpremProvider.getUuid(),
"key-code-1",
false,
false,
onpremRegion,
true,
false,
true,
false,
Collections.emptyList());
assertOk(result);
assertAuditEntry(1, defaultCustomer.getUuid());
verify(mockTemplateManager, times(1))
.createProvisionTemplate(
AccessKey.getLatestKey(onpremProvider.getUuid()),
true,
false,
true,
9300,
"prometheus",
false,
Collections.emptyList());
}
@Test
public void testCreateAccessKeySetUpNTP() {
List<String> serverList = new ArrayList<>();
serverList.add("0.yb.pool.ntp.org");
serverList.add("1.yb.pool.ntp.org");
when(mockAccessManager.addKey(
defaultRegion.getUuid(),
"key-code-1",
null,
DEFAULT_SUDO_SSH_USER,
SSH_PORT,
false,
false,
true,
serverList,
true))
.thenAnswer(
i ->
AccessKey.create(defaultProvider.getUuid(), "key-code-1", new AccessKey.KeyInfo()));
Result result =
createAccessKey(
defaultProvider.getUuid(),
"key-code-1",
false,
false,
defaultRegion,
false,
false,
false,
true,
serverList);
assertOk(result);
assertAuditEntry(1, defaultCustomer.getUuid());
}
@Test
public void testCreateAccessKeySetUpNTPWithList() {
List<String> serverList = new ArrayList<>();
serverList.add("0.yb.pool.ntp.org");
serverList.add("1.yb.pool.ntp.org");
when(mockAccessManager.addKey(
defaultRegion.getUuid(),
"key-code-1",
null,
DEFAULT_SUDO_SSH_USER,
SSH_PORT,
false,
false,
true,
serverList,
true))
.thenAnswer(
i ->
AccessKey.create(defaultProvider.getUuid(), "key-code-1", new AccessKey.KeyInfo()));
Result result =
createAccessKey(
defaultProvider.getUuid(),
"key-code-1",
false,
false,
defaultRegion,
false,
false,
false,
true,
serverList);
assertOk(result);
assertAuditEntry(1, defaultCustomer.getUuid());
}
@Test
public void testCreateAccessKeySetUpNTPWithoutListOnPrem() {
Result result =
assertPlatformException(
() ->
createAccessKey(
defaultProvider.getUuid(),
"key-code-1",
false,
false,
defaultRegion,
false,
false,
false,
true,
Collections.emptyList()));
assertBadRequest(result, "NTP servers not provided");
assertAuditEntry(0, defaultCustomer.getUuid());
}
@Test
public void testCreateAccessKeyWithShowSetUpChronyFalse() {
List<String> ntpServerList = ImmutableList.of("0.yb.pool.ntp.org", "1.yb.pool.ntp.org");
when(mockAccessManager.addKey(
defaultRegion.getUuid(),
"key-code-1",
null,
DEFAULT_SUDO_SSH_USER,
SSH_PORT,
false,
false,
true,
ntpServerList,
false))
.then(
invocation ->
AccessKey.create(defaultProvider.getUuid(), "key-code-1", new AccessKey.KeyInfo()));
Result result =
createAccessKey(
defaultProvider.getUuid(),
"key-code-1",
false,
false,
defaultRegion,
false,
false,
false,
true,
ntpServerList,
false,
null);
assertOk(result);
assertAuditEntry(1, defaultCustomer.getUuid());
}
@Test
public void testCreateAccessKeyWithExpirationThresholdDays() {
Integer expirationThresholdDays = 365;
final String keyCode = "key-code-1";
when(mockAccessManager.addKey(
defaultRegion.getUuid(),
keyCode,
null,
DEFAULT_SUDO_SSH_USER,
SSH_PORT,
false,
false,
false,
Collections.emptyList(),
false))
.thenAnswer(i -> AccessKey.create(defaultProvider.getUuid(), keyCode, new KeyInfo()));
Result result =
createAccessKey(
defaultProvider.getUuid(),
keyCode,
false,
false,
defaultRegion,
false,
false,
false,
false,
Collections.emptyList(),
false,
expirationThresholdDays);
assertOk(result);
JsonNode json = Json.parse(contentAsString(result));
AccessKey createdAccessKey = Json.fromJson(json, AccessKey.class);
assertEquals(
AccessKey.getLatestKey(defaultProvider.getUuid()).getExpirationDate().toString(),
createdAccessKey.getExpirationDate().toString());
assertAuditEntry(1, defaultCustomer.getUuid());
}
@Test
public void testDeleteAccessKeyWithInvalidProviderUUID() {
UUID invalidProviderUUID = UUID.randomUUID();
Result result = assertPlatformException(() -> deleteAccessKey(invalidProviderUUID, "foo"));
assertBadRequest(result, "Invalid Provider UUID: " + invalidProviderUUID);
assertAuditEntry(0, defaultCustomer.getUuid());
}
@Test
public void testDeleteAccessKeyWithInvalidAccessKeyCode() {
Result result =
assertPlatformException(() -> deleteAccessKey(defaultProvider.getUuid(), "foo"));
assertBadRequest(result, "KeyCode not found: foo");
assertAuditEntry(0, defaultCustomer.getUuid());
}
@Test
public void testDeleteAccessKeyWithValidAccessKeyCode() {
AccessKey.create(defaultProvider.getUuid(), "key-code-1", new AccessKey.KeyInfo());
Result result = deleteAccessKey(defaultProvider.getUuid(), "key-code-1");
assertEquals(OK, result.status());
assertAuditEntry(1, defaultCustomer.getUuid());
assertThat(
contentAsString(result),
allOf(notNullValue(), containsString("Deleted KeyCode: key-code-1")));
}
}
| Java | CL | 4e7b8dd9e816349d2816358021bb6e1cb458a1adc915850b2647914ed71d0b22 |
package ar.com.kfgodel.asql.impl.vendors;
import ar.com.kfgodel.asql.api.interpreter.VendorInterpreter;
import ar.com.kfgodel.asql.api.vendors.Vendor;
import ar.com.kfgodel.asql.impl.interpreter.TemplateInterpreter;
import ar.com.kfgodel.nary.api.Nary;
/**
* This type implements the vendor behavior by using classpath located templates,
* and a priority base template lookup to convert agnostic queries to vendor queries
* Created by kfgodel on 13/07/15.
*/
public class ClasspathTemplatingVendor implements Vendor {
private String[] priorityOrderedTemplateLocations;
public Nary<String> getTemplateLocationInClasspath() {
return Nary.create(priorityOrderedTemplateLocations);
}
public static ClasspathTemplatingVendor create(String... priorityOrderedTemplateLocations) {
ClasspathTemplatingVendor vendor = new ClasspathTemplatingVendor();
vendor.priorityOrderedTemplateLocations = priorityOrderedTemplateLocations;
return vendor;
}
@Override
public VendorInterpreter getInterpreter() {
Nary<String> templateLocationInClasspath = this.getTemplateLocationInClasspath();
return TemplateInterpreter.create(templateLocationInClasspath);
}
}
| Java | CL | 85d0c0812ea7dbe8bfc86fe30386741fdd46fb31f56bc5ff546ff0623d2690bb |
package by.epam.gym.command.joint;
import by.epam.gym.command.Command;
import by.epam.gym.exception.ServiceException;
import by.epam.gym.model.Page;
import by.epam.gym.model.user.User;
import by.epam.gym.model.user.UserRole;
import by.epam.gym.service.ComplexService;
import org.apache.log4j.Logger;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
/**
* Command to clear all complexes at concrete training program by client and trainer.
*
* @author Dzmitry Turko
* @see ComplexService
*/
public class ClearComplexesCommand implements Command {
private static final Logger LOGGER = Logger.getLogger(ClearComplexesCommand.class);
private static final String MY_PROGRAM_COMMAND = "/controller?command=client_myProgram&userId=";
private static final String EDIT_CLIENT_INFO_COMMAND = "/controller?command=trainer_editClientInfo&clientId=";
private static final String USER_ATTRIBUTE = "user";
private static final String USER_ID_ATTRIBUTE = "userId";
private static final String CLIENT_ID_ATTRIBUTE = "clientId";
private static final String PROGRAM_ID_ATTRIBUTE = "programId";
private static final String DELETE_COMPLEXES_FAILED_MESSAGE = "&saveMessage=An error while deleting complexes.";
private static final String DELETE_COMPLEXES_SUCCESS_MESSAGE = "&saveMessage=All complexes were deleted.";
/**
* Implementation of command to remove all complexes from concrete training program.
*
* @param request HttpServletRequest object.
* @return Page with next command.
* @throws ServiceException object if execution of method is failed.
*/
@Override
public Page execute(HttpServletRequest request) throws ServiceException {
String userIdValue = getId(request);
String nextCommand = getNextCommand(request);
String programIdValue = request.getParameter(PROGRAM_ID_ATTRIBUTE);
int programId = Integer.parseInt(programIdValue);
ComplexService complexService = new ComplexService();
boolean isComplexesRemoved = complexService.removeAllComplexes(programId);
if (!isComplexesRemoved) {
String url = nextCommand + userIdValue + DELETE_COMPLEXES_FAILED_MESSAGE;
LOGGER.debug("UserID:" + userIdValue + " cannot delete complexes. Some problems from complex service.");
return new Page(url, true);
}
String url = nextCommand + userIdValue + DELETE_COMPLEXES_SUCCESS_MESSAGE;
return new Page(url, true);
}
/**
* The method finds current user's role and returns correct next command to execute.
*
* @param request HttpServletRequest object.
* @return String next command to execute.
*/
private String getNextCommand(HttpServletRequest request) {
HttpSession session = request.getSession();
User user = (User) session.getAttribute(USER_ATTRIBUTE);
UserRole userRole;
if (user != null) {
userRole = user.getUserRole();
} else {
throw new UnsupportedOperationException("Unsupported operation from quest.");
}
if (userRole == UserRole.CLIENT) {
return MY_PROGRAM_COMMAND;
}
return EDIT_CLIENT_INFO_COMMAND;
}
/**
* The method finds which attribute was transferred to request and returns it's value.
*
* @param request HttpServletRequest object.
* @return String the ID attribute.
*/
private String getId(HttpServletRequest request) {
String clientId = request.getParameter(CLIENT_ID_ATTRIBUTE);
String userId = request.getParameter(USER_ID_ATTRIBUTE);
if (clientId != null) {
return clientId;
} else if (userId != null) {
return userId;
} else {
throw new IllegalArgumentException("There are no any user id argument to prepare complex.");
}
}
}
| Java | CL | ab807b3093cc1e63aec134e7e742ab70d04054511ad4268fdc897e4d8a8ce75d |
package com.btc.ep.plugins.embeddedplatform;
import java.io.IOException;
import org.jenkinsci.plugins.scriptsecurity.sandbox.whitelists.ProxyWhitelist;
import org.jenkinsci.plugins.scriptsecurity.sandbox.whitelists.StaticWhitelist;
import com.btc.ep.plugins.pipelinedsl.PipelineDSLGlobal;
import hudson.Extension;
@Extension
public class EmbeddedPlatformDSL extends PipelineDSLGlobal {
@Override
public String getFunctionName() {
return "btc";
}
@Extension
public static class MiscWhitelist extends ProxyWhitelist {
public MiscWhitelist() throws IOException {
super(new StaticWhitelist(
"method java.util.Map$Entry getKey",
"method java.util.Map$Entry getValue"));
}
}
}
| Java | CL | d0ead4e72a2ab7e958f31ff7f237945ca4ef2579b659e4d829d98ce857164c56 |
package com.gosun.isap.warn.api.alert.rest;
import com.gosun.isap.dao.po.alert.Alert;
import com.gosun.isap.warn.api.alert.model.ResponseData;
import com.gosun.isap.warn.api.alert.model.statistics.AverageItem;
import com.gosun.isap.warn.api.alert.model.statistics.StatisticsDiagramData;
import com.gosun.isap.warn.api.alert.model.statistics.StatisticsNode;
import java.util.List;
import java.util.Map;
/**
* <p>创建时间:2017-6-8 16:47</p>
*
* @author 娄存银
* @version 1.0
*/
public interface GuardGroupRestService extends RestConst{
/**
* @param groupId 保安 id
* @param strDate 时间
* @param startTime 开始时间
* @param endTime 截止时间
* @param start 分页
* @param limit 分页
* @param userId 用户 id
* @return Alerts
*/
ResponseData<List<Alert>> alerts(Long groupId, String strDate, String startTime, String endTime, Integer start, Integer limit, Long userId);
/**
* @param groupId 保安 id
* @param strDate 时间
* @param startTime 开始时间
* @param endTime 截止时间
* @param start 分页
* @param limit 分页
* @param userId 用户 id
* @return Alerts
*/
ResponseData<List<Map<String,Object>>> unfinished(Long groupId, String strDate, String startTime, String endTime, Integer start, Integer limit, Long userId);
/**
* @param groupId 保安 id
* @param strDate 时间
* @param startTime 开始时间
* @param endTime 截止时间
* @param start 分页
* @param limit 分页
* @param userId 用户 id
* @return Alerts
*/
ResponseData<List<Map<String,Object>>> questionedSuspect(Long groupId, String strDate, String startTime, String endTime, Integer start, Integer limit, Long userId);
/**
* @param date 日期
* @param start 开始时间
* @param end 截止时间
* @param groupId 保安组 id
* @param userId 用户 id
* @return 数量统计
*/
ResponseData<List<StatisticsNode>> getStatisticsItem(String date, String start, String end, Long groupId, Long userId);
/**
* @param date 日期
* @param start 开始时间
* @param end 截止时间
* @param groupId 保安组 id
* @param userId 用户 id
* @return 平均数据统计
*/
ResponseData<List<AverageItem>> getAverageItem(String date, String start, String end, Long groupId, Long userId);
/**
* @param date 日期
* @param start 开始时间
* @param end 截止时间
* @param groupId 保安组 id
* @param userId 用户 id
* @return 表格数据
*/
ResponseData<List<StatisticsDiagramData>> getDiagramData(String date, String start, String end, Long groupId, Long userId);
}
| Java | CL | 2e57eb93768ae760f49e52d317a66120f3b37d4e4b352f3978f16775d46976a4 |
package eu.openminted.registry.component.service;
import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import java.net.JarURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.jar.JarFile;
import java.util.zip.ZipEntry;
import org.apache.commons.io.IOUtils;
import org.apache.maven.repository.internal.MavenRepositorySystemUtils;
import org.eclipse.aether.DefaultRepositorySystemSession;
import org.eclipse.aether.RepositorySystem;
import org.eclipse.aether.RepositorySystemSession;
import org.eclipse.aether.artifact.Artifact;
import org.eclipse.aether.artifact.DefaultArtifact;
import org.eclipse.aether.connector.basic.BasicRepositoryConnectorFactory;
import org.eclipse.aether.impl.DefaultServiceLocator;
import org.eclipse.aether.repository.LocalRepository;
import org.eclipse.aether.repository.RemoteRepository;
import org.eclipse.aether.resolution.ArtifactRequest;
import org.eclipse.aether.resolution.ArtifactResolutionException;
import org.eclipse.aether.resolution.ArtifactResult;
import org.eclipse.aether.spi.connector.RepositoryConnectorFactory;
import org.eclipse.aether.spi.connector.transport.TransporterFactory;
import org.eclipse.aether.transport.file.FileTransporterFactory;
import org.eclipse.aether.transport.http.HttpTransporterFactory;
import org.jdom.Document;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import eu.openminted.interop.componentoverview.exporter.Exporter;
import eu.openminted.interop.componentoverview.exporter.OpenMinTeDExporter;
import eu.openminted.interop.componentoverview.importer.CreoleImporter;
import eu.openminted.interop.componentoverview.importer.Importer;
import eu.openminted.interop.componentoverview.importer.UimaImporter;
import eu.openminted.interop.componentoverview.model.ComponentMetaData;
import groovy.util.Node;
import groovy.xml.XmlUtil;
public class ComponentRegistryService {
public List<ComponentMetaData> describe(String groupID, String artifactID, String version) throws IOException {
ComponentMetaData metadata = new ComponentMetaData();
Artifact artifactObj = new DefaultArtifact(groupID, artifactID, "jar", version);
// TODO this shouldn't be hardcoded
RemoteRepository central = new RemoteRepository.Builder("central", "default", "http://repo1.maven.org/maven2/")
.build();
ArtifactRequest artifactRequest = new ArtifactRequest();
artifactRequest.setArtifact(artifactObj);
artifactRequest.addRepository(central);
try {
ArtifactResult artifactResult = getRepositorySystem().resolveArtifact(getRepositorySession(),
artifactRequest);
return describe(artifactResult.getArtifact().getFile().toURI().toURL(), metadata);
} catch (ArtifactResolutionException e) {
throw new IOException("unable to retrieve plugin from maven", e);
}
}
/**
* describes the components available in the jar at the given URL
*/
public List<ComponentMetaData> describe(URL jarURL) throws IOException {
return describe(jarURL, new ComponentMetaData());
}
/**
* describes the components available in the jar at the given URL mixing in
* any other information that may already have been provided
*/
public List<ComponentMetaData> describe(URL jarURL, ComponentMetaData existingMetadata) throws IOException {
List<ComponentMetaData> metadata = null;
// TODO how do we determine if a JAR is a GATE or UIMA (and which
// framework) so we can use the correct importer to extract the relevant
// metadata?
URL baseURL = new URL("jar:" + jarURL + "!/");
// System.out.println(baseURL);
JarURLConnection connection = (JarURLConnection) baseURL.openConnection();
Importer<ComponentMetaData> importer = null;
JarFile jarFile = connection.getJarFile();
ZipEntry entry = null;
if (jarFile.getEntry("creole.xml") != null) {
// if it has a creole.xml at the root then this is a GATE component
importer = new CreoleImporter();
URL directoryXmlFileUrl = new URL(baseURL, "creole.xml");
metadata = importer.process(directoryXmlFileUrl, existingMetadata);
} else if ((entry = jarFile.getEntry("META-INF/org.apache.uima.fit/components.txt")) != null) {
// WARNING, you are entering the mad world of UIMA, abandon all
// hope!
List<String> lines = IOUtils.readLines(jarFile.getInputStream(entry));
metadata = new ArrayList<ComponentMetaData>();
for (String line : lines) {
if (line.startsWith("classpath")) {
line = line.split(":")[1];
importer = new UimaImporter("uimaFIT");
metadata.addAll(importer.process(new URL(baseURL, line), existingMetadata));
}
}
} else {
throw new IOException("URL points to unknown component type:" + jarURL);
}
return metadata;
}
/**
* Register the component described by the XML document. This method is the
* one that actually registers the component with the metadata service all
* the other methods end up calling this one eventually
*/
public void register(ComponentMetaData metadata) {
Document itemMetadata = null;
Exporter<Node> mse = new OpenMinTeDExporter();
Node w = mse.process(metadata);
try {
itemMetadata = new SAXBuilder().build(new StringReader(XmlUtil.serialize(w)));
// TODO save the XML into the actual registry store
} catch (IOException | JDOMException e) {
// this should be impossible
}
}
/**
* @return true if the component has been registered with the system even if
* registration is still pending, false otherwise
*/
public boolean isKnown(String className, String version) {
return isRegistered(className, version) || isPending(className, version);
}
/**
* @return true if this component is in the pending queue prior to full
* registration, false otherwise
*/
public boolean isPending(String className, String version) {
// TODO implement the lookup within the metadata service
return false;
}
/**
* @return true if this component is fully registered and available for use,
* false otherwise
*/
public boolean isRegistered(String className, String version) {
// TODO implement the lookup within the metadata service
return false;
}
private static RepositorySystem repoSystem = null;
private static DefaultRepositorySystemSession repoSystemSession = null;
private static RepositorySystem getRepositorySystem() {
if (repoSystem != null)
return repoSystem;
DefaultServiceLocator locator = MavenRepositorySystemUtils.newServiceLocator();
locator.addService(RepositoryConnectorFactory.class, BasicRepositoryConnectorFactory.class);
locator.addService(TransporterFactory.class, FileTransporterFactory.class);
locator.addService(TransporterFactory.class, HttpTransporterFactory.class);
repoSystem = locator.getService(RepositorySystem.class);
return repoSystem;
}
private static RepositorySystemSession getRepositorySession() {
if (repoSystemSession != null)
return repoSystemSession;
repoSystemSession = MavenRepositorySystemUtils.newSession();
// TODO pull this from the maven settings.xml file
LocalRepository localRepo = new LocalRepository(
System.getProperty("user.home") + File.separator + ".m2" + File.separator + "repository/");
System.out.println(localRepo);
repoSystemSession.setLocalRepositoryManager(
getRepositorySystem().newLocalRepositoryManager(repoSystemSession, localRepo));
return repoSystemSession;
}
}
| Java | CL | 9577166e026931e7308ac77a7b7bc831832e46f0397e49cf3c6b965d8c87f90b |
package ch.eonum.pipeline.classification.tree;
import java.io.IOException;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import ch.eonum.pipeline.classification.Classifier;
import ch.eonum.pipeline.core.DataSet;
import ch.eonum.pipeline.core.Features;
import ch.eonum.pipeline.core.Instance;
import ch.eonum.pipeline.evaluation.Evaluator;
import ch.eonum.pipeline.util.FileUtil;
import ch.eonum.pipeline.util.Gnuplot;
import ch.eonum.pipeline.util.Log;
/**
* Gradient boosting machine for decision trees (regression). Similar to @see
* GradientBoosting but specialized on decision trees and hence more efficient.
*
* @author tim
*
*/
public class GBM<E extends Instance> extends Classifier<E> {
protected static final Map<String, String> PARAMETERS = new HashMap<String, String>();
static {
PARAMETERS.put("shrinkage", "shrink factor (default 1.0)");
PARAMETERS.put("m", "number of trees (default 10.0)");
PARAMETERS.put("k", "percentage of features which are taken into account at each split node [0,1] (default 0.333)");
PARAMETERS.put("f", "fraction of the bootstrap size, relative to the training set size (default 1.0)");
PARAMETERS.put("maxDepth", "maximum depth of the tree (default 10.0)");
PARAMETERS.put("minSize", "minimum number of training instances within one terminal node (default 5.0)");
PARAMETERS.put("tolerance", "tolerance range for distinct values (default 0.01)");
}
/** decision trees. */
protected List<DecisionTree<E>> trees;
private Evaluator<E> evaluator;
private double[] gammas;
private Random rand;
public GBM(Features features, Evaluator<E> evaluator, int seed) {
this.evaluator = evaluator;
this.setSupportedParameters(GBM.PARAMETERS);
this.putParameter("shrinkage", 1.0);
this.putParameter("m", 10.0);
this.putParameter("k", 0.333);
this.putParameter("maxDepth", 10.0);
this.putParameter("minSize", 15.0);
this.putParameter("tolerance", 0.01);
this.putParameter("f", 1.0);
this.rand = new Random(seed);
this.features = features;
}
@Override
public void train() {
Map<Instance, Double> originalOutcomes = saveOutcomes(this.trainingDataSet);
Map<Integer, Double> curve = new LinkedHashMap<Integer, Double>();
Map<String, List<Double>> splitsPerFeature = DecisionTree.calculateSplitsPerFeature(features,
trainingDataSet, this.getDoubleParameter("tolerance"));
int M = (int)this.getDoubleParameter("m");
double shrinkage = this.getDoubleParameter("shrinkage");
trees = new ArrayList<DecisionTree<E>>();
for(int i = 0; i < M-1; i++){
DecisionTree<E> dt = new DecisionTree<E>(features, rand.nextInt(), splitsPerFeature, i);
dt.putParameter("k", this.getDoubleParameter("k"));
dt.putParameter("maxDepth", this.getDoubleParameter("maxDepth"));
dt.putParameter("minSize", this.getDoubleParameter("minSize"));
trees.add(dt);
}
// F_0 average outcome
double avg = 0.0;
for (Instance each : trainingDataSet)
avg += each.outcome;
avg /= trainingDataSet.size();
for (Instance each : trainingDataSet)
each.putResult("result", avg);
this.gammas = new double[M];
gammas[0] = avg;
// F_m minus 1
Map<Instance, Double> F_m1 = saveResults(this.trainingDataSet);
PrintStream p;
try {
p = new PrintStream(this.getBaseDir() + "gradientBoosting.txt");
p.println("Gamma[0] = " + avg);
for (int m = 1; m < M; m++) {
DecisionTree<E> tree = trees.get(m-1);
DataSet<E> trainSet = bootstrap(trainingDataSet);
DataSet<E> testSet = outOfBag(trainSet, trainingDataSet);
// calculate residuals and set outcome/target to residual
for (Instance each : trainingDataSet)
each.outcome = originalOutcomes.get(each) - F_m1.get(each);
FileUtil.mkdir(baseDir + m + "/");
tree.setBaseDir(baseDir + m + "/");
tree.setTrainingSet(trainSet);
tree.train();
tree.setTestSet(trainingDataSet);
trainingDataSet = tree.test();
trainingDataSet.renameResults("result", "Fm");
loadOutComes(this.trainingDataSet, originalOutcomes);
double maxGamma = 0.0;
double maxEval = Double.NEGATIVE_INFINITY;
for (int i = 0; i < 150; i++) {
double gamma = i * 0.01;
for (Instance each : testSet)
each.putResult("result",
each.getResult("Fm") * gamma + F_m1.get(each));
double eval = this.evaluator.evaluate(testSet);
// Log.puts("Gamma: " + gamma + " Eval: " + eval);
if (eval > maxEval) {
maxEval = eval;
maxGamma = gamma;
}
}
Log.puts("Iteration " + m + " Maximum Gamma: " + maxGamma
+ " Eval: " + maxEval);
gammas[m] = maxGamma * shrinkage;
for (Instance each : trainingDataSet)
each.putResult("result", (each.getResult("Fm"))
* gammas[m] + F_m1.get(each));
F_m1 = saveResults(trainingDataSet);
double eval = evaluator.evaluate(testSet);
p.println("Iteration " + m + " Maximum Gamma: " + maxGamma
+ " Eval: " + maxEval + " max eval shrinked: " + eval);
curve.put(m, eval);
Gnuplot.plotOneDimensionalCurve(curve, "GBM", this.getBaseDir() + "gbm");
}
p.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
loadOutComes(this.trainingDataSet, originalOutcomes);
}
private <T extends Instance> DataSet<T> bootstrap(DataSet<T> data) {
DataSet<T> bootstrap = new DataSet<T>();
int size = (int) (this.getDoubleParameter("f") * data.size());
for(int i = 0; i < size; i++)
bootstrap.addInstance(data.get(rand.nextInt(data.size())));
return bootstrap;
}
/**
* OOB, out of bag
* @param bag
* @param all
* @return
*/
private <T extends Instance> DataSet<T> outOfBag(DataSet<T> bag, DataSet<T> all) {
DataSet<T> oob = new DataSet<T>();
for(T each : all)
if(!bag.contains(each))
oob.addInstance(each);
return oob;
}
private Map<Instance, Double> saveResults(DataSet<E> data) {
Map<Instance, Double> map = new HashMap<Instance, Double>();
for (Instance each : data)
map.put(each, (double)each.getResult("result"));
return map;
}
private void loadOutComes(DataSet<E> data,
Map<Instance, Double> originalOutcomes) {
for (Instance each : data)
each.outcome = (double)originalOutcomes.get(each);
}
private Map<Instance, Double> saveOutcomes(DataSet<E> data) {
Map<Instance, Double> map = new HashMap<Instance, Double>();
for (Instance each : data)
map.put(each, each.outcome);
return map;
}
@Override
public DataSet<E> test() {
int M = (int) this.getDoubleParameter("m");
for (Instance each : testDataSet)
each.putResult("gbmSum", gammas[0]);
for (int m = 1; m < M; m++) {
DecisionTree<E> tree = trees.get(m-1);
tree.setTestSet(testDataSet);
tree.setBaseDir(baseDir + m + "/");
this.testDataSet = tree.test();
for(Instance each : testDataSet)
each.putResult("gbmSum", each.getResult("gbmSum") + gammas[m] * (each.getResult("result")));
}
for (Instance each : testDataSet){
each.putResult("result", Math.max(0.0, each.getResult("gbmSum")));
each.removeResult("gbmSum");
}
return this.testDataSet;
}
}
| Java | CL | 0abcaaf2e7f7f9c3d9da2c574bc206aea977150d9e044bb6184cbab383fd0556 |
package com.iknow.imageselect.core;
import android.support.v7.app.AppCompatActivity;
/**
* @Author: Jason.Chou
* @Email: who_know_me@163.com
* @Created: 2016年04月26日 5:08 PM
* @Description:
*/
public class CoreActivity extends AppCompatActivity {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java | CL | ad0825ddf6515524c2e74621d8021fcc0f261bb7d1ea21e66fe02e2e4f5e928e |
package com.example.rabbitmqdemo.rabbit.routingkey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
@Component
public class Receiver{
private static Logger logger = LoggerFactory.getLogger(Receiver.class);
//注解很重要,标注了exchange、routingkey、queue之间的关系,对应指定到这个queue
@RabbitListener(bindings = {@QueueBinding(value = @Queue(value = "${qf}"),
exchange = @Exchange(value = "exchange.ff.ff.sendPush"), key = "routingkey.ff.ff.sendPush")})
public void receiver(String message) {
logger.info("sendPush接收消息:{}", message);
}
@RabbitListener(bindings = {@QueueBinding(value = @Queue(value = "123"),
exchange = @Exchange(value = "exchange.ff.ff.aaa"), key = "sendPush111")})
public void receiverResp(String message) {
logger.info("sendPush111接收消息:{}", message);
}
} | Java | CL | ccd1e9666c145bda52df7e0b911cd640d952dc6c0f01560948177c19b63aa613 |
package net.ooici.ion.cc.messaging.platform.rabbitmq;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import net.ooici.ion.cc.messaging.Broker;
import net.ooici.ion.cc.messaging.Dispatcher;
import net.ooici.ion.cc.messaging.MessagingException;
import net.ooici.ion.cc.messaging.platform.Platform;
import net.ooici.ion.cc.messaging.platform.PlatformException;
import net.ooici.ion.properties.LocalProperties;
import net.ooici.ion.properties.PropertiesException;
/**
*
* @author brianfox
*
*/
public class RabbitPlatform extends Platform {
Logger logger = LoggerFactory.getLogger(RabbitPlatform.class);
@Override
public Broker createBroker(LocalProperties properties)
throws
PlatformException,
MessagingException,
PropertiesException
{
return RabbitBroker.createBroker(properties);
}
@Override
public Dispatcher createDispatcher(
LocalProperties properties,
Broker broker
)
throws
PlatformException {
try {
return new RabbitDispatcher(properties, broker);
} catch (Exception e) {
String err = "Unable to create RabbitDispatcher: " + e.getClass().getName();
logger.error(err);
throw new PlatformException(err, e);
}
}
} | Java | CL | 327d1f2427e5ab1213a5a5cac621906dd8364568511a10f5169aa8d6b3e90745 |
/*
* Copyright 2007-2016 Michael Hoffer <info@michaelhoffer.de>. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY Michael Hoffer <info@michaelhoffer.de> "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL Michael Hoffer <info@michaelhoffer.de> OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are those of the
* authors and should not be interpreted as representing official policies, either expressed
* or implied, of Michael Hoffer <info@michaelhoffer.de>.
*/
/*
* WorldDescription.java
*
* Created on 11. Juli 2007, 21:38
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/
package eu.mihosoft.ai.astar;
import java.util.ArrayList;
import java.util.List;
/**
* This class provides everything the a* solver needs to know about a problem
* and its domain.
*
* @author miho
* @param <T>
*/
public class WorldDescription<T> {
private final Heuristic<T> heuristic;
private State<T> initialState;
// private State<T> finalState;
private Condition<T> goal;
private List<Action<T>> actionSet;
// private ArrayList<Predicate> predicateSet;
/**
* Creates a new instance of WorldDescription.
*
* @param initialState The initial state (s_0).
* @param goal The condition that describes the final state (s_n).
* @param actionSet The set of actions (containing operators with all
* possible parameter combinations)
* @param heuristic The heuristic that is to be used.
*/
public WorldDescription(State<T> initialState, Condition<T> goal, List<Action<T>> actionSet, Heuristic<T> heuristic) {
this.heuristic = heuristic;
this.initialState = initialState.clone();
// this.finalState = initialState.newInstance(initialState.size());
// this.setFinalState (initialState.newInstance(initialState.size()));
this.goal = goal;
// Effect g = new Effect();
//
// for (int i = 0; i < goal.size(); i++) {
// g.add((EffectPredicate) goal.get(i));
// }
//
// g.apply(this.finalState);
this.actionSet = actionSet;
// this.predicateSet = null;
}
// /**
// * Overloaded version of the above named constructor.
// * This constructor is to be used if one wants to use the domain independant
// * world generator.
// *
// * @param initialState The initial state (s_0).
// * @param actionSet The set of actions (containing operators with all
// * possible parameter combinations)
// * @param heuristic The heuristic that is to be used.
// */
// public WorldDescription (State<T> initialState,
// ArrayList<Action> actionSet,
//// ArrayList<Predicate> predicateSet,
// Heuristic<T> heuristic)
// {
// this.heuristic = heuristic;
//
// this.setInitialState (initialState);
//
// this.actionSet = actionSet;
//// this.predicateSet = predicateSet;
// }
//
/**
* Returns the action set.
*
* @return
*/
public List<Action<T>> getActionSet() {
return actionSet;
}
/**
* Returns the goal condition.
*/
public Condition<T> getGoal() {
return goal;
}
/**
* Returns the initial state.
*/
public State<T> getInitialState() {
return initialState;
}
/**
* Returns the heuristic.
*/
public Heuristic<T> getHeuristic() {
return heuristic;
}
// /**
// * Returns the final state (s_n).
// *<br><br>
// * <b>Warning:</b> If the WorldDescriptions initial and final states
// * will be initialized by a WorldGenerator, this method
// * returns null as long as this has not be done.
// */
// public State getFinalState ()
// {
// return finalState;
// }
// /**
// * Sets the initial state.
// *
// * @param initialState The initial state (s_0).
// */
// public final void setInitialState(State<T> initialState) {
// this.initialState = initialState.clone();
// }
// /**
// * Sets the final state.
// *
// * @param finalState The final state (s_n).
// */
// public final void setFinalState (State<?> finalState)
// {
// this.finalState = (State) finalState.clone ();
//
// goal = new Condition ();
//
// for (int i = 0; i < finalState.size ();i++)
// {
// if (finalState.get (i) == true )
// {
// goal.add ( new Predicate (i, true) );
// }
// }
// }
// /**
// * Returns the set of predicates.
// * <br><br>
// * <b>Warning:</b> This method will return null if WorldDescription
// * is not initialized for use with a WorldGenerator.
// */
// public ArrayList<Predicate> getPredicateSet ()
// {
// return predicateSet;
// }
}
| Java | CL | 5fa1fea82c4a1ab610804b0a620c9612242d7300c0e89b41b820d058e9355fc0 |
/*
* Copyright (c) 2017, Wasiq Bhamla.
*
* 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.wasiqb.coteafs.appium.ios;
import static com.github.wasiqb.coteafs.appium.utils.BatteryHealth.check;
import com.github.wasiqb.coteafs.appium.config.enums.DeviceType;
import com.github.wasiqb.coteafs.appium.device.DeviceActivity;
import io.appium.java_client.MobileElement;
import io.appium.java_client.ios.IOSBatteryInfo;
import io.appium.java_client.ios.IOSDriver;
import io.appium.java_client.ios.IOSTouchAction;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
/**
* @author wasiq.bhamla
* @since 26-Apr-2017 7:41:49 PM
*/
public abstract class IOSActivity extends DeviceActivity<IOSDriver<MobileElement>, IOSDevice, IOSTouchAction> {
private static final Logger log = LogManager.getLogger ();
/**
* @param device Device instance
*
* @author wasiq.bhamla
* @since 26-Apr-2017 7:42:13 PM
*/
protected IOSActivity (final IOSDevice device) {
super (device, new IOSTouchAction (device.getDriver ()));
}
/*
* (non-Javadoc)
* @see com.github.wasiqb.coteafs.appium.device.DeviceActivity#onDevice()
*/
@Override
public IOSDeviceActions onDevice () {
checkBattery ();
log.trace ("Preparing to perform actions on iOS device...");
return new IOSDeviceActions (this.device);
}
/*
* (non-Javadoc)
* @see
* com.github.wasiqb.coteafs.appium.device.DeviceActivity#onElement(java.lang.
* String)
*/
@Override
public IOSDeviceElementActions onElement (final String name) {
checkBattery ();
log.trace ("Preparing to perform actions on iOS device element [{}]...", name);
return new IOSDeviceElementActions (this.device, name, getElement (name));
}
private void checkBattery () {
final IOSBatteryInfo battery = this.device.getDriver ()
.getBatteryInfo ();
if (!this.device.getSetting ()
.isCloud () && this.device.getSetting ()
.getType () == DeviceType.REAL) {
check (battery.getState ()
.name (), battery.getLevel ());
}
}
} | Java | CL | 4055c15247cfb9a014b74963a312a229c672e5dbdaf0cba171dc67b27f6e9701 |
package vn.com.vhc.alarm.core;
import java.io.IOException;
import java.lang.management.*;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import javax.sql.DataSource;
import org.apache.log4j.Logger;
import vn.com.vhc.alarm.cni.AL_ConvertService;
import vn.com.vhc.alarm.cni.AL_ImportDirectlyService;
import vn.com.vhc.alarm.dnu.AL_SelectionService;
import vn.com.vhc.alarm.util.AL_Attribute;
import vn.com.vhc.alarm.util.task.AL_TaskService;
import vn.com.vhc.alarm.utils.log.AL_DbAppender;
/**
*
* @author Mr
* @return Coreservice thread
*
*/
@SuppressWarnings("rawtypes")
public class AL_CoreServiceThread implements Callable {
private static Logger logger = Logger.getLogger(AL_CoreServiceThread.class.getName());
// private AL_DownloadServicesTelnet downloadServiceTelnet = null;
private AL_SelectionService selectionService = null;
private AL_ConvertService convertService = null;
private AL_ImportDirectlyService importService = null;
AL_CoreService al = null;
private static AL_CoreServiceThread singleton = null;
private DataSource dataSource = null;
private AL_TaskService runningService = null;
private Thread runningThread = null;
private boolean exitLoop = false;
private boolean stopped = true;
public static final String DATE_FORMAT_NOW = "yyyy-MM-dd HH-mm-ss";
private String status = "";
private long delay = 0;
private static CallableStatement cs = null;
private AL_CoreServiceThread(DataSource ds, long delay) {
this.dataSource = ds;
this.delay = delay;
//downloadServiceTelnet = new AL_DownloadServicesTelnet("AL_DownloadService",dataSource);
selectionService = new AL_SelectionService("AL_SelectionService", dataSource);
convertService = new AL_ConvertService("AL_ConvertService", dataSource);
importService = new AL_ImportDirectlyService("JDBCImportService", dataSource);
}
@SuppressWarnings("unchecked")
public static synchronized void startService(ExecutorService threadPool,
DataSource ds, long delay) {
if (singleton == null) {
singleton = new AL_CoreServiceThread(ds, delay);
} else {
singleton.delay = delay;
singleton.dataSource = ds;
}
if (singleton.isStopped()) {
singleton.exitLoop = false;
threadPool.submit(singleton);
}
}
public static synchronized void stopService() {
if (singleton != null) {
singleton.stop();
}
}
public static synchronized void switchToNextService() {
if (singleton != null && !singleton.isStopped()) {
singleton.switchNext();
}
}
public static synchronized List<AL_Attribute> getRunningServiceInfo() {
List<AL_Attribute> serviceInfo = null;
if (singleton != null) {
serviceInfo = singleton.getServiceInfo();
}
return serviceInfo;
}
public static synchronized boolean isStarted() {
if (singleton != null && !singleton.isStopped()) {
return true;
}
return false;
}
// Call thread
@SuppressWarnings("unused")
public Object call() {
stopped = false;
logger.info("Core service started");
runningThread = Thread.currentThread();
Date selectionDate, convertDate, importDate, finishDate, downLoadStartTime;
selectionDate = new Date(System.currentTimeMillis());
convertDate = selectionDate;
importDate = selectionDate;
finishDate = selectionDate;
int selectionCnt = 0;
int convertCnt = 0;
int importCnt = 0;
int downloadCnt=0;
AL_CoreDBLogParam logParam = null;
AL_FileSweeper cleaner = null;
String rawBaseDir = AL_Global.SYSTEM_CONFIG.getProperty("raw.base.dir");
long rawBackupDay = 3;
try {
rawBackupDay =
Long.parseLong(AL_Global.SYSTEM_CONFIG.getProperty("raw.backup.day"));
} catch (Exception e) {
logger.warn("Not found 'raw.backup.day' in C_SYSTEM_CONFIGS_MLMN");
}
if (rawBaseDir != null) {
try {
cleaner = new AL_FileSweeper(rawBaseDir, rawBackupDay);
} catch (IOException e) {
logger.warn("Init raw file cleaner error: " +
e.getMessage());
}
}
while (!exitLoop) {
try {
//Start download
/*logger.info("Process downloading ...");
switchService("Download", downloadServiceTelnet);
downloadServiceTelnet.processTasks();
logger.info("DownloadService finished" + downloadServiceTelnet.getStartTime() );
downloadCnt = downloadServiceTelnet.getDoneTasks();
if (exitLoop) {
break;
}*/
//Start select
logger.info("Process selecting ...");
switchService("SELECTING", selectionService);
selectionService.processTasks();
selectionDate = selectionService.getStartTime();
selectionCnt = selectionService.getDoneTasks();
logger.info("Selection finished");
if (exitLoop) {
break;
}
//Start convert
logger.info("Process converting ...");
switchService("CONVERTING", convertService);
convertService.processTasks();
convertDate = convertService.getStartTime();
convertCnt = convertService.getDoneTasks();
logger.info("Convert finished");
if (exitLoop) {
break;
}
//Start import
logger.info("Process importing ...");
switchService("IMPORTING", importService);
importService.processTasks();
importDate = importService.getStartTime();
importCnt = importService.getDoneTasks();
logger.info("Import finished");
//Call package sms
summary_data();
if (exitLoop) {
break;
}
} catch (Exception ex) {
logger.warn("Core service fatal error: " + ex.getMessage(), ex);
} finally {
finishDate = new Date(System.currentTimeMillis());
logParam =
new AL_CoreDBLogParam(selectionDate, selectionCnt, convertDate,
convertCnt, importDate, importCnt,
finishDate);
logger.info("Finish one core cycle, write log to database");
if(selectionCnt > 0)
AL_DbAppender.log(logParam);
//Reset variables
selectionCnt = 0;
convertCnt = 0;
importCnt = 0;
selectionDate = finishDate;
convertDate = finishDate;
importDate = finishDate;
}
switchService("IDLE", null);
try {
logger.info("Core service sleep for " + delay + " seconds");
Thread.sleep(delay * 1000);
} catch (InterruptedException e) {
logger.warn("Core service interrupted");
}
}
switchService("STOPPED", null);
logger.info("Core service stopped!!!");
runningThread = null;
stopped = true;
return null;
}
protected synchronized void stop() {
logger.info("Try to stop Core service");
status = "STOPPING";
this.exitLoop = true;
if (runningService != null) {
logger.info("Try to stop running service");
runningService.stop();
}
if (runningThread != null) {
logger.info("Try to interrupt Core service's running thread");
runningThread.interrupt();
}
}
protected synchronized void switchNext() {
if (runningService != null) {
runningService.stop();
}
}
private synchronized void switchService(String status,
AL_TaskService service) {
this.status = status;
runningService = service;
logger.info("Service status switched, new status = " + status +
", running service = " + runningService);
}
//Get service info
@SuppressWarnings("unchecked")
protected synchronized List<AL_Attribute> getServiceInfo() {
List<AL_Attribute> list = new ArrayList<AL_Attribute>();
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
list.add(new AL_Attribute("Status: ", status, 0));
if (runningService != null) {
list.add(new AL_Attribute("Start time: ",
format.format(runningService.getStartTime()),
1));
list.add(new AL_Attribute("Total files: ",
String.valueOf(runningService.getTotalTasks()),
2));
list.add(new AL_Attribute("Remain files: ",
String.valueOf(runningService.getRemainTasks()),
3));
list.add(new AL_Attribute("Current file: ",
runningService.getWorkingTaskInfos(), 4));
list.add(new AL_Attribute("", "---------------^^^--------------", 5));
}
Collections.sort(list);
return list;
}
//Check thread isstopped
protected synchronized boolean isStopped() {
return stopped;
}
//Call package Sms
public void summary_data(){
Connection conn = null;
try {
conn = this.dataSource.getConnection();
cs = conn.prepareCall(
"{call PK_AL_CORE_MLMN.summary_data_alarm}"
);
cs.executeQuery();
cs.close();
} catch (SQLException e) {
logger.warn("File list to import is empty", e);
} finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException sqlEx) {
logger.warn("Cannot close the connection to database",
sqlEx);
}
}
}
}
}
| Java | CL | 3441fa670c5180422a39d8f8128d4a076520199cc629a7c9a81d7743649deaf3 |
package ru.levelup.at.api.serialization;
import static io.restassured.RestAssured.given;
import static org.assertj.core.api.Assertions.assertThat;
import io.restassured.builder.RequestSpecBuilder;
import io.restassured.builder.ResponseSpecBuilder;
import io.restassured.filter.log.LogDetail;
import io.restassured.http.ContentType;
import io.restassured.specification.RequestSpecification;
import io.restassured.specification.ResponseSpecification;
import org.apache.http.HttpStatus;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import ru.levelup.at.api.error.ErrorResponse;
import ru.levelup.at.api.error.UserRequest;
public class RestAssuredErrorExample {
private RequestSpecification requestSpecification;
private ResponseSpecification responseSpecification;
@BeforeMethod
public void setUp() {
requestSpecification = new RequestSpecBuilder()
.log(LogDetail.ALL)
.setBaseUri("https://reqres.in")
.setContentType(ContentType.JSON)
.build();
responseSpecification = new ResponseSpecBuilder()
.log(LogDetail.ALL)
.build();
}
@Test
public void emailErrorTest() {
ErrorResponse actualResponse = given()
.spec(requestSpecification)
.body(UserRequest.builder().email("hsdkskd@jdsvjsdva").build())
.when()
.post("/api/register")
.then()
.spec(responseSpecification)
.statusCode(HttpStatus.SC_BAD_REQUEST)
.extract()
.as(ErrorResponse.class);
ErrorResponse expectedResponse = ErrorResponse.builder()
.error("Missing password")
.build();
assertThat(actualResponse).isEqualTo(expectedResponse);
}
}
| Java | CL | d4a605d87cef948a718cb8c6c4c449093006e19764e220c92e7babb95e316dd3 |
/**
* Copyright (C) 2011-2022 Red Hat, Inc. (https://github.com/Commonjava/indy)
*
* 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.commonjava.indy.model.core.dto;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import org.commonjava.indy.IndyException;
@ApiModel( description = "Configuration for replicating the content stores on a remote Indy system" )
public class ReplicationDTO
implements Iterable<ReplicationAction>
{
@ApiModelProperty( "Whether to overwrite pre-existing artifact stores on the local Indy instance with definitions from the remote system" )
private boolean overwrite;
@ApiModelProperty( required = true, value = "The URL to the remote Indy instance" )
private String apiUrl;
private String proxyHost;
private int proxyPort;
@ApiModelProperty( required = true, value = "The list of replication actions to be performed" )
private List<ReplicationAction> actions;
public String getApiUrl()
{
return apiUrl;
}
public List<ReplicationAction> getActions()
{
return actions;
}
public void setApiUrl( final String apiUrl )
{
this.apiUrl = apiUrl;
}
public void setActions( final List<ReplicationAction> actions )
{
this.actions = actions;
}
public boolean isOverwrite()
{
return overwrite;
}
public void setOverwrite( final boolean overwrite )
{
this.overwrite = overwrite;
}
public void validate()
throws IndyException
{
final StringBuilder sb = new StringBuilder();
if ( apiUrl == null )
{
sb.append( "You must provide an api URL to the remote Indy instance." );
}
else
{
try
{
new URL( apiUrl );
}
catch ( final MalformedURLException e )
{
sb.append( "You must provide a VALID api URL to the remote Indy instance. (invalid: '" )
.append( apiUrl )
.append( "'): " )
.append( e.getMessage() );
}
}
if ( actions == null || actions.isEmpty() )
{
actions = Collections.<ReplicationAction> singletonList( new ReplicationAction() );
}
if ( sb.length() > 0 )
{
throw new IndyException( sb.toString() );
}
}
@Override
public Iterator<ReplicationAction> iterator()
{
return actions.iterator();
}
public String getProxyHost()
{
return proxyHost;
}
public int getProxyPort()
{
return proxyPort;
}
public void setProxyHost( final String proxyHost )
{
this.proxyHost = proxyHost;
}
public void setProxyPort( final int proxyPort )
{
this.proxyPort = proxyPort;
}
@Override
public String toString()
{
return String.format( "ReplicationDTO [overwrite=%s, apiUrl=%s, proxyHost=%s, proxyPort=%s, actions=%s]", overwrite, apiUrl, proxyHost,
proxyPort, actions );
}
}
| Java | CL | b9ae1d37e9a9429d06cbdeb03fe619e05c35e540e4515f24bc030a0085009f24 |
package io.semla.serialization.json;
import io.semla.exception.DeserializationException;
import io.semla.serialization.Deserializer;
import io.semla.serialization.Token;
import io.semla.serialization.io.CharacterReader;
import lombok.extern.slf4j.Slf4j;
import java.util.Set;
import static io.semla.serialization.io.CharacterReader.EOF;
@Slf4j
public class JsonDeserializer extends Deserializer<JsonDeserializer.Context> {
@Override
protected Context newContext(CharacterReader reader, Set<Option> options) {
return new Context(reader, options);
}
@Override
protected String read(Context context) {
StringBuilder content = new StringBuilder();
boolean escaped = false, quoted = false, read = true;
char current = context.reader().current();
do {
switch (current) {
case EOF:
read = false;
break;
case '\\':
escaped ^= true;
if (!escaped) {
content.append(current);
}
break;
case ',':
case ':':
case '}':
case ']':
case '\r':
case '\n':
case ' ':
if (quoted) {
content.append(current);
} else {
if (current == '}') {
context.enqueue(Token.OBJECT_END);
} else if (current == ']') {
context.enqueue(Token.ARRAY_END);
}
read = false;
}
break;
case '"':
if (!escaped) {
quoted ^= true;
}
default:
escaped = false;
content.append(current);
break;
}
if (read) {
current = context.reader().next();
}
} while (read);
if (content.charAt(0) == '"' && content.charAt(content.length() - 1) == '"') {
content.deleteCharAt(0).deleteCharAt(content.length() - 1);
}
if (log.isTraceEnabled()) {
log.trace("read: {}", content.toString());
}
return content.toString();
}
public class Context extends Deserializer<Context>.Context {
public Context(CharacterReader reader, Set<Option> options) {
super(reader, options);
}
@Override
public Token evaluateNextToken() {
char c = reader().nextNonWhiteSpaceCharacter();
if (log.isTraceEnabled()) {
log.trace("evaluating: " + c);
}
return switch (c) {
case '"' -> {
if (last() == Token.OBJECT) {
yield Token.PROPERTY;
}
yield Token.STRING;
}
case 't', 'f' -> Token.BOOLEAN;
case 'n' -> {
reader().assertNextCharactersAre("ull");
yield Token.NULL;
}
case '{' -> Token.OBJECT;
case '[' -> Token.ARRAY;
case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '.' -> Token.NUMBER;
case ':', ',', '\n', '\r' -> evaluateNextToken();
case EOF -> Token.END;
case '}' -> Token.OBJECT_END;
case ']' -> Token.ARRAY_END;
default -> throw new DeserializationException("unexpected character '" + c + "' at " + reader().index() + "/" + reader().length());
};
}
}
}
| Java | CL | bba92411ada5467c794809d4ed12b650a2eeeaacba3dfb6e61f1de89b97295cf |
package com.ices.reservation.manager.web;
import com.ices.pojo.User;
import com.ices.pojo.system.Buser;
import com.ices.reservation.manager.service.LoginService;
import io.swagger.annotations.Api;
import javafx.scene.chart.ValueAxis;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.Map;
@RestController
@CrossOrigin
@Api(tags = {"登录接口"})
public class LoginController {
@Autowired
LoginService loginService;
@RequestMapping(path = {"/login/test"}, method = {RequestMethod.GET})
@ResponseBody
public String test() {
return "123";
}
@RequestMapping(value = "/login/buser", method = RequestMethod.POST)
public Object login(@RequestBody Buser buser){
return loginService.login(buser);
}
@RequestMapping(value = "/user/login", method = RequestMethod.POST)
public Object userLogin(@RequestBody User user){
return loginService.userLogin(user);
}
@RequestMapping(value = "/user/register", method = RequestMethod.POST)
public Object registerUser(@RequestBody User user){
return loginService.registerUser(user);
}
}
| Java | CL | fe324fe9784d673adcd8994473fe4dd8c3bd5f1cd47b18f369bd429dea4cdee3 |
package com.dianping.pigeon.remoting.common.codec.fst;
import java.io.InputStream;
import java.io.OutputStream;
import com.ymm.tracker.CacheExecutionTrace;
import com.ymm.tracker.SqlExecutionTrace;
import com.ymm.tracker.TrackerContext;
import com.dianping.dpsf.protocol.DefaultRequest;
import com.dianping.dpsf.protocol.DefaultResponse;
import com.dianping.pigeon.remoting.common.codec.DefaultAbstractSerializer;
import com.dianping.pigeon.remoting.common.exception.SerializationException;
import de.ruedigermoeller.serialization.FSTConfiguration;
import de.ruedigermoeller.serialization.FSTObjectInput;
import de.ruedigermoeller.serialization.FSTObjectOutput;
public class FstSerializer extends DefaultAbstractSerializer {
static FSTConfiguration conf = FSTConfiguration.createDefaultConfiguration();
public FstSerializer() {
conf.registerClass(DefaultRequest.class, DefaultResponse.class, TrackerContext.class,
CacheExecutionTrace.class, SqlExecutionTrace.class);
// conf.registerSerializer(BigInteger.class, new FSTBigIntegerSerializer(), true);
// conf.registerSerializer(BigDecimal.class, new FSTBigDecimalSerializer(), true);
}
public Object deserializeObject(InputStream is) throws SerializationException {
try {
FSTObjectInput in = conf.getObjectInput(is);
Object result = in.readObject();
is.close();
return result;
} catch (Throwable e) {
throw new SerializationException(e.getMessage(), e);
}
}
@Override
public Object deserializeRequest(InputStream is) throws SerializationException {
return deserializeObject(is);
}
@Override
public void serializeRequest(OutputStream os, Object obj) throws SerializationException {
try {
FSTObjectOutput out = conf.getObjectOutput(os);
out.writeObject(obj);
out.flush();
os.close();
} catch (Throwable e) {
throw new SerializationException(e.getMessage(), e);
}
}
@Override
public Object deserializeResponse(InputStream is) throws SerializationException {
return deserializeObject(is);
}
@Override
public void serializeResponse(OutputStream os, Object obj) throws SerializationException {
serializeRequest(os, obj);
}
}
| Java | CL | c41580361636a5f6e2ba06b35fd8353998b435f9d4f95751208f103c53f261e5 |
/*
* Copyright (c) 2016-present, RxJava Contributors.
*
* 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.reactivex.rxjava3.internal.functions;
import static org.junit.Assert.*;
import java.lang.reflect.Method;
import java.util.List;
import org.junit.Test;
import io.reactivex.rxjava3.core.RxJavaTest;
import io.reactivex.rxjava3.exceptions.TestException;
import io.reactivex.rxjava3.functions.*;
import io.reactivex.rxjava3.internal.functions.Functions.*;
import io.reactivex.rxjava3.internal.util.ExceptionHelper;
import io.reactivex.rxjava3.plugins.RxJavaPlugins;
import io.reactivex.rxjava3.testsupport.TestHelper;
public class FunctionsTest extends RxJavaTest {
@Test
public void utilityClass() {
TestHelper.checkUtilityClass(Functions.class);
}
@SuppressWarnings("unchecked")
@Test
public void hashSetCallableEnum() {
// inlined TestHelper.checkEnum due to access restrictions
try {
Method m = Functions.HashSetSupplier.class.getMethod("values");
m.setAccessible(true);
Method e = Functions.HashSetSupplier.class.getMethod("valueOf", String.class);
e.setAccessible(true);
for (Enum<HashSetSupplier> o : (Enum<HashSetSupplier>[])m.invoke(null)) {
assertSame(o, e.invoke(null, o.name()));
}
} catch (Throwable ex) {
throw ExceptionHelper.wrapOrThrow(ex);
}
}
@SuppressWarnings("unchecked")
@Test
public void naturalComparatorEnum() {
// inlined TestHelper.checkEnum due to access restrictions
try {
Method m = Functions.NaturalComparator.class.getMethod("values");
m.setAccessible(true);
Method e = Functions.NaturalComparator.class.getMethod("valueOf", String.class);
e.setAccessible(true);
for (Enum<NaturalComparator> o : (Enum<NaturalComparator>[])m.invoke(null)) {
assertSame(o, e.invoke(null, o.name()));
}
} catch (Throwable ex) {
throw ExceptionHelper.wrapOrThrow(ex);
}
}
@Test
public void booleanSupplierPredicateReverse() throws Throwable {
BooleanSupplier s = new BooleanSupplier() {
@Override
public boolean getAsBoolean() throws Exception {
return false;
}
};
assertTrue(Functions.predicateReverseFor(s).test(1));
s = new BooleanSupplier() {
@Override
public boolean getAsBoolean() throws Exception {
return true;
}
};
assertFalse(Functions.predicateReverseFor(s).test(1));
}
@Test(expected = IllegalArgumentException.class)
public void toFunction2() throws Throwable {
Functions.toFunction(new BiFunction<Integer, Integer, Integer>() {
@Override
public Integer apply(Integer t1, Integer t2) throws Exception {
return null;
}
}).apply(new Object[20]);
}
@Test(expected = IllegalArgumentException.class)
public void toFunction3() throws Throwable {
Functions.toFunction(new Function3<Integer, Integer, Integer, Integer>() {
@Override
public Integer apply(Integer t1, Integer t2, Integer t3) throws Exception {
return null;
}
}).apply(new Object[20]);
}
@Test(expected = IllegalArgumentException.class)
public void toFunction4() throws Throwable {
Functions.toFunction(new Function4<Integer, Integer, Integer, Integer, Integer>() {
@Override
public Integer apply(Integer t1, Integer t2, Integer t3, Integer t4) throws Exception {
return null;
}
}).apply(new Object[20]);
}
@Test(expected = IllegalArgumentException.class)
public void toFunction5() throws Throwable {
Functions.toFunction(new Function5<Integer, Integer, Integer, Integer, Integer, Integer>() {
@Override
public Integer apply(Integer t1, Integer t2, Integer t3, Integer t4, Integer t5) throws Exception {
return null;
}
}).apply(new Object[20]);
}
@Test(expected = IllegalArgumentException.class)
public void toFunction6() throws Throwable {
Functions.toFunction(new Function6<Integer, Integer, Integer, Integer, Integer, Integer, Integer>() {
@Override
public Integer apply(Integer t1, Integer t2, Integer t3, Integer t4, Integer t5, Integer t6) throws Exception {
return null;
}
}).apply(new Object[20]);
}
@Test(expected = IllegalArgumentException.class)
public void toFunction7() throws Throwable {
Functions.toFunction(new Function7<Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer>() {
@Override
public Integer apply(Integer t1, Integer t2, Integer t3, Integer t4, Integer t5, Integer t6, Integer t7) throws Exception {
return null;
}
}).apply(new Object[20]);
}
@Test(expected = IllegalArgumentException.class)
public void toFunction8() throws Throwable {
Functions.toFunction(new Function8<Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer>() {
@Override
public Integer apply(Integer t1, Integer t2, Integer t3, Integer t4, Integer t5, Integer t6, Integer t7, Integer t8) throws Exception {
return null;
}
}).apply(new Object[20]);
}
@Test(expected = IllegalArgumentException.class)
public void toFunction9() throws Throwable {
Functions.toFunction(new Function9<Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer>() {
@Override
public Integer apply(Integer t1, Integer t2, Integer t3, Integer t4, Integer t5, Integer t6, Integer t7, Integer t8, Integer t9) throws Exception {
return null;
}
}).apply(new Object[20]);
}
@Test
public void identityFunctionToString() {
assertEquals("IdentityFunction", Functions.identity().toString());
}
@Test
public void emptyActionToString() {
assertEquals("EmptyAction", Functions.EMPTY_ACTION.toString());
}
@Test
public void emptyRunnableToString() {
assertEquals("EmptyRunnable", Functions.EMPTY_RUNNABLE.toString());
}
@Test
public void emptyConsumerToString() {
assertEquals("EmptyConsumer", Functions.EMPTY_CONSUMER.toString());
}
@Test
public void errorConsumerEmpty() throws Throwable {
List<Throwable> errors = TestHelper.trackPluginErrors();
try {
Functions.ERROR_CONSUMER.accept(new TestException());
TestHelper.assertUndeliverable(errors, 0, TestException.class);
assertEquals(errors.toString(), 1, errors.size());
} finally {
RxJavaPlugins.reset();
}
}
}
| Java | CL | fdd2b3360d93ea6118efa28a55a1b3ddad8c247df334048143b428fb17abdc0c |
/*
* 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 net.thevpc.upa.impl.android;
import net.thevpc.upa.impl.util.classpath.ClassFileIteratorFactory;
import net.thevpc.upa.persistence.PersistenceStore;
import net.thevpc.upa.ObjectFactory;
import net.thevpc.upa.ObjectFactoryConfigurator;
/**
*
* @author vpc
*/
public class AndroidObjectFactoryConfigurator implements ObjectFactoryConfigurator {
@Override
public void configure(ObjectFactory factory) {
LogHelper.configure();
factory.addAlternative(ClassFileIteratorFactory.class, ApkClassFileIteratorFactory.class);
factory.addAlternative(PersistenceStore.class, AndroidSqlitePersistenceStore.class);
}
@Override
public int getContextSupportLevel() {
return 1;
}
}
| Java | CL | ba7e7357d7a174f6cf744f1bf9a7ef6e4dd3aa5c812a48580b997dad3954891a |
/*
* This file was automatically generated by EvoSuite
* Sat Jan 05 09:14:43 GMT 2019
*/
package com.google.javascript.jscomp;
import org.junit.Test;
import static org.junit.Assert.*;
import static org.evosuite.runtime.EvoAssertions.*;
import com.google.javascript.jscomp.ClosureCodingConvention;
import com.google.javascript.jscomp.Compiler;
import com.google.javascript.jscomp.DefaultCodingConvention;
import com.google.javascript.jscomp.GoogleCodingConvention;
import com.google.javascript.jscomp.Scope;
import com.google.javascript.jscomp.TypedScopeCreator;
import com.google.javascript.rhino.Node;
import java.io.PrintStream;
import org.evosuite.runtime.EvoRunner;
import org.evosuite.runtime.EvoRunnerParameters;
import org.junit.runner.RunWith;
@RunWith(EvoRunner.class) @EvoRunnerParameters(mockJVMNonDeterminism = true, useVFS = true, useVNET = true, resetStaticState = true, separateClassLoader = true, useJEE = true)
public class TypedScopeCreator_ESTest extends TypedScopeCreator_ESTest_scaffolding {
@Test(timeout = 4000)
public void test00() throws Throwable {
Compiler compiler0 = new Compiler((PrintStream) null);
Node node0 = compiler0.parseTestCode("com.gogle.javascript.jscomp.TypedScopeCreator$DeferredSetTyp");
GoogleCodingConvention googleCodingConvention0 = new GoogleCodingConvention();
TypedScopeCreator typedScopeCreator0 = new TypedScopeCreator(compiler0, googleCodingConvention0);
Scope scope0 = typedScopeCreator0.createScope(node0, (Scope) null);
assertEquals(33, scope0.getVarCount());
typedScopeCreator0.patchGlobalScope(scope0, node0);
assertEquals(32, scope0.getVarCount());
}
@Test(timeout = 4000)
public void test01() throws Throwable {
Compiler compiler0 = new Compiler();
Node node0 = compiler0.parseTestCode("[6");
node0.setType(37);
TypedScopeCreator typedScopeCreator0 = new TypedScopeCreator(compiler0);
Scope scope0 = typedScopeCreator0.createScope(node0, (Scope) null);
assertFalse(scope0.isLocal());
}
@Test(timeout = 4000)
public void test02() throws Throwable {
Compiler compiler0 = new Compiler();
Node node0 = compiler0.parseTestCode("[6");
node0.setType(120);
TypedScopeCreator typedScopeCreator0 = new TypedScopeCreator(compiler0);
// Undeclared exception!
try {
typedScopeCreator0.createScope(node0, (Scope) null);
fail("Expecting exception: RuntimeException");
} catch(RuntimeException e) {
//
// INTERNAL COMPILER ERROR.
// Please report this problem.
// null
//
verifyException("com.google.common.base.Preconditions", e);
}
}
@Test(timeout = 4000)
public void test03() throws Throwable {
Compiler compiler0 = new Compiler();
Node node0 = compiler0.parseTestCode("msg.miing.exponent");
TypedScopeCreator typedScopeCreator0 = new TypedScopeCreator(compiler0);
Scope scope0 = typedScopeCreator0.createScope(node0, (Scope) null);
Node node1 = Node.newString(105, "msg.miing.exponent", 2894, 2);
// Undeclared exception!
try {
typedScopeCreator0.createScope(node1, scope0);
fail("Expecting exception: RuntimeException");
} catch(RuntimeException e) {
//
// INTERNAL COMPILER ERROR.
// Please report this problem.
// null
//
verifyException("com.google.common.base.Preconditions", e);
}
}
@Test(timeout = 4000)
public void test04() throws Throwable {
Compiler compiler0 = new Compiler();
Node node0 = compiler0.parseTestCode("y68Y");
Scope scope0 = compiler0.getTopScope();
DefaultCodingConvention defaultCodingConvention0 = new DefaultCodingConvention();
TypedScopeCreator typedScopeCreator0 = new TypedScopeCreator(compiler0, defaultCodingConvention0);
Node[] nodeArray0 = new Node[1];
nodeArray0[0] = node0;
Node node1 = new Node(3209, nodeArray0, 1391, 1146);
// Undeclared exception!
try {
typedScopeCreator0.patchGlobalScope(scope0, node1);
fail("Expecting exception: IllegalStateException");
} catch(IllegalStateException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("com.google.common.base.Preconditions", e);
}
}
@Test(timeout = 4000)
public void test05() throws Throwable {
Compiler compiler0 = new Compiler((PrintStream) null);
Node node0 = compiler0.parseTestCode("com.gogle.javascript.jscomp.TypedScopeCreator$DeferredSetTyp");
Scope scope0 = compiler0.getTopScope();
GoogleCodingConvention googleCodingConvention0 = new GoogleCodingConvention();
TypedScopeCreator typedScopeCreator0 = new TypedScopeCreator(compiler0, googleCodingConvention0);
// Undeclared exception!
try {
typedScopeCreator0.patchGlobalScope(scope0, node0);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("com.google.common.base.Preconditions", e);
}
}
@Test(timeout = 4000)
public void test06() throws Throwable {
Compiler compiler0 = new Compiler();
Node node0 = compiler0.parseTestCode("[6");
node0.setType(118);
TypedScopeCreator typedScopeCreator0 = new TypedScopeCreator(compiler0);
// Undeclared exception!
try {
typedScopeCreator0.createScope(node0, (Scope) null);
fail("Expecting exception: RuntimeException");
} catch(RuntimeException e) {
//
// INTERNAL COMPILER ERROR.
// Please report this problem.
// null
//
verifyException("com.google.common.base.Preconditions", e);
}
}
@Test(timeout = 4000)
public void test07() throws Throwable {
Compiler compiler0 = new Compiler();
Node node0 = compiler0.parseTestCode("tfactory = ull");
TypedScopeCreator typedScopeCreator0 = new TypedScopeCreator(compiler0);
Scope scope0 = typedScopeCreator0.createScope(node0, (Scope) null);
assertFalse(scope0.isLocal());
}
@Test(timeout = 4000)
public void test08() throws Throwable {
Compiler compiler0 = new Compiler();
Node node0 = compiler0.parseTestCode("[6");
node0.setType(43);
TypedScopeCreator typedScopeCreator0 = new TypedScopeCreator(compiler0);
Scope scope0 = typedScopeCreator0.createScope(node0, (Scope) null);
assertEquals(32, scope0.getVarCount());
}
@Test(timeout = 4000)
public void test09() throws Throwable {
Compiler compiler0 = new Compiler();
Node node0 = compiler0.parseTestCode("factory == null");
Scope scope0 = compiler0.getTopScope();
TypedScopeCreator typedScopeCreator0 = new TypedScopeCreator(compiler0);
Node node1 = new Node(2, node0);
Node node2 = new Node(44, 17, 118);
node1.addChildBefore(node2, node0);
Scope scope1 = typedScopeCreator0.createScope(node1, scope0);
assertFalse(scope1.isLocal());
}
@Test(timeout = 4000)
public void test10() throws Throwable {
Compiler compiler0 = new Compiler();
Node node0 = compiler0.parseTestCode("[6");
node0.setType(47);
TypedScopeCreator typedScopeCreator0 = new TypedScopeCreator(compiler0);
Scope scope0 = typedScopeCreator0.createScope(node0, (Scope) null);
assertEquals(32, scope0.getVarCount());
}
@Test(timeout = 4000)
public void test11() throws Throwable {
Compiler compiler0 = new Compiler();
Node node0 = compiler0.parseTestCode("msg.miing.exponent");
node0.setType(69);
TypedScopeCreator typedScopeCreator0 = new TypedScopeCreator(compiler0);
Scope scope0 = typedScopeCreator0.createScope(node0, (Scope) null);
assertEquals(33, scope0.getVarCount());
}
@Test(timeout = 4000)
public void test12() throws Throwable {
Compiler compiler0 = new Compiler();
Node node0 = compiler0.parseTestCode("[6");
node0.setType(122);
ClosureCodingConvention closureCodingConvention0 = new ClosureCodingConvention();
TypedScopeCreator typedScopeCreator0 = new TypedScopeCreator(compiler0, closureCodingConvention0);
Scope scope0 = typedScopeCreator0.createScope(node0, (Scope) null);
assertEquals(32, scope0.getVarCount());
}
@Test(timeout = 4000)
public void test13() throws Throwable {
Compiler compiler0 = new Compiler();
Node node0 = compiler0.parseTestCode("omgogjavscriptjscoBp.TpedScopreator$DeferrdSetTyp");
GoogleCodingConvention googleCodingConvention0 = new GoogleCodingConvention();
Node node1 = new Node(1, node0, node0, node0, node0);
TypedScopeCreator typedScopeCreator0 = new TypedScopeCreator(compiler0, googleCodingConvention0);
Scope scope0 = typedScopeCreator0.createScope(node0, (Scope) null);
Scope scope1 = typedScopeCreator0.createScope(node1, scope0);
assertEquals(1, scope1.getVarCount());
assertEquals(33, scope0.getVarCount());
}
}
| Java | CL | f5a5cc8de863450f4f33a2d0347ecaeca14ecc141ce63e430e3e347a1b901aec |
package wpsr.engines.types;
import org.apache.uima.cas.Feature;
import org.apache.uima.cas.FeatureStructure;
import org.apache.uima.cas.Type;
import org.apache.uima.cas.impl.CASImpl;
import org.apache.uima.cas.impl.FSGenerator;
import org.apache.uima.cas.impl.FeatureImpl;
import org.apache.uima.cas.impl.TypeImpl;
import org.apache.uima.jcas.JCas;
import org.apache.uima.jcas.JCasRegistry;
import org.apache.uima.jcas.tcas.Annotation_Type;
public class RDFGeneric_Type extends Annotation_Type {
final Feature casFeat_scores;
final int casFeatCode_scores;
public final static int typeIndexID = RDFGeneric.typeIndexID;
public final static boolean featOkTst = JCasRegistry.getFeatOkTst("wpsr.engines.types.RDFGeneric");
@Override
protected FSGenerator getFSGenerator() {
return fsGenerator;
}
private final FSGenerator fsGenerator = new FSGenerator() {
public FeatureStructure createFS(int addr, CASImpl cas) {
if (RDFGeneric_Type.this.useExistingInstance) {
// Return eq fs instance if already created
FeatureStructure fs = RDFGeneric_Type.this.jcas
.getJfsFromCaddr(addr);
if (null == fs) {
fs = new RDFGeneric(addr,
RDFGeneric_Type.this);
RDFGeneric_Type.this.jcas.putJfsFromCaddr(addr,
fs);
return fs;
}
return fs;
} else {
return new RDFGeneric(addr,
RDFGeneric_Type.this);
}
}
};
public RDFGeneric_Type(JCas jcas, Type casType) {
super(jcas, casType);
casImpl.getFSClassRegistry().addGeneratorForType(
(TypeImpl) this.casType, getFSGenerator());
casFeat_scores = jcas.getRequiredFeatureDE(casType, "scores",
"wpsr.engines.types.RDFScore", featOkTst);
casFeatCode_scores = null == casFeat_scores ? JCas.INVALID_FEATURE_CODE
: ((FeatureImpl) casFeat_scores).getCode();
}
} | Java | CL | eb5beb50ccbb3959fc0635d7a764edc4a3b26d22d0bd4f3ef7ee505af106a51c |
/*
* Copyright (C) 2010 Brockmann Consult GmbH (info@brockmann-consult.de)
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program 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 this program; if not, see http://www.gnu.org/licenses/
*/
package org.esa.beam.dataio.netcdf;
import junit.framework.TestCase;
import org.esa.beam.dataio.netcdf.util.Constants;
import org.jdom.input.DOMBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Enumeration;
public class FormatNameTest extends TestCase {
protected void setUp() throws Exception {
}
protected void tearDown() throws Exception {
}
public void testFormatnameInModuleXmlIsTheSameAsInConstants() throws IOException {
final Enumeration<URL> urlEnumeration = ClassLoader.getSystemResources("module.xml");
InputStream stream = null;
while (urlEnumeration.hasMoreElements()) {
final URL url = (URL) urlEnumeration.nextElement();
System.out.println("url = " + url);
if (url.toString().contains("beam-netcdf")) {
stream = new FileInputStream(url.getFile());
System.out.println(" SELECTED");
break;
}
}
assertNotNull(stream);
final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
try {
final DocumentBuilder builder = factory.newDocumentBuilder();
final Document document = builder.parse(stream);
final DOMBuilder domBuilder = new DOMBuilder();
final org.jdom.Document jDoc = domBuilder.build(document);
final XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());
outputter.output(jDoc, System.out);
final NodeList byTagName = document.getElementsByTagName("formatName");
assertEquals(2, byTagName.getLength());
final Node node = byTagName.item(0);
assertNotNull(node);
assertEquals(Constants.FORMAT_NAME, node.getTextContent());
} catch (Exception e) {
fail("should not come here");
}
}
}
| Java | CL | e162cac1c2aeba0f34b0321673eb016b270215295af195b8288440e07d51713e |
package leetcode;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
* 300. Longest Increasing Subsequence
* Medium
* #Array, #Binary Search, #DP
*
* Given an integer array nums, return the length of the longest strictly increasing subsequence.
*
* A subsequence is a sequence that can be derived from an array by
* deleting some or no elements without changing the order of the remaining elements.
* For example, [3,6,2,7] is a subsequence of the array [0,3,1,6,2,2,7].
*
* Example 1:
* Input: nums = [10,9,2,5,3,7,101,18]
* Output: 4
* Explanation: The longest increasing subsequence is [2,3,7,101], therefore the length is 4.
*
* Example 2:
* Input: nums = [0,1,0,3,2,3]
* Output: 4
*
* Example 3:
* Input: nums = [7,7,7,7,7,7,7]
* Output: 1
*
*
* Constraints:
* 1 <= nums.length <= 2500
* -10^4 <= nums[i] <= 10^4
*
*
* Follow up: Can you come up with an algorithm that runs in O(n log(n)) time complexity?
*/
public class _0300_Longest_Increasing_Subsequence {
/*
暴力穷举 - 每个值都有 选 或者 不选 两个值, 对于 n 个值, 就有 n 个 2 相乘 -> O(2 ^ n)
DP - dp[i]: 到当前 i 位为止, 最小的 subsequence 的长度 -> O(n ^ 2)
- 当检查到 i 的时候
- 左指针 j 从 0 到 i - 1, 比较 dp[j] + 1 VS dp[i]
改进 - patience sorting - O(n * logn) - https://www.youtube.com/watch?v=l2rCz7skAlk&t=1s
dp[i]: subsequence 长度为 i 的时候, subsequence 的最后一位能取的最小值
例如 [10,9,2,5,3,7,101,18]. 依次读取每个值, 当读取到:
10 -> dp[1] = 10 (表示 subsequence 长度为 1 的话, 当前已知的 subsequence 最后一位的最小值为 10)
9 -> dp[1] = 9 -> [9]
2 -> dp[1] = 2 -> [2]
5 -> dp[2] = 5 -> [2], [*, 5]
3 -> dp[2] = 3 -> [2], [*, 3]
7 -> dp[3] = 7 -> [2], [*, 3], [*, *, 7]
101 -> dp[4] = 101 -> [2], [*, 3], [*, *, 7], [*, *, *, 101]
18 -> dp[4] = 18 -> [2], [*, 3], [*, *, 7], [*, *, *, 18]
每次读取, 使用二分法来决定 需要更新的 dp 下标
*/
/**
* DP - 时间 O(n^2), 空间 O(n)
*/
public int lengthOfLIS(int[] nums) {
if (nums == null) { return 0; }
int n = nums.length;
int[] dp = new int[n];
int ans = 1; // 从 1 开始, 因为最小的递增 subsequence 就是 只有一个元素 (另外, 也是为了特判)
// 所有值自己都可以作为 subsequence 的开头
Arrays.fill(dp, 1);
for (int i = 1; i < n; i++) {
for (int j = 0; j < i; j++) {
if (nums[j] < nums[i]) {
dp[i] = Math.max(dp[i], dp[j] + 1);
}
}
ans = Math.max(ans, dp[i]);
}
return ans;
}
/**
* patience sorting - 使用 list 来记录当前 pile
* 找寻 pile 的时候
* 1. 基本做法就是遍历, 如果
* - 如果 num > pile.get(i) => 跳过, 检查下一位 i + 1
* - 如果 num <= pile.get(i) => i 就是将被更新的 index
*/
public int lengthOfLIS_patience_sorting_list(int[] nums) {
if (nums == null) { return 0; }
List<Integer> pile = new ArrayList<>();
for (int num : nums) {
// 遍历法
//int index = findPile(pile, num);
// 使用 二分法 改进
/* 利用现成的 API
int index = Collections.binarySearch(pile, num);
if (index < 0) {
index = -(index + 1); // 这是 Collections.binarySearch 里未找到 target 时的返回值
}
*/
int index = binarySearch(pile, num);
if (index == pile.size()) { // 需要个新 pile
pile.add(num);
} else { // 更新现有 pile 即可
pile.set(index, num);
}
}
return pile.size();
}
/* 方法 1 - 遍历 */
public int findPile(List<Integer> pile, int target) {
for (int i = 0; i < pile.size(); i++) {
if (target <= pile.get(i)) { // 注意 是 <=, 遇到相同的时候, 并不需要个新的pile
return i;
}
}
return pile.size();
}
/* 改进 方法 2 - 二分法 */
public int binarySearch(List<Integer> pile, int target){
int l = 0, r = pile.size(); // 注意 这里 r 的取值, 不能时 pile.size() - 1
while (l < r) {
int mid = l + (r - l) / 2;
if (pile.get(mid) == target) {
return mid;
}
if (pile.get(mid) < target) {
l = mid + 1;
} else {
r = mid; // 注意 这里不能用 mid - 1, 因为可能会错误的跳过当前的 mid
}
}
return l;
}
/**
* patience sorting - 使用 dp array + 遍历 或者 二分法
*
* array 中并不是所有元素都有效, 所以 多加入一个 index_newPile 参数 (从它开始都是无效元素)
* 此解法用 1-indexed, 所以数组 从 1 到 index_newPile - 1 为有效元素
* 也就是, 共有 index_newPile - 1 个有效的 pile (此为返回值)
*/
public int lengthOfLIS_patience_sorting_array(int[] nums) {
if (nums == null) { return 0; }
int[] dp = new int[nums.length + 1]; // 这里使用 1-indexed, 为了方便理解. dp[1] 即 subsequence 长度为 1
int index_newPile = 1; // 1-indexed
for (int num : nums) {
// 遍历法
//int index_pileToUpdate = findPile(dp, 1, index_newPile, int num) {
// 使用 二分法 改进
/* 利用现成的 API
int index = Arrays.binarySearch(dp, 1, size, );
if (index < 0) {
index = -(index + 1); // 这是 Arrays.binarySearch 里未找到 target 时的返回值
}
*/
int index_pileToUpdate = binarySearch(dp, 1, index_newPile, num);
dp[index_pileToUpdate] = num;
// 别忘了, 如果开启个新 pile 时, 要更新 size (这里的 size 可以理解为 下一个 pile 的 下标)
if (index_pileToUpdate == index_newPile) {
index_newPile++;
}
}
return index_newPile - 1;
}
/* 方法 1 - 遍历 */
public int findPile(int[] dp, int start, int index_newPile, int target) {
for (int i = start; i < index_newPile; i++) { // 理论上, 这里必须用 <, 而不是 <=
if (target <= dp[i]) { // 注意 是 <=
return i;
}
}
return index_newPile;
}
/* 改进 方法 2 - 二分法 */
public int binarySearch(int[] dp, int start, int index_newPile, int target) {
while (start < index_newPile) {
int mid = start + (index_newPile - start) / 2;
if (dp[mid] == target) {
return mid;
}
if (dp[mid] < target) {
start = mid + 1;
} else {
index_newPile = mid; // 注意 这里不能用 mid - 1, 因为可能会错误的跳过当前的 mid
}
}
return start;
}
@Test
public void test1(){
int[] nums = {10,9,2,5,3,4};
org.junit.Assert.assertEquals(3, lengthOfLIS_patience_sorting_list(nums));
}
}
| Java | CL | f678f39d3c05b8c0f8cdddbfe2e15a18876d663ca4109086194e4683771d080f |
package by.segg3r.git;
import static org.testng.Assert.*;
import static org.mockito.Mockito.*;
import org.eclipse.jgit.api.Git;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import by.segg3r.Application;
public class GitRepositoryTest {
private GitRepository repository;
@BeforeClass
public void initMocks() {
GitRepository rawRepository = new GitRepository("remoteUrl", "repo");
this.repository = spy(rawRepository);
}
@AfterMethod
public void resetMocks() {
reset(repository);
}
@Test(description = "should create repository if not exists")
public void testInitializeCreate() throws GitRepositoryException {
doReturn(false).when(repository).exists();
Git createGit = mock(Git.class);
doReturn(createGit).when(repository).create();
Git openGit = mock(Git.class);
doReturn(openGit).when(repository).open();
repository.initialize();
verify(repository).create();
}
@Test(description = "should create repository if exists")
public void testInitializeOpen() throws GitRepositoryException {
doReturn(true).when(repository).exists();
Git createGit = mock(Git.class);
doReturn(createGit).when(repository).create();
Git openGit = mock(Git.class);
doReturn(openGit).when(repository).open();
repository.initialize();
verify(repository).open();
}
@Test(description = "should correctly build repository path")
public void testGetDeployPath() {
System.setProperty("user.dir", "D:/upgrade-server");
assertEquals(repository.getDeployDirectory(Application.CLIENT),
"D:/upgrade-server/repo/deploy/client");
}
}
| Java | CL | faa6442da720c8e87eaddadaa92da2b9245b4201eaf3caeb145ff18952b9449f |
package com.girl.common;
import org.codehaus.jackson.annotate.JsonIgnore;
import org.codehaus.jackson.map.annotate.JsonSerialize;
import java.io.Serializable;
/**
* 服务响应对象
*
* Created by girl on 2017/5/30.
*/
//当字段为空时,不放入响应对象中,即响应对象自动忽略该属性
@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
public class ServerResponse<T> implements Serializable {
private int status;// 响应状态码
private String msg;// 响应提示信息
private T data;// 返回数据
private ServerResponse(int status) {
this.status = status;
}
private ServerResponse(int status, T data) {
this.status = status;
this.data = data;
}
private ServerResponse(int status, String msg, T data) {
this.status = status;
this.msg = msg;
this.data = data;
}
private ServerResponse(int status, String msg) {
this.status = status;
this.msg = msg;
}
/**
* 响应状态是否成功
*
* @return
*/
@JsonIgnore
public boolean isSuccess() {
return this.status == ResponseCode.SUCCESS.getCode();
}
/**
* 对外开放get方法
*
* @return
*/
public int getStatus() {
return status;
}
public String getMsg() {
return msg;
}
public T getData() {
return data;
}
/**
* 创建响应成功的数据返回对象
*
* @param <T>
* @return
*/
public static <T> ServerResponse<T> createBySuccess() {
return new ServerResponse<T>(ResponseCode.SUCCESS.getCode());
}
public static <T> ServerResponse<T> createBySuccessMessage(String msg) {
return new ServerResponse<T>(ResponseCode.SUCCESS.getCode(), msg);
}
public static <T> ServerResponse<T> createBySuccess(T data) {
return new ServerResponse<T>(ResponseCode.SUCCESS.getCode(), data);
}
public static <T> ServerResponse<T> createBySuccess(String msg, T data) {
return new ServerResponse<T>(ResponseCode.SUCCESS.getCode(), msg , data);
}
/**
* 创建响应失败的数据返回对象
*
* @param <T>
* @return
*/
public static <T> ServerResponse<T> createByError() {
return new ServerResponse<T>(ResponseCode.ERROR.getCode(), ResponseCode.ERROR.getDesc());
}
public static <T> ServerResponse<T> createByErrorMessage(String errorMessage) {
return new ServerResponse<T>(ResponseCode.ERROR.getCode(), errorMessage);
}
/**
* 创建其他响应的数据返回对象
*
* @param errorCode
* @param errorMessage
* @param <T>
* @return
*/
public static <T> ServerResponse<T> createByErrorCodeMessage(int errorCode, String errorMessage) {
return new ServerResponse<T>(errorCode, errorMessage);
}
}
| Java | CL | d43752f49a0cf6ff7a6d09542e543de4ea208f6e92cead82bee4ae103a31d32e |
package com.jc.multipong.bootstrap.threads;
import com.google.gson.JsonSyntaxException;
import com.jc.multipong.bootstrap.entities.GameConnectionRequest;
import com.jc.multipong.bootstrap.entities.GetGameLogicRequest;
import com.jc.multipong.bootstrap.entities.PaddleMovementRequest;
import com.jc.multipong.bootstrap.entities.StartGameRequest;
import com.jc.multipong.bootstrap.game.GameManager;
import com.jc.multipong.bootstrap.nio.ClientMessage;
import com.jc.multipong.bootstrap.nio.ServerThread;
import com.jc.multipong.bootstrap.utils.JsonUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.nio.channels.SocketChannel;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
/**
* This class is responsible for:
* - queueing the socket activities received from the client
* - going through the queue and executing the activities
* - sending the response back to the client
* * * * *
*/
public class WorkerThread implements Runnable {
static final Logger logger = LoggerFactory.getLogger(WorkerThread.class);
private GameManager gameManager;
private ServerThread serverThread;
private BlockingQueue<ClientMessage> workingQueue;
private static WorkerThread instance;
public static WorkerThread getInstance() {
if (instance == null) {
synchronized (WorkerThread.class) {
if (instance == null) {
instance = new WorkerThread();
}
}
}
return instance;
}
public WorkerThread() {
this.gameManager = new GameManager();
this.workingQueue = new LinkedBlockingQueue<>();
}
public void run() {
logger.info("starting working thread...");
while (true) {
if (workingQueue.isEmpty()) {
continue;
}
while (!workingQueue.isEmpty()) {
executeTask(workingQueue.poll());
}
}
}
/**
* Enqueues a message for the worker thread
*
* @param socket
* @param data
* @param count
*/
public void submitTask(ServerThread serverThread, SocketChannel socket, byte[] data, int count) {
if (this.serverThread == null) {
this.serverThread = serverThread;
}
byte[] dataCopy = new byte[count];
System.arraycopy(data, 0, dataCopy, 0, count);
workingQueue.add(new ClientMessage(socket, new String(dataCopy)));
}
/**
* Handles the socket activity from the client
*
* @param clientMessage
*/
private void executeTask(ClientMessage clientMessage) {
String rawMessage = clientMessage.getMessage();
SocketChannel clientSocket = clientMessage.getSocket();
if (rawMessage != null) {
logger.debug("processing message(s): " + rawMessage);
String[] messages = rawMessage.split("\\r?\\n");
for (String message : messages) {
try {
Object responseMessage = null;
if (message.contains("GameConnectionRequest")) {
GameConnectionRequest gameConnectionRequest = JsonUtils.fromJson(message, GameConnectionRequest.class);
responseMessage = gameManager.connect(clientSocket, gameConnectionRequest);
} else if (message.contains("StartGameRequest")) {
StartGameRequest startGameRequest = JsonUtils.fromJson(message, StartGameRequest.class);
responseMessage = gameManager.startGameSign(startGameRequest);
} else if (message.contains("PaddleMovementRequest")) {
PaddleMovementRequest paddleMovementRequest = JsonUtils.fromJson(message, PaddleMovementRequest.class);
gameManager.registerInput(paddleMovementRequest);
} else if (message.contains("GetGameLogicRequest")) {
GetGameLogicRequest getGameLogicRequest = JsonUtils.fromJson(message, GetGameLogicRequest.class);
responseMessage = gameManager.getGameState(
getGameLogicRequest.gameId,
getGameLogicRequest.clientTick
);
} else {
logger.warn("message: " + message + " not recognized.");
}
if (responseMessage != null) {
serverThread.send(clientSocket, JsonUtils.toJson(responseMessage));
}
} catch (JsonSyntaxException mal) {
logger.error("Error reading json message: " + message, mal);
}
}
}
}
}
| Java | CL | 2019f54a2b5066b6b14be59c6449c0e42bbfbeca2ec8b0f48cbcf84853d7ddd5 |
/*******************************************************************************
* Copyright (c) 2005 Actuate Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Actuate Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.birt.report.engine.api.script;
import java.util.Locale;
import java.util.Map;
import java.io.Serializable;
/**
* An interface used to share information between the event methods in
* scripting. Gives access to report parameters and configuration values. Also
* provides a way for the report developer to register and retrieve custom
* properties.
*/
public interface IReportContext
{
/**
*
* @param name
* @return
*/
Object getParameterValue( String name );
/**
*
* @param name
* @param value
*/
void setParameterValue( String name, Object value );
/**
* always return NULL as 125963
* @param varName
* @return
* @deprecated 2.1
*/
Object getConfigVariableValue( String varName );
/**
*
* @return
*/
Locale getLocale( );
/**
*
* @return
*/
String getOutputFormat( );
/**
* Get the application context
*/
Map getAppContext( );
/**
* Get the http servlet request object
*
*/
Object getHttpServletRequest( );
/**
* Add the object to runtime scope. This object can only be retrieved in the
* same phase, i.e. it is not persisted between generation and presentation.
*/
void setGlobalVariable( String name, Object obj );
/**
* Remove an object from runtime scope.
*/
void deleteGlobalVariable( String name );
/**
* Retireve an object from runtime scope.
*/
Object getGlobalVariable( String name );
/**
* Add the object to report document scope. This object can be retrieved
* later. It is persisted between phases, i.e. between generation and
* presentation.
*/
void setPersistentGlobalVariable( String name, Serializable obj );
/**
* Remove an object from report document scope.
*/
void deletePersistentGlobalVariable( String name );
/**
* Retireve an object from report document scope.
*/
Object getPersistentGlobalVariable( String name );
/**
* Finds user-defined messages for the current thread's locale.
*/
String getMessage( String key );
/**
* Finds user-defined messages for the given locale.
*/
String getMessage( String key, Locale locale );
/**
* Finds user-defined messages for the current thread's locale
*/
String getMessage( String key, Object[] params );
/**
* Finds user-defined messages for the given locale using parameters
*/
String getMessage( String key, Locale locale, Object[] params );
}
| Java | CL | 34a4f720a41521dae6672fcba03715790bd4f94a4b97753b5b7f3263af340e60 |
package edu.duke.raft;
import java.util.Timer;
import java.util.TimerTask;
import java.util.List;
import java.util.LinkedList;
public class FollowerMode extends RaftMode {
//Election timer
Timer electionTimer;
public void go () {
synchronized (mLock) {
int term = mConfig.getCurrentTerm();
System.out.println ("S" +
mID +
"." +
term +
": switched to follower mode.");
//Add election timer to see if leader failed
electionTimer = scheduleTimer((long) (Math.random()*(ELECTION_TIMEOUT_MAX - ELECTION_TIMEOUT_MIN) + ELECTION_TIMEOUT_MIN), 1);
}
}
// @param candidate’s term
// @param candidate requesting vote
// @param index of candidate’s last log entry
// @param term of candidate’s last log entry
// @return 0, if server votes for candidate; otherwise, server's
// current term
public int requestVote (int candidateTerm,
int candidateID,
int lastLogIndex,
int lastLogTerm) {
synchronized (mLock) {
int term = mConfig.getCurrentTerm();
//If candidate's term is greater than server's term, update server term
if(candidateTerm > term) {
mConfig.setCurrentTerm(candidateTerm, 0);
term = mConfig.getCurrentTerm();
}
//If candidate's term is less than server's term, reject vote
if(candidateTerm < term)
return term;
//If server did not vote for anyone or voted for the candidate
//AND candidate's log is at least up to date as the servers, then approve vote
if((mConfig.getVotedFor() == 0 || mConfig.getVotedFor() == candidateID)) {
if(lastLogTerm > mLog.getLastTerm()) {
electionTimer.cancel();
electionTimer = scheduleTimer((long) (Math.random()*(ELECTION_TIMEOUT_MAX - ELECTION_TIMEOUT_MIN) + ELECTION_TIMEOUT_MIN), 1);
mConfig.setCurrentTerm(term, candidateID);
return 0;
}
if(lastLogTerm == mLog.getLastTerm()) {
if(lastLogIndex >= mLog.getLastIndex()) {
electionTimer.cancel();
electionTimer = scheduleTimer((long) (Math.random()*(ELECTION_TIMEOUT_MAX - ELECTION_TIMEOUT_MIN) + ELECTION_TIMEOUT_MIN), 1);
mConfig.setCurrentTerm(term, candidateID);
return 0;
}
}
}
return term;
}
}
// @param leader’s term
// @param current leader
// @param index of log entry before entries to append
// @param term of log entry before entries to append
// @param entries to append (in order of 0 to append.length-1)
// @param index of highest committed entry
// @return 0, if server appended entries; otherwise, server's
// current term
public int appendEntries (int leaderTerm,
int leaderID,
int prevLogIndex,
int prevLogTerm,
Entry[] entries,
int leaderCommit) {
synchronized (mLock) {
int term = mConfig.getCurrentTerm();
//If leader's term is less than server's term, reject append
if(leaderTerm < term) {
//System.out.println(mID + " rejected " + leaderID + " in follower");
return term;
}
electionTimer.cancel();
electionTimer = scheduleTimer((long) (Math.random()*(ELECTION_TIMEOUT_MAX - ELECTION_TIMEOUT_MIN) + ELECTION_TIMEOUT_MIN), 1);
//If leader's term is greater than server's term, update server term
if(leaderTerm > term)
mConfig.setCurrentTerm(leaderTerm, 0);
//Check if it is a hearbeat
/*
if(entries == null) {
//System.out.println(mID + " recevied heartbeat");
//Reset election timer
electionTimer.cancel();
electionTimer = scheduleTimer((long) (Math.random()*(ELECTION_TIMEOUT_MAX - ELECTION_TIMEOUT_MIN) + ELECTION_TIMEOUT_MIN), 1);
return 0;
}
*/
//Handle non-heatbeat
if(mLog.getEntry(prevLogIndex) == null) {
return term;
}
if(mLog.getEntry(prevLogIndex).term != prevLogTerm) {
return term;
}
mLog.insert(entries, prevLogIndex, prevLogTerm);
if(leaderCommit > mCommitIndex) {
mCommitIndex = leaderCommit;
}
return 0;
}
}
// @param id of the timer that timed out
public void handleTimeout (int timerID) {
synchronized (mLock) {
//Election timer case
if(timerID == 1) {
//Increment term
mConfig.setCurrentTerm(mConfig.getCurrentTerm() + 1, 0);
//Change to candidate mode
RaftServerImpl.setMode(new CandidateMode());
}
}
}
}
| Java | CL | a08611fac2d6c1feb3aae17b645c6420dc424290c1039235d577b580c57a0445 |
package ca.landonjw.remoraids.api.rewards;
import java.util.List;
import ca.landonjw.remoraids.api.battles.IBossBattle;
import ca.landonjw.remoraids.api.rewards.contents.IRewardContent;
import ca.landonjw.remoraids.api.util.DataSerializable;
import net.minecraft.entity.player.EntityPlayerMP;
/**
* Interface for a reward for a boss.
* When a boss dies, these rewards may be distributed.
*
* @author landonjw
* @since 1.0.0
*/
public interface IReward extends DataSerializable {
/**
* Distributes the rewards to players who battled a boss.
*
* @param player the player to distribute reward to.
*/
void distributeReward(EntityPlayerMP player);
/**
* Gets all players that will receive the reward.
*
* @param battle battle to get winners for.
*
* @return list of players that will receive the reward upon distribution.
*/
List<EntityPlayerMP> getWinnersList(IBossBattle battle);
/**
* Gets the contents of the reward.
*
* @return the contents of the reward.
*/
List<IRewardContent> getContents();
/**
* Adds contents to the reward.
*
* @param contents contents to add
*/
void addContents(IRewardContent... contents);
/**
* Removes contents from the reward.
*
* @param contents contents to remove
*/
void removeContents(IRewardContent... contents);
/**
* Clears all contents from the reward.
*/
void clearContents();
/**
* Gets a description of the reward and it's contents.
*
* @return A description of the reward and it's contents.
*/
String getDescription();
int getPriority();
} | Java | CL | b59e7efe81812995683142fb39f5b55313d73958425ae23aa914d3e80ce5c676 |
package com.janknspank.common;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
/**
* Generic utility class for collecting many strings with associated integer
* values and retaining only the N with the highest values. Basically, this
* is an semi-efficient way to implement a "top 10" list. Usage:
*
* <code>
* TopList<String, Integer> t = new TopList<>(3);
* t.add("ten", 10);
* t.add("eleven", 11);
* t.add("twelve", 12);
* t.add("two", 2);
* for (String topThree : t.getKeys()) {
* // Print out "twelve", "eleven", "ten".
* }
* </code>
*
* NOTE(jonemerson): Turns out this is a generally useful class and I should
* re-implement it with a linked HashMap, though LinkedHashMap doesn't allow
* for arbitrary input positioning, so I'd have to probably build my own.
*/
public class TopList<T, U extends Number> implements Iterable<T> {
private final int maxSize;
private U smallestValue = null;
private HashMap<T, U> values = Maps.newHashMap();
public TopList(int maxSize) {
this.maxSize = maxSize;
}
@SuppressWarnings("unchecked")
public synchronized void add(T key, U value) {
if (values.containsKey(key)) {
values.put(key, value);
return;
}
// If we're already at capacity...
if (values.size() == maxSize) {
if (smallestValue == null ||
((Comparable<U>) value).compareTo(smallestValue) <= 0) {
// Do nothing if the new value isn't bigger than what we've got.
return;
}
// Else, remove the smallest thing we've got.
for (T existingKey : values.keySet()) {
if (values.get(existingKey).equals(smallestValue)) {
values.remove(existingKey);
break;
}
}
// And update our notion of what the smallest thing is.
smallestValue = value;
for (U existingValue : values.values()) {
if (((Comparable<U>) existingValue).compareTo(smallestValue) < 0) {
smallestValue = existingValue;
}
}
} else {
if (values.size() == 0 || ((Comparable<U>) value).compareTo(smallestValue) < 0) {
smallestValue = value;
}
}
values.put(key, value);
}
/**
* Returns all the keys we're currently tracking, sorted descendingly by
* their underlying values.
*/
public synchronized List<T> getKeys() {
List<T> keyList = Lists.newArrayList(values.keySet());
Collections.sort(keyList, new Comparator<T>() {
@SuppressWarnings("unchecked")
@Override
public int compare(T t1, T t2) {
return ((Comparable<U>) values.get(t2)).compareTo(values.get(t1));
}
});
return keyList;
}
/**
* Returns the "i"th top-most key in this top list. Note: This isn't at all
* efficient.
*/
public T getKey(int i) {
return Iterables.get(getKeys(), i);
}
public U getValue(T key) {
return values.containsKey(key) ? values.get(key) : null;
}
@Override
public Iterator<T> iterator() {
return getKeys().iterator();
}
public int size() {
return values.size();
}
public Map<T, U> toMap() {
ImmutableMap.Builder<T, U> builder = ImmutableMap.<T, U>builder();
for (Map.Entry<T, U> entry : values.entrySet()) {
builder.put(entry.getKey(), entry.getValue());
}
return builder.build();
}
}
| Java | CL | dcba39abf0019251b21663b30f3b49c0f7d8a52e51d50f2f4c6fbc41afc6b0a6 |
package com.nuno1212s.bungee.loginhandler.events;
import com.nuno1212s.bungee.loginhandler.SessionHandler;
import com.nuno1212s.bungee.loginhandler.tasks.AsyncPremiumCheck;
import com.nuno1212s.bungee.loginhandler.tasks.ForceLoginTask;
import com.nuno1212s.bungee.main.Main;
import net.md_5.bungee.api.ProxyServer;
import net.md_5.bungee.api.connection.ProxiedPlayer;
import net.md_5.bungee.api.event.PlayerDisconnectEvent;
import net.md_5.bungee.api.event.PreLoginEvent;
import net.md_5.bungee.api.event.ServerConnectedEvent;
import net.md_5.bungee.api.plugin.Listener;
import net.md_5.bungee.event.EventHandler;
/**
* Handles player connections
*/
public class PlayerLoginEvent implements Listener {
private Main m;
public PlayerLoginEvent(Main m) {
this.m = m;
}
@EventHandler
public void loginEvent(PreLoginEvent e) {
if (e.isCancelled()) {
return;
}
e.registerIntent(Main.getPlugin());
ProxyServer.getInstance().getScheduler().runAsync(Main.getPlugin(), new AsyncPremiumCheck(m, e));
}
@EventHandler
public void serverConnect(ServerConnectedEvent serverConnect) {
ProxiedPlayer p = serverConnect.getPlayer();
ForceLoginTask task = new ForceLoginTask(m, p, serverConnect.getServer());
ProxyServer.getInstance().getScheduler().runAsync(Main.getPlugin(), task);
}
@EventHandler
public void onDisconnect(PlayerDisconnectEvent dc) {
ProxiedPlayer player = dc.getPlayer();
//m.getSession().remove(player.getPendingConnection());
SessionHandler.getIns().removeSession(player.getUniqueId());
}
}
| Java | CL | fca0aa85036291379c3da0e15afb007f20edfea0b7355168fe5d019e5afe4ab1 |
/*
* Copyright 2020-2020 the nameserviceangent team
*
* 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.github.bmhm.nameserviceagent.api;
import java.net.InetAddress;
import java.net.UnknownHostException;
/**
* Basic interface for returning addresses for a host lookup or a hostname (reverse lookup) for an address.
*
* <p><strong>Implementation notice:</strong> Do not use this directly.
* You must use the {@link AbstractProxyNameService} instead. The agent depends on this.</p>
*/
public interface NameService {
/**
* Lookup a host mapping by name. Retrieve the IP addresses associated with a host
*
* @param host the specified hostname to resolve.
* @return array of IP addresses for the requested host
* @throws UnknownHostException if no IP address for the {@code host} could be found
*/
InetAddress[] lookupAllHostAddr(final String host) throws UnknownHostException;
/**
* Lookup the host corresponding to the IP address provided.
*
* <p>This method is called by {@link java.net.InetAddress}{@code #getHostFromNameService(InetAddress, boolean)}.</p>
*
* @param addr byte array representing an IP address
* @return {@code String} representing the host name mapping
* @throws UnknownHostException if no host found for the specified IP address
*/
String getHostByAddr(final byte[] addr) throws UnknownHostException;
}
| Java | CL | c06cc31a96d12d7fd2046e06cf2efc664c35182500b10bc6d90bfb9a36255965 |
/*******************************************************************************
* Copyright (c) 2006-2007 Koji Hisano <hisano@gmail.com> - UBION Inc. Developer
* Copyright (c) 2006-2007 UBION Inc. <http://www.ubion.co.jp/>
*
* Copyright (c) 2006-2007 Skype Technologies S.A. <http://www.skype.com/>
*
* Skype4Java is licensed under either the Apache License, Version 2.0 or
* the Eclipse Public License v1.0.
* You may use it freely in commercial and non-commercial products.
* You may obtain a copy of the licenses at
*
* the Apache License - http://www.apache.org/licenses/LICENSE-2.0
* the Eclipse Public License - http://www.eclipse.org/legal/epl-v10.html
*
* If it is possible to cooperate with the publicity of Skype4Java, please add
* links to the Skype4Java web site <https://developer.skype.com/wiki/Java_API>
* in your web site or documents.
*
* Contributors:
* Koji Hisano - initial API and implementation
* Gabriel Takeuchi - Ignored non working tests, fixed some, removed warnings
******************************************************************************/
package com.skype;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
@Ignore
public final class SkypeExceptionHandlerTest {
@Test
public void testDefaultHanlder() throws Exception {
fireHanlderWithSkypeException();
TestUtils.showCheckDialog("The default output contains a stack trace?");
}
@Test
public void testSetHandler() throws Exception {
final Object wait = new Object();
final boolean[] result = new boolean[1];
Skype.setSkypeExceptionHandler(new SkypeExceptionHandler() {
public void uncaughtExceptionHappened(Throwable e) {
result[0] = true;
synchronized (wait) {
wait.notify();
}
}
});
synchronized (wait) {
fireHanlderWithSkypeException();
try {
wait.wait();
} catch (InterruptedException e) {
}
}
Assert.assertTrue(result[0]);
Skype.setSkypeExceptionHandler(null);
fireHanlderWithSkypeException();
TestUtils.showCheckDialog("The default output contains a stack trace?");
}
private void fireHanlderWithSkypeException() throws SkypeException {
final Object wait = new Object();
ChatMessageListener listener = new ChatMessageAdapter() {
@Override
public void chatMessageSent(ChatMessage sentChatMessage) throws SkypeException {
try {
throw new SkypeException();
} finally {
synchronized (wait) {
wait.notify();
}
}
}
};
Skype.addChatMessageListener(listener);
synchronized (wait) {
TestData.getFriend().send("a message for a method test");
try {
wait.wait();
} catch (InterruptedException e) {
}
}
Skype.removeChatMessageListener(listener);
}
}
| Java | CL | bcac5bb6ceae555bc0ac9a9a226c147c41a3a62a11c805ce5abf1f20684102d6 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.