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
2cc1ae789c19adcaa54e111f2e61620f144ba6b6
1,040
package io.quarkus.hibernate.orm.sql_load_script; import org.hamcrest.Matchers; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; import io.quarkus.hibernate.orm.MyEntity; import io.quarkus.test.QuarkusUnitTest; import io.restassured.RestAssured; public class ImportSqlLoadScriptTestCase { @RegisterExtension static QuarkusUnitTest runner = new QuarkusUnitTest() .setArchiveProducer(() -> ShrinkWrap.create(JavaArchive.class) .addClasses(MyEntity.class, SqlLoadScriptTestResource.class) .addAsResource("application-import-load-script-test.properties", "application.properties") .addAsResource("import.sql")); @Test public void testImportSqlLoadScriptTest() { String name = "import.sql load script entity"; RestAssured.when().get("/orm-sql-load-script/2").then().body(Matchers.is(name)); } }
38.518519
110
0.727885
9213754ab1b812b453033bae0c967eb7dcf8b992
5,178
/* * Copyright (c) 2017-2018 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tencentcloudapi.cdb.v20170320.models; import com.tencentcloudapi.common.AbstractModel; import com.google.gson.annotations.SerializedName; import com.google.gson.annotations.Expose; import java.util.HashMap; public class RollbackInstancesInfo extends AbstractModel{ /** * 云数据库实例ID 注意:此字段可能返回 null,表示取不到有效值。 */ @SerializedName("InstanceId") @Expose private String InstanceId; /** * 回档策略。可选值为:table、db、full;默认值为full。table - 急速回档模式,仅导入所选中表级别的备份和binlog,如有跨表操作,且关联表未被同时选中,将会导致回档失败,该模式下参数Databases必须为空;db - 快速模式,仅导入所选中库级别的备份和binlog,如有跨库操作,且关联库未被同时选中,将会导致回档失败;full - 普通回档模式,将导入整个实例的备份和binlog,速度较慢。 */ @SerializedName("Strategy") @Expose private String Strategy; /** * 数据库回档时间,时间格式为:yyyy-mm-dd hh:mm:ss */ @SerializedName("RollbackTime") @Expose private String RollbackTime; /** * 待回档的数据库信息,表示整库回档 注意:此字段可能返回 null,表示取不到有效值。 */ @SerializedName("Databases") @Expose private RollbackDBName [] Databases; /** * 待回档的数据库表信息,表示按表回档 注意:此字段可能返回 null,表示取不到有效值。 */ @SerializedName("Tables") @Expose private RollbackTables [] Tables; /** * Get 云数据库实例ID 注意:此字段可能返回 null,表示取不到有效值。 * @return InstanceId 云数据库实例ID 注意:此字段可能返回 null,表示取不到有效值。 */ public String getInstanceId() { return this.InstanceId; } /** * Set 云数据库实例ID 注意:此字段可能返回 null,表示取不到有效值。 * @param InstanceId 云数据库实例ID 注意:此字段可能返回 null,表示取不到有效值。 */ public void setInstanceId(String InstanceId) { this.InstanceId = InstanceId; } /** * Get 回档策略。可选值为:table、db、full;默认值为full。table - 急速回档模式,仅导入所选中表级别的备份和binlog,如有跨表操作,且关联表未被同时选中,将会导致回档失败,该模式下参数Databases必须为空;db - 快速模式,仅导入所选中库级别的备份和binlog,如有跨库操作,且关联库未被同时选中,将会导致回档失败;full - 普通回档模式,将导入整个实例的备份和binlog,速度较慢。 * @return Strategy 回档策略。可选值为:table、db、full;默认值为full。table - 急速回档模式,仅导入所选中表级别的备份和binlog,如有跨表操作,且关联表未被同时选中,将会导致回档失败,该模式下参数Databases必须为空;db - 快速模式,仅导入所选中库级别的备份和binlog,如有跨库操作,且关联库未被同时选中,将会导致回档失败;full - 普通回档模式,将导入整个实例的备份和binlog,速度较慢。 */ public String getStrategy() { return this.Strategy; } /** * Set 回档策略。可选值为:table、db、full;默认值为full。table - 急速回档模式,仅导入所选中表级别的备份和binlog,如有跨表操作,且关联表未被同时选中,将会导致回档失败,该模式下参数Databases必须为空;db - 快速模式,仅导入所选中库级别的备份和binlog,如有跨库操作,且关联库未被同时选中,将会导致回档失败;full - 普通回档模式,将导入整个实例的备份和binlog,速度较慢。 * @param Strategy 回档策略。可选值为:table、db、full;默认值为full。table - 急速回档模式,仅导入所选中表级别的备份和binlog,如有跨表操作,且关联表未被同时选中,将会导致回档失败,该模式下参数Databases必须为空;db - 快速模式,仅导入所选中库级别的备份和binlog,如有跨库操作,且关联库未被同时选中,将会导致回档失败;full - 普通回档模式,将导入整个实例的备份和binlog,速度较慢。 */ public void setStrategy(String Strategy) { this.Strategy = Strategy; } /** * Get 数据库回档时间,时间格式为:yyyy-mm-dd hh:mm:ss * @return RollbackTime 数据库回档时间,时间格式为:yyyy-mm-dd hh:mm:ss */ public String getRollbackTime() { return this.RollbackTime; } /** * Set 数据库回档时间,时间格式为:yyyy-mm-dd hh:mm:ss * @param RollbackTime 数据库回档时间,时间格式为:yyyy-mm-dd hh:mm:ss */ public void setRollbackTime(String RollbackTime) { this.RollbackTime = RollbackTime; } /** * Get 待回档的数据库信息,表示整库回档 注意:此字段可能返回 null,表示取不到有效值。 * @return Databases 待回档的数据库信息,表示整库回档 注意:此字段可能返回 null,表示取不到有效值。 */ public RollbackDBName [] getDatabases() { return this.Databases; } /** * Set 待回档的数据库信息,表示整库回档 注意:此字段可能返回 null,表示取不到有效值。 * @param Databases 待回档的数据库信息,表示整库回档 注意:此字段可能返回 null,表示取不到有效值。 */ public void setDatabases(RollbackDBName [] Databases) { this.Databases = Databases; } /** * Get 待回档的数据库表信息,表示按表回档 注意:此字段可能返回 null,表示取不到有效值。 * @return Tables 待回档的数据库表信息,表示按表回档 注意:此字段可能返回 null,表示取不到有效值。 */ public RollbackTables [] getTables() { return this.Tables; } /** * Set 待回档的数据库表信息,表示按表回档 注意:此字段可能返回 null,表示取不到有效值。 * @param Tables 待回档的数据库表信息,表示按表回档 注意:此字段可能返回 null,表示取不到有效值。 */ public void setTables(RollbackTables [] Tables) { this.Tables = Tables; } /** * Internal implementation, normal users should not use it. */ public void toMap(HashMap<String, String> map, String prefix) { this.setParamSimple(map, prefix + "InstanceId", this.InstanceId); this.setParamSimple(map, prefix + "Strategy", this.Strategy); this.setParamSimple(map, prefix + "RollbackTime", this.RollbackTime); this.setParamArrayObj(map, prefix + "Databases.", this.Databases); this.setParamArrayObj(map, prefix + "Tables.", this.Tables); } }
30.821429
233
0.693511
9461051526ba8d11a44e5c094df4789cd4ff0aa3
588
package march; import java.util.*; public class Offer48 { public int lengthOfLongestSubstring(String s) { char[] ch = new char[26]; int res = 0; int len = 0; for (int i = 0; i < s.length(); i++) { for (int j = 0; j < len; j++) { if(ch[j] == s.charAt(i)) { len -= (j+1); System.arraycopy(ch, j+1, ch, 0, len); break; } } ch[++len] = s.charAt(i); res = Math.max(res, len); } return res; } }
24.5
59
0.389456
14efa40b3d8cafafbe1e6d0015ac0848da4a08a7
486
package tue.shop4cf.integration.ngsild.dto; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import javax.validation.constraints.NotBlank; import java.util.Map; @Data @NoArgsConstructor @AllArgsConstructor public class WorkParametersProperty { @NotBlank @JsonProperty("type") private String type = "Property"; @JsonProperty("value") private Map<String,String> value; }
21.130435
53
0.783951
437fc76967e77a06ad6ed5d8ead47911474d1241
2,445
/* * Copyright 2017-2019 EPAM Systems, Inc. (https://www.epam.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.epam.pipeline.manager.python; import com.epam.pipeline.controller.vo.TaskGraphVO; import org.junit.Assert; import org.junit.Test; public class GraphReaderTest { @Test public void testParsing() { String output = "SimplePipeline(sample=&sample&, run_id=&run_id&)\n" + "IN:R1_001_fastqc.zip;L001_R2_001_fastqc.zip;AlignmentSummaryMetrics.txt;\n" + "OUT:\n" + "SimplePipeline(sample=&sample&, run_id=&run_id&) => " + "FastQC(sample=&sample&, run_id=&run_id&, first=True)\n" + "IN:L001_R1_001.fastq.gz;L001_R2_001.fastq.gz;\n" + "OUT:L001_R1_001_fastqc.zip;L001_R1_001_fastqc.html;\n" + "FastQC(sample=&sample&, run_id=&run_id&, first=True) => \n" + "IN:\n" + "OUT:L001_R1_001.fastq.gz;L001_R2_001.fastq.gz;\n" + "SimplePipeline(sample=&sample&, run_id=&run_id&) => " + "FastQC(sample=&sample&, run_id=&run_id&, first=False)\n" + "IN:L001_R1_001.fastq.gz;L001_R2_001.fastq.gz;\n" + "OUT:L001_R2_001_fastqc.zip;L001_R2_001_fastqc.html;\n" + "FastQC(sample=&sample&, run_id=&run_id&, first=False) => \n" + "IN:\n" + "OUT:L001_R1_001.fastq.gz;L001_R2_001.fastq.gz;\n" + "SimplePipeline(sample=&sample&, run_id=&run_id&) =>" + " AlignmentSummaryMetrics(sample=&sample&, run_id=&run_id&)\n" + "IN:sample.bai\n" + "OUT:AlignmentSummaryMetrics.txt\n"; GraphReader reader = new GraphReader(); TaskGraphVO graph = reader.createGraphFromScriptOutput(output); Assert.assertNotNull(graph); Assert.assertEquals(4, graph.getTasks().size()); } }
45.277778
94
0.622086
b676c7d1a5ffba9f29706159290cb7844caf348a
5,994
package deltix.qsrv.hf.tickdb.comm.server.aeron.download.multicast; import deltix.qsrv.hf.pub.ChannelPerformance; import deltix.qsrv.hf.pub.RawMessage; import deltix.qsrv.hf.tickdb.comm.TDBProtocol; import deltix.qsrv.hf.tickdb.comm.server.DownloadHandler; import deltix.qsrv.hf.tickdb.comm.server.aeron.AeronThreadTracker; import deltix.qsrv.hf.tickdb.comm.server.aeron.DXServerAeronContext; import deltix.qsrv.hf.tickdb.comm.server.aeron.download.unicast.AeronDownloadHandler; import deltix.qsrv.hf.tickdb.impl.ServerStreamImpl; import deltix.qsrv.hf.tickdb.pub.DXTickDB; import deltix.qsrv.hf.tickdb.pub.DXTickStream; import deltix.qsrv.hf.tickdb.pub.SelectionOptions; import deltix.qsrv.hf.tickdb.pub.query.InstrumentMessageSource; import deltix.util.concurrent.QuickExecutor; import deltix.util.io.UncheckedIOException; import deltix.util.security.DataFilter; import deltix.util.security.TimebaseAccessController; import deltix.util.time.TimeKeeper; import deltix.util.vsocket.VSChannel; import io.aeron.Aeron; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.security.Principal; /** * Reads content of cursor creation request, decides on client type and creates corresponding client (socket-based or Aeron-based). * * @author Alexei Osipov */ public class DownloadHandlerFactoryMulticast { public static void start(Principal user, VSChannel ds, DXTickDB db, QuickExecutor executor, TimebaseAccessController ac, int clientVersion, AeronThreadTracker aeronThreadTracker, DXServerAeronContext aeronContext, boolean isLocal) throws IOException { String aeronChannel = aeronContext.getMulticastChannel(); SelectionOptions options = new SelectionOptions(); options.live = true; options.raw = true; String remoteAddress = ds.getRemoteAddress(); DataFilter<RawMessage> filter = (ac != null ? ac.createFilter(user, remoteAddress) : null); DataOutputStream dout = ds.getDataOutputStream(); DataInputStream din = ds.getDataInputStream (); boolean binary = din.readBoolean (); DXTickStream[] streams; try { streams = DownloadHandler.readStreamList (ds, db); } catch (RuntimeException e) { dout.writeBoolean (false); AeronDownloadHandler.writeException(e, binary, dout); throw e; } if (streams.length != 1) { throw new IllegalArgumentException("Exactly one stream expected"); } ServerStreamImpl stream = (ServerStreamImpl) streams[0]; String streamKey = stream.getKey(); AeronMulticastStreamContext multicastContext; try { multicastContext = aeronContext.subscribeToMulticast(streamKey, (__, existingValue) -> { AeronMulticastStreamContext result; if (existingValue != null) { result = existingValue; } else { // TODO: We can open cursor in the the handling thread // TODO: Consider right start time long startTime = TimeKeeper.currentTime; InstrumentMessageSource cursor = stream.select(startTime, options); int aeronDataStreamId = aeronContext.getNextStreamId(); int aeronCommandStreamId = aeronContext.getNextStreamId(); Aeron aeron = aeronContext.getAeron(); result = new AeronMulticastStreamContext(cursor, aeronDataStreamId, aeronChannel); try { createAndStart(options, cursor, filter, binary, aeronThreadTracker, aeron, aeronDataStreamId, aeronCommandStreamId, aeronChannel, result); } catch (IOException e) { throw new UncheckedIOException(e); } } result.addSubscriber(ds); AeronMulticastDownloadControlTask controlTask = new AeronMulticastDownloadControlTask(executor, streamKey, ds, aeronContext, result.getCursorMetadata()); ds.setAvailabilityListener(controlTask.avlnr); return result; }); } catch (Exception e) { dout.writeBoolean (false); AeronDownloadHandler.writeException(e, binary, dout); dout.flush(); throw new RuntimeException(e); } dout.writeBoolean(true); // OK DownloadHandler.writeSelectedTransport(clientVersion, dout, TDBProtocol.TRANSPORT_TYPE_AERON); // If client is local then give him direct path to aeron directory so client can use it as is. // Otherwise send empty string. In this case client should figure out location of Aeron on it's machine himself. String aeronDir = isLocal ? aeronContext.getAeronDir() : ""; dout.writeUTF(aeronDir); dout.writeUTF(multicastContext.getAeronChannel()); //dout.writeUTF(aeronDir); dout.writeInt(multicastContext.getAeronDataStreamId()); dout.flush(); ds.setAutoflush(true); } public static void createAndStart(SelectionOptions options, InstrumentMessageSource cursor, DataFilter<RawMessage> filter, boolean binary, AeronThreadTracker aeronThreadTracker, Aeron aeron, int aeronDataStreamId, int aeronCommandStreamId, String aeronChannel, AeronMulticastStreamContext streamContext) throws IOException { AeronMulticastDownloadTask downloadTask = new AeronMulticastDownloadTask(aeron, aeronDataStreamId, aeronCommandStreamId, cursor, filter, binary, options.channelPerformance, aeronChannel, streamContext); Thread downloaderThread = aeronThreadTracker.newMulticastDownloaderThread(downloadTask, options.channelPerformance == ChannelPerformance.LATENCY_CRITICAL); // Empty runnable to trigger NextResult.UNAVAILABLE cursor.setAvailabilityListener(() -> {}); downloaderThread.start(); } }
47.952
328
0.697531
cc895a3139ccf5b7c7c67075a2c679fc7cc5d464
9,068
/* * COPYLEFT by 'Open Commons' & Park Jun-Hong All Rights Reserved. * * This file is generated under this project, "SystemPropertiesView". * * Date : 2012. 10. 2. 오후 6:04:19 * * Author: Park_Jun_Hong_(jhpark_at_ymtech_dot_co_dot_kr) * */ package open.eclipse.plugins.apps.command.shell; import java.util.Map.Entry; import java.util.Properties; import java.util.concurrent.ConcurrentSkipListMap; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.jface.viewers.TableViewerColumn; import org.eclipse.jface.viewers.ViewerCell; import org.eclipse.swt.SWT; import org.eclipse.swt.events.KeyAdapter; import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.events.MouseAdapter; import org.eclipse.swt.events.MouseEvent; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.TableColumn; import org.eclipse.swt.widgets.Text; import org.eclipse.wb.swt.ResourceManager; import open.eclipse.plugins.apps.command.utils.Utils; public class SystemPropertiesShell { protected Shell shell; private Text textFilter; private Table tableProperties; private TableViewer tblvwProperties; private TableColumn tblclmnKey; private TableViewerColumn tblclmnvwKey; private TableColumn tblclmnValue; private TableViewerColumn tblclmvwValue; private ConcurrentSkipListMap<String, String> properties = new ConcurrentSkipListMap<String, String>(); /** true: ascending order, false: descending order **/ private boolean orderDirectionKey = true; /** true: ascending order, false: descending order **/ private boolean orderDirectionValue = true; private SPSSorter sorter; private Button btnClearFilter; public SystemPropertiesShell() { sorter = new SPSSorter(SPSTableLabelProvider.INDEX_KEY, true); } private void sorting(int target, boolean direction) { sorter.setTarget(target); sorter.setDirection(direction); loadProperties(); } /** * Create contents of the window. */ protected void createContents() { shell = new Shell(); shell.setSize(640, 548); shell.setText("System Properteis"); shell.setLayout(new GridLayout(3, false)); Label lblFilter = new Label(shell, SWT.NONE); lblFilter.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); lblFilter.setText("Key &Filter: "); textFilter = new Text(shell, SWT.BORDER); textFilter.addKeyListener(new KeyAdapter() { @Override public void keyReleased(KeyEvent e) { loadProperties(); } }); textFilter.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); btnClearFilter = new Button(shell, SWT.NONE); btnClearFilter.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { textFilter.setText(""); loadProperties(); } }); btnClearFilter.setText("&Clear"); tblvwProperties = new TableViewer(shell, SWT.BORDER | SWT.FULL_SELECTION); tableProperties = tblvwProperties.getTable(); tableProperties.addMouseListener(new MouseAdapter() { @Override public void mouseDoubleClick(MouseEvent e) { ViewerCell cell = tblvwProperties.getCell(new Point(e.x, e.y)); if (cell != null) { String text = cell.getText(); if (text != null && !"".equals(text)) { Utils.copyToClipboard(text); } } } }); tableProperties.setLinesVisible(true); tableProperties.setHeaderVisible(true); tableProperties.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 3, 1)); // start - TableColumn about Key : 2012. 10. 7. 오후 5:31:37 tblclmnvwKey = new TableViewerColumn(tblvwProperties, SWT.NONE); tblclmnvwKey.setLabelProvider(new STSColumnLabelProvider()); tblclmnKey = tblclmnvwKey.getColumn(); tblclmnKey.setText("Key"); tblclmnKey.setImage(ResourceManager.getPluginImage("open.eclipse.plugins.apps.command", "icons/dir_no.gif")); tblclmnKey.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { orderDirectionKey = !orderDirectionKey; sorting(SPSTableLabelProvider.INDEX_KEY, orderDirectionKey); Image image = null; if (orderDirectionKey) { image = ResourceManager.getPluginImage("open.eclipse.plugins.apps.command", "icons/dir_ascending.gif"); } else { image = ResourceManager.getPluginImage("open.eclipse.plugins.apps.command", "icons/dir_descending.gif"); } tblclmnKey.setImage(image); tblclmnValue.setImage(ResourceManager.getPluginImage("open.eclipse.plugins.apps.command", "icons/dir_no.gif")); } }); tblclmnKey.setWidth(234); // end - TableColumn about Key : 2012. 10. 7. 오후 5:31:37 // start - TableColumn about Value : 2012. 10. 7. 오후 5:31:24 tblclmvwValue = new TableViewerColumn(tblvwProperties, SWT.NONE); tblclmnValue = tblclmvwValue.getColumn(); tblclmnValue.setText("Value"); tblclmnValue.setImage(ResourceManager.getPluginImage("open.eclipse.plugins.apps.command", "icons/dir_no.gif")); tblclmnValue.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { orderDirectionValue = !orderDirectionValue; sorting(SPSTableLabelProvider.INDEX_VALUE, orderDirectionValue); Image image = null; if (orderDirectionValue) { image = ResourceManager.getPluginImage("open.eclipse.plugins.apps.command", "icons/dir_ascending.gif"); } else { image = ResourceManager.getPluginImage("open.eclipse.plugins.apps.command", "icons/dir_descending.gif"); } tblclmnValue.setImage(image); tblclmnKey.setImage(ResourceManager.getPluginImage("open.eclipse.plugins.apps.command", "icons/dir_no.gif")); } }); tblclmnValue.setWidth(435); // end - TableColumn about Value : 2012. 10. 7. 오후 5:31:24 // start - set provider : 2012. 10. 7. 오후 5:26:14 tblvwProperties.setSorter(sorter); tblvwProperties.setLabelProvider(new SPSTableLabelProvider()); tblvwProperties.setContentProvider(new SPSContentProvider()); } private void loadProperties() { String filter = textFilter.getText().trim(); properties.clear(); Properties props = System.getProperties(); String key = null; String value = null; for (Entry<Object, Object> entry : props.entrySet()) { key = (String) entry.getKey(); value = (String) entry.getValue(); if (key.contains(filter)) { this.properties.put(key, value); } } tblclmnKey.setImage(ResourceManager.getPluginImage("open.eclipse.plugins.apps.command", "icons/dir_no.gif")); tblclmnValue.setImage(ResourceManager.getPluginImage("open.eclipse.plugins.apps.command", "icons/dir_no.gif")); tblvwProperties.setInput(properties); StringBuffer sb = new StringBuffer(); for (Entry<String, String> entry : properties.entrySet()) { sb.append(String.format(" %-20s = %s\n", entry.getKey(), entry.getValue())); } } /** * Open the window. */ public void open() { Display display = Display.getDefault(); createContents(); shell.open(); shell.layout(); loadProperties(); while (!shell.isDisposed()) { if (!display.readAndDispatch()) { display.sleep(); } } } /** * Launch the application. * * @param args */ public static void main(String[] args) { try { SystemPropertiesShell window = new SystemPropertiesShell(); window.open(); } catch (Exception e) { e.printStackTrace(); } } }
35.700787
119
0.625386
26d13ca253f503236b01ccdc541689ea3c9fd328
319
package cn.stylefeng.roses.system.modular.service; import cn.stylefeng.roses.system.modular.entity.BizMailInfo; import com.baomidou.mybatisplus.extension.service.IService; /** * <p> * 站内信 服务类 * </p> * * @author Hyer * @since 2019-11-26 */ public interface BizMailInfoService extends IService<BizMailInfo> { }
18.764706
67
0.742947
01bce573a9080c04001a86f5823ae2c90e287115
560
package creational.builder.meal.after.director; import creational.builder.meal.after.builders.entities.FastFoodMealBuilder; import creational.builder.meal.after.entities.FastFoodMeal; public class MealDirector { private FastFoodMealBuilder builder; public MealDirector(FastFoodMealBuilder builder) { this.builder = builder; } public void constructCombo() { builder.buildDrink(); builder.buildMain(); builder.buildSide(); builder.buildDessert(); builder.buildGift(); } public FastFoodMeal getCombo() { return builder.getMeal(); } }
21.538462
75
0.771429
b0f32fa7342fe80feca87cbdf7e4097ee8b4a850
1,124
package com.mysiteforme.admin.service; import com.baomidou.mybatisplus.plugins.Page; import com.baomidou.mybatisplus.service.IService; import com.mysiteforme.admin.entity.BlogTags; import java.util.List; import java.util.Map; /** * <p> * 博客标签 服务类 * </p> * * @author wangl * @since 2018-01-17 */ public interface BlogTagsService extends IService<BlogTags> { /** * 根据标签名称获取数量 * * @param name 标签名称 * @return */ Integer getCountByName(String name); /** * 新增标签 * * @param tags */ void saveTag(BlogTags tags); /** * 获取所有标签 * * @return */ List<BlogTags> listAll(); /** * 获取栏目对应的文章的所有标签 * * @param channelId 栏目ID * @return */ List<BlogTags> getTagsByChannelId(Long channelId); /** * 获取文章的所有标签 * * @param articleId 文章ID * @return */ List<BlogTags> getTagsByArticleId(Long articleId); void deleteThisTag(Long id); Page<BlogTags> selectTagsPage(Map<String, Object> map, Page<BlogTags> page); List<BlogTags> selectTagsPage(Map<String, Object> map); }
17.5625
80
0.61032
d5071c6ce15e0d93e4159351c93307bea07dc182
415
package onethreeseven.trajsuite.osm.model.tag; /** * For Shops that offer repair of goods (e.g. computers). * @author Luke Bermingham */ public class Repair extends OsmTag { public Repair(String value) { super(value); } @Override Specificity getSpecificityImpl() { return Specificity.SPECIFIC; } @Override public String getName() { return "repair"; } }
18.863636
57
0.638554
e388499fba90daf5426340af888c9b80b78641e4
6,208
package com.github.fmjsjx.libnetty.http.server.middleware; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.lang.reflect.Type; import java.util.Objects; import java.util.concurrent.CompletionStage; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import com.github.fmjsjx.libnetty.http.server.HttpRequestContext; import com.github.fmjsjx.libnetty.http.server.HttpResult; import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufAllocator; import io.netty.buffer.ByteBufInputStream; import io.netty.buffer.ByteBufOutputStream; /** * A {@link Middleware} provides a {@link JsonLibrary} to support JSON features. * * @since 1.1 * * @author MJ Fang * * @see Middleware * @see MiddlewareChain * @see JsonLibrary */ @Deprecated public class SupportJson implements Middleware { /** * Provides methods to support JSON features. * * @author MJ Fang * * @see Jackson2JsonLibrary * * @deprecated please use * {@link com.github.fmjsjx.libnetty.http.server.component.JsonLibrary} * instead */ @Deprecated public interface JsonLibrary { /** * The key of the {@link JsonLibrary} used in HTTP request context properties. * <p> * The value is * {@code com.github.fmjsjx.libnetty.http.server.middleware.SupportJson.JsonLibrary.class}. */ Class<JsonLibrary> KEY = JsonLibrary.class; /** * Read a JSON value from the given content. * * @param <T> the type of the value to be converted to * @param content a {@link ByteBuf} * @param valueType the common type of the value * @return the converted object */ <T> T read(ByteBuf content, Type valueType); /** * Write a JSON value into the a {@link ByteBuf}. * * @param alloc the {@link ByteBufAllocator} allocates {@link ByteBuf}s * @param value the value object * @return a {@code ByteBuf} */ ByteBuf write(ByteBufAllocator alloc, Object value); } /** * A runtime exception threw by a JSON encoder/decoder. * * @since 1.1 * * @author MJ Fang * * @deprecated please use * {@link com.github.fmjsjx.libnetty.http.server.component.JsonLibrary.JsonException} * instead */ @Deprecated public static class JsonException extends RuntimeException { private static final long serialVersionUID = 4697052174693197902L; /** * Constructs a new JSON exception with the specified detail message and cause. * * @param message the detail message * @param cause the cause */ public JsonException(String message, Throwable cause) { super(message, cause); } /** * Constructs a new JSON exception with the specified cause. * * @param cause the cause */ public JsonException(Throwable cause) { super(cause); } } /** * Implementation of {@link JsonLibrary} using {@code jackson2}. * * @author MJ Fang * * @deprecated please use * {@link com.github.fmjsjx.libnetty.http.server.component.Jackson2JsonLibrary} * instead */ @Deprecated public static class Jackson2JsonLibrary implements JsonLibrary { private static final ConcurrentMap<Type, com.fasterxml.jackson.databind.JavaType> cachedJavaTypes = new ConcurrentHashMap<>(); private final com.fasterxml.jackson.databind.ObjectMapper objectMapper; /** * Constructs a new {@link Jackson2JsonLibrary} with the specified * {@link com.fasterxml.jackson.databind.ObjectMapper}. * * @param objectMapper an {@code ObjectMapper} */ public Jackson2JsonLibrary(com.fasterxml.jackson.databind.ObjectMapper objectMapper) { this.objectMapper = Objects.requireNonNull(objectMapper, "objectMapper must not be null"); } /** * Constructs a new {@link Jackson2JsonLibrary} with the default * {@link com.fasterxml.jackson.databind.ObjectMapper}. */ public Jackson2JsonLibrary() { this(new com.fasterxml.jackson.databind.ObjectMapper() .setSerializationInclusion(com.fasterxml.jackson.annotation.JsonInclude.Include.NON_ABSENT) .disable(com.fasterxml.jackson.databind.DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)); } @Override @SuppressWarnings("unchecked") public <T> T read(ByteBuf content, Type valueType) { try (InputStream src = new ByteBufInputStream(content.duplicate())) { if (valueType instanceof Class) { if (com.fasterxml.jackson.databind.JsonNode.class.isAssignableFrom((Class<T>) valueType)) { return (T) objectMapper.readTree(src); } return objectMapper.readValue(src, (Class<T>) valueType); } com.fasterxml.jackson.databind.JavaType javaType = cachedJavaTypes.computeIfAbsent(valueType, objectMapper::constructType); return objectMapper.readValue(src, javaType); } catch (IOException e) { throw new JsonException(e.getMessage(), e); } } @Override public ByteBuf write(ByteBufAllocator alloc, Object value) { ByteBuf buf = alloc.buffer(); try (OutputStream out = new ByteBufOutputStream(buf)) { objectMapper.writeValue(out, value); return buf; } catch (IOException e) { buf.release(); throw new JsonException(e.getMessage(), e); } } } @Override public CompletionStage<HttpResult> apply(HttpRequestContext ctx, MiddlewareChain next) { return next.doNext(ctx); } }
33.021277
134
0.613563
6aa2b134d347d7bc4bfe6c8f06db1999ff2cc22a
75
package com.slang.backend.vm.core; public class MemoryDedicated { }
12.5
35
0.72
134dc31ed605a59deb36cb827fba09e7a9f4cac3
1,727
/* * 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.chemistry.opencmis.server.shared; import javax.servlet.http.HttpServletRequest; import org.apache.chemistry.opencmis.commons.server.TempStoreOutputStream; /** * A {@link TempStoreOutputStream} that knows about the HTTP request */ public abstract class RequestAwareTempStoreOutputStream extends TempStoreOutputStream { /** * Sets the HTTP request object. * * This method is usually be called right after creation of this object. It * might never be called if the HTTP request object is unknown or this * object is not used in the context of a HTTP request. * * @param request * the HTTP request object or {@code null} if the HTTP request * object is unknown or this object is not used in the context of * a HTTP request */ public abstract void setHttpServletRequest(HttpServletRequest request); }
39.25
87
0.726694
5b13df76e7c0ceb8c853e40eb91a04eb61f32a9c
2,519
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.remoting; import org.jboss.as.controller.AttributeDefinition; import org.jboss.as.controller.OperationStepHandler; import org.jboss.as.controller.SimpleResourceDefinition; import org.jboss.as.controller.capability.RuntimeCapability; import org.jboss.as.controller.registry.ManagementResourceRegistration; /** * @author Jaikiran Pai */ abstract class AbstractOutboundConnectionResourceDefinition extends SimpleResourceDefinition { static final String OUTBOUND_CONNECTION_CAPABILITY_NAME = "org.wildfly.remoting.outbound-connection"; static final String OUTBOUND_SOCKET_BINDING_CAPABILITY_NAME = "org.wildfly.network.outbound-socket-binding"; static final RuntimeCapability<Void> OUTBOUND_CONNECTION_CAPABILITY = RuntimeCapability.Builder.of(OUTBOUND_CONNECTION_CAPABILITY_NAME, true, AbstractOutboundConnectionService.class) .build(); protected AbstractOutboundConnectionResourceDefinition(final Parameters parameters) { super(parameters.addCapabilities(OUTBOUND_CONNECTION_CAPABILITY)); } public abstract void registerChildren(ManagementResourceRegistration resourceRegistration); /** * Returns the write attribute handler for the <code>attribute</code> * @param attribute The attribute for which the write operation handler is being queried * @return the handler */ protected abstract OperationStepHandler getWriteAttributeHandler(final AttributeDefinition attribute); }
44.192982
124
0.779277
4c60a682276bcfd3f89694d210d3f1b5bed11d04
1,722
package org.cucina.engine.definition; import org.cucina.engine.ExecutionContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Collection; /** * <code>Decision</code>s are states that exit through one of the configured * list of {@link Transition Transitions} based on the * {@link Check Conditions} assigned to those {@link Transition Transitions}. * * @author Rob Harrop */ public class Decision extends AbstractState { private static final Logger LOG = LoggerFactory.getLogger(Decision.class); /** * JAVADOC * * @return JAVADOC */ public Transition getDefaultTransition() { return null; } /** * JAVADOC * * @param from JAVADOC * @param executionContext JAVADOC */ public void enter(Transition from, ExecutionContext executionContext) { super.enter(from, executionContext); leave((Transition) null, executionContext); } /** * JAVADOC * * @param transition JAVADOC * @param executionContext JAVADOC */ protected void leaveInternal(Transition transition, ExecutionContext executionContext) { if (transition != null) { throw new IllegalArgumentException( "Cannot specify a transition when leaving a Decision state."); } Collection<Transition> transitions = getEnabledTransitions(executionContext); for (Transition exitTransition : transitions) { if (LOG.isDebugEnabled()) { LOG.debug("Evaluating transition:" + exitTransition); } if (exitTransition.isEnabled(executionContext)) { exitTransition.occur(executionContext); fireLeaveActions(executionContext); return; } } throw new IllegalStateException("Cannot leave Decision state - no transitions are active."); } }
24.253521
94
0.723577
03b00652aa2572a241c9e1db7a37f858fea7e20a
3,141
package com.wxb.mall.product.app; import com.wxb.common.utils.PageUtils; import com.wxb.common.utils.R; import com.wxb.common.valid.AddGroup; import com.wxb.common.valid.UpdateGroup; import com.wxb.common.valid.UpdateStatusGroup; import com.wxb.mall.product.entity.BrandEntity; import com.wxb.mall.product.service.BrandService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import java.util.Arrays; import java.util.List; import java.util.Map; /** * 品牌 * * @author leifengyang * @email [email protected] * @date 2019-10-01 22:50:32 */ @RestController @RequestMapping("product/brand") public class BrandController { @Autowired private BrandService brandService; /** * 列表 */ @RequestMapping("/list") //@RequiresPermissions("product:brand:list") public R list(@RequestParam Map<String, Object> params) { PageUtils page = brandService.queryPage (params); return R.ok ().put ("page", page); } /** * 信息 */ @RequestMapping("/info/{brandId}") //@RequiresPermissions("product:brand:info") public R info(@PathVariable("brandId") Long brandId) { BrandEntity brand = brandService.getById (brandId); return R.ok ().put ("brand", brand); } @GetMapping("/infos") public R info(@PathVariable("brandIds") List<Long> brandId) { List<BrandEntity> brand = brandService.getBrandsByIds (brandId); return R.ok ().put ("brand", brand); } /** * 保存 */ @RequestMapping("/save") //@RequiresPermissions("product:brand:save") public R save(@Validated({AddGroup.class}) @RequestBody BrandEntity brand/*,BindingResult result*/) { // if(result.hasErrors()){ // Map<String,String> map = new HashMap<>(); // //1、获取校验的错误结果 // result.getFieldErrors().forEach((item)->{ // //FieldError 获取到错误提示 // String message = item.getDefaultMessage(); // //获取错误的属性的名字 // String field = item.getField(); // map.put(field,message); // }); // // return R.error(400,"提交的数据不合法").put("data",map); // }else { // // } brandService.save (brand); return R.ok (); } /** * 修改 */ @RequestMapping("/update") public R update(@Validated(UpdateGroup.class) @RequestBody BrandEntity brand) { brandService.updateDetail (brand); return R.ok (); } /** * 修改状态 */ @RequestMapping("/update/status") //@RequiresPermissions("product:brand:update") public R updateStatus(@Validated(UpdateStatusGroup.class) @RequestBody BrandEntity brand) { brandService.updateById (brand); return R.ok (); } /** * 删除 */ @RequestMapping("/delete") //@RequiresPermissions("product:brand:delete") public R delete(@RequestBody Long[] brandIds) { brandService.removeByIds (Arrays.asList (brandIds)); return R.ok (); } }
25.330645
105
0.618911
02f543b86197f36afdb08da88e1e6e2d7a84b88c
2,321
package org.iguanatool.search.evolve.mutation; import org.iguanatool.search.randomnumbergenerator.RandomNumberGenerator; import org.iguanatool.search.solution.NumericalSolution; import org.iguanatool.search.solution.NumericalSolutionType; /** * User: phil * Date: 14-Feb-2006 * Time: 10:55:09 */ public class GaussianMutation extends NumericalMutation { private double standardDeviation = 1.0; private double domainUnits; private boolean haveDomainUnits = false; private double domainPercentage; private boolean haveDomainPercentage = false; public GaussianMutation(RandomNumberGenerator r) { super(r); } public GaussianMutation(RandomNumberGenerator r, double standardDeviation) { super(r); this.standardDeviation = standardDeviation; } public void setDomainUnits(double domainUnits) { this.domainUnits = domainUnits; this.haveDomainUnits = true; this.haveDomainPercentage = false; } public void setDomainPercentage(double domainPercentage) { this.domainPercentage = domainPercentage; this.haveDomainPercentage = true; this.haveDomainUnits = false; } protected void mutateGene(NumericalSolution ind, int locus) { if (haveDomainPercentage) { NumericalSolutionType species = (NumericalSolutionType) ind.getType(); double standardDeviation = (species.getMax(locus) - species.getMin(locus)) * Math.pow(10, species.getAccuracy(locus)); standardDeviation *= domainPercentage; mutateGene(ind, locus, standardDeviation); } else if (haveDomainUnits) { int precision = ((NumericalSolutionType) ind.getType()).getAccuracy(locus); double standardDeviation = Math.pow(10, -precision) * domainUnits; mutateGene(ind, locus, standardDeviation); } else { mutateGene(ind, locus, standardDeviation); } } private void mutateGene(NumericalSolution ind, int locus, double standardDeviation) { ind.setElement(locus, ind.getRawElement(locus) + r.nextGaussian(standardDeviation)); } }
35.166667
93
0.64972
9e0dd55a73345059945d773e7e906accfcd8bc6b
7,871
package com.lyhome.ETNews.fragment; import android.app.Fragment; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; import com.lyhome.ETNews.MyApplication; import com.lyhome.ETNews.activity.DetailActivity; import com.lyhome.ETNews.adapter.MyRecyclerAdapter; import com.lyhome.ETNews.bean.Constant; import com.lyhome.ETNews.bean.NewsItem; import com.lyhome.ETNews.biz.NewsBiz; import com.lyhome.ETNews.biz.OnparseListener; import com.lyhome.ETNews.util.ACache; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; /** * Created by lyhome on 2015/11/22. */ public class JoyFragment extends Fragment { private static final String TAG = "Fragment_Joy"; private SwipeRefreshLayout mRefreshLayout; private RecyclerView mRecyclerView; private MyRecyclerAdapter mAdapter; private Button reloadBtn; private Handler mHandler = new Handler(); private ACache mACache; final List<NewsItem> itemList = new ArrayList<>(); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mACache = ACache.get(getActivity()); } public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); initView(view); setListener(); loadCache(); mHandler.postDelayed(new Runnable() { @Override public void run() { setViewVisible(true, true, false); loadData(); } }, 1000); } public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(com.lyhome.ETNews.R.layout.fragment_joy, container, false); } private void loadCache() { if (covertToList()) { if (mAdapter != null) { mAdapter.notifyDataSetChanged(); } } } private void setListener() { mRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { loadData(); } }); } private void initView(View view) { // 下拉刷新 mRefreshLayout = (SwipeRefreshLayout) view.findViewById(com.lyhome.ETNews.R.id.srl_content); mRefreshLayout.setColorSchemeResources(com.lyhome.ETNews.R.color.colorPrimary, com.lyhome.ETNews.R.color.secondColor, com.lyhome.ETNews.R.color.purple, com.lyhome.ETNews.R.color.blue); // 主要内容 mRecyclerView = (RecyclerView) view.findViewById(com.lyhome.ETNews.R.id.recycler_content); mAdapter = new MyRecyclerAdapter(getActivity(), itemList); LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false); mRecyclerView.setLayoutManager(layoutManager); mRecyclerView.setItemAnimator(new DefaultItemAnimator()); mAdapter.setOnItemClickListener(new MyRecyclerAdapter.OnItemClickListener() { @Override public void onItemClick(View view, int position) { Intent intent = new Intent(getActivity(), DetailActivity.class); intent.putExtra(Constant.NEWS_ITEM, itemList.get(position)); startActivity(intent); } }); mRecyclerView.setAdapter(mAdapter); reloadBtn = (Button) view.findViewById(com.lyhome.ETNews.R.id.refresh_btn); reloadBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { loadData(); } }); } public void loadData() { StringRequest stringrequest = new StringRequest(Constant.JOY_URL, new Response.Listener<String>() { @Override public void onResponse(String response) { NewsBiz.getFeed(response, new OnparseListener() { @Override public void onParseSuccess(List<NewsItem> list) { if (list != null) { itemList.clear(); itemList.addAll(list); if (mAdapter != null) { mAdapter.updateData(itemList); } setViewVisible(false, true, false); mACache.put(TAG, convertToJson(itemList)); } else { } } @Override public void onParseFailed() { setViewVisible(false, false, true); } }); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError volleyError) { if (itemList == null) { setViewVisible(false, false, true); } else { setViewVisible(false, true, false); } } }); stringrequest.setTag(TAG); MyApplication.getRequestQueue().add(stringrequest); } public void setViewVisible(boolean mSrl, boolean mRecyclerView, boolean reloadBtn) { if (mSrl) { if (this.mRefreshLayout != null) { this.mRefreshLayout.setRefreshing(true); } } else { if (this.mRefreshLayout != null) { this.mRefreshLayout.setRefreshing(false); } } if (mRecyclerView) { if (this.mRecyclerView != null) { this.mRecyclerView.setVisibility(View.VISIBLE); } } else { if (this.mRecyclerView != null) { this.mRecyclerView.setVisibility(View.GONE); } } if (reloadBtn) { if (this.reloadBtn != null) { this.reloadBtn.setVisibility(View.VISIBLE); } } else { if (this.reloadBtn != null) { this.reloadBtn.setVisibility(View.GONE); } } } public boolean covertToList() { JSONObject jsonObj = mACache.getAsJSONObject(TAG); if (jsonObj != null) { try { JSONArray feedlistAr = jsonObj.getJSONArray("feed_list"); itemList.clear(); for (int i = 0; i < feedlistAr.length(); i++) { JSONObject feedlist = feedlistAr.getJSONObject(i); NewsItem item = NewsItem.parse(feedlist); itemList.add(item); } } catch (JSONException e) { e.printStackTrace(); } return true; } return false; } private JSONObject convertToJson(List<NewsItem> item_list) { JSONObject outJsonObj = new JSONObject(); JSONArray itemJsonAr = new JSONArray(); for (NewsItem feedlistItem : item_list) { JSONObject jsonObj = feedlistItem.toJSONObj(); itemJsonAr.put(jsonObj); } try { outJsonObj.put("feed_list", itemJsonAr); } catch (JSONException e) { e.printStackTrace(); } return outJsonObj; } }
33.926724
192
0.588616
d739f841a86ef5da17d1ff72c52cc39f826e8869
764
/** */ package org.sculptor.sculptormetamodel.impl; import org.eclipse.emf.ecore.EClass; import org.sculptor.sculptormetamodel.Parameter; import org.sculptor.sculptormetamodel.SculptormetamodelPackage; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Parameter</b></em>'. * <!-- end-user-doc --> * * @generated */ public class ParameterImpl extends DomainObjectTypedElementImpl implements Parameter { /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected ParameterImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return SculptormetamodelPackage.Literals.PARAMETER; } } //ParameterImpl
20.105263
86
0.667539
4c2562e27b10bd82ecdea3016eb030e35750a375
472
package org.apache.http.client; import org.apache.http.HttpHost; import org.apache.http.auth.AuthScheme; public interface AuthCache { void put(HttpHost paramHttpHost, AuthScheme paramAuthScheme); AuthScheme get(HttpHost paramHttpHost); void remove(HttpHost paramHttpHost); void clear(); } /* Location: /mnt/r/ConTenDoViewer.jar!/org/apache/http/client/AuthCache.class * Java compiler version: 6 (50.0) * JD-Core Version: 1.1.3 */
23.6
91
0.716102
83632d0571b441897198b90ad3e1f528ba0172a4
633
package fred.angel.com.mgank.component; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.provider.ContactsContract; import android.support.v4.app.LoaderManager; import android.support.v4.content.Loader; /** * @author chenqiang */ public class ContactDataSource implements LoaderManager.LoaderCallbacks<Cursor> { @Override public Loader onCreateLoader(int id, Bundle args) { return null; } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor data) { } @Override public void onLoaderReset(Loader loader) { } }
16.230769
81
0.725118
7b3880f88e94e615fafc08d48d27d1927833ad59
1,116
package me.zhujiajie.exam; public class updataInfo { int versionCode; float versionName; String updateContent; String apkURL; public int getVersionCode() { return versionCode; } public void setVersionCode(int versionCode) { this.versionCode = versionCode; } public float getVersionName() { return versionName; } public void setVersionName(float versionName) { this.versionName = versionName; } public String getUpdateContent() { return updateContent; } public void setUpdateContent(String updateContent) { this.updateContent = updateContent; } public String getApkURL() { return apkURL; } public void setApkURL(String apkURL) { this.apkURL = apkURL; } @Override public String toString() { return "updataInfo{" + "versionCode=" + versionCode + ", versionName=" + versionName + ", updateContent='" + updateContent + '\'' + ", apkURL='" + apkURL + '\'' + '}'; } }
21.461538
60
0.577061
962d92a27d66e857f7b0377d915996f5b6f63cc6
9,063
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.platform.mbean; import static org.jboss.as.platform.mbean.PlatformMBeanUtil.escapeMBeanName; import java.lang.management.ManagementFactory; import java.lang.management.MemoryPoolMXBean; import org.jboss.as.controller.OperationContext; import org.jboss.as.controller.OperationFailedException; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.descriptions.ModelDescriptionConstants; import org.jboss.as.controller.operations.validation.LongRangeValidator; import org.jboss.as.controller.operations.validation.ParametersValidator; import org.jboss.as.platform.mbean.logging.PlatformMBeanLogger; import org.jboss.dmr.ModelNode; /** * Handles read-attribute and write-attribute for the resource representing {@link java.lang.management.MemoryPoolMXBean}. * * @author Brian Stansberry (c) 2011 Red Hat Inc. */ class MemoryPoolMXBeanAttributeHandler extends AbstractPlatformMBeanAttributeHandler { static final MemoryPoolMXBeanAttributeHandler INSTANCE = new MemoryPoolMXBeanAttributeHandler(); private final ParametersValidator usageValidator = new ParametersValidator(); private MemoryPoolMXBeanAttributeHandler() { usageValidator.registerValidator(ModelDescriptionConstants.VALUE, new LongRangeValidator(0)); } @Override protected void executeReadAttribute(OperationContext context, ModelNode operation) throws OperationFailedException { final String memPoolName = PathAddress.pathAddress(operation.require(ModelDescriptionConstants.OP_ADDR)).getLastElement().getValue(); final String name = operation.require(ModelDescriptionConstants.NAME).asString(); try { if ((PlatformMBeanConstants.OBJECT_NAME.getName().equals(name)) || MemoryPoolResourceDefinition.MEMORY_POOL_READ_ATTRIBUTES.contains(name) || MemoryPoolResourceDefinition.MEMORY_POOL_READ_WRITE_ATTRIBUTES.contains(name) || MemoryPoolResourceDefinition.MEMORY_POOL_METRICS.contains(name)) { MemoryPoolMXBean memoryPoolMXBean = getMemoryPoolMXBean(memPoolName); storeResult(name, context.getResult(), memoryPoolMXBean, memPoolName); } else { // Shouldn't happen; the global handler should reject throw unknownAttribute(operation); } } catch (UnsupportedOperationException e) { throw new OperationFailedException(e.toString()); } } @Override protected void executeWriteAttribute(OperationContext context, ModelNode operation) throws OperationFailedException { final String memPoolName = PathAddress.pathAddress(operation.require(ModelDescriptionConstants.OP_ADDR)).getLastElement().getValue(); MemoryPoolMXBean memoryPoolMXBean = getMemoryPoolMXBean(memPoolName); final String name = operation.require(ModelDescriptionConstants.NAME).asString(); try { if (PlatformMBeanConstants.USAGE_THRESHOLD.equals(name)) { context.getServiceRegistry(true); //to trigger auth usageValidator.validate(operation); memoryPoolMXBean.setUsageThreshold(operation.require(ModelDescriptionConstants.VALUE).asLong()); } else if (PlatformMBeanConstants.COLLECTION_USAGE_THRESHOLD.equals(name)) { context.getServiceRegistry(true); //to trigger auth usageValidator.validate(operation); memoryPoolMXBean.setCollectionUsageThreshold(operation.require(ModelDescriptionConstants.VALUE).asLong()); } else if (MemoryPoolResourceDefinition.MEMORY_POOL_READ_WRITE_ATTRIBUTES.contains(name)) { // Bug throw PlatformMBeanLogger.ROOT_LOGGER.badWriteAttributeImpl(name); } else { // Shouldn't happen; the global handler should reject throw unknownAttribute(operation); } } catch (SecurityException e) { throw new OperationFailedException(e.toString()); } catch (UnsupportedOperationException e) { throw new OperationFailedException(e.toString()); } } static void storeResult(final String name, final ModelNode store, final MemoryPoolMXBean memoryPoolMXBean, final String memPoolName) { if (PlatformMBeanConstants.OBJECT_NAME.getName().equals(name)) { final String objName = PlatformMBeanUtil.getObjectNameStringWithNameKey(ManagementFactory.MEMORY_POOL_MXBEAN_DOMAIN_TYPE, memPoolName); store.set(objName); } else if (ModelDescriptionConstants.NAME.equals(name)) { store.set(escapeMBeanName(memoryPoolMXBean.getName())); } else if (PlatformMBeanConstants.TYPE.equals(name)) { store.set(memoryPoolMXBean.getType().name()); } else if (PlatformMBeanConstants.USAGE.equals(name)) { final ModelNode usage = PlatformMBeanUtil.getDetypedMemoryUsage(memoryPoolMXBean.getUsage()); store.set(usage); } else if (PlatformMBeanConstants.PEAK_USAGE.equals(name)) { final ModelNode usage = PlatformMBeanUtil.getDetypedMemoryUsage(memoryPoolMXBean.getPeakUsage()); store.set(usage); } else if (PlatformMBeanConstants.VALID.getName().equals(name)) { store.set(memoryPoolMXBean.isValid()); } else if (PlatformMBeanConstants.MEMORY_MANAGER_NAMES.equals(name)) { store.setEmptyList(); for (String mgr : memoryPoolMXBean.getMemoryManagerNames()) { store.add(escapeMBeanName(mgr)); } } else if (PlatformMBeanConstants.USAGE_THRESHOLD.equals(name)) { store.set(memoryPoolMXBean.getUsageThreshold()); } else if (PlatformMBeanConstants.USAGE_THRESHOLD_EXCEEDED.equals(name)) { store.set(memoryPoolMXBean.isUsageThresholdExceeded()); } else if (PlatformMBeanConstants.USAGE_THRESHOLD_COUNT.equals(name)) { store.set(memoryPoolMXBean.getUsageThresholdCount()); } else if (PlatformMBeanConstants.USAGE_THRESHOLD_SUPPORTED.equals(name)) { store.set(memoryPoolMXBean.isUsageThresholdSupported()); } else if (PlatformMBeanConstants.COLLECTION_USAGE_THRESHOLD.equals(name)) { store.set(memoryPoolMXBean.getCollectionUsageThreshold()); } else if (PlatformMBeanConstants.COLLECTION_USAGE_THRESHOLD_EXCEEDED.equals(name)) { store.set(memoryPoolMXBean.isCollectionUsageThresholdExceeded()); } else if (PlatformMBeanConstants.COLLECTION_USAGE_THRESHOLD_COUNT.equals(name)) { store.set(memoryPoolMXBean.getCollectionUsageThresholdCount()); } else if (PlatformMBeanConstants.COLLECTION_USAGE_THRESHOLD_SUPPORTED.equals(name)) { store.set(memoryPoolMXBean.isCollectionUsageThresholdSupported()); } else if (PlatformMBeanConstants.COLLECTION_USAGE.equals(name)) { final ModelNode usage = PlatformMBeanUtil.getDetypedMemoryUsage(memoryPoolMXBean.getCollectionUsage()); store.set(usage); } else if (MemoryPoolResourceDefinition.MEMORY_POOL_READ_ATTRIBUTES.contains(name) || MemoryPoolResourceDefinition.MEMORY_POOL_READ_WRITE_ATTRIBUTES.contains(name) || MemoryPoolResourceDefinition.MEMORY_POOL_METRICS.contains(name)) { // Bug throw PlatformMBeanLogger.ROOT_LOGGER.badReadAttributeImpl(name); } } static MemoryPoolMXBean getMemoryPoolMXBean(String memPoolName) throws OperationFailedException { MemoryPoolMXBean memoryPoolMXBean = null; for (MemoryPoolMXBean mbean : ManagementFactory.getMemoryPoolMXBeans()) { if (memPoolName.equals(escapeMBeanName(mbean.getName()))) { memoryPoolMXBean = mbean; } } if (memoryPoolMXBean == null) { throw PlatformMBeanLogger.ROOT_LOGGER.unknownMemoryPool(memPoolName); } return memoryPoolMXBean; } }
51.788571
147
0.718305
f72f27e447383e65620c4a2e54a1f5ffe51df66d
1,731
package com.winson.spring.utils; import com.winson.spring.overview.domain.User; import org.springframework.util.ReflectionUtils; import java.lang.reflect.Field; import java.lang.reflect.Method; /** * @author winson * @date 2021/10/9 **/ public class ReflectionMethodUtilsDemo { public static void main(String[] args) { // Method[] methods = ReflectionUtils.getDeclaredMethods(User.class); // for (Method method : methods) { // System.out.println(method.getName()); // } System.out.println("============= doWithMethods ============="); ReflectionUtils.doWithMethods(User.class, new ReflectionUtils.MethodCallback() { @Override public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException { System.out.println(method.getName()); } }); // ReflectionUtils.doWithLocalMethods(User.class, null); System.out.println("============= doWithFields ============="); ReflectionUtils.doWithFields(User.class, new ReflectionUtils.FieldCallback() { @Override public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException { System.out.println(field.getName()); } }); System.out.println("============= doWithLocalFields ============="); ReflectionUtils.doWithLocalFields(User.class, new ReflectionUtils.FieldCallback() { @Override public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException { System.out.println(field.getName()); } }); ReflectionUtils.clearCache(); } }
33.941176
103
0.618718
54f33fec0019dca3cac45d3af4635535df16ecb8
1,198
package com.dev.crm.core.dto; import java.io.Serializable; public class DatosOnuInstalacionResultViewModel implements Serializable { /** * */ private static final long serialVersionUID = -192569864502908955L; private String macDescripcion; private String snDescripcion; private String winUser; private String winPassword; private String ponDescripcion; public DatosOnuInstalacionResultViewModel() { } public String getMacDescripcion() { return macDescripcion; } public void setMacDescripcion(String macDescripcion) { this.macDescripcion = macDescripcion; } public String getSnDescripcion() { return snDescripcion; } public void setSnDescripcion(String snDescripcion) { this.snDescripcion = snDescripcion; } public String getWinUser() { return winUser; } public void setWinUser(String winUser) { this.winUser = winUser; } public String getWinPassword() { return winPassword; } public void setWinPassword(String winPassword) { this.winPassword = winPassword; } public String getPonDescripcion() { return ponDescripcion; } public void setPonDescripcion(String ponDescripcion) { this.ponDescripcion = ponDescripcion; } }
18.151515
73
0.758765
577b3eee0685f0be155e9d2436a96728d8d886c7
900
package me.hvkcoder.spring_security.controller; import me.hvkcoder.spring_security.business.UserInfoService; import me.hvkcoder.spring_security.domain.UserInfo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * @author h-vk * @since 2021/5/21 */ @RestController public class IndexController { /** * normal 或 admin 角色可访问的接口 * * @return */ @RequestMapping("/access/normal") @PreAuthorize(value = "hasAnyRole('normal', 'admin')") public String accessNormal() { return "Hello User"; } /** * admin 角色可访问的接口 * * @return */ @RequestMapping("/access/admin") @PreAuthorize(value = "hasAnyRole('admin')") public String accessAdmin() { return "Hello Admin"; } }
22.5
64
0.742222
dc60e1a23822fa733e6ccbda64f730ded9617238
1,776
/* * Copyright 2018 ThoughtWorks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.thoughtworks.go.validation; import java.io.IOException; import com.thoughtworks.go.agent.ChecksumValidationPublisher; import com.thoughtworks.go.domain.ArtifactMd5Checksums; import org.apache.commons.lang3.StringUtils; public class ChecksumValidator { private final ArtifactMd5Checksums artifactMd5Checksums; public ChecksumValidator(ArtifactMd5Checksums artifactMd5Checksums) { this.artifactMd5Checksums = artifactMd5Checksums; } public void validate(String effectivePath, String artifactMD5, ChecksumValidationPublisher checksumValidationPublisher) { if (artifactMd5Checksums == null) { checksumValidationPublisher.md5ChecksumFileNotFound(); return; } String expectedMd5 = artifactMd5Checksums.md5For(effectivePath); if (StringUtils.isBlank(expectedMd5)) { checksumValidationPublisher.md5NotFoundFor(effectivePath); return; } if (expectedMd5.equals(artifactMD5)) { checksumValidationPublisher.md5Match(effectivePath); } else { checksumValidationPublisher.md5Mismatch(effectivePath); } } }
35.52
125
0.731982
fbdc8bd82ce62d80a6a2f389e3769e81cb5d376c
1,306
package potionstudios.aloneandtogether; import net.fabricmc.api.ModInitializer; import net.fabricmc.fabric.api.client.itemgroup.FabricItemGroupBuilder; import net.minecraft.core.Registry; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.Items; import potionstudios.aloneandtogether.common.blocks.AnTBlocks; import potionstudios.aloneandtogether.common.items.AnTCreativeTab; import potionstudios.aloneandtogether.common.items.AnTItems; public class AloneAndTogetherFabric implements ModInitializer { @Override public void onInitialize() { AloneAndTogether.init(); AnTBlocks.bootStrap(registryObjects -> registryObjects.forEach(registryObject -> Registry.register(Registry.BLOCK, new ResourceLocation(AloneAndTogether.MOD_ID, registryObject.id()), registryObject.object()))); AnTCreativeTab.init(FabricItemGroupBuilder.build(new ResourceLocation(AloneAndTogether.MOD_ID, "at"), () -> new ItemStack(Items.IRON_NUGGET))); AnTItems.bootStrap(registryObjects -> registryObjects.forEach(registryObject -> Registry.register(Registry.ITEM, new ResourceLocation(AloneAndTogether.MOD_ID, registryObject.id()), registryObject.object()))); AloneAndTogether.threadSafeLoadFinish(); } }
54.416667
218
0.804747
01eb1cfd5fd2f05505f7ef4ae7dd0870401c154e
2,040
package com.company; /* * Dit programma is geschreven als oeventoets in week 4 voor het vak "Programming" * het doel is om het "Plof" spel te simuleeren dat door kinderen vaak gespeeld wordt. * @Author Dylan Piera */ import java.util.InputMismatchException; import java.util.Scanner; public class Main { private static Scanner scan = new Scanner(System.in); private static String output = ""; private static int plofGetal; public static void main(String[] args) { try { /* * Zolang het plofGetal niet tussen 2 & 9 is zal er worden gevraagt om een plofgetal in te vullen. */ do { System.out.print("Wat is het \"Plof\" getal (2..9)? "); plofGetal = scan.nextInt(); } while (plofGetal < 2 || plofGetal > 9); System.out.print("Tot en met welk getal moet ik tellen? "); int max = scan.nextInt(); int index = 1; while (index <= max) { checkIfPlof(plofGetal, index); index++; } /* * output alle samegevoegde text, het had alleen een overbodige spatie aan het begin van de regel. * Daarom wordt eerst trim() er op uitgevoerd om die overbodige spatie weg te werken. */ System.out.println(output.trim()); } catch (InputMismatchException e) { /* * mocht het voorkomen dat er geen int wordt ingevuld zal je een melding geven dat je dit wel moet doen. */ System.out.println("Het plofgetal en maxiumum moeten een heel getal zijn in numbers geschreven."); } } /* * Voegt of " plof" of " " + number aan output toe, zodat alles in een zin kan worden uit "geprint" */ private static void checkIfPlof(int plof, int number) { if ( (number % plof) == 0) { output = output + " plof"; } else { output = output + " " + number; } } }
30.909091
116
0.563235
14aa2edc4d2bc507d84b4647d56ec4f383c4a82c
1,767
package randomizers.gameplay.filters.rules; import java.util.Random; import org.jdom2.Element; import com.google.common.collect.ImmutableSet; /* * Randomly breaks a repairable object. * * Original state --> New State * Broken --> Broken = OK * Not Broken --> Not Broken = OK * Broken --> Not Broken = OK * Not Broken --> Broken = Iffy */ public class BrokenObjectRule implements Rule { private static ImmutableSet<String> GUIDS_NOT_TO_RANDOMIZE = ImmutableSet.of(); private static final float BROKEN_RATIO = 0.5f; private static final ImmutableSet<String> BREAKABLE_ARCHETYPES = ImmutableSet.of( "ArkGameplayArchitecture.ElectricalBox.ElectricBox_DurationIndefinite", "ArkGameplayObjects.Recycler.Recycler_Default", "ArkGameplayObjects.Fabricator.Fabricator_Default", "ArkGameplayObjects.RepairableObject.RepairBox", "ArkGameplayObjects.RepairableObject.RepairBox_Level2", "ArkGameplayObjects.RepairableObject.RepairBox_Level3", "ArkGameplayObjects.RepairableObject.BrokenGroundingResistor", "ArkGameplayObjects.RepairableObject.BrokenDivertor", "ArkGameplayObjects.RepairableObject.WaterRegulator", "ArkGameplayObjects.RepairableObject.HeatExchangeMonitor"); @Override public boolean trigger(Element e, Random r, String filename) { String archetype = e.getAttributeValue("Archetype"); String guid = e.getAttributeValue("EntityGuid"); return guid != null && archetype != null && !GUIDS_NOT_TO_RANDOMIZE.contains(guid) && BREAKABLE_ARCHETYPES.contains(archetype); } @Override public void apply(Element e, Random r, String filename) { boolean isBroken = r.nextFloat() < BROKEN_RATIO; e.getChild("Properties2").setAttribute("bStartsBroken", isBroken ? "1" : "0"); } }
38.413043
131
0.757782
a1019d18ce5e1d78fe53f5899fbb8c4001b56240
303
package com.qdw.controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * <p> * 前端控制器 * </p> * * @author qdw * @since 2020-05-30 */ @RestController @RequestMapping("/tag") public class TagController { }
13.772727
62
0.716172
ee43fbb982d50b24340be7059e50c01c3a475e49
1,134
package com.szczygiel.bibtex; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import java.util.List; import static org.testng.Assert.assertEquals; /** * Tests for {@link Strings}. */ public class StringsTest { /** * {@link SingletonParser} instance. */ private SingletonParser parser; /** * Setup before tests. */ @BeforeClass public void setUp() { parser = SingletonParser.getInstance(); } /** * Test simple strings functionality. */ @Test public void testStrings() { String entryStr = "@STRING{\n" + " str1 = \"Hello\",\n" + " str2 = \"world\",\n" + " str1 = \"redefinition\"\n" + "}"; Entry entry = parser.parseEntry(entryStr); Strings strings = new Strings(); strings.extractFrom(List.of(entry)); assertEquals(strings.getString("str1"), "redefinition"); assertEquals(strings.getString("str2"), "world"); assertEquals(strings.toString(), "str1 = redefinition\nstr2 = world\n"); } }
23.625
80
0.57672
835d64835c4116974fd62623446388ba5ea6b31e
2,685
package com.exercise.mysys.web; import com.exercise.mysys.dao.GoodRepository; import com.exercise.mysys.dao.ManufacturePlanRepository; import com.exercise.mysys.domain.Good; import com.exercise.mysys.domain.ManufacturePlan; import com.exercise.mysys.domain.SysUser; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletRequest; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; /** * @ProjectName 食品企业订货销售系统 * @Author 朱向阳 * @Date 2018/7/23 17:09 * @Description: TODO */ @Controller @RequestMapping(value = "/jihua") public class JihuaController { @Autowired private ManufacturePlanRepository manufacturePlanRepository; @Autowired private GoodRepository goodRepository; @RequestMapping(value = "", method = RequestMethod.GET) public String jihua() { return "index/index_jihua"; } @GetMapping("/tianjiashengchanjihua") public String addShengchanjihua(){ return "shengchan/shengchan_order"; } @PostMapping("/tianjiashengchanjihua") @ResponseBody public String tianjiashengchanjihua(HttpServletRequest request){ try { //获取当前用户 SysUser nowUser = (SysUser) SecurityContextHolder.getContext() .getAuthentication() .getPrincipal(); //新建一个生产计划 ManufacturePlan manufacturePlan = new ManufacturePlan(); //设置生产计划有效 manufacturePlan.setEffective(true); //设置员工编号 manufacturePlan.setEmployee_id(nowUser.getId()); List<Good> list = goodRepository.myFindJingque(request.getParameter("name").trim()); if (list.size() == 0){ return "不存在该商品"; } Good good = list.get(0); manufacturePlan.setGood_id(good.getId()); manufacturePlan.setNumber(Integer.parseInt(request.getParameter("number").trim())); manufacturePlan.setMoney(Integer.parseInt(request.getParameter("money").trim())); //设置生产时间 DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd"); Date date = fmt.parse(request.getParameter("date")); manufacturePlan.setManufacture_date(date); manufacturePlanRepository.save(manufacturePlan); return "true"; } catch (Exception e){ System.out.println(e.toString()); return "操作失败"; } } }
33.5625
96
0.667784
dd7e2bb5ddba02ff9e89ef91c0f534ad540d5072
608
package com.databaseproj.caltracker.view; import android.app.Activity; import android.os.Bundle; import android.view.Window; import android.widget.TextView; import com.databaseproj.caltracker.R; public class HelpActivity extends Activity { private TextView textView; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.train_help); textView = (TextView) findViewById(R.id.TrainHelpTextView); textView.setText(getString(R.string.help_tips)); } }
26.434783
67
0.753289
491be15f72c4740b0861be6bcea23ecdfa2199e5
1,686
package com.example.reservation.controller; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponses; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Value; import org.springframework.cloud.context.config.annotation.RefreshScope; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; /** * Created by a.c.parthasarathy */ @RefreshScope @RestController @Slf4j @Api(value = "/message", tags = "Message", description = "API to display run-time config change") public class MessageRestController { @Value("${message}") private String message; @GetMapping(value = "/message", produces = MediaType.TEXT_PLAIN_VALUE) @ApiOperation( value = "Display value of message property", notes = "This API is used to demonstrate how config values can be changed at run-time " + "without the need to restart the application (using Spring's RefreshScope)", response = String.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = String.class), @ApiResponse(code = 400, message = "failed operation", response = String.class) }) public ResponseEntity<String> message() { log.info("Ani came inside message method"); return new ResponseEntity<String>(this.message, HttpStatus.OK); } }
41.121951
101
0.734282
3c033adb0ccc404f2f827ead1e9dab4d64956fed
1,996
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.storage.blob.models; import com.azure.core.implementation.annotation.Fluent; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement; /** * Additional parameters for a set of operations. */ @JacksonXmlRootElement(localName = "customer-provided-key-info") @Fluent public final class CustomerProvidedKeyInfo { /* * Optional. Specifies the encryption scope to use to encrypt the data * provided in the request. If not specified, encryption is performed with * the root account encryption key. For more information, see Encryption * at Rest for Azure Storage Services. */ @JsonProperty(value = "encryptionScope") private String encryptionScope; /** * Get the encryptionScope property: Optional. Specifies the encryption * scope to use to encrypt the data provided in the request. If not * specified, encryption is performed with the root account encryption key. * For more information, see Encryption at Rest for Azure Storage Services. * * @return the encryptionScope value. */ public String encryptionScope() { return this.encryptionScope; } /** * Set the encryptionScope property: Optional. Specifies the encryption * scope to use to encrypt the data provided in the request. If not * specified, encryption is performed with the root account encryption key. * For more information, see Encryption at Rest for Azure Storage Services. * * @param encryptionScope the encryptionScope value to set. * @return the CustomerProvidedKeyInfo object itself. */ public CustomerProvidedKeyInfo encryptionScope(String encryptionScope) { this.encryptionScope = encryptionScope; return this; } }
38.384615
79
0.730461
36d551884a787fea1320fbd550125f53d9dc0bc5
877
package examples.hibernate.domainmodel.identifiers.idgenerator.rowid; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import org.hibernate.annotations.RowId; @Entity(name = "Product") @RowId("ROWID") public class Product { @Id private Long id; @Column(name = "`name`") private String name; @Column(name = "`number`") private String number; public Product() { } public Product(Long id,String name,String number) { this.id = id ; this.name = name ; this.number = number; } public Long getId() { return this.id; } public void setId(Long id) { this.id = id; } public String getName() { return this.name; } public void setName(String name) { this.name = name; } public String getNumber() { return this.number; } public void setNumber(String number) { this.number = number; } }
15.12069
69
0.688712
0b6485e3b087c6e08ec88d652501300b21b946f7
4,861
package com.taobao.api.request; import java.util.Date; import com.taobao.api.internal.util.RequestCheckUtils; import java.util.Map; import com.taobao.api.TaobaoRequest; import com.taobao.api.internal.util.TaobaoHashMap; import com.taobao.api.response.RefundsReceiveGetResponse; import com.taobao.api.ApiRuleException; /** * TOP API: taobao.refunds.receive.get request * * @author auto create * @since 1.0, 2013-03-14 16:30:18 */ public class RefundsReceiveGetRequest implements TaobaoRequest<RefundsReceiveGetResponse> { private TaobaoHashMap udfParams; // add user-defined text parameters private Long timestamp; /** * 买家昵称 */ private String buyerNick; /** * 查询修改时间结束。格式: yyyy-MM-dd HH:mm:ss */ private Date endModified; /** * 需要返回的字段。目前支持有:refund_id, tid, title, buyer_nick, seller_nick, total_fee, status, created, refund_fee, oid, good_status, company_name, sid, payment, reason, desc, has_good_return, modified, order_status */ private String fields; /** * 页码。取值范围:大于零的整数; 默认值:1 */ private Long pageNo; /** * 每页条数。取值范围:大于零的整数; 默认值:40;最大值:100 */ private Long pageSize; /** * 查询修改时间开始。格式: yyyy-MM-dd HH:mm:ss */ private Date startModified; /** * 退款状态,默认查询所有退款状态的数据,除了默认值外每次只能查询一种状态。 WAIT_SELLER_AGREE(买家已经申请退款,等待卖家同意) WAIT_BUYER_RETURN_GOODS(卖家已经同意退款,等待买家退货) WAIT_SELLER_CONFIRM_GOODS(买家已经退货,等待卖家确认收货) SELLER_REFUSE_BUYER(卖家拒绝退款) CLOSED(退款关闭) SUCCESS(退款成功) */ private String status; /** * 交易类型列表,一次查询多种类型可用半角逗号分隔,默认同时查询guarantee_trade, auto_delivery的2种类型的数据。 fixed(一口价) auction(拍卖) guarantee_trade(一口价、拍卖) independent_simple_trade(旺店入门版交易) independent_shop_trade(旺店标准版交易) auto_delivery(自动发货) ec(直冲) cod(货到付款) fenxiao(分销) game_equipment(游戏装备) shopex_trade(ShopEX交易) netcn_trade(万网交易) external_trade(统一外部交易) */ private String type; /** * 是否启用has_next的分页方式,如果指定true,则返回的结果中不包含总记录数,但是会新增一个是否存在下一页的的字段,通过此种方式获取增量退款,接口调用成功率在原有的基础上有所提升。 */ private Boolean useHasNext; public void setBuyerNick(String buyerNick) { this.buyerNick = buyerNick; } public String getBuyerNick() { return this.buyerNick; } public void setEndModified(Date endModified) { this.endModified = endModified; } public Date getEndModified() { return this.endModified; } public void setFields(String fields) { this.fields = fields; } public String getFields() { return this.fields; } public void setPageNo(Long pageNo) { this.pageNo = pageNo; } public Long getPageNo() { return this.pageNo; } public void setPageSize(Long pageSize) { this.pageSize = pageSize; } public Long getPageSize() { return this.pageSize; } public void setStartModified(Date startModified) { this.startModified = startModified; } public Date getStartModified() { return this.startModified; } public void setStatus(String status) { this.status = status; } public String getStatus() { return this.status; } public void setType(String type) { this.type = type; } public String getType() { return this.type; } public void setUseHasNext(Boolean useHasNext) { this.useHasNext = useHasNext; } public Boolean getUseHasNext() { return this.useHasNext; } private Map<String,String> headerMap=new TaobaoHashMap(); public Long getTimestamp() { return this.timestamp; } public void setTimestamp(Long timestamp) { this.timestamp = timestamp; } public String getApiMethodName() { return "taobao.refunds.receive.get"; } public Map<String, String> getTextParams() { TaobaoHashMap txtParams = new TaobaoHashMap(); txtParams.put("buyer_nick", this.buyerNick); txtParams.put("end_modified", this.endModified); txtParams.put("fields", this.fields); txtParams.put("page_no", this.pageNo); txtParams.put("page_size", this.pageSize); txtParams.put("start_modified", this.startModified); txtParams.put("status", this.status); txtParams.put("type", this.type); txtParams.put("use_has_next", this.useHasNext); if(this.udfParams != null) { txtParams.putAll(this.udfParams); } return txtParams; } public void putOtherTextParam(String key, String value) { if(this.udfParams == null) { this.udfParams = new TaobaoHashMap(); } this.udfParams.put(key, value); } public Class<RefundsReceiveGetResponse> getResponseClass() { return RefundsReceiveGetResponse.class; } public void check() throws ApiRuleException { RequestCheckUtils.checkNotEmpty(fields,"fields"); RequestCheckUtils.checkMinValue(pageNo,1L,"pageNo"); RequestCheckUtils.checkMaxValue(pageSize,100L,"pageSize"); RequestCheckUtils.checkMinValue(pageSize,1L,"pageSize"); } public Map<String,String> getHeaderMap() { return headerMap; } }
24.064356
205
0.709319
01cadb467dfc6edc957d9cac8faa7f3876e08614
1,862
package com.enderio.core.common.util; import javax.annotation.Nonnull; import javax.annotation.Nullable; import net.minecraft.block.state.IBlockState; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.BlockPos; import net.minecraft.world.IBlockAccess; import net.minecraft.world.WorldType; import net.minecraft.world.biome.Biome; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; public class IBlockAccessWrapper implements IBlockAccess { protected @Nonnull IBlockAccess wrapped; public IBlockAccessWrapper(@Nonnull IBlockAccess ba) { wrapped = ba; } @Override public boolean isSideSolid(@Nonnull BlockPos pos, @Nonnull EnumFacing side, boolean _default) { return wrapped.isSideSolid(pos, side, _default); } @Override public @Nullable TileEntity getTileEntity(@Nonnull BlockPos pos) { if (pos.getY() >= 0 && pos.getY() < 256) { return wrapped.getTileEntity(pos); } else { return null; } } @Override public @Nonnull IBlockState getBlockState(@Nonnull BlockPos pos) { return wrapped.getBlockState(pos); } @SideOnly(Side.CLIENT) @Override public int getCombinedLight(@Nonnull BlockPos pos, int lightValue) { return 15 << 20 | 15 << 4; } @Override public boolean isAirBlock(@Nonnull BlockPos pos) { return wrapped.isAirBlock(pos); } @Override public @Nonnull Biome getBiome(@Nonnull BlockPos pos) { return wrapped.getBiome(pos); } @Override public int getStrongPower(@Nonnull BlockPos pos, @Nonnull EnumFacing direction) { return wrapped.getStrongPower(pos, direction); } @Override public @Nonnull WorldType getWorldType() { return wrapped.getWorldType(); } }
26.6
98
0.712675
9270c185896e3a0e2a0fedfcc05622c50ff45419
1,262
package com.wxmp.backstage.common; import java.text.MessageFormat; import java.util.Locale; import java.util.ResourceBundle; import com.wxmp.backstage.util.ExcptUtil; /** * @author : hermit */ public class I18n { public static final String FILED_RPEAT = getMessage("core.field.rpeat"); public static final String FILED_EXISTS = getMessage("core.field.exists"); public static final String FILED_REQUIRED = getMessage("core.field.required"); public static final String FILED_UNLAWFUL = getMessage("core.field.unlawful"); private static final String MSG_BASE_NAME = "i18n/messages"; public static String getMessage(String key, Object[] params) { if ((params == null) || (params.length < 1)) { return ResourceBundle.getBundle("i18n/messages", Locale.CHINA).getString(key); } return MessageFormat.format(ResourceBundle.getBundle("i18n/messages", Locale.CHINA).getString(key), params); } public static String getMessage(String key) { String value = key; try { ResourceBundle resource = ResourceBundle.getBundle("i18n/messages", Locale.CHINA); String temp = resource.getString(key); if (temp != null) value = temp; } catch (Exception e) { ExcptUtil.unchecked(e); } return value; } }
31.55
112
0.716323
8150e921627d7da4d5740b7c21be481694d0a53c
509
package com.warner.factory.presenter.account; import com.warner.factory.presenter.BaseContract; /** * Created by warner on 2018/1/15. */ public interface RegisterContract { interface View extends BaseContract.View<Presenter> { // 注册成功 void registerSuccess(); } interface Presenter extends BaseContract.Presenter { // 发起一个注册 void register(String phone, String name, String password); // 检查手机号是否正确 boolean checkMobile(String phone); } }
19.576923
66
0.671906
1a7b06c51dc2787b2027d6a780c52c36e602c3f9
9,612
/* * DBeaver - Universal Database Manager * Copyright (C) 2010-2021 DBeaver Corp and others * * 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.jkiss.dbeaver.ext.hana.model; import org.jkiss.dbeaver.DBException; import org.jkiss.dbeaver.ext.generic.model.GenericCatalog; import org.jkiss.dbeaver.ext.generic.model.GenericFunctionResultType; import org.jkiss.dbeaver.ext.generic.model.GenericPackage; import org.jkiss.dbeaver.ext.generic.model.GenericProcedure; import org.jkiss.dbeaver.ext.generic.model.GenericSchema; import org.jkiss.dbeaver.ext.generic.model.GenericStructContainer; import org.jkiss.dbeaver.model.DBUtils; import org.jkiss.dbeaver.model.exec.jdbc.JDBCPreparedStatement; import org.jkiss.dbeaver.model.exec.jdbc.JDBCResultSet; import org.jkiss.dbeaver.model.exec.jdbc.JDBCSession; import org.jkiss.dbeaver.model.impl.jdbc.JDBCUtils; import org.jkiss.dbeaver.model.meta.Association; import org.jkiss.dbeaver.model.meta.Property; import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor; import org.jkiss.dbeaver.model.struct.DBSObject; import org.jkiss.dbeaver.model.struct.rdb.DBSProcedureParameterKind; import org.jkiss.dbeaver.model.struct.rdb.DBSProcedureType; import java.sql.SQLException; import java.util.List; import java.util.Map; import java.util.HashMap; import java.util.LinkedList; public class HANAProcedure extends GenericProcedure { static final String DATA_TYPE_NAME_TABLE_TYPE = "TABLE_TYPE"; static final String DATA_TYPE_NAME_ANY_TABLE_TYPE = "ANY_TABLE_TYPE"; private static final String PARAMETER_TYPE_IN = "IN"; private static final String PARAMETER_TYPE_INOUT = "INOUT"; private static final String PARAMETER_TYPE_OUT = "OUT"; private static final String PARAMETER_TYPE_RETURN = "RETURN"; Map<String, List<HANAInplaceTableTypeColumn> > inplaceTableTypes; public HANAProcedure(GenericStructContainer container, String procedureName, String specificName, String description, DBSProcedureType procedureType, GenericFunctionResultType functionResultType) { super(container, procedureName, specificName, description, procedureType, functionResultType); } private void loadInplaceTableTypes(DBRProgressMonitor monitor) throws DBException { inplaceTableTypes = new HashMap<>(); try (JDBCSession session = DBUtils.openMetaSession(monitor, getDataSource(), "Read procedure parameter columns")) { String stmt = "SELECT PARAMETER_NAME, COLUMN_NAME, DATA_TYPE_NAME, LENGTH, SCALE"; if (DBSProcedureType.PROCEDURE == getProcedureType()) { stmt += " FROM SYS.PROCEDURE_PARAMETER_COLUMNS"+ " WHERE SCHEMA_NAME=? AND PROCEDURE_NAME=?"+ " ORDER BY PARAMETER_NAME, POSITION"; } else { stmt += " FROM SYS.FUNCTION_PARAMETER_COLUMNS"+ " WHERE SCHEMA_NAME=? AND FUNCTION_NAME=?"+ " ORDER BY PARAMETER_NAME, POSITION"; } try (JDBCPreparedStatement dbStat = session.prepareStatement(stmt)) { dbStat.setString(1, getParentObject().getName()); dbStat.setString(2, getName()); try (JDBCResultSet dbResult = dbStat.executeQuery()) { while (dbResult.next()) { String parameterName = JDBCUtils.safeGetString(dbResult, 1); String columnName = JDBCUtils.safeGetString(dbResult, 2); String typeName = JDBCUtils.safeGetString(dbResult, 3); int length = JDBCUtils.safeGetInt(dbResult, 4); int scale = JDBCUtils.safeGetInt(dbResult, 5); List<HANAInplaceTableTypeColumn> inplaceTableType = inplaceTableTypes.get(parameterName); if (inplaceTableType == null) { inplaceTableType = new LinkedList<HANAInplaceTableTypeColumn>(); inplaceTableTypes.put(parameterName, inplaceTableType); } inplaceTableType.add(new HANAInplaceTableTypeColumn(this, columnName, typeName, inplaceTableType.size() + 1, length, scale)); } } } } catch (SQLException e) { throw new DBException(e, getDataSource()); } } @Override public void loadProcedureColumns(DBRProgressMonitor monitor) throws DBException { try (JDBCSession session = DBUtils.openMetaSession(monitor, getDataSource(), "Read procedure parameter")) { String stmt; stmt = "SELECT PARAMETER_NAME, DATA_TYPE_NAME, LENGTH, SCALE, POSITION,"+ " TABLE_TYPE_SCHEMA, TABLE_TYPE_NAME, IS_INPLACE_TYPE,"+ " PARAMETER_TYPE, HAS_DEFAULT_VALUE"; if (DBSProcedureType.PROCEDURE == getProcedureType()) { stmt += " FROM SYS.PROCEDURE_PARAMETERS"+ " WHERE SCHEMA_NAME=? AND PROCEDURE_NAME=?"+ " ORDER BY POSITION"; } else { stmt += " FROM SYS.FUNCTION_PARAMETERS"+ " WHERE SCHEMA_NAME=? AND FUNCTION_NAME=?"+ " ORDER BY POSITION"; } try (JDBCPreparedStatement dbStat = session.prepareStatement(stmt)) { dbStat.setString(1, getParentObject().getName()); dbStat.setString(2, getName()); try (JDBCResultSet dbResult = dbStat.executeQuery()) { while (dbResult.next()) { String columnName = JDBCUtils.safeGetString(dbResult, 1); String typeName = JDBCUtils.safeGetString(dbResult, 2); int columnSize = JDBCUtils.safeGetInt(dbResult, 3); int scale = JDBCUtils.safeGetInt(dbResult, 4); int position = JDBCUtils.safeGetInt(dbResult, 5); String parameterTypeStr = JDBCUtils.safeGetString(dbResult, 9); boolean hasInplaceTableType = "TRUE".equals(JDBCUtils.safeGetString(dbResult, 8)); boolean hasDefaultValue = "TRUE".equals(JDBCUtils.safeGetString(dbResult, 10)); DBSProcedureParameterKind parameterType; switch(parameterTypeStr) { case PARAMETER_TYPE_IN: parameterType = DBSProcedureParameterKind.IN; break; case PARAMETER_TYPE_INOUT: parameterType = DBSProcedureParameterKind.INOUT; break; case PARAMETER_TYPE_OUT: parameterType = DBSProcedureParameterKind.OUT; break; case PARAMETER_TYPE_RETURN: parameterType = DBSProcedureParameterKind.RETURN; break; default: parameterType = DBSProcedureParameterKind.UNKNOWN; break; } DBSObject tableType = null; List<HANAInplaceTableTypeColumn> inplaceTableType = null; if(DATA_TYPE_NAME_TABLE_TYPE.equals(typeName)) { if (hasInplaceTableType) { if (inplaceTableTypes == null) { loadInplaceTableTypes(monitor); } inplaceTableType = inplaceTableTypes.get(columnName); } else { String tableTypeSchema = dbResult.getString(6); String tableTypeName = dbResult.getString(7); GenericSchema schema = getDataSource().getSchema(tableTypeSchema); if (schema != null) { tableType = schema.getTable(monitor, tableTypeName); } } } addColumn(new HANAProcedureParameter( this, columnName, typeName, position, columnSize, scale, parameterType, tableType, inplaceTableType, hasDefaultValue)); } } } } catch (SQLException e) { throw new DBException(e, getDataSource()); } } @Association public List<HANADependency> getDependencies(DBRProgressMonitor monitor) throws DBException { return HANADependency.readDependencies(monitor, this); } @Property(hidden = true) public GenericCatalog getCatalog() { return super.getCatalog(); } @Property(hidden = true) public GenericPackage getPackage() { return super.getPackage(); } // hide, as not properly filled by driver. type is anyway obvious from RETURN parameter @Property(hidden = true) public GenericFunctionResultType getFunctionResultType() { return super.getFunctionResultType(); } }
53.4
149
0.616625
a3e3cd6397390bb2c446be84a11990d6fd6ab341
336
package tr.edu.iztech.teamstech.user; import tr.edu.iztech.teamstech.entity.EntityDirector; public class Instructor extends Academician { public Instructor(EntityDirector director, int id, String username, String email, String password, String[] teamIds) { super(director, id, username, email, password, teamIds); } }
33.6
122
0.755952
65c7a4c374d74b8dfb7685f2748ea8e97eade0ba
4,047
/** * Copyright (C) FuseSource, Inc. * http://fusesource.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.fusesource.fabric.agent; import org.fusesource.fabric.api.Constants; import org.fusesource.fabric.api.FabricService; import org.osgi.framework.BundleActivator; import org.osgi.framework.BundleContext; import org.osgi.framework.ServiceReference; import org.osgi.framework.ServiceRegistration; import org.osgi.service.cm.Configuration; import org.osgi.service.cm.ConfigurationAdmin; import org.osgi.service.cm.ManagedService; import org.osgi.util.tracker.ServiceTracker; import org.slf4j.LoggerFactory; import java.util.Dictionary; import java.util.Hashtable; public class Activator implements BundleActivator { private static final String OBR_RESOLVE_OPTIONAL_IMPORTS = "obr.resolve.optional.imports"; private static final String RESOLVE_OPTIONAL_IMPORTS = "resolve.optional.imports"; private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(Activator.class); private DeploymentAgent agent; private ServiceTracker<FabricService, FabricService> fabricService; private ServiceRegistration registration; public void start(BundleContext context) throws Exception { agent = new DeploymentAgent(); agent.setBundleContext(context); Dictionary<String, Object> config = getConfig(context); agent.setResolveOptionalImports(getResolveOptionalImports(config)); agent.setFabricService(getFabricService(context)); agent.start(); Hashtable<String, String> props = new Hashtable<String, String>(); props.put(org.osgi.framework.Constants.SERVICE_PID, Constants.AGENT_PID); registration = context.registerService(ManagedService.class.getName(), agent, props); } public void stop(BundleContext context) throws Exception { registration.unregister(); agent.stop(); fabricService.close(); } private boolean getResolveOptionalImports(Dictionary<String, Object> config) { if (config != null) { String str = (String) config.get(OBR_RESOLVE_OPTIONAL_IMPORTS); if (str == null) { str = (String) config.get(RESOLVE_OPTIONAL_IMPORTS); } if (str != null) { return Boolean.parseBoolean(str); } } return false; } private Dictionary<String, Object> getConfig(BundleContext bundleContext) { try { ServiceReference configAdminServiceReference = bundleContext.getServiceReference(ConfigurationAdmin.class.getName()); if (configAdminServiceReference != null) { ConfigurationAdmin configAdmin = (ConfigurationAdmin) bundleContext.getService(configAdminServiceReference); if (configAdmin != null) { Configuration[] configuration = configAdmin.listConfigurations("(service.pid=" + Constants.AGENT_PID + ")"); return (configuration != null && configuration.length > 0) ? configuration[0].getProperties() : null; } } } catch (Exception e) { LOGGER.warn("Unable to retrieve agent configuration", e); } return null; } private ServiceTracker<FabricService, FabricService> getFabricService(BundleContext context) { fabricService = new ServiceTracker<FabricService, FabricService>(context, FabricService.class, null); fabricService.open(); return fabricService; } }
41.295918
129
0.704225
7d2c5907d3afd735a18aaab6b55a3d8696216396
2,137
package gui; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JTextField; import ij.IJ; public class k_means { private String K; boolean cancelled; public k_means() { optionsSelect(); if (cancelled) { return; } if (K != null && !("").equals(K) && !K.matches(".*[A-Za-z].*") && Integer.valueOf(K) > 0){ IJ.run("Cluster My Data", "k_means="+K); } else { IJ.showMessage("k should be a whole number over 0."); return; } } public void optionsSelect() { JTextField k = new JTextField(3); JPanel panel = new JPanel(new GridBagLayout()); GridBagConstraints constraints = new GridBagConstraints(); constraints.anchor = GridBagConstraints.WEST; constraints.insets = new Insets(0, 4, 0, 0); constraints.gridx = 0; constraints.gridy = 0; panel.add(new JLabel("K-Means 'k':"), constraints); constraints.gridx = 1; panel.add(k, constraints); constraints.gridx = 0; constraints.gridy = 1; constraints.gridwidth = 2; panel.add(new JLabel("The number of clusters to form."), constraints); //panel.add(new JLabel("Minimum cluster size:")); //panel.add(minCS); //panel.add(new JLabel("The smallest grouping you wish to have as a cluster.")); //intpanel.add(Box.createHorizontalStrut(10)); // a spacer //panel.add(new JLabel("Minimum points:")); //panel.add(minP); //panel.add(new JLabel("The larger the value, the more points will be declared as noise, and clusters will be restricted to progressively more dense areas.")); int result = JOptionPane.showConfirmDialog(null, panel, "Optionally enter K-Means parameters", JOptionPane.OK_CANCEL_OPTION); if (result == JOptionPane.OK_OPTION) { K = k.getText(); } else if (result == JOptionPane.CANCEL_OPTION) { cancelled = true; } } }
30.528571
168
0.620028
21b8678ed1386c23084cd076bd8afcddca35977b
1,692
package io.snice.networking.netty; import io.netty.channel.Channel; import io.snice.buffer.Buffer; import io.snice.buffer.Buffers; import io.snice.networking.common.ConnectionId; import io.snice.networking.common.Transport; import java.net.InetSocketAddress; import java.net.URI; import java.util.Optional; /** * Encapsulates a * * @author [email protected] */ public final class UdpConnection<T> extends AbstractConnection<T> { public UdpConnection(final Channel channel, final ConnectionId id, final Optional<URI> vipAddress) { super(channel, id, vipAddress); } public UdpConnection(final Channel channel, final InetSocketAddress remoteAddress, final Optional<URI> vipAddress) { super(Transport.udp, channel, remoteAddress, vipAddress); } public UdpConnection(final Channel channel, final InetSocketAddress remoteAddress) { super(Transport.udp, channel, remoteAddress, Optional.empty()); } @Override public int getDefaultPort() { return 5060; } /** * {@inheritDoc} */ @Override public boolean isUDP() { return true; } /** * {@inheritDoc} */ @Override public void send(final T msg) { write(msg); } private Buffer serialize(final Object msg) { if (msg instanceof String) { return Buffers.wrap((String)msg); } if (msg instanceof Buffer) { return (Buffer)msg; } throw new IllegalArgumentException("I do not have a serializer for object of type : " + msg.getClass().getSimpleName()); } @Override public boolean connect() { return true; } }
23.5
128
0.65721
cee43aad8385fe80c7219ca2d2d50c75113970ed
205
// // Generated from archetype; please customize. // package org.sonar; /** * Example Java class. */ public class Helper { public void help(final Example example) { example.show(); } }
12.8125
46
0.629268
94b54c454e8b92e98b02a62ff9559583e96dbe4e
4,055
package com.redhat.uxl.webapp.web.rest; import com.codahale.metrics.annotation.Timed; import com.redhat.uxl.services.utils.SSLUtils; import io.swagger.annotations.ApiOperation; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate; import org.springframework.web.util.UriComponentsBuilder; /** * The type Allego resource. */ @RestController @RequestMapping(value = "/api/allego", produces = MediaType.APPLICATION_JSON_VALUE) @Slf4j public class AllegoResource extends BaseResource { /** * The Recipient url. */ @Value("${app.allego.api.recipient.url}") protected String recipientUrl; /** * The Search url. */ @Value("${app.allego.api.search.url}") protected String searchUrl; /** * The Auth key. */ @Value("${app.allego.api.key.auth}") protected String authKey; /** * Allego recipients string. * * @param from the from * @param size the size * @return the string */ @ApiOperation(value = "Get content recipients in allego", notes = "<p>Get content recipients in allego. Useful to bypass the cloudfront proxy</p>") @RequestMapping(value = "/recipients", method = RequestMethod.GET) @Timed public String allegoRecipients(@RequestParam(required = false) Integer from, @RequestParam(required = false) Integer size) { return doAllegoCall(recipientUrl, from, size); } /** * Allego search string. * * @param from the from * @param size the size * @return the string */ @ApiOperation(value = "Search in allego", notes = "<p>Search in allego. Useful to bypass the cloudfront proxy</p>") @RequestMapping(value = "/", method = RequestMethod.GET) @Timed public String allegoSearch(@RequestParam(required = false) Integer from, @RequestParam(required = false) Integer size) { log.info("Enabling SNI"); SSLUtils.enableSNI(); try { log.info("Trying Search Allego call"); return doAllegoCall(searchUrl, from, size); } finally { log.info("Finally Disabling SNI"); SSLUtils.disableSNI(); ; } } /** * Allego search no sni string. * * @param from the from * @param size the size * @return the string */ @ApiOperation(value = "Search in allego", notes = "<p>Search in allego. Useful to bypass the cloudfront proxy</p>") @RequestMapping(value = "/search/nosni", method = RequestMethod.GET) @Timed public String allegoSearchNoSni(@RequestParam(required = false) Integer from, @RequestParam(required = false) Integer size) { log.info("Disabling SNI"); SSLUtils.disableSNI(); log.info("Trying Search Allego call"); return doAllegoCall(searchUrl, from, size); } private String doAllegoCall(String url, Integer from, Integer size) { UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url).queryParam("from", from).queryParam("size", size); RestTemplate restTemplate = new RestTemplate(); HttpHeaders headers = new HttpHeaders(); headers.add("Authorization", "Allego " + authKey); HttpEntity<String> entity = new HttpEntity(null, headers); final ResponseEntity<String> response = restTemplate.exchange(builder.toUriString(), HttpMethod.GET, entity, String.class); return response.getBody(); } }
34.956897
151
0.674229
fb15d9c1b862937cd23e882b80a79c0498508328
3,994
package com.situjunjie.gulimall.member.controller; import java.util.Arrays; import java.util.Map; //import org.apache.shiro.authz.annotation.RequiresPermissions; import com.situjunjie.common.constant.AuthServerConst; import com.situjunjie.common.exception.BizCodeEnum; import com.situjunjie.gulimall.member.exception.UsernameExistsException; import com.situjunjie.gulimall.member.service.feign.CouponFeign; import com.situjunjie.gulimall.member.vo.MemberLoginVo; import com.situjunjie.gulimall.member.vo.MemberRegistVo; import com.situjunjie.gulimall.member.vo.WeiboAccessTokenVo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import com.situjunjie.gulimall.member.entity.MemberEntity; import com.situjunjie.gulimall.member.service.MemberService; import com.situjunjie.common.utils.PageUtils; import com.situjunjie.common.utils.R; import javax.servlet.http.HttpSession; /** * 会员 * * @author situjunjie * @email [email protected] * @date 2021-06-16 13:32:11 */ @RestController @RequestMapping("member/member") public class MemberController { @Autowired private MemberService memberService; @Autowired private CouponFeign couponFeign; /** * * 测试feign远程调用 */ @RequestMapping("/testfeign/list") public R testFeign(){ R couponR = couponFeign.testcoupon(); MemberEntity memberEntity = new MemberEntity(); memberEntity.setNickname("张三"); return R.ok().put("member",memberEntity).put("coupon",couponR.get("coupon")); } /** * 列表 */ @RequestMapping("/list") // @RequiresPermissions("member:member:list") public R list(@RequestParam Map<String, Object> params){ PageUtils page = memberService.queryPage(params); return R.ok().put("page", page); } /** * 信息 */ @RequestMapping("/info/{id}") // @RequiresPermissions("member:member:info") public R info(@PathVariable("id") Long id){ MemberEntity member = memberService.getById(id); return R.ok().put("member", member); } /** * 保存 */ @RequestMapping("/save") // @RequiresPermissions("member:member:save") public R save(@RequestBody MemberEntity member){ memberService.save(member); return R.ok(); } /** * 修改 */ @RequestMapping("/update") //@RequiresPermissions("member:member:update") public R update(@RequestBody MemberEntity member){ memberService.updateById(member); return R.ok(); } /** * 删除 */ @RequestMapping("/delete") //@RequiresPermissions("member:member:delete") public R delete(@RequestBody Long[] ids){ memberService.removeByIds(Arrays.asList(ids)); return R.ok(); } /** * 会员注册 */ @RequestMapping("/regist") public R memberRegist(@RequestBody MemberRegistVo vo){ try { memberService.regist(vo); } catch (UsernameExistsException e){ return R.error(BizCodeEnum.USERNAME_EXISTS_EXCETION.getCode(),BizCodeEnum.USERNAME_EXISTS_EXCETION.getMessage()); } return R.ok(); } /** * 会员登录 */ @PostMapping("/login") public R memberLogin(@RequestBody MemberLoginVo vo){ MemberEntity entity = memberService.memberLogin(vo); if(entity==null){ //没获取到对象即登录失败 return R.error(BizCodeEnum.USERNAME_PASSWORD_INVALID_EXCEPTION.getCode(), BizCodeEnum.USERNAME_PASSWORD_INVALID_EXCEPTION.getMessage()); } return R.ok().put(AuthServerConst.LOGIN_USER_SESSION,entity); } /** * 微博登录 */ @PostMapping("/weibo_login") public R weiboLogin(@RequestBody WeiboAccessTokenVo weiboAccessTokenVo) throws Exception { MemberEntity entity = memberService.weiboLogin(weiboAccessTokenVo); if(entity==null){ return R.error(); } return R.ok().put("memberInfo",entity); } }
26.104575
148
0.670005
6da2c2d080537c71599c70014fb00b079cc36bd2
404
package com.sunnysuperman.repository.db; public class DBFunction { private String function; private Object[] params; public DBFunction(String function, Object[] params) { super(); this.function = function; this.params = params; } public String getFunction() { return function; } public Object[] getParams() { return params; } }
19.238095
57
0.616337
deb34d90814c22080b0fce92954c8ce6a028ac22
1,793
package com.intuit.quickfabric.schedulers.mappers; import org.springframework.dao.DataAccessException; import org.springframework.jdbc.core.ResultSetExtractor; import com.intuit.quickfabric.commons.vo.ClusterStatus; import com.intuit.quickfabric.commons.vo.EMRClusterMetricsVO; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; public class EMRClusterMetricsMapper implements ResultSetExtractor<List<EMRClusterMetricsVO>> { public List<EMRClusterMetricsVO> extractData(ResultSet rs) throws SQLException, DataAccessException { List<EMRClusterMetricsVO> eMRClusterMetricsList = new ArrayList<EMRClusterMetricsVO>(); EMRClusterMetricsVO vo = null; while (rs.next()) { vo = new EMRClusterMetricsVO(); vo.setEmrId(rs.getString("emr_id")); vo.setRmUrl(rs.getString("rm_url")); vo.setRefreshTimestamp(rs.getTimestamp("refresh_timestamp").toString()); vo.setClusterCreateTimestamp(rs.getTimestamp("cluster_create_timestamp").toString()); vo.setMetricsJson(rs.getString("metrics_json")); vo.setEmrStatus(ClusterStatus.valueOf((rs.getString("emr_status")))); vo.setCost(rs.getFloat("emr_cost")); vo.setEmrName(rs.getString("emr_name")); vo.setCoresUsagePct(rs.getFloat("cores_usage_pct")); vo.setMemoryUsagePct(rs.getFloat("memory_usage_pct")); vo.setActiveNodes(rs.getInt("total_nodes")); vo.setAppsPending(rs.getInt("apps_pending")); vo.setAppsRunning(rs.getInt("apps_running")); vo.setAppsSucceeded(rs.getInt("apps_succeeded")); vo.setAppsFailed(rs.getInt("apps_failed")); vo.setContainersPending(rs.getInt("containers_pending")); vo.setAccount(rs.getString("account")); eMRClusterMetricsList.add(vo); } return eMRClusterMetricsList; } }
34.480769
95
0.767987
2f512a7e2064016636f031ee9a8f2c3a5ad8d221
2,918
import java.util.Scanner; import java.io.*; public class SimpleStateAwards { private static String[] allStates = new String[]{"AK", "AL", "AR", "AS", "AZ", "CA", "CO", "CT", "DC", "DE", "FL", "GA", "GU", "HI", "IA", "ID", "IL", "IN", "KS", "KY", "LA", "MA", "MD", "ME", "MI", "MN", "MO", "MP", "MS", "MT", "NC", "ND", "NE", "NH", "NJ", "NM", "NV", "NY", "OH", "OK", "OR", "PA", "PR", "RI", "SC", "SD", "TN", "TX", "UM", "UT", "VA", "VI", "VT", "WA", "WI", "WV", "WY"}; private static int getStateIndex(String name) { for (int i = 0; i < allStates.length; i++) { if (allStates[i].compareTo(name) == 0) { return i; } } return -1; } private static double[][] stateList(String filename){ int[] countPerState = new int[allStates.length]; int stateCount = 0; Scanner sc; try { BufferedReader br = new BufferedReader(new FileReader(filename)); br.readLine(); String current = null; while ((current = br.readLine()) != null) { String[] award = current.split("\",\""); int currentIndex = getStateIndex(award[7]); if (currentIndex != -1) { if (countPerState[currentIndex] == 0) { stateCount += 1; } countPerState[currentIndex] += 1; } } } catch (IOException e) { e.printStackTrace(); } double[][] statesReport = new double[stateCount][3]; int index = 0; for (int i = 0; i < allStates.length; i++){ if (countPerState[i] > 0) { statesReport[index][0] = i; try { BufferedReader br = new BufferedReader(new FileReader(filename)); br.readLine(); String current = null; while ((current = br.readLine()) != null) { String[] award = current.split("\",\""); if (allStates[i].compareTo(award[7]) == 0) { statesReport[index][1] += 1; statesReport[index][2] += Double.parseDouble(award[12].substring(1).replaceAll(",", "")); } } } catch (IOException e) { e.printStackTrace(); } index++; } } return statesReport; } public static void main(String[] args) { double[][] fundedStates = stateList("Awards_CISE_2019.csv"); for (int i = 0; i < fundedStates.length; i++) { System.out.printf("%s: %08.02f\n", allStates[(int)fundedStates[i][0]], fundedStates[i][2]); } } }
37.410256
103
0.43523
218caf1be3c50729070839fb2422de2be1b998f2
557
package org.ray.cli; import com.beust.jcommander.Parameter; import com.beust.jcommander.Parameters; /** * Arguments for command start. */ @Parameters(separators = "= ", commandDescription = "start ray daemons") public class CommandStart { @Parameter(names = "--head", description = "start the head node") public boolean head; @Parameter(names = "--config", description = "the config file of ray") public String config = ""; @Parameter(names = "--overwrite", description = "the overwrite items of config") public String overwrite = ""; }
25.318182
82
0.70377
f8e7b9f47fc1f3a443dd8210058b42c2cebb445f
250
package io.webapp.generator.mapper; import io.webapp.generator.entity.GeneratorConfig; import com.baomidou.mybatisplus.core.mapper.BaseMapper; /** * @author ADMIN */ public interface GeneratorConfigMapper extends BaseMapper<GeneratorConfig> { }
20.833333
76
0.804
a2deb623674d110e537711cd33e6104c5b7b61a2
5,397
/* * Copyright (C) 2010-2020 Evolveum and contributors * * This work is dual-licensed under the Apache License 2.0 * and European Union Public License. See LICENSE file for details. */ package com.evolveum.midpoint.gui.api.component; import java.util.ArrayList; import java.util.List; import javax.xml.namespace.QName; import org.apache.commons.collections4.CollectionUtils; import org.apache.wicket.markup.html.WebMarkupContainer; import org.apache.wicket.markup.html.panel.Fragment; import org.jetbrains.annotations.NotNull; import com.evolveum.midpoint.gui.api.page.PageBase; import com.evolveum.midpoint.gui.api.util.WebComponentUtil; import com.evolveum.midpoint.prism.PrismConstants; import com.evolveum.midpoint.prism.delta.ObjectDelta; import com.evolveum.midpoint.schema.util.ObjectTypeUtil; import com.evolveum.midpoint.util.QNameUtil; import com.evolveum.midpoint.util.exception.SchemaException; import com.evolveum.midpoint.util.logging.LoggingUtils; import com.evolveum.midpoint.util.logging.Trace; import com.evolveum.midpoint.util.logging.TraceManager; import com.evolveum.midpoint.web.component.input.RelationDropDownChoicePanel; import com.evolveum.midpoint.web.component.util.VisibleEnableBehaviour; import com.evolveum.midpoint.xml.ns._public.common.common_3.*; /** * Created by honchar */ public abstract class MemberPopupTabPanel<O extends ObjectType> extends AbstractPopupTabPanel<O> { private static final long serialVersionUID = 1L; private static final Trace LOGGER = TraceManager.getTrace(MemberPopupTabPanel.class); private static final String ID_RELATION_CONTAINER = "relationContainer"; private static final String ID_RELATION = "relation"; private PageBase pageBase; private final RelationSearchItemConfigurationType relationConfig; private final List<ObjectReferenceType> archetypeReferenceList; public MemberPopupTabPanel(String id, RelationSearchItemConfigurationType supportedRelationList) { this(id, supportedRelationList, new ArrayList<>()); } public MemberPopupTabPanel(String id, RelationSearchItemConfigurationType relationConfig, List<ObjectReferenceType> archetypeReferenceList) { super(id); this.relationConfig = relationConfig; this.archetypeReferenceList = archetypeReferenceList; } @Override protected void onInitialize() { super.onInitialize(); pageBase = getPageBase(); } @Override protected void initParametersPanel(Fragment parametersPanel) { WebMarkupContainer relationContainer = new WebMarkupContainer(ID_RELATION_CONTAINER); relationContainer.setOutputMarkupId(true); relationContainer.add(new VisibleEnableBehaviour() { private static final long serialVersionUID = 1L; @Override public boolean isVisible() { return CollectionUtils.isNotEmpty(relationConfig.getSupportedRelations()); } @Override public boolean isEnabled() { return CollectionUtils.isNotEmpty(relationConfig.getSupportedRelations()) && relationConfig.getSupportedRelations().size() > 1; } }); parametersPanel.add(relationContainer); relationContainer.add(new RelationDropDownChoicePanel( ID_RELATION, getDefaultRelation(), relationConfig.getSupportedRelations(), false)); } private QName getDefaultRelation() { QName relation = relationConfig.getDefaultValue(); if (QNameUtil.match(relation, PrismConstants.Q_ANY)) { QName defRelation = WebComponentUtil.getDefaultRelation(); if (relationConfig.getSupportedRelations().contains(defRelation)) { relation = defRelation; } else { relation = relationConfig.getSupportedRelations().iterator().next(); } } return relation; } protected ObjectDelta prepareDelta() { ObjectDelta delta = null; try { Class classType = WebComponentUtil.qnameToClass(pageBase.getPrismContext(), getObjectType().getTypeQName()); delta = pageBase.getPrismContext().deltaFactory() .object().createEmptyModifyDelta(classType, "fakeOid"); AssignmentType newAssignment = new AssignmentType(); ObjectReferenceType ref = ObjectTypeUtil.createObjectRef(getAbstractRoleTypeObject(), getRelationValue()); newAssignment.setTargetRef(ref); pageBase.getPrismContext().adopt(newAssignment); delta.addModificationAddContainer(FocusType.F_ASSIGNMENT, newAssignment); } catch (SchemaException e) { LoggingUtils.logUnexpectedException(LOGGER, "Failed to prepare delta for adding a member operation ", e); } return delta; } protected abstract AbstractRoleType getAbstractRoleTypeObject(); @Override protected List<ObjectReferenceType> getArchetypeRefList() { return archetypeReferenceList; } public @NotNull QName getRelationValue() { return getRelationDropDown() .getRelationValue(); } private RelationDropDownChoicePanel getRelationDropDown() { return (RelationDropDownChoicePanel) get(ID_PARAMETERS_PANEL).get(ID_RELATION_CONTAINER).get(ID_RELATION); } }
39.108696
120
0.7204
82ba8fa35386e5c43a70f9cab3ac0909230463d7
27,130
/* ### * IP: GHIDRA * * 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 ghidra.app.plugin.core.searchtext; import static org.junit.Assert.*; import java.awt.Component; import java.awt.Container; import java.awt.event.ActionListener; import java.util.*; import java.util.concurrent.atomic.AtomicReference; import javax.swing.*; import org.junit.*; import docking.action.DockingActionIf; import docking.widgets.fieldpanel.support.Highlight; import ghidra.app.plugin.core.codebrowser.CodeBrowserPlugin; import ghidra.app.plugin.core.codebrowser.CodeViewerProvider; import ghidra.app.plugin.core.marker.MarkerManagerPlugin; import ghidra.app.plugin.core.programtree.ProgramTreePlugin; import ghidra.app.services.GoToService; import ghidra.app.services.ProgramManager; import ghidra.app.util.HighlightProvider; import ghidra.app.util.viewer.field.*; import ghidra.app.util.viewer.format.*; import ghidra.app.util.viewer.listingpanel.ListingPanel; import ghidra.framework.options.Options; import ghidra.framework.plugintool.PluginTool; import ghidra.program.database.ProgramBuilder; import ghidra.program.model.address.Address; import ghidra.program.model.data.*; import ghidra.program.model.listing.*; import ghidra.program.model.symbol.*; import ghidra.program.util.*; import ghidra.test.AbstractGhidraHeadedIntegrationTest; import ghidra.test.TestEnv; import ghidra.util.exception.CancelledException; import ghidra.util.task.TaskMonitorComponent; import utilities.util.reflection.ReflectionUtilities; public class SearchTextPlugin3Test extends AbstractGhidraHeadedIntegrationTest { private TestEnv env; private PluginTool tool; private Program program; private SearchTextPlugin plugin; private DockingActionIf searchAction; private Listing listing; private CodeBrowserPlugin cbPlugin; private CodeViewerProvider provider; private GoToService goToService; public SearchTextPlugin3Test() { super(); } @Before public void setUp() throws Exception { env = new TestEnv(); tool = env.getTool(); tool.addPlugin(ProgramTreePlugin.class.getName()); tool.addPlugin(CodeBrowserPlugin.class.getName()); tool.addPlugin(SearchTextPlugin.class.getName()); tool.addPlugin(MarkerManagerPlugin.class.getName()); plugin = env.getPlugin(SearchTextPlugin.class); goToService = tool.getService(GoToService.class); program = buildProgram(); listing = program.getListing(); ProgramManager pm = tool.getService(ProgramManager.class); pm.openProgram(program.getDomainFile()); searchAction = getAction(plugin, "Search Text"); cbPlugin = env.getPlugin(CodeBrowserPlugin.class); provider = cbPlugin.getProvider(); env.showTool(); } private Program buildProgram() throws Exception { ProgramBuilder builder = new ProgramBuilder("TestX86", ProgramBuilder._X86); builder.createMemory(".text", Long.toHexString(0x1001000), 0x6600); builder.createMemory(".data", Long.toHexString(0x1008000), 0x600); builder.createMemory(".rsrc", Long.toHexString(0x100A000), 0x5400); builder.createMemory(".bound_import_table", Long.toHexString(0xF0000248), 0xA8); builder.createMemory(".debug_data", Long.toHexString(0xF0001300), 0x1C); builder.createComment("0x100415a", "scanf, fscanf, sscanf ...", CodeUnit.PRE_COMMENT); //create and disassemble a function builder.setBytes("0x0100415a", "55 8b ec 83 ec 0c 33 c0 c7 45 f8 01 00 00 00 21 45 fc 39 45 08 c7 45 f4 04" + " 00 00 00 74 1a 8d 45 f4 50 8d 45 f8 50 8d 45 fc 50 6a 00 ff 75 0c ff 75 08 " + "ff 15 08 10 00 01 85 c0 75 06 83 7d fc 04 74 05 8b 45 10 eb 03 8b 45 f8 c9 " + "c2 0c 00"); builder.disassemble("0x0100415a", 0x4d, true); Function function = builder.createEmptyFunction("sscanf", "0x0100415a", 77, DataType.DEFAULT); builder.createLocalVariable(function, "i", new WordDataType(), -4); builder.createLocalVariable(function, "count", new FloatDataType(), -8); builder.createLocalVariable(function, "formatCount", new ByteDataType(), -12); builder.createStackReference("100416f", RefType.DATA, -12, SourceType.USER_DEFINED, 0); builder.createStackReference("1004178", RefType.DATA, -12, SourceType.USER_DEFINED, 1); builder.setBytes("0100448f", "e8 c6 fc ff ff", true); builder.createMemoryReference("1001000", "1004000", RefType.COMPUTED_JUMP, SourceType.ANALYSIS); builder.createMemoryReference("1001000", "1004010", RefType.COMPUTED_JUMP, SourceType.ANALYSIS); builder.createMemoryReference("1001000", "1004020", RefType.COMPUTED_JUMP, SourceType.ANALYSIS); builder.createMemoryReference("1001000", "1004030", RefType.COMPUTED_JUMP, SourceType.ANALYSIS); builder.createMemoryReference("1001000", "1004040", RefType.COMPUTED_JUMP, SourceType.ANALYSIS); builder.createMemoryReference("1001000", "1004050", RefType.COMPUTED_JUMP, SourceType.ANALYSIS); builder.createMemoryReference("1001000", "1004060", RefType.COMPUTED_JUMP, SourceType.ANALYSIS); builder.createMemoryReference("1001000", "1004070", RefType.COMPUTED_JUMP, SourceType.ANALYSIS); builder.applyDataType("1001000", new PointerDataType()); builder.applyDataType("1001004", new PointerDataType()); builder.applyDataType("1001008", new PointerDataType()); builder.applyDataType("100100c", new PointerDataType()); builder.applyDataType("1001010", new PointerDataType()); builder.applyDataType("1001014", new PointerDataType()); builder.applyDataType("1001018", new PointerDataType()); builder.setBytes("0x01002cf5", "55 8b ec 83 7d 14 00 56 8b 35 e0 10 00 01 57 74 09 ff 75 14 ff d6 8b f8 " + "eb 02 33 ff ff 75 10 ff d6 03 c7 8d 44 00 02 50 6a 40 ff 15 dc 10 00 01 8b " + "f0 85 f6 74 27 56 ff 75 14 ff 75 10 e8 5c ff ff ff ff 75 18 ff 75 0c 56 ff 75" + " 08 ff 15 04 12 00 01 56 8b f8 ff 15 c0 10 00 01 eb 14 ff 75 18 ff 75 0c ff 75" + "10 ff 75 08 ff 15 04 12 00 01 8b f8 8b c7 5f 5e 5d c2 14"); builder.disassemble("0x01002cf5", 0x121, true); ParameterImpl param = new ParameterImpl(null, new WordDataType(), builder.getProgram()); builder.createEmptyFunction("ghidra", "0x01002cf5", 60, DataType.DEFAULT, param, param, param, param); builder.setBytes("1002c93", "8b 4c 24 04 8b 44 24 0c 56 57"); builder.disassemble("1002c93", 10); builder.createEmptyFunction("foo", "0x01002c9c", 10, DataType.DEFAULT); return builder.getProgram(); } @After public void tearDown() throws Exception { runSwing(() -> tool.close()); env.release(program); env.dispose(); } @Test public void testCancelSearch() throws Exception { cancelSearch(SearchTextPlugin1Test.EXACT_MATCH_SEARCH); } @Test public void testCancelSearchQuick() throws Exception { cancelSearch(SearchTextPlugin1Test.QUICK_SEARCH); } @Test public void testSearchOrder() throws Exception { // Only for the Quick Search... // put hits on search in comments CodeUnit cu = listing.getCodeUnitAt(getAddr(0x01002c97)); int transactionID = program.startTransaction("test"); cu.setComment(CodeUnit.PLATE_COMMENT, "find hit for eax"); cu.setComment(CodeUnit.PRE_COMMENT, "find another hit for eax"); SymbolTable st = program.getSymbolTable(); st.createLabel(cu.getMinAddress(), "My_EAX", SourceType.USER_DEFINED); cu.setComment(CodeUnit.EOL_COMMENT, "eol comment for eax"); cu.setComment(CodeUnit.POST_COMMENT, "last comment for eax"); program.endTransaction(transactionID, true); SearchTextDialog dialog = getDialog(); JComponent container = dialog.getComponent(); JTextField tf = findTextField(container); JCheckBox cb = (JCheckBox) findAbstractButtonByText(container, "Functions"); cb.setSelected(true); cb = (JCheckBox) findAbstractButtonByText(container, "Labels"); setToggleButtonSelected(cb, true); cb = (JCheckBox) findAbstractButtonByText(container, "Instruction Mnemonics"); setToggleButtonSelected(cb, true); cb = (JCheckBox) findAbstractButtonByText(container, "Instruction Operands"); setToggleButtonSelected(cb, true); cb = (JCheckBox) findAbstractButtonByText(container, "Defined Data Mnemonics"); setToggleButtonSelected(cb, true); cb = (JCheckBox) findAbstractButtonByText(container, "Defined Data Values"); setToggleButtonSelected(cb, true); goToService.goTo(new ProgramLocation(program, getAddr(0x01002c92))); ActionListener listener = tf.getActionListeners()[0]; runSwing(() -> { tf.setText("eax"); listener.actionPerformed(null); }); waitForSearchTasks(dialog); ProgramLocation loc = cbPlugin.getCurrentLocation(); assertTrue(loc instanceof CommentFieldLocation); assertEquals(CodeUnit.PLATE_COMMENT, ((CommentFieldLocation) loc).getCommentType()); assertEquals(cu.getMinAddress(), loc.getAddress()); runSwing(() -> listener.actionPerformed(null)); waitForSearchTasks(dialog); loc = cbPlugin.getCurrentLocation(); assertTrue(loc instanceof CommentFieldLocation); assertEquals(CodeUnit.PRE_COMMENT, ((CommentFieldLocation) loc).getCommentType()); runSwing(() -> listener.actionPerformed(null)); waitForSearchTasks(dialog); loc = cbPlugin.getCurrentLocation(); assertTrue(loc instanceof LabelFieldLocation); assertEquals(3, ((LabelFieldLocation) loc).getCharOffset()); runSwing(() -> listener.actionPerformed(null)); waitForSearchTasks(dialog); loc = cbPlugin.getCurrentLocation(); assertTrue(loc instanceof OperandFieldLocation); assertEquals(0, ((OperandFieldLocation) loc).getOperandIndex()); assertEquals(cu.getMinAddress(), loc.getAddress()); runSwing(() -> listener.actionPerformed(null)); waitForSearchTasks(dialog); loc = cbPlugin.getCurrentLocation(); assertTrue(loc instanceof CommentFieldLocation); assertEquals(CodeUnit.EOL_COMMENT, ((CommentFieldLocation) loc).getCommentType()); assertEquals(cu.getMinAddress(), loc.getAddress()); runSwing(() -> listener.actionPerformed(null)); waitForSearchTasks(dialog); loc = cbPlugin.getCurrentLocation(); assertTrue(loc instanceof CommentFieldLocation); assertEquals(CodeUnit.POST_COMMENT, ((CommentFieldLocation) loc).getCommentType()); assertEquals(cu.getMinAddress(), loc.getAddress()); } @Test public void testSearchOrderForFunction() throws Exception { // ONLY for the Quick Search... // put "sscanf" in function comments int transactionID = program.startTransaction("test"); List<Function> globalFunctions = listing.getGlobalFunctions("sscanf"); assertEquals(1, globalFunctions.size()); Function f = globalFunctions.get(0); f.setComment("Function comment for sscanf"); StackFrame frame = f.getStackFrame(); Variable[] vars = frame.getStackVariables(); vars[1].setComment("this is a comment for sscanf"); program.endTransaction(transactionID, true); SearchTextDialog dialog = getDialog(); JComponent container = dialog.getComponent(); JTextField tf = findTextField(container); JButton searchButton = (JButton) findAbstractButtonByText(container, "Next"); JCheckBox cb = (JCheckBox) findAbstractButtonByText(container, "Functions"); setToggleButtonSelected(cb, true); runSwing(() -> { tf.setText("sscanf"); searchButton.getActionListeners()[0].actionPerformed(null); }); waitForSearchTasks(dialog); ProgramLocation loc = cbPlugin.getCurrentLocation(); assertTrue(loc instanceof CommentFieldLocation); assertEquals(CodeUnit.PLATE_COMMENT, ((CommentFieldLocation) loc).getCommentType()); ActionListener listener = searchButton.getActionListeners()[0]; runSwing(() -> listener.actionPerformed(null)); waitForSearchTasks(dialog); loc = cbPlugin.getCurrentLocation(); assertTrue(loc instanceof FunctionSignatureFieldLocation); runSwing(() -> listener.actionPerformed(null)); waitForSearchTasks(dialog); loc = cbPlugin.getCurrentLocation(); assertTrue(loc instanceof VariableCommentFieldLocation); runSwing(() -> listener.actionPerformed(null)); waitForSearchTasks(dialog); loc = cbPlugin.getCurrentLocation(); assertTrue(loc instanceof CommentFieldLocation); assertEquals(CodeUnit.PRE_COMMENT, ((CommentFieldLocation) loc).getCommentType()); } @Test public void testSaveState() { Options options = tool.getOptions("Search"); options.setInt("Search Limit", 20); env.saveRestoreToolState(); assertEquals(20, plugin.getResultsLimit()); } @Test public void testExactSearchMnemonicOperandBackward() throws Exception { DockingActionIf toggleAction = getAction(cbPlugin, "Toggle Header"); performAction(toggleAction, provider, true); ListingPanel listingPanel = cbPlugin.getListingPanel(); FieldHeader headerPanel = listingPanel.getFieldHeader(); assertNotNull(provider); assertTrue(cbPlugin.goToField(getAddr(0x10018f4), OperandFieldFactory.FIELD_NAME, 0, 0)); FieldHeaderComp header = headerPanel.getHeaderTab(); FieldFormatModel model = header.getModel(); assertEquals("Instruction/Data", model.getName()); runSwing(() -> model.removeAllFactories()); addField(model, AddressFieldFactory.FIELD_NAME, 0); addField(model, MnemonicFieldFactory.FIELD_NAME, 1); addField(model, OperandFieldFactory.FIELD_NAME, 2); // create Plate, pre, end of line, post and repeatable comments // that contain a hit for a search CodeUnit cu = listing.getCodeUnitAt(getAddr(0x0100416f)); int transactionID = program.startTransaction("test"); cu.setComment(CodeUnit.EOL_COMMENT, "call sscanf"); cu = listing.getCodeUnitAt(getAddr(0x01004178)); cu.setComment(CodeUnit.REPEATABLE_COMMENT, "make a reference to sscanf"); cu = listing.getCodeUnitAt(getAddr(0x01004192)); cu.setComment(CodeUnit.POST_COMMENT, "sscanf in a post comment"); cu = listing.getCodeUnitAt(getAddr(0x0100467b)); cu.setComment(CodeUnit.PRE_COMMENT, "call sscanf here"); program.endTransaction(transactionID, true); SearchTextDialog dialog = getDialog(); JComponent container = dialog.getComponent(); JTextField tf = findTextField(container); selectRadioButton(container, SearchTextPlugin1Test.EXACT_MATCH_SEARCH); JCheckBox cb = (JCheckBox) findAbstractButtonByText(container, "Instruction Mnemonics"); setToggleButtonSelected(cb, true); cb = (JCheckBox) findAbstractButtonByText(container, "Instruction Operands"); setToggleButtonSelected(cb, true); cb = (JCheckBox) findAbstractButtonByText(container, "Comments"); setToggleButtonSelected(cb, false); goToService.goTo(new ProgramLocation(program, getAddr(0x01004160))); runSwing(() -> tf.setText("sscanf")); JButton searchButton = (JButton) findAbstractButtonByText(container, "Previous"); pressButton(searchButton); waitForSearchTasks(dialog); Symbol symbol = getUniqueSymbol(program, "sscanf"); ReferenceManager refMgr = program.getReferenceManager(); ReferenceIterator iter = refMgr.getReferencesTo(symbol.getAddress()); List<Address> list = new ArrayList<>(); while (iter.hasNext()) { Reference ref = iter.next(); list.add(ref.getFromAddress()); } // go to the end of the program assertTrue( cbPlugin.goToField(program.getMaxAddress(), OperandFieldFactory.FIELD_NAME, 0, 0)); Collections.sort(list); Collections.reverse(list); for (int i = 0; i < list.size(); i++) { Address addr = list.get(i); pressSearchButton(dialog, searchButton); ProgramLocation loc = cbPlugin.getCurrentLocation(); assertEquals(addr, loc.getAddress()); assertTrue(loc instanceof OperandFieldLocation); } } private void addField(FieldFormatModel model, String fieldName, int column) { FieldFactory[] allFactories = model.getAllFactories(); for (FieldFactory fieldFactory : allFactories) { if (fieldFactory.getFieldName().equals(fieldName)) { runSwing(() -> model.addFactory(fieldFactory, 0, column)); return; } } } @Test public void testExactSearchMnemonicOperandForward() throws Exception { DockingActionIf toggleAction = getAction(cbPlugin, "Toggle Header"); performAction(toggleAction, provider, true); ListingPanel listingPanel = cbPlugin.getListingPanel(); FieldHeader headerPanel = listingPanel.getFieldHeader(); assertTrue(cbPlugin.goToField(getAddr(0x10018f4), OperandFieldFactory.FIELD_NAME, 0, 0)); FieldHeaderComp header = headerPanel.getHeaderTab(); FieldFormatModel model = header.getModel(); assertEquals("Instruction/Data", model.getName()); runSwing(() -> model.removeAllFactories()); addField(model, AddressFieldFactory.FIELD_NAME, 0); addField(model, OperandFieldFactory.FIELD_NAME, 1); // create Plate, pre, end of line, post and repeatable comments // that contain a hit for a search CodeUnit cu = listing.getCodeUnitAt(getAddr(0x0100416f)); int transactionID = program.startTransaction("test"); cu.setComment(CodeUnit.EOL_COMMENT, "call sscanf"); cu = listing.getCodeUnitAt(getAddr(0x01004178)); cu.setComment(CodeUnit.REPEATABLE_COMMENT, "make a reference to sscanf"); cu = listing.getCodeUnitAt(getAddr(0x01004192)); cu.setComment(CodeUnit.POST_COMMENT, "sscanf in a post comment"); cu = listing.getCodeUnitAt(getAddr(0x0100467b)); cu.setComment(CodeUnit.PRE_COMMENT, "call sscanf here"); program.endTransaction(transactionID, true); SearchTextDialog dialog = getDialog(); JComponent container = dialog.getComponent(); final JTextField tf = findTextField(container); selectRadioButton(container, SearchTextPlugin1Test.EXACT_MATCH_SEARCH); JCheckBox cb = (JCheckBox) findAbstractButtonByText(container, "Instruction Mnemonics"); setToggleButtonSelected(cb, true); cb = (JCheckBox) findAbstractButtonByText(container, "Instruction Operands"); setToggleButtonSelected(cb, true); cb = (JCheckBox) findAbstractButtonByText(container, "Comments"); setToggleButtonSelected(cb, true); // Backwards goToService.goTo(new ProgramLocation(program, getAddr(0x01004160))); runSwing(() -> tf.setText("call sscanf")); JButton searchButton = (JButton) findAbstractButtonByText(container, "Previous"); pressButton(searchButton); waitForSearchTasks(dialog); Symbol symbol = getUniqueSymbol(program, "sscanf"); ReferenceManager refMgr = program.getReferenceManager(); ReferenceIterator iter = refMgr.getReferencesTo(symbol.getAddress()); List<Address> list = new ArrayList<>(); while (iter.hasNext()) { Reference ref = iter.next(); list.add(ref.getFromAddress()); } // go to the end of the program assertTrue( cbPlugin.goToField(program.getMinAddress(), OperandFieldFactory.FIELD_NAME, 0, 0)); pressSearchButton(dialog, searchButton); ProgramLocation loc = cbPlugin.getCurrentLocation(); assertEquals(program.getMinAddress(), loc.getAddress()); assertEquals("Not found", dialog.getStatusText()); } @Test public void testHighlights() throws Exception { SearchTextDialog dialog = getDialog(); JComponent container = dialog.getComponent(); JTextField tf = findTextField(container); JCheckBox cb = (JCheckBox) findAbstractButtonByText(container, "Instruction Mnemonics"); setToggleButtonSelected(cb, true); cb = (JCheckBox) findAbstractButtonByText(container, "Instruction Operands"); setToggleButtonSelected(cb, true); cb = (JCheckBox) findAbstractButtonByText(container, "Functions"); setToggleButtonSelected(cb, true); String searchText = "param_"; runSwing(() -> { tf.setText(searchText); ActionListener[] listeners = tf.getActionListeners(); listeners[0].actionPerformed(null); }); waitForSearchTasks(dialog); ProgramLocation loc = plugin.getNavigatable().getLocation(); assertTrue(loc instanceof FunctionSignatureFieldLocation); assertEquals(0x1002cf5, loc.getAddress().getOffset()); verifyPluginHighlightText(searchText); String signature = ((FunctionSignatureFieldLocation) loc).getSignature(); Function function = listing.getFunctionAt(loc.getAddress()); HighlightProvider highlightProvider = cbPlugin.getFormatManager().getFormatHighlightProvider(); Highlight[] h = highlightProvider.getHighlights(signature, function, FunctionSignatureFieldFactory.class, signature.indexOf(searchText)); assertEquals(1, h.length); runSwing(() -> dialog.close()); // highlights should be gone h = highlightProvider.getHighlights(signature, function, FunctionSignatureFieldFactory.class, -1); assertEquals(0, h.length); } private void verifyPluginHighlightText(String text) { final AtomicReference<String> ref = new AtomicReference<>(); runSwing(() -> ref.set(plugin.getLastSearchText())); assertEquals("Plugin does not have current search text", text, ref.get()); } @Test public void testHighlightsWithMultipleProviders() throws Exception { SearchTextDialog dialog = getDialog(); JComponent container = dialog.getComponent(); JTextField tf = findTextField(container); JCheckBox cb = (JCheckBox) findAbstractButtonByText(container, "Instruction Mnemonics"); setToggleButtonSelected(cb, true); cb = (JCheckBox) findAbstractButtonByText(container, "Instruction Operands"); setToggleButtonSelected(cb, true); cb = (JCheckBox) findAbstractButtonByText(container, "Functions"); setToggleButtonSelected(cb, true); JButton searchAllButton = (JButton) getInstanceField("allButton", dialog); runSwing(() -> { tf.setText("param_"); searchAllButton.doClick(); }); while (plugin.isWaitingForSearchAll()) { Thread.sleep(20); } waitForSwing(); // first match at: 0x01002cf5 Address addr = getAddr(0x01002cf5); cbPlugin.goToField(addr, "Function Signature", 0, 32); waitForSwing(); ProgramLocation loc = plugin.getNavigatable().getLocation(); assertTrue(loc instanceof FunctionSignatureFieldLocation); String signature = ((FunctionSignatureFieldLocation) loc).getSignature(); Function function = listing.getFunctionAt(loc.getAddress()); HighlightProvider highlightProvider = cbPlugin.getFormatManager().getFormatHighlightProvider(); Highlight[] h = highlightProvider.getHighlights(signature, function, FunctionSignatureFieldFactory.class, -1); int numberOfHighlights = h.length; assertTrue("Did not find highlights at expected field.", (numberOfHighlights > 0)); // re-show the dialog to perform a new search SearchTextDialog dialogTwo = getDialog(); container = dialogTwo.getComponent(); JTextField tfTwo = findTextField(container); JButton searchAllButtonTwo = (JButton) getInstanceField("allButton", dialog); runSwing(() -> { tfTwo.setText("text"); searchAllButtonTwo.doClick(); }); while (plugin.isWaitingForSearchAll()) { Thread.sleep(20); } waitForSwing(); // first match at: 0x01002b39 addr = getAddr(0x01002b39); cbPlugin.goToField(addr, "Operands", 0, 2); waitForSwing(); loc = plugin.getNavigatable().getLocation(); assertTrue(loc instanceof OperandFieldLocation); OperandFieldLocation operandLocation = (OperandFieldLocation) loc; Instruction instruction = listing.getInstructionAt(addr); h = highlightProvider.getHighlights(operandLocation.getOperandRepresentation(), instruction, OperandFieldFactory.class, 0); assertTrue("Did not update highlights for new search.", (numberOfHighlights != h.length)); } private void cancelSearch(String buttonText) throws Exception { SearchTextDialog dialog = getDialog(); JComponent container = dialog.getComponent(); JTextField tf = findTextField(container); selectRadioButton(container, buttonText); JCheckBox cb = (JCheckBox) findAbstractButtonByText(container, "Functions"); setToggleButtonSelected(cb, true); cb = (JCheckBox) findAbstractButtonByText(container, "Labels"); setToggleButtonSelected(cb, true); cb = (JCheckBox) findAbstractButtonByText(container, "Instruction Mnemonics"); setToggleButtonSelected(cb, true); cb = (JCheckBox) findAbstractButtonByText(container, "Instruction Operands"); setToggleButtonSelected(cb, true); cb = (JCheckBox) findAbstractButtonByText(container, "Defined Data Mnemonics"); setToggleButtonSelected(cb, true); cb = (JCheckBox) findAbstractButtonByText(container, "Defined Data Values"); setToggleButtonSelected(cb, true); // install our own task monitor so we can cancel before the task finishes CancellingStubTaskMonitorComponent testMonitor = new CancellingStubTaskMonitorComponent(); setInstanceField("taskMonitorComponent", dialog, testMonitor); setText(tf, "hello"); triggerEnter(tf); waitForSearchTasks(dialog); String text = runSwing(() -> dialog.getStatusText()); assertTrue("expected:<Search cancelled> or <operation canceled> but was:<" + text + ">", text != null && (text.equals("Search cancelled") || text.equals("operation canceled"))); } private void selectRadioButton(Container container, String buttonText) throws Exception { final JRadioButton rb = (JRadioButton) findAbstractButtonByText(container, buttonText); runSwing(() -> rb.setSelected(true)); } private SearchTextDialog getDialog() throws Exception { runSwing(() -> searchAction.actionPerformed(provider.getActionContext(null))); return plugin.getSearchDialog(); } private Address getAddr(int offset) { return program.getMinAddress().getNewAddress(offset); } private JTextField findTextField(Container container) { Component[] c = container.getComponents(); for (Component element : c) { if (element instanceof JTextField) { return (JTextField) element; } if (element instanceof Container) { JTextField tf = findTextField((Container) element); if (tf != null) { return tf; } } } return null; } private void pressSearchButton(SearchTextDialog dialog, JButton searchButton) throws InterruptedException { pressButton(searchButton); waitForSearchTasks(dialog); cbPlugin.updateNow(); } private void waitForSearchTasks(SearchTextDialog dialog1) throws InterruptedException { waitForSwing(); Thread t = dialog1.getTaskScheduler().getCurrentThread(); if (t == null) { // just in case we missed the thread and the callback hasn't happened yet waitForSwing(); t = dialog1.getTaskScheduler().getCurrentThread(); } while (t != null) { t.join(); waitForSwing(); t = dialog1.getTaskScheduler().getCurrentThread(); } waitForSwing(); } /* * A task monitor class that will cancel itself when it is run from the SearchTask */ private class CancellingStubTaskMonitorComponent extends TaskMonitorComponent { @Override public void checkCanceled() throws CancelledException { if (calledFromSearchTask()) { throw new CancelledException(); } } @Override public boolean isCancelled() { return calledFromSearchTask(); } private boolean calledFromSearchTask() { String s = ReflectionUtilities.stackTraceToString(new Throwable()); return s.contains(SearchTask.class.getSimpleName()); } } }
37.215364
94
0.756027
6716450abb668e7bd119f302c65c92b2548482e1
2,022
/** * Copyright 2021 Tianmian Tech. 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.welab.wefe.board.service.api.account; import com.welab.wefe.common.exception.StatusCodeWithException; import com.welab.wefe.common.web.api.base.AbstractNoneInputApi; import com.welab.wefe.common.web.api.base.Api; import com.welab.wefe.common.web.dto.AbstractApiOutput; import com.welab.wefe.common.web.dto.ApiResult; import com.welab.wefe.common.web.dto.Captcha; import com.welab.wefe.common.web.service.CaptchaService; /** * @author hunter.zhao */ @Api(path = "account/captcha", name = "get captcha", login = false) public class CaptchaApi extends AbstractNoneInputApi<CaptchaApi.Output> { @Override protected ApiResult<Output> handle() throws StatusCodeWithException { Captcha captcha = CaptchaService.get(); Output output = new Output(); output.setKey(captcha.getKey()); output.setImage(captcha.getImage()); return success(output); } public static class Output extends AbstractApiOutput { private String image; private String key; //region getter/setter public String getImage() { return image; } public void setImage(String image) { this.image = image; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } //endregion } }
28.083333
75
0.681503
9f6812119dbdcd0c63ff28aec81586dd8586635a
1,032
package xmilcode.mclib.util; import xmilcode.gianttreemod.mob.stickman.StickManEntity; import cpw.mods.fml.common.registry.EntityRegistry; import net.minecraft.entity.EntityLiving; import net.minecraft.entity.EnumCreatureType; import net.minecraft.world.biome.BiomeGenBase; public class EntityUtil { public static void addSpawnForAllBiomes( Class <? extends EntityLiving > entityClass, int spawnFrequency, int minSpawned, int maxSpawned, EnumCreatureType creatureType) { for (int i = 0; i < BiomeGenBase.getBiomeGenArray().length; ++i) { BiomeGenBase biome = BiomeGenBase.getBiomeGenArray()[i]; if (biome != null) { EntityRegistry.addSpawn( entityClass, spawnFrequency, minSpawned, maxSpawned, creatureType, biome); } } } }
29.485714
72
0.564922
61f34e4e3fc45f493c39e5d3549f04feb6e8dced
91,198
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. package com.cloud.network.as; import java.security.InvalidParameterException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Arrays; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import javax.inject.Inject; import com.cloud.event.ActionEventUtils; import com.cloud.network.as.dao.AutoScaleVmProfileNetworkMapDao; import com.cloud.network.dao.NetworkVO; import com.cloud.server.ResourceTag; import com.cloud.server.TaggedResourceService; import com.cloud.tags.ResourceTagVO; import com.cloud.tags.dao.ResourceTagDao; import com.cloud.vm.UserVmVO; import com.cloud.vm.dao.UserVmDao; import org.apache.cloudstack.framework.config.ConfigKey; import org.apache.cloudstack.framework.config.Configurable; import org.apache.commons.codec.binary.Base64; import org.apache.log4j.Logger; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import org.apache.cloudstack.acl.ControlledEntity; import org.apache.cloudstack.api.ApiConstants; import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseCmd.HTTPMethod; import org.apache.cloudstack.api.BaseListAccountResourcesCmd; import org.apache.cloudstack.api.ServerApiException; import org.apache.cloudstack.api.command.admin.autoscale.CreateCounterCmd; import org.apache.cloudstack.api.command.user.autoscale.CreateAutoScalePolicyCmd; import org.apache.cloudstack.api.command.user.autoscale.CreateAutoScaleVmGroupCmd; import org.apache.cloudstack.api.command.user.autoscale.CreateAutoScaleVmProfileCmd; import org.apache.cloudstack.api.command.user.autoscale.CreateConditionCmd; import org.apache.cloudstack.api.command.user.autoscale.ListAutoScalePoliciesCmd; import org.apache.cloudstack.api.command.user.autoscale.ListAutoScaleVmGroupsCmd; import org.apache.cloudstack.api.command.user.autoscale.ListAutoScaleVmProfilesCmd; import org.apache.cloudstack.api.command.user.autoscale.ListConditionsCmd; import org.apache.cloudstack.api.command.user.autoscale.ListCountersCmd; import org.apache.cloudstack.api.command.user.autoscale.UpdateAutoScalePolicyCmd; import org.apache.cloudstack.api.command.user.autoscale.UpdateAutoScaleVmGroupCmd; import org.apache.cloudstack.api.command.user.autoscale.UpdateAutoScaleVmProfileCmd; import org.apache.cloudstack.api.command.user.vm.DeployVMCmd; import org.apache.cloudstack.config.ApiServiceConfiguration; import org.apache.cloudstack.context.CallContext; import org.apache.cloudstack.framework.config.dao.ConfigurationDao; import com.cloud.api.ApiDBUtils; import com.cloud.api.dispatch.DispatchChainFactory; import com.cloud.api.dispatch.DispatchTask; import com.cloud.configuration.ConfigurationManager; import com.cloud.dc.DataCenter; import com.cloud.dc.DataCenter.NetworkType; import com.cloud.dc.dao.DataCenterDao; import com.cloud.event.ActionEvent; import com.cloud.event.EventTypes; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; import com.cloud.exception.InsufficientServerCapacityException; import com.cloud.exception.InvalidParameterValueException; import com.cloud.exception.ResourceAllocationException; import com.cloud.exception.ResourceInUseException; import com.cloud.exception.ResourceUnavailableException; import com.cloud.hypervisor.Hypervisor.HypervisorType; import com.cloud.network.Network.Capability; import com.cloud.network.Network.IpAddresses; import com.cloud.network.as.AutoScaleCounter.AutoScaleCounterParam; import com.cloud.network.as.dao.AutoScalePolicyConditionMapDao; import com.cloud.network.as.dao.AutoScalePolicyDao; import com.cloud.network.as.dao.AutoScaleVmGroupDao; import com.cloud.network.as.dao.AutoScaleVmGroupPolicyMapDao; import com.cloud.network.as.dao.AutoScaleVmGroupVmMapDao; import com.cloud.network.as.dao.AutoScaleVmProfileDao; import com.cloud.network.as.dao.ConditionDao; import com.cloud.network.as.dao.CounterDao; import com.cloud.network.dao.IPAddressDao; import com.cloud.network.dao.LoadBalancerDao; import com.cloud.network.dao.LoadBalancerVMMapDao; import com.cloud.network.dao.LoadBalancerVMMapVO; import com.cloud.network.dao.LoadBalancerVO; import com.cloud.network.dao.LoadBalancerNetworkMapVO; import com.cloud.network.dao.NetworkDao; import com.cloud.network.dao.LoadBalancerNetworkMapDao; import com.cloud.vm.dao.NicDao; import com.cloud.network.lb.LoadBalancingRule; import com.cloud.network.lb.LoadBalancingRulesManager; import com.cloud.network.lb.LoadBalancingRulesService; import com.cloud.network.rules.LoadBalancer; import com.cloud.offering.ServiceOffering; import com.cloud.projects.Project.ListProjectResourcesCriteria; import com.cloud.template.TemplateManager; import com.cloud.template.VirtualMachineTemplate; import com.cloud.user.Account; import com.cloud.user.AccountManager; import com.cloud.user.AccountService; import com.cloud.user.User; import com.cloud.user.dao.AccountDao; import com.cloud.user.dao.UserDao; import com.cloud.uservm.UserVm; import com.cloud.utils.Pair; import com.cloud.utils.Ternary; import com.cloud.utils.component.ComponentContext; import com.cloud.utils.component.ManagerBase; import com.cloud.utils.db.DB; import com.cloud.utils.db.EntityManager; import com.cloud.utils.db.Filter; import com.cloud.utils.db.GenericDao; import com.cloud.utils.db.JoinBuilder; import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchCriteria; import com.cloud.utils.db.TransactionCallback; import com.cloud.utils.db.SearchCriteria.Op; import com.cloud.utils.db.Transaction; import com.cloud.utils.db.TransactionStatus; import com.cloud.utils.net.NetUtils; import com.cloud.vm.UserVmManager; import com.cloud.vm.UserVmService; import com.cloud.vm.Nic; public class AutoScaleManagerImpl<Type> extends ManagerBase implements AutoScaleManager, AutoScaleService, Configurable { private static final Logger s_logger = Logger.getLogger(AutoScaleManagerImpl.class); protected ScheduledExecutorService _executor = Executors.newScheduledThreadPool(1); @Inject protected DispatchChainFactory dispatchChainFactory = null; @Inject EntityManager _entityMgr; @Inject AccountDao _accountDao; @Inject AccountManager _accountMgr; @Inject ConfigurationManager _configMgr; @Inject TemplateManager _templateMgr; @Inject LoadBalancingRulesManager _lbRulesMgr; @Inject NetworkDao _networkDao; @Inject CounterDao _counterDao; @Inject ConditionDao _conditionDao; @Inject LoadBalancerVMMapDao _lb2VmMapDao; @Inject LoadBalancerDao _lbDao; @Inject AutoScaleVmProfileDao _autoScaleVmProfileDao; @Inject AutoScaleVmProfileNetworkMapDao _autoScaleVmProfileNetworkMapDao; @Inject AutoScalePolicyDao _autoScalePolicyDao; @Inject AutoScalePolicyConditionMapDao _autoScalePolicyConditionMapDao; @Inject AutoScaleVmGroupDao _autoScaleVmGroupDao; @Inject AutoScaleVmGroupPolicyMapDao _autoScaleVmGroupPolicyMapDao; @Inject AutoScaleVmGroupVmMapDao _autoScaleVmGroupVmMapDao; @Inject DataCenterDao _dcDao = null; @Inject UserDao _userDao; @Inject ConfigurationDao _configDao; @Inject IPAddressDao _ipAddressDao; @Inject AccountService _accountService; @Inject UserVmService _userVmService; @Inject UserVmManager _userVmManager; @Inject LoadBalancerVMMapDao _lbVmMapDao; @Inject NicDao _nicDao; @Inject LoadBalancerNetworkMapDao _lbNetMapDao; @Inject LoadBalancingRulesService _loadBalancingRulesService; @Inject ResourceTagDao _resourceTagDao; @Inject UserVmDao _userVmDao; @Inject TaggedResourceService _taggedResourceService; private static final int MAX_HTTP_POST_LENGTH = 16 * 2048; private static final ConfigKey<String> AutoScaledVmPrefix = new ConfigKey<String>("Advanced", String.class, "autoscale.vm.prefix", "as-vm-", "Auto scaled virtual machine name prefix", true, ConfigKey.Scope.Global); public List<AutoScaleCounter> getSupportedAutoScaleCounters(long networkid) { String capability = _lbRulesMgr.getLBCapability(networkid, Capability.AutoScaleCounters.getName()); if (capability == null) { return null; } Gson gson = new Gson(); java.lang.reflect.Type listType = new TypeToken<List<AutoScaleCounter>>() { }.getType(); List<AutoScaleCounter> result = gson.fromJson(capability, listType); return result; } public void validateAutoScaleCounters(long networkid, List<Counter> counters, List<Pair<String, String>> counterParamPassed) { List<AutoScaleCounter> supportedCounters = getSupportedAutoScaleCounters(networkid); if (supportedCounters == null) { throw new InvalidParameterException("AutoScale is not supported in the network"); } for (Counter counter : counters) { String counterName = counter.getSource().name().toString(); boolean isCounterSupported = false; for (AutoScaleCounter autoScaleCounter : supportedCounters) { if (autoScaleCounter.getName().equals(counterName)) { isCounterSupported = true; List<AutoScaleCounterParam> counterParams = autoScaleCounter.getParamList(); for (AutoScaleCounterParam autoScaleCounterParam : counterParams) { boolean isRequiredParameter = autoScaleCounterParam.getRequired(); if (isRequiredParameter) { boolean isRequiredParamPresent = false; for (Pair<String, String> pair : counterParamPassed) { if (pair.first().equals(autoScaleCounterParam.getParamName())) isRequiredParamPresent = true; } if (!isRequiredParamPresent) { throw new InvalidParameterException("Parameter " + autoScaleCounterParam.getParamName() + " has to be set in AutoScaleVmProfile's " + ApiConstants.COUNTERPARAM_LIST); } } } break; } } if (!isCounterSupported) { throw new InvalidParameterException("AutoScale counter with source='" + counter.getSource().name() + "' is not supported " + "in the network"); } } } private <VO extends ControlledEntity> VO getEntityInDatabase(Account caller, String paramName, Long id, GenericDao<VO, Long> dao) { VO vo = dao.findById(id); if (vo == null) { throw new InvalidParameterValueException("Unable to find " + paramName); } _accountMgr.checkAccess(caller, null, false, (ControlledEntity)vo); return vo; } private boolean isAutoScaleScaleUpPolicy(AutoScalePolicy policyVO) { return policyVO.getAction().equals("scaleup"); } private List<AutoScalePolicyVO> getAutoScalePolicies(String paramName, List<Long> policyIds, List<Counter> counters, int interval, boolean scaleUpPolicies) { SearchBuilder<AutoScalePolicyVO> policySearch = _autoScalePolicyDao.createSearchBuilder(); policySearch.and("ids", policySearch.entity().getId(), Op.IN); policySearch.done(); SearchCriteria<AutoScalePolicyVO> sc = policySearch.create(); sc.setParameters("ids", policyIds.toArray(new Object[0])); List<AutoScalePolicyVO> policies = _autoScalePolicyDao.search(sc, null); int prevQuietTime = 0; for (AutoScalePolicyVO policy : policies) { int quietTime = policy.getQuietTime(); if (prevQuietTime == 0) { prevQuietTime = quietTime; } int duration = policy.getDuration(); if (duration < interval) { throw new InvalidParameterValueException("duration : " + duration + " specified in a policy cannot be less than vm group's interval : " + interval); } if (quietTime != prevQuietTime) { throw new InvalidParameterValueException("quietTime should be same for all the policies specified in " + paramName); } if (scaleUpPolicies) { if (!isAutoScaleScaleUpPolicy(policy)) { throw new InvalidParameterValueException("Only scaleup policies can be specified in scaleuppolicyids"); } } else { if (isAutoScaleScaleUpPolicy(policy)) { throw new InvalidParameterValueException("Only scaledown policies can be specified in scaledownpolicyids"); } } List<AutoScalePolicyConditionMapVO> policyConditionMapVOs = _autoScalePolicyConditionMapDao.listByAll(policy.getId(), null); for (AutoScalePolicyConditionMapVO policyConditionMapVO : policyConditionMapVOs) { long conditionid = policyConditionMapVO.getConditionId(); Condition condition = _conditionDao.findById(conditionid); Counter counter = _counterDao.findById(condition.getCounterid()); counters.add(counter); } } return policies; } @DB protected AutoScaleVmProfileVO checkValidityAndPersist(final AutoScaleVmProfileVO vmProfile, final List<Long> networkIds, final boolean removeNetworks) { long templateId = vmProfile.getTemplateId(); long autoscaleUserId = vmProfile.getAutoScaleUserId(); int destroyVmGraceperiod = vmProfile.getDestroyVmGraceperiod(); VirtualMachineTemplate template = _entityMgr.findById(VirtualMachineTemplate.class, templateId); // Make sure a valid template ID was specified if (template == null) { throw new InvalidParameterValueException("Unable to use the given template."); } if (destroyVmGraceperiod < 0) { throw new InvalidParameterValueException("Destroy Vm Grace Period cannot be less than 0."); } User user = _userDao.findById(autoscaleUserId); //Validate auto scale user against the vmprofile account is not needed anymore, //because the profile may be associated with the project account not an user account. /*if (user.getAccountId() != vmProfile.getAccountId()) { throw new InvalidParameterValueException("AutoScale User id does not belong to the same account"); }*/ String apiKey = user.getApiKey(); String secretKey = user.getSecretKey(); String csUrl = ApiServiceConfiguration.ApiServletPath.value(); if (apiKey == null) { throw new InvalidParameterValueException("apiKey for user: " + user.getUsername() + " is empty. Please generate it"); } if (secretKey == null) { throw new InvalidParameterValueException("secretKey for user: " + user.getUsername() + " is empty. Please generate it"); } if (csUrl == null || csUrl.contains("localhost")) { throw new InvalidParameterValueException("Global setting endpointe.url has to be set to the Management Server's API end point"); } validateUserData(vmProfile.getUserData()); return Transaction.execute(new TransactionCallback<AutoScaleVmProfileVO>() { @Override public AutoScaleVmProfileVO doInTransaction(TransactionStatus status) { AutoScaleVmProfileVO newVmProfile = _autoScaleVmProfileDao.persist(vmProfile); if (networkIds != null && !networkIds.isEmpty()) { SearchBuilder<NetworkVO> networkSearch = _networkDao.createSearchBuilder(); networkSearch.and("ids", networkSearch.entity().getId(), Op.IN); networkSearch.done(); SearchCriteria<NetworkVO> sc = networkSearch.create(); sc.setParameters("ids", networkIds.toArray(new Object[0])); List<NetworkVO> networks = _networkDao.search(sc, null); ControlledEntity[] sameOwnerEntities = networks.toArray(new ControlledEntity[networks.size() + 1]); sameOwnerEntities[sameOwnerEntities.length - 1] = newVmProfile; _accountMgr.checkAccess(CallContext.current().getCallingAccount(), null, true, sameOwnerEntities); if (networkIds.size() != networks.size()) { throw new InvalidParameterValueException("Unable to find the network specified"); } /* For update case remove the existing mappings and create fresh ones */ _autoScaleVmProfileNetworkMapDao.removeByVmProfileId(newVmProfile.getId()); Set<Long> networkSet = new LinkedHashSet<>(networkIds); //convert to set to remove duplicates for (Long networkId : networkSet) { _autoScaleVmProfileNetworkMapDao.persist(new AutoScaleVmProfileNetworkMapVO(newVmProfile.getId(), networkId)); } }else if(removeNetworks){ _autoScaleVmProfileNetworkMapDao.removeByVmProfileId(newVmProfile.getId()); } return newVmProfile; } }); } protected void validateUserData(String userData) { byte[] decodedUserData; if (userData != null) { if (!Base64.isBase64(userData)) { throw new InvalidParameterValueException("User data is not base64 encoded"); } if (userData.length() >= MAX_HTTP_POST_LENGTH) { throw new InvalidParameterValueException("User data is too long for an http POST request"); } decodedUserData = Base64.decodeBase64(userData.getBytes()); if (decodedUserData.length > MAX_HTTP_POST_LENGTH) { throw new InvalidParameterValueException("User data is too long for POST request"); } if (decodedUserData.length < 1) { throw new InvalidParameterValueException("User data is too short"); } } } @Override @ActionEvent(eventType = EventTypes.EVENT_AUTOSCALEVMPROFILE_CREATE, eventDescription = "creating autoscale vm profile", create = true) public AutoScaleVmProfile createAutoScaleVmProfile(CreateAutoScaleVmProfileCmd cmd) { Account owner = _accountDao.findById(cmd.getAccountId()); Account caller = CallContext.current().getCallingAccount(); _accountMgr.checkAccess(caller, null, true, owner); long zoneId = cmd.getZoneId(); long serviceOfferingId = cmd.getServiceOfferingId(); long autoscaleUserId = cmd.getAutoscaleUserId(); DataCenter zone = _entityMgr.findById(DataCenter.class, zoneId); if (zone == null) { throw new InvalidParameterValueException("Unable to find zone by id"); } ServiceOffering serviceOffering = _entityMgr.findById(ServiceOffering.class, serviceOfferingId); if (serviceOffering == null) { throw new InvalidParameterValueException("Unable to find service offering by id"); } // validations HashMap<String, String> deployParams = cmd.getDeployParamMap(); if (deployParams.containsKey("networks") && deployParams.get("networks").length() > 0) { throw new InvalidParameterValueException( "'networks' is not a valid parameter, network for an AutoScaled VM is chosen automatically. An autoscaled VM is deployed in the loadbalancer's network"); } /* * Just for making sure the values are right in other deploy params. * For ex. if projectId is given as a string instead of an long value, this * will be throwing an error. */ dispatchChainFactory.getStandardDispatchChain().dispatch(new DispatchTask(ComponentContext.inject(DeployVMCmd.class), deployParams)); AutoScaleVmProfileVO profileVO = new AutoScaleVmProfileVO(cmd.getZoneId(), cmd.getDomainId(), cmd.getAccountId(), cmd.getServiceOfferingId(), cmd.getTemplateId(), cmd.getOtherDeployParams(), cmd.getCounterParamList(), cmd.getDestroyVmGraceperiod(), autoscaleUserId, cmd.getUserData()); if (cmd.getDisplay() != null) { profileVO.setDisplay(cmd.getDisplay()); } profileVO = checkValidityAndPersist(profileVO, cmd.getNetworkIds(), cmd.isRemoveNetworks()); s_logger.info("Successfully create AutoScale Vm Profile with Id: " + profileVO.getId()); return profileVO; } @Override @ActionEvent(eventType = EventTypes.EVENT_AUTOSCALEVMPROFILE_UPDATE, eventDescription = "updating autoscale vm profile") public AutoScaleVmProfile updateAutoScaleVmProfile(UpdateAutoScaleVmProfileCmd cmd) { Long profileId = cmd.getId(); Long templateId = cmd.getTemplateId(); Long autoscaleUserId = cmd.getAutoscaleUserId(); Map counterParamList = cmd.getCounterParamList(); Integer destroyVmGraceperiod = cmd.getDestroyVmGraceperiod(); AutoScaleVmProfileVO vmProfile = getEntityInDatabase(CallContext.current().getCallingAccount(), "Auto Scale Vm Profile", profileId, _autoScaleVmProfileDao); boolean physicalParameterUpdate = (templateId != null || autoscaleUserId != null || counterParamList != null || destroyVmGraceperiod != null); if (templateId != null) { vmProfile.setTemplateId(templateId); } if (autoscaleUserId != null) { vmProfile.setAutoscaleUserId(autoscaleUserId); } if (counterParamList != null) { vmProfile.setCounterParamsForUpdate(counterParamList); } if (destroyVmGraceperiod != null) { vmProfile.setDestroyVmGraceperiod(destroyVmGraceperiod); } if (cmd.getCustomId() != null) { vmProfile.setUuid(cmd.getCustomId()); } if (cmd.getDisplay() != null) { vmProfile.setDisplay(cmd.getDisplay()); } if(cmd.getUserData() != null){ vmProfile.setUserData(cmd.getUserData()); } List<AutoScaleVmGroupVO> vmGroupList = _autoScaleVmGroupDao.listByAll(null, profileId); for (AutoScaleVmGroupVO vmGroupVO : vmGroupList) { if (physicalParameterUpdate && !vmGroupVO.getState().equals(AutoScaleVmGroup.State_Disabled)) { throw new InvalidParameterValueException("The AutoScale Vm Profile can be updated only if the Vm Group it is associated with is disabled in state"); } } vmProfile = checkValidityAndPersist(vmProfile, cmd.getNetworkIds(), cmd.isRemoveNetworks()); s_logger.info("Updated Auto Scale Vm Profile id:" + vmProfile.getId()); return vmProfile; } @Override @ActionEvent(eventType = EventTypes.EVENT_AUTOSCALEVMPROFILE_DELETE, eventDescription = "deleting autoscale vm profile") public boolean deleteAutoScaleVmProfile(long id) { /* Check if entity is in database */ getEntityInDatabase(CallContext.current().getCallingAccount(), "AutoScale Vm Profile", id, _autoScaleVmProfileDao); if (_autoScaleVmGroupDao.isProfileInUse(id)) { throw new InvalidParameterValueException("Cannot delete AutoScale Vm Profile when it is in use by one more vm groups"); } boolean success = _autoScaleVmProfileDao.remove(id); if (success) { s_logger.info("Successfully deleted AutoScale Vm Profile with Id: " + id); } return success; } @Override public List<? extends AutoScaleVmProfile> listAutoScaleVmProfiles(ListAutoScaleVmProfilesCmd cmd) { Long id = cmd.getId(); Long templateId = cmd.getTemplateId(); String otherDeployParams = cmd.getOtherDeployParams(); Long serviceOffId = cmd.getServiceOfferingId(); Long zoneId = cmd.getZoneId(); Long projectId = cmd.getProjectId(); Boolean display = cmd.getDisplay(); SearchWrapper<AutoScaleVmProfileVO> searchWrapper = new SearchWrapper<AutoScaleVmProfileVO>(_autoScaleVmProfileDao, AutoScaleVmProfileVO.class, cmd, cmd.getId()); SearchBuilder<AutoScaleVmProfileVO> sb = searchWrapper.getSearchBuilder(); sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ); sb.and("templateId", sb.entity().getTemplateId(), SearchCriteria.Op.EQ); sb.and("serviceOfferingId", sb.entity().getServiceOfferingId(), SearchCriteria.Op.EQ); sb.and("otherDeployParams", sb.entity().getOtherDeployParams(), SearchCriteria.Op.LIKE); sb.and("zoneId", sb.entity().getZoneId(), SearchCriteria.Op.EQ); sb.and("display", sb.entity().isDisplay(), SearchCriteria.Op.EQ); SearchCriteria<AutoScaleVmProfileVO> sc = searchWrapper.buildSearchCriteria(); if (id != null) { sc.setParameters("id", id); } if (templateId != null) { sc.setParameters("templateId", templateId); } if (otherDeployParams != null) { sc.addAnd("otherDeployParams", SearchCriteria.Op.LIKE, "%" + otherDeployParams + "%"); } if (serviceOffId != null) { sc.setParameters("serviceOfferingId", serviceOffId); } if (zoneId != null) { sc.setParameters("zoneId", zoneId); } if (projectId != null) { sc.setParameters("accountIdIN", projectId); } if (display != null) { sc.setParameters("display", display); } return searchWrapper.search(); } @DB protected AutoScalePolicyVO checkValidityAndPersist(final AutoScalePolicyVO autoScalePolicyVOFinal, final List<Long> conditionIds) { final int duration = autoScalePolicyVOFinal.getDuration(); final int quietTime = autoScalePolicyVOFinal.getQuietTime(); if (duration < 0) { throw new InvalidParameterValueException("duration is an invalid value: " + duration); } if (quietTime < 0) { throw new InvalidParameterValueException("quiettime is an invalid value: " + quietTime); } return Transaction.execute(new TransactionCallback<AutoScalePolicyVO>() { @Override public AutoScalePolicyVO doInTransaction(TransactionStatus status) { AutoScalePolicyVO autoScalePolicyVO = _autoScalePolicyDao.persist(autoScalePolicyVOFinal); if (conditionIds != null) { SearchBuilder<ConditionVO> conditionsSearch = _conditionDao.createSearchBuilder(); conditionsSearch.and("ids", conditionsSearch.entity().getId(), Op.IN); conditionsSearch.done(); SearchCriteria<ConditionVO> sc = conditionsSearch.create(); sc.setParameters("ids", conditionIds.toArray(new Object[0])); List<ConditionVO> conditions = _conditionDao.search(sc, null); ControlledEntity[] sameOwnerEntities = conditions.toArray(new ControlledEntity[conditions.size() + 1]); sameOwnerEntities[sameOwnerEntities.length - 1] = autoScalePolicyVO; _accountMgr.checkAccess(CallContext.current().getCallingAccount(), null, true, sameOwnerEntities); if (conditionIds.size() != conditions.size()) { // TODO report the condition id which could not be found throw new InvalidParameterValueException("Unable to find the condition specified"); } ArrayList<Long> counterIds = new ArrayList<Long>(); for (ConditionVO condition : conditions) { if (counterIds.contains(condition.getCounterid())) { throw new InvalidParameterValueException( "atleast two conditions in the conditionids have the same counter. It is not right to apply two different conditions for the same counter"); } counterIds.add(condition.getCounterid()); } /* For update case remove the existing mappings and create fresh ones */ _autoScalePolicyConditionMapDao.removeByAutoScalePolicyId(autoScalePolicyVO.getId()); for (Long conditionId : conditionIds) { AutoScalePolicyConditionMapVO policyConditionMapVO = new AutoScalePolicyConditionMapVO(autoScalePolicyVO.getId(), conditionId); _autoScalePolicyConditionMapDao.persist(policyConditionMapVO); } } return autoScalePolicyVO; } }); } @Override @ActionEvent(eventType = EventTypes.EVENT_AUTOSCALEPOLICY_CREATE, eventDescription = "creating autoscale policy", create = true) public AutoScalePolicy createAutoScalePolicy(CreateAutoScalePolicyCmd cmd) { int duration = cmd.getDuration(); Integer quietTime = cmd.getQuietTime(); String action = cmd.getAction(); Integer step = cmd.getStep(); AutoScalePolicy.LogicalOperator operator; try { operator = AutoScalePolicy.LogicalOperator.valueOf(cmd.getLogicalOperator()); } catch (IllegalArgumentException ex) { throw new InvalidParameterValueException("The logical Operator " + cmd.getLogicalOperator() + " does not exist; Unable to create policy."); } if (quietTime == null) { quietTime = NetUtils.DEFAULT_AUTOSCALE_POLICY_QUIET_TIME; } action = action.toLowerCase(); if (!NetUtils.isValidAutoScaleAction(action)) { throw new InvalidParameterValueException("action is invalid, only 'scaleup' and 'scaledown' is supported"); } AutoScalePolicyVO policyVO = new AutoScalePolicyVO(cmd.getDomainId(), cmd.getAccountId(), duration, quietTime, null, action, step, operator); policyVO = checkValidityAndPersist(policyVO, cmd.getConditionIds()); s_logger.info("Successfully created AutoScale Policy with Id: " + policyVO.getId()); return policyVO; } @Override @DB @ActionEvent(eventType = EventTypes.EVENT_AUTOSCALEPOLICY_DELETE, eventDescription = "deleting autoscale policy") public boolean deleteAutoScalePolicy(final long id) { /* Check if entity is in database */ getEntityInDatabase(CallContext.current().getCallingAccount(), "AutoScale Policy", id, _autoScalePolicyDao); if (_autoScaleVmGroupPolicyMapDao.isAutoScalePolicyInUse(id)) { throw new InvalidParameterValueException("Cannot delete AutoScale Policy when it is in use by one or more AutoScale Vm Groups"); } return Transaction.execute(new TransactionCallback<Boolean>() { @Override public Boolean doInTransaction(TransactionStatus status) { boolean success = true; success = _autoScalePolicyDao.remove(id); if (!success) { s_logger.warn("Failed to remove AutoScale Policy db object"); return false; } success = _autoScalePolicyConditionMapDao.removeByAutoScalePolicyId(id); if (!success) { s_logger.warn("Failed to remove AutoScale Policy Condition mappings"); return false; } s_logger.info("Successfully deleted autoscale policy id : " + id); return success; } }); } public void checkCallerAccess(String accountName, Long domainId) { Account caller = CallContext.current().getCallingAccount(); Account owner = _accountDao.findActiveAccount(accountName, domainId); if (owner == null) { List<String> idList = new ArrayList<String>(); idList.add(ApiDBUtils.findDomainById(domainId).getUuid()); throw new InvalidParameterValueException("Unable to find account " + accountName + " in domain with specifed domainId"); } _accountMgr.checkAccess(caller, null, false, owner); } private class SearchWrapper<VO extends ControlledEntity> { GenericDao<VO, Long> dao; SearchBuilder<VO> searchBuilder; SearchCriteria<VO> searchCriteria; Long domainId; boolean isRecursive; List<Long> permittedAccounts = new ArrayList<Long>(); ListProjectResourcesCriteria listProjectResourcesCriteria; Filter searchFilter; public SearchWrapper(GenericDao<VO, Long> dao, Class<VO> entityClass, BaseListAccountResourcesCmd cmd, Long id) { this.dao = dao; this.searchBuilder = dao.createSearchBuilder(); domainId = cmd.getDomainId(); String accountName = cmd.getAccountName(); isRecursive = cmd.isRecursive(); boolean listAll = cmd.listAll(); long startIndex = cmd.getStartIndex(); long pageSizeVal = cmd.getPageSizeVal(); Account caller = CallContext.current().getCallingAccount(); Ternary<Long, Boolean, ListProjectResourcesCriteria> domainIdRecursiveListProject = new Ternary<Long, Boolean, ListProjectResourcesCriteria>(domainId, isRecursive, null); _accountMgr.buildACLSearchParameters(caller, id, accountName, null, permittedAccounts, domainIdRecursiveListProject, listAll, false); domainId = domainIdRecursiveListProject.first(); isRecursive = domainIdRecursiveListProject.second(); ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third(); _accountMgr.buildACLSearchBuilder(searchBuilder, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); searchFilter = new Filter(entityClass, "id", false, startIndex, pageSizeVal); } public SearchBuilder<VO> getSearchBuilder() { return searchBuilder; } public SearchCriteria<VO> buildSearchCriteria() { searchCriteria = searchBuilder.create(); _accountMgr.buildACLSearchCriteria(searchCriteria, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); return searchCriteria; } public List<VO> search() { return dao.search(searchCriteria, searchFilter); } } @Override public List<? extends AutoScalePolicy> listAutoScalePolicies(ListAutoScalePoliciesCmd cmd) { SearchWrapper<AutoScalePolicyVO> searchWrapper = new SearchWrapper<AutoScalePolicyVO>(_autoScalePolicyDao, AutoScalePolicyVO.class, cmd, cmd.getId()); SearchBuilder<AutoScalePolicyVO> sb = searchWrapper.getSearchBuilder(); Long id = cmd.getId(); Long conditionId = cmd.getConditionId(); String action = cmd.getAction(); Long vmGroupId = cmd.getVmGroupId(); Long projectId = cmd.getProjectId(); sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ); sb.and("action", sb.entity().getAction(), SearchCriteria.Op.EQ); if (conditionId != null) { SearchBuilder<AutoScalePolicyConditionMapVO> asPolicyConditionSearch = _autoScalePolicyConditionMapDao.createSearchBuilder(); asPolicyConditionSearch.and("conditionId", asPolicyConditionSearch.entity().getConditionId(), SearchCriteria.Op.EQ); sb.join("asPolicyConditionSearch", asPolicyConditionSearch, sb.entity().getId(), asPolicyConditionSearch.entity().getPolicyId(), JoinBuilder.JoinType.INNER); } if (vmGroupId != null) { SearchBuilder<AutoScaleVmGroupPolicyMapVO> asVmGroupPolicySearch = _autoScaleVmGroupPolicyMapDao.createSearchBuilder(); asVmGroupPolicySearch.and("vmGroupId", asVmGroupPolicySearch.entity().getVmGroupId(), SearchCriteria.Op.EQ); sb.join("asVmGroupPolicySearch", asVmGroupPolicySearch, sb.entity().getId(), asVmGroupPolicySearch.entity().getPolicyId(), JoinBuilder.JoinType.INNER); } SearchCriteria<AutoScalePolicyVO> sc = searchWrapper.buildSearchCriteria(); if (id != null) { sc.setParameters("id", id); } if (action != null) { sc.setParameters("action", action); } if (projectId != null) { sc.setParameters("accountIdIN", projectId); } if (conditionId != null) { sc.setJoinParameters("asPolicyConditionSearch", "conditionId", conditionId); } if (vmGroupId != null) { sc.setJoinParameters("asVmGroupPolicySearch", "vmGroupId", vmGroupId); } return searchWrapper.search(); } @Override @ActionEvent(eventType = EventTypes.EVENT_AUTOSCALEPOLICY_UPDATE, eventDescription = "updating autoscale policy") public AutoScalePolicy updateAutoScalePolicy(UpdateAutoScalePolicyCmd cmd) { Long policyId = cmd.getId(); Integer duration = cmd.getDuration(); Integer quietTime = cmd.getQuietTime(); Integer step = cmd.getStep(); List<Long> conditionIds = cmd.getConditionIds(); AutoScalePolicy.LogicalOperator operator; try { operator = AutoScalePolicy.LogicalOperator.valueOf(cmd.getLogicalOperator()); } catch (IllegalArgumentException ex) { throw new InvalidParameterValueException("The logical Operator " + cmd.getLogicalOperator() + " does not exist; Unable to update policy."); } AutoScalePolicyVO policy = getEntityInDatabase(CallContext.current().getCallingAccount(), "Auto Scale Policy", policyId, _autoScalePolicyDao); if (duration != null) { policy.setDuration(duration); } if (quietTime != null) { policy.setQuietTime(quietTime); } if (step != null) { policy.setStep(step); } if(operator != null){ policy.setLogicalOperator(operator); } List<AutoScaleVmGroupPolicyMapVO> vmGroupPolicyList = _autoScaleVmGroupPolicyMapDao.listByPolicyId(policyId); for (AutoScaleVmGroupPolicyMapVO vmGroupPolicy : vmGroupPolicyList) { AutoScaleVmGroupVO vmGroupVO = _autoScaleVmGroupDao.findById(vmGroupPolicy.getVmGroupId()); if (vmGroupVO == null) { s_logger.warn("Stale database entry! There is an entry in VmGroupPolicyMap but the vmGroup is missing:" + vmGroupPolicy.getVmGroupId()); continue; } if (!vmGroupVO.getState().equals(AutoScaleVmGroup.State_Disabled)) { throw new InvalidParameterValueException("The AutoScale Policy can be updated only if the Vm Group it is associated with is disabled in state"); } if (policy.getDuration() < vmGroupVO.getInterval()) { throw new InvalidParameterValueException("duration is less than the associated AutoScaleVmGroup's interval"); } } policy = checkValidityAndPersist(policy, conditionIds); s_logger.info("Successfully updated Auto Scale Policy id:" + policyId); return policy; } @Override @ActionEvent(eventType = EventTypes.EVENT_AUTOSCALEVMGROUP_CREATE, eventDescription = "creating autoscale vm group", create = true) public AutoScaleVmGroup createAutoScaleVmGroup(CreateAutoScaleVmGroupCmd cmd) { int minMembers = cmd.getMinMembers(); int maxMembers = cmd.getMaxMembers(); Integer interval = cmd.getInterval(); Boolean forDisplay = cmd.getDisplay(); if (interval == null) { interval = NetUtils.DEFAULT_AUTOSCALE_POLICY_INTERVAL_TIME; } LoadBalancerVO loadBalancer = getEntityInDatabase(CallContext.current().getCallingAccount(), ApiConstants.LBID, cmd.getLbRuleId(), _lbDao); Long zoneId = _ipAddressDao.findById(loadBalancer.getSourceIpAddressId()).getDataCenterId(); if (_autoScaleVmGroupDao.isAutoScaleLoadBalancer(loadBalancer.getId())) { throw new InvalidParameterValueException("an AutoScaleVmGroup is already attached to the lb rule, the existing vm group has to be first deleted"); } // if (_lb2VmMapDao.isVmAttachedToLoadBalancer(loadBalancer.getId())) { // throw new InvalidParameterValueException( // "there are Vms already bound to the specified LoadBalancing Rule. User bound Vms and AutoScaled Vm Group cannot co-exist on a Load Balancing Rule"); // } AutoScaleVmGroupVO vmGroupVO = new AutoScaleVmGroupVO(cmd.getLbRuleId(), zoneId, loadBalancer.getDomainId(), loadBalancer.getAccountId(), minMembers, maxMembers, loadBalancer.getDefaultPortStart(), interval, null, cmd.getProfileId(), AutoScaleVmGroup.State_New, cmd.getVmPrefixName()); if (forDisplay != null) { vmGroupVO.setDisplay(forDisplay); } vmGroupVO = checkValidityAndPersist(vmGroupVO, cmd.getScaleUpPolicyIds(), cmd.getScaleDownPolicyIds()); s_logger.info("Successfully created Autoscale Vm Group with Id: " + vmGroupVO.getId()); return vmGroupVO; } @Override @ActionEvent(eventType = EventTypes.EVENT_AUTOSCALEVMGROUP_CREATE, eventDescription = "creating autoscale vm group", async = true) public boolean configureAutoScaleVmGroup(CreateAutoScaleVmGroupCmd cmd) throws ResourceUnavailableException { return configureAutoScaleVmGroup(cmd.getEntityId(), AutoScaleVmGroup.State_Disabled); } public boolean isLoadBalancerBasedAutoScaleVmGroup(AutoScaleVmGroup vmGroup) { return vmGroup.getLoadBalancerId() != null; } private boolean configureAutoScaleVmGroup(long vmGroupid, String currentState) throws ResourceUnavailableException { AutoScaleVmGroup vmGroup = _autoScaleVmGroupDao.findById(vmGroupid); if (isLoadBalancerBasedAutoScaleVmGroup(vmGroup)) { try { return _lbRulesMgr.configureLbAutoScaleVmGroup(vmGroupid, currentState); } catch (ResourceUnavailableException re) { throw re; } catch (Exception e) { s_logger.warn("Exception during configureLbAutoScaleVmGroup in lb rules manager", e); return false; } } // This should never happen, because today loadbalancerruleid is manadatory for AutoScaleVmGroup. throw new InvalidParameterValueException("Only LoadBalancer based AutoScale is supported"); } @Override @DB @ActionEvent(eventType = EventTypes.EVENT_AUTOSCALEVMGROUP_DELETE, eventDescription = "deleting autoscale vm group", async = true) public boolean deleteAutoScaleVmGroup(final long id) { AutoScaleVmGroupVO autoScaleVmGroupVO = getEntityInDatabase(CallContext.current().getCallingAccount(), "AutoScale Vm Group", id, _autoScaleVmGroupDao); if (autoScaleVmGroupVO.getState().equals(AutoScaleVmGroup.State_New)) { /* This condition is for handling failures during creation command */ return _autoScaleVmGroupDao.remove(id); } String bakupState = autoScaleVmGroupVO.getState(); autoScaleVmGroupVO.setState(AutoScaleVmGroup.State_Revoke); _autoScaleVmGroupDao.persist(autoScaleVmGroupVO); boolean success = false; try { success = configureAutoScaleVmGroup(id, bakupState); } catch (ResourceUnavailableException e) { autoScaleVmGroupVO.setState(bakupState); _autoScaleVmGroupDao.persist(autoScaleVmGroupVO); } finally { if (!success) { s_logger.warn("Could not delete AutoScale Vm Group id : " + id); return false; } } //removing VMS before removing auto scale group this.destroyVmGroupVMs(id); return Transaction.execute(new TransactionCallback<Boolean>() { @Override public Boolean doInTransaction(TransactionStatus status) { boolean success = _autoScaleVmGroupDao.remove(id); if (!success) { s_logger.warn("Failed to remove AutoScale Group db object"); return false; } success = _autoScaleVmGroupPolicyMapDao.removeByGroupId(id); if (!success) { s_logger.warn("Failed to remove AutoScale Group Policy mappings"); return false; } s_logger.info("Successfully deleted autoscale vm group id : " + id); return success; // Successfull } }); } @Override @DB @ActionEvent(eventType = EventTypes.EVENT_AUTOSCALEVMGROUP_DELETE, eventDescription = "deleting autoscale vm group with dependencies") public boolean deleteAutoScaleVmGroupWithDependencies(final long id) { AutoScaleVmGroupVO autoScaleVmGroupVO = getEntityInDatabase(CallContext.current().getCallingAccount(), "AutoScale Vm Group", id, _autoScaleVmGroupDao); if (autoScaleVmGroupVO.getState().equals(AutoScaleVmGroup.State_New)) { /* This condition is for handling failures during creation command */ return _autoScaleVmGroupDao.remove(id); } String bakupState = autoScaleVmGroupVO.getState(); autoScaleVmGroupVO.setState(AutoScaleVmGroup.State_Revoke); _autoScaleVmGroupDao.persist(autoScaleVmGroupVO); boolean success = false; try { success = configureAutoScaleVmGroup(id, bakupState); } catch (ResourceUnavailableException e) { autoScaleVmGroupVO.setState(bakupState); _autoScaleVmGroupDao.persist(autoScaleVmGroupVO); } finally { if (!success) { s_logger.warn("Could not delete AutoScale Vm Group id : " + id); return false; } } //removing VMS before removing auto scale group this.destroyVmGroupVMs(id); // Set up objects to be deleted final Long vmProfileId = autoScaleVmGroupVO.getProfileId(); return Transaction.execute(new TransactionCallback<Boolean>() { @Override public Boolean doInTransaction(TransactionStatus status) { boolean success = _autoScaleVmGroupDao.remove(id); if (!success) { s_logger.warn("Failed to remove AutoScale Group db object"); return false; } success = deleteAutoScaleVmProfile(vmProfileId); if (!success) { s_logger.warn("Failed to remove AutoScale VM Profile associated to Autoscale VM Group"); return false; } // Save up policies to be deleted List<AutoScaleVmGroupPolicyMapVO> policiesMapList = _autoScaleVmGroupPolicyMapDao.listByVmGroupId(id); // Remove mapping between AutoScale VM Group and policies so policies are not in use anymore success = _autoScaleVmGroupPolicyMapDao.removeByGroupId(id); if (!success) { s_logger.warn("Failed to remove AutoScale Group Policy mappings"); return false; } for(AutoScaleVmGroupPolicyMapVO policyMapVO : policiesMapList) { Long policyId = policyMapVO.getPolicyId(); List<AutoScalePolicyConditionMapVO> conditionsMapList = _autoScalePolicyConditionMapDao.findByPolicyId(policyId); success = deleteAutoScalePolicy(policyId); if (!success) { s_logger.warn("Failed to remove AutoScale Policy " + policyId); return false; } for(AutoScalePolicyConditionMapVO conditionMapVO : conditionsMapList) { Long conditionId = conditionMapVO.getConditionId(); try { success = deleteCondition(conditionId); } catch (ResourceInUseException e) { s_logger.warn("Failed to remove condition " + conditionId); return false; } if (!success) { s_logger.warn("Failed to remove condition " + conditionId); return false; } } } s_logger.info("Successfully deleted autoscale vm group id : " + id); return success; // Successfull } }); } protected void destroyVmGroupVMs(long groupId) { AutoScaleVmGroupVO asGroup = _autoScaleVmGroupDao.findById(groupId); asGroup.setMinMembers(0); asGroup.setState(AutoScaleVmGroup.State_Disabled); _autoScaleVmGroupDao.persist(asGroup); for(AutoScaleVmGroupVmMapVO autoScaleVmGroupVmMap : _autoScaleVmGroupVmMapDao.listByGroup(groupId)){ _autoScaleVmGroupVmMapDao.remove(groupId, autoScaleVmGroupVmMap.getInstanceId()); destroyVM(autoScaleVmGroupVmMap.getInstanceId()); } } @Override public List<? extends AutoScaleVmGroup> listAutoScaleVmGroups(ListAutoScaleVmGroupsCmd cmd) { Long id = cmd.getId(); Long policyId = cmd.getPolicyId(); Long loadBalancerId = cmd.getLoadBalancerId(); Long profileId = cmd.getProfileId(); Long zoneId = cmd.getZoneId(); Long projectId = cmd.getProjectId(); Boolean forDisplay = cmd.getDisplay(); SearchWrapper<AutoScaleVmGroupVO> searchWrapper = new SearchWrapper<AutoScaleVmGroupVO>(_autoScaleVmGroupDao, AutoScaleVmGroupVO.class, cmd, cmd.getId()); SearchBuilder<AutoScaleVmGroupVO> sb = searchWrapper.getSearchBuilder(); sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ); sb.and("loadBalancerId", sb.entity().getLoadBalancerId(), SearchCriteria.Op.EQ); sb.and("profileId", sb.entity().getProfileId(), SearchCriteria.Op.EQ); sb.and("zoneId", sb.entity().getZoneId(), SearchCriteria.Op.EQ); sb.and("display", sb.entity().isDisplay(), SearchCriteria.Op.EQ); if (policyId != null) { SearchBuilder<AutoScaleVmGroupPolicyMapVO> asVmGroupPolicySearch = _autoScaleVmGroupPolicyMapDao.createSearchBuilder(); asVmGroupPolicySearch.and("policyId", asVmGroupPolicySearch.entity().getPolicyId(), SearchCriteria.Op.EQ); sb.join("asVmGroupPolicySearch", asVmGroupPolicySearch, sb.entity().getId(), asVmGroupPolicySearch.entity().getVmGroupId(), JoinBuilder.JoinType.INNER); } SearchCriteria<AutoScaleVmGroupVO> sc = searchWrapper.buildSearchCriteria(); if (id != null) { sc.setParameters("id", id); } if (loadBalancerId != null) { sc.setParameters("loadBalancerId", loadBalancerId); } if (profileId != null) { sc.setParameters("profileId", profileId); } if (zoneId != null) { sc.setParameters("zoneId", zoneId); } if (projectId != null) { sc.setParameters("accountIdIN", projectId); } if (policyId != null) { sc.setJoinParameters("asVmGroupPolicySearch", "policyId", policyId); } if (forDisplay != null) { sc.setParameters("display", forDisplay); } return searchWrapper.search(); } @DB protected AutoScaleVmGroupVO checkValidityAndPersist(final AutoScaleVmGroupVO vmGroup, final List<Long> passedScaleUpPolicyIds, final List<Long> passedScaleDownPolicyIds) { int minMembers = vmGroup.getMinMembers(); int maxMembers = vmGroup.getMaxMembers(); int interval = vmGroup.getInterval(); List<Counter> counters = new ArrayList<Counter>(); List<AutoScalePolicyVO> policies = new ArrayList<AutoScalePolicyVO>(); final List<Long> policyIds = new ArrayList<Long>(); List<Long> currentScaleUpPolicyIds = new ArrayList<Long>(); List<Long> currentScaleDownPolicyIds = new ArrayList<Long>(); if (vmGroup.getCreated() != null) { ApiDBUtils.getAutoScaleVmGroupPolicyIds(vmGroup.getId(), currentScaleUpPolicyIds, currentScaleDownPolicyIds); } if (minMembers < 0) { throw new InvalidParameterValueException(ApiConstants.MIN_MEMBERS + " is an invalid value: " + minMembers); } if (maxMembers < 0) { throw new InvalidParameterValueException(ApiConstants.MAX_MEMBERS + " is an invalid value: " + maxMembers); } if (minMembers > maxMembers) { throw new InvalidParameterValueException(ApiConstants.MIN_MEMBERS + " (" + minMembers + ")cannot be greater than " + ApiConstants.MAX_MEMBERS + " (" + maxMembers + ")"); } if (interval < 0) { throw new InvalidParameterValueException("interval is an invalid value: " + interval); } if (passedScaleUpPolicyIds != null) { policies.addAll(getAutoScalePolicies("scaleuppolicyid", passedScaleUpPolicyIds, counters, interval, true)); policyIds.addAll(passedScaleUpPolicyIds); } else { // Run the interval check for existing policies getAutoScalePolicies("scaleuppolicyid", currentScaleUpPolicyIds, counters, interval, true); policyIds.addAll(currentScaleUpPolicyIds); } if (passedScaleDownPolicyIds != null) { policies.addAll(getAutoScalePolicies("scaledownpolicyid", passedScaleDownPolicyIds, counters, interval, false)); policyIds.addAll(passedScaleDownPolicyIds); } else { // Run the interval check for existing policies getAutoScalePolicies("scaledownpolicyid", currentScaleDownPolicyIds, counters, interval, false); policyIds.addAll(currentScaleDownPolicyIds); } AutoScaleVmProfileVO profileVO = getEntityInDatabase(CallContext.current().getCallingAccount(), ApiConstants.VMPROFILE_ID, vmGroup.getProfileId(), _autoScaleVmProfileDao); LoadBalancerVO loadBalancer = getEntityInDatabase(CallContext.current().getCallingAccount(), ApiConstants.LBID, vmGroup.getLoadBalancerId(), _lbDao); validateAutoScaleCounters(loadBalancer.getNetworkId(), counters, profileVO.getCounterParams()); ControlledEntity[] sameOwnerEntities = policies.toArray(new ControlledEntity[policies.size() + 2]); sameOwnerEntities[sameOwnerEntities.length - 2] = loadBalancer; sameOwnerEntities[sameOwnerEntities.length - 1] = profileVO; _accountMgr.checkAccess(CallContext.current().getCallingAccount(), null, true, sameOwnerEntities); return Transaction.execute(new TransactionCallback<AutoScaleVmGroupVO>() { @Override public AutoScaleVmGroupVO doInTransaction(TransactionStatus status) { AutoScaleVmGroupVO vmGroupNew = _autoScaleVmGroupDao.persist(vmGroup); if (passedScaleUpPolicyIds != null || passedScaleDownPolicyIds != null) { _autoScaleVmGroupPolicyMapDao.removeByGroupId(vmGroupNew.getId()); for (Long policyId : policyIds) { _autoScaleVmGroupPolicyMapDao.persist(new AutoScaleVmGroupPolicyMapVO(vmGroupNew.getId(), policyId)); } } return vmGroupNew; } }); } @Override @ActionEvent(eventType = EventTypes.EVENT_AUTOSCALEVMGROUP_UPDATE, eventDescription = "updating autoscale vm group", async = true) public AutoScaleVmGroup updateAutoScaleVmGroup(UpdateAutoScaleVmGroupCmd cmd) { Long vmGroupId = cmd.getId(); Integer minMembers = cmd.getMinMembers(); Integer maxMembers = cmd.getMaxMembers(); Integer interval = cmd.getInterval(); Boolean forDisplay = cmd.getDisplay(); List<Long> scaleUpPolicyIds = cmd.getScaleUpPolicyIds(); List<Long> scaleDownPolicyIds = cmd.getScaleDownPolicyIds(); AutoScaleVmGroupVO vmGroupVO = getEntityInDatabase(CallContext.current().getCallingAccount(), "AutoScale Vm Group", vmGroupId, _autoScaleVmGroupDao); boolean physicalParametersUpdate = (minMembers != null || maxMembers != null || interval != null); if (physicalParametersUpdate && !vmGroupVO.getState().equals(AutoScaleVmGroup.State_Disabled)) { throw new InvalidParameterValueException("An AutoScale Vm Group can be updated with minMembers/maxMembers/Interval only when it is in disabled state"); } if (minMembers != null) { vmGroupVO.setMinMembers(minMembers); } if (maxMembers != null) { vmGroupVO.setMaxMembers(maxMembers); } if (maxMembers != null) { vmGroupVO.setInterval(interval); } if (cmd.getCustomId() != null) { vmGroupVO.setUuid(cmd.getCustomId()); } if (forDisplay != null) { vmGroupVO.setDisplay(forDisplay); } vmGroupVO = checkValidityAndPersist(vmGroupVO, scaleUpPolicyIds, scaleDownPolicyIds); if (vmGroupVO != null) { s_logger.debug("Updated Auto Scale VmGroup id:" + vmGroupId); return vmGroupVO; } else return null; } @Override @DB @ActionEvent(eventType = EventTypes.EVENT_AUTOSCALEVMGROUP_ENABLE, eventDescription = "enabling autoscale vm group", async = true) public AutoScaleVmGroup enableAutoScaleVmGroup(Long id) { AutoScaleVmGroupVO vmGroup = getEntityInDatabase(CallContext.current().getCallingAccount(), "AutoScale Vm Group", id, _autoScaleVmGroupDao); boolean success = false; if (!vmGroup.getState().equals(AutoScaleVmGroup.State_Disabled)) { throw new InvalidParameterValueException("Only a AutoScale Vm Group which is in Disabled state can be enabled."); } try { vmGroup.setState(AutoScaleVmGroup.State_Enabled); vmGroup = _autoScaleVmGroupDao.persist(vmGroup); success = configureAutoScaleVmGroup(id, AutoScaleVmGroup.State_Disabled); } catch (ResourceUnavailableException e) { vmGroup.setState(AutoScaleVmGroup.State_Disabled); _autoScaleVmGroupDao.persist(vmGroup); } finally { if (!success) { s_logger.warn("Failed to enable AutoScale Vm Group id : " + id); return null; } s_logger.info("Successfully enabled AutoScale Vm Group with Id:" + id); } return vmGroup; } @Override @ActionEvent(eventType = EventTypes.EVENT_AUTOSCALEVMGROUP_DISABLE, eventDescription = "disabling autoscale vm group", async = true) @DB public AutoScaleVmGroup disableAutoScaleVmGroup(Long id) { AutoScaleVmGroupVO vmGroup = getEntityInDatabase(CallContext.current().getCallingAccount(), "AutoScale Vm Group", id, _autoScaleVmGroupDao); boolean success = false; if (!vmGroup.getState().equals(AutoScaleVmGroup.State_Enabled)) { throw new InvalidParameterValueException("Only a AutoScale Vm Group which is in Enabled state can be disabled."); } try { vmGroup.setState(AutoScaleVmGroup.State_Disabled); vmGroup = _autoScaleVmGroupDao.persist(vmGroup); success = configureAutoScaleVmGroup(id, AutoScaleVmGroup.State_Enabled); } catch (ResourceUnavailableException e) { vmGroup.setState(AutoScaleVmGroup.State_Enabled); _autoScaleVmGroupDao.persist(vmGroup); } finally { if (!success) { s_logger.warn("Failed to disable AutoScale Vm Group id : " + id); return null; } s_logger.info("Successfully disabled AutoScale Vm Group with Id:" + id); } return vmGroup; } @Override @ActionEvent(eventType = EventTypes.EVENT_COUNTER_CREATE, eventDescription = "Counter", create = true) @DB public Counter createCounter(CreateCounterCmd cmd) { String source = cmd.getSource().toLowerCase(); String name = cmd.getName(); Counter.Source src; // Validate Source try { src = Counter.Source.valueOf(source); } catch (Exception ex) { throw new InvalidParameterValueException("The Source " + source + " does not exist; Unable to create Counter"); } CounterVO counter = null; s_logger.debug("Adding Counter " + name); counter = _counterDao.persist(new CounterVO(src, name, cmd.getValue())); CallContext.current().setEventDetails(" Id: " + counter.getId() + " Name: " + name); return counter; } @Override @ActionEvent(eventType = EventTypes.EVENT_CONDITION_CREATE, eventDescription = "Condition", create = true) public Condition createCondition(CreateConditionCmd cmd) { checkCallerAccess(cmd.getAccountName(), cmd.getDomainId()); String opr = cmd.getRelationalOperator().toUpperCase(); long cid = cmd.getCounterId(); long threshold = cmd.getThreshold(); Condition.Operator op; // Validate Relational Operator try { op = Condition.Operator.valueOf(opr); } catch (IllegalArgumentException ex) { throw new InvalidParameterValueException("The Operator " + opr + " does not exist; Unable to create Condition."); } // TODO - Validate threshold CounterVO counter = _counterDao.findById(cid); if (counter == null) { throw new InvalidParameterValueException("Unable to find counter"); } ConditionVO condition = null; condition = _conditionDao.persist(new ConditionVO(cid, threshold, cmd.getEntityOwnerId(), cmd.getDomainId(), op)); s_logger.info("Successfully created condition with Id: " + condition.getId()); CallContext.current().setEventDetails(" Id: " + condition.getId()); return condition; } @Override public List<? extends Counter> listCounters(ListCountersCmd cmd) { String name = cmd.getName(); Long id = cmd.getId(); String source = cmd.getSource(); if (source != null) source = source.toLowerCase(); Filter searchFilter = new Filter(CounterVO.class, "created", false, cmd.getStartIndex(), cmd.getPageSizeVal()); List<CounterVO> counters = _counterDao.listCounters(id, name, source, cmd.getKeyword(), searchFilter); return counters; } @Override public List<? extends Condition> listConditions(ListConditionsCmd cmd) { Long id = cmd.getId(); Long counterId = cmd.getCounterId(); Long policyId = cmd.getPolicyId(); Long projectId = cmd.getProjectId(); SearchWrapper<ConditionVO> searchWrapper = new SearchWrapper<ConditionVO>(_conditionDao, ConditionVO.class, cmd, cmd.getId()); SearchBuilder<ConditionVO> sb = searchWrapper.getSearchBuilder(); if (policyId != null) { SearchBuilder<AutoScalePolicyConditionMapVO> asPolicyConditionSearch = _autoScalePolicyConditionMapDao.createSearchBuilder(); asPolicyConditionSearch.and("policyId", asPolicyConditionSearch.entity().getPolicyId(), SearchCriteria.Op.EQ); sb.join("asPolicyConditionSearch", asPolicyConditionSearch, sb.entity().getId(), asPolicyConditionSearch.entity().getConditionId(), JoinBuilder.JoinType.INNER); } sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ); sb.and("counterId", sb.entity().getCounterid(), SearchCriteria.Op.EQ); // now set the SC criteria... SearchCriteria<ConditionVO> sc = searchWrapper.buildSearchCriteria(); if (id != null) { sc.setParameters("id", id); } if (counterId != null) { sc.setParameters("counterId", counterId); } if (projectId != null) { sc.setParameters("accountIdIN", projectId); } if (policyId != null) { sc.setJoinParameters("asPolicyConditionSearch", "policyId", policyId); } return searchWrapper.search(); } @Override @ActionEvent(eventType = EventTypes.EVENT_COUNTER_DELETE, eventDescription = "counter") public boolean deleteCounter(long counterId) throws ResourceInUseException { // Verify Counter id CounterVO counter = _counterDao.findById(counterId); if (counter == null) { throw new InvalidParameterValueException("Unable to find Counter"); } // Verify if it is used in any Condition ConditionVO condition = _conditionDao.findByCounterId(counterId); if (condition != null) { s_logger.info("Cannot delete counter " + counter.getName() + " as it is being used in a condition."); throw new ResourceInUseException("Counter is in use."); } boolean success = _counterDao.remove(counterId); if (success) { s_logger.info("Successfully deleted counter with Id: " + counterId); } return success; } @Override @ActionEvent(eventType = EventTypes.EVENT_CONDITION_DELETE, eventDescription = "condition") public boolean deleteCondition(long conditionId) throws ResourceInUseException { /* Check if entity is in database */ ConditionVO condition = getEntityInDatabase(CallContext.current().getCallingAccount(), "Condition", conditionId, _conditionDao); if (condition == null) { throw new InvalidParameterValueException("Unable to find Condition"); } // Verify if condition is used in any autoscale policy if (_autoScalePolicyConditionMapDao.isConditionInUse(conditionId)) { s_logger.info("Cannot delete condition " + conditionId + " as it is being used in a condition."); throw new ResourceInUseException("Cannot delete Condition when it is in use by one or more AutoScale Policies."); } boolean success = _conditionDao.remove(conditionId); if (success) { s_logger.info("Successfully deleted condition " + condition.getId()); } return success; } @Override public void cleanUpAutoScaleResources(Long accountId) { // cleans Autoscale VmProfiles, AutoScale Policies and Conditions belonging to an account int count = 0; count = _autoScaleVmProfileDao.removeByAccountId(accountId); if (count > 0) { s_logger.debug("Deleted " + count + " AutoScale Vm Profile for account Id: " + accountId); } count = _autoScalePolicyDao.removeByAccountId(accountId); if (count > 0) { s_logger.debug("Deleted " + count + " AutoScale Policies for account Id: " + accountId); } count = _conditionDao.removeByAccountId(accountId); if (count > 0) { s_logger.debug("Deleted " + count + " Conditions for account Id: " + accountId); } } private boolean checkConditionUp(AutoScaleVmGroupVO asGroup, Integer numVm) { // check maximum Integer currentVM = _autoScaleVmGroupVmMapDao.countByGroup(asGroup.getId()); Integer maxVm = asGroup.getMaxMembers(); if (currentVM + numVm > maxVm) { s_logger.warn("number of VM will greater than the maximum in this group if scaling up, so do nothing more"); return false; } return true; } protected boolean checkConditionDown(AutoScaleVmGroupVO asGroup) { Integer currentVM = _autoScaleVmGroupVmMapDao.countByGroup(asGroup.getId()); Integer minVm = asGroup.getMinMembers(); if (currentVM - 1 < minVm) { s_logger.warn("number of VM will less than the minimum in this group if scaling down, so do nothing more"); return false; } return true; } protected UserVm createNewVM(AutoScaleVmGroupVO asGroup) { AutoScaleVmProfileVO profileVo = _autoScaleVmProfileDao.findById(asGroup.getProfileId()); long templateId = profileVo.getTemplateId(); long serviceOfferingId = profileVo.getServiceOfferingId(); if (templateId == -1) { return null; } // create new VM into DB try { //Verify that all objects exist before passing them to the service Account owner = _accountService.getActiveAccountById(profileVo.getAccountId()); DataCenter zone = _entityMgr.findById(DataCenter.class, profileVo.getZoneId()); if (zone == null) { throw new InvalidParameterValueException("Unable to find zone by id=" + profileVo.getZoneId()); } ServiceOffering serviceOffering = _entityMgr.findById(ServiceOffering.class, serviceOfferingId); if (serviceOffering == null) { throw new InvalidParameterValueException("Unable to find service offering: " + serviceOfferingId); } VirtualMachineTemplate template = _entityMgr.findById(VirtualMachineTemplate.class, templateId); // Make sure a valid template ID was specified if (template == null) { throw new InvalidParameterValueException("Unable to use template " + templateId); } if (!zone.isLocalStorageEnabled()) { if (serviceOffering.getUseLocalStorage()) { throw new InvalidParameterValueException("Zone is not configured to use local storage but service offering " + serviceOffering.getName() + " uses it"); } } UserVm vm = null; IpAddresses addrs = new IpAddresses(null, null); String instanceName = createInstanceName(asGroup); Map<String, String> customParameters = new HashMap<>(); if (zone.getNetworkType() == NetworkType.Basic) { vm = _userVmService.createBasicSecurityGroupVirtualMachine(zone, serviceOffering, template, null, owner, instanceName, instanceName, null, null, null, HypervisorType.XenServer, HTTPMethod.GET, null, null, null, null, true, null, null, null, null, null, null); } else { if (zone.isSecurityGroupEnabled()) { vm = _userVmService.createAdvancedSecurityGroupVirtualMachine(zone, serviceOffering, template, null, null, owner, instanceName, instanceName, null, null, null, HypervisorType.XenServer, HTTPMethod.GET, null, null, null, null, true, null, null, customParameters, null, null, null); } else { List<Long> networkIds = new ArrayList<>(); Long mainNetworkId = getDestinationNetworkId(asGroup); zone = getZone(mainNetworkId); networkIds.add(mainNetworkId); networkIds.addAll(getAdditionalNetWorkIds(profileVo, zone)); vm = _userVmService.createAdvancedVirtualMachine(zone, serviceOffering, template, networkIds, owner, instanceName, instanceName, null, null, null, template.getHypervisorType(), HTTPMethod.POST, profileVo.getUserData(), null, null, addrs, true, null, null, customParameters, null, null, null); } } return vm; } catch (InsufficientCapacityException ex) { s_logger.warn(ex.getMessage(), ex); throw new ServerApiException(ApiErrorCode.INSUFFICIENT_CAPACITY_ERROR, ex.getMessage()); } catch (ResourceUnavailableException ex) { s_logger.warn("Exception: ", ex); throw new ServerApiException(ApiErrorCode.RESOURCE_UNAVAILABLE_ERROR, ex.getMessage()); } catch (ConcurrentOperationException ex) { s_logger.warn("Exception: ", ex); throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage()); } catch (ResourceAllocationException ex) { s_logger.warn("Exception: ", ex); throw new ServerApiException(ApiErrorCode.RESOURCE_ALLOCATION_ERROR, ex.getMessage()); } } protected String createInstanceName(AutoScaleVmGroupVO asGroup) { String vmPrefixName = asGroup.getVmPrefixName(); if (vmPrefixName.isEmpty() || vmPrefixName.equals("")){ return AutoScaledVmPrefix.value() + asGroup.getId() + "-" + getCurrentTimeStampString(); } return vmPrefixName + asGroup.getId() + "-" + getCurrentTimeStampString(); } private List<Long> getAdditionalNetWorkIds(AutoScaleVmProfileVO profileVo, DataCenter zone) { List<Long> networkIds = new ArrayList<>(); for(AutoScaleVmProfileNetworkMapVO asProfileNetMap : _autoScaleVmProfileNetworkMapDao.listByVmProfileId(profileVo.getId())){ NetworkVO network = _networkDao.findById(asProfileNetMap.getNetworkId()); if(network.getDataCenterId() == zone.getId()) { networkIds.add(asProfileNetMap.getNetworkId()); } } return networkIds; } private DataCenter getZone(Long mainNetworkId) { return _entityMgr.findById(DataCenter.class, _networkDao.findById(mainNetworkId).getDataCenterId()); } protected Long getDestinationNetworkId(AutoScaleVmGroup asGroup){ LoadBalancer lb = _loadBalancingRulesService.findById(asGroup.getLoadBalancerId()); List<LoadBalancerNetworkMapVO> lbNetMapList = _lbNetMapDao.listByLoadBalancerId(lb.getId()); Map<Long, Integer> networkInstanceCount = new HashMap<>(); networkInstanceCount.put(lb.getNetworkId(), 0); for (LoadBalancerNetworkMapVO lbNetMap : lbNetMapList) { networkInstanceCount.put(lbNetMap.getNetworkId(), 0); } for(LoadBalancingRule.LbDestination destination : getExistingDestinations(lb, lbNetMapList)){ Integer currentCount = networkInstanceCount.get(destination.getNetworkId()); networkInstanceCount.put(destination.getNetworkId(), currentCount + 1); } Map.Entry<Long, Integer> chosenNetworkId = null; for (Map.Entry<Long, Integer> entry : networkInstanceCount.entrySet()) { if (chosenNetworkId == null || chosenNetworkId.getValue() > entry.getValue()) { chosenNetworkId = entry; } } if(chosenNetworkId == null){ return lb.getNetworkId(); }else{ return chosenNetworkId.getKey(); } } private List<LoadBalancingRule.LbDestination> getExistingDestinations(LoadBalancer lb, List<LoadBalancerNetworkMapVO> lbNetMapList) { List<LoadBalancingRule.LbDestination> dstList = new ArrayList<>(); List<LoadBalancerVMMapVO> lbVmMaps = _lb2VmMapDao.listByLoadBalancerId(lb.getId()); for (LoadBalancerVMMapVO lbVmMap : lbVmMaps) { Nic nic = this.getLbInstanceNic(lb, lbVmMap.getInstanceId(), lbNetMapList); LoadBalancingRule.LbDestination lbDst = new LoadBalancingRule.LbDestination(lb.getDefaultPortStart(), lb.getDefaultPortEnd(), null, nic.getNetworkId(), lbVmMap.getInstanceId(), lbVmMap.isRevoke()); AutoScaleVmGroupVmMapVO autoScaleVmMap = _autoScaleVmGroupVmMapDao.findByVmId(lbVmMap.getInstanceId()); if(autoScaleVmMap != null){ dstList.add(lbDst); } } return dstList; } private Nic getLbInstanceNic(LoadBalancer lb, long vmId, List<LoadBalancerNetworkMapVO> lbNetMapList) { Nic nic = _nicDao.findByInstanceIdAndNetworkIdIncludingRemoved(lb.getNetworkId(), vmId); if (nic != null) { return nic; } for (LoadBalancerNetworkMapVO lbNetMap : lbNetMapList) { nic = _nicDao.findByInstanceIdAndNetworkIdIncludingRemoved(lbNetMap.getNetworkId(), vmId); if (nic != null) { return nic; } } return null; } private String getCurrentTimeStampString() { Date current = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss"); return sdf.format(current); } protected void startNewVM(long vmId) { try { CallContext.current().setEventDetails("Vm Id: " + vmId); _userVmManager.startVirtualMachine(vmId, null, null, null); } catch (final ResourceUnavailableException ex) { s_logger.warn("Exception: ", ex); throw new ServerApiException(ApiErrorCode.RESOURCE_UNAVAILABLE_ERROR, ex.getMessage()); } catch (ConcurrentOperationException ex) { s_logger.warn("Exception: ", ex); throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage()); } catch (InsufficientCapacityException ex) { StringBuilder message = new StringBuilder(ex.getMessage()); if (ex instanceof InsufficientServerCapacityException) { if (((InsufficientServerCapacityException)ex).isAffinityApplied()) { message.append(", Please check the affinity groups provided, there may not be sufficient capacity to follow them"); } } s_logger.info(message.toString(), ex); throw new ServerApiException(ApiErrorCode.INSUFFICIENT_CAPACITY_ERROR, message.toString()); } } protected boolean assignLBruleToNewVm(UserVm vm, AutoScaleVmGroupVO asGroup) { long lbId = asGroup.getLoadBalancerId(); List<LoadBalancerVMMapVO> LbVmMapVos = _lbVmMapDao.listByLoadBalancerId(lbId); if ((LbVmMapVos != null) && (LbVmMapVos.size() > 0)) { for (LoadBalancerVMMapVO LbVmMapVo : LbVmMapVos) { long instanceId = LbVmMapVo.getInstanceId(); if (instanceId == vm.getId()) { s_logger.warn("the new VM is already mapped to LB rule. What's wrong?"); return true; } } } try { return _loadBalancingRulesService.assignToLoadBalancer(lbId, Arrays.asList(new Long(vm.getId())), new HashMap<Long, List<String>>()); }catch(Exception e){ // Rolling back VM creation as it cannot be assigned to the load balancer destroyVM(vm.getId()); return false; } } protected long removeLBrule(AutoScaleVmGroupVO asGroup) { long lbId = asGroup.getLoadBalancerId(); long asGroupId = asGroup.getId(); long instanceId = -1; List<AutoScaleVmGroupVmMapVO> autoScaleVmGroupVmMapVos = _autoScaleVmGroupVmMapDao.listByGroup(asGroupId); if ((autoScaleVmGroupVmMapVos != null) && (autoScaleVmGroupVmMapVos.size() > 0)) { for (AutoScaleVmGroupVmMapVO autoScaleVmGroupVmMapVO : autoScaleVmGroupVmMapVos) { instanceId = autoScaleVmGroupVmMapVO.getInstanceId(); } } // take last VM out of the list List<Long> lstVmId = new ArrayList<Long>(); if (instanceId != -1) lstVmId.add(instanceId); if (_loadBalancingRulesService.removeFromLoadBalancer(lbId, lstVmId, new HashMap<Long, List<String>>())) return instanceId; else return -1; } public void applyTagToAutoScaleGroupVm(Long groupId, ResourceTagVO resourceTagVO) { AutoScaleVmGroupVO asGroup = _autoScaleVmGroupDao.findById(groupId); if (asGroup != null) { List<AutoScaleVmGroupVmMapVO> autoScaleVmGroupVmMapVOs = _autoScaleVmGroupVmMapDao.listByGroup(asGroup.getId()); List<String> resourceIds = new ArrayList(); Map<String, String> tags = new HashMap(); for(AutoScaleVmGroupVmMapVO autoscaleVmGroupVmMapVO: autoScaleVmGroupVmMapVOs) { UserVmVO userVmVO = _userVmDao.findById(autoscaleVmGroupVmMapVO.getInstanceId()); if (userVmVO != null) { resourceIds.add(String.valueOf(userVmVO.getId())); } } tags.put(resourceTagVO.getKey(), resourceTagVO.getValue()); _taggedResourceService.createTags(resourceIds, ResourceTag.ResourceObjectType.UserVm, tags, resourceTagVO.getCustomer()); } } @Override public void deleteTagsFromAutoScaleGroupVms(List<String> resourceIds, Map<String, String> tags) { for (String resourceUuid: resourceIds) { AutoScaleVmGroupVO autoscaleVmGroupVO = _autoScaleVmGroupDao.findByUuid(resourceUuid); if (autoscaleVmGroupVO != null) { List<AutoScaleVmGroupVmMapVO> autoScaleVmGroupVmMapVOs = _autoScaleVmGroupVmMapDao.listByGroup(autoscaleVmGroupVO.getId()); for (AutoScaleVmGroupVmMapVO autoScaleVmGroupVmMapVO: autoScaleVmGroupVmMapVOs) { List<String> vmResourceIds = new ArrayList(); vmResourceIds.add(String.valueOf(autoScaleVmGroupVmMapVO.getInstanceId())); try { _taggedResourceService.deleteTags(vmResourceIds, ResourceTag.ResourceObjectType.UserVm, tags); } catch(InvalidParameterValueException ex) { String message = ex.getMessage(); s_logger.info(message + " Tags were already removed for the resource: "+vmResourceIds.get(0)); } } } } } @Override public void doScaleUp(long groupId, Integer numVm) { AutoScaleVmGroupVO asGroup = _autoScaleVmGroupDao.findById(groupId); if (asGroup == null) { s_logger.error("Can not find the groupid " + groupId + " for scaling up"); return; } try { for (int i = 0; i < numVm; i++) { if (!checkConditionUp(asGroup, numVm)) { return; } UserVm vm = createNewVM(asGroup); if (vm == null) { s_logger.error("Can not deploy new VM for scaling up in the group " + asGroup.getId() + ". Waiting for next round"); break; } addVirtualMachineTags(asGroup, vm); try { startNewVM(vm.getId()); } catch(Exception ex){ destroyVM(vm.getId()); throw ex; } if (assignLBruleToNewVm(vm, asGroup)) { _autoScaleVmGroupVmMapDao.persist(new AutoScaleVmGroupVmMapVO(asGroup.getId(), vm.getId())); updateLastQuietTime(groupId, "scaleup"); createScaleUpSuccessEvent(asGroup.getUuid(), "VM " + vm.getDisplayName() + " was created as result of a scale up action. Auto Scale Id: " + asGroup.getUuid()); } else { createScaleUpFailedEvent(asGroup.getUuid(), "VM could not be assigned to LB for Auto Scale Id: " + asGroup.getUuid()); s_logger.error("Can not assign LB rule for this new VM"); break; } } } catch(ServerApiException ex) { String message = "It was not possible do start VM for Auto Scale Id: " + asGroup.getUuid() + " Reason: " + ex.getDescription(); createScaleUpFailedEvent(asGroup.getUuid(), message); s_logger.error(message, ex); throw ex; } catch(Exception ex){ String message = "It was not possible do start VM for Auto Scale Id: " + asGroup.getUuid() + " Reason: unexpected error during execution"; createScaleUpFailedEvent(asGroup.getUuid(), message); s_logger.error(message, ex); throw ex; } } private void addVirtualMachineTags(AutoScaleVmGroupVO asGroup, UserVm vm) { List<? extends ResourceTag> resourceTags = _resourceTagDao.listBy(asGroup.getId(), ResourceTag.ResourceObjectType.AutoScaleVmGroup); for (ResourceTag resourceTag : resourceTags) { ResourceTagVO tag = new ResourceTagVO(resourceTag.getKey(), resourceTag.getValue(), resourceTag.getAccountId(), resourceTag.getDomainId(), vm.getId(), ResourceTag.ResourceObjectType.UserVm, resourceTag.getCustomer(), vm.getUuid()); _resourceTagDao.persist(tag); } } @Override public void doScaleDown(final long groupId, Integer numVm) { final AutoScaleVmGroupVO asGroup = _autoScaleVmGroupDao.findById(groupId); for(int i = 0; i < numVm; i++) { try{ if (asGroup == null) { s_logger.error("Can not find the groupid " + groupId + " for scaling up"); return; } if (!checkConditionDown(asGroup)) { return; } final long vmId = removeLBrule(asGroup); if (vmId != -1) { _autoScaleVmGroupVmMapDao.remove(groupId, vmId); updateLastQuietTime(groupId, "scaledown"); Integer destroyVmGracePeriod = getDestroyVmGracePeriod(asGroup); if (destroyVmGracePeriod >= 0) { _executor.schedule(new Runnable() { @Override public void run() { if(destroyVM(vmId)){ createScaleDownSuccessEvent(asGroup.getUuid(), "VM was destroyed as result of a scale down action. Auto Scale Id: " + groupId); }else{ createScaleDownFailedEvent(asGroup.getUuid(), "Scale down action failed for Auto Scale group id: " + groupId); } } }, destroyVmGracePeriod, TimeUnit.SECONDS); } } else { String message = "Failed to remove LB rule for the VM being destroyed."; createScaleDownFailedEvent(asGroup.getUuid(), "Scale down action failed for Auto Scale group id: " + groupId + ". Reason: " + message); s_logger.error(message); } }catch(Exception ex){ String message = "Scale down action failed for Auto Scale group id: " + groupId; createScaleDownFailedEvent(asGroup.getUuid(), message); s_logger.error(message, ex); throw ex; } } } private Integer getDestroyVmGracePeriod(AutoScaleVmGroupVO asGroup) { AutoScaleVmProfileVO asProfile = _autoScaleVmProfileDao.findById(asGroup.getProfileId()); return asProfile.getDestroyVmGraceperiod(); } protected void updateLastQuietTime(long groupId, String action) { for (AutoScaleVmGroupPolicyMapVO groupPolicyMap : _autoScaleVmGroupPolicyMapDao.listByVmGroupId(groupId)) { AutoScalePolicyVO policy = _autoScalePolicyDao.findById(groupPolicyMap.getPolicyId()); if (policy.getAction().equals(action)) { policy.setLastQuiteTime(new Date()); _autoScalePolicyDao.persist(policy); break; } } } private boolean destroyVM(long vmId) { try { _userVmManager.destroyVm(vmId, true); return true; } catch (ResourceUnavailableException | ConcurrentOperationException e) { s_logger.error("It was not possible to destroy VM id: " + vmId, e); } return false; } public void createScaleUpSuccessEvent(String asGroupId, String description){ createEvent(asGroupId, EventTypes.EVENT_AUTOSCALEVMGROUP_SCALEUP, description); } public void createScaleUpFailedEvent(String asGroupId, String description){ createEvent(asGroupId, EventTypes.EVENT_AUTOSCALEVMGROUP_SCALEUP_FAILED, description); } public void createScaleDownSuccessEvent(String asGroupId, String description){ createEvent(asGroupId, EventTypes.EVENT_AUTOSCALEVMGROUP_SCALEDOWN, description); } public void createScaleDownFailedEvent(String asGroupId, String description){ createEvent(asGroupId, EventTypes.EVENT_AUTOSCALEVMGROUP_SCALEDOWN_FAILED, description); } protected void createEvent(String asGroupId, String eventType, String description) { CallContext callContext = CallContext.current(); AutoScaleVmGroupVO asGroup = _autoScaleVmGroupDao.findByUuid(asGroupId); AutoScaleVmProfileVO profile = _autoScaleVmProfileDao.findById(asGroup.getProfileId()); User user = _userDao.getUser(profile.getAutoScaleUserId()); callContext.getContextParameters().put(AutoScaleVmGroup.class.getName(), asGroupId); ActionEventUtils.onActionEvent(user.getId(), user.getAccountId(), asGroup.getDomainId(), eventType, description); } @Override public ConfigKey<?>[] getConfigKeys() { return new ConfigKey<?>[] { AutoScaledVmPrefix }; } @Override public String getConfigComponentName() { return AutoScaleManagerImpl.class.getSimpleName(); } }
46.152834
209
0.656067
63f72f359e8983b035d790d0cb6419342bc0c80d
668
package springbootmvc.helloworld.controller; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @EnableAutoConfiguration public class HelloWorld { @RequestMapping("/helloworld") String home() { return "Hello World!"; } @RequestMapping("/hello/{myName}") String index(@PathVariable String myName) { return "Hello "+myName+"!!!"; } }
31.809524
73
0.676647
e6d3730636cc33e2edfead5e6f61268d98060d39
737
package uk.gov.di.ipv.atp.dcs.controllers; import org.springframework.http.MediaType; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.reactive.function.BodyInserters; import org.springframework.web.reactive.function.server.ServerRequest; import org.springframework.web.reactive.function.server.ServerResponse; import reactor.core.publisher.Mono; @Controller public class WelcomeController { @GetMapping() public Mono<ServerResponse> hello(ServerRequest request) { return ServerResponse .ok() .contentType(MediaType.TEXT_PLAIN) .body(BodyInserters.fromValue("Generic ATP Service")); } }
33.5
71
0.772049
d6368c3d4afc1967057cf794ced63bce71e11b91
10,387
//======================================================================== //Copyright 2004-2008 Mort Bay Consulting Pty. Ltd. //------------------------------------------------------------------------ //Licensed under the Apache License, Version 2.0 (the "License"); //you may not use this file except in compliance with the License. //You may obtain a copy of the License at //http://www.apache.org/licenses/LICENSE-2.0 //Unless required by applicable law or agreed to in writing, software //distributed under the License is distributed on an "AS IS" BASIS, //WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //See the License for the specific language governing permissions and //limitations under the License. //======================================================================== package org.mortbay.util; import java.util.AbstractList; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; import java.util.Queue; /* ------------------------------------------------------------ */ /** Queue backed by circular array. * * This partial Queue implementation (also with {@link #pop()} for stack operation) * is backed by a growable circular array. * * @author gregw * * @param <E> */ public class ArrayQueue<E> extends AbstractList<E> implements Queue<E> { public final int DEFAULT_CAPACITY=64; public final int DEFAULT_GROWTH=32; protected Object _lock=this; protected Object[] _elements; protected int _nextE; protected int _nextSlot; protected int _size; protected int _growCapacity; /* ------------------------------------------------------------ */ public ArrayQueue() { _elements=new Object[64]; _growCapacity=32; } /* ------------------------------------------------------------ */ public ArrayQueue(int capacity) { _elements=new Object[capacity]; _growCapacity=-1; } /* ------------------------------------------------------------ */ public ArrayQueue(int initCapacity,int growBy) { _elements=new Object[initCapacity]; _growCapacity=growBy; } /* ------------------------------------------------------------ */ public ArrayQueue(int initCapacity,int growBy,Object lock) { _elements=new Object[initCapacity]; _growCapacity=growBy; _lock=lock; } /* ------------------------------------------------------------ */ public int getCapacity() { return _elements.length; } /* ------------------------------------------------------------ */ @Override public boolean add(E e) { if (!offer(e)) throw new IllegalStateException("Full"); return true; } /* ------------------------------------------------------------ */ public boolean offer(E e) { synchronized(_lock) { if (_size==_elements.length && !grow()) return false; _size++; _elements[_nextSlot++]=e; if (_nextSlot==_elements.length) _nextSlot=0; } return true; } /* ------------------------------------------------------------ */ /** * Add without synchronization or bounds checking * @see #add(Object) */ public void addUnsafe(E e) { if (_size==_elements.length && !grow()) throw new IllegalStateException("Full"); _size++; _elements[_nextSlot++]=e; if (_nextSlot==_elements.length) _nextSlot=0; } /* ------------------------------------------------------------ */ public E element() { synchronized(_lock) { if (_size==0) throw new NoSuchElementException(); return (E)_elements[_nextE]; } } /* ------------------------------------------------------------ */ public E peek() { synchronized(_lock) { if (_size==0) return null; return (E)_elements[_nextE]; } } /* ------------------------------------------------------------ */ public E poll() { synchronized(_lock) { if (_size==0) return null; E e = (E)_elements[_nextE]; _elements[_nextE]=null; _size--; if (++_nextE==_elements.length) _nextE=0; return e; } } /* ------------------------------------------------------------ */ public E remove() { synchronized(_lock) { if (_size==0) throw new NoSuchElementException(); E e = (E)_elements[_nextE]; _elements[_nextE]=null; _size--; if (++_nextE==_elements.length) _nextE=0; return e; } } /* ------------------------------------------------------------ */ @Override public void clear() { synchronized(_lock) { _size=0; _nextE=0; _nextSlot=0; } } /* ------------------------------------------------------------ */ public boolean isEmpty() { synchronized(_lock) { return _size==0; } } /* ------------------------------------------------------------ */ @Override public int size() { return _size; } /* ------------------------------------------------------------ */ @Override public E get(int index) { synchronized(_lock) { if (index<0 || index>=_size) throw new IndexOutOfBoundsException("!("+0+"<"+index+"<="+_size+")"); int i = (_nextE+index)%_elements.length; return (E)_elements[i]; } } /* ------------------------------------------------------------ */ /** * Get without synchronization or bounds checking. * @see get(int) */ public E getUnsafe(int index) { int i = (_nextE+index)%_elements.length; return (E)_elements[i]; } /* ------------------------------------------------------------ */ public E remove(int index) { synchronized(_lock) { if (index<0 || index>=_size) throw new IndexOutOfBoundsException("!("+0+"<"+index+"<="+_size+")"); int i = (_nextE+index)%_elements.length; E old=(E)_elements[i]; if (i<_nextSlot) { // 0 _elements.length // _nextE........._nextSlot System.arraycopy(_elements,i+1,_elements,i,_nextSlot-i); _nextSlot--; _size--; } else { // 0 _elements.length // ......_nextSlot _nextE.......... System.arraycopy(_elements,i+1,_elements,i,_elements.length-i-1); if (_nextSlot>0) { _elements[_elements.length-1]=_elements[0]; System.arraycopy(_elements,1,_elements,0,_nextSlot-1); _nextSlot--; } else _nextSlot=_elements.length-1; _size--; } return old; } } /* ------------------------------------------------------------ */ public E set(int index, E element) { synchronized(_lock) { if (index<0 || index>=_size) throw new IndexOutOfBoundsException("!("+0+"<"+index+"<="+_size+")"); int i = _nextE+index; if (i>=_elements.length) i-=_elements.length; E old=(E)_elements[i]; _elements[i]=element; return old; } } /* ------------------------------------------------------------ */ public void add(int index, E element) { synchronized(_lock) { if (index<0 || index>_size) throw new IndexOutOfBoundsException("!("+0+"<"+index+"<="+_size+")"); if (_size==_elements.length && !grow()) throw new IllegalStateException("Full"); if (index==_size) { add(element); } else { int i = _nextE+index; if (i>=_elements.length) i-=_elements.length; _size++; _nextSlot++; if (_nextSlot==_elements.length) _nextSlot=0; if (i<_nextSlot) { // 0 _elements.length // _nextE.....i..._nextSlot // 0 _elements.length // ..i..._nextSlot _nextE.......... System.arraycopy(_elements,i,_elements,i+1,_nextSlot-i); _elements[i]=element; } else { // 0 _elements.length // ......_nextSlot _nextE.....i.... if (_nextSlot>0) { System.arraycopy(_elements,0,_elements,1,_nextSlot); _elements[0]=_elements[_elements.length-1]; } System.arraycopy(_elements,i,_elements,i+1,_elements.length-i-1); _elements[i]=element; } } } } protected boolean grow() { if (_growCapacity<=0) return false; Object[] elements=new Object[_elements.length+_growCapacity]; int split=_elements.length-_nextE; if (split>0) System.arraycopy(_elements,_nextE,elements,0,split); if (_nextE!=0) System.arraycopy(_elements,0,elements,split,_nextSlot); _elements=elements; _nextE=0; _nextSlot=_size; return true; } }
29.095238
85
0.405507
553ed17e2128247b380083aa8e4b246c96d2a1a8
705
package uk.gov.dvsa.mot.trade.api.response; import com.fasterxml.jackson.annotation.JsonInclude; import java.util.List; @JsonInclude(JsonInclude.Include.NON_NULL) public class VehicleV2Response extends VehicleResponse { private String motTestExpiryDate; private List<MotTestV2Response> motTests; public String getMotTestExpiryDate() { return motTestExpiryDate; } public void setMotTestExpiryDate(String motTestExpiryDate) { this.motTestExpiryDate = motTestExpiryDate; } public List<MotTestV2Response> getMotTests() { return motTests; } public void setMotTests(List<MotTestV2Response> motTests) { this.motTests = motTests; } }
25.178571
64
0.737589
4320f9f06804b5076eefee8501b5bd5c34fba9fd
7,617
package org.superboot.global.wrapper; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.xiaoleilu.hutool.crypto.asymmetric.KeyType; import com.xiaoleilu.hutool.crypto.asymmetric.RSA; import com.xiaoleilu.hutool.lang.Base64; import com.xiaoleilu.hutool.util.CharsetUtil; import com.xiaoleilu.hutool.util.StrUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.util.StreamUtils; import org.superboot.base.BaseConstants; import org.superboot.base.BaseException; import org.superboot.base.StatusCode; import org.superboot.utils.AESUtil; import javax.servlet.ReadListener; import javax.servlet.ServletInputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; import java.io.*; import java.util.Enumeration; import java.util.Set; /** * <b> 重构上行请求信息,对上行内容进行解密操作 </b> * <p> * 功能描述:重构上行请求信息,主要是对已经加密后的Body内容进行统一解密操作 * </p> */ public class RequestBodyDecryptWrapper extends HttpServletRequestWrapper { private Logger log = LoggerFactory.getLogger(getClass()); private byte[] requestBody = null; public RequestBodyDecryptWrapper(HttpServletRequest request) throws IOException { super(request); try { requestBody = StreamUtils.copyToByteArray(request.getInputStream()); } catch (IOException e) { e.printStackTrace(); } } @Override public ServletInputStream getInputStream() throws IOException { if (requestBody == null) { requestBody = new byte[0]; } //变更请求内容 setRequestBody(); final ByteArrayInputStream bais = new ByteArrayInputStream(requestBody); return new ServletInputStream() { @Override public int read() throws IOException { return bais.read(); } @Override public boolean isFinished() { return false; } @Override public boolean isReady() { return true; } @Override public void setReadListener(ReadListener listener) { } }; } @Override public BufferedReader getReader() throws IOException { return new BufferedReader(new InputStreamReader(getInputStream())); } @Override public String getHeader(String name) { return super.getHeader(name); } @Override public Enumeration<String> getHeaderNames() { return super.getHeaderNames(); } @Override public Enumeration<String> getHeaders(String name) { return super.getHeaders(name); } /** * 将RequestBody参数转为字符串 * * @return * @throws UnsupportedEncodingException */ public String getRequestBody() throws UnsupportedEncodingException { return (new String(requestBody, "UTF-8")); } /** * 变更Json对象内容信息 * * @throws UnsupportedEncodingException */ public void setRequestBody() throws UnsupportedEncodingException { //读取Body内容后变更为对象 String body = getRequestBody(); if (StrUtil.isNotBlank(body)) { Object json = null; //扑捉转换异常调用JSON转换 try { json = JSON.parse(body); } catch (Exception e) { json = JSON.toJSON(body); } String secretKey = getHeader(BaseConstants.SECRET_KEY); log.debug("--------------执行密钥解密------------------"); //执行RSA解密 try { secretKey = rsaDecrypt(secretKey); } catch (Exception e) { throw new BaseException(StatusCode.DECODE_FAIL); } log.debug("--------------执行数据解密------------------"); if (StrUtil.isNotBlank(secretKey)) { //判断是否为数组 if (json instanceof JSONArray) { JSONArray jsonArray = JSON.parseArray(json.toString()); jsonArray = aesJsonArray(secretKey, jsonArray); //返回变更后的对象信息 this.requestBody = jsonArray.toJSONString().getBytes("UTF-8"); } else if (json instanceof JSONObject) { JSONObject jsonObject = JSON.parseObject(json.toString()); jsonObject = aesJsonObject(secretKey, jsonObject); //返回变更后的对象信息 this.requestBody = jsonObject.toJSONString().getBytes("UTF-8"); } else { //非JSON对象直接返回到后台业务内处理 this.requestBody = json.toString().getBytes("UTF-8"); } } } } /** * 解密JSON数组对象 * * @param secretKey 密钥 * @param jsonArray JSON数组 * @return */ public JSONArray aesJsonArray(String secretKey, JSONArray jsonArray) { for (int i = 0; i < jsonArray.size(); i++) { //判断是否为JSON对象 if (jsonArray.get(i) instanceof JSONObject) { JSONObject jsonObject = jsonArray.getJSONObject(i); //变更JSON数组对象 jsonArray.set(i, aesJsonObject(secretKey, jsonObject)); } else { //非JSON对象直接执行解密 jsonArray.set(i, aesDecrypt(secretKey, jsonArray.getString(i))); } } return jsonArray; } /** * 解密JSON对象 * * @param secretKey 密钥 * @param jsonObject JSON数组 * @return */ public JSONObject aesJsonObject(String secretKey, JSONObject jsonObject) { Set<String> keys = jsonObject.keySet(); for (String key : keys) { //获取内部嵌套对象是否为数组,如果是数组则进行数组循环解密 Object jsonItem = jsonObject.get(key); if (null != jsonItem) { if (jsonItem instanceof JSONArray) { JSONArray jsonArray = JSON.parseArray(jsonItem.toString()); jsonArray = aesJsonArray(secretKey, jsonArray); //便跟对象内容 jsonObject.put(key, jsonArray); }else if (jsonItem instanceof JSONObject) { JSONObject item = JSON.parseObject(jsonItem.toString()); item = aesJsonObject(secretKey, item); jsonObject.put(key, item); } else { //获取内容 String value = jsonItem.toString(); //执行AES解密 value = aesDecrypt(secretKey, value); //便跟对象内容 jsonObject.put(key, value); } } } return jsonObject; } /** * 执行数据解密 * * @param secretKey 密钥 * @param value 加密后内容 * @return */ public String aesDecrypt(String secretKey, String value) { //解密密文信息 try { String deValue = AESUtil.aesDecrypt(value, secretKey); log.debug("--------------执行字段解密------------------"); return deValue; } catch (Exception e) { throw new BaseException(StatusCode.DECODE_FAIL); } } /** * RSA解密 * * @param text 密文 * @return */ public String rsaDecrypt(String text) throws Exception { //使用hutool进行RSA解密,这个的优势是免去使用第三方JAR包的依赖 RSA rsa = new RSA(BaseConstants.DEFAULT_PKCS8_PRIVATE_KEY, BaseConstants.DEFAULT_PUBLIC_KEY); //URL转码 return new String(rsa.decrypt(Base64.decode(text), KeyType.PrivateKey), CharsetUtil.UTF_8); } }
30.22619
101
0.567546
c2f0b64326ffda9550106aa4b3f043a03d1ff6c8
2,564
/* This file is part of VoltDB. * Copyright (C) 2008-2020 VoltDB Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with VoltDB. If not, see <http://www.gnu.org/licenses/>. */ package org.voltdb.messaging; import java.io.IOException; import java.nio.ByteBuffer; import org.voltcore.messaging.TransactionInfoBaseMessage; import org.voltcore.utils.CoreUtils; import org.voltdb.iv2.TxnEgo; /** * Message issued from an initiator just after newly leader promotion, helping flushing * the transaction task queue on all partition replicas. */ public class DummyTransactionTaskMessage extends TransactionInfoBaseMessage { public DummyTransactionTaskMessage() { super(); m_isReadOnly = true; m_isForReplay = false; } public DummyTransactionTaskMessage (long initiatorHSId, long txnId, long uniqueId) { super(initiatorHSId, initiatorHSId, txnId, uniqueId, true, false); m_isReadOnly = true; m_isForReplay = false; setSpHandle(txnId); } @Override public boolean isSinglePartition() { return true; } @Override public void flattenToBuffer(ByteBuffer buf) throws IOException { buf.put(VoltDbMessageFactory.DUMMY_TRANSACTION_TASK_ID); super.flattenToBuffer(buf); assert(buf.capacity() == buf.position()); buf.limit(buf.position()); } @Override public void toDuplicateCounterString(StringBuilder sb) { sb.append("Unexpected DummyTransactionTask"); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("DummyTaskMessage (FROM "); sb.append(CoreUtils.hsIdToString(m_sourceHSId)); sb.append(" TO "); sb.append(CoreUtils.hsIdToString(getCoordinatorHSId())); sb.append(") FOR TXN ").append(TxnEgo.txnIdToString(m_txnId)); sb.append("SP HANDLE: ").append(TxnEgo.txnIdToString(getSpHandle())).append("\n"); return sb.toString(); } }
32.05
90
0.699298
52683b2ee4f4f931c0ba758f2d576d5a4d179c64
996
package org.smartrplace.logging.fendodb.impl; import java.util.List; import org.ogema.core.channelmanager.measurements.SampledValue; interface FendoCache { FendoInstanceCache getCache(String encodedRecordedData, String filename); void clearCache(); /** * One instance per FileObject */ static interface FendoInstanceCache { void cache(List<SampledValue> values); void invalidate(); List<SampledValue> getCache(); } static FendoCache noopCache() { final FendoInstanceCache NOOP_INSTANCE_CACHE = new FendoInstanceCache() { @Override public void invalidate() { } @Override public List<SampledValue> getCache() { return null; } @Override public void cache(List<SampledValue> values) { } }; return new FendoCache(){ @Override public FendoInstanceCache getCache(String encodedRecordedData, String filename) { return NOOP_INSTANCE_CACHE; } @Override public void clearCache() { } }; } }
17.785714
84
0.699799
ebf7fdb0879e00462b8c3e9648dae845d7a898a5
1,051
package indi.w4xj.juc.aqs.code; import java.util.concurrent.Exchanger; /** * @Author lemon joker * @Project java_upstream * @Package indi.w4xj.juc.aqs.code * @Classname ExchangerTest * @Description TODO * @Date 2021/3/28 19:45 * @Created by IntelliJ IDEA */ public class ExchangerTest { static Exchanger<String> exchanger = new Exchanger<>(); public static void main(String[] args) { new Thread(() -> { String s = "T1"; try { s = exchanger.exchange(s); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + " " + s); }, "t1").start(); new Thread(() -> { String s = "T2"; try { s = exchanger.exchange(s); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + " " + s); }, "t2").start(); } }
23.886364
75
0.525214
c4def15dee0fc3ab2b666ccf7cce54037ff98d70
4,789
package com.mathiastechera.topic5; import java.util.List; import java.util.Optional; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; @RestController public class UserController { private final UserRepository repository; UserController(UserRepository repository) { this.repository = repository; } /** * @return All the users */ @GetMapping("/Users") List<User> allUsers() { return repository.findAll(); } /** * Creates a new user if the username is new. * @param newUser * @return returns the User created. */ @PostMapping("/Users") ResponseEntity<User> newUser(@RequestBody User newUserData) { if(newUserData.getFname() != null && newUserData.getLname() != null && newUserData.getEmail() != null && newUserData.getPassword() != null && newUserData.getUsername() != null ) { Optional<User> userSearched = repository.findById(newUserData.getUsername()); if (userSearched.isPresent()) { return ResponseEntity.status(HttpStatus.CONFLICT).body(null); }else { return ResponseEntity.ok(repository.save(newUserData)); } }else { return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null); } } /** * Return an specific user by his username * @param username * @return json file with the data of the user */ @GetMapping("/User/{username}") ResponseEntity<Optional<User>> getUserByUsername(@PathVariable String username) { Optional<User> userSearched = repository.findById(username); if (userSearched.isPresent()) { return ResponseEntity.ok(userSearched); }else { return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null); } } /** * Change the attributes of an existing user. If the username of the path is new, it will create a new user. * @param newUserData - User Information to be changed. It will check the User object structure. * @param username - ID of the user to be updated. * @return the user updated. */ @PutMapping("/User/{username}") ResponseEntity<User> replaceUser(@RequestBody User newUserData, @PathVariable String username) { Optional<User> userToUpdate = repository.findById(username); if(newUserData.getFname() != null && newUserData.getLname() != null && newUserData.getEmail() != null && newUserData.getPassword() != null && newUserData.getUsername() != null && newUserData.getUsername().compareToIgnoreCase(username) == 0 ) { if(userToUpdate.isPresent()) { userToUpdate.get().setFname(newUserData.getFname()); userToUpdate.get().setLname(newUserData.getLname()); userToUpdate.get().setEmail(newUserData.getEmail()); userToUpdate.get().setPassword(newUserData.getPassword()); return ResponseEntity.ok(repository.save(userToUpdate.get())); }else { return ResponseEntity.ok(repository.save(newUserData)); } } else { return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null); } } /** * Delete a certain user by his username * @param username */ @DeleteMapping("/User/{username}") ResponseEntity<Optional<User>> deleteUser(@PathVariable String username) { Optional<User> userSearched = repository.findById(username); if (userSearched.isPresent()) { repository.deleteById(username); return ResponseEntity.ok(userSearched); }else { return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null); } } /** * Return the users with a certain first and last. It is not case sensitive * @param username First name and last name separated with "-" * @return The data of the users found. */ @GetMapping("/UserByName/{fnamelname}") ResponseEntity<List<User>> getUserByName(@PathVariable String fnamelname) { String[] parts = fnamelname.split("-"); String fname = parts[0]; List<User> lista; if ( parts.length == 2) { String lname = parts[1]; lista = repository.getByFullName(fname, lname); if( lista.size() == 0) { return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null); }else { return ResponseEntity.ok(lista); } }else if (parts.length == 1){ lista = repository.findAllByName(fname); if( lista.size() == 0) { return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null); }else { return ResponseEntity.ok(lista); } }else { return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null); } } }
33.48951
245
0.718939
7e7cbc871d3f77141f91086ef3356474260f1292
1,959
package xyz.deszaras.grounds.command; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import com.google.common.collect.ImmutableMap; import com.google.common.net.InetAddresses; import java.net.InetAddress; import java.time.Instant; import java.time.ZoneId; import java.time.ZoneOffset; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; public class ActorTest { private Actor actor; @BeforeEach public void setUp() { actor = new Actor("bob"); } @Test public void testGettersAndSetters() { assertEquals("bob", actor.getUsername()); @SuppressWarnings("PMD.AvoidUsingHardCodedIP") InetAddress actorAddress = InetAddresses.forString("1.2.3.4"); actor.setMostRecentIPAddress(actorAddress); assertEquals(actorAddress, actor.getMostRecentIPAddress()); Instant now = Instant.now(); actor.setLastLoginTime(now); assertEquals(now, actor.getLastLoginTime()); assertTrue(actor.getPreferences().isEmpty()); actor.setPreference("this", "that"); assertEquals("that", actor.getPreference("this").get()); assertEquals(1, actor.getPreferences().size()); assertEquals("that", actor.getPreferences().get("this")); assertTrue(actor.getPreference("missing").isEmpty()); actor.setPreferences(ImmutableMap.of("hi", "there")); assertEquals("there", actor.getPreference("hi").get()); assertTrue(actor.getPreference("this").isEmpty()); actor.setPreference("hi", null); assertTrue(actor.getPreference("hi").isEmpty()); } @Test public void testTimezone() { assertEquals(ZoneOffset.UTC, actor.getTimezone()); actor.setPreference(Actor.PREFERENCE_TIMEZONE, "America/New_York"); assertEquals(ZoneId.of("America/New_York"), actor.getTimezone()); actor.setPreference(Actor.PREFERENCE_TIMEZONE, "My area"); assertEquals(ZoneOffset.UTC, actor.getTimezone()); } }
30.609375
71
0.730985
98b03c99b2269eae799686cdc809a3970531be23
3,040
package edu.washington.escience.myria.io; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.SequenceInputStream; import java.io.Serializable; import java.net.URI; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.Objects; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; /** * A data source that pulls data from a specified URI. The URI may be: a path on the local file system; an HDFS link; a * web link; an AWS link; and perhaps more. * * If the URI points to a directory, all files in that directory will be concatenated into a single {@link InputStream}. */ public class UriSource implements DataSource, Serializable { /** Required for Java serialization. */ private static final long serialVersionUID = 1L; /** The logger for debug, trace, etc. messages in this class. */ private static final org.slf4j.Logger LOGGER = org.slf4j.LoggerFactory.getLogger(UriSource.class); /** The Uniform Resource Indicator (URI) of the data source. */ @JsonProperty private final String uri; /** * Construct a source of data from the specified URI. The URI may be: a path on the local file system; an HDFS link; a * web link; an AWS link; and perhaps more. * * If the URI points to a directory in HDFS, all files in that directory will be concatenated into a single * {@link InputStream}. * * @param uri the Uniform Resource Indicator (URI) of the data source. */ @JsonCreator public UriSource(@JsonProperty(value = "uri", required = true) final String uri) { this.uri = Objects.requireNonNull(uri, "Parameter uri to UriSource may not be null"); } @Override public InputStream getInputStream() throws IOException { URI parsedUri = URI.create(uri); return (parsedUri.getScheme().equals("http") || parsedUri.getScheme().equals("https")) ? parsedUri.toURL().openConnection().getInputStream() : getHadoopFileSystemInputStream(parsedUri); } /** * Get an input stream using the configured Hadoop file system for the given URI scheme */ private static InputStream getHadoopFileSystemInputStream(final URI uri) throws IOException { Configuration conf = new Configuration(); FileSystem fs = FileSystem.get(uri, conf); Path rootPath = new Path(uri); FileStatus[] statii = fs.globStatus(rootPath); if (statii == null || statii.length == 0) { throw new FileNotFoundException(uri.toString()); } List<InputStream> streams = new ArrayList<InputStream>(); for (FileStatus status : statii) { Path path = status.getPath(); LOGGER.debug("Incorporating input file: " + path); streams.add(fs.open(path)); } return new SequenceInputStream(java.util.Collections.enumeration(streams)); } }
35.348837
120
0.725987
bc6845a5f47d346197640637931070d6f86c0b92
1,411
package me.rina.turok.math; import net.minecraft.client.Minecraft; import net.minecraft.util.math.Vec3d; import java.math.BigDecimal; import java.math.RoundingMode; /** * @author SrRina * @since 21/10/2020 */ public class TurokMath { public static int intClamp(int value, int minimum, int maximum) { if (value <= minimum) { return minimum; } else if (value >= maximum) { return maximum; } return value; } public static double doubleClamp(double value, double minimum, double maximum) { if (value <= minimum) { return minimum; } else if (value >= maximum) { return maximum; } return value; } public static float floatClamp(float value, float minimum, float maximum) { if (value <= minimum) { return minimum; } else if (value >= maximum) { return maximum; } return value; } public static double decimal(double vDouble) { BigDecimal decimal = new BigDecimal(vDouble); decimal = decimal.setScale(2, RoundingMode.HALF_UP); return decimal.doubleValue(); } public static Vec3d lerp(Vec3d a, Vec3d b, float ticks) { return new Vec3d( a.x + (b.x - a.x) * ticks, a.y + (b.y - a.y) * ticks, a.z + (b.z - a.z) * ticks ); } }
23.915254
84
0.564848
e20466fceae4c4818b1e064598802ffe178e05c7
858
package com.example.android.camera2basic.util; import com.example.android.camera2basic.interfaces.ISessionStateCallback; import java.util.List; public class ComboCaptureSessionStateCallback implements ISessionStateCallback { private final List<ISessionStateCallback> mCaptureSessionStateCallbacks; public ComboCaptureSessionStateCallback(List<ISessionStateCallback> captureSessionStateCallbacks) { mCaptureSessionStateCallbacks = captureSessionStateCallbacks; } @Override public void onConfigured() { for (ISessionStateCallback callback : mCaptureSessionStateCallbacks) { callback.onConfigured(); } } @Override public void onConfigureFailed() { for (ISessionStateCallback callback : mCaptureSessionStateCallbacks) { callback.onConfigureFailed(); } } }
30.642857
103
0.750583
3f5d62aed648fc79bcc7c012b7b494408332686f
1,086
package com.lailatan.Portfolio.service; import com.lailatan.Portfolio.model.Experiencia; import com.lailatan.Portfolio.repository.ExperienciaRepository; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class ExperienciaService implements IExperienciaService{ @Autowired private ExperienciaRepository experienciaRepository; @Override public List<Experiencia> traerExperiencias() { //return experienciaRepository.findAll(); return experienciaRepository.findAllExperienciaByOrderByFechaDesdeDesc(); } @Override public Experiencia guardarExperiencia(Experiencia experiencia) { return (experiencia.datosCorrectos()?experienciaRepository.save(experiencia):null); } @Override public void borrarExperiencia(Integer id) { experienciaRepository.deleteById(id); } @Override public Experiencia traerExperienciaPorId(Integer id) { return experienciaRepository.findById(id).orElse(null); } }
30.166667
91
0.767035
0e4573fee899e05dc1aed509738893f62d5e7efd
102
/** * Marshalling for various Java specific types. */ package org.infinispan.protostream.types.java;
25.5
47
0.764706
431d287458ae63039637439b74552c659938940c
7,545
package org.apache.manifoldcf.agents.output.mongodb; import com.mongodb.MongoClient; import org.apache.manifoldcf.agents.output.BaseOutputConnector; import org.apache.manifoldcf.core.interfaces.*; import java.io.IOException; import java.net.UnknownHostException; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; public class MongodbConnector extends BaseOutputConnector { private final static String MONGODB_INDEXATION_ACTIVITY = "Indexation"; private final static String MONGODB_DELETION_ACTIVITY = "Deletion"; private final static String MONGODB_OPTIMIZE_ACTIVITY = "Optimize"; protected String username = null; protected String password = null; protected String serverLocation = null; protected int portNumber = 27017; protected String database = null; protected String collection = null; protected String document = null; private final static String[] MONGODB_ACTIVITIES = { MONGODB_INDEXATION_ACTIVITY, MONGODB_DELETION_ACTIVITY, MONGODB_OPTIMIZE_ACTIVITY }; private final static String MONGODB_TAB_PARAMETERS = "MongodbConnector.Parameters"; /** Forward to the javascript to check the configuration parameters */ private static final String EDIT_CONFIG_HEADER_FORWARD = "editConfiguration.js"; /** Forward to the HTML template to edit the configuration parameters */ private static final String EDIT_CONFIG_FORWARD_PARAMETERS = "editConfiguration_Parameters.html"; /** Forward to the HTML template to view the configuration parameters */ private static final String VIEW_CONFIG_FORWARD = "viewConfiguration.html"; /** Connection expiration interval */ private static final long EXPIRATION_INTERVAL = 60000L; private MongoClient client = null; private long expirationTime = -1L; public MongodbConnector() { } @Override public void connect(ConfigParams configParams) { super.connect(configParams); username = params.getParameter( MongodbConfig.ParameterEnum.USERNAME.name()); password = params.getParameter( MongodbConfig.ParameterEnum.PASSWORD.name()); username = "user"; password = "pass"; serverLocation = params.getParameter( MongodbConfig.ParameterEnum.SERVERLOCATION.name()); portNumber = Integer.parseInt(params.getParameter( MongodbConfig.ParameterEnum.PORTNUMBER.name())); database = params.getParameter( MongodbConfig.ParameterEnum.DATABASE.name()); collection = params.getParameter( MongodbConfig.ParameterEnum.COLLECTION.name()); document = params.getParameter( MongodbConfig.ParameterEnum.DOCUMENT.name()); } /** This method is called to assess whether to count this connector instance should * actually be counted as being connected. *@return true if the connector instance is actually connected. */ @Override public boolean isConnected() { return client != null; } protected MongoClient getSession() throws ManifoldCFException { if (client == null) { try{ client = new MongoClient(serverLocation ,portNumber ); client = new MongoClient("localhost" ,27017 ); } catch(UnknownHostException e){ throw new ManifoldCFException("UnknownHostException"); } } return client; } @Override public void disconnect() throws ManifoldCFException { super.disconnect(); client = null; // closeSession(); } @Override public void poll() throws ManifoldCFException { super.poll(); // if (connectionManager != null) // { // if (System.currentTimeMillis() > expirationTime) // { // closeSession(); // } // } } @Override public String[] getActivitiesList() { return MONGODB_ACTIVITIES; } /** Build a Set of Mongodb parameters. If configParams is null, * getConfiguration() is used. * * @param configParams */ final private MongodbConfig getConfigParameters( ConfigParams configParams) { if (configParams == null) configParams = getConfiguration(); return new MongodbConfig(configParams); } @Override public void outputConfigurationHeader(IThreadContext threadContext, IHTTPOutput out, Locale locale, ConfigParams parameters, List<String> tabsArray) throws ManifoldCFException, IOException { super.outputConfigurationHeader(threadContext, out, locale, parameters, tabsArray); tabsArray.add(Messages.getString(locale, MONGODB_TAB_PARAMETERS)); outputResource(EDIT_CONFIG_HEADER_FORWARD, out, locale, null, null, null, null); } @Override public void outputConfigurationBody(IThreadContext threadContext, IHTTPOutput out, Locale locale, ConfigParams parameters, String tabName) throws ManifoldCFException, IOException { super.outputConfigurationBody(threadContext, out, locale, parameters, tabName); MongodbConfig config = this.getConfigParameters(parameters); outputResource(EDIT_CONFIG_FORWARD_PARAMETERS, out, locale, config, tabName, null, null); } /** Read the content of a resource, replace the variable ${PARAMNAME} with the * value and copy it to the out. * * @param resName * @param out * @throws ManifoldCFException */ private static void outputResource(String resName, IHTTPOutput out, Locale locale, MongodbParam params, String tabName, Integer sequenceNumber, Integer currentSequenceNumber) throws ManifoldCFException { Map<String,String> paramMap = null; if (params != null) { paramMap = params.buildMap(); if (tabName != null) { paramMap.put("TabName", tabName); } if (currentSequenceNumber != null) paramMap.put("SelectedNum",currentSequenceNumber.toString()); } else { paramMap = new HashMap<String,String>(); } if (sequenceNumber != null) paramMap.put("SeqNum",sequenceNumber.toString()); Messages.outputResourceWithVelocity(out, locale, resName, paramMap, true); } @Override public void viewConfiguration(IThreadContext threadContext, IHTTPOutput out, Locale locale, ConfigParams parameters) throws ManifoldCFException, IOException { outputResource(VIEW_CONFIG_FORWARD, out, locale, getConfigParameters(parameters), null, null, null); } @Override public VersionContext getPipelineDescription(Specification os) throws ManifoldCFException { return new VersionContext("",params,os); } @Override public String processConfigurationPost(IThreadContext threadContext, IPostParameters variableContext, ConfigParams parameters) throws ManifoldCFException { MongodbConfig.contextToConfig(variableContext, parameters); return null; } }
34.610092
136
0.649304
f8d9fff5156e769516ee011183212f3a943b2017
1,485
package dynks.http; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import static java.lang.String.valueOf; import static dynks.Strings.recycle; import static java.lang.System.currentTimeMillis; /** * Created by jszczepankiewicz on 2015-04-06. */ public class ETag { public static final String ETAG_REQUEST_HEADER = "If-None-Match"; public static final String ETAG_RESPONSE_HEADER = "ETag"; public static final int SIZEOF_ETAG = valueOf(Long.MAX_VALUE + '-' + Integer.MAX_VALUE).length(); /** * Returns fast etag for given String. * @param value * @param builder buffer (might be non-empty, will be recycled) with internal buffer size to be at least SIZEOF_ETAG * to prevent reallocation of string buffer * @return */ public static String of(String value, StringBuilder builder){ if(value == null){ throw new NullPointerException("Value for etag calculation should not be null"); } recycle(builder); builder.append(currentTimeMillis()); builder.append('-'); builder.append(value.hashCode()); return builder.toString(); } public static String getFrom(HttpServletRequest request){ return request.getHeader(ETAG_REQUEST_HEADER); } public static void writeIn(HttpServletResponse response, String value){ response.addHeader(ETAG_RESPONSE_HEADER, value); } }
27.5
120
0.689562
0632a10fac8114cef00b3ab58b5d7f2a745a2dd0
1,794
package com.ncoding.backend.enrollment.controller; import com.ncoding.backend.enrollment.controller.response.EnrollmentResponse; import com.ncoding.backend.enrollment.domain.Enrollment; import com.ncoding.backend.enrollment.service.EnrollmentService; import io.swagger.v3.oas.annotations.Operation; import lombok.AllArgsConstructor; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; @AllArgsConstructor @RestController public class EnrollmentController { private final EnrollmentService<Enrollment, EnrollmentResponse> enrollmentService; @Operation(summary = "List All the courses enrollments of a student") @GetMapping("enrollments/{studentId}") public ResponseEntity<Page<EnrollmentResponse>> getEnrollmentsByStudentId(@PathVariable Long studentId, Pageable pageable) { return ResponseEntity.ok(enrollmentService.getEnrollmentsByStudentId(studentId, pageable)); } @Operation(summary = "Enroll a student in a course") @PostMapping("enrollments/") public ResponseEntity<Enrollment> enrollmentStudentInCourse(@Valid @RequestBody Enrollment enrollment) { return ResponseEntity.ok(enrollmentService.enroll(enrollment)); } @Operation(summary = "Removes the course enrollment from a user.") @DeleteMapping("enrollments/{studentId}") public ResponseEntity<?> declineEnrollmentByStudentId(@PathVariable Long studentId, @RequestParam Long courseId) { return enrollmentService.decline(studentId, courseId); } }
43.756098
108
0.737458
19c3fae3bf068d597e56d3117fd0e3247cfbdb74
1,924
package com.builtbroken.builder.mapper.builder; import com.builtbroken.builder.converter.ConversionHandler; import com.builtbroken.builder.mapper.anno.JsonMapping; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import javax.annotation.Nonnull; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.function.BiFunction; /** * Created by Robin Seifert on 2019-05-14. */ public class JsonBuilderConstructor extends JsonBuilderMapper { protected final Constructor constructor; public JsonBuilderConstructor(Class clazz, String type, Constructor constructor, BiFunction<JsonObject, ConversionHandler, Object>[] mappers, boolean useConstructorData) { super(clazz, type, mappers, useConstructorData); this.constructor = constructor; } @Override public Object newObject(@Nonnull JsonElement data, @Nonnull ConversionHandler converter) throws IllegalAccessException, InvocationTargetException, InstantiationException { if (mappers != null) { //can only map with a JSON object as we need to get the data if (data.isJsonObject()) { final Object[] args = buildParameters(converter, data.getAsJsonObject()); //Create return constructor.newInstance(args); } else { throw new RuntimeException("JsonBuilderConstructor: can not create object with parameters due to JSON not being an object."); } } //Json element input, not need to check type as it should be valid or its broken thus nothing will work anyways else if (constructor.getParameterCount() == 1) { return constructor.newInstance(data); } //Default, honestly shouldn't be used return constructor.newInstance(); } }
35.62963
173
0.68763
a7926d1d0d3b2295d8acced83fdcb9e1324c95a9
617
package com.jzg.demo.test1.controller; import com.jzg.demo.test1.model.User; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; /** * @description: UserController * @author: JZG * @date: 2018/1/18 13:50 * @version: v1.0.0 */ @Controller @RequestMapping("/user") public class UserController { @RequestMapping("/") public String index(){ return "index"; } @ResponseBody @RequestMapping("add") public User addUser(User user){ return user; } }
20.566667
62
0.701783
6f4e174b47853a090e44ed5e8bc16be30ed48cb5
1,682
/** * @author Virtusa */ package org.bian.service; import java.util.List; import org.bian.dto.*; public interface CustomerBehaviorModelsApiService { RecordCustomerBehaviorModelSpecificationResponsePayload record(String crReferenceId, RecordCustomerBehaviorModelSpecificationRequestPayload request); CustomerBehaviorModelsDeploymentBaseWithIdAndRoot requestPostDeployments(String crReferenceId, CustomerBehaviorModelsDeploymentBase request); CustomerBehaviorModelsDeploymentBaseWithIdAndRoot requestPutDeployments(String crReferenceId, String bqReferenceId, CustomerBehaviorModelsDeploymentBase request); RetrieveCustomerBehaviorModelResponse retrieve(String crReferenceId); List<String> retrieveBQIds(String crReferenceId, String behaviorQualifier); List<String> retrieveBQs(); CustomerBehaviorModelsComplianceBaseWithIdAndRoot retrieveCompliances(String crReferenceId, String bqReferenceId); CustomerBehaviorModelsDeploymentBaseWithIdAndRoot retrieveDeployments(String crReferenceId, String bqReferenceId); CustomerBehaviorModelsDesignBaseWithIdAndRoot retrieveDesigns(String crReferenceId, String bqReferenceId); CustomerBehaviorModelsImplementationBaseWithIdAndRoot retrieveImplementations(String crReferenceId, String bqReferenceId); CustomerBehaviorModelsRecordBaseWithIdAndRoot retrieveRecords(String crReferenceId, String bqReferenceId); List<String> retrieveRefIds(); CustomerBehaviorModelsTestingBaseWithIdAndRoot retrieveTestings(String crReferenceId, String bqReferenceId); CustomerBehaviorModelsDesignBaseWithIdAndRoot updateDesigns(String crReferenceId, String bqReferenceId, CustomerBehaviorModelsDesignBase request); }
41.02439
163
0.874554
ce1031baea6ab5115d88398e8ac4853ddc896f53
755
/** * springBootDemo * @author changle * Create Time: 2019年4月8日 * Modified Time: * Modified by: * Version: 1.0 */ package cn.springBootDemo.readConfig.configurationProperties; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; import lombok.Getter; import lombok.Setter; import lombok.ToString; /** * Project Name:springBootDemo * @author changle * Purpose: * Create Time: 2019年4月8日 * Create Specification: * Modified Time: * Modified by: * Modified Specification: * Version: 1.0 */ @Setter@Getter @ToString //通过lombok运行时自动生成方法 public class ConfigDemo2 { private String userName; private String passWord; }
20.405405
76
0.709934
180e1a71dd464917c5f81144d37aff26685fa012
3,711
package com.kubrick.jsbt.rpc.grpc.server.config; import lombok.extern.slf4j.Slf4j; import net.devh.boot.grpc.server.security.authentication.BasicGrpcAuthenticationReader; import net.devh.boot.grpc.server.security.authentication.CompositeGrpcAuthenticationReader; import net.devh.boot.grpc.server.security.authentication.GrpcAuthenticationReader; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.AuthenticationProvider; import org.springframework.security.authentication.ProviderManager; import org.springframework.security.authentication.dao.DaoAuthenticationProvider; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; /** * @author k * @version 1.0.0 * @ClassName SecurityConfiguration * @description: * 1、rest api 与rpc 的访问怎么进行判断其执行优先级? * @date 2021/3/10 下午8:25 */ @Slf4j @Configuration @EnableGlobalMethodSecurity(securedEnabled = true, proxyTargetClass = true) public class SecurityConfiguration { @Bean PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(10); } @Bean UserDetailsService userDetailsService() { return username -> { log.debug("Searching user: {}", username); switch (username) { case "guest": { return new User(username, passwordEncoder().encode(username + "Password"), Collections.emptyList()); } case "kubrick": { final List<SimpleGrantedAuthority> authorities = Arrays.asList(new SimpleGrantedAuthority("ROLE_GREET")); return new User(username, passwordEncoder().encode(username + "Password"), authorities); } default: { throw new UsernameNotFoundException("Could not find user!"); } } }; } @Bean DaoAuthenticationProvider daoAuthenticationProvider() { final DaoAuthenticationProvider provider = new DaoAuthenticationProvider(); provider.setUserDetailsService(userDetailsService()); provider.setPasswordEncoder(passwordEncoder()); return provider; } @Bean AuthenticationManager authenticationManager() { final List<AuthenticationProvider> providers = new ArrayList<>(); providers.add(daoAuthenticationProvider()); return new ProviderManager(providers); } @Bean GrpcAuthenticationReader authenticationReader() { final List<GrpcAuthenticationReader> readers = new ArrayList<>(); readers.add(new BasicGrpcAuthenticationReader()); return new CompositeGrpcAuthenticationReader(readers); } /* @Bean AuthenticationManager authenticationManager() { final List<AuthenticationProvider> providers = new ArrayList<>(); providers.add(new X509CertificateAuthenticationProvider(userDetailsService())); return new ProviderManager(providers); } */ }
36.742574
120
0.728106
9ab9b681898fabe055955f4edee654b50376aea9
657
package org.edmcouncil.spec.ontoviewer.toolkit.handlers; import openllet.owlapi.OpenlletReasonerFactory; import org.edmcouncil.spec.ontoviewer.core.ontology.DetailsManager; import org.springframework.stereotype.Service; @Service public class OntologyConsistencyChecker { private final DetailsManager detailsManager; public OntologyConsistencyChecker(DetailsManager detailsManager) { this.detailsManager = detailsManager; } public boolean checkOntologyConsistency() { var ontology = detailsManager.getOntology(); var reasoner = OpenlletReasonerFactory.getInstance().createReasoner(ontology); return reasoner.isConsistent(); } }
31.285714
82
0.812785
829334a2694741bab3618a6e6bf5c7093e7c448c
2,153
package com.abdulkarimalbaik.dev.photogram.Fragments; import android.content.Context; import android.net.Uri; import android.os.Bundle; import android.support.design.widget.BottomSheetDialogFragment; import android.support.v4.app.Fragment; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.abdulkarimalbaik.dev.photogram.Adapter.EmojiAdapter; import com.abdulkarimalbaik.dev.photogram.Interface.EmojiAdapterListener; import com.abdulkarimalbaik.dev.photogram.Interface.EmojiFragmentListener; import com.abdulkarimalbaik.dev.photogram.R; import ja.burhanrashid52.photoeditor.PhotoEditor; public class EmojiFragment extends BottomSheetDialogFragment implements EmojiAdapterListener { RecyclerView recycler_emoji; public static EmojiFragment instance; EmojiFragmentListener listener; public void setListener(EmojiFragmentListener listener) { this.listener = listener; } public EmojiFragment() { } public static EmojiFragment getInstance(){ if (instance == null) instance = new EmojiFragment(); return instance; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_emoji, container, false); recycler_emoji = (RecyclerView)view.findViewById(R.id.recycler_emoji); recycler_emoji.setHasFixedSize(true); recycler_emoji.setLayoutManager(new GridLayoutManager(getActivity() , 5)); EmojiAdapter adapter = new EmojiAdapter(getContext() , PhotoEditor.getEmojis(getContext()) , this); recycler_emoji.setAdapter(adapter); return view; } @Override public void onEmojiItemSelected(String emoji) { listener.omEmojiSelected(emoji); } }
29.493151
107
0.744078
e1c0d20aa7d0152d885fd495321e14056a2edf22
4,959
package indi.chen.hellojava.basic; import java.io.*; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; public class ConverEncoding { public static void main(String[] args) throws Exception { String srcDir = "D:\\WORKSPACE\\zjkjtSimilarity"; List<String> files = new ArrayList<String>(); fetchFileList(srcDir, files, ".xml"); for (String fileName : files) { String oldCharset = get_charset(new File(fileName)); convert(fileName, oldCharset, fileName, "UTF-8"); } } public static void convert(String oldFile, String oldCharset, String newFlie, String newCharset) { BufferedReader bin; FileOutputStream fos; StringBuffer content = new StringBuffer(); try { System.out.println(oldFile); bin = new BufferedReader( new InputStreamReader(new FileInputStream(oldFile), oldCharset)); String line = null; while ((line = bin.readLine()) != null) { content.append(line); content.append(System.getProperty("line.separator")); } bin.close(); File dir = new File(newFlie.substring(0, newFlie.lastIndexOf("\\"))); if (!dir.exists()) { dir.mkdirs(); } fos = new FileOutputStream(newFlie); Writer out = new OutputStreamWriter(fos, newCharset); out.write(content.toString()); out.close(); fos.close(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public static void fetchFileList(String strPath, List<String> filelist, final String regex) { File dir = new File(strPath); File[] files = dir.listFiles(); Pattern p = Pattern.compile(regex); if (files == null) return; for (int i = 0; i < files.length; i++) { if (files[i].isDirectory()) { fetchFileList(files[i].getAbsolutePath(), filelist, regex); } else { String strFileName = files[i].getAbsolutePath(); Matcher m = p.matcher(strFileName); if (m.find()) { filelist.add(strFileName); } } } } public static String get_charset(File file) { String charset = "GBK"; byte[] first3Bytes = new byte[3]; try { boolean checked = false; BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file)); bis.mark(0); int read = bis.read(first3Bytes, 0, 3); if (read == -1) return charset; if (first3Bytes[0] == (byte) 0xFF && first3Bytes[1] == (byte) 0xFE) { charset = "UTF-16LE"; checked = true; } else if (first3Bytes[0] == (byte) 0xFE && first3Bytes[1] == (byte) 0xFF) { charset = "UTF-16BE"; checked = true; } else if (first3Bytes[0] == (byte) 0xEF && first3Bytes[1] == (byte) 0xBB && first3Bytes[2] == (byte) 0xBF) { charset = "UTF-8"; checked = true; } bis.reset(); if (!checked) { while ((read = bis.read()) != -1) { if (read >= 0xF0) break; if (0x80 <= read && read <= 0xBF) // 单独出现BF以下的,也算是GBK break; if (0xC0 <= read && read <= 0xDF) { read = bis.read(); if (0x80 <= read && read <= 0xBF) // 双字节 (0xC0 - 0xDF) // (0x80 // - 0xBF),也可能在GB编码内 continue; else break; } else if (0xE0 <= read && read <= 0xEF) {// 也有可能出错,但是几率较小 read = bis.read(); if (0x80 <= read && read <= 0xBF) { read = bis.read(); if (0x80 <= read && read <= 0xBF) { charset = "UTF-8"; break; } else break; } else break; } } } bis.close(); } catch (Exception e) { e.printStackTrace(); } return charset; } }
38.44186
103
0.446663
884f544ff9aa375b8621cb3c5517d42ee2f25cb3
3,751
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.impl; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.camel.NoSuchBeanException; import org.apache.camel.RuntimeCamelException; import org.apache.camel.spi.Registry; /** * This registry will look up the object with the sequence of the registry list until it finds the Object. */ public class CompositeRegistry implements Registry { private List<Registry> registryList; public CompositeRegistry() { registryList = new ArrayList<Registry>(); } public CompositeRegistry(List<Registry> registries) { registryList = registries; } public void addRegistry(Registry registry) { registryList.add(registry); } public <T> T lookupByNameAndType(String name, Class<T> type) { T answer = null; RuntimeCamelException ex = null; for (Registry registry : registryList) { try { answer = registry.lookupByNameAndType(name, type); } catch (Throwable e) { // do not double wrap the exception if (e instanceof NoSuchBeanException) { ex = (NoSuchBeanException)e; } else { ex = new NoSuchBeanException(name, "Cannot lookup: " + name + " from registry: " + registry + " with expected type: " + type + " due: " + e.getMessage(), e); } } if (answer != null) { return answer; } } if (ex != null) { throw ex; } else { return answer; } } public Object lookupByName(String name) { Object answer = null; for (Registry registry : registryList) { answer = registry.lookupByName(name); if (answer != null) { break; } } return answer; } public <T> Map<String, T> findByTypeWithName(Class<T> type) { Map<String, T> answer = Collections.emptyMap(); for (Registry registry : registryList) { answer = registry.findByTypeWithName(type); if (!answer.isEmpty()) { break; } } return answer; } public <T> Set<T> findByType(Class<T> type) { Set<T> answer = Collections.emptySet(); for (Registry registry : registryList) { answer = registry.findByType(type); if (!answer.isEmpty()) { break; } } return answer; } public Object lookup(String name) { return lookupByName(name); } public <T> T lookup(String name, Class<T> type) { return lookupByNameAndType(name, type); } public <T> Map<String, T> lookupByType(Class<T> type) { return findByTypeWithName(type); } }
31.788136
111
0.600906
17933c0fb316375cfb83f35d2b30a17371490082
1,372
package com.zhonghua.dileber.tools; import android.app.Activity; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.NetworkInfo.State; import com.zhonghua.dileber.app.SApplication; public class HNetwork { private ConnectivityManager con; private static volatile HNetwork instance; public static HNetwork getInstance() { if (instance == null) { synchronized (HNetwork.class) { if (instance == null) instance = new HNetwork(); } } return instance; } public HNetwork() { // TODO Auto-generated constructor stub con=(ConnectivityManager) SApplication.getAppContext().getSystemService(Activity.CONNECTIVITY_SERVICE); } /** */ public boolean checkNetwork() { // TODO Auto-generated method stub NetworkInfo info=con.getActiveNetworkInfo(); if (info != null && info.isConnected()) { // 判断当前网络是否已经连接 if (info.getState() == State.CONNECTED) { return true; }else{ return false; } } return false; } public boolean isWifi() { // TODO Auto-generated method stub if(checkNetwork()){ State wifi = con.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState(); //判断wifi已连接的条件 if(wifi == State.CONNECTED||wifi==State.CONNECTING){ return true; } return false; } return false; } }
22.129032
105
0.672012
081c15cd8bede243261b648cdb944f62c59d5ec7
15,174
package org.sunbird.portal.department.controller; import java.util.List; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PatchMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.sunbird.portal.department.PortalConstants; import org.sunbird.portal.department.dto.UserDepartmentRole; import org.sunbird.portal.department.model.DepartmentInfo; import org.sunbird.portal.department.model.UserDepartmentInfo; import org.sunbird.portal.department.service.MdoPortalService; import org.sunbird.portal.department.service.PortalService; import org.sunbird.portal.department.service.SpvPortalService; @RestController public class PortalController { @Autowired PortalService portalService; @Autowired SpvPortalService spvPortalService; @Autowired MdoPortalService mdoPortalService; // ----------------- Public APIs -------------------- @GetMapping("/portal/listDeptNames") public ResponseEntity<?> getDeptNameList() throws Exception { return new ResponseEntity<>(portalService.getDeptNameList(), HttpStatus.OK); } @GetMapping("/portal/getAllDept") public ResponseEntity<?> getAllDepartment() throws Exception { return new ResponseEntity<>(portalService.getAllDept(), HttpStatus.OK); } @GetMapping("/portal/deptSearch") public ResponseEntity<?> searchDepartment(@RequestParam(name = "friendlyName", required = true) String deptName) throws Exception { return new ResponseEntity<>(portalService.searchDept(deptName), HttpStatus.OK); } // ----------------- END of Public APIs -------------------- // ----------------- SPV APIs ----------------------- @GetMapping("/portal/spv/isAdmin") public ResponseEntity<Boolean> isSpvAdmin(@RequestHeader("wid") String wid) throws Exception { return new ResponseEntity<Boolean>( portalService.isAdmin(PortalConstants.SPV_DEPT_TYPE, PortalConstants.SPV_ROLE_NAME, wid), HttpStatus.OK); } @GetMapping("/portal/spv/mydepartment") public ResponseEntity<?> getMyDepartments(@RequestHeader("wid") String wid, @RequestParam(name = "allUsers", required = false) boolean isUserInfoRequired, @RequestHeader("rootOrg") String rootOrg) throws Exception { validateUserAccess(PortalConstants.SPV_DEPT_TYPE, PortalConstants.SPV_ROLE_NAME, wid); return new ResponseEntity<>(spvPortalService.getMyDepartment(wid, isUserInfoRequired, rootOrg), HttpStatus.OK); } @PostMapping("/portal/spv/department") public ResponseEntity<DepartmentInfo> addDepartment(@RequestHeader("xAuthUser") String authUserToken, @RequestHeader("wid") String wid, @RequestBody DepartmentInfo deptInfo, @RequestHeader("rootOrg") String rootOrg) throws Exception { validateUserAccess(PortalConstants.SPV_DEPT_TYPE, PortalConstants.SPV_ROLE_NAME, wid); return new ResponseEntity<DepartmentInfo>(spvPortalService.addDepartment(authUserToken, wid, deptInfo, rootOrg), HttpStatus.OK); } @PatchMapping("/portal/spv/department") public ResponseEntity<DepartmentInfo> updateDepartment(@RequestHeader("wid") String wid, @RequestBody DepartmentInfo deptInfo, @RequestHeader("rootOrg") String rootOrg) throws Exception { validateUserAccess(PortalConstants.SPV_DEPT_TYPE, PortalConstants.SPV_ROLE_NAME, wid); return new ResponseEntity<DepartmentInfo>(spvPortalService.updateDepartment(deptInfo, rootOrg), HttpStatus.OK); } @GetMapping("/portal/spv/department") public ResponseEntity<List<DepartmentInfo>> getAllDepartments(@RequestHeader("wid") String wid, @RequestHeader("rootOrg") String rootOrg) throws Exception { validateUserAccess(PortalConstants.SPV_DEPT_TYPE, PortalConstants.SPV_ROLE_NAME, wid); return new ResponseEntity<List<DepartmentInfo>>(spvPortalService.getAllDepartments(rootOrg), HttpStatus.OK); } @GetMapping("/portal/spv/department/{dept_id}") public ResponseEntity<DepartmentInfo> getDepartmentById(@PathVariable("dept_id") Integer deptId, @RequestParam(name = "allUsers", required = false) boolean isUserInfoRequired, @RequestHeader("wid") String wid, @RequestHeader("rootOrg") String rootOrg) throws Exception { validateUserAccess(PortalConstants.SPV_DEPT_TYPE, PortalConstants.SPV_ROLE_NAME, wid); return new ResponseEntity<DepartmentInfo>( spvPortalService.getDepartmentById(deptId, isUserInfoRequired, rootOrg), HttpStatus.OK); } @PostMapping("/portal/spv/userrole") public ResponseEntity<UserDepartmentInfo> addUserRoleInDepartmentBySPV(@RequestBody UserDepartmentRole userDeptRole, @RequestHeader("rootOrg") String rootOrg, @RequestHeader("org") String org, @RequestHeader("wid") String wid) throws Exception { validateUserAccess(PortalConstants.SPV_DEPT_TYPE, PortalConstants.SPV_ROLE_NAME, wid); return new ResponseEntity<UserDepartmentInfo>( portalService.addUserRoleInDepartment(userDeptRole, wid, rootOrg, org), HttpStatus.OK); } @PatchMapping("/portal/spv/userrole") public ResponseEntity<UserDepartmentInfo> updateUserRoleInDepartmentBySPV( @RequestBody UserDepartmentRole userDeptRole, @RequestHeader("rootOrg") String rootOrg, @RequestHeader("org") String org, @RequestHeader("wid") String wid) throws Exception { validateUserAccess(PortalConstants.SPV_DEPT_TYPE, PortalConstants.SPV_ROLE_NAME, wid); return new ResponseEntity<UserDepartmentInfo>( portalService.updateUserRoleInDepartment(userDeptRole, wid, rootOrg, org), HttpStatus.OK); } @GetMapping("/portal/spv/role") public ResponseEntity<?> getSpvRoles(@RequestHeader("rootOrg") String rootOrg) { return new ResponseEntity<>(portalService.getAllDepartments(rootOrg), HttpStatus.OK); } // ----------------- SPV APIs ----------------------- // ----------------- FRAC APIs ---------------------- @GetMapping("/portal/frac/mydepartment") public ResponseEntity<?> getMyFracDepartment(@RequestHeader("wid") String wid, @RequestParam(name = "allUsers", required = false) boolean isUserInfoRequired, @RequestHeader("rootOrg") String rootOrg) throws Exception { if (!portalService.validateFracUserLogin(wid)) { throw new Exception("User is not assigned with any FRAC related roles."); } return new ResponseEntity<>(mdoPortalService.getMyFracDepartment(wid, isUserInfoRequired, rootOrg), HttpStatus.OK); } // ----------------- END OF FRAC APIs --------------- // ----------------- MDO APIs ----------------------- @GetMapping("/portal/mdo/isAdmin") public ResponseEntity<Boolean> isMdoAdmin(@RequestHeader("wid") String wid) throws Exception { return new ResponseEntity<Boolean>( portalService.isAdmin(PortalConstants.MDO_DEPT_TYPE, PortalConstants.MDO_ROLE_NAME, wid), HttpStatus.OK); } @GetMapping("/portal/mdo/mydepartment") public ResponseEntity<?> getMyMdoDepartment(@RequestHeader("wid") String wid, @RequestParam(name = "allUsers", required = false) boolean isUserInfoRequired, @RequestHeader("rootOrg") String rootOrg) throws Exception { validateUserAccess(PortalConstants.MDO_DEPT_TYPE, PortalConstants.MDO_ROLE_NAME, wid); return new ResponseEntity<>(mdoPortalService.getMyDepartment(wid, isUserInfoRequired, rootOrg), HttpStatus.OK); } @PatchMapping("/portal/mdo/department") public ResponseEntity<DepartmentInfo> updateMdoDepartment(@RequestHeader("wid") String wid, @RequestBody DepartmentInfo deptInfo, @RequestHeader("rootOrg") String rootOrg) throws Exception { validateUserAccess(PortalConstants.MDO_DEPT_TYPE, PortalConstants.MDO_ROLE_NAME, wid, deptInfo.getId()); return new ResponseEntity<DepartmentInfo>(mdoPortalService.updateDepartment(deptInfo, rootOrg), HttpStatus.OK); } @PostMapping("/portal/mdo/userrole") public ResponseEntity<UserDepartmentInfo> addUserRoleInDepartmentByMDO(@RequestBody UserDepartmentRole userDeptRole, @RequestHeader("rootOrg") String rootOrg, @RequestHeader("org") String org, @RequestHeader("wid") String wid) throws Exception { validateUserAccess(PortalConstants.MDO_DEPT_TYPE, PortalConstants.MDO_ROLE_NAME, wid, userDeptRole.getDeptId()); return new ResponseEntity<UserDepartmentInfo>( portalService.addUserRoleInDepartment(userDeptRole, wid, rootOrg, org), HttpStatus.OK); } @PatchMapping("/portal/mdo/userrole") public ResponseEntity<UserDepartmentInfo> updateUserRoleInDepartmentByMDO( @RequestBody UserDepartmentRole userDeptRole, @RequestHeader("rootOrg") String rootOrg, @RequestHeader("org") String org, @RequestHeader("wid") String wid) throws Exception { validateUserAccess(PortalConstants.MDO_DEPT_TYPE, PortalConstants.MDO_ROLE_NAME, wid, userDeptRole.getDeptId()); return new ResponseEntity<UserDepartmentInfo>( portalService.updateUserRoleInDepartment(userDeptRole, wid, rootOrg, org), HttpStatus.OK); } // ----------------- MDO APIs ----------------------- // ----------------- CBP APIs ----------------------- @GetMapping("/portal/cbp/isAdmin") public ResponseEntity<Boolean> isCBPAdmin(@RequestHeader("wid") String wid) throws Exception { return new ResponseEntity<Boolean>(portalService.validateCBPUserLogin(wid), HttpStatus.OK); } @GetMapping("/portal/cbp/mydepartment") public ResponseEntity<?> getMyCbpDepartment(@RequestHeader("wid") String wid, @RequestHeader("rootOrg") String rootOrg) throws Exception { validateCBPUserAccess(wid); return new ResponseEntity<>(portalService.getMyCbpDepartment(wid, rootOrg), HttpStatus.OK); } @PatchMapping("/portal/cbp/department") public ResponseEntity<DepartmentInfo> updateCbpDepartment(@RequestHeader("wid") String wid, @RequestBody DepartmentInfo deptInfo, @RequestHeader("rootOrg") String rootOrg) throws Exception { validateUserAccess(PortalConstants.CBP_DEPT_TYPE, PortalConstants.CBP_ROLE_NAME, wid); return new ResponseEntity<DepartmentInfo>(mdoPortalService.updateDepartment(deptInfo, rootOrg), HttpStatus.OK); } @PostMapping("/portal/cbp/userrole") public ResponseEntity<UserDepartmentInfo> addUserRoleInDepartmentByCBP(@RequestBody UserDepartmentRole userDeptRole, @RequestHeader("rootOrg") String rootOrg, @RequestHeader("org") String org, @RequestHeader("wid") String wid) throws Exception { validateUserAccess(PortalConstants.CBP_DEPT_TYPE, PortalConstants.CBP_ROLE_NAME, wid, userDeptRole.getDeptId()); return new ResponseEntity<UserDepartmentInfo>( portalService.addUserRoleInDepartment(userDeptRole, wid, rootOrg, org), HttpStatus.OK); } @PatchMapping("/portal/cbp/userrole") public ResponseEntity<UserDepartmentInfo> updateUserRoleInDepartmentByCBP( @RequestBody UserDepartmentRole userDeptRole, @RequestHeader("rootOrg") String rootOrg, @RequestHeader("org") String org, @RequestHeader("wid") String wid) throws Exception { validateUserAccess(PortalConstants.CBP_DEPT_TYPE, PortalConstants.CBP_ROLE_NAME, wid, userDeptRole.getDeptId()); return new ResponseEntity<UserDepartmentInfo>( portalService.updateUserRoleInDepartment(userDeptRole, wid, rootOrg, org), HttpStatus.OK); } @GetMapping("/portal/cbp/searchUser/deptId/{dept_id}/role/{role_name}/userlike/{username}") public ResponseEntity<?> searchUserForRole(@PathVariable("dept_id") Integer deptId, @PathVariable("role_name") String roleName, @PathVariable("username") String userName) throws Exception { return new ResponseEntity<>(portalService.searchUserForRole(deptId, roleName, userName), HttpStatus.OK); } // ----------------- END OF CBP APIs ----------------------- @GetMapping("/portal/department/{dept_id}") public ResponseEntity<DepartmentInfo> getDepartmentById(@PathVariable("dept_id") Integer deptId, @RequestParam(name = "allUsers", required = false) boolean isUserInfoRequired, @RequestHeader("rootOrg") String rootOrg) { return new ResponseEntity<DepartmentInfo>(portalService.getDepartmentById(deptId, isUserInfoRequired, rootOrg), HttpStatus.OK); } @GetMapping("/portal/mydepartment") public ResponseEntity<DepartmentInfo> getMyDepartmentDetails(@RequestHeader("wid") String userId, @RequestParam(name = "allUsers", required = false) boolean isUserInfoRequired) throws Exception { return new ResponseEntity<DepartmentInfo>(portalService.getMyDepartmentDetails(userId, isUserInfoRequired), HttpStatus.OK); } @PatchMapping("/portal/department") public ResponseEntity<DepartmentInfo> updateDepartment(@RequestBody DepartmentInfo deptInfo, @RequestHeader("rootOrg") String rootOrg) throws Exception { return new ResponseEntity<DepartmentInfo>(portalService.updateDepartment(deptInfo, rootOrg), HttpStatus.OK); } @PostMapping("/portal/userrole") public ResponseEntity<UserDepartmentInfo> updateUserRoleInDepartment( @Valid @RequestBody UserDepartmentRole userDeptRole, @RequestHeader("rootOrg") String rootOrg, @RequestHeader("org") String org, @RequestHeader("wid") String wid) throws Exception { return new ResponseEntity<UserDepartmentInfo>( portalService.addUserRoleInDepartment(userDeptRole, wid, rootOrg, org), HttpStatus.OK); } // @GetMapping("/portal/user/{user_id}/departmentRoles") // public ResponseEntity<List<UserDepartmentInfo>> getUserDepartments(@PathVariable("user_id") String userId) { // return new ResponseEntity<List<UserDepartmentInfo>>(portalService.getUserDepartments(userId), HttpStatus.OK); // } @GetMapping("/portal/department/{dept_id}/user/{user_id}/isAdmin") public ResponseEntity<Boolean> checkAdminPrivilage(@PathVariable("dept_id") Integer deptId, @PathVariable("user_id") String userId, @RequestHeader("rootOrg") String rootOrg) throws Exception { return new ResponseEntity<Boolean>(portalService.checkAdminPrivilage(deptId, userId, rootOrg), HttpStatus.OK); } // @GetMapping("/portal/{dept_key}/isAdmin") // public ResponseEntity<Boolean> checkMDOAdminPrivilage(@PathVariable("dept_key") String deptKey, // @RequestHeader("wid") String wid) throws Exception { // return new ResponseEntity<Boolean>(portalService.checkMdoAdminPrivilage(deptKey, wid), HttpStatus.OK); // } private void validateUserAccess(String deptType, String roleName, String wid) throws Exception { validateUserAccess(deptType, roleName, wid, -1); } private void validateUserAccess(String deptType, String roleName, String wid, Integer deptId) throws Exception { if (!portalService.isAdmin(deptType, roleName, wid)) { throw new Exception("User is not assigned with Role: '" + roleName + "'."); } } private void validateCBPUserAccess(String userId) throws Exception { if (!portalService.validateCBPUserLogin(userId)) { throw new Exception("User is not assigned with any CBP related roles."); } } @GetMapping("/portal/isUserActive") public ResponseEntity<Boolean> isUserActive(@RequestHeader("userId") String userId) { return new ResponseEntity<Boolean>(portalService.isUserActive(userId), HttpStatus.OK); } }
52.14433
136
0.775801
859f98f3db1c769e4f6d8be3fd0bce10fe741417
10,640
package org.rabix.engine.store.postgres.jdbi.impl; import com.fasterxml.jackson.core.type.TypeReference; import org.postgresql.util.PGobject; import org.rabix.common.helper.JSONHelper; import org.rabix.engine.store.model.JobRecord; import org.rabix.engine.store.model.JobRecord.JobIdRootIdPair; import org.rabix.engine.store.model.JobRecord.PortCounter; import org.rabix.engine.store.model.scatter.ScatterStrategy; import org.rabix.engine.store.postgres.jdbi.impl.JDBIJobRecordRepository.JobRecordMapper; import org.rabix.engine.store.repository.JobRecordRepository; import org.skife.jdbi.v2.SQLStatement; import org.skife.jdbi.v2.StatementContext; import org.skife.jdbi.v2.sqlobject.*; import org.skife.jdbi.v2.sqlobject.customizers.RegisterMapper; import org.skife.jdbi.v2.sqlobject.stringtemplate.UseStringTemplate3StatementLocator; import org.skife.jdbi.v2.tweak.ResultSetMapper; import org.skife.jdbi.v2.unstable.BindIn; import java.lang.annotation.*; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Timestamp; import java.time.LocalDateTime; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.UUID; @RegisterMapper(JobRecordMapper.class) @UseStringTemplate3StatementLocator public abstract class JDBIJobRecordRepository extends JobRecordRepository { @Override @SqlUpdate("insert into job_record (id,external_id,root_id,parent_id,blocking,job_state,input_counters,output_counters,is_scattered,is_container,is_scatter_wrapper,global_inputs_count,global_outputs_count,scatter_strategy,dag_hash,created_at,modified_at) values (:id,:external_id,:root_id,:parent_id,:blocking,:job_state::job_record_state,:input_counters,:output_counters,:is_scattered,:is_container,:is_scatter_wrapper,:global_inputs_count,:global_outputs_count,:scatter_strategy,:dag_hash, :created_at,:modified_at)") public abstract int insert(@BindJobRecord JobRecord jobRecord); @Override @SqlUpdate("update job_record set id=:id,external_id=:external_id,root_id=:root_id,parent_id=:parent_id,blocking=:blocking,job_state=:job_state::job_record_state,input_counters=:input_counters,output_counters=:output_counters,is_scattered=:is_scattered,is_container=:is_container,is_scatter_wrapper=:is_scatter_wrapper,global_inputs_count=:global_inputs_count,global_outputs_count=:global_outputs_count,scatter_strategy=:scatter_strategy,dag_hash=:dag_hash,modified_at='now'::timestamp where id=:id and root_id=:root_id") public abstract int update(@BindJobRecord JobRecord jobRecord); @Override @SqlBatch("insert into job_record (id,external_id,root_id,parent_id,blocking,job_state,input_counters,output_counters,is_scattered,is_container,is_scatter_wrapper,global_inputs_count,global_outputs_count,scatter_strategy,dag_hash,created_at,modified_at) values (:id,:external_id,:root_id,:parent_id,:blocking,:job_state::job_record_state,:input_counters,:output_counters,:is_scattered,:is_container,:is_scatter_wrapper,:global_inputs_count,:global_outputs_count,:scatter_strategy,:dag_hash,:created_at,:modified_at)") public abstract void insertBatch(@BindJobRecord Iterator<JobRecord> records); @Override @SqlBatch("update job_record set id=:id,external_id=:external_id,root_id=:root_id,parent_id=:parent_id,blocking=:blocking,job_state=:job_state::job_record_state,input_counters=:input_counters,output_counters=:output_counters,is_scattered=:is_scattered,is_container=:is_container,is_scatter_wrapper=:is_scatter_wrapper,global_inputs_count=:global_inputs_count,global_outputs_count=:global_outputs_count,scatter_strategy=:scatter_strategy,dag_hash=:dag_hash,modified_at='now'::timestamp where id=:id and root_id=:root_id") public abstract void updateBatch(@BindJobRecord Iterator<JobRecord> records); @Override @SqlUpdate("update job_record set job_state=:state::job_record_state where root_id=:root_id and job_state::text in (<states>)") public abstract void updateStatus(@Bind("root_id") UUID rootId, @Bind("state") JobRecord.JobState state, @BindIn("states") Set<JobRecord.JobState> whereStates); @Override @SqlUpdate("delete from job_record where external_id=:external_id and root_id=:root_id") public abstract void delete(@Bind("external_id") UUID externalId, @Bind("root_id") UUID rootId); @Override @SqlQuery("select * from job_record where root_id=:root_id") public abstract List<JobRecord> get(@Bind("root_id") UUID rootId); @Override @SqlQuery("select * from job_record where id='root' and root_id=:root_id") public abstract JobRecord getRoot(@Bind("root_id") UUID rootId); @Override @SqlQuery("select * from job_record where id=:id and root_id=:root_id") public abstract JobRecord get(@Bind("id") String id, @Bind("root_id") UUID rootId); @Override @SqlQuery("select * from job_record where parent_id=:parent_id and root_id=:root_id") public abstract List<JobRecord> getByParent(@Bind("parent_id") UUID parentId, @Bind("root_id") UUID rootId); @Override @SqlQuery("select * from job_record where job_state='READY'::job_record_state and root_id=:root_id") public abstract List<JobRecord> getReady(@Bind("root_id") UUID rootId); @Override @SqlQuery("select * from job_record where job_state::text in (<states>) and root_id=:root_id") public abstract List<JobRecord> get(@Bind("root_id") UUID rootId, @BindIn("states") Set<JobRecord.JobState> states); @BindingAnnotation(BindJobRecord.JobBinderFactory.class) @Retention(RetentionPolicy.RUNTIME) @Target({ ElementType.PARAMETER }) public static @interface BindJobRecord { public static class JobBinderFactory implements BinderFactory<Annotation> { public Binder<BindJobRecord, JobRecord> build(Annotation annotation) { return new Binder<BindJobRecord, JobRecord>() { public void bind(SQLStatement<?> q, BindJobRecord bind, JobRecord jobRecord) { q.bind("id", jobRecord.getId()); q.bind("external_id", jobRecord.getExternalId()); q.bind("root_id", jobRecord.getRootId()); q.bind("parent_id", jobRecord.getParentId()); q.bind("blocking", jobRecord.isBlocking()); q.bind("job_state", jobRecord.getState()); try { PGobject data = new PGobject(); data.setType("jsonb"); data.setValue(JSONHelper.writeObject(jobRecord.getInputCounters())); q.bind("input_counters", data); } catch (SQLException ex) { throw new IllegalStateException("Error Binding input counters", ex); } try { PGobject data = new PGobject(); data.setType("jsonb"); data.setValue(JSONHelper.writeObject(jobRecord.getOutputCounters())); q.bind("output_counters", data); } catch (SQLException ex) { throw new IllegalStateException("Error Binding output counters", ex); } q.bind("is_scattered", jobRecord.isScattered()); q.bind("is_container", jobRecord.isContainer()); q.bind("is_scatter_wrapper", jobRecord.isScatterWrapper()); q.bind("global_inputs_count", jobRecord.getNumberOfGlobalInputs()); q.bind("global_outputs_count", jobRecord.getNumberOfGlobalOutputs()); try { PGobject data = new PGobject(); data.setType("jsonb"); data.setValue(JSONHelper.writeObject(jobRecord.getScatterStrategy())); q.bind("scatter_strategy", data); } catch (SQLException ex) { throw new IllegalStateException("Error Binding output counters", ex); } q.bind("dag_hash", jobRecord.getDagHash()); q.bind("modified_at", Timestamp.valueOf(jobRecord.getModifiedAt())); q.bind("created_at", Timestamp.valueOf(jobRecord.getCreatedAt())); } }; } } } @BindingAnnotation(BindJobIdRootId.JobBinderFactory.class) @Retention(RetentionPolicy.RUNTIME) @Target({ ElementType.PARAMETER }) public static @interface BindJobIdRootId { public static class JobBinderFactory implements BinderFactory<Annotation> { public Binder<BindJobIdRootId, JobIdRootIdPair> build(Annotation annotation) { return new Binder<BindJobIdRootId, JobIdRootIdPair>() { public void bind(SQLStatement<?> q, BindJobIdRootId bind, JobIdRootIdPair pair) { q.bind("id", pair.id); q.bind("root_id", pair.rootId); } }; } } } public static class JobRecordMapper implements ResultSetMapper<JobRecord> { public JobRecord map(int index, ResultSet resultSet, StatementContext ctx) throws SQLException { String id = resultSet.getString("id"); UUID externalId = resultSet.getObject("external_id", UUID.class); UUID rootId = resultSet.getObject("root_id", UUID.class); UUID parentId = resultSet.getObject("parent_id", UUID.class); Boolean isBlocking = resultSet.getBoolean("blocking"); String jobState = resultSet.getString("job_state"); String inputCounters = resultSet.getString("input_counters"); String outputCounters = resultSet.getString("output_counters"); Boolean isScattered = resultSet.getBoolean("is_scattered"); Boolean isContainer = resultSet.getBoolean("is_container"); Boolean isScatterWrapper = resultSet.getBoolean("is_scatter_wrapper"); Integer globalInputsCount = resultSet.getInt("global_inputs_count"); Integer globalOutputsCount = resultSet.getInt("global_outputs_count"); String scatterStrategy = resultSet.getString("scatter_strategy"); String dagHash = resultSet.getString("dag_hash"); LocalDateTime createdAt = resultSet.getTimestamp("created_at").toLocalDateTime(); LocalDateTime modifiedAt = resultSet.getTimestamp("modified_at").toLocalDateTime(); JobRecord jobRecord = new JobRecord(rootId, id, externalId, parentId, JobRecord.JobState.valueOf(jobState), isContainer, isScattered, externalId.equals(rootId), isBlocking, dagHash, createdAt, modifiedAt); jobRecord.setScatterWrapper(isScatterWrapper); jobRecord.setNumberOfGlobalInputs(globalInputsCount); jobRecord.setNumberOfGlobalOutputs(globalOutputsCount); jobRecord.setScatterStrategy(JSONHelper.readObject(scatterStrategy, ScatterStrategy.class)); jobRecord.setInputCounters(JSONHelper.readObject(inputCounters, new TypeReference<List<PortCounter>>() {})); jobRecord.setOutputCounters(JSONHelper.readObject(outputCounters, new TypeReference<List<PortCounter>>() {})); return jobRecord; } } }
56.595745
523
0.747932
24b47238408f136789f1912a6e8aacc0c0994184
3,429
package com.lion.materialshowcaseview; import android.graphics.Point; import android.view.View; public class ViewTarget implements Target { public enum CentreArea { LEFT_EDGE, LEFT, CENTER, RIGHT, RIGHT_EDGE } public enum RadiusCalcCategory { DEFAULT, HALF_OF_WIDTH } private final View mView; private final CentreArea mCentreArea; public ViewTarget(View view) { this(view, CentreArea.CENTER); } public ViewTarget(View view, CentreArea centreArea) { mView = view; mCentreArea = centreArea; } @Override public Point getPoint() { int[] location = new int[2]; mView.getLocationInWindow(location); // int x = location[0]; // int y = location[1]; // int width = mView.getWidth(); // int height = mView.getHeight(); // int deltaX = width/2; // // if (mView instanceof TextView && !(mView instanceof Button)) { // TextPaint paint = ((TextView) mView).getPaint(); // int textRealWidth = (int) paint.measureText(((TextView) mView).getText().toString()); // // Drawable[] drawable = ((TextView)mView).getCompoundDrawables(); // if (drawable[0] != null) { // if (!((TextView) mView).getText().toString().isEmpty()) { // deltaX = (int)(1.3*height); // } // } else { // deltaX = Math.min(textRealWidth, width) / 2; // } // } // // x += deltaX; // y += height/2; int x = location[0] + mView.getMeasuredWidth() / 2; int y = location[1] + mView.getMeasuredHeight() / 2; return new Point(x, y); } @Override public int getRadius() { int radius = 200; if (mView != null) { //radius = Math.max(mView.getMeasuredWidth(), mView.getMeasuredHeight()) / 2; int width = mView.getMeasuredWidth(); int height = mView.getMeasuredHeight(); if (width > height) { if (width > 2 * height) { radius = height; } else { radius = width / 2; } } else { if (height > 2 * width) { radius = width; } else { radius = height / 2; } } if (mView.getTag() instanceof RadiusCalcCategory) { if ((mView.getTag()) == RadiusCalcCategory.HALF_OF_WIDTH) { radius = width / 2; } } // if (mView instanceof TextView) { // Drawable[] drawable = ((TextView)mView).getCompoundDrawables(); // if (drawable[0] == null && !((TextView)mView).getText().toString().isEmpty()) { // TextPaint paint = ((TextView) mView).getPaint(); // int textRealWidth = (int) paint.measureText(((TextView) mView).getText().toString()) + 1; // if (textRealWidth < width) { // width = textRealWidth; // } // } // } // // if (width > height) { // if (width > 2 * height) { // radius = height; // scale = 1.3; // } else { // radius = width / 2; // } // } else { // if (height > 2 * width) { // radius = width; // scale = 1.3; // } else { // radius = height / 2; // } // } // // radius += 10; // add a 10 pixel padding to circle } return radius; } @Override public Point getFinalPoint(int radius) { Point point = getPoint(); int x = point.x; int[] location = new int[2]; mView.getLocationInWindow(location); if (mCentreArea == CentreArea.LEFT_EDGE) { x = location[0]; } else if (mCentreArea == CentreArea.LEFT) { x = location[0] + radius; } else if (mCentreArea == CentreArea.RIGHT) { x = location[0] + mView.getMeasuredWidth() - radius; } return new Point(x, point.y); } }
23.648276
96
0.595509
9dc55414ceea2f07d425dffa4406becb10169bdc
3,882
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * Shattered Pixel Dungeon * Copyright (C) 2014-2021 Evan Debenham * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.postmodern.postmoderndungeon.levels.rooms.standard; import com.postmodern.postmoderndungeon.levels.Level; import com.postmodern.postmoderndungeon.levels.Patch; import com.postmodern.postmoderndungeon.utils.BArray; import com.watabou.utils.PathFinder; //This room type uses the patch system to fill itself in in some manner //it's still up to the specific room to implement paint, but utility methods are provided public abstract class PatchRoom extends StandardRoom { protected boolean[] patch; protected void setupPatch(Level level, float fill, int clustering, boolean ensurePath){ int attempts = 0; if (ensurePath){ PathFinder.setMapSize(width()-2, height()-2); boolean valid; do { patch = Patch.generate(width()-2, height()-2, fill, clustering, true); int startPoint = 0; for (Door door : connected.values()) { if (door.x == left) { startPoint = xyToPatchCoords(door.x + 1, door.y); patch[xyToPatchCoords(door.x + 1, door.y)] = false; patch[xyToPatchCoords(door.x + 2, door.y)] = false; } else if (door.x == right) { startPoint = xyToPatchCoords(door.x - 1, door.y); patch[xyToPatchCoords(door.x - 1, door.y)] = false; patch[xyToPatchCoords(door.x - 2, door.y)] = false; } else if (door.y == top) { startPoint = xyToPatchCoords(door.x, door.y + 1); patch[xyToPatchCoords(door.x, door.y + 1)] = false; patch[xyToPatchCoords(door.x, door.y + 2)] = false; } else if (door.y == bottom) { startPoint = xyToPatchCoords(door.x, door.y - 1); patch[xyToPatchCoords(door.x, door.y - 1)] = false; patch[xyToPatchCoords(door.x, door.y - 2)] = false; } } PathFinder.buildDistanceMap(startPoint, BArray.not(patch, null)); valid = true; for (int i = 0; i < patch.length; i++){ if (!patch[i] && PathFinder.distance[i] == Integer.MAX_VALUE){ valid = false; break; } } attempts++; if (attempts > 100){ fill -= 0.01f; attempts = 0; } } while (!valid); PathFinder.setMapSize(level.width(), level.height()); } else { patch = Patch.generate(width()-2, height()-2, fill, clustering, true); } } //removes all diagonal-only adjacent filled patch areas, handy for making things look cleaner //note that this will reduce the fill rate very slightly protected void cleanDiagonalEdges(){ if (patch == null) return; int pWidth = width()-2; for (int i = 0; i < patch.length - pWidth; i++){ if (!patch[i]) continue; //we don't need to check above because we are either at the top // or have already dealt with those tiles //down-left if (i % pWidth != 0){ if (patch[i - 1 + pWidth] && !(patch[i - 1] || patch[i + pWidth])){ patch[i - 1 + pWidth] = false; } } //down-right if ((i + 1) % pWidth != 0){ if (patch[i + 1 + pWidth] && !(patch[i + 1] || patch[i + pWidth])){ patch[i + 1 + pWidth] = false; } } } } protected int xyToPatchCoords(int x, int y){ return (x-left-1) + ((y-top-1) * (width()-2)); } }
32.621849
94
0.647347
c9aa8cf042a433e3abad3605f0dd14bb132bbdcf
4,217
/* * 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. * * Copyright 2019-2020 the original author or authors. */ package org.quickperf.jvm.config.library; import org.quickperf.config.library.AnnotationConfig; import org.quickperf.jvm.allocation.MaxHeapAllocationPerfVerifier; import org.quickperf.jvm.allocation.MeasureHeapAllocationPerfVerifier; import org.quickperf.jvm.allocation.NoHeapAllocationPerfVerifier; import org.quickperf.jvm.allocation.bytewatcher.ByteWatcherRecorder; import org.quickperf.jvm.annotations.*; import org.quickperf.jvm.gc.EnableGcLoggingAnnotToJvmOptionConverter; import org.quickperf.jvm.gc.UseGcAnnotToJvmOptionConverter; import org.quickperf.jvm.rss.ExpectMaxRssPerfVerifier; import org.quickperf.jvm.rss.MeasureRssPerfVerifier; import org.quickperf.jvm.rss.ProcessStatusRecorder; public class JvmAnnotationsConfigs { private JvmAnnotationsConfigs() { } static final AnnotationConfig XMS = new AnnotationConfig.Builder() .testHasToBeLaunchedInASpecificJvm(XmsAnnotToJvmOptionConverter.INSTANCE) .build(Xms.class); static final AnnotationConfig XMX = new AnnotationConfig.Builder() .testHasToBeLaunchedInASpecificJvm(XmxAnnotToJvmOptionConverter.INSTANCE) .build(Xmx.class); static final AnnotationConfig HEAP_SIZE = new AnnotationConfig.Builder() .testHasToBeLaunchedInASpecificJvm(HeapSizeAnnotToJvmOptionConverter.INSTANCE) .build(HeapSize.class); static final AnnotationConfig JVM_OPTIONS = new AnnotationConfig.Builder() .testHasToBeLaunchedInASpecificJvm(JvmOptionsAnnotToJvmOptionConverter.INSTANCE) .build(JvmOptions.class); static final AnnotationConfig USE_GC = new AnnotationConfig.Builder() .testHasToBeLaunchedInASpecificJvm(UseGcAnnotToJvmOptionConverter.INSTANCE) .build(UseGC.class); static final AnnotationConfig ENABLE_GC_LOGGING = new AnnotationConfig.Builder() .testHasToBeLaunchedInASpecificJvm(EnableGcLoggingAnnotToJvmOptionConverter.INSTANCE) .build(EnableGcLogging.class); static final AnnotationConfig DISPLAY_ALLOCATION_BY_BYTE_WATCHER = new AnnotationConfig.Builder() .perfRecorderClass(ByteWatcherRecorder.class) .perfIssueVerifier(MeasureHeapAllocationPerfVerifier.INSTANCE) .testHasToBeLaunchedInASpecificJvm() .build(MeasureHeapAllocation.class); static final AnnotationConfig MAX_ALLOCATION_BY_BYTE_WATCHER = new AnnotationConfig.Builder() .perfRecorderClass(ByteWatcherRecorder.class) .perfIssueVerifier(MaxHeapAllocationPerfVerifier.INSTANCE) .testHasToBeLaunchedInASpecificJvm() .build(ExpectMaxHeapAllocation.class); static final AnnotationConfig NO_ALLOCATION_BY_BYTE_WATCHER = new AnnotationConfig.Builder() .perfRecorderClass(ByteWatcherRecorder.class) .perfIssueVerifier(NoHeapAllocationPerfVerifier.INSTANCE) .testHasToBeLaunchedInASpecificJvm() .build(ExpectNoHeapAllocation.class); static final AnnotationConfig DISPLAY_RSS_FROM_PROCESS_STATUS = new AnnotationConfig.Builder() .perfRecorderClass(ProcessStatusRecorder.class) .perfIssueVerifier(MeasureRssPerfVerifier.INSTANCE) .testHasToBeLaunchedInASpecificJvm() .build(MeasureRSS.class); static final AnnotationConfig MAX_RSS_FROM_PROCESS_STATUS = new AnnotationConfig.Builder() .perfRecorderClass(ProcessStatusRecorder.class) .perfIssueVerifier(ExpectMaxRssPerfVerifier.INSTANCE) .testHasToBeLaunchedInASpecificJvm() .build(ExpectMaxRSS.class); }
49.611765
192
0.766422
db3eb4b65264116d9dd18a5451f9bb03897ca892
297
package org.yxs.devtool.controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class DevtoolController { @GetMapping("/") String index() { return "hello spring boot"; } }
19.8
62
0.740741
30b9eef169f58fda4abee84cc1b09c3e672e0ff9
3,512
package com.vtence.molecule.http; import org.junit.Test; import static java.util.Locale.CANADA_FRENCH; import static java.util.Locale.ENGLISH; import static java.util.Locale.FRENCH; import static java.util.Locale.ITALY; import static java.util.Locale.UK; import static java.util.Locale.US; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.empty; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.nullValue; public class AcceptLanguageTest { @Test public void prefersNoLocaleWhenEmpty() { AcceptLanguage acceptLanguage = AcceptLanguage.parse(""); assertThat("no locale", acceptLanguage.list(), empty()); } @Test public void parsesNaturalLanguage() { AcceptLanguage acceptLanguage = AcceptLanguage.parse("fr"); assertThat("all locales", acceptLanguage.list(), contains(FRENCH)); } @Test public void parsesNaturalLanguageAndCountry() { AcceptLanguage acceptLanguage = AcceptLanguage.parse("fr-ca"); assertThat("all locales", acceptLanguage.list(), contains(CANADA_FRENCH)); } @Test public void listsAcceptableLocalesInPreferenceOrder() { AcceptLanguage acceptLanguage = AcceptLanguage.parse("en; q=0.8, fr-ca"); assertThat("all locales", acceptLanguage.list(), contains(CANADA_FRENCH, ENGLISH)); } @Test public void selectsNoLanguageWhenThereIsNoCandidate() { AcceptLanguage acceptLanguage = AcceptLanguage.parse("en"); assertThat("best locale", acceptLanguage.selectBest(), nullValue()); } @Test public void selectsAcceptableLanguageWithHighestQuality() { AcceptLanguage acceptLanguage = AcceptLanguage.parse("en; q=0.8, fr-ca"); assertThat("best locale", acceptLanguage.selectBest(ENGLISH, CANADA_FRENCH), equalTo(CANADA_FRENCH)); } @Test public void selectsFirstAmongstSupportedLocalesOfSameQuality() { AcceptLanguage acceptLanguage = AcceptLanguage.parse("en; q=0.8, fr-ca, it-it"); assertThat("best locale", acceptLanguage.selectBest(CANADA_FRENCH, ITALY), equalTo(CANADA_FRENCH)); } @Test public void selectsNoLocaleWhenCandidatesAreNotAcceptable() { AcceptLanguage acceptLanguage = AcceptLanguage.parse("en; q=0, fr-ca"); assertThat("best locale", acceptLanguage.selectBest(ENGLISH), nullValue()); } @Test public void fallsBackToAMoreGeneralLanguageWhenCountrySpecificLanguageNotAvailable() { AcceptLanguage acceptLanguage = AcceptLanguage.parse("en-GB"); assertThat("best locale", acceptLanguage.selectBest(US, ENGLISH), equalTo(ENGLISH)); } @Test public void usesCountrySpecificLanguageWhenGeneralLanguageNotSupported() { AcceptLanguage acceptLanguage = AcceptLanguage.parse("en"); assertThat("best locale", acceptLanguage.selectBest(FRENCH, UK), equalTo(UK)); } @Test public void usesCountrySpecificLanguageEvenWhenThereIsALowerQualityExactMatch() { AcceptLanguage acceptLanguage = AcceptLanguage.parse("fr; q=0.8, en"); assertThat("best locale", acceptLanguage.selectBest(FRENCH, UK), equalTo(UK)); } @Test public void fallbacksToAnotherCountryOfSameLanguageIfRequestedCountryIsNotAvailable() { AcceptLanguage acceptLanguage = AcceptLanguage.parse("en-GB"); assertThat("best locale", acceptLanguage.selectBest(US), equalTo(US)); } }
38.593407
109
0.72779
0965e43ffe54d02acfeec2c94d7e79c226931246
528
package daksh.userevents.storage.admins.constants; /** * Created by daksh on 22-May-16. */ public final class AdminDataConstants { public static final String MODELS_PACKAGE = "daksh.userevents.storage.admins.model"; public static final String DB_NAME = "admins"; /** * A random-but-valid ObjectId to be used as "admins" DB's collection name. */ public static final String COLLECTION_NAME = "5745e1272d9a122c1082901e"; public static final String AUTHORIZATION_TOKEN = "authorization_token"; }
29.333333
88
0.731061
c52fe3090e0c1b7dc61bbde284152dbfa239fd3e
4,243
/** * Package: MAG - VistA Imaging WARNING: Per VHA Directive 2004-038, this routine should not be modified. Date Created: Dec 01, 2007 Site Name: Washington OI Field Office, Silver Spring, MD Developer: VHAISWBUCKD Description: ;; +--------------------------------------------------------------------+ ;; Property of the US Government. ;; No permission to copy or redistribute this software is given. ;; Use of unreleased versions of this software requires the user ;; to execute a written test agreement with the VistA Imaging ;; Development Office of the Department of Veterans Affairs, ;; telephone (301) 734-0100. ;; ;; The Food and Drug Administration classifies this software as ;; a Class II medical device. As such, it may not be changed ;; in any way. Modifications to this software may result in an ;; adulterated medical device under 21CFR820, the use of which ;; is considered to be a violation of US Federal Statutes. ;; +--------------------------------------------------------------------+ */ package gov.va.med.imaging.exchange.configuration; import gov.va.med.imaging.core.interfaces.IAppConfiguration; import gov.va.med.imaging.core.interfaces.exceptions.ProcedureFilterTermsException; import java.util.ArrayList; /** * @author VHAISWBUCKD * Do not add member variables here. Instead put them in ProcedureFilterTerms. */ public class ExchangeInterfaceProcedureFilterTerms extends ProcedureFilterTerms { public final static String procedureFilterTermsFilename = "ExchangeInterfaceProcedureFilterTerms.xml"; /** * @param appConfiguration */ public ExchangeInterfaceProcedureFilterTerms(IAppConfiguration appConfiguration) { super(appConfiguration); } /** * constructor used by XMLDecoder */ public ExchangeInterfaceProcedureFilterTerms() { super(); } /** * Initialization method called by Spring. * Note that this method is not a part of the IProcedureFilterTerms interface */ public void init() throws ProcedureFilterTermsException { boolean success = false; super.init(); String filespec = this.getProcedureFilterTermFilespec(procedureFilterTermsFilename); this.setProcedureFilterTermsFilespec(filespec); if (ProcedureFilterTerms.loadFilterTermsfromFile == true) { success = this.loadProcedureFilterTermsFromFile(); } if (success == false) { this.initProcedureFilterTermsFromCode(); this.saveProcedureFilterTermsToFile(); } } /* (non-Javadoc) * @see gov.va.med.imaging.exchange.configuration.ProcedureFilterTerms#initProcedureFilterTermsFromCode() */ protected void initProcedureFilterTermsFromCode() { ArrayList<String> filterTerms = new ArrayList<String>(); filterTerms.add("CT"); filterTerms.add("RAD CT"); filterTerms.add("CR"); filterTerms.add("RAD CR"); filterTerms.add("DR"); filterTerms.add("RAD DR"); filterTerms.add("MR"); filterTerms.add("RAD MR"); filterTerms.add("US"); filterTerms.add("RAD US"); filterTerms.add("DX"); filterTerms.add("RAD DX"); filterTerms.add("RF"); filterTerms.add("RAD RF"); filterTerms.add("NM"); filterTerms.add("RAD NM"); filterTerms.add("XA"); filterTerms.add("RAD XA"); filterTerms.add("PT"); filterTerms.add("RAD PT"); filterTerms.add("DS"); filterTerms.add("RAD DS"); this.setFilterTerms(filterTerms); } /** * Used by the VIX Installer to create the procedure filter terms associated with the current VIX release and * persist to configuration file in the VixConfig directory. * @param args - no arguments at this time */ public static void main(String [] args) { ExchangeInterfaceProcedureFilterTerms terms = new ExchangeInterfaceProcedureFilterTerms(); String fileSpec = System.getenv("vixconfig"); // VIX Installer will ensure environment variable exists // add the trailing file separator character if necessary if (!fileSpec.endsWith("\\") || !fileSpec.endsWith("/")) { fileSpec += "/"; } fileSpec += procedureFilterTermsFilename; terms.procedureFilterTermsFilespec = fileSpec; terms.initProcedureFilterTermsFromCode(); terms.saveProcedureFilterTermsToFile(); } }
31.902256
110
0.698798
059c3f421a60fd135ffe1bcb63e3d0c18daec9d8
1,012
package net.mgsx.game.examples.openworld.components; import com.badlogic.ashley.core.Component; import com.badlogic.ashley.core.ComponentMapper; import net.mgsx.game.examples.openworld.model.OpenWorldElement; import net.mgsx.game.examples.openworld.systems.OpenWorldSpawnAnimalSystem.SpawnAnimalChunk; public class SpawnAnimalComponent implements Component { public static enum State{ STROLL, FLEE, IDLE, DYING // TODO, APPROACH, ATTACK, DIE } public static enum Environment{ WATER, LAND, AIR } public final static ComponentMapper<SpawnAnimalComponent> components = ComponentMapper.getFor(SpawnAnimalComponent.class); public SpawnAnimalChunk chunk; /** whether this spawn element is active (chunk entered) */ public boolean active; public OpenWorldElement element; /** current animal behavior state */ public State state; /** current animal behavior environment mode */ public Environment environment; public float pathTime; public float speed; public int directionBias; }
25.948718
123
0.790514
6b96bd072dea5e380cd5b33f481487511d4ff482
2,834
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference // Implementation, vhudson-jaxb-ri-2.1-2 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2013.04.24 at 02:09:04 PM CST // package com.fengjing.framework.webservice.springws.domain; import javax.xml.bind.JAXBElement; import javax.xml.bind.annotation.XmlElementDecl; import javax.xml.bind.annotation.XmlRegistry; import javax.xml.namespace.QName; /** * This object contains factory methods for each Java content interface and Java element interface * generated in the com.fengjing.framework.webservice.springws.domain package. * <p> * An ObjectFactory allows you to programatically construct new instances of the Java representation * for XML content. The Java representation of XML content can consist of schema derived interfaces * and classes representing the binding of schema type definitions, element declarations and model * groups. Factory methods for each of these are provided in this class. * */ @XmlRegistry public class ObjectFactory { private final static QName _StudentRequest_QNAME = new QName("http://www.example.org/student", "studentRequest"); private final static QName _StudentResponse_QNAME = new QName("http://www.example.org/student", "studentResponse"); /** * Create a new ObjectFactory that can be used to create new instances of schema derived classes * for package: com.fengjing.framework.webservice.springws.domain * */ public ObjectFactory() {} /** * Create an instance of {@link StudentRequestType } * */ public StudentRequestType createStudentRequestType() { return new StudentRequestType(); } /** * Create an instance of {@link StudentResponseType } * */ public StudentResponseType createStudentResponseType() { return new StudentResponseType(); } /** * Create an instance of {@link JAXBElement }{@code <} {@link StudentRequestType }{@code >} * */ @XmlElementDecl(namespace = "http://www.example.org/student", name = "studentRequest") public JAXBElement<StudentRequestType> createStudentRequest(StudentRequestType value) { return new JAXBElement<StudentRequestType>(_StudentRequest_QNAME, StudentRequestType.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <} {@link StudentResponseType }{@code >} * */ @XmlElementDecl(namespace = "http://www.example.org/student", name = "studentResponse") public JAXBElement<StudentResponseType> createStudentResponse(StudentResponseType value) { return new JAXBElement<StudentResponseType>(_StudentResponse_QNAME, StudentResponseType.class, null, value); } }
35.873418
100
0.739944
a5763b36535ca620f8b9f45920a762b1f8e6bc29
6,517
/* * 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.uima.ducc.ws; import java.util.Properties; import java.util.concurrent.ConcurrentHashMap; import org.apache.uima.ducc.common.boot.DuccDaemonRuntimeProperties.DaemonName; import org.apache.uima.ducc.common.utils.DuccLogger; import org.apache.uima.ducc.common.utils.TimeStamp; import org.apache.uima.ducc.transport.event.AbstractDuccEvent; import org.apache.uima.ducc.transport.event.DuccEvent.EventType; import org.apache.uima.ducc.ws.server.DuccWebProperties; public class DuccDaemonsData { private static DuccLogger duccLogger = DuccLogger.getLogger(DuccDaemonsData.class); private static DuccDaemonsData duccDaemonsData = new DuccDaemonsData(); private static ConcurrentHashMap<DaemonName,String> mapCurr = new ConcurrentHashMap<DaemonName,String>(); private static ConcurrentHashMap<DaemonName,String> mapPrev = new ConcurrentHashMap<DaemonName,String>(); private static ConcurrentHashMap<DaemonName,String> mapMax = new ConcurrentHashMap<DaemonName,String>(); private static ConcurrentHashMap<DaemonName,String> mapMaxTOD = new ConcurrentHashMap<DaemonName,String>(); private static ConcurrentHashMap<DaemonName,Long> eventSize = new ConcurrentHashMap<DaemonName,Long>(); private static ConcurrentHashMap<DaemonName,Long> eventSizeMax = new ConcurrentHashMap<DaemonName,Long>(); private static ConcurrentHashMap<DaemonName,String> eventSizeMaxTOD = new ConcurrentHashMap<DaemonName,String>(); public static DuccDaemonsData getInstance() { return duccDaemonsData; } public void put(AbstractDuccEvent duccEvent) { EventType eventType = duccEvent.getEventType(); DaemonName key; switch(eventType) { case ORCHESTRATOR_STATE: key = DaemonName.Orchestrator; putHeartbeat(key); putEventSize(key, duccEvent); break; case PM_STATE: key = DaemonName.ProcessManager; putHeartbeat(key); putEventSize(key, duccEvent); break; case RM_STATE: key = DaemonName.ResourceManager; putHeartbeat(key); putEventSize(key, duccEvent); break; case SM_STATE: case SM_HEARTBEAT: key = DaemonName.ServiceManager; putHeartbeat(key); putEventSize(key, duccEvent); break; case WEBSERVER_STATE: key = DaemonName.Webserver; putHeartbeat(key); putEventSize(key, duccEvent); break; default: break; } } public void putEventSize(DaemonName key, AbstractDuccEvent duccEvent) { Long size = duccEvent.getEventSize(); eventSize.put(key, size); Long prev; if(eventSizeMax.containsKey(key)) { prev = eventSizeMax.get(key); } else { prev = new Long(0); } if(size > prev) { eventSizeMax.put(key, size); String timestamp = TimeStamp.getCurrentMillis(); eventSizeMaxTOD.put(key, timestamp); } } public Long getEventSize(DaemonName key) { Long retVal = new Long(0); if(eventSize.containsKey(key)) { retVal = eventSize.get(key); } return retVal; } public Long getEventSizeMax(DaemonName key) { Long retVal = new Long(0); if(eventSizeMax.containsKey(key)) { retVal = eventSizeMax.get(key); } return retVal; } public String getEventSizeMaxTOD(DaemonName key) { String retVal = ""; if(mapMaxTOD.containsKey(key)) { retVal = eventSizeMaxTOD.get(key); } return retVal; } public void putHeartbeat(DaemonName key) { String timestamp = TimeStamp.getCurrentMillis(); if(mapPrev.containsKey(key)) { String t0 = mapPrev.get(key); String t1 = timestamp; long millis = TimeStamp.diffMillis(t1, t0); if(mapMax.containsKey(key)) { long max = Long.parseLong(mapMax.get(key)); if(millis > max) { mapMax.put(key, ""+millis); mapMaxTOD.put(key, t1); } } else { mapMax.put(key, ""+millis); mapMaxTOD.put(key, t1); } } if(mapCurr.containsKey(key)) { mapPrev.put(key, mapCurr.get(key)); } mapCurr.put(key, timestamp); } public String getHeartbeat(DaemonName key) { String retVal = ""; if(mapCurr.containsKey(key)) { String t1 = TimeStamp.getCurrentMillis(); String t0 = mapCurr.get(key); long millis = TimeStamp.diffMillis(t1, t0); retVal = ""+millis/1000; } return retVal; } public String getMaxHeartbeat(DaemonName key) { String retVal = ""; if(mapMax.containsKey(key)) { long max = Long.parseLong(mapMax.get(key)); retVal = ""+(max/1000); } return retVal; } public String getMaxHeartbeatTOD(DaemonName key) { String retVal = ""; if(mapMaxTOD.containsKey(key)) { retVal = mapMaxTOD.get(key); } return retVal; } /** * @return number of millis since last receipt of self publication */ private long getWsTod() { long retVal = Long.MAX_VALUE; DaemonName key = DaemonName.Webserver; if(mapCurr.containsKey(key)) { String t1 = TimeStamp.getCurrentMillis(); String t0 = mapCurr.get(key); long millis = TimeStamp.diffMillis(t1, t0); retVal = millis; } return retVal; } /** * @return number of millis after which webserver publication is considered late */ private long getMillisMIA() { String methodName = "getMillisMIA"; long secondsMIA = -1; Properties properties = DuccWebProperties.get(); String ws_rate = properties.getProperty("ducc.ws.state.publish.rate"); String ws_ratio = "1"; try { long rate = Long.parseLong(ws_rate.trim()); long ratio = Long.parseLong(ws_ratio .trim()); secondsMIA = 3 * rate * ratio; } catch(Throwable t) { duccLogger.debug(methodName, null, t); } return secondsMIA; } /** * * @return true if webserver self publications are on time, false otherwise */ public boolean isWsPublicationOntime() { boolean retVal = true; long expiry = getMillisMIA(); if(getWsTod() > expiry) { retVal = false; } return retVal; } }
28.964444
114
0.719963