hexsha
stringlengths
40
40
size
int64
8
1.04M
content
stringlengths
8
1.04M
avg_line_length
float64
2.24
100
max_line_length
int64
4
1k
alphanum_fraction
float64
0.25
0.97
6750b3e0aaed67717ea725e148dddc4a3c1db123
9,003
/* * 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.myfaces.trinidadinternal.ui.laf.base.pda; import org.apache.myfaces.trinidadinternal.ui.UIXRenderingContext; import org.apache.myfaces.trinidadinternal.ui.UIConstants; import org.apache.myfaces.trinidadinternal.ui.UINode; import org.apache.myfaces.trinidadinternal.ui.beans.MarlinBean; import org.apache.myfaces.trinidadinternal.ui.composite.ContextPoppingUINode; import org.apache.myfaces.trinidadinternal.ui.composite.RootAttributeMap; import org.apache.myfaces.trinidadinternal.ui.composite.RootUINodeList; import org.apache.myfaces.trinidadinternal.ui.composite.UINodeRenderer; import org.apache.myfaces.trinidadinternal.ui.data.bind.NotBoundValue; import org.apache.myfaces.trinidadinternal.ui.data.BoundValue; import org.apache.myfaces.trinidadinternal.ui.data.bind.OrBoundValue; import org.apache.myfaces.trinidadinternal.ui.laf.base.xhtml.XhtmlLafConstants; /** * <p> * @version $Name: $ ($Revision: adfrt/faces/adf-faces-impl/src/main/java/oracle/adfinternal/view/faces/ui/laf/base/pda/PageLayoutRenderer.java#0 $) $Date: 10-nov-2005.18:55:00 $ * @deprecated This class comes from the old Java 1.2 UIX codebase and should not be used anymore. */ @Deprecated public class PageLayoutRenderer extends UINodeRenderer implements UIConstants, XhtmlLafConstants { private static UINode _createCompositeUINode() { MarlinBean globalNavigation = new MarlinBean(TABLE_LAYOUT_NAME); globalNavigation.setAttributeValue(WIDTH_ATTR, ONE_HUNDRED_PERCENT_ATTRIBUTE_VALUE); globalNavigation.addIndexedChild(_fullWidthTableRow(NAVIGATION_GLOBAL_CHILD)); // // Create the page header layout // MarlinBean headerLayout = new MarlinBean(PAGE_HEADER_LAYOUT_NAME); headerLayout.setNamedChild(MENU_SWITCH_CHILD, ContextPoppingUINode.getUINode(MENU_SWITCH_CHILD)); headerLayout.setNamedChild(BRANDING_CHILD, ContextPoppingUINode.getUINode(BRANDING_CHILD)); headerLayout.setNamedChild(BRANDING_APP_CHILD, ContextPoppingUINode.getUINode(BRANDING_APP_CHILD)); headerLayout.setNamedChild(BRANDING_APP_CONTEXTUAL_CHILD, ContextPoppingUINode.getUINode(BRANDING_APP_CONTEXTUAL_CHILD)); headerLayout.setNamedChild(NAVIGATION1_CHILD, ContextPoppingUINode.getUINode(NAVIGATION1_CHILD)); headerLayout.setNamedChild(NAVIGATION2_CHILD, _createGlobalHeaders()); headerLayout.setNamedChild(SEARCH_CHILD, ContextPoppingUINode.getUINode(SEARCH_CHILD)); // =-= bts a little bogus since this isn't really an attribute of PageHeader headerLayout.setAttributeValue(WIDTH_ATTR, "100%"); // // Create layout used for locators at the top of the page // MarlinBean locatorLayout = new MarlinBean(STACK_LAYOUT_NAME); locatorLayout.addIndexedChild( ContextPoppingUINode.getUINode(LOCATION_CHILD)); locatorLayout.addIndexedChild( ContextPoppingUINode.getUINode(INFO_USER_CHILD)); locatorLayout.addIndexedChild( ContextPoppingUINode.getUINode(MESSAGES_CHILD)); locatorLayout.addIndexedChild( ContextPoppingUINode.getUINode(INFO_SUPPLEMENTAL_CHILD)); locatorLayout.addIndexedChild( ContextPoppingUINode.getUINode(INFO_STATUS_CHILD)); // // Create the content container containing all of the indexed children // // MarlinBean contentRoot = new MarlinBean(FLOW_LAYOUT_NAME); // use stackLayout as the default layout as it is the layout used in // the desktop version. MarlinBean contentRoot = new MarlinBean(STACK_LAYOUT_NAME); contentRoot.setIndexedNodeList(RootUINodeList.getNodeList()); // // add the page buttons line // MarlinBean pageButtonsLine = new MarlinBean(SEPARATOR_NAME); pageButtonsLine.setAttributeValue( RENDERED_ATTR, new OrBoundValue(new BoundValue[]{ PdaHtmlLafUtils.createIsRenderedBoundValue(INFO_RETURN_CHILD)})); // Create the area containing the footer MarlinBean footerTable = new MarlinBean(TABLE_LAYOUT_NAME); footerTable.setAttributeValue( WIDTH_ATTR, ONE_HUNDRED_PERCENT_ATTRIBUTE_VALUE); footerTable.addIndexedChild(_fullWidthTableRow(APP_COPYRIGHT_CHILD)); footerTable.addIndexedChild(_fullWidthTableRow(APP_PRIVACY_CHILD)); footerTable.addIndexedChild(_fullWidthTableRow(APP_ABOUT_CHILD)); MarlinBean footer = new MarlinBean(FLOW_LAYOUT_NAME); MarlinBean footerLine = new MarlinBean(CONTENT_FOOTER_NAME); footer.addIndexedChild(footerLine); footer.addIndexedChild(footerTable); BoundValue renderFooter = new OrBoundValue(new BoundValue[]{ PdaHtmlLafUtils.createIsRenderedBoundValue(APP_PRIVACY_CHILD), PdaHtmlLafUtils.createIsRenderedBoundValue(APP_ABOUT_CHILD), PdaHtmlLafUtils.createIsRenderedBoundValue(APP_COPYRIGHT_CHILD)}); footer.setAttributeValue( RENDERED_ATTR, renderFooter); MarlinBean content = new MarlinBean(STACK_LAYOUT_NAME); content.addIndexedChild(contentRoot); content.addIndexedChild( ContextPoppingUINode.getUINode(INFO_FOOTNOTE_CHILD)); content.addIndexedChild(pageButtonsLine); // // Add the footer children // content.addIndexedChild( ContextPoppingUINode.getUINode(INFO_RETURN_CHILD)); MarlinBean action = new MarlinBean(TABLE_LAYOUT_NAME); action.setAttributeValue( WIDTH_ATTR, ONE_HUNDRED_PERCENT_ATTRIBUTE_VALUE); MarlinBean actionButtonRow = new MarlinBean(ROW_LAYOUT_NAME); MarlinBean actionButtonCell = new MarlinBean(CELL_FORMAT_NAME); actionButtonCell.setAttributeValue( H_ALIGN_ATTR, CENTER_ATTRIBUTE_VALUE); actionButtonCell.addIndexedChild( ContextPoppingUINode.getUINode(ACTIONS_CHILD)); actionButtonRow.addIndexedChild( actionButtonCell); action.addIndexedChild( actionButtonRow); MarlinBean compositeRoot = new MarlinBean(FLOW_LAYOUT_NAME); // delegate all of the attributes to the RootAttribtueMap compositeRoot.setAttributeMap(RootAttributeMap.getAttributeMap()); compositeRoot.addIndexedChild(globalNavigation); compositeRoot.addIndexedChild(headerLayout); compositeRoot.addIndexedChild(locatorLayout); compositeRoot.addIndexedChild(content); compositeRoot.addIndexedChild(action); compositeRoot.addIndexedChild(footer); return compositeRoot; } /** * Creates a faced in a table cell that occupied full width of screen for the * facet name in the parameter. */ private static MarlinBean _fullWidthTableRow ( String childName) { MarlinBean row = new MarlinBean(ROW_LAYOUT_NAME); MarlinBean cell = new MarlinBean(CELL_FORMAT_NAME); cell.setAttributeValue(H_ALIGN_ATTR, CENTER_ATTRIBUTE_VALUE); cell.addIndexedChild( ContextPoppingUINode.getUINode(childName)); row.addIndexedChild(cell); return row; } /** * Create the global headers to use to render the page. The first child is * the global header set on the page layout, the second is the global * header to use if the first client global header doesn't exist or * isn't rendered. */ private static UINode _createGlobalHeaders() { MarlinBean globalHeaders = new MarlinBean(FLOW_LAYOUT_NAME); // // add the client header // globalHeaders.addIndexedChild( ContextPoppingUINode.getUINode(NAVIGATION2_CHILD)); // // create and add the default header // MarlinBean defaultHeader = new MarlinBean(GLOBAL_HEADER_NAME); defaultHeader.setAttributeValue( RENDERED_ATTR, new NotBoundValue( PdaHtmlLafUtils.createIsRenderedBoundValue(NAVIGATION2_CHILD))); globalHeaders.addIndexedChild(defaultHeader); return globalHeaders; } @Override protected UINode getRenderingUINode( UIXRenderingContext context, UINode node ) { return _INSTANCE; } private static final UINode _INSTANCE = _createCompositeUINode(); }
37.987342
179
0.74253
8906223caf5b85c5197f32c7f3b0290131aa2ebb
23,398
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package Interface.EntregadorView; import Negocio.Diversos; import Negocio.Pedido; import Persistencia.DaoPedido; import Persistencia.DaoVenda; import java.text.DateFormat; import java.text.NumberFormat; import java.util.Date; import javax.swing.JFrame; /** * * @author Pedro */ public class JDialogConfirmacaoVenda extends javax.swing.JDialog { /** Creates new form JDialogConfirmacaoVenda */ public JDialogConfirmacaoVenda(JFrame parent, boolean modal, Pedido p) { super(parent, modal); this.p = p; this.parent = (JFrmEntregadorPedido) parent; initComponents(); setLookAndFeel(); carregarObjetos(); } /** 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() { jScrollPane1 = new javax.swing.JScrollPane(); jTextPane1 = new javax.swing.JTextPane(); jScrollPane2 = new javax.swing.JScrollPane(); jTextPane2 = new javax.swing.JTextPane(); jScrollPane3 = new javax.swing.JScrollPane(); jTextPane3 = new javax.swing.JTextPane(); jPanel1 = new javax.swing.JPanel(); /* { @Override public void paintComponent(Graphics g) { super.paintComponent(g); Image imagem = new ImageIcon("C:/Users/Pedro/Desktop/blue2.jpg").getImage(); g.drawImage(imagem, 0, 0, this); } }*/; jPanel2 = new javax.swing.JPanel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); jSeparator1 = new javax.swing.JSeparator(); jLabel6 = new javax.swing.JLabel(); jLblNumeroPedido = new javax.swing.JLabel(); jLabel8 = new javax.swing.JLabel(); jLblData = new javax.swing.JLabel(); jLabel10 = new javax.swing.JLabel(); jLblNomeClientePedido = new javax.swing.JLabel(); jLabel12 = new javax.swing.JLabel(); jLblNomeEntregadorPedido = new javax.swing.JLabel(); jPanel4 = new javax.swing.JPanel(); jLblTotal = new javax.swing.JLabel(); jPanel3 = new javax.swing.JPanel(); jTxtSenhaPedido = new javax.swing.JTextField(); jLabel1 = new javax.swing.JLabel(); jBtnConfirmar = new javax.swing.JButton(); jBtnCancelar = new javax.swing.JButton(); jScrollPane1.setViewportView(jTextPane1); jScrollPane2.setViewportView(jTextPane2); jScrollPane3.setViewportView(jTextPane3); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setTitle("August- Confirmacao Pedido"); setUndecorated(true); jPanel1.setBackground(new java.awt.Color(153, 153, 153)); jPanel1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(51, 51, 51), 2)); jPanel2.setBackground(new java.awt.Color(204, 204, 204)); jLabel2.setFont(new java.awt.Font("Dialog", 1, 14)); // NOI18N jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel2.setText("August -The Divine Food"); jLabel3.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel3.setText("P. Sherman, 42 Wallaby Way, Sydney"); jLabel4.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel4.setText("CNPJ: 22.122.312/0021-50"); jLabel5.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel5.setText("Fone: (21) 4242-7373"); jLabel6.setText("Pedido Nº:"); jLblNumeroPedido.setText("121212"); jLabel8.setText("Iniciado em:"); jLblData.setText("12/05/2015 12:05:34"); jLabel10.setText("Cliente:"); jLblNomeClientePedido.setText("Carlos"); jLabel12.setText("Entregador:"); jLblNomeEntregadorPedido.setText("João"); jPanel4.setBackground(new java.awt.Color(153, 153, 153)); jPanel4.setBorder(javax.swing.BorderFactory.createCompoundBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(102, 102, 102)), javax.swing.BorderFactory.createLineBorder(new java.awt.Color(153, 153, 153)))); jLblTotal.setFont(new java.awt.Font("Segoe UI", 1, 18)); // NOI18N jLblTotal.setForeground(new java.awt.Color(0, 0, 0)); jLblTotal.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLblTotal.setText("R$ 126,64"); org.jdesktop.layout.GroupLayout jPanel4Layout = new org.jdesktop.layout.GroupLayout(jPanel4); jPanel4.setLayout(jPanel4Layout); jPanel4Layout.setHorizontalGroup( jPanel4Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(jLblTotal, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 225, Short.MAX_VALUE) ); jPanel4Layout.setVerticalGroup( jPanel4Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(jLblTotal, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); org.jdesktop.layout.GroupLayout jPanel2Layout = new org.jdesktop.layout.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(jLabel2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .add(jLabel3, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .add(org.jdesktop.layout.GroupLayout.TRAILING, jLabel4, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .add(jLabel5, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .add(jPanel2Layout.createSequentialGroup() .add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(jPanel2Layout.createSequentialGroup() .add(85, 85, 85) .add(jSeparator1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 280, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) .add(jPanel2Layout.createSequentialGroup() .addContainerGap() .add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(jPanel2Layout.createSequentialGroup() .add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING, false) .add(jLabel6, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .add(jLabel8, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(jPanel2Layout.createSequentialGroup() .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(jLblData)) .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel2Layout.createSequentialGroup() .add(7, 7, 7) .add(jLblNumeroPedido, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 112, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))) .add(jPanel2Layout.createSequentialGroup() .add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING, false) .add(jLabel12, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 68, Short.MAX_VALUE) .add(jLabel10, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false) .add(jLblNomeClientePedido, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 113, Short.MAX_VALUE) .add(jLblNomeEntregadorPedido, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))) .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED) .add(jPanel4, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))) .addContainerGap()) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(jPanel2Layout.createSequentialGroup() .add(jLabel2) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(jLabel3) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(jLabel4) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(jLabel5) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(jSeparator1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 10, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false) .add(jPanel2Layout.createSequentialGroup() .add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(jLabel6) .add(jLblNumeroPedido)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(jLabel8) .add(jLblData)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(jLabel10) .add(jLblNomeClientePedido)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(jLabel12) .add(jLblNomeEntregadorPedido))) .add(jPanel4, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addContainerGap(21, Short.MAX_VALUE)) ); jPanel3.setBackground(new java.awt.Color(204, 204, 204)); jTxtSenhaPedido.setFont(new java.awt.Font("Segoe UI", 0, 18)); // NOI18N jTxtSenhaPedido.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(255, 255, 255), 2)); jTxtSenhaPedido.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { jTxtSenhaPedidoKeyReleased(evt); } }); jLabel1.setFont(new java.awt.Font("Segoe UI Light", 0, 18)); // NOI18N jLabel1.setText("Senha:"); jBtnConfirmar.setBackground(new java.awt.Color(51, 153, 0)); jBtnConfirmar.setFont(new java.awt.Font("Segoe UI Light", 0, 18)); // NOI18N jBtnConfirmar.setForeground(new java.awt.Color(204, 255, 204)); jBtnConfirmar.setText("Confirmar"); jBtnConfirmar.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); jBtnConfirmar.setFocusPainted(false); jBtnConfirmar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jBtnConfirmarActionPerformed(evt); } }); org.jdesktop.layout.GroupLayout jPanel3Layout = new org.jdesktop.layout.GroupLayout(jPanel3); jPanel3.setLayout(jPanel3Layout); jPanel3Layout.setHorizontalGroup( jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(jPanel3Layout.createSequentialGroup() .add(12, 12, 12) .add(jLabel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 80, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(12, 12, 12) .add(jTxtSenhaPedido, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 342, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) .add(jPanel3Layout.createSequentialGroup() .add(104, 104, 104) .add(jBtnConfirmar, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 342, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) ); jPanel3Layout.setVerticalGroup( jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(jPanel3Layout.createSequentialGroup() .add(12, 12, 12) .add(jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(jLabel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 40, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(jTxtSenhaPedido, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 40, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) .add(6, 6, 6) .add(jBtnConfirmar) .addContainerGap(24, Short.MAX_VALUE)) ); jBtnCancelar.setBackground(new java.awt.Color(255, 0, 0)); jBtnCancelar.setFont(new java.awt.Font("Segoe UI", 1, 18)); // NOI18N jBtnCancelar.setForeground(new java.awt.Color(255, 204, 204)); jBtnCancelar.setText("X"); jBtnCancelar.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); jBtnCancelar.setFocusPainted(false); jBtnCancelar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jBtnCancelarActionPerformed(evt); } }); org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(jPanel1Layout.createSequentialGroup() .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(jBtnCancelar) .add(jPanel1Layout.createSequentialGroup() .addContainerGap() .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING, false) .add(jPanel3, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .add(jPanel2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))) .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(jPanel1Layout.createSequentialGroup() .addContainerGap() .add(jPanel2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(jPanel3, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(jBtnCancelar)) ); org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(layout.createSequentialGroup() .add(jPanel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(0, 0, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(jPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); pack(); setLocationRelativeTo(null); }// </editor-fold>//GEN-END:initComponents //Persistencia DaoVenda dV = new DaoVenda(); DaoPedido dP = new DaoPedido(); //Negocio Pedido p; //Interface JFrmEntregadorPedido parent; //Variaveis de Controle int senha;//Senha que é gerada no momento do pedido public void carregarObjetos() { jLblNumeroPedido.setText(String.valueOf(p.getID())); jLblData.setText(p.getData()); jLblNomeClientePedido.setText(p.getNome()); jLblNomeEntregadorPedido.setText(p.getEntregador().getNome()); jLblTotal.setText(NumberFormat.getCurrencyInstance().format(p.getValorTotal())); senha = p.getSenha(); } public void setLookAndFeel() { try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Metal".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(JDialogConfirmacaoVenda.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(JDialogConfirmacaoVenda.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(JDialogConfirmacaoVenda.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(JDialogConfirmacaoVenda.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } } private void jTxtSenhaPedidoKeyReleased(java.awt.event.KeyEvent evt)//GEN-FIRST:event_jTxtSenhaPedidoKeyReleased {//GEN-HEADEREND:event_jTxtSenhaPedidoKeyReleased // TODO add your handling code here: /* Permitir somente numeros */ jTxtSenhaPedido.setText(Diversos.testaNum(jTxtSenhaPedido.getText(), 2)); }//GEN-LAST:event_jTxtSenhaPedidoKeyReleased private void jBtnConfirmarActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jBtnConfirmarActionPerformed {//GEN-HEADEREND:event_jBtnConfirmarActionPerformed // TODO add your handling code here: if(!jTxtSenhaPedido.getText().isEmpty()) { int senhaCli = Integer.parseInt(jTxtSenhaPedido.getText()); if(senhaCli == senha || senhaCli == 42) { p.setStatus("Concluído"); p.setTempoEntrega(Diversos.tempoDecorrido(p.getData())); Negocio.Venda v = new Negocio.Venda(); DateFormat dH = DateFormat.getDateTimeInstance(); v.setData(dH.format(new Date().getTime())); v.setEntregador(p.getEntregador()); v.setTotal(p.getValorTotal()); dV.incluir(v); dP.concluido(p); Diversos.mostrarDados("Pedido foi concluído!!\nAugust Agradece","STATUS: CONCLUÍDO", true); parent.carregarCombo(JFrmEntregadorPedido.entregadorAtual);//Olhar deposi dispose(); } else { Diversos.mostrarDados("SENHA INVÁLIDA!!\nInforme a senha que lhe foi passada ao" + " telefone...\nOu informe a resposta pra vida o universo e tudo mais, 42" + "","STATUS: EM ANDAMENTO", false); } } }//GEN-LAST:event_jBtnConfirmarActionPerformed private void jBtnCancelarActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jBtnCancelarActionPerformed {//GEN-HEADEREND:event_jBtnCancelarActionPerformed // TODO add your handling code here: dispose(); }//GEN-LAST:event_jBtnCancelarActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jBtnCancelar; private javax.swing.JButton jBtnConfirmar; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel10; private javax.swing.JLabel jLabel12; 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.JLabel jLabel8; private javax.swing.JLabel jLblData; private javax.swing.JLabel jLblNomeClientePedido; private javax.swing.JLabel jLblNomeEntregadorPedido; private javax.swing.JLabel jLblNumeroPedido; private javax.swing.JLabel jLblTotal; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel3; private javax.swing.JPanel jPanel4; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JScrollPane jScrollPane3; private javax.swing.JSeparator jSeparator1; private javax.swing.JTextPane jTextPane1; private javax.swing.JTextPane jTextPane2; private javax.swing.JTextPane jTextPane3; private javax.swing.JTextField jTxtSenhaPedido; // End of variables declaration//GEN-END:variables }
52.698198
232
0.654415
d028df56ede4a7df7807637c416b0341fb5bf752
2,790
/* * Forge Mod Loader * Copyright (c) 2012-2013 cpw. * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v2.1 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html * * Contributors: * cpw - implementation */ package net.minecraftforge.fml.client.registry; import com.google.common.collect.Maps; import net.minecraft.entity.Entity; import net.minecraft.util.ResourceLocation; import org.apache.commons.lang3.ArrayUtils; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.tileentity.TileEntityRendererDispatcher; import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer; import net.minecraft.client.settings.KeyBinding; import net.minecraft.tileentity.TileEntity; import net.minecraftforge.fml.common.registry.GameRegistry; import java.util.Map; public class ClientRegistry { private static Map<Class<? extends Entity>, ResourceLocation> entityShaderMap = Maps.newHashMap(); /** * * Utility method for registering a tile entity and it's renderer at once - generally you should register them separately * * @param tileEntityClass * @param id * @param specialRenderer */ public static <T extends TileEntity> void registerTileEntity(Class<T> tileEntityClass, String id, TileEntitySpecialRenderer<? super T> specialRenderer) { GameRegistry.registerTileEntity(tileEntityClass, id); bindTileEntitySpecialRenderer(tileEntityClass, specialRenderer); } public static <T extends TileEntity> void bindTileEntitySpecialRenderer(Class<T> tileEntityClass, TileEntitySpecialRenderer<? super T> specialRenderer) { TileEntityRendererDispatcher.instance.mapSpecialRenderers.put(tileEntityClass, specialRenderer); specialRenderer.setRendererDispatcher(TileEntityRendererDispatcher.instance); } public static void registerKeyBinding(KeyBinding key) { Minecraft.getMinecraft().gameSettings.keyBindings = ArrayUtils.add(Minecraft.getMinecraft().gameSettings.keyBindings, key); } /** * Register a shader for an entity. This shader gets activated when a spectator begins spectating an entity. * Vanilla examples of this are the green effect for creepers and the invert effect for endermans. * * @param entityClass * @param shader */ public static void registerEntityShader(Class<? extends Entity> entityClass, ResourceLocation shader) { entityShaderMap.put(entityClass, shader); } public static ResourceLocation getEntityShader(Class<? extends Entity> entityClass) { return entityShaderMap.get(entityClass); } }
37.702703
155
0.755914
820327c3912403de1f8d92ce07e78d063147ec89
4,723
package xf.xfvrp.opt.init.solution.vrp; import xf.xfvrp.base.Node; import xf.xfvrp.base.NormalizeSolutionService; import xf.xfvrp.base.Util; import xf.xfvrp.base.XFVRPModel; import xf.xfvrp.base.exception.XFVRPException; import xf.xfvrp.base.monitor.StatusManager; import xf.xfvrp.base.preset.BlockNameConverter; import xf.xfvrp.opt.Solution; import xf.xfvrp.opt.init.PresetSolutionBuilder; import xf.xfvrp.opt.init.check.vrp.CheckService; import java.util.*; /** * Copyright (c) 2012-2021 Holger Schneider * All rights reserved. * * This source code is licensed under the MIT License (MIT) found in the * LICENSE file in the root directory of this source tree. * * * Creates a trivial solution out of the model. * * The solution must be feasible/valid, but no optimization is * applied. * * @author hschneid * */ public class VRPInitialSolutionBuilder { public Solution build(XFVRPModel model, List<Node> invalidNodes, StatusManager statusManager) throws XFVRPException { List<Node> validNodes = getValidCustomers(model, invalidNodes); Solution solution = buildSolution(validNodes, model, statusManager); NormalizeSolutionService.normalizeRoute(solution, model); return solution; } /** * Builds the giant tour. All invalid nodes are filtered out before. * * @param nodes List of nodes which are valid * @param model Current model of nodes, distances and parameters * @return Current route plan of single trips per customer */ private Solution buildSolution(List<Node> nodes, XFVRPModel model, StatusManager statusManager) throws XFVRPException { if(nodes == null) { return new Solution(); } // If user has given a predefined solution if(model.getParameter().getPredefinedSolutionString() != null) return new PresetSolutionBuilder().build(nodes, model, statusManager); return generateSolution(nodes, model); } private Solution generateSolution(List<Node> nodes, XFVRPModel model) { List<Node> gL = new ArrayList<>(); // GlobalIndex -> Depot Map<Integer, Node> depotMap = new HashMap<>(); for (int i = 0; i < model.getNbrOfDepots(); i++) depotMap.put(nodes.get(i).getGlobalIdx(), nodes.get(i)); // Create single routes for each block or single customer without block int depotIdx = 0; int maxIdx = 0; int lastBlockIdx = Integer.MAX_VALUE; // Create single routes for each block or single customer without block // Consider preset depot Set<Integer> depots = new HashSet<>(); for (Node dep : nodes.subList(0, model.getNbrOfDepots())) depots.add(dep.getGlobalIdx()); for (int i = model.getNbrOfDepots() + model.getNbrOfReplenish(); i < nodes.size(); i++) { Node currNode = nodes.get(i); // Reduce allowed depots to preset allowed depots List<Integer> allowedDepots = getAllowedDepots(currNode, depots); // Add a depot after each change of block or unblocked customer final int blockIdx = currNode.getPresetBlockIdx(); if(blockIdx == BlockNameConverter.DEFAULT_BLOCK_IDX || blockIdx != lastBlockIdx) { // Get an index for an element of allowed depots int idx = depotIdx % allowedDepots.size(); // Add depot with new own id gL.add(Util.createIdNode(depotMap.get(allowedDepots.get(idx)), maxIdx++)); } // Add customer gL.add(currNode); depotIdx++; lastBlockIdx = blockIdx; } // Add last depot gL.add(Util.createIdNode(nodes.get(depotIdx % depots.size()), maxIdx)); Solution solution = new Solution(); solution.setGiantRoute(gL.toArray(new Node[0])); return solution; } private List<Integer> getAllowedDepots(Node currNode, Set<Integer> depots) { if(currNode.getPresetDepotList().size() > 0) { Set<Integer> allowedDepots = new HashSet<>(depots); allowedDepots.retainAll(currNode.getPresetDepotList()); return new ArrayList<>(allowedDepots); } return new ArrayList<>(depots); } private List<Node> getValidCustomers(XFVRPModel model, List<Node> invalidNodes) throws XFVRPException { SolutionBuilderDataBag solutionBuilderDataBag = new CheckService().check(model, invalidNodes); // If all customers are invalid for this vehicle and parameters optimization has to be skipped. if(solutionBuilderDataBag.getValidCustomers().size() == 0) { return null; } // Consider Preset Rank and Position solutionBuilderDataBag.getValidCustomers().sort( Comparator .comparingInt(Node::getPresetBlockIdx) .thenComparingInt(Node::getPresetBlockPos) ); List<Node> validNodes = new ArrayList<>(); validNodes.addAll(solutionBuilderDataBag.getValidDepots()); validNodes.addAll(solutionBuilderDataBag.getValidReplenish()); validNodes.addAll(solutionBuilderDataBag.getValidCustomers()); return validNodes; } }
33.027972
120
0.73682
d49b582db1c4a84d7b0201e6fc0c636e270cc71a
651
package com.example.demo.exception; public class ClassifierNotFoundException extends Exception { public ClassifierNotFoundException() { super(); } public ClassifierNotFoundException(String message) { super(message); } public ClassifierNotFoundException(String message, Throwable cause) { super(message, cause); } public ClassifierNotFoundException(Throwable cause) { super(cause); } public ClassifierNotFoundException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } }
36.166667
98
0.729647
e62023113fb281d8efea488e6c58dbf105e2cd6d
3,244
package com.dt.betting.controller.championship; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; import com.dt.betting.controller.BettingAppController; import com.dt.betting.controller.admin.AddTeamParam; import com.dt.betting.controller.admin.AdminController; import com.dt.betting.db.domain.Championship; import com.dt.betting.db.repository.DataNotExistsInRepositoryException; import com.dt.betting.db.repository.inmemory.ChampionshipDataRepository; import com.dt.betting.user.UserDoesNotExistsException; @Controller public class ChampionshipController extends BettingAppController { @Autowired private ChampionshipDataRepository championshipDataRepository; @Autowired private ChampionshipListController championshipListController; @Autowired private RoundController roundController; @Autowired private AdminController adminController; @RequestMapping(value = "/ds/championship", params = "championshipId") public ModelAndView getChampionshipDetails(@RequestParam("championshipId") Long championshipId, HttpServletRequest request) { return getChampionshipDetails(championshipId, Arrays.asList(), request); } @RequestMapping("/ds/championship/addTeam") public ModelAndView addTeam(AddTeamParam param, HttpServletRequest request) { List<String> errorMessages = adminController.addTeam(param, request); if (param.getRoundId() != null) { return roundController.getRoundDetails(param.getRoundId(), request); } return getChampionshipDetails(param.getChampionshipId(), errorMessages, request); } public ModelAndView getChampionshipDetails(Long championshipId, List<String> previousErrorMessages, HttpServletRequest request) { if (championshipId == null) { return championshipListController.listChampionships(Arrays.asList("A kiválasztott bajnokság nem ismert."), request); } List<String> errorMessages = previousErrorMessages == null ? new ArrayList<>() : new ArrayList<>(previousErrorMessages); Championship championship = null; boolean admin = false; try { championship = championshipDataRepository.getById(championshipId); admin = isAdmin(request); } catch (DataNotExistsInRepositoryException | UserDoesNotExistsException ex) { errorHandler(errorMessages, ex); return championshipListController.listChampionships(errorMessages, request); } ModelAndView mav = new ModelAndView(getViewName(request)); mav.addObject("errorMessages", errorMessages); mav.addObject("championship", championship); mav.addObject("admin", admin); return mav; } private String getViewName(HttpServletRequest request) { return isOnlyDetailsPage(request) ? "championshipMainPage" : "championshipDetailsPage"; } private boolean isOnlyDetailsPage(HttpServletRequest request) { return request.getParameter("onlyDetails") == null; } }
38.164706
131
0.790691
2c6acacc5c6d2ab232b2597e2f9cce31f0228ed5
3,637
/* * The MIT License (MIT) * * Copyright (c) 2013 Dries K. Aka Dries007 and the CCM modding crew. * * 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 ccm.pay2spawn.network; import ccm.pay2spawn.Pay2Spawn; import ccm.pay2spawn.util.Helper; import cpw.mods.fml.common.FMLCommonHandler; import cpw.mods.fml.common.eventhandler.SubscribeEvent; import cpw.mods.fml.common.gameevent.PlayerEvent; import cpw.mods.fml.common.network.FMLNetworkEvent; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.network.NetHandlerPlayServer; import net.minecraft.server.MinecraftServer; import net.minecraft.util.EnumChatFormatting; import java.util.Timer; import java.util.TimerTask; import static ccm.pay2spawn.util.Constants.NAME; /** * Oh god its event based now -_- * * @author Dries007 */ public class ConnectionHandler { public static final ConnectionHandler INSTANCE = new ConnectionHandler(); private ConnectionHandler() { FMLCommonHandler.instance().bus().register(this); } public void init() { } @SubscribeEvent public void playerLoggedIn(PlayerEvent.PlayerLoggedInEvent event) { if (event.player instanceof EntityPlayerMP) // Cheap server detection StatusMessage.sendHandshakeToPlayer((EntityPlayerMP) event.player); } @SubscribeEvent public void connectionReceived(FMLNetworkEvent.ServerConnectionFromClientEvent event) { if (!event.isLocal && Pay2Spawn.getConfig().forceP2S) { final String username = ((NetHandlerPlayServer) event.handler).playerEntity.getCommandSenderName(); new Timer().schedule(new TimerTask() { @Override public void run() { if (!StatusMessage.doesPlayerHaveValidConfig(username)) MinecraftServer.getServer().getConfigurationManager().getPlayerForUsername(username).playerNetServerHandler.kickPlayerFromServer("Pay2Spawn is required on this server.\nIt needs to be configured properly."); } }, 5 * 1000); } } @SubscribeEvent public void disconnect(FMLNetworkEvent.ClientDisconnectionFromServerEvent event) { Pay2Spawn.reloadDB(); StatusMessage.resetServerStatus(); new Timer().schedule(new TimerTask() { @Override public void run() { if (!StatusMessage.doesServerHaveMod()) Helper.msg(EnumChatFormatting.RED + NAME + " isn't on the server. No rewards will spawn!"); } }, 5 * 1000); } }
36.37
283
0.707451
b858ad9134987a8b3ccc7f5bd8b7d6f7f15fba47
352
package com.nullpointerbay.turbochat.utils; import android.content.Context; import android.widget.ImageView; /** * Created by charafau on 2017/02/12. */ public interface ImageLoader { void loadImage(Context context, String url, ImageView target); void loadImageWithCircleTransformation(Context context, String url, ImageView target); }
20.705882
90
0.772727
60b552ecc864ffad8e1b4e6cfd8eef4860908d8e
2,809
/* * Copyright (C) 2017 Oracle * * 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.xml.xsom; import java.util.Collection; import java.util.Iterator; /** * Common aspect of {@link XSComplexType} and {@link XSAttGroupDecl} * as the container of attribute uses/attribute groups. * * @author * Kohsuke Kawaguchi ([email protected]) */ public interface XSAttContainer extends XSDeclaration { XSWildcard getAttributeWildcard(); /** * Looks for the attribute use with the specified name from * all the attribute uses that are directly/indirectly * referenced from this component. * * <p> * This is the exact implementation of the "attribute use" * schema component. */ XSAttributeUse getAttributeUse( String nsURI, String localName ); /** * Lists all the attribute uses that are directly/indirectly * referenced from this component. * * <p> * This is the exact implementation of the "attribute use" * schema component. */ Iterator<? extends XSAttributeUse> iterateAttributeUses(); /** * Gets all the attribute uses. */ Collection<? extends XSAttributeUse> getAttributeUses(); /** * Looks for the attribute use with the specified name from * the attribute uses which are declared in this complex type. * * This does not include att uses declared in att groups that * are referenced from this complex type, nor does include * att uses declared in base types. */ XSAttributeUse getDeclaredAttributeUse( String nsURI, String localName ); /** * Lists all the attribute uses that are declared in this complex type. */ Iterator<? extends XSAttributeUse> iterateDeclaredAttributeUses(); /** * Lists all the attribute uses that are declared in this complex type. */ Collection<? extends XSAttributeUse> getDeclaredAttributeUses(); /** * Iterates all AttGroups which are directly referenced from * this component. */ Iterator<? extends XSAttGroupDecl> iterateAttGroups(); /** * Iterates all AttGroups which are directly referenced from * this component. */ Collection<? extends XSAttGroupDecl> getAttGroups(); }
31.211111
77
0.686365
f36760d7d5b40c1ede512e76213575352f24cec5
3,410
/* * This file is part of the Wayback archival access software * (http://archive-access.sourceforge.net/projects/wayback/). * * Licensed to the Internet Archive (IA) by one or more individual * contributors. * * The IA 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.archive.wayback.webapp; import java.util.logging.Level; import java.util.logging.Logger; /** * Brutally simple, barely functional class to allow simple recording of * millisecond level timing within a particular request, enabling rough logging * of the time spent in various parts of the handling of a WaybackRequest * @author brad * */ public class PerformanceLogger { private static final Logger LOGGER = Logger.getLogger( PerformanceLogger.class.getName()); private static char delim = '\t'; private String type = null; private long start = 0; private long query = 0; private long retrieve = -1; private long render = 0; /** * Construct a Performance logger with the specified String "type" * @param type the String type to report with the logged output */ public PerformanceLogger(String type) { this.type = type; this.start = System.currentTimeMillis(); } /** * record the time when the query associated with this request completed */ public void queried() { this.query = System.currentTimeMillis(); } /** * record the time when the retrieval of a Resource required for this * request completed, implies a Replay request... */ public void retrieved() { this.retrieve = System.currentTimeMillis(); } /** * record the time when the replayed resource, or the query results were * returned to the client, implies the bulk of the request processing is * complete. */ public void rendered() { this.render = System.currentTimeMillis(); } /** * Produce a debug message to this classes logger, computing the time * taken to query the index, retrieve the resource (if a replay request) * and render the results to the client. * @param info String suffix to append to the log message */ public void write(String info) { StringBuilder sb = new StringBuilder(40); sb.append(type).append(delim); sb.append(query - start).append(delim); if(retrieve == -1) { sb.append(render - query).append(delim); } else { sb.append(retrieve - query).append(delim); sb.append(render - retrieve).append(delim); } sb.append(info); LOGGER.finer(sb.toString()); } public static void noteElapsed(String message, long elapsed, String note) { if(LOGGER.isLoggable(Level.INFO)) { StringBuilder sb = new StringBuilder(); sb.append("WB-PERF\t").append(message).append("\t").append(elapsed); if(note != null) { sb.append("\t").append(note); } LOGGER.info(sb.toString()); } } public static void noteElapsed(String message, long elapsed) { noteElapsed(message,elapsed,null); } }
32.169811
79
0.71085
c3c56fdf1f2bcf1bce01d9605501ddb265dec461
3,292
package de.lessvoid.nifty.slick2d.render; import org.newdawn.slick.Color; import org.newdawn.slick.ShapeFill; import org.newdawn.slick.geom.Shape; import org.newdawn.slick.geom.Vector2f; import javax.annotation.Nonnull; /** * This shape fill implementation is used to render the rectangles of slick that that have a different color on each * edge. This implementation is not supposed to be used for any other purpose. * * @author Martin Karing &lt;[email protected]&gt; */ final class SlickQuadFill implements ShapeFill { /** * This is the vector that is returned as offset at all times. */ private static final Vector2f NULL_VECTOR = new Vector2f(0, 0); /** * The color on the bottom left corner of the shape. */ @Nonnull private final Color bottomLeft; /** * The color on the bottom right corner of the shape. */ @Nonnull private final Color bottomRight; /** * The color on the top left corner of the shape. */ @Nonnull private final Color topLeft; /** * The color on the top right corner of the shape. */ @Nonnull private final Color topRight; /** * Create a new rectangle filling instance. * * @param tlColor the color at the top left * @param trColor the color at the top right * @param blColor the color at the bottom left * @param brColor the color at the bottom right */ SlickQuadFill( @Nonnull final de.lessvoid.nifty.tools.Color tlColor, @Nonnull final de.lessvoid.nifty.tools.Color trColor, @Nonnull final de.lessvoid.nifty.tools.Color blColor, @Nonnull final de.lessvoid.nifty.tools.Color brColor) { topLeft = SlickRenderUtils.convertColorNiftySlick(tlColor); topRight = SlickRenderUtils.convertColorNiftySlick(trColor); bottomLeft = SlickRenderUtils.convertColorNiftySlick(blColor); bottomRight = SlickRenderUtils.convertColorNiftySlick(brColor); } /** * Change all the color values. * * @param tlColor the color at the top left * @param trColor the color at the top right * @param blColor the color at the bottom left * @param brColor the color at the bottom right */ public void changeColors( @Nonnull final de.lessvoid.nifty.tools.Color tlColor, @Nonnull final de.lessvoid.nifty.tools.Color trColor, @Nonnull final de.lessvoid.nifty.tools.Color blColor, @Nonnull final de.lessvoid.nifty.tools.Color brColor) { SlickRenderUtils.convertColorNiftySlick(tlColor, topLeft); SlickRenderUtils.convertColorNiftySlick(trColor, topRight); SlickRenderUtils.convertColorNiftySlick(blColor, bottomLeft); SlickRenderUtils.convertColorNiftySlick(brColor, bottomRight); } /** * Get the color at one point on the shape. */ @Nonnull @Override public Color colorAt(@Nonnull final Shape shape, final float x, final float y) { final boolean isMaxX = Math.abs(x - shape.getMaxX()) < 0.0f; final boolean isMaxY = Math.abs(y - shape.getMaxY()) < 0.0f; if (isMaxX) { return isMaxY ? topRight : topLeft; } else { return isMaxY ? bottomRight : bottomLeft; } } /** * Get the offset at a location. */ @Nonnull @Override public Vector2f getOffsetAt(final Shape shape, final float x, final float y) { return NULL_VECTOR; } }
29.392857
116
0.706561
24563bc77914c47fb9724619c7a34270bbe8cba4
764
package ru.daniilazarnov.bot.core.memory; import ru.daniilazarnov.common.model.entity.Action; import ru.daniilazarnov.common.model.entity.Actor; import ru.daniilazarnov.common.model.entity.State; import java.util.Set; public interface MemoryDao { boolean isInitSession(String sessionId); void updateAppraisal(String sessionId, Actor actor, Actor target, Action action); void updateAllAppraisal(String sessionId, Actor actor, Action action); void updateSelfAppraisal(String sessionId, Actor actor, Action action); Set<State> getAppraisalState(String sessionId); void initSession(String sessionId); void initMemoryForActorInSession(String sessionId, Actor actor); boolean isNotDetermined(String sessionId, Actor actor); }
27.285714
85
0.78534
e073b2f21c13544e5fbec3dc098451e854ff322b
2,035
package org.springframework.boot.autoconfigure.http; import javax.json.bind.Jsonb; import org.springframework.boot.autoconfigure.condition.AnyNestedCondition; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Conditional; import org.springframework.context.annotation.Configuration; import org.springframework.http.converter.json.GsonHttpMessageConverter; import org.springframework.http.converter.json.JsonbHttpMessageConverter; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; /** * Configuration for HTTP Message converters that use JSON-B. * * @author Eddú Meléndez * @since 2.0.0 */ @Configuration @ConditionalOnClass(Jsonb.class) class JsonbHttpMessageConvertersConfiguration { @Configuration @ConditionalOnBean(Jsonb.class) @Conditional(PreferJsonbOrMissingJacksonAndGsonCondition.class) protected static class JsonbHttpMessageConverterConfiguration { @Bean @ConditionalOnMissingBean public JsonbHttpMessageConverter jsonbHttpMessageConverter(Jsonb jsonb) { JsonbHttpMessageConverter converter = new JsonbHttpMessageConverter(); converter.setJsonb(jsonb); return converter; } } private static class PreferJsonbOrMissingJacksonAndGsonCondition extends AnyNestedCondition { PreferJsonbOrMissingJacksonAndGsonCondition() { super(ConfigurationPhase.REGISTER_BEAN); } @ConditionalOnProperty(name = HttpMessageConvertersAutoConfiguration.PREFERRED_MAPPER_PROPERTY, havingValue = "jsonb") static class JsonbPreferred { } @ConditionalOnMissingBean({ MappingJackson2HttpMessageConverter.class, GsonHttpMessageConverter.class }) static class JacksonAndGsonMissing { } } }
31.307692
120
0.837838
b06ebc55c358b7b8f3868de4d898f36fcce99c78
1,007
package io.ebean.util; import org.junit.Test; import static org.junit.Assert.assertEquals; public class CamelCaseHelperTest { @Test public void when_underscore() throws Exception { assertEquals(CamelCaseHelper.toCamelFromUnderscore("hello_there"), "helloThere"); assertEquals(CamelCaseHelper.toCamelFromUnderscore("hello_there_jim"), "helloThereJim"); } @Test public void when_trailing_numbers() throws Exception { assertEquals(CamelCaseHelper.toCamelFromUnderscore("hello_1"), "hello1"); assertEquals(CamelCaseHelper.toCamelFromUnderscore("hello_there_2"), "helloThere2"); } @Test public void when_already_camel() throws Exception { assertEquals(CamelCaseHelper.toCamelFromUnderscore("helloThere"), "helloThere"); assertEquals(CamelCaseHelper.toCamelFromUnderscore("helloThereJim"), "helloThereJim"); assertEquals(CamelCaseHelper.toCamelFromUnderscore("hello"), "hello"); assertEquals(CamelCaseHelper.toCamelFromUnderscore("HELLO"), "HELLO"); } }
31.46875
92
0.775571
4d28f316459cc9f89246e2c2408757a682e94c65
14,131
package com.isaacsheff.charlotte.yaml; import static java.time.LocalTime.now; import java.util.Random; import java.util.concurrent.TimeUnit; import java.util.logging.Level; import java.util.logging.Logger; import javax.net.ssl.SSLException; import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; import org.bouncycastle.cert.X509CertificateHolder; import org.bouncycastle.openssl.PEMException; import org.bouncycastle.openssl.PEMParser; import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter; import org.bouncycastle.openssl.jcajce.JcaPEMWriter; import org.bouncycastle.util.io.pem.PemObject; import com.isaacsheff.charlotte.node.CharlotteNodeClient; import com.isaacsheff.charlotte.node.SignatureUtil; import com.isaacsheff.charlotte.proto.CryptoId; import io.grpc.ManagedChannel; import io.grpc.netty.GrpcSslContexts; import io.grpc.netty.NettyChannelBuilder; import io.netty.channel.ChannelOption; import io.netty.handler.ssl.SslContext; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.InputStream; import java.io.Reader; import java.lang.String; import java.nio.file.Path; import java.security.PublicKey; import java.security.Security; /** * Represents the contact information for a CharlotteNode server, as stored in a config file. * These contacts are expected to have a URL, TCP Port, and X509 certificate (public key). * This is in some sense a wrapper around JsonConfig, which is literally what you get * when you parse a config file's contact elements. * However, creating a Contact object checks a bunch of stuff, like reading and parsing the X509 cert file. * @author Isaac Sheff */ public class Contact { /** This line is required to use bouncycastle encryption libraries. */ static {Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());} /** Use this for logging events in the Contact class. */ private static final Logger logger = Logger.getLogger(Contact.class.getName()); /** The literal data parsed from a contact in a config file. */ private final JsonContact jsonContact; /** the Config of which this is a part */ private final Config parentConfig; /** The literal bytes of the x509 certificate file. */ private final byte[] x509Bytes; /** * An Ssl configuration in which the X509 certificate file for this contact is trusted. * Used in opening secure channels to talk to the server this contact represents. * We create this when we first need it, so if it's null, we have to make one. */ private SslContext sslContext; /** * The X509 certificate parsed as a PublicKey for crypto libraries. * Uses BouncyCastle. */ private final PublicKey publicKey; /** The parsed X509 Certificate */ private final X509CertificateHolder holder; /** The CryptoId of this contact (made from its public key, but a Protobuf datatype) */ private final CryptoId cryptoId; /** * For use with actually communicating with the server this Contact represents. * This is the only part of Contact that's really specific to the Charlotte API. * Remains null until first asked for. */ private CharlotteNodeClient charlotteNodeClient; /** * Generate a Contact using a JsonContact. * (which was parsed from a config file), * and the path representing the dir in which the config file was located * (to resolve relative filenames). * If the JsonContact is null, we log warnings, but do not actually crash immediately. * These contacts are expected to have a URL, TCP Port, and X509 certificate (public key). * @param jsonContact was parsed from a config file * @param path the path representing the dir in which the config file was located */ public Contact(JsonContact jsonContact, Path path, Config parentConfig) { this.jsonContact = jsonContact; this.parentConfig = parentConfig; if (null == getJsonContact()) { logger.log(Level.WARNING, "Creating a Contact with null json / yaml information. Things may break."); } x509Bytes = readFile("x509", path.resolve(getX509())); holder = generateHolder(); publicKey = generatePublicKey(); cryptoId = SignatureUtil.createCryptoId(getPublicKey()); charlotteNodeClient = null; // will be initiated when first asked for sslContext = null; // will be initiated when first asked for } /** @return The CryptoId of this contact (made from its public key, but a Protobuf datatype) */ public CryptoId getCryptoId() {return cryptoId;} /** @return the PublicKey parsed from the X509 certificate */ public PublicKey getPublicKey() {return publicKey;} /** @return the JsonContact (from which this Contact was made) parsed from the config file */ public JsonContact getJsonContact() {return this.jsonContact;} /** @return the Config of which this is a part */ public Config getParentConfig() {return parentConfig;} /** @return the url string for finding the server this Contact represents */ public String getUrl() {return getJsonContact().getUrl();} /** @return the TCP port number for the server this Contact represents */ public int getPort() {return getJsonContact().getPort();} /** @return the filename of the X509 certificate, relative to the config file. */ public String getX509() {return getJsonContact().getX509();} /** @return The literal bytes of the x509 certificate file. */ public byte[] getX509Bytes() {return this.x509Bytes;} /** @return An InputStream which reads the literal bytes of the x509 certificate file. */ public ByteArrayInputStream getX509Stream() {return (new ByteArrayInputStream(getX509Bytes()));} /** @return A Reader which reads the literal bytes of the x509 certificate file. */ public InputStreamReader getX509Reader() {return (new InputStreamReader(getX509Stream()));} /** @return The parsed X509 Certificate */ public X509CertificateHolder getHolder() {return holder;} /** * Used in opening secure channels to talk to the server this contact represents. * @return An Ssl configuration in which the X509 certificate file for this contact is trusted. */ public SslContext getSslContext() { if (sslContext == null) { sslContext = getContext(); } return sslContext; } /** * Used in opening channels to talk to the server this contact represents. * @param delayInterval the builder will pseudorandomly delay between 0 and delayInterval NANOSECONDS * @return A ChannelBuilder for this contact's url and port */ private NettyChannelBuilder getChannelBuilder(long delayInterval) { try { logger.log(Level.INFO, "Channel Start Delay is happening now: " + now()); TimeUnit.NANOSECONDS.sleep(Math.floorMod((new Random( (getParentConfig().getUrl() + ":" + getParentConfig().getPort() + "\t" + getUrl() + ":" + getPort()). hashCode() )).nextLong(), delayInterval)); } catch (InterruptedException e) { logger.log(Level.SEVERE, "Interrupted while trying to sleep prior to channel building", e); } logger.info("Establishing a new channel to " + getUrl() + ":" + getPort()); return NettyChannelBuilder.forAddress(getUrl(),getPort()); } /** * Create a Managed Channel talking to the server this Contact describes. * It uses: * <ul> * <li>TLS using the X509 certificate in this Contact</li> * <li>Automatic Retry (as implemented in NettyChannel objects</li> * </ul> * It will pseudorandomly delay between 0 and 1 seconds. * @return A Managed Channel talking to the server this Contact describes. */ public ManagedChannel getManagedChannel() { return getManagedChannel(1000000000l /** 1 second */); } /** * Create a Managed Channel talking to the server this Contact describes. * It uses: * <ul> * <li>TLS using the X509 certificate in this Contact</li> * <li>Automatic Retry (as implemented in NettyChannel objects</li> * </ul> * @param delayInterval will pseudorandomly delay between 0 and delayInterval NANOSECONDS * @return A Managed Channel talking to the server this Contact describes. */ public ManagedChannel getManagedChannel(long delayInterval) { return getChannelBuilder(delayInterval). withOption(ChannelOption.SO_REUSEADDR, true). withOption(ChannelOption.TCP_NODELAY, true). useTransportSecurity(). // disableRetry(). enableRetry(). sslContext(getSslContext()). maxInboundMessageSize(Integer.MAX_VALUE). build(); } /** @return a client for use with actually communicating with the server this Contact represents. */ public CharlotteNodeClient getCharlotteNodeClient() { // I'm trying to make this as lightweight as possible after the first time it's called. // If charlotteNodeClient has already been set, return it. // Otherwise, grab a lock if (charlotteNodeClient == null) { synchronized(this) { // If, after we've grabbed the lock, it still hasn't been set, set it if (charlotteNodeClient == null) { charlotteNodeClient = new CharlotteNodeClient(this); } } } return charlotteNodeClient; } /** * Generate the X509 Certificate Holder object (BouncyCastle's Certificate Object, essentially) from the bytes we have. * @return the X509 Certificate Holder object from the bytes we have. */ private X509CertificateHolder generateHolder() { X509CertificateHolder holder = null; Reader reader = getX509Reader(); PEMParser parser= new PEMParser(reader); try { Object object = parser.readObject(); if (!(object instanceof X509CertificateHolder)) { logger.log(Level.WARNING, "Object Parsed is not a SubjectPublicKeyInfo: " + object); } holder = ((X509CertificateHolder) object); } catch (IOException e) { logger.log(Level.SEVERE, "PEM converter could not pull a PublicKeyInfo from the X509 PEM", e); } try { parser.close(); } catch (IOException e) { logger.log(Level.WARNING, "PEM parser did not close properly, but we parsed everything, so it's probably ok.", e); } try { reader.close(); } catch (IOException e) { logger.log(Level.WARNING, "X509 byte[] reader didn't close properly, but we parsed everything, so it's probably ok.", e); } return holder; } /** * Generate a PublicKey from the PEM X509 file read in this Contact. * This parsing could go wrong and log SEVERE things, and then return null. * This will be run in the constructor. * @return PublicKey from the PEM X509 file read in this Contact. */ private PublicKey generatePublicKey() { PublicKey publicKey = null; try { SubjectPublicKeyInfo publicKeyInfo = getHolder().getSubjectPublicKeyInfo(); JcaPEMKeyConverter converter = new JcaPEMKeyConverter(); publicKey = converter.getPublicKey(publicKeyInfo); } catch (PEMException e) { logger.log(Level.SEVERE, "X509 cert file could not be parsed as PEM", e); } return publicKey; } /** * Read the PEM X509 file read in this Contact. * This could go wrong and log SEVERE things, and then return null. * This will be run in the constructor. * @return bytes from the PEM X509 file read in this Contact. */ public static byte[] readFile(String description, Path filename) { byte[] bytes = null; try { InputStream read = new FileInputStream(filename.toFile()); bytes = read.readAllBytes(); read.close(); } catch (FileNotFoundException e) { logger.log(Level.SEVERE, description + " file not found: " + filename, e); } catch (SecurityException e) { logger.log(Level.SEVERE, "Don't have permission to read " + description + ": " + filename, e); } catch (IOException e) { logger.log(Level.SEVERE, "There was an Exception reading " + description + ": " + filename, e); } catch (OutOfMemoryError e) { logger.log(Level.SEVERE, "Ran out of memory while reading " + description + ": " + filename, e); } return bytes; } /** * Generate an Ssl configuration in which the X509 certificate file for this contact is trusted. * This configuration will be used in opening secure channels to talk to the server this contact * represents. * This could go wrong and log WARNING things, and then return null. * This will be run when an sslContext is first requested. * @return an Ssl configuration in which the X509 certificate file for this contact is trusted */ private SslContext getContext() { SslContext context = null; ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); JcaPEMWriter writer = new JcaPEMWriter(new OutputStreamWriter(outputStream)); try { writer.writeObject(new PemObject("CERTIFICATE", holder.toASN1Structure().getEncoded())); } catch (IOException e) { logger.log(Level.WARNING, "Something went wrong writing cert to ssl context thing", e); } try { writer.close(); } catch (IOException e) { logger.log(Level.WARNING, "Something went wrong closing a writer. This shouldn't happen.", e); } try { context = GrpcSslContexts.forClient(). trustManager(new ByteArrayInputStream(outputStream.toByteArray())). keyManager(getParentConfig().getX509Stream(), getParentConfig().getPrivateKeyStream()). build(); } catch (NullPointerException e) { logger.log(Level.SEVERE, "Something went wrong while creating the GrpcSslContext for this Contact",e); } catch (IllegalArgumentException e) { logger.log(Level.WARNING, "Something went wrong setting trust manager. Maybe your cert is off.", e); } catch (SSLException e) { logger.log(Level.WARNING, "Something went wrong with SSL while setting trust manager. Maybe your cert is off.", e); } return context; } }
41.078488
121
0.709645
8337f2785a673bf48c53a4db5658a83e49a1ad47
2,550
package com.be.library.worker.annotations.compiler.statements; import com.be.library.worker.annotations.compiler.FieldInfo; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.TypeName; import com.squareup.javapoet.TypeVariableName; /** * Generates extra setter for ForkJoinJob * * Created by Dzhey on 29-Mar-16. */ public class ForkJoinJobExtraSetterBuilder implements MethodStatementBuilder { private final String mArgJobName; protected ForkJoinJobExtraSetterBuilder(String argJobName) { mArgJobName = argJobName; } public static ForkJoinJobExtraSetterBuilder of(String argJobName) { return new ForkJoinJobExtraSetterBuilder(argJobName); } @Override public void buildStatements(MethodSpec.Builder specBuilder, FieldInfo fieldInfo) { final String extraFieldName = fieldInfo.makeKeyFieldName(); specBuilder.beginControlFlow("if ($L.hasExtra($L))", mArgJobName, extraFieldName); final TypeName extraParamTypeName = TypeVariableName.get(fieldInfo.getVariableTypeName()); specBuilder.beginControlFlow("try"); specBuilder.addStatement("$L.$L = ($T) $L.findExtra($L)", mArgJobName, fieldInfo.getVariableSimpleName(), extraParamTypeName, mArgJobName, extraFieldName); specBuilder.endControlFlow(); specBuilder.beginControlFlow("catch ($T e)", ClassCastException.class); specBuilder.addStatement("throw new $T($S + \"\\\"\" + \n$L.findExtra($L).getClass().getName() + \"\\\"\")", RuntimeException.class, String.format("Failed to inject extra \"%s\" to \"%s\". Expected type \"%s\", but got ", fieldInfo.getVariableSimpleName(), fieldInfo.getSimpleJobName(), extraParamTypeName), mArgJobName, extraFieldName); specBuilder.endControlFlow(); specBuilder.endControlFlow(); if (!fieldInfo.isOptional()) { specBuilder.beginControlFlow("else"); specBuilder.addStatement("throw new $T($S)", IllegalArgumentException.class, String.format("Failed to inject extras to \"%s\". Required value \"%s\" not found in job params.", fieldInfo.getSimpleJobName(), fieldInfo.getVariableSimpleName())); specBuilder.endControlFlow(); } } }
39.230769
118
0.62902
fd477718f232652d3d4c59ddcae7afb7ad14e4b7
2,327
package com.github.cjqcn.tiny.statemachine.core.impl; import com.github.cjqcn.tiny.statemachine.core.*; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; public class StateMachineManagerBuilderImpl<S, E> implements StateMachineManagerBuilder<S, E> { private final String id; private final S initialState; private Map<S/* from */, List<Transition<S, E>>> transitionMap; private StateMachineManager<S, E> stateMachineManager; private volatile boolean init = false; public StateMachineManagerBuilderImpl(String id, S initialState) { this.id = id; this.initialState = initialState; this.transitionMap = new ConcurrentHashMap<>(); } @Override public TransitionsBuilder<S, E> transitions() { checkStatus(); return new TransitionBuilderImpl<>(transitionMap, this); } private void checkStatus() { if (init) { throw new IllegalStateException(); } } @Override public synchronized StateMachineManager<S, E> build() { init = true; transitionMap = Collections.unmodifiableMap(transitionMap); stateMachineManager = new StateMachineManagerImpl<>(); return stateMachineManager; } class StateMachineManagerImpl<S, E> implements StateMachineManager<S, E> { private Map<String/*machineId*/, StateMachine<S, E>> stateMachineMap = new ConcurrentHashMap<>(); @Override public String id() { return id; } @Override public StateMachine<S, E> get(String machineId) { return stateMachineMap.get(machineId); } @Override public StateMachine<S, E> newInstance() { return newInstance(UUID.randomUUID().toString()); } @Override public StateMachine<S, E> newInstance(String machineId) { StateMachine<S, E> stateMachine = new StateMachineImpl(machineId, initialState, transitionMap); StateMachine<S, E> oldStateMachine = stateMachineMap.putIfAbsent(machineId, stateMachine); if (oldStateMachine != null) { throw new IllegalStateException(); } return stateMachine; } } }
31.876712
107
0.654491
cbd9f967c07c927c1485ceed2007f596ee077d1c
1,402
import kareltherobot.*; /** * Abstract Hurdler Robot. * * @author Bryan Wu * @version 2/23/15 * * @author Period - 7 * @author Assignment - ch4_2RacerRobot * * @author Sources - Dave Wittry */ public abstract class AbstractHurdlerRobot extends AbstractRacerRobot { public AbstractHurdlerRobot( int st, int av, Direction dir, int beeps ) { super( st, av, dir, beeps ); } public abstract void over(); // implement over() method (may be abstract) public void up() // implement up() method (may be abstract) { turnLeft(); while ( wallOnRight() ) { move(); } turnRight(); } public void down() { turnRight(); move(); while ( wallOnRight() && frontIsClear() ) { move(); } turnLeft(); } public void raceStride() { moveToHurdleOrBeeper(); if ( !nextToABeeper() ) { up(); over(); down(); } } public boolean wallOnRight() { turnRight(); if ( !frontIsClear() ) { turnLeft(); return true; } turnLeft(); return false; } public void moveToHurdleOrBeeper() { while ( frontIsClear() && !nextToABeeper() ) { move(); } } }
16.891566
77
0.485735
f67d3d72df9b88927cbb8c2bb0ff012d5260daad
311
package com.springinaction.springidol; public class ThinkerImpl implements Thinker { private String thoughts; public void thinkOfSomething(String thoughts) { this.thoughts = thoughts; System.out.println("thinkOfSomething executed"); } public String getThoughts() { return thoughts; } }
23.923077
51
0.742765
695f272911771d9bbe7d730f01e5f4cb0b8bec45
6,733
/* Copyright 2014 Magnus Bridén 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.haxtastic.haxmasher.entity.hud; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.g2d.TextureAtlas.AtlasRegion; import com.haxtastic.haxmasher.Art; import com.haxtastic.haxmasher.Constants; import com.haxtastic.haxmasher.entity.Actor; import com.haxtastic.haxmasher.entity.masher.Guy; import com.haxtastic.haxmasher.entity.masher.Masher; import com.haxtastic.haxmasher.entity.masher.Player; public class MasherHUD extends Hud { public Actor hpslice; public float bars, prevbars; private float space = 1.5f; private float statsX; private float statsY; public float dmg = 1; public String type; public Masher masher; public MasherHUD(Masher mash) { super("hpframe"); hpslice = new Actor("hpbar"); masher = mash; if(mash.getClass().equals(Player.class)) { x = Constants.Positions.playerHPBarX; y = Constants.Positions.playerHPBarY; hpslice.x = Constants.Positions.playerHPBarX+(3.01f/Constants.PIXELS_PER_METER_X); hpslice.y = Constants.Positions.playerHPBarY+(3f/Constants.PIXELS_PER_METER_Y); statsX = Constants.Positions.playerStatsX*Constants.PIXELS_PER_METER_X; statsY = Constants.Positions.playerStatsY*Constants.PIXELS_PER_METER_Y; } else if(mash.getClass().equals(Guy.class)) { x = Constants.Positions.enemyHPBarX; y = Constants.Positions.enemyHPBarY; hpslice.x = Constants.Positions.enemyHPBarX+(3.01f/Constants.PIXELS_PER_METER_X); hpslice.y = Constants.Positions.enemyHPBarY+(3f/Constants.PIXELS_PER_METER_Y); statsX = Constants.Positions.enemyStatsX*Constants.PIXELS_PER_METER_X; statsY = Constants.Positions.enemyStatsY*Constants.PIXELS_PER_METER_Y; } width = Constants.Sizes.hpbarX; height = Constants.Sizes.hpbarY; hpslice.width = Constants.Sizes.hpsliceX; hpslice.height = Constants.Sizes.hpsliceY; prevbars = bars = 1f; } @Override public void act(float dt) { bars = (float)masher.curhealth/(float)masher.maxhealth; prevbars = (float)masher.health/(float)masher.maxhealth; } @Override public void draw(SpriteBatch batch, BitmapFont font) { //Draw hpframe AtlasRegion spriteRegion = Art.regions.get(name); if(width == 0) width = spriteRegion.getRegionWidth(); if(height == 0) height = spriteRegion.getRegionHeight(); if(width < 0) width = -width; float posX = x * Constants.PIXELS_PER_METER_X; float posY = y * Constants.PIXELS_PER_METER_Y; batch.draw(spriteRegion, posX, posY, width * Constants.PIXELS_PER_METER_X, height * Constants.PIXELS_PER_METER_Y); //Draw health spriteRegion = Art.regions.get(hpslice.name); if(hpslice.width == 0) hpslice.width = spriteRegion.getRegionWidth(); if(hpslice.height == 0) hpslice.height = spriteRegion.getRegionHeight(); if(hpslice.width < 0) hpslice.width = -hpslice.width; /*for(float i = 0; i < bars*100; i++) { posX = (bar.x + (0.04f*i)) * Constants.PIXELS_PER_METER_X; posY = bar.y * Constants.PIXELS_PER_METER_Y; batch.draw(spriteRegion, posX, posY, bar.width * Constants.PIXELS_PER_METER_X, bar.height * Constants.PIXELS_PER_METER_Y); }*/ posX = hpslice.x * Constants.PIXELS_PER_METER_X; posY = hpslice.y * Constants.PIXELS_PER_METER_Y; float tempwidth = hpslice.width*(prevbars*100); batch.draw(spriteRegion, posX, posY, tempwidth * Constants.PIXELS_PER_METER_X, hpslice.height * Constants.PIXELS_PER_METER_Y); //Draw text font.setColor(0, 0, 0, 1); String msg = (int)masher.health + "/" + (int)masher.maxhealth; posX = (x+(width/2))*Constants.PIXELS_PER_METER_X - (font.getBounds(msg).width/2); posY = (y+(height/2))*Constants.PIXELS_PER_METER_Y + (font.getBounds(msg).height/2); font.draw(batch, msg, posX, posY); posX = statsX; posY = statsY; msg = "Name: " + masher.nick; font.draw(batch, msg, posX, posY); posY-=(font.getBounds(msg).height*space); msg = "Level: " + masher.level; font.draw(batch, msg, posX, posY); msg = "Armor: " + (int)masher.armor + "(" + (int)((masher.armor/(Constants.Stats.armorReduction+masher.armor))*100) + "%)"; posY-=(font.getBounds(msg).height*space); font.draw(batch, msg, posX, posY); msg = "Damage: " + (int)(masher.getDamage()*Constants.Stats.minDamage) + " - " + (int)(masher.getDamage()*Constants.Stats.maxDamage) + "(" + masher.crit + "%)"; posY-=(font.getBounds(msg).height*space); font.draw(batch, msg, posX, posY); if(masher.getClass().equals(Player.class)) { int exp = masher.getExp(); int nxp = masher.expForLevel(masher.getLevel()+1); msg = "exp: " + exp + "/" + nxp + " (" + (nxp-exp) + " left)"; posY-=(font.getBounds(msg).height*space); font.draw(batch, msg, posX, posY); } else if(masher.getClass().equals(Guy.class)) { msg = "experience worth: " + masher.getExp(); posY-=(font.getBounds(msg).height*space); font.draw(batch, msg, posX, posY); } //font.setScale(1f, 1f); } /* public void drawPlayer() { } public void drawMasher() { //Draw text font.setColor(0, 0, 0, 1); String msg = (int)player.health + "/" + (int)player.maxhealth; posX = (x+(width/2))*Constants.PIXELS_PER_METER_X - (font.getBounds(msg).width/2); posY = (y+(height/2))*Constants.PIXELS_PER_METER_Y + (font.getBounds(msg).height/2); font.draw(batch, msg, posX, posY); posX = statsX; posY = statsY; msg = "Name: " + player.nick; font.draw(batch, msg, posX, posY); posY-=(font.getBounds(msg).height+space); if(type == "player") msg = "Level: " + PlayerStats.getLevel(); else msg = "Level: " + player.level; font.draw(batch, msg, posX, posY); msg = "Armor: " + (int)player.armor + "(" + (int)((player.armor/(Constants.Stats.armorReduction+player.armor))*100) + "%)"; posY-=(font.getBounds(msg).height+space); font.draw(batch, msg, posX, posY); msg = "Damage: " + (int)(player.getDamage()*Constants.Stats.minDamage) + " - " + (int)(player.getDamage()*Constants.Stats.maxDamage); posY-=(font.getBounds(msg).height+space); font.draw(batch, msg, posX, posY); }*/ }
39.605882
163
0.694193
241223353af1f41b392b6798fe8347a7a7c37dc8
1,897
package bamboo.crawl; import bamboo.core.Fixtures; import bamboo.util.Pager; import org.junit.ClassRule; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; public class CrawlsTest { @ClassRule public static Fixtures fixtures = new Fixtures(); @Rule public TemporaryFolder tmp = new TemporaryFolder(); @Test public void testCRUD() throws IOException { Serieses serieses = new Serieses(fixtures.dao.serieses()); Crawls crawls = new Crawls(fixtures.dao.crawls(), serieses, new Warcs(fixtures.dao.warcs()), null); Series series = new Series(); series.setName("test series"); series.setPath(Paths.get("/tmp/test")); long seriesId = serieses.create(series); Crawl crawlMD = new Crawl(); crawlMD.setCrawlSeriesId(seriesId); crawlMD.setName("balloon"); crawlMD.setPandasInstanceId(48L); List<Path> warcs = Arrays.asList( tmp.newFile("test.warc.gz").toPath(), tmp.newFile("test2.warc.gz").toPath()); long id = crawls.createInPlace(crawlMD, warcs); { Crawl crawl = crawls.get(id); assertEquals("balloon", crawl.getName()); assertEquals(48L, crawl.getPandasInstanceId().longValue()); assertEquals(seriesId, crawl.getCrawlSeriesId().longValue()); } crawls.update(id, "bubble", null); { Crawl crawl = crawls.get(id); assertEquals("bubble", crawl.getName()); } Pager pager = crawls.pager(1); assertTrue(pager.totalItems > 0); crawls.stats(id); } }
27.492754
107
0.639958
52c6c4284210e8eab6a5928fc599df64bb3aac19
3,597
package be.glever.antplus.speedcadence; import be.glever.ant.AntException; import be.glever.ant.channel.AntChannel; import be.glever.ant.constants.AntPlusDeviceType; import be.glever.ant.message.channel.ChannelEventOrResponseMessage; import be.glever.ant.message.channel.ChannelEventResponseCode; import be.glever.ant.message.configuration.*; import be.glever.ant.message.control.OpenChannelMessage; import be.glever.ant.usb.AntUsbDevice; import be.glever.ant.util.ByteUtils; import java.util.concurrent.ExecutionException; public class CadenceSlave { private static final byte ANTPLUS_SPEED_CADENCE_FREQUENCY = (byte) 57; // 2457Mhz private AntUsbDevice antUsbDevice; public CadenceSlave(AntUsbDevice antUsbDevice) { this.antUsbDevice = antUsbDevice; } public AntChannel[] listDevices() throws AntException, ExecutionException, InterruptedException { SpeedChannel channel = new SpeedChannel(antUsbDevice); byte channelNumber = 0x00; // ASSIGN CHANNEL NetworkKeyMessage networkKeyMessage = new NetworkKeyMessage(channelNumber, channel.getNetwork().getNetworkKey()); ChannelEventOrResponseMessage setNetworkKeyResponse = (ChannelEventOrResponseMessage) antUsbDevice.sendBlocking(networkKeyMessage); if (setNetworkKeyResponse.getResponseCode() != ChannelEventResponseCode.RESPONSE_NO_ERROR) { throw new RuntimeException("Could not set network key"); } AssignChannelMessage assignChannelMessage = new AssignChannelMessage(channelNumber, (byte) 0x40, (byte) 0x00); ChannelEventOrResponseMessage response = (ChannelEventOrResponseMessage) antUsbDevice.sendBlocking(assignChannelMessage); if (response.getResponseCode() != ChannelEventResponseCode.RESPONSE_NO_ERROR) { throw new RuntimeException("Could not assign channel"); } ChannelIdMessage channelIdMessage = new ChannelIdMessage(channelNumber, new byte[]{0x00, 0x00}, AntPlusDeviceType.HRM.value(), (byte) 0x00); ChannelEventOrResponseMessage channelIdResponse = (ChannelEventOrResponseMessage) antUsbDevice.sendBlocking(channelIdMessage); if (channelIdResponse.getResponseCode() != ChannelEventResponseCode.RESPONSE_NO_ERROR) { throw new RuntimeException("Could set channelId"); } ChannelPeriodMessage channelPeriodMessage = new ChannelPeriodMessage(channelNumber, CadenceChannel.CHANNEL_PERIOD); ChannelEventOrResponseMessage channelPeriodResponseMessage = (ChannelEventOrResponseMessage) antUsbDevice.sendBlocking(channelPeriodMessage); if (channelPeriodResponseMessage.getResponseCode() != ChannelEventResponseCode.RESPONSE_NO_ERROR) { throw new RuntimeException("Could set channel period"); } ChannelRfFrequencyMessage channelRfFrequencyMessage = new ChannelRfFrequencyMessage(channelNumber, (byte) 0x39); ChannelEventOrResponseMessage channelRfFrequencyResponse = (ChannelEventOrResponseMessage) antUsbDevice.sendBlocking(channelRfFrequencyMessage); if (channelRfFrequencyResponse.getResponseCode() != ChannelEventResponseCode.RESPONSE_NO_ERROR) { throw new RuntimeException("Could not set rf frequency"); } response = (ChannelEventOrResponseMessage) antUsbDevice.sendBlocking(new OpenChannelMessage(response.getChannelNumber())); if (response.getResponseCode() != ChannelEventResponseCode.RESPONSE_NO_ERROR) { throw new RuntimeException("Could not open channel"); } // OPEN CHANNEL return null; } }
52.130435
152
0.76675
fca1b366410942aa86f8aa73966d89ca86a238e3
371
package com.mgilangjanuar.dev.goscele.base; import com.activeandroid.Model; import com.activeandroid.query.From; import com.activeandroid.query.Select; /** * Created by mgilangjanuar ([email protected]) * * @since 2017 */ public class BaseModel extends Model { public From find() { return new Select() .from(getClass()); } }
18.55
53
0.681941
13597ce5d3ad3734f30837d74eca1845f6b7f0a6
2,099
/* * Copyright 2015-2017 Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags. * * 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.hawkular.agent.helloworld; import java.io.IOException; import java.io.PrintWriter; import javax.inject.Inject; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet(value = "/HelloWorld", loadOnStartup = 1) public class HelloWorldServlet extends HttpServlet { private static final long serialVersionUID = 1L; @Inject private SimpleMXBeanImpl mbean; @Override public void init(ServletConfig config) throws ServletException { super.init(config); mbean.setTestInteger(0); log("Test MBean has been registered: " + SimpleMXBeanImpl.OBJECT_NAME); } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Integer num = Integer.valueOf(mbean.getTestInteger().intValue() + 1); mbean.setTestInteger(num); resp.setContentType("text/html"); PrintWriter writer = resp.getWriter(); writer.println("<html><head><title>helloworld</title></head><body><h1>"); writer.println(mbean.getTestString()); writer.println(" #"); writer.println(num); writer.println("</h1></body></html>"); writer.close(); } }
35.576271
113
0.722249
eb5f3666115fadb5bab9970a09bdeda4d4c383c6
30,807
// $Id: LogQueueActivityExt.java,v 1.3 2009/12/14 21:48:22 jim Exp $ package us.temerity.pipeline.plugin.LogQueueActivityExt.v2_1_1; import java.io.*; import java.text.*; import java.util.*; import us.temerity.pipeline.*; /*------------------------------------------------------------------------------------------*/ /* L O G Q U E U E A C T I V I T Y E X T */ /*------------------------------------------------------------------------------------------*/ /** * A simple test extension which prints a message for each extendable queue operation. */ public class LogQueueActivityExt extends BaseQueueExt { /*----------------------------------------------------------------------------------------*/ /* C O N S T R U C T O R */ /*----------------------------------------------------------------------------------------*/ public LogQueueActivityExt() { super("LogQueueActivity", new VersionID("2.1.1"), "Temerity", "A simple test extension which prints a message for each extendable queue " + "operation."); /* plugin ops */ { { ExtensionParam param = new IntegerExtensionParam (aEnableDelay, "The length of time in milliseconds to delay enable.", 10000); addParam(param); } { ExtensionParam param = new IntegerExtensionParam (aDisableDelay, "The length of time in milliseconds to delay disable.", 10000); addParam(param); } } /* server ops */ { { ExtensionParam param = new BooleanExtensionParam (aLogSubmitJobs, "Enable logging of the submission of new jobs.", true); addParam(param); } { ExtensionParam param = new BooleanExtensionParam (aAllowDeleteJobGroup, "Whether to allow deletion of job groups.", true); addParam(param); } { ExtensionParam param = new BooleanExtensionParam (aLogDeleteJobGroup, "Enable logging of deletion of job groups.", true); addParam(param); } { ExtensionParam param = new BooleanExtensionParam (aLogCleanupJobs, "Enable logging of the cleanup of obsolete jobs.", true); addParam(param); } { ExtensionParam param = new BooleanExtensionParam (aAllowAddHost, "Whether to allow new job server hosts to be added.", true); addParam(param); } { ExtensionParam param = new BooleanExtensionParam (aLogAddHost, "Enable logging of the addition of new job server hosts.", true); addParam(param); } { ExtensionParam param = new BooleanExtensionParam (aAllowRemoveHosts, "Whether to allow the removal of existing job server hosts.", true); addParam(param); } { ExtensionParam param = new BooleanExtensionParam (aLogRemoveHosts, "Enable logging of the removal of existing job server hosts.", true); addParam(param); } { ExtensionParam param = new BooleanExtensionParam (aLogModifyHosts, "Enable logging of changes in host status or properties.", true); addParam(param); } { ExtensionParam param = new BooleanExtensionParam (aLogResourceSamples, "Enable logging of dynamic resource sample writes to disk.", true); addParam(param); } } /* dispatcher ops */ { { ExtensionParam param = new BooleanExtensionParam (aLogJobAbort, "Enable logging of job aborts.", true); addParam(param); } { ExtensionParam param = new BooleanExtensionParam (aLogJobBalk, "Enable logging of job balks.", true); addParam(param); } { ExtensionParam param = new BooleanExtensionParam (aLogJobStart, "Enable logging of job startup.", true); addParam(param); } { ExtensionParam param = new BooleanExtensionParam (aLogJobPreempt, "Enable logging of job preemption.", true); addParam(param); } { ExtensionParam param = new BooleanExtensionParam (aLogJobFinish, "Enable logging of job completion.", true); addParam(param); } } { LayoutGroup layout = new LayoutGroup(true); { LayoutGroup sub = new LayoutGroup ("PluginOps", "Plugin initialization and shutdown operations.", true); sub.addEntry(aEnableDelay); sub.addEntry(aDisableDelay); layout.addSubGroup(sub); } { LayoutGroup sub = new LayoutGroup ("ServerOps", "General queue mananger server operations.", true); sub.addEntry(aLogSubmitJobs); sub.addSeparator(); sub.addEntry(aAllowDeleteJobGroup); sub.addEntry(aLogDeleteJobGroup); sub.addSeparator(); sub.addEntry(aLogCleanupJobs); sub.addSeparator(); sub.addEntry(aAllowAddHost); sub.addEntry(aLogAddHost); sub.addSeparator(); sub.addEntry(aAllowRemoveHosts); sub.addEntry(aLogRemoveHosts); sub.addSeparator(); sub.addEntry(aLogModifyHosts); sub.addEntry(aLogResourceSamples); layout.addSubGroup(sub); } { LayoutGroup sub = new LayoutGroup ("DispatcherOps", "Job dispatcher operations.", true); sub.addEntry(aLogJobAbort); sub.addEntry(aLogJobBalk); sub.addEntry(aLogJobStart); sub.addEntry(aLogJobPreempt); sub.addEntry(aLogJobFinish); layout.addSubGroup(sub); } setLayout(layout); } } /*----------------------------------------------------------------------------------------*/ /* P L U G I N O P S */ /*----------------------------------------------------------------------------------------*/ /** * Whether to run a task after this extension plugin is first enabled.<P> * * A extension plugin can be enabled either during server initialization or during normal * server operation when this specific plugin is enabled manually. */ public boolean hasPostEnableTask() { return true; } /** * The task to perform after this extension plugin is first enabled.<P> * * A extension plugin can be enabled either during server initialization or during normal * server operation when this specific plugin is enabled manually. */ public void postEnableTask() { /* just to prove that the server is waiting on this task to finish... */ try { Integer delay = (Integer) getParamValue(aEnableDelay); if((delay != null) && (delay > 0)) { LogMgr.getInstance().logAndFlush (LogMgr.Kind.Ext, LogMgr.Level.Info, "LogQueueActivity Enabling - " + "Please Wait (" + delay + ") milliseconds..."); Thread.sleep(delay); } } catch(Exception ex) { LogMgr.getInstance().log (LogMgr.Kind.Ext, LogMgr.Level.Warning, ex.getMessage()); } LogMgr.getInstance().log (LogMgr.Kind.Ext, LogMgr.Level.Info, "LogQueueActivity Enabled!"); } /*----------------------------------------------------------------------------------------*/ /** * Whether to run a task after this extension plugin is disabled.<P> * * A extension plugin can be disabled either during server shutdown or during normal * server operation when this specific plugin is disabled or removed manually. */ public boolean hasPreDisableTask() { return true; } /** * The task to perform after this extension plugin is disabled.<P> * * A extension plugin can be disabled either during server shutdown or during normal * server operation when this specific plugin is disabled or removed manually. */ public void preDisableTask() { /* just to prove that the server is waiting on this task to finish... */ try { Integer delay = (Integer) getParamValue(aDisableDelay); if((delay != null) && (delay > 0)) { LogMgr.getInstance().logAndFlush (LogMgr.Kind.Ext, LogMgr.Level.Info, "LogQueueActivity Disabling - " + "Please Wait (" + delay + ") milliseconds..."); Thread.sleep(delay); } } catch(Exception ex) { LogMgr.getInstance().log (LogMgr.Kind.Ext, LogMgr.Level.Warning, ex.getMessage()); } LogMgr.getInstance().log (LogMgr.Kind.Ext, LogMgr.Level.Info, "LogQueueActivity Disabled!"); } /*----------------------------------------------------------------------------------------*/ /* S E R V E R O P S */ /*----------------------------------------------------------------------------------------*/ /** * Whether to run a task after new jobs are submitted to the queue. */ public boolean hasPostSubmitJobsTask() { return isParamTrue(aLogSubmitJobs); } /** * The task to perform after new jobs are submitted to the queue. * * @param group * The queue job group. * * @param jobs * The submitted jobs indexed by job ID. * * @throws PipelineException * If unable to perform the task. */ public void postSubmitJobsTask ( QueueJobGroup group, TreeMap<Long,QueueJob> jobs ) { StringBuilder buf = new StringBuilder(); { NodeID nodeID = group.getNodeID(); buf.append ("Job Group " + group.getGroupID() + " - SUBMITTED\n" + " Owner : " + nodeID.getAuthor() + "|" + nodeID.getView() + "\n" + " Node : " + nodeID.getName() + "\n" + " Target : " + group.getRootSequence()); } for(Long jobID : jobs.keySet()) { QueueJob job = jobs.get(jobID); NodeID nodeID = job.getNodeID(); buf.append ("\n" + "Job " + job.getJobID() + " - SUBMITTED\n" + " Owner : " + nodeID.getAuthor() + "|" + nodeID.getView() + "\n" + " Node : " + nodeID.getName() + "\n" + " Target : " + job.getActionAgenda().getPrimaryTarget()); } LogMgr.getInstance().log (LogMgr.Kind.Ext, LogMgr.Level.Info, buf.toString()); } /*----------------------------------------------------------------------------------------*/ /** * Whether to test before a completed job group has been marked for removal. */ public boolean hasPreDeleteJobGroupTest() { return true; } /** * Test to perform before a completed job group has been marked for removal. * * @param user * The name of the user attempting to delete the job group. * * @param distribution * Get the percentage of jobs in the group associated with a given JobState. * * @param group * The completed job group. * * @throws PipelineException * To abort the operation. */ public void preDeleteJobGroupTest ( String user, TreeMap<JobState,Double> distribution, QueueJobGroup group ) throws PipelineException { Boolean tf = (Boolean) getParamValue(aAllowDeleteJobGroup); if((tf == null) || !tf) throw new PipelineException ("Deleting job groups is not allowed!"); } /*----------------------------------------------------------------------------------------*/ /** * Whether to run a task after a completed job group has been marked for removal. */ public boolean hasPostDeleteJobGroupTask() { return isParamTrue(aLogDeleteJobGroup); } /** * The task to perform after a completed job group has been marked for removal. * * @param group * The completed job group. */ public void postDeleteJobGroupTask ( QueueJobGroup group ) { NodeID nodeID = group.getNodeID(); String msg = ("Job Group " + group.getGroupID() + " - DELETED\n" + " Owner : " + nodeID.getAuthor() + "|" + nodeID.getView() + "\n" + " Node : " + nodeID.getName() + "\n" + " Target : " + group.getRootSequence() + "\n" + " Started : " + TimeStamps.format(group.getSubmittedStamp()) + "\n" + " Finished : " + TimeStamps.format(group.getCompletedStamp()) + "\n" + " Duration : " + TimeStamps.formatInterval(group.getCompletedStamp() - group.getSubmittedStamp())); LogMgr.getInstance().log (LogMgr.Kind.Ext, LogMgr.Level.Info, msg); } /*----------------------------------------------------------------------------------------*/ /** * Whether to run a task after the job garbage collector has cleaned-up jobs no longer * referenced by any remaining job group.<P> * * This is a good way to collect long term information about all jobs while having a * very low impact on the queue manager. All jobs are eventually cleaned up so this will * provide the same information as the {@link #postJobFinishedTask}, but operates * on large batches of jobs instead of after each individual job. */ public boolean hasPostCleanupJobsTask() { return isParamTrue(aLogCleanupJobs); } /** * The task to perform after the job garbage collector has cleaned-up jobs no longer * referenced by any remaining job group.<P> * * This is a good way to collect long term information about all jobs while having a * very low impact on the queue manager. All jobs are eventually cleaned up so this will * provide the same information as the {@link #postJobFinishedTask}, but operates * on large batches of jobs instead of after each individual job. * * @param jobs * The completed jobs indexed by job ID. * * @param infos * Information about when and where the job was executed indexed by job ID. */ public void postCleanupJobsTask ( TreeMap<Long,QueueJob> jobs, TreeMap<Long,QueueJobInfo> infos ) { LogMgr.getInstance().log (LogMgr.Kind.Ext, LogMgr.Level.Info, "Cleaning Up (" + jobs.size() + ") Jobs..."); for(Long jobID : jobs.keySet()) postJobFinishedTask(jobs.get(jobID), infos.get(jobID)); } /*----------------------------------------------------------------------------------------*/ /** * Whether to test before adding a new job server host. */ public boolean hasPreAddHostTest() { return true; } /** * Test to perform before adding a new job server host. * * @param hostname * The fully resolved name of the host. * * @throws PipelineException * To abort the operation. */ public void preAddHostTest ( String hostname ) throws PipelineException { Boolean tf = (Boolean) getParamValue(aAllowAddHost); if((tf == null) || !tf) throw new PipelineException ("Adding the job server (" + hostname + ") is not allowed!"); } /** * Whether to run a task after adding a new job server host. */ public boolean hasPostAddHostTask() { return isParamTrue(aLogAddHost); } /** * The task to perform after adding a new job server host. * * @param hostname * The fully resolved name of the host. */ public void postAddHostTask ( String hostname ) { LogMgr.getInstance().log (LogMgr.Kind.Ext, LogMgr.Level.Info, "Job Server [" + hostname + "] - ADDED"); } /*----------------------------------------------------------------------------------------*/ /** * Whether to test before removing some existing job server hosts. */ public boolean hasPreRemoveHostsTest() { return true; } /** * Test to perform before removing some existing job server hosts. * * @param hostnames * The fully resolved names of the hosts. * * @throws PipelineException * To abort the operation. */ public void preRemoveHostsTest ( TreeSet<String> hostnames ) throws PipelineException { Boolean tf = (Boolean) getParamValue(aAllowRemoveHosts); if((tf == null) || !tf) throw new PipelineException ("Removing job servers is not allowed!"); } /** * Whether to run a task after removing some existing job server hosts. */ public boolean hasPostRemoveHostsTask() { return isParamTrue(aLogRemoveHosts); } /** * The task to perform after removing some existing job server hosts. * * @param hostnames * The fully resolved names of the hosts. */ public void postRemoveHostsTask ( TreeSet<String> hostnames ) { StringBuilder buf = new StringBuilder(); for(String hname : hostnames) buf.append("Job Server [" + hname + "] - REMOVED"); LogMgr.getInstance().log (LogMgr.Kind.Ext, LogMgr.Level.Info, buf.toString()); } /*----------------------------------------------------------------------------------------*/ /** * Whether to run a task after modifying host status or properties. */ public boolean hasPostModifyHostsTask() { return isParamTrue(aLogModifyHosts); } /** * The task to perform after modifying host status or properties.<P> * * A host may be modified either manually by users or automatically by the queue * manager itself. Automatic modifications include marking unresponsive servers as * Limbo (or Disabled), re-Enabling servers which start responding again and changes * to the Selection Group caused by a Selection Schedule. <P> * * The modified host information will not include any dynamic resource information such * as the available memory, disk or system load. This information can be obtained using * the {@link #postResourceSamplesTask} instead. * * @param hosts * The information about the modified hosts indexed by fully resolved hostname. */ public void postModifyHostsTask ( TreeMap<String,QueueHostInfo> hosts ) { StringBuilder buf = new StringBuilder(); boolean first = true; for(String hname : hosts.keySet()) { QueueHostInfo info = hosts.get(hname); OsType os = info.getOsType(); String res = info.getReservation(); Integer procs = info.getNumProcessors(); Long mem = info.getTotalMemory(); Long disk = info.getTotalDisk(); String sched = info.getSelectionSchedule(); String group = info.getSelectionGroup(); if(!first) buf.append("\n"); first = false; buf.append ("Job Server [" + hname + "] - MODIFIED\n" + " Status : " + info.getStatus() + "\n" + " OS Type : " + ((os != null) ? os : "-") + "\n" + " Num Procs : " + ((procs != null) ? procs.toString() : "-") + "\n" + " Total Memory : " + ((mem != null) ? mem : "-") + "\n" + " Total Disk : " + ((disk != null) ? disk : "-") + "\n" + " Job Slots : " + info.getJobSlots() + "\n" + " Order : " + info.getOrder() + "\n" + " Reservation : " + ((res != null) ? res : "-") + "\n" + " Group : " + ((group != null) ? group : "-") + "\n" + " Schedule : " + ((sched != null) ? sched : "-")); } LogMgr.getInstance().log (LogMgr.Kind.Ext, LogMgr.Level.Info, buf.toString()); } /*----------------------------------------------------------------------------------------*/ /** * Whether to run a task after writing job server dynamic resource samples to disk. */ public boolean hasPostResourceSamplesTask() { return isParamTrue(aLogResourceSamples); } /** * The task to perform after writing job server dynamic resource samples to disk.<P> * * The queue manager periodically writes a block of resource samples it has been caching * to disk to free up memory. This method is invoked whenever the samples are saved. * The default configuration is to write 1-minute averaged values at 30-minute intervals. * * @param samples * The dynamic resource samples indexed by fully resolved hostname. */ public void postResourceSamplesTask ( TreeMap<String,ResourceSampleCache> samples ) { DecimalFormat fmt = new DecimalFormat("###0.0"); StringBuilder buf = new StringBuilder(); boolean first = true; for(String hname : samples.keySet()) { if(!first) buf.append("\n"); first = false; buf.append("Job Server [" + hname + "] - RESOURCE SAMPLES\n"); ResourceSampleCache cache = samples.get(hname); int numSamples = cache.getNumSamples(); if(numSamples > 0) { int minJobs = Integer.MAX_VALUE; int maxJobs = 0; float minLoad = Float.MAX_VALUE; float maxLoad = 0.0f; long minMem = Long.MAX_VALUE; long maxMem = 0L; long minDisk = Long.MAX_VALUE; long maxDisk = 0L; int wk; for(wk=0; wk<numSamples; wk++) { int jobs = cache.getNumJobs(wk); minJobs = Math.min(minJobs, jobs); maxJobs = Math.max(maxJobs, jobs); float load = cache.getLoad(wk); minLoad = Math.min(minLoad, load); maxLoad = Math.max(maxLoad, load); long mem = cache.getMemory(wk); minMem = Math.min(minMem, mem); maxMem = Math.max(maxMem, mem); long disk = cache.getDisk(wk); minDisk = Math.min(minDisk, disk); maxDisk = Math.max(maxDisk, disk); } buf.append (" Started : " + TimeStamps.format(cache.getFirstTimeStamp()) + "\n" + " Ended : " + TimeStamps.format(cache.getLastTimeStamp()) + "\n" + " Num Samples : " + numSamples); if(numSamples > 0) { buf.append ("\n" + " Num Jobs : " + minJobs + " / " + maxJobs + " (min/max)\n" + " System Load : " + minLoad + " / " + maxLoad + " (min/max)\n" + " Free Memory : " + minMem + " / " + maxMem + " (min/max)\n" + " Free Disk : " + minDisk + " / " + maxDisk + " (min/max)"); } } } LogMgr.getInstance().log (LogMgr.Kind.Ext, LogMgr.Level.Info, buf.toString()); } /*----------------------------------------------------------------------------------------*/ /* D I S P A T C H E R O P S */ /*----------------------------------------------------------------------------------------*/ /** * Whether to run a task if job has been aborted (cancelled).<P> * * Jobs which where already running when aborted will also invoke the post-finish task. * If a job is aborted before it began execution, then only this method will be called. */ public boolean hasPostJobAbortedTask() { return isParamTrue(aLogJobAbort); } /** * The task to perform if job has been aborted (cancelled).<P> * * Jobs which where already running when aborted will also invoke the post-finish task. * If a job is aborted before it began execution, then only this method will be called. * * @param job * The job specification. */ public void postJobAbortedTask ( QueueJob job ) { NodeID nodeID = job.getNodeID(); String msg = ("Job " + job.getJobID() + " - ABORTED\n" + " Owner : " + nodeID.getAuthor() + "|" + nodeID.getView() + "\n" + " Node : " + nodeID.getName() + "\n" + " Target : " + job.getActionAgenda().getPrimaryTarget()); LogMgr.getInstance().log (LogMgr.Kind.Ext, LogMgr.Level.Info, msg); } /*----------------------------------------------------------------------------------------*/ /** * Whether to run a task if a job is unable to start (balked). <P> * * A job is considered to be balked if the particular job manager assigned to the job is * unable to be contacted by the queue manager in a timely manner. The job will be * automatically requeued after a balk similar to how a preempted job is handled. */ public boolean hasPostJobBalkedTask() { return isParamTrue(aLogJobBalk); } /** * The task to perform if a job is unable to start (balked). <P> * * A job is considered to be balked if the particular job manager assigned to the job is * unable to be contacted by the queue manager in a timely manner (Limbo). The job will be * automatically requeued after a balk similar to how a preempted job is handled. * * @param job * The job specification. * * @param hostname * The name of the host running the unresponsive job manager. */ public void postJobBalkedTask ( QueueJob job, String hostname ) { NodeID nodeID = job.getNodeID(); String msg = ("Job " + job.getJobID() + " - BALKED on [" + hostname + "]\n" + " Owner : " + nodeID.getAuthor() + "|" + nodeID.getView() + "\n" + " Node : " + nodeID.getName() + "\n" + " Target : " + job.getActionAgenda().getPrimaryTarget()); LogMgr.getInstance().log (LogMgr.Kind.Ext, LogMgr.Level.Info, msg); } /*----------------------------------------------------------------------------------------*/ /** * Whether to run a task after a job starts running. */ public boolean hasPostJobStartedTask() { return isParamTrue(aLogJobStart); } /** * The task to perform after a job starts running. * * @param job * The job specification. * * @param info * Information about when and where the job was started. */ public void postJobStartedTask ( QueueJob job, QueueJobInfo info ) { NodeID nodeID = job.getNodeID(); String msg = ("Job " + job.getJobID() + " - STARTED on [" + info.getHostname() + "] at " + TimeStamps.format(info.getStartedStamp()) + "\n" + " Owner : " + nodeID.getAuthor() + "|" + nodeID.getView() + "\n" + " Node : " + nodeID.getName() + "\n" + " Target : " + job.getActionAgenda().getPrimaryTarget()); LogMgr.getInstance().log (LogMgr.Kind.Ext, LogMgr.Level.Info, msg); } /*----------------------------------------------------------------------------------------*/ /** * Whether to run a task after a job finishes running. */ public boolean hasPostJobFinishedTask() { return isParamTrue(aLogJobFinish); } /** * The task to perform after a job finishes running. * * @param job * The job specification. * * @param info * Information about when and where the job was executed. */ public void postJobFinishedTask ( QueueJob job, QueueJobInfo info ) { StringBuilder buf = new StringBuilder(); buf.append ("Job " + job.getJobID() + " - "); QueueJobResults results = info.getResults(); if(results == null) { buf.append("NEVER EXECUTED"); } else { Integer code = results.getExitCode(); if(code != null) { if(code == 0) buf.append("SUCCEEDED"); else buf.append("FAILED [" + code + "]"); } Long started = info.getStartedStamp(); Long completed = info.getCompletedStamp(); if((started != null) && (completed != null)) { buf.append (" at " + TimeStamps.format(completed) + " [" + TimeStamps.formatInterval(completed - started) + "]"); } } NodeID nodeID = job.getNodeID(); buf.append ("\n" + " Owner : " + nodeID.getAuthor() + "|" + nodeID.getView() + "\n" + " Node : " + nodeID.getName() + "\n" + " Target : " + job.getActionAgenda().getPrimaryTarget()); LogMgr.getInstance().log (LogMgr.Kind.Ext, LogMgr.Level.Info, buf.toString()); } /*----------------------------------------------------------------------------------------*/ /** * Whether to run a task after a */ public boolean hasPostJobPreemptedTask() { return isParamTrue(aLogJobPreempt); } /** * The task to perform after a job is manually preempted. * * @param job * The job specification. * * @param info * Information about when and where the job was run prior to preemption. */ public void postJobPreemptedTask ( QueueJob job, QueueJobInfo info ) { NodeID nodeID = job.getNodeID(); long now = System.currentTimeMillis(); String msg = ("Job " + job.getJobID() + " - Preempted on [" + info.getHostname() + "] at " + TimeStamps.format(now) + "\n" + " Owner : " + nodeID.getAuthor() + "|" + nodeID.getView() + "\n" + " Node : " + nodeID.getName() + "\n" + " Target : " + job.getActionAgenda().getPrimaryTarget() + "\n" + " Runtime : " + TimeStamps.formatInterval(now - info.getStartedStamp())); LogMgr.getInstance().log (LogMgr.Kind.Ext, LogMgr.Level.Info, msg); } /*----------------------------------------------------------------------------------------*/ /* H E L P E R S */ /*----------------------------------------------------------------------------------------*/ /** * Whether the given boolean extension parameter is currently true. */ private boolean isParamTrue ( String pname ) { try { Boolean tf = (Boolean) getParamValue(pname); return ((tf != null) && tf); } catch(PipelineException ex) { LogMgr.getInstance().log (LogMgr.Kind.Ext, LogMgr.Level.Warning, ex.getMessage()); return false; } } /*----------------------------------------------------------------------------------------*/ /* S T A T I C I N T E R N A L S */ /*----------------------------------------------------------------------------------------*/ private static final long serialVersionUID = -6639988244348742755L; private static final String aEnableDelay = "EnableDelay"; private static final String aDisableDelay = "DisableDelay"; private static final String aLogSubmitJobs = "LogSubmitJobs"; private static final String aAllowDeleteJobGroup = "AllowDeleteJobGroup"; private static final String aLogDeleteJobGroup = "LogDeleteJobGroup"; private static final String aLogCleanupJobs = "LogCleanupJobs"; private static final String aAllowAddHost = "AllowAddHost"; private static final String aLogAddHost = "LogAddHost"; private static final String aAllowRemoveHosts = "AllowRemoveHosts"; private static final String aLogRemoveHosts = "LogRemoveHosts"; private static final String aLogModifyHosts = "LogModifyHosts"; private static final String aLogResourceSamples = "LogResourceSamples"; private static final String aLogJobAbort = "LogJobAbort"; private static final String aLogJobBalk = "LogJobBalk"; private static final String aLogJobStart = "LogJobStart"; private static final String aLogJobPreempt = "LogJobPreempt"; private static final String aLogJobFinish = "LogJobFinish"; }
27.238727
94
0.560392
22e863862979c9f4f7184e7a597eb2c762d32484
500
package eu.xenit.contentcloud.opa.client.api; import java.util.HashMap; import java.util.List; import java.util.concurrent.CompletableFuture; import lombok.Data; import lombok.EqualsAndHashCode; public interface QueryApi { <T> CompletableFuture<QueryResponse> query(String query); @Data class QueryResponse { private List<QueryResultEntry> result; } @Data @EqualsAndHashCode(callSuper = true) class QueryResultEntry extends HashMap<String, Object> { } }
20.833333
61
0.738
581fd25cbd56d67314752081b31be7c861f3c1ad
509
package com.github.peacetrue.sample.lock; import java.util.Objects; import java.util.concurrent.locks.Lock; /** * @author : xiayx * @since : 2021-06-01 19:28 **/ //tag::class[] public class LockAdapter implements CustomLock { private final Lock lock; public LockAdapter(Lock lock) { this.lock = Objects.requireNonNull(lock); } @Override public void lock() { lock.lock(); } @Override public void unlock() { lock.unlock(); } } //end::class[]
16.966667
49
0.62279
b2fc0c5ff87e2d58d519e2ca25948aed907bbfb2
1,302
/* Copyright M-Gate Labs 2007 Can be edited with permission only. */ package com.mgatelabs.swftools.support.swf.objects; public class FTexture extends FFill { /* BitmapID If type = 0x40 or 0x41 UI16 ID of bitmap character for fill BitmapMatrix if type = 0x40 or 0x41 MATRIX Matrix for bitmap fill */ // My Varables private int myBitmapID; private FImage myBitmap; private FMatrix myMatrix; // Constructor public FTexture(int style, int bitmapID, FMatrix matrix) { super(style); myBitmapID = bitmapID; myMatrix = matrix; myMatrix.setScaleX(myMatrix.getScaleX() / 20.0f); myMatrix.setScaleY(myMatrix.getScaleY() / 20.0f); myBitmap = null; } // Get my Texture Matrix public FMatrix getMatrix() { return myMatrix; } // Get The ID of My Bitmap public int getBitmapID() { return myBitmapID; } // Set Bitmap public void setBitmap(FImage aBitmap) { myBitmap = aBitmap; } // Get Bitmap public FImage getBitmap() { return myBitmap; } public String toString() { return "Texture: (" + myBitmapID + ") " + myBitmap + " Matrix: " + myMatrix; } }
23.672727
107
0.588326
2ad7b69de9afc41eaf539f29790d50d6af4a9798
3,752
/* * This file is a part of MI * * The MIT License (MIT) * * Copyright (c) 2021 Roj234 * * 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 ilib.client.renderer.mirror; import ilib.ClientProxy; import ilib.ImpLib; import ilib.client.api.ClientChangeWorldEvent; import ilib.client.renderer.mirror.render.PortalRenderer; import ilib.client.renderer.mirror.render.world.RenderGlobalProxy; import net.minecraftforge.client.event.EntityViewRenderEvent; import net.minecraftforge.client.event.PlayerSPPushOutOfBlocksEvent; import net.minecraftforge.client.event.RenderBlockOverlayEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.common.gameevent.TickEvent; import net.minecraftforge.fml.common.network.FMLNetworkEvent; import roj.math.MathUtils; public class ClientEventHandler { public static float prevCameraRoll; public static float cameraRoll; public static RenderGlobalProxy proxy; @SubscribeEvent public static void onCameraSetupEvent(EntityViewRenderEvent.CameraSetup event) { if (cameraRoll != 0F && PortalRenderer.renderLevel <= 0) { event.setRoll(MathUtils.interpolate(prevCameraRoll, cameraRoll, (float) event.getRenderPartialTicks())); } } @SubscribeEvent public static void onRenderBlockOverlay(RenderBlockOverlayEvent event) { if (EventHandler.isInPortal(event.getPlayer())) event.setCanceled(true); } @SubscribeEvent public static void onPushPlayerSPOutOfBlock(PlayerSPPushOutOfBlocksEvent event) { if (EventHandler.isInPortal(event.getEntityPlayer())) event.setCanceled(true); } @SubscribeEvent public static void onChangeWorld(ClientChangeWorldEvent event) { if (proxy == null) { proxy = new RenderGlobalProxy(ClientProxy.mc); proxy.updateDestroyBlockIcons(); } proxy.setWorldAndLoadRenderers(ClientProxy.mc.world); PortalRenderer.renderLevel = 0; PortalRenderer.renderCount = 0; } @SubscribeEvent public static void onClientTick(TickEvent.ClientTickEvent event) { if (event.phase == TickEvent.Phase.END) { prevCameraRoll = cameraRoll; cameraRoll *= 0.85F; if (Math.abs(cameraRoll) < 0.05F) { cameraRoll = 0F; } } } @SubscribeEvent public static void onClientDisconnect(FMLNetworkEvent.ClientDisconnectionFromServerEvent event) { ImpLib.proxy.runAtMainThread(true, () -> { EventHandler.monitoredEntities[0].clear(); PortalRenderer.renderLevel = 0; PortalRenderer.rollFactor.clear(); }); } }
38.680412
116
0.724147
1e45aeb308c1d08bd01d5806722b438548aceb0a
1,026
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.karaf.cellar.core; import org.apache.karaf.cellar.core.control.Switch; import java.io.Serializable; /** * Generic producer interface. */ public interface Producer<T extends Serializable> { /** * Produce an object. * * @param obj the object to produce. */ public void produce(T obj); /** * Get the producer switch. * * @return the producer switch. */ public Switch getSwitch(); }
25.65
75
0.689084
e39c872f1fc13f2812061a211508ef75249c754d
3,110
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.hadoop.utils.db; import java.io.IOException; import org.apache.hadoop.classification.InterfaceStability; /** * Interface for key-value store that stores ozone metadata. Ozone metadata is * stored as key value pairs, both key and value are arbitrary byte arrays. Each * Table Stores a certain kind of keys and values. This allows a DB to have * different kind of tables. */ @InterfaceStability.Evolving public interface Table<KEY, VALUE> extends AutoCloseable { /** * Puts a key-value pair into the store. * * @param key metadata key * @param value metadata value */ void put(KEY key, VALUE value) throws IOException; /** * Puts a key-value pair into the store as part of a bath operation. * * @param batch the batch operation * @param key metadata key * @param value metadata value */ void putWithBatch(BatchOperation batch, KEY key, VALUE value) throws IOException; /** * @return true if the metadata store is empty. * @throws IOException on Failure */ boolean isEmpty() throws IOException; /** * Returns the value mapped to the given key in byte array or returns null * if the key is not found. * * @param key metadata key * @return value in byte array or null if the key is not found. * @throws IOException on Failure */ VALUE get(KEY key) throws IOException; /** * Deletes a key from the metadata store. * * @param key metadata key * @throws IOException on Failure */ void delete(KEY key) throws IOException; /** * Deletes a key from the metadata store as part of a batch operation. * * @param batch the batch operation * @param key metadata key * @throws IOException on Failure */ void deleteWithBatch(BatchOperation batch, KEY key) throws IOException; /** * Returns the iterator for this metadata store. * * @return MetaStoreIterator */ TableIterator<KEY, ? extends KeyValue<KEY, VALUE>> iterator(); /** * Returns the Name of this Table. * @return - Table Name. * @throws IOException on failure. */ String getName() throws IOException; /** * Class used to represent the key and value pair of a db entry. */ interface KeyValue<KEY, VALUE> { KEY getKey(); VALUE getValue(); } }
28.272727
80
0.698714
fb6e0230dfe3c9cc64dfd03d8bf3e0f3237b5dce
568
package com.workflowconversion.portlet.core.exception; /** * Resource thrown when it is attempted to edit a read-only resource. * * @author delagarza * */ public class ResourceNotEditableException extends ApplicationException { private static final long serialVersionUID = 9177207244367838146L; /** * @param message * the message */ public ResourceNotEditableException(final String message) { super(message); } /** * Default constructor. */ public ResourceNotEditableException() { this("This resource is not editable."); } }
19.586207
72
0.71831
521dbb8ff924b14ddcdef9e6be556356daa5da5b
8,346
package alex.mojaki.s3upload.test; import alex.mojaki.s3upload.MultiPartOutputStream; import alex.mojaki.s3upload.StreamTransferManager; import com.amazonaws.ClientConfiguration; import com.amazonaws.SDKGlobalConfiguration; import com.amazonaws.auth.BasicAWSCredentials; import com.amazonaws.services.s3.AmazonS3Client; import com.amazonaws.services.s3.S3ClientOptions; import com.amazonaws.services.s3.model.ObjectMetadata; import com.amazonaws.services.s3.model.S3ObjectInputStream; import com.amazonaws.services.s3.model.UploadPartRequest; import com.amazonaws.util.IOUtils; import com.google.common.base.Strings; import com.google.common.collect.ImmutableList; import com.google.common.io.Resources; import com.google.inject.Module; import org.eclipse.jetty.util.component.AbstractLifeCycle; import org.gaul.s3proxy.S3Proxy; import org.gaul.s3proxy.S3ProxyConstants; import org.jclouds.Constants; import org.jclouds.ContextBuilder; import org.jclouds.blobstore.BlobStore; import org.jclouds.blobstore.BlobStoreContext; import org.jclouds.logging.slf4j.config.SLF4JLoggingModule; import org.junit.*; import org.junit.rules.ExpectedException; import java.io.InputStream; import java.net.URI; import java.util.ArrayList; import java.util.List; import java.util.Properties; import java.util.Random; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; /** * A WIP test using s3proxy to avoid requiring actually connecting to a real S3 bucket. */ public class StreamTransferManagerTest { static { System.setProperty( SDKGlobalConfiguration.DISABLE_CERT_CHECKING_SYSTEM_PROPERTY, "true"); } @Rule public ExpectedException thrown = ExpectedException.none(); private URI s3Endpoint; private S3Proxy s3Proxy; private BlobStoreContext context; private String containerName; private String key; private BasicAWSCredentials awsCreds; @Before public void setUp() throws Exception { Properties s3ProxyProperties = new Properties(); InputStream is = Resources.asByteSource(Resources.getResource( "s3proxy.conf")).openStream(); try { s3ProxyProperties.load(is); } finally { is.close(); } String provider = s3ProxyProperties.getProperty( Constants.PROPERTY_PROVIDER); String identity = s3ProxyProperties.getProperty( Constants.PROPERTY_IDENTITY); String credential = s3ProxyProperties.getProperty( Constants.PROPERTY_CREDENTIAL); String endpoint = s3ProxyProperties.getProperty( Constants.PROPERTY_ENDPOINT); String s3Identity = s3ProxyProperties.getProperty( S3ProxyConstants.PROPERTY_IDENTITY); String s3Credential = s3ProxyProperties.getProperty( S3ProxyConstants.PROPERTY_CREDENTIAL); awsCreds = new BasicAWSCredentials(s3Identity, s3Credential); s3Endpoint = new URI(s3ProxyProperties.getProperty( S3ProxyConstants.PROPERTY_ENDPOINT)); String keyStorePath = s3ProxyProperties.getProperty( S3ProxyConstants.PROPERTY_KEYSTORE_PATH); String keyStorePassword = s3ProxyProperties.getProperty( S3ProxyConstants.PROPERTY_KEYSTORE_PASSWORD); String virtualHost = s3ProxyProperties.getProperty( S3ProxyConstants.PROPERTY_VIRTUAL_HOST); ContextBuilder builder = ContextBuilder .newBuilder(provider) .credentials(identity, credential) .modules(ImmutableList.<Module>of(new SLF4JLoggingModule())) .overrides(s3ProxyProperties); if (!Strings.isNullOrEmpty(endpoint)) { builder.endpoint(endpoint); } context = builder.build(BlobStoreContext.class); BlobStore blobStore = context.getBlobStore(); containerName = createRandomContainerName(); key = "stuff"; blobStore.createContainerInLocation(null, containerName); S3Proxy.Builder s3ProxyBuilder = S3Proxy.builder() .blobStore(blobStore) .endpoint(s3Endpoint); //noinspection ConstantConditions if (s3Identity != null || s3Credential != null) { s3ProxyBuilder.awsAuthentication(s3Identity, s3Credential); } if (keyStorePath != null || keyStorePassword != null) { s3ProxyBuilder.keyStore( Resources.getResource(keyStorePath).toString(), keyStorePassword); } if (virtualHost != null) { s3ProxyBuilder.virtualHost(virtualHost); } s3Proxy = s3ProxyBuilder.build(); s3Proxy.start(); while (!s3Proxy.getState().equals(AbstractLifeCycle.STARTED)) { Thread.sleep(1); } // reset endpoint to handle zero port s3Endpoint = new URI(s3Endpoint.getScheme(), s3Endpoint.getUserInfo(), s3Endpoint.getHost(), s3Proxy.getPort(), s3Endpoint.getPath(), s3Endpoint.getQuery(), s3Endpoint.getFragment()); } @After public void tearDown() throws Exception { if (s3Proxy != null) { s3Proxy.stop(); } if (context != null) { context.getBlobStore().deleteContainer(containerName); context.close(); } } @Test public void testTransferManager() throws Exception { AmazonS3Client client = new AmazonS3Client(awsCreds, new ClientConfiguration().withSignerOverride("S3SignerType")); client.setEndpoint(s3Endpoint.toString()); client.setS3ClientOptions(new S3ClientOptions().withPathStyleAccess(true)); int numStreams = 2; final StreamTransferManager manager = new StreamTransferManager(containerName, key, client) { @Override public void customiseUploadPartRequest(UploadPartRequest request) { /* Workaround from https://github.com/andrewgaul/s3proxy/commit/50a302436271ec46ce81a415b4208b9e14fcaca4 to deal with https://github.com/andrewgaul/s3proxy/issues/80 */ ObjectMetadata metadata = new ObjectMetadata(); metadata.setContentType("application/unknown"); request.setObjectMetadata(metadata); } }.numStreams(numStreams) .numUploadThreads(2) .queueCapacity(2) .partSize(10); final List<MultiPartOutputStream> streams = manager.getMultiPartOutputStreams(); List<StringBuilder> builders = new ArrayList<StringBuilder>(numStreams); ExecutorService pool = Executors.newFixedThreadPool(numStreams); for (int i = 0; i < numStreams; i++) { final int streamIndex = i; final StringBuilder builder = new StringBuilder(); builders.add(builder); Runnable task = new Runnable() { @Override public void run() { MultiPartOutputStream outputStream = streams.get(streamIndex); for (int lineNum = 0; lineNum < 1000000; lineNum++) { String line = String.format("Stream %d, line %d\n", streamIndex, lineNum); outputStream.write(line.getBytes()); builder.append(line); } outputStream.close(); } }; pool.submit(task); } pool.shutdown(); pool.awaitTermination(5, TimeUnit.SECONDS); manager.complete(); for (int i = 1; i < numStreams; i++) { builders.get(0).append(builders.get(i)); } String expectedResult = builders.get(0).toString(); S3ObjectInputStream objectContent = client.getObject(containerName, key).getObjectContent(); String result = IOUtils.toString(objectContent); IOUtils.closeQuietly(objectContent, null); Assert.assertEquals(expectedResult, result); } private static String createRandomContainerName() { return "s3proxy-" + new Random().nextInt(Integer.MAX_VALUE); } }
39.183099
117
0.654445
66a29547bcb584527205b97b54730dc74ed4c9ab
287
package com.fans.service; import com.alibaba.fastjson.JSONObject; /** * interfaceName: IUserService * * @author k * @version 1.0 * @description * @date 2020-06-29 15:29 **/ public interface IUserService { void updateUserWxInfo(JSONObject weChatUserInfo); }
16.882353
54
0.675958
5408639242e615d58f494c02e04d572906cffbe1
9,370
package uk.gov.homeoffice.pontus; /** * Created by leo on 04/11/2016. */ /* * 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. */ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.elasticsearch.action.support.ActionFilter; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.plugins.ActionPlugin; import org.elasticsearch.plugins.Plugin; import org.elasticsearch.plugins.SearchPlugin; import java.util.ArrayList; import java.util.List; /** * Example of a plugin. */ public class ElasticSearchFilterPlugin extends Plugin implements ActionPlugin, SearchPlugin { private static final String CLIENT_TYPE = "client.type"; private static final String TRIBE_NAME = "tribe.name"; private final Settings settings; private boolean tribeNodeClient; private boolean client; protected static final Log LOG = LogFactory.getLog(ElasticSearchFilterPlugin.class); public ElasticSearchFilterPlugin(Settings settings) { this.settings = settings; tribeNodeClient = this.settings.get(TRIBE_NAME, null) != null; client = !"node".equals(this.settings.get(CLIENT_TYPE, "node")); } // LPPM - 2.x // @Override // public String name() { // return "pontus_pole_redaction"; // } // // @Override // public String description() { // return "Common Data Platform Person, Object, Location, Event (POLE) security filter to redact unauthorized data"; // } @Override public Settings additionalSettings() { return Settings.EMPTY; } // LPPM - 2.x // // public void onModule(final ActionModule module) { // //// if(!tribeNodeClient) { //// module.registerAction(ConfigUpdateAction.INSTANCE, TransportConfigUpdateAction.class); //// if (!client) { //// } //// } // if (Boolean.parseBoolean(System.getProperties().getProperty(PontusElasticEmbeddedKafkaSubscriber.ENABLE_PLUGIN_CONF, "false"))) { // module.registerFilter(ElasticSearchFilter.class); // LOG.info("Registered gov.uk.homeoffice.pontus.ElasticSearchFilter"); // } // } // @Override // public Collection<Class<? extends LifecycleComponent>> getGuiceServiceClasses() { // return Collections.emptyList(); // } // LPPM _ had to stop using this approach, as it was causing an exception similar to the one below: // java.lang.IllegalArgumentException: action for name [indices:data/read/search] already registered // at org.elasticsearch.common.NamedRegistry.register(NamedRegistry.java:48) // at org.elasticsearch.action.ActionModule$1ActionRegistry.register(ActionModule.java:355) // at java.util.stream.ForEachOps$ForEachOp$OfRef.accept(ForEachOps.java:184) // at java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1374) // at java.util.stream.ReferencePipeline$Head.forEach(ReferencePipeline.java:580) // at java.util.stream.ReferencePipeline$7$1.accept(ReferencePipeline.java:270) // at java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1374) // at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481) // at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471) // at java.util.stream.ForEachOps$ForEachOp.evaluateSequential(ForEachOps.java:151) // at java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(ForEachOps.java:174) // at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234) // at java.util.stream.ReferencePipeline.forEach(ReferencePipeline.java:418) // at org.elasticsearch.action.ActionModule.setupActions(ActionModule.java:457) // at org.elasticsearch.action.ActionModule.<init>(ActionModule.java:335) // at org.elasticsearch.node.Node.<init>(Node.java:339) // at org.elasticsearch.bootstrap.Bootstrap$5.<init>(Bootstrap.java:217) // at org.elasticsearch.bootstrap.Bootstrap.setup(Bootstrap.java:217) // at org.elasticsearch.bootstrap.Bootstrap.init(Bootstrap.java:314) // at org.elasticsearch.bootstrap.PontusElasticEmbeddedKafkaSubscriber.init(PontusElasticEmbeddedKafkaSubscriber.java:443) // at org.elasticsearch.bootstrap.Elasticsearch.execute(Elasticsearch.java:112) // at org.elasticsearch.cli.SettingCommand.execute(SettingCommand.java:54) // at org.elasticsearch.cli.Command.mainWithoutErrorHandling(Command.java:96) // at org.elasticsearch.cli.Command.main(Command.java:62) // at org.elasticsearch.bootstrap.Elasticsearch.main(Elasticsearch.java:89) // at org.elasticsearch.bootstrap.PontusElasticEmbeddedKafkaSubscriber.<init>(PontusElasticEmbeddedKafkaSubscriber.java:270) // at org.elasticsearch.bootstrap.PontusElasticEmbeddedKafkaSubscriber.create(PontusElasticEmbeddedKafkaSubscriber.java:289) // at org.elasticsearch.bootstrap.PontusElasticEmbeddedKafkaSubscriber.main(PontusElasticEmbeddedKafkaSubscriber.java:407) // @Override // public List<ActionHandler<? extends ActionRequest<?>, ? extends ActionResponse>> getActions() { // List<ActionHandler<? extends ActionRequest<?>, ? extends ActionResponse>> retVal = new ArrayList<>(1); // // ActionHandler<? extends ActionRequest<?>, ? extends ActionResponse> handler = // new ActionHandler<SearchRequest, SearchResponse>(SearchAction.INSTANCE,TransportSearchAction.class); // // retVal.add(handler); // // return retVal; // } @Override public List<Class<? extends ActionFilter>> getActionFilters() { List<Class<? extends ActionFilter>> filters = new ArrayList<>(1); if (!tribeNodeClient && !client) { filters.add(ElasticSearchFilter.class); } return filters; } //@Override // public void onIndexModule(IndexModule indexModule) { // indexModule.setSearcherWrapper(new IndexModule.IndexSearcherWrapperFactory() { // @Override // public IndexSearcherWrapper newWrapper(IndexService indexService) { // return new PontusIndexSearcherWrapper(indexService,settings); // } // }); // // } // // // // public class PontusIndexSearcherWrapper extends IndexSearcherWrapper { // // protected final ThreadContext threadContext; // protected final Index index; //// protected final String searchguardIndex; // // //constructor is called per index, so avoid costly operations here // public PontusIndexSearcherWrapper(final IndexService indexService, Settings settings) { // index = indexService.index(); // threadContext = indexService.getThreadPool().getThreadContext(); //// this.searchguardIndex = settings.get(ConfigConstants.SG_CONFIG_INDEX, ConfigConstants.SG_DEFAULT_CONFIG_INDEX); // } // // @Override // public final DirectoryReader wrap(final DirectoryReader reader) throws IOException { // //// if (!isAdminAuthenticatedOrInternalRequest()) { //// return dlsFlsWrap(reader); //// } // // // // return reader; // } // // @Override // public final IndexSearcher wrap(final IndexSearcher searcher) throws EngineException { // //// if (isSearchGuardIndexRequest() && !isAdminAuthenticatedOrInternalRequest()) { //// return new IndexSearcher(new EmptyReader()); //// } //// //// if (!isAdminAuthenticatedOrInternalRequest()) { //// return dlsFlsWrap(searcher); //// } // // return searcher; // } // // protected IndexSearcher dlsFlsWrap(final IndexSearcher searcher) throws EngineException { // return searcher; // } // // protected DirectoryReader dlsFlsWrap(final DirectoryReader reader) throws IOException { // return reader; // } // //// protected final boolean isAdminAuthenticatedOrInternalRequest() { //// //// final User user = (User) threadContext.getTransient(ConfigConstants.SG_USER); //// //// if (user != null && AdminDNs.isAdmin(user.getName())) { //TODO static hack //// return true; //// } //// //// if ("true".equals(HeaderHelper.getSafeFromHeader(threadContext, ConfigConstants.SG_CONF_REQUEST_HEADER))) { //// return true; //// } //// //// return false; //// } //// //// protected final boolean isSearchGuardIndexRequest() { //// return index.getName().equals(searchguardIndex); //// } // } }
40.387931
139
0.693383
0717faee98b72585091b8055d72703429643111b
2,668
/** * Cash-Register * Copyright (c) 1995-2018 All Rights Reserved. */ package cn.cash.register.controller.frontstage; import java.util.List; import javax.annotation.Resource; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import cn.cash.register.dao.domain.GoodsTag; import cn.cash.register.service.GoodsTagService; import cn.cash.register.util.AssertUtil; import cn.cash.register.util.ResultSet; /** * 商品标签Controller * @author HuHui * @version $Id: GoodsTagController.java, v 0.1 2018年4月25日 下午9:20:42 HuHui Exp $ */ @Controller @RequestMapping("/cashier/goods") public class CashierGoodsTagController { @Resource private GoodsTagService tagService; /** * 增加商品标签 * @param tagName 商品标签名称 * @return 主键id */ @ResponseBody @RequestMapping(value = "/addGoodsTag") public ResultSet addGoodsTag(String tagName) { AssertUtil.assertNotBlank(tagName, "商品标签不能为空"); Long id = tagService.add(tagName); return ResultSet.success().put("id", id); } /** * 删除商品标签 * @param id 商品标签主键id * @return 1:删除成功,0:删除失败 */ @ResponseBody @RequestMapping(value = "/deleteGoodsTag") public ResultSet deleteGoodsTag(Long id) { int result = tagService.delete(id); return ResultSet.success().put("result", result); } /** * 修改商品标签 * @param tag 只需填充对象的id和tagName两个值 * @return 1:修改成功,0:修改失败 */ @ResponseBody @RequestMapping(value = "/updateGoodsTag") public ResultSet updateGoodsTag(GoodsTag tag) { AssertUtil.assertNotNull(tag.getId()); AssertUtil.assertNotBlank(tag.getTagName(), "商品标签不能为空"); int result = tagService.update(tag); return ResultSet.success().put("result", result); } /** * 根据主键查询商品标签 * @param id 商品标签主键id * @return 商品标签对象 */ @ResponseBody @RequestMapping(value = "/queryGoodsTagById") public ResultSet queryGoodsTagById(Long id) { AssertUtil.assertNotNull(id, "商品标签id不能为空"); GoodsTag tag = tagService.queryById(id); return ResultSet.success().put("tag", tag); } /** * 查询所有商品标签 */ @ResponseBody @GetMapping(value = "/queryAllGoodsTag") public ResultSet queryAllGoodsTag() { List<GoodsTag> tags = tagService.queryAll(); return ResultSet.success().put("tags", tags); } }
27.791667
81
0.643178
f476ffaad1a215daecb6482e43a914edaf009eef
63,789
// ============================================================================ // // Copyright (C) 2006-2021 Talend Inc. - www.talend.com // // This source code is available under agreement available at // %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt // // You should have received a copy of the agreement // along with this program; if not, write to Talend SA // 9 rue Pages 92150 Suresnes, France // // ============================================================================ package org.talend.repository.ui.wizards.exportjob.scriptsmanager.esb; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.PrintWriter; import java.net.MalformedURLException; import java.net.URI; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Properties; import java.util.Set; import java.util.jar.Attributes; import java.util.jar.Manifest; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; import java.util.stream.Stream; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.map.MultiKeyMap; import org.apache.commons.lang3.StringUtils; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IFolder; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.Platform; import org.eclipse.core.runtime.Status; import org.eclipse.emf.common.util.EList; import org.osgi.framework.Bundle; import org.talend.commons.exception.ExceptionHandler; import org.talend.commons.exception.PersistenceException; import org.talend.commons.utils.generation.JavaUtils; import org.talend.commons.utils.io.FilesUtils; import org.talend.core.CorePlugin; import org.talend.core.GlobalServiceRegister; import org.talend.core.PluginChecker; import org.talend.core.model.components.IComponent; import org.talend.core.model.general.ModuleNeeded; import org.talend.core.model.general.Project; import org.talend.core.model.process.IProcess; import org.talend.core.model.process.JobInfo; import org.talend.core.model.properties.Item; import org.talend.core.model.properties.ProcessItem; import org.talend.core.model.properties.Property; import org.talend.core.model.properties.RoutineItem; import org.talend.core.model.repository.ERepositoryObjectType; import org.talend.core.model.repository.IRepositoryViewObject; import org.talend.core.model.utils.JavaResourcesHelper; import org.talend.core.repository.constants.FileConstants; import org.talend.core.repository.model.ProxyRepositoryFactory; import org.talend.core.runtime.maven.MavenArtifact; import org.talend.core.runtime.maven.MavenConstants; import org.talend.core.runtime.process.ITalendProcessJavaProject; import org.talend.core.runtime.process.LastGenerationInfo; import org.talend.core.runtime.repository.build.BuildExportManager; import org.talend.core.service.ITaCoKitDependencyService; import org.talend.core.ui.branding.IBrandingService; import org.talend.core.utils.CodesJarResourceCache; import org.talend.designer.core.ICamelDesignerCoreService; import org.talend.designer.core.IDesignerCoreService; import org.talend.designer.core.model.utils.emf.component.IMPORTType; import org.talend.designer.core.model.utils.emf.talendfile.ElementParameterType; import org.talend.designer.core.model.utils.emf.talendfile.ElementValueType; import org.talend.designer.core.model.utils.emf.talendfile.NodeType; import org.talend.designer.core.model.utils.emf.talendfile.RoutinesParameterType; import org.talend.designer.maven.model.TalendMavenConstants; import org.talend.designer.maven.utils.PomIdsHelper; import org.talend.designer.maven.utils.PomUtil; import org.talend.designer.runprocess.IProcessor; import org.talend.designer.runprocess.IRunProcessService; import org.talend.designer.runprocess.ProcessorException; import org.talend.designer.runprocess.ProcessorUtilities; import org.talend.repository.ProjectManager; import org.talend.repository.RepositoryPlugin; import org.talend.repository.documentation.ExportFileResource; import org.talend.repository.ui.wizards.exportjob.scriptsmanager.JobJavaScriptsManager; import org.talend.repository.utils.EmfModelUtils; import org.talend.repository.utils.TemplateProcessor; import aQute.bnd.header.Parameters; import aQute.bnd.osgi.Analyzer; import aQute.bnd.osgi.Clazz; import aQute.bnd.osgi.Domain; import aQute.bnd.osgi.FileResource; import aQute.bnd.osgi.Jar; /** * DOC ycbai class global comment. Detailled comment */ public class JobJavaScriptOSGIForESBManager extends JobJavaScriptsManager { protected static final char MANIFEST_ITEM_SEPARATOR = ','; protected static final String OSGI_EXCLUDE_PROP_FILENAME = "osgi-exclude.properties"; ////$NON-NLS-1$ private boolean ENABLE_CACHE = StringUtils.equals(System.getProperty("enable.manifest.cache", "false"), "true"); private static final Collection<String> EXCLUDED_MODULES = new ArrayList<String>(); private Bundle esbBundle = Platform.getBundle(PluginChecker.ESBSE_PLUGIN_ID); File cacheFile = null; public JobJavaScriptOSGIForESBManager(Map<ExportChoice, Object> exportChoiceMap, String contextName, String launcher, int statisticPort, int tracePort) { super(exportChoiceMap, contextName, launcher, statisticPort, tracePort); if (esbBundle != null) { IPath stateLocationPath = Platform.getStateLocation(esbBundle); cacheFile = new File(stateLocationPath.toFile().getAbsolutePath() + File.separatorChar + "dependencyMap.cache"); FileInputStream fi = null; ObjectInputStream oi = null; try { if (!cacheFile.exists()) { cacheFile.createNewFile(); } else { if (cacheFile.length() > 0) { fi = new FileInputStream(cacheFile); oi = new ObjectInputStream(fi); dependencyCacheMap = (Map) oi.readObject(); } } } catch (Exception e) { e.printStackTrace(); } finally { try { if (oi != null) { oi.close(); } } catch (IOException e) { e.printStackTrace(); } } } } Map<String, List<Object>> dependencyCacheMap = null; protected static final char PACKAGE_SEPARATOR = '.'; private static final String JAVA = "java"; //$NON-NLS-1$ private static final String JAVA_VERSION = "java.version"; private static File routineClassRootFolder = null; private static File beanClassRootFolder = null; private MultiKeyMap requireBundleModules = new MultiKeyMap(); // private String itemType = null; private final File classesLocation = new File(getTmpFolder() + File.separator + "classes"); //$NON-NLS-1$; private static final String DLL_FILE = ".dll"; //$NON-NLS-1$ private static final String SO_FILE = ".so"; //$NON-NLS-1$ private static final String OSGI_OS_CODE = ';' + "osname=" + System.getProperty("osgi.os") + ';' + "processor=" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + System.getProperty("osgi.arch") + ','; //$NON-NLS-1$ private static final String RESOLUTION_OPTIONAL = ";resolution:=optional"; private static final String COMPILER_LOG_DELIMITER = "----------"; private static final String COMPILER_LOG_REGEX = "(^[a-z_0-9\\.]+)\\."; private static final String COMPILER_LOG_ERROR_1 = "cannot be resolved to a type"; private static final String COMPILER_LOG_ERROR_2 = "cannot be resolved"; private static String complianceLevel = "1.8"; private static String complianceParameter; static { String javaVersion = System.getProperty(JAVA_VERSION); if (javaVersion != null) { if (javaVersion.startsWith("1.7")) { complianceLevel = "1.7"; } else if (javaVersion.startsWith("1.8")) { complianceLevel = "1.8"; } else if (javaVersion.startsWith("9")) { complianceLevel = "9"; } else if (javaVersion.startsWith("10")) { complianceLevel = "10"; } else if (javaVersion.startsWith("11")) { complianceLevel = "11"; } } complianceParameter = " -" + complianceLevel + " -maxProblems 100000 -nowarn"; try (InputStream is = RepositoryPlugin.getDefault().getBundle().getEntry("/resources/osgi-exclude.properties") //$NON-NLS-1$ .openStream()) { final Properties p = new Properties(); p.load(is); for (Enumeration<?> e = p.propertyNames(); e.hasMoreElements();) { EXCLUDED_MODULES.add((String) e.nextElement()); } if ("1.8".equals(complianceLevel) && null != p.getProperty("java8.excludes")) { EXCLUDED_MODULES.addAll(Arrays.asList(p.getProperty("java8.excludes").split(","))); } } catch (IOException e) { RepositoryPlugin.getDefault().getLog() .log(new Status(Status.ERROR, RepositoryPlugin.PLUGIN_ID, "Unable to load OSGi excludes", e)); } } @Override public List<ExportFileResource> getExportResources(ExportFileResource[] processes, String... codeOptions) throws ProcessorException { List<ExportFileResource> list = new ArrayList<ExportFileResource>(); ExportFileResource osgiResource = new ExportFileResource(null, ""); //$NON-NLS-1$; ExportFileResource jobScriptResource = new ExportFileResource(null, ""); //$NON-NLS-1$ list.add(osgiResource); list.add(jobScriptResource); // set export config mode now only to be sure that the libraries will be // setup for an export mode, and not // editor mode. ProcessorUtilities.setExportConfig(JAVA, "", ""); //$NON-NLS-1$ // set export type as osgi ProcessorUtilities.setExportAsOSGI(true); try { ProcessItem processItem = null; for (ExportFileResource process : processes) { processItem = (ProcessItem) process.getItem(); if (processItem.eIsProxy() || processItem.getProcess().eIsProxy()) { try { Property property = ProxyRepositoryFactory.getInstance().getUptodateProperty(processItem.getProperty()); processItem = (ProcessItem) property.getItem(); } catch (PersistenceException e) { throw new ProcessorException(e); } } String jobVersion = processItem.getProperty().getVersion(); if (!isMultiNodes() && getSelectedJobVersion() != null) { jobVersion = getSelectedJobVersion(); } ProcessorUtilities.setExportConfig(process.getDirectoryName(), true); String processId = processItem.getProperty().getId(); if (null == contextName) { contextName = processItem.getProcess().getDefaultContext(); } IProcess iProcess = generateJobFiles(processItem, contextName, jobVersion, statisticPort != IProcessor.NO_STATISTICS, tracePort != IProcessor.NO_TRACES, isOptionChoosed(ExportChoice.applyToChildren), progressMonitor); analysisModules(processId, jobVersion); analysisMavenModule(processItem); // generate jar file for job getJobScriptsUncompressed(jobScriptResource, processItem); // dynamic DB XML mapping addXmlMapping(process, true);// isOptionChoosed(ExportChoice.needSourceCode) if (CollectionUtils.isNotEmpty(process.getAllResources())) { ExportFileResource xm = new ExportFileResource(null, JavaUtils.JAVA_XML_MAPPING); Set<URL> urls = process .getResourcesByRelativePath(JOB_SOURCE_FOLDER_NAME + PATH_SEPARATOR + JavaUtils.JAVA_XML_MAPPING); if (CollectionUtils.isNotEmpty(urls)) { xm.addResources(new ArrayList<URL>(urls)); list.add(xm); } } generateConfig(osgiResource, processItem, iProcess); addResources(osgiResource, processItem); /* * export current item's dependencies. this used for TDM components specially and need more discussion * about then */ // TCOMP-1681: feature uses this call for feeding a component-runtime compliant MAVEN-INF/repository and // TALEND-INF/plugins.properties. BuildExportManager.getInstance().exportOSGIDependencies(osgiResource, processItem); } ExportFileResource libResource = getCompiledLibExportFileResource(processes); list.add(libResource); ExportFileResource libResourceSelected = new ExportFileResource(null, LIBRARY_FOLDER_NAME); if (GlobalServiceRegister.getDefault().isServiceRegistered(ICamelDesignerCoreService.class)) { ICamelDesignerCoreService camelService = (ICamelDesignerCoreService) GlobalServiceRegister.getDefault().getService( ICamelDesignerCoreService.class); Collection<String> unselectList = camelService.getUnselectDependenciesBundle(processItem); List<URL> unselectListURLs = new ArrayList<>(); for(Set<URL> set:libResource.getAllResources()) { for (URL url : set) { boolean exist = false; for(String name: unselectList) { if (name.equals(new File(new File(url.getFile()).toURI()).getName())) { exist = true; } } if (!exist) { unselectListURLs.add(url); } } } libResourceSelected.addResources(unselectListURLs); } // generate the META-INFO folder ExportFileResource metaInfoFolder = genMetaInfoFolder(libResourceSelected, processItem); list.add(0, metaInfoFolder); ExportFileResource providedLibResources = getProvidedLibExportFileResource(processes); if (providedLibResources != null) { list.add(providedLibResources); } // TCOMP-1681: for class isolation and avoid clashes, we remove tacokit dependencies to main classpath. // However, they're in the scope of ComponentManager. if (GlobalServiceRegister.getDefault().isServiceRegistered(ITaCoKitDependencyService.class)) { ITaCoKitDependencyService tckService = (ITaCoKitDependencyService) GlobalServiceRegister.getDefault() .getService(ITaCoKitDependencyService.class); if (tckService != null && tckService.hasTaCoKitComponents(tckService.getJobComponents(processItem))) { list = cleanupResources(tckService.getJobComponents(processItem), list, tckService); } } } catch (ProcessorException e) { throw e; } catch (Exception e) { throw new ProcessorException(e); } return list; } @Override protected void analysisModules(String processId, String processVersion) { Set<ModuleNeeded> neededModules = LastGenerationInfo.getInstance().getModulesNeededWithSubjobPerJob(processId, processVersion); for (ModuleNeeded module : neededModules) { if (isCompiledLib(module)) { addModuleNeededsInMap(getCompiledModules(), processId, processVersion, module); } else if (isRequireBundleLib(module)) { addModuleNeededsInMap(getRequireBundleModules(), processId, processVersion, module); } else { addModuleNeededsInMap(getExcludedModules(), processId, processVersion, module); } } } @Override protected ExportFileResource getCompiledLibExportFileResource(ExportFileResource[] processes) { ExportFileResource libResource = new ExportFileResource(null, LIBRARY_FOLDER_NAME); // Gets talend libraries List<URL> talendLibraries = getExternalLibraries(true, processes, getCompiledModuleNames()); if (talendLibraries != null) { libResource.addResources(talendLibraries); } addRoutinesResources(processes, libResource); return libResource; } private List<ExportFileResource> cleanupResources(Stream<IComponent> components, List<ExportFileResource> resources, ITaCoKitDependencyService service) { Set<String> tckOnly = service.getTaCoKitOnlyDependencies(components); final List<ExportFileResource> rmResources = new ArrayList<>(); //This code is nicer but have to reiterate after, so not so efficient // List<URL> rmDeps = resources.stream() // .filter(rf -> "lib".equals(rf.getDirectoryName())) // .map(resource -> resource.getResourcesByRelativePath("")) // .flatMap(urls -> urls.stream()) // .filter(url -> tckOnly.stream().anyMatch(tck -> url.toString().endsWith(tck))) // .collect(Collectors.toList()); for (ExportFileResource resource : resources) { if (!("lib".equals(resource.getDirectoryName()) || "lib-provided".equals(resource.getDirectoryName()))) { continue; } List<URL> rmDeps = resource.getResourcesByRelativePath("").stream() .filter(url -> tckOnly.stream().anyMatch(tck -> url.toString().endsWith(tck))) .collect(Collectors.toList()); rmDeps.stream().forEach(dep -> resource.removeResources("", dep)); } return resources; } protected String getIncludeRoutinesPath() { return USER_ROUTINES_PATH; } protected Collection<String> getRoutinesPaths() { return Collections.singletonList(getIncludeRoutinesPath()); } @Override protected void addRoutinesResources(ExportFileResource[] processes, ExportFileResource libResource) { // codes jars ProcessItem item = (ProcessItem) processes[0].getItem(); EList<RoutinesParameterType> routinesParameter = item.getProcess().getParameters().getRoutinesParameter(); List<URL> codesjarM2Files = new ArrayList<>(); if (routinesParameter != null) { routinesParameter.stream().filter(r -> r.getType() != null).map(r -> CodesJarResourceCache.getCodesJarById(r.getId())) .filter(info -> info != null).forEach(info -> { MavenArtifact artifact = new MavenArtifact(); artifact.setGroupId(PomIdsHelper.getCodesJarGroupId(info)); artifact.setArtifactId(info.getLabel().toLowerCase()); artifact.setVersion(PomIdsHelper.getCodesJarVersion(info.getProjectTechName())); artifact.setType(MavenConstants.TYPE_JAR); try { codesjarM2Files.add(new File(PomUtil.getArtifactFullPath(artifact)).toURI().toURL()); } catch (MalformedURLException e) { e.printStackTrace(); } }); } String projectTechName = ProjectManager.getInstance().getProject(item).getTechnicalLabel(); // routines.jar MavenArtifact routinesArtifact = new MavenArtifact(); routinesArtifact.setGroupId(PomIdsHelper.getCodesGroupId(projectTechName, TalendMavenConstants.DEFAULT_CODE)); routinesArtifact.setArtifactId(TalendMavenConstants.DEFAULT_ROUTINES_ARTIFACT_ID); routinesArtifact.setVersion(PomIdsHelper.getCodesVersion(projectTechName)); routinesArtifact.setType(MavenConstants.TYPE_JAR); try { codesjarM2Files.add(new File(PomUtil.getArtifactFullPath(routinesArtifact)).toURI().toURL()); } catch (MalformedURLException e) { e.printStackTrace(); } // beans.jar MavenArtifact beansArtifact = new MavenArtifact(); beansArtifact.setGroupId(PomIdsHelper.getCodesGroupId(projectTechName, TalendMavenConstants.DEFAULT_BEAN)); beansArtifact.setArtifactId(TalendMavenConstants.DEFAULT_BEANS_ARTIFACT_ID); beansArtifact.setVersion(PomIdsHelper.getCodesVersion(projectTechName)); beansArtifact.setType(MavenConstants.TYPE_JAR); try { codesjarM2Files.add(new File(PomUtil.getArtifactFullPath(beansArtifact)).toURI().toURL()); } catch (MalformedURLException e) { e.printStackTrace(); } libResource.addResources(codesjarM2Files); } protected ExportFileResource getProvidedLibExportFileResource(ExportFileResource[] processes) { return null; // default, no provided lib for osgi bundle } /** * * This should be same as @see isIncludedLib. But, there are some special jar to exclude temp. */ @Override protected boolean isCompiledLib(ModuleNeeded module) { /* * If null, will add the lib always. * If empty, nothing will be added. * Else, add the bundle id in "Require-Bundle", but don't add the lib. */ return module != null && isIncludedLib(module); } /** * If null, will add the lib always. @see isIncludedLib * If empty, nothing will be added. @see isExcludedLib * Else, add the bundle id in "Require-Bundle", but don't add the lib. @see isIncludedInRequireBundle */ protected boolean isIncludedLib(ModuleNeeded module) { return module != null && module.getBundleName() == null && !isExcluded(module.getModuleName()); } private static boolean isExcluded(String moduleName) { for (String exclude : EXCLUDED_MODULES) { if (moduleName.startsWith(exclude)) { return true; } } return false; } protected boolean isProvidedLib(ModuleNeeded module) { return isRequireBundleLib(module) || isExcludedLib(module); } /** * nothing will be added. */ @Override protected boolean isExcludedLib(ModuleNeeded module) { if (module != null) { if (module.getBundleName() != null && "".equals(module.getBundleName().trim())) { //$NON-NLS-1$ return true; } } return false; } /** * check for the lib for "Require-Bundle" */ protected boolean isRequireBundleLib(ModuleNeeded module) { if (module != null) { if (module.getBundleName() != null && !"".equals(module.getBundleName().trim())) { //$NON-NLS-1$ return true; } } return false; } /** * Get all route resource needed. * * @param osgiResource * @param processItem * @throws MalformedURLException */ protected void addResources(ExportFileResource osgiResource, ProcessItem processItem) throws Exception { } /** * DOC ycbai Comment method "getJobScriptsUncompressed". * * @param resource * @param process * @throws IOException */ private void getJobScriptsUncompressed(ExportFileResource resource, ProcessItem process) throws IOException { final URI classRootURI = classesLocation.toURI(); List<String> jobFolderNames = getRelatedJobFolderNames(process); try { for (String jobFolderName : jobFolderNames) { String[] jf = jobFolderName.split(":"); //$NON-NLS-1$ String projectName = jf[0]; String folderName = jf[1]; String classRootLocation = getJobClassRootLocation(process.getProperty()) + projectName + File.separator; String classRoot = FilesUtils.getFileRealPath(classRootLocation + folderName); String targetPath = FilesUtils.getFileRealPath(classesLocation + File.separator + projectName + File.separator + folderName); File sourceFile = new File(classRoot); File targetFile = new File(targetPath); FilesUtils.copyFolder(sourceFile, targetFile, true, null, null, true, false); List<URL> fileURLs = FilesUtils.getFileURLs(targetFile); for (URL url : fileURLs) { resource.addResource(classRootURI.relativize(new File(url.toURI()).getParentFile().toURI()).toString(), url); } } } catch (IOException e) { throw e; } catch (Exception e) { ExceptionHandler.process(e); } } private static boolean isTalendESBJob(ProcessItem processItem) { return null != EmfModelUtils.getComponentByName(processItem, "tESBProviderRequest", "tESBConsumer", "tRouteInput"); } private static boolean isTalendESBJobFactory(ProcessItem processItem) { return null != EmfModelUtils.getComponentByName(processItem, "tESBProviderRequest", "tRouteInput"); } private static boolean isTalendStepTemplate(ProcessItem processItem) { return null != EmfModelUtils.getComponentByName(processItem, "tActionInput", "tActionOutput", "tActionReject"); } private static NodeType getRESTRequestComponent(ProcessItem processItem) { return EmfModelUtils.getComponentByName(processItem, "tRESTRequest"); } protected static String getPackageName(ProcessItem processItem) { return JavaResourcesHelper.getProjectFolderName(processItem) + PACKAGE_SEPARATOR + JavaResourcesHelper.getJobFolderName(processItem.getProperty().getLabel(), processItem.getProperty() .getVersion()); } private Map<String, Object> collectJobInfo(ProcessItem processItem, IProcess process) { // velocity template context Map<String, Object> jobInfo = new HashMap<String, Object>(); String name = processItem.getProperty().getLabel(); String className = getPackageName(processItem) + PACKAGE_SEPARATOR + name; boolean isTalendStepTemplate = isTalendStepTemplate(processItem); // job name and class name String jobName = name; if (!EmfModelUtils.getComponentsByName(processItem, "tRouteInput").isEmpty()) { //$NON-NLS-1$ jobName = className; } jobInfo.put("name", jobName); jobInfo.put("version", getBundleVersion()); //$NON-NLS-1$ jobInfo.put("className", className); //$NON-NLS-1$ // additional Talend job interfaces (ESB related) boolean isESBJob = isTalendESBJob(processItem); jobInfo.put("isESBJob", isESBJob); //$NON-NLS-1$ jobInfo.put("isESBJobFactory", isESBJob && isTalendESBJobFactory(processItem)); //$NON-NLS-1$ jobInfo.put("isTalendStepTemplate", isTalendStepTemplate); //$NON-NLS-1$ // job components use SAM / use SAML boolean useSAM = false; for (NodeType node : EmfModelUtils.getComponentsByName(processItem, "tRESTClient")) { //$NON-NLS-1$ if (!useSAM && EmfModelUtils.computeCheckElementValue("SERVICE_ACTIVITY_MONITOR", node)) { //$NON-NLS-1$ useSAM = true; break; } } jobInfo.put("useSAM", useSAM); //$NON-NLS-1$ // job OSGi DataSources jobInfo.put("dataSources", DataSourceConfig.getAliases(process)); //$NON-NLS-1$ jobInfo.put("hasDestroyMethod", ERepositoryObjectType.PROCESS_MR != ERepositoryObjectType.getItemType(processItem)); return jobInfo; } private static Map<String, Object> collectRestEndpointInfo(ProcessItem processItem) { Map<String, Object> endpointInfo = new HashMap<String, Object>(); NodeType restRequestComponent = getRESTRequestComponent(processItem); if (null == restRequestComponent) { return endpointInfo; } // REST endpoint address final String runtimeServicesContext = "/services"; //$NON-NLS-1$ final String runtimeServicesContextFull = runtimeServicesContext + '/'; String endpointUri = EmfModelUtils.computeTextElementValue("REST_ENDPOINT", restRequestComponent); //$NON-NLS-1$ if (endpointUri.contains("context.") || endpointUri.contains("(") || endpointUri.contains("+")) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ // Since TESB-24998, endpointUri could be an expression with variables, does not need unquote endpointUri = EmfModelUtils.computeTextElementValueWithoutUnquote("REST_ENDPOINT", restRequestComponent); //$NON-NLS-1$ } if (endpointUri.contains("context.")) { // TESB-24998 Add context bean in blueprint endpointInfo.put("useContextBean", true); //$NON-NLS-1$ endpointInfo.put("defaultContext", processItem.getProcess().getDefaultContext()); //$NON-NLS-1$ } else if (!endpointUri.contains("://") && !endpointUri.startsWith("/")) { //$NON-NLS-1$ //$NON-NLS-2$ endpointUri = '/' + (endpointUri.isEmpty() ? processItem.getProperty().getLabel() : endpointUri); } endpointInfo.put("originalAddress", endpointUri); //$NON-NLS-1$ Needed by Swagger String endpointDescription = ""; if (EmfModelUtils.computeCheckElementValue("INCLUDE_DOC_INTO_SWAGGER_SPEC", restRequestComponent)) { endpointDescription = EmfModelUtils.computeTextElementValue("COMMENT", restRequestComponent); if (endpointDescription == null) { endpointDescription = ""; } if (endpointDescription.contains("\r\n")) { endpointDescription = endpointDescription.replace("\r\n", "&#10;"); } else { endpointDescription = endpointDescription.replace("\n", "&#10;"); } } endpointInfo.put("description", endpointDescription); //$NON-NLS-1$ Needed by Swagger // TESB-5916: Rest service can't be deployed in the Runtime on the port said in the studio // if (endpointUri.contains("://")) { // endpointUri = new URL(endpointUri).getPath(); // } if (runtimeServicesContextFull.equals(endpointUri) || runtimeServicesContext.equals(endpointUri)) { // pass as is } else if (endpointUri.startsWith(runtimeServicesContextFull)) { // remove forwarding "/services/" context as required by runtime (but leave forwarding slash) endpointUri = endpointUri.substring(runtimeServicesContextFull.length() - 1); } endpointInfo.put("address", endpointUri); //$NON-NLS-1$ // log messages endpointInfo.put("logMessages", //$NON-NLS-1$ EmfModelUtils.computeCheckElementValue("LOG_MESSAGES", restRequestComponent)); //$NON-NLS-1$ // wrap JSON request endpointInfo.put("wrapJsonRequest", //$NON-NLS-1$ EmfModelUtils.computeCheckElementValue("WRAP_JSON_REQUEST", restRequestComponent)); //$NON-NLS-1$ // unwrap JSON response (drop root element) endpointInfo.put("unwrapJsonResponse", //$NON-NLS-1$ EmfModelUtils.computeCheckElementValue("UNWRAP_JSON_RESPONSE", restRequestComponent)); //$NON-NLS-1$ // Convert JSON to string (big double values) endpointInfo.put("convertTypesToStrings", //$NON-NLS-1$ EmfModelUtils.computeCheckElementValue("CONVERT_JSON_VALUES_TO_STRING", restRequestComponent)); //$NON-NLS-1$ // use Authentication & authentication type endpointInfo.put("useAuthentication", //$NON-NLS-1$ EmfModelUtils.computeCheckElementValue("NEED_AUTH", restRequestComponent)); //$NON-NLS-1$ endpointInfo.put("authenticationType", //$NON-NLS-1$ EmfModelUtils.computeTextElementValue("AUTH_TYPE", restRequestComponent)); //$NON-NLS-1$ // use Service Activity Monitoring endpointInfo.put("useSAM", //$NON-NLS-1$ EmfModelUtils.computeCheckElementValue("SERVICE_ACTIVITY_MONITOR", restRequestComponent)); //$NON-NLS-1$ // use Service Locator endpointInfo.put("useSL", //$NON-NLS-1$ EmfModelUtils.computeCheckElementValue("SERVICE_LOCATOR", restRequestComponent)); //$NON-NLS-1$ // use Authorization if (isStudioEEVersion()) { if (EmfModelUtils.computeCheckElementValue("NEED_AUTH", restRequestComponent)) { endpointInfo.put("useAuthorization", //$NON-NLS-1$ EmfModelUtils.computeCheckElementValue("NEED_AUTHORIZATION", restRequestComponent)); //$NON-NLS-1$ } } else { endpointInfo.put("useAuthorization", false); //$NON-NLS-1$ } // expose Swagger specification endpointInfo.put("exposeSwaggerSpecification", //$NON-NLS-1$ EmfModelUtils.computeCheckElementValue("EXPOSE_SWAGGER_SPEC", restRequestComponent)); //$NON-NLS-1$ // Service Locator custom properties Map<String, String> slCustomProperties = new HashMap<String, String>(); ElementParameterType customPropsType = EmfModelUtils.findElementParameterByName( "SERVICE_LOCATOR_CUSTOM_PROPERTIES", restRequestComponent); //$NON-NLS-1$ if (null != customPropsType) { List<?> elementValues = customPropsType.getElementValue(); final int size = elementValues.size(); for (int i = 0; i < size; i += 2) { if (size <= i + 1) { break; } ElementValueType name = (ElementValueType) elementValues.get(i); ElementValueType value = (ElementValueType) elementValues.get(i + 1); if (null != name && null != value) { if (null != name.getValue() && null != value.getValue()) { slCustomProperties.put(unquote(name.getValue()), unquote(value.getValue())); } } } } Map<String, String> samCustomProperties = new HashMap<String, String>(); customPropsType = EmfModelUtils.findElementParameterByName("SERVICE_ACTIVITY_MONITOR_CUSTOM_PROPERTIES", //$NON-NLS-1$ restRequestComponent); if (null != customPropsType) { List<?> elementValues = customPropsType.getElementValue(); final int size = elementValues.size(); for (int i = 0; i < size; i += 2) { if (size <= i + 1) { break; } ElementValueType name = (ElementValueType) elementValues.get(i); ElementValueType value = (ElementValueType) elementValues.get(i + 1); if (null != name && null != value) { if (null != name.getValue() && null != value.getValue()) { samCustomProperties.put(unquote(name.getValue()), unquote(value.getValue())); } } } } endpointInfo.put("slCustomProps", slCustomProperties); //$NON-NLS-1$ endpointInfo.put("samCustomProps", samCustomProperties); //$NON-NLS-1$ // service name & namespace endpointInfo.put("serviceName", //$NON-NLS-1$ EmfModelUtils.computeTextElementValue("SERVICE_NAME", restRequestComponent)); //$NON-NLS-1$ endpointInfo.put("serviceNamespace", //$NON-NLS-1$ EmfModelUtils.computeTextElementValue("SERVICE_NAMESPACE", restRequestComponent)); //$NON-NLS-1$ // correlation id endpointInfo.put("useBusinesCorrelation", //$NON-NLS-1$ EmfModelUtils.computeCheckElementValue("USE_BUSINESS_CORRELATION", restRequestComponent)); //$NON-NLS-1$ return endpointInfo; } /** * * Ensure that the value is not surrounded by quotes. * * @param value * @return */ private static final String unquote(String value) { String result = value; if (null != value && 1 < value.length()) { if (value.startsWith("\"") && value.endsWith("\"")) { result = value.substring(1, value.length() - 1); } } return result; } protected void generateConfig(ExportFileResource osgiResource, ProcessItem processItem, IProcess process) throws IOException { final File targetFile = new File(getTmpFolder() + PATH_SEPARATOR + "job.xml"); //$NON-NLS-1$ // restJob if (null != getRESTRequestComponent(processItem)) { generateRestJobBlueprintConfig(processItem, process, targetFile); } else { createJobBundleBlueprintConfig(processItem, process, targetFile); } osgiResource.addResource(FileConstants.BLUEPRINT_FOLDER_NAME, targetFile.toURI().toURL()); } private static final String TEMPLATE_BLUEPRINT_JOB_REST = "/resources/job-rest-template.xml"; //$NON-NLS-1$ private void generateRestJobBlueprintConfig(ProcessItem processItem, IProcess process, File targetFile) throws IOException { // velocity template context Map<String, Object> contextParams = new HashMap<String, Object>(); contextParams.put("endpoint", collectRestEndpointInfo(processItem)); //$NON-NLS-1$ contextParams.put("job", collectJobInfo(processItem, process)); //$NON-NLS-1$ TemplateProcessor.processTemplate("REST_JOB_BLUEPRINT_CONFIG", //$NON-NLS-1$ contextParams, targetFile, JobJavaScriptOSGIForESBManager.class.getResourceAsStream(TEMPLATE_BLUEPRINT_JOB_REST)); } private static final String TEMPLATE_BLUEPRINT_JOB = "/resources/job-template.xml"; //$NON-NLS-1$ private void createJobBundleBlueprintConfig(ProcessItem processItem, IProcess process, File targetFile) throws IOException { TemplateProcessor.processTemplate("JOB_BLUEPRINT_CONFIG", //$NON-NLS-1$ collectJobInfo(processItem, process), targetFile, JobJavaScriptOSGIForESBManager.class.getClassLoader() .getResourceAsStream(TEMPLATE_BLUEPRINT_JOB)); } private ExportFileResource genMetaInfoFolder(ExportFileResource libResource, ProcessItem processItem) throws IOException { ExportFileResource metaInfoResource = new ExportFileResource(null, FileConstants.META_INF_FOLDER_NAME); // generate the MANIFEST.MF file in the temp folder File manifestFile = new File(getTmpFolder() + PATH_SEPARATOR + FileConstants.MANIFEST_MF_FILE_NAME); FileOutputStream fos = null; try { Manifest manifest = getManifest(libResource, processItem); fos = new FileOutputStream(manifestFile); manifest.write(fos); } finally { if (fos != null) { fos.close(); } } metaInfoResource.addResources(Collections.singletonList(manifestFile.toURI().toURL())); return metaInfoResource; } private Manifest getManifest(ExportFileResource libResource, ProcessItem processItem) throws IOException { Analyzer analyzer = createAnalyzer(libResource, processItem); Set<String> imports = null; if (GlobalServiceRegister.getDefault().isServiceRegistered(IRunProcessService.class)) { IRunProcessService service = (IRunProcessService) GlobalServiceRegister.getDefault() .getService(IRunProcessService.class); ITalendProcessJavaProject talendProcessJavaProject = service.getTalendJobJavaProject(processItem.getProperty()); if (talendProcessJavaProject != null) { imports = importCompiler(service, processItem); String[] defaultPackages = analyzer.getProperty(Analyzer.IMPORT_PACKAGE).split(","); // JDK upgrade to 11 imports.add("org.osgi.framework"); for (String dp : defaultPackages) { if (!imports.contains(dp) && !imports.contains(dp + RESOLUTION_OPTIONAL)) { imports.add(dp); } } imports.remove("*;resolution:=optional"); imports.remove("routines.system"); imports.remove("routines.system" + RESOLUTION_OPTIONAL); if (!ENABLE_CACHE) { // TESB-24730 set specific version for "javax.annotation" imports.remove("javax.annotation"); imports.remove("javax.annotation" + RESOLUTION_OPTIONAL); imports.add("javax.annotation;version=\"[1.3,2)\"" + RESOLUTION_OPTIONAL); } analyzer.setProperty(Analyzer.IMPORT_PACKAGE, String.join(",", imports) + ",*;resolution:=optional"); } } // Calculate the manifest Manifest manifest = null; try { manifest = analyzer.calcManifest(); filterPackagesCache(manifest, imports); } catch (IOException e) { throw e; } catch (Exception e) { ExceptionHandler.process(e); } finally { analyzer.close(); } // In some cases of Java8, if user compiled some classes with newer(Java 11) JDK versions, the // Require-Capability will use the last version(Java 11) // https://github.com/bndtools/bnd/blob/master/biz.aQute.bndlib/src/aQute/bnd/osgi/Analyzer.java#L975 if ("1.8".equals(complianceLevel)) { //$NON-NLS-1$ String requireCapability = manifest.getMainAttributes().getValue(Analyzer.REQUIRE_CAPABILITY); if (StringUtils.isNotBlank(requireCapability)) { // set back to 1.8, version from: // https://github.com/bndtools/bnd/blob/master/biz.aQute.bndlib/src/aQute/bnd/osgi/Clazz.java#L141 requireCapability = requireCapability.replace(Clazz.JAVA.OpenJDK9.getFilter(), Clazz.JAVA.OpenJDK8.getFilter()) .replace(Clazz.JAVA.OpenJDK10.getFilter(), Clazz.JAVA.OpenJDK8.getFilter()) .replace(Clazz.JAVA.OpenJDK11.getFilter(), Clazz.JAVA.OpenJDK8.getFilter()); manifest.getMainAttributes().put(new Attributes.Name(Analyzer.REQUIRE_CAPABILITY), requireCapability); } } return manifest; } private boolean cacheManifest(URL url, String relativePath) { boolean result = false; ObjectOutputStream o = null; Analyzer al = new Analyzer(); try { File jarFile = new File(url.toURI()); try (InputStream is = RepositoryPlugin.getDefault().getBundle() .getEntry("/resources/osgi-ignore-calmanifest.properties").openStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is))) { Optional<String> rs = br.lines() .filter(fn -> StringUtils.equals(jarFile.getName(), fn) || StringUtils.equals(fn, "*")).findFirst(); result = rs.orElse(null) != null; } if (result) { String key = jarFile.length() + jarFile.getName(); if (dependencyCacheMap == null || dependencyCacheMap.get(key) == null) { Jar bin = new Jar(jarFile); al.setJar(bin); // al.setProperty(Analyzer.IMPORT_PACKAGE, "*;resolution:=optional"); // bin.putResource(relativePath, new FileResource(jarFile)); Manifest manifest = al.calcManifest(); String requireCapabilityString = manifest.getMainAttributes().getValue(Analyzer.REQUIRE_CAPABILITY); // Todo Handle requireCapabilityString to the MANIFEST.MF file ? // if (requireCapabilityString != null) { // // } Domain d = Domain.domain(manifest); Parameters imports = d.getImportPackage(); Parameters privates = d.getPrivatePackage(); String privatePackageString = manifest.getMainAttributes().getValue(Analyzer.PRIVATE_PACKAGE); String importPackageString = manifest.getMainAttributes().getValue(Analyzer.IMPORT_PACKAGE); if (StringUtils.isBlank(privatePackageString) || StringUtils.isBlank(importPackageString)) { bundleClasspathKeys.remove(key); return false; } List<Object> infos = new ArrayList<>(); infos.add(imports.keyList()); infos.add(privates.keyList()); infos.add(relativePath); if (dependencyCacheMap == null) { dependencyCacheMap = new HashMap<>(); } dependencyCacheMap.put(key, infos); if (cacheFile != null && cacheFile.exists()) { FileOutputStream f = new FileOutputStream(cacheFile); o = new ObjectOutputStream(f); o.writeObject(dependencyCacheMap); } } else { if (dependencyCacheMap.get(key).get(0) == null || dependencyCacheMap.get(key).get(1) == null) { dependencyCacheMap.remove(key); bundleClasspathKeys.remove(key); } } } } catch (Exception e) { e.printStackTrace(); } finally { try { if (o != null) { o.close(); } if (al != null) { al.close(); } } catch (IOException e) { e.printStackTrace(); } } return result; } private List<String> bundleClasspathKeys = new ArrayList<>(); @SuppressWarnings("unchecked") private void filterPackagesCache(Manifest manifest, Set<String> imports) { if (!ENABLE_CACHE) { bundleClasspathKeys.clear(); } Domain domain = Domain.domain(manifest); Parameters calculatedImports = domain.getImportPackage(); Parameters calculatedPrivates = domain.getPrivatePackage(); Set<String> privateNonRepetitivePackages = new HashSet<>(calculatedPrivates.keySet()); Set<String> importNonRepetitivePackages = new HashSet<>(calculatedImports.keySet()); importNonRepetitivePackages.addAll(imports); importNonRepetitivePackages = importNonRepetitivePackages.stream().map(v -> { if (!StringUtils.endsWith(v, RESOLUTION_OPTIONAL)) { return v + RESOLUTION_OPTIONAL; } return v; }).collect(Collectors.toSet()); int size = bundleClasspathKeys.size(); for (int i = 0; i < size; i++) { List<Object> infos = dependencyCacheMap.get(bundleClasspathKeys.get(i)); if (infos == null) { continue; } List<String> parameters = (List<String>) infos.get(0); importNonRepetitivePackages.addAll(parameters.stream().map(v -> { if (!StringUtils.endsWith(v, RESOLUTION_OPTIONAL)) { return v + RESOLUTION_OPTIONAL; } return v; }).collect(Collectors.toSet())); privateNonRepetitivePackages.addAll((List<String>) infos.get(1)); } importNonRepetitivePackages.remove("routines.system"); importNonRepetitivePackages.remove("routines.system" + RESOLUTION_OPTIONAL); // TESB-24730 set specific version for "javax.annotation" importNonRepetitivePackages.remove("javax.annotation"); importNonRepetitivePackages.remove("javax.annotation" + RESOLUTION_OPTIONAL); importNonRepetitivePackages.add("javax.annotation;version=\"[1.3,2)\"" + RESOLUTION_OPTIONAL); // TESB-32507 make org.talend.esb.authorization.xacml.rt.pep not optional if (importNonRepetitivePackages.contains("org.talend.esb.authorization.xacml.rt.pep" + RESOLUTION_OPTIONAL)) { importNonRepetitivePackages.remove("org.talend.esb.authorization.xacml.rt.pep" + RESOLUTION_OPTIONAL); importNonRepetitivePackages.add("org.talend.esb.authorization.xacml.rt.pep"); } Set<String> fileterdImportPackage = new HashSet<>(); for (String p : importNonRepetitivePackages) { if (!privateNonRepetitivePackages.contains(p.replace(RESOLUTION_OPTIONAL, "")) || p.startsWith("routines")) { fileterdImportPackage.add(p); } } manifest.getMainAttributes().putValue(Analyzer.PRIVATE_PACKAGE, String.join(",", privateNonRepetitivePackages)); manifest.getMainAttributes().putValue(Analyzer.IMPORT_PACKAGE, String.join(",", fileterdImportPackage)); } protected Analyzer createAnalyzer(ExportFileResource libResource, ProcessItem processItem) throws IOException { Analyzer analyzer = new Analyzer(); Jar bin = new Jar(classesLocation); analyzer.setJar(bin); final String bundleName = processItem.getProperty().getLabel(); String symbolicName = bundleName; // http://jira.talendforge.org/browse/TESB-5382 LiXiaopeng Project project = ProjectManager.getInstance().getCurrentProject(); if (project != null) { String proName = project.getLabel(); if (proName != null) { symbolicName = proName.toLowerCase() + '.' + symbolicName; } } analyzer.setProperty(Analyzer.BUNDLE_NAME, bundleName); analyzer.setProperty(Analyzer.BUNDLE_SYMBOLICNAME, symbolicName); analyzer.setProperty(Analyzer.BUNDLE_VERSION, getBundleVersion()); IBrandingService brandingService = (IBrandingService) GlobalServiceRegister.getDefault().getService( IBrandingService.class); analyzer.setProperty(Analyzer.BUNDLE_VENDOR, brandingService.getFullProductName() + " (" //$NON-NLS-1$ + brandingService.getAcronym() + '_' + RepositoryPlugin.getDefault().getBundle().getVersion().toString() + ")"); //$NON-NLS-1$ addOsgiDependencies(analyzer, libResource, processItem); final StringBuilder bundleClasspath = new StringBuilder("."); //$NON-NLS-1$ final StringBuilder bundleNativeCode = new StringBuilder(); Set<String> relativePathList = libResource.getRelativePathList(); for (String path : relativePathList) { Set<URL> resources = libResource.getResourcesByRelativePath(path); for (URL url : resources) { // TESB-21804:Fail to deploy cMessagingEndpoint with quartz component in runtime for ClassCastException String urlStr = url.getPath().replace("\\", "/"); if (urlStr.matches("(.*)camel-(.*)-alldep-(.*)$") || urlStr.matches("(.*)activemq-all-[\\d\\.]*.jar$") || urlStr.matches("(.*)/jms[\\d\\.-]*.jar$") || urlStr.matches("(.*)tdm-lib-di-[\\d\\.-]*.jar$") || urlStr.matches("(.*)dom4j-[\\d\\.-]*.jar$")) { continue; } File dependencyFile = new File(FilesUtils.getFileRealPath(url.getPath())); String relativePath = libResource.getDirectoryName() + PATH_SEPARATOR + dependencyFile.getName(); bundleClasspathKeys.add(dependencyFile.length() + dependencyFile.getName()); bundleClasspath.append(MANIFEST_ITEM_SEPARATOR).append(relativePath); // analyzer.addClasspath(new File(url.getPath())); // Add dynamic library declaration in manifest if (relativePath.toLowerCase().endsWith(DLL_FILE) || relativePath.toLowerCase().endsWith(SO_FILE)) { bundleNativeCode.append(libResource.getDirectoryName() + PATH_SEPARATOR + dependencyFile.getName()).append( OSGI_OS_CODE); } // If don't want to enable this feature just comment out if (ENABLE_CACHE && cacheManifest(url, relativePath)) { continue; } bin.putResource(relativePath, new FileResource(dependencyFile)); } } analyzer.setProperty(Analyzer.BUNDLE_CLASSPATH, bundleClasspath.toString()); // TESB-15680: Add Bundle-NativeCode in manifest if (bundleNativeCode.length() > 0) { bundleNativeCode.setLength(bundleNativeCode.length() - 1); analyzer.setProperty(Analyzer.BUNDLE_NATIVECODE, bundleNativeCode.toString()); } return analyzer; } protected void addOsgiDependencies(Analyzer analyzer, ExportFileResource libResource, ProcessItem processItem) throws IOException { analyzer.setProperty(Analyzer.EXPORT_SERVICE, "routines.system.api.TalendJob;name=" + processItem.getProperty().getLabel() + ";type=" + "job"); analyzer.setProperty(Analyzer.EXPORT_PACKAGE, getPackageName(processItem)); final Collection<String> importPackages = new HashSet<String>(); String requireBundle = null; NodeType restRequestComponent = getRESTRequestComponent(processItem); if (null != restRequestComponent) { importPackages.add("org.apache.cxf.metrics"); if (EmfModelUtils.computeCheckElementValue("EXPOSE_SWAGGER_SPEC", restRequestComponent)) { importPackages.add("org.apache.cxf.jaxrs.swagger"); } if (EmfModelUtils.computeCheckElementValue("NEED_AUTH", restRequestComponent)) { //$NON-NLS-1$ String authType = EmfModelUtils.computeTextElementValue("AUTH_TYPE", restRequestComponent); //$NON-NLS-1$ if ("BASIC".equals(authType)) { //$NON-NLS-1$ importPackages.add("org.apache.cxf.jaxrs.security"); //$NON-NLS-1$ } else if ("SAML".equals(authType)) { //$NON-NLS-1$ importPackages.add("org.apache.cxf.interceptor.security"); //$NON-NLS-1$ importPackages.add("org.apache.cxf.rs.security.saml"); //$NON-NLS-1$ if (EmfModelUtils.computeCheckElementValue("NEED_AUTHORIZATION", restRequestComponent)) { //$NON-NLS-1$ importPackages.add("org.talend.esb.authorization.xacml.rt.pep"); //$NON-NLS-1$ } } } } for (NodeType node : EmfModelUtils.getComponentsByName(processItem, "tESBConsumer")) { //$NON-NLS-1$ // https://jira.talendforge.org/browse/TESB-9574 if (requireBundle == null && EmfModelUtils.computeCheckElementValue("USE_SR", node)) { //$NON-NLS-1$ requireBundle = "tesb-xacml-rt"; //$NON-NLS-1$ } } if (ERepositoryObjectType.PROCESS_MR == ERepositoryObjectType.getItemType(processItem)) { importPackages.add("org.talend.cloud"); //$NON-NLS-1$ } if (requireBundle != null && !requireBundle.isEmpty()) { requireBundle += (", org.ops4j.pax.logging.pax-logging-api"); } else { requireBundle = "org.ops4j.pax.logging.pax-logging-api"; } if (requireBundle != null) { analyzer.setProperty(Analyzer.REQUIRE_BUNDLE, requireBundle); } StringBuilder importPackage = new StringBuilder("routines.system.api,"); //$NON-NLS-1$ for (String ip : importPackages) { importPackage.append(ip).append(','); } importPackage.append("*;resolution:=optional"); //$NON-NLS-1$ analyzer.setProperty(Analyzer.IMPORT_PACKAGE, importPackage.toString()); } protected static boolean isStudioEEVersion() { return PluginChecker.isTIS(); } @Override protected List<URL> getExternalLibraries(boolean needLibraries, ExportFileResource[] process, Set<String> neededLibraries) { if (!needLibraries) { return Collections.emptyList(); } // Lists all the needed jar files final Set<String> listModulesReallyNeeded = new HashSet<String>(neededLibraries); // jar from routines for (IRepositoryViewObject object : collectRoutines(process, getIncludeRoutinesPath())) { Item item = object.getProperty().getItem(); if (item instanceof RoutineItem) { @SuppressWarnings("unchecked") List<IMPORTType> imports = ((RoutineItem) item).getImports(); for (IMPORTType type : imports) { if (type.isREQUIRED()) { listModulesReallyNeeded.add(type.getMODULE()); } } } } return getNeededModuleURLs(listModulesReallyNeeded); } protected List<URL> getNeededModuleURLs(Set<String> neededModules) { List<URL> list = new ArrayList<URL>(); if (GlobalServiceRegister.getDefault().isServiceRegistered(IRunProcessService.class)) { IRunProcessService processService = (IRunProcessService) GlobalServiceRegister.getDefault().getService( IRunProcessService.class); IFolder libFolder = processService.getJavaProjectLibFolder(); File file = libFolder.getLocation().toFile(); File[] files = file.listFiles(FilesUtils.getAcceptModuleFilesFilter()); for (File tempFile : files) { try { if (neededModules.contains(tempFile.getName())) { list.add(tempFile.toURI().toURL()); } } catch (MalformedURLException e) { ExceptionHandler.process(e); } } } return list; } @Override public void setTopFolder(List<ExportFileResource> resourcesToExport) { return; } @Override public String getOutputSuffix() { return FileConstants.JAR_FILE_SUFFIX; } /** * Getter for requireBundleModules. * * @return the requireBundleModules */ protected MultiKeyMap getRequireBundleModules() { return this.requireBundleModules; } protected Set<ModuleNeeded> getRequireBundleModuleNeededs() { return getModuleNeededs(getRequireBundleModules()); } @Override public Set<ModuleNeeded> getExcludedModuleNeededs() { Set<ModuleNeeded> excludedModuleNeededs = super.getExcludedModuleNeededs(); excludedModuleNeededs.addAll(getRequireBundleModuleNeededs()); return excludedModuleNeededs; } @Override protected Set<String> getExcludedModuleNames() { Set<String> providedModulesSet = super.getExcludedModuleNames(); for (ModuleNeeded module : getRequireBundleModuleNeededs()) { providedModulesSet.add(module.getModuleName()); } return providedModulesSet; } @Override protected IProcess generateJobFiles(ProcessItem process, String contextName, String version, boolean statistics, boolean trace, boolean applyContextToChildren, IProgressMonitor monitor) throws ProcessorException { IDesignerCoreService service = CorePlugin.getDefault().getDesignerCoreService(); IProcess currentProcess = service.getProcessFromProcessItem(process); IProcessor processor = ProcessorUtilities.getProcessor(currentProcess, process.getProperty()); return processor.getProcess(); } private Set<String> importCompiler(IRunProcessService service, ProcessItem processItem) { Set<String> imports = new HashSet<String>(); if (processItem != null && service != null && processItem.getProperty() != null) { ITalendProcessJavaProject talendProcessJavaProject = service.getTalendJobJavaProject(processItem.getProperty()); if (talendProcessJavaProject != null) { String src = JavaResourcesHelper.getJobClassFilePath(processItem, true); IFile srcFile = talendProcessJavaProject.getSrcFolder().getFile(src); imports.addAll(importCompiler(srcFile.getLocation().toString())); // include imports from child jobs if (ERepositoryObjectType.getType(processItem.getProperty()).equals(ERepositoryObjectType.PROCESS)) { for (JobInfo subjobInfo : ProcessorUtilities.getChildrenJobInfo(processItem)) { imports.addAll(importCompiler(service, subjobInfo.getProcessItem())); } } } } return imports; } private Set<String> importCompiler(String src) { Set<String> imports = new HashSet<String>(); ByteArrayOutputStream out = new ByteArrayOutputStream(); ByteArrayOutputStream err = new ByteArrayOutputStream(); try { org.eclipse.jdt.core.compiler.batch.BatchCompiler.compile(src.concat(complianceParameter), new PrintWriter(out), new PrintWriter(err), null); String errString = new String(err.toByteArray()); String[] errBlocks = errString.split(COMPILER_LOG_DELIMITER); String reg = COMPILER_LOG_REGEX; Pattern pattern = Pattern.compile(reg); for (String errBlock : errBlocks) { String[] lines = errBlock.trim().replaceAll("\r", "").split("\n"); if (lines.length == 4) { if (lines[3].endsWith(COMPILER_LOG_ERROR_1) || lines[3].endsWith(COMPILER_LOG_ERROR_2)) { int markerPos = lines[2].indexOf('^'); Matcher m = pattern.matcher(lines[1].substring(markerPos)); if (m.find()) { if (m.groupCount() == 1 && m.group(1).indexOf('.') > 0) { imports.add(m.group(1) + RESOLUTION_OPTIONAL); } } } } } out.close(); err.close(); } catch (IOException e) { e.printStackTrace(); } return imports; } }
45.336887
157
0.626989
3ba70bdef1d4050cbf5aa5586c607f77c4a84bd1
152
package com.coolweather.app.util; public interface HttpCallbackListener { void onFinish(String response); void onError(Exception Exception); }
16.888889
39
0.776316
4446a75e11a865ba2280938a41ae91ce7932bc22
768
/* * Copyright oVirt Authors * SPDX-License-Identifier: Apache-2.0 */ package org.ovirt.engine.api.v3.adapters; import org.ovirt.engine.api.model.CustomProperty; import org.ovirt.engine.api.v3.V3Adapter; import org.ovirt.engine.api.v3.types.V3CustomProperty; public class V3CustomPropertyOutAdapter implements V3Adapter<CustomProperty, V3CustomProperty> { @Override public V3CustomProperty adapt(CustomProperty from) { V3CustomProperty to = new V3CustomProperty(); if (from.isSetName()) { to.setName(from.getName()); } if (from.isSetRegexp()) { to.setRegexp(from.getRegexp()); } if (from.isSetValue()) { to.setValue(from.getValue()); } return to; } }
27.428571
96
0.65625
26d745e86bce66e1cecf7a29f68319c2492b7a35
176
package com.example.framework.mvvm.ui.login; public interface LoginNavigator { void handleError(Throwable throwable); void login(); void openMainActivity(); }
14.666667
44
0.727273
0d4f473322ca390db447ecefe172fb3d55fbb244
3,494
package com.o3dr.services.android.lib.drone.companion.solo.tlv.mpcc; import android.os.Parcel; import com.o3dr.services.android.lib.drone.companion.solo.tlv.TLVMessageTypes; import com.o3dr.services.android.lib.drone.companion.solo.tlv.TLVPacket; import java.nio.ByteBuffer; /** * Sent by: App -> ShotManager. * Valid: Valid only in Play mode when the vehicle is attached to the Path. Ignored at other times. * This message tells ShotManager to fly the vehicle to a position along the normalized length of the Path. * The cruiseState value indicates pause/play state of the vehicle. This does not overwrite the stored cruise speed set by SOLO_SPLINE_PATH_SETTINGS. * Created by Fredia Huya-Kouadio on 12/8/15. * * @since 2.8.0 */ public class SoloSplineSeek extends TLVPacket { public static final int MESSAGE_LENGTH = 8; /** * A parametric offset along the Path normalized to (0,1) */ private float uPosition; /** * Used by the app to determine the state of the cruise play/pause buttons. * -1: Cruising to the start of the cable(negative cruise speed). * 0 : Not moving/paused (cruise speed == 0). (DEFAULT) * 1 : Cruising to the end of the cable (positive cruise speed). */ private int cruiseState; public SoloSplineSeek(float uPosition, int cruiseState){ super(TLVMessageTypes.TYPE_SOLO_SPLINE_SEEK, MESSAGE_LENGTH); this.uPosition = uPosition; this.cruiseState = cruiseState; } public SoloSplineSeek(ByteBuffer buffer){ this(buffer.getFloat(), buffer.getInt()); } @Override protected void getMessageValue(ByteBuffer valueCarrier){ valueCarrier.putFloat(uPosition); valueCarrier.putInt(cruiseState); } public float getUPosition() { return uPosition; } public int getCruiseState() { return cruiseState; } @Override public String toString() { return "SoloSplineSeek{" + "uPosition=" + uPosition + ", cruiseState=" + cruiseState + '}'; } @Override public void writeToParcel(Parcel dest, int flags) { super.writeToParcel(dest, flags); dest.writeFloat(this.uPosition); dest.writeInt(this.cruiseState); } protected SoloSplineSeek(Parcel in) { super(in); this.uPosition = in.readFloat(); this.cruiseState = in.readInt(); } public static final Creator<SoloSplineSeek> CREATOR = new Creator<SoloSplineSeek>() { public SoloSplineSeek createFromParcel(Parcel source) { return new SoloSplineSeek(source); } public SoloSplineSeek[] newArray(int size) { return new SoloSplineSeek[size]; } }; @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } if (!super.equals(o)) { return false; } SoloSplineSeek that = (SoloSplineSeek) o; if (Float.compare(that.uPosition, uPosition) != 0) { return false; } return cruiseState == that.cruiseState; } @Override public int hashCode() { int result = super.hashCode(); result = 31 * result + (uPosition != +0.0f ? Float.floatToIntBits(uPosition) : 0); result = 31 * result + cruiseState; return result; } }
29.116667
149
0.632513
b7e02d39a4853a446ee7f7f54ebbd878ba676c18
876
/** * */ package com.ppang; /** * @author ppang * */ public class TrieNode { public TrieNode[] children; public boolean hasWord; public String word; public int rank; public TrieNode() { children = new TrieNode[26]; hasWord = false; word = ""; rank = Integer.MAX_VALUE; } public void insert(String word, int rank, int idx) { if (idx==word.length()) { hasWord = true; this.rank = rank; this.word = word; return; } int pos = word.charAt(idx) - 'a'; if (children[pos]==null) { children[pos] = new TrieNode(); } children[pos].insert(word, rank, idx+1); } public TrieNode find(String word, int idx) { if (idx==word.length()) { return this; } int pos = word.charAt(idx) - 'a'; if (children[pos]==null) { return null; } return children[pos].find(word, idx+1); } }
18.638298
54
0.576484
fe4fb0dc6ad503fb5c663c79124c1be46f480478
1,407
package com.celesea.runtime.annotation; import io.swagger.annotations.ApiModel; import java.io.Serializable; import java.time.LocalDateTime; import java.util.UUID; import javax.validation.constraints.NotEmpty; import javax.validation.constraints.NotNull; import lombok.Builder; import lombok.Data; import org.springframework.http.HttpStatus; /** * ErrorResponse * * @author <a href="https://github.com/vnobo">Alex bob</a> * @date Created by 2020/7/22 */ @Data @ApiModel("Request controller error entity model") public class ErrorResponse implements Serializable { private UUID requestId; private LocalDateTime time; private String message; private int status; private Object errors; @Builder private ErrorResponse(@NotNull HttpStatus status, @NotEmpty String message, Object errors) { this.message = message; this.errors = errors; this.requestId = UUID.randomUUID(); this.time = LocalDateTime.now(); this.errors = status.value(); } public static ErrorResponse withMessage(String message) { return ErrorResponse.builder().message(message).build(); } public ErrorResponse message(String message) { this.message = message; return this; } public ErrorResponse status(HttpStatus status) { this.status = status.value(); return this; } public ErrorResponse errors(Object errors) { this.errors = errors; return this; } }
24.258621
94
0.735608
eff8368a1fb51df877540fcf00eef440d872390d
2,590
package it.algos.vaad23.backend.packages.utility.preferenza; import static it.algos.vaad23.backend.boot.VaadCost.*; import it.algos.vaad23.backend.logic.*; import org.springframework.beans.factory.annotation.*; import org.springframework.data.mongodb.repository.*; import org.springframework.stereotype.*; import java.util.*; /** * Project vaadin23 * Created by Algos * User: gac * Date: sab, 26-mar-2022 * Time: 14:02 * <p> * Service di una entityClazz specifica e di un package <br> * Garantisce i metodi di collegamento per accedere al database <br> * Non mantiene lo stato di una istanza entityBean <br> * Mantiene lo stato della entityClazz <br> * NOT annotated with @SpringComponent (inutile, esiste già @Service) <br> * NOT annotated with @Scope(ConfigurableBeanFactory.SCOPE_SINGLETON) (inutile, esiste già @Service) <br> */ @Service @Qualifier(TAG_PRE) public class PreferenzaBackend extends CrudBackend { private PreferenzaRepository repository; /** * Costruttore @Autowired (facoltativo) @Qualifier (obbligatorio) <br> * In the newest Spring release, it’s constructor does not need to be annotated with @Autowired annotation <br> * Si usa un @Qualifier(), per specificare la classe che incrementa l'interfaccia repository <br> * Si usa una costante statica, per essere sicuri di scriverla uguale a quella di xxxRepository <br> * Regola la classe di persistenza dei dati specifica e la passa al costruttore della superclasse <br> * Regola la entityClazz (final nella superclasse) associata a questo service <br> * * @param crudRepository per la persistenza dei dati */ public PreferenzaBackend(@Autowired @Qualifier(TAG_PRE) final MongoRepository crudRepository) { super(crudRepository, Preferenza.class); this.repository = (PreferenzaRepository) crudRepository; } public boolean existsById(final String idKey) { return repository.existsById(idKey); } public boolean existsByCode(final String code) { return findByCode(code) != null; } public Preferenza findByKey(final String key) { return repository.findFirstByCode(key); } public Preferenza findByCode(final String code) { List<Preferenza> lista = findAllByCode(code); if (lista != null && lista.size() == 1) { return lista.get(0); } else { return null; } } public List<Preferenza> findAllByCode(final String code) { return repository.findAllByCode(code); } }// end of crud backend class
34.533333
115
0.707336
f62f3f502ea1971123ba76490712c8c344f4a956
2,303
package com.github.ashwinikb.amazon; import com.github.ashwinikb.Configuration; import com.github.ashwinikb.DriverSetUp; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.interactions.Actions; import org.testng.annotations.BeforeClass; import org.testng.annotations.Parameters; import org.testng.annotations.Test; import java.net.MalformedURLException; public class LoginTest { private static final Logger LOG = LogManager.getLogger(LoginTest.class); public WebDriver driver; @BeforeClass(alwaysRun = true) @Parameters({"os", "browser", "url", "node"}) public void setUp(String os, String browser, String url, String node) throws MalformedURLException { DriverSetUp setupTestDriver = new DriverSetUp(os, browser, url, node); driver = setupTestDriver.getDriver(); } @Test(priority = 1) public void SignIn() { Actions action = new Actions(driver); action.moveToElement(driver.findElement(By.xpath("//*[@id=\"nav-link-accountList\"]"))).perform(); driver.findElement(By.xpath("//*[@id=\"nav-link-accountList\"]/span[1]")).click(); driver.findElement(By.id("ap_email")).sendKeys(Configuration.getConfigurationValue("amazon_login_id")); driver.findElement(By.id("ap_password")).sendKeys(Configuration.getConfigurationValue("amazon_login_password")); driver.findElement(By.id("signInSubmit")).click(); WebElement errorMessageBox = driver.findElement(By.id("auth-warning-message-box")); errorMessageBox.isDisplayed(); driver.navigate().to("https://www.amazon.com/"); Actions actions = new Actions(driver); actions.moveToElement(driver.findElement(By.xpath("//*[@id=\"nav-link-accountList\"]"))).perform(); driver.findElement(By.xpath("//*[@id=\"nav-link-accountList\"]/span[1]")).click(); driver.findElement(By.id("ap_email")).sendKeys(Configuration.getConfigurationValue("amazon_login_id")); driver.findElement(By.id("ap_password")).sendKeys(Configuration.getConfigurationValue("amazon_login_password")); driver.findElement(By.id("signInSubmit")).click(); } }
46.06
120
0.721667
121eea18649d8c41e3ccbcd4ceba7b18674af5ea
1,648
package org.nlpcn.es4sql.query; import org.durid.sql.SQLUtils; import org.durid.sql.ast.expr.SQLQueryExpr; import org.durid.sql.ast.statement.SQLDeleteStatement; import org.durid.sql.parser.SQLParserUtils; import org.durid.sql.parser.SQLStatementParser; import org.durid.util.JdbcUtils; import org.elasticsearch.client.Client; import org.nlpcn.es4sql.domain.Delete; import org.nlpcn.es4sql.domain.Select; import org.nlpcn.es4sql.exception.SqlParseException; import org.nlpcn.es4sql.parse.SqlParser; import java.sql.SQLFeatureNotSupportedException; public class ESActionFactory { /** * Create the compatible Query object * based on the SQL query. * * @param sql The SQL query. * @return Query object. */ public static QueryAction create(Client client, String sql) throws SqlParseException, SQLFeatureNotSupportedException { String firstWord = sql.substring(0, sql.indexOf(' ')); switch (firstWord.toUpperCase()) { case "SELECT": SQLQueryExpr sqlExpr = (SQLQueryExpr) SQLUtils.toMySqlExpr(sql); Select select = new SqlParser().parseSelect(sqlExpr); if (select.isAgg) { return new AggregationQueryAction(client, select); } else { return new DefaultQueryAction(client, select); } case "DELETE": SQLStatementParser parser = SQLParserUtils.createSQLStatementParser(sql, JdbcUtils.MYSQL); SQLDeleteStatement deleteStatement = parser.parseDeleteStatement(); Delete delete = new SqlParser().parseDelete(deleteStatement); return new DeleteQueryAction(client, delete); default: throw new SQLFeatureNotSupportedException(String.format("Unsupported query: %s", sql)); } } }
32.96
120
0.762743
b8bdd083ed88aab3b1a34c981d689b9d2ee7f977
139
package Eighth.Homework; public class Homework01 { public static void main(String[] args) { Num nu = new Num(1,10); } }
13.9
44
0.618705
6ecf37d0df29039ffcff930a7bb1855edd955cec
4,257
/* * Copyright 2019 Tallence AG * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tallence.core.redirects.cae.model; import com.coremedia.cap.content.Content; import com.tallence.core.redirects.helper.RedirectHelper; import com.tallence.core.redirects.model.RedirectSourceParameter; import com.tallence.core.redirects.model.RedirectTargetParameter; import com.tallence.core.redirects.model.RedirectType; import com.tallence.core.redirects.model.SourceUrlType; import edu.umd.cs.findbugs.annotations.Nullable; import org.springframework.util.StringUtils; import java.util.List; import java.util.Objects; /** * Model for a Redirect (used instead of a ContentBean in order to keep the overhead low). * Keeps only the properties required by the CAE. */ public class Redirect { public static final String NAME = "Redirect"; public static final String TARGET_LINK = "targetLink"; public static final String TARGET_URL = "targetUrl"; public static final String SOURCE_URL = "source"; private static final String SOURCE_URL_TYPE = "sourceUrlType"; private static final String REDIRECT_TYPE = "redirectType"; private final String contentId; private final SourceUrlType sourceUrlType; private final String source; private final RedirectType redirectType; private final Content target; private final String targetUrl; private final List<RedirectSourceParameter> sourceParameters; private final List<RedirectTargetParameter> targetParameters; public Redirect(Content redirect, String rootSegment) { contentId = redirect.getId(); sourceUrlType = SourceUrlType.asSourceUrlType(redirect.getString(SOURCE_URL_TYPE)); source = rootSegment + redirect.getString(SOURCE_URL); redirectType = RedirectType.asRedirectType(redirect.getString(REDIRECT_TYPE)); target = redirect.getLink(TARGET_LINK); targetUrl = redirect.getString(TARGET_URL); sourceParameters = RedirectHelper.getSourceParameters(redirect); targetParameters = RedirectHelper.getTargetParameters(redirect); } /** * @return true, if the redirect has no targetLink or targetUrl */ public boolean hasNoTarget() { return getTarget() == null && StringUtils.isEmpty(getTargetUrl()); } /** * Returns the content id of the {@link Content} (of type Redirect) backing this model. */ public String getContentId() { return contentId; } /** * Returns the {@link SourceUrlType} of the redirect. */ public SourceUrlType getSourceUrlType() { return sourceUrlType; } /** * Returns the source url of the redirect. */ public String getSource() { return source; } /** * Returns a {@link Content} to which the redirect links. */ @Nullable public Content getTarget() { return target; } /** * @return the redirects targetUrl. It should be empty, when the {@link #target} is not null */ @Nullable public String getTargetUrl() { return targetUrl; } /** * Returns the {@link RedirectType} of the redirect. */ public RedirectType getRedirectType() { return redirectType; } public List<RedirectSourceParameter> getSourceParameters() { return sourceParameters; } public List<RedirectTargetParameter> getTargetParameters() { return targetParameters; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Redirect redirect = (Redirect) o; return contentId.equals(redirect.contentId); } @Override public int hashCode() { return Objects.hash(contentId); } @Override public String toString() { return "Redirect{" + "contentId='" + contentId + '\'' + '}'; } }
29.358621
94
0.724454
d87b01557edf923dd9f573dead75de89c96c315e
7,577
/* * Copyright (c) Octopus Deploy and contributors. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use * these files 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 octopus.teamcity.server.generic; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import jetbrains.buildServer.serverSide.InvalidProperty; import octopus.teamcity.common.buildinfo.BuildInfoPropertyNames; import octopus.teamcity.common.commonstep.CommonStepPropertyNames; import org.junit.jupiter.api.Test; /** * It should be noted that when TeamCity constructs a Properties Map, it removes leading whitespace * thus, a Server URL of " " - will be reduced to an empty string, which is then reduced to a * null/missing entry */ class OctopusBuildStepPropertiesProcessorTest { private Map<String, String> createValidPropertyMap() { final Map<String, String> result = new HashMap<>(); result.put(CommonStepPropertyNames.SERVER_URL, "http://localhost:8065"); result.put(CommonStepPropertyNames.API_KEY, "API-123456789012345678901234567890"); result.put(CommonStepPropertyNames.SPACE_NAME, "My Space"); result.put(CommonStepPropertyNames.PROXY_REQUIRED, "true"); result.put(CommonStepPropertyNames.PROXY_URL, "http://proxy.url"); result.put(CommonStepPropertyNames.PROXY_USERNAME, "ProxyUsername"); result.put(CommonStepPropertyNames.PROXY_PASSWORD, "ProxyPassword"); result.put(CommonStepPropertyNames.STEP_TYPE, new BuildInformationStep().getName()); result.put(CommonStepPropertyNames.VERBOSE_LOGGING, "false"); result.put(BuildInfoPropertyNames.PACKAGE_IDS, "Package1\nPackage2"); result.put(BuildInfoPropertyNames.PACKAGE_VERSION, "1.0"); result.put(BuildInfoPropertyNames.OVERWRITE_MODE, "OverwriteExisting"); return result; } @Test public void aValidInputMapProducesNoInvalidEntries() { final OctopusBuildStepPropertiesProcessor processor = new OctopusBuildStepPropertiesProcessor(); final Map<String, String> inputMap = createValidPropertyMap(); assertThat(processor.process(inputMap)).hasSize(0); } @Test public void anEmptyListThrowsException() { final OctopusBuildStepPropertiesProcessor processor = new OctopusBuildStepPropertiesProcessor(); assertThatThrownBy(() -> processor.process(null)).isInstanceOf(IllegalArgumentException.class); } @Test public void missingStepTypeFieldThrowsIllegalArgumentException() { final OctopusBuildStepPropertiesProcessor processor = new OctopusBuildStepPropertiesProcessor(); final Map<String, String> inputMap = createValidPropertyMap(); inputMap.remove(CommonStepPropertyNames.STEP_TYPE); assertThatThrownBy(() -> processor.process(inputMap)) .isInstanceOf(IllegalArgumentException.class); } @Test public void stepTypeWhichDoesNotAlignWithAvailableBuildProcessesThrowsIllegalArgument() { final OctopusBuildStepPropertiesProcessor processor = new OctopusBuildStepPropertiesProcessor(); final Map<String, String> inputMap = createValidPropertyMap(); inputMap.put(CommonStepPropertyNames.STEP_TYPE, "invalid-step-type"); assertThatThrownBy(() -> processor.process(inputMap)) .isInstanceOf(IllegalArgumentException.class); } @Test public void mandatoryFieldsMustBePopulated() { final OctopusBuildStepPropertiesProcessor processor = new OctopusBuildStepPropertiesProcessor(); final Map<String, String> inputMap = createValidPropertyMap(); inputMap.remove(CommonStepPropertyNames.SERVER_URL); inputMap.remove(CommonStepPropertyNames.API_KEY); final List<InvalidProperty> result = processor.process(inputMap); assertThat(result).hasSize(2); final List<String> missingPropertyNames = result.stream().map(InvalidProperty::getPropertyName).collect(Collectors.toList()); assertThat(missingPropertyNames) .containsExactlyInAnyOrder( CommonStepPropertyNames.SERVER_URL, CommonStepPropertyNames.API_KEY); } @Test public void illegallyFormattedServerUrlReturnsASingleInvalidProperty() { final OctopusBuildStepPropertiesProcessor processor = new OctopusBuildStepPropertiesProcessor(); final Map<String, String> inputMap = createValidPropertyMap(); inputMap.put(CommonStepPropertyNames.SERVER_URL, "badUrl"); final List<InvalidProperty> result = processor.process(inputMap); assertThat(result).hasSize(1); assertThat(result.get(0).getPropertyName()).isEqualTo(CommonStepPropertyNames.SERVER_URL); } @Test public void illegallyFormattedApiKeyReturnsASingleInvalidProperty() { final OctopusBuildStepPropertiesProcessor processor = new OctopusBuildStepPropertiesProcessor(); final Map<String, String> inputMap = createValidPropertyMap(); inputMap.put(CommonStepPropertyNames.API_KEY, "API-1"); final List<InvalidProperty> result = processor.process(inputMap); assertThat(result).hasSize(1); assertThat(result.get(0).getPropertyName()).isEqualTo(CommonStepPropertyNames.API_KEY); } @Test public void spaceNameCanBeNull() { // Implies the default space should be used final OctopusBuildStepPropertiesProcessor processor = new OctopusBuildStepPropertiesProcessor(); final Map<String, String> inputMap = createValidPropertyMap(); inputMap.remove(CommonStepPropertyNames.SPACE_NAME); final List<InvalidProperty> result = processor.process(inputMap); assertThat(result).hasSize(0); } @Test public void proxyUsernameAndPasswordCanBothBeNull() { final OctopusBuildStepPropertiesProcessor processor = new OctopusBuildStepPropertiesProcessor(); final Map<String, String> inputMap = createValidPropertyMap(); inputMap.remove(CommonStepPropertyNames.PROXY_PASSWORD); inputMap.remove(CommonStepPropertyNames.PROXY_USERNAME); final List<InvalidProperty> result = processor.process(inputMap); assertThat(result).hasSize(0); } @Test public void invalidPropertyIsReturnedIfProxyPasswordIsSetWithoutUsername() { final OctopusBuildStepPropertiesProcessor processor = new OctopusBuildStepPropertiesProcessor(); final Map<String, String> inputMap = createValidPropertyMap(); inputMap.remove(CommonStepPropertyNames.PROXY_USERNAME); final List<InvalidProperty> result = processor.process(inputMap); assertThat(result).hasSize(1); assertThat(result.get(0).getPropertyName()).isEqualTo(CommonStepPropertyNames.PROXY_USERNAME); } @Test public void invalidPropertyIsReturnedIfProxyUsernameIsSetWithoutPassword() { final OctopusBuildStepPropertiesProcessor processor = new OctopusBuildStepPropertiesProcessor(); final Map<String, String> inputMap = createValidPropertyMap(); inputMap.remove(CommonStepPropertyNames.PROXY_PASSWORD); final List<InvalidProperty> result = processor.process(inputMap); assertThat(result).hasSize(1); assertThat(result.get(0).getPropertyName()).isEqualTo(CommonStepPropertyNames.PROXY_PASSWORD); } }
43.545977
100
0.784215
9791a021ef0fd88a529e7a561f17989958ffd267
2,398
package com.douglas.cursomc.domain; import java.io.Serializable; import java.util.Objects; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Entity; /** * Categoria das cidades. * Classe responsável por representar as Cidades que * serão persistidas no banco de dados. * Nome da Tabela no Banco de Dados: cidade. * Atributos: * id : Integer (Gerado automaticamente pelo banco) * nome : String * Metodos: Getters and Setters, HashCode e Equals. * Relacionamentos: estado: OneToMany, Muitas Cidades percetencem á um Estado; * * @see Produto * @author douglas eleuterio * @version 0.2.0 */ @Entity(name = "cidade") public class Cidade implements Serializable { private static final long servialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; private String nome; /** * Relacionamento entre Cidade e Estado. Tipo de Relacionamento: ManyToOne, * Muitas Cidades percetencem á um Estado. * Coluna de assciação: "estado_id" */ @ManyToOne @JoinColumn(name = "estado_id") private Estado estado; public Cidade() { } public Cidade(Integer id, String nome, Estado estado) { this.id = id; this.nome = nome; this.estado = estado; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public Estado getEstado() { return estado; } public void setEstado(Estado estado) { this.estado = estado; } @Override public int hashCode() { int hash = 7; hash = 89 * hash + Objects.hashCode(this.id); return hash; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Cidade other = (Cidade) obj; if (!Objects.equals(this.id, other.id)) { return false; } return true; } }
22.838095
79
0.619683
9ae781166e504b973f9da6b1a9379865b3c4c523
2,090
/******************************************************************************* * MoonLight: a light-weight framework for runtime monitoring * Copyright (C) 2018 * * See the NOTICE file distributed with this work for additional information * regarding copyright ownership. * * 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 eu.quanticol.moonlight.formula; import eu.quanticol.moonlight.signal.DataHandler; import java.util.function.BiFunction; public interface SignalDomain<R> extends Semiring<R> { R negation(R x); boolean equalTo(R x, R y); public default R implies(R x, R y) { return disjunction(negation(x), y); } R valueOf(boolean b); R valueOf(double v); default R valueOf(int v) { return valueOf((double) v); } R computeLessThan(double v1, double v2); R computeLessOrEqualThan(double v1, double v2); R computeEqualTo(double v1, double v2); R computeGreaterThan(double v1, double v2); R computeGreaterOrEqualThan(double v1, double v2); DataHandler<R> getDataHandler(); static <S> BiFunction<Double, Double,S> getOperator(SignalDomain<S> domain, String op) { if ("<".equals(op)) { return domain::computeLessThan; } if ("<=".equals(op)) { return domain::computeLessOrEqualThan; } if ("==".equals(op)) { return domain::computeEqualTo; } if (">=".equals(op)) { return domain::computeGreaterOrEqualThan; } if (">".equals(op)) { return domain::computeGreaterThan; } return (x,y) -> domain.min(); } }
27.5
89
0.654545
658ad978114e9f8f5bd8cd1fa0e872dfa4b02937
968
package com.salmon.TO; import javax.persistence.*; import java.io.Serializable; /** * Created by Aprin on 1/20/2019. */ @Entity(name = "Ant") @Table(name = "ANT") public class Annotation implements Serializable { @Id @SequenceGenerator(name = "ANT_SEQ",sequenceName = "ANT_SEQ") @GeneratedValue(strategy = GenerationType.AUTO,generator = "ANT_SEQ") private long id; @Column(name = "LINK",columnDefinition = "CHAR(100)") private String link; @Column(name = "ANNOTATE",columnDefinition = "CHAR(700000)") private String annotate; public long getId() { return id; } public void setId(long id) { this.id = id; } public String getLink() { return link; } public void setLink(String link) { this.link = link; } public String getAnnotate() { return annotate; } public void setAnnotate(String annotate) { this.annotate = annotate; } }
19.755102
73
0.623967
986f037f68608013ed9b3718755e5c858ee2318f
2,349
package com.braintreepayments.api.dropin.adapters; import android.content.Context; import com.braintreepayments.api.dropin.DropInRequest; import com.braintreepayments.api.dropin.utils.PaymentMethodType; import com.braintreepayments.api.models.CardNonce; import com.braintreepayments.api.models.Configuration; import com.braintreepayments.api.models.GooglePaymentCardNonce; import com.braintreepayments.api.models.PayPalAccountNonce; import com.braintreepayments.api.models.PaymentMethodNonce; import com.braintreepayments.api.models.VenmoAccountNonce; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; class AvailablePaymentMethodNonceList { final private List<PaymentMethodNonce> items; AvailablePaymentMethodNonceList(Context context, Configuration configuration, List<PaymentMethodNonce> paymentMethodNonces, DropInRequest dropInRequest, boolean googlePayEnabled) { items = new ArrayList<>(); for (PaymentMethodNonce paymentMethodNonce: paymentMethodNonces) { boolean shouldAddPaymentMethod = false; if (paymentMethodNonce instanceof PayPalAccountNonce) { shouldAddPaymentMethod = dropInRequest.isPayPalEnabled() && configuration.isPayPalEnabled(); } else if (paymentMethodNonce instanceof VenmoAccountNonce) { shouldAddPaymentMethod = dropInRequest.isVenmoEnabled() && configuration.getPayWithVenmo().isEnabled(context); } else if (paymentMethodNonce instanceof CardNonce) { shouldAddPaymentMethod = dropInRequest.isCardEnabled() && !configuration.getCardConfiguration().getSupportedCardTypes().isEmpty(); } else if (paymentMethodNonce instanceof GooglePaymentCardNonce) { shouldAddPaymentMethod = googlePayEnabled && dropInRequest.isGooglePaymentEnabled(); } if (shouldAddPaymentMethod) { items.add(paymentMethodNonce); } } } int size() { return items.size(); } PaymentMethodNonce get(int index) { return items.get(index); } public boolean hasCardNonce() { for (PaymentMethodNonce nonce : items) { if (nonce instanceof CardNonce) { return true; } } return false; } }
37.887097
184
0.715624
a0d4738c55ec139aa8ad2003c6c6ae7f45a7e3d9
3,894
package eu.monnetproject.ontology.owlapi; import eu.monnetproject.ontology.*; import eu.monnetproject.ontology.Class; import org.semanticweb.owlapi.model.*; import java.util.*; public class OWLAPIClass extends OWLAPIEntity implements Class { final OWLClassExpression clazz; public OWLAPIClass(OWLClassExpression wrapped,OWLOntology onto) { super(onto); clazz = wrapped; } protected OWLClass cl() { if(clazz instanceof OWLClass) { return (OWLClass)clazz; } else { throw new RuntimeException("Class is a restriction"); } } protected OWLEntity entity() { return cl(); } public Collection<Class> getSubClassOf() { return convertC(cl().getSubClasses(onto)); } public boolean addSubClassOf(Class clazz2) { return isChange(manager.addAxiom(onto, factory.getOWLSubClassOfAxiom(clazz,convert(clazz2)))); } public boolean removeSubClassOf(Class clazz2) { return isChange(manager.removeAxiom(onto, factory.getOWLSubClassOfAxiom(clazz,convert(clazz2)))); } public Collection<Class> getSuperClassOf() { return convertC(cl().getSuperClasses(onto)); } public Collection<Class> getEquivalentClass() { return convertC(cl().getEquivalentClasses(onto)); } public boolean addEquivalentClass(Class clazz2) { return isChange(manager.addAxiom(onto, factory.getOWLEquivalentClassesAxiom(clazz,convert(clazz2)))); } public boolean removeEquivalentClass(Class clazz2) { return isChange(manager.removeAxiom(onto, factory.getOWLEquivalentClassesAxiom(clazz,convert(clazz2)))); } public Collection<Class> getDisjointWith() { return convertC(cl().getDisjointClasses(onto)); } public boolean addDisjointWith(Class clazz2) { return isChange(manager.addAxiom(onto, factory.getOWLDisjointClassesAxiom(clazz,convert(clazz2)))); } public boolean removeDisjointWith(Class clazz2) { return isChange(manager.addAxiom(onto, factory.getOWLDisjointClassesAxiom(clazz,convert(clazz2)))); } /** * Inverse of Individual.getType */ public Collection<Individual> getIsTypeOf() { return convertI(cl().getIndividuals(onto)); } /** * Inverse of Property.getDomain */ public Collection<Property> getIsDomainOf() { Set<Property> rval = new HashSet<Property>(); for (OWLDataProperty oWLDataProperty : this.onto.getDataPropertiesInSignature()) { for (OWLClassExpression oWLClassExpression : oWLDataProperty.getDomains(onto)) { if(oWLClassExpression.equals(clazz)) { rval.add(new OWLAPIDatatypeProperty(oWLDataProperty, onto)); } } } for (OWLObjectProperty oWLObjectProperty : this.onto.getObjectPropertiesInSignature()) { for (OWLClassExpression oWLClassExpression : oWLObjectProperty.getDomains(onto)) { if(oWLClassExpression.equals(clazz)) { rval.add(new OWLAPIObjectProperty(oWLObjectProperty, onto)); } } } return Collections.unmodifiableSet(rval); } /** * Inverse ofObjectProperty.getRange */ public Collection<ObjectProperty> getIsRangeOf() { Set<ObjectProperty> rval = new HashSet<ObjectProperty>(); for (OWLObjectProperty oWLObjectProperty : this.onto.getObjectPropertiesInSignature()) { for (OWLClassExpression oWLClassExpression : oWLObjectProperty.getRanges(onto)) { if(oWLClassExpression.equals(clazz)) { rval.add(new OWLAPIObjectProperty(oWLObjectProperty, onto)); } } } return Collections.unmodifiableSet(rval); } }
33.568966
101
0.653056
ee45e217c3c80a0ce5eb039e997c55cb7a5a534b
2,200
package org.trefoil.pat.entity; import java.util.Date; public class Period { private Integer sid; private Integer projectsid; private String sequence; private String iterationname; private Date starttime; private Date endtime; private Integer createdBy; private Date createdDt; private Integer updatedBy; private Date updatedDt; private Integer version; public Integer getSid() { return sid; } public void setSid(Integer sid) { this.sid = sid; } public Integer getProjectsid() { return projectsid; } public void setProjectsid(Integer projectsid) { this.projectsid = projectsid; } public String getSequence() { return sequence; } public void setSequence(String sequence) { this.sequence = sequence == null ? null : sequence.trim(); } public String getIterationname() { return iterationname; } public void setIterationname(String iterationname) { this.iterationname = iterationname == null ? null : iterationname.trim(); } public Date getStarttime() { return starttime; } public void setStarttime(Date starttime) { this.starttime = starttime; } public Date getEndtime() { return endtime; } public void setEndtime(Date endtime) { this.endtime = endtime; } public Integer getCreatedBy() { return createdBy; } public void setCreatedBy(Integer createdBy) { this.createdBy = createdBy; } public Date getCreatedDt() { return createdDt; } public void setCreatedDt(Date createdDt) { this.createdDt = createdDt; } public Integer getUpdatedBy() { return updatedBy; } public void setUpdatedBy(Integer updatedBy) { this.updatedBy = updatedBy; } public Date getUpdatedDt() { return updatedDt; } public void setUpdatedDt(Date updatedDt) { this.updatedDt = updatedDt; } public Integer getVersion() { return version; } public void setVersion(Integer version) { this.version = version; } }
19.130435
81
0.625
418f57a8cf4cfe8954f47582da4e07efb892ec0b
5,749
package com.dnastack.ga4gh.dataconnect.adapter.security; import com.dnastack.ga4gh.dataconnect.adapter.security.AuthConfig.OauthClientConfig; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.IOException; import java.time.Instant; import java.util.Base64; import lombok.extern.slf4j.Slf4j; import okhttp3.Call; import okhttp3.FormBody; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import okhttp3.ResponseBody; @Slf4j @SuppressWarnings("Duplicates") public class ServiceAccountAuthenticator { private final static Long TOKEN_BUFFER = 60L; private final String clientId; private final String clientSecret; private final String scopes; private final String resource; private final String audience; private final String tokenEndpoint; private final boolean shouldAuthenticate; private AuthTokenResponse tokenResponse; private Long tokenRetrievedAt = 0L; public ServiceAccountAuthenticator(OauthClientConfig config) { this.clientId = config.getClientId(); this.clientSecret = config.getClientSecret(); this.scopes = config.getScopes(); this.resource = config.getResource(); this.audience = config.getAudience(); this.tokenEndpoint = config.getTokenUri(); this.shouldAuthenticate = true; refreshAccessToken(); } public ServiceAccountAuthenticator() { this.clientId = null; this.clientSecret = null; this.scopes = null; this.resource = null; this.audience = null; this.tokenEndpoint = null; this.shouldAuthenticate = false; } public boolean requiresAuthentication() { return shouldAuthenticate; } public String getAccessToken() { long now = Instant.now().getEpochSecond(); if (tokenResponse == null) { refreshAccessToken(); } else if (tokenResponse.getExpiresIn() != null && now > (tokenRetrievedAt + tokenResponse.getExpiresIn() - TOKEN_BUFFER)) { log.info("Access token has expired, or will be expiring within the buffer window. Refreshing token now"); refreshAccessToken(); } else if (tokenResponse.getExpiresIn() == null) { log.info("Token response does not have any expiry information. Optimistically assuming token is valid"); } return tokenResponse.getAccessToken(); } public void refreshAccessToken() { try { tokenResponse = authorizeServiceAndRetrieveAccessToken(); tokenRetrievedAt = Instant.now().getEpochSecond(); log.info("Successfully retrieved access token"); } catch (IOException e) { throw new ServiceAccountAuthenticationException( "Encountered error while authenticating service account: " + e.getMessage(), e); } } private AuthTokenResponse authorizeServiceAndRetrieveAccessToken() throws IOException { log.info("Retrieving access token with client={} aud={} scopes={} from {}", clientId, audience, scopes, tokenEndpoint); String combinedClientCredentials = clientId + ":" + clientSecret; String encodedClientCredentials = "Basic " + Base64.getEncoder().encodeToString(combinedClientCredentials.getBytes()); FormBody.Builder formBodyBuilder = new FormBody.Builder().add("grant_type", "client_credentials"); if (audience != null && !audience.isEmpty()) { formBodyBuilder.add("audience", audience); } if (scopes != null && !scopes.isEmpty()) { formBodyBuilder.add("scope", scopes); } formBodyBuilder.add("client_id", clientId); formBodyBuilder.add("client_secret", clientSecret); Request request = new Request.Builder() .url(tokenEndpoint) .method("POST", formBodyBuilder.build()) .header("Authorization", encodedClientCredentials) .build(); return executeRequest(request); } private AuthTokenResponse executeRequest(Request request) throws IOException { OkHttpClient httpClient = new OkHttpClient(); log.info(">>> {} {}", request.method(), request.url()); Call call = httpClient.newCall(request); try (Response response = call.execute()) { log.info("<<< {} ({}ms)", response.code(), response.receivedResponseAtMillis() - response.sentRequestAtMillis()); ResponseBody body = response.body(); if (response.isSuccessful() && body != null) { ObjectMapper mapper = new ObjectMapper(); String bodyString = body.string(); JsonNode node = mapper.readTree(bodyString); if (node.has("access_token")) { return mapper.readValue(bodyString, AuthTokenResponse.class); } else { throw new IOException("Received successful status code but could not read access_token, property does not exist in body"); } } else if (response.isSuccessful()) { throw new IOException("Received successful status code but could not read access_token, response does not have a body"); } else { String message; if (body != null) { message = body.string(); } else { message = response.message(); } throw new ServiceAccountAuthenticationException( "Could not authenticate service account, statusCode=" + response.code() + ", message=" + message); } } } }
40.77305
142
0.641677
ec40214e4becfa2383a3362cae6884517258110c
857
package com.pay.aphrodite.core.service.impl; import com.pay.aphrodite.core.dao.hive.HqlExecuteDao; import com.pay.aphrodite.core.service.HqlExecuteService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; import java.util.Map; /** * @ClassName:HqlExecuteServiceImpl * @Author: yangyang.wang * @Date: 2018-04-21 15:48 * @Version: 1.0 * @Description: 执行HQL业务类 调用 hql 进行数据查询 和 下载数据到本地的操作 **/ @Service public class HqlExecuteServiceImpl implements HqlExecuteService { @Autowired private HqlExecuteDao hqlExecuteDao; @Override public List<Map<String, String>> select(String hql){ return hqlExecuteDao.select(hql); } @Override public void download(String hql,String localPath){ hqlExecuteDao.load(hql,localPath); } }
23.805556
65
0.745624
a1248e78b7e190b330de45c58330bac9c224c829
626
package pl.coderslab.spring01hibernate.validation; import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; import java.time.LocalDate; public class IsOverXYOValidator implements ConstraintValidator<IsOverXYO, Integer> { private int minimumAge; @Override public void initialize(IsOverXYO constraintAnnotation) { this.minimumAge = constraintAnnotation.value(); } @Override public boolean isValid(Integer value, ConstraintValidatorContext context) { return (LocalDate.now().getYear() - value) > this.minimumAge; } }
28.454545
79
0.738019
0d387437f79a66a27ad75be793ef561e09a3291c
432
package com.joe.easysocket.client.ext; /** * 序列化器 * * @author joe */ public interface Serializer { /** * 序列化对象 * * @param obj 要序列化的对象,不能为null * @return 序列化后的数据 */ byte[] write(Object obj); /** * 反序列化对象 * * @param data 对象数据,不能为null * @param clazz 对象的Class,不能为null * @param <T> 对象类型 * @return 反序列化得到的对象 */ <T> T read(byte[] data, Class<T> clazz); }
16
44
0.530093
91d426bce924731faf527ee1368b81ce1f8c146f
5,567
/* * Copyright (c) 2020 SAP SE or an SAP affiliate company. All rights reserved. */ package de.hybris.platform.sap.sapcpiorderexchange.service.impl; import de.hybris.platform.sap.core.configuration.global.dao.SAPGlobalConfigurationDAO; import de.hybris.platform.sap.sapcpiorderexchange.exceptions.SapCpiOmmOrderConversionServiceException; import de.hybris.platform.sap.sapcpiorderexchange.service.SapCpiOrderDestinationService; import de.hybris.platform.sap.sapmodel.enums.SapSystemType; import de.hybris.platform.sap.sapmodel.model.SAPLogicalSystemModel; import de.hybris.platform.sap.sapmodel.services.SapPlantLogSysOrgService; import de.hybris.platform.servicelayer.search.FlexibleSearchQuery; import de.hybris.platform.servicelayer.search.FlexibleSearchService; import de.hybris.platform.store.BaseStoreModel; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Objects; import java.util.Set; /** * Determine which SAP Logical Backend to send OMM Order data to. */ public class SapCpiOmmOrderDestinationService implements SapCpiOrderDestinationService { private static final Logger LOG = LoggerFactory.getLogger(SapCpiOmmOrderDestinationService.class); private final static String SAP_CLIENT = "sap-client="; private static final String IDOC = "/sap/bc/srt/idoc"; private static final String SOAP = "/sap/bc/srt/scs/sap"; private SAPGlobalConfigurationDAO sapCoreSAPGlobalConfigurationDAO; private SapPlantLogSysOrgService sapPlantLogSysOrgService; private FlexibleSearchService flexibleSearchService; @Override public SAPLogicalSystemModel readSapLogicalSystem() { final Set<SAPLogicalSystemModel> logicalSystems = getSapCoreSAPGlobalConfigurationDAO().getSAPGlobalConfiguration().getSapLogicalSystemGlobalConfig(); Objects.requireNonNull(logicalSystems, "No logical system is maintained in back-office for order replication to SCPI!"); return logicalSystems.stream() .filter(ls -> ls.isDefaultLogicalSystem()) .findFirst() .orElseThrow(() -> new SapCpiOmmOrderConversionServiceException("No logical system is maintained in back-office for OMM order replication to SCPI!")); } @Override public SAPLogicalSystemModel readSapLogicalSystem(String sapLogicalSystemName) { final FlexibleSearchQuery flexibleSearchQuery = new FlexibleSearchQuery("SELECT {o:pk} FROM {SAPLogicalSystem AS o} WHERE { o.sapLogicalSystemName} = ?sapLogicalSystemName"); flexibleSearchQuery.addQueryParameter("sapLogicalSystemName", sapLogicalSystemName); final SAPLogicalSystemModel sapLogicalSystem = getFlexibleSearchService().searchUnique(flexibleSearchQuery); if (sapLogicalSystem == null) { throw new SapCpiOmmOrderConversionServiceException("No logical system is maintained in back-office for OMS order cancellation replication to SCPI!"); } return sapLogicalSystem; } @Override public SAPLogicalSystemModel readSapLogicalSystem(BaseStoreModel baseStoreModel, String plantCode) { SAPLogicalSystemModel sapLogicalSystemForPlant = getSapPlantLogSysOrgService().getSapLogicalSystemForPlant(baseStoreModel, plantCode); Objects.requireNonNull(sapLogicalSystemForPlant.getSapHTTPDestination(), "No Logical system is maintained in back-office for OMS order replication to SCPI!"); return sapLogicalSystemForPlant; } @Override public String determineUrlDestination(SAPLogicalSystemModel sapLogicalSystem) { final String targetURL = sapLogicalSystem.getSapHTTPDestination().getTargetURL(); // SAP ERP if (SapSystemType.SAP_ERP.equals(sapLogicalSystem.getSapSystemType()) && targetURL.contains(SOAP)) { final String idocURL = targetURL.replace(SOAP, IDOC); LOG.info("Convert the URL destination from SOAP [{}] to IDoc [{}]!", targetURL, idocURL); return targetURL.replace(SOAP, IDOC); } else { // SAP S/4HANA or SAP S/4HANA CE return targetURL; } } @Override public String extractSapClient(SAPLogicalSystemModel sapLogicalSystem) { final int TARGET_URL_PIECES = 2; final int SYSTEM_PREFIX = 3; final String targetURL = determineUrlDestination(sapLogicalSystem); final String[] sapClientSplit = targetURL.split(SAP_CLIENT); if (sapClientSplit.length == TARGET_URL_PIECES && StringUtils.isNotBlank(sapClientSplit[1]) && sapClientSplit[1].strip().matches("\\d\\d\\d")) { return sapClientSplit[1].strip().substring(0, SYSTEM_PREFIX); } else { throw new SapCpiOmmOrderConversionServiceException(String.format("The HTTP destination [%s] does not maintain sap-client properly for order IDoc destination!", targetURL)); } } protected SAPGlobalConfigurationDAO getSapCoreSAPGlobalConfigurationDAO() { return sapCoreSAPGlobalConfigurationDAO; } public void setSapCoreSAPGlobalConfigurationDAO(SAPGlobalConfigurationDAO sapCoreSAPGlobalConfigurationDAO) { this.sapCoreSAPGlobalConfigurationDAO = sapCoreSAPGlobalConfigurationDAO; } protected SapPlantLogSysOrgService getSapPlantLogSysOrgService() { return sapPlantLogSysOrgService; } public void setSapPlantLogSysOrgService(SapPlantLogSysOrgService sapPlantLogSysOrgService) { this.sapPlantLogSysOrgService = sapPlantLogSysOrgService; } public FlexibleSearchService getFlexibleSearchService() { return flexibleSearchService; } public void setFlexibleSearchService(FlexibleSearchService flexibleSearchService) { this.flexibleSearchService = flexibleSearchService; } }
39.204225
178
0.791629
62922e45a4e40c22aeadc7540e44d5fa12b0e92d
812
package utils; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import org.json.JSONArray; public class MotionPlayer { private static final Object lock = new Object(); private static final ExecutorService service = Executors.newSingleThreadExecutor(); private static Future<?> future; public static void play(JSONArray array) { synchronized (lock) { future = service.submit(new MotionExecutorThread(array)); } } public static void play(String text) { synchronized (lock) { JSONArray array = new JSONArray(text); play(array); } } public static void play(byte[] bytes) { synchronized (lock) { String text = new String(bytes); play(text); } } public static void stop() { future.cancel(true); } }
20.820513
84
0.724138
2ea6a0dcd94573af5718d660ec71108e0ef07b15
901
package com.github.damianwajser.model; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; import com.github.damianwajser.utils.ReflectionUtils; @JsonAutoDetect(fieldVisibility = Visibility.ANY) public class QueryString { private List<Parameters> params = new ArrayList<>(); public QueryString(Method m) { this.params = ReflectionUtils.getQueryString(m); } public QueryString() { } public String toString() { StringBuilder pathVariable = new StringBuilder(); params.forEach(r -> { if (pathVariable.length() > 0) { pathVariable.append("&"); } pathVariable.append(r.getName() + "={" + r.getType() + "}"); }); return pathVariable.toString(); } public List<Parameters> getParams() { return this.params; } }
23.102564
66
0.73141
118fa87e36add6e1e1c6c1cd2453a9adcccbbfb8
298
package api.wynn.structs; public class ForumId { private String username; private String ign; private int id; public String getUsername() { return username; } public String getIgn() { return ign; } public int getId() { return id; } }
14.9
33
0.583893
a3cc20d693ae70659cb5c68d5d937aaf6336664f
677
package net.n2oapp.security.admin; import net.n2oapp.security.admin.api.service.UserDetailsService; import net.n2oapp.security.admin.rest.api.UserDetailsRestService; import net.n2oapp.security.admin.rest.impl.UserDetailsRestServiceImpl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class AdminBackendConfiguration { @Autowired UserDetailsService userDetailsService; @Bean public UserDetailsRestService UserDetailsRestService() { return new UserDetailsRestServiceImpl(userDetailsService); } }
32.238095
70
0.825702
bbec6b7dcddf7a3114ba7ba28c21cf0e7ca7e139
12,437
package org.openobservatory.ooniprobe.activity; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import androidx.annotation.Nullable; import androidx.appcompat.app.ActionBar; import androidx.appcompat.widget.Toolbar; import androidx.coordinatorlayout.widget.CoordinatorLayout; import androidx.fragment.app.Fragment; import com.google.android.material.snackbar.Snackbar; import com.google.gson.GsonBuilder; import com.google.gson.JsonParser; import com.raizlabs.android.dbflow.sql.language.SQLite; import org.apache.commons.io.FileUtils; import org.openobservatory.ooniprobe.R; import org.openobservatory.ooniprobe.common.MKCollectorResubmitTask; import org.openobservatory.ooniprobe.fragment.measurement.DashFragment; import org.openobservatory.ooniprobe.fragment.measurement.FacebookMessengerFragment; import org.openobservatory.ooniprobe.fragment.measurement.FailedFragment; import org.openobservatory.ooniprobe.fragment.measurement.HeaderNdtFragment; import org.openobservatory.ooniprobe.fragment.measurement.HeaderOutcomeFragment; import org.openobservatory.ooniprobe.fragment.measurement.HttpHeaderFieldManipulationFragment; import org.openobservatory.ooniprobe.fragment.measurement.HttpInvalidRequestLineFragment; import org.openobservatory.ooniprobe.fragment.measurement.NdtFragment; import org.openobservatory.ooniprobe.fragment.measurement.TelegramFragment; import org.openobservatory.ooniprobe.fragment.measurement.WebConnectivityFragment; import org.openobservatory.ooniprobe.fragment.measurement.WhatsappFragment; import org.openobservatory.ooniprobe.fragment.resultHeader.ResultHeaderDetailFragment; import org.openobservatory.ooniprobe.model.database.Measurement; import org.openobservatory.ooniprobe.model.database.Measurement_Table; import org.openobservatory.ooniprobe.test.suite.PerformanceSuite; import org.openobservatory.ooniprobe.test.test.Dash; import org.openobservatory.ooniprobe.test.test.FacebookMessenger; import org.openobservatory.ooniprobe.test.test.HttpHeaderFieldManipulation; import org.openobservatory.ooniprobe.test.test.HttpInvalidRequestLine; import org.openobservatory.ooniprobe.test.test.Ndt; import org.openobservatory.ooniprobe.test.test.Telegram; import org.openobservatory.ooniprobe.test.test.WebConnectivity; import org.openobservatory.ooniprobe.test.test.Whatsapp; import java.io.File; import java.nio.charset.StandardCharsets; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; public class MeasurementDetailActivity extends AbstractActivity { private static final String ID = "id"; @BindView(R.id.coordinatorLayout) CoordinatorLayout coordinatorLayout; @BindView(R.id.toolbar) Toolbar toolbar; private Measurement measurement; private Snackbar snackbar; public static Intent newIntent(Context context, int id) { return new Intent(context, MeasurementDetailActivity.class).putExtra(ID, id); } @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); measurement = SQLite.select().from(Measurement.class) .where(Measurement_Table.id.eq(getIntent().getIntExtra(ID, 0))).querySingle(); assert measurement != null; measurement.result.load(); setTheme(measurement.is_failed ? R.style.Theme_MaterialComponents_Light_DarkActionBar_App_NoActionBar_Failed : measurement.result.test_group_name.equals(PerformanceSuite.NAME) ? measurement.result.getTestSuite().getThemeLight() : measurement.is_anomaly ? R.style.Theme_MaterialComponents_Light_DarkActionBar_App_NoActionBar_Failure : R.style.Theme_MaterialComponents_Light_DarkActionBar_App_NoActionBar_Success); setContentView(R.layout.activity_measurement_detail); ButterKnife.bind(this); setSupportActionBar(toolbar); ActionBar bar = getSupportActionBar(); if (bar != null) { bar.setDisplayHomeAsUpEnabled(true); bar.setTitle(measurement.getTest().getLabelResId()); } Fragment detail = null; Fragment head = null; if (measurement.is_failed) { head = HeaderOutcomeFragment.newInstance(R.drawable.error_48dp, getString(R.string.bold, getString(R.string.outcomeHeader, getString(R.string.TestResults_Details_Failed_Title), getString(R.string.TestResults_Details_Failed_Paragraph)))); detail = FailedFragment.newInstance(measurement); } else { int iconRes = measurement.is_anomaly ? R.drawable.exclamation_white_48dp : R.drawable.tick_white_48dp; switch (measurement.test_name) { case Dash.NAME: head = HeaderOutcomeFragment.newInstance(null, getString(R.string.outcomeHeader, getString(measurement.getTestKeys().getVideoQuality(true)), getString(R.string.TestResults_Details_Performance_Dash_VideoWithoutBuffering, getString(measurement.getTestKeys().getVideoQuality(false))))); detail = DashFragment.newInstance(measurement); break; case FacebookMessenger.NAME: head = HeaderOutcomeFragment.newInstance(iconRes, getString(R.string.bold, getString(measurement.is_anomaly ? R.string.TestResults_Details_InstantMessaging_WhatsApp_Registrations_Label_Failed : R.string.TestResults_Details_InstantMessaging_WhatsApp_Reachable_Hero_Title))); detail = FacebookMessengerFragment.newInstance(measurement); break; case HttpHeaderFieldManipulation.NAME: head = HeaderOutcomeFragment.newInstance(iconRes, getString(R.string.bold, getString(measurement.is_anomaly ? R.string.TestResults_Details_Middleboxes_HTTPHeaderFieldManipulation_Found_Hero_Title : R.string.TestResults_Details_Middleboxes_HTTPHeaderFieldManipulation_NotFound_Hero_Title))); detail = HttpHeaderFieldManipulationFragment.newInstance(measurement); break; case HttpInvalidRequestLine.NAME: head = HeaderOutcomeFragment.newInstance(iconRes, getString(R.string.bold, getString(measurement.is_anomaly ? R.string.TestResults_Details_Middleboxes_HTTPInvalidRequestLine_Found_Hero_Title : R.string.TestResults_Details_Middleboxes_HTTPInvalidRequestLine_NotFound_Hero_Title))); detail = HttpInvalidRequestLineFragment.newInstance(measurement); break; case Ndt.NAME: head = HeaderNdtFragment.newInstance(measurement); detail = NdtFragment.newInstance(measurement); break; case Telegram.NAME: head = HeaderOutcomeFragment.newInstance(iconRes, getString(R.string.bold, getString(measurement.is_anomaly ? R.string.TestResults_Details_InstantMessaging_WhatsApp_Registrations_Label_Failed : R.string.TestResults_Details_InstantMessaging_WhatsApp_Reachable_Hero_Title))); detail = TelegramFragment.newInstance(measurement); break; case WebConnectivity.NAME: head = HeaderOutcomeFragment.newInstance(iconRes, getString(R.string.outcomeHeader, measurement.url.url, getString(measurement.is_anomaly ? R.string.TestResults_Details_Websites_LikelyBlocked_Hero_Title : R.string.TestResults_Details_Websites_Reachable_Hero_Title))); detail = WebConnectivityFragment.newInstance(measurement); break; case Whatsapp.NAME: head = HeaderOutcomeFragment.newInstance(iconRes, getString(R.string.bold, getString(measurement.is_anomaly ? R.string.TestResults_Details_InstantMessaging_WhatsApp_Registrations_Label_Failed : R.string.TestResults_Details_InstantMessaging_WhatsApp_Reachable_Hero_Title))); detail = WhatsappFragment.newInstance(measurement); break; } } assert detail != null && head != null; getSupportFragmentManager().beginTransaction() .replace(R.id.footer, ResultHeaderDetailFragment.newInstance( true, null, null, measurement.start_time, measurement.runtime, false, measurement.result.network.country_code, measurement.result.network)) .replace(R.id.body, detail) .replace(R.id.head, head) .commit(); snackbar = Snackbar.make(coordinatorLayout, R.string.Snackbar_ResultsNotUploaded_Text, Snackbar.LENGTH_INDEFINITE) .setAction(R.string.Snackbar_ResultsNotUploaded_Upload, v1 -> runMKCollectorResubmitSettingsAsyncTask()); load(); } private void runMKCollectorResubmitSettingsAsyncTask() { new MKCollectorResubmitSettingsAsyncTask(this).execute(null, measurement.id); } private void load() { if (!measurement.is_failed && (!measurement.is_uploaded || measurement.report_id == null)) snackbar.show(); else snackbar.dismiss(); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.measurement, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.rawData: try { File entryFile = Measurement.getEntryFile(this, measurement.id, measurement.test_name); String json = FileUtils.readFileToString(entryFile, StandardCharsets.UTF_8); json = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create().toJson(new JsonParser().parse(json)); startActivity(TextActivity.newIntent(this, json)); } catch (Exception e) { e.printStackTrace(); } return true; case R.id.viewLog: try { File logFile = Measurement.getLogFile(this, measurement.result.id, measurement.test_name); String log = FileUtils.readFileToString(logFile, StandardCharsets.UTF_8); startActivity(TextActivity.newIntent(this, log)); } catch (Exception e) { e.printStackTrace(); } return true; default: return super.onOptionsItemSelected(item); } } @OnClick(R.id.methodology) void methodologyClick() { startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(getString(measurement.getTest().getUrlResId())))); } private static class MKCollectorResubmitSettingsAsyncTask extends MKCollectorResubmitTask<MeasurementDetailActivity> { MKCollectorResubmitSettingsAsyncTask(MeasurementDetailActivity activity) { super(activity); } @Override protected void onPostExecute(Void result) { super.onPostExecute(result); MeasurementDetailActivity activity = getActivity(); if (activity != null) { activity.measurement = SQLite.select().from(Measurement.class) .where(Measurement_Table.id.eq(activity.measurement.id)).querySingle(); activity.load(); } } } }
52.256303
133
0.665675
d272847febc00dcdd5f3cd6bd777b5e5bdfff102
569
package cz.cuni.mff.d3s.deeco.processor; import java.io.File; import java.io.FilenameFilter; /** * Generic filter class used to filter files by their extensions. * * @author Michal Kit * */ public class FileExtensionFilter implements FilenameFilter { private String ext = "*"; public FileExtensionFilter(String ext) { this.ext = ext; } /* (non-Javadoc) * @see java.io.FilenameFilter#accept(java.io.File, java.lang.String) */ @Override public boolean accept(File dir, String name) { if (name.endsWith(ext)) return true; return false; } }
18.966667
70
0.704745
68dd477ab13b873d553a523b1c513728596c0fe8
7,417
/* * Copyright 2022 Creek Contributors (https://github.com/creek-service) * * 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.creekservice.api.system.test.gradle.plugin.task; import static org.creekservice.api.system.test.gradle.plugin.SystemTestPlugin.EXECUTOR_DEP_ARTEFACT_NAME; import static org.creekservice.api.system.test.gradle.plugin.SystemTestPlugin.EXECUTOR_DEP_GROUP_NAME; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.concurrent.Callable; import org.creekservice.api.system.test.gradle.plugin.SystemTestPlugin; import org.gradle.api.DefaultTask; import org.gradle.api.GradleException; import org.gradle.api.artifacts.Configuration; import org.gradle.api.artifacts.Dependency; import org.gradle.api.file.ConfigurableFileCollection; import org.gradle.api.file.DirectoryProperty; import org.gradle.api.provider.ListProperty; import org.gradle.api.provider.Property; import org.gradle.api.tasks.Input; import org.gradle.api.tasks.InputDirectory; import org.gradle.api.tasks.Internal; import org.gradle.api.tasks.OutputDirectory; import org.gradle.api.tasks.SkipWhenEmpty; import org.gradle.api.tasks.TaskAction; import org.gradle.api.tasks.options.Option; /** Task for running Creek system tests. */ public abstract class SystemTest extends DefaultTask { private final ConfigurableFileCollection classPath; public SystemTest() { this.classPath = getProject().getObjects().fileCollection(); this.classPath.from((Callable<Object>) this::getSystemTestExecutor); this.classPath.from((Callable<Object>) this::getSystemTestExtensions); this.classPath.from((Callable<Object>) this::getSystemTestComponents); setDescription("Task for running Creek system tests"); } /** @return the source directory containing test */ @SkipWhenEmpty @InputDirectory public abstract DirectoryProperty getTestDirectory(); /** @return the directory result files will be written to. */ @OutputDirectory public abstract DirectoryProperty getResultDirectory(); /** @return dependencies of the system test executor. */ @Internal public abstract ConfigurableFileCollection getSystemTestExecutor(); /** @return dependencies of the system test extensions. */ @Internal public abstract ConfigurableFileCollection getSystemTestExtensions(); /** @return dependencies of the components being system tested. */ @Internal public abstract ConfigurableFileCollection getSystemTestComponents(); @Option( option = "verification-timeout-seconds", description = "Set an optional custom verifier timeout. " + "The verifier timeout is the maximum amount of time the system tests " + "will wait for a defined expectation to be met. A longer timeout will mean " + "tests have more time for expectations to be met, but may run slower as a consequence.") @Input public abstract Property<String> getVerificationTimeoutSeconds(); @Option( option = "include-suites", description = "Set an optional regular expression pattern to limit the test suites to run. " + "Only test suites whose relative path matches the supplied pattern will be included.") @Input public abstract Property<String> getSuitesPathPattern(); /** @return additional command line arguments to pass to the executor */ @Input public abstract ListProperty<String> getExtraArguments(); /** Method to allow setting extra arguments from the command line. */ @SuppressWarnings("unused") // Invoked via reflection @Option( option = "extra-argument", description = "Any additional arguments to use when running system tests.") public void setExtraArgumentsFromOption(final List<String> args) { getExtraArguments().set(args); } @TaskAction public void run() { checkDependenciesIncludesRunner(); getProject() .javaexec( spec -> { spec.getMainClass() .set( "org.creekservice.api.system.test.executor.SystemTestExecutor"); spec.setClasspath(classPath); spec.setArgs(arguments()); spec.jvmArgs(jvmArgs()); }); } private void checkDependenciesIncludesRunner() { final Configuration configuration = getProject() .getConfigurations() .getByName(SystemTestPlugin.EXECUTOR_CONFIGURATION_NAME); configuration.resolve(); final Optional<Dependency> executorDep = configuration.getDependencies().stream() .filter(dep -> EXECUTOR_DEP_GROUP_NAME.equals(dep.getGroup())) .filter(dep -> EXECUTOR_DEP_ARTEFACT_NAME.equals(dep.getName())) .findFirst(); if (executorDep.isEmpty()) { throw new MissingExecutorDependencyException(); } getLogger().debug("Using system test executor version: " + executorDep.get().getVersion()); } private List<String> arguments() { final List<String> arguments = new ArrayList<>(); arguments.add( "--test-directory=" + getTestDirectory().getAsFile().get().toPath().toAbsolutePath()); arguments.add( "--result-directory=" + getResultDirectory().getAsFile().get().toPath().toAbsolutePath()); arguments.add("--verifier-timeout-seconds=" + getVerificationTimeoutSeconds().getOrNull()); arguments.add("--include-suites=" + getSuitesPathPattern().getOrNull()); arguments.addAll(getExtraArguments().get()); return arguments; } private List<String> jvmArgs() { final Object jvmArgs = getProject().findProperty("org.gradle.jvmargs"); if ((!(jvmArgs instanceof String))) { return List.of(); } return List.of(((String) jvmArgs).split("\\s+")); } private static final class MissingExecutorDependencyException extends GradleException { MissingExecutorDependencyException() { super( "No system test executor dependency found in " + SystemTestPlugin.EXECUTOR_CONFIGURATION_NAME + " configuration. Please ensure the configuration contains " + EXECUTOR_DEP_GROUP_NAME + ":" + EXECUTOR_DEP_ARTEFACT_NAME); } } }
40.309783
118
0.64851
160e49d4770f6e155734944a1ba8328c60c1c52d
6,997
/* * This file is part of TechReborn, licensed under the MIT License (MIT). * * Copyright (c) 2020 TechReborn * * 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 techreborn.world; import com.google.gson.JsonElement; import net.fabricmc.fabric.api.biome.v1.BiomeSelectionContext; import net.fabricmc.fabric.api.biome.v1.BiomeSelectors; import net.minecraft.block.BlockState; import net.minecraft.block.Blocks; import net.minecraft.structure.rule.BlockStateMatchRuleTest; import net.minecraft.structure.rule.RuleTest; import net.minecraft.util.Identifier; import net.minecraft.util.collection.DataPool; import net.minecraft.util.math.Direction; import net.minecraft.util.math.intprovider.ConstantIntProvider; import net.minecraft.util.registry.Registry; import net.minecraft.world.biome.Biome; import net.minecraft.world.gen.GenerationStep; import net.minecraft.world.gen.decorator.ChanceDecoratorConfig; import net.minecraft.world.gen.feature.ConfiguredFeature; import net.minecraft.world.gen.feature.OreFeatureConfig; import net.minecraft.world.gen.feature.TreeFeatureConfig; import net.minecraft.world.gen.feature.size.TwoLayersFeatureSize; import net.minecraft.world.gen.stateprovider.BlockStateProvider; import net.minecraft.world.gen.stateprovider.SimpleBlockStateProvider; import net.minecraft.world.gen.stateprovider.WeightedBlockStateProvider; import net.minecraft.world.gen.trunk.StraightTrunkPlacer; import org.apache.logging.log4j.util.TriConsumer; import techreborn.blocks.misc.BlockRubberLog; import techreborn.init.TRContent; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.function.Predicate; public class DefaultWorldGen { private static final RuleTest END_STONE = new BlockStateMatchRuleTest(Blocks.END_STONE.getDefaultState()); private static ConfiguredFeature<?, ?> getRubberTree() { DataPool.Builder<BlockState> logPoolBuilder = DataPool.<BlockState>builder() .add(TRContent.RUBBER_LOG.getDefaultState(), 10); Arrays.stream(Direction.values()) .filter(direction -> direction.getAxis().isHorizontal()) .map(direction -> TRContent.RUBBER_LOG.getDefaultState() .with(BlockRubberLog.HAS_SAP, true) .with(BlockRubberLog.SAP_SIDE, direction) ) .forEach(state -> logPoolBuilder.add(state, 1)); BlockStateProvider logProvider = new WeightedBlockStateProvider(logPoolBuilder.build()); TreeFeatureConfig treeFeatureConfig = new TreeFeatureConfig.Builder( logProvider, new StraightTrunkPlacer(6, 3, 0), new SimpleBlockStateProvider(TRContent.RUBBER_LEAVES.getDefaultState()), new SimpleBlockStateProvider(TRContent.RUBBER_SAPLING.getDefaultState()), new RubberTreeFeature.FoliagePlacer(ConstantIntProvider.create(2), ConstantIntProvider.create(0), 3, 3, TRContent.RUBBER_LEAVES.getDefaultState()), new TwoLayersFeatureSize(1, 0, 1) ).build(); return WorldGenerator.RUBBER_TREE_FEATURE.configure(treeFeatureConfig) .decorate(WorldGenerator.RUBBER_TREE_DECORATOR .configure(new ChanceDecoratorConfig(50) )); } public static List<DataDrivenFeature> getDefaultFeatures() { List<DataDrivenFeature> features = new ArrayList<>(); TriConsumer<Predicate<BiomeSelectionContext>, RuleTest, TRContent.Ores> addOre = (worldTargetType, ruleTest, ore) -> features.add(ore.asNewOres(new Identifier("techreborn", Registry.BLOCK.getId(ore.block).getPath()), worldTargetType, ruleTest)); addOre.accept(BiomeSelectors.foundInTheNether(), OreFeatureConfig.Rules.BASE_STONE_NETHER, TRContent.Ores.CINNABAR); addOre.accept(BiomeSelectors.foundInTheNether(), OreFeatureConfig.Rules.BASE_STONE_NETHER, TRContent.Ores.PYRITE); addOre.accept(BiomeSelectors.foundInTheNether(), OreFeatureConfig.Rules.BASE_STONE_NETHER, TRContent.Ores.SPHALERITE); addOre.accept(BiomeSelectors.foundInTheEnd(), END_STONE, TRContent.Ores.PERIDOT); addOre.accept(BiomeSelectors.foundInTheEnd(), END_STONE, TRContent.Ores.SHELDONITE); addOre.accept(BiomeSelectors.foundInTheEnd(), END_STONE, TRContent.Ores.SODALITE); addOre.accept(BiomeSelectors.foundInTheEnd(), END_STONE, TRContent.Ores.TUNGSTEN); addOre.accept(BiomeSelectors.foundInOverworld(), OreFeatureConfig.Rules.BASE_STONE_OVERWORLD, TRContent.Ores.BAUXITE); addOre.accept(BiomeSelectors.foundInOverworld(), OreFeatureConfig.Rules.BASE_STONE_OVERWORLD, TRContent.Ores.GALENA); addOre.accept(BiomeSelectors.foundInOverworld(), OreFeatureConfig.Rules.BASE_STONE_OVERWORLD, TRContent.Ores.IRIDIUM); addOre.accept(BiomeSelectors.foundInOverworld(), OreFeatureConfig.Rules.BASE_STONE_OVERWORLD, TRContent.Ores.LEAD); addOre.accept(BiomeSelectors.foundInOverworld(), OreFeatureConfig.Rules.BASE_STONE_OVERWORLD, TRContent.Ores.RUBY); addOre.accept(BiomeSelectors.foundInOverworld(), OreFeatureConfig.Rules.BASE_STONE_OVERWORLD, TRContent.Ores.SAPPHIRE); addOre.accept(BiomeSelectors.foundInOverworld(), OreFeatureConfig.Rules.BASE_STONE_OVERWORLD, TRContent.Ores.SILVER); addOre.accept(BiomeSelectors.foundInOverworld(), OreFeatureConfig.Rules.BASE_STONE_OVERWORLD, TRContent.Ores.TIN); features.add(new DataDrivenFeature( RubberSaplingGenerator.IDENTIFIER, BiomeSelectors.categories(Biome.Category.FOREST, Biome.Category.TAIGA, Biome.Category.SWAMP), getRubberTree(), GenerationStep.Feature.VEGETAL_DECORATION )); return features; } // Used to export the worldgen jsons public static void export() { for (DataDrivenFeature defaultFeature : getDefaultFeatures()) { JsonElement jsonElement = defaultFeature.serialise(); String json = jsonElement.toString(); Path dir = Paths.get("..\\src\\main\\resources\\data\\techreborn\\techreborn\\features"); try { Files.writeString(dir.resolve(defaultFeature.getIdentifier().getPath() + ".json"), json); } catch (IOException e) { e.printStackTrace(); } } } }
47.924658
150
0.798342
14478d641bfc5410c97ea27e75d8b0cb2db93951
7,314
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2011, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * --------------------------------- * BoxAndWhiskerCategoryDataset.java * --------------------------------- * (C) Copyright 2003-2008, by David Browning and Contributors. * * Original Author: David Browning (for Australian Institute of Marine * Science); * Contributor(s): -; * * Changes * ------- * 05-Aug-2003 : Version 1, contributed by David Browning (DG); * 27-Aug-2003 : Renamed getAverageValue --> getMeanValue, changed * getAllOutliers to return a List rather than an array (DG); * ------------- JFREECHART 1.0.x --------------------------------------------- * 02-Feb-2007 : Removed author tags from all over JFreeChart sources (DG); * */ package org.jfree.data.statistics; import java.util.List; import org.jfree.data.category.CategoryDataset; /** * A category dataset that defines various medians, outliers and an average * value for each item. */ public interface BoxAndWhiskerCategoryDataset extends CategoryDataset { /** * Returns the mean value for an item. * * @param row the row index (zero-based). * @param column the column index (zero-based). * * @return The mean value. */ public Number getMeanValue(int row, int column); /** * Returns the average value for an item. * * @param rowKey the row key. * @param columnKey the columnKey. * * @return The average value. */ public Number getMeanValue(Comparable rowKey, Comparable columnKey); /** * Returns the median value for an item. * * @param row the row index (zero-based). * @param column the column index (zero-based). * * @return The median value. */ public Number getMedianValue(int row, int column); /** * Returns the median value for an item. * * @param rowKey the row key. * @param columnKey the columnKey. * * @return The median value. */ public Number getMedianValue(Comparable rowKey, Comparable columnKey); /** * Returns the q1median value for an item. * * @param row the row index (zero-based). * @param column the column index (zero-based). * * @return The q1median value. */ public Number getQ1Value(int row, int column); /** * Returns the q1median value for an item. * * @param rowKey the row key. * @param columnKey the columnKey. * * @return The q1median value. */ public Number getQ1Value(Comparable rowKey, Comparable columnKey); /** * Returns the q3median value for an item. * * @param row the row index (zero-based). * @param column the column index (zero-based). * * @return The q3median value. */ public Number getQ3Value(int row, int column); /** * Returns the q3median value for an item. * * @param rowKey the row key. * @param columnKey the columnKey. * * @return The q3median value. */ public Number getQ3Value(Comparable rowKey, Comparable columnKey); /** * Returns the minimum regular (non-outlier) value for an item. * * @param row the row index (zero-based). * @param column the column index (zero-based). * * @return The minimum regular value. */ public Number getMinRegularValue(int row, int column); /** * Returns the minimum regular (non-outlier) value for an item. * * @param rowKey the row key. * @param columnKey the columnKey. * * @return The minimum regular value. */ public Number getMinRegularValue(Comparable rowKey, Comparable columnKey); /** * Returns the maximum regular (non-outlier) value for an item. * * @param row the row index (zero-based). * @param column the column index (zero-based). * * @return The maximum regular value. */ public Number getMaxRegularValue(int row, int column); /** * Returns the maximum regular (non-outlier) value for an item. * * @param rowKey the row key. * @param columnKey the columnKey. * * @return The maximum regular value. */ public Number getMaxRegularValue(Comparable rowKey, Comparable columnKey); /** * Returns the minimum outlier (non-farout) for an item. * * @param row the row index (zero-based). * @param column the column index (zero-based). * * @return The minimum outlier. */ public Number getMinOutlier(int row, int column); /** * Returns the minimum outlier (non-farout) for an item. * * @param rowKey the row key. * @param columnKey the columnKey. * * @return The minimum outlier. */ public Number getMinOutlier(Comparable rowKey, Comparable columnKey); /** * Returns the maximum outlier (non-farout) for an item. * * @param row the row index (zero-based). * @param column the column index (zero-based). * * @return The maximum outlier. */ public Number getMaxOutlier(int row, int column); /** * Returns the maximum outlier (non-farout) for an item. * * @param rowKey the row key. * @param columnKey the columnKey. * * @return The maximum outlier. */ public Number getMaxOutlier(Comparable rowKey, Comparable columnKey); /** * Returns a list of outlier values for an item. The list may be empty, * but should never be <code>null</code>. * * @param row the row index (zero-based). * @param column the column index (zero-based). * * @return A list of outliers for an item. */ public List getOutliers(int row, int column); /** * Returns a list of outlier values for an item. The list may be empty, * but should never be <code>null</code>. * * @param rowKey the row key. * @param columnKey the columnKey. * * @return A list of outlier values for an item. */ public List getOutliers(Comparable rowKey, Comparable columnKey); }
30.348548
79
0.615258
ae646e6ba7c876464d52a2c30519c4c0e4cefb26
1,132
package cityguide.datastorage.view; import static org.assertj.core.api.Assertions.assertThat; import java.util.ArrayList; import java.util.Collections; import org.junit.jupiter.api.Test; import cityguide.datastorage.model.Description; import cityguide.datastorage.model.ShowPlace; class TelegramMessageViewImplTest { @Test void prepareMessageForNotFoundShowPlace() { assertThat(new TelegramMessageViewImpl().prepareMessage(Collections.emptyList())).isEqualTo("Ничего не найдено"); } private ShowPlace prepareShowPlace(){ final var showPlace = new ShowPlace(); final var descriptionList = new ArrayList<Description>(); final var description = new Description(); description.setInfo("some description"); descriptionList.add(description); showPlace.setDescriptionList(descriptionList); return showPlace; } @Test void prepareMessage(){ final var showPlaceList = Collections.singletonList(prepareShowPlace()); assertThat(new TelegramMessageViewImpl().prepareMessage(showPlaceList)).isEqualTo("some description"); } }
31.444444
121
0.737633
cbda426e9dcab3fc749501cb9e144ddfd3c872e3
1,401
/* * Copyright (c) 2021 www.hoprxi.com 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 identity.hoprxi.core.application.command; /** * @author <a href="www.hoprxi.com/authors/guan xiangHuan">guan xiangHuan</a> * @version 0.0.1 2020-12-18 * @since JDK8.0 */ public class ChangeUserPasswordCommand { private String username; private String newPassword; public ChangeUserPasswordCommand(String username, String newPassword) { this.username = username; this.newPassword = newPassword; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getNewPassword() { return newPassword; } public void setNewPassword(String newPassword) { this.newPassword = newPassword; } }
28.02
77
0.698073
a4fa9c9752d8a129a6731e21665e325b8994374c
1,737
// Copyright (c) FIRST and other WPILib contributors. // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. package frc.robot.subsystems; import com.ctre.phoenix.motorcontrol.can.WPI_TalonSRX; import edu.wpi.first.wpilibj.DigitalInput; import edu.wpi.first.wpilibj2.command.SubsystemBase; public class IntakeSubsystem extends SubsystemBase { private WPI_TalonSRX deployMotor; private WPI_TalonSRX rollerMotor; private DigitalInput limitSwitchUp; private DigitalInput limitSwitchDown; private final double intakeSpeed = 0.5; private final double deploySpeed = 0.2; /** Creates a new IntakeSubsystem. */ public IntakeSubsystem() { deployMotor = new WPI_TalonSRX(0); rollerMotor = new WPI_TalonSRX(1); limitSwitchUp = new DigitalInput(0); limitSwitchDown = new DigitalInput(1); } @Override public void periodic() { // This method will be called once per scheduler run } /** * Deploys the intake device for picking up cargo */ public void deployIntake() { if(limitSwitchDown.get()) { deployMotor.set(0); } else { deployMotor.set(deploySpeed); } } /** * Retracts the intake device */ public void retractIntake(){ if(limitSwitchUp.get()) { deployMotor.set(0); } else { deployMotor.set(deploySpeed * -1); } } /** * Activates the intake rollers to collect cargo */ public void intakeCargo() { rollerMotor.set(intakeSpeed); } /** * Reverses the intake system to remove jammed cargo */ public void reverseIntakeCargo() { rollerMotor.set(intakeSpeed * -1); } }
20.197674
74
0.680484
3416afc2e0f5580abcefc3bceeffa0846123980a
5,476
package org.seqcode.viz.metaprofile; import java.awt.Color; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.Vector; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.seqcode.data.motifdb.WeightMatrix; import org.seqcode.genome.Genome; import org.seqcode.genome.Species; import org.seqcode.genome.location.Point; import org.seqcode.genome.location.StrandedPoint; import org.seqcode.gseutils.Args; import org.seqcode.gseutils.NotFoundException; import org.seqcode.gseutils.Pair; import org.seqcode.viz.metaprofile.swing.MetaFrame; import org.seqcode.viz.metaprofile.swing.MetaNonFrame; public class EventMetaMaker { private static boolean batchRun = false; private static boolean cluster = false; private static Genome gen; public static void main(String[] args) { try { if(args.length < 2){ printError();} Pair<Species, Genome> pair = Args.parseGenome(args); gen = pair.cdr(); int winLen = Args.parseInteger(args,"win", 10000); int bins = Args.parseInteger(args,"bins", 100); String profilerType = Args.parseString(args, "profiler", "events"); String eventFile = Args.parseString(args,"events", null); String peakFile = Args.parseString(args, "peaks", null); String outName = Args.parseString(args, "out", "meta"); double lineMax = Args.parseDouble(args,"linemax", 100); if(Args.parseFlags(args).contains("batch")){batchRun=true;} if(Args.parseFlags(args).contains("cluster")){cluster=true;} Color c = Color.blue; String newCol = Args.parseString(args, "color", "blue"); if(newCol.equals("red")) c=Color.red; if(newCol.equals("orange")) c=Color.orange; if(newCol.equals("green")) c=new Color(0,153,0); if(newCol.equals("black")) c=Color.black; if(gen==null || eventFile==null){printError();} BinningParameters params = new BinningParameters(winLen, bins); System.out.println("Binding Parameters:\tWindow size: "+params.getWindowSize()+"\tBins: "+params.getNumBins()); PointProfiler profiler=null; boolean normalizeProfile=false; if(profilerType.equals("events")){ ArrayList<Point> events = loadPoints(new File(eventFile), gen); System.out.println("Loading data..."); profiler = new EventProfiler(params, gen, events); } if(batchRun){ System.out.println("Batch running..."); MetaNonFrame nonframe = new MetaNonFrame(gen, params, profiler, normalizeProfile, false); nonframe.setColor(c); MetaProfileHandler handler = nonframe.getHandler(); if(peakFile != null){ Vector<Point> points = nonframe.getUtils().loadPoints(new File(peakFile)); handler.addPoints(points); }else{ Iterator<Point> points = nonframe.getUtils().loadTSSs("refGene"); handler.addPoints(points); } while(handler.addingPoints()){} if(cluster) nonframe.clusterLinePanel(); //Set the panel sizes here... nonframe.setLineMin(0); nonframe.setLineMax(lineMax); nonframe.saveImages(outName); nonframe.savePointsToFile(outName); System.out.println("Finished"); }else{ System.out.println("Initializing Meta-point frame..."); MetaFrame frame = new MetaFrame(gen, params, profiler, normalizeProfile); frame.setColor(c); frame.startup(); MetaProfileHandler handler = frame.getHandler(); if(peakFile != null){ Vector<Point> points = frame.getUtils().loadPoints(new File(peakFile)); handler.addPoints(points); }frame.setLineMax(lineMax); } } catch (NotFoundException e) { e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private static void printError(){ System.err.println("Usage: EventMetaMaker --species <organism;genome> \n" + "--win <profile width> --bins <num bins> \n" + "--profiler <events> \n" + "--events <point file>\n" + "--linemax <max>\n" + "--peaks <peaks file name> --out <output root name> \n" + "--color <red/green/blue/black> \n" + "--cluster [flag to cluster in batch mode] \n" + "--batch [a flag to run without displaying the window]"); System.exit(1); } public static ArrayList<Point> loadPoints(File f, Genome g) throws IOException { System.err.println("Loading points"); ArrayList<Point> pts = new ArrayList<Point>(); BufferedReader br = new BufferedReader(new FileReader(f)); Pattern ptpatt = Pattern.compile("([^:\\s]+):(\\d+)"); Pattern strptpatt = Pattern.compile("([^:\\s]+):(\\d+):([^:\\s]+)"); String line; while((line = br.readLine()) != null) { Matcher m = ptpatt.matcher(line); if(m.find()) { String chrom = m.group(1); int location = Integer.parseInt(m.group(2)); char strand = '?'; Matcher sm = strptpatt.matcher(line); if(sm.find()){ String strandstr = sm.group(3); if(strandstr.length() > 0) { strand = strandstr.charAt(0); } } Point pt = null; if(strand == '+') { pt = new StrandedPoint(g, chrom, location, strand); } else if (strand == '-') { pt = new StrandedPoint(g, chrom, location, strand); } else { pt = new Point(g, chrom, location); } pts.add(pt); } else { System.err.println(String.format("Couldn't find point in line \"%s\"", line)); } } br.close(); System.err.println(pts.size()+" points loaded"); return pts; } }
34.440252
114
0.673667
9207bf9bbfe0bf03ea081142afa5ed3eba271756
10,228
/* * 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. */ /* * 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. */ /* * Modifications Copyright OpenSearch Contributors. See * GitHub history for details. */ package org.opensearch.search.rescore; import org.opensearch.common.ParseField; import org.opensearch.common.ParsingException; import org.opensearch.common.io.stream.StreamInput; import org.opensearch.common.io.stream.StreamOutput; import org.opensearch.common.xcontent.ObjectParser; import org.opensearch.common.xcontent.XContentBuilder; import org.opensearch.common.xcontent.XContentParser; import org.opensearch.index.query.QueryBuilder; import org.opensearch.index.query.QueryRewriteContext; import org.opensearch.index.query.QueryShardContext; import org.opensearch.search.rescore.QueryRescorer.QueryRescoreContext; import java.io.IOException; import java.util.Locale; import java.util.Objects; import static org.opensearch.index.query.AbstractQueryBuilder.parseInnerQueryBuilder; public class QueryRescorerBuilder extends RescorerBuilder<QueryRescorerBuilder> { public static final String NAME = "query"; private static final ParseField RESCORE_QUERY_FIELD = new ParseField("rescore_query"); private static final ParseField QUERY_WEIGHT_FIELD = new ParseField("query_weight"); private static final ParseField RESCORE_QUERY_WEIGHT_FIELD = new ParseField("rescore_query_weight"); private static final ParseField SCORE_MODE_FIELD = new ParseField("score_mode"); private static final ObjectParser<InnerBuilder, Void> QUERY_RESCORE_PARSER = new ObjectParser<>(NAME); static { QUERY_RESCORE_PARSER.declareObject(InnerBuilder::setQueryBuilder, (p, c) -> { try { return parseInnerQueryBuilder(p); } catch (IOException e) { throw new ParsingException(p.getTokenLocation(), "Could not parse inner query", e); } } , RESCORE_QUERY_FIELD); QUERY_RESCORE_PARSER.declareFloat(InnerBuilder::setQueryWeight, QUERY_WEIGHT_FIELD); QUERY_RESCORE_PARSER.declareFloat(InnerBuilder::setRescoreQueryWeight, RESCORE_QUERY_WEIGHT_FIELD); QUERY_RESCORE_PARSER.declareString((struct, value) -> struct.setScoreMode(QueryRescoreMode.fromString(value)), SCORE_MODE_FIELD); } public static final float DEFAULT_RESCORE_QUERYWEIGHT = 1.0f; public static final float DEFAULT_QUERYWEIGHT = 1.0f; public static final QueryRescoreMode DEFAULT_SCORE_MODE = QueryRescoreMode.Total; private final QueryBuilder queryBuilder; private float rescoreQueryWeight = DEFAULT_RESCORE_QUERYWEIGHT; private float queryWeight = DEFAULT_QUERYWEIGHT; private QueryRescoreMode scoreMode = DEFAULT_SCORE_MODE; /** * Creates a new {@link QueryRescorerBuilder} instance * @param builder the query builder to build the rescore query from */ public QueryRescorerBuilder(QueryBuilder builder) { if (builder == null) { throw new IllegalArgumentException("rescore_query cannot be null"); } this.queryBuilder = builder; } /** * Read from a stream. */ public QueryRescorerBuilder(StreamInput in) throws IOException { super(in); queryBuilder = in.readNamedWriteable(QueryBuilder.class); scoreMode = QueryRescoreMode.readFromStream(in); rescoreQueryWeight = in.readFloat(); queryWeight = in.readFloat(); } @Override public void doWriteTo(StreamOutput out) throws IOException { out.writeNamedWriteable(queryBuilder); scoreMode.writeTo(out); out.writeFloat(rescoreQueryWeight); out.writeFloat(queryWeight); } @Override public String getWriteableName() { return NAME; } /** * @return the query used for this rescore query */ public QueryBuilder getRescoreQuery() { return this.queryBuilder; } /** * Sets the original query weight for rescoring. The default is {@code 1.0} */ public QueryRescorerBuilder setQueryWeight(float queryWeight) { this.queryWeight = queryWeight; return this; } /** * Gets the original query weight for rescoring. The default is {@code 1.0} */ public float getQueryWeight() { return this.queryWeight; } /** * Sets the original query weight for rescoring. The default is {@code 1.0} */ public QueryRescorerBuilder setRescoreQueryWeight(float rescoreQueryWeight) { this.rescoreQueryWeight = rescoreQueryWeight; return this; } /** * Gets the original query weight for rescoring. The default is {@code 1.0} */ public float getRescoreQueryWeight() { return this.rescoreQueryWeight; } /** * Sets the original query score mode. The default is {@link QueryRescoreMode#Total}. */ public QueryRescorerBuilder setScoreMode(QueryRescoreMode scoreMode) { this.scoreMode = scoreMode; return this; } /** * Gets the original query score mode. The default is {@code total} */ public QueryRescoreMode getScoreMode() { return this.scoreMode; } @Override public void doXContent(XContentBuilder builder, Params params) throws IOException { builder.startObject(NAME); builder.field(RESCORE_QUERY_FIELD.getPreferredName(), queryBuilder); builder.field(QUERY_WEIGHT_FIELD.getPreferredName(), queryWeight); builder.field(RESCORE_QUERY_WEIGHT_FIELD.getPreferredName(), rescoreQueryWeight); builder.field(SCORE_MODE_FIELD.getPreferredName(), scoreMode.name().toLowerCase(Locale.ROOT)); builder.endObject(); } public static QueryRescorerBuilder fromXContent(XContentParser parser) throws IOException { InnerBuilder innerBuilder = QUERY_RESCORE_PARSER.parse(parser, new InnerBuilder(), null); return innerBuilder.build(); } @Override public QueryRescoreContext innerBuildContext(int windowSize, QueryShardContext context) throws IOException { QueryRescoreContext queryRescoreContext = new QueryRescoreContext(windowSize); // query is rewritten at this point already queryRescoreContext.setQuery(queryBuilder.toQuery(context)); queryRescoreContext.setQueryWeight(this.queryWeight); queryRescoreContext.setRescoreQueryWeight(this.rescoreQueryWeight); queryRescoreContext.setScoreMode(this.scoreMode); return queryRescoreContext; } @Override public final int hashCode() { int result = super.hashCode(); return 31 * result + Objects.hash(scoreMode, queryWeight, rescoreQueryWeight, queryBuilder); } @Override public final boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } QueryRescorerBuilder other = (QueryRescorerBuilder) obj; return super.equals(obj) && Objects.equals(scoreMode, other.scoreMode) && Objects.equals(queryWeight, other.queryWeight) && Objects.equals(rescoreQueryWeight, other.rescoreQueryWeight) && Objects.equals(queryBuilder, other.queryBuilder); } /** * Helper to be able to use {@link ObjectParser}, since we need the inner query builder * for the constructor of {@link QueryRescorerBuilder}, but {@link ObjectParser} only * allows filling properties of an already constructed value. */ private static class InnerBuilder { private QueryBuilder queryBuilder; private float rescoreQueryWeight = DEFAULT_RESCORE_QUERYWEIGHT; private float queryWeight = DEFAULT_QUERYWEIGHT; private QueryRescoreMode scoreMode = DEFAULT_SCORE_MODE; void setQueryBuilder(QueryBuilder builder) { this.queryBuilder = builder; } QueryRescorerBuilder build() { QueryRescorerBuilder queryRescoreBuilder = new QueryRescorerBuilder(queryBuilder); queryRescoreBuilder.setQueryWeight(queryWeight); queryRescoreBuilder.setRescoreQueryWeight(rescoreQueryWeight); queryRescoreBuilder.setScoreMode(scoreMode); return queryRescoreBuilder; } void setQueryWeight(float queryWeight) { this.queryWeight = queryWeight; } void setRescoreQueryWeight(float rescoreQueryWeight) { this.rescoreQueryWeight = rescoreQueryWeight; } void setScoreMode(QueryRescoreMode scoreMode) { this.scoreMode = scoreMode; } } @Override public QueryRescorerBuilder rewrite(QueryRewriteContext ctx) throws IOException { QueryBuilder rewrite = queryBuilder.rewrite(ctx); if (rewrite == queryBuilder) { return this; } QueryRescorerBuilder queryRescoreBuilder = new QueryRescorerBuilder(rewrite); queryRescoreBuilder.setQueryWeight(queryWeight); queryRescoreBuilder.setRescoreQueryWeight(rescoreQueryWeight); queryRescoreBuilder.setScoreMode(scoreMode); if (windowSize() != null) { queryRescoreBuilder.windowSize(windowSize()); } return queryRescoreBuilder; } }
37.602941
138
0.70571
3227faffbf6b3261780e595c56277c476f438fb9
474
/* * Copyright (c) 2010-2019 Evolveum and contributors * * This work is dual-licensed under the Apache License 2.0 * and European Union Public License. See LICENSE file for details. */ package com.evolveum.midpoint.task.quartzimpl.statistics; /** * */ public interface WorkBucketStatisticsCollector { void register(String situation, long totalTime, int conflictCount, long conflictWastedTime, int bucketWaitCount, long bucketWaitTime, int bucketsReclaimed); }
27.882353
160
0.772152
abd659030d7babc2a072cfda63cf4f7e044d1f74
4,540
package cn.myzju.jzbook.activity; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.EditText; import android.widget.Toast; import com.dd.processbutton.iml.ActionProcessButton; import cn.myzju.jzbook.R; import cn.myzju.jzbook.entity.Session; import cn.myzju.jzbook.entity.User; import cn.myzju.jzbook.utils.ProgressGenerator; import cn.myzju.lib.sprinkles.CursorList; import static cn.myzju.jzbook.db.DbManager.getSession; import static cn.myzju.jzbook.db.DbManager.getUser; public class LoginActivity extends AppCompatActivity implements ProgressGenerator.OnCompleteListener{ public static final String EXTRAS_ENDLESS_MODE = "EXTRAS_ENDLESS_MODE"; @Override protected void onCreate(Bundle savedInstanceState) { int timenow=(int)(System.currentTimeMillis()/1000); CursorList<Session> sessions=getSession(); if (sessions.size()>0){ Session session=sessions.get(0); int ltime=session.getLtime(); if (timenow-ltime<(60*60*24*7)){ Intent intent=new Intent(LoginActivity.this, MainActivity.class); startActivity(intent); LoginActivity.this.finish(); }else{ session.delete(); } } sessions.close(); super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); final EditText editEmail = (EditText) findViewById(R.id.username); final EditText editPassword = (EditText) findViewById(R.id.password); final ProgressGenerator progressGenerator = new ProgressGenerator(this); final ActionProcessButton btnSignIn = (ActionProcessButton) findViewById(R.id.login); Bundle extras = getIntent().getExtras(); if(extras != null && extras.getBoolean(EXTRAS_ENDLESS_MODE)) { btnSignIn.setMode(ActionProcessButton.Mode.ENDLESS); } else { btnSignIn.setMode(ActionProcessButton.Mode.PROGRESS); } editEmail.setEnabled(true); editPassword.setEnabled(true); btnSignIn.setClickable(true); btnSignIn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (editEmail.getText()==null||"".equals(editEmail.getText().toString())){ Toast.makeText(LoginActivity.this, "请输入邮箱", Toast.LENGTH_LONG).show(); return; } else if (editPassword.getText()==null||"".equals(editPassword.getText().toString())){ Toast.makeText(LoginActivity.this, "请输入密码", Toast.LENGTH_LONG).show(); return; } else { CursorList<User> users=getUser(editEmail.getText().toString()); if (users.size()>0){ User user=users.get(0); users.close(); String uname=user.getUsername(); String pwd=user.getPwd(); if (!pwd.equals(editPassword.getText().toString())){ Toast.makeText(LoginActivity.this, "密码错误!", Toast.LENGTH_LONG).show(); return; } long uid=user.getUid(); Session s=new Session(); s.setUid(uid); s.setUsername(editEmail.getText().toString()); s.setPwd(editPassword.getText().toString()); s.save(); editEmail.setEnabled(false); editPassword.setEnabled(false); btnSignIn.setClickable(false); }else{ users.close(); User user1=new User(); user1.setUsername(editEmail.getText().toString()); user1.setPwd(editPassword.getText().toString()); user1.save(); Toast.makeText(LoginActivity.this, "注册成功,请重新登录!", Toast.LENGTH_LONG).show(); return; } } progressGenerator.start(btnSignIn); } }); } @Override public void onComplete() { Intent intent=new Intent(LoginActivity.this, MainActivity.class); startActivity(intent); LoginActivity.this.finish(); } }
42.037037
104
0.576872
0e15d9c348f1de23b839288835707c54382a2878
2,144
/** * Licensed to The Apereo Foundation under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * * The Apereo Foundation licenses this file to you under the Educational * Community 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://opensource.org/licenses/ecl2.txt * * 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.opencastproject.message.broker.api; import org.opencastproject.security.api.JaxbOrganization; import org.opencastproject.security.api.JaxbUser; import org.opencastproject.security.api.Organization; import org.opencastproject.security.api.OrganizationParser; import org.opencastproject.security.api.User; import org.opencastproject.security.api.UserParser; import com.entwinemedia.fn.data.Opt; import java.io.Serializable; public class BaseMessage implements Serializable { private static final long serialVersionUID = 3895355230339323251L; private final String organization; private final String user; private final Serializable object; public BaseMessage(Organization organization, User user, Serializable object) { this.organization = OrganizationParser.toXml(JaxbOrganization.fromOrganization(organization)); this.user = UserParser.toXml(JaxbUser.fromUser(user)); this.object = object; } public Opt<String> getId() { if (object instanceof MessageItem) return Opt.some(((MessageItem) object).getId()); return Opt.none(); } public Organization getOrganization() { return OrganizationParser.fromXml(organization); } public User getUser() { return UserParser.fromXml(user); } public Serializable getObject() { return object; } }
31.072464
98
0.766791
01e0de369063892935191ea1c75be6387e58b5e4
1,156
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.acidmanic.cicdassistant.html.theme; import com.acidmanic.cicdassistant.html.styles.StyleColor; /** * * @author diego */ public class ColorProperty implements Property { private String name; private StyleColor color; @Override public String getName() { return name; } @Override public void setName(String name) { this.name = name; } @Override public String getValue() { return this.color.toCode(); } @Override public void setValue(String value) { this.color = StyleColor.fromCode(value); } public StyleColor getColor() { return color; } public void setColor(StyleColor color) { this.color = color; } public ColorProperty(String name, StyleColor color) { this.name = name; this.color = color; } public ColorProperty() { this.name = "color"; this.color = new StyleColor(); } }
19.266667
79
0.630623
c294287551bc8c4092e7d5c38d9ad64e759187ff
2,999
package com.fourlife.plugins.sprig; import com.getcapacitor.JSObject; import com.getcapacitor.Plugin; import com.getcapacitor.PluginCall; import com.getcapacitor.PluginMethod; import com.getcapacitor.annotation.CapacitorPlugin; import android.content.Context; import androidx.fragment.app.FragmentActivity; import com.userleap.UserLeap; @CapacitorPlugin(name = "Sprig") public class SprigPlugin extends Plugin { @PluginMethod public void configure(PluginCall call) { String environmentId = call.getString("environmentId"); Context context = getContext(); UserLeap.INSTANCE.configure(context, environmentId); call.resolve(); } @PluginMethod public void setUserIdentifier(PluginCall call) { String identifier = call.getString("identifier"); UserLeap.INSTANCE.setUserIdentifier(identifier); call.resolve(); } @PluginMethod public void setEmailAddress(PluginCall call) { String email = call.getString("email"); UserLeap.INSTANCE.setEmailAddress(email); call.resolve(); } @PluginMethod public void setVisitorAttribute(PluginCall call) { String key = call.getString("key"); String value = call.getString("value"); UserLeap.INSTANCE.setVisitorAttribute(key, value); call.resolve(); } @PluginMethod public void removeVisitorAttributes(PluginCall call) { call.unimplemented("Not implemented on Android."); } @PluginMethod public void trackEvent(PluginCall call) { String eventName = call.getString("eventName"); UserLeap.INSTANCE.track(eventName, null); call.resolve(); } @PluginMethod public void presentSurvey(PluginCall call) { JSObject ret = new JSObject(); String eventName = call.getString("eventName"); UserLeap.INSTANCE.track(eventName, (surveyState) -> { FragmentActivity activity = getActivity(); UserLeap.INSTANCE.presentSurvey(activity); switch (surveyState) { case READY: // We received a survey for the event, present it to the user ret.put("surveryState", 0); break; case NO_SURVEY: // No survey available based on event ret.put("surveryState", 1); break; case DISABLED: // Sprig has been disabled remotely ret.put("surveryState", 2); break; } call.resolve(ret); return null; }); } @PluginMethod public void presentDebugSurvey(PluginCall call) { FragmentActivity activity = getActivity(); UserLeap.INSTANCE.presentDebugSurvey(activity); call.resolve(); } @PluginMethod public void logout(PluginCall call) { UserLeap.INSTANCE.logout(); call.resolve(); } }
30.292929
81
0.623208
b04488112f230e68c42e87a4df6e69080a929271
3,311
package com.intellij.execution.testframework.actions; import com.intellij.execution.ExecutionException; import com.intellij.execution.configurations.RunProfileState; import com.intellij.execution.executors.DefaultRunExecutor; import com.intellij.execution.runners.ExecutionEnvironment; import com.intellij.execution.runners.ExecutionEnvironmentBuilder; import com.intellij.execution.testframework.actions.AbstractRerunFailedTestsAction.MyRunProfile; import com.intellij.execution.ui.RunContentDescriptor; import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.util.Ref; import com.intellij.testFramework.UsefulTestCase; import com.jetbrains.python.testing.PyRerunFailedTestsAction; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /** * Utils to work with "rerun failed tests" action * * @author Ilya.Kazakevich */ public final class RerunFailedActionsTestTools { private RerunFailedActionsTestTools() { } /** * Fetches "rerun" env from run action * * @param runAction action to fetch state from * @return state or null if not found */ @Nullable public static ExecutionEnvironment getReRunEnvironment(@NotNull final AbstractRerunFailedTestsAction runAction) { final MyRunProfile profile = runAction.getRunProfile(new ExecutionEnvironment()); if (profile == null) { return null; } final Ref<ExecutionEnvironment> stateRef = new Ref<ExecutionEnvironment>(); UsefulTestCase.edt(new Runnable() { @Override public void run() { stateRef.set(ExecutionEnvironmentBuilder.create(DefaultRunExecutor.getRunExecutorInstance(), profile).build()); } }); return stateRef.get(); } /** * Searches for "rerun failed tests" action and fetches state from it * * @param descriptor previous run descriptor * @return state (if found) */ @Nullable public static RunProfileState findRestartActionState(@NotNull final RunContentDescriptor descriptor) { final ExecutionEnvironment action = findRestartAction(descriptor); if (action == null) { return null; } final Ref<RunProfileState> stateRef = new Ref<RunProfileState>(); ApplicationManager.getApplication().invokeAndWait(new Runnable() { @Override public void run() { try { stateRef.set(action.getState()); } catch (final ExecutionException e) { throw new IllegalStateException("Error obtaining execution state", e); } } }, ModalityState.NON_MODAL); return stateRef.get(); } /** * Searches for "rerun failed tests" action and returns it's environment * * @param descriptor previous run descriptor * @return environment (if found) */ @Nullable public static ExecutionEnvironment findRestartAction(@NotNull final RunContentDescriptor descriptor) { for (final AnAction action : descriptor.getRestartActions()) { if (action instanceof PyRerunFailedTestsAction) { final PyRerunFailedTestsAction rerunFailedTestsAction = (PyRerunFailedTestsAction)action; return getReRunEnvironment(rerunFailedTestsAction); } } return null; } }
34.489583
119
0.743582
534566318cad936033a06f4b5b3d67bf1b4aad25
3,337
/* * Copyright (c) 2017-2019 Contributors to the Eclipse Foundation * * See the NOTICE file(s) distributed with this work for additional * information regarding copyright ownership. * * 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. * * Contributors: * 2018-09-29 - Rudy De Busscher * Initially authored in Atbash Jessie */ package org.eclipse.microprofile.starter.addon.microprofile.servers.model; import org.eclipse.microprofile.starter.core.model.MicroProfileVersion; import java.util.Arrays; import java.util.Collections; import java.util.List; public enum SupportedServer { // @formatter:off WILDFLY_SWARM("wildfly-swarm", "WildFly Swarm", Collections.singletonList(MicroProfileVersion.MP12)) , THORNTAIL_V2("thorntail-v2", "Thorntail V2", Arrays.asList(MicroProfileVersion.MP12, MicroProfileVersion.MP13, MicroProfileVersion.MP21, MicroProfileVersion.MP22)) , LIBERTY("liberty", "Open Liberty", Arrays.asList(MicroProfileVersion.MP12, MicroProfileVersion.MP13, MicroProfileVersion.MP14, MicroProfileVersion.MP20, MicroProfileVersion.MP21, MicroProfileVersion.MP22)) , KUMULUZEE("kumuluzEE", "KumuluzEE", Arrays.asList(MicroProfileVersion.MP12, MicroProfileVersion.MP13, MicroProfileVersion.MP14, MicroProfileVersion.MP20, MicroProfileVersion.MP21)) , PAYARA_MICRO("payara-micro", "Payara Micro", Arrays.asList(MicroProfileVersion.MP12, MicroProfileVersion.MP13, MicroProfileVersion.MP14, MicroProfileVersion.MP20, MicroProfileVersion.MP21, MicroProfileVersion.MP22)) , TOMEE("tomee", "Apache TomEE 8.0.0-M2", Arrays.asList(MicroProfileVersion.MP12, MicroProfileVersion.MP13, MicroProfileVersion.MP14, MicroProfileVersion.MP20)) , HELIDON("helidon", "Helidon", Collections.singletonList(MicroProfileVersion.MP12)); // @formatter:on private String code; private String displayName; private List<MicroProfileVersion> mpVersions; SupportedServer(String code, String displayName, List<MicroProfileVersion> mpVersions) { this.code = code; this.displayName = displayName; this.mpVersions = mpVersions; } public String getCode() { return code; } public String getDisplayName() { return displayName; } public List<MicroProfileVersion> getMpVersions() { return mpVersions; } public static SupportedServer valueFor(String data) { SupportedServer result = null; for (SupportedServer supportedServer : SupportedServer.values()) { if (supportedServer.code.equals(data)) { result = supportedServer; } } return result; } }
38.802326
103
0.698831
6d33172e64128f6033a72ac2ace51af2f3ce80ff
1,788
/* * Copyright (c) 2008-2017 Haulmont. * * 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.haulmont.cuba.gui.model; import com.haulmont.cuba.core.entity.Entity; import com.haulmont.cuba.core.global.LoadContext; import com.haulmont.cuba.core.global.View; import com.haulmont.cuba.gui.screen.InstallSubject; import java.util.Collection; import java.util.function.Function; /** * */ @InstallSubject("loadDelegate") public interface CollectionLoader<E extends Entity> extends BaseCollectionLoader { CollectionContainer<E> getContainer(); void setContainer(CollectionContainer<E> container); LoadContext<E> createLoadContext(); boolean isLoadDynamicAttributes(); void setLoadDynamicAttributes(boolean loadDynamicAttributes); boolean isCacheable(); void setCacheable(boolean cacheable); View getView(); void setView(View view); void setView(String viewName); /** * Returns a function which will be used to load data instead of standard implementation. */ Function<LoadContext<E>, Collection<E>> getDelegate(); /** * Sets a function which will be used to load data instead of standard implementation. */ void setLoadDelegate(Function<LoadContext<E>, Collection<E>> delegate); }
28.380952
93
0.738255
33b17a3a4be91cf71b6b9341d0bab646c7297fd5
4,249
/* (c) 2014 LinkedIn Corp. 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. */ package com.linkedin.cubert.operator; import java.io.IOException; import java.util.Map; import org.apache.pig.data.Tuple; import org.apache.pig.data.TupleFactory; import org.codehaus.jackson.JsonNode; import org.codehaus.jackson.JsonParseException; import org.codehaus.jackson.map.JsonMappingException; import com.linkedin.cubert.block.Block; import com.linkedin.cubert.block.BlockProperties; import com.linkedin.cubert.block.BlockSchema; import com.linkedin.cubert.block.Index; import com.linkedin.cubert.utils.FileCache; import com.linkedin.cubert.utils.JsonUtils; public class BlockIndexJoinOperator implements TupleOperator { public static final String INPUT_INDEX_FILE_PATH = "indexFilePath"; public static final String OUTPUT_BLOCKID_NAME = "BLOCK_ID"; public static final String INPUT_PARTITION_KEY_COLUMNS = "partitionKeys"; BlockSchema inputColumns; private Block block; private Tuple outputTuple; private Tuple partitionKey; private int[] partitionKeyIndex; private Index index = null; @Override public void setInput(Map<String, Block> input, JsonNode root, BlockProperties props) throws JsonParseException, JsonMappingException, IOException { block = input.values().iterator().next(); String[] partitionKeyColumnNames = JsonUtils.asArray(root, INPUT_PARTITION_KEY_COLUMNS); BlockSchema inputSchema = block.getProperties().getSchema(); outputTuple = TupleFactory.getInstance().newTuple(inputSchema.getNumColumns() + 1); partitionKey = TupleFactory.getInstance().newTuple(partitionKeyColumnNames.length); partitionKeyIndex = new int[partitionKeyColumnNames.length]; for (int i = 0; i < partitionKeyIndex.length; i++) partitionKeyIndex[i] = inputSchema.getIndex(partitionKeyColumnNames[i]); String indexName = JsonUtils.getText(root, "index"); try { index = FileCache.get().getCachedIndex(indexName); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } if (index == null) { throw new RuntimeException("Cannot load index for [" + JsonUtils.getText(root, "indexName") + "]"); } } @Override public Tuple next() throws IOException, InterruptedException { Tuple tuple = block.next(); if (tuple == null) return null; for (int i = 0; i < partitionKeyIndex.length; i++) partitionKey.set(i, tuple.get(partitionKeyIndex[i])); long blockId = index.getBlockId(partitionKey); if (blockId < 0) throw new RuntimeException(String.format("The block id is -1 for partitionKey %s", partitionKey.toString())); int i = 0; for (i = 0; i < tuple.size(); i++) outputTuple.set(i, tuple.get(i)); outputTuple.set(i, blockId); return outputTuple; } @Override public PostCondition getPostCondition(Map<String, PostCondition> preConditions, JsonNode json) throws PreconditionException { PostCondition condition = preConditions.values().iterator().next(); BlockSchema inputSchema = condition.getSchema(); BlockSchema blockIdSchema = new BlockSchema("long " + OUTPUT_BLOCKID_NAME); BlockSchema outputSchema = inputSchema.append(blockIdSchema); return new PostCondition(outputSchema, condition.getPartitionKeys(), condition.getSortKeys()); } }
35.408333
115
0.655684
ced840623a7dca4c251bcff790cc04c98f30c0e0
596
package com.accedia.tutorial.spring.app; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.ComponentScan; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; @SpringBootApplication @ComponentScan(basePackages = { "com.accedia.tutorial.spring" }) @EnableJpaRepositories(basePackages = { "com.accedia.tutorial.spring.repositories" }) public class SpringApp { public static void main(String[] args) { SpringApplication.run(SpringApp.class, args); } }
35.058824
85
0.822148
fabc9573b57c63fe650f3555ba759906efb5dfcb
3,401
package jenkins.plugins.accurev; import com.cloudbees.plugins.credentials.common.StandardUsernamePasswordCredentials; import edu.umd.cs.findbugs.annotations.NonNull; import jenkins.scm.api.SCMFile; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; import java.util.ArrayList; import java.util.List; public class AccurevSCMFile extends SCMFile { private final AccurevSCMFileSystem fs; private Type fileType; public AccurevSCMFile(AccurevSCMFileSystem fs) { this.fs = fs; } public AccurevSCMFile(AccurevSCMFileSystem fs, AccurevSCMFile parent, String name, Type fileType) { super(parent, name); this.fs = fs; this.fileType = fileType; } @NonNull @Override protected SCMFile newChild(@NonNull String name, boolean assumeIsDirectory) { return new AccurevSCMFile(fs, this, name, assumeIsDirectory ? Type.DIRECTORY : Type.REGULAR_FILE); } @NonNull @Override public Iterable<SCMFile> children() throws IOException, InterruptedException { List<SCMFile> result = new ArrayList<>(); Path path = Paths.get(fs.getRoot().getPath()); Files.walkFileTree(path, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { if(file.getFileName() != null) { Path filename = file.getFileName(); if(filename!= null) result.add(new AccurevSCMFile(fs, AccurevSCMFile.this, filename.toString(), Type.REGULAR_FILE)); } return FileVisitResult.CONTINUE; } @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) { if(dir.getFileName() != null) { Path dirname = dir.getFileName(); if(dirname != null) result.add(new AccurevSCMFile(fs, AccurevSCMFile.this, dirname.toString(), Type.DIRECTORY)); } return FileVisitResult.CONTINUE; } }); return result; } @Override public long lastModified() throws IOException, InterruptedException { return 1; } @NonNull @Override protected Type type() throws IOException, InterruptedException { return fileType; } @Override public InputStream content() throws IOException, InterruptedException { if(fs.getAccurevClient() != null) { StandardUsernamePasswordCredentials cred = fs.getAccurevClient().getCredentials(); if (cred != null) { fs.getAccurevClient().login().username(cred.getUsername()).password(cred.getPassword()).execute(); String file = fs.getAccurevClient().getFile(fs.getHead(), getPath(), Long.toString(fs.lastModified())); return new ByteArrayInputStream(file.getBytes("UTF-8")); } } return new ByteArrayInputStream("".getBytes("UTF-8")); } }
36.967391
140
0.631579
2c0d4f3a3c0d8eadbe26f8e64efb077e33ec6089
96,655
package onemessageui.dialog; import android.Manifest; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Bitmap; import android.net.Uri; import android.provider.MediaStore; import android.support.v4.content.ContextCompat; import android.text.Editable; import android.text.TextWatcher; import android.view.Gravity; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.view.WindowManager; import android.view.inputmethod.EditorInfo; import android.view.inputmethod.InputMethodManager; import android.webkit.WebView; import android.widget.AdapterView; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.TextView; import com.shizhefei.view.largeimage.LargeImageView; import com.shizhefei.view.largeimage.factory.FileBitmapDecoderFactory; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import oneapp.onechat.oneandroid.chatsdk.OneAccountHelper; import oneapp.onechat.oneandroid.chatsdk.OneCommunityHelper; import oneapp.onechat.oneandroid.chatsdk.OneGroupHelper; import oneapp.onechat.oneandroid.chatsdk.OneOpenHelper; import oneapp.onechat.oneandroid.chatsdk.OneRedpacketHelper; import oneapp.onechat.oneandroid.graphenechain.interfaces.ProgressRequestListener; import oneapp.onechat.oneandroid.graphenechain.interfaces.RequestSuccessListener; import oneapp.onechat.oneandroid.graphenechain.models.UserContactItem; import oneapp.onechat.oneandroid.graphenechain.models.UserGroupInfoItem; import oneapp.onechat.oneandroid.onemessage.CommonConstants; import oneapp.onechat.oneandroid.onemessage.RpcCallProxy; import oneapp.onechat.oneandroid.onemessage.bean.RedPacketAssetBean; import oneapp.onechat.oneandroid.onemessage.beanchat.util.PathUtil; import oneapp.onechat.oneandroid.onemessage.community.bean.CommentBean; import oneapp.onechat.oneandroid.onemessage.community.bean.WeiboBean; import oneapp.onechat.oneandroid.onemessage.community.bean.WeiboCatchModel; import oneapp.onechat.oneandroid.onewallet.modle.AssetInfo; import oneapp.onechat.oneandroid.onewallet.modle.MapResult; import oneapp.onechat.oneandroid.onewallet.util.BaseUtils; import oneapp.onechat.oneandroid.onewallet.util.Keyboard; import oneapp.onechat.oneandroid.onewallet.util.ListUtils; import oneapp.onechat.oneandroid.onewallet.util.SharePreferenceUtils; import oneapp.onechat.oneandroid.onewallet.util.StringUtils; import oneapp.onechat.oneandroid.onewallet.util.TimeUtils; import oneapp.onechat.oneandroid.onewallet.util.ToastUtils; import oneapp.onechat.oneandroid.onewallet.util.UiUtils; import onemessageui.adpter.SelectAssetAdapter; import onemessageui.widght.FlippingImageView.FlippingImageView; import onemessageui.widght.ProgressWheel; import onewalletui.ui.BaseActivity; import onewalletui.ui.DialogBuilder; import onewalletui.ui.adaptors.SelectRedPacketAssetListAdapter; import onewalletui.util.ImageUtils; import onewalletui.util.jump.JumpAppOutUtil; import onewalletui.util.jump.JumpAppPageUtil; import onewalletui.util.qrcode.QrUtils; import sdk.android.onechatui.R; import top.zibin.luban.Luban; import top.zibin.luban.OnCompressListener; public class DialogUtil { public static final int PHOTO_REQUEST_CAMERA = 1;// 拍照 public static final int PHOTO_REQUEST_GALLERY = 2;// 从相册中选择 public static final int PHOTO_REQUEST_CUT = 3;// 结果 public static final float DEFAULT_DIALOG_DIMAMOUNT = 0.5f;// 结果 public static final String DELETE = "1";// public static final String REPLY = "2";// public static final String CALL_BACK_TYPE_DELETE = "delete"; public static final String CALL_BACK_TYPE_ADD_JINGHUA = "add_jinghua"; public static final String CALL_BACK_TYPE_AT_USER = "at_user"; public static final String CALL_BACK_TYPE_ADD_ADMIN = "add_admin"; /** * 提交推荐码对话框 * * @return */ private static Context mContext; /** * dialog中点击确认按钮的回调 * * @author heshuai */ public interface ConfirmCallBackInf { void onConfirmClick(String content); } public interface ConfirmCallBackObject<T> { void onConfirmClick(T t); } /** * dialog中点击取消按钮的回调 * * @author heshuai */ public interface CancelCallBackInf { void onCancelClick(String content); } /** * dialog中点击不再提醒按钮的回调 * * @author zengyuxin */ public interface RemindCallBackInf { void onRemindClick(String content); } /** * 有一个按钮仅提示的对话框 * * @param context * @param msg 提示信息 * @return */ public static Dialog tipDialog(Context context, String msg, boolean ifCanCancel) { final LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); final LinearLayout layout = (LinearLayout) inflater.inflate(R.layout.dialog_tip, null, false); final Dialog dialog = new Dialog(context, R.style.ActionToastDialogStyle); mContext = context; dialog.setContentView(layout); TextView mMsgTv = (TextView) layout.findViewById(R.id.dialog_msg_tv); if (!StringUtils.equalsNull(msg)) { mMsgTv.setText(msg); } final TextView okBt = (TextView) layout.findViewById(R.id.btn_commit); okBt.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (dialog != null) { dialog.dismiss(); } } }); dialog.setCancelable(true); dialog.setCanceledOnTouchOutside(ifCanCancel); final Window dialogWindow = dialog.getWindow(); final WindowManager.LayoutParams lp = dialogWindow.getAttributes(); dialogWindow.setGravity(Gravity.CENTER); dialogWindow.setBackgroundDrawableResource(R.color.toumin); lp.width = context.getResources().getDimensionPixelSize(R.dimen.simple_dialog_width); lp.height = ViewGroup.LayoutParams.WRAP_CONTENT; lp.dimAmount = DEFAULT_DIALOG_DIMAMOUNT; dialogWindow.setAttributes(lp); dialogWindow.addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND); dialog.show(); return dialog; } /** * 有一个按钮仅提示的对话框 * * @param context * @param msg 提示信息 * @return */ public static Dialog tipDialog(Context context, String msg) { return tipDialog(context, msg, false); } public static Dialog simpleDialog(Context context, String msg, ConfirmCallBackInf callBack) { return simpleDialog(context, msg, callBack, null); } /** * 有两个按钮的对话框 * * @param context * @param msg 提示信息 * @param callBack * @return */ public static Dialog simpleDialog(Context context, String msg, final ConfirmCallBackInf callBack, final CancelCallBackInf cancelCallBack) { return simpleDialog(context, msg, null, null, callBack, cancelCallBack); } /** * 有两个按钮的对话框 * * @param context * @param msg 提示信息 * @param callBack * @return */ public static Dialog simpleDialog(Context context, String msg, String confirText, String cancelText, final ConfirmCallBackInf callBack) { return simpleDialog(context, msg, confirText, cancelText, callBack, null); } /** * 对话框 * * @param context * @param msg 提示信息 * @param callBack * @return */ public static Dialog simpleDialog(Context context, String msg, String confirText, String cancelText, final ConfirmCallBackInf callBack, final CancelCallBackInf cancelCallBack) { if (context == null) { return null; } final LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); final LinearLayout layout = (LinearLayout) inflater.inflate(R.layout.dialog_simple, null, false); final Dialog dialog = new Dialog(context, R.style.ActionSheetDialogStyle); mContext = context; dialog.setContentView(layout); final TextView confirmBt = (TextView) layout.findViewById(R.id.btn_commit); if (!StringUtils.equalsNull(confirText)) { confirmBt.setText(confirText); } TextView mMsgTv = (TextView) layout.findViewById(R.id.dialog_msg_tv); if (!StringUtils.equalsNull(msg)) { mMsgTv.setText(msg); } confirmBt.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (dialog != null) { dialog.dismiss(); } if (callBack != null) { callBack.onConfirmClick(""); } } }); final TextView cancelBt = (TextView) layout.findViewById(R.id.btn_cancel); if (!StringUtils.equalsNull(cancelText)) { cancelBt.setText(cancelText); } cancelBt.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (dialog != null) { dialog.dismiss(); } if (cancelCallBack != null) { cancelCallBack.onCancelClick(""); } } }); dialog.setCancelable(true); dialog.setCanceledOnTouchOutside(true); final Window dialogWindow = dialog.getWindow(); final WindowManager.LayoutParams lp = dialogWindow.getAttributes(); dialogWindow.setGravity(Gravity.CENTER); dialogWindow.setBackgroundDrawableResource(R.color.toumin); lp.width = context.getResources().getDimensionPixelSize(R.dimen.simple_dialog_width); lp.height = ViewGroup.LayoutParams.WRAP_CONTENT; lp.dimAmount = DEFAULT_DIALOG_DIMAMOUNT; dialogWindow.setAttributes(lp); dialogWindow.addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND); dialog.show(); return dialog; } /** * 有三个按钮的对话框 * * @param context * @param msg * @param confirText * @param remindText * @param cancelText * @param callBack * @param remindCallBack * @return */ public static Dialog threeBtnDialog(Context context, String msg, String confirText, String remindText, String cancelText, final ConfirmCallBackInf callBack, final RemindCallBackInf remindCallBack) { final LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); final LinearLayout layout = (LinearLayout) inflater.inflate(R.layout.dialog_triple, null, false); final Dialog dialog = new Dialog(context, R.style.ActionSheetDialogStyle); mContext = context; dialog.setContentView(layout); final TextView confirmBt = (TextView) layout.findViewById(R.id.btn_commit); confirmBt.setText(confirText); TextView mMsgTv = (TextView) layout.findViewById(R.id.dialog_msg_tv); if (!StringUtils.equalsNull(msg)) { mMsgTv.setText(msg); } confirmBt.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (callBack != null) { callBack.onConfirmClick(""); if (dialog != null) { dialog.dismiss(); } } } }); final TextView cancelBt = (TextView) layout.findViewById(R.id.btn_cancel); cancelBt.setText(cancelText); cancelBt.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (dialog != null) { dialog.dismiss(); } } }); TextView remindBt = (TextView) layout.findViewById(R.id.btn_remind); if (!StringUtils.equalsNull(remindText)) { remindBt.setText(remindText); remindBt.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (remindCallBack != null) { remindCallBack.onRemindClick(""); if (dialog != null) { dialog.dismiss(); } } } }); } else { remindBt.setVisibility(View.GONE); } // dialog.setCancelable(true); // dialog.setCanceledOnTouchOutside(true); final Window dialogWindow = dialog.getWindow(); final WindowManager.LayoutParams lp = dialogWindow.getAttributes(); dialogWindow.setGravity(Gravity.CENTER); dialogWindow.setBackgroundDrawableResource(R.color.toumin); lp.width = context.getResources().getDimensionPixelSize(R.dimen.simple_dialog_width); lp.height = ViewGroup.LayoutParams.WRAP_CONTENT; lp.dimAmount = DEFAULT_DIALOG_DIMAMOUNT; dialogWindow.setAttributes(lp); dialogWindow.addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND); dialog.show(); return dialog; } /** * 对话框 * * @param context * @param callBack * @return */ public static Dialog editNameDialog(final Context context, String title, String name, final ConfirmCallBackInf callBack) { final LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); final LinearLayout layout = (LinearLayout) inflater.inflate(R.layout.dialog_edit_text, null, false); final Dialog dialog = new Dialog(context, R.style.ActionToastDialogStyle); mContext = context; dialog.setContentView(layout); TextView mTitleTv = (TextView) layout.findViewById(R.id.dialog_msg_tv); mTitleTv.setText(title); final EditText mEditText = (EditText) layout.findViewById(R.id.dialog_edit_et); mEditText.setText(name); mEditText.setLines(1); if (!StringUtils.equalsNull(name)) mEditText.setSelection(name.length()); final TextView confirmBt = (TextView) layout.findViewById(R.id.btn_commit); confirmBt.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { UiUtils.closeKeybord(mEditText, context); String text = mEditText.getText().toString(); if (!StringUtils.equalsNull(text) && callBack != null) { callBack.onConfirmClick(text); if (dialog != null) { dialog.dismiss(); } } } }); final TextView cancelBt = (TextView) layout.findViewById(R.id.btn_cancel); cancelBt.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { UiUtils.closeKeybord(mEditText, context); if (dialog != null) { dialog.dismiss(); } } }); dialog.setCancelable(true); dialog.setCanceledOnTouchOutside(true); final Window dialogWindow = dialog.getWindow(); final WindowManager.LayoutParams lp = dialogWindow.getAttributes(); dialogWindow.setGravity(Gravity.CENTER); dialogWindow.setBackgroundDrawableResource(R.color.toumin); lp.width = context.getResources().getDimensionPixelSize(R.dimen.edit_dialog_width); lp.height = context.getResources().getDimensionPixelSize(R.dimen.edit_dialog_height); lp.dimAmount = DEFAULT_DIALOG_DIMAMOUNT; dialogWindow.setAttributes(lp); dialogWindow.addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND); dialog.show(); return dialog; } /** * 对话框 * * @param context * @param callBack * @return */ public static Dialog editInputDialog(final Context context, String title, String defaultContent, String editHint, final ConfirmCallBackInf callBack) { final LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); final LinearLayout layout = (LinearLayout) inflater.inflate(R.layout.dialog_edit_text, null, false); final Dialog dialog = new Dialog(context, R.style.ActionToastDialogStyle); mContext = context; dialog.setContentView(layout); TextView mTitleTv = (TextView) layout.findViewById(R.id.dialog_msg_tv); mTitleTv.setText(title); final EditText mEditText = (EditText) layout.findViewById(R.id.dialog_edit_et); if (!StringUtils.equalsNull(editHint)) { mEditText.setHint(editHint); } if (!StringUtils.equalsNull(defaultContent)) { mEditText.setText(defaultContent); mEditText.setSelection(defaultContent.length()); } final TextView confirmBt = (TextView) layout.findViewById(R.id.btn_commit); confirmBt.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { UiUtils.closeKeybord(mEditText, context); String text = mEditText.getText().toString(); if (!StringUtils.equalsNull(text) && callBack != null) { callBack.onConfirmClick(text); if (dialog != null) { dialog.dismiss(); } } } }); final TextView cancelBt = (TextView) layout.findViewById(R.id.btn_cancel); cancelBt.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { UiUtils.closeKeybord(mEditText, context); if (dialog != null) { dialog.dismiss(); } } }); dialog.setCancelable(true); dialog.setCanceledOnTouchOutside(true); final Window dialogWindow = dialog.getWindow(); final WindowManager.LayoutParams lp = dialogWindow.getAttributes(); dialogWindow.setGravity(Gravity.CENTER); dialogWindow.setBackgroundDrawableResource(R.color.toumin); lp.width = context.getResources().getDimensionPixelSize(R.dimen.edit_dialog_width); lp.height = ViewGroup.LayoutParams.WRAP_CONTENT; lp.dimAmount = DEFAULT_DIALOG_DIMAMOUNT; dialogWindow.setAttributes(lp); dialogWindow.addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND); dialog.show(); return dialog; } /** * 输入密码对话框 * * @param context * @param callBack * @return */ public static Dialog inputPswDialog(final Context context, String title, final ConfirmCallBackInf callBack) { final LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); final LinearLayout layout = (LinearLayout) inflater.inflate(R.layout.dialog_input_password, null, false); final Dialog dialog = new Dialog(context, R.style.ActionToastDialogStyle); mContext = context; dialog.setContentView(layout); TextView mTitleTv = (TextView) layout.findViewById(R.id.dialog_msg_tv); mTitleTv.setText(title); TextView mForgetPswTv = (TextView) layout.findViewById(R.id.forget_psw); mForgetPswTv.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { new AlertDialog.Builder(context).setTitle(R.string.override_wallet_warning_title) .setMessage(R.string.override_new_wallet_warning_message) .setNegativeButton(R.string.button_cancel, null) .setPositiveButton(R.string.button_confirm, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { OneAccountHelper.deleteWallet(); } }).create().show(); // JumpAppPageUtil.jumpRegisterGuidePage(context, Constants.FROM_OTHER); } }); final EditText mEditText = (EditText) layout.findViewById(R.id.dialog_edit_et); final TextView confirmBt = (TextView) layout.findViewById(R.id.btn_commit); confirmBt.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { UiUtils.closeKeybord(mEditText, context); if (callBack != null) { if (dialog != null) { dialog.dismiss(); } callBack.onConfirmClick(mEditText.getText().toString()); } } }); final TextView cancelBt = (TextView) layout.findViewById(R.id.btn_cancel); cancelBt.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { UiUtils.closeKeybord(mEditText, context); if (dialog != null) { dialog.dismiss(); } } }); dialog.setCancelable(true); dialog.setCanceledOnTouchOutside(false); final Window dialogWindow = dialog.getWindow(); final WindowManager.LayoutParams lp = dialogWindow.getAttributes(); dialogWindow.setGravity(Gravity.CENTER); dialogWindow.setBackgroundDrawableResource(R.color.toumin); lp.width = context.getResources().getDimensionPixelSize(R.dimen.edit_dialog_width); lp.height = ViewGroup.LayoutParams.WRAP_CONTENT; lp.dimAmount = DEFAULT_DIALOG_DIMAMOUNT; dialogWindow.setAttributes(lp); dialogWindow.addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND); dialog.show(); return dialog; } /** * 检查密码对话框 * * @param context * @param callBack * @return */ public static Dialog checkPswDialog(final Context context, final String title, final ConfirmCallBackInf callBack) { final LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); final LinearLayout layout = (LinearLayout) inflater.inflate(R.layout.dialog_input_password, null, false); final Dialog dialog = new Dialog(context, R.style.ActionToastDialogStyle); mContext = context; dialog.setContentView(layout); TextView mTitleTv = (TextView) layout.findViewById(R.id.dialog_msg_tv); mTitleTv.setText(title); TextView mForgetPswTv = (TextView) layout.findViewById(R.id.forget_psw); mForgetPswTv.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { new AlertDialog.Builder(context).setTitle(R.string.override_wallet_warning_title) .setMessage(R.string.override_new_wallet_warning_message) .setNegativeButton(R.string.button_cancel, null) .setPositiveButton(R.string.button_confirm, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { OneAccountHelper.deleteWallet(); } }).create().show(); // JumpAppPageUtil.jumpRegisterGuidePage(context, Constants.FROM_OTHER); } }); final EditText mEditText = (EditText) layout.findViewById(R.id.dialog_edit_et); final TextView confirmBt = (TextView) layout.findViewById(R.id.btn_commit); confirmBt.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { UiUtils.closeKeybord(mEditText, context); String password = mEditText.getText().toString(); if (callBack != null && !StringUtils.equalsNull(password)) { if (dialog != null) { dialog.dismiss(); } if (OneAccountHelper.checkPassword(password)) { callBack.onConfirmClick(password); } else if (StringUtils.equalsNull(OneAccountHelper.getMePasswordBackend())) { RpcCallProxy.getInstance().savePassword(password); } else { DialogBuilder.warn(context, R.string.unlocking_wallet_error_title) .setMessage(R.string.unlocking_wallet_error_detail) .setNegativeButton(R.string.button_cancel, null) .setPositiveButton(R.string.button_retry, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { checkPswDialog(context, title, callBack); } }).create().show(); } } mEditText.setText(""); } }); final TextView cancelBt = (TextView) layout.findViewById(R.id.btn_cancel); cancelBt.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { UiUtils.closeKeybord(mEditText, context); if (dialog != null) { dialog.dismiss(); } } }); dialog.setCancelable(true); dialog.setCanceledOnTouchOutside(false); final Window dialogWindow = dialog.getWindow(); final WindowManager.LayoutParams lp = dialogWindow.getAttributes(); dialogWindow.setGravity(Gravity.CENTER); dialogWindow.setBackgroundDrawableResource(R.color.toumin); lp.width = context.getResources(). getDimensionPixelSize(R.dimen.edit_dialog_width); lp.height = context.getResources(). getDimensionPixelSize(R.dimen.edit_dialog_height); lp.dimAmount = DEFAULT_DIALOG_DIMAMOUNT; dialogWindow.setAttributes(lp); dialogWindow.addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND); dialog.show(); return dialog; } /** * 选择单张图片对话框 * * @param mActivity * @return */ public static Dialog chooceAndCropImageDialog(final BaseActivity mActivity, final String tempImgSaveFile) { final LayoutInflater inflater = (LayoutInflater) mActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE); final LinearLayout layout = (LinearLayout) inflater.inflate(R.layout.dialog_chooce_pic, null, false); final Dialog dialog = new Dialog(mActivity, R.style.ActionSheetDialogStyle); mContext = mActivity; dialog.setContentView(layout); final TextView galleryBt = (TextView) layout.findViewById(R.id.btn_gallery); galleryBt.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (dialog != null) { dialog.dismiss(); mActivity.checkPermission(new BaseActivity.CheckPermListener() { @Override public void superPermission() { // 激活系统图库,选择一张图片 Intent intent = new Intent(Intent.ACTION_PICK); intent.setType("image/*"); mActivity.startActivityForResult(intent, PHOTO_REQUEST_GALLERY); } }, R.string.gallery, Manifest.permission.WRITE_EXTERNAL_STORAGE); } } }); final TextView cameraBt = (TextView) layout.findViewById(R.id.btn_camera); cameraBt.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (dialog != null) { dialog.dismiss(); mActivity.checkPermission(new BaseActivity.CheckPermListener() { @Override public void superPermission() { Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); // 判断存储卡是否可以用,可用进行存储 if (BaseUtils.isMounted()) { intent.putExtra(MediaStore.EXTRA_OUTPUT, BaseUtils.getUriForFile(mActivity, new File(tempImgSaveFile))); } mActivity.startActivityForResult(intent, PHOTO_REQUEST_CAMERA); } }, R.string.camera, Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE); } } }); final TextView cancelBt = (TextView) layout.findViewById(R.id.tv_cancel); cancelBt.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (dialog != null) { dialog.dismiss(); } } }); dialog.setCancelable(true); dialog.setCanceledOnTouchOutside(true); final Window dialogWindow = dialog.getWindow(); final WindowManager.LayoutParams lp = dialogWindow.getAttributes(); dialogWindow.setGravity(Gravity.BOTTOM); lp.width = mActivity.getResources().getDimensionPixelSize(R.dimen.choose_pic_dialog_height); lp.height = mActivity.getResources().getDimensionPixelSize(R.dimen.choose_pic_dialog_width); lp.dimAmount = DEFAULT_DIALOG_DIMAMOUNT; dialogWindow.setAttributes(lp); dialogWindow.setBackgroundDrawableResource(R.color.toumin); dialogWindow.addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND); dialog.show(); return dialog; } /** * webvie菜单 * * @param mActivity * @return */ public static Dialog webviewMeuDialog(final BaseActivity mActivity, final WebView mWebView) { final LayoutInflater inflater = (LayoutInflater) mActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE); final LinearLayout layout = (LinearLayout) inflater.inflate(R.layout.dialog_webview_menu, null, false); final Dialog dialog = new Dialog(mActivity, R.style.ActionSheetDialogStyle); mContext = mActivity; dialog.setContentView(layout); final String webUrl = mWebView.getUrl(); final TextView openOutBrowserTv = (TextView) layout.findViewById(R.id.btn_open_out_browser); openOutBrowserTv.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (dialog != null) { dialog.dismiss(); } JumpAppOutUtil.jumpOutBrowser(mContext, webUrl); } }); final TextView copyUrlTv = (TextView) layout.findViewById(R.id.btn_copy_url); copyUrlTv.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (dialog != null) { dialog.dismiss(); UiUtils.copy(mContext, webUrl); } } }); final TextView refreshTv = (TextView) layout.findViewById(R.id.btn_refresh); refreshTv.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (dialog != null) { dialog.dismiss(); } mWebView.reload(); } }); final TextView cancelBt = (TextView) layout.findViewById(R.id.tv_cancel); cancelBt.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (dialog != null) { dialog.dismiss(); } } }); dialog.setCancelable(true); dialog.setCanceledOnTouchOutside(true); final Window dialogWindow = dialog.getWindow(); final WindowManager.LayoutParams lp = dialogWindow.getAttributes(); dialogWindow.setGravity(Gravity.BOTTOM); lp.width = mActivity.getResources().getDimensionPixelSize(R.dimen.webview_dialog_height); lp.height = mActivity.getResources().getDimensionPixelSize(R.dimen.webview_dialog_width); lp.dimAmount = DEFAULT_DIALOG_DIMAMOUNT; dialogWindow.setAttributes(lp); dialogWindow.setBackgroundDrawableResource(R.color.toumin); dialogWindow.addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND); dialog.show(); return dialog; } /** * dialog消息,并且可以隐藏键盘 * * @param dialog * @param keyBoardView */ private static void dimissDialog(Dialog dialog, View keyBoardView) { if (dialog != null) { dialog.dismiss(); } if (keyBoardView != null) { InputMethodManager manager = (InputMethodManager) mContext.getApplicationContext() .getSystemService(Context.INPUT_METHOD_SERVICE); manager.hideSoftInputFromWindow(keyBoardView.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); } } /** * 重要提示对话框 * * @param context * @param msg 提示信息 * @param callBack * @return */ public static Dialog importentTipDialog(Context context, String msg, final ConfirmCallBackInf callBack) { final LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); final LinearLayout layout = (LinearLayout) inflater.inflate(R.layout.dialog_simple, null, false); final Dialog dialog = new Dialog(context, R.style.ActionToastDialogStyle); mContext = context; dialog.setContentView(layout); final TextView confirmBt = (TextView) layout.findViewById(R.id.btn_commit); TextView mMsgTv = (TextView) layout.findViewById(R.id.dialog_msg_tv); if (!StringUtils.equalsNull(msg)) { mMsgTv.setText(msg); mMsgTv.setTextColor(ContextCompat.getColor(context, R.color.base_color)); } confirmBt.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (callBack != null) { callBack.onConfirmClick(""); if (dialog != null) { dialog.dismiss(); } } } }); final TextView cancelBt = (TextView) layout.findViewById(R.id.btn_cancel); cancelBt.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (dialog != null) { dialog.dismiss(); } } }); dialog.setCancelable(true); dialog.setCanceledOnTouchOutside(true); final Window dialogWindow = dialog.getWindow(); final WindowManager.LayoutParams lp = dialogWindow.getAttributes(); dialogWindow.setGravity(Gravity.CENTER); dialogWindow.setBackgroundDrawableResource(R.color.toumin); lp.width = context.getResources().getDimensionPixelSize(R.dimen.simple_dialog_width); lp.height = ViewGroup.LayoutParams.WRAP_CONTENT; lp.dimAmount = DEFAULT_DIALOG_DIMAMOUNT; dialogWindow.setAttributes(lp); dialogWindow.addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND); dialog.show(); return dialog; } /** * 红包对话框 * * @param context * @param redPacketId 红包id * @param callBack * @return */ public static Dialog redPacketDialog(final Context context, String redPacketSenderId, final String redPacketId, final String redPacketMsg, final ConfirmCallBackInf callBack) { final LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); final LinearLayout layout = (LinearLayout) inflater.inflate(R.layout.dialog_red_packet, null, false); final Dialog dialog = new Dialog(context, R.style.ActionToastDialogStyle); mContext = context; dialog.setContentView(layout); TextView mRedPacketMsgTv = (TextView) layout.findViewById(R.id.tv_red_packet_msg); if (!StringUtils.equalsNull(redPacketMsg)) { mRedPacketMsgTv.setText(redPacketMsg); } UserContactItem sender = OneAccountHelper.getDatabase().getUserContactItemById(redPacketSenderId); TextView senderName = (TextView) layout.findViewById(R.id.tv_sender_name); ImageView senderAvatar = (ImageView) layout.findViewById(R.id.iv_sender_avatar); if (sender != null) { senderName.setText(sender.getUserName()); ImageUtils.displayAvatarNetImage(context, sender.getAvatar(), senderAvatar, sender.getSex()); } final FlippingImageView imageView = (FlippingImageView) layout.findViewById(R.id.iv_chai); final View redPacketView = layout.findViewById(R.id.view_red_packet); redPacketView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (callBack != null) { redPacketView.setClickable(false); imageView.startAnimation(); OneRedpacketHelper.clickRedpacket(context, redPacketId, new RequestSuccessListener<Boolean>() { @Override public void onResponse(Boolean mapResult) { if (!mapResult) { redPacketView.setClickable(true); imageView.clearRotateAnimation(); } else { JumpAppPageUtil.jumpRedPacketInfoPage(context, redPacketId); callBack.onConfirmClick(""); if (dialog != null) { dialog.dismiss(); } } } }); } } }); dialog.setCancelable(true); dialog.setCanceledOnTouchOutside(true); dialog.setOnDismissListener(new DialogInterface.OnDismissListener() { @Override public void onDismiss(DialogInterface dialogInterface) { layout.setBackgroundResource(0); imageView.clearRotateAnimation(); imageView.setImageResource(0); System.gc(); } }); final Window dialogWindow = dialog.getWindow(); final WindowManager.LayoutParams lp = dialogWindow.getAttributes(); dialogWindow.setGravity(Gravity.CENTER); dialogWindow.setBackgroundDrawableResource(R.color.toumin); lp.width = context.getResources().getDimensionPixelSize(R.dimen.red_packet_dialog_width); lp.height = context.getResources().getDimensionPixelSize(R.dimen.red_packet_dialog_height); lp.dimAmount = DEFAULT_DIALOG_DIMAMOUNT; dialogWindow.setAttributes(lp); dialogWindow.addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND); dialog.show(); return dialog; } /** * 选择红包资产类型对话框 * * @param context * @param callBack * @return */ public static Dialog selectRedPacketAssetDialog(final Context context, List<RedPacketAssetBean> assetBeanList, final ConfirmCallBackObject<String> callBack) { final LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); final LinearLayout layout = (LinearLayout) inflater.inflate(R.layout.dialog_select_asset, null, false); final Dialog dialog = new Dialog(context, R.style.ActionSheetDialogStyle); mContext = context; dialog.setContentView(layout); final ListView assetLv = (ListView) layout.findViewById(R.id.dialog_asset_lv); if (assetBeanList != null) { final SelectRedPacketAssetListAdapter mAdapter = new SelectRedPacketAssetListAdapter(context, assetBeanList); assetLv.setAdapter(mAdapter); assetLv.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { if (callBack != null) { callBack.onConfirmClick(mAdapter.getItem(i).getAsset_code()); if (dialog != null) { dialog.dismiss(); } } } }); } TextView assetListTitle = (TextView) layout.findViewById(R.id.tv_asset_list_title); assetListTitle.setText(context.getString(R.string.select_coin_type)); final TextView rechargeBt = (TextView) layout.findViewById(R.id.tv_recharge); rechargeBt.setVisibility(View.GONE); rechargeBt.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (dialog != null) { dialog.dismiss(); } } }); dialog.setCancelable(true); dialog.setCanceledOnTouchOutside(true); final Window dialogWindow = dialog.getWindow(); final WindowManager.LayoutParams lp = dialogWindow.getAttributes(); dialogWindow.setGravity(Gravity.CENTER); dialogWindow.setBackgroundDrawableResource(R.color.toumin); lp.width = context.getResources().getDimensionPixelSize(R.dimen.select_asset_dialog_width); lp.height = context.getResources().getDimensionPixelSize(R.dimen.select_asset_dialog_height); lp.dimAmount = 0; dialogWindow.setAttributes(lp); dialogWindow.addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND); dialog.show(); return dialog; } /** * 重要提示对话框 * * @param context * @param msg 禁止截图 * @param callBack * @return */ public static Dialog noScreenshotDialog(Context context, String msg, String hint, final ConfirmCallBackInf callBack) { final LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); final LinearLayout layout = (LinearLayout) inflater.inflate(R.layout.dialog_screenshot, null, false); final Dialog dialog = new Dialog(context, R.style.ActionToastDialogStyle); mContext = context; dialog.setContentView(layout); final TextView confirmBt = (TextView) layout.findViewById(R.id.btn_commit); TextView mMsgTv = (TextView) layout.findViewById(R.id.dialog_msg_tv); TextView mHintTv = (TextView) layout.findViewById(R.id.dialog_msg_hint); if (!StringUtils.equalsNull(msg)) { mMsgTv.setText(msg); } if (!StringUtils.equalsNull(hint)) { mHintTv.setText(hint); } confirmBt.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (callBack != null) { callBack.onConfirmClick(""); if (dialog != null) { dialog.dismiss(); } } } }); dialog.setCancelable(true); dialog.setCanceledOnTouchOutside(true); final Window dialogWindow = dialog.getWindow(); final WindowManager.LayoutParams lp = dialogWindow.getAttributes(); dialogWindow.setGravity(Gravity.CENTER); dialogWindow.setBackgroundDrawableResource(R.color.toumin); lp.width = context.getResources().getDimensionPixelSize(R.dimen.screenshot_width); lp.height = context.getResources().getDimensionPixelSize(R.dimen.screenshot_height); lp.dimAmount = DEFAULT_DIALOG_DIMAMOUNT; dialogWindow.setAttributes(lp); dialogWindow.addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND); dialog.show(); return dialog; } /** * 展示发送的图片 * * @param context * @return */ public static Dialog showSendImgDialog(BaseActivity context, String imgFile, final ConfirmCallBackInf callBack) { final LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); final View layout = inflater.inflate(R.layout.dialog_show_send_img, null, false); final Dialog dialog = new Dialog(context, R.style.ActionSheetDialogStyle); mContext = context; dialog.setContentView(layout); final LargeImageView showSendIv = (LargeImageView) layout.findViewById(R.id.iv_send_img); Luban.with(context) .load(imgFile) // 传人要压缩的图片列表 .ignoreBy(ImageUtils.MAX_UPLOAD_IMG_SIZE) // 忽略不压缩图片的大小 .setTargetDir(PathUtil.getInstance().getImagePath()) // 设置压缩后文件存储位置 .setCompressListener(new OnCompressListener() { //设置回调 @Override public void onStart() { // TODO 压缩开始前调用,可以在方法内启动 loading UI } @Override public void onSuccess(final File file) { if (file != null) { final String filePath = file.getAbsolutePath(); TextView sendTv = (TextView) layout.findViewById(R.id.tv_send); sendTv.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (dialog != null) { dialog.dismiss(); } if (callBack != null) { callBack.onConfirmClick(filePath); } } }); showSendIv.setImage(new FileBitmapDecoderFactory(filePath)); } } @Override public void onError(Throwable e) { // TODO 当压缩过程出现问题时调用 } }).launch(); TextView cancelTv = (TextView) layout.findViewById(R.id.tv_cancel); cancelTv.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (dialog != null) { dialog.dismiss(); } } }); dialog.setCancelable(true); dialog.setCanceledOnTouchOutside(true); final Window dialogWindow = dialog.getWindow(); final WindowManager.LayoutParams lp = dialogWindow.getAttributes(); dialogWindow.setGravity(Gravity.CENTER); dialogWindow.setBackgroundDrawableResource(R.color.toumin); lp.width = ViewGroup.LayoutParams.MATCH_PARENT; lp.height = ViewGroup.LayoutParams.MATCH_PARENT; lp.dimAmount = 1; dialogWindow.setAttributes(lp); dialogWindow.addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND); dialog.show(); return dialog; } /** * 上传视频到服务器进度对话框 * * @param callBack * @return */ public static Dialog uploadDialog(final Context context, String groupId, String text, String videoPatch, String keyword, final String is_pay, final String asset_code, final String reward_price, final ConfirmCallBackInf callBack) { final LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); final LinearLayout layout = (LinearLayout) inflater.inflate(R.layout.dialog_upload, null, false); final Dialog dialog = new Dialog(context, R.style.ActionSheetDialogStyle); mContext = context; dialog.setContentView(layout); final ProgressWheel mCirclePercentView = (ProgressWheel) layout.findViewById(R.id.upload_progress); final TextView mUploadTipTv = (TextView) layout.findViewById(R.id.tv_upload_tip_tv); //开始上传 OneCommunityHelper.createArticle(groupId, text, keyword, videoPatch, is_pay, asset_code, reward_price, new ProgressRequestListener() { @Override public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { int uploadPercent = (int) ((100 * bytesWritten) / contentLength); // if (percent[0] < uploadPercent) { //ui层回调 try { mCirclePercentView.setProgress(uploadPercent * 3.6f); mCirclePercentView.setText(uploadPercent + "%"); // percent[0] = uploadPercent; if (uploadPercent == 100) { // callBack.onConfirmClick(""); // dialog.dismiss(); } } catch (Exception e) { e.printStackTrace(); } // } } }, new RequestSuccessListener<MapResult>() { @Override public void onResponse(MapResult videoBeanResult) { mCirclePercentView.setVisibility(View.GONE); mUploadTipTv.setText(mContext.getString(R.string.video_upload_ok)); mUploadTipTv.setTextColor(mContext.getResources().getColor(R.color.base_color)); callBack.onConfirmClick(""); dialog.dismiss(); } }); dialog.setCancelable(false); dialog.setCanceledOnTouchOutside(false); dialog.setOnKeyListener(new DialogInterface.OnKeyListener() { @Override public boolean onKey(DialogInterface dialogInterface, int keyCode, KeyEvent keyEvent) { if (keyCode == KeyEvent.KEYCODE_BACK && keyEvent.getRepeatCount() == 0 && keyEvent.getAction() == KeyEvent.ACTION_UP) { DialogUtil.simpleDialog(context, context.getString(R.string.is_sure_to_forgive_this), new ConfirmCallBackInf() { @Override public void onConfirmClick(String content) { OneOpenHelper.cancelAllHttp(); dialog.dismiss(); } }); return false; } else { return true; } } }); final Window dialogWindow = dialog.getWindow(); final WindowManager.LayoutParams lp = dialogWindow.getAttributes(); dialogWindow.setGravity(Gravity.CENTER); dialogWindow.setBackgroundDrawableResource(R.color.toumin); lp.width = context.getResources().getDimensionPixelSize(R.dimen.dimen_100); lp.height = context.getResources().getDimensionPixelSize(R.dimen.dimen_100); lp.dimAmount = 0.5f; dialogWindow.setAttributes(lp); dialogWindow.addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND); dialog.show(); return dialog; } /** * 第一次打赏提示对话框 * * @param context * @return */ public static Dialog shangTipDialog(Context context) { final LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); final LinearLayout layout = (LinearLayout) inflater.inflate(R.layout.dialog_shang_tip, null, false); final Dialog dialog = new Dialog(context, R.style.ActionSheetDialogStyle); mContext = context; dialog.setContentView(layout); layout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); } }); SharePreferenceUtils.putObject(mContext, SharePreferenceUtils.SP_IF_FIRST_SHANG, false); dialog.setCancelable(true); dialog.setCanceledOnTouchOutside(true); final Window dialogWindow = dialog.getWindow(); final WindowManager.LayoutParams lp = dialogWindow.getAttributes(); dialogWindow.setGravity(Gravity.BOTTOM); lp.width = context.getResources().getDimensionPixelSize(R.dimen.dimen_200); lp.height = context.getResources().getDimensionPixelSize(R.dimen.dimen_110); lp.dimAmount = 0.5f; dialogWindow.setAttributes(lp); dialogWindow.setBackgroundDrawableResource(R.color.toumin); dialogWindow.addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND); dialog.show(); return dialog; } /** * 回复对话框 * * @return */ public static Dialog replyWeiboDialog(final BaseActivity context, final CommentBean commentBean, final String sourceWeiboId, final String weiboId, final String groupId, final ConfirmCallBackInf callBack) { final LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); final LinearLayout layout = (LinearLayout) inflater.inflate(R.layout.dialog_reply, null, false); final Dialog dialog = new Dialog(context, R.style.ActionSheetDialogStyle); mContext = context; dialog.setContentView(layout); final EditText mZhuanfaEt = (EditText) layout.findViewById(R.id.zhuanfa_et); mZhuanfaEt.setHint(context.getString(R.string.reply) + commentBean.getNickname()); Keyboard.changeKeyboard(context); mZhuanfaEt.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if (actionId == EditorInfo.IME_ACTION_SEND || (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN)) { //点击发送 context.showLoadingDialog(); OneCommunityHelper.commentToArticleComment(mZhuanfaEt.getText().toString(), weiboId, commentBean.getId(), commentBean.getAccount_name(), groupId, new RequestSuccessListener<MapResult>() { @Override public void onResponse(MapResult mapResult) { dialog.dismiss(); mZhuanfaEt.setText(""); callBack.onConfirmClick(commentBean.getId()); } }); return true; } return false; } }); View mSendTv = layout.findViewById(R.id.tv_send); mSendTv.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //点击发送 context.showLoadingDialog(); OneCommunityHelper.commentToArticleComment(mZhuanfaEt.getText().toString(), weiboId, commentBean.getId(), commentBean.getAccount_name(), groupId, new RequestSuccessListener<MapResult>() { @Override public void onResponse(MapResult mapResult) { dialog.dismiss(); mZhuanfaEt.setText(""); callBack.onConfirmClick(commentBean.getId()); } }); } }); dialog.setOnDismissListener(new DialogInterface.OnDismissListener() { @Override public void onDismiss(DialogInterface dialog) { callBack.onConfirmClick(""); } }); dialog.setCancelable(true); dialog.setCanceledOnTouchOutside(true); final Window dialogWindow = dialog.getWindow(); final WindowManager.LayoutParams lp = dialogWindow.getAttributes(); dialogWindow.setGravity(Gravity.BOTTOM); lp.width = ViewGroup.LayoutParams.MATCH_PARENT; lp.height = ViewGroup.LayoutParams.WRAP_CONTENT; lp.dimAmount = 0.5f; dialogWindow.setAttributes(lp); dialogWindow.addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND); dialog.show(); return dialog; } /** * 支付精品课对话框 * * @param context * @param callBack * @return */ public static Dialog payGoodVideoDialog(final Context context, final String money, final ConfirmCallBackInf callBack) { final LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); final LinearLayout layout = (LinearLayout) inflater.inflate(R.layout.dialog_pay_weibo, null, false); final Dialog dialog = new Dialog(context, R.style.ActionSheetDialogStyle); mContext = context; dialog.setContentView(layout); final TextView confirmBt = (TextView) layout.findViewById(R.id.btn_commit); TextView mMsgTv = (TextView) layout.findViewById(R.id.dialog_msg_tv); TextView mTitleTv = (TextView) layout.findViewById(R.id.dialog_title_tv); final EditText mInputMoneyEt = (EditText) layout.findViewById(R.id.et_input_money); TextView mTipTv = (TextView) layout.findViewById(R.id.dialog_tip_tv); confirmBt.setText(context.getString(R.string.pay)); mTitleTv.setText("支付" + money + "元"); // mMsgTv.setText(context.getString(R.string.look_good_vieo)); mTipTv.setVisibility(View.GONE); mInputMoneyEt.setVisibility(View.GONE); confirmBt.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (callBack != null) { callBack.onConfirmClick(money + ""); if (dialog != null) { dialog.dismiss(); } } } }); final TextView cancelBt = (TextView) layout.findViewById(R.id.btn_cancel); cancelBt.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (dialog != null) { dialog.dismiss(); } } }); dialog.setCancelable(true); dialog.setCanceledOnTouchOutside(true); final Window dialogWindow = dialog.getWindow(); final WindowManager.LayoutParams lp = dialogWindow.getAttributes(); dialogWindow.setGravity(Gravity.CENTER); dialogWindow.setBackgroundDrawableResource(R.drawable.tuoyuan_bg); lp.width = context.getResources().getDimensionPixelSize(R.dimen.pay_dialog_width); lp.height = context.getResources().getDimensionPixelSize(R.dimen.pay_dialog_height); lp.dimAmount = 0.5f; dialogWindow.setAttributes(lp); dialogWindow.addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND); dialog.show(); return dialog; } /** * 微博评论操作对话框 * * @param context * @return */ public static Dialog weiboReplyDetailDialog(final BaseActivity context, final String groupId, final String weiboId, final CommentBean commentBean, final String mHxid, final ConfirmCallBackInf confirmCallBackInf) { final LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); final LinearLayout layout = (LinearLayout) inflater.inflate(R.layout.dialog_weibo_reply_detail, null, false); final Dialog dialog = new Dialog(context, R.style.ActionSheetDialogStyle); mContext = context; dialog.setContentView(layout); final TextView replyBt = (TextView) layout.findViewById(R.id.tv_reply); replyBt.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (!StringUtils.equalsNull(commentBean.getId())) { dialog.dismiss(); confirmCallBackInf.onConfirmClick(DialogUtil.REPLY); } } }); final TextView copyBt = (TextView) layout.findViewById(R.id.tv_copy); copyBt.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (!StringUtils.equalsNull(commentBean.getContent())) UiUtils.copy(mContext, commentBean.getContent()); if (dialog != null) { dialog.dismiss(); } } }); final TextView deleteBt = (TextView) layout.findViewById(R.id.tv_delete); if (commentBean.getAccount_name().equals(OneAccountHelper.getMeAccountName()) || mHxid.equals(OneAccountHelper.getMeAccountName())) { deleteBt.setText(context.getString(R.string.delete)); deleteBt.setVisibility(View.VISIBLE); copyBt.setBackgroundResource(R.drawable.base_click_bg_white); } else { deleteBt.setText(context.getString(R.string.report)); deleteBt.setVisibility(View.GONE); copyBt.setBackgroundResource(R.drawable.tuoyuan_bottom_bg); } deleteBt.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (commentBean.getAccount_name().equals(OneAccountHelper.getMeAccountName()) || mHxid.equals(OneAccountHelper.getMeAccountName())) { context.showLoadingDialog(); OneCommunityHelper.deleteComment(groupId, weiboId, commentBean.getId(), new RequestSuccessListener<MapResult>() { @Override public void onResponse(MapResult mapResult) { confirmCallBackInf.onConfirmClick(DialogUtil.DELETE); } }); } else { context.showLoadingDialog(); OneCommunityHelper.reportArticle("", commentBean.getId(), groupId, new RequestSuccessListener<MapResult>() { @Override public void onResponse(MapResult mapResult) { } }); } if (dialog != null) { dialog.dismiss(); } } }); final TextView cancelBt = (TextView) layout.findViewById(R.id.tv_cancel); cancelBt.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (dialog != null) { dialog.dismiss(); } } }); dialog.setCancelable(true); dialog.setCanceledOnTouchOutside(true); final Window dialogWindow = dialog.getWindow(); final WindowManager.LayoutParams lp = dialogWindow.getAttributes(); dialogWindow.setGravity(Gravity.BOTTOM); lp.width = context.getResources().getDimensionPixelSize(R.dimen.dimen_300); lp.height = ViewGroup.LayoutParams.WRAP_CONTENT; lp.dimAmount = 0.5f; dialogWindow.setAttributes(lp); dialogWindow.setBackgroundDrawableResource(R.color.toumin); dialogWindow.addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND); dialog.show(); return dialog; } /** * 微博更多操作对话框 * * @param context * @return */ public static Dialog weiboMoreDialog(final Context context, final String mWeibiId, final String mSourceWeibiId, final WeiboBean mWeibiBean, final boolean ifFinishPage, final String groupId, final ConfirmCallBackInf confirmCallBackInf) { final LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); final LinearLayout layout = (LinearLayout) inflater.inflate(R.layout.dialog_weibo_more, null, false); final Dialog dialog = new Dialog(context, R.style.ActionSheetDialogStyle); mContext = context; dialog.setContentView(layout); boolean isAdmin = false; final TextView shoucangBt = (TextView) layout.findViewById(R.id.tv_shoucang); final TextView jubaoBt = (TextView) layout.findViewById(R.id.tv_jubao); final TextView deleteBt = (TextView) layout.findViewById(R.id.tv_delete); final TextView bannedBt = (TextView) layout.findViewById(R.id.tv_banned); shoucangBt.setText(context.getString(R.string.article_set_essence)); deleteBt.setText(context.getString(R.string.delete)); jubaoBt.setText(context.getString(R.string.report)); if (!StringUtils.equalsNull(mWeibiBean.getAccount_name()) && mWeibiBean.getAccount_name().equals(OneAccountHelper.getMeAccountName())) { jubaoBt.setVisibility(View.GONE); } else { deleteBt.setVisibility(View.GONE); } if (groupId != null) { final UserGroupInfoItem mGroupInfo = OneAccountHelper.getDatabase().getUserGroupInfoItemById(groupId, false); if (mGroupInfo.getGroupAdminMap() != null && mGroupInfo.getGroupAdminMap().containsKey(OneAccountHelper.getAccountId())) { isAdmin = true; } else { isAdmin = false; } if (StringUtils.equals(mGroupInfo.owner, OneAccountHelper.getAccountId())) { if (!StringUtils.equalsNull(mWeibiBean.getAccount_name()) && mWeibiBean.getAccount_name().equals(OneAccountHelper.getMeAccountName())) { jubaoBt.setVisibility(View.GONE); bannedBt.setVisibility(View.GONE); } else { jubaoBt.setVisibility(View.VISIBLE); bannedBt.setVisibility(View.VISIBLE); } shoucangBt.setVisibility(View.VISIBLE); deleteBt.setVisibility(View.VISIBLE); } else if (isAdmin) { if (!StringUtils.equalsNull(mWeibiBean.getAccount_name()) && mWeibiBean.getAccount_name().equals(OneAccountHelper.getMeAccountName())) { jubaoBt.setVisibility(View.GONE); bannedBt.setVisibility(View.GONE); } else { jubaoBt.setVisibility(View.VISIBLE); bannedBt.setVisibility(View.VISIBLE); } shoucangBt.setVisibility(View.VISIBLE); deleteBt.setVisibility(View.VISIBLE); } else { bannedBt.setVisibility(View.GONE); shoucangBt.setVisibility(View.GONE); jubaoBt.setBackgroundResource(R.drawable.tuoyuan_bg); deleteBt.setBackgroundResource(R.drawable.tuoyuan_bg); } } bannedBt.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { OneGroupHelper.muteMember(mWeibiBean.getGroup_uid(), mWeibiBean.getAccount_id(), new RequestSuccessListener<MapResult>() { @Override public void onResponse(MapResult result) { if (result != null) { ToastUtils.simpleToast(R.string.mute_member_success); } else { ToastUtils.simpleToast(R.string.erro); } } }); if (dialog != null) { dialog.dismiss(); } } }); final TextView zhuanfaBt = (TextView) layout.findViewById(R.id.tv_zhuanfa); zhuanfaBt.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (!StringUtils.equalsNull(mSourceWeibiId)) { dialog.dismiss(); // DialogUtil.showZhuanDialog((BaseActivity) context, mSourceWeibiId, mWeibiId, new DialogUtil.ConfirmCallBackInf() { // @Override // public void onConfirmClick(String content) { // confirmCallBackInf.onConfirmClick(""); // } // }); } } }); deleteBt.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { OneCommunityHelper.deleteArticle(mWeibiId, mWeibiBean.getGroup_uid(), new RequestSuccessListener<MapResult>() { @Override public void onResponse(MapResult mapResult) { // EventBus.getDefault().post(new DeleteWeiboEvent()); if (mapResult != null) { if (ifFinishPage) ((BaseActivity) context).finish(); WeiboCatchModel.getDeleteWeiboMap().put(mWeibiId, mWeibiId); confirmCallBackInf.onConfirmClick(CALL_BACK_TYPE_DELETE); } } }); if (dialog != null) { dialog.dismiss(); } } }); jubaoBt.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { OneCommunityHelper.reportArticle("", mWeibiId, groupId, new RequestSuccessListener<MapResult>() { @Override public void onResponse(MapResult mapResult) { if (mapResult != null) { ToastUtils.simpleToast(R.string.article_report_success); } } }); if (dialog != null) { dialog.dismiss(); } } }); shoucangBt.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { OneCommunityHelper.essenceArticle(mWeibiId, groupId, new RequestSuccessListener<MapResult>() { @Override public void onResponse(MapResult result) { if (result != null) { WeiboCatchModel.getJinghuaWeiboMap().put(mWeibiId, mWeibiId); if (confirmCallBackInf != null) confirmCallBackInf.onConfirmClick(CALL_BACK_TYPE_ADD_JINGHUA); mWeibiBean.setWeibo_jinghua(CommonConstants.TRUE_VALUE); ToastUtils.simpleToast(context.getString(R.string.article_essence_success)); } } }); if (dialog != null) { dialog.dismiss(); } } }); final TextView shareBt = (TextView) layout.findViewById(R.id.tv_share); if (!StringUtils.equalsNull(mWeibiBean.getType()) && mWeibiBean.getType().equals(CommonConstants.WEIBO_TYPE_VIDEO)) { // shareBt.setVisibility(View.VISIBLE); shareBt.setVisibility(View.GONE); } else { shareBt.setVisibility(View.GONE); } shareBt.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (dialog != null) { dialog.dismiss(); //分享 String title = "【" + mWeibiBean.getNickname() + "】"; // if (StringUtils.equalsNull(mWeibiBean.getContent())) // title = title + context.getString(R.string.share_video_title); // else // title = title + mWeibiBean.getContent(); // ShareUtils.shareVideo((Activity) context, NetConstants.SHARE_VIDEO_URL + mSourceWeibiId, title); } } }); final TextView copyBt = (TextView) layout.findViewById(R.id.tv_copy); if (StringUtils.equalsNull(mWeibiBean.getContent())) copyBt.setVisibility(View.GONE); else copyBt.setVisibility(View.VISIBLE); copyBt.setVisibility(View.GONE); copyBt.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (!StringUtils.equalsNull(mWeibiBean.getContent())) UiUtils.copy(mContext, mWeibiBean.getContent()); if (dialog != null) { dialog.dismiss(); } } }); final TextView cancelBt = (TextView) layout.findViewById(R.id.tv_cancel); cancelBt.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (dialog != null) { dialog.dismiss(); } } }); dialog.setCancelable(true); dialog.setCanceledOnTouchOutside(true); final Window dialogWindow = dialog.getWindow(); final WindowManager.LayoutParams lp = dialogWindow.getAttributes(); dialogWindow.setGravity(Gravity.BOTTOM); lp.width = context.getResources().getDimensionPixelSize(R.dimen.dimen_300); lp.height = ViewGroup.LayoutParams.WRAP_CONTENT; lp.dimAmount = 0.5f; dialogWindow.setAttributes(lp); dialogWindow.setBackgroundDrawableResource(R.color.toumin); dialogWindow.addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND); dialog.show(); return dialog; } /** * 点击头像弹出对话框 * * @return */ public static Dialog chooceGroupUserAvatarDialog(final Context context, final String otherAccountId, final String groupUid, boolean isAdmin, final DialogUtil.ConfirmCallBackInf listener) { final String groupAdmin = "ADMIN"; final LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); final LinearLayout layout = (LinearLayout) inflater.inflate(R.layout.dialog_group_option_menu, null, false); final Dialog dialog = new Dialog(context, R.style.ActionSheetDialogStyle); mContext = context; dialog.setContentView(layout); final TextView setAsManagerBt = (TextView) layout.findViewById(R.id.tv_set_as_manager); final TextView bannedToPostBt = (TextView) layout.findViewById(R.id.tv_banned_to_post); final TextView checkCardBt = (TextView) layout.findViewById(R.id.tv_check_card); final TextView informOthersBt = (TextView) layout.findViewById(R.id.tv_inform_others); final TextView groupDeleteBt = (TextView) layout.findViewById(R.id.tv_group_delete); TextView addBlackList = (TextView) layout.findViewById(R.id.tv_add_blacklist); View lineOne = layout.findViewById(R.id.view_one); View lineTwo = layout.findViewById(R.id.view_two); View lineThree = layout.findViewById(R.id.view_three); informOthersBt.setText("@TA"); if (!isAdmin) { setAsManagerBt.setVisibility(View.GONE); bannedToPostBt.setVisibility(View.GONE); groupDeleteBt.setVisibility(View.GONE); addBlackList.setVisibility(View.GONE); lineOne.setVisibility(View.GONE); lineTwo.setVisibility(View.GONE); lineThree.setVisibility(View.GONE); } informOthersBt.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (listener != null) { listener.onConfirmClick(CALL_BACK_TYPE_AT_USER); Keyboard.changeKeyboard((BaseActivity) context); } if (dialog != null) { dialog.dismiss(); } } }); setAsManagerBt.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { OneGroupHelper.addMemberToAdminList(groupUid, groupAdmin, otherAccountId, new RequestSuccessListener<MapResult>() { @Override public void onResponse(MapResult result) { if (result != null) { if (listener != null) { listener.onConfirmClick(CALL_BACK_TYPE_ADD_ADMIN); } ToastUtils.simpleToast(R.string.set_admin_success); } else { ToastUtils.simpleToast(R.string.erro); } } }); if (dialog != null) { dialog.dismiss(); } } }); bannedToPostBt.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { OneGroupHelper.muteMember(groupUid, otherAccountId, new RequestSuccessListener<MapResult>() { @Override public void onResponse(MapResult result) { if (result != null) { ToastUtils.simpleToast(R.string.mute_member_success); } else { ToastUtils.simpleToast(R.string.erro); } } }); if (dialog != null) { dialog.dismiss(); } } }); checkCardBt.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { JumpAppPageUtil.jumpOtherUserInfoPage(context, otherAccountId); if (dialog != null) { dialog.dismiss(); } } }); groupDeleteBt.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { DialogUtil.simpleDialog(context, context.getString(R.string.sure_delete_user), new DialogUtil.ConfirmCallBackInf() { @Override public void onConfirmClick(String content) { List<String> deleteMemberIds = new ArrayList<>(); deleteMemberIds.add(otherAccountId); //更新群聊请求 OneGroupHelper.removeOccupants(groupUid, deleteMemberIds, new RequestSuccessListener<Boolean>() { @Override public void onResponse(Boolean result) { if (result) { ToastUtils.simpleToast(R.string.delete_success); } else { ToastUtils.simpleToast(R.string.delete_failed); } } }); } }); if (dialog != null) { dialog.dismiss(); } } }); addBlackList.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { DialogUtil.simpleDialog(context, context.getString(R.string.sure_delete_user), new DialogUtil.ConfirmCallBackInf() { @Override public void onConfirmClick(String content) { List<String> deleteMemberIds = new ArrayList<>(); deleteMemberIds.add(otherAccountId); //更新群聊请求 OneGroupHelper.addMemberToBlackList(groupUid, deleteMemberIds, new RequestSuccessListener<Boolean>() { @Override public void onResponse(Boolean result) { if (result) { ToastUtils.simpleToast(R.string.add_member_to_blacklist_success); } else { ToastUtils.simpleToast(R.string.delete_failed); } } }); } }); if (dialog != null) { dialog.dismiss(); } } }); final TextView cancelBt = (TextView) layout.findViewById(R.id.tv_cancel); cancelBt.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (dialog != null) { dialog.dismiss(); } } }); dialog.setCancelable(true); dialog.setCanceledOnTouchOutside(true); final Window dialogWindow = dialog.getWindow(); final WindowManager.LayoutParams lp = dialogWindow.getAttributes(); dialogWindow.setGravity(Gravity.BOTTOM); lp.width = ViewGroup.LayoutParams.WRAP_CONTENT; lp.height = ViewGroup.LayoutParams.WRAP_CONTENT; lp.dimAmount = DEFAULT_DIALOG_DIMAMOUNT; dialogWindow.setAttributes(lp); dialogWindow.setBackgroundDrawableResource(R.color.toumin); dialogWindow.addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND); dialog.show(); return dialog; } /** * 选择资产类型对话框 * 输入密码对话框 * * @param context * @param callBack * @return */ public static Dialog selectAssetDialog(final Context context, final List<AssetInfo> assetInfoList, final ConfirmCallBackObject<String> callBack) { final LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); final LinearLayout layout = (LinearLayout) inflater.inflate(R.layout.dialog_select_asset, null, false); final Dialog dialog = new Dialog(context, R.style.ActionSheetDialogStyle); mContext = context; dialog.setContentView(layout); layout.findViewById(R.id.search_view).setVisibility(View.VISIBLE); final ListView assetLv = (ListView) layout.findViewById(R.id.dialog_asset_lv); final EditText mSearchEt = (EditText) layout.findViewById(R.id.et_search); layout.findViewById(R.id.tv_recharge).setVisibility(View.GONE); mSearchEt.addTextChangedListener(new TextWatcher() { public void onTextChanged(CharSequence s, int start, int before, int count) { final SelectAssetAdapter adapter; if (s.length() > 0) { String str_s = mSearchEt.getText().toString().trim().toLowerCase(); List<AssetInfo> tempCoinList = ListUtils.searchAssetInfoList(assetInfoList, str_s); adapter = new SelectAssetAdapter(context, tempCoinList, str_s); assetLv.setAdapter(adapter); } else { adapter = new SelectAssetAdapter(context, assetInfoList, ""); assetLv.setAdapter(adapter); } assetLv.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { if (callBack != null) { callBack.onConfirmClick(adapter.getItem(i).getAsset_code()); if (dialog != null) { dialog.dismiss(); } } } }); } public void beforeTextChanged(CharSequence s, int start, int count, int after) { } public void afterTextChanged(Editable s) { } }); if (assetInfoList != null) { final SelectAssetAdapter mAdapter = new SelectAssetAdapter(context, assetInfoList, ""); assetLv.setAdapter(mAdapter); assetLv.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { if (callBack != null) { callBack.onConfirmClick(mAdapter.getItem(i).getAsset_code()); if (dialog != null) { dialog.dismiss(); } } } }); } dialog.setCancelable(true); dialog.setCanceledOnTouchOutside(true); final Window dialogWindow = dialog.getWindow(); final WindowManager.LayoutParams lp = dialogWindow.getAttributes(); dialogWindow.setGravity(Gravity.CENTER); dialogWindow.setBackgroundDrawableResource(R.color.toumin); lp.width = context.getResources().getDimensionPixelSize(R.dimen.select_asset_dialog_width); lp.height = context.getResources().getDimensionPixelSize(R.dimen.select_asset_dialog_height); lp.dimAmount = 0; dialogWindow.setAttributes(lp); dialogWindow.addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND); dialog.show(); return dialog; } /** * 输入关键词对话框 * * @param context * @param callBack * @return */ public static Dialog inputKeywordDialog(final Context context, final ConfirmCallBackInf callBack) { final LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); final LinearLayout layout = (LinearLayout) inflater.inflate(R.layout.dialog_input_keyword, null, false); final Dialog dialog = new Dialog(context, R.style.ActionToastDialogStyle); mContext = context; dialog.setContentView(layout); final EditText mEditText = (EditText) layout.findViewById(R.id.dialog_edit_et); final TextView confirmBt = (TextView) layout.findViewById(R.id.btn_commit); confirmBt.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (!StringUtils.equalsNull(mEditText.getText().toString().trim())) { UiUtils.closeKeybord(mEditText, context); if (callBack != null) { if (dialog != null) { dialog.dismiss(); } callBack.onConfirmClick(mEditText.getText().toString()); } } } }); final TextView cancelBt = (TextView) layout.findViewById(R.id.btn_cancel); cancelBt.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { UiUtils.closeKeybord(mEditText, context); if (dialog != null) { dialog.dismiss(); } } }); dialog.setCancelable(true); dialog.setCanceledOnTouchOutside(false); final Window dialogWindow = dialog.getWindow(); final WindowManager.LayoutParams lp = dialogWindow.getAttributes(); dialogWindow.setGravity(Gravity.CENTER); dialogWindow.setBackgroundDrawableResource(R.color.toumin); lp.width = context.getResources().getDimensionPixelSize(R.dimen.edit_dialog_width); lp.height = context.getResources().getDimensionPixelSize(R.dimen.edit_dialog_height); lp.dimAmount = DEFAULT_DIALOG_DIMAMOUNT; dialogWindow.setAttributes(lp); dialogWindow.addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND); dialog.show(); return dialog; } /** * 长摁大图提示框 * * @return */ public static Dialog longClickBigImageDialog(final Activity context, final Uri uri, final Bitmap mBitmap) { final LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); final LinearLayout layout = (LinearLayout) inflater.inflate(R.layout.dialog_big_image, null, false); final Dialog dialog = new Dialog(context, R.style.ActionSheetDialogStyle); mContext = context; dialog.setContentView(layout); TextView headingCodeBt = (TextView) layout.findViewById(R.id.tv_heading_code); headingCodeBt.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (uri != null) { try { Bitmap bitmap = MediaStore.Images.Media.getBitmap(context.getContentResolver(), uri); QrUtils.analyzeBitmap(bitmap, new QrUtils.AnalyzeCallback() { @Override public void onAnalyzeSuccess(Bitmap mBitmap, String result) { if (result != null) { JumpAppPageUtil.detailIntentDataJump((BaseActivity) context, result, true); } } @Override public void onAnalyzeFailed() { ToastUtils.simpleToast(R.string.erro); } }); if (dialog != null) { dialog.dismiss(); } } catch (IOException e) { e.printStackTrace(); } } else if (mBitmap != null) { QrUtils.analyzeBitmap(mBitmap, new QrUtils.AnalyzeCallback() { @Override public void onAnalyzeSuccess(Bitmap mBitmap, String result) { if (result != null) { JumpAppPageUtil.detailIntentDataJump((BaseActivity) context, result, true); } } @Override public void onAnalyzeFailed() { ToastUtils.simpleToast(R.string.erro); } }); if (dialog != null) { dialog.dismiss(); } } } }); TextView saveBt = (TextView) layout.findViewById(R.id.tv_save); saveBt.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (uri != null && new File(uri.getPath()).exists()) { BaseUtils.inertImageToPhone(new File(uri.getPath())); ToastUtils.simpleToast(R.string.save_to_phone_success); if (dialog != null) { dialog.dismiss(); } } else { File file = BaseUtils.saveBitmapFile(mBitmap, TimeUtils.getTrueTime() + ImageUtils.DEFAULT_IMAGE_FORMAT); BaseUtils.inertImageToPhone(file); ToastUtils.simpleToast(R.string.save_to_phone_success); if (dialog != null) { dialog.dismiss(); } } } }); final TextView cancelBt = (TextView) layout.findViewById(R.id.tv_cancel); cancelBt.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (dialog != null) { dialog.dismiss(); } } }); dialog.setCancelable(true); dialog.setCanceledOnTouchOutside(true); final Window dialogWindow = dialog.getWindow(); final WindowManager.LayoutParams lp = dialogWindow.getAttributes(); dialogWindow.setGravity(Gravity.BOTTOM); lp.width = ViewGroup.LayoutParams.MATCH_PARENT; lp.height = ViewGroup.LayoutParams.WRAP_CONTENT; lp.dimAmount = DEFAULT_DIALOG_DIMAMOUNT; dialogWindow.setAttributes(lp); dialogWindow.setBackgroundDrawableResource(R.color.toumin); dialogWindow.addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND); dialog.show(); return dialog; } }
42.281277
241
0.576152
1cb66e3951ffec8d015966df609da2e82f55869c
8,579
/** * Copyright 2009 Humboldt-Universität zu Berlin, INRIA. * * 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.corpus_tools.pepper.impl; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyInt; import static org.mockito.Mockito.verify; import java.io.File; import java.io.FileNotFoundException; import java.util.Collection; import java.util.HashSet; import java.util.Set; import org.apache.commons.io.FileUtils; import org.corpus_tools.pepper.exceptions.NotInitializedException; import org.corpus_tools.pepper.testFramework.PepperTestUtil; import org.eclipse.emf.common.util.URI; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; import com.google.common.collect.Multimap; public class CorpusPathResolverTest { private CorpusPathResolver fixture; @Before public void beforeEach() { fixture = new CorpusPathResolver(); } private String getTestResources() { return PepperTestUtil.getTestResources() + "isImportable/"; } @Test public void whenSettingCorpusPath_thenCorpusPathResolverShouldBeUnEmpty() throws FileNotFoundException { File corpusPath = new File(getTestResources() + "differentFileEndings"); fixture.setCorpusPath(URI.createFileURI(corpusPath.getAbsolutePath())); assertThat(fixture.unreadFilesGroupedByExtension.size()).isGreaterThan(0); } @Test public void whenGroupingFilesByEndingFor5DifferentEndings_thenReturnMapWith5Entries() throws FileNotFoundException { File corpusPath = new File(getTestResources() + "differentFileEndings"); Multimap<String, File> map = fixture.groupFilesByEnding(URI.createFileURI(corpusPath.getAbsolutePath())); assertThat(map.keySet().size()).isEqualTo(6); assertThat(map.get("xml").size()).isEqualTo(5); assertThat(map.get("txt").size()).isEqualTo(3); assertThat(map.get("csv").size()).isEqualTo(4); assertThat(map.get("tab").size()).isEqualTo(1); assertThat(map.get("doc").size()).isEqualTo(4); assertThat(map.get("all").size()).isEqualTo(17); } @Test public void whenSamplingSetOfFiles_thenReturnSampledFiles() { File corpusPath = new File(getTestResources() + "sampleFiles"); Collection<File> allFiles = FileUtils.listFiles(corpusPath, null, true); assertThat(fixture.sampleFiles(allFiles, 5).size()).isEqualTo(5); } @Test public void whenSamplingFiles_thenReturnNoDuplicates() { File corpusPath = new File(getTestResources() + "sampleFiles"); Collection<File> allFiles = FileUtils.listFiles(corpusPath, null, true); Collection<File> sampledFiles = fixture.sampleFiles(allFiles, 20); assertThat(sampledFiles.size()).isEqualTo(15); // no duplicates Set<File> noDuplicates = new HashSet<>(); for (File sampledFile : sampledFiles) { noDuplicates.add(sampledFile); } assertThat(noDuplicates.size()).isEqualTo(15); } @Test public void whenSamplingFilesTwice_thenResultsShouldBeDifferent() { File corpusPath = new File(getTestResources() + "sampleFiles"); Collection<File> allFiles = FileUtils.listFiles(corpusPath, null, true); assertThat(fixture.sampleFiles(allFiles, 5).size()).isEqualTo(5); assertThat(fixture.sampleFiles(allFiles, 3)).isNotEqualTo(fixture.sampleFiles(allFiles, 3)); } @Test public void whenReadingFirst10LinesOfFile_thenReturn10FirstLines() { File corpusFile = new File(getTestResources() + "10lineFile.txt"); String content = fixture.readFirstLines(corpusFile, 10); assertEquals("1\n2\n3\n4\n5\n6\n7\n8\n9\n10", content); } @Test public void whenReadingFirst10LinesOfFileWithOnly5Lines_thenReturn5FirstLines() { File corpusFile = new File(getTestResources() + "5lineFile.txt"); String content = fixture.readFirstLines(corpusFile, 10); assertEquals("1\n2\n3\n4\n5", content); } @Test public void whenFileContentIsSampledTwice_thenItShouldBeReadOnlyOnce() throws FileNotFoundException { File corpusPath = new File(getTestResources() + "normalFiles/"); CorpusPathResolver fixture = Mockito.spy(CorpusPathResolver.class); fixture.setCorpusPath(URI.createFileURI(corpusPath.getAbsolutePath())); fixture.sampleFileContent("me"); int numberOfFilesWithExtensionMe = 2; verify(fixture, Mockito.times(numberOfFilesWithExtensionMe)).readFirstLines(any(File.class), anyInt()); Collection<String> fileContents = fixture.sampleFileContent("me"); // verify that files was not read twice verify(fixture, Mockito.times(numberOfFilesWithExtensionMe)).readFirstLines(any(File.class), anyInt()); assertThat(fileContents.size()).isEqualTo(numberOfFilesWithExtensionMe); } @Test public void whenFileContentIsSampledForEnding1AndThenSampledForEnding2_thenShouldContainBothFileContents() throws FileNotFoundException { File corpusPath = new File(getTestResources() + "sampleFiles"); fixture.setCorpusPath(URI.createFileURI(corpusPath.getAbsolutePath())); fixture.sampleFileContent("xml"); assertThat(fixture.readFilesGroupedByExtension.keySet().size()).isEqualTo(1); fixture.sampleFileContent("doc"); assertThat(fixture.readFilesGroupedByExtension.keySet().size()).isEqualTo(2); } @Test public void whenFileContentIsSampledForEndingXml_thenShouldContain3SampledContents() throws FileNotFoundException { File corpusPath = new File(getTestResources() + "sampleFiles"); fixture.setCorpusPath(URI.createFileURI(corpusPath.getAbsolutePath())); Collection<String> content = fixture.sampleFileContent("xml"); assertThat(content.size()).isEqualTo(3); } @Test public void whenFileContentIsSampledWithoutEnding_thenShouldContainContentForAllFiles() throws FileNotFoundException { File corpusPath = new File(getTestResources() + "sampleFiles"); fixture.setCorpusPath(URI.createFileURI(corpusPath.getAbsolutePath())); Collection<String> content = fixture.sampleFileContent(new String[0]); assertThat(content.size()).isEqualTo(15); content = fixture.sampleFileContent((String[]) null); assertThat(content.size()).isEqualTo(15); } @Test public void whenFileContentIsSampledForEndingXmlAndCsv_thenShouldContain9SampledContents() throws FileNotFoundException { File corpusPath = new File(getTestResources() + "sampleFiles"); fixture.setCorpusPath(URI.createFileURI(corpusPath.getAbsolutePath())); Collection<String> content = fixture.sampleFileContent("xml", "csv"); assertThat(content.size()).isEqualTo(6); } @Test public void whenSamplingDocFiles_thenReturnContentWithWord() throws FileNotFoundException { File corpusPath = new File(getTestResources() + "sampleFiles"); fixture.setCorpusPath(URI.createFileURI(corpusPath.getAbsolutePath())); Collection<String> content = fixture.sampleFileContent("doc"); assertThat(content.size()).isEqualTo(3); assertThat(content).containsExactlyInAnyOrder("word", "word", "This\nis\na\nsample\ntext\nto\ncheck\nwhether\nit\nwas"); } @Test public void whenSamplingFileContentAndNumberOfFilesIs0_thenReturnEmptyContent() { assertThat(fixture.sampleFileContent(0, 10, "doc")).isEmpty(); } @Test public void whenSamplingFileContentAndNumberOfLinesIs0_thenReturnEmptyContent() { assertThat(fixture.sampleFileContent(10, 0, "doc")).isEmpty(); } @Test public void whenSamplingMoreFilesInTheSecondRun_thenSampleMoreFiles() throws FileNotFoundException { File corpusPath = new File(getTestResources() + "sampleMoreFilesin2ndRun"); fixture.setCorpusPath(URI.createFileURI(corpusPath.getAbsolutePath())); Collection<String> content = fixture.sampleFileContent(3, 10, "xml"); assertThat(content.size()).isEqualTo(3); content = fixture.sampleFileContent(10, 10, "xml"); assertThat(content.size()).isEqualTo(10); } @Test(expected = NotInitializedException.class) public void whenSamplingFileContentWithOutInitializing_thenThrowException() { fixture.sampleFileContent("xml"); } @Test(expected = FileNotFoundException.class) public void whenSettingUpWithInvalidURI_thenThrowException() throws FileNotFoundException { fixture.setCorpusPath(URI.createFileURI("/fakeFolder")); } }
39.717593
117
0.780744
76c3c876358335437df7095a8fc3a0ee95bd8e6d
1,239
package com.kalessil.phpStorm.phpInspectionsEA.codeStyle; import com.kalessil.phpStorm.phpInspectionsEA.PhpCodeInsightFixtureTestCase; import com.kalessil.phpStorm.phpInspectionsEA.inspectors.codeStyle.ComparisonOperandsOrderInspector; import com.kalessil.phpStorm.phpInspectionsEA.settings.ComparisonStyle; final public class ComparisonOperandsOrderInspectorTest extends PhpCodeInsightFixtureTestCase { public void testIfFindsYodaPatterns() { ComparisonStyle.force(ComparisonStyle.YODA); myFixture.enableInspections(new ComparisonOperandsOrderInspector()); myFixture.configureByFile("testData/fixtures/codeStyle/comparison-order-yoda.php"); myFixture.testHighlighting(true, false, true); myFixture.getAllQuickFixes().forEach(fix -> myFixture.launchAction(fix)); myFixture.setTestDataPath("."); myFixture.checkResultByFile("testData/fixtures/codeStyle/comparison-order-yoda.fixed.php"); } public void testIfFindsRegularPatterns() { myFixture.enableInspections(new ComparisonOperandsOrderInspector()); myFixture.configureByFile("testData/fixtures/codeStyle/comparison-order-regular.php"); myFixture.testHighlighting(true, false, true); } }
49.56
100
0.788539
40a7993ea114d6bde913d26358d0c582db184d3d
5,603
package com.codepath.apps.restclienttemplate.activities; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import com.bumptech.glide.Glide; import com.bumptech.glide.load.resource.bitmap.RoundedCorners; import com.codepath.apps.restclienttemplate.R; import com.codepath.apps.restclienttemplate.TwitterApp; import com.codepath.apps.restclienttemplate.TwitterClient; import com.codepath.apps.restclienttemplate.models.Tweet; import com.codepath.asynchttpclient.callback.JsonHttpResponseHandler; import org.json.JSONException; import org.parceler.Parcels; import okhttp3.Headers; /* ReplyActivity.java allows users to reply to tweets from other users. Note: The usage of a constraint layout was done on purpose, as I originally intended to use a fragment, but was stuck. Thus, I converted the fragment formatting into this activity, though if I had more time I would continue to try with the fragment. */ public class ReplyActivity extends AppCompatActivity { public static String TAG = "ReplyActivity"; ImageView ivReplyProfile, ivReplyOwnProfile, ivReplyEmbed; TextView tvReplyTweet, tvReplyName, tvReplyScreenName, tvReplyTime, tvReplyStatement; EditText etReply; Button btnExit, btnReply; TwitterClient client; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_reply); client = TwitterApp.getRestClient(this); // Unwrap the tweet passed by the intent in TweetsAdapter final Tweet tweet = Parcels.unwrap(getIntent().getParcelableExtra(Tweet.class.getSimpleName())); ivReplyProfile = findViewById(R.id.ivReplyProfile); // I intended to load one's own profile picture like in Twitter desktop, but ran out of // time. ivReplyOwnProfile = findViewById(R.id.ivReplyOwnProfile); ivReplyEmbed = findViewById(R.id.ivEmbed); // Load the images into their appropriate locale assert tweet != null; Glide.with(this).load(tweet.user.profileImageUrl).transform(new RoundedCorners(200)).into(ivReplyProfile); if (tweet.imageUrl != null) { Glide.with(this).load(tweet.imageUrl).into(ivReplyEmbed); } else { ivReplyEmbed.setVisibility(View.GONE); } tvReplyTweet = findViewById(R.id.tvReplyTweet); tvReplyTweet.setText(tweet.body); tvReplyName = findViewById(R.id.tvReplyName); tvReplyName.setText(tweet.user.name); tvReplyScreenName = findViewById(R.id.tvReplyScreenName); tvReplyScreenName.setText("@" + tweet.user.screenName); tvReplyTime = findViewById(R.id.tvReplyTime); tvReplyTime.setText(tweet.createdAt); tvReplyStatement = findViewById(R.id.tvReplyStatement); tvReplyStatement.setText("Replying to @" + tweet.user.screenName); etReply = findViewById(R.id.etDetail); // Check to see if user wants to back out. btnExit = findViewById(R.id.btnBack); btnExit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { finish(); } }); // Check to see if user is ready to reply btnReply = findViewById(R.id.btnReply); btnReply.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String tweetContent = etReply.getText().toString(); // Check to see if tweet meets Twitter requirements if (tweetContent.isEmpty()) { Toast.makeText(ReplyActivity.this, "Sorry, your tweet cannot be empty", Toast.LENGTH_LONG).show(); return; } if (tweetContent.length() > ComposeActivity.MAX_TWEET_LENGTH) { Toast.makeText(ReplyActivity.this, "Sorry, your tweet is too long", Toast.LENGTH_LONG).show(); return; } // Api call to reply to the tweet client.replyTweet(tweetContent, tweet.id, new JsonHttpResponseHandler() { @Override public void onSuccess(int statusCode, Headers headers, JSON json) { Log.i(TAG, "Replied to Tweet"); try { Tweet tweet = Tweet.fromJson(json.jsonObject); // Pass a new intent with the tweet Intent intent = new Intent(); intent.putExtra("tweet", Parcels.wrap(tweet)); // set result code and bundle data for response setResult(RESULT_OK, intent); // closes the activity, pass data to parent finish(); } catch (JSONException e) { e.printStackTrace(); } } @Override public void onFailure(int statusCode, Headers headers, String response, Throwable throwable) { Log.e(TAG, "Failed to reply to tweet"); }; }); } }); } }
38.909722
118
0.627342
eeb69f1f7c455c0cc82da44adfa63928bfddee4c
125
package uk.co.alt236.apkdetails.repo.signing; public enum SignatureStatus { ERROR, ABSENT, VALID, INVALID }
13.888889
45
0.688
3611e26830b8b0cc3834b10829dfe82196ab4924
3,278
package org.orienteer.bpm.component.widget; import java.util.Optional; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.model.IModel; import org.apache.wicket.model.PropertyModel; import org.apache.wicket.model.ResourceModel; import org.camunda.bpm.BpmPlatform; import org.camunda.bpm.engine.ProcessEngine; import org.camunda.bpm.engine.TaskService; import org.camunda.bpm.engine.task.Task; import org.orienteer.bpm.camunda.handler.TaskEntityHandler; import org.orienteer.bpm.component.command.CompleteTaskCommand; import org.orienteer.core.component.command.EditODocumentCommand; import org.orienteer.core.component.command.SaveODocumentCommand; import org.orienteer.core.widget.Widget; import com.orientechnologies.orient.core.record.impl.ODocument; import ru.ydn.wicket.wicketorientdb.model.NvlModel; /** * Widget showing a form for a user task */ @Widget(id="user-task-form", domain="document", selector=TaskEntityHandler.OCLASS_NAME, autoEnable=true, tab="form") public class TaskFormWidget extends AbstractFormWidget { private SaveODocumentCommand saveODocumentCommand; public TaskFormWidget(String id, IModel<ODocument> model, IModel<ODocument> widgetDocumentModel) { super(id, model, widgetDocumentModel); } @Override protected void onInitialize() { super.onInitialize(); propertiesStructureTable.addCommand(new EditODocumentCommand(propertiesStructureTable, getModeModel())); propertiesStructureTable.addCommand(saveODocumentCommand = new SaveODocumentCommand(propertiesStructureTable, getModeModel()){ @Override public void onClick(Optional<AjaxRequestTarget> targetOptional) { super.onClick(targetOptional); associateTaskWithDocument(); }; }.setForceCommit(true)); propertiesStructureTable.addCommand(new CompleteTaskCommand(propertiesStructureTable, getModel(), getModeModel(), formKey)); } @Override protected FormKey obtainFormKey() { ProcessEngine processEngine = BpmPlatform.getDefaultProcessEngine(); TaskService taskService = processEngine.getTaskService(); Task task = taskService.createTaskQuery() .taskId((String)getModelObject().field("id")) .initializeFormKeys() .singleResult(); return FormKey.parse(task.getFormKey()); } @Override protected ODocument resolveODocument(FormKey formKey) { return formKey.calculateODocument(BpmPlatform.getDefaultProcessEngine(), (String)getModelObject().field("id")); } protected void associateTaskWithDocument() { associateTaskWithDocument((String)getModelObject().field("id"), formDocumentModel.getObject()); } protected void associateTaskWithDocument(String taskId, ODocument doc) { ProcessEngine processEngine = BpmPlatform.getDefaultProcessEngine(); TaskService taskService = processEngine.getTaskService(); String var = formKey.getVariableName(); taskService.setVariable(taskId, var, doc.getIdentity().toString()); } @Override protected IModel<String> getDefaultTitleModel() { return new NvlModel<>(new PropertyModel<String>(getModel(), "name"), new ResourceModel("widget.form")); } }
39.02381
126
0.748017
f693dd7c1a527ec2c96149acd6c56b3cb6296360
119
/** * Domain interfaces * * @author mckelvym * @since May 11, 2018 * */ package gov.usgs.warc.iridium.sbd.domain;
14.875
41
0.655462
aceb7ad1ac9ee2f812d9316dc97c89386823151d
567
package com.zhihuianxin.xyaxf.app.home.business; import modellib.thrift.business.Business; import com.zhihuianxin.xyaxf.app.BasePresenter; import com.zhihuianxin.xyaxf.app.BaseView; import io.realm.RealmResults; /** * Created by zcrpro on 2016/10/31. */ public interface BusinessGridContract { interface IBusinessGridView extends BaseView<IBusinessGridPresenter> { void success(RealmResults<Business> businesses); void failure(); } interface IBusinessGridPresenter extends BasePresenter { void loadBusinessData(); } }
23.625
74
0.749559
11aab7a5232353fa3716890fad0553edc52fc25b
3,422
package io.renren.modules.org_cbs.controller; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import io.renren.common.utils.PageUtils; import io.renren.common.utils.R; import io.renren.common.validator.ValidatorUtils; import io.renren.modules.org_cbs.entity.OrgCbsCompanyEntity; import io.renren.modules.org_cbs.entity.OrgCbsMenuEntity; import io.renren.modules.org_cbs.service.OrgCbsCompanyService; import io.renren.modules.org_cbs.service.OrgCbsMenuService; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; /** * 用户公司表 * * @author chenning * @email [email protected] * @date 2019-10-17 16:41:40 */ @RestController @RequestMapping("org/cbs/company") public class OrgCbsCompanyController extends AbstractController { @Autowired private OrgCbsCompanyService orgCbsCompanyService; @Autowired private OrgCbsMenuService orgCbsMenuService; /** * 列表 */ @PostMapping("/list") @RequiresPermissions("org:cbs:company:list") public R list(@RequestBody OrgCbsCompanyEntity entity) { entity.setId(getTenantId()); PageUtils page = orgCbsCompanyService.queryIndex(entity); return R.ok().put("page", page); } /** * 信息 */ @RequestMapping("/info/{id}") @RequiresPermissions("org:cbs:company:info") public R info(@PathVariable("id") Long id) { OrgCbsCompanyEntity orgCbsCompany = orgCbsCompanyService.getById(id); List<OrgCbsMenuEntity> list = orgCbsMenuService.list(new QueryWrapper<OrgCbsMenuEntity>().eq("tenant_id", id)); List<Long> longList = list.stream().map(item -> { return item.getFkSysCbsMenuId(); }).collect(Collectors.toList()); orgCbsCompany.setMenuIdList(longList); return R.ok().put("company", orgCbsCompany); } /** * 保存 */ @RequestMapping("/save") @RequiresPermissions("org:cbs:company:save") public R save(@RequestBody OrgCbsCompanyEntity orgCbsCompany) { ValidatorUtils.validateEntity(orgCbsCompany); orgCbsCompany.setCreateUserId(getUserId()); orgCbsCompanyService.saveCompany(orgCbsCompany); return R.ok(); } /** * 修改 */ @RequestMapping("/update") @RequiresPermissions("org:cbs:company:update") public R update(@RequestBody OrgCbsCompanyEntity orgCbsCompany) { ValidatorUtils.validateEntity(orgCbsCompany); orgCbsCompany.setCreateUserId(getUserId()); orgCbsCompanyService.updateCompanyById(orgCbsCompany); return R.ok(); } /** * 只修改公司信息,给与公司修改信息权限 */ @RequestMapping("/updateInfoOnly") @RequiresPermissions("org:cbs:company:update") public R updateInfoOnly(@RequestBody OrgCbsCompanyEntity orgCbsCompany) { ValidatorUtils.validateEntity(orgCbsCompany); orgCbsCompany.setCreateUserId(getUserId()); orgCbsCompanyService.updateCompanyInfoOnlyById(orgCbsCompany); return R.ok(); } /** * 删除 */ @RequestMapping("/delete") @RequiresPermissions("org:cbs:company:delete") public R delete(@RequestBody Long[] ids) { orgCbsCompanyService.removeByIds(Arrays.asList(ids)); return R.ok(); } }
30.828829
119
0.701929
29a8e40c388dd59694bf57869a83876a8e5e579c
2,169
package com.honvay.cola.service.attachment.configuration; import com.honvay.cola.service.attachment.validator.FileValidator; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.boot.web.servlet.MultipartConfigFactory; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import javax.servlet.MultipartConfigElement; import java.util.Arrays; /** * @author LIQIU * @date 2018-4-3 **/ @Configuration @EnableConfigurationProperties({FileUploadProperties.class}) public class FileValidatorConfiguration { private static long DEFUALT_MAX_SIZE = 1024 * 1024 * 500; @Autowired private FileUploadProperties fileUploadProperties; @Bean public MultipartConfigElement multipartConfigElement() { MultipartConfigFactory factory = new MultipartConfigFactory(); long maxSize = fileUploadProperties.getMaxSize() != null ? fileUploadProperties.getMaxSize() : DEFUALT_MAX_SIZE; factory.setMaxFileSize(maxSize); factory.setMaxRequestSize(maxSize); return factory.createMultipartConfig(); } @Bean public FileValidator defaultFileValidation() { if (fileUploadProperties != null) { FileValidator fileValidator = new FileValidator(); if(fileUploadProperties.getMaxSize() != null){ fileValidator.setMaxBytesSize(fileUploadProperties.getMaxSize()); } if (fileUploadProperties.getContentType() != null) { fileValidator.setContentTypes(Arrays.asList(fileUploadProperties.getContentType())); } if (fileUploadProperties.getExcludeSuffix() != null) { fileValidator.setExcludeSuffix(Arrays.asList(fileUploadProperties.getExcludeSuffix())); } if (fileUploadProperties.getIncludeSuffix() != null) { fileValidator.setIncludeSuffix(Arrays.asList(fileUploadProperties.getIncludeSuffix())); } return fileValidator; } return null; } }
39.436364
120
0.719225
49f4137c3208d884cff35aae9bffa1d247080789
4,135
package top.ftas.util.glide; import android.graphics.Bitmap; import android.graphics.Matrix; import androidx.annotation.NonNull; import android.util.Log; import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool; import com.bumptech.glide.load.resource.bitmap.BitmapTransformation; import com.bumptech.glide.load.resource.bitmap.TransformationUtils; import java.nio.ByteBuffer; import java.security.MessageDigest; /* 示例: int px = DisplayUtil.dip2px(context, 4); GlideApp.with(context) .asBitmap() .transform(new CutLeftRightBottomTransform(px)) .placeholder(R.drawable.im_lecture_hall_default_picture) .error(R.drawable.im_lecture_hall_default_picture) .load(item.small_image) .diskCacheStrategy(DiskCacheStrategy.RESOURCE) .into(imageView); */ /** * @author tik5213 ([email protected]) * @since 2019-01-18 16:18 * <p> * 总说明:等比缩放图片并充满图框,允许裁剪图片的左右或者下边 * a * 在一个固定宽高的 ImageView 中,如果希望同时满足以下几个条件,可以使用此转换器 * 1、图片不变形,永远等比例缩放 * 2、图片水平方向上居中展示。左右不留任何空白。(即,允许等比例缩放并剪裁左右) * 3、图片垂直方向上居上展示。上边和下边不留任何空白。(即,允许等比例缩放并剪裁图片底边。不允许剪裁顶部) * <p> * GlideApp.with(mContext).asBitmap().transform(new CutLeftRightBottomTransform()).load(picPath).diskCacheStrategy(DiskCacheStrategy.ALL).into(ivStartAdView); * <p> * <p> * 圆角参考:RoundedCorners.java TransformationUtils.java ,圆角单位 px */ public class GlideCutLeftRightBottomTransform extends BitmapTransformation { // The version of this transformation, incremented to correct an error in a previous version. // See #455. private static final int VERSION = 1; private static final String ID = "com.bumptech.glide.load.resource.bitmap.CutLeftRightBottomTransform." + VERSION; private static final byte[] ID_BYTES = ID.getBytes(CHARSET); private final int roundingRadius; public GlideCutLeftRightBottomTransform(int pxRoundingRadius) { this.roundingRadius = pxRoundingRadius; } public GlideCutLeftRightBottomTransform() { roundingRadius = 0; } // Bitmap doesn't implement equals, so == and .equals are equivalent here. @SuppressWarnings("PMD.CompareObjectsWithEquals") @Override protected Bitmap transform( @NonNull BitmapPool pool, @NonNull Bitmap toTransform, int outWidth, int outHeight) { Matrix matrix = new Matrix(); int bitmapWidth = toTransform.getWidth(); int bitmapHeight = toTransform.getHeight(); float maxScale = outWidth / (float) bitmapWidth; float minScale = outHeight / (float) bitmapHeight; if (maxScale < minScale) { float tmpScale = maxScale; maxScale = minScale; minScale = tmpScale; } float differenceScale = maxScale / minScale; //如果网络图片的宽高比,和目标 ImageView 的宽高比差了 5 倍以上。说明此图片有问题。不做缩放处理。 //原因。如果比值差得太多,图片缩放得过大。对于小内存手机,会引发 OOM 危机。 //注意,如果仅仅是图片无法展示。很可能是硬件对图片大小有限制。不同设备可能有不同的最大值限制。只须 android:hardwareAccelerated="false"。 // (但是,如果关闭了硬件加速,图片及动画展示可能会不够平滑,突兀) if (differenceScale > 5) { Log.e("CutTransform", "比值差得过大,可能 OOM,不进行缩放"); return toTransform; } matrix.setScale(maxScale, maxScale); //传递的 outHeight 而非 Bitmap newBitmap = Bitmap.createBitmap(toTransform, (bitmapWidth - outWidth) / 2, 0, outWidth, outHeight, matrix, true); //处理圆角 if (roundingRadius > 0) { newBitmap = TransformationUtils.roundedCorners(pool, newBitmap, roundingRadius); } return newBitmap; } @Override public boolean equals(Object o) { return o instanceof GlideCutLeftRightBottomTransform; } @Override public int hashCode() { return ID.hashCode(); } @Override public void updateDiskCacheKey(@NonNull MessageDigest messageDigest) { messageDigest.update(ID_BYTES); if (roundingRadius > 0) { byte[] radiusData = ByteBuffer.allocate(4).putInt(roundingRadius).array(); messageDigest.update(radiusData); } } }
32.559055
158
0.674486
0a47ca9e2dfa51a13683e06b622cd3f0e5f23697
1,473
package mq.rabbitmq.demo05_topic_mode; import com.rabbitmq.client.*; import lombok.SneakyThrows; import mq.rabbitmq.demo01_hello.ConnectionHelper; import java.io.IOException; /** * @Author KJ * @Date 2020-03-30 10:21 PM * @Description */ public class Consumer01 { private final static String QUEUE_NAME = "test_queue_topic_work_1"; private final static String EXCHANGE_NAME = "test_exchange_topic"; public static void main(String[] argv) throws Exception { // 获取到连接以及mq通道 Connection connection = ConnectionHelper.getConnection(); Channel channel = connection.createChannel(); // 声明队列 channel.queueDeclare(QUEUE_NAME, false, false, false, null); // 绑定队列到交换机 channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, "routekey.*"); // 同一时刻服务器只会发一条消息给消费者 channel.basicQos(1); // 定义队列的消费者 Consumer consumer = new DefaultConsumer(channel) { @SneakyThrows @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { String message = new String(body); System.out.println(" [ca] Received '" + message + "'"); Thread.sleep(10); channel.basicAck(envelope.getDeliveryTag(), false); } }; // 监听队列,手动返回完成 channel.basicConsume(QUEUE_NAME, false, consumer); } }
28.326923
144
0.643585
21d031555b49c5379877de76e007cd854e1153e7
355
package com.baeldung.concurrentrequest; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class ConcurrentRequestApplication { public static void main(String[] args) { SpringApplication.run(ConcurrentRequestApplication.class, args); } }
29.583333
72
0.814085
0e641c247aa5defcc821413e7c57aba7728c9ce3
3,932
package com.example.jpro; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; public class SupervisorLogin extends AppCompatActivity { EditText email,password; Button blogin; private FirebaseAuth mAuth; private static String TAG="SupervisorLogin"; // @Override // protected void onStart() { // super.onStart(); // // Check if user is signed in (non-null) and update UI accordingly. // FirebaseUser currentUser = mAuth.getCurrentUser(); // updateUI(currentUser); // } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_supervisor_login); email = (EditText)findViewById(R.id.email); password = (EditText)findViewById(R.id.password); blogin = (Button)findViewById(R.id.btn_login); mAuth = FirebaseAuth.getInstance(); //onclick listerner for the login button blogin.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String mEmail = email.getText().toString().trim(); String mPass = password.getText().toString().trim(); if (mEmail.isEmpty()){ email.setError("Enter email"); email.requestFocus(); return; } if (!isEmailValid(mEmail)){ email.setError("invalid email"); email.requestFocus(); return; } if (mPass.isEmpty()){ password.setError("Enter password"); password.requestFocus(); return; } //call loginAdmin method. loginAdmin(mEmail,mPass); } }); } boolean isEmailValid(CharSequence email) { return android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches(); } //loginAdmin method private void loginAdmin(String email, String password){ mAuth.signInWithEmailAndPassword(email, password) .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { // Sign in success, update UI with the signed-in user's information Log.d(TAG, "signInWithEmail:success"); FirebaseUser user = mAuth.getCurrentUser(); updateUI(user); } else { // If sign in fails, display a message to the user. Log.w(TAG, "signInWithEmail:failure", task.getException()); Toast.makeText(SupervisorLogin.this, "Authentication failed.", Toast.LENGTH_SHORT).show(); } // ... } }); } //updateUI method private void updateUI(FirebaseUser currentUser){ Intent adminDash = new Intent(this, SupervisorDashboard.class); adminDash.putExtra("email",currentUser.getEmail());//sends the email to the adminddash activity startActivity(adminDash); finish(); } }
35.423423
103
0.576806
8d6616a49ca55c678b0a9ff22ce689c8c6637f03
1,836
package hu.akarnokd.rxjava2; import java.io.IOException; import java.util.concurrent.TimeUnit; import java.util.function.Function; import org.junit.Test; import io.reactivex.Observable; import io.reactivex.disposables.Disposable; import io.reactivex.subjects.*; public class RetryWhenPlain { public static <T> Observable<T> retryWhen(Observable<T> source, Function<Observable<Throwable>, Observable<?>> handler) { return Observable.<T>defer(() -> { PublishSubject<Throwable> errorSignal = PublishSubject.create(); Observable<?> retrySignal = handler.apply(errorSignal); BehaviorSubject<Observable<T>> sources = BehaviorSubject.createDefault(source); Disposable d = retrySignal.map(v -> source) .subscribe(sources::onNext, sources::onError, sources::onComplete); return sources.concatMap(src -> { return src .doOnComplete(() -> errorSignal.onComplete()) .onErrorResumeNext(e -> { errorSignal.onNext(e); return Observable.<T>empty(); }); }).doFinally(() -> d.dispose()); }); } @Test public void test() { int[] count = { 3 }; Observable.<String>defer(() -> { if (count[0]-- == 0) { return Observable.just("Success"); } return Observable.error(new IOException()); }) .compose(o -> retryWhen(o, f -> f.flatMap(e -> { System.out.println("Retrying..."); return Observable.timer(1, TimeUnit.SECONDS); })) ) .blockingSubscribe(System.out::println, Throwable::printStackTrace, () -> System.out.println("Done")); } }
33.381818
125
0.563725