text
stringlengths
7
1.01M
package com.ateam.paw_pals.model.entity; import javax.persistence.*; import com.ateam.paw_pals.model.SecurityRoleName; import lombok.Getter; import lombok.Setter; @Getter @Setter @Entity(name = "security_role") public class RoleEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Enumerated(EnumType.STRING) @Column(nullable = false, length = 256) private SecurityRoleName name; }
package com.apicatalog.jsonld.suite; import java.net.URI; import java.util.HashSet; import java.util.Set; import java.util.stream.Collectors; import javax.json.JsonObject; import javax.json.JsonString; import javax.json.JsonValue; import com.apicatalog.jsonld.api.JsonLdErrorCode; import com.apicatalog.jsonld.api.JsonLdOptions; import com.apicatalog.jsonld.http.media.MediaType; import com.apicatalog.jsonld.json.JsonUtils; import com.apicatalog.jsonld.lang.Keywords; import com.apicatalog.jsonld.loader.LoadDocumentCallback; import com.apicatalog.jsonld.suite.loader.UriRewriter; import com.apicatalog.jsonld.suite.loader.ZipResourceLoader; public final class JsonLdTestCase { public String id; public String name; public URI input; public URI context; public URI expect; public URI frame; public JsonLdErrorCode expectErrorCode; public String baseUri; public String uri; public Set<String> type; public JsonLdTestCaseOptions options; public MediaType contentType; public URI redirectTo; public Integer httpStatus; public Set<String> httpLink; private final String testsBase; public JsonLdTestCase(final String testsBase) { this.testsBase = testsBase; } public static final JsonLdTestCase of(JsonObject o, String manifestUri, String manifestBase, String baseUri) { final JsonLdTestCase testCase = new JsonLdTestCase(manifestBase); testCase.id = o.getString(Keywords.ID); testCase.uri = baseUri + manifestUri.substring(0, manifestUri.length() - ".jsonld".length()) + testCase.id; testCase.type = o.get(Keywords.TYPE).asJsonArray().stream() .map(JsonString.class::cast) .map(JsonString::getString) .collect(Collectors.toSet()); testCase.name = o.getString("name"); testCase.input = o.containsKey("input") ? URI.create(baseUri + o.getString("input")) : null; testCase.context = o.containsKey("context") ? URI.create(baseUri + o.getString("context")) : null; testCase.expect = o.containsKey("expect") ? URI.create(baseUri + o.getString("expect")) : null; testCase.frame = o.containsKey("frame") ? URI.create(baseUri + o.getString("frame")) : null; testCase.expectErrorCode = o.containsKey("expectErrorCode") ? errorCode((o.getString("expectErrorCode"))) : null; testCase.options = o.containsKey("option") ? JsonLdTestCaseOptions.of(o.getJsonObject("option"), baseUri) : new JsonLdTestCaseOptions(); testCase.baseUri = baseUri; testCase.contentType = o.containsKey("option") && o.getJsonObject("option").containsKey("contentType") ? MediaType.of(o.getJsonObject("option").getString("contentType")) : null; if (testCase.contentType == null && testCase.input != null) { if (testCase.input.toString().endsWith(".jsonld")) { testCase.contentType = MediaType.JSON_LD; } else if (testCase.input.toString().endsWith(".json")) { testCase.contentType = MediaType.JSON; } else if (testCase.input.toString().endsWith(".html")) { testCase.contentType = MediaType.HTML; } } testCase.redirectTo = o.containsKey("option") && o.getJsonObject("option").containsKey("redirectTo") ? URI.create(baseUri + o.getJsonObject("option").getString("redirectTo")) : null; testCase.httpStatus = o.containsKey("option") ? o.getJsonObject("option").getInt("httpStatus", 301) : null ; if (o.containsKey("option") && o.getJsonObject("option").containsKey("httpLink")) { JsonValue links = o.getJsonObject("option").get("httpLink"); if (JsonUtils.isArray(links)) { testCase.httpLink = links.asJsonArray().stream() .map(JsonString.class::cast) .map(JsonString::getString) .collect(Collectors.toSet()); } else { testCase.httpLink = new HashSet<>(); testCase.httpLink.add(((JsonString)links).getString()); } } return testCase; } public JsonLdOptions getOptions() { final LoadDocumentCallback loader = new UriRewriter( baseUri, testsBase, new ZipResourceLoader(true) ); JsonLdOptions jsonLdOptions = new JsonLdOptions(); jsonLdOptions.setOrdered(true); jsonLdOptions.setDocumentLoader(loader); options.setup(jsonLdOptions); return jsonLdOptions; } public static final JsonLdErrorCode errorCode(String errorCode) { if (errorCode == null || errorCode.isBlank()) { return null; } /* * Because scoped contexts can lead to contexts being reloaded, * replace the recursive context inclusion error with a context overflow error. * * @see <a href="https://www.w3.org/TR/json-ld11-api/#changes-from-cg">Changes since JSON-LD Community Group Final Report</a> */ if ("recursive context inclusion".equalsIgnoreCase(errorCode)) { return JsonLdErrorCode.CONTEXT_OVERFLOW; } if ("list of lists".equalsIgnoreCase(errorCode)) { return JsonLdErrorCode.UNSPECIFIED; } if ("compaction to list of lists".equalsIgnoreCase(errorCode)) { return JsonLdErrorCode.UNSPECIFIED; } return JsonLdErrorCode.valueOf(errorCode.strip().toUpperCase().replace(" ", "_").replace("-", "_").replaceAll("\\_\\@", "_KEYWORD_" )); } }
package com.capitalone.dashboard.repository; import com.capitalone.dashboard.model.Build; import com.capitalone.dashboard.model.GenericCollectorItem; import org.bson.types.ObjectId; import org.springframework.data.querydsl.QueryDslPredicateExecutor; import org.springframework.data.repository.CrudRepository; import java.util.List; /** * Repository for {@link Build} data. */ public interface GenericCollectorItemRepository extends CrudRepository<GenericCollectorItem, ObjectId>, QueryDslPredicateExecutor<GenericCollectorItem> { List<GenericCollectorItem> findAllByToolName(String toolName); List<GenericCollectorItem> findAllByRelatedCollectorItem (ObjectId relatedCollectorItemId); GenericCollectorItem findByToolNameAndRawDataAndRelatedCollectorItem(String toolName, String rawData, ObjectId relatedCollectorItem); List<GenericCollectorItem> findAllByToolNameAndProcessTimeEquals(String toolName, long processTime); }
package net.sf.esfinge.metadata.locate.conventions.mapping; import net.sf.esfinge.metadata.annotation.container.ContainerFor; import net.sf.esfinge.metadata.annotation.container.ContainsAnnotation; import net.sf.esfinge.metadata.container.ContainerTarget; import net.sf.esfinge.metadata.locate.conventions.annotations.PrefixConvention; @ContainerFor(ContainerTarget.TYPE) public class ContainerClass { @ContainsAnnotation(PrefixConvention.class) private boolean secure; public boolean isSecure() { return secure; } public void setSecure(boolean secure) { this.secure = secure; } }
package no.ntnu; import org.springframework.data.repository.CrudRepository; import java.util.List; /** * Repository interface for accessing Book data in the database. * Spring will auto-generate necessary methods. */ public interface BookRepository extends CrudRepository<Book, Integer> { List<Book> findByGenreNameContainingIgnoreCase(String genre); List<Book> findByAuthorsFirstNameContainingIgnoreCase(String author); List<Book> findByAuthorsFirstNameContainingIgnoreCaseAndGenreNameContainingIgnoreCase(String author, String genre); }
package JavaCode.random_records.N1301_1400; /** * author:fangjie * time:2020/3/17 */ public class N1381_design_a_stack_with_increment_operation { class CustomStack { private int size; private final int maxSize; private Node head; private Node tail; public CustomStack(int maxSize) { this.maxSize=maxSize; this.size=0; this.head=new Node(-1); this.tail=new Node(-1); head.next=tail; tail.pre=head; } public void push(int x) { if(size==maxSize)return; Node node=new Node(x); node.pre=tail.pre; node.next=tail; node.pre.next=node; tail.pre=node; size++; } public int pop() { if(tail.pre==head)return -1; Node node=tail.pre; node.pre.next=tail; tail.pre=node.pre; size--; return node.val; } public void increment(int k, int val) { Node cur=head.next; while (cur!=null&&k-->0) { cur.add(val); cur=cur.next; } } private class Node { Node pre,next; int val; public Node(int val) { this.val=val; } public void add(int num) { this.val+=num; } } } /* * Your CustomStack object will be instantiated and called as such: * CustomStack obj = new CustomStack(maxSize); * obj.push(x); * int param_2 = obj.pop(); * obj.increment(k,val); */ } /* 请你设计一个支持下述操作的栈。 实现自定义栈类 CustomStack : CustomStack(int maxSize):用 maxSize 初始化对象,maxSize 是栈中最多能容纳的元素数量,栈在增长到 maxSize 之后则不支持 push 操作。 void push(int x):如果栈还未增长到 maxSize ,就将 x 添加到栈顶。 int pop():返回栈顶的值,或栈为空时返回 -1 。 void inc(int k, int val):栈底的 k 个元素的值都增加 val 。如果栈中元素总数小于 k ,则栈中的所有元素都增加 val 。   示例: 输入: ["CustomStack","push","push","pop","push","push","push","increment","increment","pop","pop","pop","pop"] [[3],[1],[2],[],[2],[3],[4],[5,100],[2,100],[],[],[],[]] 输出: [null,null,null,2,null,null,null,null,null,103,202,201,-1] 解释: CustomStack customStack = new CustomStack(3); // 栈是空的 [] customStack.push(1); // 栈变为 [1] customStack.push(2); // 栈变为 [1, 2] customStack.pop(); // 返回 2 --> 返回栈顶值 2,栈变为 [1] customStack.push(2); // 栈变为 [1, 2] customStack.push(3); // 栈变为 [1, 2, 3] customStack.push(4); // 栈仍然是 [1, 2, 3],不能添加其他元素使栈大小变为 4 customStack.increment(5, 100); // 栈变为 [101, 102, 103] customStack.increment(2, 100); // 栈变为 [201, 202, 103] customStack.pop(); // 返回 103 --> 返回栈顶值 103,栈变为 [201, 202] customStack.pop(); // 返回 202 --> 返回栈顶值 202,栈变为 [201] customStack.pop(); // 返回 201 --> 返回栈顶值 201,栈变为 [] customStack.pop(); // 返回 -1 --> 栈为空,返回 -1   提示: 1 <= maxSize <= 1000 1 <= x <= 1000 1 <= k <= 1000 0 <= val <= 100 每种方法 increment,push 以及 pop 分别最多调用 1000 次 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/design-a-stack-with-increment-operation 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 */
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is * regenerated. */ package fixtures.bodycomplex.models; import com.fasterxml.jackson.annotation.JsonProperty; /** * The Error model. */ public class Error { /** * The status property. */ @JsonProperty(value = "status") private Integer status; /** * The message property. */ @JsonProperty(value = "message") private String message; /** * Get the status value. * * @return the status value */ public Integer status() { return this.status; } /** * Set the status value. * * @param status the status value to set * @return the Error object itself. */ public Error withStatus(Integer status) { this.status = status; return this; } /** * Get the message value. * * @return the message value */ public String message() { return this.message; } /** * Set the message value. * * @param message the message value to set * @return the Error object itself. */ public Error withMessage(String message) { this.message = message; return this; } }
package com.onlinepayments.client.android.exampleapp.view; import android.view.View; /** * ViewInterface that depicts a contract all views should follow * * Copyright 2020 Global Collect Services B.V */ public interface GeneralView { View getRootView(); }
package uam.mx.ayd.proyecto.presentacion; import javax.swing.JOptionPane; import uam.mx.ayd.proyecto.Aplicacion; import uam.mx.ayd.proyecto.negocio.ControlCatalogo; /** * * @author Omar JRZ */ public class VentanaAltaModelo extends javax.swing.JFrame { private ControlCatalogo controlC; private Aplicacion app; /** * Creates new form VentanaAltaModelo */ public VentanaAltaModelo(ControlCatalogo controlC) { this.controlC = controlC; initComponents(); setLocationRelativeTo(null); setTitle("Alta de Modelo"); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { btn_Aceptar = new javax.swing.JButton(); btn_Regresar = new javax.swing.JButton(); jPanel1 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); txt_Id = new javax.swing.JTextField(); jLabel2 = new javax.swing.JLabel(); txt_Descripcion = new javax.swing.JTextField(); jLabel3 = new javax.swing.JLabel(); txt_Precio = new javax.swing.JTextField(); jLabel4 = new javax.swing.JLabel(); txt_Color = new javax.swing.JTextField(); jLabel5 = new javax.swing.JLabel(); txt_Talla = new javax.swing.JTextField(); jLabel6 = new javax.swing.JLabel(); txt_Piezas = new javax.swing.JTextField(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); btn_Aceptar.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N btn_Aceptar.setText("Aceptar"); btn_Aceptar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btn_AceptarActionPerformed(evt); } }); btn_Regresar.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N btn_Regresar.setText("Regresar"); btn_Regresar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btn_RegresarActionPerformed(evt); } }); jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder()); jLabel1.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel1.setText("Id Modelo: "); jLabel2.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel2.setText("Descripcion: "); jLabel3.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel3.setText("Precio: "); jLabel4.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel4.setText("Color: "); jLabel5.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel5.setText("Talla: "); jLabel6.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel6.setText("Número de piezas: "); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel6) .addGap(18, 18, 18) .addComponent(txt_Piezas, javax.swing.GroupLayout.PREFERRED_SIZE, 237, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(48, 48, 48) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel3) .addComponent(jLabel5) .addComponent(jLabel4) .addComponent(jLabel2) .addComponent(jLabel1)) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(txt_Descripcion, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 237, Short.MAX_VALUE) .addComponent(txt_Precio, javax.swing.GroupLayout.Alignment.LEADING) .addComponent(txt_Color) .addComponent(txt_Talla) .addComponent(txt_Id)))) .addContainerGap(27, Short.MAX_VALUE)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(20, 20, 20) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(txt_Id, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(txt_Descripcion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(21, 21, 21) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel3) .addComponent(txt_Precio, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(21, 21, 21) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel4) .addComponent(txt_Color, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(21, 21, 21) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel5) .addComponent(txt_Talla, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(21, 21, 21) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel6) .addComponent(txt_Piezas, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(34, Short.MAX_VALUE)) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addGap(94, 94, 94) .addComponent(btn_Aceptar) .addGap(58, 58, 58) .addComponent(btn_Regresar))) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(40, 40, 40) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btn_Aceptar) .addComponent(btn_Regresar)) .addContainerGap(28, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void btn_AceptarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_AceptarActionPerformed if(txt_Id.getText().isEmpty() || txt_Descripcion.getText().isEmpty() || txt_Precio.getText().isEmpty() || txt_Color.getText().isEmpty() || txt_Talla.getText().isEmpty() || txt_Piezas.getText().isEmpty()){ JOptionPane.showMessageDialog(null, "Es necesario llenar todos los campos"); } try{ int id = Integer.parseInt(txt_Id.getText()); String descripcion = txt_Descripcion.getText(); double precio = Double.parseDouble(txt_Precio.getText()); String color = txt_Color.getText(); String talla = txt_Talla.getText(); int piezas = Integer.parseInt(txt_Piezas.getText()); String regla = ""; if(precio <= 0) JOptionPane.showMessageDialog(null, "Verifico el precio"); if(piezas <= 0) JOptionPane.showMessageDialog(null, "Verifique el número de piezas"); controlC.altaModelo(id, descripcion, precio, color, talla, piezas, regla); } catch(NumberFormatException E){ JOptionPane.showMessageDialog(null, "Verifique el precio o el número de piezas"); } controlC.ventanaAdministrarC(); setVisible(false); }//GEN-LAST:event_btn_AceptarActionPerformed private void btn_RegresarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_RegresarActionPerformed txt_Id.setText(""); txt_Descripcion.setText(""); txt_Precio.setText(""); txt_Color.setText(""); txt_Talla.setText(""); txt_Piezas.setText(""); this.setVisible(false); controlC.ventanaAdministrarC(); }//GEN-LAST:event_btn_RegresarActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(VentanaAltaModelo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(VentanaAltaModelo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(VentanaAltaModelo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(VentanaAltaModelo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btn_Aceptar; private javax.swing.JButton btn_Regresar; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JPanel jPanel1; private javax.swing.JTextField txt_Color; private javax.swing.JTextField txt_Descripcion; private javax.swing.JTextField txt_Id; private javax.swing.JTextField txt_Piezas; private javax.swing.JTextField txt_Precio; private javax.swing.JTextField txt_Talla; // End of variables declaration//GEN-END:variables }
package com.perosa.bot.traffic.core.common; import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static org.junit.jupiter.api.Assertions.*; public class EnvConfigurationTest { private static final Logger LOGGER = LoggerFactory.getLogger(EnvConfigurationTest.class); @Test void getPort() { assertEquals(8886, new EnvConfiguration().getPort()); } @Test void getHome() { assertEquals("src/test/resources/", new EnvConfiguration().getHome()); } }
package je.techtribes.component.activity; import je.techtribes.AbstractComponentTestsBase; import je.techtribes.domain.Activity; import je.techtribes.domain.ContentSource; import je.techtribes.domain.Person; import je.techtribes.domain.Tribe; import je.techtribes.util.DateUtils; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.springframework.jdbc.core.JdbcTemplate; import java.text.SimpleDateFormat; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.TimeZone; import static org.junit.Assert.assertEquals; public class ActivityComponentTests extends AbstractComponentTestsBase { private SimpleDateFormat dateTimeFormat; @Before public void setUp() { JdbcTemplate template = getJdbcTemplate(); dateTimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); dateTimeFormat.setTimeZone(TimeZone.getTimeZone(DateUtils.UTC_TIME_ZONE)); // activity records for today for (ContentSource contentSource : getContentSourceComponent().getPeopleAndTribes()) { int id = contentSource.getId(); template.update("insert into activity (content_source_id, international_talks, local_talks, content, tweets, events, last_activity_datetime, activity_datetime) values (?, ?, ?, ?, ?, ?, ?, ?)", id, contentSource.isPerson() ? id * 1 : 0, contentSource.isPerson() ? id * 2 : 0, id * 3, id * 4, contentSource.isTribe() ? id * 5 : 0, dateTimeFormat.format(DateUtils.getDate(2013, 7, 1, 12+id, 0)), dateTimeFormat.format(DateUtils.getToday()) ); } // and also some for yesterday (these will be ignored) for (ContentSource contentSource : getContentSourceComponent().getPeopleAndTribes()) { template.update("insert into activity (content_source_id, international_talks, local_talks, content, tweets, events, last_activity_datetime, activity_datetime) values (?, ?, ?, ?, ?, ?, ?, ?)", contentSource.getId(), 0, 0, 0, 0, 0, dateTimeFormat.format(DateUtils.getDate(2013, 7, 1, 9, 0)), dateTimeFormat.format(DateUtils.getXDaysAgo(1)) ); } } @Test public void test_getRecentActivity_ReturnsTheMostRecentActivityRecords() { getActivityComponent().refreshRecentActivity(); List<Activity> activityListForPeople = getActivityComponent().getActivityListForPeople(); assertEquals(2, activityListForPeople.size()); assertEquals("Chris Clark", activityListForPeople.get(0).getContentSource().getName()); assertEquals("Simon Brown", activityListForPeople.get(1).getContentSource().getName()); List<Activity> activityListForBusinessTribes = getActivityComponent().getActivityListForBusinessTribes(); assertEquals(1, activityListForBusinessTribes.size()); assertEquals("Prosperity 24.7", activityListForBusinessTribes.get(0).getContentSource().getName()); List<Activity> activityListForCommunityTribes = getActivityComponent().getActivityListForCommunityTribes(); assertEquals(1, activityListForCommunityTribes.size()); assertEquals("techtribes.je", activityListForCommunityTribes.get(0).getContentSource().getName()); } @Test public void test_getActivityForContentSource_ReturnsTheCorrectInformationFromTheDatabase() { ContentSource contentSource = getContentSourceComponent().findByShortName("chrisclark"); int id = contentSource.getId(); getActivityComponent().refreshRecentActivity(); Activity activity = getActivityComponent().getActivity(contentSource); assertEquals("Chris Clark", activity.getContentSource().getName()); assertEquals(id*1, activity.getNumberOfInternationalTalks()); assertEquals(id*2, activity.getNumberOfLocalTalks()); assertEquals(id*3, activity.getNumberOfNewsFeedEntries()); assertEquals(id*4, activity.getNumberOfTweets()); assertEquals(0, activity.getNumberOfEvents()); assertEquals("2013-07-01 13:00:00", dateTimeFormat.format(activity.getLastActivityDate())); // UTC date } @Test public void test_getActivityForContentSource_ReturnsAggregatedActivity_WhenThereAreMembersOfATribe() { Person chrisclark = (Person)getContentSourceComponent().findByShortName("chrisclark"); Tribe p247 = (Tribe)getContentSourceComponent().findByShortName("prosperity247"); getActivityComponent().refreshRecentActivity(); Activity activityForChrisClark = getActivityComponent().getActivity(chrisclark); assertEquals(2, activityForChrisClark.getNumberOfInternationalTalks()); assertEquals(4, activityForChrisClark.getNumberOfLocalTalks()); assertEquals(6, activityForChrisClark.getNumberOfNewsFeedEntries()); assertEquals(8, activityForChrisClark.getNumberOfTweets()); assertEquals(0, activityForChrisClark.getNumberOfEvents()); Activity activityForP247 = getActivityComponent().getActivity(p247); assertEquals(0, activityForP247.getNumberOfInternationalTalks()); assertEquals(0, activityForP247.getNumberOfLocalTalks()); assertEquals(9, activityForP247.getNumberOfNewsFeedEntries()); assertEquals(12, activityForP247.getNumberOfTweets()); assertEquals(15, activityForP247.getNumberOfEvents()); Set<Integer> personIds = new HashSet<>(); personIds.add(chrisclark.getId()); getContentSourceComponent().updateTribeMembers(p247, personIds); getActivityComponent().refreshRecentActivity(); activityForChrisClark = getActivityComponent().getActivity(chrisclark); assertEquals(2, activityForChrisClark.getNumberOfInternationalTalks()); assertEquals(4, activityForChrisClark.getNumberOfLocalTalks()); assertEquals(6, activityForChrisClark.getNumberOfNewsFeedEntries()); assertEquals(8, activityForChrisClark.getNumberOfTweets()); assertEquals(0, activityForChrisClark.getNumberOfEvents()); activityForP247 = getActivityComponent().getActivity(p247); assertEquals(0, activityForP247.getNumberOfInternationalTalks()); assertEquals(0, activityForP247.getNumberOfLocalTalks()); assertEquals(9, activityForP247.getNumberOfNewsFeedEntries()); assertEquals(12, activityForP247.getNumberOfTweets()); assertEquals(15, activityForP247.getNumberOfEvents()); } @After public void tearDown() { JdbcTemplate template = getJdbcTemplate(); template.execute("delete from activity"); } }
package com.lanking.uxb.zycon.book.api; import java.util.List; import com.lanking.cloud.domain.common.baseData.School; import com.lanking.cloud.domain.common.resource.book.BookVersion; import com.lanking.cloud.domain.yoomath.school.UserSchoolBook; import com.lanking.cloud.sdk.bean.Status; import com.lanking.cloud.sdk.data.Page; import com.lanking.cloud.sdk.data.Pageable; import com.lanking.uxb.zycon.book.form.BookForm; /** * 书本管理接口 * * @author wangsenhao * */ public interface ZycBookManageService { /** * 书本查询 * * @param bq * @return */ Page<BookVersion> queryBook(BookQuery bq); /** * 获取开通了校本题库的学校(不翻页) * * @return */ Page<School> getQuestionSchoolList(Long bookId, Pageable p); /** * 获取开通了校本题库的学校(不翻页) * * @param bookId * @return */ List<School> getQuestionSchoolList(Long bookId); /** * 书本状态设置 * * @param bookForm * 页面返回的值 */ void updateBookStatus(BookForm bookForm); /** * 通过学校获取书本 * * @param schoolId * @param phaseCode * @return */ Page<BookVersion> getBookBySchool(Long schoolId, Integer phaseCode, Pageable p); /** * 根据书本ID 获取 选择该书本的用户的记录列表 * * @param bookId * 书本ID * @return userschoolBookList */ List<UserSchoolBook> getUserSchoolBookByBookId(long bookId); /** * 根据ID 更改userschoolBook 状态 * * @param ids * useschoolbook IDs * @param status * 状态 */ void updateUserSchoolBookStatus(List<Long> ids, Status status); }
package com.xiaoxin.guid.activity; import android.content.Intent; import android.os.Bundle; import androidx.annotation.Nullable; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.view.View; import android.widget.Button; import android.widget.TextView; import com.chad.library.adapter.base.BaseQuickAdapter; import com.xiaoxin.guid.Api; import com.xiaoxin.guid.GsonUtils; import com.xiaoxin.guid.HttpGet; import com.xiaoxin.guid.R; import com.xiaoxin.guid.adapter.FollowZzAdapter; import com.xiaoxin.guid.base.BaseActivity; import com.xiaoxin.guid.bean.BwBean; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @author: xiaoxin * date: 2018/10/10 * describe:第三步:伴随症状 * 修改内容: */ public class FollowZzActivity extends BaseActivity { private RecyclerView mRvFollowZz; private FollowZzAdapter mFollowZzAdapter; private List<BwBean.DataBean> mKsdmListBeans; private BwBean.DataBean mBean; int mSymptomCourseId; private String mSex; private Button mBtSure; private Map<Integer,String> symptomIds; private void initAdapter() { mKsdmListBeans = new ArrayList<>(); mFollowZzAdapter = new FollowZzAdapter(R.layout.item_followzz,mKsdmListBeans,this); mRvFollowZz.setLayoutManager(new LinearLayoutManager(this)); mRvFollowZz.setAdapter(mFollowZzAdapter); mFollowZzAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() { @Override public void onItemClick(BaseQuickAdapter adapter, View view, int position) { BwBean.DataBean bean = (BwBean.DataBean)adapter.getData().get(position); if (bean.status) { symptomIds.remove(bean.id); }else { symptomIds.put(bean.id,bean.id+","); } bean.status = !bean.status; mFollowZzAdapter.notifyItemChanged(position); } }); mBtSure.setOnClickListener(v -> { StringBuilder ids = new StringBuilder(); for (Map.Entry<Integer, String> m : symptomIds.entrySet()) { ids.append(m.getValue()); } Intent intent = new Intent(FollowZzActivity.this,ResultActivity.class); intent.putExtra("symptomIds",ids.toString()); intent.putExtra("sex",mSex); intent.putExtra("symptomCourseId",mSymptomCourseId); startActivity(intent); }); } /** * 请求对应部位症状列表的具体一项病症 */ private void loadBz() { new Thread(() -> { Map<String,String> map = new HashMap<>(); map.put("sex",mSex); map.put("symptomCourseId",mBean.symptomCourseId+""); runOnUI(HttpGet.get(Api.THREE, map)); }).start(); } /** * 更新ui * @param result */ private void runOnUI(String result) { runOnUiThread(() ->{ BwBean bwBean = GsonUtils.GsonToBean(result, BwBean.class); mFollowZzAdapter.setNewData(bwBean.getData()); }); } @Override public void initData(@Nullable Bundle bundle) { mSex = getIntent().getStringExtra("sex"); mBean = (BwBean.DataBean)getIntent().getSerializableExtra("bean"); } @Override public int bindLayout() { return R.layout.activity_follow_zz; } @Override public void initView(Bundle savedInstanceState, View contentView) { TextView title = findViewById(R.id.tv_title_name); title.setText("伴随症状"); title.setOnClickListener(v -> { finish(); }); mRvFollowZz = findViewById(R.id.rv_follow_zz); mBtSure = findViewById(R.id.bt_sure); } @Override public void doBusiness() { mSymptomCourseId = mBean.symptomCourseId; symptomIds = new HashMap<>(); initAdapter(); loadBz(); } }
package org.broadinstitute.hellbender.tools.spark.pipelines.metrics; import org.broadinstitute.hellbender.CommandLineProgramTest; import org.broadinstitute.hellbender.cmdline.StandardArgumentDefinitions; import org.broadinstitute.hellbender.engine.filters.ReadFilterLibrary; import org.broadinstitute.hellbender.metrics.MetricAccumulationLevel; import org.broadinstitute.hellbender.testutils.ArgumentsBuilder; import org.broadinstitute.hellbender.GATKBaseTest; import org.broadinstitute.hellbender.testutils.IntegrationTestSpec; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import java.io.*; /** * Integration tests for {@link CollectInsertSizeMetricsSpark}. */ public final class CollectInsertSizeMetricsSparkIntegrationTest extends CommandLineProgramTest { private static final File TEST_DATA_DIR = new File( "src/test/resources/org/broadinstitute/hellbender/metrics/analysis/CollectInsertSizeMetrics"); @Override public String getTestedClassName() { return CollectInsertSizeMetricsSpark.class.getSimpleName(); } @DataProvider(name="metricsInputFiles") public Object[][] insertSizeMetricsInputFiles() { return new Object[][] { // single level collection {"insert_size_metrics_test.sam", null, false, "expectedInsertSizeMetricsL1.txt"}, {"insert_size_metrics_test.bam", null, false, "expectedInsertSizeMetricsL1.txt"}, {"insert_size_metrics_test.cram", hg19_chr1_1M_Reference, false, "expectedInsertSizeMetricsL1.txt"}, // collect for all levels {"insert_size_metrics_test.sam", null, true, "expectedInsertSizeMetricsL3.txt"}, {"insert_size_metrics_test.bam", null, true, "expectedInsertSizeMetricsL3.txt"}, {"insert_size_metrics_test.cram", hg19_chr1_1M_Reference, true, "expectedInsertSizeMetricsL3.txt"} }; } //NOTE: These tests run on small files in a test environment, so only a single partition is // used, and the collector's combine/reduce code is never executed. In order to test that, // these same tests are included in in InsertSizeMetricsCollectorSparkUnitTest, using the // InsertSizeMetricsCollectorSpark object directly, where a repartition on the RDD is used to // force the code to run on more than one partition and execute the combine/reduce code. @Test(dataProvider="metricsInputFiles", groups = {"R", "spark"}) public void test( final String fileName, final String referenceName, final boolean allLevels, // collect metrics for each possible level final String expectedResultsFile) throws IOException { // set up test data input and result outputs (two: one text one histogram plot in pdf) final File input = new File(TEST_DATA_DIR, fileName); final File textOut = GATKBaseTest.createTempFile("test", ".txt"); final File pdfOut = GATKBaseTest.createTempFile("test", ".pdf"); final ArgumentsBuilder args = new ArgumentsBuilder(); // IO arguments args.addRaw("-" + StandardArgumentDefinitions.INPUT_SHORT_NAME); args.addRaw(input.getAbsolutePath()); args.addRaw("-" + StandardArgumentDefinitions.OUTPUT_SHORT_NAME); args.addRaw(textOut.getAbsolutePath()); args.addRaw("--produce-plot"); args.addRaw("-" + "histogram-plot-file"); args.addRaw(pdfOut.getAbsolutePath()); if (null != referenceName) { final File REF = new File(referenceName); args.addRaw("-" + StandardArgumentDefinitions.REFERENCE_SHORT_NAME); args.addRaw(REF.getAbsolutePath()); } // some filter options args.addRaw("-DF"); args.addRaw(ReadFilterLibrary.FirstOfPairReadFilter.class.getSimpleName()); args.addRaw("-RF"); args.addRaw(ReadFilterLibrary.SecondOfPairReadFilter.class.getSimpleName()); if (allLevels) { // accumulation level options (all included for better test coverage) args.addRaw("-" + "LEVEL"); args.addRaw(MetricAccumulationLevel.ALL_READS.toString()); args.addRaw("-" + "LEVEL"); args.addRaw(MetricAccumulationLevel.SAMPLE.toString()); args.addRaw("-" + "LEVEL"); args.addRaw(MetricAccumulationLevel.LIBRARY.toString()); args.addRaw("-" + "LEVEL"); args.addRaw(MetricAccumulationLevel.READ_GROUP.toString()); } this.runCommandLine(args.getArgsArray()); IntegrationTestSpec.assertEqualTextFiles( textOut, new File(TEST_DATA_DIR, expectedResultsFile), "#" ); } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.ignite.internal.processors.cache; import javax.cache.configuration.Factory; import org.apache.ignite.cache.store.CacheStore; /** * */ public class IgniteCacheAtomicPrimaryWriteOrderWithStoreInvokeTest extends IgniteCacheAtomicPrimaryWriteOrderInvokeTest { /** {@inheritDoc} */ @Override protected Factory<CacheStore> cacheStoreFactory() { return new TestStoreFactory(); } }
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.prestosql.plugin.atop; import io.prestosql.spi.Node; import io.prestosql.spi.NodeManager; import io.prestosql.spi.connector.ConnectorSession; import io.prestosql.spi.connector.ConnectorSplit; import io.prestosql.spi.connector.ConnectorSplitManager; import io.prestosql.spi.connector.ConnectorSplitSource; import io.prestosql.spi.connector.ConnectorTableHandle; import io.prestosql.spi.connector.ConnectorTransactionHandle; import io.prestosql.spi.connector.DynamicFilter; import io.prestosql.spi.connector.FixedSplitSource; import io.prestosql.spi.predicate.Domain; import io.prestosql.spi.predicate.Range; import io.prestosql.spi.predicate.ValueSet; import javax.inject.Inject; import java.time.ZoneId; import java.time.ZonedDateTime; import java.util.ArrayList; import java.util.List; import static io.prestosql.spi.type.DateTimeEncoding.packDateTimeWithZone; import static io.prestosql.spi.type.TimeZoneKey.UTC_KEY; import static io.prestosql.spi.type.TimestampWithTimeZoneType.TIMESTAMP_TZ_MILLIS; import static java.util.Objects.requireNonNull; public class AtopSplitManager implements ConnectorSplitManager { private final NodeManager nodeManager; private final ZoneId timeZone; private final int maxHistoryDays; @Inject public AtopSplitManager(NodeManager nodeManager, AtopConnectorConfig config) { this.nodeManager = requireNonNull(nodeManager, "nodeManager is null"); requireNonNull(config, "config is null"); timeZone = config.getTimeZoneId(); maxHistoryDays = config.getMaxHistoryDays(); } @Override public ConnectorSplitSource getSplits( ConnectorTransactionHandle transaction, ConnectorSession session, ConnectorTableHandle table, SplitSchedulingStrategy splitSchedulingStrategy, DynamicFilter dynamicFilter) { AtopTableHandle tableHandle = (AtopTableHandle) table; List<ConnectorSplit> splits = new ArrayList<>(); ZonedDateTime end = ZonedDateTime.now(timeZone); for (Node node : nodeManager.getWorkerNodes()) { ZonedDateTime start = end.minusDays(maxHistoryDays - 1).withHour(0).withMinute(0).withSecond(0).withNano(0); while (start.isBefore(end)) { ZonedDateTime splitEnd = start.withHour(23).withMinute(59).withSecond(59).withNano(0); Domain splitDomain = Domain.create( ValueSet.ofRanges(Range.range( TIMESTAMP_TZ_MILLIS, packDateTimeWithZone(start.toInstant().toEpochMilli(), UTC_KEY), true, packDateTimeWithZone(splitEnd.toInstant().toEpochMilli(), UTC_KEY), true)), false); if (tableHandle.getStartTimeConstraint().overlaps(splitDomain) && tableHandle.getEndTimeConstraint().overlaps(splitDomain)) { splits.add(new AtopSplit(node.getHostAndPort(), start.toEpochSecond(), start.getZone())); } start = start.plusDays(1).withHour(0).withMinute(0).withSecond(0).withNano(0); } } return new FixedSplitSource(splits); } }
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ package org.elasticsearch.xpack.core.ilm; import org.elasticsearch.common.Strings; import org.elasticsearch.common.io.stream.StreamOutput; import org.elasticsearch.common.util.set.Sets; import org.elasticsearch.core.TimeValue; import org.elasticsearch.rollup.RollupV2; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; import static java.util.stream.Collectors.toList; /** * Represents the lifecycle of an index from creation to deletion. A * {@link TimeseriesLifecycleType} is made up of a set of {@link Phase}s which it will * move through. Soon we will constrain the phases using some kinda of lifecycle * type which will allow only particular {@link Phase}s to be defined, will * dictate the order in which the {@link Phase}s are executed and will define * which {@link LifecycleAction}s are allowed in each phase. */ public class TimeseriesLifecycleType implements LifecycleType { public static final TimeseriesLifecycleType INSTANCE = new TimeseriesLifecycleType(); public static final String TYPE = "timeseries"; static final String HOT_PHASE = "hot"; static final String WARM_PHASE = "warm"; static final String COLD_PHASE = "cold"; static final String FROZEN_PHASE = "frozen"; static final String DELETE_PHASE = "delete"; public static final List<String> ORDERED_VALID_PHASES = List.of(HOT_PHASE, WARM_PHASE, COLD_PHASE, FROZEN_PHASE, DELETE_PHASE); public static final List<String> ORDERED_VALID_HOT_ACTIONS = Stream.of( SetPriorityAction.NAME, UnfollowAction.NAME, RolloverAction.NAME, ReadOnlyAction.NAME, RollupV2.isEnabled() ? RollupILMAction.NAME : null, ShrinkAction.NAME, ForceMergeAction.NAME, SearchableSnapshotAction.NAME ).filter(Objects::nonNull).toList(); public static final List<String> ORDERED_VALID_WARM_ACTIONS = Arrays.asList( SetPriorityAction.NAME, UnfollowAction.NAME, ReadOnlyAction.NAME, AllocateAction.NAME, MigrateAction.NAME, ShrinkAction.NAME, ForceMergeAction.NAME ); public static final List<String> ORDERED_VALID_COLD_ACTIONS = Stream.of( SetPriorityAction.NAME, UnfollowAction.NAME, ReadOnlyAction.NAME, SearchableSnapshotAction.NAME, AllocateAction.NAME, MigrateAction.NAME, FreezeAction.NAME, RollupV2.isEnabled() ? RollupILMAction.NAME : null ).filter(Objects::nonNull).toList(); public static final List<String> ORDERED_VALID_FROZEN_ACTIONS = List.of(UnfollowAction.NAME, SearchableSnapshotAction.NAME); public static final List<String> ORDERED_VALID_DELETE_ACTIONS = List.of(WaitForSnapshotAction.NAME, DeleteAction.NAME); static final Set<String> VALID_HOT_ACTIONS = Sets.newHashSet(ORDERED_VALID_HOT_ACTIONS); static final Set<String> VALID_WARM_ACTIONS = Sets.newHashSet(ORDERED_VALID_WARM_ACTIONS); static final Set<String> VALID_COLD_ACTIONS = Sets.newHashSet(ORDERED_VALID_COLD_ACTIONS); static final Set<String> VALID_FROZEN_ACTIONS = Sets.newHashSet(ORDERED_VALID_FROZEN_ACTIONS); static final Set<String> VALID_DELETE_ACTIONS = Sets.newHashSet(ORDERED_VALID_DELETE_ACTIONS); private static final Map<String, Set<String>> ALLOWED_ACTIONS = Map.of( HOT_PHASE, VALID_HOT_ACTIONS, WARM_PHASE, VALID_WARM_ACTIONS, COLD_PHASE, VALID_COLD_ACTIONS, DELETE_PHASE, VALID_DELETE_ACTIONS, FROZEN_PHASE, VALID_FROZEN_ACTIONS ); static final Set<String> HOT_ACTIONS_THAT_REQUIRE_ROLLOVER = Sets.newHashSet( ReadOnlyAction.NAME, ShrinkAction.NAME, ForceMergeAction.NAME, RollupILMAction.NAME, SearchableSnapshotAction.NAME ); // Set of actions that cannot be defined (executed) after the managed index has been mounted as searchable snapshot. // It's ordered to produce consistent error messages which can be unit tested. public static final Set<String> ACTIONS_CANNOT_FOLLOW_SEARCHABLE_SNAPSHOT = Collections.unmodifiableSet( new LinkedHashSet<>(Arrays.asList(ForceMergeAction.NAME, FreezeAction.NAME, ShrinkAction.NAME, RollupILMAction.NAME)) ); private TimeseriesLifecycleType() {} @Override public void writeTo(StreamOutput out) throws IOException {} @Override public String getWriteableName() { return TYPE; } public List<Phase> getOrderedPhases(Map<String, Phase> phases) { List<Phase> orderedPhases = new ArrayList<>(ORDERED_VALID_PHASES.size()); for (String phaseName : ORDERED_VALID_PHASES) { Phase phase = phases.get(phaseName); if (phase != null) { Map<String, LifecycleAction> actions = phase.getActions(); if (actions.containsKey(UnfollowAction.NAME) == false && (actions.containsKey(RolloverAction.NAME) || actions.containsKey(ShrinkAction.NAME) || actions.containsKey(SearchableSnapshotAction.NAME))) { Map<String, LifecycleAction> actionMap = new HashMap<>(phase.getActions()); actionMap.put(UnfollowAction.NAME, UnfollowAction.INSTANCE); phase = new Phase(phase.getName(), phase.getMinimumAge(), actionMap); } if (shouldInjectMigrateStepForPhase(phase)) { Map<String, LifecycleAction> actionMap = new HashMap<>(phase.getActions()); actionMap.put(MigrateAction.NAME, MigrateAction.ENABLED); phase = new Phase(phase.getName(), phase.getMinimumAge(), actionMap); } orderedPhases.add(phase); } } return orderedPhases; } public static boolean shouldInjectMigrateStepForPhase(Phase phase) { // searchable snapshots automatically set their own allocation rules, no need to configure them with a migrate step. if (phase.getActions().get(SearchableSnapshotAction.NAME) != null) { return false; } // if the user configured the {@link MigrateAction} already we won't automatically configure it if (phase.getActions().get(MigrateAction.NAME) != null) { return false; } return true; } @Override public String getNextPhaseName(String currentPhaseName, Map<String, Phase> phases) { int index = ORDERED_VALID_PHASES.indexOf(currentPhaseName); if (index < 0 && "new".equals(currentPhaseName) == false) { throw new IllegalArgumentException("[" + currentPhaseName + "] is not a valid phase for lifecycle type [" + TYPE + "]"); } else { // Find the next phase after `index` that exists in `phases` and return it while (++index < ORDERED_VALID_PHASES.size()) { String phaseName = ORDERED_VALID_PHASES.get(index); if (phases.containsKey(phaseName)) { return phaseName; } } // if we have exhausted VALID_PHASES and haven't found a matching // phase in `phases` return null indicating there is no next phase // available return null; } } public String getPreviousPhaseName(String currentPhaseName, Map<String, Phase> phases) { if ("new".equals(currentPhaseName)) { return null; } int index = ORDERED_VALID_PHASES.indexOf(currentPhaseName); if (index < 0) { throw new IllegalArgumentException("[" + currentPhaseName + "] is not a valid phase for lifecycle type [" + TYPE + "]"); } else { // Find the previous phase before `index` that exists in `phases` and return it while (--index >= 0) { String phaseName = ORDERED_VALID_PHASES.get(index); if (phases.containsKey(phaseName)) { return phaseName; } } // if we have exhausted VALID_PHASES and haven't found a matching // phase in `phases` return null indicating there is no previous phase // available return null; } } public List<LifecycleAction> getOrderedActions(Phase phase) { Map<String, LifecycleAction> actions = phase.getActions(); return switch (phase.getName()) { case HOT_PHASE -> ORDERED_VALID_HOT_ACTIONS.stream().map(actions::get).filter(Objects::nonNull).collect(toList()); case WARM_PHASE -> ORDERED_VALID_WARM_ACTIONS.stream().map(actions::get).filter(Objects::nonNull).collect(toList()); case COLD_PHASE -> ORDERED_VALID_COLD_ACTIONS.stream().map(actions::get).filter(Objects::nonNull).collect(toList()); case FROZEN_PHASE -> ORDERED_VALID_FROZEN_ACTIONS.stream().map(actions::get).filter(Objects::nonNull).collect(toList()); case DELETE_PHASE -> ORDERED_VALID_DELETE_ACTIONS.stream().map(actions::get).filter(Objects::nonNull).collect(toList()); default -> throw new IllegalArgumentException("lifecycle type [" + TYPE + "] does not support phase [" + phase.getName() + "]"); }; } @Override public String getNextActionName(String currentActionName, Phase phase) { List<String> orderedActionNames = switch (phase.getName()) { case HOT_PHASE -> ORDERED_VALID_HOT_ACTIONS; case WARM_PHASE -> ORDERED_VALID_WARM_ACTIONS; case COLD_PHASE -> ORDERED_VALID_COLD_ACTIONS; case FROZEN_PHASE -> ORDERED_VALID_FROZEN_ACTIONS; case DELETE_PHASE -> ORDERED_VALID_DELETE_ACTIONS; default -> throw new IllegalArgumentException("lifecycle type [" + TYPE + "] does not support phase [" + phase.getName() + "]"); }; int index = orderedActionNames.indexOf(currentActionName); if (index < 0) { throw new IllegalArgumentException( "[" + currentActionName + "] is not a valid action for phase [" + phase.getName() + "] in lifecycle type [" + TYPE + "]" ); } else { // Find the next action after `index` that exists in the phase and return it while (++index < orderedActionNames.size()) { String actionName = orderedActionNames.get(index); if (phase.getActions().containsKey(actionName)) { return actionName; } } // if we have exhausted `validActions` and haven't found a matching // action in the Phase return null indicating there is no next // action available return null; } } @Override public void validate(Collection<Phase> phases) { phases.forEach(phase -> { if (ALLOWED_ACTIONS.containsKey(phase.getName()) == false) { throw new IllegalArgumentException("Timeseries lifecycle does not support phase [" + phase.getName() + "]"); } phase.getActions().forEach((actionName, action) -> { if (ALLOWED_ACTIONS.get(phase.getName()).contains(actionName) == false) { throw new IllegalArgumentException( "invalid action [" + actionName + "] " + "defined in phase [" + phase.getName() + "]" ); } }); }); // Check for actions in the hot phase that require a rollover String invalidHotPhaseActions = phases.stream() // Is there a hot phase .filter(phase -> HOT_PHASE.equals(phase.getName())) // that does *not* contain the 'rollover' action .filter(phase -> phase.getActions().containsKey(RolloverAction.NAME) == false) // but that does have actions that require a rollover action? .flatMap(phase -> Sets.intersection(phase.getActions().keySet(), HOT_ACTIONS_THAT_REQUIRE_ROLLOVER).stream()) .collect(Collectors.joining(", ")); if (Strings.hasText(invalidHotPhaseActions)) { throw new IllegalArgumentException( "the [" + invalidHotPhaseActions + "] action(s) may not be used in the [" + HOT_PHASE + "] phase without an accompanying [" + RolloverAction.NAME + "] action" ); } // look for phases that have the migrate action enabled and also specify allocation rules via the AllocateAction String phasesWithConflictingMigrationActions = phases.stream() .filter( phase -> phase.getActions().containsKey(MigrateAction.NAME) && ((MigrateAction) phase.getActions().get(MigrateAction.NAME)).isEnabled() && phase.getActions().containsKey(AllocateAction.NAME) && definesAllocationRules((AllocateAction) phase.getActions().get(AllocateAction.NAME)) ) .map(Phase::getName) .collect(Collectors.joining(",")); if (Strings.hasText(phasesWithConflictingMigrationActions)) { throw new IllegalArgumentException( "phases [" + phasesWithConflictingMigrationActions + "] specify an enabled " + MigrateAction.NAME + " action and an " + AllocateAction.NAME + " action with allocation rules. specify only a single " + "data migration in each phase" ); } validateActionsFollowingSearchableSnapshot(phases); validateAllSearchableSnapshotActionsUseSameRepository(phases); validateFrozenPhaseHasSearchableSnapshotAction(phases); } static void validateActionsFollowingSearchableSnapshot(Collection<Phase> phases) { // invalid configurations can occur if searchable_snapshot is defined in the `hot` phase, with subsequent invalid actions // being defined in the warm/cold/frozen phases, or if it is defined in the `cold` phase with subsequent invalid actions // being defined in the frozen phase Optional<Phase> hotPhaseWithSearchableSnapshot = phases.stream() .filter(phase -> phase.getName().equals(HOT_PHASE)) .filter(phase -> phase.getActions().containsKey(SearchableSnapshotAction.NAME)) .findAny(); final List<Phase> phasesFollowingSearchableSnapshot = new ArrayList<>(phases.size()); if (hotPhaseWithSearchableSnapshot.isPresent()) { for (Phase phase : phases) { if (phase.getName().equals(HOT_PHASE) == false) { phasesFollowingSearchableSnapshot.add(phase); } } } else { // let's see if the cold phase defines `searchable_snapshot` Optional<Phase> coldPhaseWithSearchableSnapshot = phases.stream() .filter(phase -> phase.getName().equals(COLD_PHASE)) .filter(phase -> phase.getActions().containsKey(SearchableSnapshotAction.NAME)) .findAny(); if (coldPhaseWithSearchableSnapshot.isPresent()) { for (Phase phase : phases) { if (phase.getName().equals(FROZEN_PHASE)) { phasesFollowingSearchableSnapshot.add(phase); break; } } } } final String phasesDefiningIllegalActions = phasesFollowingSearchableSnapshot.stream() // filter the phases that define illegal actions .filter(phase -> Collections.disjoint(ACTIONS_CANNOT_FOLLOW_SEARCHABLE_SNAPSHOT, phase.getActions().keySet()) == false) .map(Phase::getName) .collect(Collectors.joining(",")); if (Strings.hasText(phasesDefiningIllegalActions)) { throw new IllegalArgumentException( "phases [" + phasesDefiningIllegalActions + "] define one or more of " + ACTIONS_CANNOT_FOLLOW_SEARCHABLE_SNAPSHOT + " actions which are not allowed after a " + "managed index is mounted as a searchable snapshot" ); } } static void validateAllSearchableSnapshotActionsUseSameRepository(Collection<Phase> phases) { Set<String> allRepos = phases.stream() .flatMap(phase -> phase.getActions().entrySet().stream()) .filter(e -> e.getKey().equals(SearchableSnapshotAction.NAME)) .map(Map.Entry::getValue) .map(action -> (SearchableSnapshotAction) action) .map(SearchableSnapshotAction::getSnapshotRepository) .collect(Collectors.toSet()); if (allRepos.size() > 1) { throw new IllegalArgumentException( "policy specifies [" + SearchableSnapshotAction.NAME + "] action multiple times with differing repositories " + allRepos + ", the same repository must be used for all searchable snapshot actions" ); } } /** * Validates that phases don't configure a min_age that is smaller than a previous phase (which can be confusing to users) */ public static String validateMonotonicallyIncreasingPhaseTimings(Collection<Phase> phases) { List<String> errors = new ArrayList<>(); Set<String> invalidPhases = new HashSet<>(); // Loop through all phases in order, for each phase with a min_age // configured, look at all the future phases to see if their ages are // >= the configured age. A min_age of 0 means that the age was not // configured, so we don't validate it. for (int i = 0; i < ORDERED_VALID_PHASES.size(); i++) { String phaseName = ORDERED_VALID_PHASES.get(i); // Check if this phase is present with a configured min_age Optional<Phase> maybePhase = phases.stream() .filter(p -> phaseName.equals(p.getName())) .filter(p -> p.getMinimumAge() != null && p.getMinimumAge().equals(TimeValue.ZERO) == false) .findFirst(); if (maybePhase.isPresent()) { Phase phase = maybePhase.get(); // We only consider a phase bad once, otherwise we can duplicate // errors, so we keep track of the invalid phases we've seen and // ignore them if they come around again. if (invalidPhases.contains(phase.getName())) { continue; } TimeValue phaseMinAge = phase.getMinimumAge(); Set<String> followingPhases = new HashSet<>(ORDERED_VALID_PHASES.subList(i + 1, ORDERED_VALID_PHASES.size())); Set<Phase> phasesWithBadAges = phases.stream() .filter(p -> followingPhases.contains(p.getName())) .filter(p -> p.getMinimumAge() != null && p.getMinimumAge().equals(TimeValue.ZERO) == false) .filter(p -> p.getMinimumAge().compareTo(phaseMinAge) < 0) .collect(Collectors.toSet()); if (phasesWithBadAges.size() > 0) { phasesWithBadAges.forEach(p -> invalidPhases.add(p.getName())); // build an error message string Iterator<Phase> it = phasesWithBadAges.iterator(); Phase badPhase = it.next(); String error = "Your policy is configured to run the " + badPhase.getName() + " phase (min_age: " + badPhase.getMinimumAge() + ")"; if (phasesWithBadAges.size() > 1) { while (it.hasNext()) { badPhase = it.next(); error = error + ", the " + badPhase.getName() + " phase (min_age: " + badPhase.getMinimumAge() + ")"; } // if multiple phases are cited replace last occurrence of "," with " and" StringBuilder builder = new StringBuilder(); int last_comma_index = error.lastIndexOf(","); builder.append(error, 0, last_comma_index); builder.append(" and"); builder.append(error.substring(last_comma_index + 1)); error = builder.toString(); } error = error + " before the " + phaseName + " phase (min_age: " + phase.getMinimumAge() + "). You should change the phase timing so that the phases will execute in the order of hot, warm, then cold."; errors.add(error); } } } // If we found any invalid phase timings, concatenate their messages and return the message return Strings.collectionToCommaDelimitedString(errors); } /** * Require that the "frozen" phase configured in a policy has a searchable snapshot action. */ static void validateFrozenPhaseHasSearchableSnapshotAction(Collection<Phase> phases) { Optional<Phase> maybeFrozenPhase = phases.stream().filter(p -> FROZEN_PHASE.equals(p.getName())).findFirst(); maybeFrozenPhase.ifPresent(p -> { if (p.getActions().containsKey(SearchableSnapshotAction.NAME) == false) { throw new IllegalArgumentException( "policy specifies the [" + FROZEN_PHASE + "] phase without a corresponding [" + SearchableSnapshotAction.NAME + "] action, but a searchable snapshot action is required in the frozen phase" ); } }); } private static boolean definesAllocationRules(AllocateAction action) { return action.getRequire().isEmpty() == false || action.getInclude().isEmpty() == false || action.getExclude().isEmpty() == false; } }
/* * 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.ratis; import org.apache.log4j.Level; import org.apache.ratis.conf.ConfUtils; import org.apache.ratis.util.ExitUtils; import org.apache.ratis.util.FileUtils; import org.apache.ratis.util.JavaUtils; import org.apache.ratis.util.Log4jUtils; import org.apache.ratis.util.TimeDuration; import org.apache.ratis.util.function.CheckedRunnable; import org.junit.After; import org.junit.Assert; import org.junit.Rule; import org.junit.rules.TestName; import org.junit.rules.Timeout; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; import java.util.Objects; import java.util.concurrent.CompletableFuture; import java.util.concurrent.Future; import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Supplier; public abstract class BaseTest { public final Logger LOG = LoggerFactory.getLogger(getClass()); public static final TimeDuration HUNDRED_MILLIS = TimeDuration.valueOf(100, TimeUnit.MILLISECONDS); public static final TimeDuration ONE_SECOND = TimeDuration.ONE_SECOND; public static final TimeDuration FIVE_SECONDS = TimeDuration.valueOf(5, TimeUnit.SECONDS); { Log4jUtils.setLogLevel(ConfUtils.LOG, Level.WARN); Log4jUtils.setLogLevel(FileUtils.LOG, Level.TRACE); ExitUtils.disableSystemExit(); } private final AtomicReference<Throwable> firstException = new AtomicReference<>(); public void setFirstException(Throwable e) { if (firstException.compareAndSet(null, e)) { LOG.error("Set firstException", e); } } @After public void assertNoFailures() { final Throwable e = firstException.get(); if (e != null) { throw new IllegalStateException("Failed: first exception was set", e); } ExitUtils.assertNotTerminated(); } @Rule public final Timeout globalTimeout = new Timeout(getGlobalTimeoutSeconds(), TimeUnit.SECONDS ); @Rule public final TestName testName = new TestName(); public int getGlobalTimeoutSeconds() { return 100; } private static final Supplier<File> rootTestDir = JavaUtils.memoize( () -> JavaUtils.callAsUnchecked(() -> { final File dir = new File(System.getProperty("test.build.data", "target/test/data"), Integer.toHexString(ThreadLocalRandom.current().nextInt())); if (dir.exists() && !dir.isDirectory()) { throw new IOException(dir + " already exists and is not a directory"); } else if (!dir.exists() && !dir.mkdirs()) { throw new IOException("Cannot create test directory " + dir); } return dir; })); public static File getRootTestDir() { return rootTestDir.get(); } public File getClassTestDir() { return new File(getRootTestDir(), getClass().getSimpleName()); } public File getTestDir() { return new File(getClassTestDir(), testName.getMethodName()); } @SafeVarargs public static void assertThrowable( String description, Throwable t, Class<? extends Throwable> expectedThrowableClass, Logger log, Class<? extends Throwable>... expectedCauseClasses) { if (log != null) { log.info("The test \"" + description + "\" throws " + t.getClass().getSimpleName(), t); } Assert.assertEquals(expectedThrowableClass, t.getClass()); for (Class<? extends Throwable> expectedCause : expectedCauseClasses) { final Throwable previous = t; t = Objects.requireNonNull(previous.getCause(), () -> "previous.getCause() == null for previous=" + previous); Assert.assertEquals(expectedCause, t.getClass()); } } @SafeVarargs public static Throwable testFailureCase( String description, CheckedRunnable<?> testCode, Class<? extends Throwable> expectedThrowableClass, Logger log, Class<? extends Throwable>... expectedCauseClasses) { if (log != null) { log.info("run '{}'", description); } try { testCode.run(); } catch (Throwable t) { assertThrowable(description, t, expectedThrowableClass, log, expectedCauseClasses); return t; } throw new AssertionError("The test \"" + description + "\" does not throw anything."); } @SafeVarargs public final Throwable testFailureCase( String description, CheckedRunnable<?> testCode, Class<? extends Throwable> expectedThrowableClass, Class<? extends Throwable>... expectedCauseClasses) { return testFailureCase(description, testCode, expectedThrowableClass, LOG, expectedCauseClasses); } @SafeVarargs public static Throwable testFailureCaseAsync( String description, Supplier<CompletableFuture<?>> testCode, Class<? extends Throwable> expectedThrowableClass, Logger log, Class<? extends Throwable>... expectedCauseClasses) { if (log != null) { log.info("run '{}'", description); } try { testCode.get().join(); } catch (Throwable t) { t = JavaUtils.unwrapCompletionException(t); assertThrowable(description, t, expectedThrowableClass, log, expectedCauseClasses); return t; } throw new AssertionError("The test \"" + description + "\" does not throw anything."); } @SafeVarargs public final Throwable testFailureCaseAsync( String description, Supplier<CompletableFuture<?>> testCode, Class<? extends Throwable> expectedThrowableClass, Class<? extends Throwable>... expectedCauseClasses) { return testFailureCaseAsync(description, testCode, expectedThrowableClass, LOG, expectedCauseClasses); } static <T> T getWithDefaultTimeout(Future<T> future) throws Exception { return future.get(FIVE_SECONDS.getDuration(), FIVE_SECONDS.getUnit()); } }
package com.huang.hm.member; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest class HmMemberApplicationTests { @Test void contextLoads() { } }
/* * Copyright (c) 2017 Strapdata (http://www.strapdata.com) * Contains some code from Elasticsearch (http://www.elastic.co) * * 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.elassandra.cluster.routing; import org.elasticsearch.cluster.node.DiscoveryNode; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Random; /** * Sub query nodes in the same rack if possible, from the coordinator's rack if its shard is green. * * @author vroyer * */ public class RackAwareSearchStrategy extends RandomSearchStrategy { @Override public void sortNodes(DiscoveryNode pivotNode, List<DiscoveryNode> greenNodes, Random random) { Collections.sort(greenNodes, new RackComparator(pivotNode.getAttributes().get("rack"), random)); } static class RackComparator implements Comparator<DiscoveryNode> { String rack; Random random; public RackComparator(String rack, Random random) { this.rack = rack; this.random = random; } @Override public int compare(DiscoveryNode o1, DiscoveryNode o2) { if (rack.equals(o1.getAttributes().get("rack"))) { return (rack.equals(o2.getAttributes().get("rack"))) ? random.nextInt(2)*2 -1 // load balance subqueries in the rack : -1; } if (rack.equals(o2.getAttributes().get("rack"))) { return 1; } return random.nextInt(2)*2 -1; // random node outside the rack } } }
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package de.dennisguse.opentracks.content.provider; import android.content.ContentResolver; import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.location.Location; import android.util.Pair; import androidx.test.core.app.ApplicationProvider; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.UUID; import de.dennisguse.opentracks.content.data.Marker; import de.dennisguse.opentracks.content.data.MarkerColumns; import de.dennisguse.opentracks.content.data.TestDataUtil; import de.dennisguse.opentracks.content.data.Track; import de.dennisguse.opentracks.content.data.TrackPoint; import de.dennisguse.opentracks.content.data.TrackPointsColumns; import de.dennisguse.opentracks.content.data.TracksColumns; import de.dennisguse.opentracks.stats.TrackStatistics; import de.dennisguse.opentracks.util.FileUtils; import de.dennisguse.opentracks.util.UUIDUtils; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.when; /** * A unit test for {@link ContentProviderUtils}. * * @author Bartlomiej Niechwiej * @author Youtao Liu */ @RunWith(MockitoJUnitRunner.class) public class CustomContentProviderUtilsTest { private static final String NAME_PREFIX = "test name"; private static final String MOCK_DESC = "Mock Next Waypoint Desc!"; private static final String TEST_DESC = "Test Desc!"; private static final String TEST_DESC_NEW = "Test Desc new!"; private static final String TEST_NAME_NEW = "Test Name new!"; private final Context context = ApplicationProvider.getApplicationContext(); private ContentProviderUtils contentProviderUtils; @Mock private Cursor cursorMock; @Mock private ContentResolver contentResolverMock; @Before public void setUp() { contentProviderUtils = new ContentProviderUtils(context); contentProviderUtils.deleteAllTracks(context); } @Test public void testLocationIterator_noPoints() { testIterator(new Track.Id(1), 0, 1, false); } @Test public void testLocationIterator_noBatchAscending() { testIterator(new Track.Id(1), 50, 100, false); testIterator(new Track.Id(2), 50, 50, false); } @Test public void testLocationIterator_noBatchDescending() { testIterator(new Track.Id(1), 50, 100, true); testIterator(new Track.Id(2), 50, 50, true); } @Test public void testLocationIterator_batchAscending() { testIterator(new Track.Id(1), 50, 11, false); testIterator(new Track.Id(2), 50, 25, false); } @Test public void testLocationIterator_batchDescending() { testIterator(new Track.Id(1), 50, 11, true); testIterator(new Track.Id(2), 50, 25, true); } @Test public void testLocationIterator_largeTrack() { testIterator(new Track.Id(1), 20000, 2000, false); } private void testIterator(Track.Id trackId, int numPoints, int batchSize, boolean descending) { long lastPointId = initializeTrack(trackId, numPoints); contentProviderUtils.setDefaultCursorBatchSize(batchSize); List<TrackPoint> locations = new ArrayList<>(numPoints); try (TrackPointIterator it = contentProviderUtils.getTrackPointLocationIterator(trackId, -1L, descending)) { while (it.hasNext()) { TrackPoint loc = it.next(); assertNotNull(loc); locations.add(loc); // Make sure the IDs are returned in the right order. assertEquals(descending ? lastPointId - locations.size() + 1 : lastPointId - numPoints + locations.size(), it.getTrackPointId()); } assertEquals(numPoints, locations.size()); } } private long initializeTrack(Track.Id id, int numPoints) { Track track = new Track(); track.setId(id); track.setName("Test: " + id.getId()); contentProviderUtils.insertTrack(track); track = contentProviderUtils.getTrack(id); assertNotNull(track); TrackPoint[] trackPoints = new TrackPoint[numPoints]; for (int i = 0; i < numPoints; ++i) { Location loc = new Location("test"); loc.setLatitude(37.0 + (double) i / 10000.0); loc.setLongitude(57.0 - (double) i / 10000.0); loc.setAccuracy((float) i / 100.0f); loc.setAltitude(i * 2.5); trackPoints[i] = new TrackPoint(loc); } contentProviderUtils.bulkInsertTrackPoint(trackPoints, id); // Load all inserted trackPoints. long lastPointId = -1; int counter = 0; try (TrackPointIterator it = contentProviderUtils.getTrackPointLocationIterator(id, -1L, false)) { while (it.hasNext()) { it.next(); lastPointId = it.getTrackPointId(); counter++; } } assertTrue(numPoints == 0 || lastPointId > 0); assertEquals(numPoints, counter); return lastPointId; } /** * Tests the method {@link ContentProviderUtils#createTrack(Cursor)}. */ @Test public void testCreateTrack() { Track.Id trackId = new Track.Id(System.currentTimeMillis()); int columnIndex = 1; // Id when(cursorMock.getColumnIndexOrThrow(TracksColumns._ID)).thenReturn(columnIndex); when(cursorMock.isNull(columnIndex)).thenReturn(false); when(cursorMock.getLong(columnIndex)).thenReturn(trackId.getId()); //Uuid columnIndex++; when(cursorMock.getColumnIndexOrThrow(TracksColumns.UUID)).thenReturn(columnIndex); when(cursorMock.isNull(columnIndex)).thenReturn(false); when(cursorMock.getBlob(columnIndex)).thenReturn(UUIDUtils.toBytes(UUID.randomUUID())); // Name columnIndex++; String name = NAME_PREFIX + trackId.getId(); when(cursorMock.getColumnIndexOrThrow(TracksColumns.NAME)).thenReturn(columnIndex); when(cursorMock.isNull(columnIndex)).thenReturn(false); when(cursorMock.getString(columnIndex)).thenReturn(name); Track track = contentProviderUtils.createTrack(cursorMock); assertEquals(trackId, track.getId()); assertEquals(name, track.getName()); } /** * Tests the method {@link ContentProviderUtils#deleteAllTracks(Context)} */ @Test public void testDeleteAllTracks() { // Insert track, points and waypoint at first. Track.Id trackId = new Track.Id(System.currentTimeMillis()); TestDataUtil.createTrackAndInsert(contentProviderUtils, trackId, 10); Marker waypoint = new Marker(trackId, contentProviderUtils.getLastValidTrackPoint(trackId)); contentProviderUtils.insertMarker(waypoint); ContentResolver contentResolver = context.getContentResolver(); Cursor tracksCursor = contentResolver.query(TracksColumns.CONTENT_URI, null, null, null, TracksColumns._ID); assertEquals(1, tracksCursor.getCount()); Cursor tracksPointsCursor = contentResolver.query(TrackPointsColumns.CONTENT_URI_BY_ID, null, null, null, TrackPointsColumns._ID); assertEquals(10, tracksPointsCursor.getCount()); Cursor waypointCursor = contentResolver.query(MarkerColumns.CONTENT_URI, null, null, null, MarkerColumns._ID); assertEquals(1, waypointCursor.getCount()); // Delete all. contentProviderUtils.deleteAllTracks(context); // Check whether all have been deleted. tracksCursor = contentResolver.query(TracksColumns.CONTENT_URI, null, null, null, TracksColumns._ID); assertEquals(0, tracksCursor.getCount()); tracksPointsCursor = contentResolver.query(TrackPointsColumns.CONTENT_URI_BY_ID, null, null, null, TrackPointsColumns._ID); assertEquals(0, tracksPointsCursor.getCount()); waypointCursor = contentResolver.query(MarkerColumns.CONTENT_URI, null, null, null, MarkerColumns._ID); assertEquals(0, waypointCursor.getCount()); } /** * Tests the method {@link ContentProviderUtils#deleteAllTracks(Context)} */ @Test public void testDeleteAllTracks_withWaypointAndPhoto() throws IOException { // Insert track, points and waypoint with photo at first. Track.Id trackId = new Track.Id(System.currentTimeMillis()); Track track = TestDataUtil.createTrackAndInsert(contentProviderUtils, trackId, 10); TrackPoint trackPoint = contentProviderUtils.getLastValidTrackPoint(trackId); Marker waypoint = TestDataUtil.createWaypointWithPhoto(context, trackId, trackPoint.getLocation()); contentProviderUtils.insertMarker(waypoint); ContentResolver contentResolver = context.getContentResolver(); Cursor tracksCursor = contentResolver.query(TracksColumns.CONTENT_URI, null, null, null, TracksColumns._ID); assertEquals(1, tracksCursor.getCount()); Cursor tracksPointsCursor = contentResolver.query(TrackPointsColumns.CONTENT_URI_BY_ID, null, null, null, TrackPointsColumns._ID); assertEquals(10, tracksPointsCursor.getCount()); Cursor waypointCursor = contentResolver.query(MarkerColumns.CONTENT_URI, null, null, null, MarkerColumns._ID); assertEquals(1, waypointCursor.getCount()); // Check waypoint has photo and it's in the external storage. assertTrue(waypoint.hasPhoto()); File dir = FileUtils.getPhotoDir(context, trackId); assertTrue(dir.isDirectory()); assertEquals(1, dir.list().length); assertTrue(dir.exists()); // Delete all. contentProviderUtils.deleteAllTracks(context); // Check whether all have been deleted. tracksCursor = contentResolver.query(TracksColumns.CONTENT_URI, null, null, null, TracksColumns._ID); assertEquals(0, tracksCursor.getCount()); tracksPointsCursor = contentResolver.query(TrackPointsColumns.CONTENT_URI_BY_ID, null, null, null, TrackPointsColumns._ID); assertEquals(0, tracksPointsCursor.getCount()); waypointCursor = contentResolver.query(MarkerColumns.CONTENT_URI, null, null, null, MarkerColumns._ID); assertEquals(0, waypointCursor.getCount()); assertFalse(dir.exists()); } /** * Tests the method {@link ContentProviderUtils#deleteTrack(Context, Track.Id)}. */ @Test public void testDeleteTrack() { // Insert three tracks, points of two tracks and way point of one track. long random = System.currentTimeMillis(); Track.Id trackId1 = new Track.Id(random); Track.Id trackId2 = new Track.Id(random + 1); Track.Id trackId3 = new Track.Id(random + 2); TestDataUtil.createTrackAndInsert(contentProviderUtils, trackId1, 0); TestDataUtil.createTrackAndInsert(contentProviderUtils, trackId2, 10); TestDataUtil.createTrackAndInsert(contentProviderUtils, trackId3, 10); Marker waypoint = new Marker(trackId1, contentProviderUtils.getLastValidTrackPoint(trackId2)); contentProviderUtils.insertMarker(waypoint); ContentResolver contentResolver = context.getContentResolver(); Cursor tracksCursor = contentResolver.query(TracksColumns.CONTENT_URI, null, null, null, TracksColumns._ID); assertEquals(3, tracksCursor.getCount()); Cursor tracksPointsCursor = contentResolver.query(TrackPointsColumns.CONTENT_URI_BY_ID, null, null, null, TrackPointsColumns._ID); assertEquals(20, tracksPointsCursor.getCount()); Cursor waypointCursor = contentResolver.query(MarkerColumns.CONTENT_URI, null, null, null, MarkerColumns._ID); assertEquals(1, waypointCursor.getCount()); // Delete one track. contentProviderUtils.deleteTrack(context, trackId1); // Check whether all data of a track has been deleted. tracksCursor = contentResolver.query(TracksColumns.CONTENT_URI, null, null, null, TracksColumns._ID); assertEquals(2, tracksCursor.getCount()); tracksPointsCursor = contentResolver.query(TrackPointsColumns.CONTENT_URI_BY_ID, null, null, null, TrackPointsColumns._ID); assertEquals(20, tracksPointsCursor.getCount()); waypointCursor = contentResolver.query(MarkerColumns.CONTENT_URI, null, null, null, MarkerColumns._ID); assertEquals(0, waypointCursor.getCount()); } /** * Tests the method {@link ContentProviderUtils#deleteTrack(Context, Track.Id)}. */ @Test public void testDeleteTrack_withWaypointPhoto() throws IOException { // Insert three tracks. long random = System.currentTimeMillis(); Track.Id trackId1 = new Track.Id(random); Track.Id trackId2 = new Track.Id(random + 1); Track.Id trackId3 = new Track.Id(random + 2); TestDataUtil.createTrackAndInsert(contentProviderUtils, trackId1, 10); TestDataUtil.createTrackAndInsert(contentProviderUtils, trackId2, 10); TestDataUtil.createTrackAndInsert(contentProviderUtils, trackId3, 10); // Insert a waypoint in tracks trackId and trackId + 1. TrackPoint trackPoint1 = contentProviderUtils.getLastValidTrackPoint(trackId1); Marker waypoint1 = TestDataUtil.createWaypointWithPhoto(context, trackId1, trackPoint1.getLocation()); contentProviderUtils.insertMarker(waypoint1); File dir1 = FileUtils.getPhotoDir(context, trackId1); TrackPoint trackPoint2 = contentProviderUtils.getLastValidTrackPoint(trackId2); Marker waypoint2 = TestDataUtil.createWaypointWithPhoto(context, trackId2, trackPoint2.getLocation()); contentProviderUtils.insertMarker(waypoint2); File dir2 = FileUtils.getPhotoDir(context, trackId2); // Check. ContentResolver contentResolver = context.getContentResolver(); Cursor tracksCursor = contentResolver.query(TracksColumns.CONTENT_URI, null, null, null, TracksColumns._ID); assertEquals(3, tracksCursor.getCount()); Cursor tracksPointsCursor = contentResolver.query(TrackPointsColumns.CONTENT_URI_BY_ID, null, null, null, TrackPointsColumns._ID); assertEquals(30, tracksPointsCursor.getCount()); Cursor waypointCursor = contentResolver.query(MarkerColumns.CONTENT_URI, null, null, null, MarkerColumns._ID); assertEquals(2, waypointCursor.getCount()); assertTrue(waypoint1.hasPhoto()); assertTrue(dir1.isDirectory()); assertEquals(1, dir1.list().length); assertTrue(dir1.exists()); assertTrue(dir2.isDirectory()); assertEquals(1, dir2.list().length); assertTrue(dir2.exists()); // Delete one track. contentProviderUtils.deleteTrack(context, trackId1); // Check whether all data of a track has been deleted. tracksCursor = contentResolver.query(TracksColumns.CONTENT_URI, null, null, null, TracksColumns._ID); assertEquals(2, tracksCursor.getCount()); tracksPointsCursor = contentResolver.query(TrackPointsColumns.CONTENT_URI_BY_ID, null, null, null, TrackPointsColumns._ID); assertEquals(20, tracksPointsCursor.getCount()); waypointCursor = contentResolver.query(MarkerColumns.CONTENT_URI, null, null, null, MarkerColumns._ID); assertEquals(1, waypointCursor.getCount()); assertFalse(dir1.exists()); assertTrue(dir2.exists()); } /** * Tests the method {@link ContentProviderUtils#getTracks()} */ @Test public void testGetAllTracks() { // given int initialTrackNumber = contentProviderUtils.getTracks().size(); Track.Id trackId = new Track.Id(System.currentTimeMillis()); contentProviderUtils.insertTrack(TestDataUtil.createTrack(trackId)); // when List<Track> allTracks = contentProviderUtils.getTracks(); // then assertEquals(initialTrackNumber + 1, allTracks.size()); assertEquals(trackId, allTracks.get(allTracks.size() - 1).getId()); } /** * Tests the method {@link ContentProviderUtils#getLastTrack()} */ @Test public void testGetLastTrack() { Track.Id trackId = new Track.Id(System.currentTimeMillis()); contentProviderUtils.insertTrack(TestDataUtil.createTrack(trackId)); assertEquals(trackId, contentProviderUtils.getLastTrack().getId()); } /** * Tests the method {@link ContentProviderUtils#getTrack(Track.Id)} */ @Test public void testGetTrack_by_id() { // given Track.Id trackId = new Track.Id(System.currentTimeMillis()); contentProviderUtils.insertTrack(TestDataUtil.createTrack(trackId)); // when / then assertNotNull(contentProviderUtils.getTrack(trackId)); } /** * Tests the method {@link ContentProviderUtils#getTrack(Track.Id)} */ @Test public void testGetTrack_by_uuid() { // given Track.Id trackId = new Track.Id(System.currentTimeMillis()); Track track = TestDataUtil.createTrack(trackId); contentProviderUtils.insertTrack(track); // when / then assertNotNull(contentProviderUtils.getTrack(track.getUuid())); } /** * Tests the method {@link ContentProviderUtils#updateTrack(Track)} */ @Test public void testUpdateTrack() { // given Track.Id trackId = new Track.Id(System.currentTimeMillis()); Track track = TestDataUtil.createTrack(trackId); String nameOld = "name1"; String nameNew = "name2"; track.setName(nameOld); // when / then contentProviderUtils.insertTrack(track); assertEquals(nameOld, contentProviderUtils.getTrack(trackId).getName()); track.setName(nameNew); contentProviderUtils.updateTrack(track); assertEquals(nameNew, contentProviderUtils.getTrack(trackId).getName()); } /** * Tests the method {@link ContentProviderUtils#createContentValues(Marker)}. */ @Test public void testCreateContentValues_waypoint() { Track.Id trackId = new Track.Id(System.currentTimeMillis()); Pair<Track, TrackPoint[]> track = TestDataUtil.createTrack(trackId, 10); // Bottom long startTime = 1000L; // AverageSpeed TrackStatistics statistics = new TrackStatistics(); statistics.setStartTime_ms(startTime); statistics.setStopTime_ms(2500L); statistics.setTotalTime(1500L); statistics.setMovingTime(700L); statistics.setTotalDistance(750.0); statistics.setTotalElevationGain(50.0f); statistics.setMaxSpeed(60.0); statistics.setMaxElevation(1250.0); statistics.setMinElevation(1200.0); track.first.setTrackStatistics(statistics); contentProviderUtils.insertTrack(track.first); Marker waypoint = new Marker(trackId, track.second[0]); waypoint.setDescription(TEST_DESC); contentProviderUtils.insertMarker(waypoint); ContentProviderUtils contentProviderUtils = new ContentProviderUtils(contentResolverMock); Marker.Id waypointId = new Marker.Id(System.currentTimeMillis()); waypoint.setId(waypointId); ContentValues contentValues = contentProviderUtils.createContentValues(waypoint); assertEquals(waypointId.getId(), contentValues.get(MarkerColumns._ID)); assertEquals((int) (TestDataUtil.INITIAL_LONGITUDE * 1000000), contentValues.get(MarkerColumns.LONGITUDE)); assertEquals(TEST_DESC, contentValues.get(MarkerColumns.DESCRIPTION)); } /** * Tests the method {@link ContentProviderUtils#createMarker(Cursor)}. */ @Test public void testCreateWaypoint() { int startColumnIndex = 1; int columnIndex = startColumnIndex; when(cursorMock.getColumnIndexOrThrow(MarkerColumns._ID)).thenReturn(columnIndex++); when(cursorMock.getColumnIndexOrThrow(MarkerColumns.NAME)).thenReturn(columnIndex++); when(cursorMock.getColumnIndexOrThrow(MarkerColumns.TRACKID)).thenReturn(columnIndex++); columnIndex = startColumnIndex; // Id when(cursorMock.isNull(columnIndex++)).thenReturn(false); // Name when(cursorMock.isNull(columnIndex++)).thenReturn(false); // trackIdIndex when(cursorMock.isNull(columnIndex++)).thenReturn(false); long id = System.currentTimeMillis(); columnIndex = startColumnIndex; // Id when(cursorMock.getLong(columnIndex++)).thenReturn(id); // Name String name = NAME_PREFIX + id; when(cursorMock.getString(columnIndex++)).thenReturn(name); // trackIdIndex long trackId = 11L; when(cursorMock.getLong(columnIndex++)).thenReturn(trackId); Marker waypoint = contentProviderUtils.createMarker(cursorMock); assertEquals(id, waypoint.getId().getId()); assertEquals(name, waypoint.getName()); assertEquals(trackId, waypoint.getTrackId().getId()); } /** * Tests the method * {@link ContentProviderUtils#deleteMarker(Context, Marker.Id)} * when there is only one waypoint in the track. */ @Test public void testDeleteWaypoint_onlyOneWayPoint() { Track.Id trackId = new Track.Id(System.currentTimeMillis()); TestDataUtil.createTrackAndInsert(contentProviderUtils, trackId, 10); // Insert at first. Marker waypoint1 = new Marker(trackId, contentProviderUtils.getLastValidTrackPoint(trackId)); waypoint1.setDescription(TEST_DESC); contentProviderUtils.insertMarker(waypoint1); // Check insert was done. assertEquals(contentProviderUtils.getMarkerCount(trackId), 1); // Get waypoint id that needs to delete. Marker.Id waypoint1Id = new Marker.Id(ContentUris.parseId(contentProviderUtils.insertMarker(waypoint1))); // Delete contentProviderUtils.deleteMarker(context, waypoint1Id); assertNull(contentProviderUtils.getMarker(waypoint1Id)); } /** * Tests the method * {@link ContentProviderUtils#deleteMarker(Context, Marker.Id)} * when there is only one waypoint in the track. */ @Test public void testDeleteWaypoint_onlyOneWayPointWithPhotoUrl() throws IOException { Track.Id trackId = new Track.Id(System.currentTimeMillis()); TestDataUtil.createTrackAndInsert(contentProviderUtils, trackId, 10); // Insert at first. TrackPoint trackPoint = contentProviderUtils.getLastValidTrackPoint(trackId); Marker waypoint1 = TestDataUtil.createWaypointWithPhoto(context, trackId, trackPoint.getLocation()); contentProviderUtils.insertMarker(waypoint1); // Check insert was done. assertEquals(contentProviderUtils.getMarkerCount(trackId), 1); // Get waypoint id that needs to delete. Marker.Id waypoint1Id = new Marker.Id(ContentUris.parseId(contentProviderUtils.insertMarker(waypoint1))); // Check waypoint has photo and it's in the external storage. assertTrue(waypoint1.hasPhoto()); File dir = FileUtils.getPhotoDir(context, trackId); assertTrue(dir.isDirectory()); assertEquals(1, dir.list().length); assertTrue(dir.exists()); // Delete contentProviderUtils.deleteMarker(context, waypoint1Id); // Check waypoint doesn't exists and photo folder was deleted. assertNull(contentProviderUtils.getMarker(waypoint1Id)); assertFalse(dir.exists()); } /** * Tests the method {@link ContentProviderUtils#deleteMarker(Context, Marker.Id)} when there is more than one waypoint in the track. */ @Test public void testDeleteWaypoint_hasNextWayPoint() { Track.Id trackId = new Track.Id(System.currentTimeMillis()); TestDataUtil.createTrackAndInsert(contentProviderUtils, trackId, 10); // Track track = TestDataUtil.createTrackAndInsert(trackId, 10); // // TrackStatistics statistics = new TrackStatistics(); // statistics.setStartTime_ms(1000L); // statistics.setStopTime_ms(2500L); // statistics.setTotalTime(1500L); // statistics.setMovingTime(700L); // statistics.setTotalDistance(750.0); // statistics.setTotalElevationGain(50.0); // statistics.setMaxSpeed(60.0); // statistics.setMaxElevation(1250.0); // statistics.setMinElevation(1200.0); // // track.setTrackStatistics(statistics); // TestDataUtil.insertTrackWithLocations(contentProviderUtils, track); // Insert at first. Marker waypoint1 = new Marker(trackId, contentProviderUtils.getLastValidTrackPoint(trackId)); waypoint1.setDescription(MOCK_DESC); Marker.Id waypoint1Id = new Marker.Id(ContentUris.parseId(contentProviderUtils.insertMarker(waypoint1))); Marker waypoint2 = new Marker(trackId, contentProviderUtils.getLastValidTrackPoint(trackId)); waypoint2.setDescription(MOCK_DESC); Marker.Id waypoint2Id = new Marker.Id(ContentUris.parseId(contentProviderUtils.insertMarker(waypoint2))); // Delete assertNotNull(contentProviderUtils.getMarker(waypoint1Id)); contentProviderUtils.deleteMarker(context, waypoint1Id); assertNull(contentProviderUtils.getMarker(waypoint1Id)); assertEquals(MOCK_DESC, contentProviderUtils.getMarker(waypoint2Id).getDescription()); } /** * Tests the method {@link ContentProviderUtils#getNextMarkerNumber(Track.Id)}. */ @Test public void testGetNextWaypointNumber() { Track.Id trackId = new Track.Id(System.currentTimeMillis()); TestDataUtil.createTrackAndInsert(contentProviderUtils, trackId, 10); Marker waypoint1 = new Marker(trackId, contentProviderUtils.getLastValidTrackPoint(trackId)); Marker waypoint2 = new Marker(trackId, contentProviderUtils.getLastValidTrackPoint(trackId)); Marker waypoint3 = new Marker(trackId, contentProviderUtils.getLastValidTrackPoint(trackId)); Marker waypoint4 = new Marker(trackId, contentProviderUtils.getLastValidTrackPoint(trackId)); contentProviderUtils.insertMarker(waypoint1); contentProviderUtils.insertMarker(waypoint2); contentProviderUtils.insertMarker(waypoint3); contentProviderUtils.insertMarker(waypoint4); assertEquals(4, contentProviderUtils.getNextMarkerNumber(trackId)); } /** * Tests the method {@link ContentProviderUtils#insertMarker(Marker)} and * {@link ContentProviderUtils#getMarker(Marker.Id)}. */ @Test public void testInsertAndGetWaypoint() { Track.Id trackId = new Track.Id(System.currentTimeMillis()); TestDataUtil.createTrackAndInsert(contentProviderUtils, trackId, 10); Marker waypoint = new Marker(trackId, contentProviderUtils.getLastValidTrackPoint(trackId)); waypoint.setDescription(TEST_DESC); Marker.Id waypointId = new Marker.Id(ContentUris.parseId(contentProviderUtils.insertMarker(waypoint))); assertEquals(TEST_DESC, contentProviderUtils.getMarker(waypointId).getDescription()); } /** * Tests the method {@link ContentProviderUtils#updateMarker(Context, Marker)}. */ @Test public void testUpdateWaypoint() { Track.Id trackId = new Track.Id(System.currentTimeMillis()); TestDataUtil.createTrackAndInsert(contentProviderUtils, trackId, 10); // Insert at first. Marker waypoint = new Marker(trackId, contentProviderUtils.getLastValidTrackPoint(trackId)); waypoint.setDescription(TEST_DESC); Marker.Id waypointId = new Marker.Id(ContentUris.parseId(contentProviderUtils.insertMarker(waypoint))); // Update waypoint = contentProviderUtils.getMarker(waypointId); waypoint.setDescription(TEST_DESC_NEW); contentProviderUtils.updateMarker(context, waypoint); assertEquals(TEST_DESC_NEW, contentProviderUtils.getMarker(waypointId).getDescription()); } /** * Tests the method {@link ContentProviderUtils#updateMarker(Context, Marker)}. */ @Test public void testUpdateWaypoint_withPhoto() throws IOException { // tests after update waypoint with photo the photo remains in the storage. Track.Id trackId = new Track.Id(System.currentTimeMillis()); TestDataUtil.createTrackAndInsert(contentProviderUtils, trackId, 10); // Insert at first. TrackPoint trackPoint = contentProviderUtils.getLastValidTrackPoint(trackId); Marker waypoint = TestDataUtil.createWaypointWithPhoto(context, trackId, trackPoint.getLocation()); waypoint.setDescription(TEST_DESC); Marker.Id waypointId = new Marker.Id(ContentUris.parseId(contentProviderUtils.insertMarker(waypoint))); File dir = new File(FileUtils.getPhotoDir(context), "" + trackId.getId()); assertTrue(dir.exists()); assertTrue(dir.isDirectory()); assertEquals(1, dir.list().length); // Update waypoint = contentProviderUtils.getMarker(waypointId); waypoint.setName(TEST_NAME_NEW); waypoint.setDescription(TEST_DESC_NEW); contentProviderUtils.updateMarker(context, waypoint); assertEquals(TEST_NAME_NEW, contentProviderUtils.getMarker(waypointId).getName()); assertEquals(TEST_DESC_NEW, contentProviderUtils.getMarker(waypointId).getDescription()); assertTrue(waypoint.hasPhoto()); assertTrue(dir.exists()); assertTrue(dir.isDirectory()); assertEquals(1, dir.list().length); } /** * Tests the method {@link ContentProviderUtils#updateMarker(Context, Marker)}. */ @Test public void testUpdateWaypoint_delPhotoAndDir() throws IOException { // tests after update waypoint if user deletes the photo then file photo is deleted from the storage. Also empty directory is deleted. Track.Id trackId = new Track.Id(System.currentTimeMillis()); TestDataUtil.createTrackAndInsert(contentProviderUtils, trackId, 10); // Insert at first. TrackPoint trackPoint = contentProviderUtils.getLastValidTrackPoint(trackId); Marker waypoint = TestDataUtil.createWaypointWithPhoto(context, trackId, trackPoint.getLocation()); waypoint.setDescription(TEST_DESC); Marker.Id waypointId = new Marker.Id(ContentUris.parseId(contentProviderUtils.insertMarker(waypoint))); File dir = new File(FileUtils.getPhotoDir(context), "" + trackId.getId()); assertTrue(dir.exists()); assertTrue(dir.isDirectory()); assertEquals(1, dir.list().length); // Update waypoint = contentProviderUtils.getMarker(waypointId); waypoint.setName(TEST_NAME_NEW); waypoint.setDescription(TEST_DESC_NEW); waypoint.setPhotoUrl(null); contentProviderUtils.updateMarker(context, waypoint); assertEquals(TEST_NAME_NEW, contentProviderUtils.getMarker(waypointId).getName()); assertEquals(TEST_DESC_NEW, contentProviderUtils.getMarker(waypointId).getDescription()); assertFalse(waypoint.hasPhoto()); assertFalse(dir.exists()); } /** * Tests the method {@link ContentProviderUtils#updateMarker(Context, Marker)}. */ @Test public void testUpdateWaypoint_delPhotoNotDir() throws IOException { // tests after update waypoint if user deletes the photo then file photo is deleted from the storage. Directory remains if there are more photos from other waypoints. Track.Id trackId = new Track.Id(System.currentTimeMillis()); TestDataUtil.createTrackAndInsert(contentProviderUtils, trackId, 10); // Insert two waypoints with photos. TrackPoint trackPoint = contentProviderUtils.getLastValidTrackPoint(trackId); Marker waypoint = TestDataUtil.createWaypointWithPhoto(context, trackId, trackPoint.getLocation()); waypoint.setDescription(TEST_DESC); Marker otherWaypoint = TestDataUtil.createWaypointWithPhoto(context, trackId, trackPoint.getLocation()); otherWaypoint.setDescription(TEST_DESC); Marker.Id waypointId = new Marker.Id(ContentUris.parseId(contentProviderUtils.insertMarker(waypoint))); contentProviderUtils.insertMarker(otherWaypoint); File dir = new File(FileUtils.getPhotoDir(context), "" + trackId.getId()); assertTrue(dir.exists()); assertTrue(dir.isDirectory()); assertEquals(2, dir.list().length); // Update one waypoint deleting photo. waypoint = contentProviderUtils.getMarker(waypointId); waypoint.setPhotoUrl(null); contentProviderUtils.updateMarker(context, waypoint); assertEquals(TEST_DESC, contentProviderUtils.getMarker(waypointId).getDescription()); assertFalse(waypoint.hasPhoto()); assertTrue(dir.exists()); assertTrue(dir.isDirectory()); assertEquals(1, dir.list().length); } /** * Tests the method {@link ContentProviderUtils#bulkInsertTrackPoint(TrackPoint[], Track.Id)}. */ @Test public void testBulkInsertTrackPoint() { // given Track.Id trackId = new Track.Id(System.currentTimeMillis()); Pair<Track, TrackPoint[]> track = TestDataUtil.createTrack(trackId, 10); TestDataUtil.insertTrackWithLocations(contentProviderUtils, track.first, track.second); // when / then contentProviderUtils.bulkInsertTrackPoint(track.second, trackId); assertEquals(20, contentProviderUtils.getTrackPointCursor(trackId, -1L, 1000, false).getCount()); contentProviderUtils.bulkInsertTrackPoint(Arrays.copyOfRange(track.second, 0, 8), trackId); assertEquals(28, contentProviderUtils.getTrackPointCursor(trackId, -1L, 1000, false).getCount()); } /** * Tests the method {@link ContentProviderUtils#createTrackPoint(Cursor)}. */ //TODO incomplete @Test public void testCreateTrackPoint() { // given when(cursorMock.getColumnIndex(TrackPointsColumns._ID)).thenReturn(1); when(cursorMock.getColumnIndexOrThrow(TrackPointsColumns.LONGITUDE)).thenReturn(2); when(cursorMock.isNull(2)).thenReturn(false); int longitude = 11; when(cursorMock.getInt(2)).thenReturn(longitude * 1000000); when(cursorMock.getColumnIndexOrThrow(TrackPointsColumns.LATITUDE)).thenReturn(3); when(cursorMock.isNull(3)).thenReturn(false); int latitude = 22; when(cursorMock.getInt(3)).thenReturn(latitude * 1000000); when(cursorMock.getColumnIndexOrThrow(TrackPointsColumns.TIME)).thenReturn(4); when(cursorMock.isNull(4)).thenReturn(false); long time = System.currentTimeMillis(); when(cursorMock.getLong(4)).thenReturn(time); when(cursorMock.getColumnIndexOrThrow(TrackPointsColumns.SPEED)).thenReturn(5); when(cursorMock.isNull(5)).thenReturn(false); float speed = 2.2f; when(cursorMock.getFloat(5)).thenReturn(speed); when(cursorMock.getColumnIndexOrThrow(TrackPointsColumns.SENSOR_HEARTRATE)).thenReturn(6); when(cursorMock.isNull(6)).thenReturn(false); // when TrackPoint trackPoint = contentProviderUtils.createTrackPoint(cursorMock); // then assertEquals(longitude, trackPoint.getLongitude(), 0.01); assertEquals(latitude, trackPoint.getLatitude(), 0.01); assertEquals(time, trackPoint.getTime(), 0.01); assertEquals(speed, trackPoint.getSpeed(), 0.01); assertFalse(trackPoint.hasHeartRate()); } /** * Tests the method * {@link ContentProviderUtils#insertTrackPoint(TrackPoint, Track.Id)}. */ @Test public void testInsertTrackPoint() { // Insert track, point at first. Track.Id trackId = new Track.Id(System.currentTimeMillis()); Track track = TestDataUtil.createTrackAndInsert(contentProviderUtils, trackId, 10); contentProviderUtils.insertTrackPoint(TestDataUtil.createTrackPoint(22), trackId); assertEquals(11, contentProviderUtils.getTrackPoints(trackId).size()); } @Test public void testInsertAndLoadTrackPoint() { // given Track.Id trackId = new Track.Id(System.currentTimeMillis()); Track track = TestDataUtil.createTrackAndInsert(contentProviderUtils, trackId, 10); TrackPoint trackPoint = TestDataUtil.createTrackPoint(5); trackPoint.setHeartRate_bpm(1F); trackPoint.setCyclingCadence_rpm(2F); trackPoint.setPower(3F); // when contentProviderUtils.insertTrackPoint(trackPoint, trackId); // then List<TrackPoint> trackPoints = contentProviderUtils.getTrackPoints(trackId); assertTrue(trackPoints.get(10).hasHeartRate()); assertEquals(trackPoint.getHeartRate_bpm(), trackPoints.get(10).getHeartRate_bpm(), 0.01); assertEquals(trackPoint.getCyclingCadence_rpm(), trackPoints.get(10).getCyclingCadence_rpm(), 0.01); assertEquals(trackPoint.getPower(), trackPoints.get(10).getPower(), 0.01); } /** * Tests the method {@link ContentProviderUtils#getLastValidTrackPoint(Track.Id)}. */ @Test public void testGetLastValidTrackPoint() { // Insert track, points at first. Track.Id trackId = new Track.Id(System.currentTimeMillis()); Track track = TestDataUtil.createTrackAndInsert(contentProviderUtils, trackId, 10); TrackPoint lastTrackPoint = contentProviderUtils.getLastValidTrackPoint(trackId); checkLocation(9, lastTrackPoint.getLocation()); } /** * Tests the method {@link ContentProviderUtils#getTrackPointCursor(Track.Id, long, int, boolean)} in descending. */ @Test public void testGetTrackPointCursor_desc() { // given Track.Id trackId = new Track.Id(System.currentTimeMillis()); Pair<Track, TrackPoint[]> track = TestDataUtil.createTrack(trackId, 10); contentProviderUtils.insertTrack(track.first); long[] trackpointIds = new long[track.second.length]; for (int i = 0; i < trackpointIds.length; i++) { trackpointIds[i] = ContentUris.parseId(contentProviderUtils.insertTrackPoint(track.second[i], track.first.getId())); } // when Cursor cursor = contentProviderUtils.getTrackPointCursor(trackId, trackpointIds[1], 5, true); // then assertEquals(2, cursor.getCount()); } /** * Tests the method {@link ContentProviderUtils#getTrackPointCursor(Track.Id, long, int, boolean)} in ascending. */ @Test public void testGetTrackPointCursor_asc() { // given Track.Id trackId = new Track.Id(System.currentTimeMillis()); Pair<Track, TrackPoint[]> track = TestDataUtil.createTrack(trackId, 10); contentProviderUtils.insertTrack(track.first); long[] trackpointIds = new long[track.second.length]; for (int i = 0; i < trackpointIds.length; i++) { trackpointIds[i] = ContentUris.parseId(contentProviderUtils.insertTrackPoint(track.second[i], track.first.getId())); } // when Cursor cursor = contentProviderUtils.getTrackPointCursor(trackId, trackpointIds[8], 5, false); // then assertEquals(2, cursor.getCount()); } /** * Tests the method {@link ContentProviderUtils#getTrackPointLocationIterator(Track.Id, long, boolean)} in descending. */ @Test public void testGetTrackPointLocationIterator_desc() { // given Track.Id trackId = new Track.Id(System.currentTimeMillis()); Pair<Track, TrackPoint[]> track = TestDataUtil.createTrack(trackId, 10); contentProviderUtils.insertTrack(track.first); long[] trackpointIds = new long[track.second.length]; for (int i = 0; i < trackpointIds.length; i++) { trackpointIds[i] = ContentUris.parseId(contentProviderUtils.insertTrackPoint(track.second[i], track.first.getId())); } long startTrackPointId = trackpointIds[9]; // when TrackPointIterator trackPointIterator = contentProviderUtils.getTrackPointLocationIterator(trackId, startTrackPointId, true); // then for (int i = 0; i < trackpointIds.length; i++) { assertTrue(trackPointIterator.hasNext()); TrackPoint trackPoint = trackPointIterator.next(); assertEquals(startTrackPointId - i, trackPointIterator.getTrackPointId()); checkLocation((trackpointIds.length - 1) - i, trackPoint.getLocation()); } assertFalse(trackPointIterator.hasNext()); } /** * Tests the method {@link ContentProviderUtils#getTrackPointLocationIterator(Track.Id, long, boolean)} in ascending. */ @Test public void testGetTrackPointLocationIterator_asc() { // given Track.Id trackId = new Track.Id(System.currentTimeMillis()); Pair<Track, TrackPoint[]> track = TestDataUtil.createTrack(trackId, 10); contentProviderUtils.insertTrack(track.first); long[] trackpointIds = new long[track.second.length]; for (int i = 0; i < trackpointIds.length; i++) { trackpointIds[i] = ContentUris.parseId(contentProviderUtils.insertTrackPoint(track.second[i], track.first.getId())); } long startTrackPointId = trackpointIds[0]; // when TrackPointIterator trackPointIterator = contentProviderUtils.getTrackPointLocationIterator(trackId, startTrackPointId, false); // then for (int i = 0; i < trackpointIds.length; i++) { assertTrue(trackPointIterator.hasNext()); TrackPoint trackPoint = trackPointIterator.next(); assertEquals(startTrackPointId + i, trackPointIterator.getTrackPointId()); checkLocation(i, trackPoint.getLocation()); } assertFalse(trackPointIterator.hasNext()); } /** * Checks the value of a location. * * @param i the index of this location which created in the method {@link TestDataUtil#createTrack(Track.Id, int)} * @param location the location to be checked */ private void checkLocation(int i, Location location) { assertEquals(TestDataUtil.INITIAL_LATITUDE + (double) i / 10000.0, location.getLatitude(), 0.01); assertEquals(TestDataUtil.INITIAL_LONGITUDE - (double) i / 10000.0, location.getLongitude(), 0.01); assertEquals((float) i / 100.0f, location.getAccuracy(), 0.01); assertEquals(i * TestDataUtil.ALTITUDE_INTERVAL, location.getAltitude(), 0.01); } @Test public void testFormatIdListForUri() { assertEquals("", ContentProviderUtils.formatIdListForUri()); assertEquals("12", ContentProviderUtils.formatIdListForUri(new Track.Id(12))); assertEquals("42,43,44", ContentProviderUtils.formatIdListForUri(new Track.Id(42), new Track.Id(43), new Track.Id(44))); } }
package tests.unit.com.microsoft.azure.sdk.iot.service; import com.microsoft.azure.sdk.iot.deps.serializer.ConfigurationContentParser; import com.microsoft.azure.sdk.iot.service.ConfigurationContent; import org.junit.Assert; import org.junit.Test; import java.util.HashMap; import java.util.Map; import static junit.framework.TestCase.assertEquals; public class ConfigurationContentTest { // Tests_SRS_SERVICE_SDK_JAVA_CONFIGURATION_METRICS_28_001: [The constructor shall initialize results and queries fields.] @Test public void constructor_initialize() { // Act ConfigurationContent cm = new ConfigurationContent(); // Assert Assert.assertNotNull(cm); Assert.assertNotNull(cm.getModulesContent()); Assert.assertNotNull(cm.getDeviceContent()); } // Tests_SRS_SERVICE_SDK_JAVA_CONFIGURATION_CONTENT_28_002: [The ConfigurationContent class shall have the following properties: modulesContent and deviceContent @Test public void getterAndSetter() { //arrange Map<String, Map<String, Object>> mc = new HashMap<String, Map<String, Object>>(){{put("mproperty", new HashMap<String, Object>(){{put("abc", "123"); put("cde", "456");}});}}; Map<String, Object> dc = new HashMap<String, Object>(){{put("dproperty", new HashMap<String, Integer>(){{put("c", 3);put("d", 4);}});}}; ConfigurationContent cc= new ConfigurationContent(); // Act cc.setDeviceContent(dc); cc.setModulesContent(mc); // Assert Assert.assertNotNull(cc); Map<String, Object> moduleContentMap = (cc.getModulesContent().get("mproperty")); assertEquals("123", moduleContentMap.get("abc")); assertEquals("456", moduleContentMap.get("cde")); Map<String, Object> deviceContentMap = ((Map<String,Object>)(cc.getDeviceContent().get("dproperty"))); assertEquals(3, deviceContentMap.get("c")); assertEquals(4, deviceContentMap.get("d")); } // Tests_SRS_SERVICE_SDK_JAVA_CONFIGURATION_CONTENT_34_003: [This function shall return a configuration parser instance with the same modules content and device content as this object.] @Test public void ToParserSuccess() { //arrange Map<String, Map<String, Object>> mc = new HashMap<String, Map<String, Object>>(){{put("mproperty", new HashMap<String, Object>(){{put("abc", "123"); put("cde", "456");}});}}; Map<String, Object> dc = new HashMap<String, Object>(){{put("dproperty", new HashMap<String, Integer>(){{put("c", 3);put("d", 4);}});}}; ConfigurationContent cc = new ConfigurationContent(); // act ConfigurationContentParser parser = cc.toConfigurationContentParser(); // assert assertEquals(cc.getDeviceContent(), parser.getDeviceContent()); assertEquals(cc.getModulesContent(), parser.getModulesContent()); } }
/* * Copyright 2014 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.samples.apps.iosched.ui; import android.app.ActionBar; import android.app.Fragment; import android.os.Bundle; import com.google.samples.apps.iosched.BuildConfig; import com.google.samples.apps.iosched.R; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import static com.google.samples.apps.iosched.util.LogUtils.makeLogTag; public class SocialActivity extends BaseActivity { private static final String TAG = makeLogTag(SocialActivity.class); private static final String SCREEN_LABEL = "Social"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (isFinishing()) { return; } setContentView(R.layout.activity_social); getLPreviewUtils().trySetActionBar(); if (null == savedInstanceState) { getFragmentManager().beginTransaction() .replace(R.id.container, createSocialFragment()) .commit(); } overridePendingTransition(0, 0); } private void updateActionBarNavigation() { boolean show = !isNavDrawerOpen(); if (getLPreviewUtils().shouldChangeActionBarForDrawer()) { ActionBar ab = getActionBar(); ab.setDisplayShowTitleEnabled(show); ab.setDisplayUseLogoEnabled(!show); } } protected Fragment createSocialFragment() { try { Method fragmentCreator = BuildConfig.SOCIAL_FRAGMENT_CLASS.getMethod("newInstance"); return (Fragment) fragmentCreator.invoke(null); } catch (NoSuchMethodException e) { throw new RuntimeException("Unable to create social fragment "+BuildConfig.SOCIAL_FRAGMENT_CLASS.getName(), e); } catch (InvocationTargetException e) { throw new RuntimeException("Unable to create social fragment "+BuildConfig.SOCIAL_FRAGMENT_CLASS.getName(), e); } catch (IllegalAccessException e) { throw new RuntimeException("Unable to create social fragment "+BuildConfig.SOCIAL_FRAGMENT_CLASS.getName(), e); } } @Override protected void onNavDrawerStateChanged(boolean isOpen, boolean isAnimating) { super.onNavDrawerStateChanged(isOpen, isAnimating); updateActionBarNavigation(); } @Override protected int getSelfNavDrawerItem() { return NAVDRAWER_ITEM_SOCIAL; } @Override protected void onResume() { super.onResume(); invalidateOptionsMenu(); } }
package ai.classifai.ui.component.os; public interface OS { boolean openLogInEditor(); boolean openBrowser(); }
package com.dazhuang.mall.product.entity; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import java.io.Serializable; import java.util.Date; import lombok.Data; /** * 品牌分类关联 * * @author dazhuangf * @email 1743460289@qq.com * @date 2021-08-02 14:22:45 */ @Data @TableName("pms_category_brand_relation") public class CategoryBrandRelationEntity implements Serializable { private static final long serialVersionUID = 1L; /** * */ @TableId private Long id; /** * 品牌id */ private Long brandId; /** * 分类id */ private Long catelogId; /** * */ private String brandName; /** * */ private String catelogName; }
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.client.ml.inference; import org.elasticsearch.Version; import org.elasticsearch.client.common.TimeUtil; import org.elasticsearch.common.ParseField; import org.elasticsearch.common.Strings; import org.elasticsearch.common.xcontent.ObjectParser; import org.elasticsearch.common.xcontent.ToXContentObject; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentParser; import java.io.IOException; import java.time.Instant; import java.util.Collections; import java.util.Map; import java.util.Objects; public class TrainedModelConfig implements ToXContentObject { public static final String NAME = "trained_model_doc"; public static final ParseField MODEL_ID = new ParseField("model_id"); public static final ParseField CREATED_BY = new ParseField("created_by"); public static final ParseField VERSION = new ParseField("version"); public static final ParseField DESCRIPTION = new ParseField("description"); public static final ParseField CREATED_TIME = new ParseField("created_time"); public static final ParseField MODEL_VERSION = new ParseField("model_version"); public static final ParseField DEFINITION = new ParseField("definition"); public static final ParseField MODEL_TYPE = new ParseField("model_type"); public static final ParseField METADATA = new ParseField("metadata"); public static final ObjectParser<Builder, Void> PARSER = new ObjectParser<>(NAME, true, TrainedModelConfig.Builder::new); static { PARSER.declareString(TrainedModelConfig.Builder::setModelId, MODEL_ID); PARSER.declareString(TrainedModelConfig.Builder::setCreatedBy, CREATED_BY); PARSER.declareString(TrainedModelConfig.Builder::setVersion, VERSION); PARSER.declareString(TrainedModelConfig.Builder::setDescription, DESCRIPTION); PARSER.declareField(TrainedModelConfig.Builder::setCreatedTime, (p, c) -> TimeUtil.parseTimeFieldToInstant(p, CREATED_TIME.getPreferredName()), CREATED_TIME, ObjectParser.ValueType.VALUE); PARSER.declareLong(TrainedModelConfig.Builder::setModelVersion, MODEL_VERSION); PARSER.declareString(TrainedModelConfig.Builder::setModelType, MODEL_TYPE); PARSER.declareObject(TrainedModelConfig.Builder::setMetadata, (p, c) -> p.map(), METADATA); PARSER.declareObject(TrainedModelConfig.Builder::setDefinition, (p, c) -> TrainedModelDefinition.fromXContent(p), DEFINITION); } public static TrainedModelConfig.Builder fromXContent(XContentParser parser) throws IOException { return PARSER.parse(parser, null); } private final String modelId; private final String createdBy; private final Version version; private final String description; private final Instant createdTime; private final Long modelVersion; private final String modelType; private final Map<String, Object> metadata; private final TrainedModelDefinition definition; TrainedModelConfig(String modelId, String createdBy, Version version, String description, Instant createdTime, Long modelVersion, String modelType, TrainedModelDefinition definition, Map<String, Object> metadata) { this.modelId = modelId; this.createdBy = createdBy; this.version = version; this.createdTime = Instant.ofEpochMilli(createdTime.toEpochMilli()); this.modelType = modelType; this.definition = definition; this.description = description; this.metadata = metadata == null ? null : Collections.unmodifiableMap(metadata); this.modelVersion = modelVersion; } public String getModelId() { return modelId; } public String getCreatedBy() { return createdBy; } public Version getVersion() { return version; } public String getDescription() { return description; } public Instant getCreatedTime() { return createdTime; } public Long getModelVersion() { return modelVersion; } public String getModelType() { return modelType; } public Map<String, Object> getMetadata() { return metadata; } public TrainedModelDefinition getDefinition() { return definition; } public static Builder builder() { return new Builder(); } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { builder.startObject(); if (modelId != null) { builder.field(MODEL_ID.getPreferredName(), modelId); } if (createdBy != null) { builder.field(CREATED_BY.getPreferredName(), createdBy); } if (version != null) { builder.field(VERSION.getPreferredName(), version.toString()); } if (description != null) { builder.field(DESCRIPTION.getPreferredName(), description); } if (createdTime != null) { builder.timeField(CREATED_TIME.getPreferredName(), CREATED_TIME.getPreferredName() + "_string", createdTime.toEpochMilli()); } if (modelVersion != null) { builder.field(MODEL_VERSION.getPreferredName(), modelVersion); } if (modelType != null) { builder.field(MODEL_TYPE.getPreferredName(), modelType); } if (definition != null) { builder.field(DEFINITION.getPreferredName(), definition); } if (metadata != null) { builder.field(METADATA.getPreferredName(), metadata); } builder.endObject(); return builder; } @Override public String toString() { return Strings.toString(this); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; TrainedModelConfig that = (TrainedModelConfig) o; return Objects.equals(modelId, that.modelId) && Objects.equals(createdBy, that.createdBy) && Objects.equals(version, that.version) && Objects.equals(description, that.description) && Objects.equals(createdTime, that.createdTime) && Objects.equals(modelVersion, that.modelVersion) && Objects.equals(modelType, that.modelType) && Objects.equals(definition, that.definition) && Objects.equals(metadata, that.metadata); } @Override public int hashCode() { return Objects.hash(modelId, createdBy, version, createdTime, modelType, definition, description, metadata, modelVersion); } public static class Builder { private String modelId; private String createdBy; private Version version; private String description; private Instant createdTime; private Long modelVersion; private String modelType; private Map<String, Object> metadata; private TrainedModelDefinition.Builder definition; public Builder setModelId(String modelId) { this.modelId = modelId; return this; } private Builder setCreatedBy(String createdBy) { this.createdBy = createdBy; return this; } private Builder setVersion(Version version) { this.version = version; return this; } private Builder setVersion(String version) { return this.setVersion(Version.fromString(version)); } public Builder setDescription(String description) { this.description = description; return this; } private Builder setCreatedTime(Instant createdTime) { this.createdTime = createdTime; return this; } public Builder setModelVersion(Long modelVersion) { this.modelVersion = modelVersion; return this; } public Builder setModelType(String modelType) { this.modelType = modelType; return this; } public Builder setMetadata(Map<String, Object> metadata) { this.metadata = metadata; return this; } public Builder setDefinition(TrainedModelDefinition.Builder definition) { this.definition = definition; return this; } public TrainedModelConfig build() { return new TrainedModelConfig( modelId, createdBy, version, description, createdTime, modelVersion, modelType, definition == null ? null : definition.build(), metadata); } } }
// // Author: Yves Lafon <ylafon@w3.org> // // (c) COPYRIGHT MIT, ERCIM, Keio University, Beihang, 2012. // Please first read the full copyright statement in file COPYRIGHT.html package org.w3c.css.properties.css3; import org.w3c.css.util.ApplContext; import org.w3c.css.util.InvalidParamException; import org.w3c.css.values.CssExpression; import org.w3c.css.values.CssIdent; import org.w3c.css.values.CssTypes; import org.w3c.css.values.CssValue; import org.w3c.css.values.CssValueList; import java.util.ArrayList; /** * @spec https://www.w3.org/TR/2021/CRD-css-text-3-20210422/#propdef-text-indent */ public class CssTextIndent extends org.w3c.css.properties.css.CssTextIndent { public static final CssIdent hanging, each_line; static { hanging = CssIdent.getIdent("hanging"); each_line = CssIdent.getIdent("each-line"); } /** * Create a new CssTextIndent */ public CssTextIndent() { value = initial; } /** * Creates a new CssTextIndent * * @param expression The expression for this property * @throws org.w3c.css.util.InvalidParamException Expressions are incorrect */ public CssTextIndent(ApplContext ac, CssExpression expression, boolean check) throws InvalidParamException { if (check && expression.getCount() > 3) { throw new InvalidParamException("unrecognize", ac); } setByUser(); CssValue val; char op; CssValue sizeVal = null; CssValue hangVal = null; CssValue eachVal = null; value = null; while (!expression.end()) { val = expression.getValue(); op = expression.getOperator(); switch (val.getType()) { case CssTypes.CSS_NUMBER: val.getLength(); case CssTypes.CSS_LENGTH: case CssTypes.CSS_PERCENTAGE: if (sizeVal != null) { throw new InvalidParamException("value", val.toString(), getPropertyName(), ac); } sizeVal = val; // we check that we are at the beginning or at the end // as it can't happen between two idents. if ((hangVal != null || eachVal != null) && expression.getRemainingCount() > 1) { // TODO specific error (can't happen between...) throw new InvalidParamException("value", val.toString(), getPropertyName(), ac); } break; case CssTypes.CSS_IDENT: CssIdent ident = val.getIdent(); if (CssIdent.isCssWide(ident)) { value = val; if (check && expression.getCount() > 1) { throw new InvalidParamException("unrecognize", ac); } break; } if (hangVal == null && hanging.equals(ident)) { hangVal = val; break; } if (eachVal == null && each_line.equals(ident)) { eachVal = val; break; } default: throw new InvalidParamException("value", expression.getValue().toString(), getPropertyName(), ac); } expression.next(); } // sanity check, we must have a length or percentage if (value == null) { if (sizeVal == null) { throw new InvalidParamException("value", expression.toString(), getPropertyName(), ac); } if (expression.getCount() == 1) { value = sizeVal; } else { ArrayList<CssValue> v = new ArrayList<>(4); v.add(sizeVal); if (hangVal != null) { v.add(hangVal); } if (eachVal != null) { v.add(eachVal); } value = new CssValueList(v); } } } public CssTextIndent(ApplContext ac, CssExpression expression) throws InvalidParamException { this(ac, expression, false); } }
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1 begin_comment comment|/* * 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. */ end_comment begin_package DECL|package|org.apache.camel.test.patterns package|package name|org operator|. name|apache operator|. name|camel operator|. name|test operator|. name|patterns package|; end_package begin_comment comment|/** * */ end_comment begin_interface DECL|interface|MySender specifier|public interface|interface name|MySender block|{ DECL|method|send (String body) name|void name|send parameter_list|( name|String name|body parameter_list|) function_decl|; block|} end_interface end_unit
/* * Copyright 1999-2015 dangdang.com. * <p> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * </p> */ package com.dangdang.ddframe.job.lite.spring; import com.dangdang.ddframe.job.lite.spring.job.AllSpringIntegrateTests; import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; @RunWith(Suite.class) @SuiteClasses(AllSpringIntegrateTests.class) public final class AllLiteSpringTests { }
package hmm; public enum Direction { North(0, -1), West(-1, 0), South(0, 1), East(1, 0); private Direction opposite; public final int dx, dy; static { North.opposite = South; South.opposite = North; West.opposite = East; East.opposite = West; } Direction(int dx, int dy) { this.dx = dx; this.dy = dy; } public Direction opposite() { return opposite; } public String toString() { return name(); } }
/* * Copyright 2016-2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.cloudfront.model.transform; import javax.xml.stream.events.XMLEvent; import javax.annotation.Generated; import com.amazonaws.services.cloudfront.model.*; import com.amazonaws.transform.Unmarshaller; import com.amazonaws.transform.StaxUnmarshallerContext; import com.amazonaws.transform.SimpleTypeStaxUnmarshallers.*; /** * GetFieldLevelEncryptionConfigResult StAX Unmarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class GetFieldLevelEncryptionConfigResultStaxUnmarshaller implements Unmarshaller<GetFieldLevelEncryptionConfigResult, StaxUnmarshallerContext> { public GetFieldLevelEncryptionConfigResult unmarshall(StaxUnmarshallerContext context) throws Exception { GetFieldLevelEncryptionConfigResult getFieldLevelEncryptionConfigResult = new GetFieldLevelEncryptionConfigResult(); int originalDepth = context.getCurrentDepth(); int targetDepth = originalDepth + 1; if (context.isStartOfDocument()) { context.setCurrentHeader("ETag"); getFieldLevelEncryptionConfigResult.setETag(StringStaxUnmarshaller.getInstance().unmarshall(context)); } while (true) { XMLEvent xmlEvent = context.nextEvent(); if (xmlEvent.isEndDocument()) return getFieldLevelEncryptionConfigResult; if (xmlEvent.isAttribute() || xmlEvent.isStartElement()) { if (context.testExpression("FieldLevelEncryptionConfig", targetDepth)) { getFieldLevelEncryptionConfigResult.setFieldLevelEncryptionConfig(FieldLevelEncryptionConfigStaxUnmarshaller.getInstance().unmarshall( context)); continue; } } else if (xmlEvent.isEndElement()) { if (context.getCurrentDepth() < originalDepth) { return getFieldLevelEncryptionConfigResult; } } } } private static GetFieldLevelEncryptionConfigResultStaxUnmarshaller instance; public static GetFieldLevelEncryptionConfigResultStaxUnmarshaller getInstance() { if (instance == null) instance = new GetFieldLevelEncryptionConfigResultStaxUnmarshaller(); return instance; } }
import java.io.*; import java.util.*; /** * Expander is the class handling expansions of strings. It recognizes * ${X} and ${=X} sequences. Detection of sequences are not fast at the * moment. * * @author Brian Schau * @since 0.1 */ public class Expander { private Properties properties; private PathManager pMan; private StringBuffer sBuf; /** * Set up Expander * * @param p Properties to retrieve macros from. * @param m Path Manager. */ public Expander(Properties p, PathManager m) { properties=p; pMan=m; sBuf=new StringBuffer(2048); } /** * Find and expand any macros from the string. * * @param in String to expand. * @return Possibly expanded string. */ public String Expand(String in) { String v; int begin, end; if (in==null) return null; if ((begin=in.lastIndexOf("${"))==-1) return in; if ((end=in.indexOf("}", begin+2))==-1) return in; if (in.charAt(begin+2)=='=') v=ExpandCommand(in.substring(begin+3, end)); else if (in.charAt(begin+2)=='@') v=ExpandFile(in.substring(begin+3, end)); else if (in.charAt(begin+2)=='$') v=ExpandSysVariable(in.substring(begin+3, end)); else v=ExpandVariable(in.substring(begin+2, end)); if (v==null) return null; return Expand(in.substring(0, begin)+v+in.substring(end+1)); } /** * Handle ${X} sequence. */ private String ExpandVariable(String key) { String v; if ((v=properties.getProperty(key))==null) { System.err.println("Unknown property, "+key); return null; } return v; } /** * Handle ${@X} sequence. */ private String ExpandFile(String file) { String s; sBuf.setLength(0); try { BufferedReader r=new BufferedReader(new FileReader(pMan.FullPath(file, true))); String term=""; while ((s=r.readLine())!=null) { sBuf.append(term).append(s); term=pMan.lineSeparator; } r.close(); } catch (Exception ex) { System.err.println("Cannot read file "+file); System.exit(1); } return sBuf.toString(); } /** * Handle ${=X} sequence. */ private String ExpandCommand(String cmd) { ProcessManager pp=new ProcessManager(); String v; int retCode; if ((retCode=pp.Run(cmd))!=0) { System.err.println("Command returned "+retCode); System.err.println("Output from command: "+pp.Messages()); return null; } v=pp.Messages(); if (v==null || v.length()==0) { System.err.println("No output from command, "+cmd); return null; } return v; } /** * Handle ${$X} sequence. */ private String ExpandSysVariable(String key) { String v; if ((v=System.getProperty(key))==null) { System.err.println("Unknown property, "+key); return null; } return v; } }
// File: Trap.java // Purpose: Calculate area using trapezoidal rule // // Input: a: left endpoint of interval // b: right endpoint of interval // n: number of trapezoids // Output: estimate of area between the x-axis, x = a, x = b, and // the graph of f(x) using n trapezoids // // Compile: javac Trap.java // Usage: java Trap // // Notes: f(x) is hardwired as a private static member. import java.util.Scanner; public class Trap { public static void main(String args[]) { double area; // Store result in area double a, b; // Left and right endpoints int n; // Number of trapezoids double h; // Trapezoid base width Scanner sc = new Scanner(System.in); System.out.println("Enter a, b, and n"); a = sc.nextDouble(); b = sc.nextDouble(); n = sc.nextInt(); h = (b-a)/n; area = trap(a, b, n, h); System.out.println("With n = " + n + " trapezoids, our estimate"); System.out.print("of the area from " + a + " to " + b); System.out.println(" = " + area); } // main // Method: trap // Purpose: Estimate area using the trapezoidal rule // Input args: a: left endpoint // b: right endpoint // n: number of trapezoids // h: stepsize = length of base of trapezoids // Return val: Trapezoidal rule estimate of area between x-axis, // x = a, x = b, and graph of f(x) // Note: Need *static* so trap can be called from main without // instantiating an object static double trap(double a, double b, int n, double h) { double area; // Store result in area double x; int i; area = (f(a) + f(b))/2.0; for (i = 1; i <= n-1; i++) { x = a + i*h; area = area + f(x); } area = area*h; return area; } // trap // Method: f // Purpose: Compute value of function being integrated // Input arg: x // Note: Need *static* so f can be called from trap without // instantiating an object static double f(double x) { double return_val; return_val = x*x + 1; return return_val; } // f } // class Trap
/* * Copyright 2013-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.cloud.contract.verifier.util; import static org.apache.commons.lang3.StringEscapeUtils.escapeJava; import java.util.LinkedList; import java.util.regex.Pattern; import com.toomuchcoding.jsonassert.JsonVerifiable; /** * Implementation of the {@link MethodBufferingJsonVerifiable} that contains a list * of String method commands that need to be executed to assert JSONs. * * @author Marcin Grzejszczak * * @since 1.0.0 */ class DelegatingJsonVerifiable implements MethodBufferingJsonVerifiable { private static final Pattern FIELD_PATTERN = Pattern.compile("\\.field\\((\")?(.)+(\")?\\)"); private static final Pattern ARRAY_PATTERN = Pattern.compile("\\.array\\((\")?(.)+(\")?\\)"); final JsonVerifiable delegate; final LinkedList<String> methodsBuffer; DelegatingJsonVerifiable(JsonVerifiable delegate, LinkedList<String> methodsBuffer) { this.delegate = delegate; this.methodsBuffer = new LinkedList<>(methodsBuffer); } DelegatingJsonVerifiable(JsonVerifiable delegate) { this.delegate = delegate; this.methodsBuffer = new LinkedList<>(); } private static String stringWithEscapedQuotes(Object object) { String stringValue = object.toString(); return stringValue.replaceAll("\"", "\\\\\""); } private static String wrapValueWithQuotes(Object value) { return value instanceof String ? "\"" + stringWithEscapedQuotes(value) + "\"" : value.toString(); } private void appendMethodWithValue(String methodName, Object value) { this.methodsBuffer.offer("." + methodName + "(" + value + ")"); } private void appendMethodWithQuotedValue(String methodName, Object value) { appendMethodWithValue(methodName, wrapValueWithQuotes(value)); } @Override public MethodBufferingJsonVerifiable contains(Object value) { DelegatingJsonVerifiable verifiable = new FinishedDelegatingJsonVerifiable(this.delegate.contains(value), this.methodsBuffer); verifiable.appendMethodWithQuotedValue("contains", value); if (isAssertingAValueInArray()) { verifiable.methodsBuffer.offer(".value()"); } return verifiable; } @Override public MethodBufferingJsonVerifiable field(Object value) { Object valueToPut = value instanceof ShouldTraverse ? ((ShouldTraverse) value).value : value; DelegatingJsonVerifiable verifiable = new DelegatingJsonVerifiable(this.delegate.field(valueToPut), this.methodsBuffer); if (this.delegate.isIteratingOverArray() && !(value instanceof ShouldTraverse)) { verifiable.appendMethodWithQuotedValue("contains", valueToPut); } else { verifiable.appendMethodWithQuotedValue("field", valueToPut); } return verifiable; } @Override public MethodBufferingJsonVerifiable field(String... strings) { MethodBufferingJsonVerifiable verifiable = null; for (String string : strings) { verifiable = verifiable == null ? field(string) : verifiable.field(string); } return verifiable; } @Override public MethodBufferingJsonVerifiable array(Object value) { DelegatingJsonVerifiable verifiable = new DelegatingJsonVerifiable(this.delegate.array(value), this.methodsBuffer); verifiable.appendMethodWithQuotedValue("array", value); return verifiable; } @Override public MethodBufferingJsonVerifiable arrayField(Object value) { DelegatingJsonVerifiable verifiable = new DelegatingJsonVerifiable(this.delegate.field(value).arrayField(), this.methodsBuffer); verifiable.appendMethodWithQuotedValue("array", value); return verifiable; } @Override public MethodBufferingJsonVerifiable arrayField() { DelegatingJsonVerifiable verifiable = new DelegatingJsonVerifiable(this.delegate.arrayField(), this.methodsBuffer); verifiable.methodsBuffer.offer(".arrayField()"); return verifiable; } @Override public MethodBufferingJsonVerifiable array() { DelegatingJsonVerifiable verifiable = new DelegatingJsonVerifiable(this.delegate.array(), this.methodsBuffer); verifiable.methodsBuffer.offer(".array()"); return verifiable; } @Override public JsonVerifiable elementWithIndex(int i) { DelegatingJsonVerifiable verifiable = new DelegatingJsonVerifiable(this.delegate.elementWithIndex(i), this.methodsBuffer); this.methodsBuffer.offer(".elementWithIndex(" + i + ")"); return verifiable; } @Override public MethodBufferingJsonVerifiable iterationPassingArray() { return new DelegatingJsonVerifiable(this.delegate, this.methodsBuffer); } @Override public MethodBufferingJsonVerifiable isEqualTo(String value) { DelegatingJsonVerifiable readyToCheck = new FinishedDelegatingJsonVerifiable(this.delegate.isEqualTo(value), this.methodsBuffer); if (this.delegate.isAssertingAValueInArray() && readyToCheck.methodsBuffer.peekLast().equals(".arrayField()")) { readyToCheck.appendMethodWithQuotedValue("isEqualTo", escapeJava(value)); readyToCheck.methodsBuffer.offer(".value()"); } else if (this.delegate.isAssertingAValueInArray() && !readyToCheck.methodsBuffer.peekLast().contains("array")) { readyToCheck.methodsBuffer.offer(".value()"); } else { readyToCheck.appendMethodWithQuotedValue("isEqualTo", escapeJava(value)); } return readyToCheck; } @Override public MethodBufferingJsonVerifiable isEqualTo(Object value) { if (value == null) { return isNull(); } return isEqualTo(value.toString()); } @Override public MethodBufferingJsonVerifiable isEqualTo(Number value) { DelegatingJsonVerifiable readyToCheck = new FinishedDelegatingJsonVerifiable(this.delegate.isEqualTo(value), this.methodsBuffer); // related to #271 - the problem is with asserting arrays of maps vs arrays of primitives String last = readyToCheck.methodsBuffer.peekLast(); boolean containsAMatcher = containsAnyMatcher(last); if (this.delegate.isAssertingAValueInArray() && containsAMatcher) { readyToCheck.methodsBuffer.offer(".value()"); } else { readyToCheck.appendMethodWithValue("isEqualTo", String.valueOf(value)); } return readyToCheck; } private boolean containsAnyMatcher(String string) { return string.contains("isEqualTo") || string.contains("matches") || string.contains("isNull"); } @Override public MethodBufferingJsonVerifiable isNull() { DelegatingJsonVerifiable readyToCheck = new FinishedDelegatingJsonVerifiable(this.delegate.isNull(), this.methodsBuffer); readyToCheck.methodsBuffer.offer(".isNull()"); return readyToCheck; } @Override public MethodBufferingJsonVerifiable isEmpty() { DelegatingJsonVerifiable readyToCheck = new FinishedDelegatingJsonVerifiable(this.delegate.isEmpty(), this.methodsBuffer); readyToCheck.methodsBuffer.offer(".isEmpty()"); return readyToCheck; } @Override public MethodBufferingJsonVerifiable matches(String value) { DelegatingJsonVerifiable readyToCheck = new FinishedDelegatingJsonVerifiable(this.delegate.matches(value), this.methodsBuffer); if (this.delegate.isAssertingAValueInArray()) { readyToCheck.appendMethodWithQuotedValue("matches", escapedHackedJavaText(value)); readyToCheck.methodsBuffer.offer(".value()"); } else { readyToCheck.appendMethodWithQuotedValue("matches", escapedHackedJavaText(value)); } return readyToCheck; } /** * We need to escape the pattern in order for the produced text to be compilable. * The problem is that sometimes we get quotes that already escaped. If we escape them * we get code that doesn't compile. That's why we're doing this hack to unescape * an double escaped text. Related to https://github.com/spring-cloud/spring-cloud-contract/issues/169 */ private String escapedHackedJavaText(String value) { return escapeJava(value) .replace("\\\"", "\""); } @Override public MethodBufferingJsonVerifiable isEqualTo(Boolean value) { DelegatingJsonVerifiable readyToCheck = new FinishedDelegatingJsonVerifiable(this.delegate.isEqualTo(value), this.methodsBuffer); if (this.delegate.isAssertingAValueInArray()) { readyToCheck.methodsBuffer.offer(".value()"); } else { readyToCheck.appendMethodWithValue("isEqualTo", String.valueOf(value)); } return readyToCheck; } @Override public MethodBufferingJsonVerifiable value() { return new FinishedDelegatingJsonVerifiable(this.delegate, this.methodsBuffer); } @Override public boolean assertsSize() { for (String s : this.methodsBuffer) { if (s.contains(".hasSize(") || s.contains(".isEmpty()")) { return true; } } return false; } @Override public boolean assertsConcreteValue() { for (String s : this.methodsBuffer) { if (FIELD_PATTERN.matcher(s).matches()|| ARRAY_PATTERN.matcher(s).matches()) { return true; } } return false; } @Override public JsonVerifiable withoutThrowingException() { return this.delegate.withoutThrowingException(); } @Override public String jsonPath() { return this.delegate.jsonPath(); } @Override public void matchesJsonPath(String s) { this.delegate.matchesJsonPath(s); } @Override public JsonVerifiable hasSize(int size) { FinishedDelegatingJsonVerifiable verifiable = new FinishedDelegatingJsonVerifiable(this.delegate.hasSize(size), this.methodsBuffer); verifiable.methodsBuffer.offer(".hasSize(" + size + ")"); return verifiable; } @Override public boolean isIteratingOverNamelessArray() { return this.delegate.isIteratingOverNamelessArray(); } @Override public boolean isIteratingOverArray() { return this.delegate.isIteratingOverArray(); } @Override public boolean isAssertingAValueInArray() { return this.delegate.isAssertingAValueInArray(); } @Override public String method() { return createMethodString(); } private String createMethodString() { LinkedList<String> queue = new LinkedList<>(this.methodsBuffer); StringBuilder stringBuffer = new StringBuilder(); while (!queue.isEmpty()) { stringBuffer.append(queue.remove()); } return stringBuffer.toString(); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; DelegatingJsonVerifiable that = (DelegatingJsonVerifiable) o; if (this.delegate != null ? !this.delegate.equals(that.delegate) : that.delegate != null) return false; if (this.delegate == null) { return false; } if (this.delegate.jsonPath() == null && that.delegate.jsonPath() == null) return true; return this.delegate.jsonPath().equals(that.delegate.jsonPath()); } @Override public int hashCode() { int result = this.delegate != null ? this.delegate.jsonPath().hashCode() : 0; return 31 * result; } @Override public String toString() { return "DelegatingJsonVerifiable{" + "delegate=\n" + this.delegate + ", methodsBuffer=" + this.methodsBuffer + '}'; } @Override public <T> T read(Class<T> aClass) { return this.delegate.read(aClass); } }
package de.metas.ui.web.session; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationListener; import org.springframework.session.events.SessionDestroyedEvent; import org.springframework.stereotype.Component; import de.metas.ui.web.notification.UserNotificationsService; /* * #%L * metasfresh-webui-api * %% * Copyright (C) 2018 metas GmbH * %% * 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 2 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/gpl-2.0.html>. * #L% */ @Component public class SessionDestroyedListener implements ApplicationListener<SessionDestroyedEvent> { @Autowired private UserNotificationsService userNotificationsService; @Override public void onApplicationEvent(final SessionDestroyedEvent event) { final String sessionId = event.getSessionId(); userNotificationsService.disableForSession(sessionId); } }
/* * SPDX-License-Identifier: Apache-2.0 * * The OpenSearch Contributors require contributions made to * this file be licensed under the Apache-2.0 license or a * compatible open source license. * * Modifications Copyright OpenSearch Contributors. See * GitHub history for details. */ package org.opensearch.knn.plugin.transport; import org.opensearch.action.ActionRequest; import org.opensearch.action.ActionRequestValidationException; import org.opensearch.common.Strings; import org.opensearch.common.io.stream.StreamInput; import org.opensearch.common.io.stream.StreamOutput; import java.io.IOException; import static org.opensearch.action.ValidateActions.addValidationError; public class DeleteModelRequest extends ActionRequest { private String modelID; public DeleteModelRequest(StreamInput in) throws IOException { super(in); this.modelID = in.readString(); } public DeleteModelRequest(String modelID) { super(); this.modelID = modelID; } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); out.writeString(modelID); } @Override public ActionRequestValidationException validate() { if (Strings.hasText(modelID)) { return null; } return addValidationError("Model id cannot be empty ", null); } public String getModelID() { return modelID; } }
package it; import com.atlassian.confluence.plugin.functest.AbstractConfluencePluginWebTestCase; import com.atlassian.confluence.plugin.functest.JWebUnitConfluenceWebTester; import com.atlassian.confluence.plugin.functest.TesterConfiguration; import junit.framework.Assert; import java.io.IOException; import java.util.Properties; public class AbstractIntegrationTestCase extends AbstractConfluencePluginWebTestCase { @Override protected JWebUnitConfluenceWebTester createConfluenceWebTester() { Properties props = new Properties(); props.put("confluence.webapp.protocol", "http"); props.put("confluence.webapp.host", "localhost"); // this is deceiving: the func test library checks for the system properties // *before* checking in this properties file for these values, so these // properties are technically ignored props.put("confluence.webapp.port", Integer.parseInt(System.getProperty("http.port"))); props.put("confluence.webapp.context.path", System.getProperty("context.path")); props.put("confluence.auth.admin.username", "admin"); props.put("confluence.auth.admin.password", "admin"); TesterConfiguration conf; try { conf = new TesterConfiguration(props); } catch (IOException ioe) { Assert.fail("Unable to create tester: " + ioe.getMessage()); return null; } JWebUnitConfluenceWebTester tester = new JWebUnitConfluenceWebTester(conf); tester.getTestContext().setBaseUrl(tester.getBaseUrl()); tester.setScriptingEnabled(false); return tester; } }
package com.google.codeu.servlets; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.google.appengine.api.users.UserService; import com.google.appengine.api.users.UserServiceFactory; /** * Handles fetching and saving user data. */ @WebServlet("/navbar") public final class NavBarServlet extends HttpServlet { @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/html"); request.getRequestDispatcher("/navbar.jsp").forward(request,response); } }
/* * Copyright (c) 2007, 2021, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. */ /* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.sun.org.apache.xalan.internal.xsltc.compiler.util; import java.util.ListResourceBundle; /** * @author Morten Jorgensen */ public class ErrorMessages_zh_TW extends ListResourceBundle { /* * XSLTC compile-time error messages. * * General notes to translators and definitions: * * 1) XSLTC is the name of the product. It is an acronym for "XSLT Compiler". * XSLT is an acronym for "XML Stylesheet Language: Transformations". * * 2) A stylesheet is a description of how to transform an input XML document * into a resultant XML document (or HTML document or text). The * stylesheet itself is described in the form of an XML document. * * 3) A template is a component of a stylesheet that is used to match a * particular portion of an input document and specifies the form of the * corresponding portion of the output document. * * 4) An axis is a particular "dimension" in a tree representation of an XML * document; the nodes in the tree are divided along different axes. * Traversing the "child" axis, for instance, means that the program * would visit each child of a particular node; traversing the "descendant" * axis means that the program would visit the child nodes of a particular * node, their children, and so on until the leaf nodes of the tree are * reached. * * 5) An iterator is an object that traverses nodes in a tree along a * particular axis, one at a time. * * 6) An element is a mark-up tag in an XML document; an attribute is a * modifier on the tag. For example, in <elem attr='val' attr2='val2'> * "elem" is an element name, "attr" and "attr2" are attribute names with * the values "val" and "val2", respectively. * * 7) A namespace declaration is a special attribute that is used to associate * a prefix with a URI (the namespace). The meanings of element names and * attribute names that use that prefix are defined with respect to that * namespace. * * 8) DOM is an acronym for Document Object Model. It is a tree * representation of an XML document. * * SAX is an acronym for the Simple API for XML processing. It is an API * used inform an XML processor (in this case XSLTC) of the structure and * content of an XML document. * * Input to the stylesheet processor can come from an XML parser in the * form of a DOM tree or through the SAX API. * * 9) DTD is a document type declaration. It is a way of specifying the * grammar for an XML file, the names and types of elements, attributes, * etc. * * 10) XPath is a specification that describes a notation for identifying * nodes in a tree-structured representation of an XML document. An * instance of that notation is referred to as an XPath expression. * * 11) Translet is an invented term that refers to the class file that contains * the compiled form of a stylesheet. */ // These message should be read from a locale-specific resource bundle /** Get the lookup table for error messages. * * @return The message lookup table. */ public Object[][] getContents() { return new Object[][] { {ErrorMsg.MULTIPLE_STYLESHEET_ERR, "\u76F8\u540C\u6A94\u6848\u4E2D\u5B9A\u7FA9\u4E86\u8D85\u904E\u4E00\u500B\u6A23\u5F0F\u8868\u3002"}, /* * Note to translators: The substitution text is the name of a * template. The same name was used on two different templates in the * same stylesheet. */ {ErrorMsg.TEMPLATE_REDEF_ERR, "\u6A23\u677F ''{0}'' \u5DF2\u7D93\u5B9A\u7FA9\u5728\u6B64\u6A23\u5F0F\u8868\u4E2D\u3002"}, /* * Note to translators: The substitution text is the name of a * template. A reference to the template name was encountered, but the * template is undefined. */ {ErrorMsg.TEMPLATE_UNDEF_ERR, "\u6A23\u677F ''{0}'' \u672A\u5B9A\u7FA9\u5728\u6B64\u6A23\u5F0F\u8868\u4E2D\u3002"}, /* * Note to translators: The substitution text is the name of a variable * that was defined more than once. */ {ErrorMsg.VARIABLE_REDEF_ERR, "\u8B8A\u6578 ''{0}'' \u5728\u76F8\u540C\u7BC4\u570D\u4E2D\u5B9A\u7FA9\u591A\u6B21\u3002"}, /* * Note to translators: The substitution text is the name of a variable * or parameter. A reference to the variable or parameter was found, * but it was never defined. */ {ErrorMsg.VARIABLE_UNDEF_ERR, "\u8B8A\u6578\u6216\u53C3\u6578 ''{0}'' \u672A\u5B9A\u7FA9\u3002"}, /* * Note to translators: The word "class" here refers to a Java class. * Processing the stylesheet required a class to be loaded, but it could * not be found. The substitution text is the name of the class. */ {ErrorMsg.CLASS_NOT_FOUND_ERR, "\u627E\u4E0D\u5230\u985E\u5225 ''{0}''\u3002"}, /* * Note to translators: The word "method" here refers to a Java method. * Processing the stylesheet required a reference to the method named by * the substitution text, but it could not be found. "public" is the * Java keyword. */ {ErrorMsg.METHOD_NOT_FOUND_ERR, "\u627E\u4E0D\u5230\u5916\u90E8\u65B9\u6CD5 ''{0}'' (\u5FC5\u9808\u70BA\u516C\u7528)\u3002"}, /* * Note to translators: The word "method" here refers to a Java method. * Processing the stylesheet required a reference to the method named by * the substitution text, but no method with the required types of * arguments or return type could be found. */ {ErrorMsg.ARGUMENT_CONVERSION_ERR, "\u7121\u6CD5\u8F49\u63DB\u547C\u53EB\u65B9\u6CD5 ''{0}'' \u4E2D\u7684\u5F15\u6578/\u50B3\u56DE\u985E\u578B"}, /* * Note to translators: The file or URI named in the substitution text * is missing. */ {ErrorMsg.FILE_NOT_FOUND_ERR, "\u627E\u4E0D\u5230\u6A94\u6848\u6216 URI ''{0}''\u3002"}, /* * Note to translators: This message is displayed when the URI * mentioned in the substitution text is not well-formed syntactically. */ {ErrorMsg.INVALID_URI_ERR, "\u7121\u6548\u7684 URI ''{0}''\u3002"}, /* * Note to translators: The file or URI named in the substitution text * exists but could not be opened. */ {ErrorMsg.FILE_ACCESS_ERR, "\u7121\u6CD5\u958B\u555F\u6A94\u6848\u6216 URI ''{0}''\u3002"}, /* * Note to translators: <xsl:stylesheet> and <xsl:transform> are * keywords that should not be translated. */ {ErrorMsg.MISSING_ROOT_ERR, "\u9810\u671F <xsl:stylesheet> \u6216 <xsl:transform> \u5143\u7D20\u3002"}, /* * Note to translators: The stylesheet contained a reference to a * namespace prefix that was undefined. The value of the substitution * text is the name of the prefix. */ {ErrorMsg.NAMESPACE_UNDEF_ERR, "\u672A\u5BA3\u544A\u547D\u540D\u7A7A\u9593\u524D\u7F6E\u78BC ''{0}''\u3002"}, /* * Note to translators: The Java function named in the stylesheet could * not be found. */ {ErrorMsg.FUNCTION_RESOLVE_ERR, "\u7121\u6CD5\u89E3\u6790\u51FD\u6578 ''{0}'' \u7684\u547C\u53EB\u3002"}, /* * Note to translators: The substitution text is the name of a * function. A literal string here means a constant string value. */ {ErrorMsg.NEED_LITERAL_ERR, "''{0}'' \u7684\u5F15\u6578\u5FC5\u9808\u662F\u6587\u5B57\u5B57\u4E32\u3002"}, /* * Note to translators: This message indicates there was a syntactic * error in the form of an XPath expression. The substitution text is * the expression. */ {ErrorMsg.XPATH_PARSER_ERR, "\u5256\u6790 XPath \u8868\u793A\u5F0F ''{0}'' \u6642\u767C\u751F\u932F\u8AA4\u3002"}, /* * Note to translators: An element in the stylesheet requires a * particular attribute named by the substitution text, but that * attribute was not specified in the stylesheet. */ {ErrorMsg.REQUIRED_ATTR_ERR, "\u907A\u6F0F\u5FC5\u8981\u7684\u5C6C\u6027 ''{0}''\u3002"}, /* * Note to translators: This message indicates that a character not * permitted in an XPath expression was encountered. The substitution * text is the offending character. */ {ErrorMsg.ILLEGAL_CHAR_ERR, "XPath \u8868\u793A\u5F0F\u4E2D\u7121\u6548\u7684\u5B57\u5143 ''{0}''\u3002"}, /* * Note to translators: A processing instruction is a mark-up item in * an XML document that request some behaviour of an XML processor. The * form of the name of was invalid in this case, and the substitution * text is the name. */ {ErrorMsg.ILLEGAL_PI_ERR, "\u8655\u7406\u6307\u793A\u7684\u7121\u6548\u540D\u7A31 ''{0}''\u3002"}, /* * Note to translators: This message is reported if the stylesheet * being processed attempted to construct an XML document with an * attribute in a place other than on an element. The substitution text * specifies the name of the attribute. */ {ErrorMsg.STRAY_ATTRIBUTE_ERR, "\u5C6C\u6027 ''{0}'' \u5728\u5143\u7D20\u4E4B\u5916\u3002"}, /* * Note to translators: An attribute that wasn't recognized was * specified on an element in the stylesheet. The attribute is named * by the substitution * text. */ {ErrorMsg.ILLEGAL_ATTRIBUTE_ERR, "\u7121\u6548\u7684\u5C6C\u6027 ''{0}''\u3002"}, /* * Note to translators: "import" and "include" are keywords that should * not be translated. This messages indicates that the stylesheet * named in the substitution text imported or included itself either * directly or indirectly. */ {ErrorMsg.CIRCULAR_INCLUDE_ERR, "\u5FAA\u74B0\u532F\u5165/\u5305\u542B\u3002\u5DF2\u7D93\u8F09\u5165\u6A23\u5F0F\u8868 ''{0}''\u3002"}, /* * Note to translators: A result-tree fragment is a portion of a * resulting XML document represented as a tree. "<xsl:sort>" is a * keyword and should not be translated. */ {ErrorMsg.RESULT_TREE_SORT_ERR, "\u7121\u6CD5\u6392\u5E8F Result-tree \u7247\u6BB5 (\u5FFD\u7565 <xsl:sort> \u5143\u7D20)\u3002\u5EFA\u7ACB\u7D50\u679C\u6A39\u72C0\u7D50\u69CB\u6642\uFF0C\u5FC5\u9808\u6392\u5E8F\u7BC0\u9EDE\u3002"}, /* * Note to translators: A name can be given to a particular style to be * used to format decimal values. The substitution text gives the name * of such a style for which more than one declaration was encountered. */ {ErrorMsg.SYMBOLS_REDEF_ERR, "\u5DF2\u7D93\u5B9A\u7FA9\u5341\u9032\u4F4D\u683C\u5F0F ''{0}''\u3002"}, /* * Note to translators: The stylesheet version named in the * substitution text is not supported. */ {ErrorMsg.XSL_VERSION_ERR, "XSLTC \u4E0D\u652F\u63F4 XSL \u7248\u672C ''{0}''\u3002"}, /* * Note to translators: The definitions of one or more variables or * parameters depend on one another. */ {ErrorMsg.CIRCULAR_VARIABLE_ERR, "\u5728 ''{0}'' \u4E2D\u6709\u5FAA\u74B0\u8B8A\u6578/\u53C3\u6578\u53C3\u7167\u3002"}, /* * Note to translators: The operator in an expresion with two operands was * not recognized. */ {ErrorMsg.ILLEGAL_BINARY_OP_ERR, "\u4E8C\u9032\u4F4D\u8868\u793A\u5F0F\u4E0D\u660E\u7684\u904B\u7B97\u5B50\u3002"}, /* * Note to translators: This message is produced if a reference to a * function has too many or too few arguments. */ {ErrorMsg.ILLEGAL_ARG_ERR, "\u51FD\u6578\u547C\u53EB\u7121\u6548\u7684\u5F15\u6578\u3002"}, /* * Note to translators: "document()" is the name of function and must * not be translated. A node-set is a set of the nodes in the tree * representation of an XML document. */ {ErrorMsg.DOCUMENT_ARG_ERR, "document() \u51FD\u6578\u7684\u7B2C\u4E8C\u500B\u5F15\u6578\u5FC5\u9808\u662F node-set\u3002"}, /* * Note to translators: "<xsl:when>" and "<xsl:choose>" are keywords * and should not be translated. This message describes a syntax error * in the stylesheet. */ {ErrorMsg.MISSING_WHEN_ERR, "\u5728 <xsl:choose> \u4E2D\u81F3\u5C11\u9700\u8981\u4E00\u500B <xsl:when> \u5143\u7D20\u3002"}, /* * Note to translators: "<xsl:otherwise>" and "<xsl:choose>" are * keywords and should not be translated. This message describes a * syntax error in the stylesheet. */ {ErrorMsg.MULTIPLE_OTHERWISE_ERR, "\u5728 <xsl:choose> \u4E2D\u53EA\u5141\u8A31\u4E00\u500B <xsl:otherwise> \u5143\u7D20\u3002"}, /* * Note to translators: "<xsl:otherwise>" and "<xsl:choose>" are * keywords and should not be translated. This message describes a * syntax error in the stylesheet. */ {ErrorMsg.STRAY_OTHERWISE_ERR, "<xsl:otherwise> \u53EA\u80FD\u5728 <xsl:choose> \u5167\u4F7F\u7528\u3002"}, /* * Note to translators: "<xsl:when>" and "<xsl:choose>" are keywords * and should not be translated. This message describes a syntax error * in the stylesheet. */ {ErrorMsg.STRAY_WHEN_ERR, "<xsl:when> \u53EA\u80FD\u5728 <xsl:choose> \u5167\u4F7F\u7528\u3002"}, /* * Note to translators: "<xsl:when>", "<xsl:otherwise>" and * "<xsl:choose>" are keywords and should not be translated. This * message describes a syntax error in the stylesheet. */ {ErrorMsg.WHEN_ELEMENT_ERR, "\u5728 <xsl:choose> \u4E2D\u53EA\u5141\u8A31 <xsl:when> \u8207 <xsl:otherwise> \u5143\u7D20\u3002"}, /* * Note to translators: "<xsl:attribute-set>" and "name" are keywords * that should not be translated. */ {ErrorMsg.UNNAMED_ATTRIBSET_ERR, "<xsl:attribute-set> \u907A\u6F0F 'name' \u5C6C\u6027\u3002"}, /* * Note to translators: An element in the stylesheet contained an * element of a type that it was not permitted to contain. */ {ErrorMsg.ILLEGAL_CHILD_ERR, "\u7121\u6548\u7684\u5B50\u9805\u5143\u7D20\u3002"}, /* * Note to translators: The stylesheet tried to create an element with * a name that was not a valid XML name. The substitution text contains * the name. */ {ErrorMsg.ILLEGAL_ELEM_NAME_ERR, "\u60A8\u7121\u6CD5\u547C\u53EB\u5143\u7D20 ''{0}''"}, /* * Note to translators: The stylesheet tried to create an attribute * with a name that was not a valid XML name. The substitution text * contains the name. */ {ErrorMsg.ILLEGAL_ATTR_NAME_ERR, "\u60A8\u7121\u6CD5\u547C\u53EB\u5C6C\u6027 ''{0}''"}, /* * Note to translators: The children of the outermost element of a * stylesheet are referred to as top-level elements. No text should * occur within that outermost element unless it is within a top-level * element. This message indicates that that constraint was violated. * "<xsl:stylesheet>" is a keyword that should not be translated. */ {ErrorMsg.ILLEGAL_TEXT_NODE_ERR, "\u6700\u4E0A\u5C64 <xsl:stylesheet> \u5143\u7D20\u4E4B\u5916\u7684\u6587\u5B57\u8CC7\u6599\u3002"}, /* * Note to translators: JAXP is an acronym for the Java API for XML * Processing. This message indicates that the XML parser provided to * XSLTC to process the XML input document had a configuration problem. */ {ErrorMsg.SAX_PARSER_CONFIG_ERR, "\u672A\u6B63\u78BA\u8A2D\u5B9A JAXP \u5256\u6790\u5668"}, /* * Note to translators: The substitution text names the internal error * encountered. */ {ErrorMsg.INTERNAL_ERR, "\u7121\u6CD5\u5FA9\u539F\u7684 XSLTC-internal \u932F\u8AA4: ''{0}''"}, /* * Note to translators: The stylesheet contained an element that was * not recognized as part of the XSL syntax. The substitution text * gives the element name. */ {ErrorMsg.UNSUPPORTED_XSL_ERR, "\u4E0D\u652F\u63F4\u7684 XSL \u5143\u7D20 ''{0}''\u3002"}, /* * Note to translators: The stylesheet referred to an extension to the * XSL syntax and indicated that it was defined by XSLTC, but XSTLC does * not recognized the particular extension named. The substitution text * gives the extension name. */ {ErrorMsg.UNSUPPORTED_EXT_ERR, "\u7121\u6CD5\u8FA8\u8B58\u7684 XSLTC \u64F4\u5145\u5957\u4EF6 ''{0}''\u3002"}, /* * Note to translators: The XML document given to XSLTC as a stylesheet * was not, in fact, a stylesheet. XSLTC is able to detect that in this * case because the outermost element in the stylesheet has to be * declared with respect to the XSL namespace URI, but no declaration * for that namespace was seen. */ {ErrorMsg.MISSING_XSLT_URI_ERR, "\u8F38\u5165\u6587\u4EF6\u4E0D\u662F\u6A23\u5F0F\u8868 (\u6839\u5143\u7D20\u4E2D\u672A\u5BA3\u544A XSL \u547D\u540D\u7A7A\u9593)\u3002"}, /* * Note to translators: XSLTC could not find the stylesheet document * with the name specified by the substitution text. */ {ErrorMsg.MISSING_XSLT_TARGET_ERR, "\u627E\u4E0D\u5230\u6A23\u5F0F\u8868\u76EE\u6A19 ''{0}''\u3002"}, /* * Note to translators: access to the stylesheet target is denied */ {ErrorMsg.ACCESSING_XSLT_TARGET_ERR, "\u7121\u6CD5\u8B80\u53D6\u6A23\u5F0F\u8868\u76EE\u6A19 ''{0}''\uFF0C\u56E0\u70BA accessExternalStylesheet \u5C6C\u6027\u8A2D\u5B9A\u7684\u9650\u5236\uFF0C\u6240\u4EE5\u4E0D\u5141\u8A31 ''{1}'' \u5B58\u53D6\u3002"}, /* * Note to translators: This message represents an internal error in * condition in XSLTC. The substitution text is the class name in XSLTC * that is missing some functionality. */ {ErrorMsg.NOT_IMPLEMENTED_ERR, "\u672A\u5BE6\u884C: ''{0}''\u3002"}, /* * Note to translators: The XML document given to XSLTC as a stylesheet * was not, in fact, a stylesheet. */ {ErrorMsg.NOT_STYLESHEET_ERR, "\u8F38\u5165\u6587\u4EF6\u672A\u5305\u542B XSL \u6A23\u5F0F\u8868\u3002"}, /* * Note to translators: The element named in the substitution text was * encountered in the stylesheet but is not recognized. */ {ErrorMsg.ELEMENT_PARSE_ERR, "\u7121\u6CD5\u5256\u6790\u5143\u7D20 ''{0}''"}, /* * Note to translators: "use", "<key>", "node", "node-set", "string" * and "number" are keywords in this context and should not be * translated. This message indicates that the value of the "use" * attribute was not one of the permitted values. */ {ErrorMsg.KEY_USE_ATTR_ERR, "<key> \u7684\u4F7F\u7528\u5C6C\u6027\u5FC5\u9808\u662F\u7BC0\u9EDE\u3001node-set\u3001\u5B57\u4E32\u6216\u6578\u5B57\u3002"}, /* * Note to translators: An XML document can specify the version of the * XML specification to which it adheres. This message indicates that * the version specified for the output document was not valid. */ {ErrorMsg.OUTPUT_VERSION_ERR, "\u8F38\u51FA XML \u6587\u4EF6\u7248\u672C\u61C9\u70BA 1.0"}, /* * Note to translators: The operator in a comparison operation was * not recognized. */ {ErrorMsg.ILLEGAL_RELAT_OP_ERR, "\u95DC\u806F\u8868\u793A\u5F0F\u7684\u904B\u7B97\u5B50\u4E0D\u660E"}, /* * Note to translators: An attribute set defines as a set of XML * attributes that can be added to an element in the output XML document * as a group. This message is reported if the name specified was not * used to declare an attribute set. The substitution text is the name * that is in error. */ {ErrorMsg.ATTRIBSET_UNDEF_ERR, "\u5617\u8A66\u4F7F\u7528\u4E0D\u5B58\u5728\u7684\u5C6C\u6027\u96C6 ''{0}''\u3002"}, /* * Note to translators: The term "attribute value template" is a term * defined by XSLT which describes the value of an attribute that is * determined by an XPath expression. The message indicates that the * expression was syntactically incorrect; the substitution text * contains the expression that was in error. */ {ErrorMsg.ATTR_VAL_TEMPLATE_ERR, "\u7121\u6CD5\u5256\u6790\u5C6C\u6027\u503C\u6A23\u677F ''{0}''\u3002"}, /* * Note to translators: ??? */ {ErrorMsg.UNKNOWN_SIG_TYPE_ERR, "\u985E\u5225 ''{0}'' \u7C3D\u7AE0\u6709\u4E0D\u660E\u7684 data-type\u3002"}, /* * Note to translators: The substitution text refers to data types. * The message is displayed if a value in a particular context needs to * be converted to type {1}, but that's not possible for a value of * type {0}. */ {ErrorMsg.DATA_CONVERSION_ERR, "\u7121\u6CD5\u8F49\u63DB data-type ''{0}'' \u70BA ''{1}''\u3002"}, /* * Note to translators: "Templates" is a Java class name that should * not be translated. */ {ErrorMsg.NO_TRANSLET_CLASS_ERR, "\u6B64\u6A23\u677F\u672A\u5305\u542B\u6709\u6548\u7684 translet \u985E\u5225\u5B9A\u7FA9\u3002"}, /* * Note to translators: "Templates" is a Java class name that should * not be translated. */ {ErrorMsg.NO_MAIN_TRANSLET_ERR, "\u6B64\u6A23\u677F\u672A\u5305\u542B\u540D\u7A31\u70BA ''{0}'' \u7684\u985E\u5225\u3002"}, /* * Note to translators: The substitution text is the name of a class. */ {ErrorMsg.TRANSLET_CLASS_ERR, "\u7121\u6CD5\u8F09\u5165 translet \u985E\u5225 ''{0}''\u3002"}, {ErrorMsg.TRANSLET_OBJECT_ERR, "\u5DF2\u8F09\u5165 translet \u985E\u5225\uFF0C\u4F46\u7121\u6CD5\u5EFA\u7ACB translet \u57F7\u884C\u8655\u7406\u3002"}, /* * Note to translators: "ErrorListener" is a Java interface name that * should not be translated. The message indicates that the user tried * to set an ErrorListener object on object of the class named in the * substitution text with "null" Java value. */ {ErrorMsg.ERROR_LISTENER_NULL_ERR, "\u5617\u8A66\u5C07 ''{0}'' \u7684 ErrorListener \u8A2D\u5B9A\u70BA\u7A7A\u503C"}, /* * Note to translators: StreamSource, SAXSource and DOMSource are Java * interface names that should not be translated. */ {ErrorMsg.JAXP_UNKNOWN_SOURCE_ERR, "XSLTC \u50C5\u652F\u63F4 StreamSource\u3001SAXSource \u8207 DOMSource"}, /* * Note to translators: "Source" is a Java class name that should not * be translated. The substitution text is the name of Java method. */ {ErrorMsg.JAXP_NO_SOURCE_ERR, "\u50B3\u9001\u81F3 ''{0}'' \u7684\u4F86\u6E90\u7269\u4EF6\u6C92\u6709\u5167\u5BB9\u3002"}, /* * Note to translators: The message indicates that XSLTC failed to * compile the stylesheet into a translet (class file). */ {ErrorMsg.JAXP_COMPILE_ERR, "\u7121\u6CD5\u7DE8\u8B6F\u6A23\u5F0F\u8868"}, /* * Note to translators: "TransformerFactory" is a class name. In this * context, an attribute is a property or setting of the * TransformerFactory object. The substitution text is the name of the * unrecognised attribute. The method used to retrieve the attribute is * "getAttribute", so it's not clear whether it would be best to * translate the term "attribute". */ {ErrorMsg.JAXP_INVALID_ATTR_ERR, "TransformerFactory \u7121\u6CD5\u8FA8\u8B58\u5C6C\u6027 ''{0}''\u3002"}, {ErrorMsg.JAXP_INVALID_ATTR_VALUE_ERR, "\u70BA ''{0}'' \u5C6C\u6027\u6307\u5B9A\u7684\u503C\u4E0D\u6B63\u78BA\u3002"}, /* * Note to translators: "setResult()" and "startDocument()" are Java * method names that should not be translated. */ {ErrorMsg.JAXP_SET_RESULT_ERR, "\u547C\u53EB startDocument() \u4E4B\u524D\uFF0C\u5FC5\u9808\u5148\u547C\u53EB setResult()\u3002"}, /* * Note to translators: "Transformer" is a Java interface name that * should not be translated. A Transformer object should contained a * reference to a translet object in order to be used for * transformations; this message is produced if that requirement is not * met. */ {ErrorMsg.JAXP_NO_TRANSLET_ERR, "\u8F49\u63DB\u5668\u6C92\u6709\u5C01\u88DD\u7684 translet \u7269\u4EF6\u3002"}, /* * Note to translators: The XML document that results from a * transformation needs to be sent to an output handler object; this * message is produced if that requirement is not met. */ {ErrorMsg.JAXP_NO_HANDLER_ERR, "\u8F49\u63DB\u7D50\u679C\u6C92\u6709\u5B9A\u7FA9\u7684\u8F38\u51FA\u8655\u7406\u7A0B\u5F0F\u3002"}, /* * Note to translators: "Result" is a Java interface name in this * context. The substitution text is a method name. */ {ErrorMsg.JAXP_NO_RESULT_ERR, "\u50B3\u9001\u81F3 ''{0}'' \u7684\u7D50\u679C\u7269\u4EF6\u7121\u6548\u3002"}, /* * Note to translators: "Transformer" is a Java interface name. The * user's program attempted to access an unrecognized property with the * name specified in the substitution text. The method used to retrieve * the property is "getOutputProperty", so it's not clear whether it * would be best to translate the term "property". */ {ErrorMsg.JAXP_UNKNOWN_PROP_ERR, "\u5617\u8A66\u5B58\u53D6\u7121\u6548\u7684\u8F49\u63DB\u5668\u5C6C\u6027 ''{0}''\u3002"}, /* * Note to translators: SAX2DOM is the name of a Java class that should * not be translated. This is an adapter in the sense that it takes a * DOM object and converts it to something that uses the SAX API. */ {ErrorMsg.SAX2DOM_ADAPTER_ERR, "\u7121\u6CD5\u5EFA\u7ACB SAX2DOM \u8F49\u63A5\u5668: ''{0}''\u3002"}, /* * Note to translators: "XSLTCSource.build()" is a Java method name. * "systemId" is an XML term that is short for "system identification". */ {ErrorMsg.XSLTC_SOURCE_ERR, "\u672A\u8A2D\u5B9A systemId \u800C\u547C\u53EB XSLTCSource.build()\u3002"}, { ErrorMsg.ER_RESULT_NULL, "\u7D50\u679C\u4E0D\u61C9\u70BA\u7A7A\u503C"}, /* * Note to translators: This message indicates that the value argument * of setParameter must be a valid Java Object. */ {ErrorMsg.JAXP_INVALID_SET_PARAM_VALUE, "\u53C3\u6578 {0} \u7684\u503C\u5FC5\u9808\u662F\u6709\u6548\u7684 Java \u7269\u4EF6"}, {ErrorMsg.COMPILE_STDIN_ERR, "-i \u9078\u9805\u5FC5\u9808\u8207 -o \u9078\u9805\u4E00\u8D77\u4F7F\u7528\u3002"}, /* * Note to translators: This message contains usage information for a * means of invoking XSLTC from the command-line. The message is * formatted for presentation in English. The strings <output>, * <directory>, etc. indicate user-specified argument values, and can * be translated - the argument <package> refers to a Java package, so * it should be handled in the same way the term is handled for JDK * documentation. */ {ErrorMsg.COMPILE_USAGE_STR, "\u6982\u8981\n java com.sun.org.apache.xalan.internal.xsltc.cmdline.Compile [-o <output>]\n [-d <directory>] [-j <jarfile>] [-p <package>]\n [-n] [-x] [-u] [-v] [-h] { <stylesheet> | -i }\n\n\u9078\u9805\n -o <output> \u6307\u6D3E\u540D\u7A31 <output> \u81F3\u7522\u751F\u7684\n translet\u3002\u6839\u64DA\u9810\u8A2D\uFF0Ctranslet \u540D\u7A31\n \u884D\u751F\u81EA <stylesheet> \u540D\u7A31\u3002\u82E5\u7DE8\u8B6F\n \u591A\u500B\u6A23\u5F0F\u8868\uFF0C\u5C07\u5FFD\u7565\u6B64\u9078\u9805\u3002\n -d <directory> \u6307\u5B9A translet \u7684\u76EE\u7684\u5730\u76EE\u9304\n -j <jarfile> \u5C01\u88DD translet \u985E\u5225\u6210\u70BA jar \u6A94\u6848\uFF0C\n \u540D\u7A31\u6307\u5B9A\u70BA <jarfile>\n -p <package> \u6307\u5B9A\u6240\u6709\u7522\u751F\u7684 translet \u985E\u5225\u7684\u5957\u88DD\u7A0B\u5F0F\n \u540D\u7A31\u524D\u7F6E\u78BC\u3002\n -n \u555F\u7528\u6A23\u677F\u5167\u5D4C (\u9810\u8A2D\u884C\u70BA\u4E00\u822C\u800C\u8A00\n \u8F03\u4F73)\u3002\n -x \u958B\u555F\u984D\u5916\u7684\u9664\u932F\u8A0A\u606F\u8F38\u51FA\n -u \u89E3\u8B6F <stylesheet> \u5F15\u6578\u70BA URL\n -i \u5F37\u5236\u7DE8\u8B6F\u5668\u5F9E stdin \u8B80\u53D6\u6A23\u5F0F\u8868\n -v \u5217\u5370\u7DE8\u8B6F\u5668\u7248\u672C\n -h \u5217\u5370\u6B64\u7528\u6CD5\u6558\u8FF0\n"}, /* * Note to translators: This message contains usage information for a * means of invoking XSLTC from the command-line. The message is * formatted for presentation in English. The strings <jarfile>, * <document>, etc. indicate user-specified argument values, and can * be translated - the argument <class> refers to a Java class, so it * should be handled in the same way the term is handled for JDK * documentation. */ {ErrorMsg.TRANSFORM_USAGE_STR, "\u6982\u8981 \n java com.sun.org.apache.xalan.internal.xsltc.cmdline.Transform [-j <jarfile>]\n [-x] [-n <iterations>] {-u <document_url> | <document>}\n <class> [<param1>=<value1> ...]\n\n \u4F7F\u7528 translet <class> \u8F49\u63DB\u6307\u5B9A\u70BA <document> \n \u7684 XML \u6587\u4EF6\u3002translet <class> \u4F4D\u65BC\n \u4F7F\u7528\u8005\u7684\u985E\u5225\u8DEF\u5F91\uFF0C\u6216\u662F\u5728\u9078\u64C7\u6027\u6307\u5B9A\u7684 <jarfile> \u4E2D\u3002\n\u9078\u9805\n -j <jarfile> \u6307\u5B9A\u8F09\u5165 translet \u7684\u4F86\u6E90 jarfile\n -x \u958B\u555F\u984D\u5916\u7684\u9664\u932F\u8A0A\u606F\u8F38\u51FA\n -n <iterations> \u57F7\u884C\u8F49\u63DB <iterations> \u6B21\u6578\u8207\n \u986F\u793A\u5206\u6790\u8CC7\u8A0A\n -u <document_url> \u6307\u5B9A XML \u8F38\u5165\u6587\u4EF6\u70BA URL\n"}, /* * Note to translators: "<xsl:sort>", "<xsl:for-each>" and * "<xsl:apply-templates>" are keywords that should not be translated. * The message indicates that an xsl:sort element must be a child of * one of the other kinds of elements mentioned. */ {ErrorMsg.STRAY_SORT_ERR, "<xsl:sort> \u53EA\u80FD\u5728 <xsl:for-each> \u6216 <xsl:apply-templates> \u4E2D\u4F7F\u7528\u3002"}, /* * Note to translators: The message indicates that the encoding * requested for the output document was on that requires support that * is not available from the Java Virtual Machine being used to execute * the program. */ {ErrorMsg.UNSUPPORTED_ENCODING, "\u6B64 JVM \u4E0D\u652F\u63F4\u8F38\u51FA\u7DE8\u78BC ''{0}''\u3002"}, /* * Note to translators: The message indicates that the XPath expression * named in the substitution text was not well formed syntactically. */ {ErrorMsg.SYNTAX_ERR, "''{0}'' \u4E2D\u7684\u8A9E\u6CD5\u932F\u8AA4\u3002"}, /* * Note to translators: The substitution text is the name of a Java * class. The term "constructor" here is the Java term. The message is * displayed if XSLTC could not find a constructor for the specified * class. */ {ErrorMsg.CONSTRUCTOR_NOT_FOUND, "\u627E\u4E0D\u5230\u5916\u90E8\u5EFA\u69CB\u5B50 ''{0}''\u3002"}, /* * Note to translators: "static" is the Java keyword. The substitution * text is the name of a function. The first argument of that function * is not of the required type. */ {ErrorMsg.NO_JAVA_FUNCT_THIS_REF, "\u975E\u975C\u614B Java \u51FD\u6578 ''{0}'' \u7684\u7B2C\u4E00\u500B\u5F15\u6578\u4E0D\u662F\u6709\u6548\u7684\u7269\u4EF6\u53C3\u7167\u3002"}, /* * Note to translators: An XPath expression was not of the type * required in a particular context. The substitution text is the * expression that was in error. */ {ErrorMsg.TYPE_CHECK_ERR, "\u6AA2\u67E5\u8868\u793A\u5F0F ''{0}'' \u7684\u985E\u578B\u6642\u767C\u751F\u932F\u8AA4\u3002"}, /* * Note to translators: An XPath expression was not of the type * required in a particular context. However, the location of the * problematic expression is unknown. */ {ErrorMsg.TYPE_CHECK_UNK_LOC_ERR, "\u6AA2\u67E5\u4F4D\u65BC\u4E0D\u660E\u4F4D\u7F6E\u8868\u793A\u5F0F\u7684\u985E\u578B\u6642\u767C\u751F\u932F\u8AA4\u3002"}, /* * Note to translators: The substitution text is the name of a command- * line option that was not recognized. */ {ErrorMsg.ILLEGAL_CMDLINE_OPTION_ERR, "\u547D\u4EE4\u884C\u9078\u9805 ''{0}'' \u7121\u6548\u3002"}, /* * Note to translators: The substitution text is the name of a command- * line option. */ {ErrorMsg.CMDLINE_OPT_MISSING_ARG_ERR, "\u547D\u4EE4\u884C\u9078\u9805 ''{0}'' \u907A\u6F0F\u5FC5\u8981\u7684\u5F15\u6578\u3002"}, /* * Note to translators: This message is used to indicate the severity * of another message. The substitution text contains two error * messages. The spacing before the second substitution text indents * it the same amount as the first in English. */ {ErrorMsg.WARNING_PLUS_WRAPPED_MSG, "WARNING: ''{0}''\n :{1}"}, /* * Note to translators: This message is used to indicate the severity * of another message. The substitution text is an error message. */ {ErrorMsg.WARNING_MSG, "WARNING: ''{0}''"}, /* * Note to translators: This message is used to indicate the severity * of another message. The substitution text contains two error * messages. The spacing before the second substitution text indents * it the same amount as the first in English. */ {ErrorMsg.FATAL_ERR_PLUS_WRAPPED_MSG, "FATAL ERROR: ''{0}''\n :{1}"}, /* * Note to translators: This message is used to indicate the severity * of another message. The substitution text is an error message. */ {ErrorMsg.FATAL_ERR_MSG, "FATAL ERROR: ''{0}''"}, /* * Note to translators: This message is used to indicate the severity * of another message. The substitution text contains two error * messages. The spacing before the second substitution text indents * it the same amount as the first in English. */ {ErrorMsg.ERROR_PLUS_WRAPPED_MSG, "ERROR: ''{0}''\n :{1}"}, /* * Note to translators: This message is used to indicate the severity * of another message. The substitution text is an error message. */ {ErrorMsg.ERROR_MSG, "ERROR: ''{0}''"}, /* * Note to translators: The substitution text is the name of a class. */ {ErrorMsg.TRANSFORM_WITH_TRANSLET_STR, "\u4F7F\u7528 translet ''{0}'' \u8F49\u63DB"}, /* * Note to translators: The first substitution is the name of a class, * while the second substitution is the name of a jar file. */ {ErrorMsg.TRANSFORM_WITH_JAR_STR, "\u4F7F\u7528\u4F86\u81EA jar \u6A94\u6848 ''{1}'' \u7684 translet ''{0}'' \u8F49\u63DB"}, /* * Note to translators: "TransformerFactory" is the name of a Java * interface and must not be translated. The substitution text is * the name of the class that could not be instantiated. */ {ErrorMsg.COULD_NOT_CREATE_TRANS_FACT, "\u7121\u6CD5\u5EFA\u7ACB TransformerFactory \u985E\u5225 ''{0}'' \u7684\u57F7\u884C\u8655\u7406\u3002"}, /* * Note to translators: This message is produced when the user * specified a name for the translet class that contains characters * that are not permitted in a Java class name. The substitution * text "{0}" specifies the name the user requested, while "{1}" * specifies the name the processor used instead. */ {ErrorMsg.TRANSLET_NAME_JAVA_CONFLICT, "\u540D\u7A31 ''{0}'' \u7121\u6CD5\u4F5C\u70BA translet \u985E\u5225\u7684\u540D\u7A31\uFF0C\u56E0\u70BA\u5B83\u5305\u542B Java \u985E\u5225\u540D\u7A31\u4E0D\u5141\u8A31\u7684\u5B57\u5143\u3002\u8ACB\u6539\u7528\u540D\u7A31 ''{1}''\u3002"}, /* * Note to translators: The following message is used as a header. * All the error messages are collected together and displayed beneath * this message. */ {ErrorMsg.COMPILER_ERROR_KEY, "\u7DE8\u8B6F\u5668\u932F\u8AA4:"}, /* * Note to translators: The following message is used as a header. * All the warning messages are collected together and displayed * beneath this message. */ {ErrorMsg.COMPILER_WARNING_KEY, "\u7DE8\u8B6F\u5668\u8B66\u544A:"}, /* * Note to translators: The following message is used as a header. * All the error messages that are produced when the stylesheet is * applied to an input document are collected together and displayed * beneath this message. A 'translet' is the compiled form of a * stylesheet (see above). */ {ErrorMsg.RUNTIME_ERROR_KEY, "Translet \u932F\u8AA4:"}, /* * Note to translators: An attribute whose value is constrained to * be a "QName" or a list of "QNames" had a value that was incorrect. * 'QName' is an XML syntactic term that must not be translated. The * substitution text contains the actual value of the attribute. */ {ErrorMsg.INVALID_QNAME_ERR, "\u503C\u5FC5\u9808\u70BA QName \u6216\u4F7F\u7528\u7A7A\u683C\u52A0\u4EE5\u5340\u9694\u7684 QNames \u6E05\u55AE\u7684\u5C6C\u6027\uFF0C\u5177\u6709\u503C ''{0}''"}, /* * Note to translators: An attribute whose value is required to * be an "NCName". * 'NCName' is an XML syntactic term that must not be translated. The * substitution text contains the actual value of the attribute. */ {ErrorMsg.INVALID_NCNAME_ERR, "\u503C\u5FC5\u9808\u70BA NCName \u7684\u5C6C\u6027\uFF0C\u5177\u6709\u503C ''{0}''"}, /* * Note to translators: An attribute with an incorrect value was * encountered. The permitted value is one of the literal values * "xml", "html" or "text"; it is also permitted to have the form of * a QName that is not also an NCName. The terms "method", * "xsl:output", "xml", "html" and "text" are keywords that must not * be translated. The term "qname-but-not-ncname" is an XML syntactic * term. The substitution text contains the actual value of the * attribute. */ {ErrorMsg.INVALID_METHOD_IN_OUTPUT, "<xsl:output> \u5143\u7D20\u7684\u65B9\u6CD5\u5C6C\u6027\u5177\u6709\u503C ''{0}''\u3002\u6B64\u503C\u5FC5\u9808\u662F ''xml''\u3001''html''\u3001''text'' \u6216 qname-but-not-ncname \u5176\u4E2D\u4E4B\u4E00"}, {ErrorMsg.JAXP_GET_FEATURE_NULL_NAME, "TransformerFactory.getFeature(\u5B57\u4E32\u540D\u7A31) \u4E2D\u7684\u529F\u80FD\u540D\u7A31\u4E0D\u53EF\u70BA\u7A7A\u503C\u3002"}, {ErrorMsg.JAXP_SET_FEATURE_NULL_NAME, "TransformerFactory.setFeature(\u5B57\u4E32\u540D\u7A31, \u5E03\u6797\u503C) \u4E2D\u7684\u529F\u80FD\u540D\u7A31\u4E0D\u53EF\u70BA\u7A7A\u503C\u3002"}, {ErrorMsg.JAXP_UNSUPPORTED_FEATURE, "\u7121\u6CD5\u5728\u6B64 TransformerFactory \u4E0A\u8A2D\u5B9A\u529F\u80FD ''{0}''\u3002"}, {ErrorMsg.JAXP_SECUREPROCESSING_FEATURE, "FEATURE_SECURE_PROCESSING: \u5B89\u5168\u7BA1\u7406\u7A0B\u5F0F\u5B58\u5728\u6642\uFF0C\u7121\u6CD5\u5C07\u529F\u80FD\u8A2D\u70BA\u507D\u3002"}, /* * Note to translators: This message describes an internal error in the * processor. The term "byte code" is a Java technical term for the * executable code in a Java method, and "try-catch-finally block" * refers to the Java keywords with those names. "Outlined" is a * technical term internal to XSLTC and should not be translated. */ {ErrorMsg.OUTLINE_ERR_TRY_CATCH, "\u5167\u90E8 XSLTC \u932F\u8AA4: \u7522\u751F\u7684\u4F4D\u5143\u7D44\u78BC\u5305\u542B try-catch-finally \u5340\u584A\uFF0C\u7121\u6CD5\u52A0\u4EE5 outlined."}, /* * Note to translators: This message describes an internal error in the * processor. The terms "OutlineableChunkStart" and * "OutlineableChunkEnd" are the names of classes internal to XSLTC and * should not be translated. The message indicates that for every * "start" there must be a corresponding "end", and vice versa, and * that if one of a pair of "start" and "end" appears between another * pair of corresponding "start" and "end", then the other half of the * pair must also be between that same enclosing pair. */ {ErrorMsg.OUTLINE_ERR_UNBALANCED_MARKERS, "\u5167\u90E8 XSLTC \u932F\u8AA4: OutlineableChunkStart \u548C OutlineableChunkEnd \u6A19\u8A18\u5FC5\u9808\u6210\u5C0D\u51FA\u73FE\uFF0C\u4E26\u4F7F\u7528\u6B63\u78BA\u7684\u5DE2\u72C0\u7D50\u69CB\u3002"}, /* * Note to translators: This message describes an internal error in the * processor. The term "byte code" is a Java technical term for the * executable code in a Java method. The "method" that is being * referred to is a Java method in a translet that XSLTC is generating * in processing a stylesheet. The "instruction" that is being * referred to is one of the instrutions in the Java byte code in that * method. "Outlined" is a technical term internal to XSLTC and * should not be translated. */ {ErrorMsg.OUTLINE_ERR_DELETED_TARGET, "\u5167\u90E8 XSLTC \u932F\u8AA4: \u539F\u59CB\u65B9\u6CD5\u4E2D\u4ECD\u7136\u53C3\u7167\u5C6C\u65BC outlined \u4F4D\u5143\u7D44\u78BC\u5340\u584A\u4E00\u90E8\u5206\u7684\u6307\u793A\u3002" }, /* * Note to translators: This message describes an internal error in the * processor. The "method" that is being referred to is a Java method * in a translet that XSLTC is generating. * */ {ErrorMsg.OUTLINE_ERR_METHOD_TOO_BIG, "\u5167\u90E8 XSLTC \u932F\u8AA4: translet \u4E2D\u7684\u65B9\u6CD5\u8D85\u904E Java \u865B\u64EC\u6A5F\u5668\u5C0D\u65BC\u65B9\u6CD5\u9577\u5EA6 64 KB \u7684\u9650\u5236\u3002\u9019\u901A\u5E38\u662F\u56E0\u70BA\u6A23\u5F0F\u8868\u4E2D\u6709\u975E\u5E38\u5927\u7684\u6A23\u677F\u3002\u8ACB\u5617\u8A66\u91CD\u65B0\u7D44\u7E54\u60A8\u7684\u6A23\u5F0F\u8868\u4EE5\u4F7F\u7528\u8F03\u5C0F\u7684\u6A23\u677F\u3002" }, {ErrorMsg.DESERIALIZE_TRANSLET_ERR, "\u555F\u7528 Java \u5B89\u5168\u6642\uFF0C\u6703\u505C\u7528\u9084\u539F\u5E8F\u5217\u5316 TemplatesImpl \u7684\u652F\u63F4\u3002\u5C07 jdk.xml.enableTemplatesImplDeserialization \u7CFB\u7D71\u5C6C\u6027\u8A2D\u70BA\u771F\u5373\u53EF\u8986\u5BEB\u6B64\u8A2D\u5B9A\u3002"} }; } }
/* * Copyright 2000-2009 JetBrains s.r.o. * * 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.intellij.ide.macro; import com.intellij.ide.IdeBundle; import com.intellij.openapi.actionSystem.CommonDataKeys; import com.intellij.openapi.actionSystem.DataContext; import com.intellij.openapi.actionSystem.PlatformDataKeys; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.ProjectRootManager; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.vfs.VirtualFile; public class FileDirRelativeToSourcepathMacro extends Macro { @Override public String getName() { return "FileDirRelativeToSourcepath"; } @Override public String getDescription() { return IdeBundle.message("macro.file.dir.relative.to.sourcepath.root"); } @Override public String expand(final DataContext dataContext) { final Project project = CommonDataKeys.PROJECT.getData(dataContext); if (project == null) { return null; } VirtualFile file = CommonDataKeys.VIRTUAL_FILE.getData(dataContext); if (file == null) { return null; } if (!file.isDirectory()) { file = file.getParent(); if (file == null) { return null; } } final VirtualFile sourceRoot = ProjectRootManager.getInstance(project).getFileIndex().getSourceRootForFile(file); if (sourceRoot == null) return null; return FileUtil.getRelativePath(getIOFile(sourceRoot), getIOFile(file)); } }
// Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.firebase.firestore.local; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; @RunWith(RobolectricTestRunner.class) @Config(manifest = Config.NONE) public class SQLiteLruGarbageCollectorTest extends LruGarbageCollectorTestCase { @Override Persistence createPersistence() { return PersistenceTestHelpers.createSQLitePersistence(); } }
package client_state_policies; import client_store.ClientState; import client_store.StatePolicy; import common.StoreAction; import client_store_actions.ClientDiscardObjectCardAction; public class DiscardObjectCardStatePolicy implements StatePolicy { @Override public ClientState apply(ClientState state, StoreAction action) { ClientDiscardObjectCardAction castedAction = (ClientDiscardObjectCardAction) action; state.getPlayer().getPrivateDeck().removeCard(castedAction.getDiscardedObjectCard()); return state; } }
/******************************************************************************* * Copyright (c) 2013 BSI Business Systems Integration AG. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * BSI Business Systems Integration AG - initial API and implementation ******************************************************************************/ package org.eclipsescout.demo.widgets.ui.swt.views; import org.eclipse.scout.rt.ui.swt.ISwtEnvironment; import org.eclipse.scout.rt.ui.swt.window.desktop.view.AbstractScoutView; import org.eclipsescout.demo.widgets.ui.swt.Activator; public class NorthWestView extends AbstractScoutView { public NorthWestView() { } @Override protected ISwtEnvironment getSwtEnvironment() { return Activator.getDefault().getEnvironment(); } }
package top.tangyh.lamp.msg.dao; import com.baomidou.mybatisplus.core.metadata.IPage; import top.tangyh.basic.base.mapper.SuperMapper; import top.tangyh.basic.base.request.PageParams; import top.tangyh.lamp.msg.dto.MsgPageResult; import top.tangyh.lamp.msg.dto.MsgQuery; import top.tangyh.lamp.msg.entity.Msg; import org.apache.ibatis.annotations.Param; import org.springframework.stereotype.Repository; /** * <p> * Mapper 接口 * 消息中心 * </p> * * @author zuihou * @date 2019-08-01 */ @Repository public interface MsgMapper extends SuperMapper<Msg> { /** * 查询消息中心分页数据 * * @param page 分页参数 * @param param 消息参数 * @return 分页数据 */ IPage<MsgPageResult> page(IPage<MsgPageResult> page, @Param("param") PageParams<MsgQuery> param); }
package com.fnklabs.nast.network.echo; import com.fnklabs.nast.network.AbstractServerChannelHandler; import com.fnklabs.nast.network.io.Session; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.nio.ByteBuffer; import java.util.concurrent.CompletableFuture; public class ServerNoOpChannelHandler extends AbstractServerChannelHandler { public static final Logger log = LoggerFactory.getLogger(ServerNoOpChannelHandler.class); public ServerNoOpChannelHandler(int queueSize) { super(queueSize); } @Override public CompletableFuture<Void> onRead(Session session, ByteBuffer data) { int requestID = data.getInt(); int value = data.getInt(); return CompletableFuture.completedFuture(null); } }
/* ### * 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.framework.main.datatree; import java.io.File; import javax.swing.Icon; import javax.swing.ImageIcon; import docking.tool.ToolConstants; import ghidra.framework.client.RepositoryAdapter; import ghidra.framework.model.*; import resources.ResourceManager; public class DomainFolderRootNode extends DomainFolderNode { private static final ImageIcon CLOSED_PROJECT = ResourceManager.loadImage("images/closedSmallFolder.png"); private static final ImageIcon OPEN_PROJECT = ResourceManager.loadImage("images/openSmallFolder.png"); private String projectName; private String toolTipText; DomainFolderRootNode(String projectName, DomainFolder rootFolder, ProjectData projectData, DomainFileFilter filter) { super(rootFolder, filter); this.projectName = projectName; toolTipText = getToolTip(projectData); } @Override public String getName() { if (projectName == null) { return ToolConstants.NO_ACTIVE_PROJECT; } return projectName; } void setName(String newName) { projectName = newName; fireNodeChanged(null, this); } @Override public String getToolTip() { return toolTipText; } @Override public Icon getIcon(boolean expanded) { return expanded ? OPEN_PROJECT : CLOSED_PROJECT; } private String getToolTip(ProjectData projectData) { RepositoryAdapter repository = projectData.getRepository(); File dir = projectData.getProjectLocator().getProjectDir(); String toolTip = dir.getAbsolutePath(); if (!getDomainFolder().isInWritableProject() && repository != null) { ServerInfo info = repository.getServerInfo(); String serverName = ""; if (info != null) { serverName = info.getServerName() + ", "; } toolTip += " [" + serverName + repository.getName() + "]"; } return toolTip; } }
package com.alipay.api.domain; import com.alipay.api.AlipayObject; import com.alipay.api.internal.mapping.ApiField; /** * 附件撤回(服务商->支付宝) API * * @author auto create * @since 1.0, 2021-03-02 13:27:43 */ public class AlipayInsSceneInsserviceprodSerattachmentDeleteModel extends AlipayObject { private static final long serialVersionUID = 7757865166665581788L; /** * 待撤回的文件编号 (本字段也就是上传附件接口返回的那个附件ID) */ @ApiField("attachment_no") private String attachmentNo; public String getAttachmentNo() { return this.attachmentNo; } public void setAttachmentNo(String attachmentNo) { this.attachmentNo = attachmentNo; } }
// Copyright (c) YugaByte, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except // in compliance with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed under the License // is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express // or implied. See the License for the specific language governing permissions and limitations // under the License. // package org.yb.loadtester; import com.datastax.driver.core.Row; import com.yugabyte.sample.apps.CassandraSparkWordCount; import com.yugabyte.sample.common.CmdLineOpts; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.yb.cql.BaseCQLTest; import org.yb.minicluster.MiniYBClusterBuilder; import static org.yb.AssertionWrappers.assertTrue; import static org.yb.AssertionWrappers.assertEquals; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.stream.Collectors; import org.yb.util.YBTestRunnerNonTsanOnly; @RunWith(value=YBTestRunnerNonTsanOnly.class) public class TestCassandraSparkWordCount extends BaseCQLTest { private CassandraSparkWordCount app = new CassandraSparkWordCount(); @Override protected void customizeMiniClusterBuilder(MiniYBClusterBuilder builder) { super.customizeMiniClusterBuilder(builder); // Disable the system.partitions vtable refresh bg thread. builder.yqlSystemPartitionsVtableRefreshSecs(0); } protected Map<String, String> getTServerFlags() { Map<String, String> flagMap = super.getTServerFlags(); flagMap.put("cql_update_system_query_cache_msecs", "1000"); return flagMap; } @Test public void testDefaultRun() throws Exception { // Set up config. String nodes = miniCluster.getCQLContactPoints().stream() .map(addr -> addr.getHostString() + ":" + addr.getPort()) .collect(Collectors.joining(",")); String[] args = {"--workload", "CassandraSparkWordCount", "--nodes", nodes}; CmdLineOpts config = CmdLineOpts.createFromArgs(args); // Run the app. app.workloadInit(config, false); app.run(); // Check row. Map<String, Integer> expectedValues = new HashMap<>(); expectedValues.put("one", 1); expectedValues.put("two", 2); expectedValues.put("three", 3); expectedValues.put("four", 4); expectedValues.put("five", 5); expectedValues.put("six", 6); expectedValues.put("seven", 7); expectedValues.put("eight", 8); expectedValues.put("nine", 9); expectedValues.put("ten", 10); Iterator<Row> iterator = runSelect("SELECT * FROM ybdemo_keyspace.wordcounts"); int rows_count = 0; while (iterator.hasNext()) { Row row = iterator.next(); String word = row.getString("word"); assertTrue(expectedValues.containsKey(word)); assertEquals(expectedValues.get(word).intValue(), row.getInt("count")); rows_count++; } assertEquals(10, rows_count); } }
/* * Copyright 2009-2013 by The Regents of the University of California * 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 from * * 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.hyracks.storage.am.common.dataflow; import org.apache.hyracks.api.dataflow.IActivity; import org.apache.hyracks.api.dataflow.value.INullWriterFactory; import org.apache.hyracks.api.dataflow.value.RecordDescriptor; import org.apache.hyracks.dataflow.std.file.IFileSplitProvider; import org.apache.hyracks.storage.am.common.api.IIndexLifecycleManagerProvider; import org.apache.hyracks.storage.am.common.api.IModificationOperationCallbackFactory; import org.apache.hyracks.storage.am.common.api.ISearchOperationCallbackFactory; import org.apache.hyracks.storage.am.common.api.ITupleFilterFactory; import org.apache.hyracks.storage.common.IStorageManagerInterface; import org.apache.hyracks.storage.common.file.ILocalResourceFactoryProvider; public interface IIndexOperatorDescriptor extends IActivity { public IFileSplitProvider getFileSplitProvider(); public IStorageManagerInterface getStorageManager(); public IIndexLifecycleManagerProvider getLifecycleManagerProvider(); public RecordDescriptor getRecordDescriptor(); public IIndexDataflowHelperFactory getIndexDataflowHelperFactory(); public boolean getRetainInput(); public boolean getRetainNull(); public INullWriterFactory getNullWriterFactory(); public ISearchOperationCallbackFactory getSearchOpCallbackFactory(); public IModificationOperationCallbackFactory getModificationOpCallbackFactory(); public ITupleFilterFactory getTupleFilterFactory(); public ILocalResourceFactoryProvider getLocalResourceFactoryProvider(); }
/* * 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.rocketmq.store.ha; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.SocketChannel; import org.apache.rocketmq.common.ServiceThread; import org.apache.rocketmq.common.constant.LoggerName; import org.apache.rocketmq.logging.InternalLogger; import org.apache.rocketmq.logging.InternalLoggerFactory; import org.apache.rocketmq.remoting.common.RemotingUtil; import org.apache.rocketmq.store.SelectMappedBufferResult; public class HAConnection { private static final InternalLogger log = InternalLoggerFactory.getLogger(LoggerName.STORE_LOGGER_NAME); private final HAService haService; private final SocketChannel socketChannel; private final String clientAddr; private WriteSocketService writeSocketService; private ReadSocketService readSocketService; private volatile long slaveRequestOffset = -1; private volatile long slaveAckOffset = -1; public HAConnection(final HAService haService, final SocketChannel socketChannel) throws IOException { this.haService = haService; this.socketChannel = socketChannel; this.clientAddr = this.socketChannel.socket().getRemoteSocketAddress().toString(); this.socketChannel.configureBlocking(false); this.socketChannel.socket().setSoLinger(false, -1); this.socketChannel.socket().setTcpNoDelay(true); this.socketChannel.socket().setReceiveBufferSize(1024 * 64); this.socketChannel.socket().setSendBufferSize(1024 * 64); this.writeSocketService = new WriteSocketService(this.socketChannel); this.readSocketService = new ReadSocketService(this.socketChannel); this.haService.getConnectionCount().incrementAndGet(); } public void start() { this.readSocketService.start(); this.writeSocketService.start(); } public void shutdown() { this.writeSocketService.shutdown(true); this.readSocketService.shutdown(true); this.close(); } public void close() { if (this.socketChannel != null) { try { this.socketChannel.close(); } catch (IOException e) { HAConnection.log.error("", e); } } } public SocketChannel getSocketChannel() { return socketChannel; } class ReadSocketService extends ServiceThread { private static final int READ_MAX_BUFFER_SIZE = 1024 * 1024; private final Selector selector; private final SocketChannel socketChannel; private final ByteBuffer byteBufferRead = ByteBuffer.allocate(READ_MAX_BUFFER_SIZE); private int processPosition = 0; private volatile long lastReadTimestamp = System.currentTimeMillis(); public ReadSocketService(final SocketChannel socketChannel) throws IOException { this.selector = RemotingUtil.openSelector(); this.socketChannel = socketChannel; this.socketChannel.register(this.selector, SelectionKey.OP_READ); this.setDaemon(true); } @Override public void run() { HAConnection.log.info(this.getServiceName() + " service started"); while (!this.isStopped()) { try { this.selector.select(1000); boolean ok = this.processReadEvent(); if (!ok) { HAConnection.log.error("processReadEvent error"); break; } long interval = HAConnection.this.haService.getDefaultMessageStore().getSystemClock().now() - this.lastReadTimestamp; if (interval > HAConnection.this.haService.getDefaultMessageStore().getMessageStoreConfig().getHaHousekeepingInterval()) { log.warn("ha housekeeping, found this connection[" + HAConnection.this.clientAddr + "] expired, " + interval); break; } } catch (Exception e) { HAConnection.log.error(this.getServiceName() + " service has exception.", e); break; } } this.makeStop(); writeSocketService.makeStop(); haService.removeConnection(HAConnection.this); HAConnection.this.haService.getConnectionCount().decrementAndGet(); SelectionKey sk = this.socketChannel.keyFor(this.selector); if (sk != null) { sk.cancel(); } try { this.selector.close(); this.socketChannel.close(); } catch (IOException e) { HAConnection.log.error("", e); } HAConnection.log.info(this.getServiceName() + " service end"); } @Override public String getServiceName() { return ReadSocketService.class.getSimpleName(); } private boolean processReadEvent() { int readSizeZeroTimes = 0; if (!this.byteBufferRead.hasRemaining()) { this.byteBufferRead.flip(); this.processPosition = 0; } while (this.byteBufferRead.hasRemaining()) { try { int readSize = this.socketChannel.read(this.byteBufferRead); if (readSize > 0) { readSizeZeroTimes = 0; this.lastReadTimestamp = HAConnection.this.haService.getDefaultMessageStore().getSystemClock().now(); if ((this.byteBufferRead.position() - this.processPosition) >= 8) { int pos = this.byteBufferRead.position() - (this.byteBufferRead.position() % 8); long readOffset = this.byteBufferRead.getLong(pos - 8); this.processPosition = pos; HAConnection.this.slaveAckOffset = readOffset; if (HAConnection.this.slaveRequestOffset < 0) { HAConnection.this.slaveRequestOffset = readOffset; log.info("slave[" + HAConnection.this.clientAddr + "] request offset " + readOffset); } HAConnection.this.haService.notifyTransferSome(HAConnection.this.slaveAckOffset); } } else if (readSize == 0) { if (++readSizeZeroTimes >= 3) { break; } } else { log.error("read socket[" + HAConnection.this.clientAddr + "] < 0"); return false; } } catch (IOException e) { log.error("processReadEvent exception", e); return false; } } return true; } } class WriteSocketService extends ServiceThread { private final Selector selector; private final SocketChannel socketChannel; private final int headerSize = 8 + 4; private final ByteBuffer byteBufferHeader = ByteBuffer.allocate(headerSize); private long nextTransferFromWhere = -1; private SelectMappedBufferResult selectMappedBufferResult; private boolean lastWriteOver = true; private long lastWriteTimestamp = System.currentTimeMillis(); public WriteSocketService(final SocketChannel socketChannel) throws IOException { this.selector = RemotingUtil.openSelector(); this.socketChannel = socketChannel; this.socketChannel.register(this.selector, SelectionKey.OP_WRITE); this.setDaemon(true); } @Override public void run() { HAConnection.log.info(this.getServiceName() + " service started"); while (!this.isStopped()) { try { this.selector.select(1000); if (-1 == HAConnection.this.slaveRequestOffset) { Thread.sleep(10); continue; } if (-1 == this.nextTransferFromWhere) { if (0 == HAConnection.this.slaveRequestOffset) { // slaveRequestOffset 等于0 则从当前commitLog文件最大的便宜量开始传输,否则从服务端拉取请求的偏移量开始请求 long masterOffset = HAConnection.this.haService.getDefaultMessageStore().getCommitLog().getMaxOffset(); masterOffset = masterOffset - (masterOffset % HAConnection.this.haService.getDefaultMessageStore().getMessageStoreConfig() .getMappedFileSizeCommitLog()); if (masterOffset < 0) { masterOffset = 0; } this.nextTransferFromWhere = masterOffset; } else { this.nextTransferFromWhere = HAConnection.this.slaveRequestOffset; } log.info("master transfer data from " + this.nextTransferFromWhere + " to slave[" + HAConnection.this.clientAddr + "], and slave request " + HAConnection.this.slaveRequestOffset); } if (this.lastWriteOver) { long interval = HAConnection.this.haService.getDefaultMessageStore().getSystemClock().now() - this.lastWriteTimestamp; if (interval > HAConnection.this.haService.getDefaultMessageStore().getMessageStoreConfig() .getHaSendHeartbeatInterval()) { // Build Header this.byteBufferHeader.position(0); this.byteBufferHeader.limit(headerSize); this.byteBufferHeader.putLong(this.nextTransferFromWhere); this.byteBufferHeader.putInt(0); this.byteBufferHeader.flip(); this.lastWriteOver = this.transferData(); if (!this.lastWriteOver) continue; } } else { this.lastWriteOver = this.transferData(); if (!this.lastWriteOver) continue; } SelectMappedBufferResult selectResult = HAConnection.this.haService.getDefaultMessageStore().getCommitLogData(this.nextTransferFromWhere); if (selectResult != null) { int size = selectResult.getSize(); if (size > HAConnection.this.haService.getDefaultMessageStore().getMessageStoreConfig().getHaTransferBatchSize()) { size = HAConnection.this.haService.getDefaultMessageStore().getMessageStoreConfig().getHaTransferBatchSize(); } long thisOffset = this.nextTransferFromWhere; this.nextTransferFromWhere += size; selectResult.getByteBuffer().limit(size); // Body this.selectMappedBufferResult = selectResult; // Build Header this.byteBufferHeader.position(0); this.byteBufferHeader.limit(headerSize); this.byteBufferHeader.putLong(thisOffset); this.byteBufferHeader.putInt(size); this.byteBufferHeader.flip(); // 发起写 this.lastWriteOver = this.transferData(); } else { HAConnection.this.haService.getWaitNotifyObject().allWaitForRunning(100); } } catch (Exception e) { HAConnection.log.error(this.getServiceName() + " service has exception.", e); break; } } HAConnection.this.haService.getWaitNotifyObject().removeFromWaitingThreadTable(); if (this.selectMappedBufferResult != null) { this.selectMappedBufferResult.release(); } this.makeStop(); readSocketService.makeStop(); haService.removeConnection(HAConnection.this); SelectionKey sk = this.socketChannel.keyFor(this.selector); if (sk != null) { sk.cancel(); } try { this.selector.close(); this.socketChannel.close(); } catch (IOException e) { HAConnection.log.error("", e); } HAConnection.log.info(this.getServiceName() + " service end"); } private boolean transferData() throws Exception { int writeSizeZeroTimes = 0; // Write Header while (this.byteBufferHeader.hasRemaining()) { int writeSize = this.socketChannel.write(this.byteBufferHeader); if (writeSize > 0) { writeSizeZeroTimes = 0; this.lastWriteTimestamp = HAConnection.this.haService.getDefaultMessageStore().getSystemClock().now(); } else if (writeSize == 0) { if (++writeSizeZeroTimes >= 3) { break; } } else { throw new Exception("ha master write header error < 0"); } } if (null == this.selectMappedBufferResult) { return !this.byteBufferHeader.hasRemaining(); } writeSizeZeroTimes = 0; // Write Body if (!this.byteBufferHeader.hasRemaining()) { while (this.selectMappedBufferResult.getByteBuffer().hasRemaining()) { int writeSize = this.socketChannel.write(this.selectMappedBufferResult.getByteBuffer()); if (writeSize > 0) { writeSizeZeroTimes = 0; this.lastWriteTimestamp = HAConnection.this.haService.getDefaultMessageStore().getSystemClock().now(); } else if (writeSize == 0) { if (++writeSizeZeroTimes >= 3) { break; } } else { throw new Exception("ha master write body error < 0"); } } } boolean result = !this.byteBufferHeader.hasRemaining() && !this.selectMappedBufferResult.getByteBuffer().hasRemaining(); if (!this.selectMappedBufferResult.getByteBuffer().hasRemaining()) { this.selectMappedBufferResult.release(); this.selectMappedBufferResult = null; } return result; } @Override public String getServiceName() { return WriteSocketService.class.getSimpleName(); } @Override public void shutdown() { super.shutdown(); } } }
package openinghoursevaluator; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.time.LocalDateTime; import java.util.Locale; import org.junit.Test; import ch.poole.openinghoursparser.OpeningHoursParseException; import io.github.goodudetheboy.worldholidaydates.holidaydata.HolidayData; public class UnitTest { /** * Test for timepoint, used when main test suite doesn't cover certain cases */ @Test public void timepointTest() throws OpeningHoursParseException, OpeningHoursEvaluationException { assertTrue(InputTest.evaluateCheck("00:00-02:00,12:00-14:00,17:00-24:00", "2021-06-09T15:00", Status.CLOSED)); assertTrue(InputTest.evaluateCheck("00:00-02:00,12:00-14:00,17:00-24:00", "2021-06-09T18:00", Status.OPEN)); assertTrue(InputTest.evaluateCheck("2021 open", "2020-12-31T00:00", Status.CLOSED)); } /** * Test for open next, used when main test suite doesn't cover certain cases */ @Test public void openNextTest() throws OpeningHoursParseException, OpeningHoursEvaluationException { LocalDateTime time = LocalDateTime.parse("2021-07-01T12:00"); LocalDateTime answerTime = LocalDateTime.parse("2021-07-01T14:00"); assertEquals(answerTime, InputTest.getNextEvent("14:00-18:00 unknown", time).getNextEventTime()); } /** * Test for open last, used when main test suite doesn't cover certain cases */ @Test public void openLastTest() throws OpeningHoursParseException, OpeningHoursEvaluationException { LocalDateTime time = LocalDateTime.parse("2021-06-30T12:00"); LocalDateTime answerTime = LocalDateTime.parse("2021-06-29T18:00"); assertEquals(answerTime, InputTest.getLastEvent("14:00-18:00 unknown", time).getLastEventTime()); } /** * Test for variable time test */ @Test public void variableTimeTest() throws OpeningHoursParseException, OpeningHoursEvaluationException { OpeningHoursEvaluator evaluator = new OpeningHoursEvaluator("sunset-sunrise", false); assertEquals(Status.OPEN, evaluator.checkStatus("2021-06-13T05:31")); assertEquals(Status.CLOSED, evaluator.checkStatus("2021-06-13T05:32")); } /** * Test for testing variable time of countries with different coordinates */ @Test public void diffCountryVarTimeTest() throws OpeningHoursParseException, OpeningHoursEvaluationException { double[][] countries = {{ 31.2304 , 121.4737 }, // Shanghai, China { 41.8781 , -87.6298 }, // Chicago, USA { 52.5200 , 10.4515 } // Berlin, Germany }; String[] inputTime = { "2021-07-22T04:50", "2021-07-22T06:00", "2021-07-22T05:20" }; Status[] status = { Status.CLOSED, Status.OPEN, Status.CLOSED }; for (int i=0; i<countries.length; i++) { OpeningHoursEvaluator evaluator = new OpeningHoursEvaluator("sunrise-sunset", false, countries[i][0], countries[i][1], ""); assertEquals(status[i], evaluator.checkStatus(inputTime[i])); } } /** * Test for different Locale-based week number */ @Test public void localeBasedWeekTest() throws OpeningHoursParseException, OpeningHoursEvaluationException { // US and some countries considers the first days of the year to be week 1 OpeningHoursEvaluator evaluator = new OpeningHoursEvaluator("week 1", false, 43.1566, -77.6088, "US"); assertEquals(Status.OPEN, evaluator.checkStatus("2021-01-01T05:31")); evaluator.setOpeningHoursTag("week 53"); assertEquals(Status.CLOSED, evaluator.checkStatus("2021-01-01T05:32")); OpeningHoursEvaluator evaluator2 = new OpeningHoursEvaluator("week 1", false, 46.2276, 2.2276, Locale.FRANCE); assertEquals(Status.CLOSED, evaluator2.checkStatus("2021-01-01T05:31")); evaluator2.setOpeningHoursTag("week 53"); assertEquals(Status.OPEN, evaluator2.checkStatus("2021-01-01T05:32")); } /** * Constructor test for evaluator */ @Test public void constructorTest() throws OpeningHoursParseException { OpeningHoursEvaluator evaluator = new OpeningHoursEvaluator("week 1", false, 43.1566, -77.6088, Locale.US); assertEquals("US", evaluator.getGeolocation().getCountry()); } /** * A weird test that I just put here to check if the code to retrieve week data * is working */ @Test public void getWeekDataTest() throws OpeningHoursParseException, OpeningHoursEvaluationException { OpeningHoursEvaluator evaluator = new OpeningHoursEvaluator("10:00-20:00; 13:00-15:00 off", false); LocalDateTime inputTime = LocalDateTime.parse("2021-07-01T00:00"); String expected = "Mo (2021-06-28) : 10:00-13:00(opening) 15:00-20:00(opening) "; // unsquashed String actual = evaluator.getWeekData(inputTime).get(0).getStartWeekDayRule().toString(); assertEquals(expected, actual); // squashed week actual = evaluator.getSquashedWeekData(inputTime).getStartWeekDayRule().toString(); assertEquals(expected, actual); } /** * A test for holiday data initialization */ @Test public void holidayDataInitializationTest() { HolidayData holidayData = HolidayData.initializeData(); assertEquals(168, holidayData.getHolidays().size()); } /** * A test for PH, SH tag */ @Test public void holidayTest() throws OpeningHoursParseException, OpeningHoursEvaluationException { OpeningHoursEvaluator e1 = new OpeningHoursEvaluator("PH open, PH -2 days unknown", false); // Vietnam geolocation Result result = e1.evaluate("2021-04-30T00:00"); // PH open (30/4 and 1/5) assertEquals(Status.OPEN, result.getStatus()); assertEquals("Day of liberating the South for national reunification", result.getComment()); // PH -2 days unknown assertEquals(Status.UNKNOWN, e1.checkStatus("2021-04-28T00:00")); // SH test OpeningHoursEvaluator e2 = new OpeningHoursEvaluator("SH open, PH -2 days unknown", false); // PH open (30/4 and 1/5) assertEquals(Status.CLOSED, e2.checkStatus("2021-04-30T00:00")); // PH -2 days unknown assertEquals(Status.UNKNOWN, e2.checkStatus("2021-04-28T00:00")); OpeningHoursEvaluator e6 = new OpeningHoursEvaluator("12:00-01:00; PH 13:00-15:00 open", false); assertEquals(Status.OPEN, e6.checkStatus("2021-09-02T00:00")); assertEquals(Status.CLOSED, e6.checkStatus("2021-09-02T02:00")); assertEquals(Status.OPEN, e6.checkStatus("2021-09-02T14:00")); OpeningHoursEvaluator e7 = new OpeningHoursEvaluator("08:00-13:00, PH 13:00-15:00 open", false); assertEquals(Status.OPEN, e7.checkStatus("2021-09-02T08:00")); assertEquals(Status.OPEN, e7.checkStatus("2021-09-02T14:00")); } /** * A test for other country holiday test */ @Test public void otherCountryHolidayTest() throws OpeningHoursParseException, OpeningHoursEvaluationException { OpeningHoursEvaluator e3 = new OpeningHoursEvaluator("PH open", false, 58.5953, 25.0136, "EE"); // Estonia assertEquals(Status.OPEN, e3.checkStatus("2021-02-24T00:00")); assertEquals(Status.CLOSED, e3.checkStatus("2021-02-23T00:00")); assertEquals(Status.OPEN, e3.checkStatus("2021-01-06T00:00")); OpeningHoursEvaluator e4 = new OpeningHoursEvaluator("PH open", false, 61.9241, 25.7482, "FI"); // Finland assertEquals(Status.OPEN, e4.checkStatus("2021-06-25T00:00")); OpeningHoursEvaluator e5 = new OpeningHoursEvaluator("12:00-15:00 open; SH open, PH 15:00-16:00 unknown", false, 42.7339, 25.4858, "BG"); // Bulgaria Result r5 = e5.evaluate("2021-11-01T00:00"); assertEquals(Status.OPEN, r5.getStatus()); assertEquals("Revival Leaders' Day", r5.getComment()); assertEquals(Status.UNKNOWN, e5.checkStatus("2021-12-24T15:00")); assertEquals(Status.OPEN, e5.checkStatus("2021-12-26T13:00")); assertEquals(Status.UNKNOWN, e5.checkStatus("2021-12-26T15:00")); } /** * A test for checking sub regions holiday */ @Test public void subRegionsHolidayTest() throws OpeningHoursParseException, OpeningHoursEvaluationException { Geolocation geolocation = new Geolocation(40.7128, -74.0060, "US", "NY"); OpeningHoursEvaluator e = new OpeningHoursEvaluator("PH open", false, geolocation); Result r = e.evaluate("2021-02-12T00:00"); assertEquals(Status.OPEN, r.getStatus()); assertEquals("Lincoln's Birthday", r.getComment()); } /** * A test for checking override */ @Test public void overrideWarningTest() throws OpeningHoursParseException, OpeningHoursEvaluationException { OpeningHoursEvaluator e1 = new OpeningHoursEvaluator("Mo 12:00-15:00; 24/7; Mo 13:00", false); Result r1 = e1.evaluate("2021-08-09T00:00"); assertNotNull(r1.getWarnings()); assertEquals(1, r1.getWarnings().size()); assertEquals("Rules overridden on 2021-08-09: Mo 12:00-15:00; 24/7; ", r1.getWarnings().get(0)); assertEquals("Mo 12:00-15:00", r1.getOverriddenRules().get(0).toString()); assertEquals("24/7", r1.getOverriddenRules().get(1).toString()); try { r1.getOverriddenRules().get(3); fail("Should have failed"); } catch (IndexOutOfBoundsException e) { // expected } } }
package org.basex.query.util.pkg; import static org.basex.query.QueryError.*; import static org.basex.query.util.pkg.PkgText.*; import static org.basex.util.Token.*; import java.io.*; import org.basex.io.*; import org.basex.query.*; import org.basex.query.value.item.*; import org.basex.query.value.node.*; import org.basex.query.value.type.*; import org.basex.util.*; /** * Parses the jar descriptors and performs schema checks. * * @author BaseX Team 2005-21, BSD License * @author Rositsa Shadura */ final class JarParser { /** Input info. */ private final InputInfo info; /** * Constructor. * @param info input info */ JarParser(final InputInfo info) { this.info = info; } /** * Parses a jar descriptor. * @param io XML input * @return jar descriptor container * @throws QueryException query exception */ public JarDesc parse(final IO io) throws QueryException { final JarDesc desc = new JarDesc(); try { final ANode node = new DBNode(io).childIter().next(); for(final ANode next : node.childIter()) { if(next.type != NodeType.ELEMENT) continue; final QNm name = next.qname(); // ignore namespace to improve compatibility if(eq(E_JAR, name.local())) desc.jars.add(next.string()); else if(eq(E_CLASS, name.local())) desc.classes.add(next.string()); } if(desc.jars.isEmpty()) throw REPO_PARSE_X_X.get(info, io.name(), NOJARS); if(desc.classes.isEmpty()) throw REPO_PARSE_X_X.get(info, io.name(), NOCLASSES); return desc; } catch(final IOException ex) { throw REPO_PARSE_X_X.get(info, io.name(), ex); } } }
package br.com.utfpr.porta.controle; import java.util.List; import javax.servlet.http.HttpServletRequest; import org.apache.logging.log4j.util.Strings; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Pageable; import org.springframework.data.web.PageableDefault; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; 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.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import br.com.utfpr.porta.controle.paginacao.PageWrapper; import br.com.utfpr.porta.dto.AnuncioDto; import br.com.utfpr.porta.dto.AnuncioUsuarioDto; import br.com.utfpr.porta.modelo.Anuncio; import br.com.utfpr.porta.modelo.AnuncioUsuarioId; import br.com.utfpr.porta.modelo.Estabelecimento; import br.com.utfpr.porta.modelo.Usuario; import br.com.utfpr.porta.repositorio.AnuncioUsuario; import br.com.utfpr.porta.repositorio.Enderecos; import br.com.utfpr.porta.repositorio.Estabelecimentos; import br.com.utfpr.porta.repositorio.Usuarios; import br.com.utfpr.porta.repositorio.filtro.AnuncioUsuarioFiltro; import br.com.utfpr.porta.seguranca.UsuarioSistema; import br.com.utfpr.porta.servico.AnuncioUsuarioServico; import br.com.utfpr.porta.servico.excecao.ValidacaoBancoDadosExcecao; @Controller @RequestMapping("/anunciosUsuario") public class AnuncioUsuarioControle { @Autowired private Enderecos enderecoRepositorio; @Autowired private AnuncioUsuario anuncioUsuarioRepositorio; @Autowired private AnuncioUsuarioServico anuncioUsuarioServico; @Autowired private br.com.utfpr.porta.repositorio.Anuncio anuncioRepositorio; @Autowired private Estabelecimentos estabelecimentoRepositorio; @Autowired private Usuarios usuarioRepositorio; @GetMapping public ModelAndView pesquisarAnuncioParaUsuario(AnuncioUsuarioFiltro filtro, @PageableDefault(size = 5) Pageable pageable, HttpServletRequest httpServletRequest) { ModelAndView mv = new ModelAndView("/anuncio/AnunciosUsuario"); mv.addObject("estados", enderecoRepositorio.obterEstados()); if(Strings.isNotEmpty(filtro.getEstado())) { mv.addObject("cidades", enderecoRepositorio.obterCidadesPorEstado(filtro.getEstado())); } filtro.setCodigoUsuario(UsuarioSistema.getUsuarioLogado().getCodigo()); PageWrapper<Anuncio> paginaWrapper = new PageWrapper<>( anuncioUsuarioRepositorio.filtrar(filtro, pageable), httpServletRequest); mv.addObject("pagina", paginaWrapper); return mv; } @GetMapping("/estado/{sigla}") public @ResponseBody ResponseEntity<?> obterListaCidadePorEstado(@PathVariable String sigla) { if(Strings.isEmpty(sigla)) { return null; } List<String> listaCidades = enderecoRepositorio.obterCidadesPorEstado(sigla); return ResponseEntity.ok().body(listaCidades); } @GetMapping("/{codigo_anuncio}") public @ResponseBody ResponseEntity<?> obterAnuncioPorCodigo(@PathVariable Long codigo_anuncio) { if(codigo_anuncio == null) { return ResponseEntity.badRequest().body("Código não informado"); } br.com.utfpr.porta.modelo.Anuncio anuncio = anuncioRepositorio.findOne(codigo_anuncio); if(anuncio == null) { return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Anúncio não encontrado"); } if(anuncio.getEstabelecimento() == null || anuncio.getEstabelecimento().getCodigo() == null) { return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Estabelecimento do anúncio não encontrado"); } //VERIFICA SE O USUÁRIO JÁ POSSUI INTERESSE br.com.utfpr.porta.modelo.AnuncioUsuarioId id = new AnuncioUsuarioId(UsuarioSistema.getUsuarioLogado(), anuncio); br.com.utfpr.porta.modelo.AnuncioUsuario anuncioUsuario = anuncioUsuarioRepositorio.findOne(id); anuncio.setUsuarioJaInteressado(anuncioUsuario != null); if(anuncio.getEstabelecimento().getResponsavel() == null || anuncio.getEstabelecimento().getEndereco() == null) { Estabelecimento estabelecimento = estabelecimentoRepositorio.findOne(anuncio.getEstabelecimento().getCodigo()); Usuario responsavel = usuarioRepositorio.findOne(estabelecimento.getResponsavel().getCodigo()); estabelecimento.setResponsavel(responsavel); anuncio.setEstabelecimento(estabelecimento); } AnuncioDto anuncioDto = new AnuncioDto(anuncio); return ResponseEntity.ok().body(anuncioDto); } @PostMapping public @ResponseBody ResponseEntity<?> marcarInteresseUsuario(@RequestBody AnuncioUsuarioDto anuncioUsuario) { if(anuncioUsuario == null || anuncioUsuario.getCodigoAnuncio() == null) { return ResponseEntity.badRequest().body("Código do anúncio não informado"); } try { anuncioUsuarioServico.adicionarUsuarioInteressado(anuncioUsuario.getCodigoAnuncio(), UsuarioSistema.getUsuarioLogado().getCodigo()); } catch(Exception e) { return ResponseEntity.badRequest().body(e.getMessage()); } return ResponseEntity.ok().build(); } @DeleteMapping("/{codigo_anuncio}") public @ResponseBody ResponseEntity<?> desmarcarInteresse(@PathVariable Long codigo_anuncio) { if(codigo_anuncio == null) { return ResponseEntity.badRequest().body("Código do anúncio não informado"); } try { anuncioUsuarioServico.retirarInteresseUsuario(codigo_anuncio, UsuarioSistema.getUsuarioLogado().getCodigo()); } catch (ValidacaoBancoDadosExcecao e) { return ResponseEntity.badRequest().body(e.getMessage()); } catch (NullPointerException e) { return ResponseEntity.badRequest().body(e.getMessage()); } return ResponseEntity.ok().build(); } }
package com.autumn.ui.actionFactory.element; /*- * #%L * autumn-ui * %% * Copyright (C) 2021 Deutsche Telekom AG * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ import org.openqa.selenium.By; public class Link extends UIElement { @Deprecated public Link(By by, String pageName) { super(by, pageName); } public Link(By by, String pageName, String elementName) { super(by, pageName, elementName); } public void clickLink() { waitUntilClickable(); click(); } }
package cn.zengjingfang.box.android.rxhandler; import android.os.Build; import cn.zengjingfang.box.android.rxhandler.rx.Observable; import cn.zengjingfang.box.android.rxhandler.rx.Scheduler; import cn.zengjingfang.box.android.rxhandler.rx.schedulers.Schedulers; import cn.zengjingfang.box.android.rxhandler.rx.Subscriber; /** * Created by ZengJingFang on 2017/12/26 */ public class RxJava1 { private static final String TAG = "RxJava1"; public static void main(String[] args) { testCreate(); } public static void testCreate() { d(TAG, "xxx " + Build.SERIAL); Observable<String> observable1 = Observable.create(new Observable.OnSubscribe<String>() { @Override public void call(Subscriber<? super String> subscriber) { d(TAG, "===>>>> " + Thread.currentThread()); subscriber.onStart(); subscriber.onNext("--test-create--next" + Thread.currentThread()); subscriber.onCompleted(); } }); Subscriber<String> stringSubscriber = new Subscriber<String>() { @Override public void onCompleted() { d(TAG, "===test=create=completed"); } @Override public void onError(Throwable e) { } @Override public void onNext(String s) { d(TAG, ">>> " + s); d(TAG, "===>>>> " + Thread.currentThread()); } }; observable1.subscribe(stringSubscriber); Scheduler ioScheduler = Schedulers.io(); Observable<String> observer2 = observable1.subscribeOn(ioScheduler); // // Scheduler mainScheduler = AndroidSchedulers.mainThread(); // Observable<String> observer3 = observer2.observeOn(mainScheduler); // observer2.subscribe(stringSubscriber); } public static void d(String tag,String s) { System.out.print("\n" + tag + s); } // public static void testDefer() { // Observable<String> defer = Observable.defer(new Func0<Observable<String>>() { // @Override // public Observable<String> call() { // final Observable<String> observable = Observable.create(new Observable.OnSubscribe<String>() { // @Override // public void call(Subscriber<? super String> subscriber) { // subscriber.onNext("defer--2--"); // // onError后不会响应onCompleted ? //// subscriber.onError(new Throwable("defer-error")); // subscriber.onCompleted(); // } // }); // return observable; // } // }); // defer.subscribe(new Action1<String>() { // @Override // public void call(String s) { // Log.d(TAG, ">>> " + s); // } // }, new Action1<Throwable>() { // @Override // public void call(Throwable throwable) { // Log.d(TAG, "=== defer" + throwable); // } // }, new Action0() { // @Override // public void call() { // Log.d(TAG, "===test=defer=completed"); // testFrom(); // } // }); // // } // // public static void testFrom() { // // Integer[] items = { 0, 1, 2, 3, 4, 5 }; // // // Observable<Integer> observable = Observable.from(items); // // observable.subscribe(new Action1<Integer>() { // @Override // public void call(Integer item) { // Log.d(TAG, "-- form --" + item); // } // }, new Action1<Throwable>() { // @Override // public void call(Throwable throwable) { // // } // }, new Action0() { // @Override // public void call() { // Log.d(TAG, "===complete==form==="); // testInterval(); // testBuffer(); // } // }); // // Future<String> future = new Future<String>() { // @Override // public boolean cancel(boolean mayInterruptIfRunning) { // return false; // } // // @Override // public boolean isCancelled() { // return false; // } // // @Override // public boolean isDone() { // return false; // } // // @Override // public String get() throws InterruptedException, ExecutionException { // return "future-1"; // } // // @Override // public String get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { // return "future-2"; // } // }; //// Observable<String> observable1 = Observable.from(future); // Observable<String> observable1 = Observable.from(future,10,TimeUnit.SECONDS); // observable1.subscribe(new Subscriber<String>() { // @Override // public void onCompleted() { // Log.d(TAG, "from-future-completed"); // } // // @Override // public void onError(Throwable e) { // Log.e(TAG, "from-future-e" + e); // } // // @Override // public void onNext(String s) { // Log.i(TAG, "from-future-next: " + s); // } // }); // // // } // // public static void testInterval() { //// Observable.interval(10L, 3, TimeUnit.SECONDS, Schedulers.newThread()).limit(10).subscribe(new Action1<Long>() { //// @Override //// public void call(Long aLong) { //// Log.d(TAG, "---test-interval--" + aLong); //// } //// }, new Action1<Throwable>() { //// @Override //// public void call(Throwable throwable) { //// //// } //// }, new Action0() { //// @Override //// public void call() { //// Log.d(TAG, "===complete==interval==="); //// } //// }); // Log.d(TAG, "-------------------------------"); // // period:3 initialDelay5L 由于要5L后才init 所以 第一个3s取到的observable为null // Observable.interval(5L, 3, TimeUnit.SECONDS, Schedulers.newThread()).limit(5).buffer(3, TimeUnit.SECONDS).subscribe(new Subscriber<List<Long>>() { // // @Override // public void onCompleted() { // Log.d(TAG, "interval-completed"); // } // // @Override // public void onError(Throwable e) { // // } // // @Override // public void onNext(List<Long> longs) { // Log.d(TAG, "interval-next-longs: " + longs); // } // }); // } // // public static void testBuffer() { // Integer[] items = { 0, 1, 2, 3, 4, 5 ,6}; // Observable.from(items).buffer(2).subscribe(new Action1<List<Integer>>() { // @Override // public void call(List<Integer> integers) { // Log.d(TAG, "from-buffer-2 >>> integers" + integers); // } // }); // Observable.from(items).buffer(2,3).subscribe(new Action1<List<Integer>>() { // @Override // public void call(List<Integer> integers) { // Log.d(TAG, "from-buffer-2-skip-3 >>> integers" + integers); // } // }); // Log.d(TAG, "============================================="); // // Observable.from(items).buffer(3,TimeUnit.SECONDS).subscribe(new Subscriber<List<Integer>>() { // @Override // public void onCompleted() { // // } // // @Override // public void onError(Throwable e) { // // } // // @Override // public void onNext(List<Integer> lists) { // Log.d(TAG, "----lists" + lists); // } // }); // // } }
package GameAuthoringEnvironment.AuthoringScreen; import Configs.Behaviors.Behavior; import Configs.Configurable; import javafx.application.Application; import javafx.beans.property.BooleanProperty; import javafx.beans.property.SimpleBooleanProperty; import javafx.collections.FXCollections; import javafx.event.EventHandler; import javafx.geometry.Pos; import javafx.scene.Node; import javafx.scene.Scene; import javafx.scene.control.*; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.input.*; import javafx.scene.layout.GridPane; import javafx.scene.layout.VBox; import javafx.stage.Modality; import javafx.stage.Stage; import java.awt.*; import java.lang.reflect.Array; import java.lang.reflect.Constructor; import java.util.*; import java.util.List; public class ConfigureBehavior extends Application { List<Class> myBehaviorList; Map<String, Object> myMap; Stage popUpWindow; VBox layout; Configurable myConfigurable; private static final DataFormat Behavior_LIST = new DataFormat("Behavior List"); private ListView<Class> sourceView = new ListView<>(); private ListView<Class> targetView = new ListView<>(); int sourceViewWidth = 250; int sourceViewHeight = 250; int viewGap = 10; private final BooleanProperty dragModeActiveProperty = new SimpleBooleanProperty(this, "dragModeActive", true); GameController myGameController; GameOutline myGameOutline; String myKey; Class myType; List<Class> unmodifiableMyBehaviorList; Object[] selectedBehavior; List<Object> tempList; boolean myBoolean; private int PADDING = 20; List<Object> myTempList; /*public ConfigureBehavior(GameOutline gameOutline, Configurable configurable, Map<String, Object> attributesMap, List<Class> behaviorList) { myGameOutline= gameOutline; myConfigurable = configurable; myList = behaviorList; myMap = attributesMap; setContent(); }*/ @Override public void start(Stage stage){ popUpWindow = stage; popUpWindow.setTitle("Behavior Editor"); Scene scene= new Scene(layout, 800, 800); scene.getStylesheets().add("authoring_style.css"); layout.setAlignment(Pos.CENTER); layout.setSpacing(PADDING); popUpWindow.setScene(scene); popUpWindow.show(); } public ConfigureBehavior(GameController gameController, Configurable configurable, Map<String, Object> myAttributesMap, List<Class> behaviorList, String key, Class clazz, List<Object> mytempList, Boolean isArray) { myType = clazz; selectedBehavior = (Object[]) Array.newInstance(myType, 0); tempList = new ArrayList<>(Arrays.asList(selectedBehavior)); myKey = key; myGameController = gameController; myConfigurable = configurable; myBehaviorList = behaviorList; unmodifiableMyBehaviorList = Collections.unmodifiableList(myBehaviorList); myMap = myAttributesMap; myBoolean = isArray; myTempList = mytempList; setContent(); } private void setContent() { layout = new VBox(10.00); Label sourceListLbl = new Label("Available Behaviors: "); Label targetListLbl = new Label("Selected Behaviors: "); Label messageLbl; if(myBoolean){ messageLbl = new Label("Drag and drop behaviors. Some behaviors require further configuration");} else{ messageLbl = new Label("Drag and drop one Behavior. You can choose only one behavior"); } sourceView.setPrefSize(sourceViewWidth, sourceViewHeight); targetView.setPrefSize(sourceViewWidth, sourceViewHeight); sourceView.getItems().addAll(unmodifiableMyBehaviorList); sourceView.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE); targetView.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE); //When clicked, calls createconfigurable again if the behavior is configurable targetView.setOnMouseClicked(new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent mouseEvent) { if(mouseEvent.getButton().equals(MouseButton.PRIMARY)) { if (mouseEvent.getClickCount() == 2) { var selected = targetView.getSelectionModel().getSelectedItem(); try { Class<?> cl = Class.forName(selected.getName()); Constructor<?> cons = cl.getConstructor(myConfigurable.getClass()); var object = cons.newInstance(myConfigurable); // For making outline if(!(myGameOutline == null)){ myGameOutline.showTheScreen((Configurable) object); }else{ myGameController.createConfigurable((Configurable) object); tempList.add(object); } } catch (Exception e) { AlertFactory af = new AlertFactory(); af.createAlert("Configuration Not Completed Properly"); } } }} }); setCellFactory(sourceView); setCellFactory(targetView); // Create the GridPane GridPane pane = new GridPane(); pane.setHgap(viewGap); pane.setVgap(viewGap); Button removeButton = new Button("Remove Behavior"); removeButton.setOnMouseClicked((new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent event) { int index = targetView.getSelectionModel().getSelectedIndex(); if(!(targetView.getItems().size() == tempList.size())){ targetView.getItems().remove(index); } else{ targetView.getItems().remove(index); tempList.remove(index);} } })); pane.addRow(0, messageLbl); pane.addRow(1, sourceListLbl, targetListLbl); pane.addRow(2, sourceView, targetView); pane.addRow(3, removeButton); pane.setAlignment(Pos.CENTER); VBox root = new VBox(); root.setAlignment(Pos.CENTER); root.getChildren().addAll(pane); Button setButton = new Button("Configuration Is Completed"); setButton.setOnMouseClicked((new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent event) { if(!myConfigurable.getConfiguration().isConfigurationComplete()){ Alert alert = new Alert(Alert.AlertType.NONE); alert.setAlertType(Alert.AlertType.WARNING); alert.setTitle("Warning"); alert.setContentText("Atrributtes not all filled out"); alert.showAndWait(); } else { Object[] ob = (Object[]) Array.newInstance(myType, tempList.size()); for(int a=0; a<tempList.size(); a++){ ob[a] = tempList.get(a); } if(myBoolean == true){ //TODO Refactor this is not the clean way myTempList.add(ob); myMap.put(myKey, ob);} else{ if (ob.length == 0){ AlertFactory alertFactory = new AlertFactory(); alertFactory.createAlert("You have to choose and configure at least one behavior"); }else{ myMap.put(myKey,ob[0]);} } popUpWindow.close(); } } })); setDragAndDrop(sourceView); setDragAndDrop(targetView); layout.getChildren().addAll(root, setButton); } public ListView<Class> getTargetView() { return targetView; } public ListView<Class> getSourceView() { return sourceView; } //TODO This can be refactord to a separate class private void setDragAndDrop(ListView listView) { listView.setOnDragDetected(new EventHandler<MouseEvent>() { public void handle(MouseEvent event) { dragDetected(event, sourceView); } }); listView.setOnDragOver(new EventHandler<DragEvent>() { public void handle(DragEvent event) { dragOver(event, sourceView); } }); listView.setOnDragDone(new EventHandler<DragEvent>() { public void handle(DragEvent event) { dragDone(event, targetView, sourceView); } }); } private void dragDetected(MouseEvent event, ListView listView) { // Make sure at least one item is selected int selectedCount = listView.getSelectionModel().getSelectedIndices().size(); if (selectedCount == 0) { event.consume(); return; } // Initiate a drag-and-drop gesture Dragboard dragboard = listView.startDragAndDrop(TransferMode.COPY_OR_MOVE); // Put the the selected items to the dragboard ArrayList<Class> selectedItems = getSelectedBehavior(listView); ClipboardContent content = new ClipboardContent(); content.put(Behavior_LIST, selectedItems); dragboard.setContent(content); //Stops any further handling of the event event.consume(); } private void dragOver(DragEvent event, ListView listView) { // If drag board has an ITEM_LIST and it is not being dragged // over itself, we accept the MOVE transfer mode Dragboard dragboard = event.getDragboard(); if (event.getGestureSource() != listView && dragboard.hasContent(Behavior_LIST)) { event.acceptTransferModes(TransferMode.COPY_OR_MOVE); } event.consume(); } @SuppressWarnings("unchecked") private void dragDone(DragEvent event, ListView source, ListView target) { // Transfer the data to the target Dragboard dragboard = event.getDragboard(); if (dragboard.hasContent(Behavior_LIST)) { ArrayList<Behavior> list = (ArrayList<Behavior>) dragboard.getContent(Behavior_LIST); source.getItems().addAll(list); } TransferMode tm = event.getTransferMode(); if (tm == TransferMode.MOVE) { removeSelectedBehaviors(target); } event.consume(); } private ArrayList<Class> getSelectedBehavior(ListView listView) { ArrayList<Class> list = new ArrayList<>(listView.getSelectionModel().getSelectedItems()); return list; } private void removeSelectedBehaviors(ListView listView) { List<Class> selectedList = new ArrayList<>(); for (Object object : listView.getSelectionModel().getSelectedItems()) { selectedList.add((Class) object); } // Clear the selection listView.getSelectionModel().clearSelection(); // Remove items from the selected list listView.getItems().removeAll(selectedList); } private void setCellFactory(ListView listView) { listView.setCellFactory(list -> { //TODO Set Images Accordingly ListCell<Class> cell = new ListCell<>() { @Override public void updateItem(Class item, boolean empty) { super.updateItem(item, empty); if (empty) { setText(null); setGraphic(null); } else { setText(item.getSimpleName()); } } }; //controlTreeCellMouseClick(cell); return cell; }); } }
package com.lanking.cloud.domain.yoo.activity.imperialExamination; import com.lanking.cloud.sdk.bean.Valueable; /** * 科举考试第二期的考试逻辑需要 * * @since 3.9.4 * @author <a href="mailto:qiuxue.jiang@elanking.com">qiuxue.jiang</a> * @version 2017年11月17日 */ public enum ImperialExaminationExamTag implements Valueable { /** * 首次成绩 */ FIRST_EXAM(1, "首次成绩"), /** * 冲刺1 */ SECOND_EXAM(2, "冲刺1"), /** * 冲刺2 */ THIRD_EXAM(3, "冲刺2"); private int value; private String name; ImperialExaminationExamTag(int value, String name) { this.value = value; this.name = name; } @Override public int getValue() { return value; } public String getName() { return name; } }
package com.it.vo; import java.util.List; public class TypeTimeVO { private String type; private String code; private List<String> x; private List<Long> y; public TypeTimeVO() { super(); // TODO Auto-generated constructor stub } public TypeTimeVO(String type, String code, List<String> x, List<Long> y) { super(); this.type = type; this.code = code; this.x = x; this.y = y; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public List<String> getX() { return x; } public void setX(List<String> xlist) { this.x = xlist; } public List<Long> getY() { return y; } public void setY(List<Long> ylist) { this.y = ylist; } }
/* * Copyright 1999-2017 Alibaba Group Holding Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package wang.yeting.sql.ast.expr; import wang.yeting.sql.FastsqlException; import wang.yeting.sql.ast.*; import wang.yeting.sql.visitor.SQLASTVisitor; import java.io.IOException; import java.util.Collections; import java.util.List; public class SQLIntervalExpr extends SQLExprImpl implements SQLReplaceable { public static final SQLDataType DATA_TYPE = new SQLDataTypeImpl("interval"); private SQLExpr value; private SQLIntervalUnit unit; public SQLIntervalExpr() { } public SQLIntervalExpr(SQLExpr value, SQLIntervalUnit unit) { setValue(value); this.unit = unit; } public SQLIntervalExpr clone() { SQLIntervalExpr x = new SQLIntervalExpr(); if (value != null) { x.setValue(value.clone()); } x.unit = unit; return x; } @Override public boolean replace(SQLExpr expr, SQLExpr target) { if (this.value == expr) { setValue(target); return true; } return false; } public SQLExpr getValue() { return value; } public void setValue(SQLExpr x) { if (x != null) { x.setParent(this); } this.value = x; } public SQLIntervalUnit getUnit() { return unit; } public void setUnit(SQLIntervalUnit unit) { this.unit = unit; } @Override public void output(Appendable buf) { try { buf.append("INTERVAL "); value.output(buf); if (unit != null) { buf.append(' '); buf.append(unit.name()); } } catch (IOException ex) { throw new FastsqlException("output error", ex); } } protected void accept0(SQLASTVisitor visitor) { if (visitor.visit(this)) { if (this.value != null) { this.value.accept(visitor); } } visitor.endVisit(this); } @Override public List getChildren() { return Collections.singletonList(value); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((unit == null) ? 0 : unit.hashCode()); result = prime * result + ((value == null) ? 0 : value.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } SQLIntervalExpr other = (SQLIntervalExpr) obj; if (unit != other.unit) { return false; } if (value == null) { if (other.value != null) { return false; } } else if (!value.equals(other.value)) { return false; } return true; } public SQLDataType computeDataType() { return DATA_TYPE; } }
/* * 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. * * Other licenses: * ----------------------------------------------------------------------------- * Commercial licenses for this work are available. These replace the above * ASL 2.0 and offer limited warranties, support, maintenance, and commercial * database integrations. * * For more information, please visit: http://www.jooq.org/licenses * * * * * * * * * * * * * * * * */ package org.jooq; /** * A model type for a records with degree <code>21</code> * * @see Row21 * @author Lukas Eder */ public interface Record21<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21> extends Record { // ------------------------------------------------------------------------ // Row value expressions // ------------------------------------------------------------------------ /** * Get this record's fields as a {@link Row21}. */ @Override Row21<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21> fieldsRow(); /** * Get this record's values as a {@link Row21}. */ @Override Row21<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21> valuesRow(); // ------------------------------------------------------------------------ // Field accessors // ------------------------------------------------------------------------ /** * Get the first field. */ Field<T1> field1(); /** * Get the second field. */ Field<T2> field2(); /** * Get the third field. */ Field<T3> field3(); /** * Get the fourth field. */ Field<T4> field4(); /** * Get the fifth field. */ Field<T5> field5(); /** * Get the sixth field. */ Field<T6> field6(); /** * Get the seventh field. */ Field<T7> field7(); /** * Get the eighth field. */ Field<T8> field8(); /** * Get the ninth field. */ Field<T9> field9(); /** * Get the tenth field. */ Field<T10> field10(); /** * Get the eleventh field. */ Field<T11> field11(); /** * Get the twelfth field. */ Field<T12> field12(); /** * Get the thirteenth field. */ Field<T13> field13(); /** * Get the fourteenth field. */ Field<T14> field14(); /** * Get the fifteenth field. */ Field<T15> field15(); /** * Get the sixteenth field. */ Field<T16> field16(); /** * Get the seventeenth field. */ Field<T17> field17(); /** * Get the eighteenth field. */ Field<T18> field18(); /** * Get the ninteenth field. */ Field<T19> field19(); /** * Get the twentieth field. */ Field<T20> field20(); /** * Get the twenty-first field. */ Field<T21> field21(); // ------------------------------------------------------------------------ // Value accessors // ------------------------------------------------------------------------ /** * Get the first value. */ T1 value1(); /** * Get the second value. */ T2 value2(); /** * Get the third value. */ T3 value3(); /** * Get the fourth value. */ T4 value4(); /** * Get the fifth value. */ T5 value5(); /** * Get the sixth value. */ T6 value6(); /** * Get the seventh value. */ T7 value7(); /** * Get the eighth value. */ T8 value8(); /** * Get the ninth value. */ T9 value9(); /** * Get the tenth value. */ T10 value10(); /** * Get the eleventh value. */ T11 value11(); /** * Get the twelfth value. */ T12 value12(); /** * Get the thirteenth value. */ T13 value13(); /** * Get the fourteenth value. */ T14 value14(); /** * Get the fifteenth value. */ T15 value15(); /** * Get the sixteenth value. */ T16 value16(); /** * Get the seventeenth value. */ T17 value17(); /** * Get the eighteenth value. */ T18 value18(); /** * Get the ninteenth value. */ T19 value19(); /** * Get the twentieth value. */ T20 value20(); /** * Get the twenty-first value. */ T21 value21(); /** * Set the first value. */ Record21<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21> value1(T1 value); /** * Set the second value. */ Record21<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21> value2(T2 value); /** * Set the third value. */ Record21<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21> value3(T3 value); /** * Set the fourth value. */ Record21<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21> value4(T4 value); /** * Set the fifth value. */ Record21<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21> value5(T5 value); /** * Set the sixth value. */ Record21<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21> value6(T6 value); /** * Set the seventh value. */ Record21<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21> value7(T7 value); /** * Set the eighth value. */ Record21<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21> value8(T8 value); /** * Set the ninth value. */ Record21<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21> value9(T9 value); /** * Set the tenth value. */ Record21<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21> value10(T10 value); /** * Set the eleventh value. */ Record21<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21> value11(T11 value); /** * Set the twelfth value. */ Record21<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21> value12(T12 value); /** * Set the thirteenth value. */ Record21<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21> value13(T13 value); /** * Set the fourteenth value. */ Record21<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21> value14(T14 value); /** * Set the fifteenth value. */ Record21<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21> value15(T15 value); /** * Set the sixteenth value. */ Record21<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21> value16(T16 value); /** * Set the seventeenth value. */ Record21<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21> value17(T17 value); /** * Set the eighteenth value. */ Record21<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21> value18(T18 value); /** * Set the ninteenth value. */ Record21<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21> value19(T19 value); /** * Set the twentieth value. */ Record21<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21> value20(T20 value); /** * Set the twenty-first value. */ Record21<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21> value21(T21 value); /** * Set all values. */ Record21<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21> values(T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6, T7 t7, T8 t8, T9 t9, T10 t10, T11 t11, T12 t12, T13 t13, T14 t14, T15 t15, T16 t16, T17 t17, T18 t18, T19 t19, T20 t20, T21 t21); /** * {@inheritDoc} */ @Override <T> Record21<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21> with(Field<T> field, T value); /** * {@inheritDoc} */ @Override <T, U> Record21<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21> with(Field<T> field, U value, Converter<? extends T, ? super U> converter); // ------------------------------------------------------------------------ // Value accessors for record destructuring in Kotlin // ------------------------------------------------------------------------ /** * Get the first value. * <p> * This is the same as {@link #value1()}. */ T1 component1(); /** * Get the second value. * <p> * This is the same as {@link #value2()}. */ T2 component2(); /** * Get the third value. * <p> * This is the same as {@link #value3()}. */ T3 component3(); /** * Get the fourth value. * <p> * This is the same as {@link #value4()}. */ T4 component4(); /** * Get the fifth value. * <p> * This is the same as {@link #value5()}. */ T5 component5(); /** * Get the sixth value. * <p> * This is the same as {@link #value6()}. */ T6 component6(); /** * Get the seventh value. * <p> * This is the same as {@link #value7()}. */ T7 component7(); /** * Get the eighth value. * <p> * This is the same as {@link #value8()}. */ T8 component8(); /** * Get the ninth value. * <p> * This is the same as {@link #value9()}. */ T9 component9(); /** * Get the tenth value. * <p> * This is the same as {@link #value10()}. */ T10 component10(); /** * Get the eleventh value. * <p> * This is the same as {@link #value11()}. */ T11 component11(); /** * Get the twelfth value. * <p> * This is the same as {@link #value12()}. */ T12 component12(); /** * Get the thirteenth value. * <p> * This is the same as {@link #value13()}. */ T13 component13(); /** * Get the fourteenth value. * <p> * This is the same as {@link #value14()}. */ T14 component14(); /** * Get the fifteenth value. * <p> * This is the same as {@link #value15()}. */ T15 component15(); /** * Get the sixteenth value. * <p> * This is the same as {@link #value16()}. */ T16 component16(); /** * Get the seventeenth value. * <p> * This is the same as {@link #value17()}. */ T17 component17(); /** * Get the eighteenth value. * <p> * This is the same as {@link #value18()}. */ T18 component18(); /** * Get the ninteenth value. * <p> * This is the same as {@link #value19()}. */ T19 component19(); /** * Get the twentieth value. * <p> * This is the same as {@link #value20()}. */ T20 component20(); /** * Get the twenty-first value. * <p> * This is the same as {@link #value21()}. */ T21 component21(); }
/** * The MIT License (MIT) * * Copyright (c) 2014-2019 <mickael.jeanroy@gmail.com> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.github.mjeanroy.junit.servers.exceptions; /** * Exception thrown when server cannot be initialized. */ @SuppressWarnings("serial") public final class ServerInitializationException extends AbstractEmbeddedServerException { public ServerInitializationException(Throwable throwable) { super(throwable); } }
/* * Copyright 2016-2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.route53.model.transform; import java.util.ArrayList; import javax.xml.stream.events.XMLEvent; import javax.annotation.Generated; import com.amazonaws.services.route53.model.*; import com.amazonaws.transform.Unmarshaller; import com.amazonaws.transform.StaxUnmarshallerContext; import com.amazonaws.transform.SimpleTypeStaxUnmarshallers.*; /** * ListTrafficPolicyInstancesByPolicyResult StAX Unmarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class ListTrafficPolicyInstancesByPolicyResultStaxUnmarshaller implements Unmarshaller<ListTrafficPolicyInstancesByPolicyResult, StaxUnmarshallerContext> { public ListTrafficPolicyInstancesByPolicyResult unmarshall(StaxUnmarshallerContext context) throws Exception { ListTrafficPolicyInstancesByPolicyResult listTrafficPolicyInstancesByPolicyResult = new ListTrafficPolicyInstancesByPolicyResult(); int originalDepth = context.getCurrentDepth(); int targetDepth = originalDepth + 1; if (context.isStartOfDocument()) targetDepth += 1; while (true) { XMLEvent xmlEvent = context.nextEvent(); if (xmlEvent.isEndDocument()) return listTrafficPolicyInstancesByPolicyResult; if (xmlEvent.isAttribute() || xmlEvent.isStartElement()) { if (context.testExpression("TrafficPolicyInstances", targetDepth)) { listTrafficPolicyInstancesByPolicyResult.withTrafficPolicyInstances(new ArrayList<TrafficPolicyInstance>()); continue; } if (context.testExpression("TrafficPolicyInstances/TrafficPolicyInstance", targetDepth)) { listTrafficPolicyInstancesByPolicyResult .withTrafficPolicyInstances(TrafficPolicyInstanceStaxUnmarshaller.getInstance().unmarshall(context)); continue; } if (context.testExpression("HostedZoneIdMarker", targetDepth)) { listTrafficPolicyInstancesByPolicyResult.setHostedZoneIdMarker(StringStaxUnmarshaller.getInstance().unmarshall(context)); continue; } if (context.testExpression("TrafficPolicyInstanceNameMarker", targetDepth)) { listTrafficPolicyInstancesByPolicyResult.setTrafficPolicyInstanceNameMarker(StringStaxUnmarshaller.getInstance().unmarshall(context)); continue; } if (context.testExpression("TrafficPolicyInstanceTypeMarker", targetDepth)) { listTrafficPolicyInstancesByPolicyResult.setTrafficPolicyInstanceTypeMarker(StringStaxUnmarshaller.getInstance().unmarshall(context)); continue; } if (context.testExpression("IsTruncated", targetDepth)) { listTrafficPolicyInstancesByPolicyResult.setIsTruncated(BooleanStaxUnmarshaller.getInstance().unmarshall(context)); continue; } if (context.testExpression("MaxItems", targetDepth)) { listTrafficPolicyInstancesByPolicyResult.setMaxItems(StringStaxUnmarshaller.getInstance().unmarshall(context)); continue; } } else if (xmlEvent.isEndElement()) { if (context.getCurrentDepth() < originalDepth) { return listTrafficPolicyInstancesByPolicyResult; } } } } private static ListTrafficPolicyInstancesByPolicyResultStaxUnmarshaller instance; public static ListTrafficPolicyInstancesByPolicyResultStaxUnmarshaller getInstance() { if (instance == null) instance = new ListTrafficPolicyInstancesByPolicyResultStaxUnmarshaller(); return instance; } }
package com.technology.jep.jepriashowcase.custom.auto; /* public class CustomAutoImpl<A extends JepRiaShowcaseAuto> extends ApplicationEntranceAuto<A, JepRiaShowcasePageManager> implements CustomAuto { public CustomAutoImpl(A jepRiaShowcaseAuto, JepRiaShowcasePageManager pageManager) { super(jepRiaShowcaseAuto, pageManager); } @Override public GoodsAuto openFullScreenModules() { pages.customPage.ensurePageLoaded(); assert(isLoggedIn()); pages.customPage.fullScreenModulesButton.click(); return this.applicationManager.getGoodsAuto(true); } @Override public boolean isReady() { pages.customPage.ensurePageLoaded(); return true; } @Override public boolean isLoggedIn() { return pages.customPage.ensurePageLoaded() .isElementPresent(By.id(CustomAutomationConstant.LOGGED_IN_USER_ID)) && pages.customPage.getWebDriver().findElement(By.id(CustomAutomationConstant.LOGGED_IN_USER_ID)).isDisplayed(); } @Override public void login(String login, String password) { pages.customPage .ensurePageLoaded() .setUsername(login) .setPassword(password) .doLogin(); pages.customPage.ensureAuthorized(); } @Override public void logout() { pages.customPage.doLogout(); pages.customPage.ensureLogout(); } @Override public boolean isAuthorizedFailed(){ return pages.customPage.isElementPresent(By.id(CustomAutomationConstant.ERROR_LABEL_ID)) && pages.customPage.isElementPresent(By.id(CustomAutomationConstant.LOGIN_BUTTON_ID)) && !pages.customPage.loginButton.isEnabled(); } } */
/* * 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.aliyuncs.mopen.model.v20180211; import com.aliyuncs.RpcAcsRequest; import com.aliyuncs.http.ProtocolType; import com.aliyuncs.http.MethodType; /** * @author auto create * @version */ public class MoPenAddGroupMemberRequest extends RpcAcsRequest<MoPenAddGroupMemberResponse> { public MoPenAddGroupMemberRequest() { super("MoPen", "2018-02-11", "MoPenAddGroupMember", "mopen"); setProtocol(ProtocolType.HTTPS); setMethod(MethodType.POST); } private String groupId; private String deviceName; public String getGroupId() { return this.groupId; } public void setGroupId(String groupId) { this.groupId = groupId; if(groupId != null){ putBodyParameter("GroupId", groupId); } } public String getDeviceName() { return this.deviceName; } public void setDeviceName(String deviceName) { this.deviceName = deviceName; if(deviceName != null){ putBodyParameter("DeviceName", deviceName); } } @Override public Class<MoPenAddGroupMemberResponse> getResponseClass() { return MoPenAddGroupMemberResponse.class; } }
package fr.javatronic.blog.massive.annotation1.sub1; import fr.javatronic.blog.processor.Annotation_001; @Annotation_001 public class Class_7538 { }
package org.hl7.fhir.r4.model; /* Copyright (c) 2011+, HL7, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of HL7 nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Set; import org.hl7.fhir.exceptions.DefinitionException; import org.hl7.fhir.r4.context.IWorkerContext; import org.hl7.fhir.r4.model.ElementDefinition.ElementDefinitionBindingComponent; import org.hl7.fhir.r4.model.ExpressionNode.CollectionStatus; import org.hl7.fhir.utilities.Utilities; public class TypeDetails { public static final String FHIR_NS = "http://hl7.org/fhir/StructureDefinition/"; public static final String FP_NS = "http://hl7.org/fhirpath/"; public static final String FP_String = "http://hl7.org/fhirpath/String"; public static final String FP_Boolean = "http://hl7.org/fhirpath/Boolean"; public static final String FP_Integer = "http://hl7.org/fhirpath/Integer"; public static final String FP_Decimal = "http://hl7.org/fhirpath/Decimal"; public static final String FP_Quantity = "http://hl7.org/fhirpath/Quantity"; public static final String FP_DateTime = "http://hl7.org/fhirpath/DateTime"; public static final String FP_Time = "http://hl7.org/fhirpath/Time"; public static final String FP_SimpleTypeInfo = "http://hl7.org/fhirpath/SimpleTypeInfo"; public static final String FP_ClassInfo = "http://hl7.org/fhirpath/ClassInfo"; public static class ProfiledType { private String uri; private List<String> profiles; // or, not and private List<ElementDefinitionBindingComponent> bindings; public ProfiledType(String n) { uri = ns(n); } public String getUri() { return uri; } public boolean hasProfiles() { return profiles != null && profiles.size() > 0; } public List<String> getProfiles() { return profiles; } public boolean hasBindings() { return bindings != null && bindings.size() > 0; } public List<ElementDefinitionBindingComponent> getBindings() { return bindings; } public static String ns(String n) { return Utilities.isAbsoluteUrl(n) ? n : FHIR_NS+n; } public void addProfile(String profile) { if (profiles == null) profiles = new ArrayList<String>(); profiles.add(profile); } public void addBinding(ElementDefinitionBindingComponent binding) { bindings = new ArrayList<ElementDefinitionBindingComponent>(); bindings.add(binding); } public boolean hasBinding(ElementDefinitionBindingComponent b) { return false; // todo: do we need to do this? } public void addProfiles(List<CanonicalType> list) { if (profiles == null) profiles = new ArrayList<String>(); for (UriType u : list) profiles.add(u.getValue()); } public boolean isSystemType() { return uri.startsWith(FP_NS); } } private List<ProfiledType> types = new ArrayList<ProfiledType>(); private CollectionStatus collectionStatus; public TypeDetails(CollectionStatus collectionStatus, String... names) { super(); this.collectionStatus = collectionStatus; for (String n : names) { this.types.add(new ProfiledType(n)); } } public TypeDetails(CollectionStatus collectionStatus, Set<String> names) { super(); this.collectionStatus = collectionStatus; for (String n : names) { addType(new ProfiledType(n)); } } public TypeDetails(CollectionStatus collectionStatus, ProfiledType pt) { super(); this.collectionStatus = collectionStatus; this.types.add(pt); } public String addType(String n) { ProfiledType pt = new ProfiledType(n); String res = pt.uri; addType(pt); return res; } public String addType(String n, String p) { ProfiledType pt = new ProfiledType(n); pt.addProfile(p); String res = pt.uri; addType(pt); return res; } public void addType(ProfiledType pt) { for (ProfiledType et : types) { if (et.uri.equals(pt.uri)) { if (pt.profiles != null) { for (String p : pt.profiles) { if (et.profiles == null) et.profiles = new ArrayList<String>(); if (!et.profiles.contains(p)) et.profiles.add(p); } } if (pt.bindings != null) { for (ElementDefinitionBindingComponent b : pt.bindings) { if (et.bindings == null) et.bindings = new ArrayList<ElementDefinitionBindingComponent>(); if (!et.hasBinding(b)) et.bindings.add(b); } } return; } } types.add(pt); } public void addTypes(Collection<String> names) { for (String n : names) addType(new ProfiledType(n)); } public boolean hasType(IWorkerContext context, String... tn) { for (String n: tn) { String t = ProfiledType.ns(n); if (typesContains(t)) return true; if (Utilities.existsInList(n, "boolean", "string", "integer", "decimal", "Quantity", "dateTime", "time", "ClassInfo", "SimpleTypeInfo")) { t = FP_NS+Utilities.capitalize(n); if (typesContains(t)) return true; } } for (String n: tn) { String id = n.contains("#") ? n.substring(0, n.indexOf("#")) : n; String tail = null; if (n.contains("#")) { tail = n.substring( n.indexOf("#")+1); tail = tail.substring(tail.indexOf(".")); } String t = ProfiledType.ns(n); StructureDefinition sd = context.fetchResource(StructureDefinition.class, t); while (sd != null) { if (tail == null && typesContains(sd.getUrl())) return true; if (tail == null && getSystemType(sd.getUrl()) != null && typesContains(getSystemType(sd.getUrl()))) return true; if (tail != null && typesContains(sd.getUrl()+"#"+sd.getType()+tail)) return true; if (sd.hasBaseDefinition()) { if (sd.getBaseDefinition().equals("http://hl7.org/fhir/StructureDefinition/Element") && !sd.getType().equals("string") && sd.getType().equals("uri")) sd = context.fetchResource(StructureDefinition.class, "http://hl7.org/fhir/StructureDefinition/string"); else sd = context.fetchResource(StructureDefinition.class, sd.getBaseDefinition()); } else sd = null; } } return false; } private String getSystemType(String url) { if (url.startsWith("http://hl7.org/fhir/StructureDefinition/")) { String code = url.substring(40); if (Utilities.existsInList(code, "string", "boolean", "integer", "decimal", "dateTime", "time", "Quantity")) return FP_NS+Utilities.capitalize(code); } return null; } private boolean typesContains(String t) { for (ProfiledType pt : types) if (pt.uri.equals(t)) return true; return false; } public void update(TypeDetails source) { for (ProfiledType pt : source.types) addType(pt); if (collectionStatus == null) collectionStatus = source.collectionStatus; else if (source.collectionStatus == CollectionStatus.UNORDERED) collectionStatus = source.collectionStatus; else collectionStatus = CollectionStatus.ORDERED; } public TypeDetails union(TypeDetails right) { TypeDetails result = new TypeDetails(null); if (right.collectionStatus == CollectionStatus.UNORDERED || collectionStatus == CollectionStatus.UNORDERED) result.collectionStatus = CollectionStatus.UNORDERED; else result.collectionStatus = CollectionStatus.ORDERED; for (ProfiledType pt : types) result.addType(pt); for (ProfiledType pt : right.types) result.addType(pt); return result; } public TypeDetails intersect(TypeDetails right) { TypeDetails result = new TypeDetails(null); if (right.collectionStatus == CollectionStatus.UNORDERED || collectionStatus == CollectionStatus.UNORDERED) result.collectionStatus = CollectionStatus.UNORDERED; else result.collectionStatus = CollectionStatus.ORDERED; for (ProfiledType pt : types) { boolean found = false; for (ProfiledType r : right.types) found = found || pt.uri.equals(r.uri); if (found) result.addType(pt); } for (ProfiledType pt : right.types) result.addType(pt); return result; } public boolean hasNoTypes() { return types.isEmpty(); } public Set<String> getTypes() { Set<String> res = new HashSet<String>(); for (ProfiledType pt : types) res.add(pt.uri); return res; } public TypeDetails toSingleton() { TypeDetails result = new TypeDetails(CollectionStatus.SINGLETON); result.types.addAll(types); return result; } public CollectionStatus getCollectionStatus() { return collectionStatus; } public boolean hasType(String n) { String t = ProfiledType.ns(n); if (typesContains(t)) return true; if (Utilities.existsInList(n, "boolean", "string", "integer", "decimal", "Quantity", "dateTime", "time", "ClassInfo", "SimpleTypeInfo")) { t = FP_NS+Utilities.capitalize(n); if (typesContains(t)) return true; } return false; } public boolean hasType(Set<String> tn) { for (String n: tn) { String t = ProfiledType.ns(n); if (typesContains(t)) return true; if (Utilities.existsInList(n, "boolean", "string", "integer", "decimal", "Quantity", "dateTime", "time", "ClassInfo", "SimpleTypeInfo")) { t = FP_NS+Utilities.capitalize(n); if (typesContains(t)) return true; } } return false; } public String describe() { return getTypes().toString(); } public String getType() { for (ProfiledType pt : types) return pt.uri; return null; } @Override public String toString() { return (collectionStatus == null ? collectionStatus.SINGLETON.toString() : collectionStatus.toString()) + getTypes().toString(); } public String getTypeCode() throws DefinitionException { if (types.size() != 1) throw new DefinitionException("Multiple types? ("+types.toString()+")"); for (ProfiledType pt : types) if (pt.uri.startsWith("http://hl7.org/fhir/StructureDefinition/")) return pt.uri.substring(40); else return pt.uri; return null; } public List<ProfiledType> getProfiledTypes() { return types; } public boolean hasBinding() { for (ProfiledType pt : types) { if (pt.hasBindings()) return true; } return false; } public ElementDefinitionBindingComponent getBinding() { for (ProfiledType pt : types) { for (ElementDefinitionBindingComponent b : pt.getBindings()) return b; } return null; } }
package net.anotheria.moskito.core.snapshot; import net.anotheria.moskito.core.dynamic.OnDemandStatsProducer; import net.anotheria.moskito.core.predefined.ServiceStats; import net.anotheria.moskito.core.registry.ProducerRegistryFactory; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertEquals; /** * TODO comment this class * * @author lrosenberg * @since 20.03.13 14:38 */ public class SnapshotRepositoryTest extends BaseSnapshotTest{ @Before public void setup(){ System.setProperty("JUNITTEST", "true"); ProducerRegistryFactory.reset(); } @Test public void testConsumeCycle() throws Exception{ MySnapshotConsumer consumer = new MySnapshotConsumer(); assertEquals(0, consumer.getConsumedCount()); SnapshotRepository.getInstance().addConsumer(consumer); String intervalName = "5m"; //force interval update forceIntervalUpdate(intervalName); OnDemandStatsProducer<ServiceStats> producer = setupProducer(); ProducerRegistryFactory.getProducerRegistryInstance().registerProducer(producer); //add first stat. ServiceStats stat1 = producer.getStats("case1"); stat1.addRequest(); stat1.addExecutionTime(100); //100 milliseconds //force interval update forceIntervalUpdate(intervalName); assertEquals(1, consumer.getConsumedCount()); SnapshotRepository.getInstance().removeConsumer(consumer); //force interval update forceIntervalUpdate(intervalName); assertEquals(1, consumer.getConsumedCount()); } private static class MySnapshotConsumer implements SnapshotConsumer{ private int consumedCount = 0; @Override public void consumeSnapshot(ProducerSnapshot snapshot) { consumedCount++; } public int getConsumedCount(){ return consumedCount; } @Override public String toString(){ return getClass().getSimpleName()+" "+getConsumedCount(); } @Override public boolean equals(Object o){ return o == this; } } }
package com.example.exa1_intermedios_acreditar; import androidx.appcompat.app.AppCompatActivity; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentManager; import androidx.fragment.app.FragmentTransaction; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.Toast; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //Procedimiento estándar para colocar un fragmento en android //startActivity(intento); AnotherFrag frag = new AnotherFrag(); cambiarFragmento(frag); //ft2.setCustomAnimations(R.anim.anim_enter, R.anim.anim_exit, R.anim.anim_enter, R.anim.anim_exit); } public void cambiarFragmento(Fragment f){ FragmentTransaction fr = getSupportFragmentManager().beginTransaction(); fr.setCustomAnimations(R.anim.anim_enter, R.anim.anim_exit, R.anim.anim_enter, R.anim.anim_exit); fr.replace(R.id.container, f).addToBackStack(null).commit(); } }
package net.jodah.failsafe; import static org.testng.Assert.assertEquals; import org.testng.annotations.Test; @Test public class AbstractExecutionTest { public void testRandomizeDelayForFactor() { assertEquals(AbstractExecution.randomizeDelay(100, .5, 0), 150); assertEquals(AbstractExecution.randomizeDelay(100, .5, .25), 125); assertEquals(AbstractExecution.randomizeDelay(100, .5, .5), 100); assertEquals(AbstractExecution.randomizeDelay(100, .5, .75), 75); assertEquals(AbstractExecution.randomizeDelay(100, .5, .9999), 50); assertEquals(AbstractExecution.randomizeDelay(500, .5, .25), 625); assertEquals(AbstractExecution.randomizeDelay(500, .5, .75), 375); assertEquals(AbstractExecution.randomizeDelay(50000, .5, .25), 62500); } public void testRandomizeDelayForDuration() { assertEquals(AbstractExecution.randomizeDelay(100, 50, 0), 150); assertEquals(AbstractExecution.randomizeDelay(100, 50, .25), 125); assertEquals(AbstractExecution.randomizeDelay(100, 50, .5), 100); assertEquals(AbstractExecution.randomizeDelay(100, 50, .75), 75); assertEquals(AbstractExecution.randomizeDelay(100, 50, .9999), 50); assertEquals(AbstractExecution.randomizeDelay(500, 50, .25), 525); assertEquals(AbstractExecution.randomizeDelay(50000, 5000, .25), 52500); } }
// Author: Jamie Hunter, 2019 // Refer to LICENSE.TXT for copyright and license information // package org.jprolog.flags; import org.jprolog.bootstrap.Interned; import org.jprolog.exceptions.FutureFlagError; import org.jprolog.exceptions.PrologDomainError; import org.jprolog.execution.Environment; import org.jprolog.expressions.Term; import java.util.Optional; import java.util.function.Consumer; /** * Structured options parsed from a list of option atoms, used for reading. */ public class ReadOptions implements Flags { private static final OptionParser<ReadOptions> parser = new OptionParser<>(); static { // TODO: These are all placeholders and not yet parsed parser.booleanFlag(Interned.internAtom("backquoted_string"), (o, v) -> o.backquotedString = v); parser.booleanFlag(Interned.internAtom("character_escapes"), (o, v) -> o.characterEscapes = v); parser.booleanFlag(Interned.internAtom("cycles"), (o, v) -> o.cycles = v); parser.booleanFlag(Interned.internAtom("dotlists"), (o, v) -> o.dotlists = v); parser.enumFlag(Interned.internAtom("double_quotes"), PrologFlags.Quotes.class, (o, v) -> o.doubleQuotes = v); parser.enumFlag(Interned.internAtom("singletons"), Singletons.class, (o, v) -> o.singletons = v); parser.enumFlag(Interned.internAtom("syntax_errors"), SyntaxErrors.class, (o, v) -> o.syntaxErrors = v); parser.enumFlag(Interned.internAtom("full_stop"), FullStop.class, (o, v) -> o.fullStop = v); parser.enumFlag(Interned.internAtom("white_space"), WhiteSpace.class, (o, v) -> o.whiteSpace = v); parser.booleanFlag(Interned.internAtom("var_prefix"), (o, v) -> o.varPrefix = v); parser.other(Interned.internAtom("variables"), (o, v) -> o.variables = Optional.of(v)); parser.other(Interned.internAtom("variable_names"), (o, v) -> o.variableNames = Optional.of(v)); } /** * If true, backquotes produces a string object */ public boolean backquotedString; /** * If true (default), parse '\' in strings */ public boolean characterEscapes; /** * Override how double-quotes are handled */ public PrologFlags.Quotes doubleQuotes; /** * If true, handle the @(Template, Substitution) operator for producing cycling terms */ public boolean cycles = false; /** * If true, read .(x,y) as a list term. */ public boolean dotlists = false; /** * Specify how to handle variables that are mentioned only once. */ public Singletons singletons = Singletons.ATOM_warning; /** * Specify how to handle syntax errors. */ public SyntaxErrors syntaxErrors = SyntaxErrors.ATOM_error; /** * Specify how to handle missing '.' at end of file. */ public FullStop fullStop = FullStop.ATOM_required; /** * Specify how to handle whitespace. */ public WhiteSpace whiteSpace = WhiteSpace.ATOM_skip; /** * Force variables to begin with '_' */ public boolean varPrefix = false; /** * Receives list of variables read */ public Optional<Term> variables = Optional.empty(); /** * Receive list of unifiable variables */ public Optional<Term> variableNames = Optional.empty(); /** * Set this object of options from a list of option terms. * * @param environment Execution environment * @param prepare Prepare defaults * @param optionsTerm List of options */ public ReadOptions(Environment environment, Consumer<ReadOptions> prepare, Term optionsTerm) { PrologFlags flags = environment.getFlags(); try { backquotedString = flags.backQuotes == PrologFlags.Quotes.ATOM_string; doubleQuotes = flags.doubleQuotes; characterEscapes = flags.characterEscapes; if (prepare != null) { prepare.accept(this); } parser.apply(environment, this, optionsTerm); } catch (FutureFlagError ffe) { throw PrologDomainError.error(environment, environment.internAtom("read_option"), ffe.getTerm(), ffe); } } /** * Set this object of options from a list of option terms. * * @param environment Execution environment * @param optionsTerm List of options */ public ReadOptions(Environment environment, Term optionsTerm) { this(environment, null, optionsTerm); } public enum Singletons { ATOM_warning } public enum SyntaxErrors { ATOM_error, ATOM_fail, ATOM_quiet } public enum FullStop { ATOM_required, ATOM_optional } public enum WhiteSpace { ATOM_skip, ATOM_atom } }
package com.example.android_hw2; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.TextView; public class ResultActivity extends AppCompatActivity { TextView test; int currentScore; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_result); currentScore=getIntent().getIntExtra("score",0); test=findViewById(R.id.ResultTextView); if(currentScore!=10) test.setText("the current score is "+currentScore +" Try to get to 10 ,loser."); if(currentScore==10) test.setText("the current score is "+currentScore +" YOU WIN!"); } }
package br.edu.utfpr.cp.emater.midmipsystem.entity.pulverisation; import br.edu.utfpr.cp.emater.midmipsystem.entity.base.AuditingPersistenceEntity; import br.edu.utfpr.cp.emater.midmipsystem.entity.mip.GrowthPhase; import br.edu.utfpr.cp.emater.midmipsystem.entity.survey.Survey; import br.edu.utfpr.cp.emater.midmipsystem.exception.ProductUseClassDifferFromTargetException; import java.io.Serializable; import java.util.Date; import java.util.HashSet; import java.util.Set; import javax.persistence.ElementCollection; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToOne; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.validation.constraints.NotNull; import lombok.Builder; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.Setter; @Entity @Getter @Setter @EqualsAndHashCode(onlyExplicitlyIncluded = true) public class PulverisationOperation extends AuditingPersistenceEntity implements Serializable { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @EqualsAndHashCode.Include @ManyToOne private Survey survey; @EqualsAndHashCode.Include @Temporal(TemporalType.DATE) @NotNull(message = "A data da coleta precisa ser informada!") private Date sampleDate; @Enumerated(EnumType.STRING) private GrowthPhase growthPhase; private double caldaVolume; @ElementCollection private Set<PulverisationOperationOccurrence> operationOccurrences; @Builder public static PulverisationOperation create(Long id, Survey survey, Date sampleDate, GrowthPhase growthPhase, double caldaVolume) { var instance = new PulverisationOperation(); instance.setId(id); instance.setSurvey(survey); instance.setSampleDate(sampleDate); instance.setGrowthPhase(growthPhase); instance.setCaldaVolume(caldaVolume); return instance; } public PulverisationOperation() { super(); this.setOperationOccurrences(new HashSet<>()); } public boolean addOperationOccurrence(Product product, double productPrice, double productDose, Target target) throws ProductUseClassDifferFromTargetException { if (product.getUseClass() != target.getUseClass()) { throw new ProductUseClassDifferFromTargetException(); } else { var occurrence = PulverisationOperationOccurrence.builder().product(product).productPrice(productPrice).dose(productDose).target(target).build(); var result = this.getOperationOccurrences().add(occurrence); return result; } } public double getSoyaPrice() { if (this.getSurvey() != null) { if (this.getSurvey().getPulverisationData() != null) { return this.getSurvey().getPulverisationData().getSoyaPrice(); } } return 0; } public double getApplicationCostCurrency() { if (this.getSurvey() != null) { if (this.getSurvey().getPulverisationData() != null) { return this.getSurvey().getPulverisationData().getApplicationCostCurrency(); } } return 0; } public double getApplicationCostQty() { if (this.getSurvey() != null) { if (this.getSurvey().getPulverisationData() != null) { return this.getSurvey().getPulverisationData().getApplicationCostQty(); } } return 0; } public double getTotalOperationCostCurrency() { if (this.getOperationOccurrences() != null) { if (this.getOperationOccurrences().size() != 0) { var totalCostWithProducts = this.getOperationOccurrences().stream().mapToDouble(occurrence -> occurrence.getProductCostCurrency()).sum(); return totalCostWithProducts + this.getApplicationCostCurrency(); } } return 0; } }
package io.localmotion.initiative.controller; import com.coxautodev.graphql.tools.GraphQLQueryResolver; import io.localmotion.initiative.projection.InitiativeProjection; import lombok.NoArgsConstructor; import lombok.extern.slf4j.Slf4j; import javax.inject.Inject; import javax.inject.Singleton; @Slf4j @Singleton @NoArgsConstructor @SuppressWarnings("unused") public class InitiativeQuery implements GraphQLQueryResolver { @Inject private InitiativeProjection initiativeProjection; /** * Compute and return the total number of members. * @return total member count */ public long totalVolunteers() { return initiativeProjection.getInitiatives(null).stream() .flatMap(playground -> playground.getMembers().stream()) .distinct() .count(); } }
package br.com.zup.mercadolivre.categoria; import javax.persistence.*; import javax.validation.constraints.NotBlank; @Entity public class Categoria { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @NotBlank @Column(unique = true) private String nome; @ManyToOne @JoinColumn(name = "categoriaMae") private Categoria categoriaMae; public Categoria() { } public Categoria(String nome, Categoria categoriaMae) { this.nome = nome; this.categoriaMae = categoriaMae; } public Long getId() { return id; } public String getNome() { return nome; } public Categoria getCategoriaMae() { return categoriaMae; } }
package com.vscode4teaching.vscode4teachingserver.services.websockets; import com.google.gson.Gson; import com.vscode4teaching.vscode4teachingserver.model.User; import com.vscode4teaching.vscode4teachingserver.services.exceptions.EmptyJSONObjectException; import com.vscode4teaching.vscode4teachingserver.services.exceptions.EmptyURIException; import com.vscode4teaching.vscode4teachingserver.services.exceptions.MissingPropertyException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import org.springframework.web.socket.CloseStatus; import org.springframework.web.socket.TextMessage; import org.springframework.web.socket.WebSocketSession; import org.springframework.web.socket.handler.TextWebSocketHandler; import java.io.IOException; import java.net.URI; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.concurrent.CopyOnWriteArrayList; @Component public class SocketHandler extends TextWebSocketHandler { private final List<WebSocketSession> sessions = new CopyOnWriteArrayList<>(); private static final Logger logger = LoggerFactory.getLogger(SocketHandler.class); @Override public void handleTextMessage(WebSocketSession session, TextMessage message) throws InterruptedException, IOException, EmptyURIException, EmptyJSONObjectException, MissingPropertyException { URI uri = session.getUri(); if (uri == null) { logger.error("Empty URI received from WebSocket session: " + session.getId()); throw new EmptyURIException(); } String path = uri.getPath(); switch (path) { case "/dashboard-refresh": { handleRefresh(message); break; } case "/liveshare": { handleLiveshare(message); break; } } deleteClosedSessions(); } @Override public void afterConnectionEstablished(WebSocketSession session) throws Exception { URI uri = session.getUri(); if (uri == null) { logger.error("Empty URI received from WebSocket session: " + session.getId()); throw new EmptyURIException(); } String path = uri.getPath(); switch (path) { case "/dashboard-refresh": case "/liveshare": { sessions.add(session); break; } } if (session.getPrincipal() == null) { logger.info("Websocket connection with unidentified user"); } else { logger.info("Websocket connection with user: " + Objects.requireNonNull(session.getPrincipal()).getName()); } deleteClosedSessions(); } @Override public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception { sessions.remove(session); if (session.getPrincipal() == null) { logger.info("Closed Websocket connection with unidentified user"); } else { logger.info("Closed Websocket connection with user: " + Objects.requireNonNull(session.getPrincipal()).getName()); } } public void refreshExerciseDashboards(Set<User> teachers) { logger.info("Exercise user info updated, sending updates to teachers " + teachers.toString() + "..."); for (User teacher : teachers) { sessions.stream() .filter(t -> t.isOpen() && Objects.requireNonNull(t.getPrincipal()).getName().equals(teacher.getUsername())) .forEach(t -> { try { t.sendMessage(new TextMessage("{\"handle\":\"refresh\"}")); } catch (IOException e) { System.out.println("Error sending websocket message: " + e.getMessage()); } }); } logger.info("Updates sent to teachers"); } private void handleRefresh(TextMessage message) throws EmptyJSONObjectException, MissingPropertyException { logger.info("Websockets: handling refresh"); Map<String, String> objects = getMessageObjects(message); if (objects == null) throw new EmptyJSONObjectException(); String teacherUsername = objects.get("teacher"); if (teacherUsername == null) throw new MissingPropertyException("teacher"); sessions.stream() .filter(t -> t.isOpen() && Objects.requireNonNull(t.getPrincipal()).getName().equals(teacherUsername)) .forEach(t -> { try { t.sendMessage(new TextMessage("{\"handle\":\"refresh\"}")); } catch (IOException e) { System.out.println("Error sending websocket message: " + e.getMessage()); } }); } private void handleLiveshare(TextMessage message) throws EmptyJSONObjectException, MissingPropertyException { logger.info("Websockets: handling liveshare"); Map<String, String> objects = getMessageObjects(message); if (objects == null) throw new EmptyJSONObjectException(); String code = objects.get("code"); String from = objects.get("from"); String target = objects.get("target"); if (code == null || target == null) throw new MissingPropertyException("code", "target"); sessions.stream() .filter(t -> t.isOpen() && Objects.requireNonNull(t.getPrincipal()).getName().equals(target)) .forEach(t -> { try { t.sendMessage(new TextMessage("{\"handle\":\"liveshare\",\"from\":\"" + from + "\",\"code\":\"" + code + "\"}")); } catch (IOException e) { System.out.println("Error sending websocket message: " + e.getMessage()); } }); } private Map<String, String> getMessageObjects(TextMessage message) { try { logger.info("Received WebSocket message"); logger.info(message.getPayload()); return new Gson().fromJson(message.getPayload(), Map.class); } catch (Exception e) { System.out.println("Error parsing websocket message: " + e.getMessage()); return null; } } private void deleteClosedSessions() { sessions.removeIf(t -> !t.isOpen()); } }
/* * Copyright © 2014-2020 Vladlen V. Larionov and others as noted. * * 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 colesico.framework.undertow.internal; import colesico.framework.http.*; import io.undertow.security.api.SecurityContext; import io.undertow.server.HttpServerExchange; import io.undertow.server.handlers.Cookie; import io.undertow.server.handlers.form.FormData; import io.undertow.server.handlers.form.FormDataParser; import io.undertow.util.HeaderValues; import io.undertow.util.HttpString; import org.apache.commons.lang3.StringUtils; import java.io.*; import java.nio.charset.StandardCharsets; import java.nio.file.Path; import java.util.*; import java.util.stream.Stream; /** * @author Vladlen Larionov */ public final class HttpRequestImpl implements HttpRequest { private final HttpServerExchange exchange; private FormData formData = null; private Map<String, String> headers = null; private Map<String, HttpCookie> cookies = null; private HttpValues<String, String> queryParams = null; private HttpValues<String, String> postParams = null; private HttpValues<String, HttpFile> postFiles = null; private InputStream inputStream = null; public HttpRequestImpl(HttpServerExchange exchange) { this.exchange = exchange; } public HttpServerExchange getExchange() { return exchange; } public FormData getFormData() { return formData; } private Map<String, String> createHeadersMap() { Map headersMap = new HashMap<>(); Collection<HttpString> headerNames = exchange.getRequestHeaders().getHeaderNames(); for (HttpString headerName : headerNames) { headersMap.put(headerName.toString(), exchange.getRequestHeaders().getFirst(headerName)); } return Collections.unmodifiableMap(headersMap); } private Map<String, HttpCookie> createCookiesMap() { Map<String, HttpCookie> cookiesMap = new HashMap<>(); for (Map.Entry<String, Cookie> e : exchange.getRequestCookies().entrySet()) { Cookie cookie = e.getValue(); HttpCookie httpCookie = new HttpCookie() .setName(cookie.getName()) .setValue(cookie.getValue()) .setDomain(cookie.getDomain()) .setPath(cookie.getPath()) .setExpires(cookie.getExpires()) .setSecure(cookie.isSecure()) .setHttpOnly(cookie.isHttpOnly()); cookiesMap.put(e.getKey(), httpCookie); } return Collections.unmodifiableMap(cookiesMap); } private HttpValues<String, String> createQueryParams() { Map<String, MultiValue<String>> params = new HashMap<>(); for (Map.Entry<String, Deque<String>> e : exchange.getQueryParameters().entrySet()) { params.put(e.getKey(), new MultiValue<>(e.getValue())); } return new HttpValues<>(params); } private void createPostValues() { Map<String, MultiValue<String>> params = new HashMap<>(); postParams = new HttpValues<>(params); Map<String, MultiValue<HttpFile>> files = new HashMap<>(); postFiles = new HttpValues<>(files); if (formData == null) { formData = exchange.getAttachment(FormDataParser.FORM_DATA); } if (formData == null) { return; } for (String paramName : formData) { Deque<FormData.FormValue> values = formData.get(paramName); List<String> foundParams = new ArrayList<>(); List<HttpFile> foundFiles = new ArrayList<>(); for (FormData.FormValue value : values) { if (value.isFileItem()) { HeaderValues hv = value.getHeaders().get("Content-Type"); String contentType = hv != null ? hv.getFirst() : ""; HttpFile httpFile = new HttpFileImpl(value.getFileName(), contentType, value.getFileItem().getFile()); foundFiles.add(httpFile); } else { foundParams.add(value.getValue()); } } if (!foundFiles.isEmpty()) { files.put(paramName, new MultiValue<>(foundFiles)); } if (!foundParams.isEmpty()) { params.put(paramName, new MultiValue<>(foundParams)); } } } @Override public HttpMethod getRequestMethod() { return HttpMethod.of(exchange.getRequestMethod().toString()); } @Override public String getRequestScheme() { return exchange.getRequestScheme(); } @Override public String getQueryString() { return exchange.getQueryString(); } @Override public Map<String, String> getHeaders() { if (headers == null) { headers = createHeadersMap(); } return headers; } @Override public Map<String, HttpCookie> getCookies() { if (cookies == null) { cookies = createCookiesMap(); } return cookies; } @Override public HttpValues<String, String> getQueryParameters() { if (queryParams == null) { queryParams = createQueryParams(); } return queryParams; } @Override public HttpValues<String, String> getPostParameters() { if (postParams == null) { createPostValues(); } return postParams; } @Override public HttpValues<String, HttpFile> getPostFiles() { if (postFiles == null) { createPostValues(); } return postFiles; } @Override public String getRequestURI() { return StringUtils.substringBefore(exchange.getRequestURI(), "?"); } @Override public String getHost() { return exchange.getHostName(); } @Override public Integer getPort() { return exchange.getHostPort(); } @Override public InputStream getInputStream() { if (inputStream == null) { exchange.startBlocking(); inputStream = exchange.getInputStream(); } return inputStream; } @Override public void dump(final Writer out) { try { out.append(getRequestMethod().getName() + " " + getRequestScheme() + "://" + exchange.getHostName() + ":" + exchange.getDestinationAddress().getPort() + exchange.getRequestURI() + "?" + exchange.getQueryString() + "\n"); out.append("protocol: " + exchange.getProtocol() + "\n"); out.append("remoteAddr: " + exchange.getSourceAddress() + "\n"); out.append("remoteHost: " + exchange.getSourceAddress().getHostName() + "\n"); out.append("isSecure:" + exchange.isSecure() + "\n"); for (HeaderValues header : exchange.getRequestHeaders()) { for (String value : header) { out.append("header: " + header.getHeaderName() + "=" + value + "\n"); } } Map<String, Cookie> cookies = exchange.getRequestCookies(); if (cookies != null) { for (Map.Entry<String, Cookie> entry : cookies.entrySet()) { Cookie cookie = entry.getValue(); out.append("cookie: " + cookie.getName() + "=" + cookie.getValue() + "\n"); } } final SecurityContext sc = exchange.getSecurityContext(); if (sc != null) { if (sc.isAuthenticated()) { out.append("authType: " + sc.getMechanismName() + "\n"); out.append("principle: " + sc.getAuthenticatedAccount().getPrincipal() + "\n"); } else { out.append("authType: none" + "\n"); } } if (inputStream == null) { out.append("body:\n"); if (!exchange.isInIoThread()) { exchange.startBlocking(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); exchange.getInputStream().transferTo(baos); inputStream = new ByteArrayInputStream(baos.toByteArray()); Stream<String> bodyLines = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8)).lines(); bodyLines.forEach(line -> { try { out.append(line).append('\n'); } catch (IOException e) { throw new RuntimeException(e); } }); inputStream.reset(); } else { out.append("Request is in non-blocking mode. Can't dump request body"); } } else { out.append("body: Input stream has already been open\n"); } } catch (Exception e) { throw new RuntimeException(e); } } private static class HttpFileImpl implements HttpFile { private final String fileName; private final String contentType; private final Path filePath; public HttpFileImpl(String fileName, String contentType, Path filePath) { this.fileName = fileName; this.contentType = contentType; this.filePath = filePath; } @Override public void release() { try { boolean res = filePath.toFile().delete(); if (!res) { throw new RuntimeException("Cant's release uploaded file"); } } catch (Exception e) { throw new RuntimeException(e); } } @Override public String getFileName() { return fileName; } @Override public String getContentType() { return contentType; } @Override public InputStream getInputStream() { try { return new FileInputStream(filePath.toFile()); } catch (Exception e) { throw new RuntimeException(e); } } } }
/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activemq.openwire.v11; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Marshalling code for Open Wire Format for ProducerInfoMarshaller * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class ProducerInfoMarshaller extends BaseCommandMarshaller { /** * Return the type of Data Structure we marshal * @return short representation of the type data structure */ public byte getDataStructureType() { return ProducerInfo.DATA_STRUCTURE_TYPE; } /** * @return a new object instance */ public DataStructure createObject() { return new ProducerInfo(); } /** * Un-marshal an object instance from the data input stream * * @param o the object to un-marshal * @param dataIn the data input stream to build the object from * @throws IOException */ public void tightUnmarshal(OpenWireFormat wireFormat, Object o, DataInput dataIn, BooleanStream bs) throws IOException { super.tightUnmarshal(wireFormat, o, dataIn, bs); ProducerInfo info = (ProducerInfo)o; info.setProducerId((org.apache.activemq.command.ProducerId) tightUnmarsalCachedObject(wireFormat, dataIn, bs)); info.setDestination((org.apache.activemq.command.ActiveMQDestination) tightUnmarsalCachedObject(wireFormat, dataIn, bs)); if (bs.readBoolean()) { short size = dataIn.readShort(); org.apache.activemq.command.BrokerId value[] = new org.apache.activemq.command.BrokerId[size]; for( int i=0; i < size; i++ ) { value[i] = (org.apache.activemq.command.BrokerId) tightUnmarsalNestedObject(wireFormat,dataIn, bs); } info.setBrokerPath(value); } else { info.setBrokerPath(null); } info.setDispatchAsync(bs.readBoolean()); info.setWindowSize(dataIn.readInt()); } /** * Write the booleans that this object uses to a BooleanStream */ public int tightMarshal1(OpenWireFormat wireFormat, Object o, BooleanStream bs) throws IOException { ProducerInfo info = (ProducerInfo)o; int rc = super.tightMarshal1(wireFormat, o, bs); rc += tightMarshalCachedObject1(wireFormat, (DataStructure)info.getProducerId(), bs); rc += tightMarshalCachedObject1(wireFormat, (DataStructure)info.getDestination(), bs); rc += tightMarshalObjectArray1(wireFormat, info.getBrokerPath(), bs); bs.writeBoolean(info.isDispatchAsync()); return rc + 4; } /** * Write a object instance to data output stream * * @param o the instance to be marshaled * @param dataOut the output stream * @throws IOException thrown if an error occurs */ public void tightMarshal2(OpenWireFormat wireFormat, Object o, DataOutput dataOut, BooleanStream bs) throws IOException { super.tightMarshal2(wireFormat, o, dataOut, bs); ProducerInfo info = (ProducerInfo)o; tightMarshalCachedObject2(wireFormat, (DataStructure)info.getProducerId(), dataOut, bs); tightMarshalCachedObject2(wireFormat, (DataStructure)info.getDestination(), dataOut, bs); tightMarshalObjectArray2(wireFormat, info.getBrokerPath(), dataOut, bs); bs.readBoolean(); dataOut.writeInt(info.getWindowSize()); } /** * Un-marshal an object instance from the data input stream * * @param o the object to un-marshal * @param dataIn the data input stream to build the object from * @throws IOException */ public void looseUnmarshal(OpenWireFormat wireFormat, Object o, DataInput dataIn) throws IOException { super.looseUnmarshal(wireFormat, o, dataIn); ProducerInfo info = (ProducerInfo)o; info.setProducerId((org.apache.activemq.command.ProducerId) looseUnmarsalCachedObject(wireFormat, dataIn)); info.setDestination((org.apache.activemq.command.ActiveMQDestination) looseUnmarsalCachedObject(wireFormat, dataIn)); if (dataIn.readBoolean()) { short size = dataIn.readShort(); org.apache.activemq.command.BrokerId value[] = new org.apache.activemq.command.BrokerId[size]; for( int i=0; i < size; i++ ) { value[i] = (org.apache.activemq.command.BrokerId) looseUnmarsalNestedObject(wireFormat,dataIn); } info.setBrokerPath(value); } else { info.setBrokerPath(null); } info.setDispatchAsync(dataIn.readBoolean()); info.setWindowSize(dataIn.readInt()); } /** * Write the booleans that this object uses to a BooleanStream */ public void looseMarshal(OpenWireFormat wireFormat, Object o, DataOutput dataOut) throws IOException { ProducerInfo info = (ProducerInfo)o; super.looseMarshal(wireFormat, o, dataOut); looseMarshalCachedObject(wireFormat, (DataStructure)info.getProducerId(), dataOut); looseMarshalCachedObject(wireFormat, (DataStructure)info.getDestination(), dataOut); looseMarshalObjectArray(wireFormat, info.getBrokerPath(), dataOut); dataOut.writeBoolean(info.isDispatchAsync()); dataOut.writeInt(info.getWindowSize()); } }
package com.javaweb.aspect; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.aspectj.lang.annotation.Pointcut; import com.javaweb.handler.MultipleDataSourceManage; @Aspect public class DataSourceAspect { //切入点execution @Pointcut("execution(* com.javaweb..*.test..*(..))") public void methodCall() { /*do nothing*/ } @Before(value="methodCall()") //这里写具体的数据源切换逻辑 public void beforeMethod(JoinPoint joinPoint) throws Throwable { String methodExecution = joinPoint.getStaticPart().toShortString(); //System.out.println(methodExecution); if(methodExecution.equals("execution(APPTestController.testGet(..))")){ MultipleDataSourceManage.setDataSourceKey("dataSource"); }else if(methodExecution.equals("execution(APPTestController.testGet2(..))")){ MultipleDataSourceManage.setDataSourceKey("dataSource2"); }else if(methodExecution.equals("execution(APPTestController.testGet3(..))")){ MultipleDataSourceManage.setDataSourceKey("dataSource3"); }else{ MultipleDataSourceManage.setDataSourceKey("dataSource"); } } }
package org.occideas; import org.occideas.common.NodeType; import org.occideas.entity.JobModule; import org.occideas.entity.PossibleAnswer; import org.occideas.entity.Question; import org.occideas.mapper.ModuleMapperImpl; import org.occideas.mapper.PossibleAnswerMapperImpl; import java.util.ArrayList; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; public class CommonDataGenerator { private static final AtomicInteger idNode = new AtomicInteger(); private static String[] letters = new String[]{"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"}; private static ModuleMapperImpl moduleMapper = new ModuleMapperImpl(); private static PossibleAnswerMapperImpl answerMapper = new PossibleAnswerMapperImpl(); public static JobModule createModule(int numberOfChildQuestions, int numberOfAnswers) { JobModule module = new JobModule(); long generatedIdNode = CommonDataGenerator.idNode.incrementAndGet(); module.setName("Sample Intro Module " + generatedIdNode); module.setIdNode(generatedIdNode); module.setChildNodes(createQuestions(numberOfChildQuestions, numberOfAnswers)); return module; } public static Question createQuestion(String nodeNumber, int numberOfAnswers) { Question question = new Question(); long generatedIdNode = CommonDataGenerator.idNode.incrementAndGet(); question.setIdNode(generatedIdNode); question.setName("Sample Question " + generatedIdNode); question.setNumber(nodeNumber); question.setType(NodeType.Q_MULTIPLE.getDescription()); question.setChildNodes(createPossibleAnswer(numberOfAnswers)); return question; } public static List<Question> createQuestions(int numberOfQuestions, int numberOfAnswers) { List<Question> questions = new ArrayList<>(); int letterInd = 0; for (int i = 0; i < numberOfQuestions; i++) { if (letterInd == letters.length - 1) { letterInd = 0; } questions.add(createQuestion(i + 1 + letters[letterInd], numberOfAnswers)); } return questions; } public static PossibleAnswer createPossibleAnswer(String nodeNumber) { PossibleAnswer possibleAnswer = new PossibleAnswer(); long generatedIdNode = CommonDataGenerator.idNode.incrementAndGet(); possibleAnswer.setIdNode(generatedIdNode); possibleAnswer.setName("Sample Answer " + generatedIdNode); possibleAnswer.setNumber(nodeNumber); return possibleAnswer; } public static PossibleAnswer createPossibleAnswer(String nodeNumber, int numberOfChildQuestions, int numberOfChildAnswers) { PossibleAnswer possibleAnswer = new PossibleAnswer(); long generatedIdNode = CommonDataGenerator.idNode.incrementAndGet(); possibleAnswer.setIdNode(generatedIdNode); possibleAnswer.setName("Sample Answer " + generatedIdNode); possibleAnswer.setNumber(nodeNumber); possibleAnswer.setChildNodes(createQuestions(numberOfChildQuestions, numberOfChildAnswers)); return possibleAnswer; } public static List<PossibleAnswer> createPossibleAnswer(int numberOfAnswers) { List<PossibleAnswer> possibleAnswers = new ArrayList<>(); int letterInd = 0; for (int i = 0; i < numberOfAnswers; i++) { if (letterInd == letters.length - 1) { letterInd = 0; } possibleAnswers.add(createPossibleAnswer(i + 1 + letters[letterInd])); } return possibleAnswers; } public static List<PossibleAnswer> createPossibleAnswers(int numberOfChildAnswers, int numberOfChildQuestions) { List<PossibleAnswer> possibleAnswers = new ArrayList<>(); int letterInd = 0; for (int i = 0; i < numberOfChildAnswers; i++) { if (letterInd == letters.length - 1) { letterInd = 0; } possibleAnswers.add(createPossibleAnswer(i + 1 + letters[letterInd], numberOfChildQuestions, numberOfChildAnswers)); } return possibleAnswers; } public static void resetIdNodes() { idNode.set(0); } }
package api.press.repo; import api.press.model.Question; import api.press.repo.IRepo.IQuestionRepo; import api.press.util.QueryUtil; import lombok.RequiredArgsConstructor; import org.springframework.dao.DataIntegrityViolationException; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Repository; import java.util.ArrayList; import java.util.Collections; @Repository @RequiredArgsConstructor public class QuestionRepo implements IQuestionRepo { private final JdbcTemplate jdbcTemplate; @Override public Integer insert(Question question) { String statement = "INSERT INTO question" + "(post_id, viewer_id, body, create_date, viewer_name)" + " VALUES (?,?,?,?,?)"; ArrayList<? super Object> values = new ArrayList<>(); Collections.addAll(values, question.getPostId(), question.getViewerId(), question.getBody() , question.getCreateDate(), question.getViewerName()); return QueryUtil.insertRow(jdbcTemplate, statement, values); } @Override public int update(Question question) { String query = "update question set body = ? where id = ? and viewer_id = ? and post_id = ?"; return jdbcTemplate.update(query, question.getBody(), question.getId(), question.getViewerId(),question.getPostId()); } @Override public int delete(Integer postId, Integer questionId, Integer viewerId) { return jdbcTemplate.update("delete from question where id = " + questionId + " and post_id = " + postId + " and viewer_id = " + viewerId); } }
/******************************************************************************* * Copyright (c) 2015-2018 Skymind, Inc. * * This program and the accompanying materials are made available under the * terms of the Apache License, Version 2.0 which is available at * https://www.apache.org/licenses/LICENSE-2.0. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. * * SPDX-License-Identifier: Apache-2.0 ******************************************************************************/ package org.nd4j.linalg.api.ops.impl.transforms.strict; import org.nd4j.autodiff.samediff.SDVariable; import org.nd4j.imports.NoOpNameFoundException; import org.nd4j.linalg.api.ndarray.INDArray; import org.nd4j.linalg.api.ops.BaseTransformOp; import org.nd4j.linalg.api.ops.BaseTransformStrictOp; import java.util.List; /** * Tan Derivative elementwise function * * @author raver119@gmail.com */ public class TanDerivative extends BaseTransformStrictOp { public TanDerivative() {} public TanDerivative(INDArray x, INDArray z) { super(x, z); } public TanDerivative(INDArray x) { super(x); } @Override public int opNum() { return 8; } @Override public String opName() { return "tanderivative"; } @Override public String onnxName() { throw new NoOpNameFoundException("No onnx op opName found for " + opName()); } @Override public String tensorflowName() { throw new NoOpNameFoundException("No tensorflow op opName found for " + opName()); } @Override public List<SDVariable> doDiff(List<SDVariable> f1) { return null; } }
/******************************************************************************* * Copyright (C) 2018 Joao Sousa * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. ******************************************************************************/ package org.rookit.utils.string.template; import javax.annotation.concurrent.ThreadSafe; @ThreadSafe final class SelfTemplate1 implements Template1 { @Override public String build(final CharSequence parameter) { return parameter.toString(); } }
package io.onedev.server.infomanager; import java.io.File; import java.util.Date; import javax.inject.Inject; import javax.inject.Singleton; import org.joda.time.DateTime; import com.google.common.collect.Lists; import io.onedev.commons.loader.Listen; import io.onedev.server.event.codecomment.CodeCommentEvent; import io.onedev.server.event.entity.EntityRemoved; import io.onedev.server.event.issue.IssueEvent; import io.onedev.server.event.pullrequest.PullRequestCodeCommentEvent; import io.onedev.server.event.pullrequest.PullRequestEvent; import io.onedev.server.model.CodeComment; import io.onedev.server.model.Issue; import io.onedev.server.model.PullRequest; import io.onedev.server.model.User; import io.onedev.server.persistence.annotation.Transactional; import io.onedev.server.storage.StorageManager; import jetbrains.exodus.env.Environment; import jetbrains.exodus.env.Store; import jetbrains.exodus.env.Transaction; import jetbrains.exodus.env.TransactionalComputable; import jetbrains.exodus.env.TransactionalExecutable; /** * Store project visit information here as we only need to load a single database to sort projects based on user * visit information * * @author robin * */ @Singleton public class DefaultUserInfoManager extends AbstractEnvironmentManager implements UserInfoManager { private static final int INFO_VERSION = 6; private static final String PULL_REQUEST_VISIT_STORE = "pullRequestVisit"; private static final String PULL_REQUEST_CODE_COMMENTS_VISIT_STORE = "pullRequestCodeCommentsVisit"; private static final String CODE_COMMENT_VISIT_STORE = "codeCommentVisit"; private static final String ISSUE_VISIT_STORE = "issueVisit"; private final StorageManager storageManager; @Inject public DefaultUserInfoManager(StorageManager storageManager) { this.storageManager = storageManager; } @Transactional @Listen public void on(EntityRemoved event) { if (event.getEntity() instanceof User) removeEnv(event.getEntity().getId().toString()); } @Override protected File getEnvDir(String envKey) { return storageManager.getUserInfoDir(Long.valueOf(envKey)); } @Override protected int getEnvVersion() { return INFO_VERSION; } @Override public void visitIssue(User user, Issue issue) { Environment env = getEnv(issue.getProject().getId().toString()); Store store = getStore(env, ISSUE_VISIT_STORE); env.executeInTransaction(new TransactionalExecutable() { @Override public void execute(Transaction txn) { long time = new DateTime().plusSeconds(1).getMillis(); writeLong(store, txn, new LongsByteIterable(Lists.newArrayList(user.getId(), issue.getId())), time); } }); } @Override public void visitPullRequest(User user, PullRequest request) { Environment env = getEnv(request.getTargetProject().getId().toString()); Store store = getStore(env, PULL_REQUEST_VISIT_STORE); env.executeInTransaction(new TransactionalExecutable() { @Override public void execute(Transaction txn) { long time = new DateTime().plusSeconds(1).getMillis(); writeLong(store, txn, new LongsByteIterable(Lists.newArrayList(user.getId(), request.getId())), time); } }); } @Override public void visitPullRequestCodeComments(User user, PullRequest request) { Environment env = getEnv(request.getTargetProject().getId().toString()); Store store = getStore(env, PULL_REQUEST_CODE_COMMENTS_VISIT_STORE); env.executeInTransaction(new TransactionalExecutable() { @Override public void execute(Transaction txn) { long time = new DateTime().plusSeconds(1).getMillis(); writeLong(store, txn, new LongsByteIterable(Lists.newArrayList(user.getId(), request.getId())), time); } }); } @Override public void visitCodeComment(User user, CodeComment comment) { Environment env = getEnv(comment.getProject().getId().toString()); Store store = getStore(env, CODE_COMMENT_VISIT_STORE); env.executeInTransaction(new TransactionalExecutable() { @Override public void execute(Transaction txn) { long time = new DateTime().plusSeconds(1).getMillis(); writeLong(store, txn, new LongsByteIterable(Lists.newArrayList(user.getId(), comment.getId())), time); } }); } @Override public Date getPullRequestVisitDate(User user, PullRequest request) { Environment env = getEnv(request.getTargetProject().getId().toString()); Store store = getStore(env, PULL_REQUEST_VISIT_STORE); return env.computeInTransaction(new TransactionalComputable<Date>() { @Override public Date compute(Transaction txn) { long millis = readLong(store, txn, new LongsByteIterable(Lists.newArrayList(user.getId(), request.getId())), -1); if (millis != -1) return new Date(millis); else return null; } }); } @Override public Date getIssueVisitDate(User user, Issue issue) { Environment env = getEnv(issue.getProject().getId().toString()); Store store = getStore(env, ISSUE_VISIT_STORE); return env.computeInTransaction(new TransactionalComputable<Date>() { @Override public Date compute(Transaction txn) { long millis = readLong(store, txn, new LongsByteIterable(Lists.newArrayList(user.getId(), issue.getId())), -1); if (millis != -1) return new Date(millis); else return null; } }); } @Override public Date getPullRequestCodeCommentsVisitDate(User user, PullRequest request) { Environment env = getEnv(request.getTargetProject().getId().toString()); Store store = getStore(env, PULL_REQUEST_CODE_COMMENTS_VISIT_STORE); return env.computeInTransaction(new TransactionalComputable<Date>() { @Override public Date compute(Transaction txn) { long millis = readLong(store, txn, new LongsByteIterable(Lists.newArrayList(user.getId(), request.getId())), -1); if (millis != -1) return new Date(millis); else return null; } }); } @Override public Date getCodeCommentVisitDate(User user, CodeComment comment) { Environment env = getEnv(comment.getProject().getId().toString()); Store store = getStore(env, CODE_COMMENT_VISIT_STORE); return env.computeInTransaction(new TransactionalComputable<Date>() { @Override public Date compute(Transaction txn) { long millis = readLong(store, txn, new LongsByteIterable(Lists.newArrayList(user.getId(), comment.getId())), -1); if (millis != -1) return new Date(millis); else return null; } }); } @Listen public void on(IssueEvent event) { if (event.getUser() != null) visitIssue(event.getUser(), event.getIssue()); } @Listen public void on(CodeCommentEvent event) { if (event.getUser() != null) visitCodeComment(event.getUser(), event.getComment()); } @Listen public void on(PullRequestEvent event) { if (event.getUser() != null) { visitPullRequest(event.getUser(), event.getRequest()); if (event instanceof PullRequestCodeCommentEvent) { visitPullRequest(event.getUser(), event.getRequest()); visitPullRequestCodeComments(event.getUser(), event.getRequest()); } } } }
package com.froobworld.nabsuite.modules.admin.command; import cloud.commandframework.Command; import cloud.commandframework.arguments.standard.StringArgument; import cloud.commandframework.context.CommandContext; import com.froobworld.nabsuite.command.NabCommand; import com.froobworld.nabsuite.command.argument.arguments.PlayerIdentityArgument; import com.froobworld.nabsuite.command.argument.predicate.ArgumentPredicate; import com.froobworld.nabsuite.data.identity.PlayerIdentity; import com.froobworld.nabsuite.modules.admin.AdminModule; import org.bukkit.command.CommandSender; import java.util.Optional; public class BanCommand extends NabCommand { private final AdminModule adminModule; public BanCommand(AdminModule adminModule) { super( "ban", "Ban a player from the server.", "nabsuite.command.ban", CommandSender.class ); this.adminModule = adminModule; } @Override public void execute(CommandContext<CommandSender> context) { PlayerIdentity player = context.get("player"); Optional<String> reason = context.getOptional("reason"); adminModule.getPunishmentManager().getBanEnforcer().ban( player, context.getSender(), reason.orElse(null), -1 ); } @Override public Command.Builder<CommandSender> populateBuilder(Command.Builder<CommandSender> builder) { return builder .argument(new PlayerIdentityArgument<>( true, "player", adminModule.getPlugin().getPlayerIdentityManager(), true, new ArgumentPredicate<>( true, (context, player) -> adminModule.getPunishmentManager().getPunishments(player.getUuid()).getBanPunishment() == null, "That player is already banned." ) )) .argument(StringArgument.<CommandSender>newBuilder("reason") .greedy() .asOptional() ); } }
/* * Copyright (C) 2016 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.pets; import android.app.AlertDialog; import android.app.LoaderManager; import android.content.ContentValues; import android.content.CursorLoader; import android.content.DialogInterface; import android.content.Intent; import android.content.Loader; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.NavUtils; import android.support.v7.app.AppCompatActivity; import android.text.TextUtils; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.Spinner; import android.widget.Toast; import com.example.android.pets.data.PetContract.PetEntry; import com.example.android.pets.data.PetDbHelper; /** * Allows user to create a new pet or edit an existing one. */ public class EditorActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<Cursor> { /** Identifier for the pet data loader */ private static final int EXISTING_PET_LOADER = 0; /** Content URI for the existing pet (null if it's a new pet) */ private Uri mCurrentPetUri; /** EditText field to enter the pet's name */ private EditText mNameEditText; /** EditText field to enter the pet's breed */ private EditText mBreedEditText; /** EditText field to enter the pet's weight */ private EditText mWeightEditText; /** EditText field to enter the pet's gender */ private Spinner mGenderSpinner; /** * Gender of the pet. The possible values are: * 0 for unknown gender, 1 for male, 2 for female. */ private int mGender = PetEntry.GENDER_UNKNOWN; /** Boolean flag that keeps track of whether the pet has been edited (true) or not (false) */ private boolean mPetHasChanged = false; /** * OnTouchListener that listens for any user touches on a View, implying that they are modifying * the view, and we change the mPetHasChanged boolean to true. */ private View.OnTouchListener mTouchListener = new View.OnTouchListener() { @Override public boolean onTouch(View view, MotionEvent motionEvent) { mPetHasChanged = true; return false; } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_editor); // Check the intent Intent intent = getIntent(); mCurrentPetUri = intent.getData(); if (mCurrentPetUri == null) { setTitle(R.string.editor_activity_title_new_pet); // Invalidate the options menu, so the "Delete" menu option can be hidden. // (It doesn't make sense to delete a pet that hasn't been created yet.) invalidateOptionsMenu(); } else { setTitle(R.string.editor_activity_title_edit_pet); // Initialise the loader getLoaderManager().initLoader(EXISTING_PET_LOADER, null, this); } // Find all relevant views that we will need to read user input from mNameEditText = (EditText) findViewById(R.id.edit_pet_name); mBreedEditText = (EditText) findViewById(R.id.edit_pet_breed); mWeightEditText = (EditText) findViewById(R.id.edit_pet_weight); mGenderSpinner = (Spinner) findViewById(R.id.spinner_gender); // Setup OnTouchListeners on all the input fields, so we can determine if the user // has touched or modified them. This will let us know if there are unsaved changes // or not, if the user tries to leave the editor without saving. mNameEditText.setOnTouchListener(mTouchListener); mBreedEditText.setOnTouchListener(mTouchListener); mWeightEditText.setOnTouchListener(mTouchListener); mGenderSpinner.setOnTouchListener(mTouchListener); setupSpinner(); } /** * Setup the dropdown spinner that allows the user to select the gender of the pet. */ private void setupSpinner() { // Create adapter for spinner. The list options are from the String array it will use // the spinner will use the default layout ArrayAdapter genderSpinnerAdapter = ArrayAdapter.createFromResource(this, R.array.array_gender_options, android.R.layout.simple_spinner_item); // Specify dropdown layout style - simple list view with 1 item per line genderSpinnerAdapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line); // Apply the adapter to the spinner mGenderSpinner.setAdapter(genderSpinnerAdapter); // Set the integer mSelected to the constant values mGenderSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { String selection = (String) parent.getItemAtPosition(position); if (!TextUtils.isEmpty(selection)) { if (selection.equals(getString(R.string.gender_male))) { mGender = PetEntry.GENDER_MALE; // Male } else if (selection.equals(getString(R.string.gender_female))) { mGender = PetEntry.GENDER_FEMALE; // Female } else { mGender = PetEntry.GENDER_UNKNOWN; // Unknown } } } // Because AdapterView is an abstract class, onNothingSelected must be defined @Override public void onNothingSelected(AdapterView<?> parent) { mGender = PetEntry.GENDER_UNKNOWN; // Unknown } }); } /** * Get user input from editor and save pet into database. */ private void savePet() { String nameString = mNameEditText.getText().toString().trim(); String breedString = mBreedEditText.getText().toString().trim(); String weightString = mWeightEditText.getText().toString().trim(); // Check if this is supposed to be a new pet // and check if all the fields in the editor are blank if (mCurrentPetUri == null && TextUtils.isEmpty(nameString) && TextUtils.isEmpty(breedString) && TextUtils.isEmpty(weightString) && mGender == PetEntry.GENDER_UNKNOWN) { // Since no fields were modified, we can return early without creating a new pet. // No need to create ContentValues and no need to do any ContentProvider operations. return; } // and pass the context, which is the current activity. PetDbHelper mDbHelper = new PetDbHelper(this); // Create and/or open a database to read from it SQLiteDatabase db = mDbHelper.getReadableDatabase(); // Create a new map of values, where column names are the keys ContentValues values = new ContentValues(); values.put(PetEntry.COLUMN_PET_NAME, nameString); values.put(PetEntry.COLUMN_PET_BREED, breedString); values.put(PetEntry.COLUMN_PET_GENDER, mGender); // If the weight is not provided by the user, don't try to parse the string into an // integer value. Use 0 by default. int weight = 0; if (!TextUtils.isEmpty(weightString)) { weight = Integer.parseInt(weightString); } values.put(PetEntry.COLUMN_PET_WEIGHT, weight); if (mCurrentPetUri == null) { // Insert a new pet into the provider, returning the content URI for the new pet. Uri newUri = getContentResolver().insert(PetEntry.CONTENT_URI, values); String toastMessage; if (newUri == null) { toastMessage = "Error with saving pet"; } else { toastMessage = "Pet saved"; } Toast.makeText(this, toastMessage, Toast.LENGTH_SHORT).show(); } else { // Otherwise this is an EXISTING pet, so update the pet with content URI: mCurrentPetUri // and pass in the new ContentValues. Pass in null for the selection and selection args // because mCurrentPetUri will already identify the correct row in the database that // we want to modify. int rowsAffected = getContentResolver().update(mCurrentPetUri, values, null, null); // Show a toast message depending on whether or not the update was successful. if (rowsAffected == 0) { // If no rows were affected, then there was an error with the update. Toast.makeText(this, getString(R.string.editor_update_pet_failed), Toast.LENGTH_SHORT).show(); } else { // Otherwise, the update was successful and we can display a toast. Toast.makeText(this, getString(R.string.editor_update_pet_successful), Toast.LENGTH_SHORT).show(); } } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu options from the res/menu/menu_editor.xml file. // This adds menu items to the app bar. getMenuInflater().inflate(R.menu.menu_editor, menu); return true; } @Override public boolean onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu); // If this is a new pet, hide the "Delete" menu item. if (mCurrentPetUri == null) { MenuItem menuItem = menu.findItem(R.id.action_delete); menuItem.setVisible(false); } return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // User clicked on a menu option in the app bar overflow menu switch (item.getItemId()) { // Respond to a click on the "Save" menu option case R.id.action_save: savePet(); finish(); return true; // Respond to a click on the "Delete" menu option case R.id.action_delete: // Pop up confirmation dialog for deletion showDeleteConfirmationDialog(); return true; // Respond to a click on the "Up" arrow button in the app bar case android.R.id.home: // If the pet hasn't changed, continue with navigating up to parent activity // which is the {@link CatalogActivity}. if (!mPetHasChanged) { NavUtils.navigateUpFromSameTask(EditorActivity.this); return true; } // Otherwise if there are unsaved changes, setup a dialog to warn the user. // Create a click listener to handle the user confirming that // changes should be discarded. DialogInterface.OnClickListener discardButtonClickListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { // User clicked "Discard" button, navigate to parent activity. NavUtils.navigateUpFromSameTask(EditorActivity.this); } }; // Show a dialog that notifies the user they have unsaved changes showUnsavedChangesDialog(discardButtonClickListener); return true; } return super.onOptionsItemSelected(item); } /** * This method is called when the back button is pressed. */ @Override public void onBackPressed() { // If the pet hasn't changed, continue with handling back button press if (!mPetHasChanged) { super.onBackPressed(); return; } // Otherwise if there are unsaved changes, setup a dialog to warn the user. // Create a click listener to handle the user confirming that changes should be discarded. DialogInterface.OnClickListener discardButtonClickListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { // User clicked "Discard" button, close the current activity. finish(); } }; // Show dialog that there are unsaved changes showUnsavedChangesDialog(discardButtonClickListener); } @Override public Loader<Cursor> onCreateLoader(int i, Bundle bundle) { // Since the editor shows all pet attributes, define a projection that contains // all columns from the pet table String[] projection = { PetEntry._ID, PetEntry.COLUMN_PET_NAME, PetEntry.COLUMN_PET_BREED, PetEntry.COLUMN_PET_GENDER, PetEntry.COLUMN_PET_WEIGHT }; // This loader will execute the ContentProvider's query method on a background thread return new CursorLoader(this, // Parent activity context mCurrentPetUri, // Query the content URI for the current pet projection, // Columns to include in the resulting Cursor null, // No selection clause null, // No selection arguments null); } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) { // Bail early if the cursor is null or there is less than 1 row in the cursor if (cursor == null || cursor.getCount() < 1) { return; } // Proceed with moving to the first row of the cursor and reading data from it // (This should be the only row in the cursor) if (cursor.moveToFirst()) { // Find the columns of pet attributes that we're interested in int nameColumnIndex = cursor.getColumnIndex(PetEntry.COLUMN_PET_NAME); int breedColumnIndex = cursor.getColumnIndex(PetEntry.COLUMN_PET_BREED); int genderColumnIndex = cursor.getColumnIndex(PetEntry.COLUMN_PET_GENDER); int weightColumnIndex = cursor.getColumnIndex(PetEntry.COLUMN_PET_WEIGHT); // Extract out the value from the Cursor for the given column index String name = cursor.getString(nameColumnIndex); String breed = cursor.getString(breedColumnIndex); int gender = cursor.getInt(genderColumnIndex); int weight = cursor.getInt(weightColumnIndex); // Update the views on the screen with the values from the database mNameEditText.setText(name); mBreedEditText.setText(breed); mWeightEditText.setText(Integer.toString(weight)); // Gender is a dropdown spinner, so map the constant value from the database // into one of the dropdown options (0 is Unknown, 1 is Male, 2 is Female). // Then call setSelection() so that option is displayed on screen as the current selection. switch (gender) { case PetEntry.GENDER_MALE: mGenderSpinner.setSelection(1); break; case PetEntry.GENDER_FEMALE: mGenderSpinner.setSelection(2); break; default: mGenderSpinner.setSelection(0); break; } } } @Override public void onLoaderReset(Loader<Cursor> loader) { // If the loader is invalidated, clear out all the data from the input fields. mNameEditText.setText(""); mBreedEditText.setText(""); mWeightEditText.setText(""); mGenderSpinner.setSelection(0); // Select "Unknown" gender } /** * Show a dialog that warns the user there are unsaved changes that will be lost * if they continue leaving the editor. * * @param discardButtonClickListener is the click listener for what to do when * the user confirms they want to discard their changes */ private void showUnsavedChangesDialog( DialogInterface.OnClickListener discardButtonClickListener) { // Create an AlertDialog.Builder and set the message, and click listeners // for the postivie and negative buttons on the dialog. AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(R.string.unsaved_changes_dialog_msg); builder.setPositiveButton(R.string.discard, discardButtonClickListener); builder.setNegativeButton(R.string.keep_editing, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // User clicked the "Keep editing" button, so dismiss the dialog // and continue editing the pet. if (dialog != null) { dialog.dismiss(); } } }); // Create and show the AlertDialog AlertDialog alertDialog = builder.create(); alertDialog.show(); } /** * Prompt the user to confirm that they want to delete this pet. */ private void showDeleteConfirmationDialog() { // Create an AlertDialog.Builder and set the message, and click listeners // for the positive and negative buttons on the dialog. AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(R.string.delete_dialog_msg); builder.setPositiveButton(R.string.delete, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // User clicked the "Delete" button, so delete the pet. deletePet(); } }); builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // User clicked the "Cancel" button, so dismiss the dialog // and continue editing the pet. if (dialog != null) { dialog.dismiss(); } } }); // Create and show the AlertDialog AlertDialog alertDialog = builder.create(); alertDialog.show(); } /** * Perform the deletion of the pet in the database. */ private void deletePet() { // Only perform the delete if this is an existing pet. if (mCurrentPetUri != null) { // Call the ContentResolver to delete the pet at the given content URI. // Pass in null for the selection and selection args because the mCurrentPetUri // content URI already identifies the pet that we want. int rowsDeleted = getContentResolver().delete(mCurrentPetUri, null, null); // Show a toast message depending on whether or not the delete was successful. if (rowsDeleted == 0) { // If no rows were deleted, then there was an error with the delete. Toast.makeText(this, getString(R.string.editor_delete_pet_failed), Toast.LENGTH_SHORT).show(); } else { // Otherwise, the delete was successful and we can display a toast. Toast.makeText(this, getString(R.string.editor_delete_pet_successful), Toast.LENGTH_SHORT).show(); } } // Close the activity finish(); } }
package kr.ac.kopo.kopo44.DAO; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import kr.ac.kopo.kopo44.DTO.UserDTO; public class UserDAOImpl implements UserDAO { private Connection conn;//자바와 데이터베이스 연결 private PreparedStatement pstmt;//쿼리문 대기 및 설정 private ResultSet rset;//결과값 받아오기 (블로그에서는 rs라고 선언) private static UserDAOImpl instance; //기본 생성자 //UserDAO가 실행되면 자동으로 생성되는 부분 //메소드마다 반복되는 코드를 이곳에 넣으면 코드가 간소화된다. public UserDAOImpl() { try { Class.forName("com.mysql.cj.jdbc.Driver"); conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/BOARD","root","gusehdqls92410!@"); } catch (Exception e) { e.printStackTrace(); } } public static UserDAOImpl getInstance() { if (instance == null) { instance = new UserDAOImpl(); } return instance; } //로그인영역 @Override public int login (String userID, String userPassword) { String sql = "select userPassword from USER WHERE userID = ?"; try { pstmt = conn.prepareStatement(sql);//sql쿼리문을 대기 시킨다. pstmt.setString(1, userID); rset = pstmt.executeQuery(); if (rset.next()) { if (rset.getString(1).equals(userPassword)) { return 1;//로그인 성공 } else return 0;//비밀번호 틀림 } return -1;//아이디 없음 }catch (Exception e) { e.printStackTrace(); } return -2;//오류 } //회원가입 영역 @Override public int join (UserDTO user) { String sql = "insert into USER(userID, userPassword, userName, userGender, userEmail) values (?, ?, ?, ?, ?)"; try { pstmt = conn.prepareStatement(sql); pstmt.setString(1, user.getUserID()); pstmt.setString(2, user.getUserPassword()); pstmt.setString(3, user.getUserName()); pstmt.setString(4, user.getUserGender()); pstmt.setString(5, user.getUserEmail()); return pstmt.executeUpdate(); } catch (Exception e) { e.printStackTrace(); } return -1; } }
/* * Copyright 2018-2020 adorsys GmbH & Co KG * * 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 de.adorsys.psd2.xs2a.service.validator.pis.authorisation.cancellation; import de.adorsys.psd2.consent.api.pis.PisCommonPaymentResponse; import de.adorsys.psd2.xs2a.core.domain.TppMessageInformation; import de.adorsys.psd2.xs2a.core.error.ErrorType; import de.adorsys.psd2.xs2a.core.error.MessageError; import de.adorsys.psd2.xs2a.core.service.validator.ValidationResult; import de.adorsys.psd2.xs2a.core.tpp.TppInfo; import de.adorsys.psd2.xs2a.service.RequestProviderService; import de.adorsys.psd2.xs2a.service.validator.OauthPaymentValidator; import de.adorsys.psd2.xs2a.service.validator.pis.authorisation.PisAuthorisationValidator; import de.adorsys.psd2.xs2a.service.validator.tpp.PisTppInfoValidator; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import static de.adorsys.psd2.xs2a.core.error.MessageErrorCode.*; import static de.adorsys.psd2.xs2a.core.profile.PaymentType.SINGLE; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @ExtendWith(MockitoExtension.class) class GetPaymentCancellationAuthorisationScaStatusValidatorTest { private static final TppInfo TPP_INFO = buildTppInfo("authorisation number"); private static final TppInfo INVALID_TPP_INFO = buildTppInfo("invalid authorisation number"); private static final String AUTHORISATION_ID = "random"; private static final String WRONG_AUTHORISATION_ID = "random but wrong"; private static final MessageError TPP_VALIDATION_ERROR = new MessageError(ErrorType.PIS_401, TppMessageInformation.of(UNAUTHORIZED)); private static final MessageError PAYMENT_PRODUCT_VALIDATION_ERROR = new MessageError(ErrorType.PIS_403, TppMessageInformation.of(PRODUCT_INVALID_FOR_PAYMENT)); private static final MessageError AUTHORISATION_VALIDATION_ERROR = new MessageError(ErrorType.PIS_403, TppMessageInformation.of(RESOURCE_UNKNOWN_403)); private static final String CORRECT_PAYMENT_PRODUCT = "sepa-credit-transfers"; private static final String WRONG_PAYMENT_PRODUCT = "sepa-credit-transfers111"; @Mock private PisAuthorisationValidator pisAuthorisationValidator; @Mock private PisTppInfoValidator pisTppInfoValidator; @Mock private RequestProviderService requestProviderService; @Mock private OauthPaymentValidator oauthPaymentValidator; @InjectMocks private GetPaymentCancellationAuthorisationScaStatusValidator getPaymentCancellationAuthorisationScaStatusValidator; @BeforeEach void setUp() { // Inject pisTppInfoValidator via setter getPaymentCancellationAuthorisationScaStatusValidator.setPisValidators(pisTppInfoValidator); } @Test void validate_withValidPaymentObject_shouldReturnValid() { // Given PisCommonPaymentResponse commonPaymentResponse = buildPisCommonPaymentResponse(TPP_INFO); when(pisTppInfoValidator.validateTpp(TPP_INFO)).thenReturn(ValidationResult.valid()); when(pisAuthorisationValidator.validate(AUTHORISATION_ID, commonPaymentResponse)) .thenReturn(ValidationResult.valid()); when(oauthPaymentValidator.validate(commonPaymentResponse)) .thenReturn(ValidationResult.valid()); // When ValidationResult validationResult = getPaymentCancellationAuthorisationScaStatusValidator.validate(new GetPaymentCancellationAuthorisationScaStatusPO(commonPaymentResponse, AUTHORISATION_ID, SINGLE, CORRECT_PAYMENT_PRODUCT)); // Then verify(pisTppInfoValidator).validateTpp(commonPaymentResponse.getTppInfo()); assertNotNull(validationResult); assertTrue(validationResult.isValid()); assertNull(validationResult.getMessageError()); } @Test void validate_withInvalidAuthorisation_shouldReturnAuthorisationValidationError() { // Given PisCommonPaymentResponse commonPaymentResponse = buildPisCommonPaymentResponse(TPP_INFO); when(pisTppInfoValidator.validateTpp(TPP_INFO)).thenReturn(ValidationResult.valid()); when(pisAuthorisationValidator.validate(WRONG_AUTHORISATION_ID, commonPaymentResponse)) .thenReturn(ValidationResult.invalid(AUTHORISATION_VALIDATION_ERROR)); // When ValidationResult validationResult = getPaymentCancellationAuthorisationScaStatusValidator.validate(new GetPaymentCancellationAuthorisationScaStatusPO(commonPaymentResponse, WRONG_AUTHORISATION_ID, SINGLE, CORRECT_PAYMENT_PRODUCT)); // Then verify(pisTppInfoValidator).validateTpp(commonPaymentResponse.getTppInfo()); assertNotNull(validationResult); assertTrue(validationResult.isNotValid()); assertEquals(AUTHORISATION_VALIDATION_ERROR, validationResult.getMessageError()); } @Test void validate_withInvalidPaymentProduct_shouldReturnPaymentProductValidationError() { // Given PisCommonPaymentResponse commonPaymentResponse = buildPisCommonPaymentResponse(TPP_INFO); // When ValidationResult validationResult = getPaymentCancellationAuthorisationScaStatusValidator.validate(new GetPaymentCancellationAuthorisationScaStatusPO(commonPaymentResponse, AUTHORISATION_ID, SINGLE, WRONG_PAYMENT_PRODUCT)); // Then assertNotNull(validationResult); assertTrue(validationResult.isNotValid()); assertEquals(PAYMENT_PRODUCT_VALIDATION_ERROR, validationResult.getMessageError()); } @Test void validate_withInvalidTppInPayment_shouldReturnTppValidationError() { // Given PisCommonPaymentResponse commonPaymentResponse = buildPisCommonPaymentResponse(INVALID_TPP_INFO); when(pisTppInfoValidator.validateTpp(INVALID_TPP_INFO)).thenReturn(ValidationResult.invalid(TPP_VALIDATION_ERROR)); // When ValidationResult validationResult = getPaymentCancellationAuthorisationScaStatusValidator.validate(new GetPaymentCancellationAuthorisationScaStatusPO(commonPaymentResponse, AUTHORISATION_ID, SINGLE, CORRECT_PAYMENT_PRODUCT)); // Then verify(pisTppInfoValidator).validateTpp(commonPaymentResponse.getTppInfo()); assertNotNull(validationResult); assertTrue(validationResult.isNotValid()); assertEquals(TPP_VALIDATION_ERROR, validationResult.getMessageError()); } private static TppInfo buildTppInfo(String authorisationNumber) { TppInfo tppInfo = new TppInfo(); tppInfo.setAuthorisationNumber(authorisationNumber); return tppInfo; } private PisCommonPaymentResponse buildPisCommonPaymentResponse(TppInfo tppInfo) { PisCommonPaymentResponse pisCommonPaymentResponse = new PisCommonPaymentResponse(); pisCommonPaymentResponse.setTppInfo(tppInfo); pisCommonPaymentResponse.setPaymentProduct(CORRECT_PAYMENT_PRODUCT); pisCommonPaymentResponse.setPaymentType(SINGLE); return pisCommonPaymentResponse; } }
/* * Copyright 2016-2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.iot.model; import java.io.Serializable; import javax.annotation.Generated; @Generated("com.amazonaws:aws-java-sdk-code-generator") public class ListStreamsResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable { /** * <p> * A list of streams. * </p> */ private java.util.List<StreamSummary> streams; /** * <p> * A token used to get the next set of results. * </p> */ private String nextToken; /** * <p> * A list of streams. * </p> * * @return A list of streams. */ public java.util.List<StreamSummary> getStreams() { return streams; } /** * <p> * A list of streams. * </p> * * @param streams * A list of streams. */ public void setStreams(java.util.Collection<StreamSummary> streams) { if (streams == null) { this.streams = null; return; } this.streams = new java.util.ArrayList<StreamSummary>(streams); } /** * <p> * A list of streams. * </p> * <p> * <b>NOTE:</b> This method appends the values to the existing list (if any). Use * {@link #setStreams(java.util.Collection)} or {@link #withStreams(java.util.Collection)} if you want to override * the existing values. * </p> * * @param streams * A list of streams. * @return Returns a reference to this object so that method calls can be chained together. */ public ListStreamsResult withStreams(StreamSummary... streams) { if (this.streams == null) { setStreams(new java.util.ArrayList<StreamSummary>(streams.length)); } for (StreamSummary ele : streams) { this.streams.add(ele); } return this; } /** * <p> * A list of streams. * </p> * * @param streams * A list of streams. * @return Returns a reference to this object so that method calls can be chained together. */ public ListStreamsResult withStreams(java.util.Collection<StreamSummary> streams) { setStreams(streams); return this; } /** * <p> * A token used to get the next set of results. * </p> * * @param nextToken * A token used to get the next set of results. */ public void setNextToken(String nextToken) { this.nextToken = nextToken; } /** * <p> * A token used to get the next set of results. * </p> * * @return A token used to get the next set of results. */ public String getNextToken() { return this.nextToken; } /** * <p> * A token used to get the next set of results. * </p> * * @param nextToken * A token used to get the next set of results. * @return Returns a reference to this object so that method calls can be chained together. */ public ListStreamsResult withNextToken(String nextToken) { setNextToken(nextToken); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getStreams() != null) sb.append("Streams: ").append(getStreams()).append(","); if (getNextToken() != null) sb.append("NextToken: ").append(getNextToken()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof ListStreamsResult == false) return false; ListStreamsResult other = (ListStreamsResult) obj; if (other.getStreams() == null ^ this.getStreams() == null) return false; if (other.getStreams() != null && other.getStreams().equals(this.getStreams()) == false) return false; if (other.getNextToken() == null ^ this.getNextToken() == null) return false; if (other.getNextToken() != null && other.getNextToken().equals(this.getNextToken()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getStreams() == null) ? 0 : getStreams().hashCode()); hashCode = prime * hashCode + ((getNextToken() == null) ? 0 : getNextToken().hashCode()); return hashCode; } @Override public ListStreamsResult clone() { try { return (ListStreamsResult) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } }
package servlets; import helpClasses.BadParameterException; import helpClasses.DBAccessClient; import helpClasses.MessageFactory; import helpClasses.ParamCheck; import java.io.IOException; import java.sql.SQLException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class RegistrationServlet extends HttpServlet { private static final long serialVersionUID = 1L; private DBAccessClient access; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { if (request.getParameter("showRegisterForm") != null) { getServletContext().getRequestDispatcher( response.encodeURL("/jsp/registration.jsp")).forward( request, response); } else if (request.getParameter("registerNewUser") != null) { access = new DBAccessClient(); String userName = request.getParameter("userName"); String userPassword = request.getParameter("userPassword"); try { ParamCheck.checkNameAndPassword(userName, userPassword); access.registerNewUser(userName, userPassword); // Registration was successful MessageFactory.setInfoList( "Thank you for registering at our shop", request); getServletContext().getRequestDispatcher( response.encodeURL("/home.action")).forward(request, response); } catch (BadParameterException paramExc) { MessageFactory.setErrorList(paramExc.getMessage(), request); String url = "/registration.action?showRegisterForm=true"; getServletContext().getRequestDispatcher( response.encodeURL(url)).forward(request, response); } catch (ServletException exc) { if (exc.getCause() instanceof SQLException && ((SQLException) exc.getCause()).getErrorCode() == 1062) { String msg = "The user name " + userName + " already exists, please pick another name"; MessageFactory.setErrorList(msg, request); String url = "/registration.action?showRegisterForm=true"; getServletContext().getRequestDispatcher( response.encodeURL(url)).forward(request, response); } else { throw exc; } } } } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { doPost(request, response); } /** Wird verwendet um belegte Ressourcen freizugeben */ public void destroy() { try { // Freigeben von Datenbank-Ressourcen access.closeConnection(); } catch (ServletException exc) { log("SQL-Exception in destroy()", exc); } } }
/* * SPDX-License-Identifier: Apache-2.0 * * The OpenSearch Contributors require contributions made to * this file be licensed under the Apache-2.0 license or a * compatible open source license. * * Modifications Copyright OpenSearch Contributors. See * GitHub history for details. */ /* * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package org.opensearch.ad.caching; import java.time.Clock; import java.time.Duration; import java.time.Instant; import org.opensearch.ad.ExpiringState; import org.opensearch.ad.MaintenanceState; import com.google.common.base.Charsets; import com.google.common.hash.BloomFilter; import com.google.common.hash.Funnels; /** * A bloom filter with regular reset. * * Reference: https://arxiv.org/abs/1512.00727 * */ public class DoorKeeper implements MaintenanceState, ExpiringState { // stores entity's model id private BloomFilter<String> bloomFilter; // the number of expected insertions to the constructed BloomFilter<T>; must be positive private final long expectedInsertions; // the desired false positive probability (must be positive and less than 1.0) private final double fpp; private Instant lastMaintenanceTime; private final Duration resetInterval; private final Clock clock; private Instant lastAccessTime; public DoorKeeper(long expectedInsertions, double fpp, Duration resetInterval, Clock clock) { this.expectedInsertions = expectedInsertions; this.fpp = fpp; this.resetInterval = resetInterval; this.clock = clock; this.lastAccessTime = clock.instant(); maintenance(); } public boolean mightContain(String modelId) { this.lastAccessTime = clock.instant(); return bloomFilter.mightContain(modelId); } public boolean put(String modelId) { this.lastAccessTime = clock.instant(); return bloomFilter.put(modelId); } /** * We reset the bloom filter when bloom filter is null or it is state ttl is reached */ @Override public void maintenance() { if (bloomFilter == null || lastMaintenanceTime.plus(resetInterval).isBefore(clock.instant())) { bloomFilter = BloomFilter.create(Funnels.stringFunnel(Charsets.US_ASCII), expectedInsertions, fpp); lastMaintenanceTime = clock.instant(); } } @Override public boolean expired(Duration stateTtl) { return expired(lastAccessTime, stateTtl, clock.instant()); } }
/*- * =========================LICENSE_START================================== * heimdall-gateway * ======================================================================== * Copyright (C) 2018 Conductor Tecnologia SA * ======================================================================== * 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. * ==========================LICENSE_END=================================== */ package br.com.conductor.heimdall.gateway.filter; import br.com.conductor.heimdall.core.entity.*; import br.com.conductor.heimdall.core.repository.AppRepository; import br.com.conductor.heimdall.core.util.Constants; import br.com.conductor.heimdall.gateway.trace.FilterDetail; import br.com.conductor.heimdall.gateway.trace.TraceContextHolder; import com.netflix.zuul.context.RequestContext; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.runners.MockitoJUnitRunner; import org.springframework.http.HttpStatus; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import static br.com.conductor.heimdall.gateway.util.ConstantsContext.*; import static org.junit.Assert.assertEquals; @RunWith(MockitoJUnitRunner.class) public class ScopesFilterTest { @InjectMocks private ScopesFilter filter; @Mock private AppRepository appRepository; private static RequestContext context; private MockHttpServletRequest request = new MockHttpServletRequest(); private MockHttpServletResponse response = new MockHttpServletResponse(); private final String clientId1 = "client_id_1"; private final String clientId2 = "client_id_2"; @BeforeClass public static void setUp() { context = RequestContext.getCurrentContext(); } @Before public void init() { context.clear(); context.setRequest(this.request); context.setResponse(this.response); context.setResponseStatusCode(HttpStatus.OK.value()); TraceContextHolder.getInstance().init(true, "developer", this.request, false, false, ""); } @Test public void clientIdNotInScope() { this.request.addHeader(CLIENT_ID, clientId1); Api api = new Api(); api.setId(1L); App app = new App(); app.setId(10L); app.setClientId(clientId1); Plan plan = new Plan(); plan.setId(20L); plan.setApi(api); Operation operation = new Operation(1111L, null, null,null, null); Scope scope = new Scope(1000L, null, null, null, null); app.setPlans(Collections.singletonList(plan)); plan.setScopes(new HashSet<>(Collections.singletonList(scope))); scope.setOperations(new HashSet<>(Collections.singletonList(operation))); context.set(OPERATION_ID, operation.getId() + 1); Mockito.when(appRepository.findByClientId(Mockito.anyString())).thenReturn(app); this.filter.run(); final FilterDetail filterDetail = TraceContextHolder.getInstance().getActualTrace().getFilters().get(0); assertEquals(HttpStatus.OK.value(), context.getResponseStatusCode()); assertEquals(Constants.SUCCESS, filterDetail.getStatus()); } @Test public void clientIdAllowedInScope() { this.request.addHeader(CLIENT_ID, clientId1); Api api = new Api(); api.setId(1L); App app = new App(); app.setId(10L); app.setClientId(clientId1); Plan plan = new Plan(); plan.setId(20L); plan.setApi(api); Operation operation = new Operation(1111L, null, null,null, null); Scope scope = new Scope(1000L, null, null, null, null); app.setPlans(Collections.singletonList(plan)); plan.setScopes(new HashSet<>(Collections.singletonList(scope))); scope.setOperations(new HashSet<>(Collections.singletonList(operation))); context.set(OPERATION_ID, operation.getId()); Mockito.when(appRepository.findByClientId(Mockito.anyString())).thenReturn(app); this.filter.run(); final FilterDetail filterDetail = TraceContextHolder.getInstance().getActualTrace().getFilters().get(0); assertEquals(HttpStatus.OK.value(), context.getResponseStatusCode()); assertEquals(Constants.SUCCESS, filterDetail.getStatus()); } @Test public void multiplePlansSuccess() { this.request.addHeader(CLIENT_ID, clientId1); Api api1 = new Api(); api1.setId(1L); Api api2 = new Api(); api2.setId(2L); Plan plan1 = new Plan(); plan1.setId(100L); plan1.setApi(api1); Plan plan2 = new Plan(); plan2.setId(200L); plan2.setApi(api2); App app1 = new App(); app1.setId(10L); app1.setClientId(clientId1); app1.setPlans(Collections.singletonList(plan1)); App app2 = new App(); app2.setId(20L); app2.setClientId(clientId2); app2.setPlans(Collections.singletonList(plan2)); Operation operation1 = new Operation(1111L, null, null,null, null); Operation operation2 = new Operation(2222L, null, null,null, null); Scope scope1 = new Scope(); scope1.setId(123L); scope1.setOperations(new HashSet<>(Collections.singletonList(operation1))); Scope scope2 = new Scope(); scope2.setId(321L); scope2.setOperations(new HashSet<>(Collections.singletonList(operation2))); plan1.setScopes(new HashSet<>(Collections.singletonList(scope1))); plan2.setScopes(new HashSet<>(Collections.singletonList(scope2))); context.set(OPERATION_ID, operation1.getId()); Mockito.when(appRepository.findByClientId(Mockito.anyString())).thenReturn(app1); this.filter.run(); final FilterDetail filterDetail = TraceContextHolder.getInstance().getActualTrace().getFilters().get(0); assertEquals(HttpStatus.OK.value(), context.getResponseStatusCode()); assertEquals(Constants.SUCCESS, filterDetail.getStatus()); } @Test public void multiplePlansFailure() { this.request.addHeader(CLIENT_ID, clientId2); Api api1 = new Api(); api1.setId(1L); Api api2 = new Api(); api2.setId(2L); Plan plan1 = new Plan(); plan1.setId(100L); plan1.setApi(api1); Plan plan2 = new Plan(); plan2.setId(200L); plan2.setApi(api2); App app1 = new App(); app1.setId(10L); app1.setClientId(clientId1); app1.setPlans(Collections.singletonList(plan1)); App app2 = new App(); app2.setId(20L); app2.setClientId(clientId2); app2.setPlans(Collections.singletonList(plan2)); Operation operation1 = new Operation(1111L, null, null,null, null); Operation operation2 = new Operation(2222L, null, null,null, null); Scope scope1 = new Scope(123L, null, null, null, new HashSet<>(Collections.singletonList(operation1))); Scope scope2 = new Scope(321L, null, null, null, new HashSet<>(Collections.singletonList(operation2))); plan1.setScopes(new HashSet<>(Collections.singletonList(scope1))); plan2.setScopes(new HashSet<>(Collections.singletonList(scope2))); context.set(OPERATION_ID, operation1.getId()); context.set(API_ID, api2.getId()); Mockito.when(appRepository.findByClientId(Mockito.anyString())).thenReturn(app2); this.filter.run(); final FilterDetail filterDetail = TraceContextHolder.getInstance().getActualTrace().getFilters().get(0); assertEquals(HttpStatus.FORBIDDEN.value(), context.getResponseStatusCode()); assertEquals(Constants.SUCCESS, filterDetail.getStatus()); } @Test public void overlappingPlansApp1() { this.request.addHeader(CLIENT_ID, clientId1); Api api1 = new Api(); api1.setId(1L); Api api2 = new Api(); api2.setId(2L); Plan plan1 = new Plan(); plan1.setId(100L); plan1.setApi(api1); Plan plan2 = new Plan(); plan2.setId(200L); plan2.setApi(api2); App app1 = new App(); app1.setId(10L); app1.setClientId(clientId1); app1.setPlans(Collections.singletonList(plan1)); App app2 = new App(); app2.setId(20L); app2.setClientId(clientId2); app2.setPlans(Collections.singletonList(plan2)); Operation operation1 = new Operation(1111L, null, null,null, null); Operation operation2 = new Operation(2222L, null, null,null, null); Operation operation3 = new Operation(3333L, null, null,null, null); List<Operation> operations1 = new ArrayList<>(); List<Operation> operations2 = new ArrayList<>(); operations1.add(operation1); operations1.add(operation3); operations2.add(operation2); operations2.add(operation3); Scope scope1 = new Scope(123L, null, null, null, new HashSet<>(operations1)); Scope scope2 = new Scope(321L, null, null, null, new HashSet<>(operations2)); plan1.setScopes(new HashSet<>(Collections.singletonList(scope1))); plan2.setScopes(new HashSet<>(Collections.singletonList(scope2))); context.set(OPERATION_ID, operation3.getId()); context.set(API_ID, api1.getId()); Mockito.when(appRepository.findByClientId(Mockito.anyString())).thenReturn(app1); this.filter.run(); final FilterDetail filterDetail = TraceContextHolder.getInstance().getActualTrace().getFilters().get(0); assertEquals(HttpStatus.OK.value(), context.getResponseStatusCode()); assertEquals(Constants.SUCCESS, filterDetail.getStatus()); } @Test public void overlappingPlansApp2() { this.request.addHeader(CLIENT_ID, clientId1); Api api1 = new Api(); api1.setId(1L); Api api2 = new Api(); api2.setId(2L); Plan plan1 = new Plan(); plan1.setId(100L); plan1.setApi(api1); Plan plan2 = new Plan(); plan2.setId(200L); plan2.setApi(api2); App app1 = new App(); app1.setId(10L); app1.setClientId(clientId1); app1.setPlans(Collections.singletonList(plan1)); Operation operation1 = new Operation(1111L, null, null,null, null); Operation operation2 = new Operation(2222L, null, null,null, null); Operation operation3 = new Operation(3333L, null, null,null, null); List<Operation> operations1 = new ArrayList<>(); List<Operation> operations2 = new ArrayList<>(); operations1.add(operation1); operations1.add(operation3); operations2.add(operation2); operations2.add(operation3); Scope scope1 = new Scope(123L, null, null, null, new HashSet<>(operations1)); Scope scope2 = new Scope(321L, null, null, null, new HashSet<>(operations2)); plan1.setScopes(new HashSet<>(Collections.singletonList(scope1))); plan2.setScopes(new HashSet<>(Collections.singletonList(scope2))); context.set(OPERATION_ID, operation2.getId()); context.set(API_ID, api1.getId()); Mockito.when(appRepository.findByClientId(Mockito.anyString())).thenReturn(app1); this.filter.run(); final FilterDetail filterDetail = TraceContextHolder.getInstance().getActualTrace().getFilters().get(0); assertEquals(HttpStatus.FORBIDDEN.value(), context.getResponseStatusCode()); assertEquals(Constants.SUCCESS, filterDetail.getStatus()); } @Test public void noClientIdHeader() { Api api = new Api(); api.setId(1L); App app = new App(); app.setId(100L); app.setClientId(clientId1); Plan plan = new Plan(); plan.setId(10L); plan.setApi(api); Operation operation = new Operation(1111L, null, null,null, null); Scope scope = new Scope(1000L, null, null, null, null); app.setPlans(Collections.singletonList(plan)); plan.setScopes(new HashSet<>(Collections.singletonList(scope))); scope.setOperations(new HashSet<>(Collections.singletonList(operation))); context.set(OPERATION_ID, operation.getId()); context.set(API_ID, api.getId()); this.filter.run(); final FilterDetail filterDetail = TraceContextHolder.getInstance().getActualTrace().getFilters().get(0); assertEquals(HttpStatus.OK.value(), context.getResponseStatusCode()); assertEquals(Constants.SUCCESS, filterDetail.getStatus()); } @Test public void noApp() { this.request.addHeader(CLIENT_ID, clientId1); Api api = new Api(); api.setId(1L); Operation operation = new Operation(1111L, null, null,null, null); Scope scope = new Scope(1000L, null, null, null, null); scope.setOperations(new HashSet<>(Collections.singletonList(operation))); context.set(OPERATION_ID, operation.getId()); context.set(API_ID, api.getId()); Mockito.when(appRepository.findByClientId(Mockito.anyString())).thenReturn(null); this.filter.run(); final FilterDetail filterDetail = TraceContextHolder.getInstance().getActualTrace().getFilters().get(0); assertEquals(HttpStatus.OK.value(), context.getResponseStatusCode()); assertEquals(Constants.SUCCESS, filterDetail.getStatus()); } @Test public void noPlan() { this.request.addHeader(CLIENT_ID, clientId1); App app = new App(); app.setId(1L); app.setClientId(clientId1); Operation operation = new Operation(1111L, null, null,null, null); Scope scope = new Scope(1000L, null, null, null, null); scope.setOperations(new HashSet<>(Collections.singletonList(operation))); context.set(OPERATION_ID, operation.getId()); Mockito.when(appRepository.findByClientId(Mockito.anyString())).thenReturn(app); this.filter.run(); final FilterDetail filterDetail = TraceContextHolder.getInstance().getActualTrace().getFilters().get(0); assertEquals(HttpStatus.OK.value(), context.getResponseStatusCode()); assertEquals(Constants.SUCCESS, filterDetail.getStatus()); } @Test public void noScopes() { this.request.addHeader(CLIENT_ID, clientId1); App app = new App(); app.setId(1L); app.setClientId(clientId1); Plan plan = new Plan(); plan.setId(1L); Operation operation = new Operation(1111L, null, null,null, null); context.set(OPERATION_ID, operation.getId()); Mockito.when(appRepository.findByClientId(Mockito.anyString())).thenReturn(app); this.filter.run(); final FilterDetail filterDetail = TraceContextHolder.getInstance().getActualTrace().getFilters().get(0); assertEquals(HttpStatus.OK.value(), context.getResponseStatusCode()); assertEquals(Constants.SUCCESS, filterDetail.getStatus()); } @Test public void noOperationIdContext() { this.request.addHeader(CLIENT_ID, clientId1); Api api = new Api(); api.setId(1L); App app = new App(); app.setId(100L); app.setClientId(clientId1); Plan plan = new Plan(); plan.setId(10L); plan.setApi(api); Operation operation = new Operation(1111L, null, null,null, null); Scope scope = new Scope(1000L, null, null, null, null); app.setPlans(Collections.singletonList(plan)); plan.setScopes(new HashSet<>(Collections.singletonList(scope))); scope.setOperations(new HashSet<>(Collections.singletonList(operation))); Mockito.when(appRepository.findByClientId(Mockito.anyString())).thenReturn(app); this.filter.run(); final FilterDetail filterDetail = TraceContextHolder.getInstance().getActualTrace().getFilters().get(0); assertEquals(HttpStatus.OK.value(), context.getResponseStatusCode()); assertEquals(Constants.SUCCESS, filterDetail.getStatus()); } }
package com.kakaopay.coupon.util; public class TestUtil { public static double mean(double[] array) { double sum = 0.0; for (double d : array) sum += d; return sum / array.length; } // 모집단 표준편차 public static double standardDeviation(double[] array) { if (array.length < 2) return Double.NaN; double sum = 0.0; double sd; double diff; double meanValue = mean(array); for (double d : array) { diff = d - meanValue; sum += diff * diff; } sd = Math.sqrt(sum / array.length); return sd; } }
package ru.stqa.pft.addressbook.appmanager; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; public class SessionHelper extends HelperBase { public SessionHelper(WebDriver wd) { super(wd); } public void login(String userName, String password) { type(By.name("user"), userName); type(By.name("pass"), password); click(By.xpath("//input[@value='Login']")); } }
package PopulationSimulator.model.entities; import PopulationSimulator.model.enums.Gender; import PopulationSimulator.model.enums.SexualOrientation; import org.jetbrains.annotations.NotNull; import java.util.Objects; import static PopulationSimulator.controllers.SimulationController.currentTime; import static PopulationSimulator.model.enums.SexualOrientation.Hetero; /*................................................................................................................................ . Copyright (c) . . The PersonalData class was coded by : Alexandre BOLOT . . Last modified : 14/12/18 07:36 . . Contact : bolotalex06@gmail.com ...............................................................................................................................*/ public class PersonalData { //region --------------- Attributes ---------------------- private Gender gender; private int birthday; private SexualOrientation orientation; //endregion //region --------------- Constructors -------------------- /** * <hr> * <h2>Constructor of PersonalData using : <br> * - Gender : gender param <br> * - Orientation : Hetero (as default) <br> * - Birthday : Now (SimulationController.currentTime())</h2> * <hr> * * @param gender Gender of the Person */ public PersonalData(@NotNull Gender gender) { this(currentTime(), gender, Hetero); } /** * <hr> * <h2>Constructor of PersonalData using : <br> * - Gender : gender param <br> * - Orientation : orientation param <br> * - Birthday : Now (SimulationController.currentTime())</h2> * <hr> * * @param gender Gender of the Person * @param orientation Sexual Orientation of the Person */ public PersonalData(@NotNull Gender gender, @NotNull SexualOrientation orientation) { this(currentTime(), gender, orientation); } /** * <hr> * <h2>Constructor of PersonalData using : <br> * - Gender : gender param <br> * - Orientation : orientation param <br> * - Birthday : birthday param</h2> * <hr> * * @param gender Gender of the Person * @param orientation Sexual Orientation of the Person * @param birthday Birthday of the Person */ public PersonalData(int birthday, @NotNull Gender gender, @NotNull SexualOrientation orientation) { if (birthday > currentTime()) throw new IllegalArgumentException("Bday param can't be bigger than currentTime()"); this.gender = gender; this.orientation = orientation; this.birthday = birthday; } //endregion //region --------------- Getters - Setters --------------- @NotNull public Gender gender() { return gender; } public int age() { return currentTime() - birthday; } public int birthday() { return birthday; } @NotNull public SexualOrientation orientation() { return orientation; } //endregion //region --------------- Override ------------------------ /** * <hr> * <h2>Format : Data + age + gender + orientation</h2> * <hr> * * @return Data + age + gender + orientation */ @Override @NotNull public String toString() { return String.format("Data %s,%s,%d", gender, orientation, age()); } /** * <hr> * <h2>Compares : birthday, gender and orientation</h2> * <hr> * * @param obj The Object to compare with this * @return True if obj is equal to this, False otherwise */ @Override public boolean equals(@NotNull Object obj) { if (!getClass().isInstance(obj)) return false; PersonalData dataCompare = (PersonalData) obj; if (birthday != dataCompare.birthday) return false; if (!gender.equals(dataCompare.gender)) return false; if (!orientation.equals(dataCompare.orientation)) return false; return true; } /** * <hr> * <h2>Returns a unique HashCode for this Context instance <br> * Based on : birthday, gender and orientation</h2> * <hr> * * @return A unique HashCode for this Context instance <br> * Based on : birthday, gender and orientation */ @Override public int hashCode() { return Objects.hash(birthday, gender, orientation); } //endregion }
package ru.job4j.condition; import org.junit.Test; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; public class PointTest { @Test public void pointTest() { Point a = new Point(10, 5); Point b = new Point(-3, -3); double result = a.distanceTo(b); double expected = 15.264337522473747; assertThat(result, is(expected)); } }
// Template Source: BaseEntity.java.tt // ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ package com.microsoft.graph.models; import com.microsoft.graph.serializer.ISerializer; import com.microsoft.graph.serializer.IJsonBackedObject; import com.microsoft.graph.serializer.AdditionalDataManager; import java.util.EnumSet; import com.microsoft.graph.models.SignInStatus; import com.microsoft.graph.models.Entity; import com.google.gson.JsonObject; import com.google.gson.annotations.SerializedName; import com.google.gson.annotations.Expose; import javax.annotation.Nullable; import javax.annotation.Nonnull; // **NOTE** This file was generated by a tool and any changes will be overwritten. /** * The class for the Application Sign In Detailed Summary. */ public class ApplicationSignInDetailedSummary extends Entity implements IJsonBackedObject { /** * The Aggregated Event Date Time. * The Timestamp type represents date and time information using ISO 8601 format and is always in UTC time. For example, midnight UTC on Jan 1, 2014 is 2014-01-01T00:00:00Z. */ @SerializedName(value = "aggregatedEventDateTime", alternate = {"AggregatedEventDateTime"}) @Expose @Nullable public java.time.OffsetDateTime aggregatedEventDateTime; /** * The App Display Name. * Name of the application that the user signed in to. */ @SerializedName(value = "appDisplayName", alternate = {"AppDisplayName"}) @Expose @Nullable public String appDisplayName; /** * The App Id. * ID of the application that the user signed in to. */ @SerializedName(value = "appId", alternate = {"AppId"}) @Expose @Nullable public String appId; /** * The Sign In Count. * Count of sign-ins made by the application. */ @SerializedName(value = "signInCount", alternate = {"SignInCount"}) @Expose @Nullable public Long signInCount; /** * The Status. * Details of the sign-in status. */ @SerializedName(value = "status", alternate = {"Status"}) @Expose @Nullable public SignInStatus status; /** * Sets the raw JSON object * * @param serializer the serializer * @param json the JSON object to set this object to */ public void setRawObject(@Nonnull final ISerializer serializer, @Nonnull final JsonObject json) { } }
/* * Copyright 2002-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.oauth2.provider.endpoint; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.when; import java.util.Collections; import java.util.HashMap; import java.util.Map; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.runners.MockitoJUnitRunner; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken; import org.springframework.security.oauth2.common.OAuth2AccessToken; import org.springframework.security.oauth2.provider.AuthorizationRequest; import org.springframework.security.oauth2.provider.AuthorizationRequestManager; import org.springframework.security.oauth2.provider.ClientDetailsService; import org.springframework.security.oauth2.provider.DefaultAuthorizationRequest; import org.springframework.security.oauth2.provider.TokenGranter; /** * @author Dave Syer * @author Rob Winch */ @RunWith(MockitoJUnitRunner.class) public class TestTokenEndpoint { @Mock private TokenGranter tokenGranter; @Mock private AuthorizationRequestManager authorizationRequestFactory; @Mock private ClientDetailsService clientDetailsService; @Test public void testGetAccessTokenWithNoClientId() { TokenEndpoint endpoint = new TokenEndpoint(); endpoint.setTokenGranter(tokenGranter); endpoint.setAuthorizationRequestManager(authorizationRequestFactory); endpoint.setClientDetailsService(clientDetailsService); HashMap<String, String> parameters = new HashMap<String, String>(); OAuth2AccessToken expectedToken = new DefaultOAuth2AccessToken("FOO"); when(tokenGranter.grant(Mockito.eq("authorization_code"), Mockito.any(AuthorizationRequest.class))).thenReturn( expectedToken); @SuppressWarnings("unchecked") Map<String, String> anyMap = Mockito.any(Map.class); when(authorizationRequestFactory.createAuthorizationRequest(anyMap)).thenReturn( new DefaultAuthorizationRequest(parameters)); ResponseEntity<OAuth2AccessToken> response = endpoint.getAccessToken(new UsernamePasswordAuthenticationToken( null, null, Collections.singleton(new SimpleGrantedAuthority("ROLE_CLIENT"))), "authorization_code", parameters); assertNotNull(response); assertEquals(HttpStatus.OK, response.getStatusCode()); OAuth2AccessToken body = response.getBody(); assertEquals(body, expectedToken); assertTrue("Wrong body: " + body, body.getTokenType() != null); } @Test public void testGetAccessTokenWithScope() { TokenEndpoint endpoint = new TokenEndpoint(); endpoint.setTokenGranter(tokenGranter); endpoint.setAuthorizationRequestManager(authorizationRequestFactory); endpoint.setClientDetailsService(clientDetailsService); HashMap<String, String> parameters = new HashMap<String, String>(); parameters.put("scope", "read"); parameters.put("grant_type", "authorization_code"); parameters.put("code", "kJAHDFG"); OAuth2AccessToken expectedToken = new DefaultOAuth2AccessToken("FOO"); ArgumentCaptor<AuthorizationRequest> captor = ArgumentCaptor.forClass(AuthorizationRequest.class); when(tokenGranter.grant(Mockito.eq("authorization_code"), captor.capture())).thenReturn(expectedToken); @SuppressWarnings("unchecked") Map<String, String> anyMap = Mockito.any(Map.class); when(authorizationRequestFactory.createAuthorizationRequest(anyMap)).thenReturn( new DefaultAuthorizationRequest(parameters)); ResponseEntity<OAuth2AccessToken> response = endpoint.getAccessToken(new UsernamePasswordAuthenticationToken( null, null, Collections.singleton(new SimpleGrantedAuthority("ROLE_CLIENT"))), "authorization_code", parameters); assertNotNull(response); assertEquals(HttpStatus.OK, response.getStatusCode()); OAuth2AccessToken body = response.getBody(); assertEquals(body, expectedToken); assertTrue("Wrong body: " + body, body.getTokenType() != null); assertTrue("Scope of token request not cleared", captor.getValue().getScope().isEmpty()); } }
/** * Copyright (C) 2008 Stratio (http://stratio.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.stratio.mojo.unix.util.fj; /* * The MIT License * * Copyright 2009 The Codehaus. * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is furnished to do * so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ import fj.*; public class FunctionF { public static <A, B, C> F<F2<A, B, C>, F<A, F<B, C>>> curry_() { return new F<F2<A, B, C>, F<A, F<B, C>>>() { public F<A, F<B, C>> f( F2<A, B, C> f ) { return Function.curry( f ); } }; } public static <A, B, C> F2<F2<A, B, C>, A, F<B, C>> curryA() { return new F2<F2<A, B, C>, A, F<B, C>>() { public F<B, C> f( F2<A, B, C> f, A a ) { return Function.curry( f, a ); } }; } public static <A, B, C> F2<B, A, C> flip2( final F2<A, B, C> f ) { return new F2<B, A, C>() { public C f( B b, A a ) { return f.f( a, b ); } }; } public static <A, B, C, D> F<A, D> compose( final F<C, D> h, final F<B, C> g, final F<A, B> f ) { return new F<A, D>() { public D f( A a ) { return h.f( g.f( f.f( a ) ) ); } }; } public static <A, B, C, D, E> F<A, E> compose( final F<D, E> i, final F<C, D> h, final F<B, C> g, final F<A, B> f ) { return new F<A, E>() { public E f( A a ) { return i.f( h.f( g.f( f.f( a ) ) ) ); } }; } }
package com.sdtbu.gulimall.gateway; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest class GulimallGatewayApplicationTests { @Test void contextLoads() { } }
package com.olacabs.jackhammer.handler; import com.google.inject.Inject; import com.olacabs.jackhammer.enums.Handler; import com.olacabs.jackhammer.exceptions.AbstractException; import com.olacabs.jackhammer.exceptions.HandlerNotFoundException; import com.olacabs.jackhammer.models.Upload; import com.olacabs.jackhammer.models.User; import com.olacabs.jackhammer.utilities.FileOperations; import lombok.extern.slf4j.Slf4j; import org.apache.commons.io.FilenameUtils; import java.time.Instant; import javax.ws.rs.core.Response; @Slf4j public class UploadsHandler extends AbstractHandler<Upload> { @Inject FileOperations fileOperations; @Override public Response getAllRecords(Upload upload) throws HandlerNotFoundException { try { paginationRecords = dataServiceBuilderFactory.getService(Handler.UPLOAD_SERVICE).getAllRecords(upload); return responseBuilderFactory.getResponseBuilder(Handler.UPLOAD_SERVICE).buildFetchAllRecordsResponse(paginationRecords); } catch(AbstractException e){ log.error("Exception while fetching roles"); return responseBuilderFactory.getResponseBuilder(Handler.UPLOAD_SERVICE).buildErrorResponse(e); } } @Override public Response createRecord(Upload upload) throws HandlerNotFoundException { try { // validatorBuilderFactory.getValidator(Handler.UPLOAD_SERVICE).dataValidations(upload); String baseName = FilenameUtils.getBaseName(upload.getName()); String extName = FilenameUtils.getExtension(upload.getName()); User dbUser = currentUser(upload.getUserToken()); String fileNameWithEpoc = baseName + '_' + Instant.now().toEpochMilli() + '.' + extName; upload.setUserId(dbUser.getId()); upload.setName(fileNameWithEpoc); dataServiceBuilderFactory.getService(Handler.UPLOAD_SERVICE).createRecord(upload); fileOperations.copyUploadFile(upload.getUploadedInputStream(), upload.getFindingId(), fileNameWithEpoc); // COPY FILE TO USER DIR return responseBuilderFactory.getResponseBuilder(Handler.UPLOAD_SERVICE).buildSuccessResponse(); } catch (AbstractException e){ log.error("Exception while creating role"); return responseBuilderFactory.getResponseBuilder(Handler.UPLOAD_SERVICE).buildErrorResponse(e); } } @Override public Response getRecord(long id) throws HandlerNotFoundException { try { Upload role = (Upload) dataServiceBuilderFactory.getService(Handler.UPLOAD_SERVICE).fetchRecordById(id); return responseBuilderFactory.getResponseBuilder(Handler.UPLOAD_SERVICE).buildFetchRecordResponse(role); } catch (AbstractException e){ log.error("Exception while getting role"); return responseBuilderFactory.getResponseBuilder(Handler.UPLOAD_SERVICE).buildErrorResponse(e); } } @Override public Response updateRecord(Upload upload) throws HandlerNotFoundException { try { dataServiceBuilderFactory.getService(Handler.ROLE_SERVICE).updateRecord(upload); return responseBuilderFactory.getResponseBuilder(Handler.ROLE_SERVICE).buildSuccessResponse(); } catch (AbstractException e){ log.error("Exception while updating role"); return responseBuilderFactory.getResponseBuilder(Handler.ROLE_SERVICE).buildErrorResponse(e); } } @Override public Response deleteRecord(long id) throws HandlerNotFoundException { try { dataServiceBuilderFactory.getService(Handler.ROLE_SERVICE).deleteRecord(id); return responseBuilderFactory.getResponseBuilder(Handler.ROLE_SERVICE).buildSuccessResponse(); } catch (AbstractException e){ log.error("Exception while deleting role"); return responseBuilderFactory.getResponseBuilder(Handler.ROLE_SERVICE).buildErrorResponse(e); } } }