hexsha
stringlengths
40
40
size
int64
8
1.04M
content
stringlengths
8
1.04M
avg_line_length
float64
2.24
100
max_line_length
int64
4
1k
alphanum_fraction
float64
0.25
0.97
099ba111a6cbb25eedbd16d5d5cf068f69266be9
663
package com.tss.excel_to_db.vo; import lombok.Data; /** * @Description: 值对象 * @Author: xiangjun.yang * @Date: Created in 2018-2-6 */ @Data public class ExcelModelVo { // 格式校验成功的数据大小 private long succSize; // 格式校验失败的数据大小 private long failSize; // 导入数据库失败的数据大小 private long failToDBSize; // 导入数据库成功的数据大小; private long succToDBSize; public ExcelModelVo(long succSize, long failSize, long failToDBSize) { this.succSize = succSize; this.failSize = failSize; this.failToDBSize = failToDBSize; // 校验成功的数据大小 - 导入数据库失败的数据大小 =成功导入的数据大小 this.succToDBSize = succSize - failToDBSize; } }
22.862069
74
0.666667
81f2b7881281653f13dbc45f77b3f6cc8ef873a3
467
package org.highmed.dsf.fhir.service; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; public class SnapshotInfo { private final SnapshotDependencies dependencies; @JsonCreator public SnapshotInfo(@JsonProperty("dependencies") SnapshotDependencies dependencies) { this.dependencies = dependencies; } public SnapshotDependencies getDependencies() { return dependencies; } }
22.238095
86
0.777302
e938dca086c2278c2c906617311dae7ce5d8a690
3,236
/* * Copyright 2020 ConsenSys AG. * * 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 tech.pegasys.peeps.privacy.model; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertThrows; import org.junit.jupiter.api.Test; public class PrivacyAddressTest { @Test public void missingIdMustException() { final Exception exception = assertThrows( IllegalArgumentException.class, () -> { new PrivacyAddreess(null); }); assertThat(exception.getMessage()).isEqualTo("Address is mandatory"); } @Test public void hashCodeMustMatchIdHashCode() { final String id = "A very unique address"; final PrivacyAddreess address = new PrivacyAddreess(id); assertThat(address.hashCode()).isEqualTo(id.hashCode()); } @Test public void selfReferenceEqualityMustSucced() { final PrivacyAddreess id = new PrivacyAddreess("I am a real address!"); assertThat(id).isEqualTo(id); } @Test public void identicalIdEqualityMustSucced() { final String id = "A not so unique address"; final PrivacyAddreess addressAlpha = new PrivacyAddreess(id); final PrivacyAddreess addressdBeta = new PrivacyAddreess(id); final boolean isEquals = addressAlpha.equals(addressdBeta); assertThat(isEquals).isTrue(); } @Test public void noReferenceEqualityMustFail() { final PrivacyAddreess address = new PrivacyAddreess("I am a real address value!"); final boolean isEquals = address.equals(null); assertThat(isEquals).isFalse(); } @Test public void differentTypeEqualityMustFail() { final PrivacyAddreess address = new PrivacyAddreess("I am a real address value!"); final Object other = "Type of String"; final boolean isEquals = address.equals(other); assertThat(isEquals).isFalse(); } @Test public void differentIdEqualityMustFail() { final PrivacyAddreess addressAlpha = new PrivacyAddreess("First address"); final PrivacyAddreess addressBeta = new PrivacyAddreess("Second address"); final boolean isEquals = addressAlpha.equals(addressBeta); assertThat(isEquals).isFalse(); } @Test public void hashCodeMustEqualIdHashCode() { final String id = "The one and only address!"; final PrivacyAddreess address = new PrivacyAddreess(id); final int expected = id.hashCode(); final int actual = address.hashCode(); assertThat(actual).isEqualTo(expected); } @Test public void getMustReturnAddress() { final String id = "The address!"; final PrivacyAddreess address = new PrivacyAddreess(id); final String actual = address.get(); assertThat(actual).isEqualTo(id); } }
29.153153
118
0.717862
b75874668b904e3a8e4d06c89e8f650a9f31e38d
1,792
package kentico.kentico_android_tv_app.details.cafe; import android.content.Context; import android.support.v17.leanback.widget.Presenter; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import kentico.kentico_android_tv_app.R; import kentico.kentico_android_tv_app.data.models.Cafe; import kentico.kentico_android_tv_app.utils.ResourceCache; /** * Created by Juraj on 07.04.2018. */ public class CafeDetailsDescription extends Presenter { private ResourceCache mResourceCache = new ResourceCache(); private Context mContext; CafeDetailsDescription(Context context) { mContext = context; } @Override public Presenter.ViewHolder onCreateViewHolder(ViewGroup parent) { View view = LayoutInflater.from(mContext).inflate(R.layout.detail_view_layout, null); return new Presenter.ViewHolder(view); } @Override public void onBindViewHolder(Presenter.ViewHolder viewHolder, Object item) { TextView primaryText = mResourceCache.getViewById(viewHolder.view, R.id.primary_text); TextView secondaryText = mResourceCache.getViewById(viewHolder.view, R.id.secondary_text_first); TextView extraText = mResourceCache.getViewById(viewHolder.view, R.id.extra_text); Cafe cafe = (Cafe) item; primaryText.setText(cafe.getState()); secondaryText.setText(String.valueOf(cafe.getAddress() + ", " + cafe.getZipCode())); extraText.setText(String.valueOf("Phone: " + cafe.getPhone() + System.lineSeparator() + System.lineSeparator() + "Email: " + cafe.getEmail())); } @Override public void onUnbindViewHolder(Presenter.ViewHolder viewHolder) { } }
33.811321
104
0.72433
336a94a8eb7d1b947c70fe860060b7412665e21f
783
package matgm50.jrose.core.res; import matgm50.jrose.core.gl.Texture; import org.lwjgl.BufferUtils; import org.lwjgl.stb.STBImage; import java.nio.ByteBuffer; import java.nio.IntBuffer; public class TextureProvider extends ResourceProvider<Texture> { public TextureProvider(String root) { super(root); } @Override public Texture createFromRaw(Raw raw) { ByteBuffer buffer = raw.asByteBuffer(); IntBuffer w = BufferUtils.createIntBuffer(1); IntBuffer h = BufferUtils.createIntBuffer(1); IntBuffer c = BufferUtils.createIntBuffer(1); STBImage.stbi_set_flip_vertically_on_load(true); ByteBuffer image = STBImage.stbi_load_from_memory(buffer, w, h, c, 4); return new Texture(image, w.get(), h.get()); } }
26.1
78
0.711367
80570f28b3fba7bce2ab84e22c40403725de710b
1,805
/* * 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.iotdb.db.qp.logical.sys; import org.apache.iotdb.db.exception.query.QueryProcessException; import org.apache.iotdb.db.qp.logical.Operator; import org.apache.iotdb.db.qp.physical.PhysicalPlan; import org.apache.iotdb.db.qp.physical.sys.SetSystemModePlan; import org.apache.iotdb.db.qp.strategy.PhysicalGenerator; public class SetSystemModeOperator extends Operator { private boolean isReadOnly; /** * The operator for set system to readonly / writable statement. * * @param tokenIntType tokenIntType. * @param isReadOnly isReadOnly. */ public SetSystemModeOperator(int tokenIntType, boolean isReadOnly) { super(tokenIntType); this.isReadOnly = isReadOnly; operatorType = OperatorType.SET_SYSTEM_MODE; } public boolean isReadOnly() { return isReadOnly; } @Override public PhysicalPlan generatePhysicalPlan(PhysicalGenerator generator) throws QueryProcessException { return new SetSystemModePlan(isReadOnly); } }
33.425926
71
0.759557
2b478649f4170759063bd596a147c57d9a45a64f
4,018
package com.berniac.vocalwarmup.sequence.sequencer; import com.berniac.vocalwarmup.sequence.Direction; import java.util.Comparator; import java.util.Set; import java.util.TreeSet; /** * Created by Mikhail Lipkovich on 6/01/2018. */ public class WarmUpStep { public static final WarmUpStep FINAL_STEP = new WarmUpStep(-1, -1, -1, null); private Direction direction; private int tonic; private int forwardTonic; private int backwardTonic; private Set<MidiEventShort> baseEvents; private Set<MidiEventShort> adjustmentForwardEvents; private Set<MidiEventShort> adjustmentBackwardEvents; private Set<MidiEventShort> adjustmentRepeatEvents; WarmUpStep(int tonic, int forwardTonic, int backwardTonic, Direction direction) { this.tonic = tonic; this.forwardTonic = forwardTonic; this.backwardTonic = backwardTonic; this.direction = direction; this.baseEvents = new TreeSet<>(new EventsComparator()); this.adjustmentForwardEvents = new TreeSet<>(new EventsComparator()); this.adjustmentBackwardEvents = new TreeSet<>(new EventsComparator()); this.adjustmentRepeatEvents = new TreeSet<>(new EventsComparator()); } public Direction getDirection() { return direction; } public int getTonic() { return tonic; } public int getForwardTonic() { return forwardTonic; } public int getBackwardTonic() { return backwardTonic; } public Set<MidiEventShort> getBaseEvents() { return baseEvents; } public Set<MidiEventShort> getAdjustmentForwardEvents() { return adjustmentForwardEvents; } public Set<MidiEventShort> getAdjustmentBackwardEvents() { return adjustmentBackwardEvents; } public Set<MidiEventShort> getAdjustmentRepeatEvents() { return adjustmentRepeatEvents; } void setTonic(int tonic) { this.tonic = tonic; } void addBaseEvent(MidiEventShort event) { baseEvents.add(event); } void addAdjustmentForwardEvent(MidiEventShort event) { adjustmentForwardEvents.add(event); } void addAdjustmentBackwardEvent(MidiEventShort event) { adjustmentBackwardEvents.add(event); } void addAdjustmentRepeatEvent(MidiEventShort event) { adjustmentRepeatEvents.add(event); } private static class EventsComparator implements Comparator<MidiEventShort> { @Override public int compare(MidiEventShort event1, MidiEventShort event2) { if (event1.equals(event2)) { return 0; } return (event1.getPosition() < event2.getPosition()) ? -1 : 1; } } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; WarmUpStep that = (WarmUpStep) o; if (tonic != that.tonic) return false; if (forwardTonic != that.forwardTonic) return false; if (backwardTonic != that.backwardTonic) return false; if (direction != that.direction) return false; if (!baseEvents.equals(that.baseEvents)) return false; if (!adjustmentForwardEvents.equals(that.adjustmentForwardEvents)) return false; if (!adjustmentBackwardEvents.equals(that.adjustmentBackwardEvents)) return false; return adjustmentRepeatEvents.equals(that.adjustmentRepeatEvents); } @Override public int hashCode() { int result = direction != null ? direction.hashCode() : 0; result = 31 * result + tonic; result = 31 * result + forwardTonic; result = 31 * result + backwardTonic; result = 31 * result + baseEvents.hashCode(); result = 31 * result + adjustmentForwardEvents.hashCode(); result = 31 * result + adjustmentBackwardEvents.hashCode(); result = 31 * result + adjustmentRepeatEvents.hashCode(); return result; } }
31.147287
90
0.666501
735e9b9bcceb65ab1106f518fc3f43277c6a42da
1,424
package monads; import java.io.*; import java.util.*; public class Words { public static void main(String[] args) throws Exception { Set<String> keywords = new HashSet<String>(); BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader(Words.class.getResourceAsStream("/keywords.txt"))); String line; while ((line = reader.readLine()) != null) { keywords.add(line); } } finally { if (reader != null) { reader.close(); } } List<String> words = new LinkedList<String>(); for (String arg : args) { String[] parts = arg.split(" "); for (String part : parts) { if (part.length() > 0) { words.add(part); } } } List<String> foundKeywords = new LinkedList<String>(); for (String word : words) { if (keywords.contains(word.toLowerCase())) { foundKeywords.add(word); } } System.out.println("All keywords: " + foundKeywords); List<String> upperCaseWords = new LinkedList<String>(); for (String word : words) { upperCaseWords.add(word.toUpperCase()); } System.out.println("All words in uppercase: " + upperCaseWords); } }
30.297872
113
0.514045
e84b728bc46953ffcd0bed93d39f45bf07ef3314
1,409
package com.ekwing.databindinglist; import androidx.appcompat.app.AppCompatActivity; import androidx.databinding.DataBindingUtil; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.os.Bundle; import com.ekwing.databindinglist.databinding.ActivityMainBinding; import java.util.ArrayList; import java.util.List; public class MainActivity extends AppCompatActivity { ActivityMainBinding mBinding; List<UserCenter> mDataList=new ArrayList<>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mBinding= DataBindingUtil.setContentView(this, R.layout.activity_main); initData(); RecyclerView.LayoutManager layoutManager=new LinearLayoutManager(this); ((LinearLayoutManager) layoutManager).setOrientation(LinearLayoutManager.HORIZONTAL); mBinding.rvList.setLayoutManager(layoutManager); RecyclerViewAdapter recyclerViewAdapter=new RecyclerViewAdapter(mDataList); mBinding.rvList.setAdapter(recyclerViewAdapter); } private void initData() { for (int i = 0; i <10 ; i++) { UserCenter userCenter=new UserCenter("海波",""); UserCenter userCenter1=new UserCenter("java",""); mDataList.add(userCenter); mDataList.add(userCenter1); } } }
32.767442
93
0.735273
d0d968c01e0a934c1311a830c65314c9a3e38c41
820
package com.georgebindragon.base.receiver; import android.content.Context; import android.content.Intent; import com.georgebindragon.base.monitor.BaseListenerMonitor; import com.georgebindragon.base.receiver.callbacks.IBaseReceiverCallBack; import com.georgebindragon.base.utils.EmptyUtil; import java.util.Queue; /** * 创建人:George * 类名称:BroadcastMonitor * 类概述: * 详细描述: * * * 修改人: * 修改时间: * 修改备注: */ class BroadcastMonitor extends BaseListenerMonitor<IBaseReceiverCallBack> { void notifyListeners(Context context, Intent intent) { final Queue<IBaseReceiverCallBack> listeners = getListenerList(); if (EmptyUtil.notEmpty(listeners)) { for (IBaseReceiverCallBack listener : listeners) { if (EmptyUtil.notEmpty(listener)) { listener.onReceive(context, intent); } } } } }
19.52381
73
0.745122
160b2d437a88b7e37f3b3357a67589a4fb4b950d
2,963
package com.lgy.oms.disruptor.audit; import com.alibaba.fastjson.JSON; import com.lgy.framework.util.ShiroUtils; import com.lgy.system.domain.SysUser; import com.lmax.disruptor.RingBuffer; import com.lmax.disruptor.SleepingWaitStrategy; import com.lmax.disruptor.dsl.Disruptor; import com.lmax.disruptor.dsl.ProducerType; import com.lmax.disruptor.util.DaemonThreadFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; /** * @Author LGy * @Date 2019/12/30 * @Description 审单Util */ @Service public class AuditDisruptorUtil { private static Logger logger = LoggerFactory.getLogger(AuditDisruptorUtil.class); private Disruptor<AuditOrderEvent> disruptor; private static final int RING_BUFFER_SIZE = 1024; private static final int THREAD_COUNT = 5; @Autowired private AuditHandler auditHandler; private Producer producer; /** * 销毁前执行 */ @PreDestroy public void destroy() { disruptor.shutdown(); logger.info("disruptor of auditEvent shutdown"); } /** * 启动执行 */ @PostConstruct public void afterPropertiesSet() { disruptor = new Disruptor<>( AuditOrderEvent::new, RING_BUFFER_SIZE, DaemonThreadFactory.INSTANCE, ProducerType.SINGLE, new SleepingWaitStrategy() ); //校验地址创建消费者组 AuditHandler[] auditHandlers = new AuditHandler[THREAD_COUNT]; for (int i = 0; i < THREAD_COUNT; i++) { auditHandlers[i] = auditHandler; } //创建消费者组 disruptor.handleEventsWithWorkerPool(auditHandlers); //异常处理 disruptor.setDefaultExceptionHandler(new AuditExceptionHandler()); //启动disruptor disruptor.start(); this.producer = new Producer(disruptor.getRingBuffer()); logger.info("disruptor of auditEvent start"); } Producer getProducer() { return producer; } public class Producer { private RingBuffer<AuditOrderEvent> ringBuffer; Producer(RingBuffer<AuditOrderEvent> ringBuffer) { this.ringBuffer = ringBuffer; } public void onData(AuditOrderEvent t) { logger.debug("publish auditEvent [{}]", JSON.toJSONString(t.getOrderMain().getOrderId())); long sequence = ringBuffer.next(); try { AuditOrderEvent t1 = ringBuffer.get(sequence); BeanUtils.copyProperties(t, t1); //设置用户信息,用于线程切换 SysUser sysUser = ShiroUtils.getSysUser(); t1.setSysUser(sysUser); } finally { ringBuffer.publish(sequence); } } } }
27.435185
102
0.648329
fc46a336f1c9937d425e828c99aa9a584bd49838
3,341
package com.elmakers.mine.bukkit.world.populator; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.logging.Level; import javax.annotation.Nullable; import org.bukkit.configuration.ConfigurationSection; import com.elmakers.mine.bukkit.magic.MagicController; public class MagicChunkHandler { public static final String BUILTIN_CLASSPATH = "com.elmakers.mine.bukkit.world.populator.builtin"; private final MagicController controller; private final List<MagicChunkPopulator> chunkPopulators = new ArrayList<MagicChunkPopulator>(); public MagicChunkHandler(MagicController controller) { this.controller = controller; } public void load(String worldName, ConfigurationSection config) { for (String key : config.getKeys(false)) { ConfigurationSection handlerConfig = config.getConfigurationSection(key); if (handlerConfig == null) { controller.getLogger().warning("Was expecting a properties section in world chunk_generate config for key '" + worldName + "', but got: " + config.get(key)); continue; } if (!handlerConfig.getBoolean("enabled", true)) { continue; } String className = handlerConfig.getString("class"); MagicChunkPopulator populator = createChunkPopulator(className); if (populator != null) { if (populator.load(handlerConfig, controller)) { chunkPopulators.add(populator); controller.info("Adding " + key + " populator to " + worldName); } else { controller.info("Skipping invalid " + key + " populator for " + worldName); } } else { controller.info("Skipping invalid " + key + " populator for " + worldName); } } } public Collection<MagicChunkPopulator> getPopulators() { return chunkPopulators; } @Nullable protected MagicChunkPopulator createChunkPopulator(String className) { if (className == null) return null; if (className.indexOf('.') <= 0) { className = BUILTIN_CLASSPATH + "." + className; if (!className.endsWith("Populator")) { className += "Populator"; } } Class<?> handlerClass = null; try { handlerClass = Class.forName(className); } catch (Throwable ex) { controller.getLogger().log(Level.WARNING, "Error loading chunk populator: " + className, ex); return null; } Object newObject; try { newObject = handlerClass.getDeclaredConstructor().newInstance(); } catch (Throwable ex) { controller.getLogger().log(Level.WARNING, "Error loading chunk populator: " + className, ex); return null; } if (newObject == null || !(newObject instanceof MagicChunkPopulator)) { controller.getLogger().warning("Error loading chunk populator: " + className + ", does it extend MagicChunkPopulator?"); return null; } return (MagicChunkPopulator)newObject; } public boolean isEmpty() { return chunkPopulators.size() == 0; } }
36.315217
173
0.614487
2ea9c0160c97337ecc25083b5691e14f5fe1c16d
2,519
/* * 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. * */ /* $Id$ */ package org.apache.lenya.workflow; /** * <p>A workflow schema.</p> * <p> * A workflow schema defines a state machine (deterministic finite * automaton - DFA), consisting of * </p> * <ul> * <li>states, including a marked initial state,</li> * <li>transitions, and</li> * <li>state variables.</li> */ public interface Workflow { /** * <code>NAMESPACE</code> Workflow namespace URI */ String NAMESPACE = "http://apache.org/cocoon/lenya/workflow/1.0"; /** * <code>DEFAULT_PREFIX</code> Default workflow namespace prefix */ String DEFAULT_PREFIX = "wf"; /** * Returns the initial state of this workflow. * @return The initial state */ String getInitialState(); /** * Returns the transitions that leave a state. * This method is used, e.g., to disable menu items. * @param state A state. * @return The transitions that leave the state. * @throws WorkflowException if the state is not contained. */ Transition[] getLeavingTransitions(String state) throws WorkflowException; /** * Returns the variable names. * @return A string array. */ String[] getVariableNames(); /** * @return The name of this workflow. */ String getName(); /** * @param variableName The variable name. * @return The initial value of the variable. * @throws WorkflowException if the variable does not exist. */ boolean getInitialValue(String variableName) throws WorkflowException; /** * @return The events. */ String[] getEvents(); /** * @return The states. */ String[] getStates(); }
28.954023
78
0.654625
0dca8bee433e32eb50053e833df824ebd786b109
931
package easycriteria; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.OneToOne; import javax.persistence.Table; @Entity @Table(name = "tree_node_tbl") public class TreeNode { @Id @GeneratedValue private int id; private String name; @OneToOne(fetch=FetchType.LAZY) @JoinColumn(name="PARENT_ID") private TreeNode parent; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public TreeNode getParent() { return parent; } public void setParent(TreeNode parent) { this.parent = parent; } @Override public String toString() { return "TreeNode [id=" + id + ", name=" + name + ", parent=" + parent + "]"; } }
17.240741
78
0.705693
1eaaee0cff2cabaf8ea128fda7bb7d3cad8e9219
276
package purpleblue.com.nytimessearch; /** * Created by ernest on 7/26/16. */ public class Constants { public static final String APIKEY_NEWYORKTIMES = "11119956891143ac98d2e386618db948"; public static final String SHAREDPREF_SEARCHSETTINGS = "NYTSearchSettings"; }
27.6
88
0.775362
1e07b1b33a2573b3dcf37ca33406bc1d4d0ad45c
336
package ru.job4j.tictactoe; public interface LogicAI { /** * Loads new board. */ void loadBoard(Cell[][] cells); /** * Which side AI plays. * @param markX is comp on X mark. */ void setMarkX(boolean markX); /** * calculates next move and make it.` */ boolean makeMove(); }
16
41
0.550595
292ae7768372aed75348d36126328e3451a797c7
3,781
/* * Copyright (c) terms as published in http://waffle.codehaus.org/license.html */ package org.codehaus.waffle.controller; import static org.codehaus.waffle.Constants.CONTROLLER_KEY; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.codehaus.waffle.action.MethodDefinition; import org.codehaus.waffle.action.MethodDefinitionFinder; import org.codehaus.waffle.action.MissingActionMethodException; import org.codehaus.waffle.i18n.MessageResources; import org.codehaus.waffle.i18n.MessagesContext; import org.codehaus.waffle.monitor.ControllerMonitor; import org.codehaus.waffle.ComponentFinder; /** * Implementation of the controller definition factory which uses the context container to look up the controller * objected registered. * * @author Michael Ward * @author Mauro Talevi */ public class ContextControllerDefinitionFactory implements ControllerDefinitionFactory { private final MethodDefinitionFinder methodDefinitionFinder; private final ControllerNameResolver controllerNameResolver; private final ControllerMonitor controllerMonitor; protected final MessageResources messageResources; public ContextControllerDefinitionFactory(MethodDefinitionFinder methodDefinitionFinder, ControllerNameResolver controllerNameResolver, ControllerMonitor controllerMonitor, MessageResources messageResources) { this.methodDefinitionFinder = methodDefinitionFinder; this.controllerNameResolver = controllerNameResolver; this.controllerMonitor = controllerMonitor; this.messageResources = messageResources; } /** * Retrieves the controller definition from the context container via the WaffleRequestFilter * * @see org.codehaus.waffle.context.WaffleRequestFilter */ public ControllerDefinition getControllerDefinition(HttpServletRequest request, HttpServletResponse response, MessagesContext messageContext, ComponentFinder componentFinder) { String name = controllerNameResolver.findControllerName(request); Object controller = findController(name, request, componentFinder); MethodDefinition methodDefinition = null; try { methodDefinition = findMethodDefinition(controller, request, response, messageContext); } catch (MissingActionMethodException e) { controllerMonitor.methodDefinitionNotFound(name); // default to null // TODO introduce a NullMethodDefinition? } // set the controller to the request so it can be accessed from the view request.setAttribute(CONTROLLER_KEY, controller); return new ControllerDefinition(name, controller, methodDefinition); } protected Object findController(String name, HttpServletRequest request, ComponentFinder componentFinder) { Object controller = componentFinder.getComponent(Object.class, name); if (controller == null) { controllerMonitor.controllerNotFound(name); String message = messageResources.getMessageWithDefault("controllerNotFound", "Controller ''{0}'' not found in the Registrar for the request path ''{1}''", name, request .getRequestURI()); throw new ControllerNotFoundException(message); } return controller; } protected MethodDefinition findMethodDefinition(Object controller, HttpServletRequest request, HttpServletResponse response, MessagesContext messageContext) { return methodDefinitionFinder.find(controller, request, response, messageContext); } }
45.011905
146
0.731288
c1e8e378046b1038919c4ac20ad27316260fd8e3
2,168
package com.hikki.masakapanih.adapter; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import androidx.annotation.NonNull; import androidx.databinding.DataBindingUtil; import androidx.recyclerview.widget.RecyclerView; import com.hikki.masakapanih.R; import com.hikki.masakapanih.databinding.SearchBinding; import com.hikki.masakapanih.model.ResultsSearch; import com.hikki.masakapanih.model.ResultsSearch; import org.jetbrains.annotations.NotNull; import java.util.List; public class SearchAdapter extends RecyclerView.Adapter<SearchAdapter.ViewHolder> { private List<ResultsSearch> data; private OnCLick onCLick; @NonNull @NotNull @Override public ViewHolder onCreateViewHolder(@NonNull @NotNull ViewGroup parent, int viewType) { SearchBinding binding = DataBindingUtil.inflate(LayoutInflater.from(parent.getContext()),R.layout.item_search ,parent,false); return new ViewHolder(binding); } @Override public void onBindViewHolder(@NonNull @NotNull SearchAdapter.ViewHolder holder, int position) { holder.bind(data.get(position)); } @Override public int getItemCount() { if(data != null){ return data.size(); } return 0; } public void setData(List<ResultsSearch> data){ this.data = data; notifyDataSetChanged(); } public class ViewHolder extends RecyclerView.ViewHolder { SearchBinding binding; public ViewHolder(@NonNull @NotNull SearchBinding itemView) { super(itemView.getRoot()); this.binding = itemView; binding.cardResep.setOnClickListener(v->{ onCLick.click(v,data.get(getAdapterPosition()).getKey(),data.get(getAdapterPosition()).getThumb()); }); } public void bind(ResultsSearch model){ model.setTitle(model.getTitle()); binding.setVm(model); } } public void setClick(OnCLick onCLick){ this.onCLick = onCLick; } public interface OnCLick { void click(View v,String key, String url); } }
30.971429
117
0.684502
af1d7b5a486719980f6a9d4899a6975d3cac9d74
1,633
package xyz.staffjoy.framework.api; import com.fasterxml.jackson.annotation.JsonInclude; import lombok.Data; import org.springframework.util.Assert; import java.beans.Transient; @Data public class ServiceResponse<T> { private Integer code = Result.SUCCESS.getCode(); private String message = Result.SUCCESS.getMsg(); @JsonInclude(JsonInclude.Include.NON_NULL) private T data; private ServiceResponse() { } private ServiceResponse(T data) { this.data = data; } private ServiceResponse(Integer code, String message) { this.code = code; this.message = message; } public static <T> ServiceResponse<T> ok() { return new ServiceResponse<>(); } public static ServiceResponse<Void> ok(String message) { return new ServiceResponse<>(Result.SUCCESS.getCode(), message); } public static <T> ServiceResponse<T> ok(T data) { return new ServiceResponse<>(data); } public static <T> ServiceResponse<T> fail(Result code) { Assert.isTrue(!(Result.SUCCESS.getCode() == code.getCode()), "code 必须是错误的!"); return new ServiceResponse<>(code.getCode(), code.getMsg()); } public static <T> ServiceResponse<T> fail(Result code, String message) { Assert.isTrue(!(Result.SUCCESS.getCode() == code.getCode()), "code 必须是错误的!"); return new ServiceResponse<>(code.getCode(), message); } @Transient // 避免序列化 public boolean isSuccess() { return code == Result.SUCCESS.getCode(); } @Transient // 避免序列化 public boolean isError() { return !isSuccess(); } }
27.216667
85
0.653399
572e69df0fad63f296f6d4c17af8d16a41ee2d33
368
package com.leeup.sms.mapper; import com.leeup.sms.bean.Clazz; public interface ClazzMapper { int deleteByPrimaryKey(String classStudentNo); int insert(Clazz record); int insertSelective(Clazz record); Clazz selectByPrimaryKey(String classStudentNo); int updateByPrimaryKeySelective(Clazz record); int updateByPrimaryKey(Clazz record); }
21.647059
52
0.766304
471085770ef8ec4dd4023416217e964302cb8e7c
4,321
// Code generated by lark suite oapi sdk gen package com.larksuite.oapi.service.admin.v1.model; import com.google.gson.annotations.SerializedName; public class AuditAndroidContext { @SerializedName("udid") private String udid; @SerializedName("did") private String did; @SerializedName("app_ver") private String appVer; @SerializedName("ver") private String ver; @SerializedName("region") private String region; @SerializedName("id_i") private String idI; @SerializedName("id_r") private String idR; @SerializedName("hw_brand") private String hwBrand; @SerializedName("hw_manuf") private String hwManuf; @SerializedName("wifip") private String wifip; @SerializedName("route_iip") private String routeIip; @SerializedName("route_gip") private String routeGip; @SerializedName("env_su") private String envSu; @SerializedName("env_tz") private String envTz; @SerializedName("env_ml") private String envMl; @SerializedName("location") private String location; @SerializedName("active_ip") private String activeIp; @SerializedName("active_ip_detail") private String activeIpDetail; @SerializedName("cell_base_station") private String cellBaseStation; @SerializedName("IP") private String iP; public String getUdid() { return this.udid; } public void setUdid(String udid) { this.udid = udid; } public String getDid() { return this.did; } public void setDid(String did) { this.did = did; } public String getAppVer() { return this.appVer; } public void setAppVer(String appVer) { this.appVer = appVer; } public String getVer() { return this.ver; } public void setVer(String ver) { this.ver = ver; } public String getRegion() { return this.region; } public void setRegion(String region) { this.region = region; } public String getIdI() { return this.idI; } public void setIdI(String idI) { this.idI = idI; } public String getIdR() { return this.idR; } public void setIdR(String idR) { this.idR = idR; } public String getHwBrand() { return this.hwBrand; } public void setHwBrand(String hwBrand) { this.hwBrand = hwBrand; } public String getHwManuf() { return this.hwManuf; } public void setHwManuf(String hwManuf) { this.hwManuf = hwManuf; } public String getWifip() { return this.wifip; } public void setWifip(String wifip) { this.wifip = wifip; } public String getRouteIip() { return this.routeIip; } public void setRouteIip(String routeIip) { this.routeIip = routeIip; } public String getRouteGip() { return this.routeGip; } public void setRouteGip(String routeGip) { this.routeGip = routeGip; } public String getEnvSu() { return this.envSu; } public void setEnvSu(String envSu) { this.envSu = envSu; } public String getEnvTz() { return this.envTz; } public void setEnvTz(String envTz) { this.envTz = envTz; } public String getEnvMl() { return this.envMl; } public void setEnvMl(String envMl) { this.envMl = envMl; } public String getLocation() { return this.location; } public void setLocation(String location) { this.location = location; } public String getActiveIp() { return this.activeIp; } public void setActiveIp(String activeIp) { this.activeIp = activeIp; } public String getActiveIpDetail() { return this.activeIpDetail; } public void setActiveIpDetail(String activeIpDetail) { this.activeIpDetail = activeIpDetail; } public String getCellBaseStation() { return this.cellBaseStation; } public void setCellBaseStation(String cellBaseStation) { this.cellBaseStation = cellBaseStation; } public String getIP() { return this.iP; } public void setIP(String iP) { this.iP = iP; } }
20.774038
60
0.616755
b5b14d238c084d7962c4398d3de0d1638abaf19b
3,247
package com.packtpub.techbuzz.controlers; import java.util.HashMap; import java.util.Map; import javax.faces.application.FacesMessage; import javax.faces.bean.ManagedBean; import javax.faces.bean.RequestScoped; import javax.faces.context.FacesContext; import org.apache.log4j.Logger; import org.primefaces.context.RequestContext; import org.primefaces.event.CloseEvent; import org.primefaces.event.SelectEvent; import com.packtpub.techbuzz.entities.User; /** * @author Siva * */ @ManagedBean @RequestScoped public class DialogController { private static final Logger logger = Logger.getLogger(DialogController.class); private User registerUser = new User(); private User selectedUser = null; public User getRegisterUser() { return registerUser; } public void setRegisterUser(User registerUser) { this.registerUser = registerUser; } public void handleDialogClose(CloseEvent event) { String msg = event.getComponent().getId() + " dialog is closed"; FacesContext facesContext = FacesContext.getCurrentInstance(); FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, msg, msg); facesContext.addMessage("SampleDialog", message); } public void doRegister() { boolean registered = false; try { logger.info("Register User "+registerUser); String msg = "User Registered successfully"; FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, msg, msg)); registerUser = new User(); registered = true; //RequestContext.getCurrentInstance().execute("registrationDlg.hide();"); //RequestContext.getCurrentInstance().execute("$('#registerLink').fadeOut();"); } catch (Exception e) { String msg = e.getMessage(); String componentId = "registrationFormDlg"; FacesContext.getCurrentInstance().addMessage(componentId, new FacesMessage(FacesMessage.SEVERITY_ERROR, msg, msg)); } RequestContext.getCurrentInstance().addCallbackParam("registered", registered); } public void showUserSearchForm() { Map<String,Object> options = new HashMap<String, Object>(); options.put("modal", true); options.put("draggable", false); options.put("resizable", false); options.put("contentHeight", 400); RequestContext.getCurrentInstance().openDialog("searchUsers", options, null); } public void handleSelectUser(SelectEvent event) { User user = (User) event.getObject(); FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, "User Selected", "User:" + user.getEmailId()); FacesContext.getCurrentInstance().addMessage(null, message); this.setSelectedUser(user); } public void selectUserFromDialog(User user) { RequestContext.getCurrentInstance().closeDialog(user); } public void showFacesMessage() { RequestContext.getCurrentInstance().showMessageInDialog(new FacesMessage("PrimeFaces 4.0" , "PrimeFaces rocks!!!")); } public User getSelectedUser() { return selectedUser; } public void setSelectedUser(User selectedUser) { this.selectedUser = selectedUser; } }
31.221154
125
0.70619
348e217fd4b5beb912263f95888d348ce1a24c0d
3,272
// MESSAGE STATE_CORRECTION PACKING package com.jeremydyer.mavlink.Messages.pixhawk; import com.jeremydyer.mavlink.Messages.MAVLinkMessage; import com.jeremydyer.mavlink.Messages.MAVLinkPacket; import com.jeremydyer.mavlink.Messages.MAVLinkPayload; /** * Corrects the systems state by adding an error correction term to the position and velocity, and by rotating the attitude by a correction angle. */ public class msg_state_correction extends MAVLinkMessage{ public static final int MAVLINK_MSG_ID_STATE_CORRECTION = 64; public static final int MAVLINK_MSG_LENGTH = 36; private static final long serialVersionUID = MAVLINK_MSG_ID_STATE_CORRECTION; /** * x position error */ public float xErr; /** * y position error */ public float yErr; /** * z position error */ public float zErr; /** * roll error (radians) */ public float rollErr; /** * pitch error (radians) */ public float pitchErr; /** * yaw error (radians) */ public float yawErr; /** * x velocity */ public float vxErr; /** * y velocity */ public float vyErr; /** * z velocity */ public float vzErr; /** * Generates the payload for a mavlink message for a message of this type * @return */ public MAVLinkPacket pack(){ MAVLinkPacket packet = new MAVLinkPacket(); packet.len = MAVLINK_MSG_LENGTH; packet.sysid = 255; packet.compid = 190; packet.msgid = MAVLINK_MSG_ID_STATE_CORRECTION; packet.payload.putFloat(xErr); packet.payload.putFloat(yErr); packet.payload.putFloat(zErr); packet.payload.putFloat(rollErr); packet.payload.putFloat(pitchErr); packet.payload.putFloat(yawErr); packet.payload.putFloat(vxErr); packet.payload.putFloat(vyErr); packet.payload.putFloat(vzErr); return packet; } /** * Decode a state_correction message into this class fields * * @param payload The message to decode */ public void unpack(MAVLinkPayload payload) { payload.resetIndex(); xErr = payload.getFloat(); yErr = payload.getFloat(); zErr = payload.getFloat(); rollErr = payload.getFloat(); pitchErr = payload.getFloat(); yawErr = payload.getFloat(); vxErr = payload.getFloat(); vyErr = payload.getFloat(); vzErr = payload.getFloat(); } /** * Constructor for a new message, just initializes the msgid */ public msg_state_correction(){ msgid = MAVLINK_MSG_ID_STATE_CORRECTION; } /** * Constructor for a new message, initializes the message with the payload * from a mavlink packet * */ public msg_state_correction(MAVLinkPacket mavLinkPacket){ this.sysid = mavLinkPacket.sysid; this.compid = mavLinkPacket.compid; this.msgid = MAVLINK_MSG_ID_STATE_CORRECTION; unpack(mavLinkPacket.payload); //Log.d("MAVLink", "STATE_CORRECTION"); //Log.d("MAVLINK_MSG_ID_STATE_CORRECTION", toString()); } /** * Returns a string with the MSG name and data */ public String toString(){ return "MAVLINK_MSG_ID_STATE_CORRECTION -"+" xErr:"+xErr+" yErr:"+yErr+" zErr:"+zErr+" rollErr:"+rollErr+" pitchErr:"+pitchErr+" yawErr:"+yawErr+" vxErr:"+vxErr+" vyErr:"+vyErr+" vzErr:"+vzErr+""; } }
26.387097
201
0.677262
fccec1bc208b675bc15b0b9be850dea5ed3e7795
234
package ru.job4j.professions; public class Profession { private String name; private String surname; private String education; private String birthday; public String getName() { return this.name; } }
18
29
0.679487
3972e4a48f2d0bb6641e1cf378c569869001da01
1,130
/** * */ package com.ravi.game.base; import java.util.Map; import com.ravi.game.layout.IBoard; /** * All the customization regarding a board game rule to be placed here. * * @author Ravi Kant Singh * */ public interface IGameRuleHandler { /** * Game specific starting position validity check. * * @param aBoard * @param aPlayer * @param aStartingPositions List of starting position and the piece to be placed at that position * @return */ public boolean isValidStartingPosition(IBoard aBoard, IPlayer aPlayer, Map<String, IPiece> aStartingPositions); /** * Extra checks for valid moves. * Example: whether the Piece at source position can forcefully remove the * Piece at destination position. */ public boolean isValidMove(IBoard aBoard, IGameMove aGameMove); /** * Check if a particular player has won the game. */ public boolean hasPlayerWonTheGame(IBoard aBoard, IPlayer aPlayer); /** * To be called for MACHINE player to compute the next move. */ public IGameMove computeNextMoveForPlayer(IBoard aBoard, IPlayer aPlayer); }
25.681818
113
0.69823
d628991a4b28cebe665535515efaea9158ff577b
2,907
/* * Copyright (c) 2008, 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package nsk.share.aod; import nsk.share.*; import nsk.share.jpda.SocketIOPipe; /* Class TargetApplication is part of the framework used in the AttachOnDemand tests (tests against Attach API, API from package com.sun.tools.attach). This class is used in tests where main test application uses Attach API, but doesn't load agents to the another VM. In these test there are 2 java applications: main application using Attach API and another 'dummy' application which should be alive while main application is working. To synchronize main and dummy application SocketIOPipe is used: when DummyTargetApplication starts it sends signal that it is ready for test and waits for signal permitting finish execution (socket number used for connection establishing should be passed via command line). */ public class DummyTargetApplication { protected Log log = new Log(System.out, true); protected AODTargetArgParser argParser; protected SocketIOPipe pipe; public DummyTargetApplication(String[] args) { argParser = new AODTargetArgParser(args); } protected void targetApplicationActions() { // do nothing by default } public void runTargetApplication() { pipe = SocketIOPipe.createClientIOPipe(log, "localhost", argParser.getPort(), 0); log.display("Sending signal '" + AODTestRunner.SIGNAL_READY_FOR_ATTACH + "'"); pipe.println(AODTestRunner.SIGNAL_READY_FOR_ATTACH); targetApplicationActions(); String signal = pipe.readln(); log.display("Signal received: '" + signal + "'"); if ((signal == null) || !signal.equals(AODTestRunner.SIGNAL_FINISH)) throw new TestBug("Unexpected signal: '" + signal + "'"); } public static void main(String[] args) { new DummyTargetApplication(args).runTargetApplication(); } }
39.283784
115
0.733058
2a95be2b1d57ec0e498cacc8679fbf277fb104c9
677
package me.Serophots.UHCCore.Hub; import me.Serophots.UHCCore.Main; import org.bukkit.Bukkit; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerQuitEvent; public class RemoveMessages implements Listener { private Main plugin; public RemoveMessages(Main plugin) { this.plugin = plugin; Bukkit.getPluginManager().registerEvents(this, plugin); } @EventHandler public void handle(PlayerJoinEvent e){ e.setJoinMessage(""); } @EventHandler public void handle(PlayerQuitEvent e){ e.setQuitMessage(""); } }
26.038462
63
0.722304
3d07e9a67589e4ce21fbcf8e0dfef63c28034792
943
package academy.learnprogramming; public class PC { private Case theCase; private Monitor monitor; private Motherboard motherboard; public PC(Case theCase, Monitor monitor, Motherboard motherboard) { this.theCase = theCase; this.monitor = monitor; this.motherboard = motherboard; } public void powerUp() { // getTheCase().pressPowerButton(); theCase.pressPowerButton(); drawLogo(); } private void drawLogo() { // Fancy graphics // getMonitor().drawPixelAt(1200, 50, "yellow"); // this may be preferable over using the getter method monitor.drawPixelAt(1200, 50, "yellow"); } // private Case getTheCase() { // return theCase; // } // // private Monitor getMonitor() { // return monitor; // } // // private Motherboard getMotherboard() { // return motherboard; // } }
24.179487
71
0.593849
8adc20def51836079231e7986a2ddb676df1f13a
17,530
/** * * Copyright (c) Microsoft and contributors. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * limitations under the License. * */ // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. package com.microsoft.windowsazure.management.servicebus.models; import com.microsoft.windowsazure.core.LazyArrayList; import java.util.ArrayList; import java.util.Calendar; public class ServiceBusTopic { private Calendar accessedAt; /** * Optional. The time the queue was last accessed. * @return The AccessedAt value. */ public Calendar getAccessedAt() { return this.accessedAt; } /** * Optional. The time the queue was last accessed. * @param accessedAtValue The AccessedAt value. */ public void setAccessedAt(final Calendar accessedAtValue) { this.accessedAt = accessedAtValue; } private ArrayList<ServiceBusSharedAccessAuthorizationRule> authorizationRules; /** * Optional. Gets the authorization rules for the description. (see * http://msdn.microsoft.com/en-us/library/windowsazure/hh780749.aspx for * more information) * @return The AuthorizationRules value. */ public ArrayList<ServiceBusSharedAccessAuthorizationRule> getAuthorizationRules() { return this.authorizationRules; } /** * Optional. Gets the authorization rules for the description. (see * http://msdn.microsoft.com/en-us/library/windowsazure/hh780749.aspx for * more information) * @param authorizationRulesValue The AuthorizationRules value. */ public void setAuthorizationRules(final ArrayList<ServiceBusSharedAccessAuthorizationRule> authorizationRulesValue) { this.authorizationRules = authorizationRulesValue; } private String autoDeleteOnIdle; /** * Optional. Implemented. * @return The AutoDeleteOnIdle value. */ public String getAutoDeleteOnIdle() { return this.autoDeleteOnIdle; } /** * Optional. Implemented. * @param autoDeleteOnIdleValue The AutoDeleteOnIdle value. */ public void setAutoDeleteOnIdle(final String autoDeleteOnIdleValue) { this.autoDeleteOnIdle = autoDeleteOnIdleValue; } private CountDetails countDetails; /** * Optional. Current queue statistics. * @return The CountDetails value. */ public CountDetails getCountDetails() { return this.countDetails; } /** * Optional. Current queue statistics. * @param countDetailsValue The CountDetails value. */ public void setCountDetails(final CountDetails countDetailsValue) { this.countDetails = countDetailsValue; } private Calendar createdAt; /** * Optional. The time the queue was created at. * @return The CreatedAt value. */ public Calendar getCreatedAt() { return this.createdAt; } /** * Optional. The time the queue was created at. * @param createdAtValue The CreatedAt value. */ public void setCreatedAt(final Calendar createdAtValue) { this.createdAt = createdAtValue; } private String defaultMessageTimeToLive; /** * Optional. Determines how long a message lives in the associated * subscriptions. Subscriptions inherit the TTL from the topic unless they * are created explicitly with a smaller TTL. Based on whether * dead-lettering is enabled, a message whose TTL has expired will either * be moved to the subscription's associated DeadLtterQueue or will be * permanently deleted. The following values are settable at topic creation * time:* Range: 1 second - TimeSpan.MaxValue* Default: TimeSpan.MaxValue * (see http://msdn.microsoft.com/en-us/library/windowsazure/jj839740.aspx * for more information) * @return The DefaultMessageTimeToLive value. */ public String getDefaultMessageTimeToLive() { return this.defaultMessageTimeToLive; } /** * Optional. Determines how long a message lives in the associated * subscriptions. Subscriptions inherit the TTL from the topic unless they * are created explicitly with a smaller TTL. Based on whether * dead-lettering is enabled, a message whose TTL has expired will either * be moved to the subscription's associated DeadLtterQueue or will be * permanently deleted. The following values are settable at topic creation * time:* Range: 1 second - TimeSpan.MaxValue* Default: TimeSpan.MaxValue * (see http://msdn.microsoft.com/en-us/library/windowsazure/jj839740.aspx * for more information) * @param defaultMessageTimeToLiveValue The DefaultMessageTimeToLive value. */ public void setDefaultMessageTimeToLive(final String defaultMessageTimeToLiveValue) { this.defaultMessageTimeToLive = defaultMessageTimeToLiveValue; } private String duplicateDetectionHistoryTimeWindow; /** * Optional. Specifies the time span during which the Service Bus will * detect message duplication.* Range: 1 second - 7 days* Default: 10 * minutes (see * http://msdn.microsoft.com/en-us/library/windowsazure/hh780749.aspx for * more information) * @return The DuplicateDetectionHistoryTimeWindow value. */ public String getDuplicateDetectionHistoryTimeWindow() { return this.duplicateDetectionHistoryTimeWindow; } /** * Optional. Specifies the time span during which the Service Bus will * detect message duplication.* Range: 1 second - 7 days* Default: 10 * minutes (see * http://msdn.microsoft.com/en-us/library/windowsazure/hh780749.aspx for * more information) * @param duplicateDetectionHistoryTimeWindowValue The * DuplicateDetectionHistoryTimeWindow value. */ public void setDuplicateDetectionHistoryTimeWindow(final String duplicateDetectionHistoryTimeWindowValue) { this.duplicateDetectionHistoryTimeWindow = duplicateDetectionHistoryTimeWindowValue; } private boolean enableBatchedOperations; /** * Optional. Enables or disables service side batching behavior when * performing operations for the specific queue. When enabled, service bus * will collect/batch multiple operations to the backend to be more * connection efficient. If user wants lower operation latency then they * can disable this feature. (see * http://msdn.microsoft.com/en-us/library/windowsazure/hh780749.aspx for * more information) * @return The EnableBatchedOperations value. */ public boolean isEnableBatchedOperations() { return this.enableBatchedOperations; } /** * Optional. Enables or disables service side batching behavior when * performing operations for the specific queue. When enabled, service bus * will collect/batch multiple operations to the backend to be more * connection efficient. If user wants lower operation latency then they * can disable this feature. (see * http://msdn.microsoft.com/en-us/library/windowsazure/hh780749.aspx for * more information) * @param enableBatchedOperationsValue The EnableBatchedOperations value. */ public void setEnableBatchedOperations(final boolean enableBatchedOperationsValue) { this.enableBatchedOperations = enableBatchedOperationsValue; } private String entityAvailabilityStatus; /** * Optional. The current availability status of the topic. * @return The EntityAvailabilityStatus value. */ public String getEntityAvailabilityStatus() { return this.entityAvailabilityStatus; } /** * Optional. The current availability status of the topic. * @param entityAvailabilityStatusValue The EntityAvailabilityStatus value. */ public void setEntityAvailabilityStatus(final String entityAvailabilityStatusValue) { this.entityAvailabilityStatus = entityAvailabilityStatusValue; } private boolean filteringMessagesBeforePublishing; /** * Optional. Gets or sets whether messages should be filtered before * publishing. (see * http://msdn.microsoft.com/en-us/library/windowsazure/hh780749.aspx for * more information) * @return The FilteringMessagesBeforePublishing value. */ public boolean isFilteringMessagesBeforePublishing() { return this.filteringMessagesBeforePublishing; } /** * Optional. Gets or sets whether messages should be filtered before * publishing. (see * http://msdn.microsoft.com/en-us/library/windowsazure/hh780749.aspx for * more information) * @param filteringMessagesBeforePublishingValue The * FilteringMessagesBeforePublishing value. */ public void setFilteringMessagesBeforePublishing(final boolean filteringMessagesBeforePublishingValue) { this.filteringMessagesBeforePublishing = filteringMessagesBeforePublishingValue; } private boolean isAnonymousAccessible; /** * Optional. Gets whether anonymous access is allowed. (see * http://msdn.microsoft.com/en-us/library/windowsazure/hh780749.aspx for * more information) * @return The IsAnonymousAccessible value. */ public boolean isAnonymousAccessible() { return this.isAnonymousAccessible; } /** * Optional. Gets whether anonymous access is allowed. (see * http://msdn.microsoft.com/en-us/library/windowsazure/hh780749.aspx for * more information) * @param isAnonymousAccessibleValue The IsAnonymousAccessible value. */ public void setIsAnonymousAccessible(final boolean isAnonymousAccessibleValue) { this.isAnonymousAccessible = isAnonymousAccessibleValue; } private int maxSizeInMegabytes; /** * Optional. Specifies the maximum topic size in megabytes. Any attempt to * enqueue a message that will cause the topic to exceed this value will * fail. All messages that are stored in the topic or any of its * subscriptions count towards this value. Multiple copies of a message * that reside in one or multiple subscriptions count as a single messages. * For example, if message m exists once in subscription s1 and twice in * subscription s2, m is counted as a single message. You can only set this * parameter at topic creation time using the following values:* Range: 1 - * 5*1024 MB* Default: 1*1024 (see * http://msdn.microsoft.com/en-us/library/windowsazure/hh780749.aspx for * more information) * @return The MaxSizeInMegabytes value. */ public int getMaxSizeInMegabytes() { return this.maxSizeInMegabytes; } /** * Optional. Specifies the maximum topic size in megabytes. Any attempt to * enqueue a message that will cause the topic to exceed this value will * fail. All messages that are stored in the topic or any of its * subscriptions count towards this value. Multiple copies of a message * that reside in one or multiple subscriptions count as a single messages. * For example, if message m exists once in subscription s1 and twice in * subscription s2, m is counted as a single message. You can only set this * parameter at topic creation time using the following values:* Range: 1 - * 5*1024 MB* Default: 1*1024 (see * http://msdn.microsoft.com/en-us/library/windowsazure/hh780749.aspx for * more information) * @param maxSizeInMegabytesValue The MaxSizeInMegabytes value. */ public void setMaxSizeInMegabytes(final int maxSizeInMegabytesValue) { this.maxSizeInMegabytes = maxSizeInMegabytesValue; } private String name; /** * Optional. The name of the topic. * @return The Name value. */ public String getName() { return this.name; } /** * Optional. The name of the topic. * @param nameValue The Name value. */ public void setName(final String nameValue) { this.name = nameValue; } private boolean requiresDuplicateDetection; /** * Optional. If enabled, the topic will detect duplicate messages within the * time span specified by the DuplicateDetectionHistoryTimeWindow property. * Settable only at topic creation time.* Default: false (see * http://msdn.microsoft.com/en-us/library/windowsazure/hh780749.aspx for * more information) * @return The RequiresDuplicateDetection value. */ public boolean isRequiresDuplicateDetection() { return this.requiresDuplicateDetection; } /** * Optional. If enabled, the topic will detect duplicate messages within the * time span specified by the DuplicateDetectionHistoryTimeWindow property. * Settable only at topic creation time.* Default: false (see * http://msdn.microsoft.com/en-us/library/windowsazure/hh780749.aspx for * more information) * @param requiresDuplicateDetectionValue The RequiresDuplicateDetection * value. */ public void setRequiresDuplicateDetection(final boolean requiresDuplicateDetectionValue) { this.requiresDuplicateDetection = requiresDuplicateDetectionValue; } private int sizeInBytes; /** * Optional. Reflects the actual bytes toward the topic quota that messages * in the topic currently occupy. (read-only)* Range: 0 * -MaxTopicSizeinMegaBytes (see * http://msdn.microsoft.com/en-us/library/windowsazure/hh780749.aspx for * more information) * @return The SizeInBytes value. */ public int getSizeInBytes() { return this.sizeInBytes; } /** * Optional. Reflects the actual bytes toward the topic quota that messages * in the topic currently occupy. (read-only)* Range: 0 * -MaxTopicSizeinMegaBytes (see * http://msdn.microsoft.com/en-us/library/windowsazure/hh780749.aspx for * more information) * @param sizeInBytesValue The SizeInBytes value. */ public void setSizeInBytes(final int sizeInBytesValue) { this.sizeInBytes = sizeInBytesValue; } private String status; /** * Optional. Gets or sets the current status of the topic (enabled or * disabled). When a topic is disabled, that topic cannot send or receive * messages. (see * http://msdn.microsoft.com/en-us/library/windowsazure/hh780749.aspx for * more information) * @return The Status value. */ public String getStatus() { return this.status; } /** * Optional. Gets or sets the current status of the topic (enabled or * disabled). When a topic is disabled, that topic cannot send or receive * messages. (see * http://msdn.microsoft.com/en-us/library/windowsazure/hh780749.aspx for * more information) * @param statusValue The Status value. */ public void setStatus(final String statusValue) { this.status = statusValue; } private int subscriptionCount; /** * Optional. The current number of subscriptions to the topic. * @return The SubscriptionCount value. */ public int getSubscriptionCount() { return this.subscriptionCount; } /** * Optional. The current number of subscriptions to the topic. * @param subscriptionCountValue The SubscriptionCount value. */ public void setSubscriptionCount(final int subscriptionCountValue) { this.subscriptionCount = subscriptionCountValue; } private boolean supportOrdering; /** * Optional. Gets or sets whether the topics can be ordered. (see * http://msdn.microsoft.com/en-us/library/windowsazure/hh780749.aspx for * more information) * @return The SupportOrdering value. */ public boolean isSupportOrdering() { return this.supportOrdering; } /** * Optional. Gets or sets whether the topics can be ordered. (see * http://msdn.microsoft.com/en-us/library/windowsazure/hh780749.aspx for * more information) * @param supportOrderingValue The SupportOrdering value. */ public void setSupportOrdering(final boolean supportOrderingValue) { this.supportOrdering = supportOrderingValue; } private Calendar updatedAt; /** * Optional. The time the queue was last updated. * @return The UpdatedAt value. */ public Calendar getUpdatedAt() { return this.updatedAt; } /** * Optional. The time the queue was last updated. * @param updatedAtValue The UpdatedAt value. */ public void setUpdatedAt(final Calendar updatedAtValue) { this.updatedAt = updatedAtValue; } /** * Initializes a new instance of the ServiceBusTopic class. * */ public ServiceBusTopic() { this.setAuthorizationRules(new LazyArrayList<ServiceBusSharedAccessAuthorizationRule>()); } }
36.293996
121
0.702852
8dcb6b95e211939d33a719aaf56d1602e3beeecd
4,617
/* * Copyright 2013 Xebia and Séven Le Mesle * * 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 fr.xebia.extras.selma.it; import fr.xebia.extras.selma.Selma; import fr.xebia.extras.selma.beans.AddressIn; import fr.xebia.extras.selma.beans.CityIn; import fr.xebia.extras.selma.beans.PersonIn; import fr.xebia.extras.selma.beans.PersonOut; import fr.xebia.extras.selma.it.mappers.MappingInterceptor; import fr.xebia.extras.selma.it.mappers.MappingInterceptorSupport; import fr.xebia.extras.selma.it.utils.Compile; import fr.xebia.extras.selma.it.utils.IntegrationTestBase; import org.junit.Assert; import org.junit.Test; /** * */ @Compile(withClasses = {MappingInterceptor.class, MappingInterceptorSupport.class}) public class MappingInterceptorIt extends IntegrationTestBase { @Test public void should_map_bean_with_custom_mapper() throws IllegalAccessException, InstantiationException, ClassNotFoundException { MappingInterceptorSupport mapper = Selma.getMapper(MappingInterceptorSupport.class); PersonIn personIn = new PersonIn(); personIn.setFirstName("Selma"); personIn.setAddress(new AddressIn()); personIn.getAddress().setCity(new CityIn()); personIn.getAddress().getCity().setCapital(true); personIn.getAddress().getCity().setName("Paris"); personIn.getAddress().getCity().setPopulation(3 * 1000 * 1000); personIn.getAddress().setPrincipal(true); personIn.getAddress().setNumber(55); personIn.getAddress().setStreet("rue de la truanderie"); PersonOut res = mapper.mapWithInterceptor(personIn); Assert.assertNotNull(res); Assert.assertEquals(personIn.getAddress().getStreet(), res.getAddress().getStreet()); Assert.assertEquals(personIn.getAddress().getNumber(), res.getAddress().getNumber()); Assert.assertEquals(personIn.getAddress().getExtras(), res.getAddress().getExtras()); Assert.assertEquals(personIn.getAddress().getCity().getName(), res.getAddress().getCity().getName()); Assert.assertEquals(personIn.getAddress().getCity().getPopulation(), res.getAddress().getCity().getPopulation()); Assert.assertEquals(personIn.getAddress().getCity().isCapital(), res.getAddress().getCity().isCapital()); Assert.assertEquals(personIn.getFirstName() + " BIO", res.getBiography()); } @Test public void given_bean_with_custom_mapper_when_update_graph_then_should_update_graph_with_custom() throws IllegalAccessException, InstantiationException, ClassNotFoundException { MappingInterceptorSupport mapper = Selma.getMapper(MappingInterceptorSupport.class); PersonIn personIn = new PersonIn(); personIn.setFirstName("Selma"); personIn.setAddress(new AddressIn()); personIn.getAddress().setCity(new CityIn()); personIn.getAddress().getCity().setCapital(true); personIn.getAddress().getCity().setName("Paris"); personIn.getAddress().getCity().setPopulation(3 * 1000 * 1000); personIn.getAddress().setPrincipal(true); personIn.getAddress().setNumber(55); personIn.getAddress().setStreet("rue de la truanderie"); PersonOut out = new PersonOut(); PersonOut res = mapper.mapWithInterceptor(personIn, out); Assert.assertNotNull(res); Assert.assertTrue(out == res); Assert.assertEquals(personIn.getAddress().getStreet(), res.getAddress().getStreet()); Assert.assertEquals(personIn.getAddress().getNumber(), res.getAddress().getNumber()); Assert.assertEquals(personIn.getAddress().getExtras(), res.getAddress().getExtras()); Assert.assertEquals(personIn.getAddress().getCity().getName(), res.getAddress().getCity().getName()); Assert.assertEquals(personIn.getAddress().getCity().getPopulation(), res.getAddress().getCity().getPopulation()); Assert.assertEquals(personIn.getAddress().getCity().isCapital(), res.getAddress().getCity().isCapital()); Assert.assertEquals(personIn.getFirstName() + " BIO", res.getBiography()); } }
45.264706
182
0.722764
bc73964e16854af10ba2b8c0f26f59fc63f0c23d
12,832
/* * Copyright 2008-2014 by Emeric Vernat * * This file is part of Java Melody. * * 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 net.bull.javamelody; // NOPMD import static net.bull.javamelody.HttpParameters.ACTION_PARAMETER; import static net.bull.javamelody.HttpParameters.CACHE_ID_PARAMETER; import static net.bull.javamelody.HttpParameters.CONNECTIONS_PART; import static net.bull.javamelody.HttpParameters.COUNTER_PARAMETER; import static net.bull.javamelody.HttpParameters.COUNTER_SUMMARY_PER_CLASS_PART; import static net.bull.javamelody.HttpParameters.CURRENT_REQUESTS_PART; import static net.bull.javamelody.HttpParameters.DATABASE_PART; import static net.bull.javamelody.HttpParameters.EXPLAIN_PLAN_PART; import static net.bull.javamelody.HttpParameters.FORMAT_PARAMETER; import static net.bull.javamelody.HttpParameters.GRAPH_PARAMETER; import static net.bull.javamelody.HttpParameters.HEAP_HISTO_PART; import static net.bull.javamelody.HttpParameters.HEIGHT_PARAMETER; import static net.bull.javamelody.HttpParameters.JMX_VALUE; import static net.bull.javamelody.HttpParameters.JNDI_PART; import static net.bull.javamelody.HttpParameters.JOB_ID_PARAMETER; import static net.bull.javamelody.HttpParameters.JROBINS_PART; import static net.bull.javamelody.HttpParameters.MBEANS_PART; import static net.bull.javamelody.HttpParameters.OTHER_JROBINS_PART; import static net.bull.javamelody.HttpParameters.PART_PARAMETER; import static net.bull.javamelody.HttpParameters.PATH_PARAMETER; import static net.bull.javamelody.HttpParameters.POM_XML_PART; import static net.bull.javamelody.HttpParameters.PROCESSES_PART; import static net.bull.javamelody.HttpParameters.REQUEST_PARAMETER; import static net.bull.javamelody.HttpParameters.SESSIONS_PART; import static net.bull.javamelody.HttpParameters.SESSION_ID_PARAMETER; import static net.bull.javamelody.HttpParameters.THREADS_PART; import static net.bull.javamelody.HttpParameters.THREAD_ID_PARAMETER; import static net.bull.javamelody.HttpParameters.WEB_XML_PART; import static net.bull.javamelody.HttpParameters.WIDTH_PARAMETER; import static org.easymock.EasyMock.createNiceMock; import static org.easymock.EasyMock.expect; import static org.easymock.EasyMock.replay; import static org.easymock.EasyMock.verify; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.Collections; import java.util.LinkedHashMap; import java.util.Map; import javax.servlet.ServletConfig; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.junit.After; import org.junit.Before; import org.junit.Test; /** * Test unitaire de la classe CollectorServlet. * @author Emeric Vernat */ public class TestCollectorServletWithParts { private static final String TRUE = "true"; private static final String TEST = "test"; private CollectorServlet collectorServlet; /** * Initialisation. * @throws IOException e * @throws ServletException e */ @Before public void setUp() throws IOException, ServletException { tearDown(); Utils.initialize(); Utils.setProperty(Parameters.PARAMETER_SYSTEM_PREFIX + "mockLabradorRetriever", TRUE); Utils.setProperty(Parameter.SYSTEM_ACTIONS_ENABLED, TRUE); final ServletConfig config = createNiceMock(ServletConfig.class); final ServletContext context = createNiceMock(ServletContext.class); expect(config.getServletContext()).andReturn(context).anyTimes(); collectorServlet = new CollectorServlet(); InputStream webXmlStream = null; try { webXmlStream = getClass().getResourceAsStream("/WEB-INF/web.xml"); InputStream webXmlStream2 = null; try { webXmlStream2 = context.getResourceAsStream("/WEB-INF/web.xml"); expect(webXmlStream2).andReturn(webXmlStream).anyTimes(); final String javamelodyDir = "/META-INF/maven/net.bull.javamelody/"; final String webapp = javamelodyDir + "javamelody-test-webapp/"; expect(context.getResourcePaths("/META-INF/maven/")).andReturn( Collections.singleton(javamelodyDir)).anyTimes(); expect(context.getResourcePaths(javamelodyDir)).andReturn( Collections.singleton(webapp)).anyTimes(); expect(context.getResourceAsStream(webapp + "pom.xml")).andReturn( getClass().getResourceAsStream("/pom.xml")).anyTimes(); replay(config); replay(context); collectorServlet.init(config); verify(config); verify(context); } finally { if (webXmlStream2 != null) { webXmlStream2.close(); } } } finally { if (webXmlStream != null) { webXmlStream.close(); } } } /** * Terminaison. * @throws IOException e */ @After public void tearDown() throws IOException { if (collectorServlet != null) { collectorServlet.destroy(); } Parameters.removeCollectorApplication(TEST); } /** Test. * @throws ServletException e * @throws IOException e */ @Test public void testDoPart() throws IOException, ServletException { final Map<String, String> parameters = new LinkedHashMap<String, String>(); // partParameter null: monitoring principal parameters.put(PART_PARAMETER, null); doPart(parameters); parameters.put(FORMAT_PARAMETER, "pdf"); doPart(parameters); parameters.remove(FORMAT_PARAMETER); parameters.put(PART_PARAMETER, WEB_XML_PART); doPart(parameters); parameters.put(PART_PARAMETER, POM_XML_PART); doPart(parameters); parameters.put(PART_PARAMETER, JNDI_PART); doPart(parameters); parameters.put(PATH_PARAMETER, "/"); doPart(parameters); parameters.remove(PATH_PARAMETER); parameters.put(PART_PARAMETER, MBEANS_PART); doPart(parameters); parameters.remove(PART_PARAMETER); parameters.put(JMX_VALUE, "JMImplementation:type=MBeanServerDelegate.MBeanServerId"); doPart(parameters); parameters.remove(JMX_VALUE); parameters.put(PART_PARAMETER, CURRENT_REQUESTS_PART); doPart(parameters); parameters.put(PART_PARAMETER, PROCESSES_PART); doPart(parameters); parameters.put(FORMAT_PARAMETER, "pdf"); doPart(parameters); parameters.remove(FORMAT_PARAMETER); TestDatabaseInformations.initJdbcDriverParameters(); parameters.put(PART_PARAMETER, DATABASE_PART); doPart(parameters); parameters.put(REQUEST_PARAMETER, "0"); doPart(parameters); parameters.put(PART_PARAMETER, CONNECTIONS_PART); doPart(parameters); parameters.put(PART_PARAMETER, HEAP_HISTO_PART); doPart(parameters); parameters.put(PART_PARAMETER, SESSIONS_PART); doPart(parameters); parameters.put(PART_PARAMETER, CURRENT_REQUESTS_PART); doPart(parameters); parameters.put(PART_PARAMETER, PROCESSES_PART); doPart(parameters); } /** Test. * @throws ServletException e * @throws IOException e */ @Test public void testDoCompressedSerializable() throws IOException, ServletException { final Map<String, String> parameters = new LinkedHashMap<String, String>(); parameters.put(FORMAT_PARAMETER, "xml"); // partParameter null: monitoring principal parameters.put(PART_PARAMETER, null); doPart(parameters); parameters.put(PART_PARAMETER, PROCESSES_PART); doPart(parameters); parameters.put(PART_PARAMETER, JNDI_PART); doPart(parameters); parameters.put(PART_PARAMETER, MBEANS_PART); doPart(parameters); parameters.put(PART_PARAMETER, COUNTER_SUMMARY_PER_CLASS_PART); parameters.put(COUNTER_PARAMETER, "services"); doPart(parameters); parameters.remove(COUNTER_PARAMETER); TestDatabaseInformations.initJdbcDriverParameters(); parameters.put(PART_PARAMETER, DATABASE_PART); doPart(parameters); parameters.put(REQUEST_PARAMETER, "0"); doPart(parameters); parameters.put(PART_PARAMETER, CONNECTIONS_PART); doPart(parameters); parameters.put(PART_PARAMETER, HEAP_HISTO_PART); doPart(parameters); parameters.put(PART_PARAMETER, SESSIONS_PART); doPart(parameters); parameters.put(PART_PARAMETER, THREADS_PART); doPart(parameters); parameters.put(PART_PARAMETER, CURRENT_REQUESTS_PART); doPart(parameters); parameters.put(WIDTH_PARAMETER, "80"); parameters.put(HEIGHT_PARAMETER, "80"); parameters.put(PART_PARAMETER, JROBINS_PART); doPart(parameters); parameters.put(GRAPH_PARAMETER, "cpu"); parameters.put(PART_PARAMETER, JROBINS_PART); doPart(parameters); parameters.remove(GRAPH_PARAMETER); parameters.put(PART_PARAMETER, OTHER_JROBINS_PART); doPart(parameters); parameters.remove(WIDTH_PARAMETER); parameters.remove(HEIGHT_PARAMETER); parameters.put(PART_PARAMETER, EXPLAIN_PLAN_PART); parameters.put(REQUEST_PARAMETER, "select 1 from dual"); doPart(parameters); } /** Test. * @throws ServletException e * @throws IOException e */ @Test public void testAction() throws IOException, ServletException { final Map<String, String> parameters = new LinkedHashMap<String, String>(); parameters.put("application", TEST); parameters.put(ACTION_PARAMETER, Action.GC.toString()); doPart(parameters); parameters.put(ACTION_PARAMETER, Action.CLEAR_COUNTER.toString()); parameters.put(COUNTER_PARAMETER, "all"); doPart(parameters); parameters.put(FORMAT_PARAMETER, TransportFormat.SERIALIZED.getCode()); doPart(parameters); parameters.remove(FORMAT_PARAMETER); parameters.put(ACTION_PARAMETER, Action.MAIL_TEST.toString()); doPart(parameters); parameters.put(ACTION_PARAMETER, Action.PURGE_OBSOLETE_FILES.toString()); doPart(parameters); parameters.put(ACTION_PARAMETER, Action.INVALIDATE_SESSION.toString()); parameters.put(SESSION_ID_PARAMETER, "aSessionId"); doPart(parameters); parameters.put(ACTION_PARAMETER, Action.KILL_THREAD.toString()); parameters.put(THREAD_ID_PARAMETER, "aThreadId"); doPart(parameters); parameters.put(ACTION_PARAMETER, Action.PAUSE_JOB.toString()); parameters.put(JOB_ID_PARAMETER, "all"); doPart(parameters); parameters.put(ACTION_PARAMETER, Action.CLEAR_CACHE.toString()); parameters.put(CACHE_ID_PARAMETER, "aCacheId"); doPart(parameters); parameters.put(ACTION_PARAMETER, "remove_application"); doPart(parameters); } private void doPart(Map<String, String> parameters) throws IOException, ServletException { final HttpServletRequest request = createNiceMock(HttpServletRequest.class); expect(request.getRequestURI()).andReturn("/test/monitoring").anyTimes(); final ServletContext servletContext = createNiceMock(ServletContext.class); expect(servletContext.getServerInfo()).andReturn("Mock").anyTimes(); if (MBEANS_PART.equals(parameters.get(PART_PARAMETER))) { expect(request.getHeaders("Accept-Encoding")).andReturn( Collections.enumeration(Collections.singleton("application/gzip"))).anyTimes(); } else { expect(request.getHeaders("Accept-Encoding")).andReturn( Collections.enumeration(Collections.singleton("text/html"))).anyTimes(); } Parameters.removeCollectorApplication(TEST); expect(request.getParameter("appName")).andReturn(TEST).anyTimes(); expect(request.getParameter("appUrls")).andReturn( "http://localhost/test,http://localhost:8080/test2").anyTimes(); // un cookie d'une application (qui existe) final Cookie[] cookies = { new Cookie("javamelody.application", TEST) }; expect(request.getCookies()).andReturn(cookies).anyTimes(); for (final Map.Entry<String, String> entry : parameters.entrySet()) { expect(request.getParameter(entry.getKey())).andReturn(entry.getValue()).anyTimes(); } final HttpServletResponse response = createNiceMock(HttpServletResponse.class); final FilterServletOutputStream servletOutputStream = new FilterServletOutputStream( new ByteArrayOutputStream()); expect(response.getOutputStream()).andReturn(servletOutputStream).anyTimes(); replay(request); replay(response); replay(servletContext); Parameters.initialize(servletContext); collectorServlet.doPost(request, response); collectorServlet.doGet(request, response); verify(request); verify(response); verify(servletContext); } }
40.736508
92
0.76317
a9f5e2717d711632184a6450204af5443c0f674b
183
package com.tanchaoyin.demo.module.uerinfo.presenter; /** * Created by tanchaoyin on 2017/4/28. */ public interface UserReposPresenter { void requestUserRepos(String url); }
16.636364
53
0.743169
0beb19083b6bacc77cc170090456cfa677ebef9d
7,935
// Copyright (c) guige.com. All rights reserved. // Licensed under the MIT license. See License.txt in the project root. package com.guige.tfvc; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider; import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider; import com.guige.tfvc.utils.SystemHelper; import org.apache.http.auth.AuthScope; import org.apache.http.auth.Credentials; import org.apache.http.auth.NTCredentials; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.CredentialsProvider; import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.util.VersionInfo; import org.glassfish.jersey.apache.connector.ApacheClientProperties; import org.glassfish.jersey.apache.connector.ApacheConnectorProvider; import org.glassfish.jersey.client.ClientConfig; import org.glassfish.jersey.client.ClientProperties; import org.glassfish.jersey.client.RequestEntityProcessing; import org.glassfish.jersey.client.spi.ConnectorProvider; import javax.net.ssl.SSLContext; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.ClientRequestContext; import javax.ws.rs.client.ClientRequestFilter; import javax.ws.rs.core.HttpHeaders; import java.io.IOException; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; /** * JAXRS Rest Client helper */ public class RestClientHelper { public enum Type {VSO_DEPLOYMENT, VSO, TFS} private static SSLContext mySslContext; private synchronized static SSLContext getSslContext() { if (mySslContext == null) { mySslContext = getSystemSslContext(); } return mySslContext; } private static SSLContext getSystemSslContext() { // NOTE: SSLContext.getDefault() should not be called because it automatically creates // default context which can't be initialized twice try { // actually TLSv1 support is mandatory for Java platform SSLContext context = SSLContext.getInstance("TLS"); context.init(null, null, null); return context; } catch (NoSuchAlgorithmException e) { //LOG.error(e); throw new AssertionError("Cannot get system SSL context"); } catch (KeyManagementException e) { //LOG.error(e); throw new AssertionError("Cannot initialize system SSL context"); } } private static Client createNewClient(ClientConfig clientConfig) { return ClientBuilder.newBuilder() .withConfig(clientConfig) .sslContext(getSslContext()) .build(); } public static Client getClient(final String serverUri, final String accessTokenValue) { final Credentials credentials = new UsernamePasswordCredentials("accessToken", accessTokenValue); final ClientConfig clientConfig = getClientConfig(Type.VSO_DEPLOYMENT, credentials, serverUri); return createNewClient(clientConfig); } public static Client getClient(final Type type, final AuthenticationInfo authenticationInfo) { final ClientConfig clientConfig = getClientConfig(type, authenticationInfo); return createNewClient(clientConfig); } public static ClientConfig getClientConfig(final Type type, final Credentials credentials, final String serverUri) { final CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, credentials); final ConnectorProvider connectorProvider = new ApacheConnectorProvider(); // custom json provider ignores new fields that aren't recognized final JacksonJsonProvider jacksonJsonProvider = new JacksonJaxbJsonProvider() .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); final ClientConfig clientConfig = new ClientConfig(jacksonJsonProvider).connectorProvider(connectorProvider); clientConfig.property(ApacheClientProperties.CREDENTIALS_PROVIDER, credentialsProvider); clientConfig.property(ClientProperties.REQUEST_ENTITY_PROCESSING, RequestEntityProcessing.BUFFERED); // For TFS OnPrem we only support NTLM authentication right now. Since 2016 servers support Basic as well, // we need to let the server and client negotiate the protocol instead of preemptively assuming Basic. // TODO: This prevents PATs from being used OnPrem. We need to fix this soon to support PATs onPrem. clientConfig.property(ApacheClientProperties.PREEMPTIVE_BASIC_AUTHENTICATION, type != Type.TFS); // register a filter to set the User Agent header clientConfig.register(new ClientRequestFilter() { @Override public void filter(final ClientRequestContext requestContext) throws IOException { // The default user agent is something like "Jersey/2.6" final String userAgent = VersionInfo.getUserAgent("Apache-HttpClient", "org.apache.http.client", HttpClientBuilder.class); // Finally, we can add the header requestContext.getHeaders().add(HttpHeaders.USER_AGENT, userAgent); } }); return clientConfig; } /** * Returns an NTCredentials object for given username and password * * @param userName * @param password * @return */ public static NTCredentials getNTCredentials(final String userName, final String password) { assert userName != null; assert password != null; String user = userName; String domain = ""; final String workstation = SystemHelper.getComputerName(); // If the username has a backslash, then the domain is the first part and the username is the second part if (userName.contains("\\")) { String[] parts = userName.split("[\\\\]"); if (parts.length == 2) { domain = parts[0]; user = parts[1]; } } else if (userName.contains("/")) { // If the username has a slash, then the domain is the first part and the username is the second part String[] parts = userName.split("[/]"); if (parts.length == 2) { domain = parts[0]; user = parts[1]; } } else if (userName.contains("@")) { // If the username has an asterisk, then the domain is the second part and the username is the first part String[] parts = userName.split("[@]"); if (parts.length == 2) { user = parts[0]; domain = parts[1]; } } return new org.apache.http.auth.NTCredentials(user, password, workstation, domain); } /** * Returns the NTCredentials or UsernamePasswordCredentials object * * @param type * @param authenticationInfo * @return */ public static Credentials getCredentials(final Type type, final AuthenticationInfo authenticationInfo) { if (type == Type.TFS) { return getNTCredentials(authenticationInfo.getUserName(), authenticationInfo.getPassword()); } else { return new UsernamePasswordCredentials(authenticationInfo.getUserName(), authenticationInfo.getPassword()); } } public static ClientConfig getClientConfig(final Type type, final AuthenticationInfo authenticationInfo) { final Credentials credentials = getCredentials(type, authenticationInfo); return getClientConfig(type, credentials, authenticationInfo.getServerUri()); } }
43.125
138
0.685696
5b101474b7a8cc026c7969a0cf4279691e802278
202,714
/** * Copyright 2014 IBM Corp. * * 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.ibm.datapower.amt.amp.defaultV2Provider; import java.io.IOException; import java.io.InputStream; import java.io.StringReader; import java.net.URI; import java.net.URL; import java.util.Enumeration; import java.util.Hashtable; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.apache.xmlbeans.XmlException; import org.apache.xmlbeans.XmlObject; import org.apache.xmlbeans.impl.values.XmlValueOutOfRangeException; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import com.datapower.schemas.appliance.management.x20.Backup; import com.datapower.schemas.appliance.management.x20.CompareConfigRequestDocument; import com.datapower.schemas.appliance.management.x20.CompareConfigResponseDocument; import com.datapower.schemas.appliance.management.x20.CompareResult; import com.datapower.schemas.appliance.management.x20.ConfigState; import com.datapower.schemas.appliance.management.x20.CryptoFileName; import com.datapower.schemas.appliance.management.x20.DeleteDomainRequestDocument; import com.datapower.schemas.appliance.management.x20.DeleteDomainResponseDocument; import com.datapower.schemas.appliance.management.x20.DeploymentPolicyConfiguration; import com.datapower.schemas.appliance.management.x20.File; import com.datapower.schemas.appliance.management.x20.Firmware; import com.datapower.schemas.appliance.management.x20.GetCryptoArtifactsRequestDocument; import com.datapower.schemas.appliance.management.x20.GetCryptoArtifactsResponseDocument; import com.datapower.schemas.appliance.management.x20.GetDeviceInfoRequestDocument; import com.datapower.schemas.appliance.management.x20.GetDeviceInfoResponseDocument; import com.datapower.schemas.appliance.management.x20.GetDomainExportRequestDocument; import com.datapower.schemas.appliance.management.x20.GetDomainExportResponseDocument; import com.datapower.schemas.appliance.management.x20.GetDomainListRequestDocument; import com.datapower.schemas.appliance.management.x20.GetDomainListResponseDocument; import com.datapower.schemas.appliance.management.x20.GetDomainStatusRequestDocument; import com.datapower.schemas.appliance.management.x20.GetDomainStatusResponseDocument; import com.datapower.schemas.appliance.management.x20.GetErrorReportRequestDocument; import com.datapower.schemas.appliance.management.x20.GetErrorReportResponseDocument; import com.datapower.schemas.appliance.management.x20.GetTokenRequestDocument; import com.datapower.schemas.appliance.management.x20.GetTokenResponseDocument; import com.datapower.schemas.appliance.management.x20.ManagementInterface; import com.datapower.schemas.appliance.management.x20.ManagementType; import com.datapower.schemas.appliance.management.x20.OpState; import com.datapower.schemas.appliance.management.x20.PingRequestDocument; import com.datapower.schemas.appliance.management.x20.PingResponseDocument; import com.datapower.schemas.appliance.management.x20.QuiesceRequestDocument; import com.datapower.schemas.appliance.management.x20.QuiesceResponseDocument; import com.datapower.schemas.appliance.management.x20.RebootMode; import com.datapower.schemas.appliance.management.x20.RebootRequestDocument; import com.datapower.schemas.appliance.management.x20.RebootResponseDocument; import com.datapower.schemas.appliance.management.x20.RestartDomainRequestDocument; import com.datapower.schemas.appliance.management.x20.RestartDomainResponseDocument; import com.datapower.schemas.appliance.management.x20.SecureBackup; import com.datapower.schemas.appliance.management.x20.SecureBackupRequestDocument; import com.datapower.schemas.appliance.management.x20.SecureBackupResponseDocument; import com.datapower.schemas.appliance.management.x20.SecureRestoreRequestDocument; import com.datapower.schemas.appliance.management.x20.SecureRestoreResponseDocument; import com.datapower.schemas.appliance.management.x20.SetDomainExportRequestDocument; import com.datapower.schemas.appliance.management.x20.SetDomainExportResponseDocument; import com.datapower.schemas.appliance.management.x20.SetFileRequestDocument; import com.datapower.schemas.appliance.management.x20.SetFileResponseDocument; import com.datapower.schemas.appliance.management.x20.SetFirmwareRequestDocument; import com.datapower.schemas.appliance.management.x20.SetFirmwareResponseDocument; import com.datapower.schemas.appliance.management.x20.StartDomainRequestDocument; import com.datapower.schemas.appliance.management.x20.StartDomainResponseDocument; import com.datapower.schemas.appliance.management.x20.Status; import com.datapower.schemas.appliance.management.x20.StopDomainRequestDocument; import com.datapower.schemas.appliance.management.x20.StopDomainResponseDocument; import com.datapower.schemas.appliance.management.x20.SubscribeRequestDocument; import com.datapower.schemas.appliance.management.x20.SubscribeResponseDocument; import com.datapower.schemas.appliance.management.x20.SubscriptionStateUrl; import com.datapower.schemas.appliance.management.x20.SubscriptionTopic; import com.datapower.schemas.appliance.management.x20.TokenType; import com.datapower.schemas.appliance.management.x20.UnquiesceRequestDocument; import com.datapower.schemas.appliance.management.x20.UnquiesceResponseDocument; import com.datapower.schemas.appliance.management.x20.UnsubscribeRequestDocument; import com.datapower.schemas.appliance.management.x20.UnsubscribeResponseDocument; import com.datapower.schemas.appliance.management.x20.SecureBackup.SecureBackupFile; import com.ibm.datapower.amt.Constants; import com.ibm.datapower.amt.Messages; import com.ibm.datapower.amt.ModelType; import com.ibm.datapower.amt.OperationStatus; import com.ibm.datapower.amt.QuiesceStatus; import com.ibm.datapower.amt.StringCollection; import com.ibm.datapower.amt.amp.AMPConstants; import com.ibm.datapower.amt.amp.AMPException; import com.ibm.datapower.amt.amp.AMPIOException; import com.ibm.datapower.amt.amp.Commands; import com.ibm.datapower.amt.amp.ConfigObject; import com.ibm.datapower.amt.amp.DeleteObjectResult; import com.ibm.datapower.amt.amp.DeviceContext; import com.ibm.datapower.amt.amp.DeviceExecutionException; import com.ibm.datapower.amt.amp.DeviceMetaInfo; import com.ibm.datapower.amt.amp.DomainStatus; import com.ibm.datapower.amt.amp.ErrorReport; import com.ibm.datapower.amt.amp.InterDependentServiceCollection; import com.ibm.datapower.amt.amp.InvalidCredentialsException; import com.ibm.datapower.amt.amp.NotExistException; import com.ibm.datapower.amt.amp.PingResponse; import com.ibm.datapower.amt.amp.ReferencedObjectCollection; import com.ibm.datapower.amt.amp.SOAPHelper; import com.ibm.datapower.amt.amp.SOAPHelperFactory; import com.ibm.datapower.amt.amp.SubscriptionResponseCode; import com.ibm.datapower.amt.amp.defaultV3Provider.Utils; import com.ibm.datapower.amt.clientAPI.ConfigService; import com.ibm.datapower.amt.clientAPI.DeletedException; import com.ibm.datapower.amt.clientAPI.DeploymentPolicy; import com.ibm.datapower.amt.clientAPI.Device; import com.ibm.datapower.amt.clientAPI.Manager; import com.ibm.datapower.amt.clientAPI.RuntimeService; import com.ibm.datapower.amt.logging.LoggerHelper; /** * Implements the Commands interface specified in * {@link com.ibm.datapower.amt.amp.Commands}. The device has a schema which describes * the format and allowed values for the SOAP messages, see * store:/app-mgmt-protocol-v2.xsd and store:/app-mgmt-protocol-v2.wsdl. * <p> * This implementation leverages the Apache XMLBeans generated classes from the * AMP schema. * * * @see com.ibm.datapower.amt.amp.Commands */ //* @version $Id: CommandsImpl.java,v 1.5 2011/01/18 20:46:22 wjong Exp $ public class CommandsImpl implements Commands { private SOAPHelper soapHelper; public static final String COPYRIGHT_2009_2013 = Constants.COPYRIGHT_2009_2013; final String setFirmwareHeader = "<amp:SetFirmwareRequest xmlns:amp=\"http://www.datapower.com/schemas/appliance/management/"+AMPConstants.AMP_V2_0+"\">\n<amp:Firmware>"; //$NON-NLS-1$ final String setFirmwareFooter = "</amp:Firmware>\n</amp:SetFirmwareRequest>"; //$NON-NLS-1$ final byte[] setFirmwareHeaderBytes = setFirmwareHeader.getBytes(); final byte[] setFirmwareFooterBytes = setFirmwareFooter.getBytes(); private static final String CLASS_NAME = CommandsImpl.class.getName(); protected final static Logger logger = Logger.getLogger(CLASS_NAME); static { LoggerHelper.addLoggerToGroup(logger, Manager.getLoggerGroupName()); } public CommandsImpl(String soapHelperImplementationClassName) throws AMPException{ final String METHOD_NAME = "CommandsImpl()"; //$NON-NLS-1$ soapHelper = SOAPHelperFactory.getSOAPHelper(soapHelperImplementationClassName); logger.logp(Level.FINEST, CLASS_NAME, METHOD_NAME, "soapHelper object created"); //$NON-NLS-1$ } /* * @see com.ibm.datapower.amt.amp.Commands#subscribeToDevice( * com.ibm.datapower.amt.amp.DeviceContext, java.lang.String, * com.ibm.datapower.amt.StringCollection, java.net.URL) */ public SubscriptionResponseCode subscribeToDevice(DeviceContext device, String subscriptionId, StringCollection topics, URL callback) throws InvalidCredentialsException, AMPIOException, DeviceExecutionException, AMPException { final String METHOD_NAME = "subscribeToDevice"; //$NON-NLS-1$ logger.entering(CLASS_NAME, METHOD_NAME, new Object[]{device, subscriptionId, topics, callback}); SubscribeRequestDocument requestDoc = SubscribeRequestDocument.Factory.newInstance(); SubscribeRequestDocument.SubscribeRequest subscribeRequest = requestDoc.addNewSubscribeRequest(); SubscribeRequestDocument.SubscribeRequest.Subscription subscription = subscribeRequest.addNewSubscription(); subscription.setId(subscriptionId); subscription.setURL(callback.toString()); SubscribeRequestDocument.SubscribeRequest.Subscription.Topics requestTopics = subscription.addNewTopics(); final String configuration = SubscriptionTopic.CONFIGURATION.toString(); final String firmware = SubscriptionTopic.FIRMWARE.toString(); final String operational = SubscriptionTopic.OPERATIONAL.toString(); final String all = SubscriptionTopic.X.toString(); for (int i = 0; i < topics.size(); i++){ if (topics.get(i).equalsIgnoreCase(configuration)) requestTopics.addTopic(SubscriptionTopic.CONFIGURATION); else if (topics.get(i).equalsIgnoreCase(firmware)) requestTopics.addTopic(SubscriptionTopic.FIRMWARE); else if (topics.get(i).equalsIgnoreCase(operational)) requestTopics.addTopic(SubscriptionTopic.OPERATIONAL); else if (topics.get(i).equalsIgnoreCase(all)) requestTopics.addTopic(SubscriptionTopic.X); else { String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.invalidTopic",topics.get(i)); AMPException e = new AMPException(message,"wamt.amp.defaultV2Provider.CommandsImpl.invalidTopic",topics.get(i)); logger.throwing(CLASS_NAME, METHOD_NAME,e); throw e; } } logger.logp(Level.FINEST, CLASS_NAME, METHOD_NAME, "subscribeRequestDocument created"); //$NON-NLS-1$ logger.logp(Level.FINER, CLASS_NAME, METHOD_NAME, "Sending subscriptionRequest(" + subscriptionId + ") to device " //$NON-NLS-1$ //$NON-NLS-2$ + device.getHostname() + ":" + device.getAMPPort()); //$NON-NLS-1$ /* Send request to device */ StringBuffer outMessage = new StringBuffer(requestDoc.xmlText(soapHelper.getOptions())); Node responseDocXml = soapHelper.call(device, outMessage); outMessage.delete(0,outMessage.length()); outMessage = null; requestDoc.setNil(); requestDoc = null; SubscriptionResponseCode result = null; /* Parse the request into a SubscribeResponseDocument */ try{ SubscribeResponseDocument responseDoc = SubscribeResponseDocument.Factory.parse(responseDocXml); logger.logp(Level.FINER, CLASS_NAME, METHOD_NAME, "Received subscriptionResponse(" + subscriptionId + ") from device " //$NON-NLS-1$ //$NON-NLS-2$ + device.getHostname() + ":" + device.getAMPPort()); //$NON-NLS-1$ logger.logp(Level.FINEST, CLASS_NAME, METHOD_NAME, "subscribeResponseDocument received"); //$NON-NLS-1$ SubscribeResponseDocument.SubscribeResponse subscriptionResponse = responseDoc.getSubscribeResponse(); if (subscriptionResponse == null){ Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.noResponse",params); AMPException e = new AMPException(message,"wamt.amp.defaultV2Provider.CommandsImpl.noResponse",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, e); throw e; } SubscriptionStateUrl subState = subscriptionResponse.getSubscriptionState(); if (subState == null){ Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.noSubState",params); AMPException e = new AMPException(message,"wamt.amp.defaultV2Provider.CommandsImpl.noSubState",params); //$NON-NLS-1$ //$NON-NLS-2$ throw e; } /* Return appropriate SubscriptionResponseCode from response */ if (subState.getStringValue().equalsIgnoreCase(SubscriptionResponseCode.ACTIVE.toString())) result = SubscriptionResponseCode.ACTIVE; else if (subState.getStringValue().equalsIgnoreCase(SubscriptionResponseCode.DUPLICATE_STRING)){ String originalURL = subState.getURL(); result = SubscriptionResponseCode.createWithDuplicate(originalURL); } else if (subState.getStringValue().equalsIgnoreCase(SubscriptionResponseCode.NONE.toString())) /* according to the device's AMP implementation, it will never * send a NONE in a subscribe response, only in an unsubscribe * response or a ping response. But for the sake of completeness, * set the POJO value just in case this value ever shows up. */ result = SubscriptionResponseCode.NONE; else if (subState.getStringValue().equalsIgnoreCase(SubscriptionResponseCode.FAULT.toString())){ Object[] params = {subscriptionId,device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.errSub",params); DeviceExecutionException e = new DeviceExecutionException(message,"wamt.amp.defaultV2Provider.CommandsImpl.errSub",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, e); throw e; } } catch (XmlException e){ Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.errParseSubResp",params); AMPException ex = new AMPException(message,e,"wamt.amp.defaultV2Provider.CommandsImpl.errParseSubResp",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, ex); throw ex; } catch (XmlValueOutOfRangeException e){ Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.invalidEnumSubDev",params); AMPException ex = new AMPException(message,e,"wamt.amp.defaultV2Provider.CommandsImpl.invalidEnumSubDev",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, ex); throw ex; } logger.exiting(CLASS_NAME, METHOD_NAME, result); return result; } /* * @see com.ibm.datapower.amt.amp.Commands#unsubscribeFromDevice( * com.ibm.datapower.amt.amp.DeviceContext, java.lang.String) */ public void unsubscribeFromDevice(DeviceContext device, String subscriptionID, StringCollection topics) throws NotExistException, InvalidCredentialsException, DeviceExecutionException, AMPIOException, AMPException { final String METHOD_NAME = "unsubscribeFromDevice"; //$NON-NLS-1$ logger.entering(CLASS_NAME, METHOD_NAME, new Object[]{device, subscriptionID, topics}); UnsubscribeRequestDocument requestDoc = UnsubscribeRequestDocument.Factory.newInstance(); UnsubscribeRequestDocument.UnsubscribeRequest unsubscribeRequest = requestDoc.addNewUnsubscribeRequest(); UnsubscribeRequestDocument.UnsubscribeRequest.Subscription unsubscription = unsubscribeRequest.addNewSubscription(); unsubscription.setId(subscriptionID); UnsubscribeRequestDocument.UnsubscribeRequest.Subscription.Topics requestTopics = unsubscription.addNewTopics(); final String configuration = SubscriptionTopic.CONFIGURATION.toString(); final String firmware = SubscriptionTopic.FIRMWARE.toString(); final String operational = SubscriptionTopic.OPERATIONAL.toString(); final String all = SubscriptionTopic.X.toString(); for (int i = 0; i < topics.size(); i++){ if (topics.get(i).equalsIgnoreCase(configuration)) requestTopics.addTopic(SubscriptionTopic.CONFIGURATION); else if (topics.get(i).equalsIgnoreCase(firmware)) requestTopics.addTopic(SubscriptionTopic.FIRMWARE); else if (topics.get(i).equalsIgnoreCase(operational)) requestTopics.addTopic(SubscriptionTopic.OPERATIONAL); else if (topics.get(i).equalsIgnoreCase(all)) requestTopics.addTopic(SubscriptionTopic.X); else { String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.invalidTopic",topics.get(i)); AMPException e = new AMPException(message,"wamt.amp.defaultV2Provider.CommandsImpl.invalidTopic",topics.get(i)); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, e); throw e; } } logger.logp(Level.FINEST, CLASS_NAME, METHOD_NAME, "unsubscribeRequestDocument created"); //$NON-NLS-1$ logger.logp(Level.FINER, CLASS_NAME, METHOD_NAME, "Sending unsubscriptionRequest(" + subscriptionID + ") to device " //$NON-NLS-1$ //$NON-NLS-2$ + device.getHostname() + ":" + device.getAMPPort()); //$NON-NLS-1$ /* Send request to device */ StringBuffer outMessage = new StringBuffer(requestDoc.xmlText(soapHelper.getOptions())); Node responseDocXml = soapHelper.call(device, outMessage); outMessage.delete(0,outMessage.length()); outMessage = null; requestDoc.setNil(); requestDoc = null; /* Parse the request into a UnsubscribeResponseDocument */ try{ UnsubscribeResponseDocument responseDoc = UnsubscribeResponseDocument.Factory.parse(responseDocXml); UnsubscribeResponseDocument.UnsubscribeResponse unsubscribeResponse = responseDoc.getUnsubscribeResponse(); if (unsubscribeResponse == null){ Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.noResp",params); AMPException e = new AMPException(message,"wamt.amp.defaultV2Provider.CommandsImpl.noResp",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, e); throw e; } com.datapower.schemas.appliance.management.x20.SubscriptionState.Enum subState = unsubscribeResponse.getSubscriptionState(); String subStateString = null; if (subState != null) subStateString = subState.toString(); else{ Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.noUnsubState",params); AMPException e = new AMPException(message,"wamt.amp.defaultV2Provider.CommandsImpl.noUnsubState",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, e); throw e; } if (subStateString.equalsIgnoreCase(SubscriptionResponseCode.FAULT.toString())){ Object[] params = {subscriptionID,device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.errRemSub",params); DeviceExecutionException e = new DeviceExecutionException(message,"wamt.amp.defaultV2Provider.CommandsImpl.errRemSub",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, e); throw e; } else if ((subStateString.equalsIgnoreCase(SubscriptionResponseCode.ACTIVE.toString())) || (subStateString.equalsIgnoreCase(SubscriptionResponseCode.NONE.toString()))) { logger.exiting(CLASS_NAME, METHOD_NAME); return; } else{ Object[] params = {subscriptionID,device.getHostname()}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.subIdNotExist",params); NotExistException e = new NotExistException(message,"wamt.amp.defaultV2Provider.CommandsImpl.subIdNotExist",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, e); throw e; } } catch (XmlException e){ Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.errParseSubResp",params); AMPException ex = new AMPException(message,e,"wamt.amp.defaultV2Provider.CommandsImpl.errParseSubResp",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, ex); throw ex; } catch (XmlValueOutOfRangeException e){ Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.invalidEnumUnsub",params); AMPException ex = new AMPException(message,e,"wamt.amp.defaultV2Provider.CommandsImpl.invalidEnumUnsub",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, ex); throw ex; } } /* * @see com.ibm.datapower.amt.amp.Commands#pingDevice(com.ibm.datapower.amt.amp.DeviceContext, java.lang.String) */ public PingResponse pingDevice(DeviceContext device, String subscriptionID) throws InvalidCredentialsException, DeviceExecutionException, AMPIOException, AMPException { final String METHOD_NAME = "pingDevice"; //$NON-NLS-1$ logger.entering(CLASS_NAME, METHOD_NAME, new Object[]{device, subscriptionID}); PingRequestDocument requestDoc = PingRequestDocument.Factory.newInstance(); PingRequestDocument.PingRequest pingRequest = requestDoc.addNewPingRequest(); pingRequest.setSubscriptionID(subscriptionID); logger.logp(Level.FINEST, CLASS_NAME, METHOD_NAME, "PingRequestDocument created"); //$NON-NLS-1$ logger.logp(Level.FINER, CLASS_NAME, METHOD_NAME, "Sending pingRequest(" + subscriptionID + ") to device " //$NON-NLS-1$ //$NON-NLS-2$ + device.getHostname() + ":" + device.getAMPPort()); //$NON-NLS-1$ /* Send request to device */ StringBuffer outMessage = new StringBuffer(requestDoc.xmlText(soapHelper.getOptions())); Node responseDocXml = soapHelper.call(device, outMessage); outMessage.delete(0,outMessage.length()); outMessage = null; requestDoc.setNil(); requestDoc = null; /* Parse the request into a PingResponse */ PingResponse result = null; try{ PingResponseDocument responseDoc = PingResponseDocument.Factory.parse(responseDocXml); PingResponseDocument.PingResponse pingResponse = responseDoc.getPingResponse(); if (pingResponse == null){ Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.noPingResp",params); AMPException e = new AMPException(message,"wamt.amp.defaultV2Provider.CommandsImpl.noPingResp",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, e); throw e; } com.datapower.schemas.appliance.management.x20.SubscriptionState.Enum subState = pingResponse.getSubscriptionState(); String subStateString = null; if (subState != null) subStateString = subState.toString(); else{ Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.noSubStateInPing",params); AMPException e = new AMPException(message,"wamt.amp.defaultV2Provider.CommandsImpl.noSubStateInPing",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, e); throw e; } if (subStateString.equalsIgnoreCase(SubscriptionResponseCode.ACTIVE.toString())) result = new PingResponse(com.ibm.datapower.amt.amp.SubscriptionState.ACTIVE); else if (subStateString.equalsIgnoreCase(SubscriptionResponseCode.NONE.toString())) result = new PingResponse(com.ibm.datapower.amt.amp.SubscriptionState.NONE); else if (subStateString.equalsIgnoreCase(SubscriptionResponseCode.FAULT.toString())) result = new PingResponse(com.ibm.datapower.amt.amp.SubscriptionState.FAULT); } catch (XmlException e){ Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.errParseSubResp",params); AMPException ex = new AMPException(message,e,"wamt.amp.defaultV2Provider.CommandsImpl.errParseSubResp",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, ex); throw ex; } catch (XmlValueOutOfRangeException e){ Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.invalidEnumPingResp",params); AMPException ex = new AMPException(message,e,"wamt.amp.defaultV2Provider.CommandsImpl.invalidEnumPingResp",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, ex); throw ex; } logger.exiting(CLASS_NAME, METHOD_NAME, result); return result; } /* (non-Javadoc) * @see com.ibm.datapower.amt.amp.Commands#getDeviceMetaInfo(com.ibm.datapower.amt.amp.DeviceContext) */ public DeviceMetaInfo getDeviceMetaInfo(DeviceContext device) throws InvalidCredentialsException, DeviceExecutionException, AMPIOException, AMPException { final String METHOD_NAME = "getDeviceMetaInfo"; //$NON-NLS-1$ logger.entering(CLASS_NAME, METHOD_NAME, device); GetDeviceInfoRequestDocument requestDoc = GetDeviceInfoRequestDocument.Factory.newInstance(); //GetDeviceInfoRequestDocument.GetDeviceInfoRequest getDeviceInfoRequest = requestDoc.addNewGetDeviceInfoRequest(); logger.logp(Level.FINEST, CLASS_NAME, METHOD_NAME, "getDeviceInfoRequest created"); //$NON-NLS-1$ logger.logp(Level.FINER, CLASS_NAME, METHOD_NAME, "Sending getDeviceInfoRequest to device " //$NON-NLS-1$ + device.getHostname() + ":" + device.getAMPPort()); //$NON-NLS-1$ /* Send request to device */ StringBuffer outMessage = new StringBuffer(requestDoc.xmlText(soapHelper.getOptions())); Node responseDocXml = soapHelper.call(device, outMessage); outMessage.delete(0,outMessage.length()); outMessage = null; requestDoc.setNil(); requestDoc = null; /* Parse the request into a DeviceMetaInfo object */ try{ GetDeviceInfoResponseDocument responseDoc = GetDeviceInfoResponseDocument.Factory.parse(responseDocXml); GetDeviceInfoResponseDocument.GetDeviceInfoResponse getDeviceInfoResponse = responseDoc.getGetDeviceInfoResponse(); if (getDeviceInfoResponse == null){ Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.noRespgetDevInfo",params); AMPException e = new AMPException(message,"wamt.amp.defaultV2Provider.CommandsImpl.noRespgetDevInfo",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, e); throw e; } String deviceName = getDeviceInfoResponse.getDeviceName(); String currentAMPVersion = Device.getCurrentAMPVersionFromGetDeviceInfoResponse(getDeviceInfoResponse.getCurrentAMPVersion()); String serialNumber = getDeviceInfoResponse.getDeviceSerialNo(); String responseDeviceType = getDeviceInfoResponse.getDeviceType(); if ((responseDeviceType == null) || (responseDeviceType.length() == 0)) { Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.devTypNotSpecified",params); AMPException e = new AMPException(message,"wamt.amp.defaultV2Provider.CommandsImpl.devTypNotSpecified",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, e); throw e; } com.ibm.datapower.amt.DeviceType deviceType = null; deviceType = com.ibm.datapower.amt.DeviceType.fromString(responseDeviceType); String versionComposite = getDeviceInfoResponse.getFirmwareVersion(); int periodIndex = versionComposite.indexOf("."); //$NON-NLS-1$ String firmwareLevel = versionComposite.substring(periodIndex + 1); ModelType modelType = Device.getModelTypeFromDeviceID(getDeviceInfoResponse.getDeviceID()); String hardwareOptions = Device.getHardwareOptionsFromDeviceID(getDeviceInfoResponse.getDeviceID()); StringCollection featureLicenses = new StringCollection(); String[] deviceFeaturesArray = getDeviceInfoResponse.getDeviceFeatureArray(); if (deviceFeaturesArray != null){ for (int i = 0; i < deviceFeaturesArray.length; i++) featureLicenses.add(deviceFeaturesArray[i]); } int webGUIPort = -1; ManagementInterface[] mgmtArray = getDeviceInfoResponse.getManagementInterfaceArray(); if (mgmtArray != null){ for (int i = 0; i < mgmtArray.length; i++){ if (mgmtArray[i].getType() == ManagementType.WEB_MGMT){ try{ webGUIPort = Integer.parseInt(mgmtArray[i].getStringValue()); } catch (NumberFormatException nfe){ String message = Messages.getString("wamt.amp.defaultProvider.SOAPHelper.invalidWebGUIPort"); AMPException e = new AMPException(message,"wamt.amp.defaultProvider.SOAPHelper.invalidWebGUIPort"); //$NON-NLS-1$ logger.throwing(CLASS_NAME, METHOD_NAME, e); throw e; } break; } } } int supportedCommands[] = new int[]{ Commands.BACKUP_DEVICE, Commands.DELETE_DOMAIN, Commands.GET_DEVICE_METAINFO, Commands.GET_DOMAIN, Commands.GET_DOMAIN_DIFFERENCES, Commands.GET_DOMAIN_LIST, Commands.GET_DOMAIN_STATUS, Commands.GET_ERROR_REPORT, Commands.GET_KEY_FILENAMES, Commands.GET_SAML_TOKEN, Commands.IS_DOMAIN_DIFFERENT, Commands.PING_DEVICE, Commands.QUIESCE_DEVICE, Commands.QUIESCE_DOMAIN, Commands.REBOOT, Commands.RESTART_DOMAIN, Commands.RESTORE_DEVICE, Commands.SET_DOMAIN, Commands.SET_FILE, Commands.SET_FIRMWARE_IMAGE, Commands.SET_FIRMWARE_STREAM, Commands.START_DOMAIN, Commands.STOP_DOMAIN, Commands.SUBSCRIBE_TO_DEVICE, Commands.UNSUBSCRIBE_FROM_DEVICE, Commands.UNQUIESCE_DEVICE, Commands.UNQUIESCE_DOMAIN}; DeviceMetaInfo result = new DeviceMetaInfo(deviceName, serialNumber, currentAMPVersion, modelType, hardwareOptions, webGUIPort, deviceType, firmwareLevel, featureLicenses, supportedCommands); logger.exiting(CLASS_NAME, METHOD_NAME, result); return result; } catch (XmlException e){ Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.errParseDevMetaInfo",params); AMPException ex = new AMPException(message,e,"wamt.amp.defaultV2Provider.CommandsImpl.errParseDevMetaInfo",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, ex); throw ex; } catch (XmlValueOutOfRangeException e){ Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.invalidEnumDevMetaInfo",params); AMPException ex = new AMPException(message,e,"wamt.amp.defaultV2Provider.CommandsImpl.invalidEnumDevMetaInfo",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, ex); throw ex; } } /* (non-Javadoc) * @see com.ibm.datapower.amt.amp.Commands#reboot(com.ibm.datapower.amt.amp.DeviceContext) */ public void reboot(DeviceContext device) throws InvalidCredentialsException, DeviceExecutionException, AMPIOException, AMPException { final String METHOD_NAME = "reboot"; //$NON-NLS-1$ logger.entering(CLASS_NAME, METHOD_NAME, device); RebootRequestDocument requestDoc = RebootRequestDocument.Factory.newInstance(); RebootRequestDocument.RebootRequest rebootRequest = requestDoc.addNewRebootRequest(); rebootRequest.setMode(RebootMode.REBOOT); logger.logp(Level.FINEST, CLASS_NAME, METHOD_NAME, "rebootRequest created"); //$NON-NLS-1$ logger.logp(Level.FINER, CLASS_NAME, METHOD_NAME, "Sending rebootRequest to device " //$NON-NLS-1$ + device.getHostname() + ":" + device.getAMPPort()); //$NON-NLS-1$ /* Send request to device */ StringBuffer outMessage = new StringBuffer(requestDoc.xmlText(soapHelper.getOptions())); Node responseDocXml = soapHelper.call(device, outMessage); outMessage.delete(0,outMessage.length()); outMessage = null; requestDoc.setNil(); requestDoc = null; /* Parse the request into a RebootResponse object */ try{ RebootResponseDocument responseDoc = RebootResponseDocument.Factory.parse(responseDocXml); RebootResponseDocument.RebootResponse rebootResponse = responseDoc.getRebootResponse(); if (rebootResponse == null){ Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.rebootNoResp",params); AMPException e = new AMPException(message,"wamt.amp.defaultV2Provider.CommandsImpl.rebootNoResp",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, e); throw e; } Status.Enum rebootStatus = rebootResponse.getStatus(); if (rebootStatus == null){ Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.rebootNoStat",params); AMPException e = new AMPException(message,"wamt.amp.defaultV2Provider.CommandsImpl.rebootNoStat",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, e); throw e; } if (rebootStatus.equals(Status.OK)){ logger.exiting(CLASS_NAME, METHOD_NAME); return; } else{ Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.rebootError",params); DeviceExecutionException e = new DeviceExecutionException(message,"wamt.amp.defaultV2Provider.CommandsImpl.rebootError",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, e); throw e; } } catch (XmlException e){ Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.errParseRebootResp",params); AMPException ex = new AMPException(message,e,"wamt.amp.defaultV2Provider.CommandsImpl.errParseRebootResp",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, ex); throw ex; } catch (XmlValueOutOfRangeException e){ Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.invalidEnumReboot",params); AMPException ex = new AMPException(message,e,"wamt.amp.defaultV2Provider.CommandsImpl.invalidEnumReboot",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, ex); throw ex; } } /* (non-Javadoc) * @see com.ibm.datapower.amt.amp.Commands#getDomainList(com.ibm.datapower.amt.amp.DeviceContext) */ public String[] getDomainList(DeviceContext device) throws InvalidCredentialsException, DeviceExecutionException, AMPIOException, AMPException { final String METHOD_NAME = "getDomainList"; //$NON-NLS-1$ logger.entering(CLASS_NAME, METHOD_NAME, device); GetDomainListRequestDocument requestDoc = GetDomainListRequestDocument.Factory.newInstance(); //GetDomainListRequestDocument.GetDomainListRequest getDomainListRequest = requestDoc.addNewGetDomainListRequest(); logger.logp(Level.FINEST, CLASS_NAME, METHOD_NAME, "getDomainListRequest created"); //$NON-NLS-1$ logger.logp(Level.FINER, CLASS_NAME, METHOD_NAME, "Sending getDomainListRequest to device " //$NON-NLS-1$ + device.getHostname() + ":" + device.getAMPPort()); //$NON-NLS-1$ /* Send request to device */ StringBuffer outMessage = new StringBuffer(requestDoc.xmlText(soapHelper.getOptions())); Node responseDocXml = soapHelper.call(device, outMessage); outMessage.delete(0,outMessage.length()); outMessage = null; requestDoc.setNil(); requestDoc = null; /* Parse the request into a GetDomainListResponse object */ try{ GetDomainListResponseDocument responseDoc = GetDomainListResponseDocument.Factory.parse(responseDocXml); GetDomainListResponseDocument.GetDomainListResponse getGetDomainListResponse = responseDoc.getGetDomainListResponse(); if (getGetDomainListResponse == null){ Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.getDomainListNoResp",params); AMPException e = new AMPException(message,"wamt.amp.defaultV2Provider.CommandsImpl.getDomainListNoResp",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, e); throw e; } String[] result = getGetDomainListResponse.getDomainArray(); logger.exiting(CLASS_NAME, METHOD_NAME, result); return result; } catch (XmlException e){ Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.errParseDomainGetDomList",params); AMPException ex = new AMPException(message,e,"wamt.amp.defaultV2Provider.CommandsImpl.errParseDomainGetDomList",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, ex); throw ex; } catch (XmlValueOutOfRangeException e){ Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.invalidEnumGetDomList",params); AMPException ex = new AMPException(message,e,"wamt.amp.defaultV2Provider.CommandsImpl.invalidEnumGetDomList",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, ex); throw ex; } } /* (non-Javadoc) * @see com.ibm.datapower.amt.amp.Commands#getDomain(com.ibm.datapower.amt.amp.DeviceContext, java.lang.String) */ public byte[] getDomain(DeviceContext device, String domainName) throws NotExistException, InvalidCredentialsException, DeviceExecutionException, AMPIOException, AMPException { final String METHOD_NAME = "getDomain"; //$NON-NLS-1$ logger.entering(CLASS_NAME, METHOD_NAME, new Object[]{device, domainName}); GetDomainExportRequestDocument requestDoc = GetDomainExportRequestDocument.Factory.newInstance(); GetDomainExportRequestDocument.GetDomainExportRequest getDomainExportRequest = requestDoc.addNewGetDomainExportRequest(); // set domain name getDomainExportRequest.setDomain(domainName); logger.logp(Level.FINEST, CLASS_NAME, METHOD_NAME, "getDomainExportRequest(" + domainName + ") created"); //$NON-NLS-1$ //$NON-NLS-2$ logger.logp(Level.FINER, CLASS_NAME, METHOD_NAME, "Sending getDomainExportRequest(" + domainName + ") to device " //$NON-NLS-1$ //$NON-NLS-2$ + device.getHostname() + ":" + device.getAMPPort()); //$NON-NLS-1$ /* Send request to device */ StringBuffer outMessage = new StringBuffer(requestDoc.xmlText(soapHelper.getOptions())); Node responseDocXml = soapHelper.call(device, outMessage); outMessage.delete(0,outMessage.length()); outMessage = null; requestDoc.setNil(); requestDoc = null; /* Parse the request into a GetDomainExportResponse object */ try{ GetDomainExportResponseDocument responseDoc = GetDomainExportResponseDocument.Factory.parse(responseDocXml); GetDomainExportResponseDocument.GetDomainExportResponse getGetDomainExportResponse = responseDoc.getGetDomainExportResponse(); if (getGetDomainExportResponse == null){ Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.getDomListNoResp",params); AMPException e = new AMPException(message,"wamt.amp.defaultV2Provider.CommandsImpl.getDomListNoResp",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, e); throw e; } Backup backup = getGetDomainExportResponse.getConfig(); if (backup == null){ //fix for cs # 59219 Status.Enum status = getGetDomainExportResponse.getStatus(); if (status == null){ Object[] params = {domainName,device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.noDomainElt",params); AMPException e = new AMPException(message,"wamt.amp.defaultV2Provider.CommandsImpl.noDomainElt",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, e); throw e; } else if (status.equals(Status.ERROR)){ Object[] params = {domainName,device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.errorGetDom",params); DeviceExecutionException e = new DeviceExecutionException(message,"wamt.amp.defaultV2Provider.CommandsImpl.errorGetDom",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, e); throw e; } else { Object[] params = {domainName,device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.noDomainRec",params); AMPException e = new AMPException(message,"wamt.amp.defaultV2Provider.CommandsImpl.noDomainRec",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, e); throw e; } } else if (backup.isNil()){ Object[] params = {domainName,device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.noDomainRec",params); NotExistException e = new NotExistException(message,"wamt.amp.defaultV2Provider.CommandsImpl.noDomainRec",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, e); throw e; } //byte[] result = backup.getByteArrayValue(); byte[] result = backup.getStringValue().getBytes(); logger.exiting(CLASS_NAME, METHOD_NAME, result); return result; } catch (XmlException e){ Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.errParseDomainResp",params); AMPException ex = new AMPException(message,e,"wamt.amp.defaultV2Provider.CommandsImpl.errParseDomainResp",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, ex); throw ex; } catch (XmlValueOutOfRangeException e){ Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.invalidEnumInDomainResp",params); AMPException ex = new AMPException(message,e,"wamt.amp.defaultV2Provider.CommandsImpl.invalidEnumInDomainResp",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, ex); throw ex; } } /* (non-Javadoc) * @see com.ibm.datapower.amt.amp.Commands#setDomain(com.ibm.datapower.amt.amp.DeviceContext, byte[]) */ public void setDomain(DeviceContext device, String domainName, byte[] domainImage, DeploymentPolicy policy) throws InvalidCredentialsException,DeviceExecutionException, AMPIOException, AMPException, DeletedException { final String METHOD_NAME = "setDomain"; //$NON-NLS-1$ logger.entering(CLASS_NAME, METHOD_NAME); SetDomainExportRequestDocument requestDoc = SetDomainExportRequestDocument.Factory.newInstance(); SetDomainExportRequestDocument.SetDomainExportRequest setDomainExportRequest = requestDoc.addNewSetDomainExportRequest(); // Backup image Backup image = setDomainExportRequest.addNewConfig(); image.setStringValue(new String(domainImage)); image.setDomain(domainName); // reset domain setDomainExportRequest.setResetDomain(true); // deployment policy DeploymentPolicyConfiguration deppol = null; if (policy != null){ switch (policy.getPolicyType()){ case EXPORT: deppol = setDomainExportRequest.addNewPolicyConfiguration(); deppol.setStringValue(new String(policy.getCachedBytes())); deppol.setPolicyDomainName(policy.getPolicyDomainName()); deppol.setPolicyObjectName(policy.getPolicyObjectName()); logger.logp(Level.FINEST, CLASS_NAME, METHOD_NAME, "setDomainExportRequest(" + domainName + ") " + "deployment policy (" + policy.getPolicyType().name() + "," + policy.getPolicyDomainName() + "," + policy.getPolicyObjectName() + ") set."); //$NON-NLS-1$ //$NON-NLS-2$ break; case XML: com.datapower.schemas.appliance.management.x20.DeploymentPolicy xmlpolicy; com.datapower.schemas.appliance.management.x20.DeploymentPolicy.ModifiedConfig modifiedConfig; // Parse the policy String xmlFragment = new String(policy.getCachedBytes()); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); Document doc = null; try{ DocumentBuilder db = dbf.newDocumentBuilder(); doc = db.parse(new InputSource(new StringReader(xmlFragment))); } catch (ParserConfigurationException exception){ Object[] params = new Object[] {device.getHostname()}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.setDomainInvalidPolicy",params); AMPException e = new AMPException(message,"wamt.amp.defaultV2Provider.CommandsImpl.setDomainInvalidPolicy",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, e); throw e; } catch (SAXException exception) { Object[] params = new Object[] {device.getHostname()}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.setDomainInvalidPolicy",params); AMPException e = new AMPException(message,"wamt.amp.defaultV2Provider.CommandsImpl.setDomainInvalidPolicy",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, e); throw e; } catch (IOException exception) { Object[] params = new Object[] {device.getHostname()}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.setDomainInvalidPolicy",params); AMPException e = new AMPException(message,"wamt.amp.defaultV2Provider.CommandsImpl.setDomainInvalidPolicy",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, e); throw e; } // Walk the nodes and generate the policy in the request Node node = (Node)doc; NodeList policyNode = node.getChildNodes(); for (int i=0; i<policyNode.getLength(); i++){ logger.logp(Level.FINEST, CLASS_NAME, METHOD_NAME, "setDomainExportRequest(" + domainName + ") " + "deployment policy (" + policy.getPolicyType().name() + ":" + policyNode.item(i).getNodeName() + ")"); //$NON-NLS-1$ //$NON-NLS-2$ if (policyNode.item(i).getNodeName().equalsIgnoreCase("policy")){ xmlpolicy = setDomainExportRequest.addNewPolicy(); NodeList configNodes = policyNode.item(i).getChildNodes(); for (int j=0; j<configNodes.getLength(); j++){ if (configNodes.item(j).getNodeName().equalsIgnoreCase("modifiedconfig")){ logger.logp(Level.FINEST, CLASS_NAME, METHOD_NAME, "setDomainExportRequest(" + domainName + ") " + "deployment policy (" + policy.getPolicyType().name() + ":" + configNodes.item(j).getNodeName() + ")"); //$NON-NLS-1$ //$NON-NLS-2$ modifiedConfig = xmlpolicy.addNewModifiedConfig(); NodeList propertyNodes = configNodes.item(j).getChildNodes(); for (int k=0; k<propertyNodes.getLength(); k++){ boolean logProperty = true; if (propertyNodes.item(k).getNodeName().equalsIgnoreCase("match")){ modifiedConfig.setMatch(propertyNodes.item(k).getTextContent()); } else if (propertyNodes.item(k).getNodeName().equalsIgnoreCase("type")){ modifiedConfig.setType(com.datapower.schemas.appliance.management.x20.PolicyType.CHANGE); } else if (propertyNodes.item(k).getNodeName().equalsIgnoreCase("property")){ modifiedConfig.setProperty(propertyNodes.item(k).getTextContent()); } else if (propertyNodes.item(k).getNodeName().equalsIgnoreCase("value")){ modifiedConfig.setValue(propertyNodes.item(k).getTextContent()); } else { logProperty = false; } // log if needed if (logProperty){ logger.logp(Level.FINEST, CLASS_NAME, METHOD_NAME, "setDomainExportRequest(" + domainName + ") " + "deployment policy (" + policy.getPolicyType().name() + ":" + propertyNodes.item(k).getNodeName() + ":" + propertyNodes.item(k).getTextContent() + ")"); //$NON-NLS-1$ //$NON-NLS-2$ } } } else if (configNodes.item(j).getNodeName().equalsIgnoreCase("acceptedconfig")){ logger.logp(Level.FINEST, CLASS_NAME, METHOD_NAME, "setDomainExportRequest(" + domainName + ") " + "deployment policy (" + policy.getPolicyType().name() + ":" + configNodes.item(j).getNodeName() + ":" + configNodes.item(j).getTextContent() + ")"); //$NON-NLS-1$ //$NON-NLS-2$ xmlpolicy.addAcceptedConfig(configNodes.item(j).getTextContent()); } else if (configNodes.item(j).getNodeName().equalsIgnoreCase("filteredconfig")){ logger.logp(Level.FINEST, CLASS_NAME, METHOD_NAME, "setDomainExportRequest(" + domainName + ") " + "deployment policy (" + policy.getPolicyType().name() + ":" + configNodes.item(j).getNodeName() + ":" + configNodes.item(j).getTextContent() + ")"); //$NON-NLS-1$ //$NON-NLS-2$ xmlpolicy.addFilteredConfig(configNodes.item(j).getTextContent()); } } } } break; /* case REFERENCE: setDomainExportRequest.setPolicyObjectName(policy.getPolicyObjectName()); logger.logp(Level.FINEST, CLASS_NAME, METHOD_NAME, "setDomainExportRequest(" + domainName + ") " + "deployment policy (" + policy.getPolicyType().name() + "," + policy.getPolicyObjectName() + ") set."); //$NON-NLS-1$ //$NON-NLS-2$ break;*/ default: logger.logp(Level.FINEST, CLASS_NAME, METHOD_NAME, "setDomainExportRequest(" + domainName + ") " + "deployment policy type (" + policy.getPolicyType().name() + ")is unsupported."); //$NON-NLS-1$ //$NON-NLS-2$ break; } } logger.logp(Level.FINEST, CLASS_NAME, METHOD_NAME, "setDomainExportRequest(" + domainName + ") created"); //$NON-NLS-1$ //$NON-NLS-2$ logger.logp(Level.FINER, CLASS_NAME, METHOD_NAME, "Sending setDomainExportRequest(" + domainName + ") to device " //$NON-NLS-1$ //$NON-NLS-2$ + device.getHostname() + ":" + device.getAMPPort()); //$NON-NLS-1$ /* Send request to device */ StringBuffer outMessage = new StringBuffer(requestDoc.xmlText(soapHelper.getOptions())); Node responseDocXml = soapHelper.call(device, outMessage); outMessage.delete(0,outMessage.length()); outMessage = null; requestDoc.setNil(); requestDoc = null; /* Parse the request into a SetDomainExportResponse object */ try{ SetDomainExportResponseDocument responseDoc = SetDomainExportResponseDocument.Factory.parse(responseDocXml); SetDomainExportResponseDocument.SetDomainExportResponse getSetDomainExportResponse = responseDoc.getSetDomainExportResponse(); if (getSetDomainExportResponse == null){ Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.setDomainNoResp",params); AMPException e = new AMPException(message,"wamt.amp.defaultV2Provider.CommandsImpl.setDomainNoResp",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, e); throw e; } // Use as a string to allow different error return codes. String status = getSetDomainExportResponse.getStatus(); if (status == null){ Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.noStatSetDomain",params); AMPException e = new AMPException(message,"wamt.amp.defaultV2Provider.CommandsImpl.noStatSetDomain",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, e); throw e; } if (status.equals(Status.OK.toString())){ logger.exiting(CLASS_NAME,METHOD_NAME); return; } else{ Object[] params = {domainName, device.getHostname(),Integer.toString(device.getAMPPort()), status}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.loadDomainFail",params); DeviceExecutionException e = new DeviceExecutionException(message,"wamt.amp.defaultV2Provider.CommandsImpl.loadDomainFail",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, e); throw e; } } catch (XmlException e){ Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.errParseSetDom",params); AMPException ex = new AMPException(message,e,"wamt.amp.defaultV2Provider.CommandsImpl.errParseSetDom",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, ex); throw ex; } catch (XmlValueOutOfRangeException e){ Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.invalidEnumSetDom",params); AMPException ex = new AMPException(message,e,"wamt.amp.defaultV2Provider.CommandsImpl.invalidEnumSetDom",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, ex);; throw ex; } } /* (non-Javadoc) * @see com.ibm.datapower.amt.amp.Commands#deleteDomain(com.ibm.datapower.amt.amp.DeviceContext, java.lang.String) */ public void deleteDomain(DeviceContext device, String domainName) throws NotExistException, InvalidCredentialsException, DeviceExecutionException, AMPIOException, AMPException { final String METHOD_NAME = "deleteDomain"; //$NON-NLS-1$ logger.entering(CLASS_NAME, METHOD_NAME, new Object[]{device, domainName}); DeleteDomainRequestDocument requestDoc = DeleteDomainRequestDocument.Factory.newInstance(); DeleteDomainRequestDocument.DeleteDomainRequest deleteDomainRequest = requestDoc.addNewDeleteDomainRequest(); deleteDomainRequest.setDomain(domainName); logger.logp(Level.FINEST, CLASS_NAME, METHOD_NAME, "deleteDomainRequest(" + domainName + ") created"); //$NON-NLS-1$ //$NON-NLS-2$ logger.logp(Level.FINER, CLASS_NAME, METHOD_NAME, "Sending deleteDomainRequest(" + domainName + ") to device " //$NON-NLS-1$ //$NON-NLS-2$ + device.getHostname() + ":" + device.getAMPPort()); //$NON-NLS-1$ /* Send request to device */ StringBuffer outMessage = new StringBuffer(requestDoc.xmlText(soapHelper.getOptions())); Node responseDocXml = soapHelper.call(device, outMessage); outMessage.delete(0,outMessage.length()); outMessage = null; requestDoc.setNil(); requestDoc = null; /* Parse the request into a DeleteDomainResponse object */ try{ DeleteDomainResponseDocument responseDoc = DeleteDomainResponseDocument.Factory.parse(responseDocXml); DeleteDomainResponseDocument.DeleteDomainResponse getDeleteDomainResponse = responseDoc.getDeleteDomainResponse(); if (getDeleteDomainResponse == null){ Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.delDomainNoResp",params); AMPException e = new AMPException(message,"wamt.amp.defaultV2Provider.CommandsImpl.delDomainNoResp",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, e); throw e; } Status.Enum status = getDeleteDomainResponse.getStatus(); if (status == null){ Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.noStatDelDomain",params); AMPException e = new AMPException(message,"wamt.amp.defaultV2Provider.CommandsImpl.noStatDelDomain",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, e); throw e; } if (status.equals(Status.OK)){ logger.exiting(CLASS_NAME,METHOD_NAME); return; } else{ Object[] params = {domainName, device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.delDomainFail",params); DeviceExecutionException e = new DeviceExecutionException(message,"wamt.amp.defaultV2Provider.CommandsImpl.delDomainFail",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, e); throw e; } } catch (XmlException e){ Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.errParseDelDomain",params); AMPException ex = new AMPException(message,e,"wamt.amp.defaultV2Provider.CommandsImpl.errParseDelDomain",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, ex); throw ex; } catch (XmlValueOutOfRangeException e){ Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.invalidEnumDelDom",params); AMPException ex = new AMPException(message,e,"wamt.amp.defaultV2Provider.CommandsImpl.invalidEnumDelDom",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, ex); throw ex; } } /* (non-Javadoc) * @see com.ibm.datapower.amt.amp.Commands#getDomainStatus(com.ibm.datapower.amt.amp.DeviceContext, java.lang.String) */ public DomainStatus getDomainStatus(DeviceContext device, String domainName) throws NotExistException, InvalidCredentialsException, DeviceExecutionException, AMPIOException, AMPException { final String METHOD_NAME = "getDomainStatus"; //$NON-NLS-1$ logger.entering(CLASS_NAME, METHOD_NAME, new Object[]{device, domainName}); GetDomainStatusRequestDocument requestDoc = GetDomainStatusRequestDocument.Factory.newInstance(); GetDomainStatusRequestDocument.GetDomainStatusRequest getDomainStatusRequest = requestDoc.addNewGetDomainStatusRequest(); getDomainStatusRequest.setDomain(domainName); logger.logp(Level.FINEST, CLASS_NAME, METHOD_NAME, "getDomainStatusRequest(" + domainName + ") created"); //$NON-NLS-1$ //$NON-NLS-2$ logger.logp(Level.FINER, CLASS_NAME, METHOD_NAME, "Sending getDomainStatusRequest(" + domainName + ") to device " //$NON-NLS-1$ //$NON-NLS-2$ + device.getHostname() + ":" + device.getAMPPort()); //$NON-NLS-1$ // Send request to device StringBuffer outMessage = new StringBuffer(requestDoc.xmlText(soapHelper.getOptions())); Node responseDocXml = soapHelper.call(device, outMessage); outMessage.delete(0,outMessage.length()); outMessage = null; requestDoc.setNil(); requestDoc = null; // Parse the request into a GetDomainStatusResponse object try{ GetDomainStatusResponseDocument responseDoc = GetDomainStatusResponseDocument.Factory.parse(responseDocXml); GetDomainStatusResponseDocument.GetDomainStatusResponse getGetDomainStatusResponse = responseDoc.getGetDomainStatusResponse(); if (getGetDomainStatusResponse == null){ Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.getDomNoResp",params); AMPException e = new AMPException(message,"wamt.amp.defaultV2Provider.CommandsImpl.getDomNoResp",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, e); throw e; } GetDomainStatusResponseDocument.GetDomainStatusResponse.Domain domain = getGetDomainStatusResponse.getDomain(); if (domain == null){ // see cs tracker # 59517 for more explanation about the following code // if domain isn't here, then we can't have an OpState! // therefore, if we get here, and there is no status (or there is one, // and its == 'ok'), then throw an exception as this is a REALLY weird case. // in dp build 137835+, this might return a <status>error</status> to represent // a non existant domain Status.Enum status = getGetDomainStatusResponse.getStatus(); if (status == null){ Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.getDomNoStat",params); AMPException e = new AMPException(message,"wamt.amp.defaultV2Provider.CommandsImpl.getDomNoStat",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, e); throw e; } else if (status.equals(Status.ERROR)){ Object[] params = {domainName,device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.noDomStatRet",params); NotExistException ex = new NotExistException(message,"wamt.amp.defaultV2Provider.CommandsImpl.noDomStatRet",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, ex); throw ex; } else { Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.noDomainSpec",params); AMPException e = new AMPException(message,"wamt.amp.defaultV2Provider.CommandsImpl.noDomainSpec",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, e); throw e; } } // domain object exists, which means we either have a good message, or a <=3.6.0.3 // firmware level // workaround below for bug in 3.6.0.3 (dp build 137758) OpState.Enum opState = null; try{ opState = domain.getOpState(); } catch (XmlValueOutOfRangeException e){ // a null opState == non existant domain Object[] params = {domainName,device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.noDomStatRet",params); NotExistException ex = new NotExistException(message,e,"wamt.amp.defaultV2Provider.CommandsImpl.noDomStatRet",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, ex); throw ex; } if (opState == null){ Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.opnStatNotSpec",params); AMPException e = new AMPException(message,"wamt.amp.defaultV2Provider.CommandsImpl.opnStatNotSpec",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, e); throw e; } OperationStatus opStatus; if (opState.toString().equalsIgnoreCase(OperationStatus.Enumerated.UP.toString())) opStatus = new OperationStatus(OperationStatus.Enumerated.UP); else if (opState.toString().equalsIgnoreCase(OperationStatus.Enumerated.DOWN.toString())) opStatus = new OperationStatus(OperationStatus.Enumerated.DOWN); else if (opState.toString().equalsIgnoreCase(OperationStatus.Enumerated.PARTIAL.toString())) opStatus = new OperationStatus(OperationStatus.Enumerated.PARTIAL); else if (opState.toString().equalsIgnoreCase(OperationStatus.Enumerated.UNKNOWN.toString())) opStatus = new OperationStatus(OperationStatus.Enumerated.UNKNOWN); else{ Object[] params = {opState.toString(),device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.invalidOpnStatGet",params); AMPException e = new AMPException(message,"wamt.amp.defaultV2Provider.CommandsImpl.invalidOpnStatGet",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, e); throw e; } ConfigState.Enum configState = domain.getConfigState(); if (configState == null){ Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.noConfigStat",params); AMPException e = new AMPException(message,"wamt.amp.defaultV2Provider.CommandsImpl.noConfigStat",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, e); throw e; } boolean needsSave; if (configState.toString().equalsIgnoreCase("modified")) //$NON-NLS-1$ needsSave = true; else if (configState.toString().equalsIgnoreCase("saved")) //$NON-NLS-1$ needsSave = false; else { Object[] params = {configState.toString(),device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.invalidConfigStat",params); AMPException e = new AMPException(message,"wamt.amp.defaultV2Provider.CommandsImpl.invalidConfigStat",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, e); throw e; } boolean debugState; if (domain.getDebugState() == true) debugState = true; else if (domain.getDebugState() == false) debugState = false; else { Object[] params = {Boolean.valueOf(domain.getDebugState()),device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.invalidDebugStat",params); AMPException e = new AMPException(message,"wamt.amp.defaultV2Provider.CommandsImpl.invalidDebugStat",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, e); throw e; } String quiesceState = domain.getQuiesceState(); QuiesceStatus quiesceStatus = QuiesceStatus.UNKNOWN; // default if (quiesceState.equals("")) quiesceStatus = QuiesceStatus.NORMAL; else if (quiesceState.equals("quiescing")) quiesceStatus = QuiesceStatus.QUIESCE_IN_PROGRESS; else if (quiesceState.equals("quiesced")) quiesceStatus = QuiesceStatus.QUIESCED; else if (quiesceState.equals("unquiescing")) quiesceStatus = QuiesceStatus.UNQUIESCE_IN_PROGRESS; else if (quiesceState.equals("error")) quiesceStatus = QuiesceStatus.ERROR; DomainStatus result = new DomainStatus(opStatus,needsSave,debugState,quiesceStatus); logger.exiting(CLASS_NAME, METHOD_NAME, result); return result; } catch (XmlException e){ Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.errParsingGetDomStat",params); AMPException ex = new AMPException(message,e,"wamt.amp.defaultV2Provider.CommandsImpl.errParsingGetDomStat",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, ex); throw ex; } catch (XmlValueOutOfRangeException e){ Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.invalidEnumGetDomStat",params); AMPException ex = new AMPException(message,e,"wamt.amp.defaultV2Provider.CommandsImpl.invalidEnumGetDomStat",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, ex); throw ex; } } /* (non-Javadoc) * @see com.ibm.datapower.amt.amp.Commands#startDomain(com.ibm.datapower.amt.amp.DeviceContext, java.lang.String) */ public void startDomain(DeviceContext device, String domainName) throws NotExistException, InvalidCredentialsException, DeviceExecutionException, AMPIOException, AMPException { final String METHOD_NAME = "startDomain"; //$NON-NLS-1$ logger.entering(CLASS_NAME, METHOD_NAME, new Object[]{device, domainName}); StartDomainRequestDocument requestDoc = StartDomainRequestDocument.Factory.newInstance(); StartDomainRequestDocument.StartDomainRequest startDomainRequest = requestDoc.addNewStartDomainRequest(); startDomainRequest.setDomain(domainName); logger.logp(Level.FINEST, CLASS_NAME, METHOD_NAME, "startDomainRequest(" + domainName + ") created"); //$NON-NLS-1$ //$NON-NLS-2$ logger.logp(Level.FINER, CLASS_NAME, METHOD_NAME, "Sending startDomainRequest(" + domainName + ") to device " //$NON-NLS-1$ //$NON-NLS-2$ + device.getHostname() + ":" + device.getAMPPort()); //$NON-NLS-1$ /* Send request to device */ StringBuffer outMessage = new StringBuffer(requestDoc.xmlText(soapHelper.getOptions())); Node responseDocXml = soapHelper.call(device, outMessage); outMessage.delete(0,outMessage.length()); outMessage = null; requestDoc.setNil(); requestDoc = null; /* Parse the request into a StartDomainResponse object */ try{ StartDomainResponseDocument responseDoc = StartDomainResponseDocument.Factory.parse(responseDocXml); StartDomainResponseDocument.StartDomainResponse startDomainResponse = responseDoc.getStartDomainResponse(); if (startDomainResponse == null){ Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.startDomNoResp",params); AMPException e = new AMPException(message,"wamt.amp.defaultV2Provider.CommandsImpl.startDomNoResp",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, e); throw e; } Status.Enum status = startDomainResponse.getStatus(); if (status == null){ Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.startDomNoStat",params); AMPException e = new AMPException(message,"wamt.amp.defaultV2Provider.CommandsImpl.startDomNoStat",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, e); throw e; } if (status.equals(Status.OK)){ logger.exiting(CLASS_NAME,METHOD_NAME); return; } else { Object[] params = {domainName,device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.errStartDom",params); DeviceExecutionException e = new DeviceExecutionException(message,"wamt.amp.defaultV2Provider.CommandsImpl.errStartDom",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, e); throw e; } } catch (XmlException e){ Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.errParseStartDom",params); AMPException ex = new AMPException(message,e,"wamt.amp.defaultV2Provider.CommandsImpl.errParseStartDom",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, ex); throw ex; } catch (XmlValueOutOfRangeException e){ Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.invalidEnumInStartDom",params); AMPException ex = new AMPException(message,e,"wamt.amp.defaultV2Provider.CommandsImpl.invalidEnumInStartDom",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, ex); throw ex; } } /* (non-Javadoc) * @see com.ibm.datapower.amt.amp.Commands#stopDomain(com.ibm.datapower.amt.amp.DeviceContext, java.lang.String) */ public void stopDomain(DeviceContext device, String domainName) throws NotExistException, InvalidCredentialsException, DeviceExecutionException, AMPIOException, AMPException { final String METHOD_NAME = "stopDomain"; //$NON-NLS-1$ logger.entering(CLASS_NAME, METHOD_NAME, new Object[]{device, domainName}); StopDomainRequestDocument requestDoc = StopDomainRequestDocument.Factory.newInstance(); StopDomainRequestDocument.StopDomainRequest stopDomainRequest = requestDoc.addNewStopDomainRequest(); stopDomainRequest.setDomain(domainName); logger.logp(Level.FINEST, CLASS_NAME, METHOD_NAME, "stopDomainRequest(" + domainName + ") created"); //$NON-NLS-1$ //$NON-NLS-2$ logger.logp(Level.FINER, CLASS_NAME, METHOD_NAME, "Sending stopDomainRequest(" + domainName + ") to device " //$NON-NLS-1$ //$NON-NLS-2$ + device.getHostname() + ":" + device.getAMPPort()); //$NON-NLS-1$ /* Send request to device */ StringBuffer outMessage = new StringBuffer(requestDoc.xmlText(soapHelper.getOptions())); Node responseDocXml = soapHelper.call(device, outMessage); outMessage.delete(0,outMessage.length()); outMessage = null; requestDoc.setNil(); requestDoc = null; /* Parse the request into a StopDomainResponse object */ try{ StopDomainResponseDocument responseDoc = StopDomainResponseDocument.Factory.parse(responseDocXml); StopDomainResponseDocument.StopDomainResponse stopDomainResponse = responseDoc.getStopDomainResponse(); if (stopDomainResponse == null){ Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.stopDomNoResp",params); AMPException e = new AMPException(message,"wamt.amp.defaultV2Provider.CommandsImpl.stopDomNoResp",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, e); throw e; } Status.Enum status = stopDomainResponse.getStatus(); if (status == null){ Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.stopDomNoStat",params); AMPException e = new AMPException(message,"wamt.amp.defaultV2Provider.CommandsImpl.stopDomNoStat",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, e); throw e; } if (status.equals(Status.OK)){ logger.exiting(CLASS_NAME, METHOD_NAME); return; } else { Object[] params = {domainName,device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.errStopDom",params); DeviceExecutionException e = new DeviceExecutionException(message,"wamt.amp.defaultV2Provider.CommandsImpl.errStopDom",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, e); throw e; } } catch (XmlException e){ Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.errParseStopDom",params); AMPException ex = new AMPException(message,e,"wamt.amp.defaultV2Provider.CommandsImpl.errParseStopDom",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, ex); throw ex; } catch (XmlValueOutOfRangeException e){ Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.invalidEnumStopDom",params); AMPException ex = new AMPException(message,e,"wamt.amp.defaultV2Provider.CommandsImpl.invalidEnumStopDom",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, ex); throw ex; } } /* (non-Javadoc) * @see com.ibm.datapower.amt.amp.Commands#restartDomain(com.ibm.datapower.amt.amp.DeviceContext, java.lang.String) */ public void restartDomain(DeviceContext device, String domainName) throws NotExistException, InvalidCredentialsException, DeviceExecutionException, AMPIOException, AMPException { final String METHOD_NAME = "restartDomain"; //$NON-NLS-1$ logger.entering(CLASS_NAME, METHOD_NAME, new Object[]{device, domainName}); RestartDomainRequestDocument requestDoc = RestartDomainRequestDocument.Factory.newInstance(); RestartDomainRequestDocument.RestartDomainRequest restartDomainRequest = requestDoc.addNewRestartDomainRequest(); restartDomainRequest.setDomain(domainName); logger.logp(Level.FINEST, CLASS_NAME, METHOD_NAME, "restartDomainRequest(" + domainName + ") created"); //$NON-NLS-1$ //$NON-NLS-2$ logger.logp(Level.FINER, CLASS_NAME, METHOD_NAME, "Sending restartDomainRequest(" + domainName + ") to device " //$NON-NLS-1$ //$NON-NLS-2$ + device.getHostname() + ":" + device.getAMPPort()); //$NON-NLS-1$ /* Send request to device */ StringBuffer outMessage = new StringBuffer(requestDoc.xmlText(soapHelper.getOptions())); Node responseDocXml = soapHelper.call(device, outMessage); outMessage.delete(0,outMessage.length()); outMessage = null; requestDoc.setNil(); requestDoc = null; /* Parse the request into a RestartDomainResponse object */ try{ RestartDomainResponseDocument responseDoc = RestartDomainResponseDocument.Factory.parse(responseDocXml); RestartDomainResponseDocument.RestartDomainResponse restartDomainResponse = responseDoc.getRestartDomainResponse(); if (restartDomainResponse == null){ Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.restartDomNoResp",params); AMPException e = new AMPException(message,"wamt.amp.defaultV2Provider.CommandsImpl.restartDomNoResp",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, e); throw e; } Status.Enum status = restartDomainResponse.getStatus(); if (status == null){ Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.noStatRestartDom",params); AMPException e = new AMPException(message,"wamt.amp.defaultV2Provider.CommandsImpl.noStatRestartDom",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, e); throw e; } if (status.equals(Status.OK)){ logger.exiting(CLASS_NAME, METHOD_NAME); return; } else { Object[] params = {domainName,device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.errRestartingDom",params); DeviceExecutionException e = new DeviceExecutionException(message,"wamt.amp.defaultV2Provider.CommandsImpl.errRestartingDom",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, e); throw e; } } catch (XmlException e){ Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.errParseRestDom",params); AMPException ex = new AMPException(message,e,"wamt.amp.defaultV2Provider.CommandsImpl.errParseRestDom",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, ex); throw ex; } catch (XmlValueOutOfRangeException e){ Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.invalidEnumRestartDom",params); AMPException ex = new AMPException(message,e,"wamt.amp.defaultV2Provider.CommandsImpl.invalidEnumRestartDom",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, ex); throw ex; } } /* (non-Javadoc) * @see com.ibm.datapower.amt.amp.Commands#setFirmware(com.ibm.datapower.amt.amp.DeviceContext, byte[], boolean) */ public void setFirmware(DeviceContext device, byte[] firmwareImage) throws InvalidCredentialsException,DeviceExecutionException, AMPIOException, AMPException { final String METHOD_NAME = "setFirmware(byte[]...)"; //$NON-NLS-1$ logger.entering(CLASS_NAME, METHOD_NAME); SetFirmwareRequestDocument requestDoc = SetFirmwareRequestDocument.Factory.newInstance(); SetFirmwareRequestDocument.SetFirmwareRequest setFirmwareRequest = requestDoc.addNewSetFirmwareRequest(); Firmware image = setFirmwareRequest.addNewFirmware(); image.setByteArrayValue(firmwareImage); logger.logp(Level.FINEST, CLASS_NAME, METHOD_NAME, "setFirmwareRequest created"); //$NON-NLS-1$ logger.logp(Level.FINER, CLASS_NAME, METHOD_NAME, "Sending setFirmwareRequest to device " //$NON-NLS-1$ + device.getHostname() + ":" + device.getAMPPort()); //$NON-NLS-1$ /* Send request to device */ StringBuffer outMessage = new StringBuffer(requestDoc.xmlText(soapHelper.getOptions())); Node responseDocXml = soapHelper.call(device, outMessage); outMessage.delete(0,outMessage.length()); outMessage = null; requestDoc.setNil(); requestDoc = null; /* Parse the request into a SetFirmwareResponse object */ try{ SetFirmwareResponseDocument responseDoc = SetFirmwareResponseDocument.Factory.parse(responseDocXml); SetFirmwareResponseDocument.SetFirmwareResponse getSetFirmwareResponse = responseDoc.getSetFirmwareResponse(); if (getSetFirmwareResponse == null){ Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.setFwNoResp",params); AMPException e = new AMPException(message,"wamt.amp.defaultV2Provider.CommandsImpl.setFwNoResp",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, e); throw e; } Status.Enum status = getSetFirmwareResponse.getStatus(); if (status == null){ Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.setFwNoStat",params); AMPException e = new AMPException(message,"wamt.amp.defaultV2Provider.CommandsImpl.setFwNoStat",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, e); throw e; } if (status.equals(Status.ERROR)){ Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.loadFwFail",params); DeviceExecutionException e = new DeviceExecutionException(message,"wamt.amp.defaultV2Provider.CommandsImpl.loadFwFail",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, e); throw e; } else { logger.exiting(CLASS_NAME, METHOD_NAME); return; } } catch (XmlException e){ Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.errParseSetFw",params); AMPException ex = new AMPException(message,e,"wamt.amp.defaultV2Provider.CommandsImpl.errParseSetFw",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, ex); throw ex; } catch (XmlValueOutOfRangeException e){ Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.invalidEnumSetFw",params); AMPException ex = new AMPException(message,e,"wamt.amp.defaultV2Provider.CommandsImpl.invalidEnumSetFw",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, ex); throw ex; } } /* (non-Javadoc) * @see com.ibm.datapower.amt.amp.Commands#setFirmware(com.ibm.datapower.amt.amp.DeviceContext, java.io.InputStream, boolean) */ public void setFirmware(DeviceContext device, InputStream inputStream) throws InvalidCredentialsException,DeviceExecutionException, AMPIOException, AMPException { final String METHOD_NAME = "setFirmware(InputStream...)"; //$NON-NLS-1$ logger.entering(CLASS_NAME, METHOD_NAME, new Object[]{device, inputStream}); logger.logp(Level.FINEST, CLASS_NAME, METHOD_NAME, "setFirmwareRequest created"); //$NON-NLS-1$ logger.logp(Level.FINER, CLASS_NAME, METHOD_NAME, "Sending setFirmwareRequest to device "+ device.getHostname() + //$NON-NLS-1$ ":" + device.getAMPPort()); //$NON-NLS-1$ /* Send request to device */ Node responseDocXml = soapHelper.call(device, setFirmwareHeaderBytes, setFirmwareFooterBytes, inputStream); /* Parse the request into a SetFirmwareResponse object */ try{ SetFirmwareResponseDocument responseDoc = SetFirmwareResponseDocument.Factory.parse(responseDocXml); SetFirmwareResponseDocument.SetFirmwareResponse getSetFirmwareResponse = responseDoc.getSetFirmwareResponse(); if (getSetFirmwareResponse == null){ Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.setFwNoResp",params); AMPException e = new AMPException(message,"wamt.amp.defaultV2Provider.CommandsImpl.setFwNoResp",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, e); throw e; } Status.Enum status = getSetFirmwareResponse.getStatus(); if (status == null){ Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.setFwNoStat",params); AMPException e = new AMPException(message,"wamt.amp.defaultV2Provider.CommandsImpl.setFwNoStat",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, e); throw e; } if (status.equals(Status.ERROR)){ Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.loadFwFail",params); DeviceExecutionException e = new DeviceExecutionException(message,"wamt.amp.defaultV2Provider.CommandsImpl.loadFwFail",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, e); throw e; } else { logger.exiting(CLASS_NAME, METHOD_NAME); return; } } catch (XmlException e){ Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.errParseSetFw",params); AMPException ex = new AMPException(message,e,"wamt.amp.defaultV2Provider.CommandsImpl.errParseSetFw",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, ex); throw ex; } catch (XmlValueOutOfRangeException e){ Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.invalidEnumSetFw",params); AMPException ex = new AMPException(message,e,"wamt.amp.defaultV2Provider.CommandsImpl.invalidEnumSetFw",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, ex); throw ex; } } /* (non-Javadoc) * @see com.ibm.datapower.amt.amp.Commands#getKeyFilenames(com.ibm.datapower.amt.amp.DeviceContext, java.lang.String) */ public String[] getKeyFilenames(DeviceContext device, String domainName) throws InvalidCredentialsException, DeviceExecutionException, AMPIOException, AMPException { final String METHOD_NAME = "getKeyFilenames"; //$NON-NLS-1$ logger.entering(CLASS_NAME, METHOD_NAME, new Object[]{device, domainName}); GetCryptoArtifactsRequestDocument requestDoc = GetCryptoArtifactsRequestDocument.Factory.newInstance(); GetCryptoArtifactsRequestDocument.GetCryptoArtifactsRequest getCryptoArtifactsRequest = requestDoc.addNewGetCryptoArtifactsRequest(); getCryptoArtifactsRequest.setDomain(domainName); logger.logp(Level.FINEST, CLASS_NAME, METHOD_NAME, "getCryptoArtifactsRequest created"); //$NON-NLS-1$ logger.logp(Level.FINER, CLASS_NAME, METHOD_NAME, "Sending getCryptoArtifactsRequest(" + domainName + ") to device " //$NON-NLS-1$ //$NON-NLS-2$ + device.getHostname() + ":" + device.getAMPPort()); //$NON-NLS-1$ /* Send request to device */ StringBuffer outMessage = new StringBuffer(requestDoc.xmlText(soapHelper.getOptions())); Node responseDocXml = soapHelper.call(device, outMessage); outMessage.delete(0,outMessage.length()); outMessage = null; requestDoc.setNil(); requestDoc = null; /* Parse the request into a GetDomainListResponse object */ try{ GetCryptoArtifactsResponseDocument responseDoc = GetCryptoArtifactsResponseDocument.Factory.parse(responseDocXml); GetCryptoArtifactsResponseDocument.GetCryptoArtifactsResponse getGetCryptoArtifactsResponse = responseDoc.getGetCryptoArtifactsResponse(); if (getGetCryptoArtifactsResponse == null){ Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.getKeyFNNoResp",params); AMPException e = new AMPException(message,"wamt.amp.defaultV2Provider.CommandsImpl.getKeyFNNoResp",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, e); throw e; } GetCryptoArtifactsResponseDocument.GetCryptoArtifactsResponse.CryptoArtifacts artifacts = getGetCryptoArtifactsResponse.getCryptoArtifacts(); if (artifacts == null){ Status.Enum status = getGetCryptoArtifactsResponse.getStatus(); if (status == null){ Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.getKeyFNNoStat",params); AMPException e = new AMPException(message,"wamt.amp.defaultV2Provider.CommandsImpl.getKeyFNNoStat",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, e); throw e; } else if (status.equals(Status.ERROR)){ Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.getKeyFNFail",params); DeviceExecutionException e = new DeviceExecutionException(message,"wamt.amp.defaultV2Provider.CommandsImpl.getKeyFNFail",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, e); throw e; } else { Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.getKeyFNInvalidResp",params); AMPException e = new AMPException(message,"wamt.amp.defaultV2Provider.CommandsImpl.getKeyFNInvalidResp",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, e); throw e; } } String domain = artifacts.getDomain(); if (domain == null){ Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.getKeyFNNoDom",params); AMPException e = new AMPException(message,"wamt.amp.defaultV2Provider.CommandsImpl.getKeyFNNoDom",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, e); throw e; } if (!domain.equalsIgnoreCase(domainName)){ Object[] params = {domain,device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.diffDomain",params); AMPException e = new AMPException(message,"wamt.amp.defaultV2Provider.CommandsImpl.diffDomain",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, e); throw e; } CryptoFileName[] cryptoArray = artifacts.getCryptoFileNameArray(); if ((cryptoArray == null) || (cryptoArray.length == 0)) return null; String[] result = new String[cryptoArray.length]; for (int i = 0; i < result.length; i++) result[i] = cryptoArray[i].getStringValue(); logger.exiting(CLASS_NAME, METHOD_NAME, result); return result; } catch (XmlException e){ Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.errParseGetKeyFN",params); AMPException ex = new AMPException(message,e,"wamt.amp.defaultV2Provider.CommandsImpl.errParseGetKeyFN",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, ex); throw ex; } catch (XmlValueOutOfRangeException e){ Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.getKeyFNInvalidEnum",params); AMPException ex = new AMPException(message,e,"wamt.amp.defaultV2Provider.CommandsImpl.getKeyFNInvalidEnum",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, ex); throw ex; } } /* (non-Javadoc) * @see com.ibm.datapower.amt.amp.Commands#setFile(com.ibm.datapower.amt.amp.DeviceContext, java.lang.String, java.lang.String, byte[]) */ public void setFile(DeviceContext device, String domainName, String filenameOnDevice, byte[] contents) throws NotExistException, InvalidCredentialsException, DeviceExecutionException, AMPIOException, AMPException { final String METHOD_NAME = "setFile"; //$NON-NLS-1$ logger.entering(CLASS_NAME, METHOD_NAME); SetFileRequestDocument requestDoc = SetFileRequestDocument.Factory.newInstance(); SetFileRequestDocument.SetFileRequest setFileRequest = requestDoc.addNewSetFileRequest(); try{ /*File file = setFileRequest.addNewFile(); file.setByteArrayValue(contents); //file.setStringValue(new String(contents)); file.setDomain(domainName); file.setLocation(filenameOnDevice);*/ File file = setFileRequest.addNewFile(); file.setByteArrayValue(contents); //file.setStringValue(new String(contents)); file.setDomain(domainName); // defect 12668 java.lang.OutOfMemoryError: Java heap space - Very large file upload // Check memory size Utils.checkMemorySize(contents, METHOD_NAME); // find location int iLoc = filenameOnDevice.lastIndexOf("/"); String sLocation = filenameOnDevice.substring(0, iLoc+1); file.setLocation(sLocation); // get file name String sFileName = filenameOnDevice.substring(iLoc+1); file.setName(sFileName); // Check memory size Utils.checkMemorySize(contents, METHOD_NAME); logger.logp(Level.FINEST, CLASS_NAME, METHOD_NAME, "setFileRequest created"); //$NON-NLS-1$ logger.logp(Level.FINER, CLASS_NAME, METHOD_NAME, "Sending setFileRequest(" + domainName + ", " + filenameOnDevice +") to device " //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + device.getHostname() + ":" + device.getAMPPort()); //$NON-NLS-1$ /* Send request to device */ StringBuffer outMessage = new StringBuffer(requestDoc.xmlText(soapHelper.getOptions())); Node responseDocXml = soapHelper.call(device, outMessage); outMessage.delete(0,outMessage.length()); outMessage = null; requestDoc.setNil(); requestDoc = null; /* Parse the request into a SetFileResponse object */ SetFileResponseDocument responseDoc = SetFileResponseDocument.Factory.parse(responseDocXml); SetFileResponseDocument.SetFileResponse setFileResponse = responseDoc.getSetFileResponse(); if (setFileResponse == null){ Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.setFileNoResp",params); AMPException e = new AMPException(message,"wamt.amp.defaultV2Provider.CommandsImpl.setFileNoResp",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, e); throw e; } Status.Enum status = setFileResponse.getStatus(); if (status == null){ Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.setFileNoStat",params); AMPException e = new AMPException(message,"wamt.amp.defaultV2Provider.CommandsImpl.setFileNoStat",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, e); throw e; } if (status.equals(Status.OK)){ logger.exiting(CLASS_NAME, METHOD_NAME); return; } else{ Object[] params = {filenameOnDevice,device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.setFileFail",params); DeviceExecutionException e = new DeviceExecutionException(message,"wamt.amp.defaultV2Provider.CommandsImpl.setFileFail",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, e); throw e; } } catch (XmlException e){ Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.errParseRespSetFile",params); AMPException ex = new AMPException(message,e,"wamt.amp.defaultV2Provider.CommandsImpl.errParseRespSetFile",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, ex); throw ex; } catch (XmlValueOutOfRangeException e){ Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.invalidEnumSetFile",params); AMPException ex = new AMPException(message,e,"wamt.amp.defaultV2Provider.CommandsImpl.invalidEnumSetFile",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, ex); throw ex; } catch (Error o ) { Object[] params = { }; String message = Messages.getString("wamt.clientAPI.Domain.outOfMemory", params); //$NON-NLS-1$ DeviceExecutionException e = new DeviceExecutionException(message, "wamt.clientAPI.Domain.outOfMemory", params); //$NON-NLS-1$ throw e; } } // /* (non-Javadoc) // * @see com.ibm.datapower.amt.amp.Commands#getClonableDeviceSettings(com.ibm.datapower.amt.amp.DeviceContext) // */ // public byte[] getClonableDeviceSettings(DeviceContext device) // throws InvalidCredentialsException, DeviceExecutionException, // AMPIOException, AMPException { // // final String METHOD_NAME = "getClonableDeviceSettings"; //$NON-NLS-1$ // // logger.entering(CLASS_NAME, METHOD_NAME, device); // // GetDeviceSettingsRequestDocument requestDoc = // GetDeviceSettingsRequestDocument.Factory.newInstance(); // //GetDeviceSettingsRequestDocument.GetDeviceSettingsRequest getDeviceSettingsRequest = // requestDoc.addNewGetDeviceSettingsRequest(); // // logger.logp(Level.FINEST, CLASS_NAME, METHOD_NAME, // "getDeviceSettingsRequest created"); //$NON-NLS-1$ // // logger.logp(Level.FINER, CLASS_NAME, METHOD_NAME, // "Sending getDeviceSettingsRequest to device " //$NON-NLS-1$ // + device.getHostname() + ":" + device.getAMPPort()); //$NON-NLS-1$ // // /* Send request to device */ // StringBuffer outMessage = new StringBuffer(requestDoc.xmlText(soapHelper.getOptions())); // Node responseDocXml = soapHelper.call(device, outMessage); // // outMessage.delete(0,outMessage.length()); // outMessage = null; // requestDoc.setNil(); // requestDoc = null; // // /* Parse the request into a GetDeviceSettingsResponse object */ // try{ // GetDeviceSettingsResponseDocument responseDoc = // GetDeviceSettingsResponseDocument.Factory.parse(responseDocXml); // GetDeviceSettingsResponseDocument.GetDeviceSettingsResponse getGetDeviceSettingsResponse = // responseDoc.getGetDeviceSettingsResponse(); // // if (getGetDeviceSettingsResponse == null){ // Object[] params = {device.getHostname(),new Integer(device.getAMPPort())}; // String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.getSettNoResp",params); // AMPException e = new AMPException(message,"wamt.amp.defaultV2Provider.CommandsImpl.getSettNoResp",params); //$NON-NLS-1$ //$NON-NLS-2$ // logger.throwing(CLASS_NAME, METHOD_NAME, e); // throw e; // } // // Export settings = getGetDeviceSettingsResponse.getSettings(); // if (settings == null){ // // lets try to get the error status // Status.Enum status = getGetDeviceSettingsResponse.getStatus(); // if (status == null){ // Object[] params = {device.getHostname(),new Integer(device.getAMPPort())}; // String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.getSettNoStat",params); // AMPException e = new AMPException(message,"wamt.amp.defaultV2Provider.CommandsImpl.getSettNoStat",params); //$NON-NLS-1$ //$NON-NLS-2$ // logger.throwing(CLASS_NAME, METHOD_NAME, e); // throw e; // } // // else if (status.equals(Status.ERROR)){ // Object[] params = {device.getHostname(),new Integer(device.getAMPPort())}; // String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.getSettFail",params); // DeviceExecutionException e = new DeviceExecutionException(message,"wamt.amp.defaultV2Provider.CommandsImpl.getSettFail",params); //$NON-NLS-1$ //$NON-NLS-2$ // logger.throwing(CLASS_NAME, METHOD_NAME, e); // throw e; // } // else { // Object[] params = {device.getHostname(),new Integer(device.getAMPPort())}; // String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.getSettNoSett",params); // AMPException e = new AMPException(message,"wamt.amp.defaultV2Provider.CommandsImpl.getSettNoSett",params); //$NON-NLS-1$ //$NON-NLS-2$ // logger.throwing(CLASS_NAME, METHOD_NAME, e); // throw e; // } // } // // //byte[] result = settings.getByteArrayValue(); // byte[] result = settings.getStringValue().getBytes(); // logger.exiting(CLASS_NAME, METHOD_NAME); // return result; // } // catch (XmlException e){ // Object[] params = {device.getHostname(),new Integer(device.getAMPPort())}; // String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.getSettErrParse",params); // AMPException ex = new AMPException(message,e,"wamt.amp.defaultV2Provider.CommandsImpl.getSettErrParse",params); //$NON-NLS-1$ //$NON-NLS-2$ // logger.throwing(CLASS_NAME, METHOD_NAME, ex); // throw ex; // } // catch (XmlValueOutOfRangeException e){ // Object[] params = {device.getHostname(),new Integer(device.getAMPPort())}; // String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.getSettInvalidEnum",params); // AMPException ex = new AMPException(message,e,"wamt.amp.defaultV2Provider.CommandsImpl.getSettInvalidEnum",params); //$NON-NLS-1$ //$NON-NLS-2$ // logger.throwing(CLASS_NAME, METHOD_NAME, ex); // throw ex; // } // } // // /* (non-Javadoc) // * @see com.ibm.datapower.amt.amp.Commands#setClonableDeviceSettings(com.ibm.datapower.amt.amp.DeviceContext, byte[]) // */ // public void setClonableDeviceSettings(DeviceContext device, byte[] settingsImage) // throws InvalidCredentialsException, DeviceExecutionException, // AMPIOException, AMPException { // // final String METHOD_NAME = "setClonableDeviceSettings"; //$NON-NLS-1$ // // logger.entering(CLASS_NAME, METHOD_NAME);//, new Object[]{device, settingsImage}); // // SetDeviceSettingsRequestDocument requestDoc = // SetDeviceSettingsRequestDocument.Factory.newInstance(); // SetDeviceSettingsRequestDocument.SetDeviceSettingsRequest setDeviceSettingsRequest = // requestDoc.addNewSetDeviceSettingsRequest(); // // Export export = setDeviceSettingsRequest.addNewSettings(); // //export.setByteArrayValue(settingsImage); // export.setStringValue(new String(settingsImage)); // // logger.logp(Level.FINEST, CLASS_NAME, METHOD_NAME, // "setDeviceSettingsRequest created"); //$NON-NLS-1$ // // logger.logp(Level.FINER, CLASS_NAME, METHOD_NAME, // "Sending setDeviceSettingsRequest to device " //$NON-NLS-1$ // + device.getHostname() + ":" + device.getAMPPort()); //$NON-NLS-1$ // // /* Send request to device */ // StringBuffer outMessage = new StringBuffer(requestDoc.xmlText(soapHelper.getOptions())); // Node responseDocXml = soapHelper.call(device, outMessage); // // outMessage.delete(0,outMessage.length()); // outMessage = null; // requestDoc.setNil(); // requestDoc = null; // // /* Parse the request into a SetDeviceSettingsResponse object */ // try{ // SetDeviceSettingsResponseDocument responseDoc = // SetDeviceSettingsResponseDocument.Factory.parse(responseDocXml); // SetDeviceSettingsResponseDocument.SetDeviceSettingsResponse getSetDeviceSettingsResponse = // responseDoc.getSetDeviceSettingsResponse(); // // if (getSetDeviceSettingsResponse == null){ // Object[] params = {device.getHostname(),new Integer(device.getAMPPort())}; // String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.setSettNoResp",params); // AMPException e = new AMPException(message,"wamt.amp.defaultV2Provider.CommandsImpl.setSettNoResp",params); //$NON-NLS-1$ //$NON-NLS-2$ // logger.throwing(CLASS_NAME, METHOD_NAME, e); // throw e; // } // // Status.Enum status = getSetDeviceSettingsResponse.getStatus(); // if (status == null){ // Object[] params = {device.getHostname(),new Integer(device.getAMPPort())}; // String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.setSettNoStat",params); // AMPException e = new AMPException(message,"wamt.amp.defaultV2Provider.CommandsImpl.setSettNoStat",params); //$NON-NLS-1$ //$NON-NLS-2$ // logger.throwing(CLASS_NAME, METHOD_NAME, e); // throw e; // } // // if (status.equals(Status.OK)){ // logger.exiting(CLASS_NAME, METHOD_NAME); // return; // } // else{ // Object[] params = {device.getHostname(),new Integer(device.getAMPPort())}; // String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.setSettFail",params); // DeviceExecutionException e = new DeviceExecutionException(message,"wamt.amp.defaultV2Provider.CommandsImpl.setSettFail",params); //$NON-NLS-1$ //$NON-NLS-2$ // logger.throwing(CLASS_NAME, METHOD_NAME, e); // throw e; // } // } // catch (XmlException e){ // Object[] params = {device.getHostname(),new Integer(device.getAMPPort())}; // String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.setSettErrParse",params); // AMPException ex = new AMPException(message,e,"wamt.amp.defaultV2Provider.CommandsImpl.setSettErrParse",params); //$NON-NLS-1$ //$NON-NLS-2$ // logger.throwing(CLASS_NAME, METHOD_NAME, ex); // throw ex; // } // catch (XmlValueOutOfRangeException e){ // Object[] params = {device.getHostname(),new Integer(device.getAMPPort())}; // String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.setSettInvalidEnum",params); // AMPException ex = new AMPException(message,e,"wamt.amp.defaultV2Provider.CommandsImpl.setSettInvalidEnum",params); //$NON-NLS-1$ //$NON-NLS-2$ // logger.throwing(CLASS_NAME, METHOD_NAME, ex); // throw ex; // } // } /* (non-Javadoc) * @see com.ibm.datapower.amt.amp.Commands#getErrorReport(com.ibm.datapower.amt.amp.DeviceContext) */ public ErrorReport getErrorReport(DeviceContext device) throws InvalidCredentialsException, DeviceExecutionException, AMPIOException, AMPException { final String METHOD_NAME = "getErrorReport"; //$NON-NLS-1$ logger.entering(CLASS_NAME, METHOD_NAME, device); GetErrorReportRequestDocument requestDoc = GetErrorReportRequestDocument.Factory.newInstance(); //GetErrorReportRequestDocument.GetErrorReportRequest getErrorReportRequest = requestDoc.addNewGetErrorReportRequest(); logger.logp(Level.FINEST, CLASS_NAME, METHOD_NAME, "getErrorReport created"); //$NON-NLS-1$ logger.logp(Level.FINER, CLASS_NAME, METHOD_NAME, "Sending getErrorReport to device " //$NON-NLS-1$ + device.getHostname() + ":" + device.getAMPPort()); //$NON-NLS-1$ /* Send request to device */ StringBuffer outMessage = new StringBuffer(requestDoc.xmlText(soapHelper.getOptions())); Node responseDocXml = soapHelper.call(device, outMessage); outMessage.delete(0,outMessage.length()); outMessage = null; requestDoc.setNil(); requestDoc = null; /* Parse the request into a GetErrorReportResponse object */ try{ GetErrorReportResponseDocument responseDoc = GetErrorReportResponseDocument.Factory.parse(responseDocXml); GetErrorReportResponseDocument.GetErrorReportResponse getGetErrorReportResponse = responseDoc.getGetErrorReportResponse(); if (getGetErrorReportResponse == null){ Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.getErrRepNoResp",params); AMPException e = new AMPException(message,"wamt.amp.defaultV2Provider.CommandsImpl.getErrRepNoResp",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, e); throw e; } File file = getGetErrorReportResponse.getErrorReport(); if (file == null){ // lets check for the error status Status.Enum status = getGetErrorReportResponse.getStatus(); if (status == null){ Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.getErrRepNoStat",params); AMPException e = new AMPException(message,"wamt.amp.defaultV2Provider.CommandsImpl.getErrRepNoStat",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, e); throw e; } else if (status.equals(Status.ERROR)){ Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.getErrRepFail",params); DeviceExecutionException e = new DeviceExecutionException(message,"wamt.amp.defaultV2Provider.CommandsImpl.getErrRepFail",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, e); throw e; } else { Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.getErrRepEmpty",params); AMPException e = new AMPException(message,"wamt.amp.defaultV2Provider.CommandsImpl.getErrRepEmpty",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, e); throw e; } } //byte[] stringVal = file.getByteArrayValue(); byte[] stringVal = null; if (file.getStringValue() != null){ stringVal = file.getStringValue().getBytes(); } ErrorReport result = new ErrorReport(file.getDomain(), file.getLocation(), file.getName(), stringVal); logger.exiting(CLASS_NAME, METHOD_NAME, result); return result; } catch (XmlException e){ Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.getErrRepParseErr",params); AMPException ex = new AMPException(message,e,"wamt.amp.defaultV2Provider.CommandsImpl.getErrRepParseErr",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, ex); throw ex; } catch (XmlValueOutOfRangeException e){ Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.getErrRepInvalidEnum",params); AMPException ex = new AMPException(message,e,"wamt.amp.defaultV2Provider.CommandsImpl.getErrRepInvalidEnum",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, ex); throw ex; } } /* (non-Javadoc) * @see com.ibm.datapower.amt.amp.Commands#getErrorReport(com.ibm.datapower.amt.amp.DeviceContext) */ public String getSAMLToken(DeviceContext device, String domainName) throws InvalidCredentialsException, DeviceExecutionException, AMPIOException, AMPException { final String METHOD_NAME = "getSAMLToken"; //$NON-NLS-1$ logger.entering(CLASS_NAME, METHOD_NAME, device); GetTokenRequestDocument requestDoc = GetTokenRequestDocument.Factory.newInstance(); GetTokenRequestDocument.GetTokenRequest getTokenRequest = requestDoc.addNewGetTokenRequest(); // we only support SAML tokens for login to the webGUI currently getTokenRequest.setType(TokenType.LOGIN_WEB_MGMT); getTokenRequest.setUser(device.getUserId()); getTokenRequest.setPassword(device.getPassword()); getTokenRequest.setDomain(domainName); logger.logp(Level.FINEST, CLASS_NAME, METHOD_NAME, "getToken created"); //$NON-NLS-1$ logger.logp(Level.FINER, CLASS_NAME, METHOD_NAME, "Sending getToken to device " //$NON-NLS-1$ + device.getHostname() + ":" + device.getAMPPort()); //$NON-NLS-1$ /* Send request to device */ StringBuffer outMessage = new StringBuffer(requestDoc.xmlText(soapHelper.getOptions())); Node responseDocXml = soapHelper.call(device, outMessage); outMessage.delete(0,outMessage.length()); outMessage = null; requestDoc.setNil(); requestDoc = null; /* Parse the request into a GetErrorReportResponse object */ try{ GetTokenResponseDocument responseDoc = GetTokenResponseDocument.Factory.parse(responseDocXml); GetTokenResponseDocument.GetTokenResponse getGetTokenResponse = responseDoc.getGetTokenResponse(); if (getGetTokenResponse == null){ Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.getTokenNoResp",params); AMPException e = new AMPException(message,"wamt.amp.defaultV2Provider.CommandsImpl.getTokenNoResp",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, e); throw e; } String samlToken = getGetTokenResponse.getToken(); if (samlToken == null){ Status.Enum status = getGetTokenResponse.getStatus(); if (status == null){ Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.getTokenNoStat",params); AMPException e = new AMPException(message,"wamt.amp.defaultV2Provider.CommandsImpl.getTokenNoStat",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, e); throw e; } else if (status.equals(Status.ERROR)){ Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.getTokenFail",params); DeviceExecutionException e = new DeviceExecutionException(message,"wamt.amp.defaultV2Provider.CommandsImpl.getTokenFail",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, e); throw e; } else { Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.getTokenOkStat",params); AMPException e = new AMPException(message,"wamt.amp.defaultV2Provider.CommandsImpl.getTokenOkStat",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, e); throw e; } } return samlToken; } catch (XmlException e){ Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.getTokenErrParse",params); AMPException ex = new AMPException(message,e,"wamt.amp.defaultV2Provider.CommandsImpl.getTokenErrParse",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, ex); throw ex; } catch (XmlValueOutOfRangeException e){ Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.getTokenInvalidEnum",params); AMPException ex = new AMPException(message,e,"wamt.amp.defaultV2Provider.CommandsImpl.getTokenInvalidEnum",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, ex); throw ex; } } /* (non-Javadoc) * @see com.ibm.datapower.amt.amp.Commands#isDifferent(byte[], byte[], com.ibm.datapower.amt.amp.DeviceContext) */ public boolean isDomainDifferent(String domainName, byte[] configImage1, byte[] configImage2, DeviceContext device) throws InvalidCredentialsException, DeviceExecutionException, AMPIOException, AMPException { final String METHOD_NAME = "isDomainDifferent"; //$NON-NLS-1$ logger.entering(CLASS_NAME, METHOD_NAME); //new Object[]{domainName, configImage1, configImage2, device}); CompareConfigRequestDocument requestDoc = CompareConfigRequestDocument.Factory.newInstance(); CompareConfigRequestDocument.CompareConfigRequest compareConfigRequest = requestDoc.addNewCompareConfigRequest(); CompareConfigRequestDocument.CompareConfigRequest.CompareConfig compareConfig = compareConfigRequest.addNewCompareConfig(); compareConfig.setDomain(domainName); CompareConfigRequestDocument.CompareConfigRequest.CompareConfig.From from = compareConfig.addNewFrom(); Backup fromImage = from.addNewConfig(); //fromImage.setByteArrayValue(configImage1); fromImage.setStringValue(new String(configImage1)); fromImage.setDomain(domainName); CompareConfigRequestDocument.CompareConfigRequest.CompareConfig.To to = compareConfig.addNewTo(); if (configImage2 == null) to.addNewPersisted(); else{ Backup toImage = to.addNewConfig(); //toImage.setByteArrayValue(configImage2); toImage.setStringValue(new String(configImage2)); toImage.setDomain(domainName); } logger.logp(Level.FINEST, CLASS_NAME, METHOD_NAME, "isDomainDifferent created"); //$NON-NLS-1$ logger.logp(Level.FINER, CLASS_NAME, METHOD_NAME, "Sending isDomainDifferent to device " //$NON-NLS-1$ + device.getHostname() + ":" + device.getAMPPort()); //$NON-NLS-1$ /* Send request to device */ StringBuffer outMessage = new StringBuffer(requestDoc.xmlText(soapHelper.getOptions())); Node responseDocXml = soapHelper.call(device, outMessage); outMessage.delete(0,outMessage.length()); outMessage = null; requestDoc.setNil(); requestDoc = null; /* Parse the request into a SetDeviceSettingsResponse object */ try{ CompareConfigResponseDocument responseDoc = CompareConfigResponseDocument.Factory.parse(responseDocXml); CompareConfigResponseDocument.CompareConfigResponse getCompareConfigResponse = responseDoc.getCompareConfigResponse(); if (getCompareConfigResponse == null){ Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.domDiffNoResp",params); AMPException e = new AMPException(message,"wamt.amp.defaultV2Provider.CommandsImpl.domDiffNoResp",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, e); throw e; } CompareConfigResponseDocument.CompareConfigResponse.CompareConfig compareConfigResponse = getCompareConfigResponse.getCompareConfig(); if (compareConfigResponse == null){ Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.domDiffNoCompConf",params); AMPException e = new AMPException(message,"wamt.amp.defaultV2Provider.CommandsImpl.domDiffNoCompConf",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, e); throw e; } String returnedDomain = compareConfigResponse.getDomain(); if (returnedDomain == null){ Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.domDiffNameNull",params); AMPException e = new AMPException(message,"wamt.amp.defaultV2Provider.CommandsImpl.domDiffNameNull",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, e); throw e; } if (!returnedDomain.equalsIgnoreCase(domainName)){ Object[] params = {domainName, device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.domDiffNameRec",params); AMPException e = new AMPException(message,"wamt.amp.defaultV2Provider.CommandsImpl.domDiffNameRec",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, e); throw e; } CompareResult.Enum compareResult = compareConfigResponse.getCompareResult(); if (compareResult == null){ Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.domDiffNoCompRes",params); AMPException e = new AMPException(message,"wamt.amp.defaultV2Provider.CommandsImpl.domDiffNoCompRes",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, e); throw e; } if (compareResult.toString().equalsIgnoreCase("identical")){ //$NON-NLS-1$ logger.exiting(CLASS_NAME, METHOD_NAME); return false; } else if (compareResult.toString().equalsIgnoreCase("different")){ //$NON-NLS-1$ logger.exiting(CLASS_NAME, METHOD_NAME); return true; } else { Object[] params = {compareResult,device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.domDiffInvalidRes",params); AMPException e = new AMPException(message,"wamt.amp.defaultV2Provider.CommandsImpl.domDiffInvalidRes",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, e); throw e; } } catch (XmlException e){ Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.domDiffErrParse",params); AMPException ex = new AMPException(message,e,"wamt.amp.defaultV2Provider.CommandsImpl.domDiffErrParse",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, ex); throw ex; } catch (XmlValueOutOfRangeException e){ Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.domDiffInvalidEnum",params); AMPException ex = new AMPException(message,e,"wamt.amp.defaultV2Provider.CommandsImpl.domDiffInvalidEnum",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, ex); throw ex; } } // /* (non-Javadoc) // * @see com.ibm.datapower.amt.amp.Commands#isDifferent(byte[], byte[], com.ibm.datapower.amt.amp.DeviceContext) // */ // public boolean isSettingsDifferent(byte[] configImage1, byte[] configImage2, // DeviceContext device) throws InvalidCredentialsException, // DeviceExecutionException, AMPIOException, AMPException { // // final String METHOD_NAME = "isSettingsDifferent"; //$NON-NLS-1$ // // logger.entering(CLASS_NAME, METHOD_NAME); // //new Object[]{configImage1, configImage2, device}); // // CompareConfigRequestDocument requestDoc = // CompareConfigRequestDocument.Factory.newInstance(); // CompareConfigRequestDocument.CompareConfigRequest compareConfigRequest = // requestDoc.addNewCompareConfigRequest(); // CompareConfigRequestDocument.CompareConfigRequest.CompareConfig compareConfig = // compareConfigRequest.addNewCompareConfig(); // // compareConfig.setDomain("default"); //$NON-NLS-1$ // // CompareConfigRequestDocument.CompareConfigRequest.CompareConfig.From from = // compareConfig.addNewFrom(); // Export fromImage = from.addNewSettings(); // //fromImage.setByteArrayValue(configImage1); // fromImage.setStringValue(new String(configImage1)); // // CompareConfigRequestDocument.CompareConfigRequest.CompareConfig.To to = // compareConfig.addNewTo(); // if (configImage2 == null) // to.addNewPersisted(); // else{ // Export toImage = to.addNewSettings(); // //toImage.setByteArrayValue(configImage2); // toImage.setStringValue(new String(configImage2)); // } // // logger.logp(Level.FINEST, CLASS_NAME, METHOD_NAME, // "isSettingsDifferent created"); //$NON-NLS-1$ // // logger.logp(Level.FINER, CLASS_NAME, METHOD_NAME, // "Sending isSettingsDifferent to device " //$NON-NLS-1$ // + device.getHostname() + ":" + device.getAMPPort()); //$NON-NLS-1$ // // /* Send request to device */ // StringBuffer outMessage = new StringBuffer(requestDoc.xmlText(soapHelper.getOptions())); // Node responseDocXml = soapHelper.call(device, outMessage); // // outMessage.delete(0,outMessage.length()); // outMessage = null; // requestDoc.setNil(); // requestDoc = null; // // /* Parse the request into a SetDeviceSettingsResponse object */ // try{ // CompareConfigResponseDocument responseDoc = // CompareConfigResponseDocument.Factory.parse(responseDocXml); // CompareConfigResponseDocument.CompareConfigResponse getCompareConfigResponse = // responseDoc.getCompareConfigResponse(); // // if (getCompareConfigResponse == null){ // Object[] params = {device.getHostname(),new Integer(device.getAMPPort())}; // String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.settDiffNoResp",params); // AMPException e = new AMPException(message,"wamt.amp.defaultV2Provider.CommandsImpl.settDiffNoResp",params); //$NON-NLS-1$ //$NON-NLS-2$ // logger.throwing(CLASS_NAME, METHOD_NAME, e); // throw e; // } // // CompareConfigResponseDocument.CompareConfigResponse.CompareConfig compareConfigResponse = getCompareConfigResponse.getCompareConfig(); // if (compareConfigResponse == null){ // Object[] params = {device.getHostname(),new Integer(device.getAMPPort())}; // String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.settDiffNoCompConf",params); // AMPException e = new AMPException(message,"wamt.amp.defaultV2Provider.CommandsImpl.settDiffNoCompConf",params); //$NON-NLS-1$ //$NON-NLS-2$ // logger.throwing(CLASS_NAME, METHOD_NAME, e); // throw e; // } // // CompareResult.Enum compareResult = compareConfigResponse.getCompareResult(); // if (compareConfigResponse == null){ // Object[] params = {device.getHostname(),new Integer(device.getAMPPort())}; // String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.settDiffNoCompRes",params); // AMPException e = new AMPException(message,"wamt.amp.defaultV2Provider.CommandsImpl.settDiffNoCompRes",params); //$NON-NLS-1$ //$NON-NLS-2$ // logger.throwing(CLASS_NAME, METHOD_NAME, e); // throw e; // } // // if (compareResult.toString().equalsIgnoreCase("identical")){ //$NON-NLS-1$ // logger.exiting(CLASS_NAME, METHOD_NAME); // return false; // } // else if (compareResult.toString().equalsIgnoreCase("different")){ //$NON-NLS-1$ // logger.exiting(CLASS_NAME, METHOD_NAME); // return true; // } // else { // Object[] params = {compareResult,device.getHostname(),new Integer(device.getAMPPort())}; // String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.settDiffInvalidCompRes",params); // AMPException e = new AMPException(message,"wamt.amp.defaultV2Provider.CommandsImpl.settDiffInvalidCompRes",params); //$NON-NLS-1$ //$NON-NLS-2$ // logger.throwing(CLASS_NAME, METHOD_NAME, e); // throw e; // } // } // catch (XmlException e){ // Object[] params = {device.getHostname(),new Integer(device.getAMPPort())}; // String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.settDiffErrParse",params); // AMPException ex = new AMPException(message,e,"wamt.amp.defaultV2Provider.CommandsImpl.settDiffErrParse",params); //$NON-NLS-1$ //$NON-NLS-2$ // logger.throwing(CLASS_NAME, METHOD_NAME, ex); // throw ex; // } // catch (XmlValueOutOfRangeException e){ // Object[] params = {device.getHostname(),new Integer(device.getAMPPort())}; // String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.settDiffInvalidEnum",params); // AMPException ex = new AMPException(message,e,"wamt.amp.defaultV2Provider.CommandsImpl.settDiffInvalidEnum",params); //$NON-NLS-1$ //$NON-NLS-2$ // logger.throwing(CLASS_NAME, METHOD_NAME, e); // throw ex; // } // } /* (non-Javadoc) * @see com.ibm.datapower.amt.amp.Commands#getDifferences(byte[], byte[], com.ibm.datapower.amt.amp.DeviceContext) */ public URL getDomainDifferences(String domainName, byte[] configImage1, byte[] configImage2, DeviceContext device) throws InvalidCredentialsException, DeviceExecutionException, AMPIOException, AMPException { final String METHOD_NAME = "getDomainDifferences"; //$NON-NLS-1$ logger.entering(CLASS_NAME, METHOD_NAME); //new Object[]{domainName, configImage1, configImage2, device}); logger.logp(Level.FINE, CLASS_NAME, METHOD_NAME, "getDomainDifferences is not implemented!!!"); //$NON-NLS-1$ /* CompareConfigRequestDocument requestDoc = CompareConfigRequestDocument.Factory.newInstance(); CompareConfigRequestDocument.CompareConfigRequest compareConfigRequest = requestDoc.addNewCompareConfigRequest(); CompareConfigRequestDocument.CompareConfigRequest.CompareConfig compareConfig = compareConfigRequest.addNewCompareConfig(); compareConfig.setDomain(domainName); CompareConfigRequestDocument.CompareConfigRequest.CompareConfig.From from = compareConfig.addNewFrom(); Backup fromImage = from.addNewConfig(); fromImage.setByteArrayValue(configImage1); fromImage.setDomain(domainName); CompareConfigRequestDocument.CompareConfigRequest.CompareConfig.To to = compareConfig.addNewTo(); if (configImage2 == null) to.addNewPersisted(); else{ Backup toImage = to.addNewConfig(); toImage.setByteArrayValue(configImage2); toImage.setDomain(domainName); } logger.logp(Level.FINEST, CLASS_NAME, METHOD_NAME, "getDomainDifferences created"); logger.logp(Level.FINER, CLASS_NAME, METHOD_NAME, "Sending getDomainDifferences to device " + device.getHostname() + ":" + device.getAMPPort()); StringBuffer outMessage = new StringBuffer(requestDoc.xmlText(soapHelper.getOptions())); Node responseDocXml = soapHelper.call(device, outMessage); outMessage.delete(0,outMessage.length()); outMessage = null; requestDoc.setNil(); requestDoc = null; //TODO: implement response for getDomainDifferences /* AMPException ex = new AMPException("Error parsing setClonableDeviceSettings response from device " + device.getHostname() + ":" + device.getAMPPort(),e); logger.throwing(CLASS_NAME, METHOD_NAME, ex); throw ex; catch (XmlValueOutOfRangeException e){ AMPException ex = new AMPException("Invalid enumeration in getClonableDeviceSettingsResponse from device " + device.getHostname() + ":" + device.getAMPPort(),e); logger.throwing(CLASS_NAME, METHOD_NAME, ex); throw ex; } */ logger.exiting(CLASS_NAME, METHOD_NAME); return null; } // /* (non-Javadoc) // * @see com.ibm.datapower.amt.amp.Commands#getDifferences(byte[], byte[], com.ibm.datapower.amt.amp.DeviceContext) // */ // // public URL getSettingsDifferences(byte[] configImage1, byte[] configImage2, // DeviceContext device) throws InvalidCredentialsException, // DeviceExecutionException, AMPIOException, AMPException { // // final String METHOD_NAME = "getSettingsDifferences"; //$NON-NLS-1$ // // logger.entering(CLASS_NAME, METHOD_NAME);//, new Object[]{configImage1, configImage2, device}); // // logger.logp(Level.FINE, CLASS_NAME, METHOD_NAME, "getSettingsDifferences is not implemented!!!"); //$NON-NLS-1$ // /* // CompareConfigRequestDocument requestDoc = // CompareConfigRequestDocument.Factory.newInstance(); // CompareConfigRequestDocument.CompareConfigRequest compareConfigRequest = // requestDoc.addNewCompareConfigRequest(); // CompareConfigRequestDocument.CompareConfigRequest.CompareConfig compareConfig = // compareConfigRequest.addNewCompareConfig(); // // compareConfig.setDomain("default"); // // CompareConfigRequestDocument.CompareConfigRequest.CompareConfig.From from = // compareConfig.addNewFrom(); // Export fromImage = from.addNewSettings(); // fromImage.setByteArrayValue(configImage1); // // CompareConfigRequestDocument.CompareConfigRequest.CompareConfig.To to = // compareConfig.addNewTo(); // if (configImage2 == null) // to.addNewPersisted(); // else{ // Export toImage = to.addNewSettings(); // toImage.setByteArrayValue(configImage2); // } // // logger.logp(Level.FINEST, CLASS_NAME, METHOD_NAME, // "getSettingsDifferences created"); // // logger.logp(Level.FINER, CLASS_NAME, METHOD_NAME, // "Sending getSettingsDifferences to device " // + device.getHostname() + ":" + device.getAMPPort()); // StringBuffer outMessage = new StringBuffer(requestDoc.xmlText(soapHelper.getOptions())); // Node responseDocXml = soapHelper.call(device, outMessage); // // outMessage.delete(0,outMessage.length()); // outMessage = null; // requestDoc.setNil(); // requestDoc = null; // // //TODO: implement response for getSettingsDifferences // * AMPException ex = new AMPException("Error parsing setClonableDeviceSettings response from device " + device.getHostname() + ":" + device.getAMPPort(),e); // logger.throwing(CLASS_NAME, METHOD_NAME, ex); // throw ex; // catch (XmlValueOutOfRangeException e){ // AMPException ex = new AMPException("Invalid enumeration in getClonableDeviceSettingsResponse from device " + device.getHostname() + ":" + device.getAMPPort(),e); // logger.throwing(CLASS_NAME, METHOD_NAME, ex); // throw ex; // } // */ // logger.exiting(CLASS_NAME, METHOD_NAME); // return null; // } /* * @throws InvalidParameterException * */ public Hashtable backupDevice(DeviceContext device, String cryptoCertificateName, byte[] cryptoImage, String secureBackupDestination, boolean includeISCSI, boolean includeRaid) throws AMPIOException, InvalidCredentialsException, AMPException { final String METHOD_NAME = "backupDevice"; //$NON-NLS-1$ logger.entering(CLASS_NAME, METHOD_NAME); // The crypto object name or the crypto certificate location must be specified,both cannot be specified if ((cryptoCertificateName != null)&& (cryptoImage != null)){ logger.logp(Level.SEVERE, CLASS_NAME, METHOD_NAME, "Specify the Crypto Object name or the crypto certificates location. Both may not be non-null" ); } // The crypto object name or the crypto certificate location must be specified,both cannot be null if ((cryptoCertificateName == null)&& (cryptoImage == null)){ logger.logp(Level.FINEST, CLASS_NAME, METHOD_NAME, "Specify the Crypto Object name or the crypto certificates location. Both may not be null" ); } List<SecureBackupFile> returnedBackupFilesList = null; Hashtable<String,byte[]> backupHashTable = new Hashtable<String,byte[]> (); SecureBackupRequestDocument requestDoc = SecureBackupRequestDocument.Factory.newInstance(); SecureBackupRequestDocument.SecureBackupRequest request = requestDoc.addNewSecureBackupRequest(); // Remove option to backup ISCSI, if caller specifies a value of false. It is ON by default. if(!includeISCSI){ XmlObject scsi =request.addNewDoNotIncludeiSCSI(); } // Remove option to backup RAID, if caller specifies a value of false. It is ON by default. if(!includeRaid){ XmlObject raid = request.addNewDoNotIncludeRAID(); } // Device.backupDevice() ensures that only one of the 2 is specified - cryptoObjectName or cryptoCertificate. // Both will not be null if(cryptoCertificateName !=null){ request.setCryptoCertificateName(cryptoCertificateName); } if (cryptoImage!=null ){ request.setCryptoCertificate(cryptoImage); } if (secureBackupDestination!=null){ request.setSecureBackupDestination(secureBackupDestination); } logger.logp(Level.FINEST, CLASS_NAME, METHOD_NAME, "backupRequest request created"); //$NON-NLS-1$ logger.logp(Level.FINER, CLASS_NAME, METHOD_NAME, "Sending backup request to device " //$NON-NLS-1$ + device.getHostname() + ":" + device.getAMPPort()); //$NON-NLS-1$ /* Send request to device */ StringBuffer outMessage = new StringBuffer(requestDoc.xmlText(soapHelper.getOptions())); Node responseDocXml = soapHelper.call(device, outMessage); outMessage.delete(0,outMessage.length()); outMessage = null; requestDoc.setNil(); requestDoc = null; /* Parse the request into a response object */ try{ SecureBackupResponseDocument responseDoc = SecureBackupResponseDocument.Factory.parse(responseDocXml); SecureBackupResponseDocument.SecureBackupResponse backupResponse = responseDoc.getSecureBackupResponse(); if (backupResponse == null){ Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.backupNoResp",params); AMPException e = new AMPException(message,"wamt.amp.defaultV2Provider.CommandsImpl.backupNoResp",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, e); throw e; } Status.Enum status = backupResponse.getStatus(); SecureBackup backup = backupResponse.getSecureBackup(); // By design when files are returned by backup, the status is NULL if (secureBackupDestination != null){ if (status == null ) { Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.backupNoStat",params); AMPException e = new AMPException(message,"wamt.amp.defaultV2Provider.CommandsImpl.backupNoStat",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, e); throw e; } else if (status.equals(Status.ERROR)){ Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.backupFail",params); DeviceExecutionException e = new DeviceExecutionException(message,"wamt.amp.defaultV2Provider.CommandsImpl.backupFail",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, e); throw e; } } //Retrieve backup files when secureBackupDestination specified is null. //Backup files are expected to be returned when secureBackupDestination is null if (secureBackupDestination == null) { if (backup == null){ // backup files not returned as expected! Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.backupFail",params); DeviceExecutionException e = new DeviceExecutionException(message,"wamt.amp.defaultV2Provider.CommandsImpl.backupFail",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, e); throw e; }else{ returnedBackupFilesList = backup.getSecureBackupFileList(); if (returnedBackupFilesList!=null){ logger.logp(Level.FINEST, CLASS_NAME, METHOD_NAME,"Number of backup files returned = " + returnedBackupFilesList.size()); java.util.Iterator<SecureBackupFile> it=returnedBackupFilesList.iterator(); while(it.hasNext()) { SecureBackupFile file=(SecureBackupFile)it.next(); backupHashTable.put(file.getName(),file.getStringValue().getBytes()); } } } } } catch (XmlException e){ Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.backupErrParse",params); AMPException ex = new AMPException(message,e,"wamt.amp.defaultV2Provider.CommandsImpl.backupErrParse",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, ex); throw ex; } catch (XmlValueOutOfRangeException e){ Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.backupInvalidEnum",params); AMPException ex = new AMPException(message,e,"wamt.amp.defaultV2Provider.CommandsImpl.backupInvalidEnum",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, ex); throw ex; } return backupHashTable; } public void restoreDevice(DeviceContext device, String cryptoCredentialName, boolean validate, URI secureBackupSource, Hashtable<String, byte[]> backupFilesTable) throws AMPIOException, InvalidCredentialsException, AMPException { final String METHOD_NAME = "restoreDevice"; //$NON-NLS-1$ SecureRestoreRequestDocument requestDoc = SecureRestoreRequestDocument.Factory.newInstance(); SecureRestoreRequestDocument.SecureRestoreRequest request = requestDoc.addNewSecureRestoreRequest(); if(cryptoCredentialName !=null){ request.setCryptoCredentialName(cryptoCredentialName); } if (secureBackupSource!=null ){ if (secureBackupSource.getScheme().equalsIgnoreCase("file")){ SecureBackup backupFiles = readBackUpFiles(backupFilesTable); request.setSecureBackup(backupFiles); }else{ request.setSecureBackupSource(secureBackupSource.toString()); } } if(validate){ request.addNewValidate(); } logger.logp(Level.FINEST, CLASS_NAME, METHOD_NAME, "backupRequest request created"); //$NON-NLS-1$ logger.logp(Level.FINER, CLASS_NAME, METHOD_NAME, "Sending backup request to device " //$NON-NLS-1$ + device.getHostname() + ":" + device.getAMPPort()); //$NON-NLS-1$ /* Send request to device */ StringBuffer outMessage = new StringBuffer(requestDoc.xmlText(soapHelper.getOptions())); Node responseDocXml = soapHelper.call(device, outMessage); outMessage.delete(0,outMessage.length()); outMessage = null; requestDoc.setNil(); requestDoc = null; /* Parse the request into a response object */ try{ SecureRestoreResponseDocument responseDoc = SecureRestoreResponseDocument.Factory.parse(responseDocXml); SecureRestoreResponseDocument.SecureRestoreResponse restoreResponse = responseDoc.getSecureRestoreResponse(); if (restoreResponse == null){ Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.restoreNoResp",params); AMPException e = new AMPException(message,"wamt.amp.defaultV2Provider.CommandsImpl.restoreNoResp",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, e); throw e; } Status.Enum status = restoreResponse.getStatus(); if (status == null ){ Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.restoreNoStat",params); AMPException e = new AMPException(message,"wamt.amp.defaultV2Provider.CommandsImpl.restoreNoStat",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, e); throw e; } else if (status.equals(Status.ERROR)){ Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.restoreFail",params); DeviceExecutionException e = new DeviceExecutionException(message,"wamt.amp.defaultV2Provider.CommandsImpl.restoreFail",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, e); throw e; } } catch (XmlException e){ Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.restoreErrParse",params); AMPException ex = new AMPException(message,e,"wamt.amp.defaultV2Provider.CommandsImpl.restoreErrParse",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, ex); throw ex; } catch (XmlValueOutOfRangeException e){ Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.restoreInvalidEnum",params); AMPException ex = new AMPException(message,e,"wamt.amp.defaultV2Provider.CommandsImpl.restoreInvalidEnum",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, ex); throw ex; } return; } public void quiesceDomain(DeviceContext device, String domain, int timeout) throws AMPIOException, InvalidCredentialsException, AMPException { final String METHOD_NAME = "quiesceDomain"; //$NON-NLS-1$ logger.entering(CLASS_NAME, METHOD_NAME); QuiesceRequestDocument requestDoc = QuiesceRequestDocument.Factory.newInstance(); QuiesceRequestDocument.QuiesceRequest request = requestDoc.addNewQuiesceRequest(); QuiesceRequestDocument.QuiesceRequest.Domain requestDomain = request.addNewDomain(); requestDomain.setName(domain); requestDomain.setTimeout(timeout); logger.logp(Level.FINEST, CLASS_NAME, METHOD_NAME, "quiesce request created"); //$NON-NLS-1$ logger.logp(Level.FINER, CLASS_NAME, METHOD_NAME, "Sending quiesce request to device " //$NON-NLS-1$ + device.getHostname() + ":" + device.getAMPPort()); //$NON-NLS-1$ /* Send request to device */ StringBuffer outMessage = new StringBuffer(requestDoc.xmlText(soapHelper.getOptions())); Node responseDocXml = soapHelper.call(device, outMessage); outMessage.delete(0,outMessage.length()); outMessage = null; requestDoc.setNil(); requestDoc = null; /* Parse the request into a response object */ try{ QuiesceResponseDocument responseDoc = QuiesceResponseDocument.Factory.parse(responseDocXml); QuiesceResponseDocument.QuiesceResponse quiesceResponse = responseDoc.getQuiesceResponse(); if (quiesceResponse == null){ Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.quiesceNoResp",params); AMPException e = new AMPException(message,"wamt.amp.defaultV2Provider.CommandsImpl.quiesceNoResp",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, e); throw e; } Status.Enum status = quiesceResponse.getStatus(); if (status == null){ Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.quiesceNoStat",params); AMPException e = new AMPException(message,"wamt.amp.defaultV2Provider.CommandsImpl.quiesceNoStat",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, e); throw e; } else if (status.equals(Status.ERROR)){ Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.quiesceFail",params); DeviceExecutionException e = new DeviceExecutionException(message,"wamt.amp.defaultV2Provider.CommandsImpl.quiesceFail",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, e); throw e; } // else { // Object[] params = {device.getHostname(),new Integer(device.getAMPPort())}; // String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.quiesceOkStat",params); // AMPException e = new AMPException(message,"wamt.amp.defaultV2Provider.CommandsImpl.quiesceOkStat",params); //$NON-NLS-1$ //$NON-NLS-2$ // logger.throwing(CLASS_NAME, METHOD_NAME, e); // throw e; // } } catch (XmlException e){ Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.quiesceErrParse",params); AMPException ex = new AMPException(message,e,"wamt.amp.defaultV2Provider.CommandsImpl.quiesceErrParse",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, ex); throw ex; } catch (XmlValueOutOfRangeException e){ Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.quiesceInvalidEnum",params); AMPException ex = new AMPException(message,e,"wamt.amp.defaultV2Provider.CommandsImpl.quiesceInvalidEnum",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, ex); throw ex; } } public void unquiesceDomain(DeviceContext device, String domain) throws AMPIOException, InvalidCredentialsException, AMPException { final String METHOD_NAME = "unquiesceDomain"; //$NON-NLS-1$ logger.entering(CLASS_NAME, METHOD_NAME); UnquiesceRequestDocument requestDoc = UnquiesceRequestDocument.Factory.newInstance(); UnquiesceRequestDocument.UnquiesceRequest request = requestDoc.addNewUnquiesceRequest(); UnquiesceRequestDocument.UnquiesceRequest.Domain requestDomain = request.addNewDomain(); requestDomain.setName(domain); logger.logp(Level.FINEST, CLASS_NAME, METHOD_NAME, "unquiesce request created"); //$NON-NLS-1$ logger.logp(Level.FINER, CLASS_NAME, METHOD_NAME, "Sending unquiesce request to device " //$NON-NLS-1$ + device.getHostname() + ":" + device.getAMPPort()); //$NON-NLS-1$ /* Send request to device */ StringBuffer outMessage = new StringBuffer(requestDoc.xmlText(soapHelper.getOptions())); Node responseDocXml = soapHelper.call(device, outMessage); outMessage.delete(0,outMessage.length()); outMessage = null; requestDoc.setNil(); requestDoc = null; /* Parse the request into a response object */ try{ UnquiesceResponseDocument responseDoc = UnquiesceResponseDocument.Factory.parse(responseDocXml); UnquiesceResponseDocument.UnquiesceResponse unquiesceResponse = responseDoc.getUnquiesceResponse(); if (unquiesceResponse == null){ Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.unquiesceNoResp",params); AMPException e = new AMPException(message,"wamt.amp.defaultV2Provider.CommandsImpl.unquiesceNoResp",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, e); throw e; } Status.Enum status = unquiesceResponse.getStatus(); if (status == null){ Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.unquiesceNoStat",params); AMPException e = new AMPException(message,"wamt.amp.defaultV2Provider.CommandsImpl.unquiesceNoStat",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, e); throw e; } else if (status.equals(Status.ERROR)){ Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.unquiesceFail",params); DeviceExecutionException e = new DeviceExecutionException(message,"wamt.amp.defaultV2Provider.CommandsImpl.unquiesceFail",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, e); throw e; } // else { // Object[] params = {device.getHostname(),new Integer(device.getAMPPort())}; // String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.unquiesceOkStat",params); // AMPException e = new AMPException(message,"wamt.amp.defaultV2Provider.CommandsImpl.unquiesceOkStat",params); //$NON-NLS-1$ //$NON-NLS-2$ // logger.throwing(CLASS_NAME, METHOD_NAME, e); // throw e; // } } catch (XmlException e){ Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.unquiesceErrParse",params); AMPException ex = new AMPException(message,e,"wamt.amp.defaultV2Provider.CommandsImpl.unquiesceErrParse",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, ex); throw ex; } catch (XmlValueOutOfRangeException e){ Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.unquiesceInvalidEnum",params); AMPException ex = new AMPException(message,e,"wamt.amp.defaultV2Provider.CommandsImpl.unquiesceInvalidEnum",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, ex); throw ex; } } public void quiesceDevice(DeviceContext device, int timeout) throws AMPIOException, InvalidCredentialsException, AMPException { final String METHOD_NAME = "quiesceDevice"; //$NON-NLS-1$ // logger.logp(Level.FINE, CLASS_NAME, METHOD_NAME, "quiesceDevice is not implemented in defaultProvider!"); //$NON-NLS-1$ QuiesceRequestDocument requestDoc = QuiesceRequestDocument.Factory.newInstance(); QuiesceRequestDocument.QuiesceRequest request = requestDoc.addNewQuiesceRequest(); QuiesceRequestDocument.QuiesceRequest.Device requestDevice = request.addNewDevice(); requestDevice.setTimeout(timeout); logger.logp(Level.FINEST, CLASS_NAME, METHOD_NAME, "quiesce request created"); //$NON-NLS-1$ logger.logp(Level.FINER, CLASS_NAME, METHOD_NAME, "Sending quiesce request to device " //$NON-NLS-1$ + device.getHostname() + ":" + device.getAMPPort()); //$NON-NLS-1$ /* Send request to device */ StringBuffer outMessage = new StringBuffer(requestDoc.xmlText(soapHelper.getOptions())); Node responseDocXml = soapHelper.call(device, outMessage); outMessage.delete(0,outMessage.length()); outMessage = null; requestDoc.setNil(); requestDoc = null; /* Parse the request into a response object */ try{ QuiesceResponseDocument responseDoc = QuiesceResponseDocument.Factory.parse(responseDocXml); QuiesceResponseDocument.QuiesceResponse quiesceResponse = responseDoc.getQuiesceResponse(); if (quiesceResponse == null){ Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.quiesceNoResp",params); AMPException e = new AMPException(message,"wamt.amp.defaultV2Provider.CommandsImpl.quiesceNoResp",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, e); throw e; } Status.Enum status = quiesceResponse.getStatus(); if (status == null){ Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.quiesceNoStat",params); AMPException e = new AMPException(message,"wamt.amp.defaultV2Provider.CommandsImpl.quiesceNoStat",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, e); throw e; } else if (status.equals(Status.ERROR)){ Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.quiesceFail",params); DeviceExecutionException e = new DeviceExecutionException(message,"wamt.amp.defaultV2Provider.CommandsImpl.quiesceFail",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, e); throw e; } } catch (XmlException e){ Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.quiesceErrParse",params); AMPException ex = new AMPException(message,e,"wamt.amp.defaultV2Provider.CommandsImpl.quiesceErrParse",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, ex); throw ex; } catch (XmlValueOutOfRangeException e){ Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.quiesceInvalidEnum",params); AMPException ex = new AMPException(message,e,"wamt.amp.defaultV2Provider.CommandsImpl.quiesceInvalidEnum",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, ex); throw ex; } } public void unquiesceDevice(DeviceContext device) throws AMPIOException, InvalidCredentialsException, AMPException { final String METHOD_NAME = "unquiesceDevice"; //$NON-NLS-1$ // Implemented in wamt.amp.defaultV2Provider logger.logp(Level.FINE, CLASS_NAME, METHOD_NAME, "unquiesceDevice is not implemented in defaultV2Provider!"); //$NON-NLS-1$ UnquiesceRequestDocument requestDoc = UnquiesceRequestDocument.Factory.newInstance(); UnquiesceRequestDocument.UnquiesceRequest request = requestDoc.addNewUnquiesceRequest(); request.addNewDevice(); logger.logp(Level.FINEST, CLASS_NAME, METHOD_NAME, "unquiesce request created"); //$NON-NLS-1$ logger.logp(Level.FINER, CLASS_NAME, METHOD_NAME, "Sending unquiesce request to device " //$NON-NLS-1$ + device.getHostname() + ":" + device.getAMPPort()); //$NON-NLS-1$ /* Send request to device */ StringBuffer outMessage = new StringBuffer(requestDoc.xmlText(soapHelper.getOptions())); Node responseDocXml = soapHelper.call(device, outMessage); outMessage.delete(0,outMessage.length()); outMessage = null; requestDoc.setNil(); requestDoc = null; /* Parse the request into a response object */ try{ UnquiesceResponseDocument responseDoc = UnquiesceResponseDocument.Factory.parse(responseDocXml); UnquiesceResponseDocument.UnquiesceResponse unquiesceResponse = responseDoc.getUnquiesceResponse(); if (unquiesceResponse == null){ Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.unquiesceNoResp",params); AMPException e = new AMPException(message,"wamt.amp.defaultV2Provider.CommandsImpl.unquiesceNoResp",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, e); throw e; } Status.Enum status = unquiesceResponse.getStatus(); if (status == null){ Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.unquiesceNoStat",params); AMPException e = new AMPException(message,"wamt.amp.defaultV2Provider.CommandsImpl.unquiesceNoStat",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, e); throw e; } else if (status.equals(Status.ERROR)){ Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.unquiesceFail",params); DeviceExecutionException e = new DeviceExecutionException(message,"wamt.amp.defaultV2Provider.CommandsImpl.unquiesceFail",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, e); throw e; } } catch (XmlException e){ Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.unquiesceErrParse",params); AMPException ex = new AMPException(message,e,"wamt.amp.defaultV2Provider.CommandsImpl.unquiesceErrParse",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, ex); throw ex; } catch (XmlValueOutOfRangeException e){ Object[] params = {device.getHostname(),Integer.toString(device.getAMPPort())}; String message = Messages.getString("wamt.amp.defaultV2Provider.CommandsImpl.unquiesceInvalidEnum",params); AMPException ex = new AMPException(message,e,"wamt.amp.defaultV2Provider.CommandsImpl.unquiesceInvalidEnum",params); //$NON-NLS-1$ //$NON-NLS-2$ logger.throwing(CLASS_NAME, METHOD_NAME, ex); throw ex; } } /* * Load the encrypted content from files that were previously saved from a * Secure Backup call. This method is called from * * @param backupFilesTable this is a Hashtable whose keys are file names and the values * are the corresponding file content. The information from the table will be loaded into * com.datapower.schemas.appliance.management.x20.SecureBackup and sent by AMP to the device on a Secure Restore request. * @return SecureBackup contains multiple SecureBackupFile objects - one for each file used * during Secure Restore * @see #restoreDevice */ private SecureBackup readBackUpFiles(Hashtable<String,byte[]> backupFilesTable) { final String METHOD_NAME = "writeToBackUpFile"; if (backupFilesTable == null){ return null; } SecureBackupFile sbf = null; SecureBackup sb = SecureBackup.Factory.newInstance(); Enumeration<String> fileNames = backupFilesTable.keys(); while(fileNames.hasMoreElements()) { String fileName =(String)fileNames.nextElement(); byte[] fileContent = (byte[]) backupFilesTable.get(fileName); logger.logp(Level.FINER, CLASS_NAME, METHOD_NAME, "Adding backup File: " + fileName); try{ sbf = sb.addNewSecureBackupFile(); sbf.setName(fileName); sbf.setStringValue(new String(fileContent)); }catch(Exception e){ logger.logp(Level.SEVERE, CLASS_NAME, METHOD_NAME, "Exception thrown:", e); //e.printStackTrace(); } } return sb; } // =========================== New functions for provider V3 =========================== /* * (non-Javadoc) * @see com.ibm.datapower.amt.amp.Commands#getServiceList(com.ibm.datapower.amt.amp.DeviceContext, java.lang.String) */ public RuntimeService[] getServiceListFromDomain(DeviceContext device, String domainName) throws DeviceExecutionException, AMPIOException, AMPException { final String METHOD_NAME = "getServiceListFromDomain"; //$NON-NLS-1$ logger.logp(Level.FINE, CLASS_NAME, METHOD_NAME, "getServiceListFromDomain() is not implemented in com.ibm.datapower.amt.amp.defaultV2Provider.CommandsImpl"); //$NON-NLS-1$ throw new UnsupportedOperationException(); } /* * (non-Javadoc) * @see com.ibm.datapower.amt.amp.Commands#getInterDependentServices(com.ibm.datapower.amt.amp.DeviceContext, java.lang.String, java.lang.String, java.lang.String, com.ibm.datapower.amt.amp.ObjectContext[]) */ public InterDependentServiceCollection getInterDependentServices(DeviceContext device, String domainName, String fileDomainName, String fileNameOnDevice, ConfigObject[] objectInfo) throws InvalidCredentialsException, DeviceExecutionException, AMPIOException, AMPException { final String METHOD_NAME = "getInterDependentServices"; //$NON-NLS-1$ logger.logp(Level.FINE, CLASS_NAME, METHOD_NAME, "getInterDependentServices() is not implemented in com.ibm.datapower.amt.amp.defaultV2Provider.CommandsImpl"); //$NON-NLS-1$ throw new UnsupportedOperationException(); } /* * (non-Javadoc) * @see com.ibm.datapower.amt.amp.Commands#getInterDependentServices(com.ibm.datapower.amt.amp.DeviceContext, java.lang.String, byte[], com.ibm.datapower.amt.amp.ObjectContext[]) */ public InterDependentServiceCollection getInterDependentServices(DeviceContext device, String domainName, byte[] packageImage, ConfigObject[] objectArray) throws NotExistException, InvalidCredentialsException,DeviceExecutionException, AMPIOException, AMPException { final String METHOD_NAME = "getInterDependentServices"; //$NON-NLS-1$ logger.logp(Level.FINE, CLASS_NAME, METHOD_NAME, "getInterDependentServices()s is not implemented in com.ibm.datapower.amt.amp.defaultV2Provider.CommandsImpl"); //$NON-NLS-1$ throw new UnsupportedOperationException(); } /* * (non-Javadoc) * @see com.ibm.datapower.amt.amp.Commands#getServiceListFromExport(com.ibm.datapower.amt.amp.DeviceContext, java.lang.String, java.lang.String) */ public ConfigService[] getServiceListFromExport(DeviceContext device, String fileDomainName, String fileNameOnDevice) throws InvalidCredentialsException, DeviceExecutionException, AMPIOException, AMPException { final String METHOD_NAME = "getServiceListFromExport"; //$NON-NLS-1$ logger.logp(Level.FINE, CLASS_NAME, METHOD_NAME, "getServiceListFromExport() is not implemented in com.ibm.datapower.amt.amp.defaultV2Provider.CommandsImpl"); //$NON-NLS-1$ throw new UnsupportedOperationException(); } /* * (non-Javadoc) * @see com.ibm.datapower.amt.amp.Commands#getServiceListFromExport(com.ibm.datapower.amt.amp.DeviceContext, byte[]) */ public ConfigService[] getServiceListFromExport(DeviceContext device, byte[] packageImage) throws NotExistException, InvalidCredentialsException,DeviceExecutionException, AMPIOException, AMPException { final String METHOD_NAME = "getServiceListFromExport"; //$NON-NLS-1$ logger.logp(Level.FINE, CLASS_NAME, METHOD_NAME, "getServiceListFromExport() is not implemented in com.ibm.datapower.amt.amp.defaultV2Provider.CommandsImpl"); //$NON-NLS-1$ throw new UnsupportedOperationException(); } /* * (non-Javadoc) * @see com.ibm.datapower.amt.amp.Commands#getReferencedObjects(com.ibm.datapower.amt.amp.DeviceContext, java.lang.String, java.lang.String, java.lang.String) */ public ReferencedObjectCollection getReferencedObjects(DeviceContext device, String domainName, String objectName, String objectClassName) throws InvalidCredentialsException, DeviceExecutionException, AMPIOException, AMPException { final String METHOD_NAME = "getReferencedObjects"; //$NON-NLS-1$ // Implemented in wamt.amp.defaultV3Provider logger.logp(Level.FINE, CLASS_NAME, METHOD_NAME, "getReferencedObjects() is not implemented in com.ibm.datapower.amt.amp.defaultV2Provider.CommandsImpl"); //$NON-NLS-1$ throw new UnsupportedOperationException(); } /* * (non-Javadoc) * @see com.ibm.datapower.amt.amp.Commands#deleteService(com.ibm.datapower.amt.amp.DeviceContext, java.lang.String, java.lang.String, java.lang.String, com.ibm.datapower.amt.amp.ObjectMetaInfo[], boolean) */ public DeleteObjectResult[] deleteService(DeviceContext device, String domainName, String objectName, String objectClassName, ConfigObject [] excludeObjects, boolean deleteReferencedFiles) throws NotExistException, InvalidCredentialsException, DeviceExecutionException, AMPIOException, AMPException { final String METHOD_NAME = "deleteService"; //$NON-NLS-1$ logger.logp(Level.FINE, CLASS_NAME, METHOD_NAME, "deleteService() is not implemented in com.ibm.datapower.amt.amp.defaultV2Provider.CommandsImpl"); //$NON-NLS-1$ throw new UnsupportedOperationException(); } /* * (non-Javadoc) * @see com.ibm.datapower.amt.amp.Commands#quiesceService(com.ibm.datapower.amt.amp.DeviceContext, java.lang.String, com.ibm.datapower.amt.amp.ObjectContext[], int) */ public void quiesceService(DeviceContext device, String domain, ConfigObject[] objects, int timeout) throws AMPIOException, InvalidCredentialsException, AMPException { final String METHOD_NAME = "quiesceService"; //$NON-NLS-1$ logger.logp(Level.FINE, CLASS_NAME, METHOD_NAME, "quiesceService() is not implemented in com.ibm.datapower.amt.amp.defaultV2Provider.CommandsImpl"); //$NON-NLS-1$ throw new UnsupportedOperationException(); } /* * (non-Javadoc) * @see com.ibm.datapower.amt.amp.Commands#unquiesceService(com.ibm.datapower.amt.amp.DeviceContext, java.lang.String, com.ibm.datapower.amt.amp.ObjectContext[]) */ public void unquiesceService(DeviceContext device, String domain, ConfigObject[] objects) throws AMPIOException, InvalidCredentialsException, AMPException { final String METHOD_NAME = "unquiesceService"; //$NON-NLS-1$ logger.logp(Level.FINE, CLASS_NAME, METHOD_NAME, "unquiesceService() is not implemented in com.ibm.datapower.amt.amp.defaultV2Provider.CommandsImpl"); //$NON-NLS-1$ throw new UnsupportedOperationException(); } /* * (non-Javadoc) * @see com.ibm.datapower.amt.amp.Commands#startService(com.ibm.datapower.amt.amp.DeviceContext, java.lang.String, com.ibm.datapower.amt.amp.ObjectContext[]) */ public void startService(DeviceContext device, String domainName, ConfigObject[] object) throws AMPIOException, InvalidCredentialsException, AMPException { final String METHOD_NAME = "startService"; //$NON-NLS-1$ logger.logp(Level.FINE, CLASS_NAME, METHOD_NAME, "startService() is not implemented in com.ibm.datapower.amt.amp.defaultV2Provider.CommandsImpl"); //$NON-NLS-1$ throw new UnsupportedOperationException(); } /* * (non-Javadoc) * @see com.ibm.datapower.amt.amp.Commands#stopService(com.ibm.datapower.amt.amp.DeviceContext, java.lang.String, com.ibm.datapower.amt.amp.ObjectContext[]) */ public void stopService(DeviceContext device, String domainName, ConfigObject[] objects) throws AMPIOException, InvalidCredentialsException, AMPException { final String METHOD_NAME = "stopService"; //$NON-NLS-1$ logger.logp(Level.FINE, CLASS_NAME, METHOD_NAME, "stopService() is not implemented in com.ibm.datapower.amt.amp.defaultV2Provider.CommandsImpl"); //$NON-NLS-1$ throw new UnsupportedOperationException(); } /* * (non-Javadoc) * @see com.ibm.datapower.amt.amp.Commands#setDomainByService(com.ibm.datapower.amt.amp.DeviceContext, java.lang.String, com.ibm.datapower.amt.amp.ObjectContext[], byte[], com.ibm.datapower.amt.clientAPI.DeploymentPolicy, boolean) */ public void setDomainByService(DeviceContext device, String domainName, ConfigObject[] objects, byte[] domainImage, DeploymentPolicy policy, boolean ImportAllFiles) throws InvalidCredentialsException, DeviceExecutionException, AMPIOException, AMPException, DeletedException { final String METHOD_NAME = "setDomainByService"; //$NON-NLS-1$ logger.logp(Level.FINE, CLASS_NAME, METHOD_NAME, "setDomainByService() is not implemented in com.ibm.datapower.amt.amp.defaultV2Provider.CommandsImpl"); //$NON-NLS-1$ throw new UnsupportedOperationException(); } /* * (non-Javadoc) * @see com.ibm.datapower.amt.amp.Commands#setDomainByService(com.ibm.datapower.amt.amp.DeviceContext, java.lang.String, com.ibm.datapower.amt.amp.ConfigObject[], java.lang.String, java.lang.String, com.ibm.datapower.amt.clientAPI.DeploymentPolicy, boolean) */ public void setDomainByService(DeviceContext device, String domainName, ConfigObject[] objects, String fileDomainName, String fileNameOnDevice, DeploymentPolicy policy, boolean importAllFiles) throws InvalidCredentialsException, DeviceExecutionException, AMPIOException, AMPException, DeletedException{ final String METHOD_NAME = "setDomainByService"; //$NON-NLS-1$ logger.logp(Level.FINE, CLASS_NAME, METHOD_NAME, "setDomainByService() is not implemented in com.ibm.datapower.amt.amp.defaultV2Provider.CommandsImpl"); //$NON-NLS-1$ throw new UnsupportedOperationException(); } public void setFirmware(DeviceContext device, byte[] firmwareImage, boolean acceptLicense) throws InvalidCredentialsException, DeviceExecutionException, AMPIOException, AMPException{ final String METHOD_NAME = "setFirmware"; //$NON-NLS-1$ logger.logp(Level.FINE, CLASS_NAME, METHOD_NAME, "setFirmware() with parameter acceptLicense is not implemented in com.ibm.datapower.amt.amp.defaultV2Provider.CommandsImpl"); //$NON-NLS-1$ throw new UnsupportedOperationException(); } public void setFirmware(DeviceContext device, InputStream inputStream, boolean acceptLicense) throws InvalidCredentialsException, DeviceExecutionException, AMPIOException, AMPException { final String METHOD_NAME = "setFirmware"; //$NON-NLS-1$ logger.logp(Level.FINE, CLASS_NAME, METHOD_NAME, "setFirmware() with parameter acceptLicense is not implemented in com.ibm.datapower.amt.amp.defaultV2Provider.CommandsImpl"); //$NON-NLS-1$ throw new UnsupportedOperationException(); } /* * (non-Javadoc) * @see com.ibm.datapower.amt.amp.Commands#deleteFile(com.ibm.datapower.amt.amp.DeviceContext, java.lang.String, java.lang.String) */ public void deleteFile(DeviceContext device, String domainName, String fileNameOnDevice) throws InvalidCredentialsException, DeviceExecutionException, AMPIOException, AMPException { final String METHOD_NAME = "deleteFile"; //$NON-NLS-1$ logger.logp(Level.FINE, CLASS_NAME, METHOD_NAME, "deleteFile() is not implemented in com.ibm.datapower.amt.amp.defaultV2Provider.CommandsImpl"); //$NON-NLS-1$ throw new UnsupportedOperationException(); } }
55.190308
261
0.643981
229eda430d7d3509b1b49fb7c9525aae87f2e73d
2,029
/* * Copyright The OpenTelemetry Authors * SPDX-License-Identifier: Apache-2.0 */ package io.opentelemetry.sdk.resources; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertThrows; import com.google.common.collect.ImmutableSet; import org.junit.jupiter.api.Test; class ResourcesConfigTest { @Test void defaultResourcesConfig() { assertThat(ResourcesConfig.getDefault().getDisabledResourceProviders()) .isEqualTo(ImmutableSet.of()); } @Test void updateResourcesConfig_NullDisabledResourceProviders() { assertThrows( NullPointerException.class, () -> ResourcesConfig.getDefault().toBuilder().setDisabledResourceProviders(null).build()); } @Test void updateResourcesConfig_SystemProperties() { System.setProperty( "otel.java.disabled.resource_providers", "com.package.provider.ToDisable1, com.package.provider.ToDisable2"); ResourcesConfig resourcesConfig = ResourcesConfig.newBuilder().readSystemProperties().readEnvironmentVariables().build(); assertThat(resourcesConfig.getDisabledResourceProviders()) .isEqualTo( ImmutableSet.of("com.package.provider.ToDisable1", "com.package.provider.ToDisable2")); } @Test void updateResourcesConfig_EmptyDisabledResourceProviders() { System.setProperty("otel.java.disabled.resource_providers", ""); ResourcesConfig resourcesConfig = ResourcesConfig.newBuilder().readSystemProperties().readEnvironmentVariables().build(); assertThat(resourcesConfig.getDisabledResourceProviders()).isEqualTo(ImmutableSet.of()); } @Test void updateResourcesConfig_All() { ResourcesConfig resourcesConfig = ResourcesConfig.newBuilder() .setDisabledResourceProviders(ImmutableSet.of("com.package.provider.ToDisable")) .build(); assertThat(resourcesConfig.getDisabledResourceProviders()) .isEqualTo(ImmutableSet.of("com.package.provider.ToDisable")); } }
34.389831
99
0.747166
05049b46a284824dfc99dca4e0ce72eb0cd2d740
774
package io.tomahawkd.tlstester.config; import io.tomahawkd.config.sources.ConfigSource; import java.util.HashMap; import java.util.Map; public class EnvironmentConfigSource implements ConfigSource { @Override public Map<String, String> getData() { Map<String, String> env = new HashMap<>(); // System OS String os = System.getProperty("os.name"); String osStr = EnvironmentConstants.LINUX; if (os.contains(EnvironmentConstants.WINDOWS)) { if (os.equals(EnvironmentConstants.WINDOWS10)) { osStr = EnvironmentConstants.WINDOWS10; } else { osStr = EnvironmentConstants.WINDOWS; } } else if (os.equals(EnvironmentConstants.MACOS)) { osStr = EnvironmentConstants.MACOS; } env.put(EnvironmentNames.SYSTEM_OS, osStr); return env; } }
24.967742
62
0.736434
2334db0a516eca8dd384ecff839df8611628412b
6,160
package se.codeunlimited.firebaseauthexample; import android.arch.lifecycle.ViewModelProviders; import android.content.Intent; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v4.app.FragmentTransaction; import android.widget.Toast; import com.google.android.gms.auth.api.Auth; import com.google.android.gms.auth.api.signin.GoogleSignInAccount; import com.google.android.gms.auth.api.signin.GoogleSignInOptions; import com.google.android.gms.auth.api.signin.GoogleSignInResult; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.common.api.ResultCallback; import com.google.android.gms.common.api.Status; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.AuthCredential; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.auth.GoogleAuthProvider; import timber.log.Timber; public class MainActivity extends LogActivity implements GoogleApiClient.OnConnectionFailedListener { private static final int RC_SIGN_IN = 9001; private FirebaseAuth mAuth; private GoogleApiClient mGoogleApiClient; private AuthViewModel authViewModel; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if (savedInstanceState == null) { FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction(); fragmentTransaction.replace(R.id.placeholder, new MainFragment()); fragmentTransaction.commit(); } authViewModel = ViewModelProviders.of(this).get(AuthViewModel.class); GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) .requestIdToken(getString(R.string.default_web_client_id)) .requestEmail() .build(); mGoogleApiClient = new GoogleApiClient.Builder(this) .enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */) .addApi(Auth.GOOGLE_SIGN_IN_API, gso) .build(); mAuth = FirebaseAuth.getInstance(); FirebaseUser currentUser = mAuth.getCurrentUser(); authViewModel.setLoggedIn(currentUser != null); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); // Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...); if (requestCode == RC_SIGN_IN) { GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data); if (result.isSuccess()) { // Google Sign In was successful, authenticate with Firebase GoogleSignInAccount account = result.getSignInAccount(); firebaseAuthWithGoogle(account); } else { // Google Sign In failed, update UI appropriately authViewModel.setLoggedIn(false); } } } private void firebaseAuthWithGoogle(GoogleSignInAccount acct) { Timber.d("firebaseAuthWithGoogle:" + acct.getId()); // TODO showProgressDialog(); AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null); mAuth.signInWithCredential(credential) .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { // Sign in success, update UI with the signed-in user's information Timber.d("signInWithCredential:success"); FirebaseUser user = mAuth.getCurrentUser(); authViewModel.setLoggedIn(user != null); } else { // If sign in fails, display a message to the user. Timber.w("signInWithCredential:failure", task.getException()); Toast.makeText(getApplicationContext(), "Authentication failed.", Toast.LENGTH_SHORT).show(); authViewModel.setLoggedIn(false); } // TODO hideProgressDialog(); } }); } void signIn() { Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient); startActivityForResult(signInIntent, RC_SIGN_IN); } void signOut() { // Firebase sign out mAuth.signOut(); // Google sign out Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback( new ResultCallback<Status>() { @Override public void onResult(@NonNull Status status) { authViewModel.setLoggedIn(false); } }); } void revokeAccess() { // Firebase sign out mAuth.signOut(); // Google revoke access Auth.GoogleSignInApi.revokeAccess(mGoogleApiClient).setResultCallback( new ResultCallback<Status>() { @Override public void onResult(@NonNull Status status) { authViewModel.setLoggedIn(false); } }); } @Override public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { // An unresolvable error has occurred and Google APIs (including Sign-In) will not // be available. Timber.d("onConnectionFailed:" + connectionResult); Toast.makeText(this, "Google Play Services error.", Toast.LENGTH_SHORT).show(); } }
40.526316
102
0.640097
c1071efa1b22da1660812a8c2a3ac7063dc53a8e
1,541
package com.sicdlib.dao.pyhtonDAO.imple; import com.sicdlib.dao.pyhtonDAO.IBBSChinaPostDAO; import com.sicdlib.dao.IBaseDAO; import com.sicdlib.dto.TbArticleSimilarityEntity; import com.sicdlib.dto.entity.BbsChinaPostEntity; import org.hibernate.Session; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import java.util.List; /** * Created by init on 2017/5/26. */ @Repository("bbsChinaPostDAO") public class BBSChinaPostDAO implements IBBSChinaPostDAO { @Autowired private IBaseDAO baseDAO; @Override public Boolean saveBBSChinaPost(BbsChinaPostEntity bbsChinaPost) { try { baseDAO.save(bbsChinaPost); return true; }catch (Exception e){ e.printStackTrace(); return false; } } @Override public BbsChinaPostEntity getBbsChinaPost(String id) { String hql = "from BbsChinaPostEntity cp where cp.id ='" + id + "'"; return (BbsChinaPostEntity) baseDAO.get(hql); } @Override public List<BbsChinaPostEntity> getbbsChinaPost(String authorID) { /*String hql = "FROM BbsChinaPostEntity where authorId = '" + authorID + "'"; return (List<BbsChinaPostEntity>) baseDAO.get(hql);*/ return null; } @Override public BbsChinaPostEntity getBbsChinaPostInfoByID(String postID) { String hql = "from BbsChinaPostEntity where postId ='" + postID + "'"; return (BbsChinaPostEntity) baseDAO.get(hql); } }
29.075472
85
0.69111
43f3cd5e47e9a56f077d3c32180239da1f0cd7df
1,178
/* * This file is subject to the terms and conditions outlined in the file 'LICENSE' (hint: it's MIT); this file is located in the root directory near the README.md which you should also read. * * This file is part of the 'Adama' project which is a programming language and document store for board games; however, it can be so much more. * * See http://www.adama-lang.org/ for more information. * * (c) 2020 - 2022 by Jeffrey M. Barber (http://jeffrey.io) */ package org.adamalang.grpc; import org.adamalang.grpc.client.InstanceClient; import org.adamalang.grpc.mocks.MockClentLifecycle; import org.adamalang.grpc.mocks.StdErrLogger; import org.junit.Test; public class EndToEnd_HappyTests { @Test public void ss() throws Exception { try (TestBed bed = new TestBed( 20000, "@connected(who) { return true; } public int x; @construct { x = 123; transition #p in 0.5; } #p { x++; } ")) { MockClentLifecycle lifecycle = new MockClentLifecycle(); InstanceClient instanceClient = new InstanceClient( bed.identity, "127.0.0.1:20000", bed.clientExecutor, lifecycle, new StdErrLogger()); } } }
38
190
0.686757
c6107690cb1c6b6bb0926f5517d6b7ca624ec3bf
507
/* * Copyright 2016 Gili Tzabari. * Licensed under the Apache License, Version 2.0: http://www.apache.org/licenses/LICENSE-2.0 */ package com.github.cowwoc.pouch.jersey.scope; import java.sql.Connection; /** * Values specific to a database transaction. * <p> * Implementations are not thread-safe. * * @author Gili Tzabari */ public interface TransactionScope extends ApplicationScope { /** * @return the database connection associated with the transaction */ Connection getConnection(); }
22.043478
93
0.7357
badbde37d4ac02b26c38b67bae7b2e3228c440d0
4,939
/** * Copyright (C) 2009-2016 DANS - Data Archiving and Networked Services ([email protected]) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package nl.knaw.dans.common.dataperfect; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Abstract class providing methods common to the DateFormatter and TimeFormatter classes. * * @author Martin Braaksma */ abstract class OrderedFieldFormatter extends AbstractFormatter { private static final String MODE_INDICATORS = "((?:::|;;).*)"; private final Pattern patternPicture; private final String indicatorSubgroup; private final String[] separators = new String[4]; private final int[] fieldLengths = new int[3]; private final int[] fields = new int[3]; private String fieldOrder; private int dataLength; public OrderedFieldFormatter(final String indicatorSubgroup, final String fieldOrderSubgroup, final String separatorSubgroup, final String numberSubgroup, final String picture, final String defaultFieldOrder) { super(picture); this.indicatorSubgroup = indicatorSubgroup; patternPicture = Pattern.compile(indicatorSubgroup + fieldOrderSubgroup + separatorSubgroup + "?" + numberSubgroup + "?" + separatorSubgroup + "?" + numberSubgroup + "?" + separatorSubgroup + "?" + numberSubgroup + "?" + MODE_INDICATORS + "?"); getPictureValues(strippedPicture, defaultFieldOrder); } abstract void setFields(final Object object, final int[] fields); private void getPictureValues(final String picture, final String defaultFieldOrder) { final Matcher pictureMatcher = patternPicture.matcher(picture); if (! pictureMatcher.matches()) { throw new IllegalArgumentException("Picture does not match expected pattern for type " + indicatorSubgroup + ": " + picture); } fieldOrder = pictureMatcher.group(2); if ("".equals(fieldOrder)) { fieldOrder = defaultFieldOrder; /* * Subtract 1 character that identifies the field type */ dataLength = picture.length() - 1; } else { dataLength = picture.length() - 1 - fieldOrder.length(); } separators[0] = pictureMatcher.group(3); fieldLengths[0] = getFieldLength(pictureMatcher.group(4)); separators[1] = pictureMatcher.group(5); fieldLengths[1] = getFieldLength(pictureMatcher.group(6)); separators[2] = pictureMatcher.group(7); fieldLengths[2] = getFieldLength(pictureMatcher.group(8)); } private static int getFieldLength(final String picturePart) { if (picturePart == null) { return -1; } return picturePart.length(); } protected void setField(final int[] fields, final char fieldLetter, final int fieldValue) { int index = fieldOrder.indexOf(fieldLetter); if (index != -1) { fields[index] = fieldValue; } } private static String formatField(int fieldLength, int fieldValue) { if (fieldLength == 0) { return ""; } String result = String.format("%0" + fieldLength + "d", fieldValue); return result.substring(result.length() - fieldLength); } public String format(final Object object) { if (! (object instanceof Number)) { throw new IllegalArgumentException("Object to format must be a java.lang.Number"); } setFields(object, fields); final StringBuilder buffer = new StringBuilder(); buffer.append(separators[0] == null ? "" : separators[0]); buffer.append(formatField(fieldLengths[0], fields[0])); buffer.append(separators[1] == null ? "" : separators[1]); buffer.append(fieldLengths[1] == -1 ? "" : formatField(fieldLengths[1], fields[1])); buffer.append(separators[2] == null ? "" : separators[2]); buffer.append(fieldLengths[2] == -1 ? "" : formatField(fieldLengths[2], fields[2])); return buffer.toString(); } public int getDataLength() { return dataLength; } }
33.828767
118
0.621178
9fb1828d3b20e3bc7aa59e4fd85c7cda0ff1f468
1,108
// Copyright 2011 The Apache Software Foundation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.apache.tapestry5.jpa; import org.apache.tapestry5.PersistenceConstants; /** * Constants for persistent field strategies. * * @since 5.3 */ public class JpaPersistenceConstants { /** * If the field's value is a persistent JPA entity, its type and primary key is stored in the * {@link org.apache.tapestry5.http.services.Session}. Otherwise, * the value is stored as per {@link PersistenceConstants#SESSION}. */ public static final String ENTITY = "entity"; }
33.575758
97
0.734657
070760e97ba6d5fecc4526bece3d94f2a082ca0d
13,819
// Copyright (c) 2002 Graz University of Technology. 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. The end-user documentation included with the redistribution, if any, must // include the following acknowledgment: // // "This product includes software developed by IAIK of Graz University of // Technology." // // Alternately, this acknowledgment may appear in the software itself, if and // wherever such third-party acknowledgments normally appear. // // 4. The names "Graz University of Technology" and "IAIK of Graz University of // Technology" must not be used to endorse or promote products derived from this // software without prior written permission. // // 5. Products derived from this software may not be called "IAIK PKCS Wrapper", // nor may "IAIK" appear in their name, without prior written permission of // Graz University of Technology. // // THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESSED 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 LICENSOR 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 demo.pkcs.pkcs11.wrapper.keygeneration; import iaik.pkcs.pkcs11.Mechanism; import iaik.pkcs.pkcs11.MechanismInfo; import iaik.pkcs.pkcs11.Module; import iaik.pkcs.pkcs11.Session; import iaik.pkcs.pkcs11.Slot; import iaik.pkcs.pkcs11.Token; import iaik.pkcs.pkcs11.TokenException; import iaik.pkcs.pkcs11.TokenInfo; import iaik.pkcs.pkcs11.objects.KeyPair; import iaik.pkcs.pkcs11.objects.Object; import iaik.pkcs.pkcs11.objects.RSAPrivateKey; import iaik.pkcs.pkcs11.objects.RSAPublicKey; import iaik.pkcs.pkcs11.wrapper.Functions; import iaik.pkcs.pkcs11.wrapper.PKCS11Constants; import java.io.BufferedReader; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigInteger; import java.security.KeyFactory; import java.security.NoSuchAlgorithmException; import java.security.spec.InvalidKeySpecException; import java.security.spec.RSAPublicKeySpec; import java.security.spec.X509EncodedKeySpec; import java.util.Arrays; import java.util.HashSet; import java.util.Random; import demo.pkcs.pkcs11.wrapper.util.Util; /** * This demo program generates a 2048 bit RSA key-pair on the token and writes the public key to a * file. */ public class GenerateKeyPair { static BufferedReader input_; static PrintWriter output_; static { try { // output_ = new PrintWriter(new FileWriter("SignAndVerify_output.txt"), true); output_ = new PrintWriter(System.out, true); input_ = new BufferedReader(new InputStreamReader(System.in)); } catch (Throwable thr) { thr.printStackTrace(); output_ = new PrintWriter(System.out, true); input_ = new BufferedReader(new InputStreamReader(System.in)); } } /** * Usage: GenerateKeyPair PKCS#11-module X.509-encoded-public-key-file [slot-index] [pin] */ public static void main(String[] args) throws IOException, TokenException, NoSuchAlgorithmException, InvalidKeySpecException { if (args.length < 2) { printUsage(); throw new IOException("Missing argument!"); } Module pkcs11Module = Module.getInstance(args[0]); pkcs11Module.initialize(null); Slot[] slots = pkcs11Module.getSlotList(Module.SlotRequirement.TOKEN_PRESENT); if (slots.length == 0) { output_.println("No slot with present token found!"); throw new TokenException("No token found!"); } Slot selectedSlot; if (2 < args.length) selectedSlot = slots[Integer.parseInt(args[2])]; else selectedSlot = slots[0]; Token token = selectedSlot.getToken(); TokenInfo tokenInfo = token.getTokenInfo(); output_ .println("################################################################################"); output_.println("Information of Token:"); output_.println(tokenInfo); output_ .println("################################################################################"); Session session; if (3 < args.length) session = Util.openAuthorizedSession(token, Token.SessionReadWriteBehavior.RW_SESSION, output_, input_, args[3]); else session = Util.openAuthorizedSession(token, Token.SessionReadWriteBehavior.RW_SESSION, output_, input_, null); output_ .println("################################################################################"); output_.print("Generating new 2048 bit RSA key-pair... "); output_.flush(); // first check out what attributes of the keys we may set HashSet supportedMechanisms = new HashSet(Arrays.asList(token.getMechanismList())); MechanismInfo signatureMechanismInfo; if (supportedMechanisms.contains(Mechanism.get(PKCS11Constants.CKM_RSA_PKCS))) { signatureMechanismInfo = token.getMechanismInfo(Mechanism .get(PKCS11Constants.CKM_RSA_PKCS)); } else if (supportedMechanisms.contains(Mechanism.get(PKCS11Constants.CKM_RSA_X_509))) { signatureMechanismInfo = token.getMechanismInfo(Mechanism .get(PKCS11Constants.CKM_RSA_X_509)); } else if (supportedMechanisms.contains(Mechanism.get(PKCS11Constants.CKM_RSA_9796))) { signatureMechanismInfo = token.getMechanismInfo(Mechanism .get(PKCS11Constants.CKM_RSA_9796)); } else if (supportedMechanisms.contains(Mechanism .get(PKCS11Constants.CKM_RSA_PKCS_OAEP))) { signatureMechanismInfo = token.getMechanismInfo(Mechanism .get(PKCS11Constants.CKM_RSA_PKCS_OAEP)); } else { signatureMechanismInfo = null; } Mechanism keyPairGenerationMechanism = Mechanism .get(PKCS11Constants.CKM_RSA_PKCS_KEY_PAIR_GEN); RSAPublicKey rsaPublicKeyTemplate = new RSAPublicKey(); RSAPrivateKey rsaPrivateKeyTemplate = new RSAPrivateKey(); // set the general attributes for the public key rsaPublicKeyTemplate.getModulusBits().setLongValue(new Long(2048)); byte[] publicExponentBytes = { 0x01, 0x00, 0x01 }; // 2^16 + 1 rsaPublicKeyTemplate.getPublicExponent().setByteArrayValue(publicExponentBytes); rsaPublicKeyTemplate.getToken().setBooleanValue(Boolean.TRUE); byte[] id = new byte[20]; new Random().nextBytes(id); rsaPublicKeyTemplate.getId().setByteArrayValue(id); // rsaPublicKeyTemplate.getLabel().setCharArrayValue(args[2].toCharArray()); rsaPrivateKeyTemplate.getSensitive().setBooleanValue(Boolean.TRUE); rsaPrivateKeyTemplate.getToken().setBooleanValue(Boolean.TRUE); rsaPrivateKeyTemplate.getPrivate().setBooleanValue(Boolean.TRUE); rsaPrivateKeyTemplate.getId().setByteArrayValue(id); // byte[] subject = args[1].getBytes(); // rsaPrivateKeyTemplate.getSubject().setByteArrayValue(subject); // rsaPrivateKeyTemplate.getLabel().setCharArrayValue(args[2].toCharArray()); // set the attributes in a way netscape does, this should work with most tokens if (signatureMechanismInfo != null) { rsaPublicKeyTemplate.getVerify().setBooleanValue( new Boolean(signatureMechanismInfo.isVerify())); rsaPublicKeyTemplate.getVerifyRecover().setBooleanValue( new Boolean(signatureMechanismInfo.isVerifyRecover())); rsaPublicKeyTemplate.getEncrypt().setBooleanValue( new Boolean(signatureMechanismInfo.isEncrypt())); rsaPublicKeyTemplate.getDerive().setBooleanValue( new Boolean(signatureMechanismInfo.isDerive())); rsaPublicKeyTemplate.getWrap().setBooleanValue( new Boolean(signatureMechanismInfo.isWrap())); rsaPrivateKeyTemplate.getSign().setBooleanValue( new Boolean(signatureMechanismInfo.isSign())); rsaPrivateKeyTemplate.getSignRecover().setBooleanValue( new Boolean(signatureMechanismInfo.isSignRecover())); rsaPrivateKeyTemplate.getDecrypt().setBooleanValue( new Boolean(signatureMechanismInfo.isDecrypt())); rsaPrivateKeyTemplate.getDerive().setBooleanValue( new Boolean(signatureMechanismInfo.isDerive())); rsaPrivateKeyTemplate.getUnwrap().setBooleanValue( new Boolean(signatureMechanismInfo.isUnwrap())); } else { // if we have no information we assume these attributes rsaPrivateKeyTemplate.getSign().setBooleanValue(Boolean.TRUE); rsaPrivateKeyTemplate.getDecrypt().setBooleanValue(Boolean.TRUE); rsaPublicKeyTemplate.getVerify().setBooleanValue(Boolean.TRUE); rsaPublicKeyTemplate.getEncrypt().setBooleanValue(Boolean.TRUE); } // netscape does not set these attribute, so we do no either rsaPublicKeyTemplate.getKeyType().setPresent(false); rsaPublicKeyTemplate.getObjectClass().setPresent(false); rsaPrivateKeyTemplate.getKeyType().setPresent(false); rsaPrivateKeyTemplate.getObjectClass().setPresent(false); KeyPair generatedKeyPair = session.generateKeyPair(keyPairGenerationMechanism, rsaPublicKeyTemplate, rsaPrivateKeyTemplate); RSAPublicKey generatedRSAPublicKey = (RSAPublicKey) generatedKeyPair.getPublicKey(); RSAPrivateKey generatedRSAPrivateKey = (RSAPrivateKey) generatedKeyPair .getPrivateKey(); // no we may work with the keys... output_.println("Success"); output_.println("The public key is"); output_ .println("_______________________________________________________________________________"); output_.println(generatedRSAPublicKey); output_ .println("_______________________________________________________________________________"); output_.println("The private key is"); output_ .println("_______________________________________________________________________________"); output_.println(generatedRSAPrivateKey); output_ .println("_______________________________________________________________________________"); // write the public key to file output_ .println("################################################################################"); output_.println("Writing the public key of the generated key-pair to file: " + args[1]); RSAPublicKey exportableRsaPublicKey = generatedRSAPublicKey; BigInteger modulus = new BigInteger(1, exportableRsaPublicKey.getModulus() .getByteArrayValue()); BigInteger publicExponent = new BigInteger(1, exportableRsaPublicKey .getPublicExponent().getByteArrayValue()); RSAPublicKeySpec rsaPublicKeySpec = new RSAPublicKeySpec(modulus, publicExponent); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); java.security.interfaces.RSAPublicKey javaRsaPublicKey = (java.security.interfaces.RSAPublicKey) keyFactory .generatePublic(rsaPublicKeySpec); X509EncodedKeySpec x509EncodedPublicKey = (X509EncodedKeySpec) keyFactory.getKeySpec( javaRsaPublicKey, X509EncodedKeySpec.class); FileOutputStream publicKeyFileStream = new FileOutputStream(args[1]); publicKeyFileStream.write(x509EncodedPublicKey.getEncoded()); publicKeyFileStream.flush(); publicKeyFileStream.close(); output_ .println("################################################################################"); // now we try to search for the generated keys output_ .println("################################################################################"); output_ .println("Trying to search for the public key of the generated key-pair by ID: " + Functions.toHexString(id)); // set the search template for the public key RSAPublicKey exportRsaPublicKeyTemplate = new RSAPublicKey(); exportRsaPublicKeyTemplate.getId().setByteArrayValue(id); session.findObjectsInit(exportRsaPublicKeyTemplate); Object[] foundPublicKeys = session.findObjects(1); session.findObjectsFinal(); if (foundPublicKeys.length != 1) { output_.println("Error: Cannot find the public key under the given ID!"); } else { output_.println("Found public key!"); output_ .println("_______________________________________________________________________________"); output_.println(foundPublicKeys[0]); output_ .println("_______________________________________________________________________________"); } output_ .println("################################################################################"); session.closeSession(); pkcs11Module.finalize(null); } public static void printUsage() { output_ .println("Usage: GenerateKeyPair <PKCS#11 module> <X.509 encoded public key file> [<slot-index>] [<pin>]"); output_.println(" e.g.: GenerateKeyPair pk2priv.dll publicKey.xpk"); output_.println("The given DLL must be in the search path of the system."); } }
43.731013
115
0.709241
ac8831cfa5bd27549b0ce24f2c5696c606e95cff
1,267
package com.frre.practica.tsp.programacioni.arreglos.busqueda; import java.util.Arrays; /** * Created by justo on 12/05/16. */ public final class Main { private Main() throws InstantiationException { throw new InstantiationException("This class is not created for instantiation"); } public static void main(String[] args){ int[] arreglo = {7,51,1,12,34,1,23,45,67}; String[] nombres = {"Jose","Luis","Zapata","Hector"}; //busqueda lineal for (int i = 0; i < arreglo.length; i++) { if (arreglo[i] == 1){ System.out.println("Encontrado en pos "+i); } } //lineal con centinela int i = 0; while (i < arreglo.length && arreglo[i] != 1){ i++; } if(i < arreglo.length){ System.out.println(arreglo[i]+" encontrado en la pos "+i); } //lineal con centinela con for for (i = 0; i < arreglo.length; i++) { if (arreglo[i] == 1){ System.out.println("Encontrado en pos "+i); break; } } Arrays.sort(arreglo); int pos = Arrays.binarySearch(arreglo, 23); System.out.println(pos); } }
25.34
88
0.521705
d0e9e120bf69cd63d5075ec44310373200d320a2
1,414
package com.outbrain.selenium.extjs.components; import com.outbrain.selenium.extjs.core.locators.ComponentLocator; import com.thoughtworks.selenium.Selenium; /** * @author Asaf Levy * @version $Revision: 1.0 */ public class Button extends Component { /** * Constructor for Button. * @param locator ComponentLocator */ public Button(final ComponentLocator locator) { super(locator); } /** * Constructor for Button. * @param selenium Selenium * @param expression String */ public Button(final Selenium selenium, final String expression) { super(selenium, expression); } /** * return true if the component is disabled * @return boolean */ @Override public boolean disabled() { return evalTrue(".disabled"); } /** * Method click. */ public void click() { waitForEvalTrue(".disabled == false"); selenium.click(getXPath()); } /** * Method click and check if is no error after Ajax callback. * @throws InterruptedException */ public void clickAndWaitForAjaxValid() throws InterruptedException { waitForEvalTrue(".disabled == false"); selenium.click(getXPath()); wait(2); waitForFinshAjaxRequst(); waitForDialogFailure(); } /** * Method clickNoWait. */ public void clickNoWait() { selenium.click(getXPath()); } }
22.09375
71
0.636492
8db6c12e9f6ed3b2279485b7efd66d0d28565b0f
697
package bloque; import java.util.ArrayList; import mapa.Mapa; import personaje.Personaje; import posicion.Posicion; import movimiento.Movimiento; public class BloqueMovimiento extends Bloque { private Movimiento movimiento; public BloqueMovimiento(Movimiento movimiento){ this.movimiento = movimiento; } public ArrayList<Posicion> ejecutar(Personaje personaje, Mapa mapa){ ArrayList<Posicion> listaPos = new ArrayList<Posicion>(); listaPos.add(personaje.mover(movimiento, mapa)); return listaPos; } public Bloque obtenerBloqueInvertido(){ return new BloqueMovimiento(movimiento.obtenerMovimientoInvertido()); } }
21.78125
77
0.724534
42f70b5dea1ed8c8f0fcf7c4619a87d11ddd5f24
2,321
package org.ofbiz.content.content; import javax.imageio.ImageIO; import java.awt.*; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; /** * Created by Alex on 2016/7/23. */ public class ImgCompress { private Image img; private int width; private int height; public static void compress(String oldFilePath, String newFilePath) throws Exception { ImgCompress imgCom = new ImgCompress(oldFilePath); imgCom.resizeFix(386, 386, newFilePath, oldFilePath.substring(oldFilePath.lastIndexOf(".") + 1)); } /** * 构造函数 */ public ImgCompress(String fileName) throws IOException { File file = new File(fileName);// 读入文件 img = ImageIO.read(file); // 构造Image对象 width = img.getWidth(null); // 得到源图宽 height = img.getHeight(null); // 得到源图长 } /** * 按照宽度还是高度进行压缩 * @param w int 最大宽度 * @param h int 最大高度 */ public void resizeFix(int w, int h, String newFilePath, String formatName) throws IOException { if (new Double(width) / new Double(height) > new Double(w) / new Double(h)) { resizeByWidth(w, newFilePath, formatName); } else { resizeByHeight(h, newFilePath, formatName); } } /** * 以宽度为基准,等比例放缩图片 * @param w int 新宽度 */ public void resizeByWidth(int w, String newFilePath, String formatName) throws IOException { int h = (int) (height * w / width); resize(w, h, newFilePath, formatName); } /** * 以高度为基准,等比例缩放图片 * @param h int 新高度 */ public void resizeByHeight(int h, String newFilePath, String formatName) throws IOException { int w = (int) (width * h / height); resize(w, h, newFilePath, formatName); } /** * 强制压缩/放大图片到固定的大小 * @param w int 新宽度 * @param h int 新高度 */ public void resize(int w, int h, String newFilePath, String formatName) throws IOException { // SCALE_SMOOTH 的缩略算法 生成缩略图片的平滑度的 优先级比速度高 生成的图片质量比较好 但速度慢 BufferedImage image = new BufferedImage(w, h,BufferedImage.TYPE_INT_RGB ); image.getGraphics().drawImage(img, 0, 0, w, h, null); // 绘制缩小后的图 ImageIO.write(image, /*"GIF"*/ formatName /* format desired */ , new File(newFilePath) /* target */ ); } }
32.236111
110
0.6243
adee7c77fef33090dbbf66e73068290f25cd66c7
2,805
/*************************************************************************** * Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ***************************************************************************/ package com.vmware.bdd.util.collection; import org.testng.annotations.Test; import java.util.List; import static org.testng.Assert.*; import static org.testng.Assert.assertEquals; public class TestSensitiveDataObfuscator { @Test(groups = { "SensitiveDataObfuscatorTest" }) public void testHashSensitiveData() { String value = SensitiveDataObfuscator.hashSensitiveData( CollectionConstants.OPERATION_NAME, CollectionConstants.METHOD_CONFIG_CLUSTER, null); assertEquals(value, CollectionConstants.METHOD_CONFIG_CLUSTER); value = SensitiveDataObfuscator.hashSensitiveData( "password","1234567abc", null); assertEquals(SensitiveDataObfuscator.getSensitiveDataFromFile().size(), 55); assertEquals(value, "4D74CDB3F355C750B8FE2E4C86CC062F41CA1C7373A8CD19D2C7C2D6974C3002"); } @Test(groups = { "SensitiveDataObfuscatorTest" }) public void testGetSensitiveDataFromFile() { List<String> sensitiveDataContent = SensitiveDataObfuscator.getSensitiveDataFromFile(); assertTrue(sensitiveDataContent != null && sensitiveDataContent.size() > 0); assertTrue(sensitiveDataContent.contains("ip")); assertTrue(sensitiveDataContent.contains("dns1")); assertTrue(sensitiveDataContent.contains("dns2")); assertTrue(sensitiveDataContent.contains("gateway")); assertTrue(sensitiveDataContent.contains("username")); assertTrue(sensitiveDataContent.contains("password")); assertTrue(sensitiveDataContent.contains("sslCertificate")); } @Test(groups = { "SensitiveDataObfuscatorTest" }) public void testParseStrToSHA256() { String mask = SensitiveDataObfuscator.parseStrToSHA256("255.255.255.0"); assertEquals(mask, "F9E2C70401F315FEEBFC5B2A2B7493C10578E8E5CC3D7C7354FCF5F34FEC0DB5"); String ip = SensitiveDataObfuscator.parseStrToSHA256("192.168.0.1"); assertEquals(ip, "37D7A80604871E579850A658C7ADD2AE7557D0C6ABCC9B31ECDDC4424207EBA3"); } }
48.362069
101
0.703743
ec5d200169aea4c714d8fa40494061795641a2da
130
/* * Author: Manoj Bharadwaj */ package pcap.reconst.compression; public interface Unzip { public byte[] unzip(); }
13
34
0.646154
9b177d2b693b84dd583149ef703a55c08de1a522
835
package modularmachines.common.blocks.tile; import net.minecraft.network.NetworkManager; import net.minecraft.network.play.server.SPacketUpdateTileEntity; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.ITickable; public abstract class TileEntityBase extends TileEntity implements ITickable { @Override public void update() { if (world.isRemote) { updateClient(); } else { updateServer(); } } public abstract void updateClient(); public abstract void updateServer(); @Override public SPacketUpdateTileEntity getUpdatePacket() { return new SPacketUpdateTileEntity(pos, 0, getUpdateTag()); } @Override public void onDataPacket(NetworkManager net, SPacketUpdateTileEntity packet) { world.markBlockRangeForRenderUpdate(pos, pos); handleUpdateTag(packet.getNbtCompound()); } }
24.558824
79
0.779641
cbc782432f51d5d96ea05791bbd00ac3b0c8e5e6
709
package org.robobinding.widget.timepicker; import org.robobinding.viewbinding.BindingAttributeMappings; import org.robobinding.viewbinding.ViewBinding; import android.widget.TimePicker; /** * * @since 1.0 * @version $Revision: 1.0 $ * @author Joachim Hill-Grannec */ public class TimePickerBinding implements ViewBinding<TimePicker> { @Override public void mapBindingAttributes(BindingAttributeMappings<TimePicker> mappings) { mappings.mapTwoWayProperty(TwoWayCurrentMinuteAttribute.class, "currentMinute"); mappings.mapTwoWayProperty(TwoWayCurrentHourAttribute.class, "currentHour"); mappings.mapEvent(OnTimeChangedAttribute.class, "onTimeChanged"); } }
29.541667
88
0.767278
1b3d7a4a843ffd7ac0112f2ad2a350d268e8c54d
1,104
import java.util.Locale; import java.util.Scanner; public class Exercicio06 { public static void main(String[] args){ System.out.println("digite tres valores A, B e C, que irá mostrar: |A- a área do triângulo retângulo que tem A por base e C por altura |B- a área do círculo de raio C |C- a área do trapézio que tem A e B por bases e C por altura|D- a área do quadrado que tem lado B |E- a área do retângulo que tem lados A e B"); Locale.setDefault(Locale.US); Scanner sc = new Scanner(System.in); double A, B, C, At, Ac, Atrap, Aq, Ar, pi; pi = 3.14159; A = sc.nextFloat(); B = sc.nextFloat(); C = sc.nextFloat(); At = (A * C) / 2 ; Ac = pi * (C * C); Atrap = ((A + B) * C) / 2; Aq = B * B; Ar = A * B; System.out.printf("TRIÂNGULO = %.3f%n", At); System.out.printf("CÍRCULO = %.3f%n", Ac); System.out.printf("TRAPÉZIO = %.3f%n", Atrap); System.out.printf("QUADRADO = %.3f%n", Aq); System.out.printf("RETÂNGULO = %.3f%", Ar); sc.close(); } }
42.461538
321
0.557065
c44eb7f696ccd2d32c36a4a933cdcb448d3d5f9d
1,175
/* * Copyright 2000-2021 Vaadin Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.vaadin.flow.server.startup; import com.vaadin.flow.server.VaadinContext; /** * A factory for {@link ApplicationConfiguration}. * * @author Vaadin Ltd * @since * */ public interface ApplicationConfigurationFactory { /** * Creates a new instance of {@link ApplicationConfiguration} for the given * {@code context}. * * @param context * the context to create a configuration for * @return the configuration created based on the {@code context} */ ApplicationConfiguration create(VaadinContext context); }
30.128205
80
0.711489
d6a90c68f5ea7ed935296b21c87cfda3ae574fd4
2,245
/* * Copyright (c) 2010-2016 Osman Shoukry * * 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.openpojo.log; import com.openpojo.log.common.AbstractLoggerBase; import com.openpojo.log.impl.Log4JLogger; import com.openpojo.log.impl.SLF4JLogger; import com.openpojo.utils.log.MockAppender; import com.openpojo.utils.log.MockAppenderLog4J; import com.openpojo.validation.affirm.Affirm; import org.junit.Before; import org.junit.Test; /** * @author oshoukry */ public class Log4JLoggerTest extends AbstractLoggerBase { private static final String LOGCATEGORY = Log4JLoggerTest.class.getName(); private static final int LOGLEVELS = 6; // TRACE, DEBUG, INFO, WARN, ERROR, FATAL @Override public String getCategory() { return LOGCATEGORY; } @Override public int getLogLevelsCount() { return LOGLEVELS; } @Override public Class<? extends MockAppender> getMockAppender() { return MockAppenderLog4J.class; } @Before public final void setUp() { LoggerFactory.setActiveLogger(Log4JLogger.class); } @Test public void shouldLogInVariousLevels() { testWithLogLevel(LogLevel.TRACE); testWithLogLevel(LogLevel.DEBUG); testWithLogLevel(LogLevel.WARN); testWithLogLevel(LogLevel.INFO); testWithLogLevel(LogLevel.ERROR); testWithLogLevel(LogLevel.FATAL); } @Test public void testToString() { Logger log = LoggerFactory.getLogger(getCategory()); Affirm.affirmTrue(String.format("toString() failed on [%s]!", SLF4JLogger.class.getName()), log.toString().startsWith("com.openpojo.log.impl.Log4JLogger [@") && log.toString().contains(": logger=org.apache.log4j.Logger@") && log.toString().endsWith("]")); } }
29.539474
95
0.726503
8d43696947a0ad7b7095ff5fada839f2fa047d18
5,891
/* * 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.felix.configurator.impl.model; import java.io.IOException; import java.io.Serializable; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; /** * The config list holds all configurations for a single PID */ public class ConfigList implements Serializable, Iterable<Config> { private static final long serialVersionUID = 1L; /** Serialization version. */ private static final int VERSION = 1; private List<Config> configurations = new ArrayList<>(); /** The change count. */ private volatile long changeCount = -1; /** Flag to indicate whether this list needs to be processed. */ private volatile boolean hasChanges; /** Last installed configuration. */ private volatile Config lastInstalled; /** * Serialize the object * - write version id * - serialize fields * @param out Object output stream * @throws IOException */ private void writeObject(final java.io.ObjectOutputStream out) throws IOException { out.writeInt(VERSION); out.writeObject(configurations); out.writeObject(lastInstalled); out.writeLong(changeCount); out.writeBoolean(hasChanges); } /** * Deserialize the object * - read version id * - deserialize fields */ @SuppressWarnings("unchecked") private void readObject(final java.io.ObjectInputStream in) throws IOException, ClassNotFoundException { final int version = in.readInt(); if ( version < 1 || version > VERSION ) { throw new ClassNotFoundException(this.getClass().getName()); } this.configurations = (List<Config>) in.readObject(); lastInstalled = (Config) in.readObject(); this.changeCount = in.readLong(); this.hasChanges = in.readBoolean(); } /** * Does this list need to be processed * @return {@code true} if it needs processing. */ public boolean hasChanges() { return hasChanges; } /** * Set the has changes flag. * @param value New value. */ public void setHasChanges(final boolean value) { this.hasChanges = hasChanges; } /** * Add a configuration to the list. * @param c The configuration. */ public void add(final Config c) { this.hasChanges = true; this.configurations.add(c); Collections.sort(this.configurations); } /** * Add all configurations from another list * @param configs The config list */ public void addAll(final ConfigList configs) { for(final Config cfg : configs) { // search if we already have this configuration for(final Config current : this.configurations) { if ( current.getBundleId() == cfg.getBundleId() && current.getProperties().equals(cfg.getProperties()) ) { if ( current.getState() == ConfigState.UNINSTALL ) { if ( cfg.getPolicy()!=ConfigPolicy.FORCE) cfg.setState(ConfigState.INSTALLED); current.setState(ConfigState.UNINSTALLED); } break; } } this.hasChanges = true; this.configurations.add(cfg); } Collections.sort(this.configurations); } /** * Get the size of the list of configurations * @return */ public int size() { return this.configurations.size(); } @Override public Iterator<Config> iterator() { return this.configurations.iterator(); } /** * Get the change count. * @return The change count */ public long getChangeCount() { return this.changeCount; } /** * Set the change count * @param value The new change count */ public void setChangeCount(final long value) { this.changeCount = value; } public Config getLastInstalled() { return lastInstalled; } public void setLastInstalled(Config lastInstalled) { this.lastInstalled = lastInstalled; } /** * Mark configurations for a bundle uninstall * @param bundleId The bundle id of the uninstalled bundle */ public void uninstall(final long bundleId) { for(final Config cfg : this.configurations) { if ( cfg.getBundleId() == bundleId ) { this.hasChanges = true; if ( cfg.getState() == ConfigState.INSTALLED ) { cfg.setState(ConfigState.UNINSTALL); } else { cfg.setState(ConfigState.UNINSTALLED); } } } } @Override public String toString() { return "ConfigList [configurations=" + configurations + ", changeCount=" + changeCount + ", hasChanges=" + hasChanges + ", lastInstalled=" + lastInstalled + "]"; } }
29.903553
112
0.61195
3d8cd867c3f7d5e3027ff5be7eb4000105fb79b9
13,835
package com.umiwi.ui.fragment; import android.annotation.SuppressLint; import android.app.Service; import android.content.Intent; import android.content.res.AssetFileDescriptor; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.media.SoundPool; import android.os.Bundle; import android.os.Vibrator; import android.support.v7.widget.Toolbar; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.animation.Animation; import android.view.animation.RotateAnimation; import android.widget.GridView; import android.widget.PopupWindow.OnDismissListener; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import com.umeng.analytics.MobclickAgent; import com.umiwi.ui.R; import com.umiwi.ui.activity.UmiwiContainerActivity; import com.umiwi.ui.adapter.UmiwiShakeCouponGridViewAdapter; import com.umiwi.ui.beans.UmiwiShakeBean; import com.umiwi.ui.beans.UmiwiShakeCouponBean; import com.umiwi.ui.dialog.ShakeResultDialog; import com.umiwi.ui.dialog.ShareDialog; import com.umiwi.ui.main.UmiwiAPI; import com.umiwi.ui.main.UmiwiApplication; import com.umiwi.ui.managers.NoticeManager; import com.umiwi.ui.managers.YoumiRoomUserManager; import com.umiwi.ui.util.CommonHelper; import com.umiwi.ui.util.LoginUtil; import java.io.IOException; import java.util.ArrayList; import java.util.List; import cn.youmi.framework.fragment.BaseFragment; import cn.youmi.framework.http.AbstractRequest; import cn.youmi.framework.http.AbstractRequest.Listener; import cn.youmi.framework.http.GetRequest; import cn.youmi.framework.http.HttpDispatcher; import cn.youmi.framework.http.parsers.GsonParser; import cn.youmi.framework.util.NetworkManager; import cn.youmi.framework.util.ToastU; /** * @author tjie00 * @version 2014年9月11日 下午2:17:59 TODO */ public class ShakeFragment extends BaseFragment { private GridView gvShakeCoupon; private TextView tvMineCoupons; private TextView tvShakeAD; private SensorManager mSensorManager; private Vibrator vibrator; private SoundPool soundPool; private int soundID = -1; private UmiwiSensorEventListener uSensorEventListener; private UmiwiShakeCouponGridViewAdapter couponAdapter; private Animation shakeAnimation; private ShakeResultDialog resultDialog; private boolean isLogined = false; private boolean isShakeable = false; public boolean isShaking = true; private ProgressBar loading; private CouponBeanListener couponBeanListener; private GetRequest<UmiwiShakeCouponBean> couponRequest; private ShakeBeanListener shakeBeanListener; private GetRequest<UmiwiShakeBean> shakeRequest; @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); inflater.inflate(R.menu.toolbar_share, menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.share: ShareDialog.getInstance().showDialog(getActivity(), getString(R.string.share_app_title), "@优米网 手机客户端的摇一摇功能棒棒哒,免费看付费课程。 http://m.youmi.cn/m.shtml", getString(R.string.share_app_weburl), getString(R.string.share_app_image)); break; default: break; } return super.onOptionsItemSelected(item); } @Override public void onCreate(Bundle savedInstanceState) { if (savedInstanceState != null) { umiwiShakeBean = (UmiwiShakeBean) savedInstanceState .getSerializable("umiwiShakeBean"); } super.onCreate(savedInstanceState); this.setHasOptionsMenu(true); } @SuppressLint("InflateParams") @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_shake, null); mActionBarToolbar = (Toolbar) view.findViewById(R.id.toolbar_actionbar); setSupportActionBarAndToolbarTitle(mActionBarToolbar, "摇一摇"); mSensorManager = (SensorManager) getActivity().getSystemService(Service.SENSOR_SERVICE); isLogined = checkLoginState(); if (!isLogined) { ToastU.showShort(getActivity(), "登录之后才可以摇优惠哦!");// 开线程 LoginUtil.getInstance().showLoginView(getActivity()); } isShakeable = isShakeAvailble(); if (isShakeable) { getCouponsList(); } else { ToastU.showShort(getActivity(),"么么哒,网络出错了,过会再试试!");// 开线程 } initView(view); return view; } @Override public void onPause() { super.onPause(); if (uSensorEventListener != null) { mSensorManager.unregisterListener(uSensorEventListener); uSensorEventListener = null; } isShaking = true; MobclickAgent.onPageEnd(fragmentName); } @Override public void onResume() { super.onResume(); activateSendor(); MobclickAgent.onPageStart(fragmentName); } // 初始化优惠列表出现问题 public void getCouponListError() { Toast.makeText(getActivity(), "网络有问题,请稍后重试.", Toast.LENGTH_SHORT).show(); isShaking = true; } // 获取摇奖结果异常 // 要改为默认没摇到 public void getCouponResultError() { Toast.makeText(getActivity(), "获取失败", Toast.LENGTH_SHORT).show(); isShaking = false; } public void initCouponAdapter(ArrayList<String> couponURLs) { if (couponAdapter == null) { couponAdapter = new UmiwiShakeCouponGridViewAdapter(getActivity(), couponURLs); gvShakeCoupon.setAdapter(couponAdapter); } else { couponAdapter.setData(couponURLs); couponAdapter.notifyDataSetChanged(); } isShaking = false; } public void upDateShakeAD(String shakeOtherAD) { tvShakeAD.setText(shakeOtherAD); } // check is the user login or not private boolean checkLoginState() { return YoumiRoomUserManager.getInstance().isLogin(); } private boolean getNetState() { return NetworkManager.getInstance().checkNet(UmiwiApplication.getContext()); } private boolean isShakeAvailble() { return checkLoginState() && getNetState(); } // find the ui public void initView(View view) { gvShakeCoupon = (GridView) view.findViewById(R.id.gv_shake_coupon); gvShakeCoupon.setSelector(new ColorDrawable(Color.TRANSPARENT)); tvMineCoupons = (TextView) view.findViewById(R.id.tv_mine_coupons); tvMineCoupons.setClickable(true); tvMineCoupons.setOnClickListener(mineCouponClickListener); tvShakeAD = (TextView) view.findViewById(R.id.tv_shake_couponad); uSensorEventListener = new UmiwiSensorEventListener(); // 震动 vibrator = (Vibrator) getActivity().getSystemService(Service.VIBRATOR_SERVICE); // soundPool = new SoundPool(1, AudioManager.STREAM_MUSIC, 0); soundPool = new SoundPool(1, 0, 0); loading = (ProgressBar) view.findViewById(R.id.loading); loadShakeAudio(); } private void loadShakeAudio() { AssetFileDescriptor fileDescriptor = null; try { fileDescriptor = UmiwiApplication.getContext().getAssets().openFd("shake_reward.wav"); soundID = soundPool.load(fileDescriptor, 1); } catch (IOException e) { e.printStackTrace(); } } /** * request for the coupons' content, get the rest of the shake times; */ private void getCouponsList() { if (couponBeanListener == null) couponBeanListener = new CouponBeanListener(); if (couponRequest == null) couponRequest = new GetRequest<UmiwiShakeCouponBean>(UmiwiAPI.COUPON_LIST_URL, GsonParser.class, UmiwiShakeCouponBean.class, couponBeanListener); HttpDispatcher.getInstance().go(couponRequest); } private void activateSendor() { if (isShakeAvailble()) { isShaking = false; if (uSensorEventListener == null) { uSensorEventListener = new UmiwiSensorEventListener(); } List<Sensor> sensor = mSensorManager.getSensorList(Sensor.TYPE_ALL); for (Sensor sen : sensor) { switch (sen.getType()) { case Sensor.TYPE_ACCELEROMETER: mSensorManager.registerListener(uSensorEventListener, mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL); break; case Sensor.TYPE_GYROSCOPE: mSensorManager.registerListener(uSensorEventListener, mSensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE), SensorManager.SENSOR_DELAY_NORMAL); break; } } } } private void onSensorEvenChange(float rocking, float[] values) { vibrator.vibrate(500); if (-1 != soundID) { soundPool.play(soundID, 0.4f, 0.4f, 0, 0, 1); } rocking = values[0]; if (!isShaking) { if (isShakeAvailble()) { getCouponResult(); getCouponsList(); } } if (uSensorEventListener != null) { mSensorManager.unregisterListener(uSensorEventListener); } } private class UmiwiSensorEventListener implements SensorEventListener { @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { } @Override public void onSensorChanged(SensorEvent event) { int sensorType = event.sensor.getType(); if (sensorType != Sensor.TYPE_ACCELEROMETER && sensorType != Sensor.TYPE_GYROSCOPE) { return; } float[] values = event.values; float rocking = 0; if (sensorType == Sensor.TYPE_ACCELEROMETER) { if (Math.abs(values[0]) > 13.0 || Math.abs(values[1]) > 13.0 || Math.abs(values[2]) > 13.0) { onSensorEvenChange(rocking, values); } else { rocking = 0; } } else { if (Math.abs(values[0]) > 10.0 || Math.abs(values[1]) > 10.0 || Math.abs(values[2]) > 10.0) { onSensorEvenChange(rocking, values); } else { rocking = 0; } } shakeAnimation = new RotateAnimation(values[0], rocking, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0f); shakeAnimation.setDuration(400); if (gvShakeCoupon != null) { int size = gvShakeCoupon.getChildCount(); for (int i = 0; i < size; i++) { gvShakeCoupon.getChildAt(i).startAnimation(shakeAnimation); } } } } public void getCouponResult() { if (shakeBeanListener == null) shakeBeanListener = new ShakeBeanListener(); if (shakeRequest == null) shakeRequest = new GetRequest<UmiwiShakeBean>(UmiwiAPI.COUPON_CONTENT_URL + "?" + CommonHelper.getChannelModelViesion(), GsonParser.class, UmiwiShakeBean.class, shakeBeanListener); HttpDispatcher.getInstance().go(shakeRequest); } private UmiwiShakeBean umiwiShakeBean; @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putSerializable("umiwiShakeBean", umiwiShakeBean); } // show the coupon content in pop up window public void showCouponResult(final UmiwiShakeBean bean) { if (resultDialog == null || !resultDialog.isVisible()) { resultDialog = new ShakeResultDialog(); } resultDialog.setData(bean); resultDialog.shakeFragment = this; if (!resultDialog.isVisible() && null != getActivity()) { try { resultDialog.show(this.getActivity().getSupportFragmentManager(), ShakeResultDialog.TAG); } catch (Exception e) { e.printStackTrace(); } } resultDialog.dismissListener = new OnDismissListener() { @Override public void onDismiss() { if (resultDialog != null) { resultDialog = null; } activateSendor(); } }; } @Override public void onStop() { super.onStop(); if (uSensorEventListener != null) { mSensorManager.unregisterListener(uSensorEventListener); uSensorEventListener = null; } } class CouponBeanListener implements Listener<UmiwiShakeCouponBean> { @Override public void onResult(AbstractRequest<UmiwiShakeCouponBean> request, UmiwiShakeCouponBean bean) { loading.setVisibility(View.GONE); if (bean == null) { return; } if (!"nologin".equalsIgnoreCase(bean.getStatus())) { String shakeOtherAD = bean.getLotteryuser(); if (!TextUtils.isEmpty(shakeOtherAD)) { tvShakeAD.setText(shakeOtherAD); } else { tvShakeAD.setText(""); } if (couponAdapter == null) { ArrayList<String> couponURLs = bean.getRecord(); couponAdapter = new UmiwiShakeCouponGridViewAdapter(getActivity(), couponURLs); gvShakeCoupon.setAdapter(couponAdapter); } else { couponAdapter.notifyDataSetChanged(); } isShaking = false; } else { ToastU.showShort(getActivity(),"登录之后才可以摇优惠哦!"); LoginUtil.getInstance().showLoginView(getActivity()); } if (YoumiRoomUserManager.getInstance().isLogin()) NoticeManager.getInstance().loadNotice(); } @Override public void onError(AbstractRequest<UmiwiShakeCouponBean> requet, int statusCode, String body) { loading.setVisibility(View.GONE); ToastU.showShort(getActivity(),"么么哒,网络出错了,过会再试试!"); isShaking = true; } } class ShakeBeanListener implements Listener<UmiwiShakeBean> { @Override public void onResult(AbstractRequest<UmiwiShakeBean> request, UmiwiShakeBean bean) { if (bean != null && !"nologin".equalsIgnoreCase(bean.getStatus())) { umiwiShakeBean = bean; showCouponResult(umiwiShakeBean); } else { ToastU.showShort(getActivity(),"登录之后才可以摇优惠哦!"); LoginUtil.getInstance().showLoginView(getActivity()); } } @Override public void onError(AbstractRequest<UmiwiShakeBean> requet, int statusCode, String body) { ToastU.showShort(getActivity(),"么么哒,网络出错了,过会再试试!"); isShaking = false; } } private View.OnClickListener mineCouponClickListener = new View.OnClickListener() { long lastCommit = 0; @Override public void onClick(View v) { if (System.currentTimeMillis() - lastCommit < 1000) { return; } lastCommit = System.currentTimeMillis(); Intent couponIntent = new Intent(getActivity(), UmiwiContainerActivity.class); couponIntent.putExtra(UmiwiContainerActivity.KEY_FRAGMENT_CLASS, ShakeCoupondFragment.class); getActivity().startActivity(couponIntent); } }; }
28.006073
183
0.744272
011cfe5b5c862361c26fbfaeb4f5213e9b0a45d8
434
package pl.lotko.datetime.holidays.fixed; import lombok.Value; import pl.lotko.datetime.holidays.Holiday; import java.time.LocalDate; import java.time.Month; @Value public class FixedHoliday implements Holiday { private final int dayOfMonth; private final Month month; @Override public boolean isOn(LocalDate date) { return date.getMonth() == this.month && date.getDayOfMonth() == this.dayOfMonth; } }
22.842105
88
0.732719
7cd71ee926ad39568a2c0f2c4c3d25698035743e
282
package quoter; public class ProfilingController implements ProfilingControllerMBean { private boolean enable = true; public boolean isEnable() { return enable; } @Override public void setEnable(boolean enable) { this.enable = enable; } }
18.8
70
0.673759
3dbb27305c2ef8779017650b6226128793124e3f
1,575
package net.minecraft.world; import javax.annotation.Nullable; import net.minecraft.block.BlockState; import net.minecraft.entity.Entity; import net.minecraft.util.math.BlockPos; public interface IWorldWriter { boolean setBlockState(BlockPos pos, BlockState state, int flags, int recursionLeft); /** * Sets a block state into this world.Flags are as follows: * 1 will cause a block update. * 2 will send the change to clients. * 4 will prevent the block from being re-rendered. * 8 will force any re-renders to run on the main thread instead * 16 will prevent neighbor reactions (e.g. fences connecting, observers pulsing). * 32 will prevent neighbor reactions from spawning drops. * 64 will signify the block is being moved. * Flags can be OR-ed */ default boolean setBlockState(BlockPos pos, BlockState newState, int flags) { return this.setBlockState(pos, newState, flags, 512); } boolean removeBlock(BlockPos pos, boolean isMoving); /** * Sets a block to air, but also plays the sound and particles and can spawn drops */ default boolean destroyBlock(BlockPos pos, boolean dropBlock) { return this.destroyBlock(pos, dropBlock, (Entity)null); } default boolean destroyBlock(BlockPos pos, boolean dropBlock, @Nullable Entity entity) { return this.destroyBlock(pos, dropBlock, entity, 512); } boolean destroyBlock(BlockPos pos, boolean dropBlock, @Nullable Entity entity, int recursionLeft); default boolean addEntity(Entity entityIn) { return false; } }
35
101
0.725714
7cba7f4a6b4460f84e5e31d233f669a128898964
2,365
package com.ants.modules.system.controller; import com.ants.common.system.query.QueryGenerator; import com.ants.common.system.result.Result; import com.ants.modules.system.entity.SendMailHistory; import com.ants.modules.system.service.SendMailHistoryService; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletRequest; import java.util.Map; /** * TODO 邮件工具-发送记录 * Author Chen * Date 2021/3/5 13:34 */ @Api(tags = "邮件工具-发送记录") @RestController @RequestMapping("/mail/tool") @Slf4j public class MailToolController { @Autowired SendMailHistoryService sendMailHistoryService; @ApiOperation("发送邮件") @PostMapping("/") public Result sendMail(@RequestBody Map<String, Object> map) { boolean b = sendMailHistoryService.sendMail(map); if (b){ log.info("邮件发送成功!"); return Result.ok("发送成功!"); } log.error("邮件发送失败!"); return Result.error("发送失败!"); } @ApiOperation("获取邮件发送记录") @GetMapping("/") public Result<?> get(SendMailHistory sendMailHistory, @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo, @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize, HttpServletRequest req) { QueryWrapper<SendMailHistory> qw = QueryGenerator.initQueryWrapper(sendMailHistory, req.getParameterMap()); qw.orderByDesc("create_time"); Page<SendMailHistory> page = new Page<SendMailHistory>(pageNo, pageSize); IPage<SendMailHistory> pageList = sendMailHistoryService.page(page, qw); return Result.ok(pageList); } @ApiOperation("删除邮件发送记录") @DeleteMapping("/{id}") public Result<?> delete(@PathVariable("id") String id) { boolean b = sendMailHistoryService.removeById(id); if (b){ return Result.ok("删除成功!"); } return Result.error("删除失败!"); } }
34.779412
115
0.677801
15cd928b9551ae98276fd483cf893036d484db13
197
package com.algorithm.pattern.proxy; import java.lang.annotation.*; @Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface AnotherAnnotationActorMethod { }
19.7
48
0.822335
2dd2c14b29b00074c3bbc53f9a48e2797d29154e
2,714
package com.sms.io; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.Random; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import com.sms.io.flv.IKeyFrameDataAnalyzer.KeyFrameMeta; public class CachingFileKeyFrameMetaCache extends FileKeyFrameMetaCache { private Map<String, KeyFrameMeta> inMemoryMetaCache = new HashMap<String, KeyFrameMeta>(); private ReadWriteLock rwLock = new ReentrantReadWriteLock(); private int maxCacheEntry = 500; private Random random = new Random(); private static final class SingletonHolder { private static final CachingFileKeyFrameMetaCache INSTANCE = new CachingFileKeyFrameMetaCache(); } public static CachingFileKeyFrameMetaCache getInstance() { return SingletonHolder.INSTANCE; } private CachingFileKeyFrameMetaCache() { } public void setMaxCacheEntry(int maxCacheEntry) { this.maxCacheEntry = maxCacheEntry; } @Override public KeyFrameMeta loadKeyFrameMeta(File file) { rwLock.readLock().lock(); try { String canonicalPath = file.getCanonicalPath(); if (!inMemoryMetaCache.containsKey(canonicalPath)) { rwLock.readLock().unlock(); rwLock.writeLock().lock(); try { if (inMemoryMetaCache.size() >= maxCacheEntry) { freeCachingMetadata(); } KeyFrameMeta keyFrameMeta = super.loadKeyFrameMeta(file); if (keyFrameMeta != null) { inMemoryMetaCache.put(canonicalPath, keyFrameMeta); } else { return null; } } finally { rwLock.writeLock().unlock(); rwLock.readLock().lock(); } } return inMemoryMetaCache.get(canonicalPath); } catch (IOException e) { return null; } finally { rwLock.readLock().unlock(); } } @Override public void saveKeyFrameMeta(File file, KeyFrameMeta meta) { rwLock.writeLock().lock(); try { String canonicalPath = file.getCanonicalPath(); if (inMemoryMetaCache.containsKey(canonicalPath)) { inMemoryMetaCache.remove(canonicalPath); } } catch (IOException e) { // ignore the exception here, let super class to handle it. } finally { rwLock.writeLock().unlock(); } super.saveKeyFrameMeta(file, meta); } private void freeCachingMetadata() { int cacheSize = inMemoryMetaCache.size(); int randomIndex = random.nextInt(cacheSize); Map.Entry<String, KeyFrameMeta> entryToRemove = null; for (Map.Entry<String, KeyFrameMeta> cacheEntry : inMemoryMetaCache .entrySet()) { if (randomIndex == 0) { entryToRemove = cacheEntry; break; } randomIndex--; } if (entryToRemove != null) { inMemoryMetaCache.remove(entryToRemove.getKey()); } } }
26.871287
98
0.722918
fb156737d7e29a35d4e041a113b6300b2096b78d
9,343
/* * Copyright 2005 JBoss Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.drools.guvnor.server; import com.google.gwt.user.client.rpc.SerializationException; import org.drools.guvnor.client.common.AssetFormats; import org.drools.guvnor.client.rpc.Module; import org.drools.guvnor.client.rpc.PathImpl; import org.drools.guvnor.server.files.FileManagerService; import org.drools.guvnor.server.test.GuvnorIntegrationTest; import org.drools.guvnor.server.util.DroolsHeader; import org.drools.ide.common.client.modeldriven.SuggestionCompletionEngine; import org.drools.repository.AssetItem; import org.drools.repository.ModuleItem; import org.junit.Test; import org.drools.guvnor.client.rpc.Path; import javax.inject.Inject; import java.io.InputStream; import static org.junit.Assert.*; /** * This class will setup the data in a test state, which is good for * screenshots/playing around. If you run this by itself, the database will be * wiped, and left with only this data in it. If it is run as part of the suite, * it will just augment the data. This sets up the data for a fictional company * Billasurf, dealing with surfwear and equipment (for surfing, boarding etc). */ public class PopulateDataIntegrationTest extends GuvnorIntegrationTest { @Inject private FileManagerService fileManagerService; @Inject private SuggestionCompletionEngineServiceImplementation suggestionCompletionEngineService; @Test public void testPopulate() throws Exception { createCategories(); createStates(); createPackages(); createModel(); createSomeRules(); createPackageSnapshots(); ModuleItem pkg = rulesRepository.loadModule("com.billasurf.manufacturing.plant"); Path path = new PathImpl(); path.setUUID(pkg.getUUID()); repositoryPackageService.buildPackage(path, true); } private void createModel() throws Exception { Path path = serviceImplementation.createNewRule("DomainModel", "This is the business object model", null, "com.billasurf.manufacturing.plant", AssetFormats.MODEL); InputStream file = this.getClass().getResourceAsStream("/billasurf.jar"); assertNotNull(file); fileManagerService.attachFileToAsset(path, file, "billasurf.jar"); //TODO: Replace RulesRepository with drools-repository-vfs AssetItem item = rulesRepository.loadAssetByUUID(path.getUUID()); assertNotNull(item.getBinaryContentAsBytes()); assertEquals(item.getBinaryContentAttachmentFileName(), "billasurf.jar"); ModuleItem pkg = rulesRepository.loadModule("com.billasurf.manufacturing.plant"); DroolsHeader.updateDroolsHeader("import com.billasurf.Board\nimport com.billasurf.Person" + "\n\nglobal com.billasurf.Person prs", pkg); pkg.checkin("added imports"); SuggestionCompletionEngine eng = suggestionCompletionEngineService.loadSuggestionCompletionEngine("com.billasurf.manufacturing.plant"); assertNotNull(eng); //The loader could define extra imports assertTrue(eng.getFactTypes().length >= 2); String[] fields = (String[]) eng.getModelFields("Board"); assertTrue(fields.length >= 3); String[] globalVars = eng.getGlobalVariables(); assertEquals(1, globalVars.length); assertEquals("prs", globalVars[0]); assertTrue(eng.getFieldCompletionsForGlobalVariable("prs").length >= 2); fields = (String[]) eng.getModelFields("Person"); assertTrue(fields.length >= 2); } private void createPackageSnapshots() throws SerializationException { repositoryPackageService.createModuleSnapshot("com.billasurf.manufacturing", "TEST", false, "The testing region."); repositoryPackageService.createModuleSnapshot("com.billasurf.manufacturing", "PRODUCTION", false, "The testing region."); repositoryPackageService.createModuleSnapshot("com.billasurf.manufacturing", "PRODUCTION ROLLBACK", false, "The testing region."); } private void createSomeRules() throws SerializationException { Path path = serviceImplementation.createNewRule("Surfboard_Colour_Combination", "allowable combinations for basic boards.", "Manufacturing/Boards", "com.billasurf.manufacturing", AssetFormats.BUSINESS_RULE); repositoryAssetService.changeState(path, "Pending"); path = serviceImplementation.createNewRule("Premium_Colour_Combinations", "This defines XXX.", "Manufacturing/Boards", "com.billasurf.manufacturing", AssetFormats.BUSINESS_RULE); repositoryAssetService.changeState(path, "Approved"); path = serviceImplementation.createNewRule("Fibreglass supplier selection", "This defines XXX.", "Manufacturing/Boards", "com.billasurf.manufacturing", AssetFormats.BUSINESS_RULE); path = serviceImplementation.createNewRule("Recommended wax", "This defines XXX.", "Manufacturing/Boards", "com.billasurf.manufacturing", AssetFormats.BUSINESS_RULE); path = serviceImplementation.createNewRule("SomeDSL", "Ignore me.", "Manufacturing/Boards", "com.billasurf.manufacturing", AssetFormats.DSL); } private void createPackages() throws SerializationException { Path uuid = repositoryPackageService.createModule("com.billasurf.manufacturing", "Rules for manufacturing.", "package"); Module conf = repositoryPackageService.loadModule(uuid); conf.setHeader("import com.billasurf.manuf.materials.*"); repositoryPackageService.saveModule(conf); repositoryPackageService.createModule("com.billasurf.manufacturing.plant", "Rules for manufacturing plants.", "package"); repositoryPackageService.createModule("com.billasurf.finance", "All financial rules.", "package"); repositoryPackageService.createModule("com.billasurf.hrman", "Rules for in house HR application.", "package"); repositoryPackageService.createModule("com.billasurf.sales", "Rules exposed as a service for pricing, and discounting.", "package"); } private void createStates() throws SerializationException { serviceImplementation.createState("Approved"); serviceImplementation.createState("Pending"); } private void createCategories() { repositoryCategoryService.createCategory("/", "HR", ""); repositoryCategoryService.createCategory("/", "Sales", ""); repositoryCategoryService.createCategory("/", "Manufacturing", ""); repositoryCategoryService.createCategory("/", "Finance", ""); repositoryCategoryService.createCategory("HR", "Leave", ""); repositoryCategoryService.createCategory("HR", "Training", ""); repositoryCategoryService.createCategory("Sales", "Promotions", ""); repositoryCategoryService.createCategory("Sales", "Old promotions", ""); repositoryCategoryService.createCategory("Sales", "Boogie boards", ""); repositoryCategoryService.createCategory("Sales", "Surf boards", ""); repositoryCategoryService.createCategory("Sales", "Surf wear", ""); repositoryCategoryService.createCategory("Manufacturing", "Surf wear", ""); repositoryCategoryService.createCategory("Manufacturing", "Boards", ""); repositoryCategoryService.createCategory("Finance", "Employees", ""); repositoryCategoryService.createCategory("Finance", "Payables", ""); repositoryCategoryService.createCategory("Finance", "Receivables", ""); } }
37.979675
143
0.628385
a68b47d050e7019a35edcce8784bc0df5a411a6c
1,360
/* * Copyright (c) 2010-2021 Allette Systems (Australia) * http://www.allette.com.au * * 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.pageseeder.diffx.token; /** * Assign a type of token that can affect processing of the diff. * * @author Christophe Lauret * @version 0.9.0 * @since 0.9.0 */ public enum XMLTokenType { /** * Text only. */ TEXT, /** * An XML attribute. */ ATTRIBUTE, /** * An XML element. */ ELEMENT, /** * The start of an XML element. */ START_ELEMENT, /** * The end of an XML element. */ END_ELEMENT, /** * An XML comment. */ COMMENT, /** * Any other type. */ PROCESSING_INSTRUCTION, /** * Any other type. */ OTHER; @Override public String toString() { return this.name().toLowerCase().replace('_', '-'); } }
18.888889
75
0.638971
3d6551548606a1a949ea3d20ce4f1b8d3c20a619
1,777
package org.andengine.opengl.util; import java.nio.ByteBuffer; import org.andengine.d.i.a; public class BufferUtils { private static final boolean a; private static final boolean b; private static final boolean c; static { boolean z; try { System.loadLibrary("andengine"); z = true; } catch (UnsatisfiedLinkError e) { z = false; } a = z; if (a) { if (a.a(11, 13)) { c = true; } else { c = false; } if (a.a(8)) { b = true; } else { b = false; } } else { c = false; if (a.a(11, 13)) { org.andengine.d.e.a.c("Creating a " + ByteBuffer.class.getSimpleName() + " will actually allocate 4x the memory than requested!"); } b = false; } } public static ByteBuffer a(int i) { return c ? jniAllocateDirect(i) : ByteBuffer.allocateDirect(i); } public static void a(ByteBuffer byteBuffer) { if (c) { jniFreeDirect(byteBuffer); } } public static void a(ByteBuffer byteBuffer, float[] fArr, int i, int i2) { if (b) { jniPut(byteBuffer, fArr, i, i2); } else { for (int i3 = i2; i3 < i2 + i; i3++) { byteBuffer.putFloat(fArr[i3]); } } byteBuffer.position(0); byteBuffer.limit(i << 2); } private static native ByteBuffer jniAllocateDirect(int i); private static native void jniFreeDirect(ByteBuffer byteBuffer); private static native void jniPut(ByteBuffer byteBuffer, float[] fArr, int i, int i2); }
26.132353
146
0.504783
8a3d070812f5e28c1ba9fbcffab2ae7a35dcaa1d
8,244
package com.lupicus.nasty.entity; import java.util.Random; import com.lupicus.nasty.config.MyConfig; import net.minecraft.core.BlockPos; import net.minecraft.nbt.CompoundTag; import net.minecraft.server.level.ServerLevel; import net.minecraft.world.Difficulty; import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResult; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.EntityType; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.Mob; import net.minecraft.world.entity.MobSpawnType; import net.minecraft.world.entity.MobType; import net.minecraft.world.entity.PathfinderMob; import net.minecraft.world.entity.SpawnGroupData; import net.minecraft.world.entity.ai.attributes.AttributeSupplier; import net.minecraft.world.entity.ai.attributes.Attributes; import net.minecraft.world.entity.ai.goal.FloatGoal; import net.minecraft.world.entity.ai.goal.LeapAtTargetGoal; import net.minecraft.world.entity.ai.goal.LookAtPlayerGoal; import net.minecraft.world.entity.ai.goal.MeleeAttackGoal; import net.minecraft.world.entity.ai.goal.RandomLookAroundGoal; import net.minecraft.world.entity.ai.goal.WaterAvoidingRandomStrollGoal; import net.minecraft.world.entity.ai.goal.target.HurtByTargetGoal; import net.minecraft.world.entity.ai.goal.target.NearestAttackableTargetGoal; import net.minecraft.world.entity.ai.goal.target.NonTameRandomTargetGoal; import net.minecraft.world.entity.animal.Animal; import net.minecraft.world.entity.animal.Wolf; import net.minecraft.world.entity.monster.Monster; import net.minecraft.world.entity.player.Player; import net.minecraft.world.level.Level; import net.minecraft.world.level.LevelReader; import net.minecraft.world.level.ServerLevelAccessor; import net.minecraft.world.phys.Vec3; public class NastyWolfEntity extends Wolf // Monster { public NastyWolfEntity(EntityType<? extends Wolf> type, Level worldIn) { super(type, worldIn); } @Override protected void registerGoals() { this.goalSelector.addGoal(1, new FloatGoal(this)); //this.goalSelector.addGoal(2, new SitWhenOrderedToGoal(this)); //this.goalSelector.addGoal(3, new Wolf.WolfAvoidEntityGoal<>(this, Llama.class, 24.0F, 1.5D, 1.5D)); this.goalSelector.addGoal(4, new LeapAtTargetGoal(this, 0.4F)); this.goalSelector.addGoal(5, new AttackGoal(this, 1.0D, true)); //this.goalSelector.addGoal(6, new FollowOwnerGoal(this, 1.0D, 10.0F, 2.0F, false)); //this.goalSelector.addGoal(7, new BreedGoal(this, 1.0D)); this.goalSelector.addGoal(8, new WaterAvoidingRandomStrollGoal(this, 1.0D)); //this.goalSelector.addGoal(9, new BegGoal(this, 8.0F)); this.goalSelector.addGoal(10, new LookAtPlayerGoal(this, Player.class, 8.0F)); this.goalSelector.addGoal(10, new RandomLookAroundGoal(this)); this.targetSelector.addGoal(1, new HurtByTargetGoal(this)); this.targetSelector.addGoal(2, new NearestAttackableTargetGoal<>(this, Player.class, true)); //this.targetSelector.addGoal(1, new OwnerHurtByTargetGoal(this)); //this.targetSelector.addGoal(2, new OwnerHurtTargetGoal(this)); //this.targetSelector.addGoal(3, (new HurtByTargetGoal(this)).setAlertOthers()); //this.targetSelector.addGoal(4, new NearestAttackableTargetGoal<>(this, Player.class, 10, true, false, this::func_233680_b_)); this.targetSelector.addGoal(5, new NonTameRandomTargetGoal<>(this, Animal.class, false, PREY_SELECTOR)); //this.targetSelector.addGoal(6, new NonTameRandomTargetGoal<>(this, Turtle.class, false, Turtle.BABY_ON_LAND_SELECTOR)); //this.targetSelector.addGoal(7, new NearestAttackableTargetGoal<>(this, AbstractSkeleton.class, false)); //this.targetSelector.addGoal(8, new ResetUniversalAngerTargetGoal<>(this, true)); } public static AttributeSupplier.Builder createAttributes() { return Wolf.createAttributes() .add(Attributes.MOVEMENT_SPEED, (double) 0.35F) .add(Attributes.MAX_HEALTH, 20.0D) .add(Attributes.ATTACK_DAMAGE, 4.0D) .add(Attributes.FOLLOW_RANGE, 32.0D); } @Override public MobType getMobType() { return MobType.UNDEAD; } public static boolean checkSpawnRules(EntityType<? extends NastyWolfEntity> type, ServerLevelAccessor worldIn, MobSpawnType reason, BlockPos pos, Random randomIn) { return worldIn.getDifficulty() != Difficulty.PEACEFUL && Monster.isDarkEnoughToSpawn(worldIn, pos, randomIn) && checkMobSpawnRules(type, worldIn, reason, pos, randomIn); } @SuppressWarnings("deprecation") @Override public float getWalkTargetValue(BlockPos pos, LevelReader worldIn) { return 0.5F - worldIn.getBrightness(pos); } @Override public int getMaxSpawnClusterSize() { return 4; } @Override public boolean removeWhenFarAway(double distance) { return true; } @Override protected boolean shouldDespawnInPeaceful() { return true; } @Override public boolean isInterested() { return false; } @Override public boolean isTame() { return false; } @Override public void tame(Player player) { } @Override public boolean canBeLeashed(Player player) { return false; } @Override public boolean canMate(Animal otherAnimal) { return false; } @Override public boolean canBreed() { return false; } @Override public InteractionResult mobInteract(Player player, InteractionHand hand) { return InteractionResult.PASS; } @Override public boolean isAlliedTo(Entity entityIn) { if (entityIn instanceof NastySkeletonEntity) return true; return false; } public static boolean canInfect(Wolf mob) { if (MyConfig.virusMode2 != MyConfig.VMode.OFF && mob.getRandom().nextFloat() < MyConfig.virusChance2) { if (MyConfig.virusMode2 == MyConfig.VMode.WILD) return !mob.isTame(); return !mob.hasCustomName(); } return false; } public static void onInfect(Wolf mob) { ServerLevel world = (ServerLevel) mob.level; Vec3 mobpos = mob.position(); if (mob.isOnGround()) mob.setDeltaMovement(0, 0, 0); NastyWolfEntity newmob = ModEntities.NASTY_WOLF.create(world); if (mob.hasCustomName()) { newmob.setCustomName(mob.getCustomName()); newmob.setCustomNameVisible(mob.isCustomNameVisible()); } newmob.setInvisible(mob.isInvisible()); newmob.setInvulnerable(mob.isInvulnerable()); newmob.moveTo(mobpos.x(), mobpos.y(), mobpos.z(), mob.getYRot(), mob.getXRot()); newmob.finalizeSpawn(world, world.getCurrentDifficultyAt(new BlockPos(mobpos)), MobSpawnType.CONVERSION, (SpawnGroupData) null, (CompoundTag) null); newmob.setAge(mob.getAge()); if (mob instanceof Mob) { Mob from = (Mob) mob; if (from.isPersistenceRequired()) newmob.setPersistenceRequired(); newmob.setNoAi(from.isNoAi()); //newmob.setLastHurtByMob(from.getLastHurtByMob()); newmob.yHeadRot = from.yHeadRot; newmob.yBodyRot = from.yHeadRot; } newmob.setDeltaMovement(mob.getDeltaMovement()); // SoundEvents.ZOMBIE_VILLAGER_CONVERTED world.levelEvent((Player) null, 1027, newmob.blockPosition(), 0); world.addFreshEntity(newmob); mob.discard(); } public static class AttackGoal extends MeleeAttackGoal { private double speed; public AttackGoal(PathfinderMob creature, double speedIn, boolean useLongMemory) { super(creature, speedIn, useLongMemory); speed = speedIn; } @Override protected void checkAndPerformAttack(LivingEntity enemy, double distToEnemySqr) { if (!isTimeToAttack()) return; double d0 = this.getAttackReachSqr(enemy); if (distToEnemySqr <= d0) { resetAttackCooldown(); // reset attackTick this.mob.swing(InteractionHand.MAIN_HAND); this.mob.doHurtTarget(enemy); } else if (d0 < 4.0 && mob.getNavigation().isDone()) { // (in blind spot) move the mob closer so it can attack double x = enemy.getX(); double y = enemy.getY(); double z = enemy.getZ(); x = (x - mob.getX()) * 0.5 + x; y = (y - mob.getY()) * 0.5 + y; z = (z - mob.getZ()) * 0.5 + z; mob.getMoveControl().setWantedPosition(x, y, z, speed); } } } }
32.714286
172
0.729864
a1e722b4a321213894c3486dda85673c834de9cd
294
package com.example; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class BeansConfig { // Java configuration in Spring @Bean ("myDog") public Dog getMyDog() { return new Dog("Fluffy"); } }
16.333333
60
0.748299
1c71539dc49c4a5a1e06ea2f30d1e5382ec98396
919
package ceylon.language; import com.redhat.ceylon.compiler.java.metadata.Annotation; import com.redhat.ceylon.compiler.java.metadata.Annotations; import com.redhat.ceylon.compiler.java.metadata.Ceylon; import com.redhat.ceylon.compiler.java.metadata.TypeInfo; @Ceylon(major = 3) public interface Number { @Annotations(@Annotation("formal")) public boolean getPositive(); @Annotations(@Annotation("formal")) public boolean getNegative(); @Annotations(@Annotation("formal")) public double getFloat(); @Annotations(@Annotation("formal")) public long getInteger(); @Annotations(@Annotation("formal")) public Number getMagnitude(); @Annotations(@Annotation("formal")) public long getSign(); @Annotations(@Annotation("formal")) public Number getFractionalPart(); @Annotations(@Annotation("formal")) public Number getWholePart(); }
26.257143
60
0.708379
9001df314d916b290958b348794db9859ee36ff2
5,842
package me.tatarka.bindingcollectionadapter2; import android.databinding.ViewDataBinding; import android.support.annotation.LayoutRes; import android.util.SparseArray; /** * Provides the necessary information to bind an item in a collection to a view. This includes the * variable id and the layout as well as any extra bindings you may want to provide. * * @param <T> The item type. */ public final class ItemBinding<T> { /** * Use this constant as the variable id to not bind the item in the collection to the layout if * no data is need, like a static footer or loading indicator. */ public static final int VAR_NONE = 0; private static final int VAR_INVALID = -1; private static final int LAYOUT_NONE = 0; /** * Constructs an instance with the given variable id and layout. */ public static <T> ItemBinding<T> of(int variableId, @LayoutRes int layoutRes) { return new ItemBinding<T>(null).set(variableId, layoutRes); } /** * Constructs an instance with the given callback. It will be called for each item in the * collection to set the binding info. * * @see OnItemBind */ public static <T> ItemBinding<T> of(OnItemBind<T> onItemBind) { if (onItemBind == null) { throw new NullPointerException("onItemBind == null"); } return new ItemBinding<>(onItemBind); } private final OnItemBind<T> onItemBind; private int variableId; @LayoutRes private int layoutRes; private SparseArray<Object> extraBindings; private ItemBinding(OnItemBind<T> onItemBind) { this.onItemBind = onItemBind; } /** * Set the variable id and layout. This is normally called in {@link * OnItemBind#onItemBind(ItemBinding, int, Object)}. */ public final ItemBinding<T> set(int variableId, @LayoutRes int layoutRes) { this.variableId = variableId; this.layoutRes = layoutRes; return this; } /** * Set the variable id. This is normally called in {@link OnItemBind#onItemBind(ItemBinding, * int, Object)}. */ public final ItemBinding<T> variableId(int variableId) { this.variableId = variableId; return this; } /** * Set the layout. This is normally called in {@link OnItemBind#onItemBind(ItemBinding, int, * Object)}. */ public final ItemBinding<T> layoutRes(@LayoutRes int layoutRes) { this.layoutRes = layoutRes; return this; } /** * Bind an extra variable to the view with the given variable id. The same instance will be * provided to all views the binding is bound to. */ public final ItemBinding<T> bindExtra(int variableId, Object value) { if (extraBindings == null) { extraBindings = new SparseArray<>(1); } extraBindings.put(variableId, value); return this; } /** * Clear all extra variables. This is normally called in {@link * OnItemBind#onItemBind(ItemBinding, int, Object)}. */ public final ItemBinding<T> clearExtras() { if (extraBindings != null) { extraBindings.clear(); } return this; } /** * Remove an extra variable with the given variable id. This is normally called in {@link * OnItemBind#onItemBind(ItemBinding, int, Object)}. */ public ItemBinding<T> removeExtra(int variableId) { if (extraBindings != null) { extraBindings.remove(variableId); } return this; } /** * Returns the current variable id of this binding. */ public final int variableId() { return variableId; } /** * Returns the current layout fo this binding. */ @LayoutRes public final int layoutRes() { return layoutRes; } /** * Returns the current extra binding for the given variable id or null if one isn't present. */ public final Object extraBinding(int variableId) { if (extraBindings == null) { return null; } return extraBindings.get(variableId); } /** * Updates the state of the binding for the given item and position. This is called internally * by the binding collection adapters. */ public void onItemBind(int position, T item) { if (onItemBind != null) { variableId = VAR_INVALID; layoutRes = LAYOUT_NONE; onItemBind.onItemBind(this, position, item); if (variableId == VAR_INVALID) { throw new IllegalStateException("variableId not set in onItemBind()"); } if (layoutRes == LAYOUT_NONE) { throw new IllegalStateException("layoutRes not set in onItemBind()"); } } } /** * Binds the item and extra bindings to the given binding. Returns true if anything was bound * and false otherwise. This is called internally by the binding collection adapters. * * @throws IllegalStateException if the variable id isn't present in the layout. */ public boolean bind(ViewDataBinding binding, T item) { if (variableId == VAR_NONE) { return false; } boolean result = binding.setVariable(variableId, item); if (!result) { Utils.throwMissingVariable(binding, variableId, layoutRes); } if (extraBindings != null) { for (int i = 0, size = extraBindings.size(); i < size; i++) { int variableId = extraBindings.keyAt(i); Object value = extraBindings.valueAt(i); if (variableId != VAR_NONE) { binding.setVariable(variableId, value); } } } return true; } }
31.75
99
0.615885
8ef590628149aa150949457f6979c1cbdee37d8f
1,271
public class Conditions { public static void main(String[] args) { boolean isTrue = true; if(isTrue) { System.out.println("True is true"); } if(10 > 5) { System.out.println("10 is greater than 5"); } // single line comment /* multiline comment */ if(returnTrue()) { System.out.println("returnTrue is true"); } if(!returnTrue()) { System.out.println("NOT returnTrue is false"); } else { System.out.println("NOT returnTrue was " + "not true"); } if(5 > 10) { System.out.println("This will not print"); } else if(10 > 5) { System.out.println("This will print"); } else { System.out.println("This will not print"); } if(true) { if(10 > 5) { System.out.println("true is true and " + "ten is greater than 5"); } else { System.out.println("this won't print"); } } int myNumber = 2; switch(myNumber) { case 1: System.out.println("10 is 1"); break; case 5: System.out.println("10 is 5"); break; case 10: System.out.println("10 is 10"); break; default: System.out.println("myNumber was not " + "1, 5, or 10"); } if("hi".equals("hi")) { System.out.println("This is true"); } } public static boolean returnTrue() { return true; } }
19.553846
49
0.5893
007028804663c0e95708c8245ec1d71db70685d0
12,259
/******************************************************************************* * Copyright (c) 2000, 2008 IBM Corporation and others. * 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: * IBM Corporation - initial API and implementation * Oakland Software (Francis Upton) <[email protected]> - * Fix for Bug 63149 [ltk] allow changes to be executed after the 'main' change during an undo [refactoring] *******************************************************************************/ package org.eclipse.ltk.core.refactoring.participants; import org.eclipse.core.runtime.Assert; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.OperationCanceledException; import org.eclipse.core.runtime.PlatformObject; import org.eclipse.ltk.core.refactoring.Change; import org.eclipse.ltk.core.refactoring.RefactoringStatus; import org.eclipse.ltk.core.refactoring.TextChange; import org.eclipse.ltk.internal.core.refactoring.ParticipantDescriptor; /** * A refactoring participant can participate in the condition checking and * change creation of a {@link RefactoringProcessor}. * <p> * If the severity of the condition checking result is {@link RefactoringStatus#FATAL} * then the whole refactoring will not be carried out. * </p> * <p> * The changes created by a participant <em>MUST</em> not conflict with any changes * provided by other participants or the refactoring itself. To ensure this, a participant * is only allowed to manipulate resources belonging to its domain. As of 3.1 this got * relaxed for textual resources. A participant can now change a textual resource already * manipulated by the processor as long as both are manipulating different regions in the * file (see {@link #createChange(IProgressMonitor)} and {@link #getTextChange(Object)}). * For example a rename type participant updating launch configuration is only allowed to * update launch configurations or shared textual resources. If a change conflicts with * another change during execution then the participant who created the change will be * disabled for the rest of the eclipse session. * </p> * <p> * A refactoring participant can not assume that all resources are saved before any * methods are called on it. Therefore a participant must be able to deal with unsaved * resources. * </p> * <p> * A refactoring participant can implement {@link ISharableParticipant} in order to be * shared for multiple elements to be refactored by the same processor. * </p> * <p> * This class should be subclassed by clients wishing to provide special refactoring * participants extension points. * </p> * <p> * Since 3.4, a refactoring participant can also override {@link #createPreChange(IProgressMonitor)} * to add changes that will be executed <em>before</em> the main refactoring changes * are executed. * </p> * * @see RefactoringProcessor * @see ISharableParticipant * * @since 3.0 */ public abstract class RefactoringParticipant extends PlatformObject { private RefactoringProcessor fProcessor; private ParticipantDescriptor fDescriptor; /** * Returns the processor that is associated with this participant. * * @return the processor that is associated with this participant */ public RefactoringProcessor getProcessor() { return fProcessor; } /** * Initializes the participant. This method is called by the framework when a * participant gets instantiated. * <p> * This method isn't intended to be extended or reimplemented by clients. * </p> * @param processor the processor this participant is associated with * @param element the element to be refactored * @param arguments the refactoring arguments * * @return <code>true</code> if the participant could be initialized; * otherwise <code>false</code> is returned. If <code>false</code> is * returned then the participant will not be added to the refactoring. * * @see #initialize(Object) */ public boolean initialize(RefactoringProcessor processor, Object element, RefactoringArguments arguments) { Assert.isNotNull(processor); Assert.isNotNull(arguments); fProcessor = processor; initialize(arguments); return initialize(element); } /** * Initializes the participant with the element to be refactored. * If this method returns <code>false</code> then the framework * will consider the participant as not being initialized and the * participant will be dropped by the framework. * * @param element the element to be refactored * * @return <code>true</code> if the participant could be initialized; * otherwise <code>false</code> is returned. */ protected abstract boolean initialize(Object element); /** * Initializes the participant with the refactoring arguments * * @param arguments the refactoring arguments */ protected abstract void initialize(RefactoringArguments arguments); /** * Returns a human readable name of this participant. * * @return a human readable name */ public abstract String getName(); /** * Checks the conditions of the refactoring participant. * <p> * The refactoring is considered as not being executable if the returned status * has the severity of <code>RefactoringStatus#FATAL</code>. Note that this blocks * the whole refactoring operation! * </p> * <p> * Clients should use the passed {@link CheckConditionsContext} to validate the changes * they generate. If the generated changes include workspace resource modifications, * clients should call ... * * <pre> (ResourceChangeChecker) context.getChecker(ResourceChangeChecker.class); * IResourceChangeDescriptionFactory deltaFactory= checker.getDeltaFactory();</pre> * * ... and use the delta factory to describe all resource modifications in advance. * </p> * <p> * This method can be called more than once. * </p> * * @param pm a progress monitor to report progress * @param context a condition checking context to collect shared condition checks * * @return a refactoring status. If the status is <code>RefactoringStatus#FATAL</code> * the refactoring is considered as not being executable. * * @throws OperationCanceledException if the condition checking got canceled * * @see org.eclipse.ltk.core.refactoring.Refactoring#checkInitialConditions(IProgressMonitor) * @see RefactoringStatus */ public abstract RefactoringStatus checkConditions(IProgressMonitor pm, CheckConditionsContext context) throws OperationCanceledException; /** * Creates a {@link Change} object that contains the workspace modifications * of this participant to be executed <em>before</em> the * changes from the refactoring are executed. Note that this implies that the * undo change of the returned Change object will be executed <em>after</em> * the undo changes from the refactoring have been executed. * <p> * The changes provided * by a participant <em>must</em> not conflict with any change provided by other * participants or by the refactoring itself. * <p> * If the change conflicts with any change provided by other participants or * by the refactoring itself, then change execution will fail and the * participant will be disabled for the rest of the eclipse session. * </p> * <p> * If an exception occurs while creating the change, the refactoring can not * be carried out, and the participant will be disabled for the rest of the * eclipse session. * </p> * <p> * A participant can manipulate text resource already manipulated by * the processor as long as the textual manipulations don't conflict (e.g. * the participant manipulates a different region of the text resource). * The method must not return those changes in its change tree since the change * is already part of another change tree. If the participant only manipulates * shared changes then it can return <code>null</code> to indicate that it didn't * create own changes. A shared text change can be accessed via the method * {@link #getTextChange(Object)}. * </p> * <p> * The default implementation returns <code>null</code>. Subclasses can extend or override. * </p> * <p> * Note that most refactorings will implement {@link #createChange(IProgressMonitor)} * rather than this method. * </p> * * @param pm a progress monitor to report progress * * @return the change representing the workspace modifications to be executed * before the refactoring change or <code>null</code> if no changes are made * * @throws CoreException if an error occurred while creating the change * * @throws OperationCanceledException if the change creation got canceled * * @see #createChange(IProgressMonitor) * * @since 3.4 */ public Change createPreChange(IProgressMonitor pm) throws CoreException, OperationCanceledException { return null; } /** * Creates a {@link Change} object that contains the workspace modifications * of this participant to be executed <em>after</em> the * changes from the refactoring are executed. Note that this implies that the * undo change of the returned Change object will be executed <em>before</em> * the undo changes from the refactoring have been executed. * <p> * The changes provided by a participant <em>must</em> * not conflict with any change provided by other participants or by the * refactoring itself. * <p> * If the change conflicts with any change provided by other participants or * by the refactoring itself, then change execution will fail and the * participant will be disabled for the rest of the eclipse session. * </p> * <p> * If an exception occurs while creating the change, the refactoring can not * be carried out, and the participant will be disabled for the rest of the * eclipse session. * </p> * <p> * As of 3.1, a participant can manipulate text resources already manipulated by * the processor as long as the textual manipulations don't conflict (i.e. * the participant manipulates a different region of the text resource). * The method must not return those changes in its change tree since the change * is already part of another change tree. If the participant only manipulates * shared changes, then it can return <code>null</code> to indicate that it didn't * create own changes. A shared text change can be accessed via the method * {@link #getTextChange(Object)}. * </p> * * @param pm a progress monitor to report progress * * @return the change representing the workspace modifications to be executed * after the refactoring change or <code>null</code> if no changes are made * * @throws CoreException if an error occurred while creating the change * * @throws OperationCanceledException if the change creation got canceled * * @see #createPreChange(IProgressMonitor) */ public abstract Change createChange(IProgressMonitor pm) throws CoreException, OperationCanceledException; /** * Returns the text change for the given element or <code>null</code> * if a text change doesn't exist. This method only returns a valid * result during change creation. Outside of change creation always * <code>null</code> is returned. * * @param element the element to be modified for which a text change * is requested * * @return the text change or <code>null</code> if no text change exists * for the element * * @since 3.1 */ public TextChange getTextChange(Object element) { return getProcessor().getRefactoring().getTextChange(element); } //---- helper method ---------------------------------------------------- /* package */ void setDescriptor(ParticipantDescriptor descriptor) { Assert.isNotNull(descriptor); fDescriptor = descriptor; } /* package */ ParticipantDescriptor getDescriptor() { return fDescriptor; } }
41.276094
141
0.722897
8ad2129fd82b5d72a59e3c21dac64e304ba3e385
2,831
package test.byexample.macro.custom; import com.github.javaparser.ast.Node; import com.github.javaparser.utils.Log; import junit.framework.TestCase; import org.jdraft._class; import org.jdraft.macro.macro; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.util.function.Consumer; /** * Shows how to develop and test a simple Macro * * Conventions * * Logging (whats the macro system doing? * Macros on different elements * Macros order of operations * */ public class _1_Annotation_With_Consumer_Field_Test extends TestCase { /* Custom Annotation/Macro as an "Annotation With Consumer Field" -type * meaning the Annotation signifying the macro */ @Retention(RetentionPolicy.RUNTIME) public @interface _annWithField { /** * THIS IS THE SIMPLEST TYPE OF ANNOTATION MACRO called a Consumer Field Macro * * this is the "macro" code, its a Field of type consumer on an Annotation * the name doesn't matter, * by */ Consumer<Node> Macro = (node)-> { /* set a System Property to verify how many times it was called */ System.setProperty(_annWithField.class.getSimpleName(), ( Integer.parseInt(System.getProperty(_annWithField.class.getSimpleName(), "0") )+ 1) +"" ); /* manually remove the annotation on the model */ macro.removeAnnotation(node, _annWithField.class); }; } /* Test "Annotation With Consumer Field" Style 1 */ public void testUseConsumerFieldMacro(){ // 1) verify the property is NOT set BEFORE calling the macro assertNull(System.getProperty(_annWithField.class.getSimpleName())); // 2) annotate an example with the macro @_annWithField class C{} // 3a) call the macro (here manually) _class _c = macro.to(C.class); // 3b) _class.of(...) will ALSO internally process macros _class _c2 = _class.of(C.class); assertEquals( _c, _c2); // verify the System property was set (in the macro) assertEquals("2",System.getProperty(_annWithField.class.getSimpleName())); // verify the model doesn't still have the macro assertFalse(_c.hasAnnos()); //verify we cleaned up the annotation on the class assertFalse(_c.hasAnno(_annWithField.class)); System.out.println(_c ); } public void setUp(){ //here we are turning internal logging (to System out) on to show internals of macros Log.setAdapter(new Log.StandardOutStandardErrorAdapter()); //remove all the properties we set System.clearProperty(_annWithField.class.getSimpleName()); } public void tearDown(){ Log.setAdapter(new Log.SilentAdapter()); } }
34.52439
112
0.665489
dcc935c9251207af60e8cb67adac79d0e7cb35ed
129
version https://git-lfs.github.com/spec/v1 oid sha256:28f0d636f9bcd0d6e7bdc0f7953c503a900aa672b9c15108463ad2963becffb8 size 7254
32.25
75
0.883721
8027fa9cc26509cf046e8f6274d5da0e8c755104
1,143
package simplest.possible; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.function.Consumer; /** * <pre> * some goals: * === * - [ ] take a string, a key or an expression, and return bytes * * cat was the most literal translation of the first goal. * * highly unsafe */ public class Cat implements Consumer<String> { public static void main(String... args) { if (args.length > 0) { cat(args[0]); } else { String x = String.valueOf(Paths.get("").toAbsolutePath()); System.err.println("you are in "+x); System.exit(1); } } public static void cat(String arg) { new Cat().accept(arg); } public static String saferKey(String arg) { return arg.replaceAll("\\.+", "\\."); } @Override public void accept(String s) { String saferKey = saferKey(s); try { byte[] bytes = Files.readAllBytes(Paths.get(saferKey)); System.out.write(bytes); } catch (IOException e) { e.printStackTrace(); } } }
22.411765
70
0.569554
f694a0fa65066b9acb4bebd128b3c0d288d43fd4
7,763
package com.edgardleal.engine; import java.awt.Color; import java.awt.Dimension; import java.awt.Toolkit; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.text.DecimalFormat; import javax.swing.BorderFactory; import javax.swing.JDialog; /** */ public class Vetor { private double x = 1, y = 1; private double direcao = 0, raio = 0; private double raioLimite = 0; /** * Constructor for Vetor. * @param x double * @param y double */ public Vetor(double x, double y) { setXY(x, y); } public Vetor() { setXY(0, 0); } /** * Method produtoInterno. * @param v Vetor * @return double */ public double produtoInterno(Vetor v) { return (v.getX() * x) + (v.getY() * y); } /** * retorna o produto externo entre este e outro vetor. * * @param v * @return Vetor */ public Vetor produtoExterno(Vetor v) { /* * 1 1 1 1 1 x1 y1 1 x1 y1 x2 y2 1 x2 y2 * * result = 1*y1*1 + 1*1*x2 + 1*x1*y2 - 1*x1*1 - 1*1*y2 - 1*y1*x2 */ return new Vetor(y - x, v.getX() - v.getY()); } /** * Method toString. * @return String */ public String toString() { return "X:" + getX() + " , Y:" + getY() + " Raio:" + getRaio() + " �ngulo : " + getDirecao() * (180 / Math.PI); } /** * Method somar. * @param x double * @param y double */ public void somar(double x, double y) { if (raioLimite != 0 && calcModulo(x, y) + getModulo() > raioLimite) return; this.x += x; this.y += y; calcRaio(); calcDirecao(); } /** * Method calcModulo. * @param x double * @param y double * @return double */ private double calcModulo(double x, double y) { return Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2)); } /** * Method somar. * @param v Vetor */ public void somar(Vetor v) { somar(v.getX(), v.getY()); } /** * Method subtrair. * @param x double * @param y double */ public void subtrair(double x, double y) { this.x -= x; this.y -= y; calcRaio(); calcDirecao(); } /** * Este m�todo faz a subtra��o do raio informado e resolve o problema de tamanho do raio subtraido * ser maior que o raio do vetor em que ser� removido. * * @param v */ public void subtrair(Vetor v) { double raioAnterior = v.getRaio(); if (raioAnterior > raio) v.setRaio(raio); subtrair(v.getX(), v.getY()); v.setRaio(raioAnterior);// devolve o valor original para o objeto par�metro } /** * Informar o valor em radianos : um círculo = 2*Pi * * @param direcao */ public void setDirecao(double direcao) { direcao = direcao == Double.NaN ? 0 : direcao; this.direcao = direcao; calcXY(); } /** * Informar o valor em graus : 0 -> 360 </br> OBS: o ângulo 0(zero) fica ao lado direito (3 horas) * * @param angulo */ public void setDirecaoGraus(double angulo) { angulo = angulo == Double.NaN ? 0 : angulo; setDirecao(((angulo % 360) / 180) * Math.PI); } /** * Method setXY. * @param x double * @param y double */ public void setXY(double x, double y) { this.x = x; this.y = y; calcDirecao(); calcRaio(); } /** * Method setRaio. * @param raio double */ public void setRaio(double raio) { this.raio = raio; calcXY(); } /** * Method setX. * @param x double */ public void setX(double x) { setXY(x, this.y); } /** * Method setY. * @param y double */ public void setY(double y) { setXY(this.x, y); } /** * Method getRaio. * @return double */ public double getRaio() { raio = raio == Double.NaN ? 0 : raio; return raio; } /** * Method getX. * @return double */ public double getX() { return x; } /** * Retorna o valor da posição X para o raio informado de acordo ângulo atual. * * @param r * @return int */ public int getXParaORaio(double r) { return round(Math.cos(getDirecao()) * r); } /** * Função para arredondamento(Encapsulamento do cast (int)2.5 ). * * @param v * @return int */ private int round(double v) { return (int) v; } /** * Method getY. * @return double */ public double getY() { return y; } /** * Retorna a direção do vetor em Radianos. * * @return double */ public double getDirecao() { direcao = direcao == Double.NaN ? 0 : direcao; return direcao; } /** * Method multiplicar. * @param v double */ public void multiplicar(double v) { x = v * x; y = v * y; calcRaio();// a direção continua a mesma } public void inverter() { inverter(this); } /** * Inverte a direção do vetor. * * @param v */ public void inverter(Vetor v) { direcao = (v.getDirecao() + Math.PI); direcao = direcao > Math.PI * 2 ? direcao - Math.PI * 2 : direcao; setDirecao(direcao);// para atualização dos calculos necessários } /** * Method getModulo. * @return double */ public double getModulo() { return raio; } private void calcRaio() { raio = Math.sqrt(Math.pow(x, 2d) + Math.pow(y, 2d)); } private void calcDirecao() { // vetor para orientação (1,0) direcao = Math.acos((x * 1 + y * 0) / (calcModulo(x, y) * 1)); direcao = y > 0 ? direcao + Math.PI : direcao; } private void calcXY() { x = Math.cos(direcao) * raio; y = Math.sin(direcao) * raio; } /** * Method paint. * @param g java.awt.Graphics */ public void paint(java.awt.Graphics g) { g.drawLine(100, 100, 100 + (int) x, 100 + (int) y); } /** * Method setRaioLimite. * @param l double */ public void setRaioLimite(double l) { raioLimite = l; } /** * Method main. * @param args String[] */ public static void main(String[] args) { Vetor v = new Vetor(20, -20), // teste de mudan�a de dire��o b = new Vetor(20, 20); b.setDirecaoGraus(45); System.out.println("B= " + b); System.out.println(v); v.inverter(); System.out.println(v); v.somar(b); System.out.println(v); v.exibir(); System.exit(0); } public void exibir() { Tela tela = new Tela(this); tela.setVisible(true); } } /** */ class Tela extends JDialog { /** * */ private static final long serialVersionUID = -382822471525634591L; private Vetor v; /** * Constructor for Tela. * @param v Vetor */ public Tela(Vetor v) { this.v = v; setSize(400, 400); Dimension d = Toolkit.getDefaultToolkit().getScreenSize(); setLocation(d.width / 2 - 200, d.height / 2 - 200); setResizable(false); setUndecorated(true); this.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { setVisible(false); } }); this.getRootPane().setBorder(BorderFactory.createLineBorder(Color.red)); setModal(true); } /** * Method paint. * @param g java.awt.Graphics */ @Override public void paint(java.awt.Graphics g) { DecimalFormat formato = new DecimalFormat("0.0"); super.paint(g); g.setColor(Color.blue); g.fillOval(197, 197, 7, 7); g.drawLine(200, 200, (int) v.getX() + 200, (int) v.getY() + 200); g.drawString("" + formato.format(v.getX()) + " - " + formato.format(v.getY()), (int) v.getX() + 190, (int) v.getY() + 190); } }
20.428947
101
0.547855
2ddf6ad87bbba1866f0ae3246e79964bcbdf6435
1,519
package javax.persistence.upsert.model; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import lombok.Getter; import lombok.experimental.SuperBuilder; @SuperBuilder public class Header { @Getter private String name; private String references; private String modifiers; public List<String> getReferences() { if (references == null) { return List.of(); } return Arrays.stream(references.split(",")).collect(Collectors.toList()); } public Map<Modifier, Object> getModifiers() { if (modifiers == null) { return Map.of(); } return Arrays .stream(modifiers.split(",")) .collect( Collectors.toMap( definition -> getModifier(definition.split("=")), definition -> { final String[] split = definition.split("="); final Modifier modifier = getModifier(split); if (split.length == 1) { return modifier.getDefaultValue(); } return modifier.getEvaluate().apply(split[1].trim()); } ) ); } private Modifier getModifier(final String[] definition) { return Modifier.valueOf(definition[0].trim().toUpperCase()); } @Override public String toString() { return String.format( "%s(%s)[%s]", name, getReferences().stream().map(Object::toString).collect(Collectors.joining(", ")), getModifiers() .entrySet() .stream() .map(modifier -> String.format("%s = %s", modifier.getKey(), modifier.getValue())) .collect(Collectors.joining(", ")) ); } }
23.015152
86
0.662936
08d6d6be44235ce84b2a1dd2be09f3335daeae43
7,735
/** */ package subkdm.kdmObjects; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.eclipse.emf.common.util.Enumerator; /** * <!-- begin-user-doc --> * A representation of the literals of the enumeration '<em><b>Metho Kind</b></em>', * and utility methods for working with them. * <!-- end-user-doc --> * @see subkdm.kdmObjects.KdmObjectsPackage#getMethoKind() * @model * @generated */ public enum MethoKind implements Enumerator { /** * The '<em><b>Method</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #METHOD_VALUE * @generated * @ordered */ METHOD(0, "method", "method"), /** * The '<em><b>Constructos</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #CONSTRUCTOS_VALUE * @generated * @ordered */ CONSTRUCTOS(1, "constructos", "constructos"), /** * The '<em><b>Destructor</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #DESTRUCTOR_VALUE * @generated * @ordered */ DESTRUCTOR(2, "destructor", "destructor"), /** * The '<em><b>Operator</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #OPERATOR_VALUE * @generated * @ordered */ OPERATOR(3, "operator", "operator"), /** * The '<em><b>Virtual</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #VIRTUAL_VALUE * @generated * @ordered */ VIRTUAL(4, "virtual", "virtual"), /** * The '<em><b>Abstract</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #ABSTRACT_VALUE * @generated * @ordered */ ABSTRACT(5, "abstract", "abstract"), /** * The '<em><b>Unknown</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #UNKNOWN_VALUE * @generated * @ordered */ UNKNOWN(6, "unknown", "unknown"); /** * The '<em><b>Method</b></em>' literal value. * <!-- begin-user-doc --> * <p> * If the meaning of '<em><b>Method</b></em>' literal object isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @see #METHOD * @model name="method" * @generated * @ordered */ public static final int METHOD_VALUE = 0; /** * The '<em><b>Constructos</b></em>' literal value. * <!-- begin-user-doc --> * <p> * If the meaning of '<em><b>Constructos</b></em>' literal object isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @see #CONSTRUCTOS * @model name="constructos" * @generated * @ordered */ public static final int CONSTRUCTOS_VALUE = 1; /** * The '<em><b>Destructor</b></em>' literal value. * <!-- begin-user-doc --> * <p> * If the meaning of '<em><b>Destructor</b></em>' literal object isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @see #DESTRUCTOR * @model name="destructor" * @generated * @ordered */ public static final int DESTRUCTOR_VALUE = 2; /** * The '<em><b>Operator</b></em>' literal value. * <!-- begin-user-doc --> * <p> * If the meaning of '<em><b>Operator</b></em>' literal object isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @see #OPERATOR * @model name="operator" * @generated * @ordered */ public static final int OPERATOR_VALUE = 3; /** * The '<em><b>Virtual</b></em>' literal value. * <!-- begin-user-doc --> * <p> * If the meaning of '<em><b>Virtual</b></em>' literal object isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @see #VIRTUAL * @model name="virtual" * @generated * @ordered */ public static final int VIRTUAL_VALUE = 4; /** * The '<em><b>Abstract</b></em>' literal value. * <!-- begin-user-doc --> * <p> * If the meaning of '<em><b>Abstract</b></em>' literal object isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @see #ABSTRACT * @model name="abstract" * @generated * @ordered */ public static final int ABSTRACT_VALUE = 5; /** * The '<em><b>Unknown</b></em>' literal value. * <!-- begin-user-doc --> * <p> * If the meaning of '<em><b>Unknown</b></em>' literal object isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @see #UNKNOWN * @model name="unknown" * @generated * @ordered */ public static final int UNKNOWN_VALUE = 6; /** * An array of all the '<em><b>Metho Kind</b></em>' enumerators. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private static final MethoKind[] VALUES_ARRAY = new MethoKind[] { METHOD, CONSTRUCTOS, DESTRUCTOR, OPERATOR, VIRTUAL, ABSTRACT, UNKNOWN, }; /** * A public read-only list of all the '<em><b>Metho Kind</b></em>' enumerators. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public static final List<MethoKind> VALUES = Collections.unmodifiableList(Arrays.asList(VALUES_ARRAY)); /** * Returns the '<em><b>Metho Kind</b></em>' literal with the specified literal value. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public static MethoKind get(String literal) { for (int i = 0; i < VALUES_ARRAY.length; ++i) { MethoKind result = VALUES_ARRAY[i]; if (result.toString().equals(literal)) { return result; } } return null; } /** * Returns the '<em><b>Metho Kind</b></em>' literal with the specified name. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public static MethoKind getByName(String name) { for (int i = 0; i < VALUES_ARRAY.length; ++i) { MethoKind result = VALUES_ARRAY[i]; if (result.getName().equals(name)) { return result; } } return null; } /** * Returns the '<em><b>Metho Kind</b></em>' literal with the specified integer value. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public static MethoKind get(int value) { switch (value) { case METHOD_VALUE: return METHOD; case CONSTRUCTOS_VALUE: return CONSTRUCTOS; case DESTRUCTOR_VALUE: return DESTRUCTOR; case OPERATOR_VALUE: return OPERATOR; case VIRTUAL_VALUE: return VIRTUAL; case ABSTRACT_VALUE: return ABSTRACT; case UNKNOWN_VALUE: return UNKNOWN; } return null; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private final int value; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private final String name; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private final String literal; /** * Only this class can construct instances. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private MethoKind(int value, String name, String literal) { this.value = value; this.name = name; this.literal = literal; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public int getValue() { return value; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String getName() { return name; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String getLiteral() { return literal; } /** * Returns the literal value of the enumerator, which is its string representation. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String toString() { return literal; } } //MethoKind
22.485465
104
0.583581
08416e798ecfd9642cbcac9297cba563086cf626
1,905
/* * Copyright 2014 OCTO Technology * * 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.octo.reactive.audit.javax.imageio; import com.octo.reactive.audit.IOTestTools; import com.octo.reactive.audit.TestTools; import com.octo.reactive.audit.lib.FileReactiveAuditException; import org.junit.Test; import javax.imageio.ImageIO; import java.io.IOException; public class ImageIOTest { @Test(expected = FileReactiveAuditException.class) public void read_File() throws IOException { TestTools.strict.commit(); ImageIO.read(IOTestTools.getTempFile()); } @Test(expected = FileReactiveAuditException.class) public void read_InputStream() throws IOException { TestTools.strict.commit(); ImageIO.read(IOTestTools.getTempFileInputStream()); } @Test(expected = FileReactiveAuditException.class) public void read_URL() throws IOException { TestTools.strict.commit(); ImageIO.read(IOTestTools.getTempFile().toURI().toURL()); } @Test(expected = FileReactiveAuditException.class) public void write_File() throws IOException { TestTools.strict.commit(); ImageIO.write(null, "", IOTestTools.getTempFile()); } @Test(expected = FileReactiveAuditException.class) public void write_OutputStream() throws IOException { TestTools.strict.commit(); ImageIO.write(null, "", IOTestTools.getTempFileOutputStream()); } }
27.608696
75
0.745932
17c97bf2e5a2b9b9561aea0cf22f530fe6bbf980
17,467
package com.example.asknanterre; import android.content.Intent; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.appcompat.app.ActionBar; import androidx.appcompat.app.AppCompatActivity; import com.baoyz.swipemenulistview.SwipeMenu; import com.baoyz.swipemenulistview.SwipeMenuCreator; import com.baoyz.swipemenulistview.SwipeMenuItem; import com.baoyz.swipemenulistview.SwipeMenuListView; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.Query; import com.google.firebase.database.ValueEventListener; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import es.dmoral.toasty.Toasty; public class DisplayQuizProf extends AppCompatActivity { SwipeMenuListView myListView; EditText name; List<QuestionProf> quiz; List<String> quizID; List<QuestionProf> quiztmp; List<String> quizIDtmp; String[] q1; String[] q2; String[] q3; String[] q4; String[] q5; Integer[] q6; Integer[] q7; ArrayList<String> list1; ArrayList<String> list2; ArrayList<String> list3; ArrayList<String> list4; ArrayList<String> list5; ArrayList<Integer> list6; ArrayList<Integer> list7; private DatabaseReference mQuestionReference; ProgressBar progressBar; Spinner spinner; EditText edit; DatabaseReference ref; CustomAdapterQuizProf adapt; Bundle b; String coursId; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_displayquizprof); b = getIntent().getExtras(); coursId = b.getString("key"); mQuestionReference = FirebaseDatabase.getInstance().getReference() .child("questionProf"); updateList(); myListView = (SwipeMenuListView) findViewById(R.id.myListView); TextView emptyText = (TextView)findViewById(android.R.id.empty); myListView.setEmptyView(emptyText); spinner = (Spinner) findViewById(R.id.spinner1); final List<String> spinnerArray = new ArrayList<String>(); final ArrayAdapter<String> adapter = new ArrayAdapter<String>( this, android.R.layout.simple_spinner_item, spinnerArray); spinnerArray.add(getString(R.string.trier_par_date_asc)); spinnerArray.add(getString(R.string.trier_par_date_des)); spinnerArray.add(getString(R.string.trier_par_bonne_reponse)); spinnerArray.add(getString(R.string.trier_par_mauvaise_reponse)); spinnerArray.add(getString(R.string.trier_par_difficulte)); adapter.notifyDataSetChanged(); spinner.setAdapter(adapter); spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) { // your code here } @Override public void onNothingSelected(AdapterView<?> parentView) { // your code here } }); ActionBar ab = getSupportActionBar(); ab.setSubtitle(getString(R.string.liste_des_nquizs)); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main2, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch(item.getItemId()) { case R.id.action_back: //add the function to perform here annuler(); return(true); case R.id.action_home: //add the function to perform here goToMainActivity(); return(true); case R.id.action_help: //add the function to perform here goToHelpActivity(); return(true); } return(super.onOptionsItemSelected(item)); } @Override protected void onStart() { super.onStart(); //show(); } public void trier(View v, final int position) { myListView = (SwipeMenuListView) findViewById(R.id.myListView); TextView emptyText = (TextView)findViewById(android.R.id.empty); myListView.setEmptyView(emptyText); progressBar = findViewById(R.id.progressBar); progressBar.setVisibility(View.VISIBLE); b = getIntent().getExtras(); coursId = b.getString("key"); DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference(); DatabaseReference questionProfRef = rootRef.child("questionProf"); quiz = new ArrayList<QuestionProf>(); quizID = new ArrayList<String>(); quiztmp = new ArrayList<QuestionProf>(); quizIDtmp = new ArrayList<String>(); String s; if (position == 2) { s = "ncorrects"; } else if (position == 3) { s = "nfalses"; } else if (position == 4) { s = "difficulte"; } else { s = ""; } Query q; if(!s.isEmpty()) { q = questionProfRef.orderByChild(s); } else { q = questionProfRef; } q.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { quiz.clear(); quizID.clear(); for (DataSnapshot ds : dataSnapshot.getChildren()) { if(ds.getValue(QuestionProf.class).coursId.equals(coursId)) { String product = ds.getKey(); quiz.add(ds.getValue(QuestionProf.class)); quizID.add(ds.getKey()); Log.d("TAG", product); } } progressBar.setVisibility(View.GONE); if(position != 0) { Collections.reverse(quiz); Collections.reverse(quizID); } q1 = new String[quiz.size()]; q3 = new String[quiz.size()]; q4 = new String[quiz.size()]; q5 = new String[quiz.size()]; q6 = new Integer[quiz.size()]; q7 = new Integer[quiz.size()]; myListView = (SwipeMenuListView) findViewById(R.id.myListView); for (int i = 0; i < quiz.size(); i++) { q1[i] = quiz.get(i).nom; q3[i] = quiz.get(i).titre; q4[i] = quiz.get(i).date; q5[i] = "" + quiz.get(i).difficulte; q6[i] = quiz.get(i).Ncorrects; q7[i] = quiz.get(i).Nfalses; } ArrayAdapter<String> adapter = new ArrayAdapter<String>(DisplayQuizProf.this, android.R.layout.simple_list_item_1, q1); list1 = new ArrayList(Arrays.asList(q1)); list2 = new ArrayList(quizID); list3 = new ArrayList(Arrays.asList(q3)); list4 = new ArrayList(Arrays.asList(q4)); list5 = new ArrayList(Arrays.asList(q5)); list6 = new ArrayList(Arrays.asList(q6)); list7 = new ArrayList(Arrays.asList(q7)); adapt = new CustomAdapterQuizProf(list1, list2, list3, list4, list5, list6, list7, DisplayQuizProf.this); myListView.setAdapter(adapt); adapt.notifyDataSetChanged(); } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); } public void updateList() { progressBar = findViewById(R.id.progressBar); progressBar.setVisibility(View.VISIBLE); b = getIntent().getExtras(); coursId = b.getString("key"); DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference(); DatabaseReference questionRef = rootRef.child("questionProf"); quiz = new ArrayList<QuestionProf>(); quizID = new ArrayList<String>(); quiztmp = new ArrayList<QuestionProf>(); quizIDtmp = new ArrayList<String>(); ValueEventListener eventListener = new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { quiz.clear(); quizID.clear(); for (DataSnapshot ds : dataSnapshot.getChildren()) { if(ds.getValue(QuestionProf.class).coursId.equals(coursId)) { String product = ds.getKey(); quiz.add(ds.getValue(QuestionProf.class)); quizID.add(ds.getKey()); } } progressBar.setVisibility(View.GONE); q1 = new String[quiz.size()]; q3 = new String[quiz.size()]; q4 = new String[quiz.size()]; q5 = new String[quiz.size()]; q6 = new Integer[quiz.size()]; q7 = new Integer[quiz.size()]; myListView = (SwipeMenuListView) findViewById(R.id.myListView); TextView emptyText = (TextView)findViewById(android.R.id.empty); myListView.setEmptyView(emptyText); for (int i = 0; i < quiz.size(); i++) { q1[i] = quiz.get(i).nom; q3[i] = quiz.get(i).titre; q4[i] = quiz.get(i).date; q5[i] = "" + quiz.get(i).difficulte; q6[i] = quiz.get(i).Ncorrects; q7[i] = quiz.get(i).Nfalses; } spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) { // your code here trier(selectedItemView, position); } @Override public void onNothingSelected(AdapterView<?> parentView) { // your code here } }); edit = (EditText) findViewById(R.id.EditText01); edit.addTextChangedListener(new TextWatcher() { public void afterTextChanged(Editable s) {} public void beforeTextChanged(CharSequence s, int start, int count, int after) {} public void onTextChanged(CharSequence s, int start, int before, int count) { quiztmp.clear(); quizIDtmp.clear(); final int size = quiz.size(); if(s.length()!=0){ for(int i=0; i<size; i++) { if(quiz.get(i).nom.toLowerCase().contains(s.toString().toLowerCase())) { quiztmp.add(quiz.get(i)); quizIDtmp.add(quizID.get(i)); } } } if(quiztmp.size()!=0) { quiz.clear(); quizID.clear(); quiz.addAll(quiztmp); quizID.addAll(quizIDtmp); q1 = new String[quiz.size()]; q3 = new String[quiz.size()]; q4 = new String[quiz.size()]; q5 = new String[quiz.size()]; q6 = new Integer[quiz.size()]; q7 = new Integer[quiz.size()]; for (int i = 0; i < quiz.size(); i++) { q1[i] = quiz.get(i).nom; q3[i] = quiz.get(i).titre; q4[i] = quiz.get(i).date; q5[i] = "" + quiz.get(i).difficulte; q6[i] = quiz.get(i).Ncorrects; q7[i] = quiz.get(i).Nfalses; } ArrayAdapter<String> adapter = new ArrayAdapter<String>(DisplayQuizProf.this, android.R.layout.simple_list_item_1, q1); list1 = new ArrayList(Arrays.asList(q1)); list2 = new ArrayList(quizID); list3 = new ArrayList(Arrays.asList(q3)); list4 = new ArrayList(Arrays.asList(q4)); list5 = new ArrayList(Arrays.asList(q5)); list6 = new ArrayList(Arrays.asList(q6)); list7 = new ArrayList(Arrays.asList(q7)); adapt = new CustomAdapterQuizProf(list1, list2, list3, list4, list5, list6, list7, DisplayQuizProf.this); myListView.setAdapter(adapt); adapt.notifyDataSetChanged(); } else { updateList(); } } }); ArrayAdapter<String> adapter = new ArrayAdapter<String>(DisplayQuizProf.this, android.R.layout.simple_list_item_1, q1); list1 = new ArrayList(Arrays.asList(q1)); list2 = new ArrayList(quizID); list3 = new ArrayList(Arrays.asList(q3)); list4 = new ArrayList(Arrays.asList(q4)); list5 = new ArrayList(Arrays.asList(q5)); list6 = new ArrayList(Arrays.asList(q6)); list7 = new ArrayList(Arrays.asList(q7)); adapt = new CustomAdapterQuizProf(list1, list2, list3, list4, list5, list6, list7, DisplayQuizProf.this); myListView.setAdapter(adapt); adapt.notifyDataSetChanged(); SwipeMenuCreator creator = new SwipeMenuCreator() { @Override public void create(SwipeMenu menu) { // create "delete" item SwipeMenuItem deleteItem = new SwipeMenuItem( getApplicationContext()); // set item background deleteItem.setBackground(new ColorDrawable(Color.rgb(0xF9, 0x3F, 0x25))); // set item width deleteItem.setWidth(170); // set a icon deleteItem.setIcon(R.drawable.ic_delete); // add to menu menu.addMenuItem(deleteItem); } }; myListView.setMenuCreator(creator); myListView.setOnMenuItemClickListener(new SwipeMenuListView.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(final int position, SwipeMenu menu, int index) { switch (index) { case 0: ref=FirebaseDatabase.getInstance().getReference().child("questionProf").child(list2.get(position)); ref.removeValue(); Toasty.success(DisplayQuizProf.this, getString(R.string.le_quiz) + list1.get(position) + getString(R.string.a_ete_supprime), Toast.LENGTH_LONG).show(); list2.remove(position); //or some other task adapt.notifyDataSetChanged(); updateList(); break; } // false : close the menu; true : not close the menu return true; } }); } @Override public void onCancelled(DatabaseError databaseError) { } }; questionRef.addListenerForSingleValueEvent(eventListener); } public void annuler() { finish(); } public void goToMainActivity(){ Intent intent = new Intent(this, MainActivity.class); startActivity(intent); } public void goToHelpActivity(){ Intent intent = new Intent(this, HelpQuizProf.class); startActivity(intent); } }
38.304825
183
0.536784
1a37945ccec3331c4d595383540a907d2f63bfe8
225
package example.service; import example.repo.Customer1392Repository; import org.springframework.stereotype.Service; @Service public class Customer1392Service { public Customer1392Service(Customer1392Repository repo) {} }
20.454545
59
0.84
15997705afe1fd528369fa81540f234b0c59d70b
1,669
/* * 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.streampipes.client.http.header; import org.apache.http.Header; import org.apache.http.message.BasicHeader; import static org.apache.streampipes.commons.constants.HttpConstants.*; public class Headers { public static Header authorizationBearer(String bearerToken) { return makeHeader(AUTHORIZATION, BEARER + bearerToken); } public static Header xApiKey(String apiKey) { return makeHeader(X_API_KEY, apiKey); } public static Header xApiUser(String apiUser) { return makeHeader(X_API_USER, apiUser); } public static Header acceptJson() { return makeHeader(ACCEPT, APPLICATION_JSON_TYPE); } private static Header makeHeader(String name, String value) { return new BasicHeader(name, value); } public static Header contentTypeJson() { return makeHeader(CONTENT_TYPE, APPLICATION_JSON_TYPE); } }
32.72549
75
0.756741
527e8da2e280cd2c7c1eac082ba5e524d2198c73
4,731
package org.mockserver.echo.http; import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; import io.netty.handler.codec.http.DefaultFullHttpResponse; import io.netty.handler.codec.http.DefaultHttpObject; import org.mockserver.codec.MockServerToNettyResponseEncoder; import org.mockserver.log.MockServerEventLog; import org.mockserver.log.model.LogEntry; import org.mockserver.logging.MockServerLogger; import org.mockserver.mappers.MockServerHttpResponseToFullHttpResponse; import org.mockserver.model.BodyWithContentType; import org.mockserver.model.HttpRequest; import org.mockserver.model.HttpResponse; import org.slf4j.event.Level; import static io.netty.handler.codec.http.HttpHeaderNames.CONTENT_LENGTH; import static io.netty.handler.codec.http.HttpResponseStatus.NOT_FOUND; import static io.netty.handler.codec.http.HttpResponseStatus.OK; import static org.mockserver.log.model.LogEntry.LogMessageType.RECEIVED_REQUEST; import static org.mockserver.model.HttpResponse.response; import static org.slf4j.event.Level.INFO; /** * @author jamesdbloom */ @ChannelHandler.Sharable public class EchoServerHandler extends SimpleChannelInboundHandler<HttpRequest> { private final EchoServer.Error error; private final MockServerLogger mockServerLogger; private final MockServerEventLog mockServerEventLog; private final EchoServer.NextResponse nextResponse; EchoServerHandler(EchoServer.Error error, MockServerLogger mockServerLogger, MockServerEventLog mockServerEventLog, EchoServer.NextResponse nextResponse) { this.error = error; this.mockServerLogger = mockServerLogger; this.mockServerEventLog = mockServerEventLog; this.nextResponse = nextResponse; } protected void channelRead0(ChannelHandlerContext ctx, HttpRequest request) { mockServerEventLog.add( new LogEntry() .setType(RECEIVED_REQUEST) .setLogLevel(INFO) .setHttpRequest(request) .setMessageFormat("EchoServer received request{}") .setArguments(request) ); if (!nextResponse.httpResponse.isEmpty()) { // WARNING: this logic is only for unit tests that run in series and is NOT thread safe!!! DefaultHttpObject httpResponse = new MockServerHttpResponseToFullHttpResponse(mockServerLogger).mapMockServerResponseToNettyResponse(nextResponse.httpResponse.remove()).get(0); ctx.writeAndFlush(httpResponse); } else { HttpResponse httpResponse = response() .withStatusCode(request.getPath().equalsIgnoreCase("/not_found") ? NOT_FOUND.code() : OK.code()) .withHeaders(request.getHeaderList()); if (request.getBody() instanceof BodyWithContentType) { httpResponse.withBody((BodyWithContentType<?>) request.getBody()); } else { httpResponse.withBody(request.getBodyAsString()); } // set hop-by-hop headers final int length = httpResponse.getBody() != null ? httpResponse.getBody().getRawBytes().length : 0; if (error == EchoServer.Error.LARGER_CONTENT_LENGTH) { httpResponse.replaceHeader(CONTENT_LENGTH.toString(), String.valueOf(length * 2)); } else if (error == EchoServer.Error.SMALLER_CONTENT_LENGTH) { httpResponse.replaceHeader(CONTENT_LENGTH.toString(), String.valueOf(length / 2)); } else { httpResponse.replaceHeader(CONTENT_LENGTH.toString(), String.valueOf(length)); } mockServerEventLog.add( new LogEntry() .setLogLevel(INFO) .setHttpRequest(request) .setHttpResponse(httpResponse) .setMessageFormat("EchoServer returning response{}for request{}") .setArguments(httpResponse, request) ); // write and flush ctx.writeAndFlush(httpResponse); if (error == EchoServer.Error.LARGER_CONTENT_LENGTH || error == EchoServer.Error.SMALLER_CONTENT_LENGTH) { ctx.close(); } } } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { mockServerLogger.logEvent( new LogEntry() .setType(LogEntry.LogMessageType.EXCEPTION) .setLogLevel(Level.ERROR) .setMessageFormat("echo server server caught exception") .setThrowable(cause) ); ctx.close(); } }
43.009091
188
0.681463
6d42bcacc2cafc1e0b98aea2c92ba3b866887ba3
1,413
/** */ package aadl2.tests; import aadl2.Aadl2Factory; import aadl2.AbstractFeature; import junit.textui.TestRunner; /** * <!-- begin-user-doc --> * A test case for the model object '<em><b>Abstract Feature</b></em>'. * <!-- end-user-doc --> * @generated */ public class AbstractFeatureTest extends DirectedFeatureTest { /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public static void main(String[] args) { TestRunner.run(AbstractFeatureTest.class); } /** * Constructs a new Abstract Feature test case with the given name. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public AbstractFeatureTest(String name) { super(name); } /** * Returns the fixture for this Abstract Feature test case. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected AbstractFeature getFixture() { return (AbstractFeature)fixture; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see junit.framework.TestCase#setUp() * @generated */ @Override protected void setUp() throws Exception { setFixture(Aadl2Factory.eINSTANCE.createAbstractFeature()); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see junit.framework.TestCase#tearDown() * @generated */ @Override protected void tearDown() throws Exception { setFixture(null); } } //AbstractFeatureTest
19.901408
71
0.634112
881e7b6f61ee00d3863acc7239dc55425e0c3af4
548
package com.github.carniwar.springboot.scalable.rest; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; /** * Application Main class. Called when package application is in run with fat jar. */ @SpringBootApplication( scanBasePackages = App.BASE_PACKAGE ) public class App { public static final String BASE_PACKAGE = "com.github.carniwar.springboot.scalable"; public static void main(String[] args) { SpringApplication.run(App.class, args); } }
27.4
88
0.759124
b45f99925e674dd39716a53d3c8486cea4624ac0
8,987
/* * (C) Copyright 2015 Kurento (http://kurento.org/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.kurento.tutorial.showdatachannel.handler; import java.io.IOException; import java.util.concurrent.ConcurrentHashMap; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.kurento.client.*; import org.kurento.jsonrpc.JsonUtils; import org.kurento.module.datachannelexample.KmsShowData; import org.kurento.tutorial.showdatachannel.service.SendMessageService; import org.kurento.tutorial.showdatachannel.utils.SignalingListener; import org.kurento.tutorial.showdatachannel.utils.UserSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.web.socket.CloseStatus; import org.springframework.web.socket.TextMessage; import org.springframework.web.socket.WebSocketSession; import org.springframework.web.socket.handler.TextWebSocketHandler; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonObject; import javax.annotation.PostConstruct; /** * Show Data Channel handler (application and media logic). * * @author Boni Garcia ([email protected]) * @author David Fernandez ([email protected]) * @since 6.1.1 */ @Slf4j @Component @RequiredArgsConstructor public class ShowDataChannelHandler extends TextWebSocketHandler { private static final Gson gson = new GsonBuilder().create(); private final ConcurrentHashMap<String, UserSession> users = new ConcurrentHashMap<>(); @Autowired private KurentoClient kurento; @Autowired private UserSession userSession; private MediaPipeline pipeline; private WebRtcEndpoint webRtcEndpoint; private SignalingListener signalingListener; private final SendMessageService sendMessageService; @PostConstruct protected void init() { log.info("init 들어오기 "); pipeline = kurento.createMediaPipeline(); webRtcEndpoint = new WebRtcEndpoint.Builder(pipeline).useDataChannels().build(); signalingListener = new SignalingListener(); //sendMessageService = new SendMessageService(); } //ws 연결 로그 @Override public void afterConnectionEstablished(WebSocketSession session) throws Exception { log.info("[Handler::afterConnectionEstablished] New WebSocket connection, sessionId: {}", session.getId()); } //ws 연결 끊겼을 경우 로그 @Override public void afterConnectionClosed(final WebSocketSession session, CloseStatus status) throws Exception { if (!status.equalsCode(CloseStatus.NORMAL)) { log.warn("[Handler::afterConnectionClosed] status: {}, sessionId: {}", status, session.getId()); } stop(session); } @Override public void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception { JsonObject jsonMessage = gson.fromJson(message.getPayload(), JsonObject.class); log.info("Incoming message: {}", jsonMessage); log.debug("Incoming message: {}", jsonMessage); switch (jsonMessage.get("id").getAsString()) { case "start": start(session, jsonMessage); //sendMessageService.start(session, jsonMessage); break; case "stop": { UserSession user = users.remove(session.getId()); if (user != null) { user.release(); } //sendMessageService.stopUserSession(session); break; } case "receive": receive(session, jsonMessage); //sendMessageService.receive(session, jsonMessage); break; case "onIceCandidate": { //sendMessageService.iceCandidate(session, jsonMessage); JsonObject jsonCandidate = jsonMessage.get("candidate").getAsJsonObject(); UserSession user = users.get(session.getId()); if (user != null) { IceCandidate candidate = new IceCandidate(jsonCandidate.get("candidate").getAsString(), jsonCandidate.get("sdpMid").getAsString(), jsonCandidate.get("sdpMLineIndex").getAsInt()); user.addCandidate(candidate); } break; } default: sendError(session, "Invalid message with id " + jsonMessage.get("id").getAsString()); break; } } private void start(final WebSocketSession session, JsonObject jsonMessage) { try { userSession.setMediaPipeline(pipeline); userSession.setWebRtcEndpoint(webRtcEndpoint); // ## 추가 webRtcEndpoint.connect(webRtcEndpoint); users.put(session.getId(), userSession); // ICE candidates webRtcEndpoint.addIceCandidateFoundListener(new EventListener<IceCandidateFoundEvent>() { @Override public void onEvent(IceCandidateFoundEvent iceCandidateFoundEvent) { JsonObject response = new JsonObject(); response.addProperty("id", "iceCandidate"); response.add("candidate", JsonUtils.toJsonObject(iceCandidateFoundEvent.getCandidate())); try { synchronized (session) { session.sendMessage(new TextMessage(response.toString())); } } catch (IOException e) { log.debug(e.getMessage()); } } }); //Media Logic KmsShowData kmsShowData = new KmsShowData.Builder(pipeline).build(); webRtcEndpoint.connect(kmsShowData); kmsShowData.connect(webRtcEndpoint); // SDP negotiation (offer and answer) String sdpOffer = jsonMessage.get("sdpOffer").getAsString(); initWebRtcEndpoint(session, webRtcEndpoint, sdpOffer); String sdpAnswer = webRtcEndpoint.processOffer(sdpOffer); JsonObject response = new JsonObject(); response.addProperty("id", "startResponse"); response.addProperty("sdpAnswer", sdpAnswer); log.info("[Handler::re] SDP Offer from browser to KMS:\n{}", sdpOffer); synchronized (session) { session.sendMessage(new TextMessage(response.toString())); } webRtcEndpoint.gatherCandidates(); } catch (Throwable t) { sendError(session, t.getMessage()); } } private void receive(final WebSocketSession session, JsonObject jsonMessage) { try { //MediaPipeline pipeline = kurento.createMediaPipeline(); //WebRtcEndpoint webRtcEndpoint = new WebRtcEndpoint.Builder(pipeline).useDataChannels().build(); userSession.setMediaPipeline(pipeline); userSession.setWebRtcEndpoint(webRtcEndpoint); // ## 추가 webRtcEndpoint.connect(webRtcEndpoint); users.put(session.getId(), userSession); // ICE candidates webRtcEndpoint.addIceCandidateFoundListener(new EventListener<IceCandidateFoundEvent>() { @Override public void onEvent(IceCandidateFoundEvent iceCandidateFoundEvent) { JsonObject response = new JsonObject(); response.addProperty("id", "iceCandidate"); response.add("candidate", JsonUtils.toJsonObject(iceCandidateFoundEvent.getCandidate())); try { synchronized (session) { session.sendMessage(new TextMessage(response.toString())); } } catch (IOException e) { log.debug(e.getMessage()); } } }); String sdpOffer = jsonMessage.get("sdpOffer").getAsString(); initWebRtcEndpoint(session, webRtcEndpoint, sdpOffer); String sdpAnswer = webRtcEndpoint.processOffer(sdpOffer); JsonObject response = new JsonObject(); response.addProperty("id", "receiveResponse"); response.addProperty("response", "accepted"); response.addProperty("sdpAnswer", sdpAnswer); log.info("[Receive Handler::re] SDP Offer from browser to KMS:\n{}", sdpOffer); synchronized (session) { session.sendMessage(new TextMessage(response.toString())); } webRtcEndpoint.gatherCandidates(); } catch (Throwable t) { sendError(session, t.getMessage()); } } private void sendError(WebSocketSession session, String message) { try { JsonObject response = new JsonObject(); response.addProperty("id", "error"); response.addProperty("message", message); session.sendMessage(new TextMessage(response.toString())); } catch (IOException e) { log.error("Exception sending message", e); } } //stop private void stop(final WebSocketSession session) { // Remove the user session and release all resources userSession = users.remove(session.getId()); if (userSession != null) { //MediaPipeline mediaPipeline = userSession.getMediaPipeline(); if (pipeline != null) { log.info("[Handler::stop] Release the Media Pipeline"); pipeline.release(); } } } private void initWebRtcEndpoint(final WebSocketSession session, final WebRtcEndpoint webRtcEp, String sdpOffer) { signalingListener.initBaseEventListeners(session, webRtcEp, "WebRtcEndpoint"); signalingListener.initWebRtcEventListeners(session, webRtcEp); } }
32.68
109
0.736397
82ef183895fe496311fed56704d741385d50b48b
1,454
package ru.job4j.bank; /** * @author Maxim Dick ([email protected]) * @version $Id$ * @since 0.1 */ public class User implements Comparable<User> { private String name; private String passport; public User() { } public User(String name, String passport) { this.name = name; this.passport = passport; } public String getName() { return name; } public String getPassport() { return passport; } @Override public String toString() { return String.format("User [Name: %s. Passport: %s.]", name, passport); } @Override public int hashCode() { return this.passport.hashCode(); } @Override public boolean equals(Object obj) { boolean valid = false; if (obj != null) { if (this == obj) { valid = true; } if (!valid && getClass() == obj.getClass()) { User user = (User) obj; if ((this.name != null && this.passport != null && user.name != null && user.passport != null)) { valid = this.name.equals(user.name) && this.passport.equals(user.passport); } } } return valid; } @Override public int compareTo(User user) { int valid = this.name.compareTo(user.name); return valid == 0 ? this.passport.compareTo(user.passport) : valid; } }
24.233333
113
0.537139
d4018b6d4b17b606fb2a40f669be5d11e50cbd57
1,754
package com.cym.model; import cn.craccd.sqlHelper.bean.BaseModel; import cn.craccd.sqlHelper.config.Table; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @ApiModel("额外参数") @Table public class Param extends BaseModel { @ApiModelProperty("所属反向代理id") String serverId; @ApiModelProperty("所属代理目标id") String locationId; @ApiModelProperty("所属负载均衡id") String upstreamId; @ApiModelProperty(hidden = true) String templateId; @ApiModelProperty("参数名") String name; @ApiModelProperty("参数值") String value; @ApiModelProperty(hidden = true) String templateValue; @ApiModelProperty(hidden = true) String templateName; public String getTemplateValue() { return templateValue; } public void setTemplateValue(String templateValue) { this.templateValue = templateValue; } public String getTemplateName() { return templateName; } public void setTemplateName(String templateName) { this.templateName = templateName; } public String getTemplateId() { return templateId; } public void setTemplateId(String templateId) { this.templateId = templateId; } public String getUpstreamId() { return upstreamId; } public void setUpstreamId(String upstreamId) { this.upstreamId = upstreamId; } public String getServerId() { return serverId; } public void setServerId(String serverId) { this.serverId = serverId; } public String getLocationId() { return locationId; } public void setLocationId(String locationId) { this.locationId = locationId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } }
18.463158
53
0.744014
a0901ee85ba8b463d69fcd77545628935642311f
5,221
package com.fasterxml.util.membuf; /* * Copyright Tatu Saloranta, 2011- */ /** * Shared allocator object, used by standardl {@link MemBuffer} implementations. * Handles allocation of new {@link Segment} instances, as well as sharing of * reusable segments (above and beyond simple reuse that individual * buffers can do). */ public abstract class SegmentAllocator<T extends Segment<T>> { /* /********************************************************************** /* Configuration /********************************************************************** */ /** * Length of segments to allocate. */ protected final int _segmentSize; /** * Maximum number of segments we will retain so that they may * be reused by buffer. Anything release beyond this number * will be freed. */ protected final int _maxReusableSegments; /** * Maximum number of segments that this allocator will allocate. */ protected final int _maxSegmentsToAllocate; /* /********************************************************************** /* State /********************************************************************** */ /** * Number of segments we have allocated for buffers and that they * have not yet released. */ protected int _bufferOwnedSegmentCount; /** * Number of segments we are holding for reuse. */ protected int _reusableSegmentCount; /* /********************************************************************** /* Life-cycle /********************************************************************** */ /** * Constructor for creating simple allocator instances. * Basic configuration is used to limit amount of memory that will * be used (by <code>maxSegments</code>), as well as degree to which * allocator can reuse released segments (to reduce churn by freeing * and reallocating segments, as segments typically use native * {@link java.nio.ByteBuffer}s that may be costly to allocate. * * @param segmentSize Length (in bytes) of segments to allocate * @param minSegmentsToRetain Number of segments that we will retain after * being released, for reuse; if 0, will not reuse any segments (although * individual buffers may still do local reuse) * @param maxSegments Maximum number of allocated (and not released) segments * allowed at any given point; * strictly limits maximum memory usage by all {@link MemBuffer}s that * use this allocator. */ public SegmentAllocator(int segmentSize, int minSegmentsToRetain, int maxSegments) { if (minSegmentsToRetain < 0 || minSegmentsToRetain > maxSegments) { throw new IllegalArgumentException("minSegmentsToRetain ("+minSegmentsToRetain +") must be at least 0; can not exceed maxSegments ("+maxSegments+")"); } _segmentSize = segmentSize; // should we pre-allocated segments? _maxReusableSegments = minSegmentsToRetain; _maxSegmentsToAllocate = maxSegments; _bufferOwnedSegmentCount = 0; _reusableSegmentCount = 0; } /* /********************************************************************** /* API /********************************************************************** */ /** * Accessor for length of individual segments that allocator will * allocate; length measured in units of backing primitive datatype. * * @return Length of segments in units of allocation (bytes, ints, longs etc) */ public final int getSegmentSize() { return _segmentSize; } // Used by unit tests /** * Accessor for number of segments that allocator is holding on to locally, * after being released by buffers. */ public final int getReusableSegmentCount() { return _reusableSegmentCount; } /** * Accessor for number of segments that have been allocated by buffers but * not released to allocator. */ public final int getBufferOwnedSegmentCount() { return _bufferOwnedSegmentCount; } /** * Accessor for checking maximum number of segments that allocator is allowed * to allocate for buffers. * * @since 0.9.1 */ public final int getMaxSegmentCount() { return _maxSegmentsToAllocate; } /** * Method that will try to allocate specified number of segments * (and exactly that number; no less). * If this can be done, segments are allocated and prepended into * given segment list; otherwise nothing is allocated and * null is returned. * * @param count Number of segments to allocate * * @return Head of segment list (with newly allocated entries as first * entries) if allocation succeeded; null if not */ public abstract T allocateSegments(int count, T segmentList); /** * Method called by {@link MemBuffer} instances when they have consumed * contents of a segment and do not want to hold on to it for local * reuse. */ public abstract void releaseSegment(T segToRelease); }
34.576159
91
0.587244
0c9cc7885b465d9b553078438830c2ea8cea68ea
3,908
/** * Copyright (C) 2013 Motown.IO ([email protected]) * * 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.motown.chargingstationconfiguration.viewmodel.persistence.repositories; import io.motown.chargingstationconfiguration.viewmodel.persistence.entities.ChargingStationType; import io.motown.chargingstationconfiguration.viewmodel.persistence.entities.Manufacturer; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.EntityNotFoundException; import javax.persistence.EntityTransaction; import java.util.List; public class ManufacturerRepository { private EntityManagerFactory entityManagerFactory; public Manufacturer createOrUpdate(Manufacturer manufacturer) { EntityManager em = getEntityManager(); EntityTransaction tx = null; try { tx = em.getTransaction(); tx.begin(); Manufacturer persistedManufacturer = em.merge(manufacturer); tx.commit(); return persistedManufacturer; } catch (Exception e) { if(tx != null && tx.isActive()) { tx.rollback(); } throw e; } finally { em.close(); } } public List<Manufacturer> findAll(int offset, int limit) { return getEntityManager().createQuery("SELECT m FROM Manufacturer m", Manufacturer.class) .setFirstResult(offset) .setMaxResults(limit) .getResultList(); } public Long getTotalNumberOfManufacturers() { return getEntityManager().createQuery("SELECT COUNT(m) FROM Manufacturer m", Long.class).getSingleResult(); } public Manufacturer findOne(Long id) { return findOne(id, getEntityManager()); } public void delete(Long id) { EntityManager em = getEntityManager(); Manufacturer manufacturer = findOne(id, em); List<ChargingStationType> chargingStationTypes = em.createQuery("SELECT cst FROM ChargingStationType AS cst where UPPER(cst.manufacturer.code) = UPPER(:manufacturerCode)", ChargingStationType.class) .setParameter("manufacturerCode", manufacturer.getCode()) .getResultList(); EntityTransaction tx = null; try { tx = em.getTransaction(); tx.begin(); for (ChargingStationType chargingStationType:chargingStationTypes) { em.remove(chargingStationType); } em.remove(manufacturer); tx.commit(); } catch (Exception e) { if(tx != null && tx.isActive()) { tx.rollback(); } throw e; } finally { em.close(); } } public void setEntityManagerFactory(EntityManagerFactory entityManagerFactory) { this.entityManagerFactory = entityManagerFactory; } private EntityManager getEntityManager() { return entityManagerFactory.createEntityManager(); } private Manufacturer findOne(Long id, EntityManager entityManager) { Manufacturer manufacturer = entityManager.find(Manufacturer.class, id); if (manufacturer != null) { return manufacturer; } throw new EntityNotFoundException(String.format("Unable to find manufacturer with id '%s'", id)); } }
33.689655
206
0.658649
6554d81743ad5e9d0fbdb7f6817b9696f496f656
1,770
package io.github.noeppi_noeppi.libx.impl.render; import net.minecraft.client.renderer.block.model.BakedQuad; import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.server.packs.resources.ResourceManager; import net.minecraft.server.packs.resources.SimplePreparableReloadListener; import net.minecraft.util.profiling.ProfilerFiller; import net.minecraftforge.client.event.RegisterClientReloadListenersEvent; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.WeakHashMap; public class BlockOverlayQuadCache { private static final WeakHashMap<TextureAtlasSprite, WeakHashMap<BakedQuad, BakedQuad>> quadCache = new WeakHashMap<>(); @Nullable public static BakedQuad get(BakedQuad source, TextureAtlasSprite sprite) { WeakHashMap<BakedQuad, BakedQuad> quads = quadCache.computeIfAbsent(sprite, k -> new WeakHashMap<>()); return quads.get(source); } public static void put(BakedQuad source, BakedQuad transformed) { WeakHashMap<BakedQuad, BakedQuad> quads = quadCache.computeIfAbsent(transformed.getSprite(), k -> new WeakHashMap<>()); quads.put(source, transformed); } public static void resourcesReload(RegisterClientReloadListenersEvent event) { event.registerReloadListener(new SimplePreparableReloadListener<Void>() { @Nonnull @Override protected Void prepare(@Nonnull ResourceManager rm, @Nonnull ProfilerFiller filler) { return null; } @Override protected void apply(@Nonnull Void obj, @Nonnull ResourceManager rm, @Nonnull ProfilerFiller filler) { quadCache.clear(); } }); } }
39.333333
127
0.719774
905b214db689a22a203cab95fd652cfb92b2451b
6,573
package ca.gc.aafc.seqdb.api.repository; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import java.io.IOException; import java.io.Serializable; import javax.inject.Inject; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import ca.gc.aafc.seqdb.api.dto.SampleDto; import ca.gc.aafc.seqdb.api.entities.Product; import ca.gc.aafc.seqdb.api.entities.Sample; import io.crnk.core.exception.ResourceNotFoundException; import io.crnk.core.queryspec.QuerySpec; import io.crnk.core.repository.ResourceRepository; public class SampleResourceRepositoryIT extends BaseRepositoryTest { private static final String TEST_SAMPLE_NAME = "sample name"; private static final String TEST_SAMPLE_VERSION = "sample version"; private static final String TEST_SAMPLE_EXPERIMENTER = "sample experimenter"; private static final String TEST_SAMPLE_NAME_CREATE = "sample name"; private static final String TEST_SAMPLE_VERSION_CREATE = "sample version"; private static final String TEST_SAMPLE_EXPERIMENTER_CREATE = "sample experimenter"; private static final String TEST_SAMPLE_NAME_UPDATE = "update name"; @Inject private ResourceRepository<SampleDto, Serializable> sampleRepository; private Sample testSample; /** * Generate a test sample entity. */ private Sample createTestSample() { testSample = new Sample(); testSample.setName(TEST_SAMPLE_NAME); testSample.setVersion(TEST_SAMPLE_VERSION); testSample.setExperimenter(TEST_SAMPLE_EXPERIMENTER); persist(testSample); return testSample; } @BeforeEach public void setup() { createTestSample(); } /** * Try to find the persisted entity and see if the data matches what was persisted. * Based on the createTestSample method. */ @Test public void findSample_whenNoFieldsAreSelected_sampleReturnedWithAllFields() { SampleDto sampleDto = sampleRepository.findOne( testSample.getId(), new QuerySpec(SampleDto.class) ); assertNotNull(sampleDto); assertEquals(testSample.getId(), sampleDto.getSampleId()); assertEquals(TEST_SAMPLE_NAME, sampleDto.getName()); assertEquals(TEST_SAMPLE_VERSION, sampleDto.getVersion()); assertEquals(TEST_SAMPLE_EXPERIMENTER, sampleDto.getExperimenter()); } /** * This test will try to retrieve the persisted entity, but this time only ask to retrieve * specific fields. In this case, the experimenter should be null since it's not being * requested specifically. */ @Test public void findSample_whenFieldsAreSelected_sampleReturnedWithSelectedFieldsOnly() { QuerySpec querySpec = new QuerySpec(SampleDto.class); querySpec.setIncludedFields(includeFieldSpecs("name", "version")); // Returned DTO must have correct values: selected fields are present, non-selected // fields are null. SampleDto sampleDto = sampleRepository.findOne( testSample.getId(), querySpec ); assertNotNull(sampleDto); assertEquals(testSample.getId(), sampleDto.getSampleId()); assertEquals(TEST_SAMPLE_NAME, sampleDto.getName()); assertEquals(TEST_SAMPLE_VERSION, sampleDto.getVersion()); assertNull(sampleDto.getExperimenter()); } /** * Test the sample repositories create method to ensure it can persisted and retrieved. */ @Test public void createSample_onSuccess_allFieldsHaveSetValueAfterPersisted() { String newSampleName = "new sample"; SampleDto newSample = new SampleDto(); newSample.setName(newSampleName); newSample.setVersion(TEST_SAMPLE_VERSION_CREATE); newSample.setExperimenter(TEST_SAMPLE_EXPERIMENTER_CREATE); SampleDto createdSample = sampleRepository.create(newSample); //DTO has the set value assertNotNull(createdSample.getSampleId()); assertEquals(newSampleName, createdSample.getName()); assertEquals(TEST_SAMPLE_VERSION_CREATE, createdSample.getVersion()); assertEquals(TEST_SAMPLE_EXPERIMENTER_CREATE, createdSample.getExperimenter()); //entity has the set value Sample sampleEntity = entityManager.find(Sample.class, createdSample.getSampleId()); assertNotNull(sampleEntity.getId()); assertEquals(newSampleName, sampleEntity.getName()); assertEquals(TEST_SAMPLE_VERSION_CREATE, sampleEntity.getVersion()); assertEquals(TEST_SAMPLE_EXPERIMENTER_CREATE, sampleEntity.getExperimenter()); } /** * This test will update a specific field for the sample, save it, then check if it updates the * test sample which has been persisted. */ @Test public void updateSample_whenSomeFieldsAreUpdated_sampleReturnedWithSelectedFieldsUpdated() { // Get the test product's DTO. QuerySpec querySpec = new QuerySpec(SampleDto.class); SampleDto sampleDto = sampleRepository.findOne(testSample.getId(), querySpec); // Change the DTO's desc value. sampleDto.setName(TEST_SAMPLE_NAME_UPDATE); // Save the DTO using the repository. sampleRepository.save(sampleDto); // Check that the entity has the new desc value. assertEquals(TEST_SAMPLE_NAME_UPDATE, testSample.getName()); } /** * Delete an existing product. It should not exist anymore if the delete was successful. */ @Test public void deleteProduct_onProductLookup_productNotFound() { sampleRepository.delete(testSample.getId()); assertNull(entityManager.find(Product.class, testSample.getId())); } /** * Test the behavior if the sample could not be found when trying to delete it. */ @Test public void deleteSample_onSampleNotFound_throwResourceNotFoundException() { assertThrows(ResourceNotFoundException.class, () -> sampleRepository.delete(1000)); } @Test public void listSample_APIResponse_schemaValidates() throws IOException { JsonSchemaAssertions.assertJsonSchema( BaseRepositoryTest.newClasspathResourceReader("static/json-schema/GETsampleJSONSchema.json"), BaseRepositoryTest.newClasspathResourceReader("realSampleResponse-all.json")); } @Test public void getSample_APIResponse_schemaValidates() throws IOException { JsonSchemaAssertions.assertJsonSchema( BaseRepositoryTest.newClasspathResourceReader("static/json-schema/sampleJSONSchema.json"), BaseRepositoryTest.newClasspathResourceReader("realSampleResponse.json")); } }
36.314917
101
0.757493
2bf8ae577afd4d1ae3a81ef38053ec34647d7655
902
package com.cezarykluczynski.stapi.server.literature.mapper; import com.cezarykluczynski.stapi.client.v1.rest.model.LiteratureBase; import com.cezarykluczynski.stapi.model.literature.dto.LiteratureRequestDTO; import com.cezarykluczynski.stapi.model.literature.entity.Literature; import com.cezarykluczynski.stapi.server.common.mapper.RequestSortRestMapper; import com.cezarykluczynski.stapi.server.configuration.MapstructConfiguration; import com.cezarykluczynski.stapi.server.literature.dto.LiteratureRestBeanParams; import org.mapstruct.Mapper; import java.util.List; @Mapper(config = MapstructConfiguration.class, uses = {RequestSortRestMapper.class}) public interface LiteratureBaseRestMapper { LiteratureRequestDTO mapBase(LiteratureRestBeanParams literatureRestBeanParams); LiteratureBase mapBase(Literature literature); List<LiteratureBase> mapBase(List<Literature> literatureList); }
39.217391
84
0.859202
557e8bff871e4ba2de138c227a5aa25464c0b250
691
package gov.samhsa.c2s.trypolicy.config; import lombok.Data; import org.hibernate.validator.constraints.NotEmpty; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; import javax.validation.Valid; import javax.validation.constraints.NotNull; import java.util.List; @Component @ConfigurationProperties(prefix = "c2s.try-policy") @Data public class TryPolicyProperties { @NotNull @Valid private List<SampleDocData> sampleUploadedDocuments; @Data public static class SampleDocData { @NotEmpty private String filePath; @NotEmpty private String documentName; } }
24.678571
75
0.765557
a9653eb4c6a490f81523df7cc4c9f534697ec373
1,892
package com.commercetools.service.ctp; import io.sphere.sdk.commands.UpdateAction; import io.sphere.sdk.payments.Payment; import io.sphere.sdk.payments.PaymentMethodInfo; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.List; import java.util.Optional; import java.util.concurrent.CompletionStage; public interface PaymentService { CompletionStage<Optional<Payment>> getById(@Nullable String id); /** * Fetch payment with by its {@link Payment#getInterfaceId()} and {@link PaymentMethodInfo#getPaymentInterface()}. * * @param paymentInterfaceName name of payment interface, like "PAYONE" * @param interfaceId the payment's {@link Payment#getInterfaceId()} * @return completion stage with optional found payment. */ CompletionStage<Optional<Payment>> getByPaymentInterfaceNameAndInterfaceId(@Nullable String paymentInterfaceName, @Nullable String interfaceId); /** * Apply {@code updateActions} to the {@code payment} * * @param payment <b>non-null</b> {@link Payment} to update * @param updateActions <b>non-null</b> list of {@link UpdateAction <Payment>} to apply to the {@code payment} * @return Completion stage with an instance of the updated payment */ CompletionStage<Payment> updatePayment(@Nonnull Payment payment, @Nullable List<UpdateAction<Payment>> updateActions); /** * Fetch and update payment by {@code paymentId}. If such payment does not exists - * throw {@link com.commercetools.exception.CtpServiceException}. * * @param paymentId payment to update * @param updateActions list of actions to apply if such a payment exists * @return stage with new update payment */ CompletionStage<Payment> updatePayment(@Nonnull String paymentId, @Nullable List<UpdateAction<Payment>> updateActions); }
42.044444
148
0.72833
9770dc0a1f8b8871b473ff91d1b2b1872c6a615a
1,391
package controllers.security; import model.dao.UserDao; import model.entity.User; import model.service.UserService; import org.springframework.beans.factory.annotation.Configurable; import org.springframework.security.authentication.AuthenticationProvider; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.stereotype.Service; import java.util.ArrayList; @Service @Configurable public class CustomAuthenticationProvider implements AuthenticationProvider { private UserDao userService = new UserService(); @Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { String password = authentication.getCredentials().toString(); User user = userService.get(password); if (user == null) { throw new BadCredentialsException("Incorrect password"); } else { return new UsernamePasswordAuthenticationToken(password, "", new ArrayList<>()); } } @Override public boolean supports(Class<?> aClass) { return (UsernamePasswordAuthenticationToken.class.isAssignableFrom(aClass)); } }
35.666667
102
0.780733
89cc0a5f372656abbda01e35a78805c953e362ef
858
package zerod.copy.domain; import javafixes.object.DataObject; import java.time.ZonedDateTime; import java.util.List; import static java.util.Collections.unmodifiableList; import static javafixes.common.CollectionUtil.newList; public class CopyProgress<Id, SuccessSummary> extends DataObject { public final Id id; public final ZonedDateTime created; public final ZonedDateTime lastUpdatedAt; public final CopyState currentState; public final List<CopyAttempt<SuccessSummary>> attempts; public CopyProgress(Id id, ZonedDateTime created, ZonedDateTime lastUpdatedAt, CopyState currentState, List<CopyAttempt> attempts) { this.id = id; this.created = created; this.lastUpdatedAt = lastUpdatedAt; this.currentState = currentState; this.attempts = unmodifiableList(newList(attempts)); } }
31.777778
136
0.758741
f5b5f1872d073668541fe145b0e36bbc1e1f56ff
4,533
package retroscope.datamodel.datastruct.struct; import retroscope.datamodel.datastruct.RQLSymbol; import retroscope.datamodel.datastruct.variables.DoubleRQLVariable; import retroscope.datamodel.datastruct.variables.LongRQLVariable; import retroscope.datamodel.datastruct.variables.StringRQLVariable; import retroscope.datamodel.parser.SetItems; import java.util.HashMap; import java.util.Map; public class RQLStruct extends RQLSymbol { private HashMap<String, RQLSymbol> elements; public RQLStruct() { super(); elements = new HashMap<>(); } public RQLStruct(String name) { super(name); this.elements = new HashMap<>(); } public RQLStruct(SetItems items) { super(); this.elements = new HashMap<>(); for (RQLSymbol s: items.getSetItems()) { elements.put(s.getName(), s); } } public RQLSymbol getElement(String name) { return elements.get(name); } @Override public void merge(RQLSymbol mergeSymbol) { } @Override public RQLSymbol clone() { RQLStruct clone = new RQLStruct(this.getName()); for (Map.Entry<String, RQLSymbol> s: elements.entrySet()) { clone.addElement(s.getValue().clone()); } return clone; } @Override public String toEmitRQLString() { StringBuilder sb = new StringBuilder(); if (getName() != null) { sb.append(this.getName()); sb.append('|'); } for (Long n : getNodeIDs()) { sb.append(n); sb.append(','); } if (sb.length() > 0) { sb.deleteCharAt(sb.length() - 1); sb.append(':'); } sb.append('['); for (Map.Entry<String, RQLSymbol> s: elements.entrySet()) { sb.append(s.getValue().toEmitRQLString()); sb.append(','); } sb.deleteCharAt(sb.length() - 1); sb.append(']'); return sb.toString(); } @Override public String toRQLString() { StringBuilder sb = new StringBuilder(); if (getName() != null) { sb.append(this.getName()); sb.append(':'); } sb.append('['); int l = sb.length(); for (Map.Entry<String, RQLSymbol> s: elements.entrySet()) { sb.append(s.getValue().toRQLString()); sb.append(','); } if (l != sb.length()) { sb.deleteCharAt(sb.length() - 1); } sb.append(']'); return sb.toString(); } @Override public String toValueString() { StringBuilder sb = new StringBuilder(); sb.append('['); int l = sb.length(); for (Map.Entry<String, RQLSymbol> s: elements.entrySet()) { sb.append(s.getValue().toRQLString()); sb.append(','); } if (l != sb.length()) { sb.deleteCharAt(sb.length() - 1); } sb.append(']'); return sb.toString(); } /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * Helpers to add vars *~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ public RQLStruct addElement(RQLSymbol e) { if (e.getName() != null) { elements.put(e.getName(), e); } return this; } public RQLStruct addValue(String name, long val) { LongRQLVariable var = new LongRQLVariable(name, val); addElement(var); return this; } public RQLStruct addValue(String name, double val) { DoubleRQLVariable var = new DoubleRQLVariable(name, val); addElement(var); return this; } public RQLStruct addValue(String name, String val) { StringRQLVariable var = new StringRQLVariable(name, val); addElement(var); return this; } /* * Equality is based on the value only and not on additional meta-data, such as name or nodeID */ public boolean equals(Object obj) { boolean eq = obj != null && obj instanceof RQLStruct; if (eq) { //TODO: fix this! Sometimes this results in a collision! eq = hashCode() == obj.hashCode(); } return eq; } public int hashCode() { int val = 0; for (Map.Entry<String, RQLSymbol> s: elements.entrySet()) { val = val << 4; val = val ^ (s.getValue().hashCode()); } return val; } }
27.143713
98
0.531436
42d76c26e9defda99e3eb27481807a9c6b9fb09c
2,198
/****************************************************************************** * Copyright (c) 2016 TypeFox and others. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0, * or the Eclipse Distribution License v. 1.0 which is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause ******************************************************************************/ package org.eclipse.lsp4j.jsonrpc.messages; import org.eclipse.lsp4j.jsonrpc.validation.NonNull; /** * A request message to describe a request between the client and the server. * Every processed request must send a response back to the sender of the * request. */ public class RequestMessage extends IdentifiableMessage { /** * The method to be invoked. */ @NonNull private String method; @NonNull public String getMethod() { return this.method; } public void setMethod(@NonNull String method) { this.method = method; } /** * The method's parameters. The object type depends on the chosen method. */ private Object params; public Object getParams() { return this.params; } public void setParams(Object params) { this.params = params; } @Override public boolean equals(final Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; if (!super.equals(obj)) return false; RequestMessage other = (RequestMessage) obj; if (this.method == null) { if (other.method != null) return false; } else if (!this.method.equals(other.method)) return false; if (this.params == null) { if (other.params != null) return false; } else if (!this.params.equals(other.params)) return false; return true; } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((this.method == null) ? 0 : this.method.hashCode()); result = prime * result + ((this.params == null) ? 0 : this.params.hashCode()); return result; } }
25.858824
81
0.635123
3ba42c7505b7de15ba77da1e0eb538651275fb71
2,579
package de.fau.amos.virtualledger.server.banking.adorsys.api.bankAccessEndpoint; import de.fau.amos.virtualledger.server.banking.model.BankAccessBankingModel; import de.fau.amos.virtualledger.server.banking.model.BankingException; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Component; import javax.inject.Inject; import java.util.ArrayList; import java.util.List; /** * Class that manages dummy data, but only for the test user. * So it isn't distinguished which user sends the request. * Make sure only the test user accesses this class. */ @Component @Qualifier("dummy") public class DummyBankAccessEndpoint implements BankAccessEndpoint { @Inject private DummyBankAccessEndpointRepository bankAccessEndpointRepository; private int number = 0; public DummyBankAccessEndpoint(DummyBankAccessEndpointRepository bankAccessEndpointRepository) { this.bankAccessEndpointRepository = bankAccessEndpointRepository; } public DummyBankAccessEndpoint() { } @Override public List<BankAccessBankingModel> getBankAccesses() throws BankingException { List<DummyBankAccessBankingModelEntity> dummyBankAccessBankingModelEntities = bankAccessEndpointRepository.findAll(); List<BankAccessBankingModel> bankAccessBankingModelList = new ArrayList<>(); for (DummyBankAccessBankingModelEntity dummyBankAccessBankingModelEntity : dummyBankAccessBankingModelEntities) { bankAccessBankingModelList.add(dummyBankAccessBankingModelEntity.transformToBankAccessBankingModel()); } return bankAccessBankingModelList; } @Override public BankAccessBankingModel addBankAccess(BankAccessBankingModel bankAccess) throws BankingException { BankAccessBankingModel bankAccessBankingModel = new BankAccessBankingModel(); bankAccessBankingModel.setId("TestID" + number + "_" + System.nanoTime()); bankAccessBankingModel.setBankLogin(bankAccess.getBankLogin()); bankAccessBankingModel.setBankCode(bankAccess.getBankCode()); bankAccessBankingModel.setBankName("TestBank" + number); bankAccessBankingModel.setPin(null); bankAccessBankingModel.setPassportState("testPassportState"); bankAccessEndpointRepository.save(new DummyBankAccessBankingModelEntity(bankAccessBankingModel)); number++; return bankAccessBankingModel; } public boolean existsBankAccess(String bankAccessId) { return bankAccessEndpointRepository.exists(bankAccessId); } }
40.936508
125
0.783249
e40a16fbb41899c26a708e67f235e77075891410
260
package com.github.sigalhu.function.unchecked; /** * @see java.util.function.IntToLongFunction * @author huxujun * @date 2019-04-20 */ @FunctionalInterface public interface UncheckedIntToLongFunction { long applyAsLong(int value) throws Exception; }
20
49
0.765385